-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
ReportUtils.js
892 lines (822 loc) · 30.7 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
import _ from 'underscore';
import Str from 'expensify-common/lib/str';
import lodashGet from 'lodash/get';
import Onyx from 'react-native-onyx';
import moment from 'moment';
import ExpensiMark from 'expensify-common/lib/ExpensiMark';
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 md5 from './md5';
import Navigation from './Navigation/Navigation';
import ROUTES from '../ROUTES';
import * as NumberUtils from './NumberUtils';
import * as NumberFormatUtils from './NumberFormatUtils';
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;
},
});
/**
* 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(', ');
}
/**
* Check whether a report action is Attachment or not.
* Ignore messages containing [Attachment] as the main content. Attachments are actions with only text as [Attachment].
*
* @param {Object} reportActionMessage report action's message as text and html
* @returns {Boolean}
*/
function isReportMessageAttachment({text, html}) {
return text === '[Attachment]' && html !== '[Attachment]';
}
/**
* Given a collection of reports returns them sorted by last visited
*
* @param {Object} reports
* @returns {Array}
*/
function sortReportsByLastVisited(reports) {
return _.chain(reports)
.toArray()
.filter(report => report && report.reportID)
.sortBy('lastVisitedTimestamp')
.value();
}
/**
* Can only edit if it's an ADDCOMMENT that is not an attachment,
* the author is this user and it's not an optimistic response.
* If it's an optimistic response comment it will not have a reportActionID,
* and we should wait until it does before we show the actions
*
* @param {Object} reportAction
* @returns {Boolean}
*/
function canEditReportAction(reportAction) {
return reportAction.actorEmail === sessionEmail
&& reportAction.reportActionID
&& reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT
&& !isReportMessageAttachment(lodashGet(reportAction, ['message', 0], {}))
&& reportAction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD
&& reportAction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE;
}
/**
* Can only delete if it's an ADDCOMMENT, the author is this user and it's not an optimistic response.
* If it's an optimistic response comment it will not have a reportActionID,
* and we should wait until it does before we show the actions
*
* @param {Object} reportAction
* @returns {Boolean}
*/
function canDeleteReportAction(reportAction) {
return reportAction.actorEmail === sessionEmail
&& reportAction.reportActionID
&& reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT
&& reportAction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD
&& 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 lodashGet(report, ['chatType'], '') === 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 lodashGet(report, ['chatType'], '') === 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 _.contains([
CONST.REPORT.CHAT_TYPE.POLICY_ADMINS,
CONST.REPORT.CHAT_TYPE.POLICY_ANNOUNCE,
CONST.REPORT.CHAT_TYPE.DOMAIN_ALL,
], lodashGet(report, ['chatType'], ''));
}
/**
* Whether the provided report is a Domain room
* @param {Object} report
* @param {String} report.chatType
* @returns {Boolean}
*/
function isDomainRoom(report) {
return lodashGet(report, ['chatType'], '') === 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 lodashGet(report, ['chatType'], '') === 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 lodashGet(report, ['chatType'], '') === 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);
}
/**
* Given a collection of reports returns the most recently accessed one
*
* @param {Record<String, {lastVisitedTimestamp, reportID}>|Array<{lastVisitedTimestamp, reportID}>} reports
* @param {Boolean} [ignoreDefaultRooms]
* @param {Object} policies
* @returns {Object}
*/
function findLastAccessedReport(reports, ignoreDefaultRooms, policies) {
let sortedReports = sortReportsByLastVisited(reports);
if (ignoreDefaultRooms) {
sortedReports = _.filter(sortedReports, report => !isDefaultRoom(report)
|| getPolicyType(report, policies) === CONST.POLICY.TYPE.FREE
|| hasExpensifyGuidesEmails(lodashGet(report, ['participants'], [])));
}
return _.last(sortedReports);
}
/**
* Whether the provided report is an archived room
* @param {Object} report
* @param {String} report.chatType
* @param {Number} report.stateNum
* @param {Number} report.statusNum
* @returns {Boolean}
*/
function isArchivedRoom(report) {
if (!isChatRoom(report) && !isPolicyExpenseChat(report)) {
return false;
}
return report.statusNum === CONST.REPORT.STATUS.CLOSED && 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) {
const policyName = (
policies[`${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`]
&& policies[`${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`].name
) || '';
return policyName || 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 (report.chatType === 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.begginningOfArchivedRoomPartOne');
welcomeMessage.phrase2 = Localize.translateLocal('reportActionsView.begginningOfArchivedRoomPartTwo');
} 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 hasExpensifyEmails(emails) {
return _.intersection(emails, CONST.EXPENSIFY_EMAILS).length > 0;
}
/**
* 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);
return !hasMultipleParticipants
&& !isChatRoom(report)
&& reportRecipient
&& reportRecipientTimezone
&& reportRecipientTimezone.selected;
}
/**
* Trim the last message text to a fixed limit.
* @param {String} lastMessageText
* @returns {String}
*/
function formatReportLastMessageText(lastMessageText) {
return String(lastMessageText).substring(0, CONST.REPORT.LAST_MESSAGE_TEXT_MAX_LENGTH);
}
/**
* Helper method to return a default avatar
*
* @param {String} [login]
* @returns {String}
*/
function getDefaultAvatar(login = '') {
// There are 8 possible default avatars, so we choose which one this user has based
// on a simple hash of their login (which is converted from HEX to INT)
const loginHashBucket = (parseInt(md5(login.toLowerCase()).substring(0, 4), 16) % 8) + 1;
return `${CONST.CLOUDFRONT_URL}/images/avatars/avatar_${loginHashBucket}.png`;
}
/**
* 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 (!report) {
return [defaultIcon || getDefaultAvatar()];
}
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 [
lodashGet(personalDetails, [report.ownerEmail, 'avatar']) || getDefaultAvatar(report.ownerEmail),
policyExpenseChatAvatarSource,
];
}
// Return avatar sources for Group chats
const sortedParticipants = _.map(report.participants, dmParticipant => ({
firstName: lodashGet(personalDetails, [dmParticipant, 'firstName'], ''),
avatar: lodashGet(personalDetails, [dmParticipant, 'avatar']) || getDefaultAvatar(dmParticipant),
})).sort((first, second) => first.firstName - second.firstName);
return _.map(sortedParticipants, item => item.avatar);
}
/**
* Get the displayName for a single report participant.
*
* @param {Object} participant
* @param {String} participant.displayName
* @param {String} participant.firstName
* @param {String} participant.login
* @param {Boolean} [shouldUseShortForm]
* @returns {String}
*/
function getDisplayNameForParticipant(participant, shouldUseShortForm = false) {
if (!participant) {
return '';
}
const loginWithoutSMSDomain = Str.removeSMSDomain(participant.login);
let longName = participant.displayName || loginWithoutSMSDomain;
if (Str.isSMSLogin(longName)) {
longName = LocalePhoneNumber.toLocalPhone(preferredLocale, longName);
}
const shortName = participant.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, 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 report.
*
* @param {Object} report
* @param {Object} [personalDetailsForParticipants]
* @param {Object} [policies]
* @returns {String}
*/
function getReportName(report, personalDetailsForParticipants = {}, policies = {}) {
let formattedName;
if (isChatRoom(report)) {
formattedName = report.reportName;
}
if (isPolicyExpenseChat(report)) {
const reportOwnerPersonalDetails = personalDetailsForParticipants[report.ownerEmail];
const reportOwnerDisplayName = getDisplayNameForParticipant(reportOwnerPersonalDetails) || report.ownerEmail || report.reportName;
formattedName = report.isOwnPolicyExpenseChat ? getPolicyName(report, policies) : reportOwnerDisplayName;
}
if (isArchivedRoom(report)) {
formattedName += ` (${Localize.translateLocal('common.archived')})`;
}
if (formattedName) {
return formattedName;
}
// Not a room or PolicyExpenseChat, generate title from participants
const participants = _.without(lodashGet(report, 'participants', []), sessionEmail);
const isMultipleParticipantReport = participants.length > 1;
const participantsToGetTheNamesOf = _.isEmpty(personalDetailsForParticipants) ? participants : personalDetailsForParticipants;
return _.map(participantsToGetTheNamesOf, participant => getDisplayNameForParticipant(participant, isMultipleParticipantReport)).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 {Number}
*/
function generateReportID() {
return (Math.floor(Math.random() * (2 ** 21)) * (2 ** 32)) + Math.floor(Math.random() * (2 ** 32));
}
/**
* @param {Object} report
* @returns {Boolean}
*/
function hasReportNameError(report) {
return !_.isEmpty(lodashGet(report, 'errorFields.reportName', {}));
}
/**
* @param {Number} sequenceNumber sequenceNumber must be provided and it must be a number. It cannot and should not be a clientID,
* reportActionID, or anything else besides an estimate of what the next sequenceNumber will be for the
* optimistic report action. Until we deprecate sequenceNumbers please assume that all report actions
* have them and they should be numbers.
* @param {String} [text]
* @param {File} [file]
* @returns {Object}
*/
function buildOptimisticReportAction(sequenceNumber, 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 < 10000 ? 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 ? '[Attachment]'
: 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,
sequenceNumber,
clientID: NumberUtils.generateReportActionClientID(),
avatar: lodashGet(allPersonalDetails, [currentUserEmail, 'avatar'], getDefaultAvatar(currentUserEmail)),
timestamp: moment().unix(),
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
*/
function buildOptimisticIOUReport(ownerEmail, recipientEmail, total, chatReportID, currency, locale) {
const formattedTotal = NumberFormatUtils.format(locale,
total, {
style: 'currency',
currency,
});
return {
cachedTotal: formattedTotal,
chatReportID,
currency,
hasOutstandingIOU: true,
managerEmail: recipientEmail,
ownerEmail,
reportID: generateReportID(),
state: CONST.REPORT.STATE.SUBMITTED,
stateNum: 1,
total,
};
}
/**
* Builds an optimistic IOU reportAction object
*
* @param {Number} sequenceNumber - Caller is responsible for providing a best guess at what the next sequenceNumber will be.
* @param {String} type - IOUReportAction type. Can be oneOf(create, decline, cancel, pay).
* @param {Number} amount - IOU amount in cents.
* @param {String} comment - User comment for the IOU.
* @param {String} paymentType - Only required if the IOUReportAction type is 'pay'. Can be oneOf(elsewhere, payPal, Expensify).
* @param {String} existingIOUTransactionID - Only required if the IOUReportAction type is oneOf(cancel, decline). Generates a randomID as default.
* @param {Number} existingIOUReportID - Only required if the IOUReportActions type is oneOf(decline, cancel, pay). Generates a randomID as default.
*
* @returns {Object}
*/
function buildOptimisticIOUReportAction(sequenceNumber, type, amount, comment, paymentType = '', existingIOUTransactionID = '', existingIOUReportID = 0) {
const currency = lodashGet(currentUserPersonalDetails, 'localCurrencyCode');
const IOUTransactionID = existingIOUTransactionID || NumberUtils.rand64();
const IOUReportID = existingIOUReportID || 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;
}
return {
actionName: CONST.REPORT.ACTIONS.TYPE.IOU,
actorAccountID: currentUserAccountID,
actorEmail: currentUserEmail,
automatic: false,
avatar: lodashGet(currentUserPersonalDetails, 'avatar', getDefaultAvatar(currentUserEmail)),
clientID: NumberUtils.generateReportActionClientID(),
isAttachment: false,
originalMessage,
person: [{
style: 'strong',
text: lodashGet(currentUserPersonalDetails, 'displayName', currentUserEmail),
type: 'TEXT',
}],
reportActionID: NumberUtils.rand64(),
sequenceNumber,
shouldShow: true,
timestamp: moment().unix(),
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
* @returns {Object}
*/
function buildOptimisticChatReport(
participantList,
reportName = 'Chat Report',
chatType = '',
policyID = CONST.POLICY.OWNER_EMAIL_FAKE,
ownerEmail = CONST.REPORT.OWNER_EMAIL_FAKE,
isOwnPolicyExpenseChat = false,
oldPolicyName = '',
visibility = undefined,
) {
return {
chatType,
hasOutstandingIOU: false,
isOwnPolicyExpenseChat,
isPinned: false,
lastActorEmail: '',
lastMessageHtml: '',
lastMessageText: null,
lastReadSequenceNumber: 0,
lastMessageTimestamp: 0,
lastVisitedTimestamp: 0,
maxSequenceNumber: 0,
notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.DAILY,
oldPolicyName,
ownerEmail,
participants: participantList,
policyID,
reportID: generateReportID(),
reportName,
stateNum: 0,
statusNum: 0,
visibility,
};
}
/**
* Returns the necessary reportAction onyx data to indicate that the chat has been created optimistically
* @param {String} ownerEmail
* @returns {Object}
*/
function buildOptimisticCreatedReportAction(ownerEmail) {
return {
0: {
actionName: CONST.REPORT.ACTIONS.TYPE.CREATED,
pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
actorAccountID: currentUserAccountID,
message: [
{
type: CONST.REPORT.MESSAGE.TYPE.TEXT,
style: 'strong',
text: ownerEmail === currentUserEmail ? 'You' : ownerEmail,
},
{
type: CONST.REPORT.MESSAGE.TYPE.TEXT,
style: 'normal',
text: ' created this report',
},
],
person: [
{
type: CONST.REPORT.MESSAGE.TYPE.TEXT,
style: 'strong',
text: lodashGet(allPersonalDetails, [currentUserEmail, 'displayName'], currentUserEmail),
},
],
automatic: false,
sequenceNumber: 0,
avatar: lodashGet(allPersonalDetails, [currentUserEmail, 'avatar'], getDefaultAvatar(currentUserEmail)),
timestamp: moment().unix(),
shouldShow: true,
},
};
}
/**
* @param {String} policyID
* @param {String} policyName
* @returns {Object}
*/
function buildOptimisticWorkspaceChats(policyID, policyName) {
const announceChatData = buildOptimisticChatReport(
[currentUserEmail],
CONST.REPORT.WORKSPACE_CHAT_ROOMS.ANNOUNCE,
CONST.REPORT.CHAT_TYPE.POLICY_ANNOUNCE,
policyID,
null,
false,
policyName,
);
const announceChatReportID = announceChatData.reportID;
const announceReportActionData = buildOptimisticCreatedReportAction(announceChatData.ownerEmail);
const adminsChatData = buildOptimisticChatReport([currentUserEmail], CONST.REPORT.WORKSPACE_CHAT_ROOMS.ADMINS, CONST.REPORT.CHAT_TYPE.POLICY_ADMINS, policyID, null, false, policyName);
const adminsChatReportID = adminsChatData.reportID;
const adminsReportActionData = buildOptimisticCreatedReportAction(adminsChatData.ownerEmail);
const expenseChatData = buildOptimisticChatReport([currentUserEmail], '', CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT, policyID, currentUserEmail, true, policyName);
const expenseChatReportID = expenseChatData.reportID;
const expenseReportActionData = buildOptimisticCreatedReportAction(expenseChatData.ownerEmail);
return {
announceChatReportID,
announceChatData,
announceReportActionData,
adminsChatReportID,
adminsChatData,
adminsReportActionData,
expenseChatReportID,
expenseChatData,
expenseReportActionData,
};
}
/**
* @param {Object} report
* @returns {Boolean}
*/
function isUnread(report) {
const lastReadSequenceNumber = report.lastReadSequenceNumber || 0;
const maxSequenceNumber = report.maxSequenceNumber || 0;
return lastReadSequenceNumber < maxSequenceNumber;
}
export {
getReportParticipantsTitle,
isReportMessageAttachment,
findLastAccessedReport,
canEditReportAction,
canDeleteReportAction,
sortReportsByLastVisited,
isDefaultRoom,
isAdminRoom,
isAnnounceRoom,
isUserCreatedPolicyRoom,
isChatRoom,
getChatRoomSubtitle,
getPolicyName,
getPolicyType,
isArchivedRoom,
isConciergeChatReport,
hasExpensifyEmails,
hasExpensifyGuidesEmails,
canShowReportRecipientLocalTime,
formatReportLastMessageText,
chatIncludesConcierge,
isPolicyExpenseChat,
getDefaultAvatar,
getIcons,
getRoomWelcomeMessage,
getDisplayNamesWithTooltips,
getReportName,
navigateToDetailsPage,
generateReportID,
hasReportNameError,
isUnread,
buildOptimisticWorkspaceChats,
buildOptimisticChatReport,
buildOptimisticCreatedReportAction,
buildOptimisticIOUReport,
buildOptimisticIOUReportAction,
buildOptimisticReportAction,
};