-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathTrackExpenseTest.ts
More file actions
3097 lines (2776 loc) · 142 KB
/
Copy pathTrackExpenseTest.ts
File metadata and controls
3097 lines (2776 loc) · 142 KB
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
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import type {RenderAPI} from '@testing-library/react-native';
import {
convertBulkTrackedExpensesToIOU,
deleteTrackExpense,
getDeleteTrackExpenseInformation,
getTrackExpenseInformation,
hasManualDistanceOverride,
trackExpense,
} from '@libs/actions/IOU/TrackExpense';
import initOnyxDerivedValues from '@libs/actions/OnyxDerived';
import {addComment, openReport} from '@libs/actions/Report';
import {subscribeToUserEvents} from '@libs/actions/User';
import {WRITE_COMMANDS} from '@libs/API/types';
import {getLoginsByAccountIDs} from '@libs/PersonalDetailsUtils';
import type * as PolicyUtils from '@libs/PolicyUtils';
import {getOriginalMessage, isActionableTrackExpense, isMoneyRequestAction} from '@libs/ReportActionsUtils';
import type {OptimisticChatReport} from '@libs/ReportUtils';
import {createDraftTransactionAndNavigateToParticipantSelector} from '@libs/ReportUtils';
import SidebarUtils from '@libs/SidebarUtils';
import {getValidWaypoints, isDistanceRequest as isDistanceRequestUtil} from '@libs/TransactionUtils';
import CONST from '@src/CONST';
import IntlStore from '@src/languages/IntlStore';
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 {IntroSelected, PersonalDetailsList, Policy, Report} from '@src/types/onyx';
import type {Accountant} from '@src/types/onyx/IOU';
import type ReportAction from '@src/types/onyx/ReportAction';
import type {ReportActions} from '@src/types/onyx/ReportAction';
import type Transaction from '@src/types/onyx/Transaction';
import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
import {format} from 'date-fns';
import Onyx from 'react-native-onyx';
import type {MockFetch} from '../../utils/TestHelper';
import createRandomPolicy from '../../utils/collections/policies';
import createRandomPolicyCategories from '../../utils/collections/policyCategory';
import {createRandomReport} from '../../utils/collections/reports';
import createRandomTransaction, {createRandomDistanceRequestTransaction} from '../../utils/collections/transaction';
import getOnyxValue from '../../utils/getOnyxValue';
import initCurrencyListContext from '../../utils/initCurrencyListContext';
import PusherHelper from '../../utils/PusherHelper';
import * as TestHelper from '../../utils/TestHelper';
import {getGlobalFetchMock, getOnyxData, setPersonalDetails, signInWithTestUser} from '../../utils/TestHelper';
import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates';
jest.mock('@src/libs/Navigation/Navigation', () => ({
navigate: jest.fn(),
dismissModal: jest.fn(),
dismissToPreviousRHP: jest.fn(),
dismissToSuperWideRHP: jest.fn(),
navigateBackToLastSuperWideRHPScreen: jest.fn(),
dismissModalWithReport: jest.fn(),
goBack: jest.fn(),
getTopmostReportId: jest.fn(() => '23423423'),
setNavigationActionToMicrotaskQueue: jest.fn(),
removeScreenByKey: jest.fn(),
isNavigationReady: jest.fn(() => Promise.resolve()),
getReportRouteByID: jest.fn(),
getActiveRouteWithoutParams: jest.fn(),
getActiveRoute: jest.fn(),
navigationRef: {
getRootState: jest.fn(),
},
}));
jest.mock('@react-navigation/native');
jest.mock('@src/libs/actions/Report', () => {
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());
jest.mock('@libs/Navigation/helpers/isReportTopmostSplitNavigator', () => jest.fn());
jest.mock('@hooks/useCardFeedsForDisplay', () => jest.fn(() => ({defaultCardFeed: null, cardFeedsByPolicy: {}})));
jest.mock('@expensify/react-native-hybrid-app', () => ({
__esModule: true,
default: {
isHybridApp: jest.fn(),
},
}));
jest.mock('@libs/PolicyUtils', () => ({
...jest.requireActual<typeof PolicyUtils>('@libs/PolicyUtils'),
isPaidGroupPolicy: jest.fn().mockReturnValue(true),
isPolicyOwner: jest.fn().mockImplementation((policy?: OnyxEntry<Policy>, currentUserAccountID?: number) => !!currentUserAccountID && policy?.ownerAccountID === currentUserAccountID),
}));
const CARLOS_EMAIL = 'cmartins@expensifail.com';
const CARLOS_ACCOUNT_ID = 1;
const RORY_EMAIL = 'rory@expensifail.com';
const RORY_ACCOUNT_ID = 3;
const VIT_EMAIL = 'vit@expensifail.com';
const VIT_ACCOUNT_ID = 4;
const TEST_INTRO_SELECTED: IntroSelected = {
choice: CONST.ONBOARDING_CHOICES.SUBMIT,
isInviteOnboardingComplete: false,
};
OnyxUpdateManager();
describe('actions/IOU/TrackExpense', () => {
let mockFetch: MockFetch;
let currencyListProvider: RenderAPI;
beforeAll(() => {
Onyx.init({keys: ONYXKEYS});
initOnyxDerivedValues();
IntlStore.load(CONST.LOCALES.EN);
return waitForBatchedUpdates();
});
beforeEach(async () => {
jest.clearAllTimers();
global.fetch = getGlobalFetchMock();
mockFetch = fetch as MockFetch;
await Onyx.clear();
currencyListProvider = await initCurrencyListContext({
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},
},
},
});
});
afterEach(async () => {
currencyListProvider.unmount();
await mockFetch?.resume?.();
await waitForBatchedUpdates();
jest.clearAllMocks();
});
describe('trackExpense', () => {
it('makes a hidden Self DM visible when tracking a distance expense optimistically', async () => {
const selfDMReport: Report = {
...createRandomReport(1, CONST.REPORT.CHAT_TYPE.SELF_DM),
type: CONST.REPORT.TYPE.CHAT,
// createRandomReport randomizes isPinned/isOwnPolicyExpenseChat; either being true would force a hidden
// report to display in the LHN (shouldOverrideHidden), so pin them down to keep this test deterministic.
isPinned: false,
isOwnPolicyExpenseChat: false,
participants: {
[RORY_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN},
},
};
const selfDMReportKey = `${ONYXKEYS.COLLECTION.REPORT}${selfDMReport.reportID}`;
const distanceTransaction = createRandomDistanceRequestTransaction(1, true);
const recentWaypoints = (await getOnyxValue(ONYXKEYS.NVP_RECENT_WAYPOINTS)) ?? [];
const hiddenReportsToDisplay = SidebarUtils.getReportsToDisplayInLHN({
currentReportId: undefined,
reports: {[selfDMReportKey]: selfDMReport},
betas: [],
priorityMode: CONST.PRIORITY_MODE.DEFAULT,
draftComments: {},
transactionViolations: {},
transactions: {},
isOffline: false,
currentUserLogin: RORY_EMAIL,
currentUserAccountID: RORY_ACCOUNT_ID,
reportNameValuePairs: {},
reportAttributes: undefined,
conciergeReportID: undefined,
});
await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${distanceTransaction.transactionID}`, distanceTransaction);
mockFetch?.pause?.();
trackExpense({
report: selfDMReport,
isDraftPolicy: true,
action: CONST.IOU.ACTION.CREATE,
participantParams: {
payeeEmail: RORY_EMAIL,
payeeAccountID: RORY_ACCOUNT_ID,
participant: {accountID: RORY_ACCOUNT_ID},
},
transactionParams: {
amount: distanceTransaction.amount,
currency: distanceTransaction.currency,
created: format(new Date(), CONST.DATE.FNS_FORMAT_STRING),
merchant: distanceTransaction.merchant,
billable: false,
validWaypoints: getValidWaypoints(distanceTransaction.comment?.waypoints, true),
customUnitRateID: CONST.CUSTOM_UNITS.FAKE_P2P_ID,
},
existingTransaction: distanceTransaction,
isASAPSubmitBetaEnabled: false,
currentUser: {accountID: RORY_ACCOUNT_ID, email: RORY_EMAIL},
introSelected: undefined,
quickAction: undefined,
recentWaypoints,
betas: [CONST.BETAS.ALL],
isSelfTourViewed: false,
currentUserLocalCurrency: undefined,
delegateAccountID: undefined,
reportActionsList: undefined,
});
await waitForBatchedUpdates();
const optimisticSelfDMReport = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${selfDMReport.reportID}`);
if (!optimisticSelfDMReport) {
throw new Error('Expected optimistic Self DM report to exist.');
}
const optimisticReportsToDisplay = SidebarUtils.getReportsToDisplayInLHN({
currentReportId: 'different-report-id',
reports: {[selfDMReportKey]: optimisticSelfDMReport},
betas: [],
priorityMode: CONST.PRIORITY_MODE.DEFAULT,
draftComments: {},
transactionViolations: {},
transactions: {},
isOffline: false,
currentUserLogin: RORY_EMAIL,
currentUserAccountID: RORY_ACCOUNT_ID,
reportNameValuePairs: {},
reportAttributes: undefined,
conciergeReportID: undefined,
});
expect(hiddenReportsToDisplay).not.toHaveProperty(selfDMReportKey);
expect(optimisticSelfDMReport?.participants?.[RORY_ACCOUNT_ID]?.notificationPreference).toBe(CONST.REPORT.NOTIFICATION_PREFERENCE.MUTE);
expect(optimisticReportsToDisplay).toHaveProperty(selfDMReportKey);
await mockFetch?.resume?.();
});
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, CONST.REPORT.CHAT_TYPE.SELF_DM);
// Given a policyExpenseChat report
const policyExpenseChat = createRandomReport(1, 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?.();
const recentWaypoints = (await getOnyxValue(ONYXKEYS.NVP_RECENT_WAYPOINTS)) ?? [];
// 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,
},
isASAPSubmitBetaEnabled: false,
currentUser: {accountID: RORY_ACCOUNT_ID, email: RORY_EMAIL},
introSelected: undefined,
quickAction: undefined,
recentWaypoints,
betas: [CONST.BETAS.ALL],
isSelfTourViewed: false,
currentUserLocalCurrency: undefined,
delegateAccountID: undefined,
reportActionsList: undefined,
});
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({
reportID: selfDMReport.reportID,
actionName: CONST.IOU.ACTION.CATEGORIZE,
reportActionID: reportActionableTrackExpense?.reportActionID,
introSelected: {choice: CONST.ONBOARDING_CHOICES.MANAGE_TEAM},
draftTransactionIDs: [],
activePolicy: undefined,
userBillingGracePeriodEnds: undefined,
amountOwed: 0,
transaction,
currentUserAccountID: RORY_ACCOUNT_ID,
currentUserEmail: RORY_EMAIL,
currentUserLocalCurrency: '',
filteredPoliciesCount: 0,
firstPolicyID: undefined,
});
await waitForBatchedUpdates();
// Then the transaction draft should be saved successfully
let allTransactionsDraft: OnyxCollection<Transaction>;
await getOnyxData({
key: ONYXKEYS.COLLECTION.TRANSACTION_DRAFT,
waitForCollectionCallback: true,
callback: (val) => {
allTransactionsDraft = val;
},
});
const transactionDraft = allTransactionsDraft?.[`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transaction?.transactionID}`];
// When the user confirms the category for the tracked expense
trackExpense({
report: policyExpenseChat,
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,
},
optimisticTransactionID: 'optimistic-ignored-for-move-from-track',
isASAPSubmitBetaEnabled: false,
currentUser: {accountID: RORY_ACCOUNT_ID, email: RORY_EMAIL},
introSelected: undefined,
quickAction: undefined,
recentWaypoints,
betas: [CONST.BETAS.ALL],
isSelfTourViewed: false,
currentUserLocalCurrency: undefined,
delegateAccountID: undefined,
reportActionsList: undefined,
});
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);
// Move-from-track must keep the tracked transaction id, not the UI-provided optimisticTransactionID.
expect(transactions?.[`${ONYXKEYS.COLLECTION.TRANSACTION}optimistic-ignored-for-move-from-track`]).toBeUndefined();
// Then the transaction category must match the original category
expect(categorizedTransaction?.category).toBe(Object.keys(fakeCategories).at(0) ?? '');
resolve();
},
});
});
await new Promise<void>((resolve) => {
const connection = Onyx.connect({
key: ONYXKEYS.NVP_QUICK_ACTION_GLOBAL_CREATE,
callback: (quickAction) => {
Onyx.disconnect(connection);
resolve();
// Then the quickAction.action should be set to REQUEST_DISTANCE
expect(quickAction?.action).toBe(CONST.QUICK_ACTIONS.REQUEST_DISTANCE);
// Then the quickAction.chatReportID should be set to the given policyExpenseChat reportID
expect(quickAction?.chatReportID).toBe(policyExpenseChat.reportID);
},
});
});
});
it('share with accountant', async () => {
const accountant: Required<Accountant> = {login: VIT_EMAIL, accountID: VIT_ACCOUNT_ID};
const policy: Policy = {...createRandomPolicy(1), id: 'ABC'};
const selfDMReport: Report = {
...createRandomReport(1, CONST.REPORT.CHAT_TYPE.SELF_DM),
reportID: '10',
};
const policyExpenseChat: Report = {
...createRandomReport(1, CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT),
reportID: '123',
policyID: policy.id,
type: CONST.REPORT.TYPE.CHAT,
isOwnPolicyExpenseChat: true,
};
const transaction: Transaction = {...createRandomTransaction(1), transactionID: '555'};
await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`, policy);
await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${policyExpenseChat.reportID}`, policyExpenseChat);
await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transaction.transactionID}`, transaction);
const recentWaypoints = (await getOnyxValue(ONYXKEYS.NVP_RECENT_WAYPOINTS)) ?? [];
// Create a tracked expense
trackExpense({
report: selfDMReport,
isDraftPolicy: true,
action: CONST.IOU.ACTION.CREATE,
participantParams: {
payeeEmail: RORY_EMAIL,
payeeAccountID: RORY_ACCOUNT_ID,
participant: {accountID: RORY_ACCOUNT_ID},
},
transactionParams: {
amount: transaction.amount,
currency: transaction.currency,
created: format(new Date(), CONST.DATE.FNS_FORMAT_STRING),
merchant: transaction.merchant,
billable: false,
},
isASAPSubmitBetaEnabled: false,
currentUser: {accountID: RORY_ACCOUNT_ID, email: RORY_EMAIL},
introSelected: undefined,
quickAction: undefined,
recentWaypoints,
betas: [CONST.BETAS.ALL],
isSelfTourViewed: false,
currentUserLocalCurrency: undefined,
delegateAccountID: undefined,
reportActionsList: undefined,
});
await waitForBatchedUpdates();
const selfDMReportActionsOnyx = await new Promise<OnyxEntry<ReportActions>>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${selfDMReport.reportID}`,
waitForCollectionCallback: false,
callback: (value) => {
Onyx.disconnect(connection);
resolve(value);
},
});
});
expect(Object.values(selfDMReportActionsOnyx ?? {}).length).toBe(2);
const linkedTrackedExpenseReportAction = Object.values(selfDMReportActionsOnyx ?? {}).find((reportAction) => isMoneyRequestAction(reportAction));
const reportActionableTrackExpense = Object.values(selfDMReportActionsOnyx ?? {}).find((reportAction) => isActionableTrackExpense(reportAction));
mockFetch?.pause?.();
// Share the tracked expense with an accountant
trackExpense({
report: policyExpenseChat,
isDraftPolicy: false,
action: CONST.IOU.ACTION.SHARE,
participantParams: {
payeeEmail: RORY_EMAIL,
payeeAccountID: RORY_ACCOUNT_ID,
participant: {reportID: policyExpenseChat.reportID, isPolicyExpenseChat: true},
},
policyParams: {
policy,
},
transactionParams: {
amount: transaction.amount,
currency: transaction.currency,
created: format(new Date(), CONST.DATE.FNS_FORMAT_STRING),
merchant: transaction.merchant,
billable: false,
actionableWhisperReportActionID: reportActionableTrackExpense?.reportActionID,
linkedTrackedExpenseReportAction,
linkedTrackedExpenseReportID: selfDMReport.reportID,
},
accountantParams: {
accountant,
newAccountIDs: [],
newLogins: [],
},
isASAPSubmitBetaEnabled: false,
currentUser: {accountID: RORY_ACCOUNT_ID, email: RORY_EMAIL},
introSelected: undefined,
quickAction: undefined,
recentWaypoints,
betas: [CONST.BETAS.ALL],
isSelfTourViewed: false,
currentUserLocalCurrency: undefined,
delegateAccountID: undefined,
reportActionsList: undefined,
});
await waitForBatchedUpdates();
const policyExpenseChatOnyx = await new Promise<OnyxEntry<Report>>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT}${policyExpenseChat.reportID}`,
waitForCollectionCallback: false,
callback: (value) => {
Onyx.disconnect(connection);
resolve(value);
},
});
});
const policyOnyx = await new Promise<OnyxEntry<Policy>>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.POLICY}${policy.id}`,
waitForCollectionCallback: false,
callback: (value) => {
Onyx.disconnect(connection);
resolve(value);
},
});
});
await mockFetch?.resume?.();
// Accountant should be invited to the expense report
expect(policyExpenseChatOnyx?.participants?.[accountant.accountID]).toBeTruthy();
// Accountant should be added to the workspace as an admin
expect(policyOnyx?.employeeList?.[accountant.login].role).toBe(CONST.POLICY.ROLE.ADMIN);
});
it('share with accountant who is already a member', async () => {
const accountant: Required<Accountant> = {login: VIT_EMAIL, accountID: VIT_ACCOUNT_ID};
const policy: Policy = {...createRandomPolicy(1), id: 'ABC', employeeList: {[accountant.login]: {email: accountant.login, role: CONST.POLICY.ROLE.USER}}};
const selfDMReport: Report = {
...createRandomReport(1, CONST.REPORT.CHAT_TYPE.SELF_DM),
reportID: '10',
};
const policyExpenseChat: Report = {
...createRandomReport(1, CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT),
reportID: '123',
policyID: policy.id,
type: CONST.REPORT.TYPE.CHAT,
isOwnPolicyExpenseChat: true,
participants: {[accountant.accountID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.ALWAYS}},
};
const transaction: Transaction = {...createRandomTransaction(1), transactionID: '555'};
await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`, policy);
await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${policyExpenseChat.reportID}`, policyExpenseChat);
await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transaction.transactionID}`, transaction);
await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, {[accountant.accountID]: accountant});
const recentWaypoints = (await getOnyxValue(ONYXKEYS.NVP_RECENT_WAYPOINTS)) ?? [];
// Create a tracked expense
trackExpense({
report: selfDMReport,
isDraftPolicy: true,
action: CONST.IOU.ACTION.CREATE,
participantParams: {
payeeEmail: RORY_EMAIL,
payeeAccountID: RORY_ACCOUNT_ID,
participant: {accountID: RORY_ACCOUNT_ID},
},
transactionParams: {
amount: transaction.amount,
currency: transaction.currency,
created: format(new Date(), CONST.DATE.FNS_FORMAT_STRING),
merchant: transaction.merchant,
billable: false,
},
isASAPSubmitBetaEnabled: false,
currentUser: {accountID: RORY_ACCOUNT_ID, email: RORY_EMAIL},
introSelected: undefined,
quickAction: undefined,
recentWaypoints,
betas: [CONST.BETAS.ALL],
isSelfTourViewed: false,
currentUserLocalCurrency: undefined,
delegateAccountID: undefined,
reportActionsList: undefined,
});
await waitForBatchedUpdates();
const selfDMReportActionsOnyx = await new Promise<OnyxEntry<ReportActions>>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${selfDMReport.reportID}`,
waitForCollectionCallback: false,
callback: (value) => {
Onyx.disconnect(connection);
resolve(value);
},
});
});
expect(Object.values(selfDMReportActionsOnyx ?? {}).length).toBe(2);
const linkedTrackedExpenseReportAction = Object.values(selfDMReportActionsOnyx ?? {}).find((reportAction) => isMoneyRequestAction(reportAction));
const reportActionableTrackExpense = Object.values(selfDMReportActionsOnyx ?? {}).find((reportAction) => isActionableTrackExpense(reportAction));
mockFetch?.pause?.();
// Share the tracked expense with an accountant
trackExpense({
report: policyExpenseChat,
isDraftPolicy: false,
action: CONST.IOU.ACTION.SHARE,
participantParams: {
payeeEmail: RORY_EMAIL,
payeeAccountID: RORY_ACCOUNT_ID,
participant: {reportID: policyExpenseChat.reportID, isPolicyExpenseChat: true},
},
policyParams: {
policy,
},
transactionParams: {
amount: transaction.amount,
currency: transaction.currency,
created: format(new Date(), CONST.DATE.FNS_FORMAT_STRING),
merchant: transaction.merchant,
billable: false,
actionableWhisperReportActionID: reportActionableTrackExpense?.reportActionID,
linkedTrackedExpenseReportAction,
linkedTrackedExpenseReportID: selfDMReport.reportID,
},
accountantParams: {
accountant,
newAccountIDs: [],
newLogins: [],
},
isASAPSubmitBetaEnabled: false,
currentUser: {accountID: RORY_ACCOUNT_ID, email: RORY_EMAIL},
introSelected: undefined,
quickAction: undefined,
recentWaypoints,
betas: [CONST.BETAS.ALL],
isSelfTourViewed: false,
currentUserLocalCurrency: undefined,
delegateAccountID: undefined,
reportActionsList: undefined,
});
await waitForBatchedUpdates();
const policyExpenseChatOnyx = await new Promise<OnyxEntry<Report>>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT}${policyExpenseChat.reportID}`,
waitForCollectionCallback: false,
callback: (value) => {
Onyx.disconnect(connection);
resolve(value);
},
});
});
const policyOnyx = await new Promise<OnyxEntry<Policy>>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.POLICY}${policy.id}`,
waitForCollectionCallback: false,
callback: (value) => {
Onyx.disconnect(connection);
resolve(value);
},
});
});
await mockFetch?.resume?.();
// Accountant should be still a participant in the expense report
expect(policyExpenseChatOnyx?.participants?.[accountant.accountID]).toBeTruthy();
// Accountant role should change to admin
expect(policyOnyx?.employeeList?.[accountant.login].role).toBe(CONST.POLICY.ROLE.ADMIN);
});
it('share with accountant who is already an admin does not update their role or re-add them', async () => {
const accountant: Required<Accountant> = {login: VIT_EMAIL, accountID: VIT_ACCOUNT_ID};
const policy: Policy = {
...createRandomPolicy(1),
id: 'ABC',
employeeList: {[accountant.login]: {email: accountant.login, role: CONST.POLICY.ROLE.ADMIN}},
};
const selfDMReport: Report = {
...createRandomReport(1, CONST.REPORT.CHAT_TYPE.SELF_DM),
reportID: '10',
};
const policyExpenseChat: Report = {
...createRandomReport(1, CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT),
reportID: '123',
policyID: policy.id,
type: CONST.REPORT.TYPE.CHAT,
isOwnPolicyExpenseChat: true,
participants: {[accountant.accountID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.ALWAYS}},
};
const transaction: Transaction = {...createRandomTransaction(1), transactionID: '555'};
await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`, policy);
await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${policyExpenseChat.reportID}`, policyExpenseChat);
await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transaction.transactionID}`, transaction);
await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, {[accountant.accountID]: accountant});
const recentWaypoints = (await getOnyxValue(ONYXKEYS.NVP_RECENT_WAYPOINTS)) ?? [];
trackExpense({
report: selfDMReport,
isDraftPolicy: true,
action: CONST.IOU.ACTION.CREATE,
participantParams: {
payeeEmail: RORY_EMAIL,
payeeAccountID: RORY_ACCOUNT_ID,
participant: {accountID: RORY_ACCOUNT_ID},
},
transactionParams: {
amount: transaction.amount,
currency: transaction.currency,
created: format(new Date(), CONST.DATE.FNS_FORMAT_STRING),
merchant: transaction.merchant,
billable: false,
},
isASAPSubmitBetaEnabled: false,
currentUser: {accountID: RORY_ACCOUNT_ID, email: RORY_EMAIL},
introSelected: undefined,
quickAction: undefined,
recentWaypoints,
betas: [CONST.BETAS.ALL],
draftTransactionIDs: [transaction.transactionID],
isSelfTourViewed: false,
currentUserLocalCurrency: undefined,
delegateAccountID: undefined,
reportActionsList: undefined,
});
await waitForBatchedUpdates();
const selfDMReportActionsOnyx = await new Promise<OnyxEntry<ReportActions>>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${selfDMReport.reportID}`,
waitForCollectionCallback: false,
callback: (value) => {
Onyx.disconnect(connection);
resolve(value);
},
});
});
const linkedTrackedExpenseReportAction = Object.values(selfDMReportActionsOnyx ?? {}).find((reportAction) => isMoneyRequestAction(reportAction));
const reportActionableTrackExpense = Object.values(selfDMReportActionsOnyx ?? {}).find((reportAction) => isActionableTrackExpense(reportAction));
mockFetch?.pause?.();
trackExpense({
report: policyExpenseChat,
isDraftPolicy: false,
action: CONST.IOU.ACTION.SHARE,
participantParams: {
payeeEmail: RORY_EMAIL,
payeeAccountID: RORY_ACCOUNT_ID,
participant: {reportID: policyExpenseChat.reportID, isPolicyExpenseChat: true},
},
policyParams: {
policy,
},
transactionParams: {
amount: transaction.amount,
currency: transaction.currency,
created: format(new Date(), CONST.DATE.FNS_FORMAT_STRING),
merchant: transaction.merchant,
billable: false,
actionableWhisperReportActionID: reportActionableTrackExpense?.reportActionID,
linkedTrackedExpenseReportAction,
linkedTrackedExpenseReportID: selfDMReport.reportID,
},
accountantParams: {
accountant,
newAccountIDs: [],
newLogins: [],
},
isASAPSubmitBetaEnabled: false,
currentUser: {accountID: RORY_ACCOUNT_ID, email: RORY_EMAIL},
introSelected: undefined,
quickAction: undefined,
recentWaypoints,
betas: [CONST.BETAS.ALL],
draftTransactionIDs: [],
isSelfTourViewed: false,
currentUserLocalCurrency: undefined,
delegateAccountID: undefined,
reportActionsList: undefined,
});
await waitForBatchedUpdates();
const policyOnyx = await new Promise<OnyxEntry<Policy>>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.POLICY}${policy.id}`,
waitForCollectionCallback: false,
callback: (value) => {
Onyx.disconnect(connection);
resolve(value);
},
});
});
await mockFetch?.resume?.();
// Accountant is already an admin so the role should stay ADMIN
expect(policyOnyx?.employeeList?.[accountant.login].role).toBe(CONST.POLICY.ROLE.ADMIN);
// And the share command should still have fired
TestHelper.expectAPICommandToHaveBeenCalled(WRITE_COMMANDS.SHARE_TRACKED_EXPENSE, 1);
});
it('share with accountant on a policy with existing members creates the optimistic announce chat', async () => {
const existingMemberA = 'member-a@expensifail.com';
const existingMemberAID = 100;
const existingMemberB = 'member-b@expensifail.com';
const existingMemberBID = 101;
const accountant: Required<Accountant> = {login: VIT_EMAIL, accountID: VIT_ACCOUNT_ID};
const policy: Policy = {
...createRandomPolicy(1),
id: 'ABC',
employeeList: {
[existingMemberA]: {email: existingMemberA, role: CONST.POLICY.ROLE.USER},
[existingMemberB]: {email: existingMemberB, role: CONST.POLICY.ROLE.USER},
},
};
const selfDMReport: Report = {
...createRandomReport(1, CONST.REPORT.CHAT_TYPE.SELF_DM),
reportID: '10',
};
const policyExpenseChat: Report = {
...createRandomReport(1, CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT),
reportID: '123',
policyID: policy.id,
type: CONST.REPORT.TYPE.CHAT,
isOwnPolicyExpenseChat: true,
};
const transaction: Transaction = {...createRandomTransaction(1), transactionID: '555'};
await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`, policy);
await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${policyExpenseChat.reportID}`, policyExpenseChat);
await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transaction.transactionID}`, transaction);
await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, {
[existingMemberAID]: {accountID: existingMemberAID, login: existingMemberA},
[existingMemberBID]: {accountID: existingMemberBID, login: existingMemberB},
});
const recentWaypoints = (await getOnyxValue(ONYXKEYS.NVP_RECENT_WAYPOINTS)) ?? [];
trackExpense({
report: selfDMReport,
isDraftPolicy: true,
action: CONST.IOU.ACTION.CREATE,
participantParams: {
payeeEmail: RORY_EMAIL,
payeeAccountID: RORY_ACCOUNT_ID,
participant: {accountID: RORY_ACCOUNT_ID},
},
transactionParams: {
amount: transaction.amount,
currency: transaction.currency,
created: format(new Date(), CONST.DATE.FNS_FORMAT_STRING),
merchant: transaction.merchant,
billable: false,
},
isASAPSubmitBetaEnabled: false,
currentUser: {accountID: RORY_ACCOUNT_ID, email: RORY_EMAIL},
introSelected: undefined,
quickAction: undefined,
recentWaypoints,
betas: [CONST.BETAS.ALL],
draftTransactionIDs: [transaction.transactionID],
isSelfTourViewed: false,
currentUserLocalCurrency: undefined,
delegateAccountID: undefined,
reportActionsList: undefined,
});
await waitForBatchedUpdates();
const selfDMReportActionsOnyx = await new Promise<OnyxEntry<ReportActions>>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${selfDMReport.reportID}`,
waitForCollectionCallback: false,
callback: (value) => {
Onyx.disconnect(connection);
resolve(value);
},
});
});
const linkedTrackedExpenseReportAction = Object.values(selfDMReportActionsOnyx ?? {}).find((reportAction) => isMoneyRequestAction(reportAction));
const reportActionableTrackExpense = Object.values(selfDMReportActionsOnyx ?? {}).find((reportAction) => isActionableTrackExpense(reportAction));
mockFetch?.pause?.();
trackExpense({
report: policyExpenseChat,
isDraftPolicy: false,
action: CONST.IOU.ACTION.SHARE,
participantParams: {
payeeEmail: RORY_EMAIL,
payeeAccountID: RORY_ACCOUNT_ID,
participant: {reportID: policyExpenseChat.reportID, isPolicyExpenseChat: true},
},