-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
Report.js
1204 lines (1075 loc) · 46.4 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 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 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 {isReportMessageAttachment} from '../reportUtils';
import Timers from '../Timers';
import {dangerouslyGetReportActionsMaxSequenceNumber, isReportMissingActions} from './ReportActions';
let currentUserEmail;
let currentUserAccountID;
Onyx.connect({
key: ONYXKEYS.SESSION,
callback: (val) => {
// When signed out, val is undefined
if (val) {
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 = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT,
callback: (val) => {
if (val && val.reportID) {
allReports[val.reportID] = val;
}
},
});
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 = {};
/**
* 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.reportActionList.length === 0) {
return 0;
}
if (!lastReadSequenceNumber) {
return report.reportActionList.length;
}
// There are unread items if the last one the user has read is less
// than the highest sequence number we have
const unreadActionCount = report.reportActionList.length - lastReadSequenceNumber;
return Math.max(0, unreadActionCount);
}
/**
* @param {Object} report
* @return {String[]}
*/
function getParticipantEmailsFromReport({sharedReportList}) {
const emailArray = _.map(sharedReportList, participant => participant.email);
return _.without(emailArray, currentUserEmail);
}
/**
* Returns a generated report title based on the participants
*
* @param {Array} sharedReportList
* @return {String}
*/
function getChatReportName(sharedReportList) {
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 reportActionList = lodashGet(report, ['reportActionList'], []);
const lastReportAction = !_.isEmpty(reportActionList) ? _.last(reportActionList) : null;
const createTimestamp = lastReportAction ? lastReportAction.created : 0;
const lastMessageTimestamp = moment.utc(createTimestamp).unix();
const isLastMessageAttachment = /<img([^>]+)\/>/gi.test(lodashGet(lastReportAction, ['message', 'html'], ''));
// 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
const lastMessageText = lodashGet(lastReportAction, ['message', 'html'], '').replace(/(<([^>]+)>)/gi, '');
const reportName = lodashGet(report, 'reportNameValuePairs.type') === 'chat'
? getChatReportName(report.sharedReportList)
: report.reportName;
const lastActorEmail = lodashGet(lastReportAction, 'accountEmail', '');
return {
reportID: report.reportID,
reportName,
unreadActionCount: getUnreadActionCount(report),
maxSequenceNumber: report.reportActionList.length,
participants: getParticipantEmailsFromReport(report),
isPinned: report.isPinned,
lastVisitedTimestamp: lodashGet(report, [
'reportNameValuePairs',
`lastRead_${currentUserAccountID}`,
'timestamp',
], 0),
lastMessageTimestamp,
lastMessageText: isLastMessageAttachment ? '[Attachment]' : lastMessageText,
lastActorEmail,
hasOutstandingIOU: 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) {
const transactions = _.map(reportData.transactionList, transaction => ({
transactionID: transaction.transactionID,
amount: transaction.amount,
currency: transaction.currency,
created: transaction.created,
comment: transaction.comment,
})).reverse(); // `transactionList` data is returned ordered by desc creation date, they are changed to asc order
// because we must instead display them in the order that they were created (asc).
return {
reportID: reportData.reportID,
ownerEmail: reportData.ownerEmail,
managerEmail: reportData.managerEmail,
currency: reportData.currency,
transactions,
chatReportID: Number(chatReportID),
state: reportData.state,
cachedTotal: reportData.cachedTotal,
total: reportData.total,
status: reportData.status,
stateNum: reportData.stateNum,
hasOutstandingIOU: reportData.stateNum === 1 && 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) => {
console.debug(`[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.
console.debug('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
*
* @param {Array} chatList
* @returns {Promise<Number[]>} only used internally when fetchAllReports() is called
*/
function fetchChatReportsByIDs(chatList) {
let fetchedReports;
const simplifiedReports = {};
return API.Get({
returnValueList: 'reportStuff',
reportIDList: chatList.join(','),
shouldLoadOptionalKeys: true,
includePinnedReports: true,
})
.then(({reports}) => {
Log.info('[Report] successfully fetched report data', true);
fetchedReports = reports;
return Promise.all(_.map(fetchedReports, (chatReport) => {
const reportActionList = chatReport.reportActionList || [];
const containsIOUAction = _.any(reportActionList,
reportAction => reportAction.action === CONST.REPORT.ACTIONS.TYPE.IOU);
// If there aren't any IOU actions, we don't need to fetch any additional data
if (!containsIOUAction) {
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.', true, {
reportID: chatReport.reportID,
participants,
});
return;
}
return fetchIOUReportID(participants[0])
.then(iouReportID => 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 === 1
&& 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(Object.values(simplifiedReports));
return _.map(fetchedReports, report => report.reportID);
});
}
/**
* 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, 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
* @returns {Promise}
*/
function fetchIOUReportByID(iouReportID, chatReportID) {
return fetchIOUReport(iouReportID, chatReportID)
.then((iouReportObject) => {
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 === 1 && 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);
}
/**
* 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 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);
}
const messageText = lodashGet(reportAction, ['message', 0, 'text'], '');
// 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
unreadActionCount: newMaxSequenceNumber - (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 = 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: isReportMessageAttachment(messageText),
loading: false,
};
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, reportActionsToMerge);
// If chat report receives an action with IOU, update IOU object
if (reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.IOU) {
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()) {
console.debug('[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
console.debug(`[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) {
console.debug('[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()) {
console.debug('[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);
}
console.debug('[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}`;
}
/**
* 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.
Pusher.subscribe(pusherChannelName, Pusher.TYPE.REPORT_COMMENT, (pushJSON) => {
Log.info(
`[Report] Handled ${Pusher.TYPE.REPORT_COMMENT} event sent by Pusher`, true, {reportID: pushJSON.reportID},
);
updateReportWithNewAction(pushJSON.reportID, pushJSON.reportAction, pushJSON.notificationPreference);
}, false,
() => {
NetworkConnection.triggerReconnectionCallbacks('pusher re-subscribed to private user channel');
})
.catch((error) => {
Log.info(
'[Report] Failed to subscribe to Pusher channel',
true,
{error, pusherChannelName, eventName: Pusher.TYPE.REPORT_COMMENT},
);
});
// Live-update a report's actions when an 'edit comment' event is received.
Pusher.subscribe(pusherChannelName, Pusher.TYPE.REPORT_COMMENT_EDIT, (pushJSON) => {
Log.info(
`[Report] Handled ${Pusher.TYPE.REPORT_COMMENT_EDIT} event sent by Pusher`, true, {
reportActionID: pushJSON.reportActionID,
},
);
updateReportActionMessage(pushJSON.reportID, pushJSON.sequenceNumber, pushJSON.message);
}, false,
() => {
NetworkConnection.triggerReconnectionCallbacks('pusher re-subscribed to private user channel');
})
.catch((error) => {
Log.info(
'[Report] Failed to subscribe to Pusher channel',
true,
{error, pusherChannelName, eventName: Pusher.TYPE.REPORT_COMMENT_EDIT},
);
});
// Live-update a report's pinned state when a 'report toggle pinned' event is received.
Pusher.subscribe(pusherChannelName, Pusher.TYPE.REPORT_TOGGLE_PINNED, (pushJSON) => {
Log.info(
`[Report] Handled ${Pusher.TYPE.REPORT_TOGGLE_PINNED} event sent by Pusher`,
true,
{reportID: pushJSON.reportID},
);
updateReportPinnedState(pushJSON.reportID, pushJSON.isPinned);
}, false,
() => {
NetworkConnection.triggerReconnectionCallbacks('pusher re-subscribed to private user channel');
})
.catch((error) => {
Log.info(
'[Report] Failed to subscribe to Pusher channel',
true,
{error, pusherChannelName, eventName: Pusher.TYPE.REPORT_TOGGLE_PINNED},
);
});
PushNotification.onReceived(PushNotification.TYPE.REPORT_COMMENT, ({reportID, reportAction}) => {
Log.info('[Report] Handled event sent by Airship', true, {reportID});
updateReportWithNewAction(reportID, reportAction);
});
// Open correct report when push notification is clicked
PushNotification.onSelected(PushNotification.TYPE.REPORT_COMMENT, ({reportID}) => {
Navigation.navigate(ROUTES.getReportRoute(reportID));
});
}
/**
* There are 2 possibilities that we can receive via pusher for a user's typing status:
* 1. The "new" way from e.cash 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', true, {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<Number[]>}
*/
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);
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 the reportID here since fetchAllReports calls this method or
// fetchChatReportsByIDs which returns an array of reportIDs.
return [data.reportID];
});
}
/**
* 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', true, {
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');
const maxSequenceNumber = _.chain(data.history)
.pluck('sequenceNumber')
.max()
.value();
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, indexedData);
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {maxSequenceNumber});
});
}
/**
* 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,
) {
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 = String(response.chatList)
.split(',')
.filter(_.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((returnedReportIDs) => {
Onyx.set(ONYXKEYS.INITIAL_REPORT_DATA_LOADED, true);
if (shouldRecordHomePageTiming) {
Timing.end(CONST.TIMING.HOMEPAGE_REPORTS_LOADED);
}
// Delay fetching report history as it significantly increases sign in to interactive time.
// Register the timer so we can clean it up if the user quickly logs out after logging in. If we don't
// cancel the timer we'll make unnecessary API requests from the sign in page.
Timers.register(setTimeout(() => {
// Filter reports to see which ones have actions we need to fetch so we can preload Onyx with new
// content and improve chat switching experience by only downloading content we don't have yet.
// This improves performance significantly when reconnecting by limiting API requests and unnecessary
// data processing by Onyx.
const reportIDsToFetchActions = _.filter(returnedReportIDs, id => (
isReportMissingActions(id, reportMaxSequenceNumbers[id])
));
if (_.isEmpty(reportIDsToFetchActions)) {
console.debug('[Report] Local reportActions up to date. Not fetching additional actions.');
return;
}
console.debug('[Report] Fetching reportActions for reportIDs: ', {
reportIDs: reportIDsToFetchActions,
});
_.each(reportIDsToFetchActions, (reportID) => {
const offset = dangerouslyGetReportActionsMaxSequenceNumber(reportID, false);
fetchActions(reportID, offset);
});
// We are waiting a set amount of time to allow the UI to finish loading before bogging it down with
// more requests and operations. Startup delay is longer since there is a lot more work done to build
// up the UI when the app first initializes.
}, shouldDelayActionsFetch ? CONST.FETCH_ACTIONS_DELAY.STARTUP : CONST.FETCH_ACTIONS_DELAY.RECONNECT));
});
}
/**
* Add an action item to a report
*
* @param {Number} reportID
* @param {String} text
* @param {Object} [file]
*/
function addAction(reportID, text, file) {
// Convert the comment from MD into HTML because that's how it is stored in the database
const parser = new ExpensiMark();
const commentText = parser.replace(text);
const isAttachment = _.isEmpty(text) && file !== undefined;
// The new sequence number will be one higher than the highest
const highestSequenceNumber = reportMaxSequenceNumbers[reportID] || 0;
const newSequenceNumber = highestSequenceNumber + 1;
const htmlForNewComment = isAttachment ? 'Uploading Attachment...' : commentText;
// Remove HTML from text when applying optimistic offline comment
const textForNewComment = isAttachment ? '[Attachment]'
: htmlForNewComment.replace(/<[^>]*>?/gm, '');
// Update the report in Onyx to have the new sequence number
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {
maxSequenceNumber: newSequenceNumber,
lastMessageTimestamp: moment().unix(),
lastMessageText: textForNewComment,
lastActorEmail: currentUserEmail,
});
// Generate a clientID so we can save the optimistic action to storage with the clientID as key. Later, we will
// remove the optimistic action when we add the real action created in the server. We do this because it's not
// safe to assume that this will use the very next sequenceNumber. An action created by another can overwrite that
// sequenceNumber if it is created before this one. We use a combination of current epoch timestamp (milliseconds)
// and a random number so that the probability of someone else having the same optimisticReportActionID is
// extremely low even if they left the comment at the same moment as another user on the same report. The random
// number is 3 digits because if we go any higher JS will convert the digits after the 16th position to 0's in
// optimisticReportActionID.
const randomNumber = Math.floor((Math.random() * (999 - 100)) + 100);
const optimisticReportActionID = parseInt(`${Date.now()}${randomNumber}`, 10);
// Store the optimistic action ID on the report the comment was added to. It will be removed later when refetching
// report actions in order to clear out any stuck actions (i.e. actions where the client never received a Pusher
// event, for whatever reason, from the server with the new action data
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {
optimisticReportActionIDs: [...(optimisticReportActionIDs[reportID] || []), optimisticReportActionID],
});
// Optimistically add the new comment to the store before waiting to save it to the server
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, {
[optimisticReportActionID]: {
actionName: 'ADDCOMMENT',
actorEmail: currentUserEmail,
actorAccountID: currentUserAccountID,
person: [
{
style: 'strong',
text: myPersonalDetails.displayName || currentUserEmail,
type: 'TEXT',
},
],
automatic: false,
// Use the client generated ID as a optimistic action ID so we can remove it later