-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathSidebarUtils.ts
More file actions
1083 lines (984 loc) · 40.8 KB
/
Copy pathSidebarUtils.ts
File metadata and controls
1083 lines (984 loc) · 40.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {LocaleContextProps, LocalizedTranslate} from '@components/LocaleContextProvider';
import type {CurrencyListActionsContextType} from '@hooks/useCurrencyList';
import type {ReportsToDisplayInLHN} from '@hooks/useSidebarOrderedReports';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {
Card,
GuideAccountIDsDerivedValue,
PersonalDetails,
PersonalDetailsList,
PolicyTagLists,
ReportActions,
ReportAttributesDerivedValue,
ReportNameValuePairs,
Transaction,
TransactionViolation,
VisibleReportActionsDerivedValue,
} from '@src/types/onyx';
import type {ReportAttributes} from '@src/types/onyx/DerivedValues';
import type {Errors} from '@src/types/onyx/OnyxCommon';
import type Policy from '@src/types/onyx/Policy';
import type PriorityMode from '@src/types/onyx/PriorityMode';
import type Report from '@src/types/onyx/Report';
import type ReportAction from '@src/types/onyx/ReportAction';
import type Rule from '@src/types/onyx/Rule';
import type {Locale as DateFnsLocale} from 'date-fns';
import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
import type {ValueOf} from 'type-fest';
import {startOfDay, subMonths} from 'date-fns';
import type {OptionData} from './ReportUtils';
import {isAnonymousUser} from './actions/Session';
import DateUtils from './DateUtils';
import Log from './Log';
import {shouldUseFullTitleForOption} from './OptionsListUtils';
import {getPersonalDetailsForAccountIDs} from './PersonalDetailsUtils';
import {getIOUReportIDFromReportActionPreview, getReportAction} from './ReportActionsUtils';
import {getReportAlternateText, getWelcomeMessage} from './ReportAlternateTextUtils';
import {getReportName} from './ReportNameUtils';
import {
canUserPerformWriteAction as canUserPerformWriteActionUtil,
excludeParticipantsForDisplay,
getAllReportActionsErrorsAndReportActionThatRequiresAttention,
getChatRoomSubtitle,
getDisplayNamesWithTooltips,
getIcons,
getParticipantsAccountIDsForDisplay,
getPendingDeleteMemberAccountIDs,
getReceiptUploadErrorReason,
getReportMetadata,
getReportNotificationPreference,
getReportParticipantsTitle,
getViolatingReportIDForRBRInLHN,
hasExpensifyGuidesEmails,
hasReportErrorsOtherThanFailedReceipt,
isArchivedNonExpenseReport,
isArchivedReport,
isChatRoom,
isChatThread,
isConciergeChatReport,
isExpenseReport,
isExpenseRequest,
isHiddenForCurrentUser,
isInvoiceReport,
isIOUOwnedByCurrentUser,
isJoinRequestInAdminRoom,
isMoneyRequestReport,
isOneOnOneChat,
isOneTransactionThread,
isPolicyExpenseChat,
isPublicRoom,
isSelfDM,
isSystemChat as isSystemChatUtil,
isTaskReport,
isTripRoom,
isUnread,
isUnreadWithMention,
isWorkspaceTaskReport,
shouldReportBeInOptionList,
shouldReportShowSubscript,
} from './ReportUtils';
function compareStringDates(a: string, b: string): 0 | 1 | -1 {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
}
const NUMERIC_PAD_WIDTH = 15;
const DIGIT_SEQUENCE = /\d+/g;
/**
* Persists across renders so sort keys are computed at most once per unique display name.
*/
const sortKeyCache = new Map<string, string>();
/**
* Reports already reported by the `[ChatReportLHN]` diagnostic log, so a stuck row is logged once per session
* instead of on every LHN recompute.
*/
const loggedChatReportIDs = new Set<string>();
/**
* Builds a normalized sort key for fast string comparison using plain < / > operators.
* Lowercases the name and zero-pads numeric segments ("Report 2" → "report 000000000000002")
* so that numeric ordering is preserved without Intl.Collator.
*
* Results are cached at module level so each unique name pays the cost only once.
*/
function buildSortKey(displayName: string): string {
const cached = sortKeyCache.get(displayName);
if (cached !== undefined) {
return cached;
}
const key = displayName.toLowerCase().replaceAll(DIGIT_SEQUENCE, (match) => match.padStart(NUMERIC_PAD_WIDTH, '0'));
sortKeyCache.set(displayName, key);
return key;
}
/**
* A mini report object that contains only the necessary information to sort reports.
* This is used to avoid copying the entire report object and only the necessary information.
*/
type MiniReport = {
reportID?: string;
displayName: string;
sortKey: string;
lastVisibleActionCreated?: string;
};
type ShouldDisplayReportInLHNParams = {
report: Report;
reports: OnyxCollection<Report>;
currentReportId: string | undefined;
isInFocusMode: boolean;
isDefaultRoomsBetaEnabled: boolean;
transactionViolations: OnyxCollection<TransactionViolation[]>;
draftComment: OnyxEntry<string>;
transactions: OnyxCollection<Transaction>;
isOffline: boolean;
isReportArchived?: boolean;
reportAttributes?: ReportAttributesDerivedValue['reports'];
currentUserLogin: string;
currentUserAccountID: number;
hasGuidesEmails: boolean;
conciergeReportID: string | undefined;
};
function shouldDisplayReportInLHN({
report,
reports,
currentReportId,
isInFocusMode,
isDefaultRoomsBetaEnabled,
transactionViolations,
draftComment,
transactions,
isOffline,
isReportArchived,
reportAttributes,
currentUserAccountID,
currentUserLogin,
conciergeReportID,
hasGuidesEmails,
}: ShouldDisplayReportInLHNParams) {
if (!report) {
return {shouldDisplay: false};
}
if ((Object.values(CONST.REPORT.UNSUPPORTED_TYPE) as string[]).includes(report?.type ?? '')) {
return {shouldDisplay: false};
}
// Get report metadata and status
const parentReportAction = getReportAction(report?.parentReportID, report?.parentReportActionID);
const doesReportHaveViolations = !!getViolatingReportIDForRBRInLHN(report, transactionViolations);
const isHidden = isHiddenForCurrentUser(report);
const isFocused = report.reportID === currentReportId;
const chatReport = reports?.[`${ONYXKEYS.COLLECTION.REPORT}${report?.chatReportID}`];
const parentReport = reports?.[`${ONYXKEYS.COLLECTION.REPORT}${report.parentReportID}`];
const hasErrorsOtherThanFailedReceipt = hasReportErrorsOtherThanFailedReceipt(
report,
chatReport,
doesReportHaveViolations,
transactionViolations,
transactions,
isOffline,
reportAttributes,
);
const isReportInAccessible = report?.errorFields?.notFound;
if (isOneTransactionThread(report, parentReport, parentReportAction, isOffline)) {
return {shouldDisplay: false};
}
// Handle reports with errors
if (hasErrorsOtherThanFailedReceipt && !isReportInAccessible) {
return {shouldDisplay: true, hasErrorsOtherThanFailedReceipt: true};
}
// Check if report should override hidden status
const requiresAttention = reportAttributes?.[report?.reportID]?.requiresAttention;
const isSystemChat = isSystemChatUtil(report);
const shouldOverrideHidden =
!!draftComment ||
hasErrorsOtherThanFailedReceipt ||
isFocused ||
// An anonymous user can only access public rooms, and such a room's notification preference
// defaults to `hidden`. Without this, opening a thread inside the room (which steals focus)
// drops the room from the LHN, leaving the anon user unable to return to it. See #92672.
(isPublicRoom(report) && isAnonymousUser()) ||
isSystemChat ||
!!report.isPinned ||
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
requiresAttention ||
(report.isOwnPolicyExpenseChat && !isReportArchived);
if (isHidden && !shouldOverrideHidden) {
return {shouldDisplay: false};
}
// Final check for display eligibility
const shouldDisplay = shouldReportBeInOptionList({
report,
chatReport,
currentReportId,
isInFocusMode,
isDefaultRoomsBetaEnabled,
excludeEmptyChats: true,
doesReportHaveViolations,
draftComment,
includeSelfDM: true,
isReportArchived,
requiresAttention,
derivedIsEmptyReport: reportAttributes?.[report?.reportID]?.isEmpty,
currentUserLogin,
currentUserAccountID,
conciergeReportID,
hasGuidesEmails,
});
return {shouldDisplay};
}
function getReportsToDisplayInLHN({
currentReportId,
reports,
isDefaultRoomsBetaEnabled,
priorityMode,
draftComments,
transactionViolations,
transactions,
isOffline,
currentUserLogin,
currentUserAccountID,
reportNameValuePairs,
reportAttributes,
conciergeReportID,
guideAccountIDs,
}: {
currentReportId: string | undefined;
reports: OnyxCollection<Report>;
isDefaultRoomsBetaEnabled: boolean;
priorityMode: OnyxEntry<PriorityMode>;
draftComments: OnyxCollection<string>;
transactionViolations: OnyxCollection<TransactionViolation[]>;
transactions: OnyxCollection<Transaction>;
isOffline: boolean;
currentUserLogin: string;
currentUserAccountID: number;
reportNameValuePairs?: OnyxCollection<ReportNameValuePairs>;
reportAttributes?: ReportAttributesDerivedValue['reports'];
guideAccountIDs?: GuideAccountIDsDerivedValue;
conciergeReportID: string | undefined;
}) {
const isInFocusMode = priorityMode === CONST.PRIORITY_MODE.GSD;
const allReportsDictValues = reports ?? {};
const reportsToDisplay: ReportsToDisplayInLHN = {};
for (const [reportID, report] of Object.entries(allReportsDictValues)) {
if (!report) {
continue;
}
const reportDraftComment = draftComments?.[`${ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT}${report.reportID}`];
const isReportArchived = isArchivedReport(reportNameValuePairs?.[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${report.reportID}`]);
const {shouldDisplay, hasErrorsOtherThanFailedReceipt} = shouldDisplayReportInLHN({
report,
reports,
currentReportId,
isInFocusMode,
isDefaultRoomsBetaEnabled,
transactionViolations,
draftComment: reportDraftComment,
transactions,
isOffline,
isReportArchived,
reportAttributes,
currentUserLogin,
hasGuidesEmails: hasExpensifyGuidesEmails(Object.keys(report.participants ?? {}).map(Number), guideAccountIDs),
currentUserAccountID,
conciergeReportID,
});
if (shouldDisplay) {
const requiresAttention = reportAttributes?.[report?.reportID]?.requiresAttention ?? false;
const isUnreadReport = getIsUnreadReportForInboxTab(report, isReportArchived, reportAttributes?.[report?.reportID]?.isEmpty);
reportsToDisplay[reportID] =
requiresAttention || hasErrorsOtherThanFailedReceipt || isUnreadReport ? {...report, requiresAttention, hasErrorsOtherThanFailedReceipt, isUnreadReport} : report;
}
}
return reportsToDisplay;
}
type UpdateReportsToDisplayInLHNProps = {
displayedReports: ReportsToDisplayInLHN;
reports: OnyxCollection<Report>;
updatedReportsKeys: string[];
currentReportId: string | undefined;
isInFocusMode: boolean;
isDefaultRoomsBetaEnabled: boolean;
transactionViolations: OnyxCollection<TransactionViolation[]>;
reportNameValuePairs?: OnyxCollection<ReportNameValuePairs>;
reportAttributes?: ReportAttributesDerivedValue['reports'];
draftComments: OnyxCollection<string>;
transactions: OnyxCollection<Transaction>;
isOffline: boolean;
currentUserLogin: string;
currentUserAccountID: number;
guideAccountIDs?: GuideAccountIDsDerivedValue;
conciergeReportID: string | undefined;
};
function updateReportsToDisplayInLHN({
displayedReports,
reports,
updatedReportsKeys,
currentReportId,
isInFocusMode,
isDefaultRoomsBetaEnabled,
transactionViolations,
reportNameValuePairs,
reportAttributes,
draftComments,
transactions,
isOffline,
currentUserLogin,
currentUserAccountID,
conciergeReportID,
guideAccountIDs,
}: UpdateReportsToDisplayInLHNProps) {
// Use a lazy copy to avoid creating a new object reference when no entries actually change.
let displayedReportsCopy: ReportsToDisplayInLHN | undefined;
const getMutableCopy = (): ReportsToDisplayInLHN => {
if (!displayedReportsCopy) {
displayedReportsCopy = {...displayedReports};
}
return displayedReportsCopy;
};
for (const reportID of updatedReportsKeys) {
const report = reports?.[reportID];
if (!report) {
if (reportID in displayedReports) {
delete getMutableCopy()[reportID];
}
continue;
}
// Get the specific draft comment for this report instead of using a single draft comment for all reports
// This fixes the issue where the current report's draft comment was incorrectly used to filter all reports
const reportDraftComment = draftComments?.[`${ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT}${report.reportID}`];
const isReportArchived = isArchivedReport(reportNameValuePairs?.[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${report.reportID}`] ?? {});
const {shouldDisplay, hasErrorsOtherThanFailedReceipt} = shouldDisplayReportInLHN({
report,
reports,
currentReportId,
isInFocusMode,
isDefaultRoomsBetaEnabled,
transactionViolations,
draftComment: reportDraftComment,
transactions,
isOffline,
isReportArchived,
reportAttributes,
currentUserLogin,
hasGuidesEmails: hasExpensifyGuidesEmails(Object.keys(report.participants ?? {}).map(Number), guideAccountIDs),
currentUserAccountID,
conciergeReportID,
});
if (shouldDisplay) {
const requiresAttention = reportAttributes?.[report?.reportID]?.requiresAttention ?? false;
const isUnreadReport = getIsUnreadReportForInboxTab(report, isReportArchived, reportAttributes?.[report?.reportID]?.isEmpty);
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
const hasFlags = requiresAttention || hasErrorsOtherThanFailedReceipt || isUnreadReport;
const existingEntry = displayedReports[reportID];
if (hasFlags) {
if (
existingEntry !== report ||
existingEntry?.requiresAttention !== requiresAttention ||
existingEntry?.hasErrorsOtherThanFailedReceipt !== hasErrorsOtherThanFailedReceipt ||
existingEntry?.isUnreadReport !== isUnreadReport
) {
getMutableCopy()[reportID] = {...report, requiresAttention, hasErrorsOtherThanFailedReceipt, isUnreadReport};
}
} else if (existingEntry !== report) {
getMutableCopy()[reportID] = report;
}
} else if (reportID in displayedReports) {
delete getMutableCopy()[reportID];
}
}
return displayedReportsCopy ?? displayedReports;
}
/**
* Categorizes reports into their respective LHN groups
*/
function categorizeReportsForLHN(
reportsToDisplay: ReportsToDisplayInLHN,
reportsDrafts: Record<string, boolean> | undefined,
reportAttributes: ReportAttributesDerivedValue['reports'] | undefined,
reportNameValuePairs?: OnyxCollection<ReportNameValuePairs>,
) {
sortKeyCache.clear();
const pinnedAndGBRReports: MiniReport[] = [];
const errorReports: MiniReport[] = [];
const draftReports: MiniReport[] = [];
const nonArchivedReports: MiniReport[] = [];
const archivedReports: MiniReport[] = [];
for (const report of Object.values(reportsToDisplay)) {
if (!report) {
continue;
}
const reportID = report.reportID;
const displayName = getReportName(report, reportAttributes?.[report.reportID]?.reportName);
const miniReport: MiniReport = {
reportID,
displayName,
sortKey: buildSortKey(displayName),
lastVisibleActionCreated: report.lastVisibleActionCreated,
};
const isPinned = !!report.isPinned;
const requiresAttention = !!report?.requiresAttention;
if (isPinned || requiresAttention) {
pinnedAndGBRReports.push(miniReport);
continue;
}
const reportNameValuePairsKey = `${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${reportID}`;
const rNVPs = reportNameValuePairs?.[reportNameValuePairsKey];
const isArchived = isArchivedNonExpenseReport(report, !!rNVPs?.private_isArchived);
const hasErrors = !!report.hasErrorsOtherThanFailedReceipt && !isArchived;
if (hasErrors) {
errorReports.push(miniReport);
} else if (reportsDrafts?.[reportID]) {
draftReports.push(miniReport);
} else if (isArchived) {
archivedReports.push(miniReport);
} else {
nonArchivedReports.push(miniReport);
}
}
return {
pinnedAndGBRReports,
errorReports,
draftReports,
nonArchivedReports,
archivedReports,
};
}
/**
* Sorts categorized reports and returns new sorted arrays (pure function).
* This function does not mutate the input and returns new arrays for better testability.
*/
function sortCategorizedReports(
categories: {
pinnedAndGBRReports: MiniReport[];
errorReports: MiniReport[];
draftReports: MiniReport[];
nonArchivedReports: MiniReport[];
archivedReports: MiniReport[];
},
isInDefaultMode: boolean,
localeCompare: LocaleContextProps['localeCompare'],
): {
pinnedAndGBRReports: MiniReport[];
errorReports: MiniReport[];
draftReports: MiniReport[];
nonArchivedReports: MiniReport[];
archivedReports: MiniReport[];
} {
const {pinnedAndGBRReports, errorReports, draftReports, nonArchivedReports, archivedReports} = categories;
const compareDisplayNames = (a: MiniReport, b: MiniReport) => {
if (a.sortKey < b.sortKey) {
return -1;
}
if (a.sortKey > b.sortKey) {
return 1;
}
if (!a.displayName || !b.displayName) {
return 0;
}
// Sort keys tied — fall back to Collator for locale-correct ordering
return localeCompare(a.displayName, b.displayName);
};
const compareDatesDesc = (a: MiniReport, b: MiniReport) =>
a?.lastVisibleActionCreated && b?.lastVisibleActionCreated ? compareStringDates(b.lastVisibleActionCreated, a.lastVisibleActionCreated) : 0;
const compareNonArchivedDefault = (a: MiniReport, b: MiniReport) => {
const compareDates = compareDatesDesc(a, b);
return compareDates !== 0 ? compareDates : compareDisplayNames(a, b);
};
const sortIfNeeded = <T>(arr: T[], compareFn: (a: T, b: T) => number): T[] => (arr.length < 2 ? arr : arr.sort(compareFn));
// Sort each group of reports accordingly
const sortedPinnedAndGBRReports = sortIfNeeded(pinnedAndGBRReports, compareDisplayNames);
const sortedErrorReports = sortIfNeeded(errorReports, compareDisplayNames);
const sortedDraftReports = sortIfNeeded(draftReports, compareDisplayNames);
let sortedNonArchivedReports: MiniReport[];
let sortedArchivedReports: MiniReport[];
if (isInDefaultMode) {
sortedNonArchivedReports = sortIfNeeded(nonArchivedReports, compareNonArchivedDefault);
sortedArchivedReports = sortIfNeeded(archivedReports, compareDatesDesc);
} else {
sortedNonArchivedReports = sortIfNeeded(nonArchivedReports, compareDisplayNames);
sortedArchivedReports = sortIfNeeded(archivedReports, compareDisplayNames);
}
return {
pinnedAndGBRReports: sortedPinnedAndGBRReports,
errorReports: sortedErrorReports,
draftReports: sortedDraftReports,
nonArchivedReports: sortedNonArchivedReports,
archivedReports: sortedArchivedReports,
};
}
/**
* Combines sorted report categories and extracts report IDs
*/
function combineReportCategories(
pinnedAndGBRReports: MiniReport[],
errorReports: MiniReport[],
draftReports: MiniReport[],
nonArchivedReports: MiniReport[],
archivedReports: MiniReport[],
): string[] {
const result: string[] = [];
const groups = [pinnedAndGBRReports, errorReports, draftReports, nonArchivedReports, archivedReports];
for (const group of groups) {
for (const report of group) {
if (report?.reportID) {
result.push(report.reportID);
}
}
}
return result;
}
/**
* @returns An array of reportIDs sorted in the proper order
*/
function sortReportsToDisplayInLHN(
reportsToDisplay: ReportsToDisplayInLHN,
priorityMode: OnyxEntry<PriorityMode>,
localeCompare: LocaleContextProps['localeCompare'],
reportsDrafts: Record<string, boolean> | undefined,
reportNameValuePairs: OnyxCollection<ReportNameValuePairs> | undefined,
reportAttributes: ReportAttributesDerivedValue['reports'] | undefined,
): string[] {
const isInFocusMode = priorityMode === CONST.PRIORITY_MODE.GSD;
const isInDefaultMode = !isInFocusMode;
// The LHN is split into five distinct groups, and each group is sorted a little differently. The groups will ALWAYS be in this order:
// 1. Pinned/GBR - Always sorted by reportDisplayName
// 2. Error reports - Always sorted by reportDisplayName
// 3. Drafts - Always sorted by reportDisplayName
// 4. Non-archived reports and settled IOUs
// - Sorted by lastVisibleActionCreated in default (most recent) view mode
// - Sorted by reportDisplayName in GSD (focus) view mode
// 5. Archived reports
// - Sorted by lastVisibleActionCreated in default (most recent) view mode
// - Sorted by reportDisplayName in GSD (focus) view mode
// Step 1: Categorize reports
const categories = categorizeReportsForLHN(reportsToDisplay, reportsDrafts, reportAttributes, reportNameValuePairs);
// Step 2: Sort each category
const sortedCategories = sortCategorizedReports(categories, isInDefaultMode, localeCompare);
// Step 3: Combine and extract IDs
const result = combineReportCategories(
sortedCategories.pinnedAndGBRReports,
sortedCategories.errorReports,
sortedCategories.draftReports,
sortedCategories.nonArchivedReports,
sortedCategories.archivedReports,
);
return result;
}
type ReasonAndReportActionThatHasRedBrickRoad = {
reason: ValueOf<typeof CONST.RBR_REASONS>;
reportAction?: OnyxEntry<ReportAction>;
};
type GetReasonAndReportActionThatHasRedBrickRoadParams = {
report: Report;
chatReport: OnyxEntry<Report>;
reportActions: OnyxEntry<ReportActions>;
hasViolations: boolean;
reportErrors: Errors;
transactions: OnyxCollection<Transaction>;
isOffline: boolean;
currentUserAccountID: number;
transactionViolations?: OnyxCollection<TransactionViolation[]>;
isReportArchived?: boolean;
reports?: OnyxCollection<Report>;
};
function getReasonAndReportActionThatHasRedBrickRoad({
report,
chatReport,
reportActions,
hasViolations,
reportErrors,
transactions,
isOffline,
currentUserAccountID,
transactionViolations,
isReportArchived = false,
reports,
}: GetReasonAndReportActionThatHasRedBrickRoadParams): ReasonAndReportActionThatHasRedBrickRoad | null {
if (isReportArchived) {
return null;
}
const violatingReportID = getViolatingReportIDForRBRInLHN(report, transactionViolations);
if (violatingReportID) {
const reportPreviewAction = Object.values(reportActions ?? {}).find((action) => getIOUReportIDFromReportActionPreview(action) === violatingReportID);
return {
reason: CONST.RBR_REASONS.HAS_TRANSACTION_THREAD_VIOLATIONS,
reportAction: reportPreviewAction,
};
}
const {reportAction} = getAllReportActionsErrorsAndReportActionThatRequiresAttention(report, reportActions, transactions, currentUserAccountID, isReportArchived, reports);
const errors = reportErrors;
const hasErrors = Object.keys(errors).length !== 0;
if (hasErrors) {
return {
reason: CONST.RBR_REASONS.HAS_ERRORS,
reportAction,
};
}
if (hasViolations) {
return {
reason: CONST.RBR_REASONS.HAS_VIOLATIONS,
};
}
return getReceiptUploadErrorReason(report, chatReport, reportActions, transactions, isOffline);
}
/**
* Gets all the data necessary for rendering an OptionRowLHN component
*/
function getOptionData({
report,
reportAttributes,
oneTransactionThreadReport,
reportNameValuePairs,
personalDetails,
policy,
parentReportAction,
conciergeReportID,
invoiceReceiverPolicy,
lastMessageTextFromReport: lastMessageTextFromReportProp,
card,
lastAction,
translate,
dateFnsLocale,
convertToDisplayString,
convertToDisplayStringWithoutCurrency,
localeCompare,
isReportArchived,
lastActionReport,
movedFromReport,
movedToReport,
currentUserAccountID,
visibleReportActionsData,
reportAttributesDerived,
policyTags,
currentUserLogin,
isTrackIntentUser,
formatPhoneNumber,
rules,
}: {
report: OnyxEntry<Report>;
oneTransactionThreadReport: OnyxEntry<Report>;
reportNameValuePairs: OnyxEntry<ReportNameValuePairs>;
personalDetails: OnyxEntry<PersonalDetailsList>;
policy: OnyxEntry<Policy>;
parentReportAction: OnyxEntry<ReportAction> | undefined;
conciergeReportID: string | undefined;
invoiceReceiverPolicy: OnyxEntry<Policy>;
lastMessageTextFromReport?: string;
reportAttributes: OnyxEntry<ReportAttributes>;
card: Card | undefined;
lastAction: ReportAction | undefined;
translate: LocalizedTranslate;
dateFnsLocale: DateFnsLocale | undefined;
convertToDisplayString: CurrencyListActionsContextType['convertToDisplayString'];
convertToDisplayStringWithoutCurrency: CurrencyListActionsContextType['convertToDisplayStringWithoutCurrency'];
localeCompare: LocaleContextProps['localeCompare'];
isReportArchived: boolean | undefined;
lastActionReport: OnyxEntry<Report>;
movedFromReport?: OnyxEntry<Report>;
movedToReport?: OnyxEntry<Report>;
currentUserAccountID: number;
visibleReportActionsData?: VisibleReportActionsDerivedValue;
reportAttributesDerived?: ReportAttributesDerivedValue['reports'];
policyTags?: OnyxEntry<PolicyTagLists>;
currentUserLogin: string;
isTrackIntentUser?: boolean;
formatPhoneNumber: LocaleContextProps['formatPhoneNumber'];
rules: OnyxCollection<Rule>;
}): OptionData | undefined {
// When a user signs out, Onyx is cleared. Due to the lazy rendering with a virtual list, it's possible for
// this method to be called after the Onyx data has been cleared out. In that case, it's fine to do
// a null check here and return early.
if (!report || !personalDetails) {
return;
}
const result: OptionData = {
text: '',
alternateText: undefined,
allReportErrors: reportAttributes?.reportErrors,
brickRoadIndicator: null,
tooltipText: null,
subtitle: undefined,
login: undefined,
accountID: undefined,
reportID: '',
phoneNumber: undefined,
isUnread: null,
isUnreadWithMention: null,
hasDraftComment: false,
keyForList: '',
searchText: undefined,
isPinned: false,
hasOutstandingChildRequest: false,
hasOutstandingChildTask: false,
hasParentAccess: undefined,
isIOUReportOwner: null,
isChatRoom: false,
private_isArchived: undefined,
shouldShowSubscript: false,
isPolicyExpenseChat: false,
isMoneyRequestReport: false,
isExpenseRequest: false,
isWaitingOnBankAccount: false,
isAllowedToComment: true,
isDeletedParentAction: false,
isConciergeChat: false,
};
const reportMetadata = getReportMetadata(report?.reportID);
const participantAccountIDs = getParticipantsAccountIDsForDisplay(report);
const participantAccountIDsExcludeCurrentUser = excludeParticipantsForDisplay(participantAccountIDs, report.participants ?? {}, reportMetadata, {shouldExcludeCurrentUser: true});
const participantPersonalDetailListExcludeCurrentUser = Object.values(getPersonalDetailsForAccountIDs(participantAccountIDsExcludeCurrentUser, personalDetails));
const visibleParticipantAccountIDs = excludeParticipantsForDisplay(participantAccountIDs, report.participants ?? {}, reportMetadata, {shouldExcludeHidden: true});
const participantPersonalDetailList = Object.values(getPersonalDetailsForAccountIDs(participantAccountIDs, personalDetails));
const personalDetail = participantPersonalDetailList.at(0) ?? ({} as PersonalDetails);
result.isThread = isChatThread(report);
result.isChatRoom = isChatRoom(report);
result.isTaskReport = isTaskReport(report);
result.isInvoiceReport = isInvoiceReport(report);
result.parentReportAction = parentReportAction;
result.private_isArchived = !!reportNameValuePairs?.private_isArchived;
result.isPolicyExpenseChat = isPolicyExpenseChat(report);
result.isExpenseRequest = isExpenseRequest(report);
result.isMoneyRequestReport = isMoneyRequestReport(report);
const rawShouldShowSubscript = shouldReportShowSubscript(report, isReportArchived);
const isWorkspaceExpenseRequest = isExpenseRequest(report) && !!policy && policy.type !== CONST.POLICY.TYPE.PERSONAL;
const threadSuppression = isChatThread(report) && !isTripRoom(report) && !isWorkspaceExpenseRequest;
// For tasks, the header resolves the parent action via chatReportID (not parentReportID).
// When chatReportID is absent (offline/nested tasks), the action can't be resolved — treat as "no action".
const taskParentAction = isTaskReport(report) && !report.chatReportID ? undefined : parentReportAction;
const isReportPreviewOrNoAction = !taskParentAction || taskParentAction?.actionName === CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW;
const taskSuppression = isTaskReport(report) && !(isWorkspaceTaskReport(report) && isReportPreviewOrNoAction);
result.shouldShowSubscript = rawShouldShowSubscript && !threadSuppression && !taskSuppression;
result.pendingAction = report.pendingFields?.addWorkspaceRoom ?? report.pendingFields?.createChat;
result.brickRoadIndicator = reportAttributes?.brickRoadStatus;
result.actionBadge = reportAttributes?.actionBadge;
result.actionTargetReportActionID = reportAttributes?.actionTargetReportActionID;
result.ownerAccountID = report.ownerAccountID;
result.managerID = report.managerID;
result.reportID = report.reportID;
result.chatReportID = report.chatReportID;
result.policyID = report.policyID;
result.stateNum = report.stateNum;
result.statusNum = report.statusNum;
// When the only message of a report is deleted lastVisibleActionCreated is not reset leading to wrongly
// setting it Unread so we add additional condition here to avoid empty chat LHN from being bold.
result.isUnread = isUnread(report, oneTransactionThreadReport, isReportArchived, reportAttributes?.isEmpty) && !!report.lastActorAccountID;
result.isUnreadWithMention = isUnreadWithMention(report);
result.isPinned = report.isPinned;
result.iouReportID = report.iouReportID;
result.keyForList = String(report.reportID);
result.hasOutstandingChildRequest = report.hasOutstandingChildRequest;
result.parentReportID = report.parentReportID;
result.parentReportActionID = report.parentReportActionID;
result.isWaitingOnBankAccount = report.isWaitingOnBankAccount;
result.notificationPreference = getReportNotificationPreference(report);
result.isAllowedToComment = canUserPerformWriteActionUtil(report, isReportArchived);
result.chatType = report.chatType;
result.isDeletedParentAction = report.isDeletedParentAction;
result.isSelfDM = isSelfDM(report);
result.tooltipText = getReportParticipantsTitle(visibleParticipantAccountIDs);
result.hasOutstandingChildTask = report.hasOutstandingChildTask;
result.hasParentAccess = report.hasParentAccess;
result.isConciergeChat = isConciergeChatReport(report, conciergeReportID);
result.isConciergeThread = isChatThread(report) && !!conciergeReportID && report.parentReportID === conciergeReportID;
result.participants = report.participants;
const isExpense = isExpenseReport(report);
const hasMultipleParticipants = participantPersonalDetailList.length > 1 || result.isChatRoom || result.isPolicyExpenseChat || isExpense;
const subtitle = getChatRoomSubtitle(report, policy, conciergeReportID, translate, rules, false, isReportArchived);
const status = personalDetail?.status ?? '';
const isOneOnOneChatReport = isOneOnOneChat(report);
result.isOneOnOneChat = isOneOnOneChatReport;
// For 1:1 DMs, add the other participant's selected timezone
if (isOneOnOneChatReport) {
const recipientPersonalDetail = participantPersonalDetailListExcludeCurrentUser.at(0);
result.timezone = recipientPersonalDetail?.timezone;
}
// We only create tooltips for the first 10 users or so since some reports have hundreds of users, causing performance to degrade.
const displayNamesWithTooltips = getDisplayNamesWithTooltips(
(participantPersonalDetailList || []).slice(0, 10),
hasMultipleParticipants,
localeCompare,
formatPhoneNumber,
translate,
undefined,
isSelfDM(report),
);
result.alternateText = getReportAlternateText({
report,
lastAction,
lastActionReport,
movedFromReport,
movedToReport,
card,
lastMessageTextFromReport: lastMessageTextFromReportProp,
personalDetails,
policy,
invoiceReceiverPolicy,
policyTags,
isReportArchived,
privateIsArchived: !!reportNameValuePairs?.private_isArchived,
conciergeReportID,
reportAttributesDerived,
visibleReportActionsData,
currentUserAccountID,
currentUserLogin,
isTrackIntentUser,
translate,
localeCompare,
formatPhoneNumber,
dateFnsLocale,
convertToDisplayString,
convertToDisplayStringWithoutCurrency,
rules,
});
result.isIOUReportOwner = isIOUOwnedByCurrentUser(result as Report);
if (isJoinRequestInAdminRoom(report, currentUserLogin)) {
result.isUnread = true;
}
if (!hasMultipleParticipants) {
result.accountID = personalDetail?.accountID ?? CONST.DEFAULT_NUMBER_ID;
result.login = personalDetail?.login ?? '';
result.phoneNumber = personalDetail?.phoneNumber ?? '';
}
const reportName = getReportName(report, report?.reportID ? reportAttributesDerived?.[report.reportID]?.reportName : undefined);
if (reportName !== CONST.REPORT.DEFAULT_REPORT_NAME) {
loggedChatReportIDs.delete(report.reportID);
} else if (!loggedChatReportIDs.has(report.reportID) && shouldUseFullTitleForOption(result)) {
const derivedEntry = reportAttributesDerived?.[report.reportID];
loggedChatReportIDs.add(report.reportID);
Log.info('[ChatReportLHN] Default report name is shown in LHN', false, {
reportID: report.reportID,
chatType: report.chatType,
rawReportName: report.reportName,
hasDerivedEntry: !!derivedEntry,
derivedReportName: derivedEntry?.reportName,
derivedCount: reportAttributesDerived ? Object.keys(reportAttributesDerived).length : 0,
});
}
result.text = reportName;
result.subtitle = subtitle;
result.participantsList = participantPersonalDetailList;
const reportIcons = getIcons(
report,
formatPhoneNumber,
translate,
personalDetails,
personalDetail?.avatar,
personalDetail?.login,
personalDetail?.accountID ?? CONST.DEFAULT_NUMBER_ID,
policy,
invoiceReceiverPolicy,
isReportArchived,
getPendingDeleteMemberAccountIDs(reportMetadata?.pendingChatMembers),
conciergeReportID,
);
// IOU icon trimming (single vs diagonal) is handled at the component level
// using useReportPreviewSenderID which has access to transaction attendee data.
// INVOICE is also exempt — B2B invoices show two workspace icons as diagonal.
if (!result.shouldShowSubscript && report.type !== CONST.REPORT.TYPE.IOU && report.type !== CONST.REPORT.TYPE.INVOICE && reportIcons.length > 1) {
const firstIcon = reportIcons.at(0);
result.icons = firstIcon ? [firstIcon] : [];
} else {
result.icons = reportIcons;
}
result.displayNamesWithTooltips = displayNamesWithTooltips;
if (status) {
result.status = status;
}
result.type = report.type;
return result;
}
/**
* Whether a report should appear in the "Unread" Inbox tab: it has unread messages and is not muted.
* Computed once while building the LHN report set (which is cached/incremental) so the tab filter only reads a flag.
*/
function getIsUnreadReportForInboxTab(report: Report, isReportArchived: boolean, derivedIsEmptyReport: boolean | undefined): boolean {
// The `lastActorAccountID` guard matches getOptionData: it keeps chats whose only visible message was
// deleted out of the Unread tab even though isUnread() can still be true (lastVisibleActionCreated isn't reset).
return (
isUnread(report, undefined, isReportArchived, derivedIsEmptyReport) &&
!!report.lastActorAccountID &&
getReportNotificationPreference(report) !== CONST.REPORT.NOTIFICATION_PREFERENCE.MUTE
);
}
/** Whether a report belongs in the "To-do" Inbox tab: it has an outstanding GBR (requiresAttention) or RBR (errors). */
function getIsTodoReportForInboxTab(report: ReportsToDisplayInLHN[string]): boolean {
return !!report.requiresAttention || !!report.hasErrorsOtherThanFailedReceipt;
}