-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Transaction.ts
267 lines (245 loc) · 9.3 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
import {isEqual} from 'lodash';
import lodashClone from 'lodash/clone';
import lodashHas from 'lodash/has';
import Onyx from 'react-native-onyx';
import * as API from '@libs/API';
import * as CollectionUtils from '@libs/CollectionUtils';
import * as TransactionUtils from '@libs/TransactionUtils';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {RecentWaypoint, Transaction} from '@src/types/onyx';
import type {OnyxData} from '@src/types/onyx/Request';
import type {WaypointCollection} from '@src/types/onyx/Transaction';
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;
},
});
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 : ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transactionID}`, {
comment: {
waypoints: {
[`waypoint${index}`]: waypoint,
},
},
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: {
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);
clonedWaypoints.unshift(waypoint);
Onyx.merge(ONYXKEYS.NVP_RECENT_WAYPOINTS, clonedWaypoints.slice(0, 5));
}
}
function removeWaypoint(transaction: Transaction, currentIndex: string, isDraft: boolean) {
// Index comes from the route params and is a string
const index = Number(currentIndex);
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;
}
const isRemovedWaypointEmpty = removed.length > 0 && !TransactionUtils.waypointHasValidAddress(removed[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 = {
...transaction,
comment: {
...transaction.comment,
waypoints: reIndexedWaypoints,
},
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: {
distance: null,
geometry: {
coordinates: null,
},
},
},
};
}
if (isDraft) {
Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transaction.transactionID}`, newTransaction);
return;
}
Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`, newTransaction);
}
function getOnyxDataForRouteRequest(transactionID: string, isDraft = false): OnyxData {
return {
optimisticData: [
{
// Clears any potentially stale error messages from fetching the route
onyxMethod: Onyx.METHOD.MERGE,
key: `${isDraft ? ONYXKEYS.COLLECTION.TRANSACTION_DRAFT : ONYXKEYS.COLLECTION.TRANSACTION}${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: `${isDraft ? ONYXKEYS.COLLECTION.TRANSACTION_DRAFT : ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`,
value: {
comment: {
isLoading: false,
},
},
},
],
failureData: [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${isDraft ? ONYXKEYS.COLLECTION.TRANSACTION_DRAFT : ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`,
value: {
comment: {
isLoading: false,
},
},
},
],
};
}
/**
* 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) {
API.read(
'GetRoute',
{
transactionID,
waypoints: JSON.stringify(waypoints),
},
getOnyxDataForRouteRequest(transactionID),
);
}
/**
* Gets the route for a set of waypoints
* Used so we can generate a map view of the provided waypoints
*/
function getRouteForDraft(transactionID: string, waypoints: WaypointCollection) {
API.read(
'GetRouteForDraft',
{
transactionID,
waypoints: JSON.stringify(waypoints),
},
getOnyxDataForRouteRequest(transactionID, true),
);
}
/**
* 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> {
return Onyx.merge(`${isDraft ? ONYXKEYS.COLLECTION.TRANSACTION_DRAFT : ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {
comment: {
waypoints,
},
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: {
distance: null,
geometry: {
coordinates: null,
},
},
},
});
}
export {addStop, createInitialWaypoints, saveWaypoint, removeWaypoint, getRoute, getRouteForDraft, updateWaypoints};