-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathReportUtils.js
555 lines (504 loc) · 18.5 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
import _ from 'underscore';
import Str from 'expensify-common/lib/str';
import lodashGet from 'lodash/get';
import Onyx from 'react-native-onyx';
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';
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;
},
});
/**
* 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], {}));
}
/**
* 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;
}
/**
* 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'], '');
}
/**
* 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);
}
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 defaultValue = report.oldPolicyName || Localize.translateLocal('workspace.common.unavailable');
return lodashGet(policies, [`${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`, 'name'], defaultValue);
}
/**
* 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
&& 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).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}`, 'avatarURL',
]) || 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 = lodashGet(personalDetailsForParticipants, report.ownerEmail);
const reportOwnerDisplayName = getDisplayNameForParticipant(reportOwnerPersonalDetails) || 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 displayNamesWithTooltips = getDisplayNamesWithTooltips(
_.isEmpty(personalDetailsForParticipants) ? participants : personalDetailsForParticipants,
participants.length > 1,
);
return _.map(displayNamesWithTooltips, ({displayName}) => displayName).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 between 98000000 (the number of reports before the switch from sequential to random)
* and the maximum safe integer of js (53 bits aka 9,007,199,254,740,991)
*
* 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() * (Number.MAX_SAFE_INTEGER - 98000000)) + 98000000;
}
export {
getReportParticipantsTitle,
isReportMessageAttachment,
findLastAccessedReport,
canEditReportAction,
canDeleteReportAction,
sortReportsByLastVisited,
isDefaultRoom,
isAdminRoom,
isAnnounceRoom,
isUserCreatedPolicyRoom,
isChatRoom,
getChatRoomSubtitle,
getPolicyName,
getPolicyType,
isArchivedRoom,
isConciergeChatReport,
hasExpensifyEmails,
canShowReportRecipientLocalTime,
formatReportLastMessageText,
chatIncludesConcierge,
isPolicyExpenseChat,
getDefaultAvatar,
getIcons,
getRoomWelcomeMessage,
getDisplayNamesWithTooltips,
getReportName,
navigateToDetailsPage,
generateReportID,
};