-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
OptionsListUtils.js
1525 lines (1366 loc) · 56.2 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 _ from 'underscore';
import Onyx from 'react-native-onyx';
import lodashOrderBy from 'lodash/orderBy';
import lodashGet from 'lodash/get';
import Str from 'expensify-common/lib/str';
import {parsePhoneNumber} from 'awesome-phonenumber';
import ONYXKEYS from '../ONYXKEYS';
import CONST from '../CONST';
import * as ReportUtils from './ReportUtils';
import * as Localize from './Localize';
import Permissions from './Permissions';
import * as CollectionUtils from './CollectionUtils';
import Navigation from './Navigation/Navigation';
import * as LoginUtils from './LoginUtils';
import * as LocalePhoneNumber from './LocalePhoneNumber';
import * as UserUtils from './UserUtils';
import * as ReportActionUtils from './ReportActionsUtils';
import * as PersonalDetailsUtils from './PersonalDetailsUtils';
import * as ErrorUtils from './ErrorUtils';
/**
* 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 = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT_ACTIONS,
callback: (actions, key) => {
if (!key || !actions) {
return;
}
const sortedReportActions = ReportActionUtils.getSortedReportActions(_.toArray(actions), true);
const reportID = CollectionUtils.extractCollectionItemID(key);
allSortedReportActions[reportID] = sortedReportActions;
lastReportActions[reportID] = _.first(sortedReportActions);
},
});
const policyExpenseReports = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT,
callback: (report, key) => {
if (!ReportUtils.isPolicyExpenseChat(report)) {
return;
}
policyExpenseReports[key] = report;
},
});
/**
* 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 policyExpenseChatAvatarSource = ReportUtils.getWorkspaceAvatar(expenseReport);
const reportName = ReportUtils.getReportName(expenseReport);
return {
...expenseReport,
keyForList: expenseReport.policyID,
text: reportName,
alternateText: Localize.translateLocal('workspace.common.workspace'),
icons: [
{
source: policyExpenseChatAvatarSource,
name: reportName,
type: CONST.ICON_TYPE_WORKSPACE,
},
],
selected: report.selected,
isPolicyExpenseChat: true,
searchText: report.searchText,
};
}
/**
* 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 = 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} 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);
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 = detail.displayName || 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,
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(participant.displayName.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([personalDetail.displayName, 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 participantAccountIDs = report.participantAccountIDs || [];
for (let i = 0; i < participantAccountIDs.length; i++) {
const accountID = participantAccountIDs[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 = {};
_.each(reportActions, (action) => {
if (action && !_.isEmpty(action.errors)) {
_.extend(reportActionErrors, action.errors);
} else if (ReportActionUtils.isReportPreviewAction(action)) {
const iouReportID = ReportActionUtils.getIOUReportIDFromReportActionPreview(action);
// Instead of adding all Smartscan errors, let's just add a generic error if there are any. This
// will be more performant and provide the same result in the UI
if (ReportUtils.hasMissingSmartscanFields(iouReportID)) {
_.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, key) => ReportActionUtils.shouldReportActionBeVisible(reportAction, key) && reportAction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE,
);
let lastMessageTextFromReport = '';
if (ReportUtils.isReportMessageAttachment({text: report.lastMessageText, html: report.lastMessageHtml, translationKey: report.lastMessageTranslationKey})) {
lastMessageTextFromReport = `[${Localize.translateLocal(report.lastMessageTranslationKey || 'common.attachment')}]`;
} else if (ReportActionUtils.isMoneyRequestAction(lastReportAction)) {
lastMessageTextFromReport = ReportUtils.getReportPreviewMessage(report, lastReportAction, true);
} else if (ReportActionUtils.isReportPreviewAction(lastReportAction)) {
const iouReport = ReportUtils.getReport(ReportActionUtils.getIOUReportIDFromReportActionPreview(lastReportAction));
lastMessageTextFromReport = ReportUtils.getReportPreviewMessage(iouReport, lastReportAction);
} else if (ReportActionUtils.isModifiedExpenseAction(lastReportAction)) {
lastMessageTextFromReport = ReportUtils.getModifiedExpenseMessage(lastReportAction);
} else {
lastMessageTextFromReport = report ? report.lastMessageText || '' : '';
// Yeah this is a bit ugly. If the latest report action that is not a whisper has been moderated as pending remove
// then set the last message text to the text of the latest visible action that is not a whisper or the report creation message.
const lastNonWhisper = _.find(allSortedReportActions[report.reportID], (action) => !ReportActionUtils.isWhisperAction(action)) || {};
if (ReportActionUtils.isPendingRemove(lastNonWhisper)) {
const latestVisibleAction =
_.find(
allSortedReportActions[report.reportID],
(action) => ReportActionUtils.shouldReportActionBeVisibleAsLastAction(action) && !ReportActionUtils.isCreatedAction(action),
) || {};
lastMessageTextFromReport = lodashGet(latestVisibleAction, 'message[0].text', '');
}
}
return lastMessageTextFromReport;
}
/**
* 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,
hasOutstandingIOU: false,
isWaitingOnBankAccount: false,
iouReportID: null,
isIOUReportOwner: null,
iouReportAmount: 0,
isChatRoom: false,
isArchivedRoom: false,
shouldShowSubscript: false,
isPolicyExpenseChat: false,
isExpenseReport: false,
policyID: null,
};
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;
if (report) {
result.isChatRoom = ReportUtils.isChatRoom(report);
result.isDefaultRoom = ReportUtils.isDefaultRoom(report);
result.isArchivedRoom = ReportUtils.isArchivedRoom(report);
result.isPolicyExpenseChat = ReportUtils.isPolicyExpenseChat(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.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.participantAccountIDs || []);
result.hasOutstandingIOU = report.hasOutstandingIOU;
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;
let lastMessageText = hasMultipleParticipants && lastActorDetails && lastActorDetails.accountID !== currentUserAccountID ? `${lastActorDetails.displayName}: ` : '';
lastMessageText += report ? 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, 'displayName'),
policyName: ReportUtils.getPolicyName(report),
});
}
if (result.isChatRoom || result.isPolicyExpenseChat) {
result.alternateText = showChatPreviewLine && !forcePolicyNamePreview && lastMessageText ? lastMessageText : subtitle;
} else if (result.isMoneyRequestReport) {
result.alternateText = lastMessageTextFromReport.length > 0 ? lastMessageText : Localize.translate(preferredLocale, 'report.noActivityYet');
} else if (result.isTaskReport) {
result.alternateText = showChatPreviewLine && lastMessageText ? lastMessageTextFromReport : 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]);
result.keyForList = String(accountIDs[0]);
result.alternateText = LocalePhoneNumber.formatPhoneNumber(lodashGet(personalDetails, [accountIDs[0], 'login'], ''));
}
result.isIOUReportOwner = ReportUtils.isIOUOwnedByCurrentUser(result);
result.iouReportAmount = ReportUtils.getMoneyRequestTotal(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), false, personalDetail.login, personalDetail.accountID);
result.subtitle = subtitle;
return result;
}
/**
* 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);
}
/**
* Build 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 = {};
_.each(options, (option) => {
if (!option.enabled) {
return;
}
if (isOneLine) {
if (_.has(optionCollection, option.name)) {
return;
}
optionCollection[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;
if (_.has(optionCollection, optionName)) {
return;
}
optionCollection[optionName] = {
text: `${indents}${optionName}`,
keyForList: optionName,
searchText: array.slice(0, index + 1).join(CONST.PARENT_CHILD_SEPARATOR),
tooltipText: optionName,
isDisabled: isChild ? !option.enabled : true,
};
});
});
return _.values(optionCollection);
}
/**
* Build 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 categorySections = [];
const categoriesValues = _.chain(categories)
.values()
.filter((category) => category.enabled)
.value();
const numberOfCategories = _.size(categoriesValues);
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(categoriesValues, (category) => category.name.toLowerCase().includes(searchInputValue.toLowerCase()));
categorySections.push({
// "Search" section
title: '',
shouldShow: false,
indexOffset,
data: getCategoryOptionTree(searchCategories, true),
});
return categorySections;
}
if (numberOfCategories < CONST.CATEGORY_LIST_THRESHOLD) {
categorySections.push({
// "All" section when items amount less than the threshold
title: '',
shouldShow: false,
indexOffset,
data: getCategoryOptionTree(categoriesValues),
});
return categorySections;
}
const selectedOptionNames = _.map(selectedOptions, (selectedOption) => selectedOption.name);
const filteredRecentlyUsedCategories = _.map(
_.filter(recentlyUsedCategories, (category) => !_.includes(selectedOptionNames, category)),
(category) => ({
name: category,
enabled: lodashGet(categories, `${category}.enabled`, false),
}),
);
const filteredCategories = _.filter(categoriesValues, (category) => !_.includes(selectedOptionNames, category.name));
if (!_.isEmpty(selectedOptions)) {
categorySections.push({
// "Selected" section
title: '',
shouldShow: false,
indexOffset,
data: getCategoryOptionTree(selectedOptions, true),
});
indexOffset += selectedOptions.length;
}
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) => ({
text: tag.name,
keyForList: tag.name,
searchText: tag.name,
tooltipText: tag.name,
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 enabledTags = _.filter(tags, (tag) => tag.enabled);
const numberOfTags = _.size(enabledTags);
let indexOffset = 0;
if (!_.isEmpty(searchInputValue)) {
const searchTags = _.filter(enabledTags, (tag) => tag.name.toLowerCase().includes(searchInputValue.toLowerCase()));
tagSections.push({
// "Search" section
title: '',
shouldShow: false,
indexOffset,
data: getTagsOptions(searchTags),
});
return tagSections;
}
if (numberOfTags < CONST.TAG_LIST_THRESHOLD) {
tagSections.push({
// "All" section when items amount less than the threshold
title: '',
shouldShow: false,
indexOffset,
data: getTagsOptions(enabledTags),
});
return tagSections;
}
const selectedOptionNames = _.map(selectedOptions, (selectedOption) => selectedOption.name);
const filteredRecentlyUsedTags = _.map(
_.filter(recentlyUsedTags, (recentlyUsedTag) => {
const tagObject = _.find(tags, (tag) => tag.name === recentlyUsedTag);
return Boolean(tagObject && tagObject.enabled) && !_.includes(selectedOptionNames, recentlyUsedTag);
}),
(tag) => ({name: tag, enabled: true}),
);
const filteredTags = _.filter(enabledTags, (tag) => !_.includes(selectedOptionNames, tag.name));
if (!_.isEmpty(selectedOptions)) {
const selectedTagOptions = _.map(selectedOptions, (option) => {
const tagObject = _.find(tags, (tag) => tag.name === option.name);
return {
name: option.name,
enabled: Boolean(tagObject && tagObject.enabled),
};
});
tagSections.push({
// "Selected" section
title: '',
shouldShow: false,
indexOffset,
data: getTagsOptions(selectedTagOptions),
});
indexOffset += selectedOptions.length;
}
if (!_.isEmpty(filteredRecentlyUsedTags)) {
const cutRecentlyUsedTags = filteredRecentlyUsedTags.slice(0, maxRecentReportsToShow);
tagSections.push({
// "Recent" section
title: Localize.translateLocal('common.recent'),
shouldShow: true,
indexOffset,
data: getTagsOptions(cutRecentlyUsedTags),
});
indexOffset += filteredRecentlyUsedTags.length;
}
tagSections.push({
// "All" section when items amount more than the threshold
title: Localize.translateLocal('common.all'),
shouldShow: true,
indexOffset,
data: getTagsOptions(filteredTags),
});
return tagSections;
}
/**
* Build the options
*
* @param {Object} reports
* @param {Object} personalDetails
* @param {Object} options
* @returns {Object}
* @private
*/
function getOptions(
reports,
personalDetails,
{
reportActions = {},
betas = [],
selectedOptions = [],
maxRecentReportsToShow = 0,
excludeLogins = [],
includeMultipleParticipantReports = false,
includePersonalDetails = false,
includeRecentReports = false,
// When sortByReportTypeInSearch flag is true, recentReports will include the personalDetails options as well.
sortByReportTypeInSearch = false,
searchInputValue = '',
showChatPreviewLine = false,
sortPersonalDetailsByAlphaAsc = true,
forcePolicyNamePreview = false,
includeOwnedWorkspaceChats = false,
includeThreads = false,
includeTasks = false,
includeMoneyRequests = false,
excludeUnknownUsers = false,
includeP2P = true,
includeCategories = false,
categories = {},
recentlyUsedCategories = [],
includeTags = false,
tags = {},
recentlyUsedTags = [],
canInviteUser = true,
},
) {
if (includeCategories) {
const categoryOptions = getCategoryListSections(categories, recentlyUsedCategories, selectedOptions, searchInputValue, maxRecentReportsToShow);
return {
recentReports: [],
personalDetails: [],
userToInvite: null,
currentUserOption: null,
categoryOptions,
tagOptions: [],
};
}
if (includeTags) {
const tagOptions = getTagListSections(_.values(tags), recentlyUsedTags, selectedOptions, searchInputValue, maxRecentReportsToShow);
return {
recentReports: [],
personalDetails: [],
userToInvite: null,
currentUserOption: null,
categoryOptions: [],
tagOptions,
};
}
if (!isPersonalDetailsReady(personalDetails)) {
return {
recentReports: [],
personalDetails: [],
userToInvite: null,
currentUserOption: null,
categoryOptions: [],
tagOptions: [],
};
}
let recentReportOptions = [];
let personalDetailsOptions = [];
const reportMapForAccountIDs = {};
const parsedPhoneNumber = parsePhoneNumber(LoginUtils.appendCountryCode(Str.removeSMSDomain(searchInputValue)));
const searchValue = parsedPhoneNumber.possible ? parsedPhoneNumber.number.e164 : searchInputValue.toLowerCase();
// Filter out all the reports that shouldn't be displayed
const filteredReports = _.filter(reports, (report) => ReportUtils.shouldReportBeInOptionList(report, Navigation.getTopmostReportId(), false, betas, policies));
// Sorting the reports works like this:
// - Order everything by the last message timestamp (descending)
// - All archived reports should remain at the bottom
const orderedReports = _.sortBy(filteredReports, (report) => {
if (ReportUtils.isArchivedRoom(report)) {
return CONST.DATE.UNIX_EPOCH;
}
return report.lastVisibleActionCreated;
});
orderedReports.reverse();
const allReportOptions = [];
_.each(orderedReports, (report) => {
if (!report) {