forked from Expensify/App
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTransaction.ts
556 lines (506 loc) · 21.9 KB
/
Transaction.ts
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
import {getUnixTime} from 'date-fns';
import lodashClone from 'lodash/clone';
import lodashHas from 'lodash/has';
import isEqual from 'lodash/isEqual';
import type {OnyxCollection, OnyxEntry, OnyxUpdate} from 'react-native-onyx';
import Onyx from 'react-native-onyx';
import * as API from '@libs/API';
import type {DismissViolationParams, GetRouteParams, MarkAsCashParams} from '@libs/API/parameters';
import {READ_COMMANDS, WRITE_COMMANDS} from '@libs/API/types';
import * as CollectionUtils from '@libs/CollectionUtils';
import * as NumberUtils from '@libs/NumberUtils';
import * as ReportActionsUtils from '@libs/ReportActionsUtils';
import {buildOptimisticDismissedViolationReportAction} from '@libs/ReportUtils';
import * as TransactionUtils from '@libs/TransactionUtils';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {PersonalDetails, RecentWaypoint, ReportAction, ReportActions, ReviewDuplicates, Transaction, TransactionViolation, TransactionViolations} from '@src/types/onyx';
import type {OnyxData} from '@src/types/onyx/Request';
import type {WaypointCollection} from '@src/types/onyx/Transaction';
import type TransactionState from '@src/types/utils/TransactionStateType';
let recentWaypoints: RecentWaypoint[] = [];
Onyx.connect({
key: ONYXKEYS.NVP_RECENT_WAYPOINTS,
callback: (val) => (recentWaypoints = val ?? []),
});
const allTransactions: Record<string, Transaction> = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.TRANSACTION,
callback: (transaction, key) => {
if (!key || !transaction) {
return;
}
const transactionID = CollectionUtils.extractCollectionItemID(key);
allTransactions[transactionID] = transaction;
},
});
const allTransactionViolation: OnyxCollection<TransactionViolation[]> = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS,
callback: (transactionViolation, key) => {
if (!key || !transactionViolation) {
return;
}
const transactionID = CollectionUtils.extractCollectionItemID(key);
allTransactionViolation[transactionID] = transactionViolation;
},
});
let allTransactionViolations: TransactionViolations = [];
Onyx.connect({
key: ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS,
callback: (val) => (allTransactionViolations = val ?? []),
});
function createInitialWaypoints(transactionID: string) {
Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {
comment: {
waypoints: {
waypoint0: {},
waypoint1: {},
},
},
});
}
/**
* Add a stop to the transaction
*/
function addStop(transactionID: string) {
const transaction = allTransactions?.[transactionID] ?? {};
const existingWaypoints = transaction?.comment?.waypoints ?? {};
const newLastIndex = Object.keys(existingWaypoints).length;
Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {
comment: {
waypoints: {
[`waypoint${newLastIndex}`]: {},
},
},
});
}
function saveWaypoint(transactionID: string, index: string, waypoint: RecentWaypoint | null, isDraft = false) {
Onyx.merge(`${isDraft ? ONYXKEYS.COLLECTION.TRANSACTION_DRAFT : ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {
comment: {
waypoints: {
[`waypoint${index}`]: waypoint,
},
customUnit: {
quantity: null,
},
},
// We want to reset the amount only for draft transactions (when creating the expense).
// When modifying an existing transaction, the amount will be updated on the actual IOU update operation.
...(isDraft && {amount: CONST.IOU.DEFAULT_AMOUNT}),
// Empty out errors when we're saving a new waypoint as this indicates the user is updating their input
errorFields: {
route: null,
},
// Clear the existing route so that we don't show an old route
routes: {
route0: {
// Clear the existing distance to recalculate next time
distance: null,
geometry: {
coordinates: null,
},
},
},
});
// You can save offline waypoints without verifying the address (we will geocode it on the backend)
// We're going to prevent saving those addresses in the recent waypoints though since they could be invalid addresses
// However, in the backend once we verify the address, we will save the waypoint in the recent waypoints NVP
if (!lodashHas(waypoint, 'lat') || !lodashHas(waypoint, 'lng')) {
return;
}
// If current location is used, we would want to avoid saving it as a recent waypoint. This prevents the 'Your Location'
// text from showing up in the address search suggestions
if (isEqual(waypoint?.address, CONST.YOUR_LOCATION_TEXT)) {
return;
}
const recentWaypointAlreadyExists = recentWaypoints.find((recentWaypoint) => recentWaypoint?.address === waypoint?.address);
if (!recentWaypointAlreadyExists && waypoint !== null) {
const clonedWaypoints = lodashClone(recentWaypoints);
const updatedWaypoint = {...waypoint, pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD};
clonedWaypoints.unshift(updatedWaypoint);
Onyx.merge(ONYXKEYS.NVP_RECENT_WAYPOINTS, clonedWaypoints.slice(0, CONST.RECENT_WAYPOINTS_NUMBER));
}
}
function removeWaypoint(transaction: OnyxEntry<Transaction>, currentIndex: string, isDraft?: boolean): Promise<void | void[]> {
// Index comes from the route params and is a string
const index = Number(currentIndex);
if (index === -1) {
return Promise.resolve();
}
const existingWaypoints = transaction?.comment?.waypoints ?? {};
const totalWaypoints = Object.keys(existingWaypoints).length;
const waypointValues = Object.values(existingWaypoints);
const removed = waypointValues.splice(index, 1);
if (removed.length === 0) {
return Promise.resolve();
}
const isRemovedWaypointEmpty = removed.length > 0 && !TransactionUtils.waypointHasValidAddress(removed.at(0) ?? {});
// When there are only two waypoints we are adding empty waypoint back
if (totalWaypoints === 2 && (index === 0 || index === totalWaypoints - 1)) {
waypointValues.splice(index, 0, {});
}
const reIndexedWaypoints: WaypointCollection = {};
waypointValues.forEach((waypoint, idx) => {
reIndexedWaypoints[`waypoint${idx}`] = waypoint;
});
// Onyx.merge won't remove the null nested object values, this is a workaround
// to remove nested keys while also preserving other object keys
// Doing a deep clone of the transaction to avoid mutating the original object and running into a cache issue when using Onyx.set
let newTransaction: Transaction = {
// eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style
...(transaction as Transaction),
comment: {
...transaction?.comment,
waypoints: reIndexedWaypoints,
customUnit: {
...transaction?.comment?.customUnit,
quantity: null,
},
},
// We want to reset the amount only for draft transactions (when creating the expense).
// When modifying an existing transaction, the amount will be updated on the actual IOU update operation.
...(isDraft && {amount: CONST.IOU.DEFAULT_AMOUNT}),
};
if (!isRemovedWaypointEmpty) {
newTransaction = {
...newTransaction,
// Clear any errors that may be present, which apply to the old route
errorFields: {
route: null,
},
// Clear the existing route so that we don't show an old route
routes: {
route0: {
// Clear the existing distance to recalculate next time
distance: null,
geometry: {
coordinates: null,
},
},
},
};
}
if (isDraft) {
return Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transaction?.transactionID}`, newTransaction);
}
return Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction?.transactionID}`, newTransaction);
}
function getOnyxDataForRouteRequest(transactionID: string, transactionState: TransactionState = CONST.TRANSACTION.STATE.CURRENT): OnyxData {
let keyPrefix;
switch (transactionState) {
case CONST.TRANSACTION.STATE.DRAFT:
keyPrefix = ONYXKEYS.COLLECTION.TRANSACTION_DRAFT;
break;
case CONST.TRANSACTION.STATE.BACKUP:
keyPrefix = ONYXKEYS.COLLECTION.TRANSACTION_BACKUP;
break;
case CONST.TRANSACTION.STATE.CURRENT:
default:
keyPrefix = ONYXKEYS.COLLECTION.TRANSACTION;
break;
}
return {
optimisticData: [
{
// Clears any potentially stale error messages from fetching the route
onyxMethod: Onyx.METHOD.MERGE,
key: `${keyPrefix}${transactionID}`,
value: {
comment: {
isLoading: true,
},
errorFields: {
route: null,
},
},
},
],
// The route and failure are sent back via pusher in the BE, we are just clearing the loading state here
successData: [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${keyPrefix}${transactionID}`,
value: {
comment: {
isLoading: false,
},
// When the user opens the distance request editor and changes the connection from offline to online,
// the transaction's pendingFields and pendingAction will be removed, but not transactionBackup.
// We clear the pendingFields and pendingAction for the backup here to ensure consistency with the transaction.
// Without this, the map will not be clickable if the user dismisses the distance request editor without saving.
...(transactionState === CONST.TRANSACTION.STATE.BACKUP && {
pendingFields: {waypoints: null},
pendingAction: null,
}),
},
},
],
failureData: [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${keyPrefix}${transactionID}`,
value: {
comment: {
isLoading: false,
},
},
},
],
};
}
/**
* Sanitizes the waypoints by removing the pendingAction property.
*
* @param waypoints - The collection of waypoints to sanitize.
* @returns The sanitized collection of waypoints.
*/
function sanitizeRecentWaypoints(waypoints: WaypointCollection): WaypointCollection {
return Object.entries(waypoints).reduce((acc, [key, waypoint]) => {
const {pendingAction, ...rest} = waypoint as RecentWaypoint;
acc[key] = rest;
return acc;
}, {} as WaypointCollection);
}
/**
* Gets the route for a set of waypoints
* Used so we can generate a map view of the provided waypoints
*/
function getRoute(transactionID: string, waypoints: WaypointCollection, routeType: TransactionState = CONST.TRANSACTION.STATE.CURRENT) {
const parameters: GetRouteParams = {
transactionID,
waypoints: JSON.stringify(sanitizeRecentWaypoints(waypoints)),
};
let command;
switch (routeType) {
case CONST.TRANSACTION.STATE.DRAFT:
command = READ_COMMANDS.GET_ROUTE_FOR_DRAFT;
break;
case CONST.TRANSACTION.STATE.CURRENT:
command = READ_COMMANDS.GET_ROUTE;
break;
case CONST.TRANSACTION.STATE.BACKUP:
command = READ_COMMANDS.GET_ROUTE_FOR_BACKUP;
break;
default:
throw new Error('Invalid route type');
}
API.read(command, parameters, getOnyxDataForRouteRequest(transactionID, routeType));
}
/**
* Updates all waypoints stored in the transaction specified by the provided transactionID.
*
* @param transactionID - The ID of the transaction to be updated
* @param waypoints - An object containing all the waypoints
* which will replace the existing ones.
*/
function updateWaypoints(transactionID: string, waypoints: WaypointCollection, isDraft = false): Promise<void | void[]> {
return Onyx.merge(`${isDraft ? ONYXKEYS.COLLECTION.TRANSACTION_DRAFT : ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {
comment: {
waypoints,
customUnit: {
quantity: null,
},
},
// We want to reset the amount only for draft transactions (when creating the expense).
// When modifying an existing transaction, the amount will be updated on the actual IOU update operation.
...(isDraft && {amount: CONST.IOU.DEFAULT_AMOUNT}),
// Empty out errors when we're saving new waypoints as this indicates the user is updating their input
errorFields: {
route: null,
},
// Clear the existing route so that we don't show an old route
routes: {
route0: {
// Clear the existing distance to recalculate next time
distance: null,
geometry: {
coordinates: null,
},
},
},
});
}
/**
* Dismisses the duplicate transaction violation for the provided transactionIDs
* and updates the transaction to include the dismissed violation in the comment.
*/
function dismissDuplicateTransactionViolation(transactionIDs: string[], dissmissedPersonalDetails: PersonalDetails) {
const currentTransactionViolations = transactionIDs.map((id) => ({transactionID: id, violations: allTransactionViolation?.[id] ?? []}));
const currentTransactions = transactionIDs.map((id) => allTransactions?.[id]);
const transactionsReportActions = currentTransactions.map((transaction) => ReportActionsUtils.getIOUActionForReportID(transaction.reportID ?? '', transaction.transactionID ?? ''));
const optimisticDissmidedViolationReportActions = transactionsReportActions.map(() => {
return buildOptimisticDismissedViolationReportAction({reason: 'manual', violationName: CONST.VIOLATIONS.DUPLICATED_TRANSACTION});
});
const optimisticData: OnyxUpdate[] = [];
const failureData: OnyxUpdate[] = [];
const optimisticReportActions: OnyxUpdate[] = transactionsReportActions.map((action, index) => ({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${action?.childReportID ?? '-1'}`,
value: {
[optimisticDissmidedViolationReportActions.at(index)?.reportActionID ?? '']: optimisticDissmidedViolationReportActions.at(index) as ReportAction,
},
}));
const optimisticDataTransactionViolations: OnyxUpdate[] = currentTransactionViolations.map((transactionViolations) => ({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionViolations.transactionID}`,
value: transactionViolations.violations?.filter((violation) => violation.name !== CONST.VIOLATIONS.DUPLICATED_TRANSACTION),
}));
optimisticData.push(...optimisticDataTransactionViolations);
optimisticData.push(...optimisticReportActions);
const optimisticDataTransactions: OnyxUpdate[] = currentTransactions.map((transaction) => ({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`,
value: {
...transaction,
comment: {
...transaction.comment,
dismissedViolations: {
duplicatedTransaction: {
[dissmissedPersonalDetails.login ?? '']: getUnixTime(new Date()),
},
},
},
},
}));
optimisticData.push(...optimisticDataTransactions);
const failureDataTransactionViolations: OnyxUpdate[] = currentTransactionViolations.map((transactionViolations) => ({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionViolations.transactionID}`,
value: transactionViolations.violations?.map((violation) => violation),
}));
const failureDataTransaction: OnyxUpdate[] = currentTransactions.map((transaction) => ({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`,
value: {
...transaction,
},
}));
const failureReportActions: OnyxUpdate[] = transactionsReportActions.map((action, index) => ({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${action?.childReportID ?? '-1'}`,
value: {
[optimisticDissmidedViolationReportActions.at(index)?.reportActionID ?? '']: null,
},
}));
failureData.push(...failureDataTransactionViolations);
failureData.push(...failureDataTransaction);
failureData.push(...failureReportActions);
const successData: OnyxUpdate[] = transactionsReportActions.map((action, index) => ({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${action?.childReportID ?? '-1'}`,
value: {
[optimisticDissmidedViolationReportActions.at(index)?.reportActionID ?? '']: null,
},
}));
// We are creating duplicate resolved report actions for each duplicate transactions and all the report actions
// should be correctly linked with their parent report but the BE is sometimes linking report actions to different
// parent reports than the one we set optimistically, resulting in duplicate report actions. Therefore, we send the BE
// random report action ids and onSuccessData we reset the report actions we added optimistically to avoid duplicate actions.
const params: DismissViolationParams = {
name: CONST.VIOLATIONS.DUPLICATED_TRANSACTION,
transactionIDList: transactionIDs.join(','),
reportActionIDList: optimisticDissmidedViolationReportActions.map(() => NumberUtils.rand64()).join(','),
};
API.write(WRITE_COMMANDS.DISMISS_VIOLATION, params, {
optimisticData,
successData,
failureData,
});
}
function setReviewDuplicatesKey(values: Partial<ReviewDuplicates>) {
Onyx.merge(`${ONYXKEYS.REVIEW_DUPLICATES}`, {
...values,
});
}
function abandonReviewDuplicateTransactions() {
Onyx.set(ONYXKEYS.REVIEW_DUPLICATES, null);
}
function clearError(transactionID: string) {
Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {errors: null, errorFields: {route: null, waypoints: null, routes: null}});
}
function markAsCash(transactionID: string, transactionThreadReportID: string) {
const optimisticReportAction = buildOptimisticDismissedViolationReportAction({
reason: 'manual',
violationName: CONST.VIOLATIONS.RTER,
});
const optimisticReportActions = {
[optimisticReportAction.reportActionID]: optimisticReportAction,
};
const onyxData: OnyxData = {
optimisticData: [
// Optimistically dismissing the violation, removing it from the list of violations
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`,
value: allTransactionViolations.filter((violation: TransactionViolation) => violation.name !== CONST.VIOLATIONS.RTER),
},
// Optimistically adding the system message indicating we dismissed the violation
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReportID}`,
value: optimisticReportActions as ReportActions,
},
],
failureData: [
// Rolling back the dismissal of the violation
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`,
value: allTransactionViolations,
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReportID}`,
value: {
[optimisticReportAction.reportActionID]: null,
},
},
],
};
const parameters: MarkAsCashParams = {
transactionID,
reportActionID: optimisticReportAction.reportActionID,
};
return API.write(WRITE_COMMANDS.MARK_AS_CASH, parameters, onyxData);
}
function openDraftDistanceExpense() {
const onyxData: OnyxData = {
optimisticData: [
{
onyxMethod: Onyx.METHOD.SET,
key: ONYXKEYS.NVP_RECENT_WAYPOINTS,
// By optimistically setting the recent waypoints to an empty array, no further loading attempts will be made
value: [],
},
],
};
API.read(READ_COMMANDS.OPEN_DRAFT_DISTANCE_EXPENSE, null, onyxData);
}
function getRecentWaypoints() {
return recentWaypoints;
}
function getAllTransactionViolationsLength() {
return allTransactionViolations.length;
}
function getAllTransactions() {
return Object.keys(allTransactions ?? {}).length;
}
export {
addStop,
createInitialWaypoints,
saveWaypoint,
removeWaypoint,
getRoute,
updateWaypoints,
clearError,
markAsCash,
dismissDuplicateTransactionViolation,
setReviewDuplicatesKey,
abandonReviewDuplicateTransactions,
openDraftDistanceExpense,
getRecentWaypoints,
sanitizeRecentWaypoints,
getAllTransactionViolationsLength,
getAllTransactions,
};