-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
ReportUtils.js
1580 lines (1434 loc) · 53.3 KB
/
ReportUtils.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
import _ from 'underscore';
import Str from 'expensify-common/lib/str';
import lodashGet from 'lodash/get';
import lodashIntersection from 'lodash/intersection';
import Onyx from 'react-native-onyx';
import ExpensiMark from 'expensify-common/lib/ExpensiMark';
import {InteractionManager} from 'react-native';
import ONYXKEYS from '../ONYXKEYS';
import CONST from '../CONST';
import * as Localize from './Localize';
import * as LocalePhoneNumber from './LocalePhoneNumber';
import * as Expensicons from '../components/Icon/Expensicons';
import hashCode from './hashCode';
import Navigation from './Navigation/Navigation';
import ROUTES from '../ROUTES';
import * as NumberUtils from './NumberUtils';
import * as NumberFormatUtils from './NumberFormatUtils';
import * as ReportActionsUtils from './ReportActionsUtils';
import Permissions from './Permissions';
import DateUtils from './DateUtils';
import linkingConfig from './Navigation/linkingConfig';
import * as defaultAvatars from '../components/Icon/DefaultAvatars';
import isReportMessageAttachment from './isReportMessageAttachment';
let sessionEmail;
Onyx.connect({
key: ONYXKEYS.SESSION,
callback: val => sessionEmail = val ? val.email : null,
});
let preferredLocale = CONST.DEFAULT_LOCALE;
Onyx.connect({
key: ONYXKEYS.NVP_PREFERRED_LOCALE,
callback: (val) => {
if (!val) {
return;
}
preferredLocale = val;
},
});
let currentUserEmail;
let currentUserAccountID;
Onyx.connect({
key: ONYXKEYS.SESSION,
callback: (val) => {
// When signed out, val is undefined
if (!val) {
return;
}
currentUserEmail = val.email;
currentUserAccountID = val.accountID;
},
});
let allPersonalDetails;
let currentUserPersonalDetails;
Onyx.connect({
key: ONYXKEYS.PERSONAL_DETAILS,
callback: (val) => {
currentUserPersonalDetails = lodashGet(val, currentUserEmail, {});
allPersonalDetails = val;
},
});
let allReports;
Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT,
waitForCollectionCallback: true,
callback: val => allReports = val,
});
let doesDomainHaveApprovedAccountant;
Onyx.connect({
key: ONYXKEYS.ACCOUNT,
waitForCollectionCallback: true,
callback: val => doesDomainHaveApprovedAccountant = lodashGet(val, 'doesDomainHaveApprovedAccountant', false),
});
function getChatType(report) {
return report ? report.chatType : '';
}
/**
* Returns the concatenated title for the PrimaryLogins of a report
*
* @param {Array} logins
* @returns {string}
*/
function getReportParticipantsTitle(logins) {
return _.map(logins, login => Str.removeSMSDomain(login)).join(', ');
}
/**
* Attempts to find a report in onyx with the provided list of participants
* @param {Object} report
* @returns {Boolean}
*/
function isIOUReport(report) {
return report && _.has(report, 'total');
}
/**
* Given a collection of reports returns them sorted by last read
*
* @param {Object} reports
* @returns {Array}
*/
function sortReportsByLastRead(reports) {
return _.chain(reports)
.toArray()
.filter(report => report && report.reportID && !isIOUReport(report))
.sortBy('lastReadTime')
.value();
}
/**
* Can only edit if:
*
* - It was written by the current user
* - It's an ADDCOMMENT that is not an attachment
* - It's not pending deletion
*
* @param {Object} reportAction
* @returns {Boolean}
*/
function canEditReportAction(reportAction) {
return reportAction.actorEmail === sessionEmail
&& reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT
&& !isReportMessageAttachment(lodashGet(reportAction, ['message', 0], {}))
&& reportAction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE;
}
/**
* Can only delete if it's an ADDCOMMENT, the author is this user.
*
* @param {Object} reportAction
* @returns {Boolean}
*/
function canDeleteReportAction(reportAction) {
return reportAction.actorEmail === sessionEmail
&& reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT
&& reportAction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE;
}
/**
* Whether the provided report is an Admin room
* @param {Object} report
* @param {String} report.chatType
* @returns {Boolean}
*/
function isAdminRoom(report) {
return getChatType(report) === CONST.REPORT.CHAT_TYPE.POLICY_ADMINS;
}
/**
* Whether the provided report is a Announce room
* @param {Object} report
* @param {String} report.chatType
* @returns {Boolean}
*/
function isAnnounceRoom(report) {
return getChatType(report) === CONST.REPORT.CHAT_TYPE.POLICY_ANNOUNCE;
}
/**
* Whether the provided report is a default room
* @param {Object} report
* @param {String} report.chatType
* @returns {Boolean}
*/
function isDefaultRoom(report) {
return [
CONST.REPORT.CHAT_TYPE.POLICY_ADMINS,
CONST.REPORT.CHAT_TYPE.POLICY_ANNOUNCE,
CONST.REPORT.CHAT_TYPE.DOMAIN_ALL,
].indexOf(getChatType(report)) > -1;
}
/**
* Whether the provided report is a Domain room
* @param {Object} report
* @param {String} report.chatType
* @returns {Boolean}
*/
function isDomainRoom(report) {
return getChatType(report) === CONST.REPORT.CHAT_TYPE.DOMAIN_ALL;
}
/**
* Whether the provided report is a user created policy room
* @param {Object} report
* @param {String} report.chatType
* @returns {Boolean}
*/
function isUserCreatedPolicyRoom(report) {
return getChatType(report) === CONST.REPORT.CHAT_TYPE.POLICY_ROOM;
}
/**
* Whether the provided report is a Policy Expense chat.
* @param {Object} report
* @param {String} report.chatType
* @returns {Boolean}
*/
function isPolicyExpenseChat(report) {
return getChatType(report) === CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT;
}
/**
* Whether the provided report is a chat room
* @param {Object} report
* @param {String} report.chatType
* @returns {Boolean}
*/
function isChatRoom(report) {
return isUserCreatedPolicyRoom(report) || isDefaultRoom(report);
}
/**
* Get the policy type from a given report
* @param {Object} report
* @param {String} report.policyID
* @param {Object} policies must have Onyxkey prefix (i.e 'policy_') for keys
* @returns {String}
*/
function getPolicyType(report, policies) {
return lodashGet(policies, [`${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`, 'type'], '');
}
/**
* Returns true if there are any guides accounts (team.expensify.com) in emails
* @param {Array} emails
* @returns {Boolean}
*/
function hasExpensifyGuidesEmails(emails) {
return _.some(emails, email => Str.extractEmailDomain(email) === CONST.EMAIL.GUIDES_DOMAIN);
}
/**
* @param {Record<String, {lastReadTime, reportID}>|Array<{lastReadTime, reportID}>} reports
* @param {Boolean} [ignoreDefaultRooms]
* @param {Object} policies
* @param {Boolean} openOnAdminRoom
* @returns {Object}
*/
function findLastAccessedReport(reports, ignoreDefaultRooms, policies, openOnAdminRoom = false) {
let sortedReports = sortReportsByLastRead(reports);
if (ignoreDefaultRooms) {
sortedReports = _.filter(sortedReports, report => !isDefaultRoom(report)
|| getPolicyType(report, policies) === CONST.POLICY.TYPE.FREE
|| hasExpensifyGuidesEmails(lodashGet(report, ['participants'], [])));
}
let adminReport;
if (!ignoreDefaultRooms && openOnAdminRoom) {
adminReport = _.find(sortedReports, (report) => {
const chatType = getChatType(report);
return chatType === CONST.REPORT.CHAT_TYPE.POLICY_ADMINS;
});
}
return adminReport || _.last(sortedReports);
}
/**
* Whether the provided report is an archived room
* @param {Object} report
* @param {Number} report.stateNum
* @param {Number} report.statusNum
* @returns {Boolean}
*/
function isArchivedRoom(report) {
return lodashGet(report, ['statusNum']) === CONST.REPORT.STATUS.CLOSED && lodashGet(report, ['stateNum']) === CONST.REPORT.STATE_NUM.SUBMITTED;
}
/**
* Get the policy name from a given report
* @param {Object} report
* @param {String} report.policyID
* @param {String} report.oldPolicyName
* @param {Object} policies must have Onyxkey prefix (i.e 'policy_') for keys
* @returns {String}
*/
function getPolicyName(report, policies) {
if (_.isEmpty(policies)) {
return Localize.translateLocal('workspace.common.unavailable');
}
const policy = policies[`${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`];
if (!policy) {
return report.oldPolicyName || Localize.translateLocal('workspace.common.unavailable');
}
return policy.name
|| report.oldPolicyName
|| Localize.translateLocal('workspace.common.unavailable');
}
/**
* Get either the policyName or domainName the chat is tied to
* @param {Object} report
* @param {Object} policiesMap must have onyxkey prefix (i.e 'policy_') for keys
* @returns {String}
*/
function getChatRoomSubtitle(report, policiesMap) {
if (!isDefaultRoom(report) && !isUserCreatedPolicyRoom(report) && !isPolicyExpenseChat(report)) {
return '';
}
if (getChatType(report) === CONST.REPORT.CHAT_TYPE.DOMAIN_ALL) {
// The domainAll rooms are just #domainName, so we ignore the prefix '#' to get the domainName
return report.reportName.substring(1);
}
if (isPolicyExpenseChat(report) && report.isOwnPolicyExpenseChat) {
return Localize.translateLocal('workspace.common.workspace');
}
if (isArchivedRoom(report)) {
return report.oldPolicyName || '';
}
return getPolicyName(report, policiesMap);
}
/**
* Get welcome message based on room type
* @param {Object} report
* @param {Object} policiesMap must have Onyxkey prefix (i.e 'policy_') for keys
* @returns {Object}
*/
function getRoomWelcomeMessage(report, policiesMap) {
const welcomeMessage = {};
const workspaceName = getPolicyName(report, policiesMap);
if (isArchivedRoom(report)) {
welcomeMessage.phrase1 = Localize.translateLocal('reportActionsView.beginningOfArchivedRoomPartOne');
welcomeMessage.phrase2 = Localize.translateLocal('reportActionsView.beginningOfArchivedRoomPartTwo');
} else if (isDomainRoom(report)) {
welcomeMessage.phrase1 = Localize.translateLocal('reportActionsView.beginningOfChatHistoryDomainRoomPartOne', {domainRoom: report.reportName});
welcomeMessage.phrase2 = Localize.translateLocal('reportActionsView.beginningOfChatHistoryDomainRoomPartTwo');
} else if (isAdminRoom(report)) {
welcomeMessage.phrase1 = Localize.translateLocal('reportActionsView.beginningOfChatHistoryAdminRoomPartOne', {workspaceName});
welcomeMessage.phrase2 = Localize.translateLocal('reportActionsView.beginningOfChatHistoryAdminRoomPartTwo');
} else if (isAnnounceRoom(report)) {
welcomeMessage.phrase1 = Localize.translateLocal('reportActionsView.beginningOfChatHistoryAnnounceRoomPartOne', {workspaceName});
welcomeMessage.phrase2 = Localize.translateLocal('reportActionsView.beginningOfChatHistoryAnnounceRoomPartTwo', {workspaceName});
} else {
// Message for user created rooms or other room types.
welcomeMessage.phrase1 = Localize.translateLocal('reportActionsView.beginningOfChatHistoryUserRoomPartOne');
welcomeMessage.phrase2 = Localize.translateLocal('reportActionsView.beginningOfChatHistoryUserRoomPartTwo');
}
return welcomeMessage;
}
/**
* Only returns true if this is our main 1:1 DM report with Concierge
*
* @param {Object} report
* @returns {Boolean}
*/
function isConciergeChatReport(report) {
return lodashGet(report, 'participants', []).length === 1
&& report.participants[0] === CONST.EMAIL.CONCIERGE;
}
/**
* Returns true if Concierge is one of the chat participants (1:1 as well as group chats)
* @param {Object} report
* @returns {Boolean}
*/
function chatIncludesConcierge(report) {
return report.participants
&& _.contains(report.participants, CONST.EMAIL.CONCIERGE);
}
/**
* Returns true if there is any automated expensify account in emails
* @param {Array} emails
* @returns {Boolean}
*/
function hasAutomatedExpensifyEmails(emails) {
return _.intersection(emails, CONST.EXPENSIFY_EMAILS).length > 0;
}
/**
* Returns true if there are any Expensify accounts (i.e. with domain 'expensify.com') in the set of emails.
*
* @param {Array<String>} emails
* @return {Boolean}
*/
function hasExpensifyEmails(emails) {
return _.some(emails, email => Str.extractEmailDomain(email) === CONST.EXPENSIFY_PARTNER_NAME);
}
/**
* Whether the time row should be shown for a report.
* @param {Array<Object>} personalDetails
* @param {Object} report
* @return {Boolean}
*/
function canShowReportRecipientLocalTime(personalDetails, report) {
const reportParticipants = _.without(lodashGet(report, 'participants', []), sessionEmail);
const participantsWithoutExpensifyEmails = _.difference(reportParticipants, CONST.EXPENSIFY_EMAILS);
const hasMultipleParticipants = participantsWithoutExpensifyEmails.length > 1;
const reportRecipient = personalDetails[participantsWithoutExpensifyEmails[0]];
const reportRecipientTimezone = lodashGet(reportRecipient, 'timezone', CONST.DEFAULT_TIME_ZONE);
const isReportParticipantValidated = lodashGet(reportRecipient, 'validated', false);
return !hasMultipleParticipants
&& !isChatRoom(report)
&& reportRecipient
&& reportRecipientTimezone
&& reportRecipientTimezone.selected
&& isReportParticipantValidated;
}
/**
* Trim the last message text to a fixed limit.
* @param {String} lastMessageText
* @returns {String}
*/
function formatReportLastMessageText(lastMessageText) {
return String(lastMessageText)
.replace(CONST.REGEX.AFTER_FIRST_LINE_BREAK, '')
.substring(0, CONST.REPORT.LAST_MESSAGE_TEXT_MAX_LENGTH);
}
/**
* Hashes provided string and returns a value between [1, range]
* @param {String} login
* @param {Number} range
* @returns {Number}
*/
function hashLogin(login, range) {
return (Math.abs(hashCode(login.toLowerCase())) % range) + 1;
}
/**
* Helper method to return the default avatar associated with the given login
* @param {String} [login]
* @returns {String}
*/
function getDefaultAvatar(login = '') {
if (!login) {
return Expensicons.FallbackAvatar;
}
if (login === CONST.EMAIL.CONCIERGE) {
return Expensicons.ConciergeAvatar;
}
// There are 24 possible default avatars, so we choose which one this user has based
// on a simple hash of their login
const loginHashBucket = hashLogin(login, CONST.DEFAULT_AVATAR_COUNT);
return defaultAvatars[`Avatar${loginHashBucket}`];
}
/**
* Helper method to return old dot default avatar associated with login
*
* @param {String} [login]
* @returns {String}
*/
function getOldDotDefaultAvatar(login = '') {
if (login === CONST.EMAIL.CONCIERGE) {
return CONST.CONCIERGE_ICON_URL;
}
// There are 8 possible old dot default avatars, so we choose which one this user has based
// on a simple hash of their login
const loginHashBucket = hashLogin(login, CONST.OLD_DEFAULT_AVATAR_COUNT);
return `${CONST.CLOUDFRONT_URL}/images/avatars/avatar_${loginHashBucket}.png`;
}
/**
* Given a user's avatar path, returns true if user doesn't have an avatar or if URL points to a default avatar
* @param {String} [avatarURL] - the avatar source from user's personalDetails
* @returns {Boolean}
*/
function isDefaultAvatar(avatarURL) {
if (_.isString(avatarURL) && (avatarURL.includes('images/avatars/avatar_') || avatarURL.includes('images/avatars/user/default'))) {
return true;
}
// If null URL, we should also use a default avatar
if (!avatarURL) {
return true;
}
return false;
}
/**
* Provided a source URL, if source is a default avatar, return the associated SVG.
* Otherwise, return the URL pointing to a user-uploaded avatar.
*
* @param {String} [avatarURL] - the avatar source from user's personalDetails
* @param {String} [login] - the email of the user
* @returns {String|Function}
*/
function getAvatar(avatarURL, login) {
if (isDefaultAvatar(avatarURL)) {
return getDefaultAvatar(login);
}
return avatarURL;
}
/**
* Avatars uploaded by users will have a _128 appended so that the asset server returns a small version.
* This removes that part of the URL so the full version of the image can load.
*
* @param {String} [avatarURL]
* @param {String} [login]
* @returns {String|Function}
*/
function getFullSizeAvatar(avatarURL, login) {
const source = getAvatar(avatarURL, login);
if (!_.isString(source)) {
return source;
}
return source.replace('_128', '');
}
/**
* Returns the appropriate icons for the given chat report using the stored personalDetails.
* The Avatar sources can be URLs or Icon components according to the chat type.
*
* @param {Object} report
* @param {Object} personalDetails
* @param {Object} policies
* @param {*} [defaultIcon]
* @returns {Array<*>}
*/
function getIcons(report, personalDetails, policies, defaultIcon = null) {
if (_.isEmpty(report)) {
return [defaultIcon || Expensicons.FallbackAvatar];
}
if (isConciergeChatReport(report)) {
return [CONST.CONCIERGE_ICON_URL];
}
if (isArchivedRoom(report)) {
return [Expensicons.DeletedRoomAvatar];
}
if (isDomainRoom(report)) {
return [Expensicons.DomainRoomAvatar];
}
if (isAdminRoom(report)) {
return [Expensicons.AdminRoomAvatar];
}
if (isAnnounceRoom(report)) {
return [Expensicons.AnnounceRoomAvatar];
}
if (isChatRoom(report)) {
return [Expensicons.ActiveRoomAvatar];
}
if (isPolicyExpenseChat(report)) {
const policyExpenseChatAvatarSource = lodashGet(policies, [
`${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`, 'avatar',
]) || Expensicons.Workspace;
// Return the workspace avatar if the user is the owner of the policy expense chat
if (report.isOwnPolicyExpenseChat) {
return [policyExpenseChatAvatarSource];
}
// If the user is an admin, return avatar source of the other participant of the report
// (their workspace chat) and the avatar source of the workspace
return [
getAvatar(lodashGet(personalDetails, [report.ownerEmail, 'avatar']), report.ownerEmail),
policyExpenseChatAvatarSource,
];
}
const participantDetails = [];
const participants = report.participants || [];
for (let i = 0; i < participants.length; i++) {
const login = participants[i];
const avatarSource = getAvatar(lodashGet(personalDetails, [login, 'avatar'], ''), login);
participantDetails.push([
login,
lodashGet(personalDetails, [login, 'firstName'], ''),
avatarSource,
]);
}
// Sort all logins by first name (which is the second element in the array)
const sortedParticipantDetails = participantDetails.sort((a, b) => a[1] - b[1]);
// Now that things are sorted, gather only the avatars (third element in the array) and return those
const avatars = [];
for (let i = 0; i < sortedParticipantDetails.length; i++) {
avatars.push(sortedParticipantDetails[i][2]);
}
return avatars;
}
/**
* Gets the personal details for a login by looking in the ONYXKEYS.PERSONAL_DETAILS Onyx key (stored in the local variable, allPersonalDetails). If it doesn't exist in Onyx,
* then a default object is constructed.
* @param {String} login
* @returns {Object}
*/
function getPersonalDetailsForLogin(login) {
if (!login) {
return {};
}
return (allPersonalDetails && allPersonalDetails[login]) || {
login,
displayName: Str.removeSMSDomain(login),
avatar: getDefaultAvatar(login),
};
}
/**
* Get the displayName for a single report participant.
*
* @param {String} login
* @param {Boolean} [shouldUseShortForm]
* @returns {String}
*/
function getDisplayNameForParticipant(login, shouldUseShortForm = false) {
if (!login) {
return '';
}
const personalDetails = getPersonalDetailsForLogin(login);
const loginWithoutSMSDomain = Str.removeSMSDomain(personalDetails.login);
let longName = personalDetails.displayName || loginWithoutSMSDomain;
if (longName === loginWithoutSMSDomain && Str.isSMSLogin(longName)) {
longName = LocalePhoneNumber.toLocalPhone(preferredLocale, longName);
}
const shortName = personalDetails.firstName || longName;
return shouldUseShortForm ? shortName : longName;
}
/**
* @param {Object} participants
* @param {Boolean} isMultipleParticipantReport
* @returns {Array}
*/
function getDisplayNamesWithTooltips(participants, isMultipleParticipantReport) {
return _.map(participants, (participant) => {
const displayName = getDisplayNameForParticipant(participant.login, isMultipleParticipantReport);
const tooltip = Str.removeSMSDomain(participant.login);
let pronouns = participant.pronouns;
if (pronouns && pronouns.startsWith(CONST.PRONOUNS.PREFIX)) {
const pronounTranslationKey = pronouns.replace(CONST.PRONOUNS.PREFIX, '');
pronouns = Localize.translateLocal(`pronouns.${pronounTranslationKey}`);
}
return {
displayName,
tooltip,
pronouns,
};
});
}
/**
* Get the title for a policy expense chat which depends on the role of the policy member seeing this report
*
* @param {Object} report
* @param {Object} [policies]
* @returns {String}
*/
function getPolicyExpenseChatName(report, policies = {}) {
const reportOwnerDisplayName = getDisplayNameForParticipant(report.ownerEmail) || report.ownerEmail || report.reportName;
// If the policy expense chat is owned by this user, use the name of the policy as the report name.
if (report.isOwnPolicyExpenseChat) {
return getPolicyName(report, policies);
}
const policyExpenseChatRole = lodashGet(policies, [
`${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`, 'role',
]) || 'user';
// If this user is not admin and this policy expense chat has been archived because of account merging, this must be an old workspace chat
// of the account which was merged into the current user's account. Use the name of the policy as the name of the report.
if (isArchivedRoom(report)) {
const lastAction = ReportActionsUtils.getLastVisibleAction(report.reportID);
const archiveReason = (lastAction && lastAction.originalMessage && lastAction.originalMessage.reason) || CONST.REPORT.ARCHIVE_REASON.DEFAULT;
if (archiveReason === CONST.REPORT.ARCHIVE_REASON.ACCOUNT_MERGED && policyExpenseChatRole !== CONST.POLICY.ROLE.ADMIN) {
return getPolicyName(report, policies);
}
}
// If user can see this report and they are not its owner, they must be an admin and the report name should be the name of the policy member
return reportOwnerDisplayName;
}
/**
* Get the title for a report.
*
* @param {Object} report
* @param {Object} [policies]
* @returns {String}
*/
function getReportName(report, policies = {}) {
let formattedName;
if (isChatRoom(report)) {
formattedName = report.reportName;
}
if (isPolicyExpenseChat(report)) {
formattedName = getPolicyExpenseChatName(report, policies);
}
if (isArchivedRoom(report)) {
formattedName += ` (${Localize.translateLocal('common.archived')})`;
}
if (formattedName) {
return formattedName;
}
// Not a room or PolicyExpenseChat, generate title from participants
const participants = (report && report.participants) || [];
const participantsWithoutCurrentUser = _.without(participants, sessionEmail);
const isMultipleParticipantReport = participantsWithoutCurrentUser.length > 1;
const displayNames = [];
for (let i = 0; i < participantsWithoutCurrentUser.length; i++) {
const login = participantsWithoutCurrentUser[i];
displayNames.push(getDisplayNameForParticipant(login, isMultipleParticipantReport));
}
return displayNames.join(', ');
}
/**
* Navigate to the details page of a given report
*
* @param {Object} report
*/
function navigateToDetailsPage(report) {
const participants = lodashGet(report, 'participants', []);
if (isChatRoom(report) || isPolicyExpenseChat(report)) {
Navigation.navigate(ROUTES.getReportDetailsRoute(report.reportID));
return;
}
if (participants.length === 1) {
Navigation.navigate(ROUTES.getDetailsRoute(participants[0]));
return;
}
Navigation.navigate(ROUTES.getReportParticipantsRoute(report.reportID));
}
/**
* Generate a random reportID up to 53 bits aka 9,007,199,254,740,991 (Number.MAX_SAFE_INTEGER).
* There were approximately 98,000,000 reports with sequential IDs generated before we started using this approach, those make up roughly one billionth of the space for these numbers,
* so we live with the 1 in a billion chance of a collision with an older ID until we can switch to 64-bit IDs.
*
* In a test of 500M reports (28 years of reports at our current max rate) we got 20-40 collisions meaning that
* this is more than random enough for our needs.
*
* @returns {String}
*/
function generateReportID() {
return ((Math.floor(Math.random() * (2 ** 21)) * (2 ** 32)) + Math.floor(Math.random() * (2 ** 32))).toString();
}
/**
* @param {Object} report
* @returns {Boolean}
*/
function hasReportNameError(report) {
return !_.isEmpty(lodashGet(report, 'errorFields.reportName', {}));
}
/**
* @param {String} [text]
* @param {File} [file]
* @returns {Object}
*/
function buildOptimisticAddCommentReportAction(text, file) {
// For comments shorter than 10k chars, convert the comment from MD into HTML because that's how it is stored in the database
// For longer comments, skip parsing and display plaintext for performance reasons. It takes over 40s to parse a 100k long string!!
const parser = new ExpensiMark();
const commentText = text.length < CONST.MAX_MARKUP_LENGTH ? parser.replace(text) : text;
const isAttachment = _.isEmpty(text) && file !== undefined;
const attachmentInfo = isAttachment ? file : {};
const htmlForNewComment = isAttachment ? 'Uploading Attachment...' : commentText;
// Remove HTML from text when applying optimistic offline comment
const textForNewComment = isAttachment ? CONST.ATTACHMENT_MESSAGE_TEXT
: parser.htmlToText(htmlForNewComment);
return {
commentText,
reportAction: {
reportActionID: NumberUtils.rand64(),
actionName: CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT,
actorEmail: currentUserEmail,
actorAccountID: currentUserAccountID,
person: [
{
style: 'strong',
text: lodashGet(allPersonalDetails, [currentUserEmail, 'displayName'], currentUserEmail),
type: 'TEXT',
},
],
automatic: false,
avatar: lodashGet(allPersonalDetails, [currentUserEmail, 'avatar'], getDefaultAvatar(currentUserEmail)),
created: DateUtils.getDBTime(),
message: [
{
type: CONST.REPORT.MESSAGE.TYPE.COMMENT,
html: htmlForNewComment,
text: textForNewComment,
},
],
isFirstItem: false,
isAttachment,
attachmentInfo,
pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
shouldShow: true,
},
};
}
/**
* Builds an optimistic IOU report with a randomly generated reportID
*
* @param {String} ownerEmail - Email of the person generating the IOU.
* @param {String} userEmail - Email of the other person participating in the IOU.
* @param {Number} total - IOU amount in cents.
* @param {String} chatReportID - Report ID of the chat where the IOU is.
* @param {String} currency - IOU currency.
* @param {String} locale - Locale where the IOU is created
* @param {Boolean} isSendingMoney - If we send money the IOU should be created as settled
*
* @returns {Object}
*/
function buildOptimisticIOUReport(ownerEmail, userEmail, total, chatReportID, currency, locale, isSendingMoney = false) {
const formattedTotal = NumberFormatUtils.format(locale,
total, {
style: 'currency',
currency,
});
return {
// If we're sending money, hasOutstandingIOU should be false
hasOutstandingIOU: !isSendingMoney,
cachedTotal: formattedTotal,
chatReportID,
currency,
managerEmail: userEmail,
ownerEmail,
reportID: generateReportID(),
state: CONST.REPORT.STATE.SUBMITTED,
stateNum: isSendingMoney
? CONST.REPORT.STATE_NUM.SUBMITTED
: CONST.REPORT.STATE_NUM.PROCESSING,
total,
};
}
/**
* @param {String} type - IOUReportAction type. Can be oneOf(create, decline, cancel, pay, split)
* @param {Number} total - IOU total in cents
* @param {Array} participants - List of logins for the IOU participants, excluding the current user login
* @param {String} comment - IOU comment
* @param {String} currency - IOU currency
* @param {String} paymentType - IOU paymentMethodType. Can be oneOf(Elsewhere, Expensify, PayPal.me)
* @param {Boolean} isSettlingUp - Whether we are settling up an IOU
* @returns {Array}
*/
function getIOUReportActionMessage(type, total, participants, comment, currency, paymentType = '', isSettlingUp = false) {
const amount = NumberFormatUtils.format(preferredLocale, total / 100, {style: 'currency', currency});
const displayNames = _.map(participants, participant => getDisplayNameForParticipant(participant.login, true));
const who = displayNames.length < 3
? displayNames.join(' and ')
: `${displayNames.slice(0, -1).join(', ')}, and ${_.last(displayNames)}`;
let paymentMethodMessage;
switch (paymentType) {
case CONST.IOU.PAYMENT_TYPE.EXPENSIFY:
paymentMethodMessage = '!';
break;
case CONST.IOU.PAYMENT_TYPE.ELSEWHERE:
paymentMethodMessage = ' elsewhere';
break;
case CONST.IOU.PAYMENT_TYPE.PAYPAL_ME:
paymentMethodMessage = ' using PayPal.me';
break;
default:
break;
}
let iouMessage;
switch (type) {
case CONST.IOU.REPORT_ACTION_TYPE.CREATE:
iouMessage = `Requested ${amount} from ${who}${comment && ` for ${comment}`}`;
break;
case CONST.IOU.REPORT_ACTION_TYPE.SPLIT:
iouMessage = `Split ${amount} with ${who}${comment && ` for ${comment}`}`;
break;
case CONST.IOU.REPORT_ACTION_TYPE.CANCEL:
iouMessage = `Cancelled the ${amount} request${comment && ` for ${comment}`}`;
break;
case CONST.IOU.REPORT_ACTION_TYPE.DECLINE:
iouMessage = `Declined the ${amount} request${comment && ` for ${comment}`}`;
break;
case CONST.IOU.REPORT_ACTION_TYPE.PAY:
iouMessage = isSettlingUp
? `Settled up${paymentMethodMessage}`
: `Sent ${amount}${comment && ` for ${comment}`}${paymentMethodMessage}`;
break;
default:
break;
}
return [{
html: iouMessage,
text: iouMessage,
isEdited: false,
type: CONST.REPORT.MESSAGE.TYPE.COMMENT,
}];
}
/**
* Builds an optimistic IOU reportAction object
*
* @param {String} type - IOUReportAction type. Can be oneOf(create, decline, cancel, pay, split).
* @param {Number} amount - IOU amount in cents.
* @param {String} currency
* @param {String} comment - User comment for the IOU.
* @param {Array} participants - An array with participants details.
* @param {String} [paymentType] - Only required if the IOUReportAction type is 'pay'. Can be oneOf(elsewhere, payPal, Expensify).
* @param {String} [iouTransactionID] - Only required if the IOUReportAction type is oneOf(cancel, decline). Generates a randomID as default.
* @param {String} [iouReportID] - Only required if the IOUReportActions type is oneOf(decline, cancel, pay). Generates a randomID as default.
* @param {Boolean} [isSettlingUp] - Whether we are settling up an IOU.
*
* @returns {Object}
*/
function buildOptimisticIOUReportAction(type, amount, currency, comment, participants, paymentType = '', iouTransactionID = '', iouReportID = '', isSettlingUp = false) {
const IOUTransactionID = iouTransactionID || NumberUtils.rand64();
const IOUReportID = iouReportID || generateReportID();
const originalMessage = {
amount,
comment,
currency,
IOUTransactionID,
IOUReportID,
type,
};
// We store amount, comment, currency in IOUDetails when type = pay
if (type === CONST.IOU.REPORT_ACTION_TYPE.PAY) {
_.each(['amount', 'comment', 'currency'], (key) => {
delete originalMessage[key];
});
originalMessage.IOUDetails = {amount, comment, currency};
originalMessage.paymentType = paymentType;
}
// IOUs of type split only exist in group DMs and those don't have an iouReport so we need to delete the IOUReportID key
if (type === CONST.IOU.REPORT_ACTION_TYPE.SPLIT) {
delete originalMessage.IOUReportID;
}
return {
actionName: CONST.REPORT.ACTIONS.TYPE.IOU,
actorAccountID: currentUserAccountID,
actorEmail: currentUserEmail,
automatic: false,
avatar: lodashGet(currentUserPersonalDetails, 'avatar', getDefaultAvatar(currentUserEmail)),
isAttachment: false,
originalMessage,
message: getIOUReportActionMessage(type, amount, participants, comment, currency, paymentType, isSettlingUp),
person: [{
style: 'strong',
text: lodashGet(currentUserPersonalDetails, 'displayName', currentUserEmail),
type: 'TEXT',
}],
reportActionID: NumberUtils.rand64(),
shouldShow: true,
created: DateUtils.getDBTime(),
pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
};
}
/**
* Builds an optimistic chat report with a randomly generated reportID and as much information as we currently have
*
* @param {Array} participantList
* @param {String} reportName
* @param {String} chatType
* @param {String} policyID
* @param {String} ownerEmail
* @param {Boolean} isOwnPolicyExpenseChat
* @param {String} oldPolicyName
* @param {String} visibility