Merge branch 'release/1.7.0' into rome/1.7.0

This commit is contained in:
Patrick Fic
2025-06-19 14:14:40 -07:00
27 changed files with 6996 additions and 6800 deletions

29
App.js
View File

@@ -1,33 +1,40 @@
import 'expo-dev-client';
import { ApolloProvider } from "@apollo/client"; import { ApolloProvider } from "@apollo/client";
import * as Sentry from "@sentry/react-native";
import "expo-asset";
import "intl";
import "intl/locale-data/jsonp/en";
import React from "react"; import React from "react";
import { MD2LightTheme as DefaultTheme, Provider as PaperProvider } from "react-native-paper"; import {
MD2LightTheme as DefaultTheme,
Provider as PaperProvider,
} from "react-native-paper";
import { SafeAreaProvider } from "react-native-safe-area-context";
import Toast from "react-native-toast-message";
import { Provider } from "react-redux"; import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/integration/react"; import { PersistGate } from "redux-persist/integration/react";
import * as Sentry from '@sentry/react-native';
import ScreenMainComponent from "./components/screen-main/screen-main.component"; import ScreenMainComponent from "./components/screen-main/screen-main.component";
import { logImEXEvent } from "./firebase/firebase.analytics"; import { logImEXEvent } from "./firebase/firebase.analytics";
import { client } from "./graphql/client"; import { client } from "./graphql/client";
import { persistor, store } from "./redux/store"; import { persistor, store } from "./redux/store";
import "intl";
import "intl/locale-data/jsonp/en";
import "./translations/i18n"; import "./translations/i18n";
import "expo-asset";
import Toast from "react-native-toast-message"; import RNEventSource from "react-native-event-source";
import { SafeAreaProvider } from "react-native-safe-area-context"; globalThis.EventSource = RNEventSource;
Sentry.init({ Sentry.init({
dsn: "https://4866820768550ca396e849fa325e84d6@o492140.ingest.sentry.io/4505637419614208", dsn: "https://4866820768550ca396e849fa325e84d6@o492140.ingest.sentry.io/4505637419614208",
enableInExpoDevelopment: true, enableInExpoDevelopment: true,
// tracesSampleRate: 0.2, // tracesSampleRate: 0.2,
// integrations: [ // integrations: [
// new Sentry.Native.ReactNativeTracing({ // new Sentry.ReactNativeTracing({
// tracingOrigins: ["localhost", "imex.online", "cloudinary.com", /^\//], // tracingOrigins: ["localhost", "imex.online", "cloudinary.com", /^\//],
// // ... other options // // ... other options
// }), // }),
// ], // ],
debug: true, // Sentry will try to print out useful debugging information if something goes wrong with sending an event. Set this to `false` in production. //debug: true, // Sentry will try to print out useful debugging information if something goes wrong with sending an event. Set this to `false` in production.
}); });
const theme = { const theme = {
...DefaultTheme, ...DefaultTheme,
colors: { colors: {
@@ -59,4 +66,4 @@ class App extends React.Component {
); );
} }
} }
export default Sentry.wrap(App); export default Sentry.wrap(App);

View File

@@ -2,29 +2,32 @@
"expo": { "expo": {
"name": "Rome Mobile", "name": "Rome Mobile",
"slug": "rome-mobile", "slug": "rome-mobile",
"version": "1.6.0", "version": "1.7.0",
"extra": { "extra": {
"expover": "5", "expover": "3",
"eas": { "eas": {
"projectId": "df105e21-a07f-4425-af10-2200a7704a48" "projectId": "df105e21-a07f-4425-af10-2200a7704a48"
} }
}, },
"runtimeVersion": "appVersion",
"orientation": "default", "orientation": "default",
"icon": "./assets/RomeIcon.png", "icon": "./assets/RomeIcon.png",
"platforms": ["ios", "android"], "platforms": ["ios", "android"],
"ios": { "ios": {
"supportsTablet": true, "supportsTablet": true,
"bundleIdentifier": "com.rome.mobile", "bundleIdentifier": "com.rome.mobile",
"buildNumber": "5",
"googleServicesFile": "./GoogleService-Info.plist", "googleServicesFile": "./GoogleService-Info.plist",
"entitlements": {
"aps-environment": "development"
},
"infoPlist": { "infoPlist": {
"NSPhotoLibraryUsageDescription": "Allow $(PRODUCT_NAME) to access your photos.", "NSPhotoLibraryUsageDescription": "Allow $(PRODUCT_NAME) to access your photos/videos in order to attach them to repair orders in the system.",
"NSPhotoLibraryAddUsageDescription": "Allow $(PRODUCT_NAME) to save photos." "NSPhotoLibraryAddUsageDescription": "Allow $(PRODUCT_NAME) to save to your photos/videos in order to attach them to repair orders in the system.",
"ITSAppUsesNonExemptEncryption": false
} }
}, },
"android": { "android": {
"package": "com.rome.mobile", "package": "com.rome.mobile",
"versionCode": 5,
"googleServicesFile": "./google-services.json", "googleServicesFile": "./google-services.json",
"permissions": [ "permissions": [
"android.permission.READ_EXTERNAL_STORAGE", "android.permission.READ_EXTERNAL_STORAGE",
@@ -71,15 +74,28 @@
[ [
"expo-media-library", "expo-media-library",
{ {
"photosPermission": "Allow $(PRODUCT_NAME) to access your photos.", "photosPermission": "Allow $(PRODUCT_NAME) to access your photos/videos in order to attach them to repair orders in the system.",
"savePhotosPermission": "Allow $(PRODUCT_NAME) to save photos.", "savePhotosPermission": "Allow $(PRODUCT_NAME) to save photos.",
"isAccessMediaLocationEnabled": "true" "isAccessMediaLocationEnabled": "true"
} }
], ],
"expo-localization" [
], "expo-image-picker",
"runtimeVersion": { {
"policy": "appVersion" "photosPermission": "Allow $(PRODUCT_NAME) to access your photos/videos in order to attach them to repair orders in the system."
} }
],
"expo-localization",
"expo-font",
[
"expo-build-properties",
{
"android": {
"minSdkVersion": 25
}
}
],
"@logrocket/react-native"
]
} }
} }

View File

