-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathIOUTest.ts
4652 lines (4172 loc) · 234 KB
/
IOUTest.ts
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 isEqual from 'lodash/isEqual';
import type {OnyxCollection, OnyxEntry, OnyxInputValue} from 'react-native-onyx';
import Onyx from 'react-native-onyx';
import {
canApproveIOU,
cancelPayment,
deleteMoneyRequest,
payMoneyRequest,
putOnHold,
requestMoney,
resolveDuplicates,
sendInvoice,
setDraftSplitTransaction,
setMoneyRequestCategory,
splitBill,
submitReport,
trackExpense,
unholdRequest,
updateMoneyRequestAmountAndCurrency,
updateMoneyRequestCategory,
} from '@libs/actions/IOU';
import {createWorkspace, generatePolicyID, setWorkspaceApprovalMode} from '@libs/actions/Policy/Policy';
import {addComment, deleteReport, notifyNewAction, openReport} from '@libs/actions/Report';
import {clearAllRelatedReportActionErrors} from '@libs/actions/ReportActions';
import {subscribeToUserEvents} from '@libs/actions/User';
import {WRITE_COMMANDS} from '@libs/API/types';
import type {ApiCommand} from '@libs/API/types';
import {translateLocal} from '@libs/Localize';
import {rand64} from '@libs/NumberUtils';
import {getLoginsByAccountIDs} from '@libs/PersonalDetailsUtils';
import {
getOriginalMessage,
getReportActionHtml,
getReportActionMessage,
getReportActionText,
getReportPreviewAction,
getSortedReportActions,
isActionableTrackExpense,
isActionOfType,
isMoneyRequestAction,
} from '@libs/ReportActionsUtils';
import {buildOptimisticIOUReport, buildOptimisticIOUReportAction, buildTransactionThread, createDraftTransactionAndNavigateToParticipantSelector, isIOUReport} from '@libs/ReportUtils';
import type {OptimisticChatReport} from '@libs/ReportUtils';
import {buildOptimisticTransaction, getValidWaypoints, isDistanceRequest as isDistanceRequestUtil} from '@libs/TransactionUtils';
import CONST from '@src/CONST';
import type {IOUAction} from '@src/CONST';
import OnyxUpdateManager from '@src/libs/actions/OnyxUpdateManager';
import * as API from '@src/libs/API';
import DateUtils from '@src/libs/DateUtils';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {Policy, Report} from '@src/types/onyx';
import type {Participant, ReportCollectionDataSet} from '@src/types/onyx/Report';
import type {ReportActions, ReportActionsCollectionDataSet} from '@src/types/onyx/ReportAction';
import type ReportAction from '@src/types/onyx/ReportAction';
import type {TransactionCollectionDataSet} from '@src/types/onyx/Transaction';
import type Transaction from '@src/types/onyx/Transaction';
import {toCollectionDataSet} from '@src/types/utils/CollectionDataSet';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import * as InvoiceData from '../data/Invoice';
import type {InvoiceTestData} from '../data/Invoice';
import createRandomPolicy, {createCategoryTaxExpenseRules} from '../utils/collections/policies';
import createRandomPolicyCategories from '../utils/collections/policyCategory';
import createRandomReport from '../utils/collections/reports';
import createRandomTransaction from '../utils/collections/transaction';
import PusherHelper from '../utils/PusherHelper';
import {getGlobalFetchMock, getOnyxData, setPersonalDetails, signInWithTestUser} from '../utils/TestHelper';
import type {MockFetch} from '../utils/TestHelper';
import waitForBatchedUpdates from '../utils/waitForBatchedUpdates';
import waitForNetworkPromises from '../utils/waitForNetworkPromises';
const topMostReportID = '23423423';
jest.mock('@src/libs/Navigation/Navigation', () => ({
navigate: jest.fn(),
dismissModal: jest.fn(),
dismissModalWithReport: jest.fn(),
goBack: jest.fn(),
getTopmostReportId: jest.fn(() => topMostReportID),
setNavigationActionToMicrotaskQueue: jest.fn(),
}));
jest.mock('@src/libs/actions/Report', () => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const originalModule = jest.requireActual('@src/libs/actions/Report');
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return {
...originalModule,
notifyNewAction: jest.fn(),
};
});
jest.mock('@libs/Navigation/helpers/isSearchTopmostFullScreenRoute', () => jest.fn());
const CARLOS_EMAIL = '[email protected]';
const CARLOS_ACCOUNT_ID = 1;
const CARLOS_PARTICIPANT: Participant = {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.ALWAYS, role: 'member'};
const JULES_EMAIL = '[email protected]';
const JULES_ACCOUNT_ID = 2;
const JULES_PARTICIPANT: Participant = {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.ALWAYS, role: 'member'};
const RORY_EMAIL = '[email protected]';
const RORY_ACCOUNT_ID = 3;
const RORY_PARTICIPANT: Participant = {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.ALWAYS, role: 'admin'};
const VIT_EMAIL = '[email protected]';
const VIT_ACCOUNT_ID = 4;
const VIT_PARTICIPANT: Participant = {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.ALWAYS, role: 'member'};
OnyxUpdateManager();
describe('actions/IOU', () => {
beforeAll(() => {
Onyx.init({
keys: ONYXKEYS,
initialKeyStates: {
[ONYXKEYS.SESSION]: {accountID: RORY_ACCOUNT_ID, email: RORY_EMAIL},
[ONYXKEYS.PERSONAL_DETAILS_LIST]: {[RORY_ACCOUNT_ID]: {accountID: RORY_ACCOUNT_ID, login: RORY_EMAIL}},
},
});
});
let mockFetch: MockFetch;
beforeEach(() => {
jest.clearAllTimers();
global.fetch = getGlobalFetchMock();
mockFetch = fetch as MockFetch;
return Onyx.clear().then(waitForBatchedUpdates);
});
describe('trackExpense', () => {
it('category a distance expense of selfDM report', async () => {
/*
* This step simulates the following steps:
* - Go to self DM
* - Track a distance expense
* - Go to Troubleshoot > Clear cache and restart > Reset and refresh
* - Go to self DM
* - Click Categorize it (click Upgrade if there is no workspace)
* - Select category and submit the expense to the workspace
*/
// Given a participant of the report
const participant = {login: CARLOS_EMAIL, accountID: CARLOS_ACCOUNT_ID};
// Given valid waypoints of the transaction
const fakeWayPoints = {
waypoint0: {
keyForList: '88 Kearny Street_1735023533854',
lat: 37.7886378,
lng: -122.4033442,
address: '88 Kearny Street, San Francisco, CA, USA',
name: '88 Kearny Street',
},
waypoint1: {
keyForList: 'Golden Gate Bridge Vista Point_1735023537514',
lat: 37.8077876,
lng: -122.4752007,
address: 'Golden Gate Bridge Vista Point, San Francisco, CA, USA',
name: 'Golden Gate Bridge Vista Point',
},
};
// Given a selfDM report
const selfDMReport = {
...createRandomReport(1),
chatType: CONST.REPORT.CHAT_TYPE.SELF_DM,
};
// Given a policyExpenseChat report
const expenseReport = {
...createRandomReport(1),
chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT,
};
// Given policy categories and a policy
const fakeCategories = createRandomPolicyCategories(3);
const fakePolicy = createRandomPolicy(1);
// Given a transaction with a distance request type and valid waypoints
const fakeTransaction = {
...createRandomTransaction(1),
iouRequestType: CONST.IOU.REQUEST_TYPE.DISTANCE,
comment: {
...createRandomTransaction(1).comment,
type: CONST.TRANSACTION.TYPE.CUSTOM_UNIT,
customUnit: {
name: CONST.CUSTOM_UNITS.NAME_DISTANCE,
},
waypoints: fakeWayPoints,
},
};
// When the transaction is saved to draft before being submitted
await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${fakeTransaction.transactionID}`, fakeTransaction);
mockFetch?.pause?.();
// When the user submits the transaction to the selfDM report
trackExpense({
report: selfDMReport,
isDraftPolicy: true,
action: CONST.IOU.ACTION.CREATE,
participantParams: {
payeeEmail: participant.login,
payeeAccountID: participant.accountID,
participant,
},
transactionParams: {
amount: fakeTransaction.amount,
currency: fakeTransaction.currency,
created: format(new Date(), CONST.DATE.FNS_FORMAT_STRING),
merchant: fakeTransaction.merchant,
billable: false,
validWaypoints: fakeWayPoints,
actionableWhisperReportActionID: fakeTransaction?.actionableWhisperReportActionID,
linkedTrackedExpenseReportAction: fakeTransaction?.linkedTrackedExpenseReportAction,
linkedTrackedExpenseReportID: fakeTransaction?.linkedTrackedExpenseReportID,
customUnitRateID: CONST.CUSTOM_UNITS.FAKE_P2P_ID,
},
});
await waitForBatchedUpdates();
await mockFetch?.resume?.();
// Given transaction after tracked expense
const transaction = await new Promise<OnyxEntry<Transaction>>((resolve) => {
const connection = Onyx.connect({
key: ONYXKEYS.COLLECTION.TRANSACTION,
waitForCollectionCallback: true,
callback: (transactions) => {
Onyx.disconnect(connection);
const trackedExpenseTransaction = Object.values(transactions ?? {}).at(0);
// Then the transaction must remain a distance request
const isDistanceRequest = isDistanceRequestUtil(trackedExpenseTransaction);
expect(isDistanceRequest).toBe(true);
resolve(trackedExpenseTransaction);
},
});
});
// Given all report actions of the selfDM report
const allReportActions = await new Promise<OnyxCollection<ReportActions>>((resolve) => {
const connection = Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT_ACTIONS,
waitForCollectionCallback: true,
callback: (reportActions) => {
Onyx.disconnect(connection);
resolve(reportActions);
},
});
});
// Then the selfDM report should have an actionable track expense whisper action and an IOU action
const selfDMReportActions = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${selfDMReport.reportID}`];
expect(Object.values(selfDMReportActions ?? {}).length).toBe(2);
// When the cache is cleared before categorizing the tracked expense
await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction?.transactionID}`, {
iouRequestType: null,
});
// When the transaction is saved to draft by selecting a category in the selfDM report
const reportActionableTrackExpense = Object.values(selfDMReportActions ?? {}).find((reportAction) => isActionableTrackExpense(reportAction));
createDraftTransactionAndNavigateToParticipantSelector(
transaction?.transactionID,
selfDMReport.reportID,
CONST.IOU.ACTION.CATEGORIZE,
reportActionableTrackExpense?.reportActionID,
);
await waitForBatchedUpdates();
// Then the transaction draft should be saved successfully
const allTransactionsDraft = await new Promise<OnyxCollection<Transaction>>((resolve) => {
const connection = Onyx.connect({
key: ONYXKEYS.COLLECTION.TRANSACTION_DRAFT,
waitForCollectionCallback: true,
callback: (transactionDrafts) => {
Onyx.disconnect(connection);
resolve(transactionDrafts);
},
});
});
const transactionDraft = allTransactionsDraft?.[`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transaction?.transactionID}`];
// When the user confirms the category for the tracked expense
trackExpense({
report: expenseReport,
isDraftPolicy: false,
action: CONST.IOU.ACTION.CATEGORIZE,
participantParams: {
payeeEmail: participant.login,
payeeAccountID: participant.accountID,
participant: {...participant, isPolicyExpenseChat: true},
},
policyParams: {
policy: fakePolicy,
policyCategories: fakeCategories,
},
transactionParams: {
amount: transactionDraft?.amount ?? fakeTransaction.amount,
currency: transactionDraft?.currency ?? fakeTransaction.currency,
created: format(new Date(), CONST.DATE.FNS_FORMAT_STRING),
merchant: transactionDraft?.merchant ?? fakeTransaction.merchant,
category: Object.keys(fakeCategories).at(0) ?? '',
validWaypoints: Object.keys(transactionDraft?.comment?.waypoints ?? {}).length ? getValidWaypoints(transactionDraft?.comment?.waypoints, true) : undefined,
actionableWhisperReportActionID: transactionDraft?.actionableWhisperReportActionID,
linkedTrackedExpenseReportAction: transactionDraft?.linkedTrackedExpenseReportAction,
linkedTrackedExpenseReportID: transactionDraft?.linkedTrackedExpenseReportID,
customUnitRateID: CONST.CUSTOM_UNITS.FAKE_P2P_ID,
},
});
await waitForBatchedUpdates();
await mockFetch?.resume?.();
// Then the expense should be categorized successfully
await new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: ONYXKEYS.COLLECTION.TRANSACTION,
waitForCollectionCallback: true,
callback: (transactions) => {
Onyx.disconnect(connection);
const categorizedTransaction = transactions?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction?.transactionID}`];
// Then the transaction must remain a distance request, ensuring that the optimistic data is correctly built and the transaction type remains accurate.
const isDistanceRequest = isDistanceRequestUtil(categorizedTransaction);
expect(isDistanceRequest).toBe(true);
// Then the transaction category must match the original category
expect(categorizedTransaction?.category).toBe(Object.keys(fakeCategories).at(0) ?? '');
resolve();
},
});
});
});
});
describe('requestMoney', () => {
it('creates new chat if needed', () => {
const amount = 10000;
const comment = 'Giv money plz';
const merchant = 'KFC';
let iouReportID: string | undefined;
let createdAction: OnyxEntry<ReportAction>;
let iouAction: OnyxEntry<ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.IOU>>;
let transactionID: string | undefined;
let transactionThread: OnyxEntry<Report>;
let transactionThreadCreatedAction: OnyxEntry<ReportAction>;
mockFetch?.pause?.();
requestMoney({
report: {reportID: ''},
participantParams: {
payeeEmail: RORY_EMAIL,
payeeAccountID: RORY_ACCOUNT_ID,
participant: {login: CARLOS_EMAIL, accountID: CARLOS_ACCOUNT_ID},
},
transactionParams: {
amount,
attendees: [],
currency: CONST.CURRENCY.USD,
created: '',
merchant,
comment,
},
});
return waitForBatchedUpdates()
.then(
() =>
new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT,
waitForCollectionCallback: true,
callback: (allReports) => {
Onyx.disconnect(connection);
// A chat report, a transaction thread, and an iou report should be created
const chatReports = Object.values(allReports ?? {}).filter((report) => report?.type === CONST.REPORT.TYPE.CHAT);
const iouReports = Object.values(allReports ?? {}).filter((report) => report?.type === CONST.REPORT.TYPE.IOU);
expect(Object.keys(chatReports).length).toBe(2);
expect(Object.keys(iouReports).length).toBe(1);
const chatReport = chatReports.at(0);
const transactionThreadReport = chatReports.at(1);
const iouReport = iouReports.at(0);
iouReportID = iouReport?.reportID;
transactionThread = transactionThreadReport;
expect(iouReport?.participants).toEqual({
[RORY_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN},
[CARLOS_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN},
});
// They should be linked together
expect(chatReport?.participants).toEqual({[RORY_ACCOUNT_ID]: RORY_PARTICIPANT, [CARLOS_ACCOUNT_ID]: CARLOS_PARTICIPANT});
expect(chatReport?.iouReportID).toBe(iouReport?.reportID);
resolve();
},
});
}),
)
.then(
() =>
new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReportID}`,
waitForCollectionCallback: false,
callback: (reportActionsForIOUReport) => {
Onyx.disconnect(connection);
// The IOU report should have a CREATED action and IOU action
expect(Object.values(reportActionsForIOUReport ?? {}).length).toBe(2);
const createdActions = Object.values(reportActionsForIOUReport ?? {}).filter(
(reportAction) => reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED,
);
const iouActions = Object.values(reportActionsForIOUReport ?? {}).filter(
(reportAction): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.IOU> => isMoneyRequestAction(reportAction),
);
expect(Object.values(createdActions).length).toBe(1);
expect(Object.values(iouActions).length).toBe(1);
createdAction = createdActions?.at(0);
iouAction = iouActions?.at(0);
const originalMessage = isMoneyRequestAction(iouAction) ? getOriginalMessage(iouAction) : undefined;
// The CREATED action should not be created after the IOU action
expect(Date.parse(createdAction?.created ?? '')).toBeLessThan(Date.parse(iouAction?.created ?? ''));
// The IOUReportID should be correct
expect(originalMessage?.IOUReportID).toBe(iouReportID);
// The comment should be included in the IOU action
expect(originalMessage?.comment).toBe(comment);
// The amount in the IOU action should be correct
expect(originalMessage?.amount).toBe(amount);
// The IOU type should be correct
expect(originalMessage?.type).toBe(CONST.IOU.REPORT_ACTION_TYPE.CREATE);
// Both actions should be pending
expect(createdAction?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD);
expect(iouAction?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD);
resolve();
},
});
}),
)
.then(
() =>
new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThread?.reportID}`,
waitForCollectionCallback: false,
callback: (reportActionsForTransactionThread) => {
Onyx.disconnect(connection);
// The transaction thread should have a CREATED action
expect(Object.values(reportActionsForTransactionThread ?? {}).length).toBe(1);
const createdActions = Object.values(reportActionsForTransactionThread ?? {}).filter(
(reportAction) => reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED,
);
expect(Object.values(createdActions).length).toBe(1);
transactionThreadCreatedAction = createdActions.at(0);
expect(transactionThreadCreatedAction?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD);
resolve();
},
});
}),
)
.then(
() =>
new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: ONYXKEYS.COLLECTION.TRANSACTION,
waitForCollectionCallback: true,
callback: (allTransactions) => {
Onyx.disconnect(connection);
// There should be one transaction
expect(Object.values(allTransactions ?? {}).length).toBe(1);
const transaction = Object.values(allTransactions ?? []).find((t) => !isEmptyObject(t));
transactionID = transaction?.transactionID;
// The transaction should be attached to the IOU report
expect(transaction?.reportID).toBe(iouReportID);
// Its amount should match the amount of the expense
expect(transaction?.amount).toBe(amount);
// The comment should be correct
expect(transaction?.comment?.comment).toBe(comment);
// It should be pending
expect(transaction?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD);
// The transactionID on the iou action should match the one from the transactions collection
expect(iouAction && getOriginalMessage(iouAction)?.IOUTransactionID).toBe(transactionID);
expect(transaction?.merchant).toBe(merchant);
resolve();
},
});
}),
)
.then(mockFetch?.resume)
.then(
() =>
new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReportID}`,
waitForCollectionCallback: false,
callback: (reportActionsForIOUReport) => {
Onyx.disconnect(connection);
expect(Object.values(reportActionsForIOUReport ?? {}).length).toBe(2);
Object.values(reportActionsForIOUReport ?? {}).forEach((reportAction) => expect(reportAction?.pendingAction).toBeFalsy());
resolve();
},
});
}),
)
.then(
() =>
new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`,
waitForCollectionCallback: false,
callback: (transaction) => {
Onyx.disconnect(connection);
expect(transaction?.pendingAction).toBeFalsy();
resolve();
},
});
}),
);
});
it('updates existing chat report if there is one', () => {
const amount = 10000;
const comment = 'Giv money plz';
let chatReport: Report = {
reportID: '1234',
type: CONST.REPORT.TYPE.CHAT,
participants: {[RORY_ACCOUNT_ID]: RORY_PARTICIPANT, [CARLOS_ACCOUNT_ID]: CARLOS_PARTICIPANT},
};
const createdAction: ReportAction = {
reportActionID: rand64(),
actionName: CONST.REPORT.ACTIONS.TYPE.CREATED,
created: DateUtils.getDBTime(),
};
let iouReportID: string | undefined;
let iouAction: OnyxEntry<ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.IOU>>;
let iouCreatedAction: OnyxEntry<ReportAction>;
let transactionID: string | undefined;
mockFetch?.pause?.();
return Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${chatReport.reportID}`, chatReport)
.then(() =>
Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport.reportID}`, {
[createdAction.reportActionID]: createdAction,
}),
)
.then(() => {
requestMoney({
report: chatReport,
participantParams: {
payeeEmail: RORY_EMAIL,
payeeAccountID: RORY_ACCOUNT_ID,
participant: {login: CARLOS_EMAIL, accountID: CARLOS_ACCOUNT_ID},
},
transactionParams: {
amount,
attendees: [],
currency: CONST.CURRENCY.USD,
created: '',
merchant: '',
comment,
},
});
return waitForBatchedUpdates();
})
.then(
() =>
new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT,
waitForCollectionCallback: true,
callback: (allReports) => {
Onyx.disconnect(connection);
// The same chat report should be reused, a transaction thread and an IOU report should be created
expect(Object.values(allReports ?? {}).length).toBe(3);
expect(Object.values(allReports ?? {}).find((report) => report?.type === CONST.REPORT.TYPE.CHAT)?.reportID).toBe(chatReport.reportID);
chatReport = Object.values(allReports ?? {}).find((report) => report?.type === CONST.REPORT.TYPE.CHAT) ?? chatReport;
const iouReport = Object.values(allReports ?? {}).find((report) => report?.type === CONST.REPORT.TYPE.IOU);
iouReportID = iouReport?.reportID;
expect(iouReport?.participants).toEqual({
[RORY_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN},
[CARLOS_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN},
});
// They should be linked together
expect(chatReport.iouReportID).toBe(iouReportID);
resolve();
},
});
}),
)
.then(
() =>
new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReportID}`,
waitForCollectionCallback: false,
callback: (allIOUReportActions) => {
Onyx.disconnect(connection);
iouCreatedAction = Object.values(allIOUReportActions ?? {}).find((reportAction) => reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED);
iouAction = Object.values(allIOUReportActions ?? {}).find((reportAction): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.IOU> =>
isMoneyRequestAction(reportAction),
);
const originalMessage = iouAction ? getOriginalMessage(iouAction) : null;
// The CREATED action should not be created after the IOU action
expect(Date.parse(iouCreatedAction?.created ?? '')).toBeLessThan(Date.parse(iouAction?.created ?? ''));
// The IOUReportID should be correct
expect(originalMessage?.IOUReportID).toBe(iouReportID);
// The comment should be included in the IOU action
expect(originalMessage?.comment).toBe(comment);
// The amount in the IOU action should be correct
expect(originalMessage?.amount).toBe(amount);
// The IOU action type should be correct
expect(originalMessage?.type).toBe(CONST.IOU.REPORT_ACTION_TYPE.CREATE);
// The IOU action should be pending
expect(iouAction?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD);
resolve();
},
});
}),
)
.then(
() =>
new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: ONYXKEYS.COLLECTION.TRANSACTION,
waitForCollectionCallback: true,
callback: (allTransactions) => {
Onyx.disconnect(connection);
// There should be one transaction
expect(Object.values(allTransactions ?? {}).length).toBe(1);
const transaction = Object.values(allTransactions ?? {}).find((t) => !isEmptyObject(t));
transactionID = transaction?.transactionID;
const originalMessage = iouAction ? getOriginalMessage(iouAction) : null;
// The transaction should be attached to the IOU report
expect(transaction?.reportID).toBe(iouReportID);
// Its amount should match the amount of the expense
expect(transaction?.amount).toBe(amount);
// The comment should be correct
expect(transaction?.comment?.comment).toBe(comment);
expect(transaction?.merchant).toBe(CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT);
// It should be pending
expect(transaction?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD);
// The transactionID on the iou action should match the one from the transactions collection
expect(originalMessage?.IOUTransactionID).toBe(transactionID);
resolve();
},
});
}),
)
.then(mockFetch?.resume)
.then(waitForBatchedUpdates)
.then(
() =>
new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReportID}`,
waitForCollectionCallback: false,
callback: (reportActionsForIOUReport) => {
Onyx.disconnect(connection);
expect(Object.values(reportActionsForIOUReport ?? {}).length).toBe(2);
Object.values(reportActionsForIOUReport ?? {}).forEach((reportAction) => expect(reportAction?.pendingAction).toBeFalsy());
resolve();
},
});
}),
)
.then(
() =>
new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`,
callback: (transaction) => {
Onyx.disconnect(connection);
expect(transaction?.pendingAction).toBeFalsy();
resolve();
},
});
}),
);
});
it('updates existing IOU report if there is one', () => {
const amount = 10000;
const comment = 'Giv money plz';
const chatReportID = '1234';
const iouReportID = '5678';
let chatReport: OnyxEntry<Report> = {
reportID: chatReportID,
type: CONST.REPORT.TYPE.CHAT,
iouReportID,
participants: {[RORY_ACCOUNT_ID]: RORY_PARTICIPANT, [CARLOS_ACCOUNT_ID]: CARLOS_PARTICIPANT},
};
const createdAction: ReportAction = {
reportActionID: rand64(),
actionName: CONST.REPORT.ACTIONS.TYPE.CREATED,
created: DateUtils.getDBTime(),
};
const existingTransaction: Transaction = {
transactionID: rand64(),
attendees: [{email: '[email protected]'}],
amount: 1000,
comment: {
comment: 'Existing transaction',
},
created: DateUtils.getDBTime(),
currency: CONST.CURRENCY.USD,
merchant: '',
reportID: '',
};
let iouReport: OnyxEntry<Report> = {
reportID: iouReportID,
chatReportID,
type: CONST.REPORT.TYPE.IOU,
ownerAccountID: RORY_ACCOUNT_ID,
managerID: CARLOS_ACCOUNT_ID,
currency: CONST.CURRENCY.USD,
total: existingTransaction.amount,
};
const iouAction: OnyxEntry<ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.IOU>> = {
reportActionID: rand64(),
actionName: CONST.REPORT.ACTIONS.TYPE.IOU,
actorAccountID: RORY_ACCOUNT_ID,
created: DateUtils.getDBTime(),
originalMessage: {
IOUReportID: iouReportID,
IOUTransactionID: existingTransaction.transactionID,
amount: existingTransaction.amount,
currency: CONST.CURRENCY.USD,
type: CONST.IOU.REPORT_ACTION_TYPE.CREATE,
participantAccountIDs: [RORY_ACCOUNT_ID, CARLOS_ACCOUNT_ID],
},
};
let newIOUAction: OnyxEntry<ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.IOU>>;
let newTransaction: OnyxEntry<Transaction>;
mockFetch?.pause?.();
return Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${chatReportID}`, chatReport)
.then(() => Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${iouReportID}`, iouReport ?? null))
.then(() =>
Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReportID}`, {
[createdAction.reportActionID]: createdAction,
[iouAction.reportActionID]: iouAction,
}),
)
.then(() => Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${existingTransaction.transactionID}`, existingTransaction))
.then(() => {
if (chatReport) {
requestMoney({
report: chatReport,
participantParams: {
payeeEmail: RORY_EMAIL,
payeeAccountID: RORY_ACCOUNT_ID,
participant: {login: CARLOS_EMAIL, accountID: CARLOS_ACCOUNT_ID},
},
transactionParams: {
amount,
attendees: [],
currency: CONST.CURRENCY.USD,
created: '',
merchant: '',
comment,
},
});
}
return waitForBatchedUpdates();
})
.then(
() =>
new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT,
waitForCollectionCallback: true,
callback: (allReports) => {
Onyx.disconnect(connection);
// No new reports should be created
expect(Object.values(allReports ?? {}).length).toBe(3);
expect(Object.values(allReports ?? {}).find((report) => report?.reportID === chatReportID)).toBeTruthy();
expect(Object.values(allReports ?? {}).find((report) => report?.reportID === iouReportID)).toBeTruthy();
chatReport = Object.values(allReports ?? {}).find((report) => report?.type === CONST.REPORT.TYPE.CHAT);
iouReport = Object.values(allReports ?? {}).find((report) => report?.type === CONST.REPORT.TYPE.IOU);
// The total on the iou report should be updated
expect(iouReport?.total).toBe(11000);
resolve();
},
});
}),
)
.then(
() =>
new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReportID}`,
waitForCollectionCallback: false,
callback: (reportActionsForIOUReport) => {
Onyx.disconnect(connection);
expect(Object.values(reportActionsForIOUReport ?? {}).length).toBe(3);
newIOUAction = Object.values(reportActionsForIOUReport ?? {}).find(
(reportAction): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.IOU> =>
reportAction?.reportActionID !== createdAction.reportActionID && reportAction?.reportActionID !== iouAction?.reportActionID,
);
const newOriginalMessage = newIOUAction ? getOriginalMessage(newIOUAction) : null;
// The IOUReportID should be correct
expect(getOriginalMessage(iouAction)?.IOUReportID).toBe(iouReportID);
// The comment should be included in the IOU action
expect(newOriginalMessage?.comment).toBe(comment);
// The amount in the IOU action should be correct
expect(newOriginalMessage?.amount).toBe(amount);
// The type of the IOU action should be correct
expect(newOriginalMessage?.type).toBe(CONST.IOU.REPORT_ACTION_TYPE.CREATE);
// The IOU action should be pending
expect(newIOUAction?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD);
resolve();
},
});
}),
)
.then(
() =>
new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: ONYXKEYS.COLLECTION.TRANSACTION,
waitForCollectionCallback: true,
callback: (allTransactions) => {
Onyx.disconnect(connection);
// There should be two transactions
expect(Object.values(allTransactions ?? {}).length).toBe(2);
newTransaction = Object.values(allTransactions ?? {}).find((transaction) => transaction?.transactionID !== existingTransaction.transactionID);
expect(newTransaction?.reportID).toBe(iouReportID);
expect(newTransaction?.amount).toBe(amount);
expect(newTransaction?.comment?.comment).toBe(comment);
expect(newTransaction?.merchant).toBe(CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT);
expect(newTransaction?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD);
// The transactionID on the iou action should match the one from the transactions collection
expect(isMoneyRequestAction(newIOUAction) ? getOriginalMessage(newIOUAction)?.IOUTransactionID : undefined).toBe(newTransaction?.transactionID);
resolve();
},
});
}),
)
.then(mockFetch?.resume)
.then(waitForNetworkPromises)
.then(
() =>
new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReportID}`,
waitForCollectionCallback: false,
callback: (reportActionsForIOUReport) => {
Onyx.disconnect(connection);
expect(Object.values(reportActionsForIOUReport ?? {}).length).toBe(3);
Object.values(reportActionsForIOUReport ?? {}).forEach((reportAction) => expect(reportAction?.pendingAction).toBeFalsy());
resolve();
},
});
}),
)
.then(
() =>
new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: ONYXKEYS.COLLECTION.TRANSACTION,
waitForCollectionCallback: true,
callback: (allTransactions) => {
Onyx.disconnect(connection);
Object.values(allTransactions ?? {}).forEach((transaction) => expect(transaction?.pendingAction).toBeFalsy());
resolve();
},
});
}),
);
});
it('correctly implements RedBrickRoad error handling', () => {
const amount = 10000;
const comment = 'Giv money plz';
let chatReportID: string | undefined;
let iouReportID: string | undefined;
let createdAction: OnyxEntry<ReportAction>;
let iouAction: OnyxEntry<ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.IOU>>;
let transactionID: string | undefined;
let transactionThreadReport: OnyxEntry<Report>;
let transactionThreadAction: OnyxEntry<ReportAction>;
mockFetch?.pause?.();
requestMoney({
report: {reportID: ''},
participantParams: {
payeeEmail: RORY_EMAIL,
payeeAccountID: RORY_ACCOUNT_ID,
participant: {login: CARLOS_EMAIL, accountID: CARLOS_ACCOUNT_ID},
},
transactionParams: {
amount,
attendees: [],
currency: CONST.CURRENCY.USD,
created: '',
merchant: '',
comment,
},
});
return (
waitForBatchedUpdates()
.then(
() =>
new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT,
waitForCollectionCallback: true,
callback: (allReports) => {
Onyx.disconnect(connection);
// A chat report, transaction thread and an iou report should be created
const chatReports = Object.values(allReports ?? {}).filter((report) => report?.type === CONST.REPORT.TYPE.CHAT);
const iouReports = Object.values(allReports ?? {}).filter((report) => report?.type === CONST.REPORT.TYPE.IOU);
expect(Object.values(chatReports).length).toBe(2);
expect(Object.values(iouReports).length).toBe(1);
const chatReport = chatReports.at(0);
chatReportID = chatReport?.reportID;
transactionThreadReport = chatReports.at(1);
const iouReport = iouReports.at(0);
iouReportID = iouReport?.reportID;
expect(chatReport?.participants).toStrictEqual({[RORY_ACCOUNT_ID]: RORY_PARTICIPANT, [CARLOS_ACCOUNT_ID]: CARLOS_PARTICIPANT});
// They should be linked together
expect(chatReport?.participants).toStrictEqual({[RORY_ACCOUNT_ID]: RORY_PARTICIPANT, [CARLOS_ACCOUNT_ID]: CARLOS_PARTICIPANT});
expect(chatReport?.iouReportID).toBe(iouReport?.reportID);
resolve();
},
});
}),
)
.then(
() =>
new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReportID}`,
waitForCollectionCallback: false,
callback: (reportActionsForIOUReport) => {
Onyx.disconnect(connection);
// The chat report should have a CREATED action and IOU action
expect(Object.values(reportActionsForIOUReport ?? {}).length).toBe(2);
const createdActions =
Object.values(reportActionsForIOUReport ?? {}).filter((reportAction) => reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED) ?? null;
const iouActions =
Object.values(reportActionsForIOUReport ?? {}).filter((reportAction): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.IOU> =>
isMoneyRequestAction(reportAction),
) ?? null;
expect(Object.values(createdActions).length).toBe(1);
expect(Object.values(iouActions).length).toBe(1);
createdAction = createdActions.at(0);
iouAction = iouActions.at(0);