/
add-payment-methods-task.js
407 lines (378 loc) · 11.4 KB
/
add-payment-methods-task.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
/**
* External dependencies
*/
import React, {
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from 'react';
import { __ } from '@wordpress/i18n';
import {
Button,
Card,
CardBody,
ExternalLink,
CardDivider,
Notice,
} from '@wordpress/components';
import interpolateComponents from '@automattic/interpolate-components';
/**
* Internal dependencies
*/
import WizardTaskContext from '../wizard/task/context';
import CollapsibleBody from '../wizard/collapsible-body';
import WizardTaskItem from '../wizard/task-item';
import {
useEnabledPaymentMethodIds,
useGetAvailablePaymentMethodIds,
useGetPaymentMethodStatuses,
useSettings,
} from '../../data';
import PaymentMethodCheckboxes from '../../components/payment-methods-checkboxes';
import PaymentMethodCheckbox from '../../components/payment-methods-checkboxes/payment-method-checkbox';
import { LoadableBlock } from '../../components/loadable';
import LoadableSettingsSection from '../../settings/loadable-settings-section';
import CurrencyInformationForMethods, {
BuildMissingCurrenciesTooltipMessage,
} from '../../components/currency-information-for-methods';
import { upeCapabilityStatuses, upeMethods } from '../constants';
import paymentMethodsMap from '../../payment-methods-map';
import ConfirmPaymentMethodActivationModal from 'wcpay/payment-methods/activation-modal';
import './add-payment-methods-task.scss';
import PAYMENT_METHOD_IDS from 'wcpay/payment-methods/constants';
const usePaymentMethodsCheckboxState = () => {
// For UPE, the card payment method is required and always active.
const [ paymentMethodsState, setPaymentMethodsState ] = useState( {
card: true,
} );
const handleChange = useCallback(
( paymentMethodName, enabled ) => {
setPaymentMethodsState( ( oldValues ) => ( {
...oldValues,
[ paymentMethodName ]: enabled,
} ) );
},
[ setPaymentMethodsState ]
);
return [ paymentMethodsState, handleChange ];
};
const ContinueButton = ( { paymentMethodsState } ) => {
const { setCompleted } = useContext( WizardTaskContext );
const [
initialEnabledPaymentMethodIds,
updateEnabledPaymentMethodIds,
] = useEnabledPaymentMethodIds();
const { saveSettings, isSaving } = useSettings();
const checkedPaymentMethods = useMemo(
() =>
Object.entries( paymentMethodsState )
.map( ( [ method, enabled ] ) => enabled && method )
.filter( Boolean ),
[ paymentMethodsState ]
);
const unCheckedPaymentMethods = Object.entries( paymentMethodsState )
.map( ( [ method, enabled ] ) => ! enabled && method )
.filter( Boolean );
const handleContinueClick = useCallback( () => {
// creating a separate callback, so that the main thread isn't blocked on click of the button
const callback = async () => {
updateEnabledPaymentMethodIds( [
// adding the newly selected payment methods and removing them from the `initialEnabledPaymentMethodIds` if unchecked
...new Set(
[
...initialEnabledPaymentMethodIds,
...checkedPaymentMethods,
].filter(
( method ) =>
! unCheckedPaymentMethods.includes( method )
)
),
] );
const isSuccess = await saveSettings();
if ( ! isSuccess ) {
// restoring the state, in case of soft route
updateEnabledPaymentMethodIds( initialEnabledPaymentMethodIds );
return;
}
setCompleted(
{
initialMethods: initialEnabledPaymentMethodIds,
},
'setup-complete'
);
};
callback();
}, [
unCheckedPaymentMethods,
checkedPaymentMethods,
updateEnabledPaymentMethodIds,
saveSettings,
setCompleted,
initialEnabledPaymentMethodIds,
] );
return (
<Button
isBusy={ isSaving }
disabled={ isSaving || checkedPaymentMethods.length < 1 }
onClick={ handleContinueClick }
isPrimary
>
{ __( 'Continue', 'woocommerce-payments' ) }
</Button>
);
};
const AddPaymentMethodsTask = () => {
const availablePaymentMethods = useGetAvailablePaymentMethodIds();
const paymentMethodStatuses = useGetPaymentMethodStatuses();
const { isActive } = useContext( WizardTaskContext );
const isPoEnabled = wcpaySettings?.progressiveOnboarding?.isEnabled;
const isPoComplete = wcpaySettings?.progressiveOnboarding?.isComplete;
const isPoInProgress = isPoEnabled && ! isPoComplete;
// I am using internal state in this component
// and committing the changes on `initialEnabledPaymentMethodIds` only when the "continue" button is clicked.
// Otherwise a user could navigate to another page via soft-routing and the settings would be in un-saved state,
// possibly causing errors.
const [
paymentMethodsState,
handlePaymentMethodChange,
] = usePaymentMethodsCheckboxState( availablePaymentMethods );
useEffect( () => {
availablePaymentMethods
.filter( ( method ) => upeMethods.includes( method ) )
.forEach( ( method ) => {
handlePaymentMethodChange( method, false );
} );
}, [ availablePaymentMethods, handlePaymentMethodChange ] );
const selectedMethods = useMemo(
() =>
Object.entries( paymentMethodsState )
.map( ( [ method, enabled ] ) => enabled && method )
.filter( Boolean ),
[ paymentMethodsState ]
);
const [ activationModalParams, handleActivationModalOpen ] = useState(
null
);
const completeActivation = ( method ) => {
handlePaymentMethodChange( method, true );
handleActivationModalOpen( null );
};
const getStatusAndRequirements = ( method ) => {
const stripeKey = paymentMethodsMap[ method ].stripe_key;
const stripeStatusContainer = paymentMethodStatuses[ stripeKey ] ?? [];
if ( ! stripeStatusContainer ) {
return {
status: upeCapabilityStatuses.UNREQUESTED,
requirements: [],
};
}
return {
status: stripeStatusContainer.status,
requirements: stripeStatusContainer.requirements,
};
};
const handleCheckClick = ( method, status ) => {
if ( status ) {
const statusAndRequirements = getStatusAndRequirements( method );
if (
statusAndRequirements.status === 'unrequested' &&
statusAndRequirements.requirements.length > 0
) {
handleActivationModalOpen( {
id: method,
requirements: statusAndRequirements.requirements,
} );
} else {
completeActivation( method );
}
} else {
handlePaymentMethodChange( method, false );
}
};
const prepareUpePaymentMethods = ( upeMethodIds ) => {
return upeMethodIds.map( ( key ) => {
const { label, currencies } = paymentMethodsMap[ key ];
if ( availablePaymentMethods.includes( key ) ) {
let isSetupRequired = false;
let setupTooltip = '';
if (
! wcpaySettings.isMultiCurrencyEnabled &&
key !== PAYMENT_METHOD_IDS.CARD
) {
const currency = wcpaySettings.storeCurrency;
if ( currencies.indexOf( currency ) < 0 ) {
isSetupRequired = true;
setupTooltip = BuildMissingCurrenciesTooltipMessage(
label,
currencies
);
}
}
return (
<PaymentMethodCheckbox
key={ key }
checked={
paymentMethodsState[ key ] &&
upeCapabilityStatuses.INACTIVE !==
getStatusAndRequirements( key ).status
}
setupTooltip={ setupTooltip }
isSetupRequired={ isSetupRequired }
status={ getStatusAndRequirements( key ).status }
locked={ isPoInProgress }
onChange={ ( name, status ) => {
handleCheckClick( name, status );
} }
name={ key }
/>
);
}
return '';
} );
};
const availableBuyNowPayLaterUpeMethods = upeMethods.filter(
( id ) =>
paymentMethodsMap[ id ].allows_pay_later &&
availablePaymentMethods.includes( id )
);
return (
<WizardTaskItem
className="add-payment-methods-task"
title={ __(
'Enable additional payment methods',
'woocommerce-payments'
) }
index={ 1 }
>
<CollapsibleBody>
<p className="wcpay-wizard-task__description-element is-muted-color">
{ interpolateComponents( {
mixedString: __(
'Increase your store’s conversion by offering your customers' +
' preferred and convenient payment methods on checkout.',
'woocommerce-payments'
),
components: {
learnMoreLink: (
// eslint-disable-next-line max-len
<ExternalLink href="https://woocommerce.com/document/woopayments/payment-methods/additional-payment-methods/" />
),
},
} ) }
</p>
{ isPoInProgress && (
<Notice
status="warning"
isDismissible={ false }
className="po__notice"
>
<span>
{ __(
'Some payment methods cannot be enabled because more information is needed about your account. ',
'woocommerce-payments'
) }
</span>
<a
// eslint-disable-next-line max-len
href="https://woocommerce.com/document/woopayments/payment-methods/additional-payment-methods/#method-cant-be-enabled"
target="_blank"
rel="external noreferrer noopener"
>
{ __(
'Learn more about enabling additional payment methods.',
'woocommerce-payments'
) }
</a>
</Notice>
) }
<Card
className="add-payment-methods-task__payment-selector-wrapper"
size="small"
>
<CardBody>
{ /* eslint-disable-next-line max-len */ }
<p className="add-payment-methods-task__payment-selector-title wcpay-wizard-task__description-element">
{ __(
'Popular in your country',
'woocommerce-payments'
) }
</p>
<LoadableBlock numLines={ 10 } isLoading={ ! isActive }>
<LoadableSettingsSection numLines={ 10 }>
<PaymentMethodCheckboxes>
<PaymentMethodCheckbox
key="card"
checked={ paymentMethodsState.card }
// The card payment method is required when UPE is active and it can't be deactivated.
required={ true }
locked={ true }
status={
getStatusAndRequirements( 'card' )
.status
}
name="card"
/>
{ prepareUpePaymentMethods(
upeMethods.filter(
( id ) =>
! paymentMethodsMap[ id ]
.allows_pay_later
)
) }
</PaymentMethodCheckboxes>
</LoadableSettingsSection>
</LoadableBlock>
</CardBody>
{ availableBuyNowPayLaterUpeMethods.length > 0 && (
<>
<CardDivider />
<CardBody>
<p className="add-payment-methods-task__payment-selector-title wcpay-wizard-task__description-element">
{ __(
'Buy Now, Pay Later',
'woocommerce-payments'
) }
</p>
<LoadableBlock
numLines={ 10 }
isLoading={ ! isActive }
>
<LoadableSettingsSection numLines={ 10 }>
<PaymentMethodCheckboxes>
{ prepareUpePaymentMethods(
availableBuyNowPayLaterUpeMethods
) }
</PaymentMethodCheckboxes>
</LoadableSettingsSection>
</LoadableBlock>
</CardBody>
</>
) }
{ activationModalParams && (
<ConfirmPaymentMethodActivationModal
onClose={ () => {
handleActivationModalOpen( null );
} }
onConfirmClose={ () => {
completeActivation( activationModalParams.id );
} }
requirements={ activationModalParams.requirements }
paymentMethod={ activationModalParams.id }
/>
) }
</Card>
<CurrencyInformationForMethods
selectedMethods={ selectedMethods }
/>
<LoadableBlock numLines={ 10 } isLoading={ ! isActive }>
<ContinueButton
paymentMethodsState={ paymentMethodsState }
/>
</LoadableBlock>
</CollapsibleBody>
</WizardTaskItem>
);
};
export default AddPaymentMethodsTask;