-
Notifications
You must be signed in to change notification settings - Fork 3k
/
IOU.js
3011 lines (2779 loc) · 118 KB
/
IOU.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
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
990
991
992
993
994
995
996
997
998
999
1000
import {format} from 'date-fns';
import Str from 'expensify-common/lib/str';
import lodashGet from 'lodash/get';
import lodashHas from 'lodash/has';
import Onyx from 'react-native-onyx';
import _ from 'underscore';
import ReceiptGeneric from '@assets/images/receipt-generic.png';
import * as API from '@libs/API';
import * as CurrencyUtils from '@libs/CurrencyUtils';
import DateUtils from '@libs/DateUtils';
import * as ErrorUtils from '@libs/ErrorUtils';
import * as IOUUtils from '@libs/IOUUtils';
import * as LocalePhoneNumber from '@libs/LocalePhoneNumber';
import * as Localize from '@libs/Localize';
import Navigation from '@libs/Navigation/Navigation';
import * as NumberUtils from '@libs/NumberUtils';
import * as OptionsListUtils from '@libs/OptionsListUtils';
import * as ReportActionsUtils from '@libs/ReportActionsUtils';
import * as ReportUtils from '@libs/ReportUtils';
import * as TransactionUtils from '@libs/TransactionUtils';
import * as UserUtils from '@libs/UserUtils';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import * as Policy from './Policy';
import * as Report from './Report';
let allPersonalDetails;
Onyx.connect({
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
callback: (val) => {
allPersonalDetails = val || {};
},
});
let allReports;
Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT,
waitForCollectionCallback: true,
callback: (val) => (allReports = val),
});
let allTransactions;
Onyx.connect({
key: ONYXKEYS.COLLECTION.TRANSACTION,
waitForCollectionCallback: true,
callback: (val) => {
if (!val) {
allTransactions = {};
return;
}
allTransactions = val;
},
});
let allDraftSplitTransactions;
Onyx.connect({
key: ONYXKEYS.COLLECTION.SPLIT_TRANSACTION_DRAFT,
waitForCollectionCallback: true,
callback: (val) => {
allDraftSplitTransactions = val || {};
},
});
let allRecentlyUsedTags = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_TAGS,
waitForCollectionCallback: true,
callback: (value) => {
if (!value) {
allRecentlyUsedTags = {};
return;
}
allRecentlyUsedTags = value;
},
});
let allPolicyTags = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.POLICY_TAGS,
waitForCollectionCallback: true,
callback: (value) => {
if (!value) {
allPolicyTags = {};
return;
}
allPolicyTags = value;
},
});
let userAccountID = '';
let currentUserEmail = '';
Onyx.connect({
key: ONYXKEYS.SESSION,
callback: (val) => {
currentUserEmail = lodashGet(val, 'email', '');
userAccountID = lodashGet(val, 'accountID', '');
},
});
let currentUserPersonalDetails = {};
Onyx.connect({
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
callback: (val) => {
currentUserPersonalDetails = lodashGet(val, userAccountID, {});
},
});
let currentDate = '';
Onyx.connect({
key: ONYXKEYS.CURRENT_DATE,
callback: (val) => {
currentDate = val;
},
});
/**
* Reset money request info from the store with its initial value
* @param {String} id
*/
function resetMoneyRequestInfo(id = '') {
const created = currentDate || format(new Date(), CONST.DATE.FNS_FORMAT_STRING);
Onyx.merge(ONYXKEYS.IOU, {
id,
amount: 0,
currency: lodashGet(currentUserPersonalDetails, 'localCurrencyCode', CONST.CURRENCY.USD),
comment: '',
participants: [],
merchant: CONST.TRANSACTION.DEFAULT_MERCHANT,
category: '',
tag: '',
created,
receiptPath: '',
receiptFilename: '',
transactionID: '',
billable: null,
isSplitRequest: false,
});
}
function buildOnyxDataForMoneyRequest(
chatReport,
iouReport,
transaction,
chatCreatedAction,
iouCreatedAction,
iouAction,
optimisticPersonalDetailListAction,
reportPreviewAction,
optimisticPolicyRecentlyUsedCategories,
optimisticPolicyRecentlyUsedTags,
isNewChatReport,
isNewIOUReport,
) {
const optimisticData = [
{
// Use SET for new reports because it doesn't exist yet, is faster and we need the data to be available when we navigate to the chat page
onyxMethod: isNewChatReport ? Onyx.METHOD.SET : Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${chatReport.reportID}`,
value: {
...chatReport,
lastReadTime: DateUtils.getDBTime(),
lastMessageTranslationKey: '',
hasOutstandingIOU: iouReport.total !== 0,
iouReportID: iouReport.reportID,
...(isNewChatReport ? {pendingFields: {createChat: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD}} : {}),
},
},
{
onyxMethod: isNewIOUReport ? Onyx.METHOD.SET : Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport.reportID}`,
value: {
...iouReport,
lastMessageText: iouAction.message[0].text,
lastMessageHtml: iouAction.message[0].html,
...(isNewIOUReport ? {pendingFields: {createChat: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD}} : {}),
},
},
{
onyxMethod: Onyx.METHOD.SET,
key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`,
value: transaction,
},
{
onyxMethod: isNewChatReport ? Onyx.METHOD.SET : Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport.reportID}`,
value: {
...(isNewChatReport ? {[chatCreatedAction.reportActionID]: chatCreatedAction} : {}),
[reportPreviewAction.reportActionID]: reportPreviewAction,
},
},
{
onyxMethod: isNewIOUReport ? Onyx.METHOD.SET : Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport.reportID}`,
value: {
...(isNewIOUReport ? {[iouCreatedAction.reportActionID]: iouCreatedAction} : {}),
[iouAction.reportActionID]: iouAction,
},
},
];
if (!_.isEmpty(optimisticPolicyRecentlyUsedCategories)) {
optimisticData.push({
onyxMethod: Onyx.METHOD.SET,
key: `${ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_CATEGORIES}${iouReport.policyID}`,
value: optimisticPolicyRecentlyUsedCategories,
});
}
if (!_.isEmpty(optimisticPolicyRecentlyUsedTags)) {
optimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_TAGS}${iouReport.policyID}`,
value: optimisticPolicyRecentlyUsedTags,
});
}
if (!_.isEmpty(optimisticPersonalDetailListAction)) {
optimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
value: optimisticPersonalDetailListAction,
});
}
const successData = [
...(isNewChatReport
? [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${chatReport.reportID}`,
value: {
pendingFields: null,
errorFields: null,
},
},
]
: []),
...(isNewIOUReport
? [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport.reportID}`,
value: {
pendingFields: null,
errorFields: null,
},
},
]
: []),
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`,
value: {
pendingAction: null,
pendingFields: null,
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport.reportID}`,
value: {
...(isNewChatReport
? {
[chatCreatedAction.reportActionID]: {
pendingAction: null,
errors: null,
},
}
: {}),
[reportPreviewAction.reportActionID]: {
pendingAction: null,
},
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport.reportID}`,
value: {
...(isNewIOUReport
? {
[iouCreatedAction.reportActionID]: {
pendingAction: null,
errors: null,
},
}
: {}),
[iouAction.reportActionID]: {
pendingAction: null,
errors: null,
},
},
},
];
const failureData = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${chatReport.reportID}`,
value: {
hasOutstandingIOU: chatReport.hasOutstandingIOU,
iouReportID: chatReport.iouReportID,
lastReadTime: chatReport.lastReadTime,
pendingFields: null,
...(isNewChatReport
? {
errorFields: {
createChat: ErrorUtils.getMicroSecondOnyxError('report.genericCreateReportFailureMessage'),
},
}
: {}),
},
},
...(isNewIOUReport
? [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport.reportID}`,
value: {
pendingFields: null,
errorFields: {
createChat: ErrorUtils.getMicroSecondOnyxError('report.genericCreateReportFailureMessage'),
},
},
},
]
: []),
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`,
value: {
errors: ErrorUtils.getMicroSecondOnyxError('iou.error.genericCreateFailureMessage'),
pendingAction: null,
pendingFields: null,
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport.reportID}`,
value: {
...(isNewChatReport
? {
[chatCreatedAction.reportActionID]: {
errors: ErrorUtils.getMicroSecondOnyxError('iou.error.genericCreateFailureMessage'),
},
[reportPreviewAction.reportActionID]: {
errors: ErrorUtils.getMicroSecondOnyxError(null),
},
}
: {
[reportPreviewAction.reportActionID]: {
created: reportPreviewAction.created,
errors: ErrorUtils.getMicroSecondOnyxError('iou.error.genericCreateFailureMessage'),
},
}),
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport.reportID}`,
value: {
...(isNewIOUReport
? {
[iouCreatedAction.reportActionID]: {
errors: ErrorUtils.getMicroSecondOnyxError('iou.error.genericCreateFailureMessage'),
},
[iouAction.reportActionID]: {
errors: ErrorUtils.getMicroSecondOnyxError(null),
},
}
: {
[iouAction.reportActionID]: {
errors: ErrorUtils.getMicroSecondOnyxError('iou.error.genericCreateFailureMessage'),
},
}),
},
},
];
return [optimisticData, successData, failureData];
}
/**
* Gathers all the data needed to make a money request. It attempts to find existing reports, iouReports, and receipts. If it doesn't find them, then
* it creates optimistic versions of them and uses those instead
*
* @param {Object} report
* @param {Object} participant
* @param {String} comment
* @param {Number} amount
* @param {String} currency
* @param {String} created
* @param {String} merchant
* @param {Number} [payeeAccountID]
* @param {String} [payeeEmail]
* @param {Object} [receipt]
* @param {String} [existingTransactionID]
* @param {String} [category]
* @param {String} [tag]
* @param {Boolean} [billable]
* @returns {Object} data
* @returns {String} data.payerEmail
* @returns {Object} data.iouReport
* @returns {Object} data.chatReport
* @returns {Object} data.transaction
* @returns {Object} data.iouAction
* @returns {Object} data.createdChatReportActionID
* @returns {Object} data.createdIOUReportActionID
* @returns {Object} data.reportPreviewAction
* @returns {Object} data.onyxData
* @returns {Object} data.onyxData.optimisticData
* @returns {Object} data.onyxData.successData
* @returns {Object} data.onyxData.failureData
*/
function getMoneyRequestInformation(
report,
participant,
comment,
amount,
currency,
created,
merchant,
payeeAccountID = userAccountID,
payeeEmail = currentUserEmail,
receipt = undefined,
existingTransactionID = undefined,
category = undefined,
tag = undefined,
billable = undefined,
) {
const payerEmail = OptionsListUtils.addSMSDomainIfPhoneNumber(participant.login);
const payerAccountID = Number(participant.accountID);
const isPolicyExpenseChat = participant.isPolicyExpenseChat;
// STEP 1: Get existing chat report OR build a new optimistic one
let isNewChatReport = false;
let chatReport = lodashGet(report, 'reportID', null) ? report : null;
// If this is a policyExpenseChat, the chatReport must exist and we can get it from Onyx.
// report is null if the flow is initiated from the global create menu. However, participant always stores the reportID if it exists, which is the case for policyExpenseChats
if (!chatReport && isPolicyExpenseChat) {
chatReport = allReports[`${ONYXKEYS.COLLECTION.REPORT}${participant.reportID}`];
}
if (!chatReport) {
chatReport = ReportUtils.getChatByParticipants([payerAccountID]);
}
// If we still don't have a report, it likely doens't exist and we need to build an optimistic one
if (!chatReport) {
isNewChatReport = true;
chatReport = ReportUtils.buildOptimisticChatReport([payerAccountID]);
}
// STEP 2: Get existing IOU report and update its total OR build a new optimistic one
const isNewIOUReport = !chatReport.iouReportID || ReportUtils.hasIOUWaitingOnCurrentUserBankAccount(chatReport);
let iouReport = isNewIOUReport ? null : allReports[`${ONYXKEYS.COLLECTION.REPORT}${chatReport.iouReportID}`];
if (iouReport) {
if (isPolicyExpenseChat) {
iouReport = {...iouReport};
// Because of the Expense reports are stored as negative values, we substract the total from the amount
iouReport.total -= amount;
} else {
iouReport = IOUUtils.updateIOUOwnerAndTotal(iouReport, payeeAccountID, amount, currency);
}
} else {
iouReport = isPolicyExpenseChat
? ReportUtils.buildOptimisticExpenseReport(chatReport.reportID, chatReport.policyID, payeeAccountID, amount, currency)
: ReportUtils.buildOptimisticIOUReport(payeeAccountID, payerAccountID, amount, chatReport.reportID, currency);
}
// STEP 3: Build optimistic receipt and transaction
const receiptObject = {};
let filename;
if (receipt && receipt.source) {
receiptObject.source = receipt.source;
receiptObject.state = receipt.state || CONST.IOU.RECEIPT_STATE.SCANREADY;
filename = receipt.name;
}
let optimisticTransaction = TransactionUtils.buildOptimisticTransaction(
ReportUtils.isExpenseReport(iouReport) ? -amount : amount,
currency,
iouReport.reportID,
comment,
created,
'',
'',
merchant,
receiptObject,
filename,
existingTransactionID,
category,
tag,
billable,
);
let optimisticPolicyRecentlyUsedCategories = [];
if (category) {
optimisticPolicyRecentlyUsedCategories = Policy.buildOptimisticPolicyRecentlyUsedCategories(iouReport.policyID, category);
}
const optimisticPolicyRecentlyUsedTags = {};
const policyTags = allPolicyTags[`${ONYXKEYS.COLLECTION.POLICY_TAGS}${iouReport.policyID}`];
const recentlyUsedPolicyTags = allRecentlyUsedTags[`${ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_TAGS}${iouReport.policyID}`];
if (policyTags) {
// For now it only uses the first tag of the policy, since multi-tags are not yet supported
const tagListKey = _.first(_.keys(policyTags));
const uniquePolicyRecentlyUsedTags = recentlyUsedPolicyTags ? _.filter(recentlyUsedPolicyTags[tagListKey], (recentlyUsedPolicyTag) => recentlyUsedPolicyTag !== tag) : [];
optimisticPolicyRecentlyUsedTags[tagListKey] = [tag, ...uniquePolicyRecentlyUsedTags];
}
// If there is an existing transaction (which is the case for distance requests), then the data from the existing transaction
// needs to be manually merged into the optimistic transaction. This is because buildOnyxDataForMoneyRequest() uses `Onyx.set()` for the transaction
// data. This is a big can of worms to change it to `Onyx.merge()` as explored in https://expensify.slack.com/archives/C05DWUDHVK7/p1692139468252109.
// I want to clean this up at some point, but it's possible this will live in the code for a while so I've created https://github.com/Expensify/App/issues/25417
// to remind me to do this.
const existingTransaction = existingTransactionID && TransactionUtils.getTransaction(existingTransactionID);
if (existingTransaction) {
optimisticTransaction = {
...optimisticTransaction,
...existingTransaction,
};
}
// STEP 4: Build optimistic reportActions. We need:
// 1. CREATED action for the chatReport
// 2. CREATED action for the iouReport
// 3. IOU action for the iouReport
// 4. REPORTPREVIEW action for the chatReport
// Note: The CREATED action for the IOU report must be optimistically generated before the IOU action so there's no chance that it appears after the IOU action in the chat
const currentTime = DateUtils.getDBTime();
const optimisticCreatedActionForChat = ReportUtils.buildOptimisticCreatedReportAction(payeeEmail);
const optimisticCreatedActionForIOU = ReportUtils.buildOptimisticCreatedReportAction(payeeEmail, DateUtils.subtractMillisecondsFromDateTime(currentTime, 1));
const iouAction = ReportUtils.buildOptimisticIOUReportAction(
CONST.IOU.REPORT_ACTION_TYPE.CREATE,
amount,
currency,
comment,
[participant],
optimisticTransaction.transactionID,
'',
iouReport.reportID,
false,
false,
receiptObject,
false,
currentTime,
);
let reportPreviewAction = isNewIOUReport ? null : ReportActionsUtils.getReportPreviewAction(chatReport.reportID, iouReport.reportID);
if (reportPreviewAction) {
reportPreviewAction = ReportUtils.updateReportPreview(iouReport, reportPreviewAction, false, comment, optimisticTransaction);
} else {
reportPreviewAction = ReportUtils.buildOptimisticReportPreview(chatReport, iouReport, comment, optimisticTransaction);
// Generated ReportPreview action is a parent report action of the iou report.
// We are setting the iou report's parentReportActionID to display subtitle correctly in IOU page when offline.
iouReport.parentReportActionID = reportPreviewAction.reportActionID;
}
const shouldCreateOptimisticPersonalDetails = isNewChatReport && !allPersonalDetails[payerAccountID];
// Add optimistic personal details for participant
const optimisticPersonalDetailListAction = shouldCreateOptimisticPersonalDetails
? {
[payerAccountID]: {
accountID: payerAccountID,
avatar: UserUtils.getDefaultAvatarURL(payerAccountID),
displayName: LocalePhoneNumber.formatPhoneNumber(participant.displayName || payerEmail),
login: participant.login,
isOptimisticPersonalDetail: true,
},
}
: undefined;
// STEP 5: Build Onyx Data
const [optimisticData, successData, failureData] = buildOnyxDataForMoneyRequest(
chatReport,
iouReport,
optimisticTransaction,
optimisticCreatedActionForChat,
optimisticCreatedActionForIOU,
iouAction,
optimisticPersonalDetailListAction,
reportPreviewAction,
optimisticPolicyRecentlyUsedCategories,
optimisticPolicyRecentlyUsedTags,
isNewChatReport,
isNewIOUReport,
);
return {
payerAccountID,
payerEmail,
iouReport,
chatReport,
transaction: optimisticTransaction,
iouAction,
createdChatReportActionID: isNewChatReport ? optimisticCreatedActionForChat.reportActionID : 0,
createdIOUReportActionID: isNewIOUReport ? optimisticCreatedActionForIOU.reportActionID : 0,
reportPreviewAction,
onyxData: {
optimisticData,
successData,
failureData,
},
};
}
/**
* Requests money based on a distance (eg. mileage from a map)
*
* @param {Object} report
* @param {Object} participant
* @param {String} comment
* @param {String} created
* @param {String} [transactionID]
* @param {String} [category]
* @param {String} [tag]
* @param {Number} amount
* @param {String} currency
* @param {String} merchant
* @param {Boolean} [billable]
*/
function createDistanceRequest(report, participant, comment, created, transactionID, category, tag, amount, currency, merchant, billable) {
// If the report is an iou or expense report, we should get the linked chat report to be passed to the getMoneyRequestInformation function
const isMoneyRequestReport = ReportUtils.isMoneyRequestReport(report);
const currentChatReport = isMoneyRequestReport ? ReportUtils.getReport(report.chatReportID) : report;
const optimisticReceipt = {
source: ReceiptGeneric,
state: CONST.IOU.RECEIPT_STATE.OPEN,
};
const {iouReport, chatReport, transaction, iouAction, createdChatReportActionID, createdIOUReportActionID, reportPreviewAction, onyxData} = getMoneyRequestInformation(
currentChatReport,
participant,
comment,
amount,
currency,
created,
merchant,
userAccountID,
currentUserEmail,
optimisticReceipt,
transactionID,
category,
tag,
billable,
);
API.write(
'CreateDistanceRequest',
{
comment,
iouReportID: iouReport.reportID,
chatReportID: chatReport.reportID,
transactionID: transaction.transactionID,
reportActionID: iouAction.reportActionID,
createdChatReportActionID,
createdIOUReportActionID,
reportPreviewReportActionID: reportPreviewAction.reportActionID,
waypoints: JSON.stringify(TransactionUtils.getValidWaypoints(transaction.comment.waypoints, true)),
created,
category,
tag,
billable,
},
onyxData,
);
Navigation.dismissModal(isMoneyRequestReport ? report.reportID : chatReport.reportID);
Report.notifyNewAction(chatReport.reportID, userAccountID);
}
/**
* Edits an existing distance request
*
* @param {String} transactionID
* @param {Number} transactionThreadReportID
* @param {Object} transactionChanges
* @param {String} [transactionChanges.created]
* @param {Number} [transactionChanges.amount]
* @param {Object} [transactionChanges.comment]
* @param {Object} [transactionChanges.waypoints]
*
*/
function editDistanceMoneyRequest(transactionID, transactionThreadReportID, transactionChanges) {
const optimisticData = [];
const successData = [];
const failureData = [];
// Step 1: Set any "pending fields" (ones updated while the user was offline) to have error messages in the failureData
const pendingFields = _.mapObject(transactionChanges, () => CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE);
const clearedPendingFields = _.mapObject(transactionChanges, () => null);
const errorFields = _.mapObject(pendingFields, () => ({
[DateUtils.getMicroseconds()]: Localize.translateLocal('iou.error.genericEditFailureMessage'),
}));
// Step 2: Get all the collections being updated
const transactionThread = allReports[`${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReportID}`];
const transaction = allTransactions[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`];
const iouReport = allReports[`${ONYXKEYS.COLLECTION.REPORT}${transactionThread.parentReportID}`];
const isFromExpenseReport = ReportUtils.isExpenseReport(iouReport);
const updatedTransaction = TransactionUtils.getUpdatedTransaction(transaction, transactionChanges, isFromExpenseReport);
const transactionDetails = ReportUtils.getTransactionDetails(updatedTransaction);
const params = {
...transactionDetails,
transactionID,
// This needs to be a JSON string since we're sending this to the MapBox API
waypoints: JSON.stringify(transactionDetails.waypoints),
};
// Step 3: Build the modified expense report actions
// We don't create a modified report action if we're updating the waypoints,
// since there isn't actually any optimistic data we can create for them and the report action is created on the server
// with the response from the MapBox API
if (!_.has(transactionChanges, 'waypoints')) {
const updatedReportAction = ReportUtils.buildOptimisticModifiedExpenseReportAction(transactionThread, transaction, transactionChanges, isFromExpenseReport);
params.reportActionID = updatedReportAction.reportActionID;
optimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThread.reportID}`,
value: {
[updatedReportAction.reportActionID]: updatedReportAction,
},
});
successData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThread.reportID}`,
value: {
[updatedReportAction.reportActionID]: {pendingAction: null},
},
});
failureData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThread.reportID}`,
value: {
[updatedReportAction.reportActionID]: updatedReportAction,
},
});
// Step 4: Compute the IOU total and update the report preview message (and report header) so LHN amount owed is correct.
// Should only update if the transaction matches the currency of the report, else we wait for the update
// from the server with the currency conversion
let updatedMoneyRequestReport = {...iouReport};
if (updatedTransaction.currency === iouReport.currency && updatedTransaction.modifiedAmount) {
const diff = TransactionUtils.getAmount(transaction, true) - TransactionUtils.getAmount(updatedTransaction, true);
if (ReportUtils.isExpenseReport(iouReport)) {
updatedMoneyRequestReport.total += diff;
} else {
updatedMoneyRequestReport = IOUUtils.updateIOUOwnerAndTotal(iouReport, updatedReportAction.actorAccountID, diff, TransactionUtils.getCurrency(transaction), false);
}
updatedMoneyRequestReport.cachedTotal = CurrencyUtils.convertToDisplayString(updatedMoneyRequestReport.total, updatedTransaction.currency);
optimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport.reportID}`,
value: updatedMoneyRequestReport,
});
successData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport.reportID}`,
value: {pendingAction: null},
});
}
}
// Optimistically modify the transaction
optimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`,
value: {
...updatedTransaction,
pendingFields,
isLoading: _.has(transactionChanges, 'waypoints'),
errorFields: null,
},
});
// Clear out the error fields and loading states on success
successData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`,
value: {
pendingFields: clearedPendingFields,
isLoading: false,
errorFields: null,
},
});
if (_.has(transactionChanges, 'waypoints')) {
// Delete the draft transaction when editing waypoints when the server responds successfully and there are no errors
successData.push({
onyxMethod: Onyx.METHOD.SET,
key: `${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transactionID}`,
value: null,
});
}
// Clear out loading states, pending fields, and add the error fields
failureData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`,
value: {
pendingFields: clearedPendingFields,
isLoading: false,
errorFields,
},
});
// Reset the iouReport to it's original state
failureData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport.reportID}`,
value: iouReport,
});
API.write('UpdateDistanceRequest', params, {optimisticData, successData, failureData});
}
/**
* Request money from another user
*
* @param {Object} report
* @param {Number} amount - always in the smallest unit of the currency
* @param {String} currency
* @param {String} created
* @param {String} merchant
* @param {String} payeeEmail
* @param {Number} payeeAccountID
* @param {Object} participant
* @param {String} comment
* @param {Object} [receipt]
* @param {String} [category]
* @param {String} [tag]
* @param {Boolean} [billable]
*/
function requestMoney(
report,
amount,
currency,
created,
merchant,
payeeEmail,
payeeAccountID,
participant,
comment,
receipt = undefined,
category = undefined,
tag = undefined,
billable = undefined,
) {
// If the report is iou or expense report, we should get the linked chat report to be passed to the getMoneyRequestInformation function
const isMoneyRequestReport = ReportUtils.isMoneyRequestReport(report);
const currentChatReport = isMoneyRequestReport ? ReportUtils.getReport(report.chatReportID) : report;
const {payerAccountID, payerEmail, iouReport, chatReport, transaction, iouAction, createdChatReportActionID, createdIOUReportActionID, reportPreviewAction, onyxData} =
getMoneyRequestInformation(currentChatReport, participant, comment, amount, currency, created, merchant, payeeAccountID, payeeEmail, receipt, undefined, category, tag, billable);
API.write(
'RequestMoney',
{
debtorEmail: payerEmail,
debtorAccountID: payerAccountID,
amount,
currency,
comment,
created,
merchant,
iouReportID: iouReport.reportID,
chatReportID: chatReport.reportID,
transactionID: transaction.transactionID,
reportActionID: iouAction.reportActionID,
createdChatReportActionID,
createdIOUReportActionID,
reportPreviewReportActionID: reportPreviewAction.reportActionID,
receipt,
receiptState: lodashGet(receipt, 'state'),
category,
tag,
billable,
},
onyxData,
);
resetMoneyRequestInfo();
Navigation.dismissModal(isMoneyRequestReport ? report.reportID : chatReport.reportID);
Report.notifyNewAction(chatReport.reportID, payeeAccountID);
}
/**
* Build the Onyx data and IOU split necessary for splitting a bill with 3+ users.
* 1. Build the optimistic Onyx data for the group chat, i.e. chatReport and iouReportAction creating the former if it doesn't yet exist.
* 2. Loop over the group chat participant list, building optimistic or updating existing chatReports, iouReports and iouReportActions between the user and each participant.
* We build both Onyx data and the IOU split that is sent as a request param and is used by Auth to create the chatReports, iouReports and iouReportActions in the database.
* The IOU split has the following shape:
* [
* {email: 'currentUser', amount: 100},
* {email: 'user2', amount: 100, iouReportID: '100', chatReportID: '110', transactionID: '120', reportActionID: '130'},
* {email: 'user3', amount: 100, iouReportID: '200', chatReportID: '210', transactionID: '220', reportActionID: '230'}
* ]
* @param {Array} participants
* @param {String} currentUserLogin
* @param {Number} currentUserAccountID
* @param {Number} amount - always in the smallest unit of the currency
* @param {String} comment
* @param {String} currency
* @param {String} category
* @param {String} existingSplitChatReportID - the report ID where the split bill happens, could be a group chat or a workspace chat
*
* @return {Object}
*/
function createSplitsAndOnyxData(participants, currentUserLogin, currentUserAccountID, amount, comment, currency, category, existingSplitChatReportID = '') {
const currentUserEmailForIOUSplit = OptionsListUtils.addSMSDomainIfPhoneNumber(currentUserLogin);
const participantAccountIDs = _.map(participants, (participant) => Number(participant.accountID));
const existingSplitChatReport =
existingSplitChatReportID || participants[0].reportID
? allReports[`${ONYXKEYS.COLLECTION.REPORT}${existingSplitChatReportID || participants[0].reportID}`]
: ReportUtils.getChatByParticipants(participantAccountIDs);
const splitChatReport = existingSplitChatReport || ReportUtils.buildOptimisticChatReport(participantAccountIDs);
const isOwnPolicyExpenseChat = splitChatReport.isOwnPolicyExpenseChat;
// ReportID is -2 (aka "deleted") on the group transaction: https://github.com/Expensify/Auth/blob/3fa2698654cd4fbc30f9de38acfca3fbeb7842e4/auth/command/SplitTransaction.cpp#L24-L27
const formattedParticipants = isOwnPolicyExpenseChat
? [currentUserLogin, ReportUtils.getReportName(splitChatReport)]
: Localize.arrayToString([currentUserLogin, ..._.map(participants, (participant) => participant.login || '')]);
const splitTransaction = TransactionUtils.buildOptimisticTransaction(
amount,
currency,
CONST.REPORT.SPLIT_REPORTID,
comment,
'',
'',
'',
`${Localize.translateLocal('iou.splitBill')} ${Localize.translateLocal('common.with')} ${formattedParticipants} [${DateUtils.getDBTime().slice(0, 10)}]`,
undefined,
undefined,
undefined,
category,
);
// Note: The created action must be optimistically generated before the IOU action so there's no chance that the created action appears after the IOU action in the chat
const splitCreatedReportAction = ReportUtils.buildOptimisticCreatedReportAction(currentUserEmailForIOUSplit);
const splitIOUReportAction = ReportUtils.buildOptimisticIOUReportAction(
CONST.IOU.REPORT_ACTION_TYPE.SPLIT,
amount,
currency,
comment,
participants,
splitTransaction.transactionID,
'',
'',
false,
false,
{},
isOwnPolicyExpenseChat,
);
splitChatReport.lastReadTime = DateUtils.getDBTime();
splitChatReport.lastMessageText = splitIOUReportAction.message[0].text;
splitChatReport.lastMessageHtml = splitIOUReportAction.message[0].html;
// If we have an existing splitChatReport (group chat or workspace) use it's pending fields, otherwise indicate that we are adding a chat
if (!existingSplitChatReport) {
splitChatReport.pendingFields = {
createChat: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
};
}
const optimisticData = [
{
// Use set for new reports because it doesn't exist yet, is faster,
// and we need the data to be available when we navigate to the chat page
onyxMethod: existingSplitChatReport ? Onyx.METHOD.MERGE : Onyx.METHOD.SET,
key: `${ONYXKEYS.COLLECTION.REPORT}${splitChatReport.reportID}`,
value: splitChatReport,
},
{
onyxMethod: existingSplitChatReport ? Onyx.METHOD.MERGE : Onyx.METHOD.SET,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${splitChatReport.reportID}`,
value: {
...(existingSplitChatReport ? {} : {[splitCreatedReportAction.reportActionID]: splitCreatedReportAction}),
[splitIOUReportAction.reportActionID]: splitIOUReportAction,
},
},
{
onyxMethod: Onyx.METHOD.SET,
key: `${ONYXKEYS.COLLECTION.TRANSACTION}${splitTransaction.transactionID}`,
value: splitTransaction,
},
];
const successData = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${splitChatReport.reportID}`,