-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
OptionsListUtils.js
1076 lines (970 loc) · 41.3 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';
/**
* 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 expenseReports = {};
const iouReports = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT,
callback: (report, key) => {
if (!report || !key || !_.isNumber(report.ownerAccountID)) {
return;
}
if (ReportUtils.isExpenseReport(report)) {
expenseReports[key] = report;
return;
}
if (ReportUtils.isIOUReport(report)) {
iouReports[key] = report;
}
},
});
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 options for a policy expense report.
* @param {Object} report
* @returns {Array}
*/
function getPolicyExpenseReportOptions(report) {
const expenseReport = policyExpenseReports[`${ONYXKEYS.COLLECTION.REPORT}${report.reportID}`];
const policyExpenseChatAvatarSource = ReportUtils.getWorkspaceAvatar(expenseReport);
return [
{
...expenseReport,
keyForList: expenseReport.policyID,
text: expenseReport.displayName,
alternateText: Localize.translateLocal('workspace.common.workspace'),
icons: [
{
source: policyExpenseChatAvatarSource,
name: expenseReport.displayName,
type: CONST.ICON_TYPE_WORKSPACE,
},
],
selected: report.selected,
isPolicyExpenseChat: true,
},
];
}
/**
* 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 options for a report.
* @param {Array<Object>} participants
* @param {Array<Object>} personalDetails
* @returns {Array}
*/
function getParticipantsOptions(participants, personalDetails) {
const details = getPersonalDetailsForAccountIDs(_.pluck(participants, 'accountID'), personalDetails);
return _.map(participants, (participant) => {
const detail = details[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,
},
],
payPalMeAddress: lodashGet(detail, 'payPalMeAddress', ''),
phoneNumber: lodashGet(detail, 'phoneNumber', ''),
selected: participant.selected,
};
});
}
/**
* 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 reportID = report.reportID;
const reportsActions = reportActions[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`] || {};
const reportActionErrors = _.reduce(
reportsActions,
(prevReportActionErrors, action) => (_.isEmpty(action.errors) ? prevReportActionErrors : _.extend(prevReportActionErrors, action.errors)),
{},
);
// 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 = lastReportActions[report.reportID];
let lastMessageTextFromReport = '';
if (ReportUtils.isReportMessageAttachment({text: report.lastMessageText, html: report.lastMessageHtml, translationKey: report.lastMessageTranslationKey})) {
lastMessageTextFromReport = `[${Localize.translateLocal(report.lastMessageTranslationKey || 'common.attachment')}]`;
} else if (ReportActionUtils.isReportPreviewAction(lastReportAction)) {
const iouReport = ReportUtils.getReport(ReportActionUtils.getIOUReportIDFromReportActionPreview(lastReportAction));
lastMessageTextFromReport = ReportUtils.getReportPreviewMessage(iouReport, 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.
const lastNonWhisper = _.find(allSortedReportActions[report.reportID], (action) => !ReportActionUtils.isWhisperAction(action)) || {};
if (ReportActionUtils.isPendingRemove(lastNonWhisper)) {
const latestVisibleAction =
_.find(
allSortedReportActions[report.reportID],
(action) => ReportActionUtils.shouldReportActionBeVisible(action, action.reportActionID) && !ReportActionUtils.isWhisperAction(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,
payPalMeAddress: null,
hasDraftComment: false,
keyForList: null,
searchText: null,
isDefaultRoom: false,
isPinned: false,
hasOutstandingIOU: false,
iouReportID: null,
isIOUReportOwner: null,
iouReportAmount: 0,
isChatRoom: false,
isArchivedRoom: false,
shouldShowSubscript: false,
isPolicyExpenseChat: false,
isExpenseReport: 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;
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;
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, iouReports);
result.iouReportAmount = ReportUtils.getMoneyRequestTotal(result, iouReports);
if (!hasMultipleParticipants) {
result.login = personalDetail.login;
result.accountID = Number(personalDetail.accountID);
result.phoneNumber = personalDetail.phoneNumber;
result.payPalMeAddress = personalDetail.payPalMeAddress;
}
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());
}
/**
* 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,
},
) {
if (!isPersonalDetailsReady(personalDetails)) {
return {
recentReports: [],
personalDetails: [],
userToInvite: null,
currentUserOption: null,
};
}
// We're only picking personal details that have logins set
// This is a temporary fix for all the logic that's been breaking because of the new privacy changes
// See https://github.com/Expensify/Expensify/issues/293465 for more context
// eslint-disable-next-line no-param-reassign
personalDetails = _.pick(personalDetails, (detail) => Boolean(detail.login));
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, iouReports, 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) {
return;
}
const isThread = ReportUtils.isChatThread(report);
const isChatRoom = ReportUtils.isChatRoom(report);
const isTaskReport = ReportUtils.isTaskReport(report);
const isPolicyExpenseChat = ReportUtils.isPolicyExpenseChat(report);
const isMoneyRequestReport = ReportUtils.isMoneyRequestReport(report);
const accountIDs = report.participantAccountIDs || [];
if (isPolicyExpenseChat && report.isOwnPolicyExpenseChat && !includeOwnedWorkspaceChats) {
return;
}
if (isThread && !includeThreads) {
return;
}
if (isTaskReport && !includeTasks) {
return;
}
if (isMoneyRequestReport && !includeMoneyRequests) {
return;
}
// Save the report in the map if this is a single participant so we can associate the reportID with the
// personal detail option later. Individuals should not be associated with single participant
// policyExpenseChats or chatRooms since those are not people.
if (accountIDs.length <= 1 && !isPolicyExpenseChat && !isChatRoom) {
reportMapForAccountIDs[accountIDs[0]] = report;
}
const isSearchingSomeonesPolicyExpenseChat = !report.isOwnPolicyExpenseChat && searchValue !== '';
// Checks to see if the current user is the admin of the policy, if so the policy
// name preview will be shown.
const isPolicyChatAdmin = ReportUtils.isPolicyExpenseChatAdmin(report, policies);
allReportOptions.push(
createOption(accountIDs, personalDetails, report, reportActions, {
showChatPreviewLine,
forcePolicyNamePreview: isPolicyExpenseChat ? isSearchingSomeonesPolicyExpenseChat || isPolicyChatAdmin : forcePolicyNamePreview,
}),
);
});
let allPersonalDetailsOptions = _.map(personalDetails, (personalDetail) =>
createOption([personalDetail.accountID], personalDetails, reportMapForAccountIDs[personalDetail.accountID], reportActions, {
showChatPreviewLine,
forcePolicyNamePreview,
}),
);
if (sortPersonalDetailsByAlphaAsc) {
// PersonalDetails should be ordered Alphabetically by default - https://github.com/Expensify/App/issues/8220#issuecomment-1104009435
allPersonalDetailsOptions = lodashOrderBy(allPersonalDetailsOptions, [(personalDetail) => personalDetail.text && personalDetail.text.toLowerCase()], 'asc');
}
// Always exclude already selected options and the currently logged in user
const loginOptionsToExclude = [...selectedOptions, {login: currentUserLogin}];
_.each(excludeLogins, (login) => {
loginOptionsToExclude.push({login});
});
if (includeRecentReports) {
for (let i = 0; i < allReportOptions.length; i++) {
const reportOption = allReportOptions[i];
// Stop adding options to the recentReports array when we reach the maxRecentReportsToShow value
if (recentReportOptions.length > 0 && recentReportOptions.length === maxRecentReportsToShow) {
break;
}
const isCurrentUserOwnedPolicyExpenseChatThatCouldShow =
reportOption.isPolicyExpenseChat && reportOption.ownerAccountID === currentUserAccountID && includeOwnedWorkspaceChats && !reportOption.isArchivedRoom;
// Skip if we aren't including multiple participant reports and this report has multiple participants
if (!isCurrentUserOwnedPolicyExpenseChatThatCouldShow && !includeMultipleParticipantReports && !reportOption.login) {
continue;
}
// If we're excluding threads, check the report to see if it has a single participant and if the participant is already selected
if (!includeThreads && reportOption.login && _.some(loginOptionsToExclude, (option) => option.login === reportOption.login)) {
continue;
}
// Finally check to see if this option is a match for the provided search string if we have one
const {searchText, participantsList, isChatRoom} = reportOption;
const participantNames = getParticipantNames(participantsList);
if (searchValue && !isSearchStringMatch(searchValue, searchText, participantNames, isChatRoom)) {
continue;
}
recentReportOptions.push(reportOption);
// Add this login to the exclude list so it won't appear when we process the personal details
if (reportOption.login) {
loginOptionsToExclude.push({login: reportOption.login});
}
}
}
if (includePersonalDetails) {
// Next loop over all personal details removing any that are selectedUsers or recentChats
_.each(allPersonalDetailsOptions, (personalDetailOption) => {
if (_.some(loginOptionsToExclude, (loginOptionToExclude) => loginOptionToExclude.login === personalDetailOption.login)) {
return;
}
const {searchText, participantsList, isChatRoom} = personalDetailOption;
const participantNames = getParticipantNames(participantsList);
if (searchValue && !isSearchStringMatch(searchValue, searchText, participantNames, isChatRoom)) {
return;
}
personalDetailsOptions.push(personalDetailOption);
});
}
let currentUserOption = _.find(allPersonalDetailsOptions, (personalDetailsOption) => personalDetailsOption.login === currentUserLogin);
if (searchValue && !isSearchStringMatch(searchValue, currentUserOption.searchText)) {
currentUserOption = null;
}
let userToInvite = null;
const noOptions = recentReportOptions.length + personalDetailsOptions.length === 0 && !currentUserOption;
const noOptionsMatchExactly = !_.find(personalDetailsOptions.concat(recentReportOptions), (option) => option.login === addSMSDomainIfPhoneNumber(searchValue).toLowerCase());
if (
searchValue &&
(noOptions || noOptionsMatchExactly) &&
!isCurrentUser({login: searchValue}) &&
_.every(selectedOptions, (option) => option.login !== searchValue) &&
((Str.isValidEmail(searchValue) && !Str.isDomainEmail(searchValue) && !Str.endsWith(searchValue, CONST.SMS.DOMAIN)) || parsedPhoneNumber.possible) &&
!_.find(loginOptionsToExclude, (loginOptionToExclude) => loginOptionToExclude.login === addSMSDomainIfPhoneNumber(searchValue).toLowerCase()) &&
(searchValue !== CONST.EMAIL.CHRONOS || Permissions.canUseChronos(betas))
) {
// Generates an optimistic account ID for new users not yet saved in Onyx
const optimisticAccountID = UserUtils.generateAccountID(searchValue);
const personalDetailsExtended = {
...personalDetails,
[optimisticAccountID]: {
accountID: optimisticAccountID,
login: searchValue,
avatar: UserUtils.getDefaultAvatar(optimisticAccountID),
},
};
userToInvite = createOption([optimisticAccountID], personalDetailsExtended, null, reportActions, {
showChatPreviewLine,
});
userToInvite.isOptimisticAccount = true;
userToInvite.login = searchValue;
userToInvite.text = userToInvite.text || searchValue;
userToInvite.alternateText = userToInvite.alternateText || searchValue;
// If user doesn't exist, use a default avatar
userToInvite.icons = [
{
source: UserUtils.getAvatar('', optimisticAccountID),
name: searchValue,
type: CONST.ICON_TYPE_AVATAR,
},
];
}
// If we are prioritizing 1:1 chats in search, do it only once we started searching
if (sortByReportTypeInSearch && searchValue !== '') {
// When sortByReportTypeInSearch is true, recentReports will be returned with all the reports including personalDetailsOptions in the correct Order.
recentReportOptions.push(...personalDetailsOptions);
personalDetailsOptions = [];
recentReportOptions = lodashOrderBy(
recentReportOptions,
[
(option) => {
if (option.isChatRoom || option.isArchivedRoom) {
return 3;
}
if (!option.login) {
return 2;
}
if (option.login.toLowerCase() !== searchValue.toLowerCase()) {
return 1;
}
// When option.login is an exact match with the search value, returning 0 puts it at the top of the option list
return 0;
},
],
['asc'],
);
}
return {
personalDetails: personalDetailsOptions,
recentReports: recentReportOptions,
userToInvite,
currentUserOption,
};
}
/**
* Build the options for the Search view
*
* @param {Object} reports
* @param {Object} personalDetails
* @param {String} searchValue
* @param {Array<String>} betas
* @returns {Object}
*/
function getSearchOptions(reports, personalDetails, searchValue = '', betas) {
return getOptions(reports, personalDetails, {
betas,
searchInputValue: searchValue.trim(),
includeRecentReports: true,
includeMultipleParticipantReports: true,
maxRecentReportsToShow: 0, // Unlimited
sortByReportTypeInSearch: true,
showChatPreviewLine: true,
includePersonalDetails: true,
forcePolicyNamePreview: true,
includeOwnedWorkspaceChats: true,
includeThreads: true,
includeMoneyRequests: true,
includeTasks: true,
});
}
/**
* Build the IOUConfirmation options for showing the payee personalDetail
*
* @param {Object} personalDetail
* @param {String} amountText
* @returns {Object}
*/
function getIOUConfirmationOptionsFromPayeePersonalDetail(personalDetail, amountText) {
return {
text: personalDetail.displayName ? personalDetail.displayName : personalDetail.login,
alternateText: personalDetail.login || personalDetail.displayName,
icons: [
{
source: UserUtils.getAvatar(personalDetail.avatar, personalDetail.accountID),
name: personalDetail.login,
type: CONST.ICON_TYPE_AVATAR,
id: personalDetail.accountID,
},
],
descriptiveText: amountText,
login: personalDetail.login,
accountID: personalDetail.accountID,
};
}
/**
* Build the IOUConfirmationOptions for showing participants
*
* @param {Array} participants
* @param {String} amountText
* @returns {Array}
*/
function getIOUConfirmationOptionsFromParticipants(participants, amountText) {
return _.map(participants, (participant) => ({
...participant,
descriptiveText: amountText,
}));
}
/**
* Build the options for the New Group view
*
* @param {Object} reports
* @param {Object} personalDetails
* @param {Array<String>} [betas]
* @param {String} [searchValue]
* @param {Array} [selectedOptions]
* @param {Array} [excludeLogins]
* @param {Boolean} [includeOwnedWorkspaceChats]
* @returns {Object}
*/
function getNewChatOptions(reports, personalDetails, betas = [], searchValue = '', selectedOptions = [], excludeLogins = [], includeOwnedWorkspaceChats = false) {
return getOptions(reports, personalDetails, {
betas,
searchInputValue: searchValue.trim(),
selectedOptions,
includeRecentReports: true,
includePersonalDetails: true,
maxRecentReportsToShow: 5,
excludeLogins,
includeOwnedWorkspaceChats,
});
}
/**
* Build the options for the Share Destination for a Task
* *
* @param {Object} reports
* @param {Object} personalDetails
* @param {Array<String>} [betas]
* @param {String} [searchValue]
* @param {Array} [selectedOptions]
* @param {Array} [excludeLogins]
* @param {Boolean} [includeOwnedWorkspaceChats]
* @returns {Object}
*
*/
function getShareDestinationOptions(reports, personalDetails, betas = [], searchValue = '', selectedOptions = [], excludeLogins = [], includeOwnedWorkspaceChats = true) {
return getOptions(reports, personalDetails, {
betas,
searchInputValue: searchValue.trim(),
selectedOptions,
maxRecentReportsToShow: 5,
includeRecentReports: true,
includeMultipleParticipantReports: true,
includePersonalDetails: true,
excludeLogins,
includeOwnedWorkspaceChats,
});
}
/**
* Build the options for the Workspace Member Invite view
*
* @param {Object} personalDetails
* @param {Array<String>} betas
* @param {String} searchValue
* @param {Array} excludeLogins
* @returns {Object}
*/
function getMemberInviteOptions(personalDetails, betas = [], searchValue = '', excludeLogins = []) {
return getOptions([], personalDetails, {