-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
User.ts
1357 lines (1234 loc) · 41.6 KB
/
User.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 {isBefore} from 'date-fns';
import type {OnyxCollection, OnyxEntry, OnyxUpdate} from 'react-native-onyx';
import Onyx from 'react-native-onyx';
import type {ValueOf} from 'type-fest';
import * as ActiveClientManager from '@libs/ActiveClientManager';
import * as API from '@libs/API';
import type {
AddNewContactMethodParams,
CloseAccountParams,
DeleteContactMethodParams,
GetStatementPDFParams,
RequestContactMethodValidateCodeParams,
SetContactMethodAsDefaultParams,
SetNameValuePairParams,
UpdateChatPriorityModeParams,
UpdateNewsletterSubscriptionParams,
UpdatePreferredEmojiSkinToneParams,
UpdateStatusParams,
UpdateThemeParams,
ValidateLoginParams,
ValidateSecondaryLoginParams,
} 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 Navigation from '@libs/Navigation/Navigation';
import * as SequentialQueue from '@libs/Network/SequentialQueue';
import * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils';
import * as Pusher from '@libs/Pusher/pusher';
import PusherUtils from '@libs/PusherUtils';
import * as ReportActionsUtils from '@libs/ReportActionsUtils';
import playSound, {SOUNDS} from '@libs/Sound';
import playSoundExcludingMobile from '@libs/Sound/playSoundExcludingMobile';
import Visibility from '@libs/Visibility';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {BlockedFromConcierge, CustomStatusDraft, LoginList, Policy} from '@src/types/onyx';
import type Login from '@src/types/onyx/Login';
import type {OnyxServerUpdate} from '@src/types/onyx/OnyxUpdatesFromServer';
import type OnyxPersonalDetails from '@src/types/onyx/PersonalDetails';
import type {Status} from '@src/types/onyx/PersonalDetails';
import type ReportAction from '@src/types/onyx/ReportAction';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import applyOnyxUpdatesReliably from './applyOnyxUpdatesReliably';
import * as Link from './Link';
import * as Report from './Report';
import * as Session from './Session';
let currentUserAccountID = -1;
let currentEmail = '';
Onyx.connect({
key: ONYXKEYS.SESSION,
callback: (value) => {
currentUserAccountID = value?.accountID ?? -1;
currentEmail = value?.email ?? '';
},
});
let myPersonalDetails: OnyxEntry<OnyxPersonalDetails>;
Onyx.connect({
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
callback: (value) => {
if (!value || currentUserAccountID === -1) {
return;
}
myPersonalDetails = value[currentUserAccountID] ?? undefined;
},
});
let allPolicies: OnyxCollection<Policy>;
Onyx.connect({
key: ONYXKEYS.COLLECTION.POLICY,
waitForCollectionCallback: true,
callback: (value) => (allPolicies = value),
});
/**
* Attempt to close the user's accountt
*/
function closeAccount(reason: string) {
// Note: successData does not need to set isLoading to false because if the CloseAccount
// command succeeds, a Pusher response will clear all Onyx data.
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.FORMS.CLOSE_ACCOUNT_FORM,
value: {isLoading: true},
},
];
const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.FORMS.CLOSE_ACCOUNT_FORM,
value: {isLoading: false},
},
];
const parameters: CloseAccountParams = {message: reason};
API.write(WRITE_COMMANDS.CLOSE_ACCOUNT, parameters, {
optimisticData,
failureData,
});
}
/**
* Resends a validation link to a given login
*/
function resendValidateCode(login: string) {
Session.resendValidateCode(login);
}
/**
* Requests a new validate code be sent for the passed contact method
*
* @param contactMethod - the new contact method that the user is trying to verify
*/
function requestContactMethodValidateCode(contactMethod: string) {
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
value: {
[contactMethod]: {
validateCodeSent: false,
errorFields: {
validateCodeSent: null,
validateLogin: null,
},
pendingFields: {
validateCodeSent: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE,
},
},
},
},
];
const successData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
value: {
[contactMethod]: {
validateCodeSent: true,
pendingFields: {
validateCodeSent: null,
},
},
},
},
];
const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
value: {
[contactMethod]: {
validateCodeSent: false,
errorFields: {
validateCodeSent: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('contacts.genericFailureMessages.requestContactMethodValidateCode'),
},
pendingFields: {
validateCodeSent: null,
},
},
},
},
];
const parameters: RequestContactMethodValidateCodeParams = {email: contactMethod};
API.write(WRITE_COMMANDS.REQUEST_CONTACT_METHOD_VALIDATE_CODE, parameters, {optimisticData, successData, failureData});
}
/**
* Sets whether the user is subscribed to Expensify news
*/
function updateNewsletterSubscription(isSubscribed: boolean) {
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.USER,
value: {isSubscribedToNewsletter: isSubscribed},
},
];
const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.USER,
value: {isSubscribedToNewsletter: !isSubscribed},
},
];
const parameters: UpdateNewsletterSubscriptionParams = {isSubscribed};
API.write(WRITE_COMMANDS.UPDATE_NEWSLETTER_SUBSCRIPTION, parameters, {
optimisticData,
failureData,
});
}
/**
* Delete a specific contact method
* @param contactMethod - the contact method being deleted
* @param loginList
*/
function deleteContactMethod(contactMethod: string, loginList: Record<string, Login>, backTo?: string) {
const oldLoginData = loginList[contactMethod];
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
value: {
[contactMethod]: {
partnerUserID: '',
errorFields: null,
pendingFields: {
deletedLogin: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE,
},
},
},
},
];
const successData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
value: {
[contactMethod]: null,
},
},
];
const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
value: {
[contactMethod]: {
...oldLoginData,
errorFields: {
...oldLoginData?.errorFields,
deletedLogin: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('contacts.genericFailureMessages.deleteContactMethod'),
},
pendingFields: {
deletedLogin: null,
},
},
},
},
];
const parameters: DeleteContactMethodParams = {partnerUserID: contactMethod};
API.write(WRITE_COMMANDS.DELETE_CONTACT_METHOD, parameters, {optimisticData, successData, failureData});
Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS.getRoute(backTo));
}
/**
* Clears a contact method optimistically. this is used when the contact method fails to be added to the backend
*/
function clearContactMethod(contactMethod: string) {
Onyx.merge(ONYXKEYS.LOGIN_LIST, {
[contactMethod]: null,
});
}
/**
* Clears error for a sepcific field on validate action code.
*/
function clearValidateCodeActionError(fieldName: string) {
Onyx.merge(ONYXKEYS.VALIDATE_ACTION_CODE, {
errorFields: {
[fieldName]: null,
},
});
}
/**
* Clears any possible stored errors for a specific field on a contact method
*/
function clearContactMethodErrors(contactMethod: string, fieldName: string) {
Onyx.merge(ONYXKEYS.LOGIN_LIST, {
[contactMethod]: {
errorFields: {
[fieldName]: null,
},
pendingFields: {
[fieldName]: null,
},
},
});
}
/**
* Resets the state indicating whether a validation code has been sent to a specific contact method.
*
* @param contactMethod - The identifier of the contact method to reset.
*/
function resetContactMethodValidateCodeSentState(contactMethod: string) {
Onyx.merge(ONYXKEYS.LOGIN_LIST, {
[contactMethod]: {
validateCodeSent: false,
},
});
}
/**
* Clears unvalidated new contact method action
*/
function clearUnvalidatedNewContactMethodAction() {
Onyx.merge(ONYXKEYS.PENDING_CONTACT_ACTION, {
validateCodeSent: null,
pendingFields: null,
errorFields: null,
});
}
/**
* When user adds a new contact method, they need to verify the magic code first
* So we add the temporary contact method to Onyx to use it later, after user verified magic code.
*/
function addPendingContactMethod(contactMethod: string) {
Onyx.merge(ONYXKEYS.PENDING_CONTACT_ACTION, {
contactMethod,
});
}
/**
* Validates the action to add secondary contact method
*/
function saveNewContactMethodAndRequestValidationCode(contactMethod: string) {
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.PENDING_CONTACT_ACTION,
value: {
contactMethod,
errorFields: {
actionVerified: null,
},
pendingFields: {
actionVerified: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
},
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.FORMS.NEW_CONTACT_METHOD_FORM,
value: {isLoading: true},
},
];
const successData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.PENDING_CONTACT_ACTION,
value: {
validateCodeSent: true,
errorFields: {
actionVerified: null,
},
pendingFields: {
actionVerified: null,
},
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.FORMS.NEW_CONTACT_METHOD_FORM,
value: {isLoading: false},
},
];
const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.PENDING_CONTACT_ACTION,
value: {
validateCodeSent: null,
errorFields: {
actionVerified: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('contacts.genericFailureMessages.requestContactMethodValidateCode'),
},
pendingFields: {
actionVerified: null,
},
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.FORMS.NEW_CONTACT_METHOD_FORM,
value: {isLoading: false},
},
];
API.write(WRITE_COMMANDS.RESEND_VALIDATE_CODE, null, {optimisticData, successData, failureData});
}
/**
* Adds a secondary login to a user's account
*/
function addNewContactMethod(contactMethod: string, validateCode = '') {
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
value: {
[contactMethod]: {
partnerUserID: contactMethod,
validatedDate: '',
errorFields: {
addedLogin: null,
},
pendingFields: {
addedLogin: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
},
},
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {isLoading: true},
},
];
const successData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
value: {
[contactMethod]: {
pendingFields: {
addedLogin: null,
},
},
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.PENDING_CONTACT_ACTION,
value: {
validateCodeSent: null,
errorFields: {
actionVerified: null,
},
pendingFields: {
actionVerified: null,
},
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {isLoading: false},
},
];
const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
value: {
[contactMethod]: {
errorFields: {
addedLogin: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('contacts.genericFailureMessages.addContactMethod'),
},
pendingFields: {
addedLogin: null,
},
},
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {isLoading: false},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.PENDING_CONTACT_ACTION,
value: {validateCodeSent: null},
},
];
const parameters: AddNewContactMethodParams = {partnerUserID: contactMethod, validateCode};
API.write(WRITE_COMMANDS.ADD_NEW_CONTACT_METHOD, parameters, {optimisticData, successData, failureData});
}
/**
* Requests a magic code to verify current user
*/
function requestValidateCodeAction() {
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.VALIDATE_ACTION_CODE,
value: {
isLoading: true,
pendingFields: {
actionVerified: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
},
errorFields: {
actionVerified: null,
},
},
},
];
const successData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.VALIDATE_ACTION_CODE,
value: {
validateCodeSent: true,
isLoading: false,
errorFields: {
actionVerified: null,
},
pendingFields: {
actionVerified: null,
},
},
},
];
const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.VALIDATE_ACTION_CODE,
value: {
validateCodeSent: null,
isLoading: false,
errorFields: {
actionVerified: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('contacts.genericFailureMessages.requestContactMethodValidateCode'),
},
pendingFields: {
actionVerified: null,
},
},
},
];
API.write(WRITE_COMMANDS.RESEND_VALIDATE_CODE, null, {optimisticData, successData, failureData});
}
/**
* Validates a login given an accountID and validation code
*/
function validateLogin(accountID: number, validateCode: string) {
Onyx.merge(ONYXKEYS.ACCOUNT, {...CONST.DEFAULT_ACCOUNT_DATA, isLoading: true});
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
isLoading: false,
},
},
];
const parameters: ValidateLoginParams = {accountID, validateCode};
API.write(WRITE_COMMANDS.VALIDATE_LOGIN, parameters, {optimisticData});
Navigation.navigate(ROUTES.HOME);
}
/**
* Validates a secondary login / contact method
*/
function validateSecondaryLogin(loginList: OnyxEntry<LoginList>, contactMethod: string, validateCode: string) {
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
value: {
[contactMethod]: {
errorFields: {
validateLogin: null,
validateCodeSent: null,
},
pendingFields: {
validateLogin: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE,
},
},
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
...CONST.DEFAULT_ACCOUNT_DATA,
isLoading: true,
},
},
];
const successData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
value: {
[contactMethod]: {
validatedDate: DateUtils.getDBTime(),
pendingFields: {
validateLogin: null,
},
errorFields: {
validateCodeSent: null,
},
},
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {isLoading: false},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.USER,
value: {
validated: true,
},
},
];
// If the primary login isn't validated yet, set the secondary login as the primary login
if (!loginList?.[currentEmail].validatedDate) {
successData.push(
...[
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
primaryLogin: contactMethod,
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.SESSION,
value: {
email: contactMethod,
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
value: {
[currentUserAccountID]: {
login: contactMethod,
displayName: PersonalDetailsUtils.createDisplayName(contactMethod, myPersonalDetails),
},
},
},
],
);
Object.values(allPolicies ?? {}).forEach((policy) => {
if (!policy) {
return;
}
let optimisticPolicyDataValue;
if (policy.employeeList) {
const currentEmployee = policy.employeeList[currentEmail];
optimisticPolicyDataValue = {
employeeList: {
[currentEmail]: null,
[contactMethod]: currentEmployee,
},
};
}
if (policy.ownerAccountID === currentUserAccountID) {
optimisticPolicyDataValue = {
...optimisticPolicyDataValue,
owner: contactMethod,
};
}
if (optimisticPolicyDataValue) {
successData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.POLICY}${policy.id}`,
value: optimisticPolicyDataValue,
});
}
});
}
const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
value: {
[contactMethod]: {
errorFields: {
validateLogin: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('contacts.genericFailureMessages.validateSecondaryLogin'),
validateCodeSent: null,
},
pendingFields: {
validateLogin: null,
},
},
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {isLoading: false},
},
];
const parameters: ValidateSecondaryLoginParams = {partnerUserID: contactMethod, validateCode};
API.write(WRITE_COMMANDS.VALIDATE_SECONDARY_LOGIN, parameters, {optimisticData, successData, failureData});
}
/**
* Checks the blockedFromConcierge object to see if it has an expiresAt key,
* and if so whether the expiresAt date of a user's ban is before right now
*
*/
function isBlockedFromConcierge(blockedFromConciergeNVP: OnyxEntry<BlockedFromConcierge>): boolean {
if (isEmptyObject(blockedFromConciergeNVP)) {
return false;
}
if (!blockedFromConciergeNVP?.expiresAt) {
return false;
}
return isBefore(new Date(), new Date(blockedFromConciergeNVP.expiresAt));
}
function triggerNotifications(onyxUpdates: OnyxServerUpdate[]) {
onyxUpdates.forEach((update) => {
if (!update.shouldNotify && !update.shouldShowPushNotification) {
return;
}
const reportID = update.key.replace(ONYXKEYS.COLLECTION.REPORT_ACTIONS, '');
const reportActions = Object.values((update.value as OnyxCollection<ReportAction>) ?? {});
reportActions.forEach((action) => action && ReportActionsUtils.isNotifiableReportAction(action) && Report.showReportActionNotification(reportID, action));
});
}
const isChannelMuted = (reportId: string) =>
new Promise((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT}${reportId}`,
callback: (report) => {
Onyx.disconnect(connection);
const notificationPreference = report?.participants?.[currentUserAccountID]?.notificationPreference;
resolve(
!notificationPreference || notificationPreference === CONST.REPORT.NOTIFICATION_PREFERENCE.MUTE || notificationPreference === CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN,
);
},
});
});
function playSoundForMessageType(pushJSON: OnyxServerUpdate[]) {
const reportActionsOnly = pushJSON.filter((update) => update.key?.includes('reportActions_'));
// "reportActions_5134363522480668" -> "5134363522480668"
const reportID = reportActionsOnly
.map((value) => value.key.split('_')[1])
.find((reportKey) => reportKey === Navigation.getTopmostReportId() && Visibility.isVisible() && Visibility.hasFocus());
if (!reportID) {
return;
}
isChannelMuted(reportID).then((isSoundMuted) => {
if (isSoundMuted) {
return;
}
try {
const flatten = reportActionsOnly.flatMap((update) => {
const value = update.value as OnyxCollection<ReportAction>;
if (!value) {
return [];
}
return Object.values(value);
}) as ReportAction[];
for (const data of flatten) {
// Someone completes a task
if (data.actionName === 'TASKCOMPLETED') {
return playSound(SOUNDS.SUCCESS);
}
}
const types = flatten.map((data) => ReportActionsUtils.getOriginalMessage(data)).filter(Boolean);
for (const message of types) {
if (!message) {
return;
}
// Pay someone flow
if ('IOUDetails' in message) {
return playSound(SOUNDS.SUCCESS);
}
// mention user
if ('html' in message && typeof message.html === 'string' && message.html.includes(`<mention-user>@${currentEmail}</mention-user>`)) {
return playSoundExcludingMobile(SOUNDS.ATTENTION);
}
// mention @here
if ('html' in message && typeof message.html === 'string' && message.html.includes('<mention-here>')) {
return playSoundExcludingMobile(SOUNDS.ATTENTION);
}
// assign a task
if ('taskReportID' in message) {
return playSound(SOUNDS.ATTENTION);
}
// Submit expense flow
if ('IOUTransactionID' in message) {
return playSound(SOUNDS.ATTENTION);
}
// Someone reimburses an expense
if ('IOUReportID' in message) {
return playSound(SOUNDS.SUCCESS);
}
// plain message
if ('html' in message) {
return playSoundExcludingMobile(SOUNDS.RECEIVE);
}
}
} catch (e) {
let errorMessage = String(e);
if (e instanceof Error) {
errorMessage = e.message;
}
Log.client(`Unexpected error occurred while parsing the data to play a sound: ${errorMessage}`);
}
});
}
/**
* Handles the newest events from Pusher where a single mega multipleEvents contains
* an array of singular events all in one event
*/
function subscribeToUserEvents() {
// If we don't have the user's accountID yet (because the app isn't fully setup yet) we can't subscribe so return early
if (currentUserAccountID === -1) {
return;
}
// Handles the mega multipleEvents from Pusher which contains an array of single events.
// Each single event is passed to PusherUtils in order to trigger the callbacks for that event
PusherUtils.subscribeToPrivateUserChannelEvent(Pusher.TYPE.MULTIPLE_EVENTS, currentUserAccountID.toString(), (pushJSON) => {
// If this is not the main client, we shouldn't process any data received from pusher.
if (!ActiveClientManager.isClientTheLeader()) {
Log.info('[Pusher] Received updates, but ignoring it since this is not the active client');
return;
}
// The data for the update is an object, containing updateIDs from the server and an array of onyx updates (this array is the same format as the original format above)
// Example: {lastUpdateID: 1, previousUpdateID: 0, updates: [{onyxMethod: 'whatever', key: 'foo', value: 'bar'}]}
const updates = {
type: CONST.ONYX_UPDATE_TYPES.PUSHER,
lastUpdateID: Number(pushJSON.lastUpdateID || 0),
updates: pushJSON.updates ?? [],
previousUpdateID: Number(pushJSON.previousUpdateID || 0),
};
applyOnyxUpdatesReliably(updates);
});
// Handles Onyx updates coming from Pusher through the mega multipleEvents.
PusherUtils.subscribeToMultiEvent(Pusher.TYPE.MULTIPLE_EVENT_TYPE.ONYX_API_UPDATE, (pushJSON: OnyxServerUpdate[]) => {
playSoundForMessageType(pushJSON);
return SequentialQueue.getCurrentRequest().then(() => {
// If we don't have the currentUserAccountID (user is logged out) or this is not the
// main client we don't want to update Onyx with data from Pusher
if (currentUserAccountID === -1) {
return;
}
if (!ActiveClientManager.isClientTheLeader()) {
Log.info('[Pusher] Received updates, but ignoring it since this is not the active client');
return;
}
const onyxUpdatePromise = Onyx.update(pushJSON).then(() => {
triggerNotifications(pushJSON);
});
// Return a promise when Onyx is done updating so that the OnyxUpdatesManager can properly apply all
// the onyx updates in order
return onyxUpdatePromise;
});
});
}
/**
* Sync preferredSkinTone with Onyx and Server
*/
function updatePreferredSkinTone(skinTone: number) {
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.SET,
key: ONYXKEYS.PREFERRED_EMOJI_SKIN_TONE,
value: skinTone,
},
];
const parameters: UpdatePreferredEmojiSkinToneParams = {value: skinTone};
API.write(WRITE_COMMANDS.UPDATE_PREFERRED_EMOJI_SKIN_TONE, parameters, {optimisticData});
}
/**
* Sync user chat priority mode with Onyx and Server
* @param mode
* @param [automatic] if we changed the mode automatically
*/
function updateChatPriorityMode(mode: ValueOf<typeof CONST.PRIORITY_MODE>, automatic = false) {
const autoSwitchedToFocusMode = mode === CONST.PRIORITY_MODE.GSD && automatic;
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.NVP_PRIORITY_MODE,
value: mode,
},
];
optimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.NVP_TRY_FOCUS_MODE,
value: true,
});
const parameters: UpdateChatPriorityModeParams = {
value: mode,
automatic,
};
API.write(WRITE_COMMANDS.UPDATE_CHAT_PRIORITY_MODE, parameters, {optimisticData});
if (!autoSwitchedToFocusMode) {
Navigation.goBack();
}
}
function clearFocusModeNotification() {
Onyx.set(ONYXKEYS.FOCUS_MODE_NOTIFICATION, false);
}
function setShouldUseStagingServer(shouldUseStagingServer: boolean) {
Onyx.merge(ONYXKEYS.USER, {shouldUseStagingServer});
}
function clearUserErrorMessage() {
Onyx.merge(ONYXKEYS.USER, {error: ''});
}
function setMuteAllSounds(isMutedAllSounds: boolean) {
Onyx.merge(ONYXKEYS.USER, {isMutedAllSounds});
}
/**
* Clear the data about a screen share request from Onyx.
*/
function clearScreenShareRequest() {
Onyx.set(ONYXKEYS.SCREEN_SHARE_REQUEST, null);
}
/**
* Open an OldDot tab linking to a screen share request.
* @param accessToken Access token required to join a screen share room, generated by the backend
* @param roomName Name of the screen share room to join
*/
function joinScreenShare(accessToken: string, roomName: string) {
Link.openOldDotLink(`inbox?action=screenShare&accessToken=${accessToken}&name=${roomName}`);
clearScreenShareRequest();
}
/**
* Downloads the statement PDF for the provided period
* @param period YYYYMM format
*/
function generateStatementPDF(period: string) {
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,