-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
MoneyRequestView.tsx
481 lines (451 loc) · 25 KB
/
MoneyRequestView.tsx
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import React, {useCallback, useMemo} from 'react';
import {View} from 'react-native';
import {withOnyx} from 'react-native-onyx';
import type {OnyxEntry} from 'react-native-onyx';
import ConfirmedRoute from '@components/ConfirmedRoute';
import * as Expensicons from '@components/Icon/Expensicons';
import MenuItemWithTopDescription from '@components/MenuItemWithTopDescription';
import OfflineWithFeedback from '@components/OfflineWithFeedback';
import ReceiptEmptyState from '@components/ReceiptEmptyState';
import SpacerView from '@components/SpacerView';
import Switch from '@components/Switch';
import Text from '@components/Text';
import ViolationMessages from '@components/ViolationMessages';
import useLocalize from '@hooks/useLocalize';
import usePermissions from '@hooks/usePermissions';
import useStyleUtils from '@hooks/useStyleUtils';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import useViolations from '@hooks/useViolations';
import type {ViolationField} from '@hooks/useViolations';
import useWindowDimensions from '@hooks/useWindowDimensions';
import * as CardUtils from '@libs/CardUtils';
import * as CurrencyUtils from '@libs/CurrencyUtils';
import * as OptionsListUtils from '@libs/OptionsListUtils';
import * as PolicyUtils from '@libs/PolicyUtils';
import * as ReceiptUtils from '@libs/ReceiptUtils';
import * as ReportActionsUtils from '@libs/ReportActionsUtils';
import * as ReportUtils from '@libs/ReportUtils';
import * as TransactionUtils from '@libs/TransactionUtils';
import ViolationsUtils from '@libs/Violations/ViolationsUtils';
import Navigation from '@navigation/Navigation';
import AnimatedEmptyStateBackground from '@pages/home/report/AnimatedEmptyStateBackground';
import * as IOU from '@userActions/IOU';
import * as Transaction from '@userActions/Transaction';
import CONST from '@src/CONST';
import type {TranslationPaths} from '@src/languages/types';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type * as OnyxTypes from '@src/types/onyx';
import type {TransactionPendingFieldsKey} from '@src/types/onyx/Transaction';
import ReportActionItemImage from './ReportActionItemImage';
type MoneyRequestViewTransactionOnyxProps = {
/** The transaction associated with the transactionThread */
transaction: OnyxEntry<OnyxTypes.Transaction>;
/** Violations detected in this transaction */
transactionViolations: OnyxEntry<OnyxTypes.TransactionViolations>;
};
type MoneyRequestViewOnyxPropsWithoutTransaction = {
/** The policy object for the current route */
policy: OnyxEntry<OnyxTypes.Policy>;
/** Collection of categories attached to a policy */
policyCategories: OnyxEntry<OnyxTypes.PolicyCategories>;
/** Collection of tags attached to a policy */
policyTagList: OnyxEntry<OnyxTypes.PolicyTagList>;
/** The expense report or iou report (only will have a value if this is a transaction thread) */
parentReport: OnyxEntry<OnyxTypes.Report>;
/** The actions from the parent report */
parentReportActions: OnyxEntry<OnyxTypes.ReportActions>;
};
type MoneyRequestViewPropsWithoutTransaction = MoneyRequestViewOnyxPropsWithoutTransaction & {
/** The report currently being looked at */
report: OnyxTypes.Report;
/** Whether we should display the horizontal rule below the component */
shouldShowHorizontalRule: boolean;
};
type MoneyRequestViewProps = MoneyRequestViewTransactionOnyxProps & MoneyRequestViewPropsWithoutTransaction;
function MoneyRequestView({
report,
parentReport,
parentReportActions,
policyCategories,
shouldShowHorizontalRule,
transaction,
policyTagList,
policy,
transactionViolations,
}: MoneyRequestViewProps) {
const theme = useTheme();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const {isSmallScreenWidth} = useWindowDimensions();
const {translate} = useLocalize();
const {canUseViolations} = usePermissions();
const parentReportAction = parentReportActions?.[report.parentReportActionID ?? ''] ?? null;
const moneyRequestReport = parentReport;
const {
created: transactionDate,
amount: transactionAmount,
currency: transactionCurrency,
comment: transactionDescription,
merchant: transactionMerchant,
billable: transactionBillable,
category: transactionCategory,
tag: transactionTag,
originalAmount: transactionOriginalAmount,
originalCurrency: transactionOriginalCurrency,
cardID: transactionCardID,
} = ReportUtils.getTransactionDetails(transaction) ?? {};
const isEmptyMerchant = transactionMerchant === '' || transactionMerchant === CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT;
const isDistanceRequest = TransactionUtils.isDistanceRequest(transaction);
const formattedTransactionAmount = transactionAmount ? CurrencyUtils.convertToDisplayString(transactionAmount, transactionCurrency) : '';
const hasPendingWaypoints = transaction?.pendingFields?.waypoints;
const showMapAsImage = isDistanceRequest && hasPendingWaypoints;
const formattedOriginalAmount = transactionOriginalAmount && transactionOriginalCurrency && CurrencyUtils.convertToDisplayString(transactionOriginalAmount, transactionOriginalCurrency);
const isCardTransaction = TransactionUtils.isCardTransaction(transaction);
const cardProgramName = isCardTransaction && transactionCardID !== undefined ? CardUtils.getCardDescription(transactionCardID) : '';
const isApproved = ReportUtils.isReportApproved(moneyRequestReport);
// Flags for allowing or disallowing editing a money request
const isSettled = ReportUtils.isSettled(moneyRequestReport?.reportID);
const isCancelled = moneyRequestReport && moneyRequestReport.isCancelledIOU;
// Used for non-restricted fields such as: description, category, tag, billable, etc.
const canEdit = ReportUtils.canEditMoneyRequest(parentReportAction);
const canEditAmount = ReportUtils.canEditFieldOfMoneyRequest(parentReportAction, CONST.EDIT_REQUEST_FIELD.AMOUNT);
const canEditMerchant = ReportUtils.canEditFieldOfMoneyRequest(parentReportAction, CONST.EDIT_REQUEST_FIELD.MERCHANT);
const canEditDate = ReportUtils.canEditFieldOfMoneyRequest(parentReportAction, CONST.EDIT_REQUEST_FIELD.DATE);
const canEditReceipt = ReportUtils.canEditFieldOfMoneyRequest(parentReportAction, CONST.EDIT_REQUEST_FIELD.RECEIPT);
const canEditDistance = ReportUtils.canEditFieldOfMoneyRequest(parentReportAction, CONST.EDIT_REQUEST_FIELD.DISTANCE);
// A flag for verifying that the current report is a sub-report of a workspace chat
// if the policy of the report is either Collect or Control, then this report must be tied to workspace chat
const isPolicyExpenseChat = ReportUtils.isGroupPolicy(report);
const policyTagLists = useMemo(() => PolicyUtils.getTagLists(policyTagList), [policyTagList]);
// Flags for showing categories and tags
// transactionCategory can be an empty string
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
const shouldShowCategory = isPolicyExpenseChat && (transactionCategory || OptionsListUtils.hasEnabledOptions(policyCategories ?? {}));
// transactionTag can be an empty string
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
const shouldShowTag = isPolicyExpenseChat && (transactionTag || OptionsListUtils.hasEnabledTags(policyTagLists));
const shouldShowBillable = isPolicyExpenseChat && (!!transactionBillable || !(policy?.disabledFields?.defaultBillable ?? true));
const {getViolationsForField} = useViolations(transactionViolations ?? []);
const hasViolations = useCallback((field: ViolationField): boolean => !!canUseViolations && getViolationsForField(field).length > 0, [canUseViolations, getViolationsForField]);
let amountDescription = `${translate('iou.amount')}`;
const saveBillable = useCallback(
(newBillable: boolean) => {
// If the value hasn't changed, don't request to save changes on the server and just close the modal
if (newBillable === TransactionUtils.getBillable(transaction)) {
Navigation.dismissModal();
return;
}
IOU.updateMoneyRequestBillable(transaction?.transactionID ?? '', report?.reportID, newBillable, policy, policyTagList, policyCategories);
Navigation.dismissModal();
},
[transaction, report, policy, policyTagList, policyCategories],
);
if (isCardTransaction) {
if (formattedOriginalAmount) {
amountDescription += ` • ${translate('iou.original')} ${formattedOriginalAmount}`;
}
if (TransactionUtils.isPending(transaction)) {
amountDescription += ` • ${translate('iou.pending')}`;
}
if (isCancelled) {
amountDescription += ` • ${translate('iou.canceled')}`;
}
} else {
if (!isDistanceRequest) {
amountDescription += ` • ${translate('iou.cash')}`;
}
if (isApproved) {
amountDescription += ` • ${translate('iou.approved')}`;
} else if (isCancelled) {
amountDescription += ` • ${translate('iou.canceled')}`;
} else if (isSettled) {
amountDescription += ` • ${translate('iou.settledExpensify')}`;
} else if (report.isWaitingOnBankAccount) {
amountDescription += ` • ${translate('iou.pending')}`;
}
}
const hasReceipt = TransactionUtils.hasReceipt(transaction);
let receiptURIs;
const hasErrors = canEdit && TransactionUtils.hasMissingSmartscanFields(transaction);
if (hasReceipt) {
receiptURIs = ReceiptUtils.getThumbnailAndImageURIs(transaction);
}
const pendingAction = transaction?.pendingAction;
const getPendingFieldAction = (fieldPath: TransactionPendingFieldsKey) => transaction?.pendingFields?.[fieldPath] ?? pendingAction;
const getErrorForField = useCallback(
(field: ViolationField, data?: OnyxTypes.TransactionViolation['data'], shouldShowViolations = true) => {
// Checks applied when creating a new money request
// NOTE: receipt field can return multiple violations, so we need to handle it separately
const fieldChecks: Partial<Record<ViolationField, {isError: boolean; translationPath: TranslationPaths}>> = {
amount: {
isError: transactionAmount === 0,
translationPath: 'common.error.enterAmount',
},
merchant: {
isError: !isSettled && !isCancelled && isPolicyExpenseChat && isEmptyMerchant,
translationPath: 'common.error.enterMerchant',
},
date: {
isError: transactionDate === '',
translationPath: 'common.error.enterDate',
},
};
const {isError, translationPath} = fieldChecks[field] ?? {};
// Return form errors if there are any
if (hasErrors && isError && translationPath) {
return translate(translationPath);
}
// Return violations if there are any
// At the moment, we only return violations for tags for workspaces with single-level tags
if (canUseViolations && shouldShowViolations && hasViolations(field)) {
const violations = getViolationsForField(field);
return ViolationsUtils.getViolationTranslation(violations[0], translate);
}
return '';
},
[transactionAmount, isSettled, isCancelled, isPolicyExpenseChat, isEmptyMerchant, transactionDate, hasErrors, canUseViolations, hasViolations, translate, getViolationsForField],
);
return (
<View style={[StyleUtils.getReportWelcomeContainerStyle(isSmallScreenWidth)]}>
<AnimatedEmptyStateBackground />
<View style={[StyleUtils.getReportWelcomeTopMarginStyle(isSmallScreenWidth)]}>
{/* eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing */}
{(showMapAsImage || hasReceipt) && (
<OfflineWithFeedback
pendingAction={pendingAction}
errors={transaction?.errors}
errorRowStyles={[styles.ml4]}
onClose={() => {
if (!transaction?.transactionID) {
return;
}
Transaction.clearError(transaction.transactionID);
}}
>
<View style={styles.moneyRequestViewImage}>
{showMapAsImage ? (
<ConfirmedRoute transaction={transaction} />
) : (
<ReportActionItemImage
thumbnail={receiptURIs?.thumbnail}
image={receiptURIs?.image}
isLocalFile={receiptURIs?.isLocalFile}
filename={receiptURIs?.filename}
transaction={transaction}
enablePreviewModal
canEditReceipt={canEditReceipt}
/>
)}
</View>
</OfflineWithFeedback>
)}
{!hasReceipt && canEditReceipt && (
<ReceiptEmptyState
hasError={hasErrors}
onPress={() =>
Navigation.navigate(
ROUTES.MONEY_REQUEST_STEP_SCAN.getRoute(
CONST.IOU.ACTION.EDIT,
CONST.IOU.TYPE.REQUEST,
transaction?.transactionID ?? '',
report.reportID,
Navigation.getActiveRouteWithoutParams(),
),
)
}
/>
)}
{canUseViolations && <ViolationMessages violations={getViolationsForField('receipt')} />}
<OfflineWithFeedback pendingAction={getPendingFieldAction('amount')}>
<MenuItemWithTopDescription
title={formattedTransactionAmount ? formattedTransactionAmount.toString() : ''}
shouldShowTitleIcon={isSettled}
titleIcon={Expensicons.Checkmark}
description={amountDescription}
titleStyle={styles.textHeadlineH2}
interactive={canEditAmount}
shouldShowRightIcon={canEditAmount}
onPress={() => Navigation.navigate(ROUTES.EDIT_REQUEST.getRoute(report.reportID, CONST.EDIT_REQUEST_FIELD.AMOUNT))}
brickRoadIndicator={getErrorForField('amount') ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined}
error={getErrorForField('amount')}
/>
</OfflineWithFeedback>
<OfflineWithFeedback pendingAction={getPendingFieldAction('comment')}>
<MenuItemWithTopDescription
description={translate('common.description')}
shouldParseTitle
title={transactionDescription}
interactive={canEdit}
shouldShowRightIcon={canEdit}
titleStyle={styles.flex1}
onPress={() =>
Navigation.navigate(
ROUTES.MONEY_REQUEST_STEP_DESCRIPTION.getRoute(CONST.IOU.ACTION.EDIT, CONST.IOU.TYPE.REQUEST, transaction?.transactionID ?? '', report.reportID),
)
}
wrapperStyle={[styles.pv2, styles.taskDescriptionMenuItem]}
brickRoadIndicator={getErrorForField('comment') ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined}
error={getErrorForField('comment')}
numberOfLinesTitle={0}
/>
</OfflineWithFeedback>
{isDistanceRequest ? (
<OfflineWithFeedback pendingAction={getPendingFieldAction('waypoints')}>
<MenuItemWithTopDescription
description={translate('common.distance')}
title={transactionMerchant}
interactive={canEditDistance}
shouldShowRightIcon={canEditDistance}
titleStyle={styles.flex1}
onPress={() => Navigation.navigate(ROUTES.EDIT_REQUEST.getRoute(report.reportID, CONST.EDIT_REQUEST_FIELD.DISTANCE))}
/>
</OfflineWithFeedback>
) : (
<OfflineWithFeedback pendingAction={getPendingFieldAction('merchant')}>
<MenuItemWithTopDescription
description={translate('common.merchant')}
title={isEmptyMerchant ? '' : transactionMerchant}
interactive={canEditMerchant}
shouldShowRightIcon={canEditMerchant}
titleStyle={styles.flex1}
onPress={() =>
Navigation.navigate(
ROUTES.MONEY_REQUEST_STEP_MERCHANT.getRoute(CONST.IOU.ACTION.EDIT, CONST.IOU.TYPE.REQUEST, transaction?.transactionID ?? '', report.reportID),
)
}
brickRoadIndicator={getErrorForField('merchant') ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined}
error={getErrorForField('merchant')}
/>
</OfflineWithFeedback>
)}
<OfflineWithFeedback pendingAction={getPendingFieldAction('created')}>
<MenuItemWithTopDescription
description={translate('common.date')}
title={transactionDate}
interactive={canEditDate}
shouldShowRightIcon={canEditDate}
titleStyle={styles.flex1}
onPress={() =>
Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_DATE.getRoute(CONST.IOU.ACTION.EDIT, CONST.IOU.TYPE.REQUEST, transaction?.transactionID ?? '', report.reportID))
}
brickRoadIndicator={getErrorForField('date') ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined}
error={getErrorForField('date')}
/>
</OfflineWithFeedback>
{shouldShowCategory && (
<OfflineWithFeedback pendingAction={getPendingFieldAction('category')}>
<MenuItemWithTopDescription
description={translate('common.category')}
title={transactionCategory}
interactive={canEdit}
shouldShowRightIcon={canEdit}
titleStyle={styles.flex1}
onPress={() =>
Navigation.navigate(
ROUTES.MONEY_REQUEST_STEP_CATEGORY.getRoute(CONST.IOU.ACTION.EDIT, CONST.IOU.TYPE.REQUEST, transaction?.transactionID ?? '', report.reportID),
)
}
brickRoadIndicator={getErrorForField('category') ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined}
error={getErrorForField('category')}
/>
</OfflineWithFeedback>
)}
{shouldShowTag &&
policyTagLists.map(({name}, index) => (
<OfflineWithFeedback
key={name}
pendingAction={getPendingFieldAction('tag')}
>
<MenuItemWithTopDescription
description={name ?? translate('common.tag')}
title={TransactionUtils.getTagForDisplay(transaction, index)}
interactive={canEdit}
shouldShowRightIcon={canEdit}
titleStyle={styles.flex1}
onPress={() =>
Navigation.navigate(
ROUTES.MONEY_REQUEST_STEP_TAG.getRoute(CONST.IOU.ACTION.EDIT, CONST.IOU.TYPE.REQUEST, index, transaction?.transactionID ?? '', report.reportID),
)
}
brickRoadIndicator={getErrorForField('tag', {}, policyTagLists.length === 1) ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined}
error={getErrorForField('tag', {}, policyTagLists.length === 1)}
/>
</OfflineWithFeedback>
))}
{isCardTransaction && (
<OfflineWithFeedback pendingAction={getPendingFieldAction('cardID')}>
<MenuItemWithTopDescription
description={translate('iou.card')}
title={cardProgramName}
titleStyle={styles.flex1}
/>
</OfflineWithFeedback>
)}
{shouldShowBillable && (
<View style={[styles.flexRow, styles.optionRow, styles.justifyContentBetween, styles.alignItemsCenter, styles.ml5, styles.mr8]}>
<View>
<Text color={!transactionBillable ? theme.textSupporting : undefined}>{translate('common.billable')}</Text>
{!!getErrorForField('billable') && (
<ViolationMessages
violations={getViolationsForField('billable')}
containerStyle={[styles.mt1]}
textStyle={[styles.ph0]}
isLast
/>
)}
</View>
<Switch
accessibilityLabel={translate('common.billable')}
isOn={!!transactionBillable}
onToggle={saveBillable}
/>
</View>
)}
</View>
<SpacerView
shouldShow={shouldShowHorizontalRule}
style={[shouldShowHorizontalRule ? styles.reportHorizontalRule : {}]}
/>
</View>
);
}
MoneyRequestView.displayName = 'MoneyRequestView';
export default withOnyx<MoneyRequestViewPropsWithoutTransaction, MoneyRequestViewOnyxPropsWithoutTransaction>({
policy: {
key: ({report}) => `${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`,
},
policyCategories: {
key: ({report}) => `${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}${report.policyID}`,
},
policyTagList: {
key: ({report}) => `${ONYXKEYS.COLLECTION.POLICY_TAGS}${report.policyID}`,
},
parentReport: {
key: ({report}) => `${ONYXKEYS.COLLECTION.REPORT}${report.parentReportID}`,
},
parentReportActions: {
key: ({report}) => `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report ? report.parentReportID : '0'}`,
canEvict: false,
},
})(
withOnyx<MoneyRequestViewProps, MoneyRequestViewTransactionOnyxProps>({
transaction: {
key: ({report, parentReportActions}) => {
const parentReportAction = parentReportActions?.[report.parentReportActionID ?? ''];
const originalMessage = parentReportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.IOU ? parentReportAction.originalMessage : undefined;
const transactionID = originalMessage?.IOUTransactionID ?? 0;
return `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`;
},
},
transactionViolations: {
key: ({report}) => {
const parentReportAction = ReportActionsUtils.getParentReportAction(report);
const originalMessage = parentReportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.IOU ? parentReportAction.originalMessage : undefined;
const transactionID = originalMessage?.IOUTransactionID ?? 0;
return `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`;
},
},
})(MoneyRequestView),
);