-
Notifications
You must be signed in to change notification settings - Fork 3k
/
ReportUtils.js
4088 lines (3713 loc) · 152 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
/* eslint-disable rulesdir/prefer-underscore-method */
import _ from 'underscore';
import {format, parseISO} from 'date-fns';
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 ONYXKEYS from '../ONYXKEYS';
import CONST from '../CONST';
import * as Localize from './Localize';
import * as Expensicons from '../components/Icon/Expensicons';
import Navigation from './Navigation/Navigation';
import ROUTES from '../ROUTES';
import * as NumberUtils from './NumberUtils';
import * as ReportActionsUtils from './ReportActionsUtils';
import * as TransactionUtils from './TransactionUtils';
import * as Url from './Url';
import Permissions from './Permissions';
import DateUtils from './DateUtils';
import linkingConfig from './Navigation/linkingConfig';
import isReportMessageAttachment from './isReportMessageAttachment';
import * as defaultWorkspaceAvatars from '../components/Icon/WorkspaceDefaultAvatars';
import * as CurrencyUtils from './CurrencyUtils';
import * as UserUtils from './UserUtils';
let currentUserEmail;
let currentUserAccountID;
let isAnonymousUser;
Onyx.connect({
key: ONYXKEYS.SESSION,
callback: (val) => {
// When signed out, val is undefined
if (!val) {
return;
}
currentUserEmail = val.email;
currentUserAccountID = val.accountID;
isAnonymousUser = val.authTokenType === 'anonymousAccount';
},
});
let allPersonalDetails;
let currentUserPersonalDetails;
Onyx.connect({
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
callback: (val) => {
currentUserPersonalDetails = lodashGet(val, currentUserAccountID, {});
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)),
});
let allPolicies;
Onyx.connect({
key: ONYXKEYS.COLLECTION.POLICY,
waitForCollectionCallback: true,
callback: (val) => (allPolicies = val),
});
let loginList;
Onyx.connect({
key: ONYXKEYS.LOGIN_LIST,
callback: (val) => (loginList = val),
});
function getChatType(report) {
return report ? report.chatType : '';
}
/**
* @param {String} policyID
* @returns {Object}
*/
function getPolicy(policyID) {
if (!allPolicies || !policyID) {
return {};
}
return allPolicies[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`] || {};
}
/**
* 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'], '');
}
/**
* Get the policy name from a given report
* @param {Object} report
* @param {String} report.policyID
* @param {String} report.oldPolicyName
* @param {String} report.policyName
* @param {Boolean} [returnEmptyIfNotFound]
* @param {Object} [policy]
* @returns {String}
*/
function getPolicyName(report, returnEmptyIfNotFound = false, policy = undefined) {
const noPolicyFound = returnEmptyIfNotFound ? '' : Localize.translateLocal('workspace.common.unavailable');
if (_.isEmpty(report)) {
return noPolicyFound;
}
if ((!allPolicies || _.size(allPolicies) === 0) && !report.policyName) {
return Localize.translateLocal('workspace.common.unavailable');
}
const finalPolicy = policy || _.get(allPolicies, `${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`);
// Public rooms send back the policy name with the reportSummary,
// since they can also be accessed by people who aren't in the workspace
const policyName = lodashGet(finalPolicy, 'name') || report.policyName || report.oldPolicyName || noPolicyFound;
return policyName;
}
/**
* Returns the concatenated title for the PrimaryLogins of a report
*
* @param {Array} accountIDs
* @returns {string}
*/
function getReportParticipantsTitle(accountIDs) {
return (
_.chain(accountIDs)
// Somehow it's possible for the logins coming from report.participantAccountIDs to contain undefined values so we use compact to remove them.
.compact()
.value()
.join(', ')
);
}
/**
* Checks if a report is a chat report.
*
* @param {Object} report
* @returns {Boolean}
*/
function isChatReport(report) {
return report && report.type === CONST.REPORT.TYPE.CHAT;
}
/**
* Checks if a report is an Expense report.
*
* @param {Object} report
* @returns {Boolean}
*/
function isExpenseReport(report) {
return report && report.type === CONST.REPORT.TYPE.EXPENSE;
}
/**
* Checks if a report is an IOU report.
*
* @param {Object} report
* @returns {Boolean}
*/
function isIOUReport(report) {
return report && report.type === CONST.REPORT.TYPE.IOU;
}
/**
* Checks if a report is a task report.
*
* @param {Object} report
* @returns {Boolean}
*/
function isTaskReport(report) {
return report && report.type === CONST.REPORT.TYPE.TASK;
}
/**
* Checks if a task has been cancelled
* When a task is deleted, the parentReportAction is updated to have a isDeletedParentAction deleted flag
* This is because when you delete a task, we still allow you to chat on the report itself
* There's another situation where you don't have access to the parentReportAction (because it was created in a chat you don't have access to)
* In this case, we have added the key to the report itself
*
* @param {Object} report
* @param {Object} parentReportAction
* @returns {Boolean}
*/
function isCanceledTaskReport(report = {}, parentReportAction = {}) {
if (!_.isEmpty(parentReportAction) && lodashGet(parentReportAction, ['message', 0, 'isDeletedParentAction'], false)) {
return true;
}
if (!_.isEmpty(report) && report.isDeletedParentAction) {
return true;
}
return false;
}
/**
* Checks if a report is an open task report.
*
* @param {Object} report
* @param {Object} parentReportAction - The parent report action of the report (Used to check if the task has been canceled)
* @returns {Boolean}
*/
function isOpenTaskReport(report, parentReportAction = {}) {
return isTaskReport(report) && !isCanceledTaskReport(report, parentReportAction) && report.stateNum === CONST.REPORT.STATE_NUM.OPEN && report.statusNum === CONST.REPORT.STATUS.OPEN;
}
/**
* Checks if a report is a completed task report.
*
* @param {Object} report
* @returns {Boolean}
*/
function isCompletedTaskReport(report) {
return isTaskReport(report) && report.stateNum === CONST.REPORT.STATE_NUM.SUBMITTED && report.statusNum === CONST.REPORT.STATUS.APPROVED;
}
/**
* Checks if the current user is the manager of the supplied report
*
* @param {Object} report
* @returns {Boolean}
*/
function isReportManager(report) {
return report && report.managerID === currentUserAccountID;
}
/**
* Checks if the supplied report has been approved
*
* @param {Object} report
* @returns {Boolean}
*/
function isReportApproved(report) {
return report && report.stateNum === CONST.REPORT.STATE_NUM.SUBMITTED && report.statusNum === CONST.REPORT.STATUS.APPROVED;
}
/**
* 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 && report.lastReadTime)
.sortBy('lastReadTime')
.value();
}
/**
* Whether the Money Request report is settled
*
* @param {String} reportID
* @returns {Boolean}
*/
function isSettled(reportID) {
if (!allReports) {
return false;
}
const report = allReports[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`] || {};
if ((typeof report === 'object' && Object.keys(report).length === 0) || report.isWaitingOnBankAccount) {
return false;
}
return report.statusNum === CONST.REPORT.STATUS.REIMBURSED;
}
/**
* Whether the current user is the submitter of the report
*
* @param {String} reportID
* @returns {Boolean}
*/
function isCurrentUserSubmitter(reportID) {
if (!allReports) {
return false;
}
const report = allReports[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`] || {};
return report && report.ownerEmail === currentUserEmail;
}
/**
* 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 an Admin-only posting room
* @param {Object} report
* @param {String} report.writeCapability
* @returns {Boolean}
*/
function isAdminsOnlyPostingRoom(report) {
return lodashGet(report, 'writeCapability', CONST.REPORT.WRITE_CAPABILITIES.ALL) === CONST.REPORT.WRITE_CAPABILITIES.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;
}
/** Wether the provided report belongs to a Control policy and is an epxense chat
* @param {Object} report
* @returns {Boolean}
*/
function isControlPolicyExpenseChat(report) {
return isPolicyExpenseChat(report) && getPolicyType(report, allPolicies) === CONST.POLICY.TYPE.CORPORATE;
}
/** Wether the provided report belongs to a Control policy and is an epxense report
* @param {Object} report
* @returns {Boolean}
*/
function isControlPolicyExpenseReport(report) {
return isExpenseReport(report) && getPolicyType(report, allPolicies) === CONST.POLICY.TYPE.CORPORATE;
}
/**
* 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);
}
/**
* Whether the provided report is a public room
* @param {Object} report
* @param {String} report.visibility
* @returns {Boolean}
*/
function isPublicRoom(report) {
return report && (report.visibility === CONST.REPORT.VISIBILITY.PUBLIC || report.visibility === CONST.REPORT.VISIBILITY.PUBLIC_ANNOUNCE);
}
/**
* Whether the provided report is a public announce room
* @param {Object} report
* @param {String} report.visibility
* @returns {Boolean}
*/
function isPublicAnnounceRoom(report) {
return report && report.visibility === CONST.REPORT.VISIBILITY.PUBLIC_ANNOUNCE;
}
/**
* If the report is a policy expense, the route should be for adding bank account for that policy
* else since the report is a personal IOU, the route should be for personal bank account.
* @param {Object} report
* @returns {String}
*/
function getBankAccountRoute(report) {
return isPolicyExpenseChat(report) ? ROUTES.BANK_ACCOUNT_WITH_STEP_TO_OPEN.getRoute('', report.policyID) : ROUTES.SETTINGS_ADD_BANK_ACCOUNT;
}
/**
* Check if personal detail of accountID is empty or optimistic data
* @param {String} accountID user accountID
* @returns {Boolean}
*/
function isOptimisticPersonalDetail(accountID) {
return _.isEmpty(allPersonalDetails[accountID]) || !!allPersonalDetails[accountID].isOptimisticPersonalDetail;
}
/**
* Checks if a report is a task report from a policy expense chat.
*
* @param {Object} report
* @returns {Boolean}
*/
function isWorkspaceTaskReport(report) {
if (!isTaskReport(report)) {
return false;
}
const parentReport = allReports[`${ONYXKEYS.COLLECTION.REPORT}${report.parentReportID}`];
return isPolicyExpenseChat(parentReport);
}
/**
* Returns true if report has a parent
*
* @param {Object} report
* @returns {Boolean}
*/
function isThread(report) {
return Boolean(report && report.parentReportID && report.parentReportActionID);
}
/**
* Returns true if report is of type chat and has a parent and is therefore a Thread.
*
* @param {Object} report
* @returns {Boolean}
*/
function isChatThread(report) {
return isThread(report) && report.type === CONST.REPORT.TYPE.CHAT;
}
/**
* 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, 'participantAccountIDs', []).length === 1 && Number(report.participantAccountIDs[0]) === CONST.ACCOUNT_ID.CONCIERGE && !isChatThread(report);
}
/**
* Check if the report is a single chat report that isn't a thread
* and personal detail of participant is optimistic data
* @param {Object} report
* @param {Array} report.participantAccountIDs
* @returns {Boolean}
*/
function shouldDisableDetailPage(report) {
const participantAccountIDs = lodashGet(report, 'participantAccountIDs', []);
if (isChatRoom(report) || isPolicyExpenseChat(report) || isChatThread(report) || isTaskReport(report)) {
return false;
}
if (participantAccountIDs.length === 1) {
return isOptimisticPersonalDetail(participantAccountIDs[0]);
}
return false;
}
/**
* Returns true if this report has only one participant and it's an Expensify account.
* @param {Object} report
* @returns {Boolean}
*/
function isExpensifyOnlyParticipantInReport(report) {
const reportParticipants = _.without(lodashGet(report, 'participantAccountIDs', []), currentUserAccountID);
return reportParticipants.length === 1 && _.some(reportParticipants, (accountID) => _.contains(CONST.EXPENSIFY_ACCOUNT_IDS, accountID));
}
/**
* Returns true if there are any Expensify accounts (i.e. with domain 'expensify.com') in the set of accountIDs
* by cross-referencing the accountIDs with personalDetails.
*
* @param {Array<Number>} accountIDs
* @return {Boolean}
*/
function hasExpensifyEmails(accountIDs) {
return _.some(accountIDs, (accountID) => Str.extractEmailDomain(lodashGet(allPersonalDetails, [accountID, 'login'], '')) === CONST.EXPENSIFY_PARTNER_NAME);
}
/**
* Returns true if there are any guides accounts (team.expensify.com) in a list of accountIDs
* by cross-referencing the accountIDs with personalDetails since guides that are participants
* of the user's chats should have their personal details in Onyx.
* @param {Array<Number>} accountIDs
* @returns {Boolean}
*/
function hasExpensifyGuidesEmails(accountIDs) {
return _.some(accountIDs, (accountID) => Str.extractEmailDomain(lodashGet(allPersonalDetails, [accountID, 'login'], '')) === CONST.EMAIL.GUIDES_DOMAIN);
}
/**
* @param {Record<String, {lastReadTime, reportID}>|Array<{lastReadTime, reportID}>} reports
* @param {Boolean} [ignoreDomainRooms]
* @param {Object} policies
* @param {Boolean} isFirstTimeNewExpensifyUser
* @param {Boolean} openOnAdminRoom
* @returns {Object}
*/
function findLastAccessedReport(reports, ignoreDomainRooms, policies, isFirstTimeNewExpensifyUser, openOnAdminRoom = false) {
// If it's the user's first time using New Expensify, then they could either have:
// - just a Concierge report, if so we'll return that
// - their Concierge report, and a separate report that must have deeplinked them to the app before they created their account.
// If it's the latter, we'll use the deeplinked report over the Concierge report,
// since the Concierge report would be incorrectly selected over the deep-linked report in the logic below.
let sortedReports = sortReportsByLastRead(reports);
let adminReport;
if (openOnAdminRoom) {
adminReport = _.find(sortedReports, (report) => {
const chatType = getChatType(report);
return chatType === CONST.REPORT.CHAT_TYPE.POLICY_ADMINS;
});
}
if (isFirstTimeNewExpensifyUser) {
if (sortedReports.length === 1) {
return sortedReports[0];
}
return adminReport || _.find(sortedReports, (report) => !isConciergeChatReport(report));
}
if (ignoreDomainRooms) {
// We allow public announce rooms, admins, and announce rooms through since we bypass the default rooms beta for them.
// Check where ReportUtils.findLastAccessedReport is called in MainDrawerNavigator.js for more context.
// Domain rooms are now the only type of default room that are on the defaultRooms beta.
sortedReports = _.filter(
sortedReports,
(report) => !isDomainRoom(report) || getPolicyType(report, policies) === CONST.POLICY.TYPE.FREE || hasExpensifyGuidesEmails(lodashGet(report, ['participantAccountIDs'], [])),
);
}
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 report && report.statusNum === CONST.REPORT.STATUS.CLOSED && report.stateNum === CONST.REPORT.STATE_NUM.SUBMITTED;
}
/**
* Checks if the current user is allowed to comment on the given report.
* @param {Object} report
* @param {String} [report.writeCapability]
* @returns {Boolean}
*/
function isAllowedToComment(report) {
// Default to allowing all users to post
const capability = lodashGet(report, 'writeCapability', CONST.REPORT.WRITE_CAPABILITIES.ALL) || CONST.REPORT.WRITE_CAPABILITIES.ALL;
if (capability === CONST.REPORT.WRITE_CAPABILITIES.ALL) {
return true;
}
// If unauthenticated user opens public chat room using deeplink, they do not have policies available and they cannot comment
if (!allPolicies) {
return false;
}
// If we've made it here, commenting on this report is restricted.
// If the user is an admin, allow them to post.
const policy = allPolicies[`${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`];
return lodashGet(policy, 'role', '') === CONST.POLICY.ROLE.ADMIN;
}
/**
* Checks if the current user is the admin of the policy given the policy expense chat.
* @param {Object} report
* @param {String} report.policyID
* @param {Object} policies must have OnyxKey prefix (i.e 'policy_') for keys
* @returns {Boolean}
*/
function isPolicyExpenseChatAdmin(report, policies) {
if (!isPolicyExpenseChat(report)) {
return false;
}
const policyRole = lodashGet(policies, [`${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`, 'role']);
return policyRole === CONST.POLICY.ROLE.ADMIN;
}
/**
* Checks if the current user is the admin of the policy.
* @param {String} policyID
* @param {Object} policies must have OnyxKey prefix (i.e 'policy_') for keys
* @returns {Boolean}
*/
function isPolicyAdmin(policyID, policies) {
const policyRole = lodashGet(policies, [`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, 'role']);
return policyRole === CONST.POLICY.ROLE.ADMIN;
}
/**
* Returns true if report is a DM/Group DM chat.
*
* @param {Object} report
* @returns {Boolean}
*/
function isDM(report) {
return !getChatType(report);
}
/**
* Returns true if report has a single participant.
*
* @param {Object} report
* @returns {Boolean}
*/
function hasSingleParticipant(report) {
return report && report.participantAccountIDs && report.participantAccountIDs.length === 1;
}
/**
* If the report is a thread and has a chat type set, it is a workspace chat.
*
* @param {Object} report
* @returns {Boolean}
*/
function isWorkspaceThread(report) {
return Boolean(isThread(report) && !isDM(report));
}
/**
* Returns true if reportAction has a child.
*
* @param {Object} reportAction
* @returns {Boolean}
*/
function isThreadParent(reportAction) {
return reportAction && reportAction.childReportID && reportAction.childReportID !== 0;
}
/**
* Returns true if reportAction is the first chat preview of a Thread
*
* @param {Object} reportAction
* @param {String} reportID
* @returns {Boolean}
*/
function isThreadFirstChat(reportAction, reportID) {
return !_.isUndefined(reportAction.childReportID) && reportAction.childReportID.toString() === reportID;
}
/**
* Checks if a report is a child report.
*
* @param {Object} report
* @returns {Boolean}
*/
function isChildReport(report) {
return isThread(report) || isTaskReport(report);
}
/**
* An Expense Request is a thread where the parent report is an Expense Report and
* the parentReportAction is a transaction.
*
* @param {Object} report
* @returns {Boolean}
*/
function isExpenseRequest(report) {
if (isThread(report)) {
const parentReportAction = ReportActionsUtils.getParentReportAction(report);
const parentReport = lodashGet(allReports, [`${ONYXKEYS.COLLECTION.REPORT}${report.parentReportID}`]);
return isExpenseReport(parentReport) && ReportActionsUtils.isTransactionThread(parentReportAction);
}
return false;
}
/**
* An IOU Request is a thread where the parent report is an IOU Report and
* the parentReportAction is a transaction.
*
* @param {Object} report
* @returns {Boolean}
*/
function isIOURequest(report) {
if (isThread(report)) {
const parentReportAction = ReportActionsUtils.getParentReportAction(report);
const parentReport = allReports[`${ONYXKEYS.COLLECTION.REPORT}${report.parentReportID}`];
return isIOUReport(parentReport) && ReportActionsUtils.isTransactionThread(parentReportAction);
}
return false;
}
/**
* Checks if a report is an IOU or expense request.
*
* @param {Object|String} reportOrID
* @returns {Boolean}
*/
function isMoneyRequest(reportOrID) {
const report = _.isObject(reportOrID) ? reportOrID : allReports[`${ONYXKEYS.COLLECTION.REPORT}${reportOrID}`];
return isIOURequest(report) || isExpenseRequest(report);
}
/**
* Checks if a report is an IOU or expense report.
*
* @param {Object|String} reportOrID
* @returns {Boolean}
*/
function isMoneyRequestReport(reportOrID) {
const report = typeof reportOrID === 'object' ? reportOrID : allReports[`${ONYXKEYS.COLLECTION.REPORT}${reportOrID}`];
return isIOUReport(report) || isExpenseReport(report);
}
/**
* Get the report given a reportID
*
* @param {String} reportID
* @returns {Object}
*/
function getReport(reportID) {
// Deleted reports are set to null and lodashGet will still return null in that case, so we need to add an extra check
return lodashGet(allReports, `${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {}) || {};
}
/**
* Can only delete if the author is this user and the action is an ADDCOMMENT action or an IOU action in an unsettled report, or if the user is a
* policy admin
*
* @param {Object} reportAction
* @param {String} reportID
* @returns {Boolean}
*/
function canDeleteReportAction(reportAction, reportID) {
const report = getReport(reportID);
const isActionOwner = reportAction.actorAccountID === currentUserAccountID;
if (ReportActionsUtils.isMoneyRequestAction(reportAction)) {
// For now, users cannot delete split actions
const isSplitAction = lodashGet(reportAction, 'originalMessage.type') === CONST.IOU.REPORT_ACTION_TYPE.SPLIT;
if (isSplitAction || isSettled(reportAction.originalMessage.IOUReportID) || isReportApproved(report)) {
return false;
}
if (isActionOwner) {
return true;
}
}
if (
reportAction.actionName !== CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT ||
reportAction.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE ||
ReportActionsUtils.isCreatedTaskReportAction(reportAction) ||
reportAction.actorAccountID === CONST.ACCOUNT_ID.CONCIERGE
) {
return false;
}
const policy = lodashGet(allPolicies, `${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`) || {};
const isAdmin = policy.role === CONST.POLICY.ROLE.ADMIN && !isDM(report);
return isActionOwner || isAdmin;
}
/**
* Get welcome message based on room type
* @param {Object} report
* @param {Boolean} isUserPolicyAdmin
* @returns {Object}
*/
function getRoomWelcomeMessage(report, isUserPolicyAdmin) {
const welcomeMessage = {showReportName: true};
const workspaceName = getPolicyName(report);
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 (isAdminsOnlyPostingRoom(report) && !isUserPolicyAdmin) {
welcomeMessage.phrase1 = Localize.translateLocal('reportActionsView.beginningOfChatHistoryAdminOnlyPostingRoom');
welcomeMessage.showReportName = false;
} 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;
}
/**
* 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 !_.isEmpty(report.participantAccountIDs) && _.contains(report.participantAccountIDs, CONST.ACCOUNT_ID.CONCIERGE);
}
/**
* Returns true if there is any automated expensify account `in accountIDs
* @param {Array} accountIDs
* @returns {Boolean}
*/
function hasAutomatedExpensifyAccountIDs(accountIDs) {
return _.intersection(accountIDs, CONST.EXPENSIFY_ACCOUNT_IDS).length > 0;
}
/**
* @param {Object} report
* @param {Number} currentLoginAccountID
* @returns {Array}
*/
function getReportRecipientAccountIDs(report, currentLoginAccountID) {
let finalReport = report;
// In 1:1 chat threads, the participants will be the same as parent report. If a report is specifically a 1:1 chat thread then we will
// get parent report and use its participants array.
if (isThread(report) && !(isTaskReport(report) || isMoneyRequestReport(report))) {
const parentReport = lodashGet(allReports, [`${ONYXKEYS.COLLECTION.REPORT}${report.parentReportID}`]);
if (hasSingleParticipant(parentReport)) {
finalReport = parentReport;
}
}
let finalParticipantAccountIDs = [];
if (isMoneyRequestReport(report)) {
// For money requests i.e the IOU (1:1 person) and Expense (1:* person) reports, use the full `initialParticipantAccountIDs` array
// and add the `ownerAccountId`. Money request reports don't add `ownerAccountId` in `participantAccountIDs` array
finalParticipantAccountIDs = _.union(lodashGet(finalReport, 'participantAccountIDs'), [report.ownerAccountID]);
} else if (isTaskReport(report)) {
// Task reports `managerID` will change when assignee is changed, in that case the old `managerID` is still present in `participantAccountIDs`
// array along with the new one. We only need the `managerID` as a participant here.
finalParticipantAccountIDs = [report.managerID];
} else {
finalParticipantAccountIDs = lodashGet(finalReport, 'participantAccountIDs');
}
const reportParticipants = _.without(finalParticipantAccountIDs, currentLoginAccountID);
const participantsWithoutExpensifyAccountIDs = _.difference(reportParticipants, CONST.EXPENSIFY_ACCOUNT_IDS);
return participantsWithoutExpensifyAccountIDs;
}
/**
* Whether the time row should be shown for a report.
* @param {Array<Object>} personalDetails
* @param {Object} report
* @param {Number} accountID
* @return {Boolean}
*/
function canShowReportRecipientLocalTime(personalDetails, report, accountID) {
const reportRecipientAccountIDs = getReportRecipientAccountIDs(report, accountID);
const hasMultipleParticipants = reportRecipientAccountIDs.length > 1;
const reportRecipient = personalDetails[reportRecipientAccountIDs[0]];
const reportRecipientTimezone = lodashGet(reportRecipient, 'timezone', CONST.DEFAULT_TIME_ZONE);
const isReportParticipantValidated = lodashGet(reportRecipient, 'validated', false);
return Boolean(
!hasMultipleParticipants &&
!isChatRoom(report) &&
!isPolicyExpenseChat(report) &&
reportRecipient &&
reportRecipientTimezone &&
reportRecipientTimezone.selected &&
isReportParticipantValidated,
);
}
/**
* Shorten last message text to fixed length and trim spaces.
* @param {String} lastMessageText
* @param {Boolean} isModifiedExpenseMessage
* @returns {String}
*/
function formatReportLastMessageText(lastMessageText, isModifiedExpenseMessage = false) {
if (isModifiedExpenseMessage) {
return String(lastMessageText).trim().replace(CONST.REGEX.LINE_BREAK, '').trim();
}
return String(lastMessageText).trim().replace(CONST.REGEX.AFTER_FIRST_LINE_BREAK, '').substring(0, CONST.REPORT.LAST_MESSAGE_TEXT_MAX_LENGTH).trim();
}
/**
* Helper method to return the default avatar associated with the given login
* @param {String} [workspaceName]
* @returns {String}
*/
function getDefaultWorkspaceAvatar(workspaceName) {
if (!workspaceName) {
return defaultWorkspaceAvatars.WorkspaceBuilding;
}
// Remove all chars not A-Z or 0-9 including underscore
const alphaNumeric = workspaceName
.normalize('NFD')
.replace(/[^0-9a-z]/gi, '')
.toUpperCase();
return !alphaNumeric ? defaultWorkspaceAvatars.WorkspaceBuilding : defaultWorkspaceAvatars[`Workspace${alphaNumeric[0]}`];
}
function getWorkspaceAvatar(report) {
const workspaceName = getPolicyName(report, allPolicies);
return lodashGet(allPolicies, [`${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`, 'avatar']) || getDefaultWorkspaceAvatar(workspaceName);
}
/**
* 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 {Array} participants
* @param {Object} personalDetails
* @returns {Array<*>}
*/
function getIconsForParticipants(participants, personalDetails) {
const participantDetails = [];
const participantsList = participants || [];
for (let i = 0; i < participantsList.length; i++) {
const accountID = participantsList[i];
const avatarSource = UserUtils.getAvatar(lodashGet(personalDetails, [accountID, 'avatar'], ''), accountID);
const displayNameLogin = lodashGet(personalDetails, [accountID, 'displayName']) || lodashGet(personalDetails, [accountID, 'login'], '');
participantDetails.push([accountID, displayNameLogin, avatarSource, lodashGet(personalDetails, [accountID, 'fallBackIcon'])]);
}
const sortedParticipantDetails = _.chain(participantDetails)
.sort((first, second) => {
// First sort by displayName/login
const displayNameLoginOrder = first[1].localeCompare(second[1]);
if (displayNameLoginOrder !== 0) {
return displayNameLoginOrder;
}
// Then fallback on accountID as the final sorting criteria.
// This will ensure that the order of avatars with same login/displayName
// stay consistent across all users and devices
return first[0] > second[0];
})
.value();
// Now that things are sorted, gather only the avatars (second element in the array) and return those
const avatars = [];
for (let i = 0; i < sortedParticipantDetails.length; i++) {
const userIcon = {
id: sortedParticipantDetails[i][0],
source: sortedParticipantDetails[i][2],
type: CONST.ICON_TYPE_AVATAR,
name: sortedParticipantDetails[i][1],
fallBackIcon: sortedParticipantDetails[i][3],