-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
MoneyRequestView.tsx
691 lines (639 loc) · 37.6 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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
import React, {useCallback, useMemo} from 'react';
import {View} from 'react-native';
import {useOnyx, withOnyx} from 'react-native-onyx';
import type {OnyxEntry} from 'react-native-onyx';
import * as Expensicons from '@components/Icon/Expensicons';
import MenuItem from '@components/MenuItem';
import MenuItemWithTopDescription from '@components/MenuItemWithTopDescription';
import OfflineWithFeedback from '@components/OfflineWithFeedback';
import {useSession} from '@components/OnyxProvider';
import ReceiptAudit, {ReceiptAuditMessages} from '@components/ReceiptAudit';
import ReceiptEmptyState from '@components/ReceiptEmptyState';
import Switch from '@components/Switch';
import Text from '@components/Text';
import ViolationMessages from '@components/ViolationMessages';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import usePermissions from '@hooks/usePermissions';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import useViolations from '@hooks/useViolations';
import type {ViolationField} from '@hooks/useViolations';
import * as CardUtils from '@libs/CardUtils';
import * as CurrencyUtils from '@libs/CurrencyUtils';
import type {MileageRate} from '@libs/DistanceRequestUtils';
import DistanceRequestUtils from '@libs/DistanceRequestUtils';
import * as ErrorUtils from '@libs/ErrorUtils';
import * as OptionsListUtils from '@libs/OptionsListUtils';
import * as PolicyUtils from '@libs/PolicyUtils';
import {isTaxTrackingEnabled} from '@libs/PolicyUtils';
import * as ReceiptUtils from '@libs/ReceiptUtils';
import * as ReportActionsUtils from '@libs/ReportActionsUtils';
import * as ReportUtils from '@libs/ReportUtils';
import type {TransactionDetails} 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 Link from '@userActions/Link';
import * as Transaction from '@userActions/Transaction';
import CONST from '@src/CONST';
import type {TranslationPaths} from '@src/languages/types';
import * as Report from '@src/libs/actions/Report';
import * as ReportActions from '@src/libs/actions/ReportActions';
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 = {
/** 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>;
/** The distance rates from the policy */
distanceRates: Record<string, MileageRate>;
};
type MoneyRequestViewPropsWithoutTransaction = MoneyRequestViewOnyxPropsWithoutTransaction & {
/** The report currently being looked at */
report: OnyxEntry<OnyxTypes.Report>;
/** Whether we should display the animated banner above the component */
shouldShowAnimatedBackground: boolean;
/** Whether we should show Money Request with disabled all fields */
readonly?: boolean;
/** Updated transaction to show in duplicate transaction flow */
updatedTransaction?: OnyxEntry<OnyxTypes.Transaction>;
};
type MoneyRequestViewProps = MoneyRequestViewTransactionOnyxProps & MoneyRequestViewPropsWithoutTransaction;
const deleteTransaction = (parentReport: OnyxEntry<OnyxTypes.Report>, parentReportAction: OnyxEntry<OnyxTypes.ReportAction>) => {
if (!parentReportAction) {
return;
}
const iouTransactionID = ReportActionsUtils.isMoneyRequestAction(parentReportAction) ? ReportActionsUtils.getOriginalMessage(parentReportAction)?.IOUTransactionID ?? '-1' : '-1';
if (ReportActionsUtils.isTrackExpenseAction(parentReportAction)) {
IOU.deleteTrackExpense(parentReport?.reportID ?? '-1', iouTransactionID, parentReportAction, true);
return;
}
IOU.deleteMoneyRequest(iouTransactionID, parentReportAction, true);
};
function MoneyRequestView({
report,
parentReport,
parentReportActions,
policyCategories,
policyTagList,
policy,
transactionViolations,
shouldShowAnimatedBackground,
distanceRates,
readonly = false,
updatedTransaction,
}: MoneyRequestViewProps) {
const theme = useTheme();
const styles = useThemeStyles();
const session = useSession();
const {isOffline} = useNetwork();
const {translate, toLocaleDigit} = useLocalize();
const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID);
const [chatReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${parentReport?.parentReportID}`, {
selector: (chatReportValue) => chatReportValue && {reportID: chatReportValue.reportID, errorFields: chatReportValue.errorFields},
});
const parentReportAction = parentReportActions?.[report?.parentReportActionID ?? '-1'];
const isTrackExpense = ReportUtils.isTrackExpenseReport(report);
const {canUseViolations, canUseP2PDistanceRequests} = usePermissions(isTrackExpense ? CONST.IOU.TYPE.TRACK : undefined);
const moneyRequestReport = parentReport;
const linkedTransactionID = useMemo(() => {
const originalMessage = parentReportAction && ReportActionsUtils.isMoneyRequestAction(parentReportAction) ? ReportActionsUtils.getOriginalMessage(parentReportAction) : undefined;
return originalMessage?.IOUTransactionID ?? '-1';
}, [parentReportAction]);
const [transaction] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION}${linkedTransactionID}`);
const {
created: transactionDate,
amount: transactionAmount,
taxAmount: transactionTaxAmount,
currency: transactionCurrency,
comment: transactionDescription,
merchant: transactionMerchant,
billable: transactionBillable,
category: transactionCategory,
tag: transactionTag,
originalAmount: transactionOriginalAmount,
originalCurrency: transactionOriginalCurrency,
cardID: transactionCardID,
} = useMemo<Partial<TransactionDetails>>(() => ReportUtils.getTransactionDetails(transaction) ?? {}, [transaction]);
const isEmptyMerchant = transactionMerchant === '' || transactionMerchant === CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT;
const isDistanceRequest = TransactionUtils.isDistanceRequest(transaction);
const formattedTransactionAmount = transactionAmount ? CurrencyUtils.convertToDisplayString(transactionAmount, transactionCurrency) : '';
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);
const isInvoice = ReportUtils.isInvoiceReport(moneyRequestReport);
const isPaidReport = ReportActionsUtils.isPayAction(parentReportAction);
const taxRates = policy?.taxRates;
const formattedTaxAmount = updatedTransaction?.taxAmount
? CurrencyUtils.convertToDisplayString(updatedTransaction?.taxAmount, transactionCurrency)
: CurrencyUtils.convertToDisplayString(transactionTaxAmount, transactionCurrency);
const taxRatesDescription = taxRates?.name;
const taxRateTitle = updatedTransaction ? TransactionUtils.getTaxName(policy, updatedTransaction) : TransactionUtils.getTaxName(policy, transaction);
const isSettled = ReportUtils.isSettled(moneyRequestReport?.reportID);
const isCancelled = moneyRequestReport && moneyRequestReport?.isCancelledIOU;
// Flags for allowing or disallowing editing an expense
// Used for non-restricted fields such as: description, category, tag, billable, etc...
const canUserPerformWriteAction = !!ReportUtils.canUserPerformWriteAction(report);
const canEdit = ReportActionsUtils.isMoneyRequestAction(parentReportAction) && ReportUtils.canEditMoneyRequest(parentReportAction, transaction) && canUserPerformWriteAction;
const canEditTaxFields = canEdit && !isDistanceRequest;
const canEditAmount = canUserPerformWriteAction && ReportUtils.canEditFieldOfMoneyRequest(parentReportAction, CONST.EDIT_REQUEST_FIELD.AMOUNT);
const canEditMerchant = canUserPerformWriteAction && ReportUtils.canEditFieldOfMoneyRequest(parentReportAction, CONST.EDIT_REQUEST_FIELD.MERCHANT);
const canEditDate = canUserPerformWriteAction && ReportUtils.canEditFieldOfMoneyRequest(parentReportAction, CONST.EDIT_REQUEST_FIELD.DATE);
const canEditReceipt = canUserPerformWriteAction && ReportUtils.canEditFieldOfMoneyRequest(parentReportAction, CONST.EDIT_REQUEST_FIELD.RECEIPT);
const hasReceipt = TransactionUtils.hasReceipt(transaction);
const isReceiptBeingScanned = hasReceipt && TransactionUtils.isReceiptBeingScanned(transaction);
const didReceiptScanSucceed = hasReceipt && TransactionUtils.didReceiptScanSucceed(transaction);
const canEditDistance = canUserPerformWriteAction && ReportUtils.canEditFieldOfMoneyRequest(parentReportAction, CONST.EDIT_REQUEST_FIELD.DISTANCE);
const isAdmin = policy?.role === 'admin';
const isApprover = ReportUtils.isMoneyRequestReport(moneyRequestReport) && moneyRequestReport?.managerID !== null && session?.accountID === moneyRequestReport?.managerID;
// 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.isReportInGroupPolicy(report);
const policyTagLists = useMemo(() => PolicyUtils.getTagLists(policyTagList), [policyTagList]);
const iouType = isTrackExpense ? CONST.IOU.TYPE.TRACK : CONST.IOU.TYPE.SUBMIT;
// 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) || !!updatedTransaction?.billable);
const shouldShowTax = isTaxTrackingEnabled(isPolicyExpenseChat, policy, isDistanceRequest);
const tripID = ReportUtils.getTripIDFromTransactionParentReport(parentReport);
const shouldShowViewTripDetails = TransactionUtils.hasReservationList(transaction) && !!tripID;
const {getViolationsForField} = useViolations(transactionViolations ?? [], isReceiptBeingScanned || !ReportUtils.isPaidGroupPolicy(report));
const hasViolations = useCallback(
(field: ViolationField, data?: OnyxTypes.TransactionViolation['data'], policyHasDependentTags = false, tagValue?: string): boolean =>
!!canUseViolations && getViolationsForField(field, data, policyHasDependentTags, tagValue).length > 0,
[canUseViolations, getViolationsForField],
);
let amountDescription = `${translate('iou.amount')}`;
const hasRoute = TransactionUtils.hasRoute(transaction, isDistanceRequest);
const rateID = transaction?.comment?.customUnit?.customUnitRateID ?? '-1';
const currency = policy ? policy.outputCurrency : PolicyUtils.getPersonalPolicy()?.outputCurrency ?? CONST.CURRENCY.USD;
const mileageRate = TransactionUtils.isCustomUnitRateIDForP2P(transaction) ? DistanceRequestUtils.getRateForP2P(currency) : distanceRates[rateID] ?? {};
const {unit} = mileageRate;
const rate = transaction?.comment?.customUnit?.defaultP2PRate ?? mileageRate.rate;
const distance = DistanceRequestUtils.convertToDistanceInMeters(TransactionUtils.getDistance(transaction), unit);
const rateToDisplay = DistanceRequestUtils.getRateForDisplay(unit, rate, currency, translate, toLocaleDigit, isOffline);
const distanceToDisplay = DistanceRequestUtils.getDistanceForDisplay(hasRoute, distance, unit, rate, translate);
let merchantTitle = isEmptyMerchant ? '' : transactionMerchant;
let amountTitle = formattedTransactionAmount ? formattedTransactionAmount.toString() : '';
if (TransactionUtils.hasReceipt(transaction) && TransactionUtils.isReceiptBeingScanned(transaction)) {
merchantTitle = translate('iou.receiptStatusTitle');
amountTitle = translate('iou.receiptStatusTitle');
}
const updatedTransactionDescription = useMemo(() => {
if (!updatedTransaction) {
return undefined;
}
return TransactionUtils.getDescription(updatedTransaction ?? null);
}, [updatedTransaction]);
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)) {
return;
}
IOU.updateMoneyRequestBillable(transaction?.transactionID ?? '-1', report?.reportID ?? '-1', newBillable, policy, policyTagList, policyCategories);
},
[transaction, report, policy, policyTagList, policyCategories],
);
if (isCardTransaction) {
if (formattedOriginalAmount) {
amountDescription += ` ${CONST.DOT_SEPARATOR} ${translate('iou.original')} ${formattedOriginalAmount}`;
}
if (isCancelled) {
amountDescription += ` ${CONST.DOT_SEPARATOR} ${translate('iou.canceled')}`;
}
} else {
if (!isDistanceRequest) {
amountDescription += ` ${CONST.DOT_SEPARATOR} ${translate('iou.cash')}`;
}
if (isApproved) {
amountDescription += ` ${CONST.DOT_SEPARATOR} ${translate('iou.approved')}`;
} else if (isCancelled) {
amountDescription += ` ${CONST.DOT_SEPARATOR} ${translate('iou.canceled')}`;
} else if (isSettled) {
amountDescription += ` • ${translate('iou.settledExpensify')}`;
}
}
let receiptURIs;
const hasErrors = 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'], policyHasDependentTags = false, tagValue?: string) => {
// Checks applied when creating a new expense
// 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] ?? {};
if (readonly) {
return '';
}
// Return form errors if there are any
if (hasErrors && isError && translationPath) {
return translate(translationPath);
}
// Return violations if there are any
if (hasViolations(field, data, policyHasDependentTags, tagValue)) {
const violations = getViolationsForField(field, data, policyHasDependentTags, tagValue);
return ViolationsUtils.getViolationTranslation(violations[0], translate);
}
return '';
},
[transactionAmount, isSettled, isCancelled, isPolicyExpenseChat, isEmptyMerchant, transactionDate, readonly, hasErrors, hasViolations, translate, getViolationsForField],
);
const distanceRequestFields = canUseP2PDistanceRequests ? (
<>
<OfflineWithFeedback pendingAction={getPendingFieldAction('waypoints')}>
<MenuItemWithTopDescription
description={translate('common.distance')}
title={getPendingFieldAction('waypoints') ? translate('iou.fieldPending') : distanceToDisplay}
interactive={canEditDistance && !readonly}
shouldShowRightIcon={canEditDistance && !readonly}
titleStyle={styles.flex1}
onPress={() =>
Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_DISTANCE.getRoute(CONST.IOU.ACTION.EDIT, iouType, transaction?.transactionID ?? '-1', report?.reportID ?? '-1'))
}
/>
</OfflineWithFeedback>
{/* TODO: correct the pending field action https://github.com/Expensify/App/issues/36987 */}
<OfflineWithFeedback pendingAction={getPendingFieldAction('waypoints')}>
<MenuItemWithTopDescription
description={translate('common.rate')}
title={rateToDisplay}
// TODO: https://github.com/Expensify/App/issues/36987 make it interactive and show right icon when EditRatePage is ready
interactive={false}
shouldShowRightIcon={false}
titleStyle={styles.flex1}
// TODO: https://github.com/Expensify/App/issues/36987 Add route for editing rate
onPress={() => {}}
/>
</OfflineWithFeedback>
</>
) : (
<OfflineWithFeedback pendingAction={getPendingFieldAction('waypoints')}>
<MenuItemWithTopDescription
description={translate('common.distance')}
title={transactionMerchant}
interactive={canEditDistance && !readonly}
shouldShowRightIcon={canEditDistance && !readonly}
titleStyle={styles.flex1}
onPress={() => Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_DISTANCE.getRoute(CONST.IOU.ACTION.EDIT, iouType, transaction?.transactionID ?? '-1', report?.reportID ?? '-1'))}
/>
</OfflineWithFeedback>
);
const isReceiptAllowed = !isPaidReport && !isInvoice;
const shouldShowReceiptEmptyState =
isReceiptAllowed && !hasReceipt && !isApproved && !isSettled && (canEditReceipt || isAdmin || isApprover) && (canEditReceipt || ReportUtils.isPaidGroupPolicy(report));
const receiptViolationNames: OnyxTypes.ViolationName[] = [
CONST.VIOLATIONS.RECEIPT_REQUIRED,
CONST.VIOLATIONS.RECEIPT_NOT_SMART_SCANNED,
CONST.VIOLATIONS.CASH_EXPENSE_WITH_NO_RECEIPT,
CONST.VIOLATIONS.SMARTSCAN_FAILED,
];
const receiptViolations =
transactionViolations?.filter((violation) => receiptViolationNames.includes(violation.name)).map((violation) => ViolationsUtils.getViolationTranslation(violation, translate)) ?? [];
// Whether to show receipt audit result (e.g.`Verified`, `Issue Found`) and messages (e.g. `Receipt not verified. Please confirm accuracy.`)
// `!!(receiptViolations.length || didReceiptScanSucceed)` is for not showing `Verified` when `receiptViolations` is empty and `didReceiptScanSucceed` is false.
const shouldShowAuditMessage =
!isReceiptBeingScanned && hasReceipt && !!(receiptViolations.length || didReceiptScanSucceed) && !!canUseViolations && ReportUtils.isPaidGroupPolicy(report);
const shouldShowReceiptAudit = isReceiptAllowed && (shouldShowReceiptEmptyState || hasReceipt);
const errors = {
...(transaction?.errorFields?.route ?? transaction?.errors),
...parentReportAction?.errors,
};
const tagList = policyTagLists.map(({name, orderWeight}, index) => {
const tagError = getErrorForField(
'tag',
{
tagListIndex: index,
tagListName: name,
},
PolicyUtils.hasDependentTags(policy, policyTagList),
TransactionUtils.getTagForDisplay(updatedTransaction ?? transaction, index),
);
return (
<OfflineWithFeedback
key={name}
pendingAction={getPendingFieldAction('tag')}
>
<MenuItemWithTopDescription
description={name ?? translate('common.tag')}
title={TransactionUtils.getTagForDisplay(updatedTransaction ?? transaction, index)}
interactive={canEdit && !readonly}
shouldShowRightIcon={canEdit && !readonly}
titleStyle={styles.flex1}
onPress={() =>
Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_TAG.getRoute(CONST.IOU.ACTION.EDIT, iouType, orderWeight, transaction?.transactionID ?? '', report?.reportID ?? '-1'))
}
brickRoadIndicator={tagError ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined}
errorText={tagError}
/>
</OfflineWithFeedback>
);
});
return (
<View style={styles.pRelative}>
{shouldShowAnimatedBackground && <AnimatedEmptyStateBackground />}
<>
{shouldShowReceiptAudit && (
<ReceiptAudit
notes={receiptViolations}
shouldShowAuditResult={shouldShowAuditMessage}
/>
)}
{(hasReceipt || errors) && (
<OfflineWithFeedback
pendingAction={pendingAction}
errors={errors}
errorRowStyles={[styles.mh4]}
onClose={() => {
if (!transaction?.transactionID && linkedTransactionID === '-1') {
return;
}
const isCreateChatErrored = !!report?.errorFields?.createChat;
if ((isCreateChatErrored || !!report?.isOptimisticReport) && parentReportAction) {
const urlToNavigateBack = IOU.cleanUpMoneyRequest(transaction?.transactionID ?? linkedTransactionID, parentReportAction, true);
Navigation.goBack(urlToNavigateBack);
return;
}
if (transaction?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD) {
if (chatReport?.reportID && ReportUtils.getAddWorkspaceRoomOrChatReportErrors(chatReport)) {
Report.navigateToConciergeChatAndDeleteReport(chatReport.reportID, true, true);
return;
}
if (Object.values(transaction?.errors ?? {})?.find((error) => ErrorUtils.isReceiptError(error))) {
deleteTransaction(parentReport, parentReportAction);
}
}
Transaction.clearError(transaction?.transactionID ?? linkedTransactionID);
ReportActions.clearAllRelatedReportActionErrors(report?.reportID ?? '-1', parentReportAction);
}}
>
{hasReceipt && (
<View style={styles.moneyRequestViewImage}>
<ReportActionItemImage
thumbnail={receiptURIs?.thumbnail}
fileExtension={receiptURIs?.fileExtension}
isThumbnail={receiptURIs?.isThumbnail}
image={receiptURIs?.image}
isLocalFile={receiptURIs?.isLocalFile}
filename={receiptURIs?.filename}
transaction={transaction}
enablePreviewModal
/>
</View>
)}
</OfflineWithFeedback>
)}
{shouldShowReceiptEmptyState && (
<ReceiptEmptyState
hasError={hasErrors}
disabled={!canEditReceipt || readonly}
onPress={() =>
Navigation.navigate(
ROUTES.MONEY_REQUEST_STEP_SCAN.getRoute(
CONST.IOU.ACTION.EDIT,
iouType,
transaction?.transactionID ?? '-1',
report?.reportID ?? '-1',
Navigation.getActiveRouteWithoutParams(),
),
)
}
/>
)}
{!shouldShowReceiptEmptyState && !hasReceipt && <View style={{marginVertical: 6}} />}
{shouldShowAuditMessage && <ReceiptAuditMessages notes={receiptViolations} />}
<OfflineWithFeedback pendingAction={getPendingFieldAction('amount')}>
<MenuItemWithTopDescription
title={amountTitle}
shouldShowTitleIcon={isSettled}
titleIcon={Expensicons.Checkmark}
description={amountDescription}
titleStyle={styles.textHeadlineH2}
interactive={canEditAmount && !readonly}
shouldShowRightIcon={canEditAmount && !readonly}
onPress={() =>
Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_AMOUNT.getRoute(CONST.IOU.ACTION.EDIT, iouType, transaction?.transactionID ?? '-1', report?.reportID ?? '-1'))
}
brickRoadIndicator={getErrorForField('amount') ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined}
errorText={getErrorForField('amount')}
/>
</OfflineWithFeedback>
<OfflineWithFeedback pendingAction={getPendingFieldAction('comment')}>
<MenuItemWithTopDescription
description={translate('common.description')}
shouldParseTitle
title={updatedTransactionDescription ?? transactionDescription}
interactive={canEdit && !readonly}
shouldShowRightIcon={canEdit && !readonly}
titleStyle={styles.flex1}
onPress={() =>
Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_DESCRIPTION.getRoute(CONST.IOU.ACTION.EDIT, iouType, transaction?.transactionID ?? '-1', report?.reportID ?? '-1'))
}
wrapperStyle={[styles.pv2, styles.taskDescriptionMenuItem]}
brickRoadIndicator={getErrorForField('comment') ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined}
errorText={getErrorForField('comment')}
numberOfLinesTitle={0}
/>
</OfflineWithFeedback>
{isDistanceRequest ? (
distanceRequestFields
) : (
<OfflineWithFeedback pendingAction={getPendingFieldAction('merchant')}>
<MenuItemWithTopDescription
description={translate('common.merchant')}
title={updatedTransaction?.modifiedMerchant ?? merchantTitle}
interactive={canEditMerchant && !readonly}
shouldShowRightIcon={canEditMerchant && !readonly}
titleStyle={styles.flex1}
onPress={() =>
Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_MERCHANT.getRoute(CONST.IOU.ACTION.EDIT, iouType, transaction?.transactionID ?? '-1', report?.reportID ?? '-1'))
}
wrapperStyle={[styles.taskDescriptionMenuItem]}
brickRoadIndicator={getErrorForField('merchant') ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined}
errorText={getErrorForField('merchant')}
numberOfLinesTitle={0}
/>
</OfflineWithFeedback>
)}
<OfflineWithFeedback pendingAction={getPendingFieldAction('created')}>
<MenuItemWithTopDescription
description={translate('common.date')}
title={transactionDate}
interactive={canEditDate && !readonly}
shouldShowRightIcon={canEditDate && !readonly}
titleStyle={styles.flex1}
onPress={() =>
Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_DATE.getRoute(CONST.IOU.ACTION.EDIT, iouType, transaction?.transactionID ?? '-1', report?.reportID ?? '-1' ?? '-1'))
}
brickRoadIndicator={getErrorForField('date') ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined}
errorText={getErrorForField('date')}
/>
</OfflineWithFeedback>
{shouldShowCategory && (
<OfflineWithFeedback pendingAction={getPendingFieldAction('category')}>
<MenuItemWithTopDescription
description={translate('common.category')}
title={updatedTransaction?.category ?? transactionCategory}
interactive={canEdit && !readonly}
shouldShowRightIcon={canEdit && !readonly}
titleStyle={styles.flex1}
onPress={() =>
Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_CATEGORY.getRoute(CONST.IOU.ACTION.EDIT, iouType, transaction?.transactionID ?? '-1', report?.reportID ?? '-1'))
}
brickRoadIndicator={getErrorForField('category') ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined}
errorText={getErrorForField('category')}
/>
</OfflineWithFeedback>
)}
{shouldShowTag && tagList}
{isCardTransaction && (
<OfflineWithFeedback pendingAction={getPendingFieldAction('cardID')}>
<MenuItemWithTopDescription
description={translate('iou.card')}
title={cardProgramName}
titleStyle={styles.flex1}
interactive={false}
/>
</OfflineWithFeedback>
)}
{shouldShowTax && (
<OfflineWithFeedback pendingAction={getPendingFieldAction('taxCode')}>
<MenuItemWithTopDescription
title={taxRateTitle ?? ''}
description={taxRatesDescription}
interactive={canEditTaxFields && !readonly}
shouldShowRightIcon={canEditTaxFields && !readonly}
titleStyle={styles.flex1}
onPress={() =>
Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_TAX_RATE.getRoute(CONST.IOU.ACTION.EDIT, iouType, transaction?.transactionID ?? '-1', report?.reportID ?? '-1'))
}
brickRoadIndicator={getErrorForField('tax') ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined}
errorText={getErrorForField('tax')}
/>
</OfflineWithFeedback>
)}
{shouldShowTax && (
<OfflineWithFeedback pendingAction={getPendingFieldAction('taxAmount')}>
<MenuItemWithTopDescription
title={formattedTaxAmount ? formattedTaxAmount.toString() : ''}
description={translate('iou.taxAmount')}
interactive={canEditTaxFields && !readonly}
shouldShowRightIcon={canEditTaxFields && !readonly}
titleStyle={styles.flex1}
onPress={() =>
Navigation.navigate(
ROUTES.MONEY_REQUEST_STEP_TAX_AMOUNT.getRoute(CONST.IOU.ACTION.EDIT, iouType, transaction?.transactionID ?? '-1', report?.reportID ?? '-1'),
)
}
/>
</OfflineWithFeedback>
)}
{shouldShowViewTripDetails && (
<MenuItem
title={translate('travel.viewTripDetails')}
icon={Expensicons.Suitcase}
iconRight={Expensicons.NewWindow}
shouldShowRightIcon
onPress={() => Link.openTravelDotLink(activePolicyID, CONST.TRIP_ID_PATH(tripID))}
/>
)}
{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={updatedTransaction?.billable ?? !!transactionBillable}
onToggle={saveBillable}
disabled={!canEdit || readonly}
/>
</View>
)}
</>
</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 : '-1'}`,
canEvict: false,
},
distanceRates: {
key: ({report}) => `${ONYXKEYS.COLLECTION.POLICY}${report?.policyID}`,
selector: (policy: OnyxEntry<OnyxTypes.Policy>) => DistanceRequestUtils.getMileageRates(policy, true),
},
})(
withOnyx<MoneyRequestViewProps, MoneyRequestViewTransactionOnyxProps>({
transactionViolations: {
key: ({report, parentReportActions}) => {
const parentReportAction = parentReportActions?.[report?.parentReportActionID ?? '-1'];
const originalMessage =
parentReportAction && ReportActionsUtils.isMoneyRequestAction(parentReportAction) ? ReportActionsUtils.getOriginalMessage(parentReportAction) : undefined;
const transactionID = originalMessage?.IOUTransactionID ?? -1;
return `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`;
},
},
})(MoneyRequestView),
);