@@ -14,9 +14,9 @@ export default function DataLabelComponent({
theContent = DateTime.fromISO(content).toLocaleString( theContent = DateTime.fromISO(content).toLocaleString(
DateTime.DATETIME_SHORT DateTime.DATETIME_SHORT
); );
const { key, ...rest } = restProps;
return ( return (
<View {...restProps} style={{ margin: 4, ...restProps.style }}> <View key={key} {...rest} style={{ margin: 4, ...restProps.style }}>
<Text style={{ color: "slategray" }}>{label}</Text> <Text style={{ color: "slategray" }}>{label}</Text>
<Text>{theContent}</Text> <Text>{theContent}</Text>
</View> </View>

View File

@@ -8,7 +8,7 @@ import {
View, View,
} from "react-native"; } from "react-native";
import MediaCacheOverlay from "../media-cache-overlay/media-cache-overlay.component"; import MediaCacheOverlay from "../media-cache-overlay/media-cache-overlay.component";
import * as Sentry from '@sentry/react-native'; import * as Sentry from "@sentry/react-native";
import Toast from "react-native-toast-message"; import Toast from "react-native-toast-message";
import cleanAxios from "../../util/CleanAxios"; import cleanAxios from "../../util/CleanAxios";
@@ -76,10 +76,7 @@ async function getPhotos({ bodyshop, jobid, setImages }) {
if (localmediaserverhttp.endsWith("/")) { if (localmediaserverhttp.endsWith("/")) {
localmediaserverhttp = localmediaserverhttp.slice(0, -1); localmediaserverhttp = localmediaserverhttp.slice(0, -1);
} }
console.log(
"🚀 ~ file: job-documents-local.component.jsx ~ line 78 ~ localmediaserverhttp",
localmediaserverhttp
);
try { try {
const imagesFetch = await cleanAxios.post( const imagesFetch = await cleanAxios.post(
`${localmediaserverhttp}/jobs/list`, `${localmediaserverhttp}/jobs/list`,
@@ -104,7 +101,7 @@ async function getPhotos({ bodyshop, jobid, setImages }) {
setImages(normalizedImages); setImages(normalizedImages);
} catch (error) { } catch (error) {
Sentry.Native.captureException(error); Sentry.captureException(error);
Toast.show({ Toast.show({
type: "error", type: "error",
text1: `Error fetching photos.`, text1: `Error fetching photos.`,

View File

@@ -1,4 +1,5 @@
import React, { useMemo, useState } from "react"; import axios from "axios";
import React, { useEffect, useState } from "react";
import { import {
FlatList, FlatList,
Image, Image,
@@ -10,38 +11,96 @@ import {
import env from "../../env"; import env from "../../env";
import { DetermineFileType } from "../../util/document-upload.utility"; import { DetermineFileType } from "../../util/document-upload.utility";
import MediaCacheOverlay from "../media-cache-overlay/media-cache-overlay.component"; import MediaCacheOverlay from "../media-cache-overlay/media-cache-overlay.component";
export default function JobDocumentsComponent({ job, loading, refetch }) {
const [previewVisible, setPreviewVisible] = useState(false);
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { splitClient } from "../screen-main/screen-main.component";
const mapStateToProps = createStructuredSelector({
//currentUser: selectCurrentUser
bodyshop: selectBodyshop,
});
const mapDispatchToProps = (dispatch) => ({
//setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(JobDocumentsComponent);
export function JobDocumentsComponent({ bodyshop, job, loading, refetch }) {
const [previewVisible, setPreviewVisible] = useState(false);
const [fullphotos, setFullPhotos] = useState([]);
const [imgIndex, setImgIndex] = useState(0); const [imgIndex, setImgIndex] = useState(0);
const useImgproxy = splitClient.getTreatment("Imgproxy");
const onRefresh = async () => { const onRefresh = async () => {
return refetch(); return refetch();
}; };
const fullphotos = useMemo( useEffect(() => {
() => async function getPhotos() {
job.documents.map((doc, idx) => { if (useImgproxy) {
return { const result = await axios.post(
id: idx, `${env.API_URL}/media/imgproxy/thumbnails`,
videoUrl: {
DetermineFileType(doc.type) === "video" && GenerateSrcUrl(doc), jobid: job.id,
source: }
DetermineFileType(doc.type) === "video" );
? { uri: GenerateThumbUrl(doc) }
: { uri: GenerateSrcUrl(doc) }, setFullPhotos(
url: result.data.map((doc, idx) => {
DetermineFileType(doc.type) === "video" return {
? GenerateThumbUrl(doc) id: idx,
: GenerateSrcUrl(doc), videoUrl:
uri: DetermineFileType(doc.type) === "video" &&
DetermineFileType(doc.type) === "video" doc.originalUrlViaProxyPath,
? GenerateThumbUrl(doc) source:
: GenerateSrcUrl(doc), DetermineFileType(doc.type) === "video"
thumbUrl: GenerateThumbUrl(doc), ? { uri: doc.thumbnailUrl }
}; : { uri: doc.originalUrl },
}), url:
[job.documents] DetermineFileType(doc.type) === "video"
); ? doc.thumbnailUrl
: doc.originalUrl,
uri:
DetermineFileType(doc.type) === "video"
? doc.originalUrlViaProxyPath
: doc.originalUrl,
thumbUrl: doc.thumbnailUrl,
};
})
);
} else {
setFullPhotos(
job.documents.map((doc, idx) => {
return {
id: idx,
videoUrl:
DetermineFileType(doc.type) === "video" && GenerateSrcUrl(doc),
source:
DetermineFileType(doc.type) === "video"
? { uri: GenerateThumbUrl(doc) }
: { uri: GenerateSrcUrl(doc) },
url:
DetermineFileType(doc.type) === "video"
? GenerateThumbUrl(doc)
: GenerateSrcUrl(doc),
uri:
DetermineFileType(doc.type) === "video"
? GenerateThumbUrl(doc)
: GenerateSrcUrl(doc),
thumbUrl: GenerateThumbUrl(doc),
};
})
);
}
}
getPhotos();
}, [job.documents]);
return ( return (
<View style={{ flex: 1 }}> <View style={{ flex: 1 }}>
@@ -49,7 +108,7 @@ export default function JobDocumentsComponent({ job, loading, refetch }) {
refreshControl={ refreshControl={
<RefreshControl refreshing={loading} onRefresh={onRefresh} /> <RefreshControl refreshing={loading} onRefresh={onRefresh} />
} }
data={job.documents} data={fullphotos}
numColumns={4} numColumns={4}
style={{ flex: 1 }} style={{ flex: 1 }}
keyExtractor={(item) => item.id} keyExtractor={(item) => item.id}
@@ -65,14 +124,19 @@ export default function JobDocumentsComponent({ job, loading, refetch }) {
style={{ flex: 1 }} style={{ flex: 1 }}
resizeMode="cover" resizeMode="cover"
source={{ source={{
uri: GenerateThumbUrl(object.item), uri: object.item.thumbUrl,
aspectRatio: 1, aspectRatio: 1,
}} }}
/> />
</TouchableOpacity> </TouchableOpacity>
)} )}
/> />
<Text>{job.documents.length}</Text>
<Text
style={{ textAlign: "center", color: useImgproxy ? "blue" : "black" }}
>
{fullphotos.length}
</Text>
<MediaCacheOverlay <MediaCacheOverlay
photos={fullphotos} photos={fullphotos}

View File

@@ -20,7 +20,7 @@ export function JobSpaceAvailable({ bodyshop, style, jobid }) {
const { t } = useTranslation(); const { t } = useTranslation();
const { data } = useQuery(GET_DOC_SIZE_TOTALS, { const { data } = useQuery(GET_DOC_SIZE_TOTALS, {
variables: { jobId: jobid }, variables: { jobId: jobid },
skip: !jobid, skip: !jobid || jobid === "temp",
}); });
if (!jobid || !data) return <></>; if (!jobid || !data) return <></>;

View File

@@ -3,6 +3,7 @@ import { View } from "react-native";
import { BarIndicator } from "react-native-indicators"; import { BarIndicator } from "react-native-indicators";
export default function LoadingDisplay({ count = 5 }) { export default function LoadingDisplay({ count = 5 }) {
//TODO: This is throwing an error per expo, but it appears to be happening inside the component itself.
return ( return (
<View style={{ flex: 1, alignContent: "center", justifyContent: "center" }}> <View style={{ flex: 1, alignContent: "center", justifyContent: "center" }}>
<BarIndicator count={count} color="dodgerblue" /> <BarIndicator count={count} color="dodgerblue" />

View File

@@ -58,17 +58,15 @@ export function ScreenJobDetail({ bodyshop, route }) {
}), }),
documents: () => { documents: () => {
return bodyshop.uselocalmediaserver return bodyshop.uselocalmediaserver ? (
? JobDocumentsLocalComponent({ <JobDocumentsLocalComponent job={data.jobs_by_pk} bodyshop={bodyshop} />
job: data.jobs_by_pk, ) : (
<JobDocuments
bodyshop: bodyshop, job={data.jobs_by_pk}
}) loading={loading}
: JobDocuments({ refetch={refetch}
job: data.jobs_by_pk, />
loading: loading, );
refetch: refetch,
});
}, },
notes: () => notes: () =>

View File

@@ -24,13 +24,16 @@ import {
selectBodyshop, selectBodyshop,
selectCurrentUser, selectCurrentUser,
} from "../../redux/user/user.selectors"; } from "../../redux/user/user.selectors";
import env from "../../env";
import ScreenJobDetail from "../screen-job-detail/screen-job-detail.component"; import ScreenJobDetail from "../screen-job-detail/screen-job-detail.component";
import ScreenJobList from "../screen-job-list/screen-job-list.component"; import ScreenJobList from "../screen-job-list/screen-job-list.component";
import ScreenMediaBrowser from "../screen-media-browser/screen-media-browser.component"; import ScreenMediaBrowser from "../screen-media-browser/screen-media-browser.component";
import ScreenSettingsComponent from "../screen-settings/screen-settings.component"; import ScreenSettingsComponent from "../screen-settings/screen-settings.component";
import ScreenSignIn from "../screen-sign-in/screen-sign-in.component"; import ScreenSignIn from "../screen-sign-in/screen-sign-in.component";
import ScreenSplash from "../screen-splash/screen-splash.component"; import ScreenSplash from "../screen-splash/screen-splash.component";
import { SplitFactory } from "@splitsoftware/splitio-react-native";
import * as Updates from "expo-updates";
import LogRocket from "@logrocket/react-native";
import SignOutButton from "../Buttons/employee-sign-out-button.component"; import SignOutButton from "../Buttons/employee-sign-out-button.component";
import EmployeeSignIn from "../screen-employee-sign-in/screen-employee-sign-in.component"; import EmployeeSignIn from "../screen-employee-sign-in/screen-employee-sign-in.component";
@@ -240,6 +243,8 @@ const BottomTabsNavigator = () => (
</BottomTabs.Navigator> </BottomTabs.Navigator>
); );
export var splitClient;
export function ScreenMainComponent({ export function ScreenMainComponent({
checkUserSession, checkUserSession,
currentUser, currentUser,
@@ -249,6 +254,23 @@ export function ScreenMainComponent({
checkUserSession(); checkUserSession();
}, [checkUserSession]); }, [checkUserSession]);
useEffect(() => {
LogRocket.init("idt6oy/imex-mobile", {
updateId: Updates.isEmbeddedLaunch ? null : Updates.updateId,
expoChannel: Updates.channel,
});
}, []);
useEffect(() => {
if (bodyshop && bodyshop.imexshopid) {
splitClient = SplitFactory({
//debug: true,
core: { authorizationKey: env.SPLIT_API, key: bodyshop.imexshopid },
}).client();
splitClient.setAttribute("imexshopid", bodyshop.imexshopid);
}
}, [bodyshop]);
return ( return (
<NavigationContainer> <NavigationContainer>
{currentUser.authorized === null ? ( {currentUser.authorized === null ? (

View File

@@ -1,23 +1,27 @@
import { Ionicons } from '@expo/vector-icons'; import { Ionicons } from "@expo/vector-icons";
import { AssetsSelector } from 'expo-images-picker'; import { AssetsSelector } from "expo-images-picker";
import { MediaType } from 'expo-media-library'; import { MediaType } from "expo-media-library";
import React, { useCallback, useMemo, useState } from 'react'; import React, { useCallback, useMemo, useState } from "react";
import { useTranslation } from 'react-i18next'; import { useTranslation } from "react-i18next";
import { StyleSheet, Text, View } from 'react-native'; import { StyleSheet, Text, View } from "react-native";
import { connect } from 'react-redux'; import { connect } from "react-redux";
import { createStructuredSelector } from 'reselect'; import { createStructuredSelector } from "reselect";
import { logImEXEvent } from '../../firebase/firebase.analytics'; import { logImEXEvent } from "../../firebase/firebase.analytics";
import { toggleDeleteAfterUpload } from '../../redux/app/app.actions'; import { toggleDeleteAfterUpload } from "../../redux/app/app.actions";
import { import {
selectCurrentCameraJobId, selectCurrentCameraJobId,
selectDeleteAfterUpload, selectDeleteAfterUpload,
} from '../../redux/app/app.selectors'; } from "../../redux/app/app.selectors";
import { selectBodyshop } from '../../redux/user/user.selectors'; import { selectBodyshop } from "../../redux/user/user.selectors";
import CameraSelectJob from '../camera-select-job/camera-select-job.component'; import CameraSelectJob from "../camera-select-job/camera-select-job.component";
import JobSpaceAvailable from '../job-space-available/job-space-available.component'; import JobSpaceAvailable from "../job-space-available/job-space-available.component";
import LocalUploadProgress from '../local-upload-progress/local-upload-progress.component'; import UploadProgressLocal from "../upload-progress-local/upload-progress-local.component";
import UploadDeleteSwitch from '../upload-delete-switch/upload-delete-switch.component'; import UploadDeleteSwitch from "../upload-delete-switch/upload-delete-switch.component";
import UploadProgress from '../upload-progress/upload-progress.component'; import UploadProgress from "../upload-progress/upload-progress.component";
import { SegmentedButtons } from "react-native-paper";
// import * as ImagePicker from "expo-image-picker";
// import { Button } from "react-native-paper";
// import * as MediaLibrary from "expo-media-library";
const mapStateToProps = createStructuredSelector({ const mapStateToProps = createStructuredSelector({
selectedCameraJobId: selectCurrentCameraJobId, selectedCameraJobId: selectCurrentCameraJobId,
@@ -37,24 +41,42 @@ export function ImageBrowserScreen({
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
const [uploads, setUploads] = useState(null); const [uploads, setUploads] = useState(null);
const [density, setDensity] = useState(3);
const [tick, setTick] = useState(0); const [tick, setTick] = useState(0);
// const [medialLibraryPermissionStatus, requestmediaLibraryPermission] =
// ImagePicker.useMediaLibraryPermissions();
const forceRerender = useCallback(() => { const forceRerender = useCallback(() => {
setTick((tick) => tick + 1); setTick((tick) => tick + 1);
}, []); }, []);
const onDone = (data) => { const onDone = (data) => {
logImEXEvent('imexmobile_upload_documents', { count: data.length }); logImEXEvent("imexmobile_upload_documents", { count: data.length });
// const uploads = await Promise.all(
// data.map(async (item) => {
// let id = item.id || item.fileName;
// if (!item.id && item.uri) {
// id = await getAssetIdFromUri(item.uri, item.fileName);
// }
// return {
// ...item,
// localUri: item.uri,
// id,
// };
// })
// );
// console.log("onDone", uploads);
if (data.length !== 0) setUploads(data); if (data.length !== 0) setUploads(data);
}; };
const widgetErrors = useMemo( const widgetErrors = useMemo(
() => ({ () => ({
errorTextColor: 'black', errorTextColor: "black",
errorMessages: { errorMessages: {
hasErrorWithPermissions: 'Please Allow media gallery permissions.', hasErrorWithPermissions: "Please Allow media gallery permissions.",
hasErrorWithLoading: 'There was an error while loading images.', hasErrorWithLoading: "There was an error while loading images.",
hasErrorWithResizing: 'There was an error while loading images.', hasErrorWithResizing: "There was an error while loading images.",
hasNoAssets: 'No images found.', hasNoAssets: "No images found.",
}, },
}), }),
[] []
@@ -63,43 +85,24 @@ export function ImageBrowserScreen({
const widgetSettings = useMemo( const widgetSettings = useMemo(
() => ({ () => ({
getImageMetaData: false, // true might perform slower results but gives meta data and absolute path for ios users getImageMetaData: false, // true might perform slower results but gives meta data and absolute path for ios users
initialLoad: 100, initialLoad: 50,
assetsType: [MediaType.photo, MediaType.video], assetsType: [MediaType.photo, MediaType.video],
minSelection: 1, minSelection: 1,
// maxSelection: 3, // maxSelection: 3,
portraitCols: 4, portraitCols: density,
landscapeCols: 4, landscapeCols: density,
}), }),
[] [density]
); );
const widgetResize = useMemo(
() => ({
width: 50,
compress: 0.7,
base64: false,
saveTo: 'jpeg',
}),
[]
);
const _textStyle = {
color: 'white',
};
const _buttonStyle = {
backgroundColor: 'orange',
borderRadius: 5,
};
const widgetNavigator = useMemo( const widgetNavigator = useMemo(
() => ({ () => ({
Texts: { Texts: {
finish: t('mediabrowser.actions.upload'), finish: t("mediabrowser.actions.upload"),
back: t('mediabrowser.actions.refresh'), back: t("mediabrowser.actions.refresh"),
selected: 'selected', selected: "selected",
}, },
midTextColor: 'black', midTextColor: "black",
minSelection: 1, minSelection: 1,
buttonTextStyle: styles.textStyle, buttonTextStyle: styles.textStyle,
buttonStyle: styles.buttonStyle, buttonStyle: styles.buttonStyle,
@@ -114,32 +117,59 @@ export function ImageBrowserScreen({
const widgetStyles = useMemo( const widgetStyles = useMemo(
() => ({ () => ({
margin: 2, margin: 2,
bgColor: 'white', bgColor: "white",
spinnerColor: 'blue', spinnerColor: "blue",
widgetWidth: 99, widgetWidth: 99,
videoIcon: { videoIcon: {
Component: Ionicons, Component: Ionicons,
iconName: 'videocam', iconName: "videocam",
color: 'white', color: "white",
size: 20, size: 20,
}, },
selectedIcon: { selectedIcon: {
Component: Ionicons, Component: Ionicons,
iconName: 'checkmark-circle-outline', iconName: "checkmark-circle-outline",
color: 'white', color: "white",
bg: 'rgba(35,35,35, 0.75)', bg: "rgba(35,35,35, 0.75)",
size: 32, size: 32,
}, },
}), }),
[] []
); );
// const handleSelectPhotos = async () => {
// let result = await ImagePicker.launchImageLibraryAsync({
// mediaTypes: ["images", "videos"],
// allowsMultipleSelection: true,
// // aspect: [4, 3],
// });
// console.log("*** ~ handleSelectPhotos ~ result:", result);
// if (!result.canceled) {
// const uploads = await Promise.all(
// result.assets.map(async (item) => {
// let id = item.id || item.fileName;
// if (!item.id && item.uri) {
// id = await getAssetIdFromUri(item.uri);
// }
// return {
// ...item,
// localUri: item.uri,
// id,
// };
// })
// );
// console.log("Uploads from handleSelectPhotos", uploads);
// setUploads(uploads);
// }
// };
return ( return (
<View style={[styles.flex, styles.container]}> <View style={[styles.flex, styles.container]}>
<CameraSelectJob /> <CameraSelectJob />
{bodyshop.uselocalmediaserver ? ( {bodyshop.uselocalmediaserver ? (
<Text style={{ margin: 10 }}> <Text style={{ margin: 10 }}>
{t('mediabrowser.labels.localserver', { {t("mediabrowser.labels.localserver", {
url: bodyshop.localmediaserverhttp, url: bodyshop.localmediaserverhttp,
})} })}
</Text> </Text>
@@ -147,25 +177,35 @@ export function ImageBrowserScreen({
<JobSpaceAvailable jobid={selectedCameraJobId} key={`${tick}-space`} /> <JobSpaceAvailable jobid={selectedCameraJobId} key={`${tick}-space`} />
)} )}
<UploadDeleteSwitch /> <UploadDeleteSwitch />
{
// <Button <SegmentedButtons
// onPress={() => { value={density}
// //Mutate the state onValueChange={(value) => {
// toggleDeleteAfterUpload(); setDensity(value);
// }} forceRerender();
// > }}
// <Text>{`From screen. ${deleteAfterUpload}`}</Text> buttons={[
// </Button> {
} value: 4,
label: "Small",
},
{
value: 3,
label: "Normal",
},
{ value: 2, label: "Large" },
]}
/>
{!selectedCameraJobId && ( {!selectedCameraJobId && (
<View <View
style={{ style={{
flex: 1, flex: 1,
justifyContent: 'center', justifyContent: "center",
alignItems: 'center', alignItems: "center",
}} }}
> >
<Text>{t('mediabrowser.labels.selectjobassetselector')}</Text> <Text>{t("mediabrowser.labels.selectjobassetselector")}</Text>
</View> </View>
)} )}
{selectedCameraJobId && ( {selectedCameraJobId && (
@@ -179,7 +219,7 @@ export function ImageBrowserScreen({
/> />
)} )}
{bodyshop.uselocalmediaserver ? ( {bodyshop.uselocalmediaserver ? (
<LocalUploadProgress <UploadProgressLocal
uploads={uploads} uploads={uploads}
setUploads={setUploads} setUploads={setUploads}
forceRerender={forceRerender} forceRerender={forceRerender}
@@ -200,7 +240,7 @@ const styles = StyleSheet.create({
flex: 1, flex: 1,
}, },
container: { container: {
display: 'flex', display: "flex",
// position: "relative", // position: "relative",
}, },
buttonStyle: { buttonStyle: {
@@ -208,7 +248,7 @@ const styles = StyleSheet.create({
}, },
// eslint-disable-next-line react-native/no-color-literals // eslint-disable-next-line react-native/no-color-literals
textStyle: { textStyle: {
color: 'dodgerblue', color: "dodgerblue",
}, },
}); });
@@ -270,3 +310,32 @@ export default connect(mapStateToProps, mapDispatchToProps)(ImageBrowserScreen);
// }, // },
// }, // },
// }} // }}
// // Utility to get asset ID from URI if missing
// async function getAssetIdFromUri(uri, filename = null, maxPages = 10) {
// let after = null;
// let found = null;
// let pageCount = 0;
// while (!found && pageCount < maxPages) {
// const page = await MediaLibrary.getAssetsAsync({
// first: 100,
// mediaType: [MediaLibrary.MediaType.photo, MediaLibrary.MediaType.video],
// after,
// });
// // Try to match by URI
// found = page.assets.find((asset) => asset.uri === uri);
// // Fallback: try to match by filename if not found and filename is available
// if (!found && filename) {
// found = page.assets.find((asset) => asset.filename === filename);
// }
// after = page.endCursor;
// pageCount++;
// if (!after) break;
// }
// return found ? found.id : null;
// }

View File

@@ -6,6 +6,7 @@ import { Title, Button } from "react-native-paper";
import { purgeStoredState } from "redux-persist"; import { purgeStoredState } from "redux-persist";
import SignOutButton from "../sign-out-button/sign-out-button.component"; import SignOutButton from "../sign-out-button/sign-out-button.component";
import * as Updates from "expo-updates"; import * as Updates from "expo-updates";
import * as Application from "expo-application";
export default function ScreenSettingsComponent() { export default function ScreenSettingsComponent() {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -21,7 +22,7 @@ export default function ScreenSettingsComponent() {
> >
<Title> <Title>
{t("settings.labels.version", { {t("settings.labels.version", {
number: `${Constants.expoConfig.version}-${Constants.expoConfig.extra.expover}`, number: `${Constants.expoConfig.version}(${Application.nativeBuildVersion} - ${Constants.expoConfig.extra.expover})`,
})} })}
</Title> </Title>

View File

@@ -70,6 +70,8 @@ export function SignIn({ emailSignInStart, signingIn }) {
label={t("signin.fields.password")} label={t("signin.fields.password")}
mode="outlined" mode="outlined"
secureTextEntry={true} secureTextEntry={true}
autoCorrect={false}
autoCapitalize="none"
onChangeText={handleChange("password")} onChangeText={handleChange("password")}
onBlur={handleBlur("password")} onBlur={handleBlur("password")}
value={values.password} value={values.password}

View File

@@ -1,11 +1,11 @@
import React from 'react'; import React from "react";
import { useTranslation } from 'react-i18next'; import { useTranslation } from "react-i18next";
import { StyleSheet, Text, View } from 'react-native'; import { StyleSheet, Text, View } from "react-native";
import { Checkbox } from 'react-native-paper'; import { Checkbox, Switch } from "react-native-paper";
import { connect } from 'react-redux'; import { connect } from "react-redux";
import { createStructuredSelector } from 'reselect'; import { createStructuredSelector } from "reselect";
import { toggleDeleteAfterUpload } from '../../redux/app/app.actions'; import { toggleDeleteAfterUpload } from "../../redux/app/app.actions";
import { selectDeleteAfterUpload } from '../../redux/app/app.selectors'; import { selectDeleteAfterUpload } from "../../redux/app/app.selectors";
const mapStateToProps = createStructuredSelector({ const mapStateToProps = createStructuredSelector({
deleteAfterUpload: selectDeleteAfterUpload, deleteAfterUpload: selectDeleteAfterUpload,
@@ -19,31 +19,30 @@ export function UploadDeleteSwitch({
deleteAfterUpload, deleteAfterUpload,
toggleDeleteAfterUpload, toggleDeleteAfterUpload,
}) { }) {
console.log("*** ~ deleteAfterUpload:", deleteAfterUpload);
const { t } = useTranslation(); const { t } = useTranslation();
console.log('🚀 ~ deleteAfterUpload:', deleteAfterUpload);
return ( return (
<View style={styles.container}> <View style={styles.container}>
<Text style={styles.text}> <Text style={styles.text}>
{t('mediabrowser.labels.deleteafterupload')} {t("mediabrowser.labels.deleteafterupload")}
</Text> </Text>
<Checkbox <Switch
// trackColor={{ false: '#767577', true: '#81b0ff' }} // trackColor={{ false: '#767577', true: '#81b0ff' }}
// thumbColor={deleteAfterUpload ? 'tomato' : '#f4f3f4'} // thumbColor={deleteAfterUpload ? 'tomato' : '#f4f3f4'}
// ios_backgroundColor='#3e3e3e' //ios_backgroundColor="#3e3e3e"
onPress={() => { onValueChange={() => {
toggleDeleteAfterUpload(); toggleDeleteAfterUpload();
}} }}
status={deleteAfterUpload ? 'checked' : 'unchecked'} value={deleteAfterUpload}
/> />
</View> </View>
); );
} }
const styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
display: 'flex', display: "flex",
flexDirection: 'row', flexDirection: "row",
alignItems: 'center', alignItems: "center",
margin: 10, margin: 10,
}, },

View File

@@ -1,27 +1,28 @@
import * as MediaLibrary from 'expo-media-library'; import * as MediaLibrary from "expo-media-library";
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from "react";
import { import {
ActivityIndicator, ActivityIndicator,
Alert, Alert,
Modal, Modal,
Platform,
StyleSheet, StyleSheet,
Text, Text,
View, View,
} from 'react-native'; } from "react-native";
import { ProgressBar } from 'react-native-paper'; import { ProgressBar } from "react-native-paper";
import Toast from 'react-native-toast-message'; import Toast from "react-native-toast-message";
import { connect } from 'react-redux'; import { connect } from "react-redux";
import { createStructuredSelector } from 'reselect'; import { createStructuredSelector } from "reselect";
import { logImEXEvent } from '../../firebase/firebase.analytics'; import { logImEXEvent } from "../../firebase/firebase.analytics";
import { import {
selectCurrentCameraJobId, selectCurrentCameraJobId,
selectDeleteAfterUpload, selectDeleteAfterUpload,
} from '../../redux/app/app.selectors'; } from "../../redux/app/app.selectors";
import * as Sentry from '@sentry/react-native'; import * as Sentry from "@sentry/react-native";
import { formatBytes } from '../../util/document-upload.utility'; import { formatBytes } from "../../util/document-upload.utility";
import { handleLocalUpload } from '../../util/local-document-upload.utility'; import { handleLocalUpload } from "../../util/local-document-upload.utility";
const mapStateToProps = createStructuredSelector({ const mapStateToProps = createStructuredSelector({
selectedCameraJobId: selectCurrentCameraJobId, selectedCameraJobId: selectCurrentCameraJobId,
@@ -54,36 +55,46 @@ export function UploadProgress({
async function handleOnSuccess({ duration, data }) { async function handleOnSuccess({ duration, data }) {
//If it's not in production, show a toast with the time. //If it's not in production, show a toast with the time.
Toast.show({ Toast.show({
type: 'success', type: "success",
text1: ` Upload completed in ${duration}.`, text1: ` Upload completed in ${duration}.`,
// //
// text2: duration, // text2: duration,
}); });
if (deleteAfterUpload) { if (deleteAfterUpload) {
try { try {
await MediaLibrary.deleteAssetsAsync(data); if (Platform.OS === "android") {
//Create a new asset with the first file to delete.
// console.log('Trying new delete.');
await MediaLibrary.getPermissionsAsync(false);
const album = await MediaLibrary.createAlbumAsync( const album = await MediaLibrary.createAlbumAsync(
'ImEX Mobile Deleted', "ImEX Mobile Deleted",
data.pop(), data.pop(),
false
);
//Move the rest.
if (data.length > 0) {
const moveResult = await MediaLibrary.addAssetsToAlbumAsync(
data,
album,
false false
); );
//Move the rest.
if (data.length > 0) {
const moveResult = await MediaLibrary.addAssetsToAlbumAsync(
data,
album,
false
);
}
const deleteResult = await MediaLibrary.deleteAlbumsAsync(album);
//Delete the album.
//This defaults to delete all assets in the album.
} else {
await MediaLibrary.deleteAssetsAsync(data.map((f) => f.id));
} }
const deleteResult = await MediaLibrary.deleteAlbumsAsync(album);
} catch (error) { } catch (error) {
console.log('Unable to delete picture.', error); console.log("Unable to delete picture.", error);
Sentry.Native.captureException(error); Sentry.captureException(error);
} }
} }
logImEXEvent('imexmobile_successful_upload'); logImEXEvent("imexmobile_successful_upload");
forceRerender(); forceRerender();
setProgress({ ...progress, speed: 0, percent: 1, uploadInProgress: false }); setProgress({ ...progress, speed: 0, percent: 1, uploadInProgress: false });
} }
@@ -98,10 +109,10 @@ export function UploadProgress({
} }
function handleOnError({ assetid, error }) { function handleOnError({ assetid, error }) {
logImEXEvent('imexmobile_upload_documents_error'); logImEXEvent("imexmobile_upload_documents_error");
Toast.show({ Toast.show({
type: 'error', type: "error",
text1: 'Unable to upload documents.', text1: "Unable to upload documents.",
text2: error, text2: error,
autoHide: false, autoHide: false,
}); });
@@ -130,7 +141,7 @@ export function UploadProgress({
onSuccess: ({ duration }) => handleOnSuccess({ duration, data }), onSuccess: ({ duration }) => handleOnSuccess({ duration, data }),
context: { context: {
jobid: jobid:
selectedCameraJobId !== 'temp' ? selectedCameraJobId : 'temporary', selectedCameraJobId !== "temp" ? selectedCameraJobId : "temporary",
}, },
}); });
}; };
@@ -138,41 +149,41 @@ export function UploadProgress({
return ( return (
<Modal <Modal
visible={progress.uploadInProgress} visible={progress.uploadInProgress}
animationType='slide' animationType="slide"
transparent={true} transparent={true}
onRequestClose={() => { onRequestClose={() => {
Alert.alert('Cancel?', 'Do you want to abort the upload?', [ Alert.alert("Cancel?", "Do you want to abort the upload?", [
{ {
text: 'Yes', text: "Yes",
onPress: () => { onPress: () => {
setUploads(null); setUploads(null);
setProgress(null); setProgress(null);
}, },
}, },
{ text: 'No' }, { text: "No" },
]); ]);
}} }}
> >
<View style={styles.modalContainer}> <View style={styles.modalContainer}>
<View style={styles.modal}> <View style={styles.modal}>
<ActivityIndicator style={{ alignSelf: 'center', marginTop: 16 }} /> <ActivityIndicator style={{ alignSelf: "center", marginTop: 16 }} />
<ProgressBar <ProgressBar
progress={progress.percent} progress={progress.percent}
style={{ alignSelf: 'center', marginTop: 16 }} style={{ alignSelf: "center", marginTop: 16 }}
color={progress.percent === 1 ? 'green' : 'blue'} color={progress.percent === 1 ? "green" : "blue"}
/> />
<Text style={{ alignSelf: 'center', marginTop: 16 }}>{`${formatBytes( <Text style={{ alignSelf: "center", marginTop: 16 }}>{`${formatBytes(
progress.speed progress.speed
)}/sec`}</Text> )}/sec`}</Text>
<Text <Text
style={{ alignSelf: 'center', marginTop: 16 }} style={{ alignSelf: "center", marginTop: 16 }}
>{`Avg. ${formatBytes( >{`Avg. ${formatBytes(
progress.loaded / ((new Date() - progress.start) / 1000) progress.loaded / ((new Date() - progress.start) / 1000)
)}/sec`}</Text> )}/sec`}</Text>
<Text <Text
style={{ alignSelf: 'center', marginTop: 16 }} style={{ alignSelf: "center", marginTop: 16 }}
>{`Total Uploaded ${formatBytes(progress.loaded)}`}</Text> >{`Total Uploaded ${formatBytes(progress.loaded)}`}</Text>
<Text style={{ alignSelf: 'center', marginTop: 16 }}>{`Duration ${( <Text style={{ alignSelf: "center", marginTop: 16 }}>{`Duration ${(
(new Date() - progress.start) / (new Date() - progress.start) /
1000 1000
).toFixed(1)} sec`}</Text> ).toFixed(1)} sec`}</Text>
@@ -183,19 +194,19 @@ export function UploadProgress({
} }
const styles = StyleSheet.create({ const styles = StyleSheet.create({
modalContainer: { modalContainer: {
display: 'flex', display: "flex",
flex: 1, flex: 1,
justifyContent: 'center', justifyContent: "center",
}, },
modal: { modal: {
// flex: 1, // flex: 1,
display: 'flex', display: "flex",
marginLeft: 20, marginLeft: 20,
marginRight: 20, marginRight: 20,
backgroundColor: 'white', backgroundColor: "white",
borderRadius: 20, borderRadius: 20,
padding: 18, padding: 18,
shadowColor: '#000', shadowColor: "#000",
shadowOffset: { shadowOffset: {
width: 0, width: 0,
height: 2, height: 2,

View File

@@ -1,8 +1,8 @@
import { useApolloClient } from '@apollo/client'; import { useApolloClient } from "@apollo/client";
import * as FileSystem from 'expo-file-system'; import * as FileSystem from "expo-file-system";
import * as MediaLibrary from 'expo-media-library'; import * as MediaLibrary from "expo-media-library";
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from "react";
import { useTranslation } from 'react-i18next'; import { useTranslation } from "react-i18next";
import { import {
ActivityIndicator, ActivityIndicator,
Alert, Alert,
@@ -11,23 +11,23 @@ import {
StyleSheet, StyleSheet,
Text, Text,
View, View,
} from 'react-native'; } from "react-native";
import { Divider, ProgressBar } from 'react-native-paper'; import { Divider, ProgressBar } from "react-native-paper";
import Toast from 'react-native-toast-message'; import Toast from "react-native-toast-message";
import { connect } from 'react-redux'; import { connect } from "react-redux";
import { createStructuredSelector } from 'reselect'; import { createStructuredSelector } from "reselect";
import * as Sentry from '@sentry/react-native'; import * as Sentry from "@sentry/react-native";
import { logImEXEvent } from '../../firebase/firebase.analytics'; import { logImEXEvent } from "../../firebase/firebase.analytics";
import { GET_DOC_SIZE_TOTALS } from '../../graphql/documents.queries'; import { GET_DOC_SIZE_TOTALS } from "../../graphql/documents.queries";
import { import {
selectCurrentCameraJobId, selectCurrentCameraJobId,
selectDeleteAfterUpload, selectDeleteAfterUpload,
} from '../../redux/app/app.selectors'; } from "../../redux/app/app.selectors";
import { import {
selectBodyshop, selectBodyshop,
selectCurrentUser, selectCurrentUser,
} from '../../redux/user/user.selectors'; } from "../../redux/user/user.selectors";
import { formatBytes, handleUpload } from '../../util/document-upload.utility'; import { formatBytes, handleUpload } from "../../util/document-upload.utility";
const mapStateToProps = createStructuredSelector({ const mapStateToProps = createStructuredSelector({
currentUser: selectCurrentUser, currentUser: selectCurrentUser,
@@ -110,10 +110,10 @@ export function UploadProgress({
}); });
} }
function handleOnError(error) { function handleOnError(error) {
logImEXEvent('imexmobile_upload_documents_error', { error }); logImEXEvent("imexmobile_upload_documents_error", { error });
Toast.show({ Toast.show({
type: 'error', type: "error",
text1: 'Unable to upload document.', text1: "Unable to upload document.",
text2: error, text2: error,
autoHide: false, autoHide: false,
}); });
@@ -124,7 +124,7 @@ export function UploadProgress({
return { return {
...progress, ...progress,
uploadInProgress: true, uploadInProgress: true,
statusText: 'Preparing upload...', statusText: "Preparing upload...",
}; };
}); });
@@ -132,16 +132,20 @@ export function UploadProgress({
const data = []; const data = [];
const totalOfUploads = await selectedFiles.reduce(async (acc, val) => { const totalOfUploads = await selectedFiles.reduce(async (acc, val) => {
//Get the size of the file based on URI. //Get the size of the file based on URI.
const info = await FileSystem.getInfoAsync(val.uri, { size: true }); if (acc.fileSize) {
data.push({ ...info, ...val }); //Add in the size. return acc + acc.fileSize;
val.albumId && MediaLibrary.migrateAlbumIfNeededAsync(val.albumId); } else {
return (await acc) + info.size; const info = await FileSystem.getInfoAsync(val.uri, { size: true });
data.push({ ...info, ...val }); //Add in the size.
val.albumId && MediaLibrary.migrateAlbumIfNeededAsync(val.albumId);
return (await acc) + info.size;
}
}, 0); }, 0);
if (selectedCameraJobId !== 'temp') { if (selectedCameraJobId !== "temp") {
const queryData = await client.query({ const queryData = await client.query({
query: GET_DOC_SIZE_TOTALS, query: GET_DOC_SIZE_TOTALS,
fetchPolicy: 'network-only', fetchPolicy: "network-only",
variables: { variables: {
jobId: selectedCameraJobId, jobId: selectedCameraJobId,
}, },
@@ -161,8 +165,8 @@ export function UploadProgress({
uploadInProgress: false, uploadInProgress: false,
})); }));
Alert.alert( Alert.alert(
t('mediabrowser.labels.storageexceeded_title'), t("mediabrowser.labels.storageexceeded_title"),
t('mediabrowser.labels.storageexceeded') t("mediabrowser.labels.storageexceeded")
); );
return; return;
} }
@@ -203,14 +207,13 @@ export function UploadProgress({
//Everything is uploaded, delete the succesful ones. //Everything is uploaded, delete the succesful ones.
if (deleteAfterUpload) { if (deleteAfterUpload) {
try { try {
console.log('Trying to Delete', filesToDelete); if (Platform.OS === "android") {
if (Platform.OS === 'android') {
//Create a new asset with the first file to delete. //Create a new asset with the first file to delete.
// console.log('Trying new delete.'); // console.log('Trying new delete.');
await MediaLibrary.getPermissionsAsync(false); await MediaLibrary.getPermissionsAsync(false);
const album = await MediaLibrary.createAlbumAsync( const album = await MediaLibrary.createAlbumAsync(
'ImEX Mobile Deleted', "ImEX Mobile Deleted",
filesToDelete.pop(), filesToDelete.pop(),
false false
); );
@@ -231,13 +234,13 @@ export function UploadProgress({
await MediaLibrary.deleteAssetsAsync(filesToDelete.map((f) => f.id)); await MediaLibrary.deleteAssetsAsync(filesToDelete.map((f) => f.id));
} }
} catch (error) { } catch (error) {
console.log('Unable to delete picture.', error); console.log("Unable to delete picture.", error);
Sentry.Native.captureException(error); Sentry.captureException(error);
} }
} }
filesToDelete = []; filesToDelete = [];
Toast.show({ Toast.show({
type: 'success', type: "success",
text1: ` Upload completed.`, text1: ` Upload completed.`,
// //
// text2: duration, // text2: duration,
@@ -269,7 +272,7 @@ export function UploadProgress({
}, },
{ {
bodyshop: bodyshop, bodyshop: bodyshop,
jobId: selectedCameraJobId !== 'temp' ? selectedCameraJobId : null, jobId: selectedCameraJobId !== "temp" ? selectedCameraJobId : null,
uploaded_by: currentUser.email, uploaded_by: currentUser.email,
photo: p, photo: p,
} }
@@ -279,12 +282,12 @@ export function UploadProgress({
return ( return (
<Modal <Modal
visible={progress.uploadInProgress} visible={progress.uploadInProgress}
animationType='slide' animationType="slide"
transparent={true} transparent={true}
onRequestClose={() => { onRequestClose={() => {
Alert.alert('Cancel?', 'Do you want to abort the upload?', [ Alert.alert("Cancel?", "Do you want to abort the upload?", [
{ {
text: 'Yes', text: "Yes",
onPress: () => { onPress: () => {
setUploads(null); setUploads(null);
setProgress({ setProgress({
@@ -299,7 +302,7 @@ export function UploadProgress({
}); });
}, },
}, },
{ text: 'No' }, { text: "No" },
]); ]);
}} }}
> >
@@ -314,13 +317,13 @@ export function UploadProgress({
<ProgressBar <ProgressBar
progress={progress.files[key].percent} progress={progress.files[key].percent}
style={styles.progress} style={styles.progress}
color={progress.files[key].percent === 1 ? 'green' : 'blue'} color={progress.files[key].percent === 1 ? "green" : "blue"}
/> />
<View <View
style={{ style={{
display: 'flex', display: "flex",
flexDirection: 'row', flexDirection: "row",
alignItems: 'center', alignItems: "center",
}} }}
> >
<Text>{`${formatBytes( <Text>{`${formatBytes(
@@ -362,19 +365,19 @@ export function UploadProgress({
} }
const styles = StyleSheet.create({ const styles = StyleSheet.create({
modalContainer: { modalContainer: {
display: 'flex', display: "flex",
flex: 1, flex: 1,
justifyContent: 'center', justifyContent: "center",
}, },
modal: { modal: {
//flex: 1, //flex: 1,
display: 'flex', display: "flex",
marginLeft: 20, marginLeft: 20,
marginRight: 20, marginRight: 20,
backgroundColor: 'white', backgroundColor: "white",
borderRadius: 20, borderRadius: 20,
padding: 18, padding: 18,
shadowColor: '#000', shadowColor: "#000",
shadowOffset: { shadowOffset: {
width: 0, width: 0,
height: 2, height: 2,
@@ -384,14 +387,14 @@ const styles = StyleSheet.create({
elevation: 5, elevation: 5,
}, },
centeredView: { centeredView: {
justifyContent: 'center', justifyContent: "center",
alignItems: 'center', alignItems: "center",
marginTop: 22, marginTop: 22,
}, },
progressItem: { progressItem: {
display: 'flex', display: "flex",
flexDirection: 'row', flexDirection: "row",
alignItems: 'center', alignItems: "center",
marginBottom: 12, marginBottom: 12,
marginLeft: 12, marginLeft: 12,
marginRight: 12, marginRight: 12,

View File

@@ -1,18 +1,35 @@
{ {
"cli": { "cli": {
"version": ">= 0.52.0" "version": ">= 0.52.0",
"appVersionSource": "remote"
}, },
"build": { "build": {
"development": { "development": {
"developmentClient": true, "developmentClient": true,
"channel": "test", "channel": "test",
"distribution": "internal" "distribution": "internal",
"ios": {},
"autoIncrement": true
},
"development-simulator": {
"developmentClient": true,
"channel": "test",
"distribution": "internal",
"ios": {
"simulator": true
},
"autoIncrement": true
}, },
"test": { "test": {
"channel": "test" "channel": "test",
// "android": {
// "buildType": "apk"
// },
"autoIncrement": true
}, },
"production": { "production": {
"channel": "production" "channel": "production",
"autoIncrement": true
} }
}, },
"submit": { "submit": {

16
env.js
View File

@@ -10,6 +10,7 @@ const ENV = {
REACT_APP_CLOUDINARY_ENDPOINT: "https://res.cloudinary.com/bodyshop", REACT_APP_CLOUDINARY_ENDPOINT: "https://res.cloudinary.com/bodyshop",
REACT_APP_CLOUDINARY_API_KEY: "473322739956866", REACT_APP_CLOUDINARY_API_KEY: "473322739956866",
REACT_APP_CLOUDINARY_THUMB_TRANSFORMATIONS: "c_fill,h_250,w_250", REACT_APP_CLOUDINARY_THUMB_TRANSFORMATIONS: "c_fill,h_250,w_250",
SPLIT_API: "ts615lqgnmk84thn72uk18uu5pgce6e0l4rc",
firebase: { firebase: {
apiKey: "AIzaSyBw7_GTy7GtQyfkIRPVrWHEGKfcqeyXw0c", apiKey: "AIzaSyBw7_GTy7GtQyfkIRPVrWHEGKfcqeyXw0c",
authDomain: "imex-test.firebaseapp.com", authDomain: "imex-test.firebaseapp.com",
@@ -29,6 +30,7 @@ const ENV = {
"https://api.cloudinary.com/v1_1/bodyshop", "https://api.cloudinary.com/v1_1/bodyshop",
REACT_APP_CLOUDINARY_ENDPOINT: "https://res.cloudinary.com/bodyshop", REACT_APP_CLOUDINARY_ENDPOINT: "https://res.cloudinary.com/bodyshop",
REACT_APP_CLOUDINARY_API_KEY: "473322739956866", REACT_APP_CLOUDINARY_API_KEY: "473322739956866",
SPLIT_API: "et9pjkik6bn67he5evpmpr1agoo7gactphgk",
REACT_APP_CLOUDINARY_THUMB_TRANSFORMATIONS: "c_fill,h_250,w_250", REACT_APP_CLOUDINARY_THUMB_TRANSFORMATIONS: "c_fill,h_250,w_250",
firebase: { firebase: {
apiKey: "AIzaSyAuLQR9SV5LsVxjU8wh9hvFLdhcAHU6cxE", apiKey: "AIzaSyAuLQR9SV5LsVxjU8wh9hvFLdhcAHU6cxE",
@@ -43,19 +45,7 @@ const ENV = {
}; };
function getEnvVars() { function getEnvVars() {
if (process.env.NODE_ENV === "development") return ENV.test; if (Updates.channel !== "production") return ENV.test;
let releaseChannel = Updates.channel;
if (
releaseChannel === null ||
releaseChannel === undefined ||
releaseChannel === ""
)
return ENV.test;
if (releaseChannel.indexOf("development") !== -1) return ENV.test;
if (releaseChannel.indexOf("test") !== -1) return ENV.test;
if (releaseChannel.indexOf("default") !== -1) return ENV.prod;
else return ENV.prod; else return ENV.prod;
} }

View File

@@ -16,6 +16,7 @@ export const QUERY_BODYSHOP = gql`
tt_allow_post_to_invoiced tt_allow_post_to_invoiced
md_responsibility_centers md_responsibility_centers
tt_enforce_hours_for_tech_console tt_enforce_hours_for_tech_console
imexshopid
} }
} }
`; `;

View File

@@ -1,41 +1,12 @@
//GQL Imports import { ApolloClient, from, HttpLink, InMemoryCache } from "@apollo/client";
import {
ApolloClient,
from,
HttpLink,
InMemoryCache,
split,
} from "@apollo/client";
import { setContext } from "@apollo/client/link/context"; import { setContext } from "@apollo/client/link/context";
import { onError } from "@apollo/client/link/error"; import { onError } from "@apollo/client/link/error";
import { RetryLink } from "@apollo/client/link/retry"; import { RetryLink } from "@apollo/client/link/retry";
import { WebSocketLink } from "@apollo/client/link/ws";
import { getMainDefinition } from "@apollo/client/utilities";
import { auth } from "../firebase/firebase.utils";
import env from "../env";
const httpLink = new HttpLink({
// uri: "https://bodyshop-dev-db.herokuapp.com/v1/graphql",
uri: env.uri,
});
const wsLink = new WebSocketLink({ import env from "../env";
//uri: "wss://bodyshop-dev-db.herokuapp.com/v1/graphql", import { auth } from "../firebase/firebase.utils";
uri: "wss://db.imex.online/v1/graphql", const httpLink = new HttpLink({
options: { uri: env.uri,
lazy: true,
reconnect: true,
connectionParams: async () => {
const token =
auth.currentUser && (await auth.currentUser.getIdToken(true));
if (token) {
return {
headers: {
authorization: token ? `Bearer ${token}` : "",
},
};
}
},
},
}); });
//https://stackoverflow.com/questions/57163454/refreshing-a-token-with-apollo-client-firebase-auth //https://stackoverflow.com/questions/57163454/refreshing-a-token-with-apollo-client-firebase-auth
@@ -61,27 +32,27 @@ const subscriptionMiddleware = {
next(); next();
}, },
}; };
wsLink.subscriptionClient.use([subscriptionMiddleware]); //wsLink.subscriptionClient.use([subscriptionMiddleware]);
const link = split( // const link = split(
// split based on operation type // // split based on operation type
({ query }) => { // ({ query }) => {
const definition = getMainDefinition(query); // const definition = getMainDefinition(query);
// console.log( // // console.log(
// "##Intercepted GQL Transaction : " + // // "##Intercepted GQL Transaction : " +
// definition.operation + // // definition.operation +
// "|" + // // "|" +
// // definition.name.value + // // // definition.name.value +
// "##" // // "##"
// ); // // );
return ( // return (
definition.kind === "OperationDefinition" && // definition.kind === "OperationDefinition" &&
definition.operation === "subscription" // definition.operation === "subscription"
); // );
}, // },
wsLink, // wsLink,
httpLink // httpLink
); // );
const authLink = setContext((_, { headers }) => { const authLink = setContext((_, { headers }) => {
return ( return (
@@ -113,23 +84,14 @@ const retryLink = new RetryLink({
}, },
}); });
// const middlewares = [];
// if (process.env.NODE_ENV === "development") {
// middlewares.push(apolloLogger);
// }
// middlewares.push(retryLink.concat(errorLink.concat(authLink.concat(link))));
const cache = new InMemoryCache({}); const cache = new InMemoryCache({});
export const client = new ApolloClient({ export const client = new ApolloClient({
//link: ApolloLink.from(middlewares), //link: ApolloLink.from(middlewares),
//link: from([apolloLogger, errorLink, authLink, link]), //link: from([apolloLogger, errorLink, authLink, link]),
link: from([authLink, link]), link: from([authLink, retryLink, errorLink, httpLink]),
cache, cache,
notifyOnNetworkStatusChange: true, notifyOnNetworkStatusChange: true,
// connectToDevTools: process.env.NODE_ENV !== "production",
defaultOptions: { defaultOptions: {
watchQuery: { watchQuery: {
fetchPolicy: "network-only", fetchPolicy: "network-only",

12526
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -2,8 +2,8 @@
"main": "node_modules/expo/AppEntry.js", "main": "node_modules/expo/AppEntry.js",
"scripts": { "scripts": {
"start": "expo start", "start": "expo start",
"android": "expo start --android", "android": "expo run:android",
"ios": "expo start --ios", "ios": "expo run:ios",
"web": "expo start --web", "web": "expo start --web",
"eject": "expo eject", "eject": "expo eject",
"release:test": "expo publish --release-channel test", "release:test": "expo publish --release-channel test",
@@ -16,85 +16,92 @@
"build:production:local:android": "eas build --profile production --platform android --local" "build:production:local:android": "eas build --profile production --platform android --local"
}, },
"dependencies": { "dependencies": {
"@apollo/client": "^3.9.5", "@apollo/client": "^3.12.11",
"@babel/preset-env": "7.1.6", "@babel/preset-env": "7.26.8",
"@expo/vector-icons": "^14.0.0", "@expo/vector-icons": "^14.0.4",
"@react-native-async-storage/async-storage": "1.21.0", "@logrocket/react-native": "^1.52.2",
"@react-native-community/cli-debugger-ui": "^9.0.0", "@react-native-async-storage/async-storage": "1.23.1",
"@react-native-community/datetimepicker": "7.6.1", "@react-native-community/cli-debugger-ui": "^15.1.3",
"@react-native-community/datetimepicker": "8.2.0",
"@react-native-community/masked-view": "^0.1.11", "@react-native-community/masked-view": "^0.1.11",
"@react-navigation/bottom-tabs": "^6.3.3", "@react-navigation/bottom-tabs": "^7.2.0",
"@react-navigation/drawer": "^6.4.4", "@react-navigation/drawer": "^7.1.1",
"@react-navigation/native": "^6.0.12", "@react-navigation/native": "^7.0.14",
"@react-navigation/native-stack": "^6.8.0", "@react-navigation/native-stack": "^7.2.0",
"@react-navigation/stack": "^6.2.3", "@react-navigation/stack": "^7.1.1",
"@sentry/react-native": "5.19.1", "@sentry/react-native": "~6.10.0",
"axios": "^1.6.7", "@splitsoftware/splitio-react-native": "^1.1.0",
"cloudinary-core": "^2.13.0", "axios": "^1.9.0",
"cloudinary-core": "^2.13.1",
"dinero.js": "^1.9.1", "dinero.js": "^1.9.1",
"expo": "~50.0.8", "expo": "~52.0.46",
"expo-application": "~5.8.3", "expo-application": "~6.0.2",
"expo-av": "~13.10.5", "expo-av": "~15.0.2",
"expo-constants": "~15.4.5", "expo-build-properties": "~0.13.3",
"expo-dev-client": "~3.3.9", "expo-constants": "~17.0.5",
"expo-device": "~5.9.3", "expo-dev-client": "~5.0.20",
"expo-file-system": "~16.0.6", "expo-device": "~7.0.3",
"expo-font": "~11.10.3", "expo-file-system": "~18.0.10",
"expo-image-manipulator": "~11.8.0", "expo-font": "~13.0.3",
"expo-images-picker": "^2.4.1", "expo-image-manipulator": "~13.0.6",
"expo-localization": "~14.8.3", "expo-image-picker": "~16.0.6",
"expo-media-library": "~15.9.1", "expo-images-picker": "^2.5.1",
"expo-status-bar": "~1.11.1", "expo-localization": "~16.0.1",
"expo-system-ui": "~2.9.3", "expo-media-library": "~17.0.6",
"expo-updates": "~0.24.11", "expo-notifications": "~0.29.14",
"expo-video-thumbnails": "~7.9.0", "expo-status-bar": "~2.0.1",
"firebase": "^10.8.0", "expo-system-ui": "~4.0.9",
"formik": "^2.4.5", "expo-updates": "~0.27.4",
"graphql": "^16.8.1", "expo-video-thumbnails": "~9.0.3",
"i18next": "^21.9.1", "firebase": "^11.3.1",
"formik": "^2.4.6",
"graphql": "^16.10.0",
"i18next": "^24.2.2",
"intl": "^1.2.5", "intl": "^1.2.5",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"luxon": "^3.4.4", "luxon": "^3.5.0",
"mime": "^3.0.0", "mime": "^4.0.6",
"moment": "^2.30.1", "moment": "^2.30.1",
"normalize-url": "^7.0.3", "normalize-url": "^8.0.1",
"react": "^18.2.0", "react": "18.3.1",
"react-dom": "^18.2.0", "react-dom": "18.3.1",
"react-i18next": "^14.0.5", "react-i18next": "^15.4.0",
"react-is": ">=18.2.0", "react-is": ">=19.0.0",
"react-native": "0.73.4", "react-native": "0.76.9",
"react-native-draggable-flatlist": "^4.0.1", "react-native-draggable-flatlist": "^4.0.1",
"react-native-element-dropdown": "^2.10.1", "react-native-element-dropdown": "^2.12.4",
"react-native-gesture-handler": "~2.14.0", "react-native-event-source": "^1.1.0",
"react-native-gesture-handler": "~2.20.2",
"react-native-image-gallery": "^2.1.5", "react-native-image-gallery": "^2.1.5",
"react-native-image-viewing": "^0.2.2", "react-native-image-viewing": "^0.2.2",
"react-native-indicators": "^0.17.0", "react-native-indicators": "^0.17.0",
"react-native-modal-datetime-picker": "^17.1.0", "react-native-modal-datetime-picker": "^18.0.0",
"react-native-pager-view": "6.2.3", "react-native-pager-view": "6.5.1",
"react-native-paper": "^5.12.3", "react-native-paper": "^5.13.1",
"react-native-progress": "^5.0.1", "react-native-progress": "^5.0.1",
"react-native-reanimated": "~3.6.2", "react-native-reanimated": "~3.16.7",
"react-native-safe-area-context": "4.8.2", "react-native-safe-area-context": "4.12.0",
"react-native-screens": "~3.29.0", "react-native-screens": "~4.4.0",
"react-native-svg": "14.1.0", "react-native-svg": "15.8.0",
"react-native-tab-view": "3.5.2", "react-native-tab-view": "4.0.5",
"react-native-toast-message": "^2.2.0", "react-native-toast-message": "^2.2.1",
"react-native-vector-icons": "*", "react-native-vector-icons": "*",
"react-native-web": "~0.19.10", "react-native-web": "~0.19.13",
"react-redux": "^9.1.0", "react-redux": "^9.2.0",
"redux": "^5.0.1", "redux": "^5.0.1",
"redux-logger": "^3.0.6", "redux-logger": "^3.0.6",
"redux-persist": "^6.0.0", "redux-persist": "^6.0.0",
"redux-saga": "^1.3.0", "redux-saga": "^1.3.0",
"reselect": "^5.1.0", "reselect": "^5.1.1"
"subscriptions-transport-ws": "^0.9.18"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.23.9", "@babel/core": "^7.26.8",
"babel-preset-expo": "^10.0.1", "babel-preset-expo": "~12.0.7",
"eslint": "^8.57.0", "eslint": "^9.20.1",
"eslint-plugin-react": "^7.33.2", "eslint-plugin-react": "^7.37.4",
"eslint-plugin-react-native": "^4.1.0" "eslint-plugin-react-native": "^5.0.0"
}, },
"private": true "private": true,
"name": "imexmobile",
"version": "1.0.0"
} }

View File

@@ -40,7 +40,6 @@ const appReducer = (state = INITIAL_STATE, action) => {
documentUploadInProgress: null, documentUploadInProgress: null,
}; };
case AppActionTypes.TOGGLE_DLETE_AFTER_UPLOAD: case AppActionTypes.TOGGLE_DLETE_AFTER_UPLOAD:
console.log("It was toggled.")
return { return {
...state, ...state,
deleteAfterUpload: !state.deleteAfterUpload, deleteAfterUpload: !state.deleteAfterUpload,

View File

@@ -8,13 +8,13 @@ import rootSaga from "./root.saga";
const sagaMiddleWare = createSagaMiddleware(); const sagaMiddleWare = createSagaMiddleware();
const middlewares = [sagaMiddleWare]; const middlewares = [sagaMiddleWare];
// if (process.env.NODE_ENV === "development") { if (process.env.NODE_ENV === "development") {
middlewares.push( middlewares.push(
createLogger({ createLogger({
collapsed: true, collapsed: true,
}) })
); );
// } }
//Add in for React Native Debugger. //Add in for React Native Debugger.
const composeEnhancers = const composeEnhancers =

View File

@@ -108,7 +108,7 @@ export function* onSignInSuccess() {
export function* signInSuccessSaga({ payload }) { export function* signInSuccessSaga({ payload }) {
try { try {
// Analytics.setUserId(payload.email);//JF:commenting out the firebase analytics portion // Analytics.setUserId(payload.email);//JF:commenting out the firebase analytics portion
//Sentry.Native.setUser({ email: payload.email }); //Sentry.setUser({ email: payload.email });
const shop = yield client.query({ query: QUERY_BODYSHOP }); const shop = yield client.query({ query: QUERY_BODYSHOP });
logImEXEvent("imexmobile_sign_in_success", payload); logImEXEvent("imexmobile_sign_in_success", payload);
@@ -123,7 +123,7 @@ export function* signInSuccessSaga({ payload }) {
// ); // );
} catch (error) { } catch (error) {
console.log("UH-OH. Couldn't get shop details.", error); console.log("UH-OH. Couldn't get shop details.", error);
Sentry.Native.captureException(error); Sentry.captureException(error);
} }
} }

3
upgrades.md Normal file
View File

@@ -0,0 +1,3 @@
upgrade to expo router
investigate image pickers
change splash to explo-splash-screen

View File

@@ -1,11 +1,12 @@
import * as Sentry from "@sentry/react-native";
import axios from "axios"; import axios from "axios";
import * as MediaLibrary from "expo-media-library";
import env from "../env"; import env from "../env";
import { client } from "../graphql/client"; import { client } from "../graphql/client";
import { INSERT_NEW_DOCUMENT } from "../graphql/documents.queries"; import { INSERT_NEW_DOCUMENT } from "../graphql/documents.queries";
import { axiosAuthInterceptorId } from "./CleanAxios"; import { axiosAuthInterceptorId } from "./CleanAxios";
import * as MediaLibrary from "expo-media-library"; import { splitClient } from "../components/screen-main/screen-main.component";
import { gql } from "@apollo/client"; import * as FileSystem from "expo-file-system";
import * as Sentry from '@sentry/react-native';
//Context: currentUserEmail, bodyshop, jobid, invoiceid //Context: currentUserEmail, bodyshop, jobid, invoiceid
@@ -16,17 +17,82 @@ cleanAxios.interceptors.request.eject(axiosAuthInterceptorId);
export const handleUpload = async (ev, context) => { export const handleUpload = async (ev, context) => {
const { mediaId, onError, onSuccess, onProgress } = ev; const { mediaId, onError, onSuccess, onProgress } = ev;
const { bodyshop, jobId } = context; const { bodyshop, jobId } = context;
try {
const imageData = await MediaLibrary.getAssetInfoAsync(mediaId);
const imageUri = imageData.localUri || imageData.uri
const newFile = await (
await fetch(imageUri)
).blob();
let extension = imageData.filename.split(".").pop();
//Default to Cloudinary in case of split treatment errors.
let destination =
splitClient?.getTreatment("Imgproxy") === "on" ? "imgproxy" : "cloudinary";
let key =
destination === "imgproxy"
? `${bodyshop.id}/${jobId}/${replaceAccents(
imageData.filename || imageUri.split("/").pop()
).replace(/[^A-Z0-9]+/gi, "_")}-${new Date().getTime()}.${extension}`
: `${bodyshop.id}/${jobId}/${(
imageData.filename || imageUri.split("/").pop()
).replace(/\.[^/.]+$/, "")}-${new Date().getTime()}`;
const res =
destination === "imgproxy"
? await uploadToImgproxy(
key,
mediaId,
imageData,
extension,
newFile.type, //Filetype
newFile, //File
onError,
onSuccess,
onProgress,
context
)
: await uploadToCloudinary(
key,
mediaId,
imageData,
extension,
newFile.type, //Filetype
newFile, //File
onError,
onSuccess,
onProgress,
context
);
return res;
} catch (error) {
console.log("Error creating upload promise", error.message, error.stack);
if (onError) onError(error.message);
Sentry.captureException(error);
return {
success: false,
error: error.message,
stack: error.stack,
mediaId,
};
}
};
export const handleUploadImgproxy = async (ev, context) => {
const { mediaId, onError, onSuccess, onProgress } = ev;
const { bodyshop, jobId } = context;
const imageData = await MediaLibrary.getAssetInfoAsync(mediaId); const imageData = await MediaLibrary.getAssetInfoAsync(mediaId);
const imageUri = imageData.localUri || imageData.uri
const newFile = await ( const newFile = await (
await fetch(imageData.localUri || imageData.uri) await fetch(imageUri)
).blob(); ).blob();
let extension = imageData.localUri.split(".").pop(); let extension = imageUri.split(".").pop();
let key = `${bodyshop.id}/${jobId}/${( let key = `${bodyshop.id}/${jobId}/${(
imageData.filename || imageData.uri.split("/").pop() imageData.filename || imageUri.split("/").pop()
).replace(/\.[^/.]+$/, "")}-${new Date().getTime()}`; ).replace(/\.[^/.]+$/, "")}-${new Date().getTime()}`;
const res = await uploadToCloudinary( const res = await uploadToImgproxy(
key, key,
mediaId, mediaId,
imageData, imageData,
@@ -41,6 +107,129 @@ export const handleUpload = async (ev, context) => {
return res; return res;
}; };
export const uploadToImgproxy = async (
key,
mediaId,
imageData,
extension,
fileType,
file,
onError,
onSuccess,
onProgress,
context
) => {
const { bodyshop, jobId, uploaded_by } = context;
//Get the signed url allowing us to PUT to S3.
const signedURLResponse = await axios.post(
`${env.API_URL}/media/imgproxy/sign`,
{
filenames: [key],
bodyshopid: bodyshop.id,
jobid: jobId,
}
);
if (signedURLResponse.status !== 200) {
console.log("Error Getting Signed URL", signedURLResponse.statusText);
if (onError) onError(signedURLResponse.statusText);
return { success: false, error: signedURLResponse.statusText };
}
const { presignedUrl: preSignedUploadUrlToS3, key: s3Key } =
signedURLResponse.data.signedUrls[0];
var options = {
headers: {
"Content-Type": fileType,
"Content-Length": file.size,
},
transformRequest: [(data) => data], //Dave had this magical solution because Axios makes no sense.
onUploadProgress: (e) => {
if (onProgress) onProgress({ percent: e.loaded / e.total, loaded: e.loaded });
},
};
try {
await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("PUT", preSignedUploadUrlToS3);
xhr.setRequestHeader("Content-Type", fileType);
xhr.upload.onprogress = (event) => {
console.log("*** ~ awaitnewPromise ~ event:", event);
if (onProgress && event.lengthComputable) {
onProgress({ percent: event.loaded / event.total, loaded: event.loaded });
}
};
xhr.onload = () => {
if (xhr.status === 200) {
resolve();
} else {
reject(new Error(`Upload failed: ${xhr.statusText}`));
}
};
xhr.onerror = (req, event) => {
reject(new Error("Network error"));
};
xhr.send(file);
});
} catch (error) {
console.log("Error uploading to S3", error.message, error.stack);
if (onError) onError(error.message);
Sentry.captureException(error);
return {
success: false,
error: error.message,
stack: error.stack,
mediaId,
};
}
const documentInsert = await client.mutate({
mutation: INSERT_NEW_DOCUMENT,
variables: {
docInput: [
{
...(jobId ? { jobid: jobId } : {}),
uploaded_by: uploaded_by,
key: s3Key,
type: fileType,
extension: extension,
bodyshopid: bodyshop.id,
size: file.size,
...(imageData.creationTime
? { takenat: new Date(imageData.creationTime) }
: {}),
},
],
},
});
if (!documentInsert.errors) {
if (onSuccess)
onSuccess({
uid: documentInsert.data.insert_documents.returning[0].id,
name: documentInsert.data.insert_documents.returning[0].name,
status: "done",
key: documentInsert.data.insert_documents.returning[0].key,
});
} else {
if (onError) onError(JSON.stringify(documentInsert.errors));
return {
success: false,
error: JSON.stringify(documentInsert.errors),
mediaId,
};
}
return { success: true, mediaId };
};
export const uploadToCloudinary = async ( export const uploadToCloudinary = async (
key, key,
mediaId, mediaId,
@@ -72,7 +261,7 @@ export const uploadToCloudinary = async (
}); });
} catch (error) { } catch (error) {
console.log("ERROR GETTING SIGNED URL", error); console.log("ERROR GETTING SIGNED URL", error);
Sentry.Native.captureException(error); Sentry.captureException(error);
return { success: false, error: error }; return { success: false, error: error };
} }
@@ -121,7 +310,7 @@ export const uploadToCloudinary = async (
); );
} catch (error) { } catch (error) {
console.log("CLOUDINARY error", error.response, cloudinaryUploadResponse); console.log("CLOUDINARY error", error.response, cloudinaryUploadResponse);
Sentry.Native.captureException(error); Sentry.captureException(error);
if (onError) onError(error.message); if (onError) onError(error.message);
return { success: false, error: error }; return { success: false, error: error };
@@ -188,13 +377,46 @@ export function DetermineFileType(filetype) {
} }
export function formatBytes(a, b = 2) { export function formatBytes(a, b = 2) {
if (0 === a || !a) return "0 Bytes"; if (0 === a || !a || isNaN(a)) return "0 Bytes";
const c = 0 > b ? 0 : b, const c = 0 > b ? 0 : b,
d = Math.floor(Math.log(a) / Math.log(1024)); d = Math.floor(Math.log(a) / Math.log(1024));
const parsedFloat = parseFloat((a / Math.pow(1024, d)).toFixed(c))
if (isNaN(parsedFloat)) {
return "0 Bytes";
}
return ( return (
parseFloat((a / Math.pow(1024, d)).toFixed(c)) + parsedFloat +
" " + " " +
["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"][d] ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"][d]
); );
} }
function replaceAccents(str) {
// Verifies if the String has accents and replace them
if (str.search(/[\xC0-\xFF]/g) > -1) {
str = str
.replace(/[\xC0-\xC5]/g, "A")
.replace(/[\xC6]/g, "AE")
.replace(/[\xC7]/g, "C")
.replace(/[\xC8-\xCB]/g, "E")
.replace(/[\xCC-\xCF]/g, "I")
.replace(/[\xD0]/g, "D")
.replace(/[\xD1]/g, "N")
.replace(/[\xD2-\xD6\xD8]/g, "O")
.replace(/[\xD9-\xDC]/g, "U")
.replace(/[\xDD]/g, "Y")
.replace(/[\xDE]/g, "P")
.replace(/[\xE0-\xE5]/g, "a")
.replace(/[\xE6]/g, "ae")
.replace(/[\xE7]/g, "c")
.replace(/[\xE8-\xEB]/g, "e")
.replace(/[\xEC-\xEF]/g, "i")
.replace(/[\xF1]/g, "n")
.replace(/[\xF2-\xF6\xF8]/g, "o")
.replace(/[\xF9-\xFC]/g, "u")
.replace(/[\xFE]/g, "p")
.replace(/[\xFD\xFF]/g, "y");
}
return str;
}

View File

@@ -2,7 +2,7 @@ import axios from "axios";
import { store } from "../redux/store"; import { store } from "../redux/store";
import mime from "mime"; import mime from "mime";
import * as MediaLibrary from "expo-media-library"; import * as MediaLibrary from "expo-media-library";
import * as Sentry from '@sentry/react-native'; import * as Sentry from "@sentry/react-native";
axios.interceptors.request.use( axios.interceptors.request.use(
function (config) { function (config) {
@@ -45,8 +45,9 @@ export const handleLocalUpload = async ({
ims_token: bodyshop.localmediatoken, ims_token: bodyshop.localmediatoken,
}, },
onUploadProgress: (e) => { onUploadProgress: (e) => {
if (onProgress) if (onProgress) {
onProgress({ percent: e.loaded / e.total, loaded: e.loaded }); onProgress({ percent: e.loaded / e.total, loaded: e.loaded });
}
}, },
}; };
@@ -95,14 +96,14 @@ export const handleLocalUpload = async ({
}); });
} }
} catch (error) { } catch (error) {
Sentry.Native.captureException(error); Sentry.captureException(error);
console.log("Error uploading documents:", error.message); console.log("Error uploading documents:", error.message);
onError && onError({ error: error.message }); onError && onError({ error: error.message });
} }
} catch (error) { } catch (error) {
console.log("Uncaught error", error); console.log("Uncaught error", error);
Sentry.Native.captureException(error); Sentry.captureException(error);
onError && onError({ error: error.message }); onError && onError({ error: error.message });
} }