-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
OptionsListUtils.js
2028 lines (1809 loc) · 76.9 KB
/
OptionsListUtils.js
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';
import lodashGet from 'lodash/get';
import lodashOrderBy from 'lodash/orderBy';
import lodashSet from 'lodash/set';
import Onyx from 'react-native-onyx';
import _ from 'underscore';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import Timing from './actions/Timing';
import * as CollectionUtils from './CollectionUtils';
import * as ErrorUtils from './ErrorUtils';
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';
/**
* 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;
let currentUserAccountID;
Onyx.connect({
key: ONYXKEYS.SESSION,
callback: (val) => {
currentUserLogin = val && val.email;
currentUserAccountID = val && val.accountID;
},
});
let loginList;
Onyx.connect({
key: ONYXKEYS.LOGIN_LIST,
callback: (val) => (loginList = _.isEmpty(val) ? {} : val),
});
let allPersonalDetails;
Onyx.connect({
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
callback: (val) => (allPersonalDetails = _.isEmpty(val) ? {} : val),
});
let preferredLocale;
Onyx.connect({
key: ONYXKEYS.NVP_PREFERRED_LOCALE,
callback: (val) => (preferredLocale = val || CONST.LOCALES.DEFAULT),
});
const policies = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.POLICY,
callback: (policy, key) => {
if (!policy || !key || !policy.name) {
return;
}
policies[key] = policy;
},
});
const lastReportActions = {};
const allSortedReportActions = {};
const allReportActions = {};
const visibleReportActionItems = {};
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(_.toArray(actions), true);
allSortedReportActions[reportID] = sortedReportActions;
lastReportActions[reportID] = _.first(sortedReportActions);
// The report is only visible if it is the last action not deleted that
// does not match a closed or created state.
const reportActionsForDisplay = _.filter(
sortedReportActions,
(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];
},
});
const policyExpenseReports = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT,
callback: (report, key) => {
if (!ReportUtils.isPolicyExpenseChat(report)) {
return;
}
policyExpenseReports[key] = report;
},
});
let allTransactions = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.TRANSACTION,
waitForCollectionCallback: true,
callback: (val) => {
if (!val) {
return;
}
allTransactions = _.pick(val, (transaction) => transaction);
},
});
/**
* Adds expensify SMS domain (@expensify.sms) if login is a phone number and if it's not included yet
*
* @param {String} login
* @return {String}
*/
function addSMSDomainIfPhoneNumber(login) {
const parsedPhoneNumber = PhoneNumber.parsePhoneNumber(login);
if (parsedPhoneNumber.possible && !Str.isValidEmail(login)) {
return parsedPhoneNumber.number.e164 + CONST.SMS.DOMAIN;
}
return login;
}
/**
* Returns avatar data for a list of user accountIDs
*
* @param {Array<Number>} accountIDs
* @param {Object} personalDetails
* @param {Object} defaultValues {login: accountID} In workspace invite page, when new user is added we pass available data to opt in
* @returns {Object}
*/
function getAvatarsForAccountIDs(accountIDs, personalDetails, defaultValues = {}) {
const reversedDefaultValues = {};
_.map(Object.entries(defaultValues), (item) => {
reversedDefaultValues[item[1]] = item[0];
});
return _.map(accountIDs, (accountID) => {
const login = lodashGet(reversedDefaultValues, accountID, '');
const userPersonalDetail = lodashGet(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
*
* @param {Array} accountIDs
* @param {Object | null} personalDetails
* @returns {Object} – keys of the object are emails, values are PersonalDetails objects.
*/
function getPersonalDetailsForAccountIDs(accountIDs, personalDetails) {
const personalDetailsForAccountIDs = {};
if (!personalDetails) {
return personalDetailsForAccountIDs;
}
_.each(accountIDs, (accountID) => {
const cleanAccountID = Number(accountID);
if (!cleanAccountID) {
return;
}
let personalDetail = personalDetails[accountID];
if (!personalDetail) {
personalDetail = {
avatar: UserUtils.getDefaultAvatar(cleanAccountID),
};
}
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.
* @param {Object} personalDetails
* @returns {Boolean}
*/
function isPersonalDetailsReady(personalDetails) {
return !_.isEmpty(personalDetails) && _.some(_.keys(personalDetails), (key) => personalDetails[key].accountID);
}
/**
* Get the participant option for a report.
* @param {Object} participant
* @param {Array<Object>} personalDetails
* @returns {Object}
*/
function getParticipantsOption(participant, personalDetails) {
const detail = getPersonalDetailsForAccountIDs([participant.accountID], personalDetails)[participant.accountID];
const login = detail.login || participant.login;
const displayName = PersonalDetailsUtils.getDisplayNameOrDefault(detail, LocalePhoneNumber.formatPhoneNumber(login));
return {
keyForList: String(detail.accountID),
login,
accountID: detail.accountID,
text: displayName,
firstName: lodashGet(detail, 'firstName', ''),
lastName: lodashGet(detail, 'lastName', ''),
alternateText: LocalePhoneNumber.formatPhoneNumber(login) || displayName,
icons: [
{
source: UserUtils.getAvatar(detail.avatar, detail.accountID),
name: login,
type: CONST.ICON_TYPE_AVATAR,
id: detail.accountID,
},
],
phoneNumber: lodashGet(detail, 'phoneNumber', ''),
selected: participant.selected,
isSelected: participant.selected,
searchText: participant.searchText,
};
}
/**
* Constructs a Set with all possible names (displayName, firstName, lastName, email) for all participants in a report,
* to be used in isSearchStringMatch.
*
* @param {Array<Object>} personalDetailList
* @return {Set<String>}
*/
function getParticipantNames(personalDetailList) {
// 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();
_.each(personalDetailList, (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
*
* @param {Array} items
* @returns {Array}
*/
function uniqFast(items) {
const seenItems = {};
const result = [];
let j = 0;
for (let i = 0; i < items.length; i++) {
const item = items[i];
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().
*
* @param {Object} report
* @param {String} reportName
* @param {Array} personalDetailList
* @param {Boolean} isChatRoomOrPolicyExpenseChat
* @param {Boolean} isThread
* @return {String}
*/
function getSearchText(report, reportName, personalDetailList, isChatRoomOrPolicyExpenseChat, isThread) {
let searchTerms = [];
if (!isChatRoomOrPolicyExpenseChat) {
for (let i = 0; i < personalDetailList.length; i++) {
const personalDetail = personalDetailList[i];
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 || [];
for (let i = 0; i < visibleChatMemberAccountIDs.length; i++) {
const accountID = visibleChatMemberAccountIDs[i];
if (allPersonalDetails[accountID] && allPersonalDetails[accountID].login) {
searchTerms = searchTerms.concat(allPersonalDetails[accountID].login);
}
}
}
}
return uniqFast(searchTerms).join(' ');
}
/**
* Get an object of error messages keyed by microtime by combining all error objects related to the report.
* @param {Object} report
* @param {Object} reportActions
* @returns {Object}
*/
function getAllReportErrors(report, reportActions) {
const reportErrors = report.errors || {};
const reportErrorFields = report.errorFields || {};
const reportActionErrors = _.reduce(
reportActions,
(prevReportActionErrors, action) => (!action || _.isEmpty(action.errors) ? prevReportActionErrors : _.extend(prevReportActionErrors, action.errors)),
{},
);
const parentReportAction = !report.parentReportID || !report.parentReportActionID ? {} : lodashGet(allReportActions, [report.parentReportID, report.parentReportActionID], {});
if (parentReportAction.actorAccountID === currentUserAccountID && ReportActionUtils.isTransactionThread(parentReportAction)) {
const transactionID = lodashGet(parentReportAction, ['originalMessage', 'IOUTransactionID'], '');
const transaction = allTransactions[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`] || {};
if (TransactionUtils.hasMissingSmartscanFields(transaction) && !ReportUtils.isSettled(transaction.reportID)) {
_.extend(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)) {
_.extend(reportActionErrors, {smartscan: ErrorUtils.getMicroSecondOnyxError('report.genericSmartscanFailureMessage')});
}
} else if (ReportUtils.hasSmartscanError(_.values(reportActions))) {
_.extend(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 = _.reduce(errorSources, (prevReportErrors, errors) => (_.isEmpty(errors) ? prevReportErrors : _.extend(prevReportErrors, errors)), {});
return allReportErrors;
}
/**
* Get the last message text from the report directly or from other sources for special cases.
* @param {Object} report
* @returns {String}
*/
function getLastMessageTextForReport(report) {
const lastReportAction = _.find(allSortedReportActions[report.reportID], (reportAction) => ReportActionUtils.shouldReportActionBeVisibleAsLastAction(reportAction));
let lastMessageTextFromReport = '';
const lastActionName = lodashGet(lastReportAction, 'actionName', '');
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 = _.find(
allSortedReportActions[iouReport.reportID],
(reportAction, key) =>
ReportActionUtils.shouldReportActionBeVisible(reportAction, key) &&
reportAction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE &&
ReportActionUtils.isMoneyRequestAction(reportAction),
);
lastMessageTextFromReport = ReportUtils.getReportPreviewMessage(iouReport, lastIOUMoneyReportAction, true, ReportUtils.isChatReport(report), null, true);
} else if (ReportActionUtils.isReimbursementQueuedAction(lastReportAction)) {
lastMessageTextFromReport = ReportUtils.getReimbursementQueuedActionMessage(lastReportAction, report);
} else if (ReportActionUtils.isReimbursementDeQueuedAction(lastReportAction)) {
lastMessageTextFromReport = ReportUtils.getReimbursementDeQueuedActionMessage(report);
} else if (ReportActionUtils.isDeletedParentAction(lastReportAction) && ReportUtils.isChatReport(report)) {
lastMessageTextFromReport = ReportUtils.getDeletedParentActionMessageForChatReport(lastReportAction);
} else if (ReportUtils.isReportMessageAttachment({text: report.lastMessageText, html: report.lastMessageHtml, translationKey: report.lastMessageTranslationKey})) {
lastMessageTextFromReport = `[${Localize.translateLocal(report.lastMessageTranslationKey || 'common.attachment')}]`;
} else if (ReportActionUtils.isModifiedExpenseAction(lastReportAction)) {
const properSchemaForModifiedExpenseMessage = ModifiedExpenseMessage.getForReportAction(lastReportAction);
lastMessageTextFromReport = ReportUtils.formatReportLastMessageText(properSchemaForModifiedExpenseMessage, true);
} else if (
lastActionName === CONST.REPORT.ACTIONS.TYPE.TASKCOMPLETED ||
lastActionName === CONST.REPORT.ACTIONS.TYPE.TASKREOPENED ||
lastActionName === CONST.REPORT.ACTIONS.TYPE.TASKCANCELLED
) {
lastMessageTextFromReport = lodashGet(lastReportAction, 'message[0].text', '');
} else if (ReportActionUtils.isCreatedTaskReportAction(lastReportAction)) {
lastMessageTextFromReport = TaskUtils.getTaskCreatedMessage(lastReportAction);
}
return lastMessageTextFromReport || lodashGet(report, 'lastMessageText', '');
}
/**
* Creates a report list option
*
* @param {Array<Number>} accountIDs
* @param {Object} personalDetails
* @param {Object} report
* @param {Object} reportActions
* @param {Object} options
* @param {Boolean} [options.showChatPreviewLine]
* @param {Boolean} [options.forcePolicyNamePreview]
* @returns {Object}
*/
function createOption(accountIDs, personalDetails, report, reportActions = {}, {showChatPreviewLine = false, forcePolicyNamePreview = false}) {
const result = {
text: null,
alternateText: null,
pendingAction: null,
allReportErrors: null,
brickRoadIndicator: null,
icons: null,
tooltipText: null,
ownerAccountID: null,
subtitle: null,
participantsList: null,
accountID: 0,
login: null,
reportID: null,
phoneNumber: null,
hasDraftComment: false,
keyForList: null,
searchText: null,
isDefaultRoom: false,
isPinned: false,
isWaitingOnBankAccount: false,
iouReportID: null,
isIOUReportOwner: null,
iouReportAmount: 0,
isChatRoom: false,
isArchivedRoom: false,
shouldShowSubscript: false,
isPolicyExpenseChat: false,
isOwnPolicyExpenseChat: false,
isExpenseReport: false,
policyID: null,
isOptimisticPersonalDetail: false,
};
const personalDetailMap = getPersonalDetailsForAccountIDs(accountIDs, personalDetails);
const personalDetailList = _.values(personalDetailMap);
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 = !_.isEmpty(result.allReportErrors) ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : '';
result.pendingAction = report.pendingFields ? report.pendingFields.addWorkspaceRoom || report.pendingFields.createChat : null;
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;
hasMultipleParticipants = personalDetailList.length > 1 || result.isChatRoom || result.isPolicyExpenseChat;
subtitle = ReportUtils.getChatRoomSubtitle(report);
const lastMessageTextFromReport = getLastMessageTextForReport(report);
const lastActorDetails = personalDetailMap[report.lastActorAccountID] || null;
const lastActorDisplayName =
hasMultipleParticipants && lastActorDetails && lastActorDetails.accountID !== currentUserAccountID
? lastActorDetails.firstName || PersonalDetailsUtils.getDisplayNameOrDefault(lastActorDetails)
: '';
let lastMessageText = lastMessageTextFromReport;
if (result.isArchivedRoom) {
const archiveReason =
(lastReportActions[report.reportID] && lastReportActions[report.reportID].originalMessage && lastReportActions[report.reportID].originalMessage.reason) ||
CONST.REPORT.ARCHIVE_REASON.DEFAULT;
lastMessageText = Localize.translate(preferredLocale, `reportArchiveReasons.${archiveReason}`, {
displayName: archiveReason.displayName || PersonalDetailsUtils.getDisplayNameOrDefault(lastActorDetails),
policyName: ReportUtils.getPolicyName(report),
});
}
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 {
reportName = ReportUtils.getDisplayNameForParticipant(accountIDs[0]) || LocalePhoneNumber.formatPhoneNumber(personalDetail.login);
result.keyForList = String(accountIDs[0]);
result.alternateText = LocalePhoneNumber.formatPhoneNumber(lodashGet(personalDetails, [accountIDs[0], 'login'], ''));
}
result.isIOUReportOwner = ReportUtils.isIOUOwnedByCurrentUser(result);
result.iouReportAmount = ReportUtils.getMoneyRequestReimbursableTotal(result);
if (!hasMultipleParticipants) {
result.login = personalDetail.login;
result.accountID = Number(personalDetail.accountID);
result.phoneNumber = personalDetail.phoneNumber;
}
result.text = reportName;
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 policy expense report.
* @param {Object} report
* @returns {Object}
*/
function getPolicyExpenseReportOption(report) {
const expenseReport = policyExpenseReports[`${ONYXKEYS.COLLECTION.REPORT}${report.reportID}`];
const option = createOption(
expenseReport.visibleChatMemberAccountIDs,
allPersonalDetails,
expenseReport,
{},
{
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 = report.selected;
option.isSelected = report.selected;
return option;
}
/**
* Searches for a match when provided with a value
*
* @param {String} searchValue
* @param {String} searchText
* @param {Set<String>} [participantNames]
* @param {Boolean} isChatRoom
* @returns {Boolean}
*/
function isSearchStringMatch(searchValue, searchText, participantNames = new Set(), isChatRoom = false) {
const searchWords = new Set(searchValue.replace(/,/g, ' ').split(' '));
const valueToSearch = searchText && 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.
*
* @param {Object} userDetails
* @returns {Boolean}
*/
function isCurrentUser(userDetails) {
if (!userDetails) {
return false;
}
// If user login is a mobile number, append sms domain if not appended already.
const userDetailsLogin = addSMSDomainIfPhoneNumber(userDetails.login);
if (currentUserLogin.toLowerCase() === userDetailsLogin.toLowerCase()) {
return true;
}
// Check if userDetails login exists in loginList
return _.some(_.keys(loginList), (login) => login.toLowerCase() === userDetailsLogin.toLowerCase());
}
/**
* Calculates count of all enabled options
*
* @param {Object[]} options - an initial strings array
* @param {Boolean} options[].enabled - a flag to enable/disable option in a list
* @param {String} options[].name - a name of an option
* @returns {Number}
*/
function getEnabledCategoriesCount(options) {
return _.filter(options, (option) => option.enabled).length;
}
/**
* Verifies that there is at least one enabled option
*
* @param {Object[]} options - an initial strings array
* @param {Boolean} options[].enabled - a flag to enable/disable option in a list
* @param {String} options[].name - a name of an option
* @returns {Boolean}
*/
function hasEnabledOptions(options) {
return _.some(options, (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.
*
* @param {Object<String, {name: String, enabled: Boolean}>} categories
* @returns {Array<Object>}
*/
function sortCategories(categories) {
// Sorts categories alphabetically by name.
const sortedCategories = _.chain(categories)
.values()
.sortBy((category) => category.name)
.value();
// 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"
* }
* }
* }
* }
*/
_.each(sortedCategories, (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.
*
* @param {Object} initialHierarchy
* @returns {Array<Object>}
*/
const flatHierarchy = (initialHierarchy) =>
_.reduce(
initialHierarchy,
(acc, category) => {
const {name, ...subcategories} = category;
if (!_.isEmpty(name)) {
const categoryObject = {
name,
enabled: lodashGet(categories, [name, 'enabled'], false),
};
acc.push(categoryObject);
}
if (!_.isEmpty(subcategories)) {
const nestedCategories = flatHierarchy(subcategories);
acc.push(..._.sortBy(nestedCategories, 'name'));
}
return acc;
},
[],
);
return flatHierarchy(hierarchy);
}
/**
* Sorts tags alphabetically by name.
*
* @param {Object<String, {name: String, enabled: Boolean}>} tags
* @returns {Array<Object>}
*/
function sortTags(tags) {
const sortedTags = _.chain(tags)
.values()
.sortBy((tag) => tag.name)
.value();
return sortedTags;
}
/**
* Builds the options for the category tree hierarchy via indents
*
* @param {Object[]} options - an initial object array
* @param {Boolean} options[].enabled - a flag to enable/disable option in a list
* @param {String} options[].name - a name of an option
* @param {Boolean} [isOneLine] - a flag to determine if text should be one line
* @returns {Array<Object>}
*/
function getCategoryOptionTree(options, isOneLine = false) {
const optionCollection = new Map();
_.each(options, (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,
});
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,
});
});
});
return Array.from(optionCollection.values());
}
/**
* Builds the section list for categories
*
* @param {Object<String, {name: String, enabled: Boolean}>} categories
* @param {String[]} recentlyUsedCategories
* @param {Object[]} selectedOptions
* @param {String} selectedOptions[].name
* @param {String} searchInputValue
* @param {Number} maxRecentReportsToShow
* @returns {Array<Object>}
*/
function getCategoryListSections(categories, recentlyUsedCategories, selectedOptions, searchInputValue, maxRecentReportsToShow) {
const sortedCategories = sortCategories(categories);
const enabledCategories = _.filter(sortedCategories, (category) => category.enabled);
const categorySections = [];
const numberOfCategories = _.size(enabledCategories);
let indexOffset = 0;
if (numberOfCategories === 0 && selectedOptions.length > 0) {
categorySections.push({
// "Selected" section
title: '',
shouldShow: false,
indexOffset,
data: getCategoryOptionTree(selectedOptions, true),
});
return categorySections;
}
if (!_.isEmpty(searchInputValue)) {
const searchCategories = _.filter(enabledCategories, (category) => category.name.toLowerCase().includes(searchInputValue.toLowerCase()));
categorySections.push({
// "Search" section
title: '',
shouldShow: true,
indexOffset,
data: getCategoryOptionTree(searchCategories, true),
});
return categorySections;
}
if (!_.isEmpty(selectedOptions)) {
categorySections.push({
// "Selected" section
title: '',
shouldShow: false,
indexOffset,
data: getCategoryOptionTree(selectedOptions, true),
});
indexOffset += selectedOptions.length;
}
const selectedOptionNames = _.map(selectedOptions, (selectedOption) => selectedOption.name);
const filteredCategories = _.filter(enabledCategories, (category) => !_.includes(selectedOptionNames, category.name));
const numberOfVisibleCategories = selectedOptions.length + filteredCategories.length;
if (numberOfVisibleCategories < CONST.CATEGORY_LIST_THRESHOLD) {
categorySections.push({
// "All" section when items amount less than the threshold
title: '',
shouldShow: false,
indexOffset,
data: getCategoryOptionTree(filteredCategories),
});
return categorySections;
}
const filteredRecentlyUsedCategories = _.chain(recentlyUsedCategories)
.filter((categoryName) => !_.includes(selectedOptionNames, categoryName) && lodashGet(categories, [categoryName, 'enabled'], false))
.map((categoryName) => ({
name: categoryName,
enabled: lodashGet(categories, [categoryName, 'enabled'], false),
}))
.value();
if (!_.isEmpty(filteredRecentlyUsedCategories)) {
const cutRecentlyUsedCategories = filteredRecentlyUsedCategories.slice(0, maxRecentReportsToShow);
categorySections.push({
// "Recent" section
title: Localize.translateLocal('common.recent'),
shouldShow: true,
indexOffset,
data: getCategoryOptionTree(cutRecentlyUsedCategories, true),
});
indexOffset += filteredRecentlyUsedCategories.length;
}
categorySections.push({
// "All" section when items amount more than the threshold
title: Localize.translateLocal('common.all'),
shouldShow: true,
indexOffset,
data: getCategoryOptionTree(filteredCategories),
});
return categorySections;
}
/**
* Transforms the provided tags into objects with a specific structure.
*
* @param {Object[]} tags - an initial tag array
* @param {Boolean} tags[].enabled - a flag to enable/disable option in a list
* @param {String} tags[].name - a name of an option
* @returns {Array<Object>}
*/
function getTagsOptions(tags) {
return _.map(tags, (tag) => {
// This is to remove unnecessary escaping backslash in tag name sent from backend.
const cleanedName = PolicyUtils.getCleanedTagName(tag.name);
return {
text: cleanedName,
keyForList: tag.name,
searchText: tag.name,
tooltipText: cleanedName,
isDisabled: !tag.enabled,
};
});
}
/**
* Build the section list for tags
*
* @param {Object[]} tags
* @param {String} tags[].name
* @param {Boolean} tags[].enabled
* @param {String[]} recentlyUsedTags
* @param {Object[]} selectedOptions
* @param {String} selectedOptions[].name
* @param {String} searchInputValue
* @param {Number} maxRecentReportsToShow
* @returns {Array<Object>}
*/
function getTagListSections(tags, recentlyUsedTags, selectedOptions, searchInputValue, maxRecentReportsToShow) {
const tagSections = [];
const sortedTags = sortTags(tags);
const enabledTags = _.filter(sortedTags, (tag) => tag.enabled);
const numberOfTags = _.size(enabledTags);
let indexOffset = 0;
// If all tags are disabled but there's a previously selected tag, show only the selected tag
if (numberOfTags === 0 && selectedOptions.length > 0) {
const selectedTagOptions = _.map(selectedOptions, (option) => ({
name: option.name,
// Should be marked as enabled to be able to be de-selected
enabled: true,
}));
tagSections.push({
// "Selected" section
title: '',
shouldShow: false,
indexOffset,
data: getTagsOptions(selectedTagOptions),
});
return tagSections;
}