-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
MoneyRequestConfirmationList.tsx
executable file
·989 lines (869 loc) · 40.6 KB
/
MoneyRequestConfirmationList.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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
import {useFocusEffect, useIsFocused} from '@react-navigation/native';
import lodashIsEqual from 'lodash/isEqual';
import React, {memo, useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {InteractionManager, View} from 'react-native';
import {withOnyx} from 'react-native-onyx';
import type {OnyxEntry} from 'react-native-onyx';
import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails';
import useDebouncedState from '@hooks/useDebouncedState';
import useLocalize from '@hooks/useLocalize';
import {MouseProvider} from '@hooks/useMouseContext';
import usePermissions from '@hooks/usePermissions';
import usePrevious from '@hooks/usePrevious';
import useThemeStyles from '@hooks/useThemeStyles';
import blurActiveElement from '@libs/Accessibility/blurActiveElement';
import * as CurrencyUtils from '@libs/CurrencyUtils';
import DistanceRequestUtils from '@libs/DistanceRequestUtils';
import type {MileageRate} from '@libs/DistanceRequestUtils';
import * as IOUUtils from '@libs/IOUUtils';
import Log from '@libs/Log';
import * as MoneyRequestUtils from '@libs/MoneyRequestUtils';
import Navigation from '@libs/Navigation/Navigation';
import * as OptionsListUtils from '@libs/OptionsListUtils';
import * as PolicyUtils from '@libs/PolicyUtils';
import {getCustomUnitRate, isTaxTrackingEnabled} from '@libs/PolicyUtils';
import * as ReportUtils from '@libs/ReportUtils';
import playSound, {SOUNDS} from '@libs/Sound';
import * as TransactionUtils from '@libs/TransactionUtils';
import * as IOU from '@userActions/IOU';
import {hasInvoicingDetails} from '@userActions/Policy/Policy';
import type {IOUAction, IOUType} from '@src/CONST';
import CONST from '@src/CONST';
import type {TranslationPaths} from '@src/languages/types';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {Route} from '@src/ROUTES';
import type * as OnyxTypes from '@src/types/onyx';
import type {Participant} from '@src/types/onyx/IOU';
import type {PaymentMethodType} from '@src/types/onyx/OriginalMessage';
import type {SplitShares} from '@src/types/onyx/Transaction';
import ButtonWithDropdownMenu from './ButtonWithDropdownMenu';
import type {DropdownOption} from './ButtonWithDropdownMenu/types';
import FormHelpMessage from './FormHelpMessage';
import MoneyRequestAmountInput from './MoneyRequestAmountInput';
import MoneyRequestConfirmationListFooter from './MoneyRequestConfirmationListFooter';
import {PressableWithFeedback} from './Pressable';
import SelectionList from './SelectionList';
import type {SectionListDataType} from './SelectionList/types';
import UserListItem from './SelectionList/UserListItem';
import SettlementButton from './SettlementButton';
import Text from './Text';
type MoneyRequestConfirmationListOnyxProps = {
/** Collection of categories attached to a policy */
policyCategories: OnyxEntry<OnyxTypes.PolicyCategories>;
/** Collection of draft categories attached to a policy */
policyCategoriesDraft: OnyxEntry<OnyxTypes.PolicyCategories>;
/** Collection of tags attached to a policy */
policyTags: OnyxEntry<OnyxTypes.PolicyTagList>;
/** The policy of the report */
policy: OnyxEntry<OnyxTypes.Policy>;
/** The draft policy of the report */
policyDraft: OnyxEntry<OnyxTypes.Policy>;
/** Unit and rate used for if the expense is a distance expense */
mileageRates: OnyxEntry<Record<string, MileageRate>>;
/** Mileage rate default for the policy */
defaultMileageRate: OnyxEntry<MileageRate>;
/** Last selected distance rates */
lastSelectedDistanceRates: OnyxEntry<Record<string, string>>;
/** List of currencies */
currencyList: OnyxEntry<OnyxTypes.CurrencyList>;
};
type MoneyRequestConfirmationListProps = MoneyRequestConfirmationListOnyxProps & {
/** Callback to inform parent modal of success */
onConfirm?: (selectedParticipants: Participant[]) => void;
/** Callback to parent modal to pay someone */
onSendMoney?: (paymentMethod: PaymentMethodType | undefined) => void;
/** IOU amount */
iouAmount: number;
/** IOU comment */
iouComment?: string;
/** IOU currency */
iouCurrencyCode?: string;
/** IOU type */
iouType?: Exclude<IOUType, typeof CONST.IOU.TYPE.REQUEST | typeof CONST.IOU.TYPE.SEND>;
/** IOU date */
iouCreated?: string;
/** IOU merchant */
iouMerchant?: string;
/** IOU Category */
iouCategory?: string;
/** IOU isBillable */
iouIsBillable?: boolean;
/** Callback to toggle the billable state */
onToggleBillable?: (isOn: boolean) => void;
/** Selected participants from MoneyRequestModal with login / accountID */
selectedParticipants: Participant[];
/** Payee of the expense with login */
payeePersonalDetails?: OnyxEntry<OnyxTypes.PersonalDetails> | null;
/** Should the list be read only, and not editable? */
isReadOnly?: boolean;
/** Depending on expense report or personal IOU report, respective bank account route */
bankAccountRoute?: Route;
/** The policyID of the request */
policyID?: string;
/** The reportID of the request */
reportID?: string;
/** File path of the receipt */
receiptPath?: string;
/** File name of the receipt */
receiptFilename?: string;
/** Transaction that represents the expense */
transaction?: OnyxEntry<OnyxTypes.Transaction>;
/** Whether the expense is a distance expense */
isDistanceRequest?: boolean;
/** Whether we're editing a split expense */
isEditingSplitBill?: boolean;
/** Whether we can navigate to receipt page */
shouldDisplayReceipt?: boolean;
/** Whether we should show the amount, date, and merchant fields. */
shouldShowSmartScanFields?: boolean;
/** A flag for verifying that the current report is a sub-report of a workspace chat */
isPolicyExpenseChat?: boolean;
/** Whether smart scan failed */
hasSmartScanFailed?: boolean;
/** The ID of the report action */
reportActionID?: string;
/** The action to take */
action?: IOUAction;
/** Should play sound on confirmation */
shouldPlaySound?: boolean;
};
type MoneyRequestConfirmationListItem = Participant | ReportUtils.OptionData;
function MoneyRequestConfirmationList({
transaction,
onSendMoney,
onConfirm,
iouType = CONST.IOU.TYPE.SUBMIT,
iouAmount,
policyCategories: policyCategoriesReal,
policyCategoriesDraft,
mileageRates,
isDistanceRequest = false,
policy: policyReal,
policyDraft,
isPolicyExpenseChat = false,
iouCategory = '',
shouldShowSmartScanFields = true,
isEditingSplitBill,
policyTags,
iouCurrencyCode,
iouMerchant,
selectedParticipants: selectedParticipantsProp,
payeePersonalDetails: payeePersonalDetailsProp,
isReadOnly = false,
bankAccountRoute = '',
policyID = '',
reportID = '',
receiptPath = '',
iouComment,
receiptFilename = '',
iouCreated,
iouIsBillable = false,
onToggleBillable,
hasSmartScanFailed,
reportActionID,
defaultMileageRate,
lastSelectedDistanceRates,
action = CONST.IOU.ACTION.CREATE,
currencyList,
shouldDisplayReceipt = false,
shouldPlaySound = true,
}: MoneyRequestConfirmationListProps) {
const policy = policyReal ?? policyDraft;
const policyCategories = policyCategoriesReal ?? policyCategoriesDraft;
const styles = useThemeStyles();
const {translate, toLocaleDigit} = useLocalize();
const currentUserPersonalDetails = useCurrentUserPersonalDetails();
const {canUseP2PDistanceRequests} = usePermissions(iouType);
const isTypeRequest = iouType === CONST.IOU.TYPE.SUBMIT;
const isTypeSplit = iouType === CONST.IOU.TYPE.SPLIT;
const isTypeSend = iouType === CONST.IOU.TYPE.PAY;
const isTypeTrackExpense = iouType === CONST.IOU.TYPE.TRACK;
const isTypeInvoice = iouType === CONST.IOU.TYPE.INVOICE;
const isScanRequest = useMemo(() => TransactionUtils.isScanRequest(transaction), [transaction]);
const transactionID = transaction?.transactionID ?? '-1';
const customUnitRateID = TransactionUtils.getRateID(transaction) ?? '-1';
useEffect(() => {
if (customUnitRateID || !canUseP2PDistanceRequests) {
return;
}
if (!customUnitRateID) {
const rateID = lastSelectedDistanceRates?.[policy?.id ?? ''] ?? defaultMileageRate?.customUnitRateID ?? '';
IOU.setCustomUnitRateID(transactionID, rateID);
}
}, [defaultMileageRate, customUnitRateID, lastSelectedDistanceRates, policy?.id, canUseP2PDistanceRequests, transactionID]);
const policyCurrency = policy?.outputCurrency ?? PolicyUtils.getPersonalPolicy()?.outputCurrency ?? CONST.CURRENCY.USD;
const mileageRate = TransactionUtils.isCustomUnitRateIDForP2P(transaction) ? DistanceRequestUtils.getRateForP2P(policyCurrency) : mileageRates?.[customUnitRateID] ?? defaultMileageRate;
const {unit, rate} = mileageRate ?? {};
const prevRate = usePrevious(rate);
const currency = (mileageRate as MileageRate)?.currency ?? policyCurrency;
// A flag for showing the categories field
const shouldShowCategories = isPolicyExpenseChat && (!!iouCategory || OptionsListUtils.hasEnabledOptions(Object.values(policyCategories ?? {})));
const shouldShowMerchant = shouldShowSmartScanFields && !isDistanceRequest && !isTypeSend;
const policyTagLists = useMemo(() => PolicyUtils.getTagLists(policyTags), [policyTags]);
const shouldShowTax = isTaxTrackingEnabled(isPolicyExpenseChat, policy, isDistanceRequest) && !isTypeInvoice;
const isMovingTransactionFromTrackExpense = IOUUtils.isMovingTransactionFromTrackExpense(action);
const distance = TransactionUtils.getDistanceInMeters(transaction, unit);
const prevDistance = usePrevious(distance);
const shouldCalculateDistanceAmount = isDistanceRequest && (iouAmount === 0 || prevRate !== rate || prevDistance !== distance);
const hasRoute = TransactionUtils.hasRoute(transaction, isDistanceRequest);
const isDistanceRequestWithPendingRoute = isDistanceRequest && (!hasRoute || !rate) && !isMovingTransactionFromTrackExpense;
const distanceRequestAmount = DistanceRequestUtils.getDistanceRequestAmount(distance, unit ?? CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES, rate ?? 0);
const formattedAmount = isDistanceRequestWithPendingRoute
? ''
: CurrencyUtils.convertToDisplayString(shouldCalculateDistanceAmount ? distanceRequestAmount : iouAmount, isDistanceRequest ? currency : iouCurrencyCode);
const previousTransactionAmount = usePrevious(transaction?.amount);
const previousTransactionCurrency = usePrevious(transaction?.currency);
const isFocused = useIsFocused();
const [formError, debouncedFormError, setFormError] = useDebouncedState<TranslationPaths | ''>('');
const [didConfirm, setDidConfirm] = useState(false);
const [didConfirmSplit, setDidConfirmSplit] = useState(false);
const shouldDisplayFieldError: boolean = useMemo(() => {
if (!isEditingSplitBill) {
return false;
}
return (!!hasSmartScanFailed && TransactionUtils.hasMissingSmartscanFields(transaction)) || (didConfirmSplit && TransactionUtils.areRequiredFieldsEmpty(transaction));
}, [isEditingSplitBill, hasSmartScanFailed, transaction, didConfirmSplit]);
const isMerchantEmpty = useMemo(() => !iouMerchant || TransactionUtils.isMerchantMissing(transaction), [transaction, iouMerchant]);
const isMerchantRequired = isPolicyExpenseChat && (!isScanRequest || isEditingSplitBill) && shouldShowMerchant;
const isCategoryRequired = !!policy?.requiresCategory;
const shouldDisableParticipant = (participant: Participant): boolean => {
if (ReportUtils.isDraftReport(participant.reportID)) {
return true;
}
if (!participant.isInvoiceRoom && !participant.isPolicyExpenseChat && !participant.isSelfDM && ReportUtils.isOptimisticPersonalDetail(participant.accountID ?? -1)) {
return true;
}
return false;
};
useEffect(() => {
if (shouldDisplayFieldError && didConfirmSplit) {
setFormError('iou.error.genericSmartscanFailureMessage');
return;
}
if (shouldDisplayFieldError && hasSmartScanFailed) {
setFormError('iou.receiptScanningFailed');
return;
}
// reset the form error whenever the screen gains or loses focus
setFormError('');
// eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps -- we don't want this effect to run if it's just setFormError that changes
}, [isFocused, transaction, shouldDisplayFieldError, hasSmartScanFailed, didConfirmSplit]);
const isFirstUpdatedDistanceAmount = useRef(false);
useEffect(() => {
if (isFirstUpdatedDistanceAmount.current) {
return;
}
if (!isDistanceRequest) {
return;
}
const amount = DistanceRequestUtils.getDistanceRequestAmount(distance, unit ?? CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES, rate ?? 0);
IOU.setMoneyRequestAmount(transactionID, amount, currency ?? '');
isFirstUpdatedDistanceAmount.current = true;
}, [distance, rate, unit, transactionID, currency, isDistanceRequest]);
useEffect(() => {
if (!shouldCalculateDistanceAmount) {
return;
}
const amount = distanceRequestAmount;
IOU.setMoneyRequestAmount(transactionID, amount, currency ?? '');
// If it's a split request among individuals, set the split shares
const participantAccountIDs: number[] = selectedParticipantsProp.map((participant) => participant.accountID ?? -1);
if (isTypeSplit && !isPolicyExpenseChat && amount && transaction?.currency) {
IOU.setSplitShares(transaction, amount, currency, participantAccountIDs);
}
}, [shouldCalculateDistanceAmount, distanceRequestAmount, transactionID, currency, isTypeSplit, isPolicyExpenseChat, selectedParticipantsProp, transaction]);
// Calculate and set tax amount in transaction draft
useEffect(() => {
if (!shouldShowTax || (transaction?.taxAmount !== undefined && previousTransactionAmount === transaction?.amount && previousTransactionCurrency === transaction?.currency)) {
return;
}
let taxableAmount: number;
let taxCode: string;
if (isDistanceRequest) {
const customUnitRate = getCustomUnitRate(policy, customUnitRateID);
taxCode = customUnitRate?.attributes?.taxRateExternalID ?? '';
taxableAmount = DistanceRequestUtils.getTaxableAmount(policy, customUnitRateID, distance);
} else {
taxableAmount = transaction?.amount ?? 0;
taxCode = transaction?.taxCode ?? TransactionUtils.getDefaultTaxCode(policy, transaction) ?? '';
}
const taxPercentage = TransactionUtils.getTaxValue(policy, transaction, taxCode) ?? '';
const taxAmount = TransactionUtils.calculateTaxAmount(taxPercentage, taxableAmount, currency);
const taxAmountInSmallestCurrencyUnits = CurrencyUtils.convertToBackendAmount(Number.parseFloat(taxAmount.toString()));
IOU.setMoneyRequestTaxAmount(transaction?.transactionID ?? '', taxAmountInSmallestCurrencyUnits);
}, [policy, shouldShowTax, previousTransactionAmount, previousTransactionCurrency, transaction, isDistanceRequest, customUnitRateID, currency, distance]);
// If completing a split expense fails, set didConfirm to false to allow the user to edit the fields again
if (isEditingSplitBill && didConfirm) {
setDidConfirm(false);
}
const splitOrRequestOptions: Array<DropdownOption<string>> = useMemo(() => {
let text;
if (isTypeInvoice) {
if (hasInvoicingDetails(policy)) {
text = translate('iou.sendInvoice', {amount: formattedAmount});
} else {
text = translate('common.next');
}
} else if (isTypeTrackExpense) {
text = translate('iou.trackExpense');
} else if (isTypeSplit && iouAmount === 0) {
text = translate('iou.splitExpense');
} else if ((receiptPath && isTypeRequest) || isDistanceRequestWithPendingRoute) {
text = translate('iou.submitExpense');
if (iouAmount !== 0) {
text = translate('iou.submitAmount', {amount: formattedAmount});
}
} else {
const translationKey = isTypeSplit ? 'iou.splitAmount' : 'iou.submitAmount';
text = translate(translationKey, {amount: formattedAmount});
}
return [
{
text: text[0].toUpperCase() + text.slice(1),
value: iouType,
},
];
}, [isTypeTrackExpense, isTypeSplit, iouAmount, receiptPath, isTypeRequest, policy, isDistanceRequestWithPendingRoute, iouType, translate, formattedAmount, isTypeInvoice]);
const onSplitShareChange = useCallback(
(accountID: number, value: number) => {
if (!transaction?.transactionID) {
return;
}
const amountInCents = CurrencyUtils.convertToBackendAmount(value);
IOU.setIndividualShare(transaction?.transactionID, accountID, amountInCents);
},
[transaction],
);
useEffect(() => {
if (!isTypeSplit || !transaction?.splitShares) {
return;
}
const splitSharesMap: SplitShares = transaction.splitShares;
const shares: number[] = Object.values(splitSharesMap).map((splitShare) => splitShare?.amount ?? 0);
const sumOfShares = shares?.reduce((prev, current): number => prev + current, 0);
if (sumOfShares !== iouAmount) {
setFormError('iou.error.invalidSplit');
return;
}
const participantsWithAmount = Object.keys(transaction?.splitShares ?? {})
.filter((accountID: string): boolean => (transaction?.splitShares?.[Number(accountID)]?.amount ?? 0) > 0)
.map((accountID) => Number(accountID));
// A split must have at least two participants with amounts bigger than 0
if (participantsWithAmount.length === 1) {
setFormError('iou.error.invalidSplitParticipants');
return;
}
setFormError('');
}, [isFocused, transaction, isTypeSplit, transaction?.splitShares, iouAmount, iouCurrencyCode, setFormError, translate]);
useEffect(() => {
if (!isTypeSplit || !transaction?.splitShares) {
return;
}
IOU.adjustRemainingSplitShares(transaction);
}, [isTypeSplit, transaction]);
const selectedParticipants = useMemo(() => selectedParticipantsProp.filter((participant) => participant.selected), [selectedParticipantsProp]);
const payeePersonalDetails = useMemo(() => payeePersonalDetailsProp ?? currentUserPersonalDetails, [payeePersonalDetailsProp, currentUserPersonalDetails]);
const shouldShowReadOnlySplits = useMemo(() => isPolicyExpenseChat || isReadOnly || isScanRequest, [isPolicyExpenseChat, isReadOnly, isScanRequest]);
const splitParticipants = useMemo(() => {
if (!isTypeSplit) {
return [];
}
const payeeOption = OptionsListUtils.getIOUConfirmationOptionsFromPayeePersonalDetail(payeePersonalDetails);
if (shouldShowReadOnlySplits) {
return [payeeOption, ...selectedParticipants].map((participantOption: Participant) => {
const isPayer = participantOption.accountID === payeeOption.accountID;
let amount: number | undefined = 0;
if (iouAmount > 0) {
amount =
transaction?.comment?.splits?.find((split) => split.accountID === participantOption.accountID)?.amount ??
IOUUtils.calculateAmount(selectedParticipants.length, iouAmount, iouCurrencyCode ?? '', isPayer);
}
return {
...participantOption,
isSelected: false,
isInteractive: !shouldDisableParticipant(participantOption),
rightElement: (
<View style={[styles.flexWrap, styles.pl2]}>
<Text style={[styles.textLabel]}>{amount ? CurrencyUtils.convertToDisplayString(amount, iouCurrencyCode) : ''}</Text>
</View>
),
};
});
}
const currencySymbol = currencyList?.[iouCurrencyCode ?? '']?.symbol ?? iouCurrencyCode;
const formattedTotalAmount = CurrencyUtils.convertToDisplayStringWithoutCurrency(iouAmount, iouCurrencyCode);
return [payeeOption, ...selectedParticipants].map((participantOption: Participant) => ({
...participantOption,
tabIndex: -1,
isSelected: false,
isInteractive: !shouldDisableParticipant(participantOption),
rightElement: (
<MoneyRequestAmountInput
autoGrow={false}
amount={transaction?.splitShares?.[participantOption.accountID ?? -1]?.amount}
currency={iouCurrencyCode}
prefixCharacter={currencySymbol}
disableKeyboard={false}
isCurrencyPressable={false}
hideFocusedState={false}
hideCurrencySymbol
formatAmountOnBlur
prefixContainerStyle={[styles.pv0]}
inputStyle={[styles.optionRowAmountInput]}
containerStyle={[styles.textInputContainer]}
touchableInputWrapperStyle={[styles.ml3]}
onFormatAmount={CurrencyUtils.convertToDisplayStringWithoutCurrency}
onAmountChange={(value: string) => onSplitShareChange(participantOption.accountID ?? -1, Number(value))}
maxLength={formattedTotalAmount.length}
contentWidth={formattedTotalAmount.length * 8}
/>
),
}));
}, [
isTypeSplit,
payeePersonalDetails,
shouldShowReadOnlySplits,
currencyList,
iouCurrencyCode,
iouAmount,
selectedParticipants,
styles.flexWrap,
styles.pl2,
styles.textLabel,
styles.pv0,
styles.optionRowAmountInput,
styles.textInputContainer,
styles.ml3,
transaction?.comment?.splits,
transaction?.splitShares,
onSplitShareChange,
]);
const isSplitModified = useMemo(() => {
if (!transaction?.splitShares) {
return;
}
return Object.keys(transaction.splitShares).some((key) => transaction.splitShares?.[Number(key) ?? -1]?.isModified);
}, [transaction?.splitShares]);
const getSplitSectionHeader = useCallback(
() => (
<View style={[styles.mt2, styles.mb1, styles.flexRow, styles.justifyContentBetween]}>
<Text style={[styles.ph5, styles.textLabelSupporting]}>{translate('iou.participants')}</Text>
{!shouldShowReadOnlySplits && isSplitModified && (
<PressableWithFeedback
onPress={() => {
IOU.resetSplitShares(transaction);
}}
accessibilityLabel={CONST.ROLE.BUTTON}
role={CONST.ROLE.BUTTON}
shouldUseAutoHitSlop
>
<Text style={[styles.pr5, styles.textLabelSupporting, styles.link]}>{translate('common.reset')}</Text>
</PressableWithFeedback>
)}
</View>
),
[
isSplitModified,
shouldShowReadOnlySplits,
styles.flexRow,
styles.justifyContentBetween,
styles.link,
styles.mb1,
styles.mt2,
styles.ph5,
styles.pr5,
styles.textLabelSupporting,
transaction,
translate,
],
);
const sections = useMemo(() => {
const options: Array<SectionListDataType<MoneyRequestConfirmationListItem>> = [];
if (isTypeSplit) {
options.push(
...[
{
title: translate('moneyRequestConfirmationList.paidBy'),
data: [OptionsListUtils.getIOUConfirmationOptionsFromPayeePersonalDetail(payeePersonalDetails)],
shouldShow: true,
},
{
CustomSectionHeader: getSplitSectionHeader,
data: splitParticipants,
shouldShow: true,
},
],
);
options.push();
} else {
const formattedSelectedParticipants = selectedParticipants.map((participant) => ({
...participant,
isSelected: false,
isInteractive: !shouldDisableParticipant(participant),
}));
options.push({
title: translate('common.to'),
data: formattedSelectedParticipants,
shouldShow: true,
});
}
return options;
}, [isTypeSplit, translate, payeePersonalDetails, getSplitSectionHeader, splitParticipants, selectedParticipants]);
useEffect(() => {
if (!isDistanceRequest || isMovingTransactionFromTrackExpense) {
return;
}
/*
Set pending waypoints based on the route status. We should handle this dynamically to cover cases such as:
When the user completes the initial steps of the IOU flow offline and then goes online on the confirmation page.
In this scenario, the route will be fetched from the server, and the waypoints will no longer be pending.
*/
IOU.setMoneyRequestPendingFields(transactionID, {waypoints: isDistanceRequestWithPendingRoute ? CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD : null});
const distanceMerchant = DistanceRequestUtils.getDistanceMerchant(hasRoute, distance, unit, rate ?? 0, currency ?? CONST.CURRENCY.USD, translate, toLocaleDigit);
IOU.setMoneyRequestMerchant(transactionID, distanceMerchant, true);
}, [
isDistanceRequestWithPendingRoute,
hasRoute,
distance,
unit,
rate,
currency,
translate,
toLocaleDigit,
isDistanceRequest,
transaction,
transactionID,
action,
isMovingTransactionFromTrackExpense,
]);
// Auto select the category if there is only one enabled category and it is required
useEffect(() => {
const enabledCategories = Object.values(policyCategories ?? {}).filter((category) => category.enabled);
if (iouCategory || !shouldShowCategories || enabledCategories.length !== 1 || !isCategoryRequired) {
return;
}
IOU.setMoneyRequestCategory(transactionID, enabledCategories[0].name);
// Keep 'transaction' out to ensure that we autoselect the option only once
// eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps
}, [shouldShowCategories, policyCategories, isCategoryRequired]);
// Auto select the tag if there is only one enabled tag and it is required
useEffect(() => {
let updatedTagsString = TransactionUtils.getTag(transaction);
policyTagLists.forEach((tagList, index) => {
const enabledTags = Object.values(tagList.tags).filter((tag) => tag.enabled);
const isTagListRequired = tagList.required ?? false;
if (!isTagListRequired || enabledTags.length !== 1 || TransactionUtils.getTag(transaction, index)) {
return;
}
updatedTagsString = IOUUtils.insertTagIntoTransactionTagsString(updatedTagsString, enabledTags[0] ? enabledTags[0].name : '', index);
});
if (updatedTagsString !== TransactionUtils.getTag(transaction) && updatedTagsString) {
IOU.setMoneyRequestTag(transactionID, updatedTagsString);
}
// Keep 'transaction' out to ensure that we autoselect the option only once
// eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps
}, [policyTagLists, policyTags]);
/**
* Navigate to report details or profile of selected user
*/
const navigateToReportOrUserDetail = (option: MoneyRequestConfirmationListItem) => {
const activeRoute = Navigation.getActiveRouteWithoutParams();
if (option.isSelfDM) {
Navigation.navigate(ROUTES.PROFILE.getRoute(currentUserPersonalDetails.accountID, activeRoute));
return;
}
if (option.accountID) {
Navigation.navigate(ROUTES.PROFILE.getRoute(option.accountID, activeRoute));
} else if (option.reportID) {
Navigation.navigate(ROUTES.REPORT_WITH_ID_DETAILS.getRoute(option.reportID, activeRoute));
}
};
/**
* @param {String} paymentMethod
*/
const confirm = useCallback(
(paymentMethod: PaymentMethodType | undefined) => {
if (iouType === CONST.IOU.TYPE.INVOICE && !hasInvoicingDetails(policy)) {
Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_COMPANY_INFO.getRoute(iouType, transactionID, reportID, Navigation.getActiveRouteWithoutParams()));
return;
}
if (selectedParticipants.length === 0) {
return;
}
if (!isEditingSplitBill && isMerchantRequired && (isMerchantEmpty || (shouldDisplayFieldError && TransactionUtils.isMerchantMissing(transaction)))) {
setFormError('iou.error.invalidMerchant');
return;
}
if (iouCategory.length > CONST.API_TRANSACTION_CATEGORY_MAX_LENGTH) {
setFormError('iou.error.invalidCategoryLength');
return;
}
if (iouType !== CONST.IOU.TYPE.PAY) {
// validate the amount for distance expenses
const decimals = CurrencyUtils.getCurrencyDecimals(iouCurrencyCode);
if (isDistanceRequest && !isDistanceRequestWithPendingRoute && !MoneyRequestUtils.validateAmount(String(iouAmount), decimals)) {
setFormError('common.error.invalidAmount');
return;
}
if (isEditingSplitBill && TransactionUtils.areRequiredFieldsEmpty(transaction)) {
setDidConfirmSplit(true);
setFormError('iou.error.genericSmartscanFailureMessage');
return;
}
if (formError) {
return;
}
if (shouldPlaySound) {
playSound(SOUNDS.DONE);
}
setDidConfirm(true);
onConfirm?.(selectedParticipants);
} else {
if (!paymentMethod) {
return;
}
if (formError) {
return;
}
setDidConfirm(true);
Log.info(`[IOU] Sending money via: ${paymentMethod}`);
onSendMoney?.(paymentMethod);
}
},
[
selectedParticipants,
isEditingSplitBill,
isMerchantRequired,
isMerchantEmpty,
shouldDisplayFieldError,
transaction,
iouCategory.length,
formError,
iouType,
setFormError,
onSendMoney,
iouCurrencyCode,
isDistanceRequest,
isDistanceRequestWithPendingRoute,
iouAmount,
onConfirm,
shouldPlaySound,
transactionID,
reportID,
policy,
],
);
const focusTimeoutRef = useRef<NodeJS.Timeout | null>(null);
useFocusEffect(
useCallback(() => {
focusTimeoutRef.current = setTimeout(() => {
InteractionManager.runAfterInteractions(() => {
blurActiveElement();
});
}, CONST.ANIMATED_TRANSITION);
return () => focusTimeoutRef.current && clearTimeout(focusTimeoutRef.current);
}, []),
);
const footerContent = useMemo(() => {
if (isReadOnly) {
return;
}
const shouldShowSettlementButton = iouType === CONST.IOU.TYPE.PAY;
const shouldDisableButton = selectedParticipants.length === 0;
const button = shouldShowSettlementButton ? (
<SettlementButton
pressOnEnter
isDisabled={shouldDisableButton}
onPress={confirm}
enablePaymentsRoute={ROUTES.IOU_SEND_ENABLE_PAYMENTS}
addBankAccountRoute={bankAccountRoute}
shouldShowPersonalBankAccountOption
currency={iouCurrencyCode}
policyID={policyID}
buttonSize={CONST.DROPDOWN_BUTTON_SIZE.LARGE}
kycWallAnchorAlignment={{
horizontal: CONST.MODAL.ANCHOR_ORIGIN_HORIZONTAL.LEFT,
vertical: CONST.MODAL.ANCHOR_ORIGIN_VERTICAL.BOTTOM,
}}
paymentMethodDropdownAnchorAlignment={{
horizontal: CONST.MODAL.ANCHOR_ORIGIN_HORIZONTAL.RIGHT,
vertical: CONST.MODAL.ANCHOR_ORIGIN_VERTICAL.BOTTOM,
}}
enterKeyEventListenerPriority={1}
useKeyboardShortcuts
/>
) : (
<ButtonWithDropdownMenu
success
pressOnEnter
isDisabled={shouldDisableButton}
onPress={(event, value) => confirm(value as PaymentMethodType)}
options={splitOrRequestOptions}
buttonSize={CONST.DROPDOWN_BUTTON_SIZE.LARGE}
enterKeyEventListenerPriority={1}
useKeyboardShortcuts
/>
);
return (
<>
{!!formError && (
<FormHelpMessage
style={[styles.ph1, styles.mb2]}
isError
message={isTypeSplit && !shouldShowReadOnlySplits ? debouncedFormError && translate(debouncedFormError) : translate(formError)}
/>
)}
{button}
</>
);
}, [
isReadOnly,
isTypeSplit,
iouType,
selectedParticipants.length,
confirm,
bankAccountRoute,
iouCurrencyCode,
policyID,
splitOrRequestOptions,
formError,
styles.ph1,
styles.mb2,
shouldShowReadOnlySplits,
debouncedFormError,
translate,
]);
const listFooterContent = (
<MoneyRequestConfirmationListFooter
action={action}
canUseP2PDistanceRequests={canUseP2PDistanceRequests}
currency={currency}
didConfirm={didConfirm}
distance={distance}
formattedAmount={formattedAmount}
formError={formError}
hasRoute={hasRoute}
iouCategory={iouCategory}
iouComment={iouComment}
iouCreated={iouCreated}
iouCurrencyCode={iouCurrencyCode}
iouIsBillable={iouIsBillable}
iouMerchant={iouMerchant}
iouType={iouType}
isCategoryRequired={isCategoryRequired}
isDistanceRequest={isDistanceRequest}
isEditingSplitBill={isEditingSplitBill}
isMerchantEmpty={isMerchantEmpty}
isMerchantRequired={isMerchantRequired}
isMovingTransactionFromTrackExpense={isMovingTransactionFromTrackExpense}
isPolicyExpenseChat={isPolicyExpenseChat}
isReadOnly={isReadOnly}
isTypeInvoice={isTypeInvoice}
onToggleBillable={onToggleBillable}
policy={policy}
policyTags={policyTags}
policyTagLists={policyTagLists}
rate={rate}
receiptFilename={receiptFilename}
receiptPath={receiptPath}
reportActionID={reportActionID}
reportID={reportID}
selectedParticipants={selectedParticipantsProp}
shouldDisplayFieldError={shouldDisplayFieldError}
shouldDisplayReceipt={shouldDisplayReceipt}
shouldShowCategories={shouldShowCategories}
shouldShowMerchant={shouldShowMerchant}
shouldShowSmartScanFields={shouldShowSmartScanFields}
shouldShowTax={shouldShowTax}
transaction={transaction}
transactionID={transactionID}
unit={unit}
/>
);
return (
<MouseProvider>
<SelectionList<MoneyRequestConfirmationListItem>
sections={sections}
ListItem={UserListItem}
onSelectRow={navigateToReportOrUserDetail}
shouldSingleExecuteRowSelect
canSelectMultiple={false}
shouldPreventDefaultFocusOnSelectRow
footerContent={footerContent}
listFooterContent={listFooterContent}
containerStyle={[styles.flexBasisAuto]}
removeClippedSubviews={false}
disableKeyboardShortcuts
/>
</MouseProvider>
);
}
MoneyRequestConfirmationList.displayName = 'MoneyRequestConfirmationList';
export default withOnyx<MoneyRequestConfirmationListProps, MoneyRequestConfirmationListOnyxProps>({
policyCategories: {
key: ({policyID}) => `${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}${policyID}`,
},
policyCategoriesDraft: {
key: ({policyID}) => `${ONYXKEYS.COLLECTION.POLICY_CATEGORIES_DRAFT}${policyID}`,
},
policyTags: {
key: ({policyID}) => `${ONYXKEYS.COLLECTION.POLICY_TAGS}${policyID}`,
},
defaultMileageRate: {
key: ({policyID}) => `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
selector: DistanceRequestUtils.getDefaultMileageRate,
},
mileageRates: {
key: ({policyID}) => `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
selector: (policy: OnyxEntry<OnyxTypes.Policy>) => DistanceRequestUtils.getMileageRates(policy),
},
policy: {
key: ({policyID}) => `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
},
policyDraft: {
key: ({policyID}) => `${ONYXKEYS.COLLECTION.POLICY_DRAFTS}${policyID}`,
},
lastSelectedDistanceRates: {
key: ONYXKEYS.NVP_LAST_SELECTED_DISTANCE_RATES,
},
currencyList: {
key: ONYXKEYS.CURRENCY_LIST,
},
})(
memo(
MoneyRequestConfirmationList,
(prevProps, nextProps) =>
lodashIsEqual(prevProps.transaction, nextProps.transaction) &&
prevProps.onSendMoney === nextProps.onSendMoney &&
prevProps.onConfirm === nextProps.onConfirm &&
prevProps.iouType === nextProps.iouType &&
prevProps.iouAmount === nextProps.iouAmount &&
prevProps.isDistanceRequest === nextProps.isDistanceRequest &&
prevProps.isPolicyExpenseChat === nextProps.isPolicyExpenseChat &&
prevProps.iouCategory === nextProps.iouCategory &&
prevProps.shouldShowSmartScanFields === nextProps.shouldShowSmartScanFields &&
prevProps.isEditingSplitBill === nextProps.isEditingSplitBill &&
prevProps.iouCurrencyCode === nextProps.iouCurrencyCode &&
prevProps.iouMerchant === nextProps.iouMerchant &&
lodashIsEqual(prevProps.selectedParticipants, nextProps.selectedParticipants) &&
lodashIsEqual(prevProps.payeePersonalDetails, nextProps.payeePersonalDetails) &&
prevProps.isReadOnly === nextProps.isReadOnly &&
prevProps.bankAccountRoute === nextProps.bankAccountRoute &&
prevProps.policyID === nextProps.policyID &&
prevProps.reportID === nextProps.reportID &&
prevProps.receiptPath === nextProps.receiptPath &&
prevProps.iouComment === nextProps.iouComment &&
prevProps.receiptFilename === nextProps.receiptFilename &&
prevProps.iouCreated === nextProps.iouCreated &&
prevProps.iouIsBillable === nextProps.iouIsBillable &&
prevProps.onToggleBillable === nextProps.onToggleBillable &&
prevProps.hasSmartScanFailed === nextProps.hasSmartScanFailed &&
prevProps.reportActionID === nextProps.reportActionID &&
lodashIsEqual(prevProps.defaultMileageRate, nextProps.defaultMileageRate) &&
lodashIsEqual(prevProps.lastSelectedDistanceRates, nextProps.lastSelectedDistanceRates) &&
lodashIsEqual(prevProps.action, nextProps.action) &&
lodashIsEqual(prevProps.currencyList, nextProps.currencyList) &&
prevProps.shouldDisplayReceipt === nextProps.shouldDisplayReceipt,
),
);