-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
ReportUtils.ts
5425 lines (4830 loc) · 214 KB
/
ReportUtils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {format} from 'date-fns';
import ExpensiMark from 'expensify-common/lib/ExpensiMark';
import Str from 'expensify-common/lib/str';
import {isEmpty} from 'lodash';
import lodashEscape from 'lodash/escape';
import lodashFindLastIndex from 'lodash/findLastIndex';
import lodashIntersection from 'lodash/intersection';
import lodashIsEqual from 'lodash/isEqual';
import type {OnyxCollection, OnyxEntry, OnyxUpdate} from 'react-native-onyx';
import Onyx from 'react-native-onyx';
import type {ValueOf} from 'type-fest';
import type {FileObject} from '@components/AttachmentModal';
import * as Expensicons from '@components/Icon/Expensicons';
import * as defaultWorkspaceAvatars from '@components/Icon/WorkspaceDefaultAvatars';
import CONST from '@src/CONST';
import type {ParentNavigationSummaryParams, TranslationPaths} from '@src/languages/types';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Route} from '@src/ROUTES';
import ROUTES from '@src/ROUTES';
import type {
Beta,
PersonalDetails,
PersonalDetailsList,
Policy,
PolicyReportField,
PolicyReportFields,
Report,
ReportAction,
ReportMetadata,
Session,
Task,
Transaction,
TransactionViolation,
} from '@src/types/onyx';
import type {Participant} from '@src/types/onyx/IOU';
import type {Errors, Icon, PendingAction} from '@src/types/onyx/OnyxCommon';
import type {
ChangeLog,
IOUMessage,
OriginalMessageActionName,
OriginalMessageCreated,
OriginalMessageReimbursementDequeued,
OriginalMessageRenamed,
PaymentMethodType,
ReimbursementDeQueuedMessage,
} from '@src/types/onyx/OriginalMessage';
import type {Status} from '@src/types/onyx/PersonalDetails';
import type {NotificationPreference, PendingChatMember} from '@src/types/onyx/Report';
import type {Message, ReportActionBase, ReportActions} from '@src/types/onyx/ReportAction';
import type {Receipt, TransactionChanges, WaypointCollection} from '@src/types/onyx/Transaction';
import type {EmptyObject} from '@src/types/utils/EmptyObject';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import type IconAsset from '@src/types/utils/IconAsset';
import * as CollectionUtils from './CollectionUtils';
import * as CurrencyUtils from './CurrencyUtils';
import DateUtils from './DateUtils';
import isReportMessageAttachment from './isReportMessageAttachment';
import localeCompare from './LocaleCompare';
import * as LocalePhoneNumber from './LocalePhoneNumber';
import * as Localize from './Localize';
import {isEmailPublicDomain} from './LoginUtils';
import linkingConfig from './Navigation/linkingConfig';
import Navigation from './Navigation/Navigation';
import * as NumberUtils from './NumberUtils';
import Permissions from './Permissions';
import * as PersonalDetailsUtils from './PersonalDetailsUtils';
import * as PhoneNumber from './PhoneNumber';
import * as PolicyUtils from './PolicyUtils';
import type {LastVisibleMessage} from './ReportActionsUtils';
import * as ReportActionsUtils from './ReportActionsUtils';
import shouldAllowRawHTMLMessages from './shouldAllowRawHTMLMessages';
import * as TransactionUtils from './TransactionUtils';
import * as Url from './Url';
import * as UserUtils from './UserUtils';
type WelcomeMessage = {showReportName: boolean; phrase1?: string; phrase2?: string};
type ExpenseOriginalMessage = {
oldComment?: string;
newComment?: string;
comment?: string;
merchant?: string;
oldCreated?: string;
created?: string;
oldMerchant?: string;
oldAmount?: number;
amount?: number;
oldCurrency?: string;
currency?: string;
category?: string;
oldCategory?: string;
tag?: string;
oldTag?: string;
billable?: string;
oldBillable?: string;
};
type SpendBreakdown = {
nonReimbursableSpend: number;
reimbursableSpend: number;
totalDisplaySpend: number;
};
type ParticipantDetails = [number, string, UserUtils.AvatarSource, UserUtils.AvatarSource];
type OptimisticAddCommentReportAction = Pick<
ReportAction,
| 'reportActionID'
| 'actionName'
| 'actorAccountID'
| 'person'
| 'automatic'
| 'avatar'
| 'created'
| 'message'
| 'isFirstItem'
| 'isAttachment'
| 'attachmentInfo'
| 'pendingAction'
| 'shouldShow'
| 'originalMessage'
| 'childReportID'
| 'parentReportID'
| 'childType'
| 'childReportName'
| 'childManagerAccountID'
| 'childStatusNum'
| 'childStateNum'
| 'errors'
> & {isOptimisticAction: boolean};
type OptimisticReportAction = {
commentText: string;
reportAction: OptimisticAddCommentReportAction;
};
type UpdateOptimisticParentReportAction = {
childVisibleActionCount: number;
childCommenterCount: number;
childLastVisibleActionCreated: string;
childOldestFourAccountIDs: string | undefined;
};
type OptimisticExpenseReport = Pick<
Report,
| 'reportID'
| 'chatReportID'
| 'policyID'
| 'type'
| 'ownerAccountID'
| 'managerID'
| 'currency'
| 'reportName'
| 'stateNum'
| 'statusNum'
| 'total'
| 'notificationPreference'
| 'parentReportID'
| 'lastVisibleActionCreated'
>;
type OptimisticIOUReportAction = Pick<
ReportAction,
| 'actionName'
| 'actorAccountID'
| 'automatic'
| 'avatar'
| 'isAttachment'
| 'originalMessage'
| 'message'
| 'person'
| 'reportActionID'
| 'shouldShow'
| 'created'
| 'pendingAction'
| 'receipt'
| 'whisperedToAccountIDs'
>;
type ReportRouteParams = {
reportID: string;
isSubReportPageRoute: boolean;
};
type ReportOfflinePendingActionAndErrors = {
reportPendingAction: PendingAction | undefined;
reportErrors: Errors | null | undefined;
};
type OptimisticApprovedReportAction = Pick<
ReportAction,
'actionName' | 'actorAccountID' | 'automatic' | 'avatar' | 'isAttachment' | 'originalMessage' | 'message' | 'person' | 'reportActionID' | 'shouldShow' | 'created' | 'pendingAction'
>;
type OptimisticSubmittedReportAction = Pick<
ReportAction,
'actionName' | 'actorAccountID' | 'automatic' | 'avatar' | 'isAttachment' | 'originalMessage' | 'message' | 'person' | 'reportActionID' | 'shouldShow' | 'created' | 'pendingAction'
>;
type OptimisticHoldReportAction = Pick<
ReportAction,
'actionName' | 'actorAccountID' | 'automatic' | 'avatar' | 'isAttachment' | 'originalMessage' | 'message' | 'person' | 'reportActionID' | 'shouldShow' | 'created' | 'pendingAction'
>;
type OptimisticCancelPaymentReportAction = Pick<
ReportAction,
'actionName' | 'actorAccountID' | 'message' | 'originalMessage' | 'person' | 'reportActionID' | 'shouldShow' | 'created' | 'pendingAction'
>;
type OptimisticEditedTaskReportAction = Pick<
ReportAction,
'reportActionID' | 'actionName' | 'pendingAction' | 'actorAccountID' | 'automatic' | 'avatar' | 'created' | 'shouldShow' | 'message' | 'person'
>;
type OptimisticClosedReportAction = Pick<
ReportAction,
'actionName' | 'actorAccountID' | 'automatic' | 'avatar' | 'created' | 'message' | 'originalMessage' | 'pendingAction' | 'person' | 'reportActionID' | 'shouldShow'
>;
type OptimisticCreatedReportAction = OriginalMessageCreated &
Pick<ReportActionBase, 'actorAccountID' | 'automatic' | 'avatar' | 'created' | 'message' | 'person' | 'reportActionID' | 'shouldShow' | 'pendingAction'>;
type OptimisticRenamedReportAction = OriginalMessageRenamed &
Pick<ReportActionBase, 'actorAccountID' | 'automatic' | 'avatar' | 'created' | 'message' | 'person' | 'reportActionID' | 'shouldShow' | 'pendingAction'>;
type OptimisticChatReport = Pick<
Report,
| 'type'
| 'chatType'
| 'chatReportID'
| 'iouReportID'
| 'isOwnPolicyExpenseChat'
| 'isPinned'
| 'lastActorAccountID'
| 'lastMessageTranslationKey'
| 'lastMessageHtml'
| 'lastMessageText'
| 'lastReadTime'
| 'lastVisibleActionCreated'
| 'notificationPreference'
| 'oldPolicyName'
| 'ownerAccountID'
| 'pendingFields'
| 'parentReportActionID'
| 'parentReportID'
| 'participantAccountIDs'
| 'visibleChatMemberAccountIDs'
| 'policyID'
| 'reportID'
| 'reportName'
| 'stateNum'
| 'statusNum'
| 'visibility'
| 'description'
| 'writeCapability'
> & {
isOptimisticReport: true;
};
type OptimisticTaskReportAction = Pick<
ReportAction,
| 'reportActionID'
| 'actionName'
| 'actorAccountID'
| 'automatic'
| 'avatar'
| 'created'
| 'isAttachment'
| 'message'
| 'originalMessage'
| 'person'
| 'pendingAction'
| 'shouldShow'
| 'isFirstItem'
| 'previousMessage'
| 'errors'
| 'linkMetadata'
>;
type OptimisticWorkspaceChats = {
announceChatReportID: string;
announceChatData: OptimisticChatReport;
announceReportActionData: Record<string, OptimisticCreatedReportAction>;
announceCreatedReportActionID: string;
adminsChatReportID: string;
adminsChatData: OptimisticChatReport;
adminsReportActionData: Record<string, OptimisticCreatedReportAction>;
adminsCreatedReportActionID: string;
expenseChatReportID: string;
expenseChatData: OptimisticChatReport;
expenseReportActionData: Record<string, OptimisticCreatedReportAction>;
expenseCreatedReportActionID: string;
};
type OptimisticModifiedExpenseReportAction = Pick<
ReportAction,
'actionName' | 'actorAccountID' | 'automatic' | 'avatar' | 'created' | 'isAttachment' | 'message' | 'originalMessage' | 'person' | 'pendingAction' | 'reportActionID' | 'shouldShow'
> & {reportID?: string};
type OptimisticTaskReport = Pick<
Report,
| 'reportID'
| 'reportName'
| 'description'
| 'ownerAccountID'
| 'participantAccountIDs'
| 'visibleChatMemberAccountIDs'
| 'managerID'
| 'type'
| 'parentReportID'
| 'policyID'
| 'stateNum'
| 'statusNum'
| 'notificationPreference'
| 'parentReportActionID'
| 'lastVisibleActionCreated'
>;
type TransactionDetails = {
created: string;
amount: number;
currency: string;
merchant: string;
waypoints?: WaypointCollection | string;
comment: string;
category: string;
billable: boolean;
tag: string;
mccGroup?: ValueOf<typeof CONST.MCC_GROUPS>;
cardID: number;
originalAmount: number;
originalCurrency: string;
};
type OptimisticIOUReport = Pick<
Report,
| 'cachedTotal'
| 'type'
| 'chatReportID'
| 'currency'
| 'managerID'
| 'policyID'
| 'ownerAccountID'
| 'participantAccountIDs'
| 'visibleChatMemberAccountIDs'
| 'reportID'
| 'stateNum'
| 'statusNum'
| 'total'
| 'reportName'
| 'notificationPreference'
| 'parentReportID'
| 'lastVisibleActionCreated'
>;
type DisplayNameWithTooltips = Array<Pick<PersonalDetails, 'accountID' | 'pronouns' | 'displayName' | 'login' | 'avatar'>>;
type CustomIcon = {
src: IconAsset;
color?: string;
};
type OptionData = {
text?: string;
alternateText?: string | null;
allReportErrors?: Errors;
brickRoadIndicator?: ValueOf<typeof CONST.BRICK_ROAD_INDICATOR_STATUS> | '' | null;
tooltipText?: string | null;
alternateTextMaxLines?: number;
boldStyle?: boolean;
customIcon?: CustomIcon;
subtitle?: string | null;
login?: string | null;
accountID?: number | null;
pronouns?: string;
status?: Status | null;
phoneNumber?: string | null;
isUnread?: boolean | null;
isUnreadWithMention?: boolean | null;
hasDraftComment?: boolean | null;
keyForList?: string | null;
searchText?: string | null;
isIOUReportOwner?: boolean | null;
isArchivedRoom?: boolean | null;
shouldShowSubscript?: boolean | null;
isPolicyExpenseChat?: boolean | null;
isMoneyRequestReport?: boolean | null;
isExpenseRequest?: boolean | null;
isAllowedToComment?: boolean | null;
isThread?: boolean | null;
isTaskReport?: boolean | null;
parentReportAction?: OnyxEntry<ReportAction>;
displayNamesWithTooltips?: DisplayNameWithTooltips | null;
isDefaultRoom?: boolean;
isExpenseReport?: boolean;
isOptimisticPersonalDetail?: boolean;
selected?: boolean;
isOptimisticAccount?: boolean;
isSelected?: boolean;
descriptiveText?: string;
notificationPreference?: NotificationPreference | null;
isDisabled?: boolean | null;
name?: string | null;
isSelfDM?: boolean | null;
} & Report;
type OnyxDataTaskAssigneeChat = {
optimisticData: OnyxUpdate[];
successData: OnyxUpdate[];
failureData: OnyxUpdate[];
optimisticAssigneeAddComment?: OptimisticReportAction;
optimisticChatCreatedReportAction?: OptimisticCreatedReportAction;
};
type Ancestor = {
report: Report;
reportAction: ReportAction;
shouldDisplayNewMarker: boolean;
shouldHideThreadDividerLine: boolean;
};
type AncestorIDs = {
reportIDs: string[];
reportActionsIDs: string[];
};
let currentUserEmail: string | undefined;
let currentUserPrivateDomain: string | undefined;
let currentUserAccountID: number | undefined;
let isAnonymousUser = false;
const defaultAvatarBuildingIconTestID = 'SvgDefaultAvatarBuilding Icon';
Onyx.connect({
key: ONYXKEYS.SESSION,
callback: (value) => {
// When signed out, val is undefined
if (!value) {
return;
}
currentUserEmail = value.email;
currentUserAccountID = value.accountID;
isAnonymousUser = value.authTokenType === CONST.AUTH_TOKEN_TYPES.ANONYMOUS;
currentUserPrivateDomain = isEmailPublicDomain(currentUserEmail ?? '') ? '' : Str.extractEmailDomain(currentUserEmail ?? '');
},
});
let allPersonalDetails: OnyxCollection<PersonalDetails>;
let allPersonalDetailLogins: string[];
let currentUserPersonalDetails: OnyxEntry<PersonalDetails>;
Onyx.connect({
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
callback: (value) => {
currentUserPersonalDetails = value?.[currentUserAccountID ?? -1] ?? null;
allPersonalDetails = value ?? {};
allPersonalDetailLogins = Object.values(allPersonalDetails).map((personalDetail) => personalDetail?.login ?? '');
},
});
let allReports: OnyxCollection<Report>;
Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT,
waitForCollectionCallback: true,
callback: (value) => (allReports = value),
});
let doesDomainHaveApprovedAccountant = false;
Onyx.connect({
key: ONYXKEYS.ACCOUNT,
callback: (value) => (doesDomainHaveApprovedAccountant = value?.doesDomainHaveApprovedAccountant ?? false),
});
let allPolicies: OnyxCollection<Policy>;
Onyx.connect({
key: ONYXKEYS.COLLECTION.POLICY,
waitForCollectionCallback: true,
callback: (value) => (allPolicies = value),
});
let allPolicyReportFields: OnyxCollection<PolicyReportFields> = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.POLICY_REPORT_FIELDS,
waitForCollectionCallback: true,
callback: (value) => (allPolicyReportFields = value),
});
let allBetas: OnyxEntry<Beta[]>;
Onyx.connect({
key: ONYXKEYS.BETAS,
callback: (value) => (allBetas = value),
});
let allTransactions: OnyxCollection<Transaction> = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.TRANSACTION,
waitForCollectionCallback: true,
callback: (value) => {
if (!value) {
return;
}
allTransactions = Object.fromEntries(Object.entries(value).filter(([, transaction]) => transaction));
},
});
const reportActionsByReport: OnyxCollection<ReportActions> = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT_ACTIONS,
callback: (actions, key) => {
if (!key || !actions) {
return;
}
const reportID = CollectionUtils.extractCollectionItemID(key);
reportActionsByReport[reportID] = actions;
},
});
function getCurrentUserAvatarOrDefault(): UserUtils.AvatarSource {
return currentUserPersonalDetails?.avatar ?? UserUtils.getDefaultAvatarURL(currentUserAccountID);
}
function getCurrentUserDisplayNameOrEmail(): string | undefined {
return currentUserPersonalDetails?.displayName ?? currentUserEmail;
}
function getChatType(report: OnyxEntry<Report> | Participant | EmptyObject): ValueOf<typeof CONST.REPORT.CHAT_TYPE> | undefined {
return report?.chatType;
}
/**
* Get the report given a reportID
*/
function getReport(reportID: string | undefined): OnyxEntry<Report> | EmptyObject {
if (!allReports) {
return {};
}
return allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`] ?? {};
}
/**
* Returns the parentReport if the given report is a thread.
*/
function getParentReport(report: OnyxEntry<Report> | EmptyObject): OnyxEntry<Report> | EmptyObject {
if (!report?.parentReportID) {
return {};
}
return allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${report.parentReportID}`] ?? {};
}
/**
* Returns the root parentReport if the given report is nested.
* Uses recursion to iterate any depth of nested reports.
*/
function getRootParentReport(report: OnyxEntry<Report> | undefined | EmptyObject): OnyxEntry<Report> | EmptyObject {
if (!report) {
return {};
}
// Returns the current report as the root report, because it does not have a parentReportID
if (!report?.parentReportID) {
return report;
}
const parentReport = getReport(report?.parentReportID);
// Runs recursion to iterate a parent report
return getRootParentReport(!isEmptyObject(parentReport) ? parentReport : null);
}
function getPolicy(policyID: string | undefined): Policy | EmptyObject {
if (!allPolicies || !policyID) {
return {};
}
return allPolicies[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`] ?? {};
}
/**
* Get the policy type from a given report
* @param policies must have Onyxkey prefix (i.e 'policy_') for keys
*/
function getPolicyType(report: OnyxEntry<Report>, policies: OnyxCollection<Policy>): string {
return policies?.[`${ONYXKEYS.COLLECTION.POLICY}${report?.policyID}`]?.type ?? '';
}
/**
* Get the policy name from a given report
*/
function getPolicyName(report: OnyxEntry<Report> | undefined | EmptyObject, returnEmptyIfNotFound = false, policy: OnyxEntry<Policy> | undefined = undefined): string {
const noPolicyFound = returnEmptyIfNotFound ? '' : Localize.translateLocal('workspace.common.unavailable');
if (isEmptyObject(report)) {
return noPolicyFound;
}
if ((!allPolicies || Object.keys(allPolicies).length === 0) && !report?.policyName) {
return Localize.translateLocal('workspace.common.unavailable');
}
const finalPolicy = policy ?? allPolicies?.[`${ONYXKEYS.COLLECTION.POLICY}${report?.policyID}`];
const parentReport = getRootParentReport(report);
// Rooms send back the policy name with the reportSummary,
// since they can also be accessed by people who aren't in the workspace
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
const policyName = finalPolicy?.name || report?.policyName || report?.oldPolicyName || parentReport?.oldPolicyName || noPolicyFound;
return policyName;
}
/**
* Returns the concatenated title for the PrimaryLogins of a report
*/
function getReportParticipantsTitle(accountIDs: number[]): string {
// Somehow it's possible for the logins coming from report.participantAccountIDs to contain undefined values so we use .filter(Boolean) to remove them.
return accountIDs.filter(Boolean).join(', ');
}
/**
* Checks if a report is a chat report.
*/
function isChatReport(report: OnyxEntry<Report> | EmptyObject): boolean {
return report?.type === CONST.REPORT.TYPE.CHAT;
}
/**
* Checks if a report is an Expense report.
*/
function isExpenseReport(report: OnyxEntry<Report> | EmptyObject): boolean {
return report?.type === CONST.REPORT.TYPE.EXPENSE;
}
/**
* Checks if a report is an IOU report using report or reportID
*/
function isIOUReport(reportOrID: OnyxEntry<Report> | string | EmptyObject): boolean {
const report = typeof reportOrID === 'string' ? allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportOrID}`] ?? null : reportOrID;
return report?.type === CONST.REPORT.TYPE.IOU;
}
/**
* Checks if a report is an IOU report using report
*/
function isIOUReportUsingReport(report: OnyxEntry<Report> | EmptyObject): report is Report {
return report?.type === CONST.REPORT.TYPE.IOU;
}
/**
* Checks if a report is a task report.
*/
function isTaskReport(report: OnyxEntry<Report>): boolean {
return report?.type === CONST.REPORT.TYPE.TASK;
}
/**
* Checks if a task has been cancelled
* When a task is deleted, the parentReportAction is updated to have a isDeletedParentAction deleted flag
* This is because when you delete a task, we still allow you to chat on the report itself
* There's another situation where you don't have access to the parentReportAction (because it was created in a chat you don't have access to)
* In this case, we have added the key to the report itself
*/
function isCanceledTaskReport(report: OnyxEntry<Report> | EmptyObject = {}, parentReportAction: OnyxEntry<ReportAction> | EmptyObject = {}): boolean {
if (!isEmptyObject(parentReportAction) && (parentReportAction?.message?.[0]?.isDeletedParentAction ?? false)) {
return true;
}
if (!isEmptyObject(report) && report?.isDeletedParentAction) {
return true;
}
return false;
}
/**
* Checks if a report is an open task report.
*
* @param parentReportAction - The parent report action of the report (Used to check if the task has been canceled)
*/
function isOpenTaskReport(report: OnyxEntry<Report>, parentReportAction: OnyxEntry<ReportAction> | EmptyObject = {}): boolean {
return (
isTaskReport(report) && !isCanceledTaskReport(report, parentReportAction) && report?.stateNum === CONST.REPORT.STATE_NUM.OPEN && report?.statusNum === CONST.REPORT.STATUS_NUM.OPEN
);
}
/**
* Checks if a report is a completed task report.
*/
function isCompletedTaskReport(report: OnyxEntry<Report>): boolean {
return isTaskReport(report) && report?.stateNum === CONST.REPORT.STATE_NUM.APPROVED && report?.statusNum === CONST.REPORT.STATUS_NUM.APPROVED;
}
/**
* Checks if the current user is the manager of the supplied report
*/
function isReportManager(report: OnyxEntry<Report>): boolean {
return Boolean(report && report.managerID === currentUserAccountID);
}
/**
* Checks if the supplied report has been approved
*/
function isReportApproved(reportOrID: OnyxEntry<Report> | string | EmptyObject): boolean {
const report = typeof reportOrID === 'string' ? allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportOrID}`] ?? null : reportOrID;
return report?.stateNum === CONST.REPORT.STATE_NUM.APPROVED && report?.statusNum === CONST.REPORT.STATUS_NUM.APPROVED;
}
/**
* Checks if the supplied report is an expense report in Open state and status.
*/
function isOpenExpenseReport(report: OnyxEntry<Report> | EmptyObject): boolean {
return isExpenseReport(report) && report?.stateNum === CONST.REPORT.STATE_NUM.OPEN && report?.statusNum === CONST.REPORT.STATUS_NUM.OPEN;
}
/**
* Checks if the supplied report has a common policy member with the array passed in params.
*/
function hasParticipantInArray(report: Report, policyMemberAccountIDs: number[]) {
if (!report.participantAccountIDs) {
return false;
}
const policyMemberAccountIDsSet = new Set(policyMemberAccountIDs);
for (const reportParticipant of report.participantAccountIDs) {
if (policyMemberAccountIDsSet.has(reportParticipant)) {
return true;
}
}
return false;
}
/**
* Whether the Money Request report is settled
*/
function isSettled(reportID: string | undefined): boolean {
if (!allReports || !reportID) {
return false;
}
const report: Report | EmptyObject = allReports[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`] ?? {};
if (isEmptyObject(report) || report.isWaitingOnBankAccount) {
return false;
}
// In case the payment is scheduled and we are waiting for the payee to set up their wallet,
// consider the report as paid as well.
if (report.isWaitingOnBankAccount && report.statusNum === CONST.REPORT.STATUS_NUM.APPROVED) {
return true;
}
return report?.statusNum === CONST.REPORT.STATUS_NUM.REIMBURSED;
}
/**
* Whether the current user is the submitter of the report
*/
function isCurrentUserSubmitter(reportID: string): boolean {
if (!allReports) {
return false;
}
const report = allReports[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`];
return Boolean(report && report.ownerAccountID === currentUserAccountID);
}
/**
* Whether the provided report is an Admin room
*/
function isAdminRoom(report: OnyxEntry<Report>): boolean {
return getChatType(report) === CONST.REPORT.CHAT_TYPE.POLICY_ADMINS;
}
/**
* Whether the provided report is an Admin-only posting room
*/
function isAdminsOnlyPostingRoom(report: OnyxEntry<Report>): boolean {
return report?.writeCapability === CONST.REPORT.WRITE_CAPABILITIES.ADMINS;
}
/**
* Whether the provided report is a Announce room
*/
function isAnnounceRoom(report: OnyxEntry<Report>): boolean {
return getChatType(report) === CONST.REPORT.CHAT_TYPE.POLICY_ANNOUNCE;
}
/**
* Whether the provided report is a default room
*/
function isDefaultRoom(report: OnyxEntry<Report>): boolean {
return [CONST.REPORT.CHAT_TYPE.POLICY_ADMINS, CONST.REPORT.CHAT_TYPE.POLICY_ANNOUNCE, CONST.REPORT.CHAT_TYPE.DOMAIN_ALL].some((type) => type === getChatType(report));
}
/**
* Whether the provided report is a Domain room
*/
function isDomainRoom(report: OnyxEntry<Report>): boolean {
return getChatType(report) === CONST.REPORT.CHAT_TYPE.DOMAIN_ALL;
}
/**
* Whether the provided report is a user created policy room
*/
function isUserCreatedPolicyRoom(report: OnyxEntry<Report>): boolean {
return getChatType(report) === CONST.REPORT.CHAT_TYPE.POLICY_ROOM;
}
/**
* Whether the provided report is a Policy Expense chat.
*/
function isPolicyExpenseChat(report: OnyxEntry<Report> | Participant | EmptyObject): boolean {
return getChatType(report) === CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT || (report?.isPolicyExpenseChat ?? false);
}
/**
* Whether the provided report belongs to a Control policy and is an expense chat
*/
function isControlPolicyExpenseChat(report: OnyxEntry<Report>): boolean {
return isPolicyExpenseChat(report) && getPolicyType(report, allPolicies) === CONST.POLICY.TYPE.CORPORATE;
}
/**
* Whether the provided report belongs to a Free, Collect or Control policy
*/
function isGroupPolicy(report: OnyxEntry<Report>): boolean {
const policyType = getPolicyType(report, allPolicies);
return policyType === CONST.POLICY.TYPE.CORPORATE || policyType === CONST.POLICY.TYPE.TEAM || policyType === CONST.POLICY.TYPE.FREE;
}
/**
* Whether the provided report belongs to a Control or Collect policy
*/
function isPaidGroupPolicy(report: OnyxEntry<Report>): boolean {
const policyType = getPolicyType(report, allPolicies);
return policyType === CONST.POLICY.TYPE.CORPORATE || policyType === CONST.POLICY.TYPE.TEAM;
}
/**
* Whether the provided report belongs to a Control or Collect policy and is an expense chat
*/
function isPaidGroupPolicyExpenseChat(report: OnyxEntry<Report>): boolean {
return isPolicyExpenseChat(report) && isPaidGroupPolicy(report);
}
/**
* Whether the provided report belongs to a Control policy and is an expense report
*/
function isControlPolicyExpenseReport(report: OnyxEntry<Report>): boolean {
return isExpenseReport(report) && getPolicyType(report, allPolicies) === CONST.POLICY.TYPE.CORPORATE;
}
/**
* Whether the provided report belongs to a Control or Collect policy and is an expense report
*/
function isPaidGroupPolicyExpenseReport(report: OnyxEntry<Report>): boolean {
return isExpenseReport(report) && isPaidGroupPolicy(report);
}
/**
* Whether the provided report is a chat room
*/
function isChatRoom(report: OnyxEntry<Report>): boolean {
return isUserCreatedPolicyRoom(report) || isDefaultRoom(report);
}
/**
* Whether the provided report is a public room
*/
function isPublicRoom(report: OnyxEntry<Report>): boolean {
return report?.visibility === CONST.REPORT.VISIBILITY.PUBLIC || report?.visibility === CONST.REPORT.VISIBILITY.PUBLIC_ANNOUNCE;
}
/**
* Whether the provided report is a public announce room
*/
function isPublicAnnounceRoom(report: OnyxEntry<Report>): boolean {
return report?.visibility === CONST.REPORT.VISIBILITY.PUBLIC_ANNOUNCE;
}
/**
* If the report is a policy expense, the route should be for adding bank account for that policy
* else since the report is a personal IOU, the route should be for personal bank account.
*/
function getBankAccountRoute(report: OnyxEntry<Report>): Route {
return isPolicyExpenseChat(report) ? ROUTES.BANK_ACCOUNT_WITH_STEP_TO_OPEN.getRoute('', report?.policyID) : ROUTES.SETTINGS_ADD_BANK_ACCOUNT;
}
/**
* Check if personal detail of accountID is empty or optimistic data
*/
function isOptimisticPersonalDetail(accountID: number): boolean {
return isEmptyObject(allPersonalDetails?.[accountID]) || !!allPersonalDetails?.[accountID]?.isOptimisticPersonalDetail;
}
/**
* Checks if a report is a task report from a policy expense chat.
*/
function isWorkspaceTaskReport(report: OnyxEntry<Report>): boolean {
if (!isTaskReport(report)) {
return false;
}
const parentReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${report?.parentReportID}`] ?? null;
return isPolicyExpenseChat(parentReport);
}
/**
* Returns true if report has a parent
*/
function isThread(report: OnyxEntry<Report>): boolean {
return Boolean(report?.parentReportID && report?.parentReportActionID);
}
/**
* Returns true if report is of type chat and has a parent and is therefore a Thread.
*/
function isChatThread(report: OnyxEntry<Report>): boolean {
return isThread(report) && report?.type === CONST.REPORT.TYPE.CHAT;
}
function isDM(report: OnyxEntry<Report>): boolean {
return isChatReport(report) && !getChatType(report);
}
function isSelfDM(report: OnyxEntry<Report>): boolean {
return getChatType(report) === CONST.REPORT.CHAT_TYPE.SELF_DM;
}
/**
* Only returns true if this is our main 1:1 DM report with Concierge
*/
function isConciergeChatReport(report: OnyxEntry<Report>): boolean {
return report?.participantAccountIDs?.length === 1 && Number(report.participantAccountIDs?.[0]) === CONST.ACCOUNT_ID.CONCIERGE && !isChatThread(report);
}
/**
* Checks if the supplied report belongs to workspace based on the provided params. If the report's policyID is _FAKE_ or has no value, it means this report is a DM.
* In this case report and workspace members must be compared to determine whether the report belongs to the workspace.
*/
function doesReportBelongToWorkspace(report: Report, policyMemberAccountIDs: number[], policyID?: string) {
return (
isConciergeChatReport(report) || (report.policyID === CONST.POLICY.ID_FAKE || !report.policyID ? hasParticipantInArray(report, policyMemberAccountIDs) : report.policyID === policyID)
);
}
/**
* Given an array of reports, return them filtered by a policyID and policyMemberAccountIDs.
*/
function filterReportsByPolicyIDAndMemberAccountIDs(reports: Report[], policyMemberAccountIDs: number[] = [], policyID?: string) {
return reports.filter((report) => !!report && doesReportBelongToWorkspace(report, policyMemberAccountIDs, policyID));
}
/**
* Given an array of reports, return them sorted by the last read timestamp.
*/
function sortReportsByLastRead(reports: Report[], reportMetadata: OnyxCollection<ReportMetadata>): Array<OnyxEntry<Report>> {
return reports
.filter((report) => !!report?.reportID && !!(reportMetadata?.[`${ONYXKEYS.COLLECTION.REPORT_METADATA}${report.reportID}`]?.lastVisitTime ?? report?.lastReadTime))
.sort((a, b) => {
const aTime = new Date(reportMetadata?.[`${ONYXKEYS.COLLECTION.REPORT_METADATA}${a?.reportID}`]?.lastVisitTime ?? a?.lastReadTime ?? '');
const bTime = new Date(reportMetadata?.[`${ONYXKEYS.COLLECTION.REPORT_METADATA}${b?.reportID}`]?.lastVisitTime ?? b?.lastReadTime ?? '');
return aTime.valueOf() - bTime.valueOf();
});
}
/**
* Returns true if report is still being processed
*/
function isProcessingReport(report: OnyxEntry<Report> | EmptyObject): boolean {
return report?.stateNum === CONST.REPORT.STATE_NUM.SUBMITTED && report?.statusNum === CONST.REPORT.STATUS_NUM.SUBMITTED;
}
/**
* Check if the report is a single chat report that isn't a thread
* and personal detail of participant is optimistic data
*/
function shouldDisableDetailPage(report: OnyxEntry<Report>): boolean {
const participantAccountIDs = report?.participantAccountIDs ?? [];
if (isChatRoom(report) || isPolicyExpenseChat(report) || isChatThread(report) || isTaskReport(report)) {
return false;
}
if (participantAccountIDs.length === 1) {
return isOptimisticPersonalDetail(participantAccountIDs[0]);
}
return false;
}
/**
* Returns true if this report has only one participant and it's an Expensify account.
*/
function isExpensifyOnlyParticipantInReport(report: OnyxEntry<Report>): boolean {
const reportParticipants = report?.participantAccountIDs?.filter((accountID) => accountID !== currentUserAccountID) ?? [];
return reportParticipants.length === 1 && reportParticipants.some((accountID) => CONST.EXPENSIFY_ACCOUNT_IDS.includes(accountID));
}
/**
* Returns whether a given report can have tasks created in it.
* We only prevent the task option if it's a DM/group-DM and the other users are all special Expensify accounts
*
*/
function canCreateTaskInReport(report: OnyxEntry<Report>): boolean {