-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
OptionsListUtils.ts
2059 lines (1837 loc) · 81.8 KB
/
OptionsListUtils.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
/* eslint-disable no-continue */
import Str from 'expensify-common/lib/str';
// eslint-disable-next-line you-dont-need-lodash-underscore/get
import lodashGet from 'lodash/get';
import lodashOrderBy from 'lodash/orderBy';
import lodashSet from 'lodash/set';
import lodashSortBy from 'lodash/sortBy';
import Onyx from 'react-native-onyx';
import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
import type {SelectedTagOption} from '@components/TagPicker';
import CONST from '@src/CONST';
import type {TranslationPaths} from '@src/languages/types';
import ONYXKEYS from '@src/ONYXKEYS';
import type {
Beta,
Login,
PersonalDetails,
PersonalDetailsList,
Policy,
PolicyCategories,
PolicyTag,
PolicyTagList,
PolicyTags,
Report,
ReportAction,
ReportActions,
TaxRate,
TaxRates,
TaxRatesWithDefault,
Transaction,
TransactionViolation,
} from '@src/types/onyx';
import type {Participant} from '@src/types/onyx/IOU';
import type * as OnyxCommon from '@src/types/onyx/OnyxCommon';
import type DeepValueOf from '@src/types/utils/DeepValueOf';
import type {EmptyObject} from '@src/types/utils/EmptyObject';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import times from '@src/utils/times';
import Timing from './actions/Timing';
import * as CollectionUtils from './CollectionUtils';
import * as ErrorUtils from './ErrorUtils';
import localeCompare from './LocaleCompare';
import * as LocalePhoneNumber from './LocalePhoneNumber';
import * as Localize from './Localize';
import * as LoginUtils from './LoginUtils';
import ModifiedExpenseMessage from './ModifiedExpenseMessage';
import Navigation from './Navigation/Navigation';
import Performance from './Performance';
import Permissions from './Permissions';
import * as PersonalDetailsUtils from './PersonalDetailsUtils';
import * as PhoneNumber from './PhoneNumber';
import * as PolicyUtils from './PolicyUtils';
import * as ReportActionUtils from './ReportActionsUtils';
import * as ReportUtils from './ReportUtils';
import * as TaskUtils from './TaskUtils';
import * as TransactionUtils from './TransactionUtils';
import * as UserUtils from './UserUtils';
type Option = Partial<ReportUtils.OptionData>;
/**
* A narrowed version of `Option` is used when we have a guarantee that given values exist.
*/
type OptionTree = {
text: string;
keyForList: string;
searchText: string;
tooltipText: string;
isDisabled: boolean;
isSelected: boolean;
} & Option;
type PayeePersonalDetails = {
text: string;
alternateText: string;
icons: OnyxCommon.Icon[];
descriptiveText: string;
login: string;
accountID: number;
keyForList: string;
};
type CategorySectionBase = {
title: string | undefined;
shouldShow: boolean;
};
type CategorySection = CategorySectionBase & {
data: Option[];
};
type CategoryTreeSection = CategorySectionBase & {
data: OptionTree[];
};
type Category = {
name: string;
enabled: boolean;
isSelected?: boolean;
};
type Hierarchy = Record<string, Category & {[key: string]: Hierarchy & Category}>;
type GetOptionsConfig = {
reportActions?: ReportActions;
betas?: OnyxEntry<Beta[]>;
selectedOptions?: Option[];
maxRecentReportsToShow?: number;
excludeLogins?: string[];
includeMultipleParticipantReports?: boolean;
includePersonalDetails?: boolean;
includeRecentReports?: boolean;
includeSelfDM?: boolean;
sortByReportTypeInSearch?: boolean;
searchInputValue?: string;
showChatPreviewLine?: boolean;
sortPersonalDetailsByAlphaAsc?: boolean;
forcePolicyNamePreview?: boolean;
includeOwnedWorkspaceChats?: boolean;
includeThreads?: boolean;
includeTasks?: boolean;
includeMoneyRequests?: boolean;
excludeUnknownUsers?: boolean;
includeP2P?: boolean;
includeCategories?: boolean;
categories?: PolicyCategories;
recentlyUsedCategories?: string[];
includeTags?: boolean;
tags?: PolicyTags | Array<SelectedTagOption | PolicyTag>;
recentlyUsedTags?: string[];
canInviteUser?: boolean;
includeSelectedOptions?: boolean;
includeTaxRates?: boolean;
taxRates?: TaxRatesWithDefault;
transactionViolations?: OnyxCollection<TransactionViolation[]>;
};
type MemberForList = {
text: string;
alternateText: string;
keyForList: string;
isSelected: boolean;
isDisabled: boolean;
accountID?: number | null;
login: string;
icons?: OnyxCommon.Icon[];
pendingAction?: OnyxCommon.PendingAction;
reportID: string;
};
type SectionForSearchTerm = {
section: CategorySection;
};
type GetOptions = {
recentReports: ReportUtils.OptionData[];
personalDetails: ReportUtils.OptionData[];
userToInvite: ReportUtils.OptionData | null;
currentUserOption: ReportUtils.OptionData | null | undefined;
categoryOptions: CategoryTreeSection[];
tagOptions: CategorySection[];
taxRatesOptions: CategorySection[];
};
type PreviewConfig = {showChatPreviewLine?: boolean; forcePolicyNamePreview?: boolean};
/**
* OptionsListUtils is used to build a list options passed to the OptionsList component. Several different UI views can
* be configured to display different results based on the options passed to the private getOptions() method. Public
* methods should be named for the views they build options for and then exported for use in a component.
*/
let currentUserLogin: string | undefined;
let currentUserAccountID: number | undefined;
Onyx.connect({
key: ONYXKEYS.SESSION,
callback: (value) => {
currentUserLogin = value?.email;
currentUserAccountID = value?.accountID;
},
});
let loginList: OnyxEntry<Login>;
Onyx.connect({
key: ONYXKEYS.LOGIN_LIST,
callback: (value) => (loginList = isEmptyObject(value) ? {} : value),
});
let allPersonalDetails: OnyxEntry<PersonalDetailsList>;
Onyx.connect({
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
callback: (value) => (allPersonalDetails = isEmptyObject(value) ? {} : value),
});
let preferredLocale: DeepValueOf<typeof CONST.LOCALES> = CONST.LOCALES.DEFAULT;
Onyx.connect({
key: ONYXKEYS.NVP_PREFERRED_LOCALE,
callback: (value) => {
if (!value) {
return;
}
preferredLocale = value;
},
});
const policies: OnyxCollection<Policy> = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.POLICY,
callback: (policy, key) => {
if (!policy || !key || !policy.name) {
return;
}
policies[key] = policy;
},
});
const lastReportActions: ReportActions = {};
const allSortedReportActions: Record<string, ReportAction[]> = {};
const allReportActions: Record<string, ReportActions | null> = {};
const visibleReportActionItems: ReportActions = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT_ACTIONS,
callback: (actions, key) => {
if (!key || !actions) {
return;
}
const reportID = CollectionUtils.extractCollectionItemID(key);
allReportActions[reportID] = actions;
const sortedReportActions = ReportActionUtils.getSortedReportActions(Object.values(actions), true);
allSortedReportActions[reportID] = sortedReportActions;
lastReportActions[reportID] = sortedReportActions[0];
// The report is only visible if it is the last action not deleted that
// does not match a closed or created state.
const reportActionsForDisplay = sortedReportActions.filter(
(reportAction, actionKey) =>
ReportActionUtils.shouldReportActionBeVisible(reportAction, actionKey) &&
!ReportActionUtils.isWhisperAction(reportAction) &&
reportAction.actionName !== CONST.REPORT.ACTIONS.TYPE.CREATED &&
reportAction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE,
);
visibleReportActionItems[reportID] = reportActionsForDisplay[reportActionsForDisplay.length - 1];
},
});
let allTransactions: OnyxCollection<Transaction> = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.TRANSACTION,
waitForCollectionCallback: true,
callback: (value) => {
if (!value) {
return;
}
allTransactions = Object.keys(value)
.filter((key) => !!value[key])
.reduce((result: OnyxCollection<Transaction>, key) => {
if (result) {
// eslint-disable-next-line no-param-reassign
result[key] = value[key];
}
return result;
}, {});
},
});
/**
* @param defaultValues {login: accountID} In workspace invite page, when new user is added we pass available data to opt in
* @returns Returns avatar data for a list of user accountIDs
*/
function getAvatarsForAccountIDs(accountIDs: number[], personalDetails: OnyxEntry<PersonalDetailsList>, defaultValues: Record<string, number> = {}): OnyxCommon.Icon[] {
const reversedDefaultValues: Record<number, string> = {};
Object.entries(defaultValues).forEach((item) => {
reversedDefaultValues[item[1]] = item[0];
});
return accountIDs.map((accountID) => {
const login = reversedDefaultValues[accountID] ?? '';
const userPersonalDetail = personalDetails?.[accountID] ?? {login, accountID, avatar: ''};
return {
id: accountID,
source: UserUtils.getAvatar(userPersonalDetail.avatar, userPersonalDetail.accountID),
type: CONST.ICON_TYPE_AVATAR,
name: userPersonalDetail.login ?? '',
};
});
}
/**
* Returns the personal details for an array of accountIDs
* @returns keys of the object are emails, values are PersonalDetails objects.
*/
function getPersonalDetailsForAccountIDs(accountIDs: number[] | undefined, personalDetails: OnyxEntry<PersonalDetailsList>): PersonalDetailsList {
const personalDetailsForAccountIDs: PersonalDetailsList = {};
if (!personalDetails) {
return personalDetailsForAccountIDs;
}
accountIDs?.forEach((accountID) => {
const cleanAccountID = Number(accountID);
if (!cleanAccountID) {
return;
}
let personalDetail: OnyxEntry<PersonalDetails> = personalDetails[accountID];
if (!personalDetail) {
personalDetail = {
avatar: UserUtils.getDefaultAvatar(cleanAccountID),
} as PersonalDetails;
}
if (cleanAccountID === CONST.ACCOUNT_ID.CONCIERGE) {
personalDetail.avatar = CONST.CONCIERGE_ICON_URL;
}
personalDetail.accountID = cleanAccountID;
personalDetailsForAccountIDs[cleanAccountID] = personalDetail;
});
return personalDetailsForAccountIDs;
}
/**
* Return true if personal details data is ready, i.e. report list options can be created.
*/
function isPersonalDetailsReady(personalDetails: OnyxEntry<PersonalDetailsList>): boolean {
const personalDetailsKeys = Object.keys(personalDetails ?? {});
return personalDetailsKeys.some((key) => personalDetails?.[key]?.accountID);
}
/**
* Get the participant option for a report.
*/
function getParticipantsOption(participant: ReportUtils.OptionData, personalDetails: OnyxEntry<PersonalDetailsList>): Participant {
const detail = getPersonalDetailsForAccountIDs([participant.accountID ?? -1], personalDetails)[participant.accountID ?? -1];
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
const login = detail?.login || participant.login || '';
const displayName = PersonalDetailsUtils.getDisplayNameOrDefault(detail, LocalePhoneNumber.formatPhoneNumber(login));
return {
keyForList: String(detail?.accountID),
login,
accountID: detail?.accountID ?? -1,
text: displayName,
firstName: detail?.firstName ?? '',
lastName: detail?.lastName ?? '',
alternateText: LocalePhoneNumber.formatPhoneNumber(login) || displayName,
icons: [
{
source: UserUtils.getAvatar(detail?.avatar ?? '', detail?.accountID ?? -1),
name: login,
type: CONST.ICON_TYPE_AVATAR,
id: detail?.accountID,
},
],
phoneNumber: detail?.phoneNumber ?? '',
selected: participant.selected,
isSelected: participant.selected,
searchText: participant.searchText ?? undefined,
};
}
/**
* Constructs a Set with all possible names (displayName, firstName, lastName, email) for all participants in a report,
* to be used in isSearchStringMatch.
*/
function getParticipantNames(personalDetailList?: Array<Partial<PersonalDetails>> | null): Set<string> {
// We use a Set because `Set.has(value)` on a Set of with n entries is up to n (or log(n)) times faster than
// `_.contains(Array, value)` for an Array with n members.
const participantNames = new Set<string>();
personalDetailList?.forEach((participant) => {
if (participant.login) {
participantNames.add(participant.login.toLowerCase());
}
if (participant.firstName) {
participantNames.add(participant.firstName.toLowerCase());
}
if (participant.lastName) {
participantNames.add(participant.lastName.toLowerCase());
}
if (participant.displayName) {
participantNames.add(PersonalDetailsUtils.getDisplayNameOrDefault(participant).toLowerCase());
}
});
return participantNames;
}
/**
* A very optimized method to remove duplicates from an array.
* Taken from https://stackoverflow.com/a/9229821/9114791
*/
function uniqFast(items: string[]): string[] {
const seenItems: Record<string, number> = {};
const result: string[] = [];
let j = 0;
for (const item of items) {
if (seenItems[item] !== 1) {
seenItems[item] = 1;
result[j++] = item;
}
}
return result;
}
/**
* Returns a string with all relevant search terms.
* Default should be serachable by policy/domain name but not by participants.
*
* This method must be incredibly performant. It was found to be a big performance bottleneck
* when dealing with accounts that have thousands of reports. For loops are more efficient than _.each
* Array.prototype.push.apply is faster than using the spread operator, and concat() is faster than push().
*/
function getSearchText(
report: OnyxEntry<Report>,
reportName: string,
personalDetailList: Array<Partial<PersonalDetails>>,
isChatRoomOrPolicyExpenseChat: boolean,
isThread: boolean,
): string {
let searchTerms: string[] = [];
if (!isChatRoomOrPolicyExpenseChat) {
for (const personalDetail of personalDetailList) {
if (personalDetail.login) {
// The regex below is used to remove dots only from the local part of the user email (local-part@domain)
// so that we can match emails that have dots without explicitly writing the dots (e.g: fistlast@domain will match first.last@domain)
// More info https://github.com/Expensify/App/issues/8007
searchTerms = searchTerms.concat([
PersonalDetailsUtils.getDisplayNameOrDefault(personalDetail, '', false),
personalDetail.login,
personalDetail.login.replace(/\.(?=[^\s@]*@)/g, ''),
]);
}
}
}
if (report) {
Array.prototype.push.apply(searchTerms, reportName.split(/[,\s]/));
if (isThread) {
const title = ReportUtils.getReportName(report);
const chatRoomSubtitle = ReportUtils.getChatRoomSubtitle(report);
Array.prototype.push.apply(searchTerms, title.split(/[,\s]/));
Array.prototype.push.apply(searchTerms, chatRoomSubtitle?.split(/[,\s]/) ?? ['']);
} else if (isChatRoomOrPolicyExpenseChat) {
const chatRoomSubtitle = ReportUtils.getChatRoomSubtitle(report);
Array.prototype.push.apply(searchTerms, chatRoomSubtitle?.split(/[,\s]/) ?? ['']);
} else {
const visibleChatMemberAccountIDs = report.visibleChatMemberAccountIDs ?? [];
if (allPersonalDetails) {
for (const accountID of visibleChatMemberAccountIDs) {
const login = allPersonalDetails[accountID]?.login;
if (login) {
searchTerms = searchTerms.concat(login);
}
}
}
}
}
return uniqFast(searchTerms).join(' ');
}
/**
* Get an object of error messages keyed by microtime by combining all error objects related to the report.
*/
function getAllReportErrors(report: OnyxEntry<Report>, reportActions: OnyxEntry<ReportActions>): OnyxCommon.Errors {
const reportErrors = report?.errors ?? {};
const reportErrorFields = report?.errorFields ?? {};
const reportActionErrors: OnyxCommon.ErrorFields = Object.values(reportActions ?? {}).reduce(
(prevReportActionErrors, action) => (!action || isEmptyObject(action.errors) ? prevReportActionErrors : {...prevReportActionErrors, ...action.errors}),
{},
);
const parentReportAction: OnyxEntry<ReportAction> =
!report?.parentReportID || !report?.parentReportActionID ? null : allReportActions?.[report.parentReportID ?? '']?.[report.parentReportActionID ?? ''] ?? null;
if (parentReportAction?.actorAccountID === currentUserAccountID && ReportActionUtils.isTransactionThread(parentReportAction)) {
const transactionID = parentReportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.IOU ? parentReportAction?.originalMessage?.IOUTransactionID : null;
const transaction = allTransactions?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`];
if (TransactionUtils.hasMissingSmartscanFields(transaction ?? null) && !ReportUtils.isSettled(transaction?.reportID)) {
reportActionErrors.smartscan = ErrorUtils.getMicroSecondOnyxError('report.genericSmartscanFailureMessage');
}
} else if ((ReportUtils.isIOUReport(report) || ReportUtils.isExpenseReport(report)) && report?.ownerAccountID === currentUserAccountID) {
if (ReportUtils.hasMissingSmartscanFields(report?.reportID ?? '') && !ReportUtils.isSettled(report?.reportID)) {
reportActionErrors.smartscan = ErrorUtils.getMicroSecondOnyxError('report.genericSmartscanFailureMessage');
}
} else if (ReportUtils.hasSmartscanError(Object.values(reportActions ?? {}))) {
reportActionErrors.smartscan = ErrorUtils.getMicroSecondOnyxError('report.genericSmartscanFailureMessage');
}
// All error objects related to the report. Each object in the sources contains error messages keyed by microtime
const errorSources = {
reportErrors,
...reportErrorFields,
...reportActionErrors,
};
// Combine all error messages keyed by microtime into one object
const allReportErrors = Object.values(errorSources)?.reduce((prevReportErrors, errors) => (isEmptyObject(errors) ? prevReportErrors : {...prevReportErrors, ...errors}), {});
return allReportErrors;
}
/**
* Get the last actor display name from last actor details.
*/
function getLastActorDisplayName(lastActorDetails: Partial<PersonalDetails> | null, hasMultipleParticipants: boolean) {
return hasMultipleParticipants && lastActorDetails && lastActorDetails.accountID !== currentUserAccountID
? // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
lastActorDetails.firstName || PersonalDetailsUtils.getDisplayNameOrDefault(lastActorDetails)
: '';
}
/**
* Get the last message text from the report directly or from other sources for special cases.
*/
function getLastMessageTextForReport(report: OnyxEntry<Report>, lastActorDetails: Partial<PersonalDetails> | null, policy?: OnyxEntry<Policy>): string {
const lastReportAction = allSortedReportActions[report?.reportID ?? '']?.find((reportAction) => ReportActionUtils.shouldReportActionBeVisibleAsLastAction(reportAction)) ?? null;
// some types of actions are filtered out for lastReportAction, in some cases we need to check the actual last action
const lastOriginalReportAction = lastReportActions[report?.reportID ?? ''] ?? null;
let lastMessageTextFromReport = '';
if (ReportUtils.isArchivedRoom(report)) {
const archiveReason =
(lastOriginalReportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.CLOSED && lastOriginalReportAction?.originalMessage?.reason) || CONST.REPORT.ARCHIVE_REASON.DEFAULT;
switch (archiveReason) {
case CONST.REPORT.ARCHIVE_REASON.ACCOUNT_CLOSED:
case CONST.REPORT.ARCHIVE_REASON.REMOVED_FROM_POLICY:
case CONST.REPORT.ARCHIVE_REASON.POLICY_DELETED: {
lastMessageTextFromReport = Localize.translate(preferredLocale, `reportArchiveReasons.${archiveReason}`, {
displayName: PersonalDetailsUtils.getDisplayNameOrDefault(lastActorDetails),
policyName: ReportUtils.getPolicyName(report, false, policy),
});
break;
}
default: {
lastMessageTextFromReport = Localize.translate(preferredLocale, `reportArchiveReasons.default`);
}
}
} else if (ReportActionUtils.isMoneyRequestAction(lastReportAction)) {
const properSchemaForMoneyRequestMessage = ReportUtils.getReportPreviewMessage(report, lastReportAction, true, false, null, true);
lastMessageTextFromReport = ReportUtils.formatReportLastMessageText(properSchemaForMoneyRequestMessage);
} else if (ReportActionUtils.isReportPreviewAction(lastReportAction)) {
const iouReport = ReportUtils.getReport(ReportActionUtils.getIOUReportIDFromReportActionPreview(lastReportAction));
const lastIOUMoneyReportAction = allSortedReportActions[iouReport?.reportID ?? '']?.find(
(reportAction, key) =>
ReportActionUtils.shouldReportActionBeVisible(reportAction, key) &&
reportAction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE &&
ReportActionUtils.isMoneyRequestAction(reportAction),
);
lastMessageTextFromReport = ReportUtils.getReportPreviewMessage(
!isEmptyObject(iouReport) ? iouReport : null,
lastIOUMoneyReportAction,
true,
ReportUtils.isChatReport(report),
null,
true,
lastReportAction,
);
} else if (ReportActionUtils.isReimbursementQueuedAction(lastReportAction)) {
lastMessageTextFromReport = ReportUtils.getReimbursementQueuedActionMessage(lastReportAction, report);
} else if (ReportActionUtils.isReimbursementDeQueuedAction(lastReportAction)) {
lastMessageTextFromReport = ReportUtils.getReimbursementDeQueuedActionMessage(lastReportAction, report);
} else if (ReportActionUtils.isDeletedParentAction(lastReportAction) && ReportUtils.isChatReport(report)) {
lastMessageTextFromReport = ReportUtils.getDeletedParentActionMessageForChatReport(lastReportAction);
} else if (ReportActionUtils.isPendingRemove(lastReportAction) && ReportActionUtils.isThreadParentMessage(lastReportAction, report?.reportID ?? '')) {
lastMessageTextFromReport = Localize.translateLocal('parentReportAction.hiddenMessage');
} else if (ReportUtils.isReportMessageAttachment({text: report?.lastMessageText ?? '', html: report?.lastMessageHtml, translationKey: report?.lastMessageTranslationKey, type: ''})) {
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
lastMessageTextFromReport = `[${Localize.translateLocal((report?.lastMessageTranslationKey || 'common.attachment') as TranslationPaths)}]`;
} else if (ReportActionUtils.isModifiedExpenseAction(lastReportAction)) {
const properSchemaForModifiedExpenseMessage = ModifiedExpenseMessage.getForReportAction(report?.reportID, lastReportAction);
lastMessageTextFromReport = ReportUtils.formatReportLastMessageText(properSchemaForModifiedExpenseMessage, true);
} else if (ReportActionUtils.isTaskAction(lastReportAction)) {
lastMessageTextFromReport = ReportUtils.formatReportLastMessageText(TaskUtils.getTaskReportActionMessage(lastReportAction).text);
} else if (ReportActionUtils.isCreatedTaskReportAction(lastReportAction)) {
lastMessageTextFromReport = TaskUtils.getTaskCreatedMessage(lastReportAction);
} else if (ReportActionUtils.isApprovedOrSubmittedReportAction(lastReportAction)) {
lastMessageTextFromReport = ReportActionUtils.getReportActionMessageText(lastReportAction);
}
return lastMessageTextFromReport || (report?.lastMessageText ?? '');
}
/**
* Creates a report list option
*/
function createOption(
accountIDs: number[],
personalDetails: OnyxEntry<PersonalDetailsList>,
report: OnyxEntry<Report>,
reportActions: ReportActions,
{showChatPreviewLine = false, forcePolicyNamePreview = false}: PreviewConfig,
): ReportUtils.OptionData {
const result: ReportUtils.OptionData = {
text: undefined,
alternateText: null,
pendingAction: undefined,
allReportErrors: undefined,
brickRoadIndicator: null,
icons: undefined,
tooltipText: null,
ownerAccountID: undefined,
subtitle: null,
participantsList: undefined,
accountID: 0,
login: null,
reportID: '',
phoneNumber: null,
hasDraftComment: false,
keyForList: null,
searchText: null,
isDefaultRoom: false,
isPinned: false,
isWaitingOnBankAccount: false,
iouReportID: undefined,
isIOUReportOwner: null,
iouReportAmount: 0,
isChatRoom: false,
isArchivedRoom: false,
shouldShowSubscript: false,
isPolicyExpenseChat: false,
isOwnPolicyExpenseChat: false,
isExpenseReport: false,
policyID: undefined,
isOptimisticPersonalDetail: false,
};
const personalDetailMap = getPersonalDetailsForAccountIDs(accountIDs, personalDetails);
const personalDetailList = Object.values(personalDetailMap).filter((details): details is PersonalDetails => !!details);
const personalDetail = personalDetailList[0];
let hasMultipleParticipants = personalDetailList.length > 1;
let subtitle;
let reportName;
result.participantsList = personalDetailList;
result.isOptimisticPersonalDetail = personalDetail?.isOptimisticPersonalDetail;
if (report) {
result.isChatRoom = ReportUtils.isChatRoom(report);
result.isDefaultRoom = ReportUtils.isDefaultRoom(report);
result.isArchivedRoom = ReportUtils.isArchivedRoom(report);
result.isExpenseReport = ReportUtils.isExpenseReport(report);
result.isMoneyRequestReport = ReportUtils.isMoneyRequestReport(report);
result.isThread = ReportUtils.isChatThread(report);
result.isTaskReport = ReportUtils.isTaskReport(report);
result.shouldShowSubscript = ReportUtils.shouldReportShowSubscript(report);
result.isPolicyExpenseChat = ReportUtils.isPolicyExpenseChat(report);
result.isOwnPolicyExpenseChat = report.isOwnPolicyExpenseChat ?? false;
result.allReportErrors = getAllReportErrors(report, reportActions);
result.brickRoadIndicator = !isEmptyObject(result.allReportErrors) ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : '';
result.pendingAction = report.pendingFields ? report.pendingFields.addWorkspaceRoom ?? report.pendingFields.createChat : undefined;
result.ownerAccountID = report.ownerAccountID;
result.reportID = report.reportID;
result.isUnread = ReportUtils.isUnread(report);
result.hasDraftComment = report.hasDraft;
result.isPinned = report.isPinned;
result.iouReportID = report.iouReportID;
result.keyForList = String(report.reportID);
result.tooltipText = ReportUtils.getReportParticipantsTitle(report.visibleChatMemberAccountIDs ?? []);
result.isWaitingOnBankAccount = report.isWaitingOnBankAccount;
result.policyID = report.policyID;
result.isSelfDM = ReportUtils.isSelfDM(report);
hasMultipleParticipants = personalDetailList.length > 1 || result.isChatRoom || result.isPolicyExpenseChat;
subtitle = ReportUtils.getChatRoomSubtitle(report);
const lastActorDetails = personalDetailMap[report.lastActorAccountID ?? 0] ?? null;
const lastActorDisplayName = getLastActorDisplayName(lastActorDetails, hasMultipleParticipants);
const lastMessageTextFromReport = getLastMessageTextForReport(report, lastActorDetails);
let lastMessageText = lastMessageTextFromReport;
const lastAction = visibleReportActionItems[report.reportID];
const shouldDisplayLastActorName = lastAction && lastAction.actionName !== CONST.REPORT.ACTIONS.TYPE.REPORTPREVIEW && lastAction.actionName !== CONST.REPORT.ACTIONS.TYPE.IOU;
if (shouldDisplayLastActorName && lastActorDisplayName && lastMessageTextFromReport) {
lastMessageText = `${lastActorDisplayName}: ${lastMessageTextFromReport}`;
}
if (result.isThread || result.isMoneyRequestReport) {
result.alternateText = lastMessageTextFromReport.length > 0 ? lastMessageText : Localize.translate(preferredLocale, 'report.noActivityYet');
} else if (result.isChatRoom || result.isPolicyExpenseChat) {
result.alternateText = showChatPreviewLine && !forcePolicyNamePreview && lastMessageText ? lastMessageText : subtitle;
} else if (result.isTaskReport) {
result.alternateText = showChatPreviewLine && lastMessageText ? lastMessageText : Localize.translate(preferredLocale, 'report.noActivityYet');
} else {
result.alternateText = showChatPreviewLine && lastMessageText ? lastMessageText : LocalePhoneNumber.formatPhoneNumber(personalDetail?.login ?? '');
}
reportName = ReportUtils.getReportName(report);
} else {
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
reportName = ReportUtils.getDisplayNameForParticipant(accountIDs[0]) || LocalePhoneNumber.formatPhoneNumber(personalDetail?.login ?? '');
result.keyForList = String(accountIDs[0]);
result.alternateText = LocalePhoneNumber.formatPhoneNumber(personalDetails?.[accountIDs[0]]?.login ?? '');
}
result.isIOUReportOwner = ReportUtils.isIOUOwnedByCurrentUser(result);
result.iouReportAmount = ReportUtils.getMoneyRequestSpendBreakdown(result).totalDisplaySpend;
if (!hasMultipleParticipants) {
result.login = personalDetail?.login;
result.accountID = Number(personalDetail?.accountID);
result.phoneNumber = personalDetail?.phoneNumber;
}
result.text = reportName;
// Disabling this line for safeness as nullish coalescing works only if the value is undefined or null
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
result.searchText = getSearchText(report, reportName, personalDetailList, !!result.isChatRoom || !!result.isPolicyExpenseChat, !!result.isThread);
result.icons = ReportUtils.getIcons(
report,
personalDetails,
UserUtils.getAvatar(personalDetail?.avatar ?? '', personalDetail?.accountID),
personalDetail?.login,
personalDetail?.accountID,
);
result.subtitle = subtitle;
return result;
}
/**
* Get the option for a given report.
*/
function getReportOption(participant: Participant): ReportUtils.OptionData {
const report = ReportUtils.getReport(participant.reportID);
const option = createOption(
report?.visibleChatMemberAccountIDs ?? [],
allPersonalDetails ?? {},
!isEmptyObject(report) ? report : null,
{},
{
showChatPreviewLine: false,
forcePolicyNamePreview: false,
},
);
// Update text & alternateText because createOption returns workspace name only if report is owned by the user
if (option.isSelfDM) {
option.alternateText = Localize.translateLocal('reportActionsView.yourSpace');
} else {
option.text = ReportUtils.getPolicyName(report);
option.alternateText = Localize.translateLocal('workspace.common.workspace');
}
option.selected = participant.selected;
option.isSelected = participant.selected;
return option;
}
/**
* Get the option for a policy expense report.
*/
function getPolicyExpenseReportOption(participant: Participant | ReportUtils.OptionData): ReportUtils.OptionData {
const expenseReport = ReportUtils.isPolicyExpenseChat(participant) ? ReportUtils.getReport(participant.reportID) : null;
const option = createOption(
expenseReport?.visibleChatMemberAccountIDs ?? [],
allPersonalDetails ?? {},
!isEmptyObject(expenseReport) ? expenseReport : null,
{},
{
showChatPreviewLine: false,
forcePolicyNamePreview: false,
},
);
// Update text & alternateText because createOption returns workspace name only if report is owned by the user
option.text = ReportUtils.getPolicyName(expenseReport);
option.alternateText = Localize.translateLocal('workspace.common.workspace');
option.selected = participant.selected;
option.isSelected = participant.selected;
return option;
}
/**
* Searches for a match when provided with a value
*/
function isSearchStringMatch(searchValue: string, searchText?: string | null, participantNames = new Set<string>(), isChatRoom = false): boolean {
const searchWords = new Set(searchValue.replace(/,/g, ' ').split(' '));
const valueToSearch = searchText?.replace(new RegExp(/ /g), '');
let matching = true;
searchWords.forEach((word) => {
// if one of the word is not matching, we don't need to check further
if (!matching) {
return;
}
const matchRegex = new RegExp(Str.escapeForRegExp(word), 'i');
matching = matchRegex.test(valueToSearch ?? '') || (!isChatRoom && participantNames.has(word));
});
return matching;
}
/**
* Checks if the given userDetails is currentUser or not.
* Note: We can't migrate this off of using logins because this is used to check if you're trying to start a chat with
* yourself or a different user, and people won't be starting new chats via accountID usually.
*/
function isCurrentUser(userDetails: PersonalDetails): boolean {
if (!userDetails) {
return false;
}
// If user login is a mobile number, append sms domain if not appended already.
const userDetailsLogin = PhoneNumber.addSMSDomainIfPhoneNumber(userDetails.login ?? '');
if (currentUserLogin?.toLowerCase() === userDetailsLogin.toLowerCase()) {
return true;
}
// Check if userDetails login exists in loginList
return Object.keys(loginList ?? {}).some((login) => login.toLowerCase() === userDetailsLogin.toLowerCase());
}
/**
* Calculates count of all enabled options
*/
function getEnabledCategoriesCount(options: PolicyCategories): number {
return Object.values(options).filter((option) => option.enabled).length;
}
function getSearchValueForPhoneOrEmail(searchTerm: string) {
const parsedPhoneNumber = PhoneNumber.parsePhoneNumber(LoginUtils.appendCountryCode(Str.removeSMSDomain(searchTerm)));
return parsedPhoneNumber.possible ? parsedPhoneNumber.number?.e164 ?? '' : searchTerm.toLowerCase();
}
/**
* Verifies that there is at least one enabled option
*/
function hasEnabledOptions(options: PolicyCategories | PolicyTag[]): boolean {
return Object.values(options).some((option) => option.enabled);
}
/**
* Sorts categories using a simple object.
* It builds an hierarchy (based on an object), where each category has a name and other keys as subcategories.
* Via the hierarchy we avoid duplicating and sort categories one by one. Subcategories are being sorted alphabetically.
*/
function sortCategories(categories: Record<string, Category>): Category[] {
// Sorts categories alphabetically by name.
const sortedCategories = Object.values(categories).sort((a, b) => a.name.localeCompare(b.name));
// An object that respects nesting of categories. Also, can contain only uniq categories.
const hierarchy = {};
/**
* Iterates over all categories to set each category in a proper place in hierarchy
* It gets a path based on a category name e.g. "Parent: Child: Subcategory" -> "Parent.Child.Subcategory".
* {
* Parent: {
* name: "Parent",
* Child: {
* name: "Child"
* Subcategory: {
* name: "Subcategory"
* }
* }
* }
* }
*/
sortedCategories.forEach((category) => {
const path = category.name.split(CONST.PARENT_CHILD_SEPARATOR);
const existedValue = lodashGet(hierarchy, path, {});
lodashSet(hierarchy, path, {
...existedValue,
name: category.name,
});
});
/**
* A recursive function to convert hierarchy into an array of category objects.
* The category object contains base 2 properties: "name" and "enabled".
* It iterates each key one by one. When a category has subcategories, goes deeper into them. Also, sorts subcategories alphabetically.
*/
const flatHierarchy = (initialHierarchy: Hierarchy) =>
Object.values(initialHierarchy).reduce((acc: Category[], category) => {
const {name, ...subcategories} = category;
if (name) {
const categoryObject: Category = {
name,
enabled: categories[name]?.enabled ?? false,
};
acc.push(categoryObject);
}
if (!isEmptyObject(subcategories)) {
const nestedCategories = flatHierarchy(subcategories);
acc.push(...nestedCategories.sort((a, b) => a.name.localeCompare(b.name)));
}
return acc;
}, []);
return flatHierarchy(hierarchy);
}
/**
* Sorts tags alphabetically by name.
*/
function sortTags(tags: Record<string, PolicyTag | SelectedTagOption> | Array<PolicyTag | SelectedTagOption>) {
const sortedTags = Array.isArray(tags) ? tags : Object.values(tags);
// Use lodash's sortBy to ensure consistency with oldDot.
return lodashSortBy(sortedTags, 'name', localeCompare);
}
/**
* Builds the options for the category tree hierarchy via indents
*
* @param options - an initial object array
* @param options[].enabled - a flag to enable/disable option in a list
* @param options[].name - a name of an option
* @param [isOneLine] - a flag to determine if text should be one line
*/
function getCategoryOptionTree(options: Record<string, Category> | Category[], isOneLine = false, selectedOptionsName: string[] = []): OptionTree[] {
const optionCollection = new Map<string, OptionTree>();
Object.values(options).forEach((option) => {
if (isOneLine) {
if (optionCollection.has(option.name)) {
return;
}
optionCollection.set(option.name, {
text: option.name,
keyForList: option.name,
searchText: option.name,
tooltipText: option.name,
isDisabled: !option.enabled,
isSelected: !!option.isSelected,
});
return;
}
option.name.split(CONST.PARENT_CHILD_SEPARATOR).forEach((optionName, index, array) => {
const indents = times(index, () => CONST.INDENTS).join('');
const isChild = array.length - 1 === index;
const searchText = array.slice(0, index + 1).join(CONST.PARENT_CHILD_SEPARATOR);
if (optionCollection.has(searchText)) {
return;
}
optionCollection.set(searchText, {
text: `${indents}${optionName}`,
keyForList: searchText,
searchText,
tooltipText: optionName,
isDisabled: isChild ? !option.enabled : true,
isSelected: isChild ? !!option.isSelected : selectedOptionsName.includes(searchText),
});
});
});
return Array.from(optionCollection.values());
}
/**
* Builds the section list for categories
*/
function getCategoryListSections(
categories: PolicyCategories,
recentlyUsedCategories: string[],
selectedOptions: Category[],
searchInputValue: string,
maxRecentReportsToShow: number,
): CategoryTreeSection[] {
const sortedCategories = sortCategories(categories);
const enabledCategories = Object.values(sortedCategories).filter((category) => category.enabled);
const categorySections: CategoryTreeSection[] = [];
const numberOfEnabledCategories = enabledCategories.length;
if (numberOfEnabledCategories === 0 && selectedOptions.length > 0) {
categorySections.push({
// "Selected" section
title: '',
shouldShow: false,
data: getCategoryOptionTree(selectedOptions, true),
});
return categorySections;
}
if (searchInputValue) {
const searchCategories: Category[] = [];
enabledCategories.forEach((category) => {
if (!category.name.toLowerCase().includes(searchInputValue.toLowerCase())) {
return;
}
searchCategories.push({
...category,
isSelected: selectedOptions.some((selectedOption) => selectedOption.name === category.name),
});
});
categorySections.push({
// "Search" section
title: '',