-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
Policy.ts
2130 lines (1934 loc) · 73.7 KB
/
Policy.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 {PUBLIC_DOMAINS} from 'expensify-common/lib/CONST';
import ExpensiMark from 'expensify-common/lib/ExpensiMark';
import Str from 'expensify-common/lib/str';
import {escapeRegExp} from 'lodash';
import lodashClone from 'lodash/clone';
import lodashUnion from 'lodash/union';
import type {NullishDeep, OnyxCollection, OnyxEntry, OnyxUpdate} from 'react-native-onyx';
import Onyx from 'react-native-onyx';
import * as API from '@libs/API';
import type {
AddMembersToWorkspaceParams,
CreateWorkspaceFromIOUPaymentParams,
CreateWorkspaceParams,
DeleteMembersFromWorkspaceParams,
DeleteWorkspaceAvatarParams,
DeleteWorkspaceParams,
OpenDraftWorkspaceRequestParams,
OpenWorkspaceInvitePageParams,
OpenWorkspaceMembersPageParams,
OpenWorkspaceParams,
OpenWorkspaceReimburseViewParams,
UpdateWorkspaceAvatarParams,
UpdateWorkspaceCustomUnitAndRateParams,
UpdateWorkspaceDescriptionParams,
UpdateWorkspaceGeneralSettingsParams,
} from '@libs/API/parameters';
import {READ_COMMANDS, WRITE_COMMANDS} from '@libs/API/types';
import DateUtils from '@libs/DateUtils';
import * as ErrorUtils from '@libs/ErrorUtils';
import Log from '@libs/Log';
import * as NumberUtils from '@libs/NumberUtils';
import * as OptionsListUtils from '@libs/OptionsListUtils';
import * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils';
import * as ReportActionsUtils from '@libs/ReportActionsUtils';
import * as ReportUtils from '@libs/ReportUtils';
import * as TransactionUtils from '@libs/TransactionUtils';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {
InvitedEmailsToAccountIDs,
PersonalDetailsList,
Policy,
PolicyMember,
PolicyTags,
RecentlyUsedCategories,
RecentlyUsedTags,
ReimbursementAccount,
Report,
ReportAction,
Transaction,
} from '@src/types/onyx';
import type {Errors} from '@src/types/onyx/OnyxCommon';
import type {Attributes, CustomUnit, Rate, Unit} from '@src/types/onyx/Policy';
import type {EmptyObject} from '@src/types/utils/EmptyObject';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
type AnnounceRoomMembersOnyxData = {
onyxOptimisticData: OnyxUpdate[];
onyxFailureData: OnyxUpdate[];
};
type ReportCreationData = Record<
string,
{
reportID: string;
reportActionID?: string;
}
>;
type WorkspaceMembersChats = {
onyxSuccessData: OnyxUpdate[];
onyxOptimisticData: OnyxUpdate[];
onyxFailureData: OnyxUpdate[];
reportCreationData: ReportCreationData;
};
type OptimisticCustomUnits = {
customUnits: Record<string, CustomUnit>;
customUnitID: string;
customUnitRateID: string;
outputCurrency: string;
};
type PoliciesRecord = Record<string, OnyxEntry<Policy>>;
type NewCustomUnit = {
customUnitID: string;
name: string;
attributes: Attributes;
rates: Rate;
};
const allPolicies: OnyxCollection<Policy> = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.POLICY,
callback: (val, key) => {
if (!key) {
return;
}
if (val === null || val === undefined) {
// If we are deleting a policy, we have to check every report linked to that policy
// and unset the draft indicator (pencil icon) alongside removing any draft comments. Clearing these values will keep the newly archived chats from being displayed in the LHN.
// More info: https://github.com/Expensify/App/issues/14260
const policyID = key.replace(ONYXKEYS.COLLECTION.POLICY, '');
const policyReports = ReportUtils.getAllPolicyReports(policyID);
const cleanUpMergeQueries: Record<`${typeof ONYXKEYS.COLLECTION.REPORT}${string}`, NullishDeep<Report>> = {};
const cleanUpSetQueries: Record<`${typeof ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT}${string}` | `${typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${string}`, null> = {};
policyReports.forEach((policyReport) => {
if (!policyReport) {
return;
}
const {reportID} = policyReport;
cleanUpMergeQueries[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`] = {hasDraft: false};
cleanUpSetQueries[`${ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT}${reportID}`] = null;
cleanUpSetQueries[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${reportID}`] = null;
});
Onyx.mergeCollection(ONYXKEYS.COLLECTION.REPORT, cleanUpMergeQueries);
Onyx.multiSet(cleanUpSetQueries);
delete allPolicies[key];
return;
}
allPolicies[key] = val;
},
});
let allReports: OnyxCollection<Report> = null;
Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT,
waitForCollectionCallback: true,
callback: (value) => (allReports = value),
});
let allPolicyMembers: OnyxCollection<PolicyMember>;
Onyx.connect({
key: ONYXKEYS.COLLECTION.POLICY_MEMBERS,
waitForCollectionCallback: true,
callback: (val) => {
allPolicyMembers = val;
},
});
let lastAccessedWorkspacePolicyID: OnyxEntry<string> = null;
Onyx.connect({
key: ONYXKEYS.LAST_ACCESSED_WORKSPACE_POLICY_ID,
callback: (value) => (lastAccessedWorkspacePolicyID = value),
});
let sessionEmail = '';
let sessionAccountID = 0;
Onyx.connect({
key: ONYXKEYS.SESSION,
callback: (val) => {
sessionEmail = val?.email ?? '';
sessionAccountID = val?.accountID ?? -1;
},
});
let allPersonalDetails: OnyxEntry<PersonalDetailsList>;
Onyx.connect({
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
callback: (val) => (allPersonalDetails = val),
});
let reimbursementAccount: OnyxEntry<ReimbursementAccount>;
Onyx.connect({
key: ONYXKEYS.REIMBURSEMENT_ACCOUNT,
callback: (val) => (reimbursementAccount = val),
});
let allRecentlyUsedCategories: OnyxCollection<RecentlyUsedCategories> = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_CATEGORIES,
waitForCollectionCallback: true,
callback: (val) => (allRecentlyUsedCategories = val),
});
let allPolicyTags: OnyxCollection<PolicyTags> = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.POLICY_TAGS,
waitForCollectionCallback: true,
callback: (value) => {
if (!value) {
allPolicyTags = {};
return;
}
allPolicyTags = value;
},
});
let allRecentlyUsedTags: OnyxCollection<RecentlyUsedTags> = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_TAGS,
waitForCollectionCallback: true,
callback: (val) => (allRecentlyUsedTags = val),
});
/**
* Stores in Onyx the policy ID of the last workspace that was accessed by the user
*/
function updateLastAccessedWorkspace(policyID: OnyxEntry<string>) {
Onyx.set(ONYXKEYS.LAST_ACCESSED_WORKSPACE_POLICY_ID, policyID);
}
/**
* Check if the user has any active free policies (aka workspaces)
*/
function hasActiveFreePolicy(policies: Array<OnyxEntry<Policy>> | PoliciesRecord): boolean {
const adminFreePolicies = Object.values(policies).filter((policy) => policy && policy.type === CONST.POLICY.TYPE.FREE && policy.role === CONST.POLICY.ROLE.ADMIN);
if (adminFreePolicies.length === 0) {
return false;
}
if (adminFreePolicies.some((policy) => !policy?.pendingAction)) {
return true;
}
if (adminFreePolicies.some((policy) => policy?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD)) {
return true;
}
if (adminFreePolicies.some((policy) => policy?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE)) {
return false;
}
// If there are no add or delete pending actions the only option left is an update
// pendingAction, in which case we should return true.
return true;
}
/**
* Delete the workspace
*/
function deleteWorkspace(policyID: string, policyName: string) {
if (!allPolicies) {
return;
}
const filteredPolicies = Object.values(allPolicies).filter((policy): policy is Policy => policy?.id !== policyID);
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
value: {
avatar: '',
pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE,
errors: null,
},
},
...(!hasActiveFreePolicy(filteredPolicies)
? [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.REIMBURSEMENT_ACCOUNT,
value: {
errors: null,
},
},
]
: []),
];
const reportsToArchive = Object.values(allReports ?? {}).filter((report) => report?.policyID === policyID && (ReportUtils.isChatRoom(report) || ReportUtils.isPolicyExpenseChat(report)));
reportsToArchive.forEach((report) => {
const {reportID, ownerAccountID} = report ?? {};
optimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
value: {
stateNum: CONST.REPORT.STATE_NUM.APPROVED,
statusNum: CONST.REPORT.STATUS_NUM.CLOSED,
hasDraft: false,
oldPolicyName: allPolicies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`]?.name ?? '',
},
});
optimisticData.push({
onyxMethod: Onyx.METHOD.SET,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${reportID}`,
value: null,
});
// Add closed actions to all chat reports linked to this policy
// Announce & admin chats have FAKE owners, but workspace chats w/ users do have owners.
let emailClosingReport: string = CONST.POLICY.OWNER_EMAIL_FAKE;
if (!!ownerAccountID && ownerAccountID !== CONST.POLICY.OWNER_ACCOUNT_ID_FAKE) {
emailClosingReport = allPersonalDetails?.[ownerAccountID]?.login ?? '';
}
const optimisticClosedReportAction = ReportUtils.buildOptimisticClosedReportAction(emailClosingReport, policyName, CONST.REPORT.ARCHIVE_REASON.POLICY_DELETED);
const optimisticReportActions: Record<string, ReportAction> = {};
optimisticReportActions[optimisticClosedReportAction.reportActionID] = optimisticClosedReportAction as ReportAction;
optimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`,
value: optimisticReportActions,
});
});
// Restore the old report stateNum and statusNum
const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.REIMBURSEMENT_ACCOUNT,
value: {
errors: reimbursementAccount?.errors ?? null,
},
},
];
reportsToArchive.forEach((report) => {
const {reportID, stateNum, statusNum, hasDraft, oldPolicyName} = report ?? {};
failureData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
value: {
stateNum,
statusNum,
hasDraft,
oldPolicyName,
},
});
});
const params: DeleteWorkspaceParams = {policyID};
API.write(WRITE_COMMANDS.DELETE_WORKSPACE, params, {optimisticData, failureData});
// Reset the lastAccessedWorkspacePolicyID
if (policyID === lastAccessedWorkspacePolicyID) {
updateLastAccessedWorkspace(null);
}
}
/**
* Is the user an admin of a free policy (aka workspace)?
*/
function isAdminOfFreePolicy(policies?: PoliciesRecord): boolean {
return Object.values(policies ?? {}).some((policy) => policy && policy.type === CONST.POLICY.TYPE.FREE && policy.role === CONST.POLICY.ROLE.ADMIN);
}
/**
* Build optimistic data for adding members to the announcement room
*/
function buildAnnounceRoomMembersOnyxData(policyID: string, accountIDs: number[]): AnnounceRoomMembersOnyxData {
const announceReport = ReportUtils.getRoom(CONST.REPORT.CHAT_TYPE.POLICY_ANNOUNCE, policyID);
const announceRoomMembers: AnnounceRoomMembersOnyxData = {
onyxOptimisticData: [],
onyxFailureData: [],
};
if (!announceReport) {
return announceRoomMembers;
}
if (announceReport?.participantAccountIDs) {
// Everyone in special policy rooms is visible
const participantAccountIDs = [...announceReport.participantAccountIDs, ...accountIDs];
announceRoomMembers.onyxOptimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${announceReport?.reportID}`,
value: {
participantAccountIDs,
visibleChatMemberAccountIDs: participantAccountIDs,
},
});
}
announceRoomMembers.onyxFailureData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${announceReport?.reportID}`,
value: {
participantAccountIDs: announceReport?.participantAccountIDs,
visibleChatMemberAccountIDs: announceReport?.visibleChatMemberAccountIDs,
},
});
return announceRoomMembers;
}
/**
* Build optimistic data for removing users from the announcement room
*/
function removeOptimisticAnnounceRoomMembers(policyID: string, accountIDs: number[]): AnnounceRoomMembersOnyxData {
const announceReport = ReportUtils.getRoom(CONST.REPORT.CHAT_TYPE.POLICY_ANNOUNCE, policyID);
const announceRoomMembers: AnnounceRoomMembersOnyxData = {
onyxOptimisticData: [],
onyxFailureData: [],
};
if (!announceReport) {
return announceRoomMembers;
}
if (announceReport?.participantAccountIDs) {
const remainUsers = announceReport.participantAccountIDs.filter((e) => !accountIDs.includes(e));
announceRoomMembers.onyxOptimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${announceReport.reportID}`,
value: {
participantAccountIDs: [...remainUsers],
visibleChatMemberAccountIDs: [...remainUsers],
},
});
announceRoomMembers.onyxFailureData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${announceReport.reportID}`,
value: {
participantAccountIDs: announceReport.participantAccountIDs,
visibleChatMemberAccountIDs: announceReport.visibleChatMemberAccountIDs,
},
});
}
return announceRoomMembers;
}
/**
* Remove the passed members from the policy employeeList
* Please see https://github.com/Expensify/App/blob/main/README.md#Security for more details
*/
function removeMembers(accountIDs: number[], policyID: string) {
// In case user selects only themselves (admin), their email will be filtered out and the members
// array passed will be empty, prevent the function from proceeding in that case as there is no one to remove
if (accountIDs.length === 0) {
return;
}
const membersListKey = `${ONYXKEYS.COLLECTION.POLICY_MEMBERS}${policyID}` as const;
const policy = ReportUtils.getPolicy(policyID);
const workspaceChats = ReportUtils.getWorkspaceChats(policyID, accountIDs);
const optimisticClosedReportActions = workspaceChats.map(() => ReportUtils.buildOptimisticClosedReportAction(sessionEmail, policy.name, CONST.REPORT.ARCHIVE_REASON.REMOVED_FROM_POLICY));
const announceRoomMembers = removeOptimisticAnnounceRoomMembers(policyID, accountIDs);
const optimisticMembersState: OnyxCollection<PolicyMember> = {};
const successMembersState: OnyxCollection<PolicyMember> = {};
const failureMembersState: OnyxCollection<PolicyMember> = {};
accountIDs.forEach((accountID) => {
optimisticMembersState[accountID] = {pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE};
successMembersState[accountID] = null;
failureMembersState[accountID] = {errors: ErrorUtils.getMicroSecondOnyxError('workspace.people.error.genericRemove')};
});
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: membersListKey,
value: optimisticMembersState,
},
...announceRoomMembers.onyxOptimisticData,
];
workspaceChats.forEach((report) => {
optimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${report?.reportID}`,
value: {
statusNum: CONST.REPORT.STATUS_NUM.CLOSED,
stateNum: CONST.REPORT.STATE_NUM.APPROVED,
oldPolicyName: policy.name,
hasDraft: false,
},
});
});
optimisticClosedReportActions.forEach((reportAction, index) => {
optimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${workspaceChats?.[index]?.reportID}`,
value: {[reportAction.reportActionID]: reportAction as ReportAction},
});
});
// If the policy has primaryLoginsInvited, then it displays informative messages on the members page about which primary logins were added by secondary logins.
// If we delete all these logins then we should clear the informative messages since they are no longer relevant.
if (!isEmptyObject(policy?.primaryLoginsInvited ?? {})) {
// Take the current policy members and remove them optimistically
const policyMemberAccountIDs = Object.keys(allPolicyMembers?.[`${ONYXKEYS.COLLECTION.POLICY_MEMBERS}${policyID}`] ?? {}).map((accountID) => Number(accountID));
const remainingMemberAccountIDs = policyMemberAccountIDs.filter((accountID) => !accountIDs.includes(accountID));
const remainingLogins: string[] = PersonalDetailsUtils.getLoginsByAccountIDs(remainingMemberAccountIDs);
const invitedPrimaryToSecondaryLogins: Record<string, string> = {};
if (policy.primaryLoginsInvited) {
Object.keys(policy.primaryLoginsInvited).forEach((key) => (invitedPrimaryToSecondaryLogins[policy.primaryLoginsInvited?.[key] ?? ''] = key));
}
// Then, if no remaining members exist that were invited by a secondary login, clear the informative messages
if (!remainingLogins.some((remainingLogin) => !!invitedPrimaryToSecondaryLogins[remainingLogin])) {
optimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: membersListKey,
value: {
primaryLoginsInvited: null,
},
});
}
}
const successData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: membersListKey,
value: successMembersState,
},
];
const filteredWorkspaceChats = workspaceChats.filter((report): report is Report => report !== null);
const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: membersListKey,
value: failureMembersState,
},
...announceRoomMembers.onyxFailureData,
];
filteredWorkspaceChats.forEach(({reportID, stateNum, statusNum, hasDraft, oldPolicyName = null}) => {
failureData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
value: {
stateNum,
statusNum,
hasDraft,
oldPolicyName,
},
});
});
optimisticClosedReportActions.forEach((reportAction, index) => {
failureData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${workspaceChats?.[index]?.reportID}`,
value: {[reportAction.reportActionID]: null},
});
});
const params: DeleteMembersFromWorkspaceParams = {
emailList: accountIDs.map((accountID) => allPersonalDetails?.[accountID]?.login).join(','),
policyID,
};
API.write(WRITE_COMMANDS.DELETE_MEMBERS_FROM_WORKSPACE, params, {optimisticData, successData, failureData});
}
/**
* Optimistically create a chat for each member of the workspace, creates both optimistic and success data for onyx.
*
* @returns - object with onyxSuccessData, onyxOptimisticData, and optimisticReportIDs (map login to reportID)
*/
function createPolicyExpenseChats(policyID: string, invitedEmailsToAccountIDs: InvitedEmailsToAccountIDs, hasOutstandingChildRequest = false): WorkspaceMembersChats {
const workspaceMembersChats: WorkspaceMembersChats = {
onyxSuccessData: [],
onyxOptimisticData: [],
onyxFailureData: [],
reportCreationData: {},
};
Object.keys(invitedEmailsToAccountIDs).forEach((email) => {
const accountID = invitedEmailsToAccountIDs[email];
const cleanAccountID = Number(accountID);
const login = OptionsListUtils.addSMSDomainIfPhoneNumber(email);
const oldChat = ReportUtils.getChatByParticipantsAndPolicy([sessionAccountID, cleanAccountID], policyID);
// If the chat already exists, we don't want to create a new one - just make sure it's not archived
if (oldChat) {
workspaceMembersChats.reportCreationData[login] = {
reportID: oldChat.reportID,
};
workspaceMembersChats.onyxOptimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${oldChat.reportID}`,
value: {
stateNum: CONST.REPORT.STATE_NUM.OPEN,
statusNum: CONST.REPORT.STATUS_NUM.OPEN,
},
});
return;
}
const optimisticReport = ReportUtils.buildOptimisticChatReport([sessionAccountID, cleanAccountID], undefined, CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT, policyID, cleanAccountID);
const optimisticCreatedAction = ReportUtils.buildOptimisticCreatedReportAction(login);
workspaceMembersChats.reportCreationData[login] = {
reportID: optimisticReport.reportID,
reportActionID: optimisticCreatedAction.reportActionID,
};
workspaceMembersChats.onyxOptimisticData.push({
onyxMethod: Onyx.METHOD.SET,
key: `${ONYXKEYS.COLLECTION.REPORT}${optimisticReport.reportID}`,
value: {
...optimisticReport,
pendingFields: {
createChat: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
},
isOptimisticReport: true,
hasOutstandingChildRequest,
},
});
workspaceMembersChats.onyxOptimisticData.push({
onyxMethod: Onyx.METHOD.SET,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${optimisticReport.reportID}`,
value: {[optimisticCreatedAction.reportActionID]: optimisticCreatedAction},
});
workspaceMembersChats.onyxSuccessData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${optimisticReport.reportID}`,
value: {
pendingFields: {
createChat: null,
},
errorFields: {
createChat: null,
},
isOptimisticReport: false,
},
});
workspaceMembersChats.onyxSuccessData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${optimisticReport.reportID}`,
value: {[optimisticCreatedAction.reportActionID]: {pendingAction: null}},
});
workspaceMembersChats.onyxFailureData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${optimisticReport.reportID}`,
value: {
isLoadingInitialReportActions: false,
},
});
});
return workspaceMembersChats;
}
/**
* Adds members to the specified workspace/policyID
* Please see https://github.com/Expensify/App/blob/main/README.md#Security for more details
*/
function addMembersToWorkspace(invitedEmailsToAccountIDs: InvitedEmailsToAccountIDs, welcomeNote: string, policyID: string) {
const membersListKey = `${ONYXKEYS.COLLECTION.POLICY_MEMBERS}${policyID}` as const;
const logins = Object.keys(invitedEmailsToAccountIDs).map((memberLogin) => OptionsListUtils.addSMSDomainIfPhoneNumber(memberLogin));
const accountIDs = Object.values(invitedEmailsToAccountIDs);
const newPersonalDetailsOnyxData = PersonalDetailsUtils.getNewPersonalDetailsOnyxData(logins, accountIDs);
const announceRoomMembers = buildAnnounceRoomMembersOnyxData(policyID, accountIDs);
// create onyx data for policy expense chats for each new member
const membersChats = createPolicyExpenseChats(policyID, invitedEmailsToAccountIDs);
const optimisticMembersState: OnyxCollection<PolicyMember> = {};
const failureMembersState: OnyxCollection<PolicyMember> = {};
accountIDs.forEach((accountID) => {
optimisticMembersState[accountID] = {pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD};
failureMembersState[accountID] = {
errors: ErrorUtils.getMicroSecondOnyxError('workspace.people.error.genericAdd'),
};
});
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: membersListKey,
// Convert to object with each key containing {pendingAction: ‘add’}
value: optimisticMembersState,
},
...newPersonalDetailsOnyxData.optimisticData,
...membersChats.onyxOptimisticData,
...announceRoomMembers.onyxOptimisticData,
];
const successData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: membersListKey,
// Convert to object with each key clearing pendingAction, when it is an existing account.
// Remove the object, when it is a newly created account.
value: accountIDs.reduce((accountIDsWithClearedPendingAction, accountID) => {
let value = null;
const accountAlreadyExists = !isEmptyObject(allPersonalDetails?.[accountID]);
if (accountAlreadyExists) {
value = {pendingAction: null, errors: null};
}
return {...accountIDsWithClearedPendingAction, [accountID]: value};
}, {}),
},
...newPersonalDetailsOnyxData.finallyData,
...membersChats.onyxSuccessData,
];
const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: membersListKey,
// Convert to object with each key containing the error. We don’t
// need to remove the members since that is handled by onClose of OfflineWithFeedback.
value: failureMembersState,
},
...newPersonalDetailsOnyxData.finallyData,
...membersChats.onyxFailureData,
...announceRoomMembers.onyxFailureData,
];
const params: AddMembersToWorkspaceParams = {
employees: JSON.stringify(logins.map((login) => ({email: login}))),
welcomeNote: new ExpensiMark().replace(welcomeNote),
policyID,
};
if (!isEmptyObject(membersChats.reportCreationData)) {
params.reportCreationData = JSON.stringify(membersChats.reportCreationData);
}
API.write(WRITE_COMMANDS.ADD_MEMBERS_TO_WORKSPACE, params, {optimisticData, successData, failureData});
}
/**
* Updates a workspace avatar image
*/
function updateWorkspaceAvatar(policyID: string, file: File) {
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
value: {
avatar: file.uri,
originalFileName: file.name,
errorFields: {
avatar: null,
},
pendingFields: {
avatar: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE,
},
},
},
];
const finallyData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
value: {
pendingFields: {
avatar: null,
},
},
},
];
const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
value: {
avatar: allPolicies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`]?.avatar,
},
},
];
const params: UpdateWorkspaceAvatarParams = {
policyID,
file,
};
API.write(WRITE_COMMANDS.UPDATE_WORKSPACE_AVATAR, params, {optimisticData, finallyData, failureData});
}
/**
* Deletes the avatar image for the workspace
*/
function deleteWorkspaceAvatar(policyID: string) {
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
value: {
pendingFields: {
avatar: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE,
},
errorFields: {
avatar: null,
},
avatar: '',
},
},
];
const finallyData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
value: {
pendingFields: {
avatar: null,
},
},
},
];
const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
value: {
errorFields: {
avatar: ErrorUtils.getMicroSecondOnyxError('avatarWithImagePicker.deleteWorkspaceError'),
},
},
},
];
const params: DeleteWorkspaceAvatarParams = {policyID};
API.write(WRITE_COMMANDS.DELETE_WORKSPACE_AVATAR, params, {optimisticData, finallyData, failureData});
}
/**
* Clear error and pending fields for the workspace avatar
*/
function clearAvatarErrors(policyID: string) {
Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, {
errorFields: {
avatar: null,
},
pendingFields: {
avatar: null,
},
});
}
/**
* Optimistically update the general settings. Set the general settings as pending until the response succeeds.
* If the response fails set a general error message. Clear the error message when updating.
*/
function updateGeneralSettings(policyID: string, name: string, currency: string) {
const policy = allPolicies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`];
if (!policy) {
return;
}
const distanceUnit = Object.values(policy?.customUnits ?? {}).find((unit) => unit.name === CONST.CUSTOM_UNITS.NAME_DISTANCE);
const distanceRate = Object.values(distanceUnit?.rates ?? {}).find((rate) => rate.name === CONST.CUSTOM_UNITS.DEFAULT_RATE);
const optimisticData: OnyxUpdate[] = [
{
// We use SET because it's faster than merge and avoids a race condition when setting the currency and navigating the user to the Bank account page in confirmCurrencyChangeAndHideModal
onyxMethod: Onyx.METHOD.SET,
key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
value: {
...policy,
pendingFields: {
generalSettings: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE,
},
// Clear errorFields in case the user didn't dismiss the general settings error
errorFields: {
generalSettings: null,
},
name,
outputCurrency: currency,
...(distanceUnit?.customUnitID && distanceRate?.customUnitRateID
? {
customUnits: {
[distanceUnit?.customUnitID]: {
...distanceUnit,
rates: {
[distanceRate?.customUnitRateID]: {
...distanceRate,
currency,
},
},
},
},
}
: {}),
},
},
];
const finallyData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
value: {
pendingFields: {
generalSettings: null,
},
},
},
];
const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
value: {
errorFields: {
generalSettings: ErrorUtils.getMicroSecondOnyxError('workspace.editor.genericFailureMessage'),
},
...(distanceUnit?.customUnitID
? {
customUnits: {
[distanceUnit.customUnitID]: distanceUnit,
},
}
: {}),
},
},
];
const params: UpdateWorkspaceGeneralSettingsParams = {
policyID,
workspaceName: name,
currency,
};
API.write(WRITE_COMMANDS.UPDATE_WORKSPACE_GENERAL_SETTINGS, params, {
optimisticData,
finallyData,
failureData,
});
}
function updateDescription(policyID: string, description: string, currentDescription: string) {
if (description === currentDescription) {
return;
}
const parsedDescription = ReportUtils.getParsedComment(description);
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
value: {
description: parsedDescription,
pendingFields: {
description: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE,
},
errorFields: {
description: null,
},
},
},
];
const finallyData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
value: {
pendingFields: {
description: null,
},
},
},
];
const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
value: {
errorFields: {
description: ErrorUtils.getMicroSecondOnyxError('workspace.editor.genericFailureMessage'),
},
},
},
];
const params: UpdateWorkspaceDescriptionParams = {
policyID,
description: parsedDescription,
};
API.write(WRITE_COMMANDS.UPDATE_WORKSPACE_DESCRIPTION, params, {
optimisticData,
finallyData,
failureData,
});
}
function clearWorkspaceGeneralSettingsErrors(policyID: string) {
Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, {
errorFields: {
generalSettings: null,
},
});
}
function setWorkspaceErrors(policyID: string, errors: Errors) {
if (!allPolicies?.[policyID]) {
return;
}
Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, {errors: null});
Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, {errors});
}
function clearCustomUnitErrors(policyID: string, customUnitID: string, customUnitRateID: string) {
Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, {