-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
IOU.js
345 lines (315 loc) · 11.4 KB
/
IOU.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
import Onyx from 'react-native-onyx';
import _ from 'underscore';
import CONST from '../../CONST';
import ONYXKEYS from '../../ONYXKEYS';
import ROUTES from '../../ROUTES';
import * as API from '../API';
import * as Report from './Report';
import Navigation from '../Navigation/Navigation';
import Growl from '../Growl';
import * as Localize from '../Localize';
import asyncOpenURL from '../asyncOpenURL';
import Log from '../Log';
/**
* Gets the IOU Reports for new transaction
*
* @param {Object[]} requestParams
* @param {Number} requestParams.reportID the ID of the IOU report
* @param {Number} requestParams.chatReportID the ID of the chat report that the IOU report belongs to
*/
function getIOUReportsForNewTransaction(requestParams) {
API.Get({
returnValueList: 'reportStuff',
reportIDList: _.pluck(requestParams, 'reportID').join(','),
shouldLoadOptionalKeys: true,
includePinnedReports: true,
})
.then((response) => {
if (response.jsonCode !== 200) {
Onyx.merge(ONYXKEYS.IOU, {error: true});
return;
}
const chatReportsToUpdate = {};
const iouReportsToUpdate = {};
_.each(response.reports, (reportData) => {
// First, the existing chat report needs to be updated with the details about the new IOU
const paramsForIOUReport = _.findWhere(requestParams, {reportID: reportData.reportID});
if (paramsForIOUReport && paramsForIOUReport.chatReportID) {
const chatReportID = paramsForIOUReport.chatReportID;
const chatReportKey = `${ONYXKEYS.COLLECTION.REPORT}${chatReportID}`;
chatReportsToUpdate[chatReportKey] = {
iouReportID: reportData.reportID,
total: reportData.total,
stateNum: reportData.stateNum,
hasOutstandingIOU: true,
};
// Second, the IOU report needs to be updated with the new IOU details too
const iouReportKey = `${ONYXKEYS.COLLECTION.REPORT_IOUS}${reportData.reportID}`;
iouReportsToUpdate[iouReportKey] = Report.getSimplifiedIOUReport(reportData, chatReportID);
}
});
Onyx.mergeCollection(ONYXKEYS.COLLECTION.REPORT, chatReportsToUpdate);
Onyx.mergeCollection(ONYXKEYS.COLLECTION.REPORT_IOUS, iouReportsToUpdate);
})
.finally(() => Onyx.merge(ONYXKEYS.IOU, {loading: false, creatingIOUTransaction: false}));
}
/**
* Returns IOU Transaction Error Messages
*
* @param {Object} response
* @returns {String}
*/
function getIOUErrorMessage(response) {
if (response && response.jsonCode) {
if (response.jsonCode === 405) {
return Localize.translateLocal('common.error.invalidAmount');
}
if (response.jsonCode === 404) {
return Localize.translateLocal('iou.error.invalidSplit');
}
if (response.jsonCode === 402) {
return Localize.translateLocal('common.error.phoneNumber');
}
}
return Localize.translateLocal('iou.error.other');
}
/**
* @param {Object} response
*/
function processIOUErrorResponse(response) {
Onyx.merge(ONYXKEYS.IOU, {
loading: false,
creatingIOUTransaction: false,
error: true,
});
Growl.error(getIOUErrorMessage(response));
}
function startLoadingAndResetError() {
Onyx.merge(ONYXKEYS.IOU, {loading: true, creatingIOUTransaction: true, error: false});
}
/**
* Creates IOUSplit Transaction
*
* @param {Object} params
* @param {Number} params.amount
* @param {String} params.comment
* @param {String} params.currency
* @param {String} params.debtorEmail
*/
function createIOUTransaction(params) {
startLoadingAndResetError();
API.CreateIOUTransaction(params)
.then((response) => {
if (response.jsonCode !== 200) {
processIOUErrorResponse(response);
return;
}
getIOUReportsForNewTransaction([response]);
Navigation.navigate(ROUTES.getReportRoute(response.chatReportID));
});
}
/**
* Creates IOUSplit Transaction
*
* @param {Object} params
* @param {Array} params.splits
* @param {String} params.comment
* @param {Number} params.amount
* @param {String} params.currency
*/
function createIOUSplit(params) {
startLoadingAndResetError();
let chatReportID;
API.CreateChatReport({
emailList: _.map(params.splits, participant => participant.email).join(','),
})
.then((response) => {
if (response.jsonCode !== 200) {
return response;
}
chatReportID = response.reportID;
return API.CreateIOUSplit({
...params,
splits: JSON.stringify(params.splits),
reportID: response.reportID,
});
})
.then((response) => {
if (response.jsonCode !== 200) {
processIOUErrorResponse(response);
return;
}
// This data needs to go from this:
// {reportIDList: [1, 2], chatReportIDList: [3, 4]}
// to this:
// [{reportID: 1, chatReportID: 3}, {reportID: 2, chatReportID: 4}]
// in order for getIOUReportsForNewTransaction to know which IOU reports are associated with which
// chat reports
const reportParams = [];
for (let i = 0; i < response.reportIDList.length; i++) {
reportParams.push({
reportID: response.reportIDList[i],
chatReportID: response.chatReportIDList[i],
});
}
getIOUReportsForNewTransaction(reportParams);
Navigation.navigate(ROUTES.getReportRoute(chatReportID));
});
}
/**
* Creates IOUSplit Transaction for Group DM
*
* @param {Object} params
* @param {Array} params.splits
* @param {String} params.comment
* @param {Number} params.amount
* @param {String} params.currency
* @param {String} params.reportID
*/
function createIOUSplitGroup(params) {
startLoadingAndResetError();
API.CreateIOUSplit({
...params,
splits: JSON.stringify(params.splits),
})
.then((response) => {
if (response.jsonCode !== 200) {
Onyx.merge(ONYXKEYS.IOU, {error: true});
return;
}
Onyx.merge(ONYXKEYS.IOU, {loading: false, creatingIOUTransaction: false});
});
}
/**
* Reject an iouReport transaction. Declining and cancelling transactions are done via the same Auth command.
*
* @param {Object} params
* @param {Number} params.reportID
* @param {Number} params.chatReportID
* @param {String} params.transactionID
* @param {String} params.comment
*/
function rejectTransaction({
reportID, chatReportID, transactionID, comment,
}) {
Onyx.merge(ONYXKEYS.TRANSACTIONS_BEING_REJECTED, {
[transactionID]: true,
});
API.RejectTransaction({
reportID,
transactionID,
comment,
})
.then((response) => {
if (response.jsonCode !== 200) {
Log.hmmm('Error rejecting transaction', {error: response.error});
return;
}
const chatReport = response.reports[chatReportID];
const iouReport = response.reports[reportID];
Report.syncChatAndIOUReports(chatReport, iouReport);
})
.finally(() => {
// Setting as null deletes the transactionID
Onyx.merge(ONYXKEYS.TRANSACTIONS_BEING_REJECTED, {
[transactionID]: null,
});
});
}
/**
* Sets IOU'S selected currency
*
* @param {String} selectedCurrencyCode
*/
function setIOUSelectedCurrency(selectedCurrencyCode) {
Onyx.merge(ONYXKEYS.IOU, {selectedCurrencyCode});
}
/**
* @param {Number} amount
* @param {String} submitterPhoneNumber
* @returns {String}
*/
function buildVenmoPaymentURL(amount, submitterPhoneNumber) {
const note = encodeURIComponent('For New Expensify request');
return `venmo://paycharge?txn=pay&recipients=${submitterPhoneNumber}&amount=${(amount / 100)}¬e=${note}`;
}
/**
* @param {Number} amount
* @param {String} submitterPayPalMeAddress
* @param {String} currency
* @returns {String}
*/
function buildPayPalPaymentUrl(amount, submitterPayPalMeAddress, currency) {
return `https://paypal.me/${submitterPayPalMeAddress}/${(amount / 100)}${currency}`;
}
/**
* Pays an IOU Report and then retrieves the iou and chat reports to trigger updates to the UI.
*
* @param {Object} params
* @param {Number} params.chatReportID
* @param {Number} params.reportID
* @param {String} params.paymentMethodType - one of CONST.IOU.PAYMENT_TYPE
* @param {Number} params.amount
* @param {String} params.currency
* @param {String} [params.requestorPhoneNumber] - used for Venmo
* @param {String} [params.requestorPayPalMeAddress]
* @param {String} [params.newIOUReportDetails] - Extra details required only for send money flow
*
* @return {Promise}
*/
function payIOUReport({
chatReportID,
reportID,
paymentMethodType,
amount,
currency,
requestorPhoneNumber,
requestorPayPalMeAddress,
newIOUReportDetails,
}) {
Onyx.merge(ONYXKEYS.IOU, {loading: true, error: false});
const payIOUPromise = paymentMethodType === CONST.IOU.PAYMENT_TYPE.EXPENSIFY
? API.PayWithWallet({reportID, newIOUReportDetails})
: API.PayIOU({reportID, paymentMethodType, newIOUReportDetails});
// Build the url for the user's platform of choice if they have selected something other than a manual settlement or Expensify Wallet e.g. Venmo or PayPal.me
let url;
if (paymentMethodType === CONST.IOU.PAYMENT_TYPE.PAYPAL_ME) {
url = buildPayPalPaymentUrl(amount, requestorPayPalMeAddress, currency);
}
if (paymentMethodType === CONST.IOU.PAYMENT_TYPE.VENMO) {
url = buildVenmoPaymentURL(amount, requestorPhoneNumber);
}
const promiseWithHandlers = payIOUPromise
.then((response) => {
if (response.jsonCode !== 200) {
switch (response.message) {
case 'You cannot pay via Expensify Wallet until you have either a verified deposit bank account or debit card.':
Growl.error(Localize.translateLocal('bankAccount.error.noDefaultDepositAccountOrDebitCardAvailable'), 5000);
break;
case 'This report doesn\'t have reimbursable expenses.':
Growl.error(Localize.translateLocal('iou.noReimbursableExpenses'), 5000);
break;
default:
Growl.error(response.message, 5000);
}
Onyx.merge(ONYXKEYS.IOU, {error: true});
return;
}
const chatReportStuff = response.reports[chatReportID];
const iouReportStuff = response.reports[reportID];
Report.syncChatAndIOUReports(chatReportStuff, iouReportStuff);
})
.finally(() => {
Onyx.merge(ONYXKEYS.IOU, {loading: false});
});
asyncOpenURL(promiseWithHandlers, url);
return promiseWithHandlers;
}
export {
createIOUTransaction,
createIOUSplit,
createIOUSplitGroup,
rejectTransaction,
payIOUReport,
setIOUSelectedCurrency,
};