@swan-io/shared-business 18.6.0 → 18.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +3 -3
- package/src/components/FileInput.js +25 -10
- package/src/components/FileTile.d.ts +4 -3
- package/src/components/FileTile.js +14 -7
- package/src/components/FilesUploader.js +12 -4
- package/src/components/FraudReport/DocumentsStep.d.ts +13 -0
- package/src/components/FraudReport/DocumentsStep.js +49 -0
- package/src/components/FraudReport/FraudReportLayout.d.ts +2 -1
- package/src/components/FraudReport/FraudReportLayout.js +2 -2
- package/src/components/FraudReport/TransferDetailsStep.d.ts +7 -0
- package/src/components/FraudReport/TransferDetailsStep.js +25 -0
- package/src/components/SupportingDocumentCollection.d.ts +1 -0
- package/src/components/SupportingDocumentCollection.js +13 -14
- package/src/hooks/__tests__/useFilesUploader.test.d.ts +1 -0
- package/src/hooks/__tests__/useFilesUploader.test.js +101 -0
- package/src/hooks/useFilesUploader.d.ts +2 -1
- package/src/hooks/useFilesUploader.js +28 -9
- package/src/locales/de.json +22 -0
- package/src/locales/en.json +22 -0
- package/src/locales/es.json +22 -0
- package/src/locales/fi.json +22 -0
- package/src/locales/fr.json +22 -0
- package/src/locales/it.json +22 -0
- package/src/locales/nl.json +22 -0
- package/src/locales/pt.json +22 -0
- package/src/utils/SwanFile.d.ts +2 -0
- package/src/utils/__tests__/fraudReport.documents.test.d.ts +1 -0
- package/src/utils/__tests__/fraudReport.documents.test.js +61 -0
- package/src/utils/__tests__/fraudReport.picker.test.js +25 -10
- package/src/utils/__tests__/fraudReport.prefill.test.js +4 -0
- package/src/utils/__tests__/fraudReport.resume.test.js +2 -1
- package/src/utils/__tests__/fraudReport.toInput.test.js +81 -15
- package/src/utils/__tests__/fraudReport.transfer.test.d.ts +1 -0
- package/src/utils/__tests__/fraudReport.transfer.test.js +31 -0
- package/src/utils/__tests__/validation.test.js +12 -5
- package/src/utils/fraudReport/documents.d.ts +9 -0
- package/src/utils/fraudReport/documents.js +18 -0
- package/src/utils/fraudReport/picker.d.ts +1 -0
- package/src/utils/fraudReport/picker.js +5 -4
- package/src/utils/fraudReport/prefill.d.ts +1 -1
- package/src/utils/fraudReport/prefill.js +2 -1
- package/src/utils/fraudReport/resume.js +1 -1
- package/src/utils/fraudReport/toInput.d.ts +1 -0
- package/src/utils/fraudReport/toInput.js +23 -4
- package/src/utils/fraudReport/transfer.d.ts +6 -0
- package/src/utils/fraudReport/transfer.js +8 -0
- package/src/utils/fraudReport/types.d.ts +1 -1
- package/src/utils/validation.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@swan-io/shared-business",
|
|
3
|
-
"version": "18.
|
|
3
|
+
"version": "18.7.0",
|
|
4
4
|
"engines": {
|
|
5
5
|
"node": ">22.12.0"
|
|
6
6
|
},
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"react": ">=19.0.0",
|
|
29
29
|
"react-dom": ">=19.0.0",
|
|
30
30
|
"react-native-web": ">=0.21.2",
|
|
31
|
-
"@swan-io/lake": "18.
|
|
31
|
+
"@swan-io/lake": "18.7.0"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
34
|
"@formatjs/intl": "^4.1.16",
|
|
@@ -54,6 +54,6 @@
|
|
|
54
54
|
"react-dom": "^19.2.7",
|
|
55
55
|
"react-native-web": "^0.21.2",
|
|
56
56
|
"type-fest": "^5.8.0",
|
|
57
|
-
"@swan-io/lake": "18.
|
|
57
|
+
"@swan-io/lake": "18.7.0"
|
|
58
58
|
}
|
|
59
59
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
-
import { Option, Result } from "@bloodyowl/boxed";
|
|
2
|
+
import { Array, Option, Result } from "@bloodyowl/boxed";
|
|
3
3
|
import { Icon } from "@swan-io/lake/src/components/Icon";
|
|
4
4
|
import { LakeButton } from "@swan-io/lake/src/components/LakeButton";
|
|
5
5
|
import { LakeHeading } from "@swan-io/lake/src/components/LakeHeading";
|
|
@@ -10,11 +10,11 @@ import { backgroundColor, colors, radii, shadows, spacings, } from "@swan-io/lak
|
|
|
10
10
|
import { useBoolean } from "@swan-io/lake/src/hooks/useBoolean";
|
|
11
11
|
import { getIconNameFromFilename } from "@swan-io/lake/src/utils/file";
|
|
12
12
|
import { isNotNullish } from "@swan-io/lake/src/utils/nullish";
|
|
13
|
-
import { useMemo } from "react";
|
|
14
|
-
import { useDropzone } from "react-dropzone";
|
|
13
|
+
import { useId, useMemo } from "react";
|
|
14
|
+
import { ErrorCode, useDropzone } from "react-dropzone";
|
|
15
15
|
import { StyleSheet, Text, View } from "react-native";
|
|
16
16
|
import { match, P } from "ts-pattern";
|
|
17
|
-
import { formatNestedMessage, t } from "../utils/i18n";
|
|
17
|
+
import { formatNestedMessage, locale, t } from "../utils/i18n";
|
|
18
18
|
const styles = StyleSheet.create({
|
|
19
19
|
container: {
|
|
20
20
|
backgroundColor: backgroundColor.accented,
|
|
@@ -94,8 +94,9 @@ const styles = StyleSheet.create({
|
|
|
94
94
|
top: spacings[20],
|
|
95
95
|
},
|
|
96
96
|
});
|
|
97
|
+
const getFormatName = (type) => { var _a; var _b; return (_a = ((_b = type.split("/")[1]) !== null && _b !== void 0 ? _b : type).split("+")[0]) === null || _a === void 0 ? void 0 : _a.toUpperCase(); };
|
|
97
98
|
export const FileInput = ({ id, icon = "document-regular", accept, value, disabled = false, onPressRemove, onFiles, onError, layout = "vertical", description, error, maxSize, }) => {
|
|
98
|
-
var _a;
|
|
99
|
+
var _a, _b;
|
|
99
100
|
const [isHovered, setIsHovered] = useBoolean(false);
|
|
100
101
|
// We use the `accept` field as a heuristic to know if we can display a preview
|
|
101
102
|
// to avoid the cost of an extra fetch to extract the actual mimeType.
|
|
@@ -123,26 +124,40 @@ export const FileInput = ({ id, icon = "document-regular", accept, value, disabl
|
|
|
123
124
|
disabled,
|
|
124
125
|
maxSize,
|
|
125
126
|
});
|
|
126
|
-
|
|
127
|
+
const errorMessage = error !== null && error !== void 0 ? error : match((_b = (_a = fileRejections[0]) === null || _a === void 0 ? void 0 : _a.errors[0]) === null || _b === void 0 ? void 0 : _b.code)
|
|
128
|
+
.with(ErrorCode.FileTooLarge, () => isNotNullish(maxSize)
|
|
129
|
+
? t("fileInput.error.tooLarge", { maxSizeMB: maxSize / 1000000 })
|
|
130
|
+
: undefined)
|
|
131
|
+
.with(ErrorCode.FileInvalidType, () => t("fileInput.error.invalidType", {
|
|
132
|
+
formats: new Intl.ListFormat(locale.language, { type: "disjunction" }).format(Array.filterMap(accept, type => Option.fromUndefined(getFormatName(type)))),
|
|
133
|
+
}))
|
|
134
|
+
.otherwise(() => undefined);
|
|
135
|
+
const errorId = useId();
|
|
136
|
+
const showsError = isNotNullish(errorMessage) && file.isNone();
|
|
137
|
+
return (_jsx(View, { style: commonStyles.fill, children: _jsx("div", { ...getRootProps(), onMouseEnter: setIsHovered.on, onMouseLeave: setIsHovered.off, children: _jsxs(View, { style: [
|
|
127
138
|
styles.container,
|
|
128
139
|
disabled && styles.disabled,
|
|
129
140
|
layout === "horizontal" && styles.horizontalContainer,
|
|
130
141
|
!disabled && isHovered && styles.hoveredContainer,
|
|
131
142
|
isDragActive && styles.activeContainer,
|
|
132
143
|
(error != null || fileRejections.length > 0) && styles.errorContainer,
|
|
133
|
-
], children: [_jsx("input", { ...getInputProps({
|
|
144
|
+
], children: [_jsx("input", { ...getInputProps({
|
|
145
|
+
id,
|
|
146
|
+
"aria-describedby": showsError ? errorId : undefined,
|
|
147
|
+
"aria-invalid": showsError,
|
|
148
|
+
}) }), match({ file, isImageOnly })
|
|
134
149
|
.with({ file: Option.Some(P.select()), isImageOnly: true }, ({ url }) => (_jsxs(_Fragment, { children: [_jsx(View, { style: [styles.preview, { backgroundImage: `url("${url}")` }] }), onPressRemove != null ? (_jsx(LakeButton, { mode: "tertiary", size: "small", icon: "delete-regular", color: "negative", onPress: onPressRemove, style: styles.deleteButton, ariaLabel: t("common.remove") })) : null] })))
|
|
135
|
-
.with({ file: Option.Some(P.select()), isImageOnly: false }, ({ name }) => (_jsxs(_Fragment, { children: [_jsx(Icon, { name: getIconNameFromFilename(name), size: 48, color: disabled ? colors.gray[200] : colors.current[500] }), _jsx(Space, { width: layout === "horizontal" ? 48 : 16, height: layout === "horizontal" ? 48 : 16 }), _jsxs(View, { style: styles.browseBlock, children: [_jsx(LakeHeading, { level:
|
|
150
|
+
.with({ file: Option.Some(P.select()), isImageOnly: false }, ({ name }) => (_jsxs(_Fragment, { children: [_jsx(Icon, { name: getIconNameFromFilename(name), size: 48, color: disabled ? colors.gray[200] : colors.current[500] }), _jsx(Space, { width: layout === "horizontal" ? 48 : 16, height: layout === "horizontal" ? 48 : 16 }), _jsxs(View, { style: styles.browseBlock, children: [_jsx(LakeHeading, { level: "none", variant: "h5", align: layout === "horizontal" ? "left" : "center", children: t("fileInput.clickToModify") }), _jsx(Space, { height: 4 }), _jsx(LakeText, { variant: "smallRegular", color: colors.gray[200], align: layout === "horizontal" ? "left" : "center", children: name })] }), onPressRemove != null ? (_jsx(LakeButton, { mode: "tertiary", size: "small", icon: "delete-regular", color: "negative", style: styles.deleteButton, onPress: onPressRemove, ariaLabel: t("common.remove") })) : null] })))
|
|
136
151
|
.otherwise(() => (_jsxs(_Fragment, { children: [_jsxs(View, { style: styles.icon, children: [_jsx(Icon, { name: icon, size: 48, color: disabled ? colors.gray[200] : colors.current[500], style: [
|
|
137
152
|
styles.decorativeIconLeft,
|
|
138
153
|
(isDragActive || isHovered) && styles.decorativeIconLeftHovered,
|
|
139
154
|
] }), _jsx(Icon, { name: icon, size: 48, color: disabled ? colors.gray[200] : colors.current[500], style: [
|
|
140
155
|
styles.decorativeIconRight,
|
|
141
156
|
(isDragActive || isHovered) && styles.decorativeIconRightHovered,
|
|
142
|
-
] }), _jsx(Icon, { name: icon, size: 48, color: disabled ? colors.gray[200] : colors.current[500] })] }), _jsx(Space, { width: layout === "horizontal" ? 48 : 16, height: layout === "horizontal" ? 48 : 16 }), _jsxs(View, { style: styles.browseBlock, children: [_jsx(LakeHeading, { level:
|
|
157
|
+
] }), _jsx(Icon, { name: icon, size: 48, color: disabled ? colors.gray[200] : colors.current[500] })] }), _jsx(Space, { width: layout === "horizontal" ? 48 : 16, height: layout === "horizontal" ? 48 : 16 }), _jsxs(View, { style: styles.browseBlock, children: [_jsx(LakeHeading, { level: "none", variant: "h5", align: layout === "horizontal" ? "left" : "center", color: disabled ? colors.gray[200] : undefined, children: disabled
|
|
143
158
|
? t("fileInput.noFile")
|
|
144
159
|
: formatNestedMessage("fileInput.dropFile", {
|
|
145
160
|
browse: _jsx(Text, { style: styles.browse, children: t("fileInput.browse") }),
|
|
146
|
-
}) }), isNotNullish(
|
|
161
|
+
}) }), isNotNullish(errorMessage) ? (_jsxs(_Fragment, { children: [_jsx(Space, { height: 4 }), _jsx(LakeText, { id: errorId, role: "alert", color: colors.negative[400], align: layout === "horizontal" ? "left" : "center", children: errorMessage })] })) : (!disabled &&
|
|
147
162
|
isNotNullish(description) && (_jsxs(_Fragment, { children: [_jsx(Space, { height: 4 }), _jsx(LakeText, { align: layout === "horizontal" ? "left" : "center", children: description })] })))] })] })))] }) }) }));
|
|
148
163
|
};
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { Future } from "@bloodyowl/boxed";
|
|
1
|
+
import { Future, Result } from "@bloodyowl/boxed";
|
|
2
2
|
import { SwanFile } from "../utils/SwanFile";
|
|
3
3
|
type Props = {
|
|
4
4
|
file: SwanFile;
|
|
5
5
|
showId?: boolean;
|
|
6
|
-
onRemove?: () => Future<unknown
|
|
6
|
+
onRemove?: () => Future<Result<unknown, unknown>>;
|
|
7
|
+
onRetry?: () => void;
|
|
7
8
|
};
|
|
8
|
-
export declare const FileTile: ({ file: { id, statusInfo, name, url }, showId, onRemove, }: Props) => import("react").JSX.Element;
|
|
9
|
+
export declare const FileTile: ({ file: { id, statusInfo, name, url }, showId, onRemove, onRetry, }: Props) => import("react").JSX.Element;
|
|
9
10
|
export {};
|
|
@@ -48,15 +48,19 @@ const styles = StyleSheet.create({
|
|
|
48
48
|
alignSelf: "flex-start",
|
|
49
49
|
},
|
|
50
50
|
});
|
|
51
|
-
export const FileTile = ({ file: { id, statusInfo, name, url }, showId = false, onRemove, }) => {
|
|
51
|
+
export const FileTile = ({ file: { id, statusInfo, name, url }, showId = false, onRemove, onRetry, }) => {
|
|
52
52
|
const [isDeleting, setIsDeleting] = useState(false);
|
|
53
53
|
const [isDeleteModalVisible, setIsDeleteModalVisible] = useState(false);
|
|
54
|
+
const [removeFailures, setRemoveFailures] = useState(0);
|
|
54
55
|
const onPressRemove = useCallback(() => {
|
|
55
56
|
if (onRemove != null) {
|
|
56
57
|
setIsDeleting(true);
|
|
57
|
-
onRemove().tap(
|
|
58
|
+
onRemove().tap(result => {
|
|
58
59
|
setIsDeleting(false);
|
|
59
60
|
setIsDeleteModalVisible(false);
|
|
61
|
+
if (result.isError()) {
|
|
62
|
+
setRemoveFailures(count => count + 1);
|
|
63
|
+
}
|
|
60
64
|
});
|
|
61
65
|
}
|
|
62
66
|
}, [onRemove]);
|
|
@@ -68,13 +72,13 @@ export const FileTile = ({ file: { id, statusInfo, name, url }, showId = false,
|
|
|
68
72
|
.with("Uploaded", "Uploading", () => colors.gray[100])
|
|
69
73
|
.with("Pending", () => colors.shakespear[100])
|
|
70
74
|
.with("Validated", () => colors.positive[500])
|
|
71
|
-
.with("Refused", () => colors.negative[100])
|
|
75
|
+
.with("Refused", "UploadFailed", () => colors.negative[100])
|
|
72
76
|
.exhaustive(),
|
|
73
77
|
},
|
|
74
78
|
], children: [_jsx(Box, { alignItems: "center", direction: "row", style: styles.content, children: statusInfo.status === "Uploading" ? (_jsxs(_Fragment, { children: [_jsx(LakeText, { numberOfLines: 1, color: colors.gray[700], children: t("fileTile.uploading") }), _jsx(Space, { width: 20 }), _jsx(View, { role: "progressbar", style: styles.progressBar, children: _jsx(View, { style: [styles.progress, { width: `${statusInfo.progress * 100}%` }] }) })] })) : (_jsxs(_Fragment, { children: [statusInfo.status === "Validated" ? (_jsx(Icon, { size: 24, color: colors.positive[500], name: "checkmark-circle-regular" })) : (_jsx(Tag, { icon: getIconNameFromFilename(name), iconSize: 20, color: match(statusInfo)
|
|
75
79
|
.with({ status: P.union("Uploaded", "Pending") }, () => "shakespear")
|
|
76
|
-
.with({ status: "Refused" }, () => "negative")
|
|
77
|
-
.exhaustive() })), _jsx(Space, { width: 16 }), _jsxs(Box, { grow: 1, children: [_jsx(LakeText, { numberOfLines: 1, color: colors.gray[700], style: commonStyles.fill, children: name }), showId ? (_jsx(View, { style: styles.id, children: _jsx(LakeTooltip, { describedBy: "copy", onHide: () => setVisibleState("copy"), togglableOnFocus: true, content: visibleState === "copy"
|
|
80
|
+
.with({ status: P.union("Refused", "UploadFailed") }, () => "negative")
|
|
81
|
+
.exhaustive() })), _jsx(Space, { width: 16 }), _jsxs(Box, { grow: 1, children: [_jsx(LakeText, { numberOfLines: 1, color: colors.gray[700], style: commonStyles.fill, children: name }), showId && statusInfo.status !== "UploadFailed" ? (_jsx(View, { style: styles.id, children: _jsx(LakeTooltip, { describedBy: "copy", onHide: () => setVisibleState("copy"), togglableOnFocus: true, content: visibleState === "copy"
|
|
78
82
|
? t("copyButton.copyTooltip")
|
|
79
83
|
: t("copyButton.copiedTooltip"), children: _jsx(Pressable, { onPress: event => {
|
|
80
84
|
event.stopPropagation();
|
|
@@ -83,8 +87,11 @@ export const FileTile = ({ file: { id, statusInfo, name, url }, showId = false,
|
|
|
83
87
|
setVisibleState("copied");
|
|
84
88
|
}, children: _jsxs(Box, { direction: "row", alignItems: "center", children: [_jsx(LakeText, { numberOfLines: 1, variant: "smallRegular", children: t("fileTile.id", { id }) }), _jsx(Space, { width: 4 }), _jsx(Icon, { size: 14, name: "copy-regular" })] }) }) }) })) : null] }), _jsx(Space, { width: 12 }), isNotNullishOrEmpty(url) && (_jsx(LakeButton, { mode: "tertiary", size: "small", icon: "open-filled", onPress: () => {
|
|
85
89
|
window.open(url, "_blank");
|
|
86
|
-
}, ariaLabel: t("common.open") })), isNotNullish(onRemove) && (_jsx(LakeButton, { mode: "tertiary", size: "small", icon: "delete-regular", color: "negative", onPress:
|
|
90
|
+
}, ariaLabel: t("common.open") })), isNotNullish(onRemove) && (_jsx(LakeButton, { mode: "tertiary", size: "small", icon: "delete-regular", color: "negative", onPress: statusInfo.status === "UploadFailed"
|
|
91
|
+
? onPressRemove
|
|
92
|
+
: () => setIsDeleteModalVisible(true), ariaLabel: t("common.remove") })), _jsx(LakeModal, { title: t("fileTile.deleteModal.title"), icon: "subtract-circle-regular", visible: isDeleteModalVisible, onPressClose: () => setIsDeleteModalVisible(false), color: "negative", children: _jsx(LakeButtonGroup, { paddingBottom: 0, children: _jsx(LakeButton, { loading: isDeleting, grow: true, color: "negative", onPress: onPressRemove, children: t("fileTile.deleteModal.delete") }) }) })] })) }), match(statusInfo)
|
|
87
93
|
.with({ status: "Pending" }, () => (_jsx(LakeAlert, { anchored: true, title: t("fileTile.status.Pending"), variant: "info" })))
|
|
88
94
|
.with({ status: "Refused" }, ({ reason, reasonCode }) => (_jsx(LakeAlert, { anchored: true, variant: "error", title: getRejectionReasonLabel(reasonCode), children: isNotNullishOrEmpty(reason) ? _jsx(LakeText, { children: reason }) : null })))
|
|
89
|
-
.
|
|
95
|
+
.with({ status: "UploadFailed" }, () => (_jsx(View, { role: "alert", children: _jsx(LakeAlert, { anchored: true, variant: "error", title: t("fileTile.error.upload"), children: isNotNullish(onRetry) ? (_jsx(Box, { alignItems: "start", children: _jsx(LakeButton, { size: "small", mode: "secondary", color: "gray", onPress: onRetry, children: t("fileTile.tryAgain") }) })) : null }) })))
|
|
96
|
+
.otherwise(() => removeFailures > 0 ? (_jsx(View, { role: "alert", children: _jsx(LakeAlert, { anchored: true, variant: "error", title: t("fileTile.error.remove"), children: _jsx(Box, { alignItems: "start", children: _jsx(LakeButton, { size: "small", mode: "secondary", color: "gray", loading: isDeleting, onPress: onPressRemove, children: t("fileTile.tryAgain") }) }) }) }, removeFailures)) : null)] }));
|
|
90
97
|
};
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { Future, Result } from "@bloodyowl/boxed";
|
|
2
3
|
import { Box } from "@swan-io/lake/src/components/Box";
|
|
3
4
|
import { Space } from "@swan-io/lake/src/components/Space";
|
|
4
5
|
import { Fragment, useEffect, useImperativeHandle, useRef } from "react";
|
|
6
|
+
import { match } from "ts-pattern";
|
|
5
7
|
import { useFilesUploader } from "../hooks/useFilesUploader";
|
|
6
8
|
import { FileInput } from "./FileInput";
|
|
7
9
|
import { FileTile } from "./FileTile";
|
|
8
10
|
export const FilesUploader = ({ ref, id, maxSize, accept, icon, getUploadConfig, onRemoveFile, onChange, formatAndSizeDescription, canUpload = true, showIds = false, ...config }) => {
|
|
9
|
-
const { files, upload, remove, add } = useFilesUploader(config);
|
|
11
|
+
const { files, upload, remove, retry, add } = useFilesUploader(config);
|
|
10
12
|
// Keep the `onChange` callback as a ref to avoid running the effect
|
|
11
13
|
// every time the function updates
|
|
12
14
|
const onChangeRef = useRef(onChange);
|
|
@@ -23,16 +25,22 @@ export const FilesUploader = ({ ref, id, maxSize, accept, icon, getUploadConfig,
|
|
|
23
25
|
}
|
|
24
26
|
const onChange = onChangeRef.current;
|
|
25
27
|
if (onChange != null) {
|
|
26
|
-
onChange(files);
|
|
28
|
+
onChange(files.filter(file => file.statusInfo.status !== "UploadFailed"));
|
|
27
29
|
}
|
|
28
30
|
}, [files]);
|
|
29
31
|
return (_jsxs(Box, { children: [canUpload ? (_jsxs(_Fragment, { children: [_jsx(FileInput, { id: id, layout: "horizontal", onFiles: files => {
|
|
30
32
|
files.forEach(file => {
|
|
31
33
|
upload(getUploadConfig(file), file);
|
|
32
34
|
});
|
|
33
|
-
}, accept: accept, icon: icon, description: formatAndSizeDescription, maxSize: maxSize }), _jsx(Space, { height: 12 })] })) : null, files.map((file, index) => (_jsxs(Fragment, { children: [index > 0 ? _jsx(Space, { height: 12 }) : null, _jsx(FileTile, { file: file, showId: showIds,
|
|
35
|
+
}, accept: accept, icon: icon, description: formatAndSizeDescription, maxSize: maxSize }), _jsx(Space, { height: 12 })] })) : null, files.map((file, index) => (_jsxs(Fragment, { children: [index > 0 ? _jsx(Space, { height: 12 }) : null, _jsx(FileTile, { file: file, showId: showIds, onRetry: () => retry(file.id), onRemove: match(file.statusInfo.status)
|
|
36
|
+
.with("UploadFailed", () => () => {
|
|
37
|
+
remove(file.id);
|
|
38
|
+
return Future.value(Result.Ok(undefined));
|
|
39
|
+
})
|
|
40
|
+
.with("Uploaded", () => onRemoveFile != null
|
|
34
41
|
? () => onRemoveFile(file).tapOk(() => {
|
|
35
42
|
remove(file.id);
|
|
36
43
|
})
|
|
37
|
-
: undefined
|
|
44
|
+
: undefined)
|
|
45
|
+
.otherwise(() => undefined) })] }, file.id)))] }));
|
|
38
46
|
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { FraudReportApi } from "../../utils/fraudReport/api";
|
|
2
|
+
import { FraudReportDocument } from "../../utils/fraudReport/documents";
|
|
3
|
+
import { FraudReportStepProps } from "./FraudReportLayout";
|
|
4
|
+
type Props = FraudReportStepProps<never> & {
|
|
5
|
+
supportingDocumentCollectionId: string;
|
|
6
|
+
api: Pick<FraudReportApi, "generateUpload" | "uploadFile" | "removeFile">;
|
|
7
|
+
initialDocuments: FraudReportDocument[];
|
|
8
|
+
onDocumentsChange: (documents: FraudReportDocument[]) => void;
|
|
9
|
+
onPrevious: () => void;
|
|
10
|
+
loading?: boolean;
|
|
11
|
+
};
|
|
12
|
+
export declare const DocumentsStep: ({ supportingDocumentCollectionId, api, initialDocuments, onDocumentsChange, onNext, onPrevious, loading, }: Props) => import("react").JSX.Element;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { LakeLabel } from "@swan-io/lake/src/components/LakeLabel";
|
|
3
|
+
import { Space } from "@swan-io/lake/src/components/Space";
|
|
4
|
+
import { Tile } from "@swan-io/lake/src/components/Tile";
|
|
5
|
+
import { Fragment, useRef, useState } from "react";
|
|
6
|
+
import { match } from "ts-pattern";
|
|
7
|
+
import { MAX_SUPPORTING_DOCUMENT_UPLOAD_SIZE, MAX_SUPPORTING_DOCUMENT_UPLOAD_SIZE_MB, } from "../../constants/uploads";
|
|
8
|
+
import { fraudReportDocumentGroups, getGroupFiles, getUploadPurpose, setGroupFiles, } from "../../utils/fraudReport/documents";
|
|
9
|
+
import { t } from "../../utils/i18n";
|
|
10
|
+
import { FilesUploader } from "../FilesUploader";
|
|
11
|
+
import { uploadSupportingDocumentFile } from "../SupportingDocumentCollection";
|
|
12
|
+
import { FraudReportFooter } from "./FraudReportLayout";
|
|
13
|
+
const ACCEPTED_FORMATS = ["application/pdf", "image/jpeg", "image/png", "image/heic"];
|
|
14
|
+
const isSameDocuments = (documents, others) => documents.length === others.length &&
|
|
15
|
+
documents.every(document => others.some(({ file, purpose }) => file === document.file && purpose === document.purpose));
|
|
16
|
+
const getGroupText = (group) => match(group)
|
|
17
|
+
.with("PoliceReport", () => ({
|
|
18
|
+
label: t("fraudReport.documents.policeReport"),
|
|
19
|
+
description: t("fraudReport.documents.policeReportDescription"),
|
|
20
|
+
}))
|
|
21
|
+
.with("OtherDocuments", () => ({
|
|
22
|
+
label: t("fraudReport.documents.otherDocuments"),
|
|
23
|
+
description: t("fraudReport.documents.otherDocumentsDescription"),
|
|
24
|
+
}))
|
|
25
|
+
.exhaustive();
|
|
26
|
+
export const DocumentsStep = ({ supportingDocumentCollectionId, api, initialDocuments, onDocumentsChange, onNext, onPrevious, loading, }) => {
|
|
27
|
+
const documentsRef = useRef(initialDocuments);
|
|
28
|
+
const [uploadingGroups, setUploadingGroups] = useState({});
|
|
29
|
+
const isUploading = Object.values(uploadingGroups).some(Boolean);
|
|
30
|
+
return (_jsxs(_Fragment, { children: [_jsx(Tile, { title: t("fraudReport.documents.title"), description: t("fraudReport.documents.description"), children: fraudReportDocumentGroups.map((group, index) => {
|
|
31
|
+
const { label, description } = getGroupText(group);
|
|
32
|
+
return (_jsxs(Fragment, { children: [index > 0 ? _jsx(Space, { height: 24 }) : null, _jsx(LakeLabel, { label: label, optionalLabel: t("common.optional"), description: description, render: id => { var _a; return (_jsx(FilesUploader, { id: id, accept: ACCEPTED_FORMATS, maxSize: MAX_SUPPORTING_DOCUMENT_UPLOAD_SIZE, icon: "document-regular", formatAndSizeDescription: t("fraudReport.documents.formats", {
|
|
33
|
+
maxSizeMB: MAX_SUPPORTING_DOCUMENT_UPLOAD_SIZE_MB,
|
|
34
|
+
}), initialFiles: getGroupFiles(initialDocuments, group), getUploadConfig: file => ({
|
|
35
|
+
fileName: file.name,
|
|
36
|
+
purpose: getUploadPurpose(group),
|
|
37
|
+
}), generateUpload: input => api.generateUpload({ supportingDocumentCollectionId, ...input }), uploadFile: (_a = api.uploadFile) !== null && _a !== void 0 ? _a : uploadSupportingDocumentFile, onRemoveFile: api.removeFile, onChange: files => {
|
|
38
|
+
setUploadingGroups(groups => ({
|
|
39
|
+
...groups,
|
|
40
|
+
[group]: files.some(({ statusInfo }) => statusInfo.status === "Uploading"),
|
|
41
|
+
}));
|
|
42
|
+
const documents = setGroupFiles(documentsRef.current, group, files.filter(({ statusInfo }) => statusInfo.status !== "Uploading"));
|
|
43
|
+
if (!isSameDocuments(documents, documentsRef.current)) {
|
|
44
|
+
documentsRef.current = documents;
|
|
45
|
+
onDocumentsChange(documents);
|
|
46
|
+
}
|
|
47
|
+
} })); } })] }, group));
|
|
48
|
+
}) }), _jsx(FraudReportFooter, { onPrevious: onPrevious, onNext: () => onNext({}), loading: loading === true || isUploading, nextLabel: t("fraudReport.documents.reviewReport") })] }));
|
|
49
|
+
};
|
|
@@ -18,6 +18,7 @@ type FooterProps = {
|
|
|
18
18
|
onNext: () => void;
|
|
19
19
|
loading?: boolean;
|
|
20
20
|
nextDisabled?: boolean;
|
|
21
|
+
nextLabel?: string;
|
|
21
22
|
};
|
|
22
|
-
export declare const FraudReportFooter: ({ onPrevious, onNext, loading, nextDisabled }: FooterProps) => import("react").JSX.Element;
|
|
23
|
+
export declare const FraudReportFooter: ({ onPrevious, onNext, loading, nextDisabled, nextLabel, }: FooterProps) => import("react").JSX.Element;
|
|
23
24
|
export {};
|
|
@@ -29,7 +29,7 @@ export const FraudReportLayout = ({ activeStep, detailsSteps, children }) => {
|
|
|
29
29
|
const stepper = getFraudReportStepper({ activeStep, detailsSteps, getLabel: getStepLabel });
|
|
30
30
|
return (_jsx(ResponsiveContainer, { breakpoint: breakpoints.medium, style: styles.root, children: ({ small }) => (_jsxs(SmallLayoutContext.Provider, { value: small, children: [small ? (_jsx(MobileStepper, { steps: stepper.steps, activeStepId: stepper.activeStepId })) : (_jsx(LakeStepper, { steps: stepper.steps, activeStepId: stepper.activeStepId })), _jsx(Space, { height: small ? 24 : 48 }), children] })) }));
|
|
31
31
|
};
|
|
32
|
-
export const FraudReportFooter = ({ onPrevious, onNext, loading, nextDisabled }) => {
|
|
32
|
+
export const FraudReportFooter = ({ onPrevious, onNext, loading, nextDisabled, nextLabel = t("fraudReport.continue"), }) => {
|
|
33
33
|
const small = useFraudReportSmallLayout();
|
|
34
|
-
return (_jsxs(_Fragment, { children: [_jsx(Space, { height: small ? 8 : 16 }), _jsxs(LakeButtonGroup, { paddingBottom: 0, children: [isNotNullish(onPrevious) ? (_jsx(LakeButton, { mode: "secondary", color: "gray", disabled: loading, onPress: onPrevious, children: t("common.previous") })) : null, _jsx(LakeButton, { color: "current", ariaLabel: loading === true ?
|
|
34
|
+
return (_jsxs(_Fragment, { children: [_jsx(Space, { height: small ? 8 : 16 }), _jsxs(LakeButtonGroup, { paddingBottom: 0, children: [isNotNullish(onPrevious) ? (_jsx(LakeButton, { mode: "secondary", color: "gray", disabled: loading, onPress: onPrevious, children: t("common.previous") })) : null, _jsx(LakeButton, { color: "current", ariaLabel: loading === true ? nextLabel : undefined, loading: loading, disabled: nextDisabled, onPress: onNext, children: nextLabel })] })] }));
|
|
35
35
|
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { FraudReportStepProps } from "./FraudReportLayout";
|
|
2
|
+
type Props = FraudReportStepProps<"hasContactedBankOrBeneficiary" | "hasFiledPoliceComplaint"> & {
|
|
3
|
+
onPrevious: () => void;
|
|
4
|
+
loading?: boolean;
|
|
5
|
+
};
|
|
6
|
+
export declare const TransferDetailsStep: ({ values, onNext, onPrevious, loading }: Props) => import("react").JSX.Element;
|
|
7
|
+
export {};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { LakeLabel } from "@swan-io/lake/src/components/LakeLabel";
|
|
3
|
+
import { MultiSelect } from "@swan-io/lake/src/components/MultiSelect";
|
|
4
|
+
import { Tile } from "@swan-io/lake/src/components/Tile";
|
|
5
|
+
import { useForm } from "@swan-io/use-form";
|
|
6
|
+
import { getTransferActions, toTransferValues, } from "../../utils/fraudReport/transfer";
|
|
7
|
+
import { t } from "../../utils/i18n";
|
|
8
|
+
import { FraudReportFooter } from "./FraudReportLayout";
|
|
9
|
+
export const TransferDetailsStep = ({ values, onNext, onPrevious, loading }) => {
|
|
10
|
+
const { Field, submitForm } = useForm({
|
|
11
|
+
actions: { initialValue: getTransferActions(values) },
|
|
12
|
+
});
|
|
13
|
+
const actionItems = [
|
|
14
|
+
{
|
|
15
|
+
label: t("fraudReport.transfer.action.bankOrBeneficiary"),
|
|
16
|
+
value: "BankOrBeneficiary",
|
|
17
|
+
group: "",
|
|
18
|
+
},
|
|
19
|
+
{ label: t("fraudReport.transfer.action.police"), value: "Police", group: "" },
|
|
20
|
+
];
|
|
21
|
+
const onPressNext = () => submitForm({
|
|
22
|
+
onSuccess: ({ actions }) => onNext(toTransferValues(actions.getOr([]))),
|
|
23
|
+
});
|
|
24
|
+
return (_jsxs(_Fragment, { children: [_jsx(Tile, { title: t("fraudReport.transfer.actionsTitle"), children: _jsx(Field, { name: "actions", children: ({ value, onChange }) => (_jsx(LakeLabel, { label: t("fraudReport.transfer.actionsLabel"), optionalLabel: t("common.optional"), render: id => (_jsx(MultiSelect, { id: id, enableGroups: false, placeholder: t("fraudReport.transfer.actionsPlaceholder"), items: actionItems, values: value, onValueChange: onChange })) })) }) }), _jsx(FraudReportFooter, { onPrevious: onPrevious, onNext: onPressNext, loading: loading })] }));
|
|
25
|
+
};
|
|
@@ -28,6 +28,7 @@ export type UploadOutput = {
|
|
|
28
28
|
value: string;
|
|
29
29
|
}[];
|
|
30
30
|
};
|
|
31
|
+
export declare const uploadSupportingDocumentFile: ({ upload, file, onProgress, }: UploadFileInput<UploadOutput>) => Future<Result<Response<string>, import("@bloodyowl/request").BadStatusError | NetworkError | TimeoutError>>;
|
|
31
32
|
type SupportingDocumentCollectionStatus = "WaitingForDocument" | "PendingReview" | "Approved" | "Canceled" | "Rejected";
|
|
32
33
|
type PurposeMetadata = {
|
|
33
34
|
title: string;
|
|
@@ -31,6 +31,18 @@ export const toDocumentPurposes = (requiredPurposes) => {
|
|
|
31
31
|
});
|
|
32
32
|
return Object.fromEntries(entries);
|
|
33
33
|
};
|
|
34
|
+
export const uploadSupportingDocumentFile = ({ upload, file, onProgress, }) => {
|
|
35
|
+
const body = new FormData();
|
|
36
|
+
upload.fields.forEach(({ key, value }) => body.append(key, value));
|
|
37
|
+
body.append("file", file);
|
|
38
|
+
setTimeout(() => onProgress(0.8), 100);
|
|
39
|
+
return Request.make({
|
|
40
|
+
url: upload.url,
|
|
41
|
+
method: "POST",
|
|
42
|
+
body,
|
|
43
|
+
type: "text",
|
|
44
|
+
}).mapOkToResult(badStatusToError);
|
|
45
|
+
};
|
|
34
46
|
const styles = StyleSheet.create({
|
|
35
47
|
button: { opacity: 1 },
|
|
36
48
|
buttonWithDefaultCursor: { opacity: 1, cursor: "default" },
|
|
@@ -127,20 +139,7 @@ export const SupportingDocumentCollection = ({ ref, documents, generateUpload, u
|
|
|
127
139
|
canUpload: !readonlyDocumentPurposes.includes(purpose) &&
|
|
128
140
|
!readOnly &&
|
|
129
141
|
status === "WaitingForDocument" &&
|
|
130
|
-
!areAllDocumentsValidated, accept: ACCEPTED_FORMATS, maxSize: 20000000, icon: "document-regular", initialFiles: files, generateUpload: generateUpload, getUploadConfig: file => ({ fileName: file.name, purpose }), uploadFile:
|
|
131
|
-
? uploadFile
|
|
132
|
-
: ({ upload, file, onProgress }) => {
|
|
133
|
-
const body = new FormData();
|
|
134
|
-
upload.fields.forEach(({ key, value }) => body.append(key, value));
|
|
135
|
-
body.append("file", file);
|
|
136
|
-
setTimeout(() => onProgress(0.8), 100);
|
|
137
|
-
return Request.make({
|
|
138
|
-
url: upload.url,
|
|
139
|
-
method: "POST",
|
|
140
|
-
body,
|
|
141
|
-
type: "text",
|
|
142
|
-
}).mapOkToResult(badStatusToError);
|
|
143
|
-
}, formatAndSizeDescription: t("supportingDocuments.documentTypes", {
|
|
142
|
+
!areAllDocumentsValidated, accept: ACCEPTED_FORMATS, maxSize: 20000000, icon: "document-regular", initialFiles: files, generateUpload: generateUpload, getUploadConfig: file => ({ fileName: file.name, purpose }), uploadFile: uploadFile !== null && uploadFile !== void 0 ? uploadFile : uploadSupportingDocumentFile, formatAndSizeDescription: t("supportingDocuments.documentTypes", {
|
|
144
143
|
maxSizeMB: 20000000 / 1000000,
|
|
145
144
|
}), onRemoveFile: readOnly ? undefined : onRemoveFile, onChange: files => {
|
|
146
145
|
if (isRequired) {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { Future, Result } from "@bloodyowl/boxed";
|
|
2
|
+
import { act, renderHook } from "@testing-library/react";
|
|
3
|
+
import { describe, expect, test, vi } from "vitest";
|
|
4
|
+
import { useFilesUploader } from "../useFilesUploader";
|
|
5
|
+
const pdf = (name) => new File(["file"], name, { type: "application/pdf" });
|
|
6
|
+
const uploaded = (id, name) => ({
|
|
7
|
+
id,
|
|
8
|
+
name,
|
|
9
|
+
statusInfo: { status: "Uploaded" },
|
|
10
|
+
});
|
|
11
|
+
const generated = (id) => Future.value(Result.Ok({ id, upload: "" }));
|
|
12
|
+
const failure = () => Future.value(Result.Error("network"));
|
|
13
|
+
const render = ({ initialFiles = [], generateUpload = vi.fn(() => generated("server")), uploadFile = vi.fn(() => Future.value(Result.Ok(undefined))), }) => renderHook(() => useFilesUploader({
|
|
14
|
+
initialFiles,
|
|
15
|
+
generateUpload,
|
|
16
|
+
uploadFile,
|
|
17
|
+
}));
|
|
18
|
+
const statuses = (files) => files.map(({ name, statusInfo }) => `${name} ${statusInfo.status}`);
|
|
19
|
+
describe("useFilesUploader", () => {
|
|
20
|
+
test("shows a file as uploading before generateUpload answers, then keeps its place", () => {
|
|
21
|
+
let answer = () => { };
|
|
22
|
+
const { result } = render({
|
|
23
|
+
initialFiles: [uploaded("saved", "saved.pdf")],
|
|
24
|
+
generateUpload: () => Future.make(resolve => {
|
|
25
|
+
answer = resolve;
|
|
26
|
+
}),
|
|
27
|
+
});
|
|
28
|
+
act(() => {
|
|
29
|
+
result.current.upload({ fileName: "report.pdf" }, pdf("report.pdf"));
|
|
30
|
+
});
|
|
31
|
+
expect(statuses(result.current.files)).toEqual(["saved.pdf Uploaded", "report.pdf Uploading"]);
|
|
32
|
+
act(() => answer(Result.Ok({ id: "server", upload: "" })));
|
|
33
|
+
expect(result.current.files).toEqual([
|
|
34
|
+
uploaded("saved", "saved.pdf"),
|
|
35
|
+
uploaded("server", "report.pdf"),
|
|
36
|
+
]);
|
|
37
|
+
});
|
|
38
|
+
test("keeps a file whose upload couldn't start, and retries it", () => {
|
|
39
|
+
const generateUpload = vi
|
|
40
|
+
.fn(() => generated("server"))
|
|
41
|
+
.mockImplementationOnce(failure);
|
|
42
|
+
const { result } = render({ generateUpload });
|
|
43
|
+
act(() => {
|
|
44
|
+
result.current.upload({ fileName: "report.pdf" }, pdf("report.pdf"));
|
|
45
|
+
});
|
|
46
|
+
expect(statuses(result.current.files)).toEqual(["report.pdf UploadFailed"]);
|
|
47
|
+
act(() => { var _a; var _b; return result.current.retry((_b = (_a = result.current.files[0]) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : ""); });
|
|
48
|
+
expect(result.current.files).toEqual([uploaded("server", "report.pdf")]);
|
|
49
|
+
expect(generateUpload).toHaveBeenCalledTimes(2);
|
|
50
|
+
});
|
|
51
|
+
test("keeps a file whose upload failed, with the ID generateUpload gave", () => {
|
|
52
|
+
const uploadFile = vi
|
|
53
|
+
.fn(() => Future.value(Result.Ok(undefined)))
|
|
54
|
+
.mockImplementationOnce(failure);
|
|
55
|
+
const { result } = render({ uploadFile });
|
|
56
|
+
act(() => {
|
|
57
|
+
result.current.upload({ fileName: "report.pdf" }, pdf("report.pdf"));
|
|
58
|
+
});
|
|
59
|
+
expect(result.current.files).toEqual([
|
|
60
|
+
{ id: "server", name: "report.pdf", statusInfo: { status: "UploadFailed" } },
|
|
61
|
+
]);
|
|
62
|
+
});
|
|
63
|
+
test("retries a failed file in its place in the list", () => {
|
|
64
|
+
const uploadFile = vi
|
|
65
|
+
.fn(() => Future.value(Result.Ok(undefined)))
|
|
66
|
+
.mockImplementationOnce(failure);
|
|
67
|
+
let nextId = 0;
|
|
68
|
+
const { result } = render({
|
|
69
|
+
initialFiles: [uploaded("saved", "saved.pdf")],
|
|
70
|
+
generateUpload: () => generated(`server-${++nextId}`),
|
|
71
|
+
uploadFile,
|
|
72
|
+
});
|
|
73
|
+
act(() => {
|
|
74
|
+
result.current.upload({ fileName: "report.pdf" }, pdf("report.pdf"));
|
|
75
|
+
});
|
|
76
|
+
act(() => {
|
|
77
|
+
result.current.upload({ fileName: "later.pdf" }, pdf("later.pdf"));
|
|
78
|
+
});
|
|
79
|
+
expect(statuses(result.current.files)).toEqual([
|
|
80
|
+
"saved.pdf Uploaded",
|
|
81
|
+
"report.pdf UploadFailed",
|
|
82
|
+
"later.pdf Uploaded",
|
|
83
|
+
]);
|
|
84
|
+
act(() => result.current.retry("server-1"));
|
|
85
|
+
expect(statuses(result.current.files)).toEqual([
|
|
86
|
+
"saved.pdf Uploaded",
|
|
87
|
+
"report.pdf Uploaded",
|
|
88
|
+
"later.pdf Uploaded",
|
|
89
|
+
]);
|
|
90
|
+
});
|
|
91
|
+
test("replaces a listed file when generateUpload gives its ID again", () => {
|
|
92
|
+
const { result } = render({
|
|
93
|
+
initialFiles: [uploaded("document", "old.pdf")],
|
|
94
|
+
generateUpload: () => generated("document"),
|
|
95
|
+
});
|
|
96
|
+
act(() => {
|
|
97
|
+
result.current.upload({ fileName: "new.pdf" }, pdf("new.pdf"));
|
|
98
|
+
});
|
|
99
|
+
expect(result.current.files).toEqual([uploaded("document", "new.pdf")]);
|
|
100
|
+
});
|
|
101
|
+
});
|
|
@@ -18,7 +18,8 @@ export type Config<UploadInput, UploadOutput, GenerateUploadError, UploadFileErr
|
|
|
18
18
|
};
|
|
19
19
|
export declare const useFilesUploader: <UploadInput, UploadOutput, GenerateUploadError, UploadFileError>(config: Config<UploadInput, UploadOutput, GenerateUploadError, UploadFileError>) => {
|
|
20
20
|
files: SwanFile[];
|
|
21
|
-
upload: (uploadInput: UploadInput, file: File) => Future<Result<unknown, GenerateUploadError | UploadFileError>>;
|
|
21
|
+
upload: (uploadInput: UploadInput, file: File, placeholderId?: string) => Future<Result<unknown, GenerateUploadError | UploadFileError>>;
|
|
22
22
|
remove: (id: string) => void;
|
|
23
|
+
retry: (id: string) => void;
|
|
23
24
|
add: (fileToAdd: SwanFile) => void;
|
|
24
25
|
};
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import { useCallback, useState } from "react";
|
|
1
|
+
import { useCallback, useRef, useState } from "react";
|
|
2
|
+
import { v4 as uuid } from "uuid";
|
|
2
3
|
export const useFilesUploader = (config) => {
|
|
3
4
|
const [files, setFiles] = useState(config.initialFiles);
|
|
5
|
+
const failedUploads = useRef(new Map());
|
|
4
6
|
const add = useCallback((fileToAdd) => {
|
|
5
7
|
setFiles(files => {
|
|
6
8
|
if (files.some(item => item.id === fileToAdd.id)) {
|
|
@@ -11,23 +13,31 @@ export const useFilesUploader = (config) => {
|
|
|
11
13
|
}
|
|
12
14
|
});
|
|
13
15
|
}, []);
|
|
14
|
-
const
|
|
16
|
+
const setFailed = useCallback((id, uploadInput, file) => {
|
|
17
|
+
failedUploads.current.set(id, { uploadInput, file });
|
|
18
|
+
add({ id, name: file.name, statusInfo: { status: "UploadFailed" } });
|
|
19
|
+
}, [add]);
|
|
20
|
+
const upload = useCallback((uploadInput, file, placeholderId = uuid()) => {
|
|
21
|
+
add({ id: placeholderId, name: file.name, statusInfo: { status: "Uploading", progress: 0 } });
|
|
15
22
|
return config
|
|
16
23
|
.generateUpload(uploadInput)
|
|
17
24
|
.tapError(error => {
|
|
18
25
|
if (config.onError != null) {
|
|
19
26
|
config.onError(error);
|
|
20
27
|
}
|
|
28
|
+
setFailed(placeholderId, uploadInput, file);
|
|
21
29
|
})
|
|
22
30
|
.flatMapOk(({ upload, id }) => {
|
|
23
|
-
setFiles(files =>
|
|
24
|
-
|
|
25
|
-
{
|
|
31
|
+
setFiles(files => {
|
|
32
|
+
const uploadingFile = {
|
|
26
33
|
id,
|
|
27
34
|
statusInfo: { status: "Uploading", progress: 0 },
|
|
28
35
|
name: file.name,
|
|
29
|
-
}
|
|
30
|
-
|
|
36
|
+
};
|
|
37
|
+
return files
|
|
38
|
+
.filter(file => file.id !== id || file.id === placeholderId)
|
|
39
|
+
.map(file => (file.id === placeholderId ? uploadingFile : file));
|
|
40
|
+
});
|
|
31
41
|
const onProgress = (progress) => {
|
|
32
42
|
setFiles(files => files.map(file => {
|
|
33
43
|
// A late progress report (upload is faster than fake progress bar)
|
|
@@ -63,17 +73,26 @@ export const useFilesUploader = (config) => {
|
|
|
63
73
|
if (config.onError != null) {
|
|
64
74
|
config.onError(error);
|
|
65
75
|
}
|
|
66
|
-
|
|
76
|
+
setFailed(id, uploadInput, file);
|
|
67
77
|
});
|
|
68
78
|
});
|
|
69
|
-
}, [config]);
|
|
79
|
+
}, [add, config, setFailed]);
|
|
70
80
|
const remove = useCallback((id) => {
|
|
81
|
+
failedUploads.current.delete(id);
|
|
71
82
|
setFiles(files => files.filter(file => file.id !== id));
|
|
72
83
|
}, []);
|
|
84
|
+
const retry = useCallback((id) => {
|
|
85
|
+
const failedUpload = failedUploads.current.get(id);
|
|
86
|
+
if (failedUpload != null) {
|
|
87
|
+
failedUploads.current.delete(id);
|
|
88
|
+
upload(failedUpload.uploadInput, failedUpload.file, id);
|
|
89
|
+
}
|
|
90
|
+
}, [upload]);
|
|
73
91
|
return {
|
|
74
92
|
files,
|
|
75
93
|
upload,
|
|
76
94
|
remove,
|
|
95
|
+
retry,
|
|
77
96
|
add,
|
|
78
97
|
};
|
|
79
98
|
};
|