-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
index.js
356 lines (321 loc) · 14.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import lodashGet from 'lodash/get';
import React, {useCallback, useContext, useReducer, useRef, useState} from 'react';
import {ActivityIndicator, PanResponder, PixelRatio, Text, View} from 'react-native';
import Hand from '@assets/images/hand.svg';
import ReceiptUpload from '@assets/images/receipt-upload.svg';
import Shutter from '@assets/images/shutter.svg';
import AttachmentPicker from '@components/AttachmentPicker';
import Button from '@components/Button';
import ConfirmModal from '@components/ConfirmModal';
import CopyTextToClipboard from '@components/CopyTextToClipboard';
import {DragAndDropContext} from '@components/DragAndDrop/Provider';
import Icon from '@components/Icon';
import * as Expensicons from '@components/Icon/Expensicons';
import PressableWithFeedback from '@components/Pressable/PressableWithFeedback';
import transactionPropTypes from '@components/transactionPropTypes';
import useLocalize from '@hooks/useLocalize';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import useWindowDimensions from '@hooks/useWindowDimensions';
import * as Browser from '@libs/Browser';
import compose from '@libs/compose';
import * as FileUtils from '@libs/fileDownload/FileUtils';
import Navigation from '@libs/Navigation/Navigation';
import ReceiptDropUI from '@pages/iou/ReceiptDropUI';
import IOURequestStepRoutePropTypes from '@pages/iou/request/step/IOURequestStepRoutePropTypes';
import StepScreenDragAndDropWrapper from '@pages/iou/request/step/StepScreenDragAndDropWrapper';
import withFullTransactionOrNotFound from '@pages/iou/request/step/withFullTransactionOrNotFound';
import withWritableReportOrNotFound from '@pages/iou/request/step/withWritableReportOrNotFound';
import reportPropTypes from '@pages/reportPropTypes';
import * as IOU from '@userActions/IOU';
import CONST from '@src/CONST';
import ROUTES from '@src/ROUTES';
import NavigationAwareCamera from './NavigationAwareCamera';
const propTypes = {
/** Navigation route context info provided by react navigation */
route: IOURequestStepRoutePropTypes.isRequired,
/* Onyx Props */
/** The report that the transaction belongs to */
report: reportPropTypes,
/** The transaction (or draft transaction) being changed */
transaction: transactionPropTypes,
};
const defaultProps = {
report: {},
transaction: {},
};
function IOURequestStepScan({
report,
route: {
params: {action, iouType, reportID, transactionID, backTo},
},
transaction: {isFromGlobalCreate},
}) {
const theme = useTheme();
const styles = useThemeStyles();
// Grouping related states
const [isAttachmentInvalid, setIsAttachmentInvalid] = useState(false);
const [attachmentInvalidReasonTitle, setAttachmentInvalidReasonTitle] = useState('');
const [attachmentInvalidReason, setAttachmentValidReason] = useState('');
const [receiptImageTopPosition, setReceiptImageTopPosition] = useState(0);
const {isSmallScreenWidth} = useWindowDimensions();
const {translate} = useLocalize();
const {isDraggingOver} = useContext(DragAndDropContext);
const [cameraPermissionState, setCameraPermissionState] = useState('prompt');
const [isFlashLightOn, toggleFlashlight] = useReducer((state) => !state, false);
const [isTorchAvailable, setIsTorchAvailable] = useState(false);
const cameraRef = useRef(null);
const hideRecieptModal = () => {
setIsAttachmentInvalid(false);
};
/**
* Sets the upload receipt error modal content when an invalid receipt is uploaded
* @param {*} isInvalid
* @param {*} title
* @param {*} reason
*/
const setUploadReceiptError = (isInvalid, title, reason) => {
setIsAttachmentInvalid(isInvalid);
setAttachmentInvalidReasonTitle(title);
setAttachmentValidReason(reason);
};
function validateReceipt(file) {
const {fileExtension} = FileUtils.splitExtensionFromFileName(lodashGet(file, 'name', ''));
if (!CONST.API_ATTACHMENT_VALIDATIONS.ALLOWED_RECEIPT_EXTENSIONS.includes(fileExtension.toLowerCase())) {
setUploadReceiptError(true, 'attachmentPicker.wrongFileType', 'attachmentPicker.notAllowedExtension');
return false;
}
if (lodashGet(file, 'size', 0) > CONST.API_ATTACHMENT_VALIDATIONS.MAX_SIZE) {
setUploadReceiptError(true, 'attachmentPicker.attachmentTooLarge', 'attachmentPicker.sizeExceeded');
return false;
}
if (lodashGet(file, 'size', 0) < CONST.API_ATTACHMENT_VALIDATIONS.MIN_SIZE) {
setUploadReceiptError(true, 'attachmentPicker.attachmentTooSmall', 'attachmentPicker.sizeNotMet');
return false;
}
return true;
}
const navigateBack = () => {
Navigation.goBack(backTo || ROUTES.HOME);
};
const navigateToConfirmationStep = useCallback(() => {
if (backTo) {
Navigation.goBack(backTo);
return;
}
// If the transaction was created from the global create, the person needs to select participants, so take them there.
if (isFromGlobalCreate) {
Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_PARTICIPANTS.getRoute(iouType, transactionID, reportID));
return;
}
// If the transaction was created from the + menu from the composer inside of a chat, the participants can automatically
// be added to the transaction (taken from the chat report participants) and then the person is taken to the confirmation step.
IOU.setMoneyRequestParticipantsFromReport(transactionID, report);
Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_CONFIRMATION.getRoute(iouType, transactionID, reportID));
}, [iouType, report, reportID, transactionID, isFromGlobalCreate, backTo]);
const updateScanAndNavigate = useCallback(
(file, source) => {
IOU.replaceReceipt(transactionID, file, source);
if (backTo) {
Navigation.goBack(backTo);
return;
}
Navigation.dismissModal();
},
[backTo, transactionID],
);
/**
* Sets the Receipt objects and navigates the user to the next page
* @param {Object} file
*/
const setReceiptAndNavigate = (file) => {
if (!validateReceipt(file)) {
return;
}
// Store the receipt on the transaction object in Onyx
const source = URL.createObjectURL(file);
IOU.setMoneyRequestReceipt(transactionID, source, file.name, action !== CONST.IOU.ACTION.EDIT);
if (action === CONST.IOU.ACTION.EDIT) {
updateScanAndNavigate(file, source);
return;
}
navigateToConfirmationStep();
};
const capturePhoto = useCallback(() => {
if (!cameraRef.current.getScreenshot) {
return;
}
const imageBase64 = cameraRef.current.getScreenshot();
const filename = `receipt_${Date.now()}.png`;
const file = FileUtils.base64ToFile(imageBase64, filename);
const source = URL.createObjectURL(file);
IOU.setMoneyRequestReceipt(transactionID, source, file.name, action !== CONST.IOU.ACTION.EDIT);
if (action === CONST.IOU.ACTION.EDIT) {
updateScanAndNavigate(file, source);
return;
}
navigateToConfirmationStep();
}, [cameraRef, action, transactionID, updateScanAndNavigate, navigateToConfirmationStep]);
const panResponder = useRef(
PanResponder.create({
onPanResponderTerminationRequest: () => false,
}),
).current;
const mobileCameraView = () => (
<>
<View style={[styles.cameraView]}>
{(cameraPermissionState === 'prompt' || !cameraPermissionState) && (
<ActivityIndicator
size={CONST.ACTIVITY_INDICATOR_SIZE.LARGE}
style={[styles.flex1]}
color={theme.textSupporting}
/>
)}
{cameraPermissionState === 'denied' && (
<View style={[styles.flex1, styles.permissionView, styles.userSelectNone]}>
<Icon
src={Hand}
width={CONST.RECEIPT.HAND_ICON_WIDTH}
height={CONST.RECEIPT.HAND_ICON_HEIGHT}
style={[styles.pb5]}
/>
<Text style={[styles.textReceiptUpload]}>{translate('receipt.takePhoto')}</Text>
<Text style={[styles.subTextReceiptUpload]}>{translate('receipt.cameraAccess')}</Text>
</View>
)}
<NavigationAwareCamera
onUserMedia={() => setCameraPermissionState('granted')}
onUserMediaError={() => setCameraPermissionState('denied')}
style={{...styles.videoContainer, display: cameraPermissionState !== 'granted' ? 'none' : 'block'}}
ref={cameraRef}
screenshotFormat="image/png"
videoConstraints={{facingMode: {exact: 'environment'}}}
torchOn={isFlashLightOn}
onTorchAvailability={setIsTorchAvailable}
forceScreenshotSourceSize
cameraTabIndex={1}
/>
</View>
<View style={[styles.flexRow, styles.justifyContentAround, styles.alignItemsCenter, styles.pv3]}>
<AttachmentPicker>
{({openPicker}) => (
<PressableWithFeedback
accessibilityLabel={translate('receipt.chooseFile')}
role={CONST.ACCESSIBILITY_ROLE.BUTTON}
onPress={() => {
openPicker({
onPicked: setReceiptAndNavigate,
});
}}
>
<Icon
height={32}
width={32}
src={Expensicons.Gallery}
fill={theme.textSupporting}
/>
</PressableWithFeedback>
)}
</AttachmentPicker>
<PressableWithFeedback
role={CONST.ACCESSIBILITY_ROLE.BUTTON}
accessibilityLabel={translate('receipt.shutter')}
style={[styles.alignItemsCenter]}
onPress={capturePhoto}
>
<Shutter
width={CONST.RECEIPT.SHUTTER_SIZE}
height={CONST.RECEIPT.SHUTTER_SIZE}
/>
</PressableWithFeedback>
<PressableWithFeedback
role={CONST.ACCESSIBILITY_ROLE.BUTTON}
accessibilityLabel={translate('receipt.flash')}
style={[styles.alignItemsEnd, !isTorchAvailable && styles.opacity0]}
onPress={toggleFlashlight}
disabled={!isTorchAvailable}
>
<Icon
height={32}
width={32}
src={Expensicons.Bolt}
fill={isFlashLightOn ? theme.iconHovered : theme.textSupporting}
/>
</PressableWithFeedback>
</View>
</>
);
const desktopUploadView = () => (
<>
<View onLayout={({nativeEvent}) => setReceiptImageTopPosition(PixelRatio.roundToNearestPixel(nativeEvent.layout.top))}>
<ReceiptUpload
width={CONST.RECEIPT.ICON_SIZE}
height={CONST.RECEIPT.ICON_SIZE}
/>
</View>
<View
style={[styles.receiptViewTextContainer, styles.userSelectNone]}
// eslint-disable-next-line react/jsx-props-no-spreading
{...panResponder.panHandlers}
>
<Text style={[styles.textReceiptUpload]}>{translate('receipt.upload')}</Text>
<Text style={[styles.subTextReceiptUpload]}>
{isSmallScreenWidth ? translate('receipt.chooseReceipt') : translate('receipt.dragReceiptBeforeEmail')}
<CopyTextToClipboard
text={CONST.EMAIL.RECEIPTS}
textStyles={[styles.textBlue]}
/>
{isSmallScreenWidth ? null : translate('receipt.dragReceiptAfterEmail')}
</Text>
</View>
<AttachmentPicker>
{({openPicker}) => (
<Button
medium
success
text={translate('receipt.chooseFile')}
accessibilityLabel={translate('receipt.chooseFile')}
style={[styles.p9]}
onPress={() => {
openPicker({
onPicked: setReceiptAndNavigate,
});
}}
/>
)}
</AttachmentPicker>
</>
);
return (
<StepScreenDragAndDropWrapper
headerTitle={translate('common.receipt')}
onBackButtonPress={navigateBack}
shouldShowWrapper={Boolean(backTo)}
testID={IOURequestStepScan.displayName}
>
<View style={[styles.flex1, !Browser.isMobile() && styles.uploadReceiptView(isSmallScreenWidth)]}>
{!isDraggingOver && (Browser.isMobile() ? mobileCameraView() : desktopUploadView())}
<ReceiptDropUI
onDrop={(e) => {
const file = lodashGet(e, ['dataTransfer', 'files', 0]);
setReceiptAndNavigate(file);
}}
receiptImageTopPosition={receiptImageTopPosition}
/>
<ConfirmModal
title={attachmentInvalidReasonTitle ? translate(attachmentInvalidReasonTitle) : ''}
onConfirm={hideRecieptModal}
onCancel={hideRecieptModal}
isVisible={isAttachmentInvalid}
prompt={attachmentInvalidReason ? translate(attachmentInvalidReason) : ''}
confirmText={translate('common.close')}
shouldShowCancelButton={false}
/>
</View>
</StepScreenDragAndDropWrapper>
);
}
IOURequestStepScan.defaultProps = defaultProps;
IOURequestStepScan.propTypes = propTypes;
IOURequestStepScan.displayName = 'IOURequestStepScan';
export default compose(withWritableReportOrNotFound, withFullTransactionOrNotFound)(IOURequestStepScan);