forked from Expensify/App
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReportActionsUtils.ts
More file actions
4274 lines (3650 loc) · 194 KB
/
ReportActionsUtils.ts
File metadata and controls
4274 lines (3650 loc) · 194 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
/* eslint-disable max-lines */
import {format} from 'date-fns';
import {fastMerge, Str} from 'expensify-common';
import clone from 'lodash/clone';
import isEmpty from 'lodash/isEmpty';
import type {NullishDeep, OnyxCollection, OnyxEntry, OnyxUpdate} from 'react-native-onyx';
import Onyx from 'react-native-onyx';
import type {ValueOf} from 'type-fest';
import type {LocaleContextProps, LocalizedTranslate} from '@components/LocaleContextProvider';
import usePrevious from '@hooks/usePrevious';
// eslint-disable-next-line @dword-design/import-alias/prefer-alias
import {doesReportContainRequestsFromMultipleUsers, getReportOrDraftReport} from '@libs/ReportUtils';
import CONST from '@src/CONST';
import IntlStore from '@src/languages/IntlStore';
import type {TranslationPaths} from '@src/languages/types';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {
Card,
OnyxInputOrEntry,
OriginalMessageIOU,
PersonalDetails,
Policy,
PrivatePersonalDetails,
ReportMetadata,
ReportNameValuePairs,
VisibleReportActionsDerivedValue,
} from '@src/types/onyx';
import type {
JoinWorkspaceResolution,
OriginalMessageChangeLog,
OriginalMessageExportIntegration,
OriginalMessageMarkedReimbursed,
OriginalMessageUnreportedTransaction,
} from '@src/types/onyx/OriginalMessage';
import type {PolicyReportFieldType} from '@src/types/onyx/Policy';
import type Report from '@src/types/onyx/Report';
import type ReportAction from '@src/types/onyx/ReportAction';
import type {Message, OldDotReportAction, OriginalMessage, ReportActions} from '@src/types/onyx/ReportAction';
import type ReportActionName from '@src/types/onyx/ReportActionName';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import {isCardPendingActivate} from './CardUtils';
import {getDecodedCategoryName} from './CategoryUtils';
import {convertAmountToDisplayString, convertToDisplayString, convertToShortDisplayString} from './CurrencyUtils';
import DateUtils from './DateUtils';
import {getEnvironmentURL, getOldDotEnvironmentURL} from './Environment/Environment';
import getBase62ReportID from './getBase62ReportID';
import {isReportMessageAttachment} from './isReportMessageAttachment';
import {toLocaleOrdinal} from './LocaleDigitUtils';
import {formatPhoneNumber} from './LocalePhoneNumber';
import {formatMessageElementList, translateLocal} from './Localize';
import Log from './Log';
import type {MessageElementBase, MessageTextElement} from './MessageElement';
import getReportURLForCurrentContext from './Navigation/helpers/getReportURLForCurrentContext';
import Parser from './Parser';
import {arePersonalDetailsMissing, createPersonalDetailsLookupByAccountID, getEffectiveDisplayName, getPersonalDetailByEmail, getPersonalDetailsByIDs} from './PersonalDetailsUtils';
import {getPolicy, isPolicyAdmin as isPolicyAdminPolicyUtils} from './PolicyUtils';
import stripFollowupListFromHtml from './ReportActionFollowupUtils/stripFollowupListFromHtml';
import type {getReportName, OptimisticIOUReportAction, PartialReportAction} from './ReportUtils';
import StringUtils from './StringUtils';
import {getReportFieldTypeTranslationKey} from './WorkspaceReportFieldUtils';
type LastVisibleMessage = {
lastMessageText: string;
lastMessageHtml?: string;
};
type MemberChangeMessageUserMentionElement = {
readonly kind: 'userMention';
readonly accountID: number;
} & MessageElementBase;
type MemberChangeMessageRoomReferenceElement = {
readonly kind: 'roomReference';
readonly roomName: string;
readonly roomID: number;
} & MessageElementBase;
type MemberChangeMessageElement = MessageTextElement | MemberChangeMessageUserMentionElement | MemberChangeMessageRoomReferenceElement;
function isPolicyExpenseChat(report: OnyxInputOrEntry<Report>): boolean {
return report?.chatType === CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT || !!(report && typeof report === 'object' && 'isPolicyExpenseChat' in report && report.isPolicyExpenseChat);
}
function isHarvestCreatedExpenseReport(origin?: string, originalID?: string): boolean {
return !!originalID && origin === 'harvest';
}
let allReportActions: OnyxCollection<ReportActions>;
Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT_ACTIONS,
waitForCollectionCallback: true,
callback: (actions) => {
if (!actions) {
return;
}
allReportActions = actions;
},
});
let allReports: OnyxCollection<Report>;
Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT,
waitForCollectionCallback: true,
callback: (value) => {
allReports = value;
},
});
let isNetworkOffline = false;
Onyx.connect({
key: ONYXKEYS.NETWORK,
callback: (val) => (isNetworkOffline = val?.isOffline ?? false),
});
let deprecatedCurrentUserAccountID: number | undefined;
Onyx.connect({
key: ONYXKEYS.SESSION,
callback: (value) => {
// When signed out, value is undefined
if (!value) {
return;
}
deprecatedCurrentUserAccountID = value.accountID;
},
});
let allReportNameValuePair: OnyxCollection<ReportNameValuePairs>;
Onyx.connectWithoutView({
key: ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS,
waitForCollectionCallback: true,
callback: (value) => {
if (!value) {
return;
}
allReportNameValuePair = value;
},
});
let environmentURL: string;
getEnvironmentURL().then((url: string) => (environmentURL = url));
let oldDotEnvironmentURL: string;
getOldDotEnvironmentURL().then((url: string) => (oldDotEnvironmentURL = url));
type SortedReportActionsCacheEntry = {
sortedActions: ReportAction[];
lastAccessed: number;
};
const DEFAULT_SORTED_REPORT_ACTIONS_CACHE_MAX_SIZE = 1000;
let sortedReportActionsCacheMaxSize = DEFAULT_SORTED_REPORT_ACTIONS_CACHE_MAX_SIZE;
const sortedReportActionsCacheAscending = new Map<string, SortedReportActionsCacheEntry>();
const sortedReportActionsCacheDescending = new Map<string, SortedReportActionsCacheEntry>();
const shouldReportActionBeVisibleAsLastActionCache = new WeakMap<ReportAction, Map<boolean, boolean>>();
/*
* Url to the Xero non reimbursable expenses list
*/
const XERO_NON_REIMBURSABLE_EXPENSES_URL = 'https://go.xero.com/Bank/BankAccounts.aspx';
/*
* Url to the NetSuite global search, which should be suffixed with the reportID.
*/
const NETSUITE_NON_REIMBURSABLE_EXPENSES_URL_PREFIX =
'https://system.netsuite.com/app/common/search/ubersearchresults.nl?quicksearch=T&searchtype=Uber&frame=be&Uber_NAMEtype=KEYWORDSTARTSWITH&Uber_NAME=';
/*
* Url prefix to any Salesforce transaction or transaction list.
*/
const SALESFORCE_EXPENSES_URL_PREFIX = 'https://login.salesforce.com/';
/*
* Url to the QBO expenses list
*/
const QBO_EXPENSES_URL = 'https://qbo.intuit.com/app/expenses';
const POLICY_CHANGE_LOG_ARRAY = new Set<ReportActionName>(Object.values(CONST.REPORT.ACTIONS.TYPE.POLICY_CHANGE_LOG));
const ROOM_CHANGE_LOG_ARRAY = new Set<ReportActionName>(Object.values(CONST.REPORT.ACTIONS.TYPE.ROOM_CHANGE_LOG));
const MEMBER_CHANGE_ARRAY = new Set<ReportActionName>([
CONST.REPORT.ACTIONS.TYPE.ROOM_CHANGE_LOG.INVITE_TO_ROOM,
CONST.REPORT.ACTIONS.TYPE.ROOM_CHANGE_LOG.REMOVE_FROM_ROOM,
CONST.REPORT.ACTIONS.TYPE.POLICY_CHANGE_LOG.INVITE_TO_ROOM,
CONST.REPORT.ACTIONS.TYPE.POLICY_CHANGE_LOG.REMOVE_FROM_ROOM,
CONST.REPORT.ACTIONS.TYPE.POLICY_CHANGE_LOG.LEAVE_POLICY,
]);
const deprecatedOldDotReportActions = new Set<ReportActionName>([
CONST.REPORT.ACTIONS.TYPE.DELETED_ACCOUNT,
CONST.REPORT.ACTIONS.TYPE.REIMBURSEMENT_REQUESTED,
CONST.REPORT.ACTIONS.TYPE.REIMBURSEMENT_SETUP_REQUESTED,
CONST.REPORT.ACTIONS.TYPE.DONATION,
CONST.REPORT.ACTIONS.TYPE.REIMBURSED,
]);
function isCreatedAction(reportAction: OnyxInputOrEntry<ReportAction>): boolean {
return reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED;
}
function isDeletedAction(reportAction: OnyxInputOrEntry<ReportAction | OptimisticIOUReportAction>): boolean {
if (isInviteOrRemovedAction(reportAction) || isActionableMentionWhisper(reportAction) || isActionableCardFraudAlert(reportAction)) {
return false;
}
if (reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.HOLD || reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.UNHOLD) {
return false;
}
// for report actions with this type we get an empty array as message by design
if (
reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.REIMBURSEMENT_DIRECTOR_INFORMATION_REQUIRED ||
reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED_REPORT_FOR_UNAPPROVED_TRANSACTIONS
) {
return false;
}
const message = reportAction?.message ?? [];
if (!Array.isArray(message)) {
return message?.html === '' || !!message?.deleted;
}
const originalMessage = getOriginalMessage(reportAction);
// A legacy deleted comment has either an empty array or an object with html field with empty string as value
const isLegacyDeletedComment = message.length === 0 || message.at(0)?.html === '';
return isLegacyDeletedComment || !!message.at(0)?.deleted || (!!originalMessage && 'deleted' in originalMessage && !!originalMessage?.deleted);
}
/**
* This function will add attachment ID attribute on img and video HTML tags inside the passed html content
* of a report action. This attachment id is the reportActionID concatenated with the order index that the attachment
* appears inside the report action message so as to identify attachments with identical source inside a report action.
*/
function getHtmlWithAttachmentID(html: string, reportActionID: string | undefined) {
if (!reportActionID) {
return html;
}
let attachmentID = 0;
return html.replaceAll(/<img |<video /g, (m) => m.concat(`${CONST.ATTACHMENT_ID_ATTRIBUTE}="${reportActionID}_${++attachmentID}" `));
}
function getReportActionMessage(reportAction: PartialReportAction) {
return Array.isArray(reportAction?.message) ? reportAction?.message.at(0) : reportAction?.message;
}
function isDeletedParentAction(reportAction: OnyxInputOrEntry<ReportAction>): boolean {
return (getReportActionMessage(reportAction)?.isDeletedParentAction ?? false) && (reportAction?.childVisibleActionCount ?? 0) > 0;
}
function isReversedTransaction(reportAction: OnyxInputOrEntry<ReportAction | OptimisticIOUReportAction>) {
return (getReportActionMessage(reportAction)?.isReversedTransaction ?? false) && ((reportAction as ReportAction)?.childVisibleActionCount ?? 0) > 0;
}
function isPendingRemove(reportAction: OnyxInputOrEntry<ReportAction>): boolean {
return getReportActionMessage(reportAction)?.moderationDecision?.decision === CONST.MODERATION.MODERATOR_DECISION_PENDING_REMOVE;
}
function isPendingHide(reportAction: OnyxInputOrEntry<ReportAction>): boolean {
return getReportActionMessage(reportAction)?.moderationDecision?.decision === CONST.MODERATION.MODERATOR_DECISION_PENDING_HIDE;
}
function isMoneyRequestAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.IOU> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.IOU);
}
function isExportedToIntegrationAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.EXPORTED_TO_INTEGRATION> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.EXPORTED_TO_INTEGRATION);
}
function isReportPreviewAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW);
}
function isSubmittedAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.SUBMITTED> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.SUBMITTED);
}
function isSubmittedAndClosedAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.SUBMITTED_AND_CLOSED> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.SUBMITTED_AND_CLOSED);
}
function isDynamicExternalWorkflowSubmitAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.SUBMITTED> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.SUBMITTED) && getOriginalMessage(reportAction)?.workflow === CONST.POLICY.APPROVAL_MODE.DYNAMICEXTERNAL;
}
function isMarkAsClosedAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.CLOSED> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.CLOSED) && !!getOriginalMessage(reportAction)?.amount;
}
function isApprovedAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.APPROVED> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.APPROVED);
}
function isUnapprovedAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.UNAPPROVED> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.UNAPPROVED);
}
function isForwardedAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.FORWARDED> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.FORWARDED);
}
function isDynamicExternalWorkflowSubmitFailedAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.DEW_SUBMIT_FAILED> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.DEW_SUBMIT_FAILED);
}
function getMostRecentActiveDEWSubmitFailedAction(reportActions: OnyxEntry<ReportActions> | ReportAction[]): ReportAction | undefined {
const actionsArray = Array.isArray(reportActions) ? reportActions : Object.values(reportActions ?? {});
let mostRecentDewSubmitFailedAction: ReportAction | undefined;
let mostRecentSubmittedAction: ReportAction | undefined;
for (const action of actionsArray) {
if (isDynamicExternalWorkflowSubmitFailedAction(action)) {
if (!mostRecentDewSubmitFailedAction || (action.created && mostRecentDewSubmitFailedAction.created && action.created > mostRecentDewSubmitFailedAction.created)) {
mostRecentDewSubmitFailedAction = action;
}
} else if (isSubmittedAction(action)) {
if (!mostRecentSubmittedAction || (action.created && mostRecentSubmittedAction.created && action.created > mostRecentSubmittedAction.created)) {
mostRecentSubmittedAction = action;
}
}
}
if (!mostRecentDewSubmitFailedAction) {
return undefined;
}
if (!mostRecentSubmittedAction || mostRecentDewSubmitFailedAction.created > mostRecentSubmittedAction.created) {
return mostRecentDewSubmitFailedAction;
}
return undefined;
}
/** Checks if there's a pending DEW submission in progress. */
function hasPendingDEWSubmit(reportMetadata: OnyxEntry<ReportMetadata>, isDEWPolicy: boolean): boolean {
return isDEWPolicy && reportMetadata?.pendingExpenseAction === CONST.EXPENSE_PENDING_ACTION.SUBMIT;
}
function isDynamicExternalWorkflowApproveFailedAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.DEW_APPROVE_FAILED> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.DEW_APPROVE_FAILED);
}
/** Actions that clear a DEW_APPROVE_FAILED error (approval succeeded or report was retracted/reopened). */
function isActionThatSupersedesDEWApproveFailure(action: ReportAction): boolean {
return isApprovedAction(action) || isForwardedAction(action) || isRetractedAction(action) || isReopenedAction(action);
}
function getMostRecentActiveDEWApproveFailedAction(reportActions: OnyxEntry<ReportActions> | ReportAction[]): ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.DEW_APPROVE_FAILED> | undefined {
const actionsArray = Array.isArray(reportActions) ? reportActions : Object.values(reportActions ?? {});
let mostRecentDewApproveFailedAction: ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.DEW_APPROVE_FAILED> | undefined;
let mostRecentSupersedingAction: ReportAction | undefined;
for (const action of actionsArray) {
if (isDynamicExternalWorkflowApproveFailedAction(action)) {
if (!mostRecentDewApproveFailedAction || (action.created && mostRecentDewApproveFailedAction.created && action.created > mostRecentDewApproveFailedAction.created)) {
mostRecentDewApproveFailedAction = action;
}
} else if (isActionThatSupersedesDEWApproveFailure(action)) {
if (!mostRecentSupersedingAction || (action.created && mostRecentSupersedingAction.created && action.created > mostRecentSupersedingAction.created)) {
mostRecentSupersedingAction = action;
}
}
}
if (!mostRecentDewApproveFailedAction) {
return undefined;
}
if (!mostRecentSupersedingAction || mostRecentDewApproveFailedAction.created > mostRecentSupersedingAction.created) {
return mostRecentDewApproveFailedAction;
}
return undefined;
}
function hasPendingDEWApprove(reportMetadata: OnyxEntry<ReportMetadata>, isDEWPolicy: boolean): boolean {
return isDEWPolicy && reportMetadata?.pendingExpenseAction === CONST.EXPENSE_PENDING_ACTION.APPROVE;
}
function isDynamicExternalWorkflowForwardedAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.FORWARDED> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.FORWARDED) && getOriginalMessage(reportAction)?.workflow === CONST.POLICY.APPROVAL_MODE.DYNAMICEXTERNAL;
}
function isModifiedExpenseAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.MODIFIED_EXPENSE> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.MODIFIED_EXPENSE);
}
function isMovedTransactionAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.MOVED_TRANSACTION> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.MOVED_TRANSACTION);
}
function isMovedAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.MOVED> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.MOVED);
}
function isPolicyChangeLogAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<ValueOf<typeof CONST.REPORT.ACTIONS.TYPE.POLICY_CHANGE_LOG>> {
return reportAction?.actionName ? POLICY_CHANGE_LOG_ARRAY.has(reportAction.actionName) : false;
}
function isChronosOOOListAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.CHRONOS_OOO_LIST> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.CHRONOS_OOO_LIST);
}
function isAddCommentAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT);
}
function isCreatedTaskReportAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT) && !!getOriginalMessage(reportAction)?.taskReportID;
}
function isTripPreview(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.TRIP_PREVIEW> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.TRIP_PREVIEW);
}
function isHoldAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.HOLD> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.HOLD);
}
function isReimbursementDirectionInformationRequiredAction(
reportAction: OnyxInputOrEntry<ReportAction>,
): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.REIMBURSEMENT_DIRECTOR_INFORMATION_REQUIRED> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.REIMBURSEMENT_DIRECTOR_INFORMATION_REQUIRED);
}
function isActionOfType<T extends ReportActionName>(action: OnyxInputOrEntry<ReportAction>, actionName: T): action is ReportAction<T> {
return action?.actionName === actionName;
}
function getOriginalMessage<T extends ReportActionName>(reportAction: OnyxInputOrEntry<ReportAction<T>>): OriginalMessage<T> | undefined {
if (!Array.isArray(reportAction?.message)) {
// eslint-disable-next-line @typescript-eslint/no-deprecated
return reportAction?.message ?? reportAction?.originalMessage;
}
// eslint-disable-next-line @typescript-eslint/no-deprecated
return reportAction?.originalMessage;
}
function getMarkedReimbursedMessage(reportAction: OnyxInputOrEntry<ReportAction>): string {
const originalMessage = getOriginalMessage(reportAction) as OriginalMessageMarkedReimbursed | undefined;
// eslint-disable-next-line @typescript-eslint/no-deprecated
return translateLocal('iou.paidElsewhere', {comment: originalMessage?.message?.trim()});
}
function getDelegateAccountIDFromReportAction(reportAction: OnyxInputOrEntry<ReportAction>): number | undefined {
if (!reportAction) {
return undefined;
}
if (reportAction.delegateAccountID) {
return reportAction.delegateAccountID;
}
const originalMessage = getOriginalMessage(reportAction);
if (!originalMessage) {
return undefined;
}
if ('delegateAccountID' in originalMessage) {
return originalMessage.delegateAccountID;
}
return undefined;
}
function isExportIntegrationAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.EXPORTED_TO_INTEGRATION> {
return reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.EXPORTED_TO_INTEGRATION;
}
function isIntegrationMessageAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.INTEGRATIONS_MESSAGE> {
return reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.INTEGRATIONS_MESSAGE;
}
function isTravelUpdate(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.TRAVEL_UPDATE> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.TRAVEL_UPDATE);
}
/**
* We are in the process of deprecating reportAction.originalMessage and will be setting the db version of "message" to reportAction.message in the future see: https://github.com/Expensify/App/issues/39797
* In the interim, we must check to see if we have an object or array for the reportAction.message, if we have an array we will use the originalMessage as this means we have not yet migrated.
*/
function getWhisperedTo(reportAction: OnyxInputOrEntry<ReportAction>): number[] {
if (!reportAction) {
return [];
}
const originalMessage = getOriginalMessage(reportAction);
const message = getReportActionMessage(reportAction);
if (!(originalMessage && typeof originalMessage === 'object' && 'whisperedTo' in originalMessage) && !(message && typeof message === 'object' && 'whisperedTo' in message)) {
return [];
}
if (message !== null && !Array.isArray(message) && typeof message === 'object' && 'whisperedTo' in message) {
return message?.whisperedTo ?? [];
}
if (originalMessage && typeof originalMessage === 'object' && 'whisperedTo' in originalMessage) {
return originalMessage?.whisperedTo ?? [];
}
if (typeof originalMessage !== 'object') {
Log.info('Original message is not an object for reportAction: ', true, {
reportActionID: reportAction?.reportActionID,
actionName: reportAction?.actionName,
});
}
return [];
}
function isWhisperAction(reportAction: OnyxInputOrEntry<ReportAction>): boolean {
return getWhisperedTo(reportAction).length > 0;
}
/**
* Checks whether the report action is a whisper targeting someone other than the current user.
*/
function isWhisperActionTargetedToOthers(reportAction: OnyxInputOrEntry<ReportAction>): boolean {
if (!isWhisperAction(reportAction)) {
return false;
}
return !getWhisperedTo(reportAction).includes(deprecatedCurrentUserAccountID ?? CONST.DEFAULT_NUMBER_ID);
}
function isReimbursementQueuedAction(reportAction: OnyxInputOrEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.REIMBURSEMENT_QUEUED> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.REIMBURSEMENT_QUEUED);
}
function isMemberChangeAction(
reportAction: OnyxInputOrEntry<ReportAction>,
): reportAction is ReportAction<ValueOf<typeof CONST.REPORT.ACTIONS.TYPE.ROOM_CHANGE_LOG | typeof CONST.REPORT.ACTIONS.TYPE.POLICY_CHANGE_LOG>> {
return reportAction?.actionName ? MEMBER_CHANGE_ARRAY.has(reportAction.actionName) : false;
}
function isInviteMemberAction(
reportAction: OnyxEntry<ReportAction>,
): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.ROOM_CHANGE_LOG.INVITE_TO_ROOM | typeof CONST.REPORT.ACTIONS.TYPE.POLICY_CHANGE_LOG.INVITE_TO_ROOM> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.ROOM_CHANGE_LOG.INVITE_TO_ROOM) || isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.POLICY_CHANGE_LOG.INVITE_TO_ROOM);
}
function isLeavePolicyAction(reportAction: OnyxEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.POLICY_CHANGE_LOG.LEAVE_POLICY> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.POLICY_CHANGE_LOG.LEAVE_POLICY);
}
function isReimbursementCanceledAction(reportAction: OnyxEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.REIMBURSEMENT_ACH_CANCELED> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.REIMBURSEMENT_ACH_CANCELED);
}
function isReimbursementDeQueuedAction(reportAction: OnyxEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.REIMBURSEMENT_DEQUEUED> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.REIMBURSEMENT_DEQUEUED);
}
function isReimbursementDeQueuedOrCanceledAction(
reportAction: OnyxEntry<ReportAction>,
): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.REIMBURSEMENT_DEQUEUED | typeof CONST.REPORT.ACTIONS.TYPE.REIMBURSEMENT_ACH_CANCELED> {
return isReimbursementDeQueuedAction(reportAction) || isReimbursementCanceledAction(reportAction);
}
function isClosedAction(reportAction: OnyxEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.CLOSED> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.CLOSED);
}
function isRenamedAction(reportAction: OnyxEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.RENAMED> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.RENAMED);
}
function isReopenedAction(reportAction: OnyxEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.REOPENED> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.REOPENED);
}
function isRetractedAction(reportAction: OnyxEntry<ReportAction>): reportAction is ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.RETRACTED> {
return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.RETRACTED);
}
function isRoomChangeLogAction(reportAction: OnyxEntry<ReportAction>): reportAction is ReportAction<ValueOf<typeof CONST.REPORT.ACTIONS.TYPE.ROOM_CHANGE_LOG>> {
return reportAction?.actionName ? ROOM_CHANGE_LOG_ARRAY.has(reportAction.actionName) : false;
}
function isInviteOrRemovedAction(
reportAction: OnyxInputOrEntry<ReportAction>,
): reportAction is ReportAction<ValueOf<typeof CONST.REPORT.ACTIONS.TYPE.POLICY_CHANGE_LOG | typeof CONST.REPORT.ACTIONS.TYPE.ROOM_CHANGE_LOG>> {
return (
isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.ROOM_CHANGE_LOG.INVITE_TO_ROOM) ||
isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.ROOM_CHANGE_LOG.REMOVE_FROM_ROOM) ||
isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.POLICY_CHANGE_LOG.INVITE_TO_ROOM) ||
isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.POLICY_CHANGE_LOG.REMOVE_FROM_ROOM)
);
}
/**
* Returns whether the comment is a thread parent message/the first message in a thread
*/
function isThreadParentMessage(reportAction: OnyxEntry<ReportAction>, reportID: string | undefined): boolean {
const {childType, childVisibleActionCount = 0, childReportID} = reportAction ?? {};
return childType === CONST.REPORT.TYPE.CHAT && (childVisibleActionCount > 0 || String(childReportID) === reportID);
}
/**
* Determines if the given report action is sent money report action by checking for 'pay' type and presence of IOUDetails object.
*/
function isSentMoneyReportAction(reportAction: OnyxEntry<ReportAction | OptimisticIOUReportAction>): boolean {
return (
isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.IOU) &&
getOriginalMessage(reportAction)?.type === CONST.IOU.REPORT_ACTION_TYPE.PAY &&
!!getOriginalMessage(reportAction)?.IOUDetails
);
}
/**
* Returns whether the thread is a transaction thread, which is any thread with IOU parent
* report action from requesting money (type - create) or from sending money (type - pay with IOUDetails field)
*/
function isTransactionThread(parentReportAction: OnyxInputOrEntry<ReportAction>): boolean {
if (isEmptyObject(parentReportAction) || !isMoneyRequestAction(parentReportAction)) {
return false;
}
const originalMessage = getOriginalMessage(parentReportAction);
return (
originalMessage?.type === CONST.IOU.REPORT_ACTION_TYPE.CREATE ||
originalMessage?.type === CONST.IOU.REPORT_ACTION_TYPE.TRACK ||
(originalMessage?.type === CONST.IOU.REPORT_ACTION_TYPE.PAY && !!originalMessage?.IOUDetails)
);
}
/**
* Clears the sorted report actions caches. Exposed for tests to avoid cross-test cache pollution
* when different tests use the same reportActionIDs with different metadata (created, actionName).
*/
function clearSortedReportActionsCache(): void {
sortedReportActionsCacheAscending.clear();
sortedReportActionsCacheDescending.clear();
}
/**
* Generates a cache key based on reportActionIDs (sorted for consistency).
* This allows us to cache sorted results even when we receive new array references.
*/
function getCacheKeyForReportActions(reportActions: ReportAction[]): string {
return reportActions
.map((action) => action.reportActionID)
.sort()
.join(',');
}
/**
* Ensures cache doesn't exceed max size by removing least recently used entries (LRU).
*/
function evictOldestCacheEntries(cache: Map<string, SortedReportActionsCacheEntry>): void {
if (cache.size <= sortedReportActionsCacheMaxSize) {
return;
}
const entries = Array.from(cache.entries());
entries.sort((a, b) => a[1].lastAccessed - b[1].lastAccessed);
const entriesToRemove = cache.size - sortedReportActionsCacheMaxSize;
for (let i = 0; i < entriesToRemove; i++) {
const entry = entries.at(i);
if (entry !== undefined) {
cache.delete(entry[0]);
}
}
}
/**
* Adjust the maximum size for the sorted report actions cache.
* Used by callers that know the current number of reports (e.g. LHN),
* while still enforcing a global hard cap for safety.
*/
function setSortedReportActionsCacheMaxSize(newSize: number): void {
if (!Number.isFinite(newSize) || newSize <= 0) {
sortedReportActionsCacheMaxSize = DEFAULT_SORTED_REPORT_ACTIONS_CACHE_MAX_SIZE;
} else {
sortedReportActionsCacheMaxSize = newSize;
}
evictOldestCacheEntries(sortedReportActionsCacheAscending);
evictOldestCacheEntries(sortedReportActionsCacheDescending);
}
/**
* Sort an array of reportActions by their created timestamp first, and reportActionID second
* This gives us a stable order even in the case of multiple reportActions created on the same millisecond
*
*/
function getSortedReportActions(reportActions: ReportAction[] | null, shouldSortInDescendingOrder = false): ReportAction[] {
if (!Array.isArray(reportActions)) {
throw new Error(`ReportActionsUtils.getSortedReportActions requires an array, received ${typeof reportActions}`);
}
const filteredActions = reportActions.filter(Boolean);
if (filteredActions.length === 0) {
return [];
}
const cache = shouldSortInDescendingOrder ? sortedReportActionsCacheDescending : sortedReportActionsCacheAscending;
const cacheKey = getCacheKeyForReportActions(filteredActions);
const cachedEntry = cache.get(cacheKey);
if (cachedEntry) {
cachedEntry.lastAccessed = Date.now();
return [...cachedEntry.sortedActions];
}
const invertedMultiplier = shouldSortInDescendingOrder ? -1 : 1;
const sortedActions = [...filteredActions].sort((first, second) => {
// First sort by action type, ensuring that `CREATED` actions always come first if they have the same or even a later timestamp as another action type
if ((first.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED || second.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED) && first.actionName !== second.actionName) {
return (first.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED ? -1 : 1) * invertedMultiplier;
}
// Ensure that neither first's nor second's created property is undefined
if (first.created === undefined || second.created === undefined) {
return (first.created === undefined ? -1 : 1) * invertedMultiplier;
}
// Then sort by timestamp
if (first.created !== second.created) {
return (first.created < second.created ? -1 : 1) * invertedMultiplier;
}
// Ensure that `REPORT_PREVIEW` actions always come after if they have the same timestamp as another action type
if ((first.actionName === CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW || second.actionName === CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW) && first.actionName !== second.actionName) {
return (first.actionName === CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW ? 1 : -1) * invertedMultiplier;
}
// Then fallback on reportActionID as the final sorting criteria. It is a random number,
// but using this will ensure that the order of reportActions with the same created time and action type
// will be consistent across all users and devices
return (first.reportActionID < second.reportActionID ? -1 : 1) * invertedMultiplier;
});
evictOldestCacheEntries(cache);
cache.set(cacheKey, {
sortedActions,
lastAccessed: Date.now(),
});
return sortedActions;
}
/**
* Returns a sorted and filtered list of report actions from a report and it's associated child
* transaction thread report in order to correctly display reportActions from both reports in the one-transaction report view.
*/
function getCombinedReportActions(
reportActions: ReportAction[],
transactionThreadReportID: string | null,
transactionThreadReportActions: ReportAction[],
reportID?: string,
): ReportAction[] {
const isSentMoneyReport = reportActions.some((action) => isSentMoneyReportAction(action));
// We don't want to combine report actions of transaction thread in iou report of send money request because we display the transaction report of send money request as a normal thread
if (!transactionThreadReportID || isSentMoneyReport) {
return reportActions;
}
// Usually, we filter out the created action from the transaction thread report actions, since we already have the parent report's created action in `reportActions`
// However, in the case of moving track expense, the transaction thread will be created first in a track expense, thus we should keep the CREATED of the transaction thread and filter out CREATED action of the IOU
// This makes sense because in a combined report action list, whichever CREATED is first need to be retained.
const transactionThreadCreatedAction = transactionThreadReportActions?.find((action) => action.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED);
const parentReportCreatedAction = reportActions?.find((action) => action.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED);
let filteredTransactionThreadReportActions = transactionThreadReportActions;
let filteredParentReportActions = reportActions;
if (transactionThreadCreatedAction && parentReportCreatedAction && transactionThreadCreatedAction.created > parentReportCreatedAction.created) {
filteredTransactionThreadReportActions = transactionThreadReportActions?.filter((action) => action.actionName !== CONST.REPORT.ACTIONS.TYPE.CREATED);
} else if (transactionThreadCreatedAction) {
filteredParentReportActions = reportActions?.filter((action) => action.actionName !== CONST.REPORT.ACTIONS.TYPE.CREATED);
}
const report = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`];
const isSelfDM = report?.chatType === CONST.REPORT.CHAT_TYPE.SELF_DM;
// Filter out request and send money request actions because we don't want to show any preview actions for one transaction reports
const filteredReportActions = [...filteredParentReportActions, ...filteredTransactionThreadReportActions].filter((action) => {
if (!isMoneyRequestAction(action)) {
return true;
}
const actionType = getOriginalMessage(action)?.type ?? '';
if (isSelfDM) {
return actionType !== CONST.IOU.REPORT_ACTION_TYPE.CREATE;
}
return actionType !== CONST.IOU.REPORT_ACTION_TYPE.CREATE && actionType !== CONST.IOU.REPORT_ACTION_TYPE.TRACK;
});
return getSortedReportActions(filteredReportActions, true);
}
const iouRequestTypes: Array<ValueOf<typeof CONST.IOU.REPORT_ACTION_TYPE>> = [CONST.IOU.REPORT_ACTION_TYPE.CREATE, CONST.IOU.REPORT_ACTION_TYPE.SPLIT, CONST.IOU.REPORT_ACTION_TYPE.TRACK];
// Get all IOU report actions for the report.
const iouRequestTypesSet = new Set<ValueOf<typeof CONST.IOU.REPORT_ACTION_TYPE>>([...iouRequestTypes, CONST.IOU.REPORT_ACTION_TYPE.PAY]);
/**
* Finds most recent IOU request action ID.
*/
function getMostRecentIOURequestActionID(reportActions: ReportAction[] | null): string | null {
if (!Array.isArray(reportActions)) {
return null;
}
const iouRequestActions =
reportActions?.filter((action) => {
if (!isActionOfType(action, CONST.REPORT.ACTIONS.TYPE.IOU)) {
return false;
}
const actionType = getOriginalMessage(action)?.type;
if (!actionType) {
return false;
}
return iouRequestTypes.includes(actionType);
}) ?? [];
if (iouRequestActions.length === 0) {
return null;
}
const sortedReportActions = getSortedReportActions(iouRequestActions);
return sortedReportActions.at(-1)?.reportActionID ?? null;
}
/**
* Returns array of links inside a given report action
*/
function extractLinksFromMessageHtml(reportAction: OnyxEntry<ReportAction>): string[] {
const htmlContent = getReportActionHtml(reportAction);
const regex = CONST.REGEX_LINK_IN_ANCHOR;
if (!htmlContent) {
return [];
}
return [...htmlContent.matchAll(regex)].map((match) => match[1]);
}
/**
* Returns the report action immediately before the specified index.
* @param reportActions - all actions
* @param actionIndex - index of the action
*/
function findPreviousAction(reportActions: ReportAction[], actionIndex: number): OnyxEntry<ReportAction> {
for (let i = actionIndex + 1; i < reportActions.length; i++) {
const action = reportActions.at(i);
// Find the next non-pending deletion report action, as the pending delete action means that it is not displayed in the UI, but still is in the report actions list.
// If we are offline, all actions are pending but shown in the UI, so we take the previous action, even if it is a delete.
if (!isNetworkOffline && action?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) {
continue;
}
if (action?.shouldShow === false) {
continue;
}
return action;
}
return undefined;
}
/**
* Returns the report action immediately after the specified index.
* @param reportActions - all actions
* @param actionIndex - index of the action
*/
function findNextAction(reportActions: ReportAction[], actionIndex: number): OnyxEntry<ReportAction> {
for (let i = actionIndex - 1; i >= 0; i--) {
const action = reportActions.at(i);
// Find the next non-pending deletion report action, as the pending delete action means that it is not displayed in the UI, but still is in the report actions list.
// If we are offline, all actions are pending but shown in the UI, so we take the previous action, even if it is a delete.
if (!isNetworkOffline && action?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) {
continue;
}
if (action?.shouldShow === false) {
continue;
}
return action;
}
return undefined;
}
/**
* Returns true when the previous report action (before actionIndex) is made by the same actor who performed the action at actionIndex.
* Also checks to ensure that the comment is not too old to be shown as a grouped comment.
*
* @param reportActions - report actions ordered from latest
* @param actionIndex - index of the comment item in state to check
*/
function isConsecutiveActionMadeByPreviousActor(reportActions: ReportAction[], actionIndex: number): boolean {
const previousAction = findPreviousAction(reportActions, actionIndex);
const currentAction = reportActions.at(actionIndex);
return canActionsBeGrouped(currentAction, previousAction);
}
/**
* Returns true when the next report action (after actionIndex) is made by the same actor who performed the action at actionIndex.
* Also checks to ensure that the comment is not too old to be shown as a grouped comment.
*
* @param reportActions - report actions ordered from oldest
* @param actionIndex - index of the comment item in state to check
*/
function hasNextActionMadeBySameActor(reportActions: ReportAction[], actionIndex: number) {
const currentAction = reportActions.at(actionIndex);
const nextAction = findNextAction(reportActions, actionIndex);
if (actionIndex === 0) {
return false;
}
return canActionsBeGrouped(currentAction, nextAction);
}
function getReportActionActorAccountID(
reportAction: OnyxEntry<ReportAction>,
iouReport: OnyxEntry<Report>,
report: OnyxEntry<Report>,
delegatePersonalDetails?: PersonalDetails | undefined | null,
): number | undefined {
switch (reportAction?.actionName) {
case CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW: {
const ownerAccountID = iouReport?.ownerAccountID ?? reportAction?.childOwnerAccountID;
const actorAccountID = iouReport?.managerID ?? reportAction?.childManagerAccountID;
if (isPolicyExpenseChat(report) || delegatePersonalDetails) {
return ownerAccountID;
}
return actorAccountID;
}
case CONST.REPORT.ACTIONS.TYPE.CREATED: {
const reportNameValuePairs = allReportNameValuePair?.[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${iouReport?.reportID}`];
if (isHarvestCreatedExpenseReport(reportNameValuePairs?.origin, reportNameValuePairs?.originalID)) {
return CONST.ACCOUNT_ID.CONCIERGE;
}
return reportAction?.actorAccountID;
}
case CONST.REPORT.ACTIONS.TYPE.SUBMITTED:
case CONST.REPORT.ACTIONS.TYPE.SUBMITTED_AND_CLOSED:
case CONST.REPORT.ACTIONS.TYPE.APPROVED:
case CONST.REPORT.ACTIONS.TYPE.FORWARDED:
case CONST.REPORT.ACTIONS.TYPE.IOU: {
const originalMessage = getOriginalMessage(reportAction);
const actionName = reportAction?.actionName;
// Check if this should show Concierge as the actor
const wasSubmittedViaHarvesting = originalMessage && 'harvesting' in originalMessage ? originalMessage.harvesting : false;
const wasAutomatic = originalMessage && 'automaticAction' in originalMessage ? originalMessage.automaticAction : false;
const isPayment = originalMessage && 'type' in originalMessage && originalMessage.type === CONST.IOU.REPORT_ACTION_TYPE.PAY;
// Show Concierge for:
// - Harvesting (delayed submissions)
// - Automatic approvals/forwards via workspace rules
// - Automatic payments via workspace rules
if (wasSubmittedViaHarvesting || (wasAutomatic && actionName !== CONST.REPORT.ACTIONS.TYPE.IOU) || (wasAutomatic && isPayment)) {
return CONST.ACCOUNT_ID.CONCIERGE;
}
// For SUBMITTED actions, check adminAccountID first (admin-submit case)
if (actionName === CONST.REPORT.ACTIONS.TYPE.SUBMITTED || actionName === CONST.REPORT.ACTIONS.TYPE.SUBMITTED_AND_CLOSED) {
return reportAction?.adminAccountID ?? reportAction?.actorAccountID;
}
return reportAction?.actorAccountID;
}
default:
return reportAction?.actorAccountID;
}
}
/**
* Combines the logic for grouping chat messages isConsecutiveActionMadeByPreviousActor and hasNextActionMadeBySameActor.
* Returns true when messages are made by the same actor and not separated by more than 5 minutes.
*
* @param currentAction - Chronologically - latest action.
* @param adjacentAction - Chronologically - previous action. Named adjacentAction to avoid confusion as isConsecutiveActionMadeByPreviousActor and hasNextActionMadeBySameActor take action lists that are in opposite orders.
*/
function canActionsBeGrouped(currentAction?: ReportAction, adjacentAction?: ReportAction): boolean {
// It's OK for there to be no previous action, and in that case, false will be returned
// so that the comment isn't grouped
if (!currentAction || !adjacentAction) {
return false;
}
// Comments are only grouped if they happen within 5 minutes of each adjacent
if (new Date(currentAction?.created).getTime() - new Date(adjacentAction.created).getTime() > CONST.REPORT.ACTIONS.MAX_GROUPING_TIME) {
return false;
}
// Do not group if adjacent action was a created action
if (adjacentAction.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED) {
return false;
}