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

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,