-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
MoneyRequestModal.js
412 lines (371 loc) · 18.9 KB
/
MoneyRequestModal.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
import _ from 'underscore';
import React, {useState, useEffect, useCallback, useMemo} from 'react';
import {View} from 'react-native';
import PropTypes from 'prop-types';
import lodashGet from 'lodash/get';
import {withOnyx} from 'react-native-onyx';
import MoneyRequestAmountPage from './steps/MoneyRequestAmountPage';
import MoneyRequestParticipantsPage from './steps/MoneyRequstParticipantsPage/MoneyRequestParticipantsPage';
import MoneyRequestConfirmPage from './steps/MoneyRequestConfirmPage';
import ModalHeader from './ModalHeader';
import styles from '../../styles/styles';
import * as IOU from '../../libs/actions/IOU';
import ONYXKEYS from '../../ONYXKEYS';
import withLocalize, {withLocalizePropTypes} from '../../components/withLocalize';
import compose from '../../libs/compose';
import * as OptionsListUtils from '../../libs/OptionsListUtils';
import FullScreenLoadingIndicator from '../../components/FullscreenLoadingIndicator';
import AnimatedStep from '../../components/AnimatedStep';
import ScreenWrapper from '../../components/ScreenWrapper';
import CONST from '../../CONST';
import * as PersonalDetails from '../../libs/actions/PersonalDetails';
import withCurrentUserPersonalDetails from '../../components/withCurrentUserPersonalDetails';
import reportPropTypes from '../reportPropTypes';
import * as ReportUtils from '../../libs/ReportUtils';
import * as ReportScrollManager from '../../libs/ReportScrollManager';
import useOnNetworkReconnect from '../../hooks/useOnNetworkReconnect';
import * as DeviceCapabilities from '../../libs/DeviceCapabilities';
import * as CurrencyUtils from '../../libs/CurrencyUtils';
/**
* A modal used for requesting money, splitting bills or sending money.
*/
const propTypes = {
/** Whether the request is for a single request or a group bill split */
hasMultipleParticipants: PropTypes.bool,
/** The type of IOU report, i.e. bill, request, send */
iouType: PropTypes.string,
/** The report passed via the route */
// eslint-disable-next-line react/no-unused-prop-types
report: reportPropTypes,
// Holds data related to request view state, rather than the underlying request data.
iou: PropTypes.shape({
/** Whether or not transaction creation has resulted to error */
error: PropTypes.bool,
// Selected Currency Code of the current request
selectedCurrencyCode: PropTypes.string,
}),
/** Personal details of all the users */
personalDetails: PropTypes.shape({
/** Primary login of participant */
login: PropTypes.string,
/** Display Name of participant */
displayName: PropTypes.string,
/** Avatar url of participant */
avatar: PropTypes.string,
}),
/** Personal details of the current user */
currentUserPersonalDetails: PropTypes.shape({
// Local Currency Code of the current user
localCurrencyCode: PropTypes.string,
}),
...withLocalizePropTypes,
};
const defaultProps = {
hasMultipleParticipants: false,
report: {
participants: [],
},
iouType: CONST.IOU.MONEY_REQUEST_TYPE.REQUEST,
currentUserPersonalDetails: {
localCurrencyCode: CONST.CURRENCY.USD,
},
personalDetails: {},
iou: {
error: false,
selectedCurrencyCode: null,
},
};
// Determines type of step to display within Modal, value provides the title for that page.
const Steps = {
MoneyRequestAmount: 'moneyRequest.amount',
MoneyRequestParticipants: 'moneyRequest.participants',
MoneyRequestConfirm: 'moneyRequest.confirm',
};
const MoneyRequestModal = (props) => {
// Skip MoneyRequestParticipants step if participants are passed in
const reportParticipants = lodashGet(props, 'report.participants', []);
const steps = useMemo(
() => (reportParticipants.length ? [Steps.MoneyRequestAmount, Steps.MoneyRequestConfirm] : [Steps.MoneyRequestAmount, Steps.MoneyRequestParticipants, Steps.MoneyRequestConfirm]),
[reportParticipants.length],
);
const [previousStepIndex, setPreviousStepIndex] = useState(-1);
const [currentStepIndex, setCurrentStepIndex] = useState(0);
const [selectedOptions, setSelectedOptions] = useState(
ReportUtils.isPolicyExpenseChat(props.report)
? OptionsListUtils.getPolicyExpenseReportOptions(props.report)
: OptionsListUtils.getParticipantsOptions(props.report, props.personalDetails),
);
const [amount, setAmount] = useState(0);
useEffect(() => {
PersonalDetails.openMoneyRequestModalPage();
IOU.setMoneyRequestDescription('');
}, []);
// We update selected currency when PersonalDetails.openMoneyRequestModalPage finishes
// props.currentUserPersonalDetails might be stale data or might not exist if user is signing in
useEffect(() => {
if (_.isUndefined(props.currentUserPersonalDetails.localCurrencyCode)) {
return;
}
IOU.setIOUSelectedCurrency(props.currentUserPersonalDetails.localCurrencyCode);
}, [props.currentUserPersonalDetails.localCurrencyCode]);
// User came back online, so let's refetch the currency details based on location
useOnNetworkReconnect(PersonalDetails.openMoneyRequestModalPage);
/**
* Decides our animation type based on whether we're increasing or decreasing
* our step index.
* @returns {String|null}
*/
const direction = useMemo(() => {
// If we're going to the "amount" step from the "confirm" step, push it in and pop it out like we're moving
// forward instead of backwards.
const amountIndex = _.indexOf(steps, Steps.MoneyRequestAmount);
const confirmIndex = _.indexOf(steps, Steps.MoneyRequestConfirm);
if (previousStepIndex === confirmIndex && currentStepIndex === amountIndex) {
return 'in';
}
if (previousStepIndex === amountIndex && currentStepIndex === confirmIndex) {
return 'out';
}
if (previousStepIndex < currentStepIndex) {
return 'in';
}
if (previousStepIndex > currentStepIndex) {
return 'out';
}
// Doesn't animate the step when first opening the modal
if (previousStepIndex === currentStepIndex) {
return null;
}
}, [previousStepIndex, currentStepIndex, steps]);
/**
* Retrieve title for current step, based upon current step and type of request
*
* @returns {String}
*/
const titleForStep = useMemo(() => {
if (currentStepIndex === 0) {
const confirmIndex = _.indexOf(steps, Steps.MoneyRequestConfirm);
if (previousStepIndex === confirmIndex) {
return props.translate('iou.amount');
}
if (props.iouType === CONST.IOU.MONEY_REQUEST_TYPE.SEND) {
return props.translate('iou.sendMoney');
}
return props.translate(props.hasMultipleParticipants ? 'iou.splitBill' : 'iou.requestMoney');
}
return props.translate('iou.cash');
// eslint-disable-next-line react-hooks/exhaustive-deps -- props does not need to be a dependency as it will always exist
}, [currentStepIndex, props.translate, steps]);
/**
* Navigate to a provided step.
*
* @param {Number} stepIndex
* @type {(function(*): void)|*}
*/
const navigateToStep = useCallback(
(stepIndex) => {
if (stepIndex < 0 || stepIndex > steps.length) {
return;
}
if (currentStepIndex === stepIndex) {
return;
}
setPreviousStepIndex(currentStepIndex);
setCurrentStepIndex(stepIndex);
},
[currentStepIndex, steps.length],
);
/**
* Navigate to the previous request step if possible
*/
const navigateToPreviousStep = useCallback(() => {
if (currentStepIndex <= 0 && previousStepIndex < 0) {
return;
}
setPreviousStepIndex(currentStepIndex);
setCurrentStepIndex(currentStepIndex - 1);
}, [currentStepIndex, previousStepIndex]);
/**
* Navigate to the next request step if possible
*/
const navigateToNextStep = useCallback(() => {
if (currentStepIndex >= steps.length - 1) {
return;
}
// If we're coming from the confirm step, it means we were editing something so go back to the confirm step.
const confirmIndex = _.indexOf(steps, Steps.MoneyRequestConfirm);
if (previousStepIndex === confirmIndex) {
navigateToStep(confirmIndex);
return;
}
setPreviousStepIndex(currentStepIndex);
setCurrentStepIndex(currentStepIndex + 1);
}, [currentStepIndex, previousStepIndex, navigateToStep, steps]);
/**
* Checks if user has a GOLD wallet then creates a paid IOU report on the fly
*
* @param {String} paymentMethodType
*/
const sendMoney = useCallback(
(paymentMethodType) => {
const currency = props.iou.selectedCurrencyCode;
const trimmedComment = props.iou.comment.trim();
const participant = selectedOptions[0];
if (paymentMethodType === CONST.IOU.PAYMENT_TYPE.ELSEWHERE) {
IOU.sendMoneyElsewhere(props.report, amount, currency, trimmedComment, props.currentUserPersonalDetails.login, participant);
return;
}
if (paymentMethodType === CONST.IOU.PAYMENT_TYPE.PAYPAL_ME) {
IOU.sendMoneyViaPaypal(props.report, amount, currency, trimmedComment, props.currentUserPersonalDetails.login, participant);
return;
}
if (paymentMethodType === CONST.IOU.PAYMENT_TYPE.EXPENSIFY) {
IOU.sendMoneyWithWallet(props.report, amount, currency, trimmedComment, props.currentUserPersonalDetails.login, participant);
}
},
[amount, props.iou.comment, selectedOptions, props.currentUserPersonalDetails.login, props.iou.selectedCurrencyCode, props.report],
);
/**
* @param {Array} selectedParticipants
*/
const createTransaction = useCallback(
(selectedParticipants) => {
const reportID = lodashGet(props.route, 'params.reportID', '');
const trimmedComment = props.iou.comment.trim();
// IOUs created from a group report will have a reportID param in the route.
// Since the user is already viewing the report, we don't need to navigate them to the report
if (props.hasMultipleParticipants && CONST.REGEX.NUMBER.test(reportID)) {
IOU.splitBill(selectedParticipants, props.currentUserPersonalDetails.login, amount, trimmedComment, props.iou.selectedCurrencyCode, reportID);
return;
}
// If the request is created from the global create menu, we also navigate the user to the group report
if (props.hasMultipleParticipants) {
IOU.splitBillAndOpenReport(selectedParticipants, props.currentUserPersonalDetails.login, amount, trimmedComment, props.iou.selectedCurrencyCode);
return;
}
IOU.requestMoney(props.report, amount, props.iou.selectedCurrencyCode, props.currentUserPersonalDetails.login, selectedParticipants[0], trimmedComment);
},
[amount, props.iou.comment, props.currentUserPersonalDetails.login, props.hasMultipleParticipants, props.iou.selectedCurrencyCode, props.report, props.route],
);
const currentStep = steps[currentStepIndex];
const moneyRequestStepIndex = _.indexOf(steps, Steps.MoneyRequestConfirm);
const isEditingAmountAfterConfirm = currentStepIndex === 0 && previousStepIndex === _.indexOf(steps, Steps.MoneyRequestConfirm);
const reportID = lodashGet(props, 'route.params.reportID', '');
const shouldShowBackButton = currentStepIndex > 0 || isEditingAmountAfterConfirm;
const modalHeader = (
<ModalHeader
title={titleForStep}
shouldShowBackButton={shouldShowBackButton}
onBackButtonPress={isEditingAmountAfterConfirm ? () => navigateToStep(moneyRequestStepIndex) : navigateToPreviousStep}
/>
);
const amountButtonText = isEditingAmountAfterConfirm ? props.translate('common.save') : props.translate('common.next');
const enableMaxHeight = DeviceCapabilities.canUseTouchScreen() && currentStep === Steps.MoneyRequestParticipants;
const bankAccountRoute = ReportUtils.getBankAccountRoute(props.report);
return (
<ScreenWrapper
includeSafeAreaPaddingBottom={false}
shouldEnableMaxHeight={enableMaxHeight}
>
{({didScreenTransitionEnd, safeAreaPaddingBottomStyle}) => (
<>
<View style={[styles.pRelative, styles.flex1]}>
{!didScreenTransitionEnd && <FullScreenLoadingIndicator />}
{didScreenTransitionEnd && (
<>
{currentStep === Steps.MoneyRequestAmount && (
<AnimatedStep
direction={direction}
style={[styles.flex1, safeAreaPaddingBottomStyle]}
>
{modalHeader}
<MoneyRequestAmountPage
onStepComplete={(value, selectedCurrencyCode) => {
const amountInSmallestCurrencyUnits = CurrencyUtils.convertToSmallestUnit(selectedCurrencyCode, Number.parseFloat(value));
IOU.setIOUSelectedCurrency(selectedCurrencyCode);
setAmount(amountInSmallestCurrencyUnits);
navigateToNextStep();
}}
reportID={reportID}
hasMultipleParticipants={props.hasMultipleParticipants}
selectedAmount={CurrencyUtils.convertToWholeUnit(props.iou.selectedCurrencyCode, amount)}
navigation={props.navigation}
route={props.route}
iouType={props.iouType}
buttonText={amountButtonText}
/>
</AnimatedStep>
)}
{currentStep === Steps.MoneyRequestParticipants && (
<AnimatedStep
style={[styles.flex1]}
direction={direction}
>
{modalHeader}
<MoneyRequestParticipantsPage
participants={selectedOptions}
hasMultipleParticipants={props.hasMultipleParticipants}
onAddParticipants={setSelectedOptions}
onStepComplete={navigateToNextStep}
safeAreaPaddingBottomStyle={safeAreaPaddingBottomStyle}
iouType={props.iouType}
/>
</AnimatedStep>
)}
{currentStep === Steps.MoneyRequestConfirm && (
<AnimatedStep
style={[styles.flex1, safeAreaPaddingBottomStyle]}
direction={direction}
>
{modalHeader}
<MoneyRequestConfirmPage
onConfirm={(selectedParticipants) => {
createTransaction(selectedParticipants);
ReportScrollManager.scrollToBottom();
}}
onSendMoney={(paymentMethodType) => {
sendMoney(paymentMethodType);
ReportScrollManager.scrollToBottom();
}}
hasMultipleParticipants={props.hasMultipleParticipants}
participants={_.filter(selectedOptions, (email) => props.currentUserPersonalDetails.login !== email.login)}
iouAmount={amount}
iouType={props.iouType}
// The participants can only be modified when the action is initiated from directly within a group chat and not the floating-action-button.
// This is because when there is a group of people, say they are on a trip, and you have some shared expenses with some of the people,
// but not all of them (maybe someone skipped out on dinner). Then it's nice to be able to select/deselect people from the group chat bill
// split rather than forcing the user to create a new group, just for that expense. The reportID is empty, when the action was initiated from
// the floating-action-button (since it is something that exists outside the context of a report).
canModifyParticipants={!_.isEmpty(reportID)}
navigateToStep={navigateToStep}
policyID={props.report.policyID}
bankAccountRoute={bankAccountRoute}
/>
</AnimatedStep>
)}
</>
)}
</View>
</>
)}
</ScreenWrapper>
);
};
MoneyRequestModal.displayName = 'MoneyRequestModal';
MoneyRequestModal.propTypes = propTypes;
MoneyRequestModal.defaultProps = defaultProps;
export default compose(
withLocalize,
withCurrentUserPersonalDetails,
withOnyx({
report: {
key: ({route}) => `${ONYXKEYS.COLLECTION.REPORT}${lodashGet(route, 'params.reportID', '')}`,
},
iou: {
key: ONYXKEYS.IOU,
},
personalDetails: {
key: ONYXKEYS.PERSONAL_DETAILS,
},
}),
)(MoneyRequestModal);