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

27
App.js
View File

@@ -1,33 +1,40 @@
import 'expo-dev-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 { 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 { PersistGate } from "redux-persist/integration/react";
import * as Sentry from '@sentry/react-native';
import ScreenMainComponent from "./components/screen-main/screen-main.component";
import { logImEXEvent } from "./firebase/firebase.analytics";
import { client } from "./graphql/client";
import { persistor, store } from "./redux/store";
import "intl";
import "intl/locale-data/jsonp/en";
import "./translations/i18n";
import "expo-asset";
import Toast from "react-native-toast-message";
import { SafeAreaProvider } from "react-native-safe-area-context";
import RNEventSource from "react-native-event-source";
globalThis.EventSource = RNEventSource;
Sentry.init({
dsn: "https://4866820768550ca396e849fa325e84d6@o492140.ingest.sentry.io/4505637419614208",
enableInExpoDevelopment: true,
// tracesSampleRate: 0.2,
// integrations: [
// new Sentry.Native.ReactNativeTracing({
// new Sentry.ReactNativeTracing({
// tracingOrigins: ["localhost", "imex.online", "cloudinary.com", /^\//],
// // ... 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 = {
...DefaultTheme,
colors: {

View File

@@ -2,29 +2,32 @@
"expo": {
"name": "Rome Mobile",
"slug": "rome-mobile",
"version": "1.6.0",
"version": "1.7.0",
"extra": {
"expover": "5",
"expover": "3",
"eas": {
"projectId": "df105e21-a07f-4425-af10-2200a7704a48"
}
},
"runtimeVersion": "appVersion",
"orientation": "default",
"icon": "./assets/RomeIcon.png",
"platforms": ["ios", "android"],
"ios": {
"supportsTablet": true,
"bundleIdentifier": "com.rome.mobile",
"buildNumber": "5",
"googleServicesFile": "./GoogleService-Info.plist",
"entitlements": {
"aps-environment": "development"
},
"infoPlist": {
"NSPhotoLibraryUsageDescription": "Allow $(PRODUCT_NAME) to access your photos.",
"NSPhotoLibraryAddUsageDescription": "Allow $(PRODUCT_NAME) to save 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 to your photos/videos in order to attach them to repair orders in the system.",
"ITSAppUsesNonExemptEncryption": false
}
},
"android": {
"package": "com.rome.mobile",
"versionCode": 5,
"googleServicesFile": "./google-services.json",
"permissions": [
"android.permission.READ_EXTERNAL_STORAGE",
@@ -71,15 +74,28 @@
[
"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.",
"isAccessMediaLocationEnabled": "true"
}
],
"expo-localization"
],
"runtimeVersion": {
"policy": "appVersion"
}
[
"expo-image-picker",
{
"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(
DateTime.DATETIME_SHORT
);
const { key, ...rest } = restProps;
return (
<View {...restProps} style={{ margin: 4, ...restProps.style }}>
<View key={key} {...rest} style={{ margin: 4, ...restProps.style }}>
<Text style={{ color: "slategray" }}>{label}</Text>
<Text>{theContent}</Text>
</View>

View File

@@ -8,7 +8,7 @@ import {
View,
} from "react-native";
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 cleanAxios from "../../util/CleanAxios";
@@ -76,10 +76,7 @@ async function getPhotos({ bodyshop, jobid, setImages }) {
if (localmediaserverhttp.endsWith("/")) {
localmediaserverhttp = localmediaserverhttp.slice(0, -1);
}
console.log(
"🚀 ~ file: job-documents-local.component.jsx ~ line 78 ~ localmediaserverhttp",
localmediaserverhttp
);
try {
const imagesFetch = await cleanAxios.post(
`${localmediaserverhttp}/jobs/list`,
@@ -104,7 +101,7 @@ async function getPhotos({ bodyshop, jobid, setImages }) {
setImages(normalizedImages);
} catch (error) {
Sentry.Native.captureException(error);
Sentry.captureException(error);
Toast.show({
type: "error",
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 {
FlatList,
Image,
@@ -10,38 +11,96 @@ import {
import env from "../../env";
import { DetermineFileType } from "../../util/document-upload.utility";
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 useImgproxy = splitClient.getTreatment("Imgproxy");
const onRefresh = async () => {
return refetch();
};
const fullphotos = useMemo(
() =>
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),
};
}),
[job.documents]
);
useEffect(() => {
async function getPhotos() {
if (useImgproxy) {
const result = await axios.post(
`${env.API_URL}/media/imgproxy/thumbnails`,
{
jobid: job.id,
}
);
setFullPhotos(
result.data.map((doc, idx) => {
return {
id: idx,
videoUrl:
DetermineFileType(doc.type) === "video" &&
doc.originalUrlViaProxyPath,
source:
DetermineFileType(doc.type) === "video"
? { uri: doc.thumbnailUrl }
: { uri: doc.originalUrl },
url:
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 (
<View style={{ flex: 1 }}>
@@ -49,7 +108,7 @@ export default function JobDocumentsComponent({ job, loading, refetch }) {
refreshControl={
<RefreshControl refreshing={loading} onRefresh={onRefresh} />
}
data={job.documents}
data={fullphotos}
numColumns={4}
style={{ flex: 1 }}
keyExtractor={(item) => item.id}
@@ -65,14 +124,19 @@ export default function JobDocumentsComponent({ job, loading, refetch }) {
style={{ flex: 1 }}
resizeMode="cover"
source={{
uri: GenerateThumbUrl(object.item),
uri: object.item.thumbUrl,
aspectRatio: 1,
}}
/>
</TouchableOpacity>
)}
/>
<Text>{job.documents.length}</Text>
<Text
style={{ textAlign: "center", color: useImgproxy ? "blue" : "black" }}
>
{fullphotos.length}
</Text>
<MediaCacheOverlay
photos={fullphotos}

View File

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

View File

@@ -3,6 +3,7 @@ import { View } from "react-native";
import { BarIndicator } from "react-native-indicators";
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 (
<View style={{ flex: 1, alignContent: "center", justifyContent: "center" }}>
<BarIndicator count={count} color="dodgerblue" />

View File

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

View File

@@ -24,13 +24,16 @@ import {
selectBodyshop,
selectCurrentUser,
} from "../../redux/user/user.selectors";
import env from "../../env";
import ScreenJobDetail from "../screen-job-detail/screen-job-detail.component";
import ScreenJobList from "../screen-job-list/screen-job-list.component";
import ScreenMediaBrowser from "../screen-media-browser/screen-media-browser.component";
import ScreenSettingsComponent from "../screen-settings/screen-settings.component";
import ScreenSignIn from "../screen-sign-in/screen-sign-in.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 EmployeeSignIn from "../screen-employee-sign-in/screen-employee-sign-in.component";
@@ -240,6 +243,8 @@ const BottomTabsNavigator = () => (
</BottomTabs.Navigator>
);
export var splitClient;
export function ScreenMainComponent({
checkUserSession,
currentUser,
@@ -249,6 +254,23 @@ export function ScreenMainComponent({
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 (
<NavigationContainer>
{currentUser.authorized === null ? (

View File

@@ -1,23 +1,27 @@
import { Ionicons } from '@expo/vector-icons';
import { AssetsSelector } from 'expo-images-picker';
import { MediaType } from 'expo-media-library';
import React, { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { StyleSheet, Text, View } from 'react-native';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { logImEXEvent } from '../../firebase/firebase.analytics';
import { toggleDeleteAfterUpload } from '../../redux/app/app.actions';
import { Ionicons } from "@expo/vector-icons";
import { AssetsSelector } from "expo-images-picker";
import { MediaType } from "expo-media-library";
import React, { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { StyleSheet, Text, View } from "react-native";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.analytics";
import { toggleDeleteAfterUpload } from "../../redux/app/app.actions";
import {
selectCurrentCameraJobId,
selectDeleteAfterUpload,
} from '../../redux/app/app.selectors';
import { selectBodyshop } from '../../redux/user/user.selectors';
import CameraSelectJob from '../camera-select-job/camera-select-job.component';
import JobSpaceAvailable from '../job-space-available/job-space-available.component';
import LocalUploadProgress from '../local-upload-progress/local-upload-progress.component';
import UploadDeleteSwitch from '../upload-delete-switch/upload-delete-switch.component';
import UploadProgress from '../upload-progress/upload-progress.component';
} from "../../redux/app/app.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import CameraSelectJob from "../camera-select-job/camera-select-job.component";
import JobSpaceAvailable from "../job-space-available/job-space-available.component";
import UploadProgressLocal from "../upload-progress-local/upload-progress-local.component";
import UploadDeleteSwitch from "../upload-delete-switch/upload-delete-switch.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({
selectedCameraJobId: selectCurrentCameraJobId,
@@ -37,24 +41,42 @@ export function ImageBrowserScreen({
}) {
const { t } = useTranslation();
const [uploads, setUploads] = useState(null);
const [density, setDensity] = useState(3);
const [tick, setTick] = useState(0);
// const [medialLibraryPermissionStatus, requestmediaLibraryPermission] =
// ImagePicker.useMediaLibraryPermissions();
const forceRerender = useCallback(() => {
setTick((tick) => tick + 1);
}, []);
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);
};
const widgetErrors = useMemo(
() => ({
errorTextColor: 'black',
errorTextColor: "black",
errorMessages: {
hasErrorWithPermissions: 'Please Allow media gallery permissions.',
hasErrorWithLoading: 'There was an error while loading images.',
hasErrorWithResizing: 'There was an error while loading images.',
hasNoAssets: 'No images found.',
hasErrorWithPermissions: "Please Allow media gallery permissions.",
hasErrorWithLoading: "There was an error while loading images.",
hasErrorWithResizing: "There was an error while loading images.",
hasNoAssets: "No images found.",
},
}),
[]
@@ -63,43 +85,24 @@ export function ImageBrowserScreen({
const widgetSettings = useMemo(
() => ({
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],
minSelection: 1,
// maxSelection: 3,
portraitCols: 4,
landscapeCols: 4,
portraitCols: density,
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(
() => ({
Texts: {
finish: t('mediabrowser.actions.upload'),
back: t('mediabrowser.actions.refresh'),
selected: 'selected',
finish: t("mediabrowser.actions.upload"),
back: t("mediabrowser.actions.refresh"),
selected: "selected",
},
midTextColor: 'black',
midTextColor: "black",
minSelection: 1,
buttonTextStyle: styles.textStyle,
buttonStyle: styles.buttonStyle,
@@ -114,32 +117,59 @@ export function ImageBrowserScreen({
const widgetStyles = useMemo(
() => ({
margin: 2,
bgColor: 'white',
spinnerColor: 'blue',
bgColor: "white",
spinnerColor: "blue",
widgetWidth: 99,
videoIcon: {
Component: Ionicons,
iconName: 'videocam',
color: 'white',
iconName: "videocam",
color: "white",
size: 20,
},
selectedIcon: {
Component: Ionicons,
iconName: 'checkmark-circle-outline',
color: 'white',
bg: 'rgba(35,35,35, 0.75)',
iconName: "checkmark-circle-outline",
color: "white",
bg: "rgba(35,35,35, 0.75)",
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 (
<View style={[styles.flex, styles.container]}>
<CameraSelectJob />
{bodyshop.uselocalmediaserver ? (
<Text style={{ margin: 10 }}>
{t('mediabrowser.labels.localserver', {
{t("mediabrowser.labels.localserver", {
url: bodyshop.localmediaserverhttp,
})}
</Text>
@@ -147,25 +177,35 @@ export function ImageBrowserScreen({
<JobSpaceAvailable jobid={selectedCameraJobId} key={`${tick}-space`} />
)}
<UploadDeleteSwitch />
{
// <Button
// onPress={() => {
// //Mutate the state
// toggleDeleteAfterUpload();
// }}
// >
// <Text>{`From screen. ${deleteAfterUpload}`}</Text>
// </Button>
}
<SegmentedButtons
value={density}
onValueChange={(value) => {
setDensity(value);
forceRerender();
}}
buttons={[
{
value: 4,
label: "Small",
},
{
value: 3,
label: "Normal",
},
{ value: 2, label: "Large" },
]}
/>
{!selectedCameraJobId && (
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
justifyContent: "center",
alignItems: "center",
}}
>
<Text>{t('mediabrowser.labels.selectjobassetselector')}</Text>
<Text>{t("mediabrowser.labels.selectjobassetselector")}</Text>
</View>
)}
{selectedCameraJobId && (
@@ -179,7 +219,7 @@ export function ImageBrowserScreen({
/>
)}
{bodyshop.uselocalmediaserver ? (
<LocalUploadProgress
<UploadProgressLocal
uploads={uploads}
setUploads={setUploads}
forceRerender={forceRerender}
@@ -200,7 +240,7 @@ const styles = StyleSheet.create({
flex: 1,
},
container: {
display: 'flex',
display: "flex",
// position: "relative",
},
buttonStyle: {
@@ -208,7 +248,7 @@ const styles = StyleSheet.create({
},
// eslint-disable-next-line react-native/no-color-literals
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 SignOutButton from "../sign-out-button/sign-out-button.component";
import * as Updates from "expo-updates";
import * as Application from "expo-application";
export default function ScreenSettingsComponent() {
const { t } = useTranslation();
@@ -21,7 +22,7 @@ export default function ScreenSettingsComponent() {
>
<Title>
{t("settings.labels.version", {
number: `${Constants.expoConfig.version}-${Constants.expoConfig.extra.expover}`,
number: `${Constants.expoConfig.version}(${Application.nativeBuildVersion} - ${Constants.expoConfig.extra.expover})`,
})}
</Title>

View File

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

View File

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

View File

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

View File

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

View File

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

16
env.js
View File

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

View File

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

View File

@@ -1,41 +1,12 @@
//GQL Imports
import {
ApolloClient,
from,
HttpLink,
InMemoryCache,
split,
} from "@apollo/client";
import { ApolloClient, from, HttpLink, InMemoryCache } from "@apollo/client";
import { setContext } from "@apollo/client/link/context";
import { onError } from "@apollo/client/link/error";
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({
//uri: "wss://bodyshop-dev-db.herokuapp.com/v1/graphql",
uri: "wss://db.imex.online/v1/graphql",
options: {
lazy: true,
reconnect: true,
connectionParams: async () => {
const token =
auth.currentUser && (await auth.currentUser.getIdToken(true));
if (token) {
return {
headers: {
authorization: token ? `Bearer ${token}` : "",
},
};
}
},
},
import env from "../env";
import { auth } from "../firebase/firebase.utils";
const httpLink = new HttpLink({
uri: env.uri,
});
//https://stackoverflow.com/questions/57163454/refreshing-a-token-with-apollo-client-firebase-auth
@@ -61,27 +32,27 @@ const subscriptionMiddleware = {
next();
},
};
wsLink.subscriptionClient.use([subscriptionMiddleware]);
//wsLink.subscriptionClient.use([subscriptionMiddleware]);
const link = split(
// split based on operation type
({ query }) => {
const definition = getMainDefinition(query);
// console.log(
// "##Intercepted GQL Transaction : " +
// definition.operation +
// "|" +
// // definition.name.value +
// "##"
// );
return (
definition.kind === "OperationDefinition" &&
definition.operation === "subscription"
);
},
wsLink,
httpLink
);
// const link = split(
// // split based on operation type
// ({ query }) => {
// const definition = getMainDefinition(query);
// // console.log(
// // "##Intercepted GQL Transaction : " +
// // definition.operation +
// // "|" +
// // // definition.name.value +
// // "##"
// // );
// return (
// definition.kind === "OperationDefinition" &&
// definition.operation === "subscription"
// );
// },
// wsLink,
// httpLink
// );
const authLink = setContext((_, { headers }) => {
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({});
export const client = new ApolloClient({
//link: ApolloLink.from(middlewares),
//link: from([apolloLogger, errorLink, authLink, link]),
link: from([authLink, link]),
link: from([authLink, retryLink, errorLink, httpLink]),
cache,
notifyOnNetworkStatusChange: true,
// connectToDevTools: process.env.NODE_ENV !== "production",
defaultOptions: {
watchQuery: {
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",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"android": "expo run:android",
"ios": "expo run:ios",
"web": "expo start --web",
"eject": "expo eject",
"release:test": "expo publish --release-channel test",
@@ -16,85 +16,92 @@
"build:production:local:android": "eas build --profile production --platform android --local"
},
"dependencies": {
"@apollo/client": "^3.9.5",
"@babel/preset-env": "7.1.6",
"@expo/vector-icons": "^14.0.0",
"@react-native-async-storage/async-storage": "1.21.0",
"@react-native-community/cli-debugger-ui": "^9.0.0",
"@react-native-community/datetimepicker": "7.6.1",
"@apollo/client": "^3.12.11",
"@babel/preset-env": "7.26.8",
"@expo/vector-icons": "^14.0.4",
"@logrocket/react-native": "^1.52.2",
"@react-native-async-storage/async-storage": "1.23.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-navigation/bottom-tabs": "^6.3.3",
"@react-navigation/drawer": "^6.4.4",
"@react-navigation/native": "^6.0.12",
"@react-navigation/native-stack": "^6.8.0",
"@react-navigation/stack": "^6.2.3",
"@sentry/react-native": "5.19.1",
"axios": "^1.6.7",
"cloudinary-core": "^2.13.0",
"@react-navigation/bottom-tabs": "^7.2.0",
"@react-navigation/drawer": "^7.1.1",
"@react-navigation/native": "^7.0.14",
"@react-navigation/native-stack": "^7.2.0",
"@react-navigation/stack": "^7.1.1",
"@sentry/react-native": "~6.10.0",
"@splitsoftware/splitio-react-native": "^1.1.0",
"axios": "^1.9.0",
"cloudinary-core": "^2.13.1",
"dinero.js": "^1.9.1",
"expo": "~50.0.8",
"expo-application": "~5.8.3",
"expo-av": "~13.10.5",
"expo-constants": "~15.4.5",
"expo-dev-client": "~3.3.9",
"expo-device": "~5.9.3",
"expo-file-system": "~16.0.6",
"expo-font": "~11.10.3",
"expo-image-manipulator": "~11.8.0",
"expo-images-picker": "^2.4.1",
"expo-localization": "~14.8.3",
"expo-media-library": "~15.9.1",
"expo-status-bar": "~1.11.1",
"expo-system-ui": "~2.9.3",
"expo-updates": "~0.24.11",
"expo-video-thumbnails": "~7.9.0",
"firebase": "^10.8.0",
"formik": "^2.4.5",
"graphql": "^16.8.1",
"i18next": "^21.9.1",
"expo": "~52.0.46",
"expo-application": "~6.0.2",
"expo-av": "~15.0.2",
"expo-build-properties": "~0.13.3",
"expo-constants": "~17.0.5",
"expo-dev-client": "~5.0.20",
"expo-device": "~7.0.3",
"expo-file-system": "~18.0.10",
"expo-font": "~13.0.3",
"expo-image-manipulator": "~13.0.6",
"expo-image-picker": "~16.0.6",
"expo-images-picker": "^2.5.1",
"expo-localization": "~16.0.1",
"expo-media-library": "~17.0.6",
"expo-notifications": "~0.29.14",
"expo-status-bar": "~2.0.1",
"expo-system-ui": "~4.0.9",
"expo-updates": "~0.27.4",
"expo-video-thumbnails": "~9.0.3",
"firebase": "^11.3.1",
"formik": "^2.4.6",
"graphql": "^16.10.0",
"i18next": "^24.2.2",
"intl": "^1.2.5",
"lodash": "^4.17.21",
"luxon": "^3.4.4",
"mime": "^3.0.0",
"luxon": "^3.5.0",
"mime": "^4.0.6",
"moment": "^2.30.1",
"normalize-url": "^7.0.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-i18next": "^14.0.5",
"react-is": ">=18.2.0",
"react-native": "0.73.4",
"normalize-url": "^8.0.1",
"react": "18.3.1",
"react-dom": "18.3.1",
"react-i18next": "^15.4.0",
"react-is": ">=19.0.0",
"react-native": "0.76.9",
"react-native-draggable-flatlist": "^4.0.1",
"react-native-element-dropdown": "^2.10.1",
"react-native-gesture-handler": "~2.14.0",
"react-native-element-dropdown": "^2.12.4",
"react-native-event-source": "^1.1.0",
"react-native-gesture-handler": "~2.20.2",
"react-native-image-gallery": "^2.1.5",
"react-native-image-viewing": "^0.2.2",
"react-native-indicators": "^0.17.0",
"react-native-modal-datetime-picker": "^17.1.0",
"react-native-pager-view": "6.2.3",
"react-native-paper": "^5.12.3",
"react-native-modal-datetime-picker": "^18.0.0",
"react-native-pager-view": "6.5.1",
"react-native-paper": "^5.13.1",
"react-native-progress": "^5.0.1",
"react-native-reanimated": "~3.6.2",
"react-native-safe-area-context": "4.8.2",
"react-native-screens": "~3.29.0",
"react-native-svg": "14.1.0",
"react-native-tab-view": "3.5.2",
"react-native-toast-message": "^2.2.0",
"react-native-reanimated": "~3.16.7",
"react-native-safe-area-context": "4.12.0",
"react-native-screens": "~4.4.0",
"react-native-svg": "15.8.0",
"react-native-tab-view": "4.0.5",
"react-native-toast-message": "^2.2.1",
"react-native-vector-icons": "*",
"react-native-web": "~0.19.10",
"react-redux": "^9.1.0",
"react-native-web": "~0.19.13",
"react-redux": "^9.2.0",
"redux": "^5.0.1",
"redux-logger": "^3.0.6",
"redux-persist": "^6.0.0",
"redux-saga": "^1.3.0",
"reselect": "^5.1.0",
"subscriptions-transport-ws": "^0.9.18"
"reselect": "^5.1.1"
},
"devDependencies": {
"@babel/core": "^7.23.9",
"babel-preset-expo": "^10.0.1",
"eslint": "^8.57.0",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-native": "^4.1.0"
"@babel/core": "^7.26.8",
"babel-preset-expo": "~12.0.7",
"eslint": "^9.20.1",
"eslint-plugin-react": "^7.37.4",
"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,
};
case AppActionTypes.TOGGLE_DLETE_AFTER_UPLOAD:
console.log("It was toggled.")
return {
...state,
deleteAfterUpload: !state.deleteAfterUpload,

View File

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

View File

@@ -108,7 +108,7 @@ export function* onSignInSuccess() {
export function* signInSuccessSaga({ payload }) {
try {
// 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 });
logImEXEvent("imexmobile_sign_in_success", payload);
@@ -123,7 +123,7 @@ export function* signInSuccessSaga({ payload }) {
// );
} catch (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 * as MediaLibrary from "expo-media-library";
import env from "../env";
import { client } from "../graphql/client";
import { INSERT_NEW_DOCUMENT } from "../graphql/documents.queries";
import { axiosAuthInterceptorId } from "./CleanAxios";
import * as MediaLibrary from "expo-media-library";
import { gql } from "@apollo/client";
import * as Sentry from '@sentry/react-native';
import { splitClient } from "../components/screen-main/screen-main.component";
import * as FileSystem from "expo-file-system";
//Context: currentUserEmail, bodyshop, jobid, invoiceid
@@ -16,17 +17,82 @@ cleanAxios.interceptors.request.eject(axiosAuthInterceptorId);
export const handleUpload = async (ev, context) => {
const { mediaId, onError, onSuccess, onProgress } = ev;
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 imageUri = imageData.localUri || imageData.uri
const newFile = await (
await fetch(imageData.localUri || imageData.uri)
await fetch(imageUri)
).blob();
let extension = imageData.localUri.split(".").pop();
let extension = imageUri.split(".").pop();
let key = `${bodyshop.id}/${jobId}/${(
imageData.filename || imageData.uri.split("/").pop()
imageData.filename || imageUri.split("/").pop()
).replace(/\.[^/.]+$/, "")}-${new Date().getTime()}`;
const res = await uploadToCloudinary(
const res = await uploadToImgproxy(
key,
mediaId,
imageData,
@@ -41,6 +107,129 @@ export const handleUpload = async (ev, context) => {
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 (
key,
mediaId,
@@ -72,7 +261,7 @@ export const uploadToCloudinary = async (
});
} catch (error) {
console.log("ERROR GETTING SIGNED URL", error);
Sentry.Native.captureException(error);
Sentry.captureException(error);
return { success: false, error: error };
}
@@ -121,7 +310,7 @@ export const uploadToCloudinary = async (
);
} catch (error) {
console.log("CLOUDINARY error", error.response, cloudinaryUploadResponse);
Sentry.Native.captureException(error);
Sentry.captureException(error);
if (onError) onError(error.message);
return { success: false, error: error };
@@ -188,13 +377,46 @@ export function DetermineFileType(filetype) {
}
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,
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 (
parseFloat((a / Math.pow(1024, d)).toFixed(c)) +
parsedFloat +
" " +
["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 mime from "mime";
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(
function (config) {
@@ -45,8 +45,9 @@ export const handleLocalUpload = async ({
ims_token: bodyshop.localmediatoken,
},
onUploadProgress: (e) => {
if (onProgress)
if (onProgress) {
onProgress({ percent: e.loaded / e.total, loaded: e.loaded });
}
},
};
@@ -95,14 +96,14 @@ export const handleLocalUpload = async ({
});
}
} catch (error) {
Sentry.Native.captureException(error);
Sentry.captureException(error);
console.log("Error uploading documents:", error.message);
onError && onError({ error: error.message });
}
} catch (error) {
console.log("Uncaught error", error);
Sentry.Native.captureException(error);
Sentry.captureException(error);
onError && onError({ error: error.message });
}