@riosst100/pwa-marketplace 2.5.0 → 2.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,574 @@
1
+ import { useCallback, useEffect, useState, useMemo } from 'react';
2
+ import { useFormState, useFormApi } from 'informed';
3
+ import { useQuery, useApolloClient, useMutation } from '@apollo/client';
4
+ import mergeOperations from '@magento/peregrine/lib/util/shallowMerge';
5
+
6
+ import { useCartContext } from '@magento/peregrine/lib/context/cart';
7
+
8
+ import DEFAULT_OPERATIONS from './xendit.gql';
9
+ import { useGoogleReCaptcha } from '@magento/peregrine/lib/hooks/useGoogleReCaptcha';
10
+
11
+ const getRegion = region => {
12
+ return region.region_id || region.label || region.code;
13
+ };
14
+
15
+ /**
16
+ * Maps address response data from GET_BILLING_ADDRESS and GET_SHIPPING_ADDRESS
17
+ * queries to input names in the billing address form.
18
+ * {@link creditCard.gql.js}.
19
+ *
20
+ * @param {ShippingCartAddress|BillingCartAddress} rawAddressData query data
21
+ */
22
+ export const mapAddressData = rawAddressData => {
23
+ if (rawAddressData) {
24
+ const {
25
+ firstName,
26
+ lastName,
27
+ city,
28
+ postcode,
29
+ phoneNumber,
30
+ street,
31
+ country,
32
+ region
33
+ } = rawAddressData;
34
+
35
+ return {
36
+ firstName,
37
+ lastName,
38
+ city,
39
+ postcode,
40
+ phoneNumber,
41
+ street1: street[0],
42
+ street2: street[1] || '',
43
+ country: country.code,
44
+ region: getRegion(region)
45
+ };
46
+ } else {
47
+ return {};
48
+ }
49
+ };
50
+
51
+ /**
52
+ * Talon to handle Credit Card payment method.
53
+ *
54
+ * @param {Boolean} props.shouldSubmit boolean value which represents if a payment nonce request has been submitted
55
+ * @param {Function} props.onSuccess callback to invoke when the a payment nonce has been generated
56
+ * @param {Function} props.onReady callback to invoke when the braintree dropin component is ready
57
+ * @param {Function} props.onError callback to invoke when the braintree dropin component throws an error
58
+ * @param {Function} props.resetShouldSubmit callback to reset the shouldSubmit flag
59
+ * @param {DocumentNode} props.operations.getBillingAddressQuery query to fetch billing address from cache
60
+ * @param {DocumentNode} props.operations.getIsBillingAddressSameQuery query to fetch is billing address same checkbox value from cache
61
+ * @param {DocumentNode} props.operations.getPaymentNonceQuery query to fetch payment nonce saved in cache
62
+ * @param {DocumentNode} props.operations.setBillingAddressMutation mutation to update billing address on the cart
63
+ * @param {DocumentNode} props.operations.setCreditCardDetailsOnCartMutation mutation to update payment method and payment nonce on the cart
64
+ *
65
+ * @returns {
66
+ * errors: Map<String, Error>,
67
+ * shouldRequestPaymentNonce: Boolean,
68
+ * onPaymentError: Function,
69
+ * onPaymentSuccess: Function,
70
+ * onPaymentReady: Function,
71
+ * isBillingAddressSame: Boolean,
72
+ * isLoading: Boolean,
73
+ * stepNumber: Number,
74
+ * initialValues: {
75
+ * firstName: String,
76
+ * lastName: String,
77
+ * city: String,
78
+ * postcode: String,
79
+ * phoneNumber: String,
80
+ * street1: String,
81
+ * street2: String,
82
+ * country: String,
83
+ * state: String,
84
+ * isBillingAddressSame: Boolean
85
+ * },
86
+ * shippingAddressCountry: String,
87
+ * shouldTeardownDropin: Boolean,
88
+ * resetShouldTeardownDropin: Function
89
+ * }
90
+ */
91
+ export const useXendit = props => {
92
+ const {
93
+ onSuccess,
94
+ onReady,
95
+ onError,
96
+ shouldSubmit,
97
+ resetShouldSubmit
98
+ } = props;
99
+
100
+ const operations = mergeOperations(DEFAULT_OPERATIONS, props.operations);
101
+
102
+ const {
103
+ getBillingAddressQuery,
104
+ getIsBillingAddressSameQuery,
105
+ getPaymentNonceQuery,
106
+ getShippingAddressQuery,
107
+ setBillingAddressMutation,
108
+ setCreditCardDetailsOnCartMutation
109
+ } = operations;
110
+
111
+ const {
112
+ recaptchaLoading,
113
+ generateReCaptchaData,
114
+ recaptchaWidgetProps
115
+ } = useGoogleReCaptcha({
116
+ currentForm: 'BRAINTREE',
117
+ formAction: 'braintree'
118
+ });
119
+
120
+ /**
121
+ * Definitions
122
+ */
123
+
124
+ const [isDropinLoading, setDropinLoading] = useState(true);
125
+ const [shouldRequestPaymentNonce, setShouldRequestPaymentNonce] = useState(
126
+ false
127
+ );
128
+ const [shouldTeardownDropin, setShouldTeardownDropin] = useState(false);
129
+ /**
130
+ * `stepNumber` depicts the state of the process flow in credit card
131
+ * payment flow.
132
+ *
133
+ * `0` No call made yet
134
+ * `1` Billing address mutation initiated
135
+ * `2` Braintree nonce requested
136
+ * `3` Payment information mutation initiated
137
+ * `4` All mutations done
138
+ */
139
+ const [stepNumber, setStepNumber] = useState(0);
140
+
141
+ const client = useApolloClient();
142
+ const formState = useFormState();
143
+ const { validate: validateBillingAddressForm } = useFormApi();
144
+ const [{ cartId }] = useCartContext();
145
+
146
+ const isLoading =
147
+ isDropinLoading ||
148
+ recaptchaLoading ||
149
+ (stepNumber >= 1 && stepNumber <= 3);
150
+
151
+ const { data: billingAddressData } = useQuery(getBillingAddressQuery, {
152
+ skip: !cartId,
153
+ variables: { cartId }
154
+ });
155
+ const { data: shippingAddressData } = useQuery(getShippingAddressQuery, {
156
+ skip: !cartId,
157
+ variables: { cartId }
158
+ });
159
+ const { data: isBillingAddressSameData } = useQuery(
160
+ getIsBillingAddressSameQuery,
161
+ { skip: !cartId, variables: { cartId } }
162
+ );
163
+ const [
164
+ updateBillingAddress,
165
+ {
166
+ error: billingAddressMutationError,
167
+ called: billingAddressMutationCalled,
168
+ loading: billingAddressMutationLoading
169
+ }
170
+ ] = useMutation(setBillingAddressMutation);
171
+
172
+ const [
173
+ updateCCDetails,
174
+ {
175
+ error: ccMutationError,
176
+ called: ccMutationCalled,
177
+ loading: ccMutationLoading
178
+ }
179
+ ] = useMutation(setCreditCardDetailsOnCartMutation);
180
+
181
+ const shippingAddressCountry = shippingAddressData
182
+ ? shippingAddressData.cart.shippingAddresses[0].country.code
183
+ : DEFAULT_COUNTRY_CODE;
184
+ const isBillingAddressSame = formState.values.isBillingAddressSame;
185
+
186
+ const initialValues = useMemo(() => {
187
+ const isBillingAddressSame = isBillingAddressSameData
188
+ ? isBillingAddressSameData.cart.isBillingAddressSame
189
+ : true;
190
+
191
+ let billingAddress = {};
192
+ /**
193
+ * If billing address is same as shipping address, do
194
+ * not auto fill the fields.
195
+ */
196
+ if (billingAddressData && !isBillingAddressSame) {
197
+ if (billingAddressData.cart.billingAddress) {
198
+ const {
199
+ // eslint-disable-next-line no-unused-vars
200
+ __typename,
201
+ ...rawBillingAddress
202
+ } = billingAddressData.cart.billingAddress;
203
+ billingAddress = mapAddressData(rawBillingAddress);
204
+ }
205
+ }
206
+
207
+ return { isBillingAddressSame, ...billingAddress };
208
+ }, [isBillingAddressSameData, billingAddressData]);
209
+
210
+ /**
211
+ * Helpers
212
+ */
213
+
214
+ /**
215
+ * This function sets the boolean isBillingAddressSame
216
+ * in cache for future use. We use cache because there
217
+ * is no way to save this on the cart in remote.
218
+ */
219
+ const setIsBillingAddressSameInCache = useCallback(() => {
220
+ client.writeQuery({
221
+ query: getIsBillingAddressSameQuery,
222
+ data: {
223
+ cart: {
224
+ __typename: 'Cart',
225
+ id: cartId,
226
+ isBillingAddressSame
227
+ }
228
+ }
229
+ });
230
+ }, [client, cartId, getIsBillingAddressSameQuery, isBillingAddressSame]);
231
+
232
+ /**
233
+ * This function sets the billing address on the cart using the
234
+ * shipping address.
235
+ */
236
+ const setShippingAddressAsBillingAddress = useCallback(() => {
237
+ var shippingAddress = shippingAddressData
238
+ ? mapAddressData(shippingAddressData.cart.shippingAddresses[0])
239
+ : {};
240
+
241
+ shippingAddress.region =
242
+ shippingAddress.region == null ? '' : shippingAddress.region;
243
+
244
+ updateBillingAddress({
245
+ variables: {
246
+ cartId,
247
+ ...shippingAddress,
248
+ sameAsShipping: true
249
+ }
250
+ });
251
+ }, [updateBillingAddress, shippingAddressData, cartId]);
252
+
253
+ /**
254
+ * This function sets the billing address on the cart using the
255
+ * information from the form.
256
+ */
257
+ const setBillingAddress = useCallback(() => {
258
+ const {
259
+ firstName,
260
+ lastName,
261
+ country,
262
+ street1,
263
+ street2,
264
+ city,
265
+ region,
266
+ postcode,
267
+ phoneNumber
268
+ } = formState.values;
269
+
270
+ updateBillingAddress({
271
+ variables: {
272
+ cartId,
273
+ firstName,
274
+ lastName,
275
+ country,
276
+ street1,
277
+ street2: street2 || '',
278
+ city,
279
+ region: getRegion(region),
280
+ postcode,
281
+ phoneNumber,
282
+ sameAsShipping: false
283
+ }
284
+ });
285
+ }, [formState.values, updateBillingAddress, cartId]);
286
+
287
+ /**
288
+ * This function sets the payment nonce details in the cache.
289
+ * We use cache because there is no way to save this information
290
+ * on the cart in the remote.
291
+ *
292
+ * We do not save the nonce code because it is a PII.
293
+ */
294
+ const setPaymentDetailsInCache = useCallback(
295
+ braintreeNonce => {
296
+ /**
297
+ * We dont save the nonce code due to PII,
298
+ * we only save the subset of details.
299
+ */
300
+ const { details, description, type } = braintreeNonce;
301
+ client.writeQuery({
302
+ query: getPaymentNonceQuery,
303
+ data: {
304
+ cart: {
305
+ __typename: 'Cart',
306
+ id: cartId,
307
+ paymentNonce: {
308
+ details,
309
+ description,
310
+ type
311
+ }
312
+ }
313
+ }
314
+ });
315
+ },
316
+ [cartId, client, getPaymentNonceQuery]
317
+ );
318
+
319
+ /**
320
+ * This function saves the nonce code from braintree
321
+ * on the cart along with the payment method used in
322
+ * this case `braintree`.
323
+ */
324
+ const updateCCDetailsOnCart = useCallback(
325
+ async braintreeNonce => {
326
+ try {
327
+ const { nonce } = braintreeNonce;
328
+ const reCaptchaData = await generateReCaptchaData();
329
+
330
+ await updateCCDetails({
331
+ variables: {
332
+ cartId,
333
+ paymentMethod: 'braintree',
334
+ paymentNonce: nonce
335
+ },
336
+ ...reCaptchaData
337
+ });
338
+ } catch (error) {
339
+ // Error is logged by apollo link - no need to double log.
340
+ }
341
+ },
342
+ [updateCCDetails, cartId, generateReCaptchaData]
343
+ );
344
+
345
+ /**
346
+ * Function to be called by the braintree dropin when the
347
+ * nonce generation is successful.
348
+ */
349
+ const onPaymentSuccess = useCallback(
350
+ braintreeNonce => {
351
+ setPaymentDetailsInCache(braintreeNonce);
352
+ /**
353
+ * Updating payment braintreeNonce and selected payment method on cart.
354
+ */
355
+ updateCCDetailsOnCart(braintreeNonce);
356
+ setStepNumber(3);
357
+ },
358
+ [setPaymentDetailsInCache, updateCCDetailsOnCart]
359
+ );
360
+
361
+ /**
362
+ * Function to be called by the braintree dropin when the
363
+ * nonce generation is not successful.
364
+ */
365
+ const onPaymentError = useCallback(
366
+ error => {
367
+ setStepNumber(0);
368
+ setShouldRequestPaymentNonce(false);
369
+ resetShouldSubmit();
370
+ if (onError) {
371
+ onError(error);
372
+ }
373
+ },
374
+ [onError, resetShouldSubmit]
375
+ );
376
+
377
+ /**
378
+ * Function to be called by the braintree dropin when the
379
+ * credit card component has loaded successfully.
380
+ */
381
+ const onPaymentReady = useCallback(() => {
382
+ setDropinLoading(false);
383
+ setStepNumber(0);
384
+ if (onReady) {
385
+ onReady();
386
+ }
387
+ }, [onReady]);
388
+
389
+ /**
390
+ * Function to be called by braintree dropin when the payment
391
+ * teardown is done successfully before re creating the new dropin.
392
+ */
393
+ const resetShouldTeardownDropin = useCallback(() => {
394
+ setShouldTeardownDropin(false);
395
+ }, []);
396
+
397
+ /**
398
+ * Effects
399
+ */
400
+
401
+ /**
402
+ * Step 1 effect
403
+ *
404
+ * User has clicked the update button
405
+ */
406
+ useEffect(() => {
407
+ try {
408
+ if (shouldSubmit) {
409
+ /**
410
+ * Validate billing address fields and only process with
411
+ * submit if there are no errors.
412
+ *
413
+ * We do this because the user can click Review Order button
414
+ * without fillig in all fields and the form submission
415
+ * happens manually. The informed Form component validates
416
+ * on submission but that only happens when we use the onSubmit
417
+ * prop. In this case we are using manually submission because
418
+ * of the nature of the credit card submission process.
419
+ */
420
+ validateBillingAddressForm();
421
+
422
+ const hasErrors = Object.keys(formState.errors).length;
423
+
424
+ if (!hasErrors) {
425
+ setStepNumber(1);
426
+ if (isBillingAddressSame) {
427
+ setShippingAddressAsBillingAddress();
428
+ } else {
429
+ setBillingAddress();
430
+ }
431
+ setIsBillingAddressSameInCache();
432
+ } else {
433
+ throw new Error('Errors in the billing address form');
434
+ }
435
+ }
436
+ } catch (err) {
437
+ if (process.env.NODE_ENV !== 'production') {
438
+ console.error(err);
439
+ }
440
+ setStepNumber(0);
441
+ resetShouldSubmit();
442
+ setShouldRequestPaymentNonce(false);
443
+ }
444
+ }, [
445
+ shouldSubmit,
446
+ isBillingAddressSame,
447
+ setShippingAddressAsBillingAddress,
448
+ setBillingAddress,
449
+ setIsBillingAddressSameInCache,
450
+ resetShouldSubmit,
451
+ validateBillingAddressForm,
452
+ formState.errors
453
+ ]);
454
+
455
+ /**
456
+ * Step 2 effect
457
+ *
458
+ * Billing address mutation has completed
459
+ */
460
+ useEffect(() => {
461
+ try {
462
+ const billingAddressMutationCompleted =
463
+ billingAddressMutationCalled && !billingAddressMutationLoading;
464
+
465
+ if (
466
+ billingAddressMutationCompleted &&
467
+ !billingAddressMutationError
468
+ ) {
469
+ /**
470
+ * Billing address save mutation is successful
471
+ * we can initiate the braintree nonce request
472
+ */
473
+ setStepNumber(2);
474
+ setShouldRequestPaymentNonce(true);
475
+ }
476
+
477
+ if (
478
+ billingAddressMutationCompleted &&
479
+ billingAddressMutationError
480
+ ) {
481
+ /**
482
+ * Billing address save mutation is not successful.
483
+ * Reset update button clicked flag.
484
+ */
485
+ throw new Error('Billing address mutation failed');
486
+ }
487
+ } catch (err) {
488
+ if (process.env.NODE_ENV !== 'production') {
489
+ console.error(err);
490
+ }
491
+ setStepNumber(0);
492
+ resetShouldSubmit();
493
+ setShouldRequestPaymentNonce(false);
494
+ }
495
+ }, [
496
+ billingAddressMutationError,
497
+ billingAddressMutationCalled,
498
+ billingAddressMutationLoading,
499
+ resetShouldSubmit
500
+ ]);
501
+
502
+ /**
503
+ * Step 3 effect
504
+ *
505
+ * Credit card save mutation has completed
506
+ */
507
+ useEffect(() => {
508
+ /**
509
+ * Saved billing address, payment method and payment nonce on cart.
510
+ *
511
+ * Time to call onSuccess.
512
+ */
513
+
514
+ try {
515
+ const ccMutationCompleted = ccMutationCalled && !ccMutationLoading;
516
+
517
+ if (ccMutationCompleted && !ccMutationError) {
518
+ if (onSuccess) {
519
+ onSuccess();
520
+ }
521
+ resetShouldSubmit();
522
+ setStepNumber(4);
523
+ }
524
+
525
+ if (ccMutationCompleted && ccMutationError) {
526
+ /**
527
+ * If credit card mutation failed, reset update button clicked so the
528
+ * user can click again and set `stepNumber` to 0.
529
+ */
530
+ throw new Error('Credit card nonce save mutation failed.');
531
+ }
532
+ } catch (err) {
533
+ if (process.env.NODE_ENV !== 'production') {
534
+ console.error(err);
535
+ }
536
+ setStepNumber(0);
537
+ resetShouldSubmit();
538
+ setShouldRequestPaymentNonce(false);
539
+ setShouldTeardownDropin(true);
540
+ }
541
+ }, [
542
+ ccMutationCalled,
543
+ ccMutationLoading,
544
+ onSuccess,
545
+ setShouldRequestPaymentNonce,
546
+ resetShouldSubmit,
547
+ ccMutationError
548
+ ]);
549
+
550
+ const errors = useMemo(
551
+ () =>
552
+ new Map([
553
+ ['setBillingAddressMutation', billingAddressMutationError],
554
+ ['setCreditCardDetailsOnCartMutation', ccMutationError]
555
+ ]),
556
+ [billingAddressMutationError, ccMutationError]
557
+ );
558
+
559
+ return {
560
+ errors,
561
+ onPaymentError,
562
+ onPaymentSuccess,
563
+ onPaymentReady,
564
+ isBillingAddressSame,
565
+ isLoading,
566
+ shouldRequestPaymentNonce,
567
+ stepNumber,
568
+ initialValues,
569
+ shippingAddressCountry,
570
+ shouldTeardownDropin,
571
+ resetShouldTeardownDropin,
572
+ recaptchaWidgetProps
573
+ };
574
+ };