-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathTransactionUtils.js
356 lines (319 loc) · 11.7 KB
/
TransactionUtils.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
import Onyx from 'react-native-onyx';
import {format, parseISO, isValid} from 'date-fns';
import lodashGet from 'lodash/get';
import _ from 'underscore';
import CONST from '../CONST';
import ONYXKEYS from '../ONYXKEYS';
import DateUtils from './DateUtils';
import * as NumberUtils from './NumberUtils';
let allTransactions = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.TRANSACTION,
waitForCollectionCallback: true,
callback: (val) => {
if (!val) {
return;
}
allTransactions = _.pick(val, (transaction) => transaction);
},
});
/**
* Optimistically generate a transaction.
*
* @param {Number} amount – in cents
* @param {String} currency
* @param {String} reportID
* @param {String} [comment]
* @param {String} [created]
* @param {String} [source]
* @param {String} [originalTransactionID]
* @param {String} [merchant]
* @param {Object} [receipt]
* @param {String} [filename]
* @param {String} [existingTransactionID] When creating a distance request, an empty transaction has already been created with a transactionID. In that case, the transaction here needs to have it's transactionID match what was already generated.
* @returns {Object}
*/
function buildOptimisticTransaction(
amount,
currency,
reportID,
comment = '',
created = '',
source = '',
originalTransactionID = '',
merchant = '',
receipt = {},
filename = '',
existingTransactionID = null,
) {
// transactionIDs are random, positive, 64-bit numeric strings.
// Because JS can only handle 53-bit numbers, transactionIDs are strings in the front-end (just like reportActionID)
const transactionID = existingTransactionID || NumberUtils.rand64();
const commentJSON = {comment};
if (source) {
commentJSON.source = source;
}
if (originalTransactionID) {
commentJSON.originalTransactionID = originalTransactionID;
}
// For the SmartScan to run successfully, we need to pass the merchant field empty to the API
const defaultMerchant = _.isEmpty(receipt) ? CONST.TRANSACTION.DEFAULT_MERCHANT : '';
return {
transactionID,
amount,
currency,
reportID,
comment: commentJSON,
merchant: merchant || defaultMerchant,
created: created || DateUtils.getDBTime(),
pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
receipt,
filename,
};
}
/**
* @param {Object|null} transaction
* @returns {Boolean}
*/
function hasReceipt(transaction) {
return lodashGet(transaction, 'receipt.state', '') !== '';
}
/**
* @param {Object} transaction
* @returns {Boolean}
*/
function areModifiedFieldsPopulated(transaction) {
return transaction.modifiedMerchant !== CONST.TRANSACTION.UNKNOWN_MERCHANT && transaction.modifiedAmount !== 0 && transaction.modifiedCreated !== '';
}
/**
* Given the edit made to the money request, return an updated transaction object.
*
* @param {Object} transaction
* @param {Object} transactionChanges
* @param {Object} isFromExpenseReport
* @returns {Object}
*/
function getUpdatedTransaction(transaction, transactionChanges, isFromExpenseReport) {
// Only changing the first level fields so no need for deep clone now
const updatedTransaction = _.clone(transaction);
let shouldStopSmartscan = false;
// The comment property does not have its modifiedComment counterpart
if (_.has(transactionChanges, 'comment')) {
updatedTransaction.comment = {
...updatedTransaction.comment,
comment: transactionChanges.comment,
};
}
if (_.has(transactionChanges, 'created')) {
updatedTransaction.modifiedCreated = transactionChanges.created;
shouldStopSmartscan = true;
}
if (_.has(transactionChanges, 'amount')) {
updatedTransaction.modifiedAmount = isFromExpenseReport ? -transactionChanges.amount : transactionChanges.amount;
shouldStopSmartscan = true;
}
if (_.has(transactionChanges, 'currency')) {
updatedTransaction.modifiedCurrency = transactionChanges.currency;
shouldStopSmartscan = true;
}
if (_.has(transactionChanges, 'merchant')) {
updatedTransaction.modifiedMerchant = transactionChanges.merchant;
shouldStopSmartscan = true;
}
if (shouldStopSmartscan && _.has(transaction, 'receipt') && !_.isEmpty(transaction.receipt) && lodashGet(transaction, 'receipt.state') !== CONST.IOU.RECEIPT_STATE.OPEN) {
updatedTransaction.receipt.state = CONST.IOU.RECEIPT_STATE.OPEN;
}
updatedTransaction.pendingFields = {
...(_.has(transactionChanges, 'comment') && {comment: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE}),
...(_.has(transactionChanges, 'created') && {created: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE}),
...(_.has(transactionChanges, 'amount') && {amount: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE}),
...(_.has(transactionChanges, 'currency') && {currency: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE}),
...(_.has(transactionChanges, 'merchant') && {merchant: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE}),
};
return updatedTransaction;
}
/**
* Retrieve the particular transaction object given its ID.
*
* @param {String} transactionID
* @returns {Object}
*/
function getTransaction(transactionID) {
return lodashGet(allTransactions, `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {});
}
/**
* Return the comment field (referred to as description in the App) from the transaction.
* The comment does not have its modifiedComment counterpart.
*
* @param {Object} transaction
* @returns {String}
*/
function getDescription(transaction) {
return lodashGet(transaction, 'comment.comment', '');
}
/**
* Return the amount field from the transaction, return the modifiedAmount if present.
*
* @param {Object} transaction
* @param {Boolean} isFromExpenseReport
* @returns {Number}
*/
function getAmount(transaction, isFromExpenseReport) {
// IOU requests cannot have negative values but they can be stored as negative values, let's return absolute value
if (!isFromExpenseReport) {
const amount = lodashGet(transaction, 'modifiedAmount', 0);
if (amount) {
return Math.abs(amount);
}
return Math.abs(lodashGet(transaction, 'amount', 0));
}
// Expense report case:
// The amounts are stored using an opposite sign and negative values can be set,
// we need to return an opposite sign than is saved in the transaction object
let amount = lodashGet(transaction, 'modifiedAmount', 0);
if (amount) {
return -amount;
}
// To avoid -0 being shown, lets only change the sign if the value is other than 0.
amount = lodashGet(transaction, 'amount', 0);
return amount ? -amount : 0;
}
/**
* Return the currency field from the transaction, return the modifiedCurrency if present.
*
* @param {Object} transaction
* @returns {String}
*/
function getCurrency(transaction) {
const currency = lodashGet(transaction, 'modifiedCurrency', '');
if (currency) {
return currency;
}
return lodashGet(transaction, 'currency', CONST.CURRENCY.USD);
}
/**
* Return the merchant field from the transaction, return the modifiedMerchant if present.
*
* @param {Object} transaction
* @returns {String}
*/
function getMerchant(transaction) {
return lodashGet(transaction, 'modifiedMerchant', null) || lodashGet(transaction, 'merchant', '');
}
/**
* Return the created field from the transaction, return the modifiedCreated if present.
*
* @param {Object} transaction
* @returns {String}
*/
function getCreated(transaction) {
const created = lodashGet(transaction, 'modifiedCreated', '') || lodashGet(transaction, 'created', '');
const createdDate = parseISO(created);
if (isValid(createdDate)) {
return format(createdDate, CONST.DATE.FNS_FORMAT_STRING);
}
return '';
}
/*
* @param {Object} transaction
* @param {Object} transaction.comment
* @param {String} transaction.comment.type
* @param {Object} [transaction.comment.customUnit]
* @param {String} [transaction.comment.customUnit.name]
* @returns {Boolean}
*/
function isDistanceRequest(transaction) {
const type = lodashGet(transaction, 'comment.type');
const customUnitName = lodashGet(transaction, 'comment.customUnit.name');
return type === CONST.TRANSACTION.TYPE.CUSTOM_UNIT && customUnitName === CONST.CUSTOM_UNITS.NAME_DISTANCE;
}
function isReceiptBeingScanned(transaction) {
return _.contains([CONST.IOU.RECEIPT_STATE.SCANREADY, CONST.IOU.RECEIPT_STATE.SCANNING], transaction.receipt.state);
}
/**
* Check if the transaction has a non-smartscanning receipt and is missing required fields
*
* @param {Object} transaction
* @returns {Boolean}
*/
function hasMissingSmartscanFields(transaction) {
return hasReceipt(transaction) && !isDistanceRequest(transaction) && !isReceiptBeingScanned(transaction) && !areModifiedFieldsPopulated(transaction);
}
/**
* Get the transactions related to a report preview with receipts
* Get the details linked to the IOU reportAction
*
* @param {Object} reportAction
* @returns {Object}
*/
function getLinkedTransaction(reportAction = {}) {
const transactionID = lodashGet(reportAction, ['originalMessage', 'IOUTransactionID'], '');
return allTransactions[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`] || {};
}
function getAllReportTransactions(reportID) {
// `reportID` from the `/CreateDistanceRequest` endpoint return's number instead of string for created `transaction`.
// For reference, https://github.com/Expensify/App/pull/26536#issuecomment-1703573277.
// We will update this in a follow-up Issue. According to this comment: https://github.com/Expensify/App/pull/26536#issuecomment-1703591019.
return _.filter(allTransactions, (transaction) => `${transaction.reportID}` === `${reportID}`);
}
/**
* Checks if a waypoint has a valid address
* @param {Object} waypoint
* @returns {Boolean} Returns true if the address is valid
*/
function waypointHasValidAddress(waypoint) {
if (!waypoint || !waypoint.address || typeof waypoint.address !== 'string' || waypoint.address.trim() === '') {
return false;
}
return true;
}
/**
* Filters the waypoints which are valid and returns those
* @param {Object} waypoints
* @param {Boolean} reArrangeIndexes
* @returns {Object} validated waypoints
*/
function getValidWaypoints(waypoints, reArrangeIndexes = false) {
const waypointValues = _.values(waypoints);
// Ensure the number of waypoints is between 2 and 25
if (waypointValues.length < 2 || waypointValues.length > 25) {
return {};
}
let lastWaypointIndex = -1;
const validWaypoints = _.reduce(
waypointValues,
(acc, currentWaypoint, index) => {
const previousWaypoint = waypointValues[lastWaypointIndex];
// Check if the waypoint has a valid address
if (!waypointHasValidAddress(currentWaypoint)) {
return acc;
}
// Check for adjacent waypoints with the same address
if (previousWaypoint && currentWaypoint.address === previousWaypoint.address) {
return acc;
}
const validatedWaypoints = {...acc, [`waypoint${reArrangeIndexes ? lastWaypointIndex + 1 : index}`]: currentWaypoint};
lastWaypointIndex += 1;
return validatedWaypoints;
},
{},
);
return validWaypoints;
}
export {
buildOptimisticTransaction,
getUpdatedTransaction,
getTransaction,
getDescription,
getAmount,
getCurrency,
getMerchant,
getCreated,
getLinkedTransaction,
getAllReportTransactions,
hasReceipt,
isReceiptBeingScanned,
getValidWaypoints,
isDistanceRequest,
hasMissingSmartscanFields,
};