-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
Report.js
1225 lines (1112 loc) · 40.7 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 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 Navigation from '../Navigation/Navigation';
import * as ActiveClientManager from '../ActiveClientManager';
import Visibility from '../Visibility';
import ROUTES from '../../ROUTES';
import * as API from '../API';
import CONFIG from '../../CONFIG';
import CONST from '../../CONST';
import Log from '../Log';
import * as ReportUtils from '../ReportUtils';
import DateUtils from '../DateUtils';
import * as ReportActionsUtils from '../ReportActionsUtils';
import * as OptionsListUtils from '../OptionsListUtils';
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;
},
});
const allReports = {};
let conciergeChatReportID;
const typingWatchTimers = {};
/**
* @param {String} reportID
* @returns {Number}
*/
function getMaxSequenceNumber(reportID) {
return lodashGet(allReports, [reportID, 'maxSequenceNumber'], 0);
}
/**
* Get the private pusher channel name for a Report.
*
* @param {String} reportID
* @returns {String}
*/
function getReportChannelName(reportID) {
return `${CONST.PUSHER.PRIVATE_REPORT_CHANNEL_PREFIX}${reportID}${CONFIG.PUSHER.SUFFIX}`;
}
/**
* Setup reportComment push notification callbacks.
*/
function subscribeToReportCommentPushNotifications() {
PushNotification.onReceived(PushNotification.TYPE.REPORT_COMMENT, ({reportID, onyxData}) => {
Log.info('[Report] Handled event sent by Airship', false, {reportID});
Onyx.update(onyxData);
});
// Open correct report when push notification is clicked
PushNotification.onSelected(PushNotification.TYPE.REPORT_COMMENT, ({reportID}) => {
if (Navigation.canNavigate('navigate')) {
// If a chat is visible other than the one we are trying to navigate to, then we need to navigate back
if (Navigation.getActiveRoute().slice(1, 2) === ROUTES.REPORT && !Navigation.isActiveRoute(`r/${reportID}`)) {
Navigation.goBack();
}
Navigation.navigate(ROUTES.getReportRoute(reportID));
} else {
// Navigation container is not yet ready, use deeplinking to open to correct report instead
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 {String} 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.hmmm('[Report] Failed to initially subscribe to Pusher channel', false, {errorType: error.type, pusherChannelName});
});
}
/**
* Remove our pusher subscriptions to listen for someone typing in a report.
*
* @param {String} reportID
*/
function unsubscribeFromReportChannel(reportID) {
if (!reportID) {
return;
}
const pusherChannelName = getReportChannelName(reportID);
Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_USER_IS_TYPING}${reportID}`, {});
Pusher.unsubscribe(pusherChannelName);
}
/**
* Add up to two report actions to a report. This method can be called for the following situations:
*
* - Adding one comment
* - Adding one attachment
* - Add both a comment and attachment simultaneously
*
* @param {String} reportID
* @param {String} [text]
* @param {Object} [file]
*/
function addActions(reportID, text = '', file) {
let reportCommentText = '';
let reportCommentAction;
let attachmentAction;
let commandName = 'AddComment';
const highestSequenceNumber = getMaxSequenceNumber(reportID);
if (text) {
const nextSequenceNumber = highestSequenceNumber + 1;
const reportComment = ReportUtils.buildOptimisticReportAction(nextSequenceNumber, text);
reportCommentAction = reportComment.reportAction;
reportCommentText = reportComment.commentText;
}
if (file) {
const nextSequenceNumber = (text && file) ? highestSequenceNumber + 2 : highestSequenceNumber + 1;
// When we are adding an attachment we will call AddAttachment.
// It supports sending an attachment with an optional comment and AddComment supports adding a single text comment only.
commandName = 'AddAttachment';
const attachment = ReportUtils.buildOptimisticReportAction(nextSequenceNumber, '', file);
attachmentAction = attachment.reportAction;
}
// Always prefer the file as the last action over text
const lastAction = attachmentAction || reportCommentAction;
// Our report needs a new maxSequenceNumber that is n larger than the current depending on how many actions we are adding.
const actionCount = text && file ? 2 : 1;
const newSequenceNumber = highestSequenceNumber + actionCount;
const currentTime = DateUtils.getDBTime();
// Update the report in Onyx to have the new sequence number
const optimisticReport = {
maxSequenceNumber: newSequenceNumber,
lastActionCreated: currentTime,
lastMessageText: ReportUtils.formatReportLastMessageText(lastAction.message[0].text),
lastActorEmail: currentUserEmail,
lastReadSequenceNumber: newSequenceNumber,
lastReadTime: currentTime,
};
// Optimistically add the new actions to the store before waiting to save them to the server. We use the clientID
// so that we can later unset these messages via the server by sending {[clientID]: null}
const optimisticReportActions = {};
if (text) {
optimisticReportActions[reportCommentAction.clientID] = reportCommentAction;
}
if (file) {
optimisticReportActions[attachmentAction.clientID] = attachmentAction;
}
const parameters = {
reportID,
reportActionID: file ? attachmentAction.reportActionID : reportCommentAction.reportActionID,
commentReportActionID: file && reportCommentAction ? reportCommentAction.reportActionID : null,
reportComment: reportCommentText,
clientID: lastAction.clientID,
commentClientID: lodashGet(reportCommentAction, 'clientID', ''),
file,
};
const optimisticData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
value: optimisticReport,
},
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`,
value: optimisticReportActions,
},
];
// Update the timezone if it's been 5 minutes from the last time the user added a comment
if (DateUtils.canUpdateTimezone()) {
const timezone = DateUtils.getCurrentTimezone();
parameters.timezone = JSON.stringify(timezone);
optimisticData.push({
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.PERSONAL_DETAILS,
value: {[currentUserEmail]: {timezone}},
});
DateUtils.setTimezoneUpdated();
}
API.write(commandName, parameters, {
optimisticData,
});
}
/**
*
* Add an attachment and optional comment.
*
* @param {String} reportID
* @param {File} file
* @param {String} [text]
*/
function addAttachment(reportID, file, text = '') {
addActions(reportID, text, file);
}
/**
* Add a single comment to a report
*
* @param {String} reportID
* @param {String} text
*/
function addComment(reportID, text) {
addActions(reportID, text);
}
/**
* Gets the latest page of report actions and updates the last read message
* If a chat with the passed reportID is not found, we will create a chat based on the passed participantList
*
* @param {String} reportID
* @param {Array} participantList The list of users that are included in a new chat, not including the user creating it
* @param {Object} newReportObject The optimistic report object created when making a new chat, saved as optimistic data
*/
function openReport(reportID, participantList = [], newReportObject = {}) {
const onyxData = {
optimisticData: [{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
value: {
isLoadingReportActions: true,
isLoadingMoreReportActions: false,
lastReadTime: DateUtils.getDBTime(),
lastReadSequenceNumber: getMaxSequenceNumber(reportID),
reportName: lodashGet(allReports, [reportID, 'reportName'], CONST.REPORT.DEFAULT_REPORT_NAME),
},
}],
successData: [{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
value: {
isLoadingReportActions: false,
pendingFields: {
createChat: null,
},
errorFields: {
createChat: null,
},
isOptimisticReport: false,
},
}],
};
const params = {
reportID,
emailList: participantList ? participantList.join(',') : '',
};
// If we are creating a new report, we need to add the optimistic report data and a report action
if (!_.isEmpty(newReportObject)) {
// Change the method to set for new reports because it doesn't exist yet, is faster,
// and we need the data to be available when we navigate to the chat page
onyxData.optimisticData[0].onyxMethod = CONST.ONYX.METHOD.SET;
const optimisticCreatedActionData = ReportUtils.buildOptimisticCreatedReportAction(newReportObject.ownerEmail);
onyxData.optimisticData[1] = {
onyxMethod: CONST.ONYX.METHOD.SET,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`,
value: optimisticCreatedActionData,
};
onyxData.optimisticData[0].value = {
...onyxData.optimisticData[0].value,
...newReportObject,
pendingFields: {
createChat: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
},
isOptimisticReport: true,
};
// Add the createdReportActionID parameter to the API call
params.createdReportActionID = optimisticCreatedActionData[0].reportActionID;
}
API.write('OpenReport', params, onyxData);
}
/**
* This will find an existing chat, or create a new one if none exists, for the given user or set of users. It will then navigate to this chat.
*
* @param {Array} userLogins list of user logins.
*/
function navigateToAndOpenReport(userLogins) {
const formattedUserLogins = _.map(userLogins, login => OptionsListUtils.addSMSDomainIfPhoneNumber(login).toLowerCase());
let newChat = {};
const chat = ReportUtils.getChatByParticipants(formattedUserLogins);
if (!chat) {
newChat = ReportUtils.buildOptimisticChatReport(formattedUserLogins);
}
const reportID = chat ? chat.reportID : newChat.reportID;
// We want to pass newChat here because if anything is passed in that param (even an existing chat), we will try to create a chat on the server
openReport(reportID, newChat.participants, newChat);
Navigation.navigate(ROUTES.getReportRoute(reportID));
}
/**
* Get the latest report history without marking the report as read.
*
* @param {String} reportID
*/
function reconnect(reportID) {
API.write('ReconnectToReport',
{reportID},
{
optimisticData: [{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
value: {
isLoadingReportActions: true,
isLoadingMoreReportActions: false,
},
}],
successData: [{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
value: {
isLoadingReportActions: false,
},
}],
failureData: [{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
value: {
isLoadingReportActions: false,
},
}],
});
}
/**
* Gets the older actions that have not been read yet.
* Normally happens when you scroll up on a chat, and the actions have not been read yet.
*
* @param {String} reportID
* @param {Number} oldestActionSequenceNumber
*/
function readOldestAction(reportID, oldestActionSequenceNumber) {
API.read('ReadOldestAction',
{
reportID,
reportActionsOffset: oldestActionSequenceNumber,
},
{
optimisticData: [{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
value: {
isLoadingMoreReportActions: true,
},
}],
successData: [{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
value: {
isLoadingMoreReportActions: false,
},
}],
failureData: [{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
value: {
isLoadingMoreReportActions: false,
},
}],
});
}
/**
* Gets the IOUReport and the associated report actions.
*
* @param {String} chatReportID
* @param {Number} iouReportID
*/
function openPaymentDetailsPage(chatReportID, iouReportID) {
API.read('OpenPaymentDetailsPage', {
reportID: chatReportID,
iouReportID,
}, {
optimisticData: [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.IOU,
value: {
loading: true,
},
},
],
successData: [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.IOU,
value: {
loading: false,
},
},
],
failureData: [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.IOU,
value: {
loading: false,
},
},
],
});
}
/**
* Marks the new report actions as read
*
* @param {String} reportID
*/
function readNewestAction(reportID) {
API.write('ReadNewestAction',
{
reportID,
},
{
optimisticData: [{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
value: {
lastReadTime: DateUtils.getDBTime(),
},
}],
});
}
/**
* Sets the last read time on a report
*
* @param {String} reportID
* @param {String} reportActionCreated
*/
function markCommentAsUnread(reportID, reportActionCreated) {
// We subtract 1 millisecond so that the lastReadTime is updated to just before a given reportAction's created date
// For example, if we want to mark a report action with ID 100 and created date '2014-04-01 16:07:02.999' unread, we set the lastReadTime to '2014-04-01 16:07:02.998'
// Since the report action with ID 100 will be the first with a timestamp above '2014-04-01 16:07:02.998', it's the first one that will be shown as unread
const lastReadTime = DateUtils.subtractMillisecondsFromDateTime(reportActionCreated, 1);
API.write('MarkAsUnread',
{
reportID,
lastReadTime,
},
{
optimisticData: [{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
value: {
lastReadTime,
},
}],
});
}
/**
* Toggles the pinned state of the report.
*
* @param {Object} report
*/
function togglePinnedState(report) {
const pinnedValue = !report.isPinned;
// Optimistically pin/unpin the report before we send out the command
const optimisticData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${report.reportID}`,
value: {isPinned: pinnedValue},
},
];
API.write('TogglePinnedChat', {
reportID: report.reportID,
pinnedValue,
}, {optimisticData});
}
/**
* Saves the comment left by the user as they are typing. By saving this data the user can switch between chats, close
* tab, refresh etc without worrying about loosing what they typed out.
*
* @param {String} reportID
* @param {String} comment
*/
function saveReportComment(reportID, comment) {
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT}${reportID}`, comment);
}
/**
* Immediate indication whether the report has a draft comment.
*
* @param {String} reportID
* @param {Boolean} hasDraft
* @returns {Promise}
*/
function setReportWithDraft(reportID, hasDraft) {
return Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {hasDraft});
}
/**
* Broadcasts whether or not a user is typing on a report over the report's private pusher channel.
*
* @param {String} reportID
*/
function broadcastUserIsTyping(reportID) {
const privateReportChannelName = getReportChannelName(reportID);
const typingStatus = {};
typingStatus[currentUserEmail] = true;
Pusher.sendEvent(privateReportChannelName, 'client-userIsTyping', typingStatus);
}
/**
* When a report changes in Onyx, this fetches the report from the API if the report doesn't have a name
* and it keeps track of the max sequence number on the report actions.
*
* @param {Object} report
*/
function handleReportChanged(report) {
if (!report || ReportUtils.isIOUReport(report)) {
return;
}
if (report && report.reportID) {
allReports[report.reportID] = report;
if (ReportUtils.isConciergeChatReport(report)) {
conciergeChatReportID = report.reportID;
}
}
// A report can be missing a name if a comment is received via pusher event
// and the report does not yet exist in Onyx (eg. a new DM created with the logged in person)
if (report.reportID && report.reportName === undefined) {
openReport(report.reportID);
}
}
Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT,
callback: handleReportChanged,
});
/**
* Deletes a comment from the report, basically sets it as empty string
*
* @param {String} reportID
* @param {Object} reportAction
*/
function deleteReportComment(reportID, reportAction) {
const sequenceNumber = reportAction.sequenceNumber;
const deletedMessage = [{
type: 'COMMENT',
html: '',
text: '',
isEdited: true,
}];
const optimisticReportActions = {
[sequenceNumber]: {
pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE,
previousMessage: reportAction.message,
message: deletedMessage,
},
};
// If we are deleting the last visible message, let's find the previous visible one and update the lastMessageText in the LHN.
// Similarly, if we are deleting the last read comment we will want to update the lastActionCreated to use the previous visible message.
const lastMessageText = ReportActionsUtils.getLastVisibleMessageText(reportID, optimisticReportActions);
const lastActionCreated = ReportActionsUtils.getLastVisibleAction(reportID, optimisticReportActions).created;
const optimisticReport = {
lastMessageText,
lastActionCreated,
};
// If the API call fails we must show the original message again, so we revert the message content back to how it was
// and and remove the pendingAction so the strike-through clears
const failureData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`,
value: {
[sequenceNumber]: {
message: reportAction.message,
pendingAction: null,
previousMessage: null,
},
},
},
];
const successData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`,
value: {
[sequenceNumber]: {
pendingAction: null,
previousMessage: null,
},
},
},
];
const optimisticData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`,
value: optimisticReportActions,
},
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
value: optimisticReport,
},
];
const parameters = {
reportID,
sequenceNumber,
reportActionID: reportAction.reportActionID,
};
API.write('DeleteComment', parameters, {optimisticData, successData, failureData});
}
/**
* @param {String} comment
* @returns {Array}
*/
const extractLinksInMarkdownComment = (comment) => {
const regex = /\[[^[\]]*\]\(([^()]*)\)/gm;
const matches = [...comment.matchAll(regex)];
// Element 1 from match is the regex group if it exists which contains the link URLs
const links = _.map(matches, match => match[1]);
return links;
};
/**
* Compares two markdown comments and returns a list of the links removed in a new comment.
*
* @param {String} oldComment
* @param {String} newComment
* @returns {Array}
*/
const getRemovedMarkdownLinks = (oldComment, newComment) => {
const linksInOld = extractLinksInMarkdownComment(oldComment);
const linksInNew = extractLinksInMarkdownComment(newComment);
return _.difference(linksInOld, linksInNew);
};
/**
* Removes the links in a markdown comment.
* example:
* comment="test [link](https://www.google.com) test",
* links=["https://www.google.com"]
* returns: "test link test"
* @param {String} comment
* @param {Array} links
* @returns {String}
*/
const removeLinks = (comment, links) => {
let commentCopy = comment.slice();
_.forEach(links, (link) => {
const regex = new RegExp(`\\[([^\\[\\]]*)\\]\\(${link}\\)`, 'gm');
const linkMatch = regex.exec(commentCopy);
const linkText = linkMatch && linkMatch[1];
commentCopy = commentCopy.replace(`[${linkText}](${link})`, linkText);
});
return commentCopy;
};
/**
* This function will handle removing only links that were purposely removed by the user while editing.
* @param {String} newCommentText text of the comment after editing.
* @param {Array} originalHtml original html of the comment before editing
* @returns {String}
*/
const handleUserDeletedLinks = (newCommentText, originalHtml) => {
const parser = new ExpensiMark();
const htmlWithAutoLinks = parser.replace(newCommentText);
const markdownWithAutoLinks = parser.htmlToMarkdown(htmlWithAutoLinks);
const markdownOriginalComment = parser.htmlToMarkdown(originalHtml);
const removedLinks = getRemovedMarkdownLinks(markdownOriginalComment, newCommentText);
return removeLinks(markdownWithAutoLinks, removedLinks);
};
/**
* Saves a new message for a comment. Marks the comment as edited, which will be reflected in the UI.
*
* @param {String} reportID
* @param {Object} originalReportAction
* @param {String} textForNewComment
*/
function editReportComment(reportID, originalReportAction, textForNewComment) {
const parser = new ExpensiMark();
// Do not autolink if someone explicitly tries to remove a link from message.
// https://github.com/Expensify/App/issues/9090
// https://github.com/Expensify/App/issues/13221
const originalCommentHTML = lodashGet(originalReportAction, 'message[0].html');
const markdownForNewComment = handleUserDeletedLinks(textForNewComment, originalCommentHTML);
const autolinkFilter = {filterRules: _.filter(_.pluck(parser.rules, 'name'), name => name !== 'autolink')};
const htmlForNewComment = parser.replace(markdownForNewComment, autolinkFilter);
const parsedOriginalCommentHTML = parser.replace(parser.htmlToMarkdown(originalCommentHTML), autolinkFilter);
// Delete the comment if it's empty
if (_.isEmpty(htmlForNewComment)) {
deleteReportComment(reportID, originalReportAction);
return;
}
// Skip the Edit if message is not changed
if (parsedOriginalCommentHTML === htmlForNewComment.trim()) {
return;
}
// Optimistically update the reportAction with the new message
const sequenceNumber = originalReportAction.sequenceNumber;
const optimisticReportActions = {
[sequenceNumber]: {
pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE,
message: [{
isEdited: true,
html: htmlForNewComment,
text: markdownForNewComment,
type: originalReportAction.message[0].type,
}],
},
};
const optimisticData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`,
value: optimisticReportActions,
},
];
const failureData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`,
value: {
[sequenceNumber]: {
...originalReportAction,
pendingAction: null,
},
},
},
];
const successData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`,
value: {
[sequenceNumber]: {
pendingAction: null,
},
},
},
];
const parameters = {
reportID,
sequenceNumber,
reportComment: htmlForNewComment,
reportActionID: originalReportAction.reportActionID,
};
API.write('UpdateComment', parameters, {optimisticData, successData, failureData});
}
/**
* Saves the draft for a comment report action. This will put the comment into "edit mode"
*
* @param {String} reportID
* @param {Number} reportActionID
* @param {String} draftMessage
*/
function saveReportActionDraft(reportID, reportActionID, draftMessage) {
Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${reportID}_${reportActionID}`, draftMessage);
}
/**
* @param {String} reportID
* @param {String} previousValue
* @param {String} newValue
*/
function updateNotificationPreference(reportID, previousValue, newValue) {
const optimisticData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
value: {notificationPreference: newValue},
},
];
const failureData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
value: {notificationPreference: previousValue},
},
];
API.write('UpdateReportNotificationPreference', {reportID, notificationPreference: newValue}, {optimisticData, failureData});
}
/**
* Navigates to the 1:1 report with Concierge
*/
function navigateToConciergeChat() {
// If we don't have a chat with Concierge then create it
if (!conciergeChatReportID) {
navigateToAndOpenReport([CONST.EMAIL.CONCIERGE]);
return;
}
Navigation.navigate(ROUTES.getReportRoute(conciergeChatReportID));
}
/**
* Add a policy report (workspace room) optimistically and navigate to it.
*
* @param {Object} policy
* @param {String} reportName
* @param {String} visibility
*/
function addPolicyReport(policy, reportName, visibility) {
// The participants include the current user (admin) and the employees. Participants must not be empty.
const participants = _.unique([currentUserEmail, ..._.pluck(policy.employeeList, 'email')]);
const policyReport = ReportUtils.buildOptimisticChatReport(
participants,
reportName,
CONST.REPORT.CHAT_TYPE.POLICY_ROOM,
policy.id,
CONST.REPORT.OWNER_EMAIL_FAKE,
false,
'',
visibility,
// The room might contain all policy members so notifying always should be opt-in only.
CONST.REPORT.NOTIFICATION_PREFERENCE.DAILY,
);
const createdReportAction = ReportUtils.buildOptimisticCreatedReportAction(policyReport.ownerEmail);
// Onyx.set is used on the optimistic data so that it is present before navigating to the workspace room. With Onyx.merge the workspace room reportID is not present when
// fetchReportIfNeeded is called on the ReportScreen, so openReport is called which is unnecessary since the optimistic data will be stored in Onyx.
// Therefore, Onyx.set is used instead of Onyx.merge.
const optimisticData = [
{
onyxMethod: CONST.ONYX.METHOD.SET,
key: `${ONYXKEYS.COLLECTION.REPORT}${policyReport.reportID}`,
value: {
pendingFields: {
addWorkspaceRoom: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
},
...policyReport,
},
},
{
onyxMethod: CONST.ONYX.METHOD.SET,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${policyReport.reportID}`,
value: createdReportAction,
},
];
const successData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${policyReport.reportID}`,
value: {
pendingFields: {
addWorkspaceRoom: null,
},
},
},
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${policyReport.reportID}`,
value: {
0: {
pendingAction: null,
},
},
},
];
API.write(
'AddWorkspaceRoom',
{
policyID: policyReport.policyID,
reportName,
visibility,
reportID: policyReport.reportID,
createdReportActionID: createdReportAction.reportActionID,
},
{optimisticData, successData},
);
Navigation.navigate(ROUTES.getReportRoute(policyReport.reportID));
}
/**
* @param {String} reportID The reportID of the policy report (workspace room)
*/
function navigateToConciergeChatAndDeleteReport(reportID) {
navigateToConciergeChat();
Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, null);
Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, null);
}
/**
* @param {Object} policyRoomReport
* @param {Number} policyRoomReport.reportID