This repository has been archived by the owner on Feb 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 218
/
payment-method-data-context.tsx
355 lines (334 loc) · 10.2 KB
/
payment-method-data-context.tsx
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
/**
* External dependencies
*/
import {
createContext,
useContext,
useReducer,
useCallback,
useRef,
useEffect,
useMemo,
} from '@wordpress/element';
/**
* Internal dependencies
*/
import type {
CustomerPaymentMethods,
PaymentMethodDataContextType,
} from './types';
import {
STATUS,
DEFAULT_PAYMENT_DATA_CONTEXT_STATE,
DEFAULT_PAYMENT_METHOD_DATA,
} from './constants';
import reducer from './reducer';
import {
usePaymentMethods,
useExpressPaymentMethods,
} from './use-payment-method-registration';
import { usePaymentMethodDataDispatchers } from './use-payment-method-dispatchers';
import { useActivePaymentMethod } from './use-active-payment-method';
import { useCheckoutContext } from '../checkout-state';
import { useEditorContext } from '../../editor-context';
import {
EMIT_TYPES,
useEventEmitters,
emitEventWithAbort,
reducer as emitReducer,
} from './event-emit';
import { useValidationContext } from '../../validation';
import { useStoreNotices } from '../../../hooks/use-store-notices';
import { useEmitResponse } from '../../../hooks/use-emit-response';
import { getCustomerPaymentMethods } from './utils';
const PaymentMethodDataContext = createContext( DEFAULT_PAYMENT_METHOD_DATA );
export const usePaymentMethodDataContext = (): PaymentMethodDataContextType => {
return useContext( PaymentMethodDataContext );
};
/**
* PaymentMethodDataProvider is automatically included in the CheckoutDataProvider.
*
* This provides the api interface (via the context hook) for payment method status and data.
*
* @param {Object} props Incoming props for provider
* @param {Object} props.children The wrapped components in this provider.
*/
export const PaymentMethodDataProvider = ( {
children,
}: {
children: React.ReactNode;
} ): JSX.Element => {
const {
isProcessing: checkoutIsProcessing,
isIdle: checkoutIsIdle,
isCalculating: checkoutIsCalculating,
hasError: checkoutHasError,
} = useCheckoutContext();
const { isEditor, getPreviewData } = useEditorContext();
const { setValidationErrors } = useValidationContext();
const { addErrorNotice, removeNotice } = useStoreNotices();
const {
isSuccessResponse,
isErrorResponse,
isFailResponse,
noticeContexts,
} = useEmitResponse();
const [ observers, observerDispatch ] = useReducer( emitReducer, {} );
const { onPaymentProcessing } = useEventEmitters( observerDispatch );
const currentObservers = useRef( observers );
// ensure observers are always current.
useEffect( () => {
currentObservers.current = observers;
}, [ observers ] );
const [ paymentData, dispatch ] = useReducer(
reducer,
DEFAULT_PAYMENT_DATA_CONTEXT_STATE
);
const {
dispatchActions,
setPaymentStatus,
} = usePaymentMethodDataDispatchers( dispatch );
const paymentMethodsInitialized = usePaymentMethods(
dispatchActions.setRegisteredPaymentMethods
);
const expressPaymentMethodsInitialized = useExpressPaymentMethods(
dispatchActions.setRegisteredExpressPaymentMethods
);
const {
activePaymentMethod,
activeSavedToken,
setActivePaymentMethod,
setActiveSavedToken,
} = useActivePaymentMethod();
const customerPaymentMethods = useMemo( (): CustomerPaymentMethods => {
if ( isEditor ) {
return getPreviewData(
'previewSavedPaymentMethods'
) as CustomerPaymentMethods;
}
return paymentMethodsInitialized
? getCustomerPaymentMethods( paymentData.paymentMethods )
: {};
}, [
isEditor,
getPreviewData,
paymentMethodsInitialized,
paymentData.paymentMethods,
] );
const setExpressPaymentError = useCallback(
( message ) => {
if ( message ) {
addErrorNotice( message, {
id: 'wc-express-payment-error',
context: noticeContexts.EXPRESS_PAYMENTS,
} );
} else {
removeNotice(
'wc-express-payment-error',
noticeContexts.EXPRESS_PAYMENTS
);
}
},
[ addErrorNotice, noticeContexts.EXPRESS_PAYMENTS, removeNotice ]
);
const isExpressPaymentMethodActive = Object.keys(
paymentData.expressPaymentMethods
).includes( activePaymentMethod );
const currentStatus = useMemo(
() => ( {
isPristine: paymentData.currentStatus === STATUS.PRISTINE,
isStarted: paymentData.currentStatus === STATUS.STARTED,
isProcessing: paymentData.currentStatus === STATUS.PROCESSING,
isFinished: [
STATUS.ERROR,
STATUS.FAILED,
STATUS.SUCCESS,
].includes( paymentData.currentStatus ),
hasError: paymentData.currentStatus === STATUS.ERROR,
hasFailed: paymentData.currentStatus === STATUS.FAILED,
isSuccessful: paymentData.currentStatus === STATUS.SUCCESS,
isDoingExpressPayment:
paymentData.currentStatus !== STATUS.PRISTINE &&
isExpressPaymentMethodActive,
} ),
[ paymentData.currentStatus, isExpressPaymentMethodActive ]
);
// Update the active (selected) payment method when it is empty, or invalid.
useEffect( () => {
const paymentMethodKeys = Object.keys( paymentData.paymentMethods );
const allPaymentMethodKeys = [
...paymentMethodKeys,
...Object.keys( paymentData.expressPaymentMethods ),
];
if ( ! paymentMethodsInitialized || ! paymentMethodKeys.length ) {
return;
}
setActivePaymentMethod( ( currentActivePaymentMethod ) => {
// If there's no active payment method, or the active payment method has
// been removed (e.g. COD vs shipping methods), set one as active.
// Note: It's possible that the active payment method might be an
// express payment method. So registered express payment methods are
// included in the check here.
if (
! currentActivePaymentMethod ||
! allPaymentMethodKeys.includes( currentActivePaymentMethod )
) {
setPaymentStatus().pristine();
return Object.keys( paymentData.paymentMethods )[ 0 ];
}
return currentActivePaymentMethod;
} );
}, [
paymentMethodsInitialized,
paymentData.paymentMethods,
paymentData.expressPaymentMethods,
setActivePaymentMethod,
setPaymentStatus,
] );
// flip payment to processing if checkout processing is complete, there are no errors, and payment status is started.
useEffect( () => {
if (
checkoutIsProcessing &&
! checkoutHasError &&
! checkoutIsCalculating &&
! currentStatus.isFinished
) {
setPaymentStatus().processing();
}
}, [
checkoutIsProcessing,
checkoutHasError,
checkoutIsCalculating,
currentStatus.isFinished,
setPaymentStatus,
] );
// When checkout is returned to idle, set payment status to pristine but only if payment status is already not finished.
useEffect( () => {
if ( checkoutIsIdle && ! currentStatus.isSuccessful ) {
setPaymentStatus().pristine();
}
}, [ checkoutIsIdle, currentStatus.isSuccessful, setPaymentStatus ] );
// if checkout has an error and payment is not being made with a saved token and payment status is success, then let's sync payment status back to pristine.
useEffect( () => {
if (
checkoutHasError &&
currentStatus.isSuccessful &&
! paymentData.hasSavedToken
) {
setPaymentStatus().pristine();
}
}, [
checkoutHasError,
currentStatus.isSuccessful,
paymentData.hasSavedToken,
setPaymentStatus,
] );
useEffect( () => {
// Note: the nature of this event emitter is that it will bail on any
// observer that returns a response that !== true. However, this still
// allows for other observers that return true for continuing through
// to the next observer (or bailing if there's a problem).
if ( currentStatus.isProcessing ) {
removeNotice( 'wc-payment-error', noticeContexts.PAYMENTS );
emitEventWithAbort(
currentObservers.current,
EMIT_TYPES.PAYMENT_PROCESSING,
{}
).then( ( observerResponses ) => {
let successResponse, errorResponse;
observerResponses.forEach( ( response ) => {
if ( isSuccessResponse( response ) ) {
// the last observer response always "wins" for success.
successResponse = response;
}
if (
isErrorResponse( response ) ||
isFailResponse( response )
) {
errorResponse = response;
}
} );
if ( successResponse && ! errorResponse ) {
setPaymentStatus().success(
successResponse?.meta?.paymentMethodData,
successResponse?.meta?.billingData,
successResponse?.meta?.shippingData
);
} else if ( errorResponse && isFailResponse( errorResponse ) ) {
if (
errorResponse.message &&
errorResponse.message.length
) {
addErrorNotice( errorResponse.message, {
id: 'wc-payment-error',
isDismissible: false,
context:
errorResponse?.messageContext ||
noticeContexts.PAYMENTS,
} );
}
setPaymentStatus().failed(
errorResponse?.message,
errorResponse?.meta?.paymentMethodData,
errorResponse?.meta?.billingData
);
} else if ( errorResponse ) {
if (
errorResponse.message &&
errorResponse.message.length
) {
addErrorNotice( errorResponse.message, {
id: 'wc-payment-error',
isDismissible: false,
context:
errorResponse?.messageContext ||
noticeContexts.PAYMENTS,
} );
}
setPaymentStatus().error( errorResponse.message );
setValidationErrors( errorResponse?.validationErrors );
} else {
// otherwise there are no payment methods doing anything so
// just consider success
setPaymentStatus().success();
}
} );
}
}, [
currentStatus.isProcessing,
setValidationErrors,
setPaymentStatus,
removeNotice,
noticeContexts.PAYMENTS,
isSuccessResponse,
isFailResponse,
isErrorResponse,
addErrorNotice,
] );
const paymentContextData: PaymentMethodDataContextType = {
setPaymentStatus,
currentStatus,
paymentStatuses: STATUS,
paymentMethodData: paymentData.paymentMethodData,
errorMessage: paymentData.errorMessage,
activePaymentMethod,
setActivePaymentMethod,
activeSavedToken,
setActiveSavedToken,
onPaymentProcessing,
customerPaymentMethods,
paymentMethods: paymentData.paymentMethods,
expressPaymentMethods: paymentData.expressPaymentMethods,
paymentMethodsInitialized,
expressPaymentMethodsInitialized,
setExpressPaymentError,
isExpressPaymentMethodActive,
shouldSavePayment: paymentData.shouldSavePaymentMethod,
setShouldSavePayment: dispatchActions.setShouldSavePayment,
};
return (
<PaymentMethodDataContext.Provider value={ paymentContextData }>
{ children }
</PaymentMethodDataContext.Provider>
);
};