-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Report.js
1576 lines (1402 loc) · 61.6 KB
/
Report.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 {Linking} from 'react-native';
import moment from 'moment';
import _ from 'underscore';
import lodashGet from 'lodash/get';
import ExpensiMark from 'expensify-common/lib/ExpensiMark';
import Str from 'expensify-common/lib/str';
import Onyx from 'react-native-onyx';
import ONYXKEYS from '../../ONYXKEYS';
import * as Pusher from '../Pusher/pusher';
import LocalNotification from '../Notification/LocalNotification';
import PushNotification from '../Notification/PushNotification';
import * as PersonalDetails from './PersonalDetails';
import * as User from './User';
import Navigation from '../Navigation/Navigation';
import * as ActiveClientManager from '../ActiveClientManager';
import Visibility from '../Visibility';
import ROUTES from '../../ROUTES';
import NetworkConnection from '../NetworkConnection';
import Timing from './Timing';
import * as API from '../API';
import CONST from '../../CONST';
import Log from '../Log';
import * as LoginUtils from '../LoginUtils';
import * as ReportUtils from '../reportUtils';
import * as OptionsListUtils from '../OptionsListUtils';
import Timers from '../Timers';
import * as ReportActions from './ReportActions';
import Growl from '../Growl';
import * as Localize from '../Localize';
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 lastViewedReportID;
Onyx.connect({
key: ONYXKEYS.CURRENTLY_VIEWED_REPORTID,
callback: val => lastViewedReportID = val ? Number(val) : null,
});
let myPersonalDetails;
Onyx.connect({
key: ONYXKEYS.MY_PERSONAL_DETAILS,
callback: val => myPersonalDetails = val,
});
const allReports = {};
let conciergeChatReportID;
const typingWatchTimers = {};
/**
* Map of the most recent sequenceNumber for a reports_* key in Onyx by reportID.
*
* There are several sources that can set the most recent reportAction's sequenceNumber for a report:
*
* - Fetching the report object
* - Fetching the report history
* - Optimistically creating a report action
* - Handling a report action via Pusher
*
* Those values are stored in reportMaxSequenceNumbers and treated as the main source of truth for each report's max
* sequenceNumber.
*/
const reportMaxSequenceNumbers = {};
// Keeps track of the last read for each report
const lastReadSequenceNumbers = {};
// Map of optimistic report action IDs. These should be cleared when replaced by a recent fetch of report history
// since we will then be up to date and any optimistic actions that are still waiting to be replaced can be removed.
const optimisticReportActionIDs = {};
// Boolean to indicate if report data is loading from the API or not.
let isReportDataLoading = true;
Onyx.connect({
key: ONYXKEYS.IS_LOADING_REPORT_DATA,
callback: val => isReportDataLoading = val,
});
/**
* Checks the report to see if there are any unread action items
*
* @param {Object} report
* @returns {Boolean}
*/
function getUnreadActionCount(report) {
const lastReadSequenceNumber = lodashGet(report, [
'reportNameValuePairs',
`lastRead_${currentUserAccountID}`,
'sequenceNumber',
]);
// Save the lastReadActionID locally so we can access this later
lastReadSequenceNumbers[report.reportID] = lastReadSequenceNumber;
if (report.reportActionCount === 0) {
return 0;
}
if (!lastReadSequenceNumber) {
return report.reportActionCount;
}
// There are unread items if the last one the user has read is less
// than the highest sequence number we have
const unreadActionCount = report.reportActionCount - lastReadSequenceNumber - ReportActions.getDeletedCommentsCount(report.reportID, lastReadSequenceNumber);
return Math.max(0, unreadActionCount);
}
/**
* @param {Object} report
* @return {String[]}
*/
function getParticipantEmailsFromReport({sharedReportList, reportNameValuePairs, ownerEmail}) {
const emailArray = _.map(sharedReportList, participant => participant.email);
if (ReportUtils.isChatRoom(reportNameValuePairs)) {
return emailArray;
}
if (ReportUtils.isPolicyExpenseChat(reportNameValuePairs)) {
// The owner of the policyExpenseChat isn't in the sharedReportsList so they need to be explicitly included.
return [ownerEmail, ...emailArray];
}
// The current user is excluded from the participants array in DMs/Group DMs because their participation is implied
// by the chat being shared to them. This also prevents the user's own avatar from being a part of the chat avatar.
return _.without(emailArray, currentUserEmail);
}
/**
* Returns the title for a default room, a policy room or generates one based on the participants
*
* @param {Object} fullReport
* @param {String} chatType
* @return {String}
*/
function getChatReportName(fullReport, chatType) {
if (ReportUtils.isDefaultRoom({chatType})) {
return `#${fullReport.reportName}${(ReportUtils.isArchivedRoom({
chatType,
stateNum: fullReport.state,
statusNum: fullReport.status,
})
? ` (${Localize.translateLocal('common.deleted')})`
: '')}`;
}
// For a basic policy room or a Policy Expense chat, return its original name
if (ReportUtils.isUserCreatedPolicyRoom({chatType}) || ReportUtils.isPolicyExpenseChat({chatType})) {
return LoginUtils.getEmailWithoutMergedAccountPrefix(fullReport.reportName);
}
const {sharedReportList} = fullReport;
return _.chain(sharedReportList)
.map(participant => participant.email)
.filter(participant => participant !== currentUserEmail)
.map(participant => PersonalDetails.getDisplayName(participant))
.value()
.join(', ');
}
/**
* Only store the minimal amount of data in Onyx that needs to be stored
* because space is limited
*
* @param {Object} report
* @param {Number} report.reportID
* @param {String} report.reportName
* @param {Object} report.reportNameValuePairs
* @returns {Object}
*/
function getSimplifiedReportObject(report) {
const createTimestamp = lodashGet(report, 'lastActionCreated', 0);
const lastMessageTimestamp = moment.utc(createTimestamp).unix();
const lastActionMessage = lodashGet(report, ['lastActionMessage', 'html'], '');
const isLastMessageAttachment = /<img([^>]+)\/>/gi.test(lastActionMessage);
const chatType = lodashGet(report, ['reportNameValuePairs', 'chatType'], '');
let lastMessageText = null;
if (report.reportActionCount > 0) {
// We are removing any html tags from the message html since we cannot access the text version of any comments as
// the report only has the raw reportActionList and not the processed version returned by Report_GetHistory
// We convert the line-breaks in html to space ' ' before striping the tags
lastMessageText = lastActionMessage
.replace(/((<br[^>]*>)+)/gi, ' ')
.replace(/(<([^>]+)>)/gi, '');
lastMessageText = ReportUtils.formatReportLastMessageText(lastMessageText);
}
const reportName = lodashGet(report, ['reportNameValuePairs', 'type']) === 'chat'
? getChatReportName(report, chatType)
: report.reportName;
const lastActorEmail = lodashGet(report, 'lastActionActorEmail', '');
const notificationPreference = ReportUtils.isChatRoom({chatType})
? lodashGet(report, ['reportNameValuePairs', 'notificationPreferences', currentUserAccountID], 'daily')
: '';
// Used for archived rooms, will store the policy name that the room used to belong to.
const oldPolicyName = lodashGet(report, ['reportNameValuePairs', 'oldPolicyName'], '');
// Used for User Created Policy Rooms, will denote how access to a chat room is given among workspace members
const visibility = lodashGet(report, ['reportNameValuePairs', 'visibility']);
return {
reportID: report.reportID,
reportName,
chatType,
ownerEmail: LoginUtils.getEmailWithoutMergedAccountPrefix(lodashGet(report, ['ownerEmail'], '')),
policyID: lodashGet(report, ['reportNameValuePairs', 'expensify_policyID'], ''),
unreadActionCount: getUnreadActionCount(report),
maxSequenceNumber: lodashGet(report, 'reportActionCount', 0),
participants: getParticipantEmailsFromReport(report),
isPinned: report.isPinned,
lastVisitedTimestamp: lodashGet(report, [
'reportNameValuePairs',
`lastRead_${currentUserAccountID}`,
'timestamp',
], 0),
lastMessageTimestamp,
lastMessageText: isLastMessageAttachment ? '[Attachment]' : lastMessageText,
lastActorEmail,
hasOutstandingIOU: false,
notificationPreference,
stateNum: report.state,
statusNum: report.status,
oldPolicyName,
visibility,
isOwnPolicyExpenseChat: lodashGet(report, ['isOwnPolicyExpenseChat'], false),
};
}
/**
* Get a simplified version of an IOU report
*
* @param {Object} reportData
* @param {String} reportData.transactionID
* @param {Number} reportData.amount
* @param {String} reportData.currency
* @param {String} reportData.created
* @param {String} reportData.comment
* @param {Object[]} reportData.transactionList
* @param {String} reportData.ownerEmail
* @param {String} reportData.managerEmail
* @param {Number} reportData.reportID
* @param {Number|String} chatReportID
* @returns {Object}
*/
function getSimplifiedIOUReport(reportData, chatReportID) {
return {
reportID: reportData.reportID,
ownerEmail: reportData.ownerEmail,
managerEmail: reportData.managerEmail,
currency: reportData.currency,
chatReportID: Number(chatReportID),
state: reportData.state,
cachedTotal: reportData.cachedTotal,
total: reportData.total,
status: reportData.status,
stateNum: reportData.stateNum,
submitterPayPalMeAddress: reportData.submitterPayPalMeAddress,
submitterPhoneNumbers: reportData.submitterPhoneNumbers,
hasOutstandingIOU: reportData.stateNum === CONST.REPORT.STATE_NUM.PROCESSING && reportData.total !== 0,
};
}
/**
* Given IOU and chat report ID fetches most recent IOU data from API.
*
* @param {Number} iouReportID
* @param {Number} chatReportID
* @returns {Promise}
*/
function fetchIOUReport(iouReportID, chatReportID) {
return API.Get({
returnValueList: 'reportStuff',
reportIDList: iouReportID,
shouldLoadOptionalKeys: true,
includePinnedReports: true,
}).then((response) => {
if (!response) {
return;
}
if (response.jsonCode !== 200) {
console.error(response.message);
return;
}
const iouReportData = response.reports[iouReportID];
if (!iouReportData) {
// IOU data for a report will be missing when the IOU report has already been paid.
// This is expected and we return early as no further processing can be done.
return;
}
return getSimplifiedIOUReport(iouReportData, chatReportID);
}).catch((error) => {
Log.hmmm('[Report] Failed to populate IOU Collection:', error.message);
});
}
/**
* Given debtorEmail finds active IOU report ID via GetIOUReport API call
*
* @param {String} debtorEmail
* @returns {Promise}
*/
function fetchIOUReportID(debtorEmail) {
return API.GetIOUReport({
debtorEmail,
}).then((response) => {
const iouReportID = response.reportID || 0;
if (response.jsonCode !== 200) {
console.error(response.message);
return;
}
if (iouReportID === 0) {
// If there is no IOU report for this user then we will assume it has been paid and do nothing here.
// All reports are initialized with hasOutstandingIOU: false. Since the IOU report we were looking for has
// been settled then there's nothing more to do.
Log.info('GetIOUReport returned a reportID of 0, not fetching IOU report data');
return;
}
return iouReportID;
});
}
/**
* Fetches chat reports when provided a list of chat report IDs.
* If the shouldRedirectIfInaccessible flag is set, we redirect to the Concierge chat
* when we find an inaccessible chat
* @param {Array} chatList
* @param {Boolean} shouldRedirectIfInaccessible
* @returns {Promise<Object[]>} only used internally when fetchAllReports() is called
*/
function fetchChatReportsByIDs(chatList, shouldRedirectIfInaccessible = false) {
let fetchedReports;
const simplifiedReports = {};
return API.GetReportSummaryList({reportIDList: chatList.join(',')})
.then(({reportSummaryList, jsonCode}) => {
Log.info('[Report] successfully fetched report data', false, {chatList});
fetchedReports = reportSummaryList;
// If we receive a 404 response while fetching a single report, treat that report as inaccessible.
if (jsonCode === 404 && shouldRedirectIfInaccessible) {
throw new Error(CONST.REPORT.ERROR.INACCESSIBLE_REPORT);
}
return Promise.all(_.map(fetchedReports, (chatReport) => {
// If there aren't any IOU actions, we don't need to fetch any additional data
if (!chatReport.hasIOUAction) {
return;
}
// Group chat reports cannot and should not be associated with a specific IOU report
const participants = getParticipantEmailsFromReport(chatReport);
if (participants.length > 1) {
return;
}
if (participants.length === 0) {
Log.alert('[Report] Report with IOU action but does not have any participant.', {
reportID: chatReport.reportID,
participants,
});
return;
}
return fetchIOUReportID(participants[0])
.then((iouReportID) => {
if (!iouReportID) {
return Promise.resolve();
}
return fetchIOUReport(iouReportID, chatReport.reportID);
});
}));
})
.then((iouReportObjects) => {
// Process the reports and store them in Onyx. At the same time we'll save the simplified reports in this
// variable called simplifiedReports which hold the participants (minus the current user) for each report.
// Using this simplifiedReport we can call PersonalDetails.getFromReportParticipants to get the
// personal details of all the participants and even link up their avatars to report icons.
const reportIOUData = {};
_.each(fetchedReports, (report) => {
const simplifiedReport = getSimplifiedReportObject(report);
simplifiedReports[`${ONYXKEYS.COLLECTION.REPORT}${report.reportID}`] = simplifiedReport;
});
_.each(iouReportObjects, (iouReportObject) => {
if (!iouReportObject) {
return;
}
const iouReportKey = `${ONYXKEYS.COLLECTION.REPORT_IOUS}${iouReportObject.reportID}`;
const reportKey = `${ONYXKEYS.COLLECTION.REPORT}${iouReportObject.chatReportID}`;
reportIOUData[iouReportKey] = iouReportObject;
simplifiedReports[reportKey].iouReportID = iouReportObject.reportID;
simplifiedReports[reportKey].hasOutstandingIOU = iouReportObject.stateNum
=== CONST.REPORT.STATE_NUM.PROCESSING && iouReportObject.total !== 0;
});
// We use mergeCollection such that it updates the collection in one go.
// Any withOnyx subscribers to this key will also receive the complete updated props just once
// than updating props for each report and re-rendering had merge been used.
Onyx.mergeCollection(ONYXKEYS.COLLECTION.REPORT_IOUS, reportIOUData);
Onyx.mergeCollection(ONYXKEYS.COLLECTION.REPORT, simplifiedReports);
// Fetch the personal details if there are any
PersonalDetails.getFromReportParticipants(_.values(simplifiedReports));
return simplifiedReports;
})
.catch((err) => {
if (err.message !== CONST.REPORT.ERROR.INACCESSIBLE_REPORT) {
return;
}
// eslint-disable-next-line no-use-before-define
handleInaccessibleReport();
});
}
/**
* Given IOU object, save the data to Onyx.
*
* @param {Object} iouReportObject
* @param {Number} iouReportObject.stateNum
* @param {Number} iouReportObject.total
* @param {Number} iouReportObject.reportID
*/
function setLocalIOUReportData(iouReportObject) {
const iouReportKey = `${ONYXKEYS.COLLECTION.REPORT_IOUS}${iouReportObject.reportID}`;
Onyx.merge(iouReportKey, iouReportObject);
}
/**
* Update the lastRead actionID and timestamp in local memory and Onyx
*
* @param {Number} reportID
* @param {Number} lastReadSequenceNumber
*/
function setLocalLastRead(reportID, lastReadSequenceNumber) {
lastReadSequenceNumbers[reportID] = lastReadSequenceNumber;
const reportMaxSequenceNumber = reportMaxSequenceNumbers[reportID];
// Determine the number of unread actions by deducting the last read sequence from the total. If, for some reason,
// the last read sequence is higher than the actual last sequence, let's just assume all actions are read
const unreadActionCount = Math.max(reportMaxSequenceNumber - lastReadSequenceNumber - ReportActions.getDeletedCommentsCount(reportID, lastReadSequenceNumber), 0);
// Update the report optimistically.
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {
unreadActionCount,
lastVisitedTimestamp: Date.now(),
});
}
/**
* Remove all optimistic actions from report actions and reset the optimisticReportActionsIDs array. We do this
* to clear any stuck optimistic actions that have not be updated for whatever reason.
*
* @param {Number} reportID
*/
function removeOptimisticActions(reportID) {
const actionIDs = optimisticReportActionIDs[reportID] || [];
const actionsToRemove = _.reduce(actionIDs, (actions, actionID) => ({
...actions,
[actionID]: null,
}), {});
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, actionsToRemove);
// Reset the optimistic report action IDs to an empty array
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {
optimisticReportActionIDs: [],
});
}
/**
* Fetch the iouReport and persist the data to Onyx.
*
* @param {Number} iouReportID - ID of the report we are fetching
* @param {Number} chatReportID - associated chatReportID, set as an iouReport field
* @param {Boolean} [shouldRedirectIfEmpty=false] - Whether to redirect to Active Report Screen if IOUReport is empty
* @returns {Promise}
*/
function fetchIOUReportByID(iouReportID, chatReportID, shouldRedirectIfEmpty = false) {
return fetchIOUReport(iouReportID, chatReportID)
.then((iouReportObject) => {
if (!iouReportObject && shouldRedirectIfEmpty) {
Growl.error(Localize.translateLocal('notFound.iouReportNotFound'));
Navigation.navigate(ROUTES.REPORT);
return;
}
setLocalIOUReportData(iouReportObject);
return iouReportObject;
});
}
/**
* If an iouReport is open (has an IOU, but is not yet paid) then we sync the reportIDs of both chatReport and
* iouReport in Onyx, simplifying IOU data retrieval and reducing necessary API calls when displaying IOU components:
* - chatReport: {id: 123, iouReportID: 987, ...}
* - iouReport: {id: 987, chatReportID: 123, ...}
*
* The reports must remain in sync when the iouReport is modified. This function ensures that we sync reportIds after
* fetching the iouReport and therefore should only be called if we are certain that the fetched iouReport is currently
* open - else we would overwrite the existing open iouReportID with a closed iouReportID.
*
* Examples of usage include 'receieving a push notification', or 'paying an IOU', because both of these cases can only
* occur for an iouReport that is currently open (notifications are not sent for closed iouReports, and you cannot pay a
* closed IOU).
*
* @param {Number} iouReportID - ID of the report we are fetching
* @param {Number} chatReportID - associated chatReportID, used to sync the reports
*/
function fetchIOUReportByIDAndUpdateChatReport(iouReportID, chatReportID) {
fetchIOUReportByID(iouReportID, chatReportID)
.then((iouReportObject) => {
// Now sync the chatReport data to ensure it has a reference to the updated iouReportID
const chatReportObject = {
hasOutstandingIOU: iouReportObject.stateNum === CONST.REPORT.STATE_NUM.PROCESSING
&& iouReportObject.total !== 0,
iouReportID: iouReportObject.reportID,
};
if (!chatReportObject.hasOutstandingIOU) {
chatReportObject.iouReportID = null;
}
const reportKey = `${ONYXKEYS.COLLECTION.REPORT}${chatReportID}`;
Onyx.merge(reportKey, chatReportObject);
});
}
/**
* @param {Number} reportID
* @param {Number} sequenceNumber
*/
function setNewMarkerPosition(reportID, sequenceNumber) {
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {
newMarkerSequenceNumber: sequenceNumber,
});
}
/**
* Updates a report action's message to be a new value.
*
* @param {Number} reportID
* @param {Number} sequenceNumber
* @param {Object} message
*/
function updateReportActionMessage(reportID, sequenceNumber, message) {
const actionToMerge = {};
actionToMerge[sequenceNumber] = {message: [message]};
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, actionToMerge).then(() => {
// If the message is deleted, update the last read message and the unread counter
if (!message.html) {
setLocalLastRead(reportID, lastReadSequenceNumbers[reportID]);
}
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {
lastMessageText: ReportActions.getLastVisibleMessageText(reportID),
});
});
}
/**
* Updates a report in the store with a new report action
*
* @param {Number} reportID
* @param {Object} reportAction
* @param {String} [notificationPreference] On what cadence the user would like to be notified
*/
function updateReportWithNewAction(
reportID,
reportAction,
notificationPreference = CONST.REPORT.NOTIFICATION_PREFERENCE.ALWAYS,
) {
const newMaxSequenceNumber = reportAction.sequenceNumber;
const isFromCurrentUser = reportAction.actorAccountID === currentUserAccountID;
const initialLastReadSequenceNumber = lastReadSequenceNumbers[reportID] || 0;
// When handling an action from the current users we can assume that their
// last read actionID has been updated in the server but not necessarily reflected
// locally so we must first update it and then calculate the unread (which should be 0)
if (isFromCurrentUser) {
setLocalLastRead(reportID, newMaxSequenceNumber);
}
let messageText = lodashGet(reportAction, ['message', 0, 'text'], '');
if (reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.RENAMED) {
messageText = lodashGet(reportAction, 'originalMessage.html', '');
}
// Always merge the reportID into Onyx
// If the report doesn't exist in Onyx yet, then all the rest of the data will be filled out
// by handleReportChanged
const updatedReportObject = {
reportID,
// Use updated lastReadSequenceNumber, value may have been modified by setLocalLastRead
// Here deletedComments count does not include the new action being added. We can safely assume that newly received action is not deleted.
unreadActionCount: newMaxSequenceNumber - (lastReadSequenceNumbers[reportID] || 0) - ReportActions.getDeletedCommentsCount(reportID, lastReadSequenceNumbers[reportID] || 0),
maxSequenceNumber: reportAction.sequenceNumber,
};
// If the report action from pusher is a higher sequence number than we know about (meaning it has come from
// a chat participant in another application), then the last message text and author needs to be updated as well
if (newMaxSequenceNumber > initialLastReadSequenceNumber) {
updatedReportObject.lastMessageTimestamp = reportAction.timestamp;
updatedReportObject.lastMessageText = ReportUtils.formatReportLastMessageText(messageText);
updatedReportObject.lastActorEmail = reportAction.actorEmail;
}
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, updatedReportObject);
const reportActionsToMerge = {};
if (reportAction.clientID) {
// Remove the optimistic action from the report since we are about to replace it
// with the real one (which has the true sequenceNumber)
reportActionsToMerge[reportAction.clientID] = null;
}
// Add the action into Onyx
reportActionsToMerge[reportAction.sequenceNumber] = {
...reportAction,
isAttachment: ReportUtils.isReportMessageAttachment(messageText),
loading: false,
};
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, reportActionsToMerge);
// If chat report receives an action with IOU and we have an IOUReportID, update IOU object
if (reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.IOU && reportAction.originalMessage.IOUReportID) {
const iouReportID = reportAction.originalMessage.IOUReportID;
// We know this iouReport is open because reportActions of type CONST.REPORT.ACTIONS.TYPE.IOU can only be
// triggered for an open iouReport (an open iouReport has an IOU, but is not yet paid). After fetching the
// iouReport we must update the chatReport with the correct iouReportID. If we don't, then new IOUs would not
// be displayed and paid IOUs would show as unpaid.
fetchIOUReportByIDAndUpdateChatReport(iouReportID, reportID);
}
if (!ActiveClientManager.isClientTheLeader()) {
Log.info('[LOCAL_NOTIFICATION] Skipping notification because this client is not the leader');
return;
}
// We don't want to send a local notification if the user preference is daily or mute
if (notificationPreference === 'mute' || notificationPreference === 'daily') {
// eslint-disable-next-line max-len
Log.info(`[LOCAL_NOTIFICATION] No notification because user preference is to be notified: ${notificationPreference}`);
return;
}
// If this comment is from the current user we don't want to parrot whatever they wrote back to them.
if (isFromCurrentUser) {
Log.info('[LOCAL_NOTIFICATION] No notification because comment is from the currently logged in user');
return;
}
// If we are currently viewing this report do not show a notification.
if (reportID === lastViewedReportID && Visibility.isVisible()) {
Log.info('[LOCAL_NOTIFICATION] No notification because it was a comment for the current report');
return;
}
// If the comment came from Concierge let's not show a notification since we already show one for expensify.com
if (lodashGet(reportAction, 'actorEmail') === CONST.EMAIL.CONCIERGE) {
return;
}
// When a new message comes in, if the New marker is not already set (newMarkerSequenceNumber === 0), set the
// marker above the incoming message.
if (lodashGet(allReports, [reportID, 'newMarkerSequenceNumber'], 0) === 0
&& updatedReportObject.unreadActionCount > 0) {
const oldestUnreadSeq = (updatedReportObject.maxSequenceNumber - updatedReportObject.unreadActionCount) + 1;
setNewMarkerPosition(reportID, oldestUnreadSeq);
}
Log.info('[LOCAL_NOTIFICATION] Creating notification');
LocalNotification.showCommentNotification({
reportAction,
onClick: () => {
// Navigate to this report onClick
Navigation.navigate(ROUTES.getReportRoute(reportID));
},
});
}
/**
* Updates a report in Onyx with a new pinned state.
*
* @param {Number} reportID
* @param {Boolean} isPinned
*/
function updateReportPinnedState(reportID, isPinned) {
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {isPinned});
}
/**
* Get the private pusher channel name for a Report.
*
* @param {Number} reportID
* @returns {String}
*/
function getReportChannelName(reportID) {
return `private-report-reportID-${reportID}`;
}
/**
* Abstraction around subscribing to private user channel events. Handles all logs and errors automatically.
*
* @param {String} eventName
* @param {Function} onEvent
* @param {Boolean} isChunked
*/
function subscribeToPrivateUserChannelEvent(eventName, onEvent, isChunked = false) {
const pusherChannelName = `private-user-accountID-${currentUserAccountID}`;
/**
* @param {Object} pushJSON
*/
function logPusherEvent(pushJSON) {
Log.info(`[Report] Handled ${eventName} event sent by Pusher`, false, {reportID: pushJSON.reportID, reportActionID: pushJSON.reportActionID});
}
function onPusherResubscribeToPrivateUserChannel() {
NetworkConnection.triggerReconnectionCallbacks('Pusher re-subscribed to private user channel');
}
/**
* @param {*} pushJSON
*/
function onEventPush(pushJSON) {
logPusherEvent(pushJSON);
onEvent(pushJSON);
}
/**
* @param {*} error
*/
function onSubscriptionFailed(error) {
Log.info('[Report] Failed to subscribe to Pusher channel', false, {error, pusherChannelName, eventName});
}
Pusher.subscribe(pusherChannelName, eventName, onEventPush, isChunked, onPusherResubscribeToPrivateUserChannel)
.catch(onSubscriptionFailed);
}
/**
* Initialize our pusher subscriptions to listen for new report comments and pin toggles
*/
function subscribeToUserEvents() {
// If we don't have the user's accountID yet we can't subscribe so return early
if (!currentUserAccountID) {
return;
}
const pusherChannelName = `private-user-accountID-${currentUserAccountID}`;
if (Pusher.isSubscribed(pusherChannelName) || Pusher.isAlreadySubscribing(pusherChannelName)) {
return;
}
// Live-update a report's actions when a 'report comment' event is received.
subscribeToPrivateUserChannelEvent(Pusher.TYPE.REPORT_COMMENT, pushJSON => updateReportWithNewAction(pushJSON.reportID, pushJSON.reportAction, pushJSON.notificationPreference));
// Live-update a report's actions when a 'chunked report comment' event is received.
subscribeToPrivateUserChannelEvent(
Pusher.TYPE.REPORT_COMMENT_CHUNK,
pushJSON => updateReportWithNewAction(pushJSON.reportID, pushJSON.reportAction, pushJSON.notificationPreference),
true,
);
// Live-update a report's actions when an 'edit comment' event is received.
subscribeToPrivateUserChannelEvent(Pusher.TYPE.REPORT_COMMENT_EDIT, pushJSON => updateReportActionMessage(pushJSON.reportID, pushJSON.sequenceNumber, pushJSON.message));
// Live-update a report's actions when an 'edit comment chunk' event is received.
subscribeToPrivateUserChannelEvent(Pusher.TYPE.REPORT_COMMENT_EDIT_CHUNK, pushJSON => updateReportActionMessage(pushJSON.reportID, pushJSON.sequenceNumber, pushJSON.message), true);
// Live-update a report's pinned state when a 'report toggle pinned' event is received.
subscribeToPrivateUserChannelEvent(Pusher.TYPE.REPORT_TOGGLE_PINNED, pushJSON => updateReportPinnedState(pushJSON.reportID, pushJSON.isPinned));
}
/**
* Setup reportComment push notification callbacks.
*/
function subscribeToReportCommentPushNotifications() {
PushNotification.onReceived(PushNotification.TYPE.REPORT_COMMENT, ({reportID, reportAction}) => {
Log.info('[Report] Handled event sent by Airship', false, {reportID});
updateReportWithNewAction(reportID, reportAction);
});
// Open correct report when push notification is clicked
PushNotification.onSelected(PushNotification.TYPE.REPORT_COMMENT, ({reportID}) => {
Navigation.setDidTapNotification();
Linking.openURL(`${CONST.DEEPLINK_BASE_URL}${ROUTES.getReportRoute(reportID)}`);
});
}
/**
* There are 2 possibilities that we can receive via pusher for a user's typing status:
* 1. The "new" way from New Expensify is passed as {[login]: Boolean} (e.g. {yuwen@expensify.com: true}), where the value
* is whether the user with that login is typing on the report or not.
* 2. The "old" way from e.com which is passed as {userLogin: login} (e.g. {userLogin: bstites@expensify.com})
*
* This method makes sure that no matter which we get, we return the "new" format
*
* @param {Object} typingStatus
* @returns {Object}
*/
function getNormalizedTypingStatus(typingStatus) {
let normalizedTypingStatus = typingStatus;
if (_.first(_.keys(typingStatus)) === 'userLogin') {
normalizedTypingStatus = {[typingStatus.userLogin]: true};
}
return normalizedTypingStatus;
}
/**
* Initialize our pusher subscriptions to listen for someone typing in a report.
*
* @param {Number} reportID
*/
function subscribeToReportTypingEvents(reportID) {
if (!reportID) {
return;
}
// Make sure we have a clean Typing indicator before subscribing to typing events
Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_USER_IS_TYPING}${reportID}`, {});
const pusherChannelName = getReportChannelName(reportID);
Pusher.subscribe(pusherChannelName, 'client-userIsTyping', (typingStatus) => {
const normalizedTypingStatus = getNormalizedTypingStatus(typingStatus);
const login = _.first(_.keys(normalizedTypingStatus));
if (!login) {
return;
}
// Don't show the typing indicator if a user is typing on another platform
if (login === currentUserEmail) {
return;
}
// Use a combo of the reportID and the login as a key for holding our timers.
const reportUserIdentifier = `${reportID}-${login}`;
clearTimeout(typingWatchTimers[reportUserIdentifier]);
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_USER_IS_TYPING}${reportID}`, normalizedTypingStatus);
// Wait for 1.5s of no additional typing events before setting the status back to false.
typingWatchTimers[reportUserIdentifier] = setTimeout(() => {
const typingStoppedStatus = {};
typingStoppedStatus[login] = false;
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_USER_IS_TYPING}${reportID}`, typingStoppedStatus);
delete typingWatchTimers[reportUserIdentifier];
}, 1500);
})
.catch((error) => {
Log.info('[Report] Failed to initially subscribe to Pusher channel', false, {error, pusherChannelName});
});
}
/**
* Remove our pusher subscriptions to listen for someone typing in a report.
*
* @param {Number} reportID
*/
function unsubscribeFromReportChannel(reportID) {
if (!reportID) {
return;
}
const pusherChannelName = getReportChannelName(reportID);
Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_USER_IS_TYPING}${reportID}`, {});
Pusher.unsubscribe(pusherChannelName);
}
/**
* Get the report ID for a chat report for a specific
* set of participants and navigate to it if wanted.
*
* @param {String[]} participants
* @param {Boolean} shouldNavigate
* @returns {Promise<Object[]>}
*/
function fetchOrCreateChatReport(participants, shouldNavigate = true) {
if (participants.length < 2) {
throw new Error('fetchOrCreateChatReport() must have at least two participants.');
}
return API.CreateChatReport({
emailList: participants.join(','),
})
.then((data) => {
if (data.jsonCode !== 200) {
console.error(data.message);
Growl.error(data.message);
return;
}
// Merge report into Onyx
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${data.reportID}`, {reportID: data.reportID});
if (shouldNavigate) {
// Redirect the logged in person to the new report
Navigation.navigate(ROUTES.getReportRoute(data.reportID));
}
// We are returning an array with a report object here since fetchAllReports calls this method or
// fetchChatReportsByIDs which returns an array of report objects.
return [getSimplifiedReportObject(data)];
});
}
/**
* Get the actions of a report
*
* @param {Number} reportID
* @param {Number} [offset]
* @returns {Promise}
*/
function fetchActions(reportID, offset) {
const reportActionsOffset = !_.isUndefined(offset) ? offset : -1;
if (!_.isNumber(reportActionsOffset)) {
Log.alert('[Report] Offset provided is not a number', {
offset,
reportActionsOffset,
});
return;
}
return API.Report_GetHistory({
reportID,
reportActionsOffset,
reportActionsLimit: CONST.REPORT.ACTIONS.LIMIT,
})
.then((data) => {
// We must remove all optimistic actions so there will not be any stuck comments. At this point, we should
// be caught up and no longer need any optimistic comments.
removeOptimisticActions(reportID);
const indexedData = _.indexBy(data.history, 'sequenceNumber');
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, indexedData);
});
}
/**
* Get the actions of a report
*
* @param {Number} reportID
* @param {Number} [offset]
*/
function fetchActionsWithLoadingState(reportID, offset) {
Onyx.set(ONYXKEYS.IS_LOADING_REPORT_ACTIONS, true);
fetchActions(reportID, offset)
.finally(() => Onyx.set(ONYXKEYS.IS_LOADING_REPORT_ACTIONS, false));
}
/**
* Get all of our reports
*
* @param {Boolean} shouldRecordHomePageTiming whether or not performance timing should be measured
* @param {Boolean} shouldDelayActionsFetch when the app loads we want to delay the fetching of additional actions
* @returns {Promise}
*/
function fetchAllReports(
shouldRecordHomePageTiming = false,
shouldDelayActionsFetch = false,
) {
Onyx.set(ONYXKEYS.IS_LOADING_REPORT_DATA, true);
return API.Get({
returnValueList: 'chatList',
})
.then((response) => {
if (response.jsonCode !== 200) {
return;
}
// The cast here is necessary as Get rvl='chatList' may return an int or Array
const reportIDs = _.filter(String(response.chatList).split(','), _.identity);
// Get all the chat reports if they have any, otherwise create one with concierge
if (reportIDs.length > 0) {
return fetchChatReportsByIDs(reportIDs);
}
return fetchOrCreateChatReport([currentUserEmail, CONST.EMAIL.CONCIERGE], false);
})
.then((returnedReports) => {
Onyx.set(ONYXKEYS.INITIAL_REPORT_DATA_LOADED, true);
Onyx.set(ONYXKEYS.IS_LOADING_REPORT_DATA, false);