-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathindex.jsx
More file actions
725 lines (669 loc) · 31 KB
/
index.jsx
File metadata and controls
725 lines (669 loc) · 31 KB
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
/*
* Copyright (c) 2021, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import React, {useEffect, useState} from 'react'
import {
Alert,
AlertIcon,
Box,
Button,
Container,
Grid,
GridItem,
Stack,
Portal,
Spinner,
Center
} from '@salesforce/retail-react-app/app/components/shared/ui'
import {FormattedMessage, useIntl} from 'react-intl'
import {useForm} from 'react-hook-form'
import {
useShopperBasketsMutation,
useShopperOrdersMutation,
useShopperCustomersMutation,
ShopperBasketsMutations,
ShopperOrdersMutations
} from '@salesforce/commerce-sdk-react'
import {useToast} from '@salesforce/retail-react-app/app/hooks/use-toast'
import useNavigation from '@salesforce/retail-react-app/app/hooks/use-navigation'
import {
useCheckout,
CheckoutProvider
} from '@salesforce/retail-react-app/app/pages/checkout-one-click/util/checkout-context'
import ContactInfo from '@salesforce/retail-react-app/app/pages/checkout-one-click/partials/one-click-contact-info'
import PickupAddress from '@salesforce/retail-react-app/app/pages/checkout-one-click/partials/one-click-pickup-address'
import ShippingAddress from '@salesforce/retail-react-app/app/pages/checkout-one-click/partials/one-click-shipping-address'
import ShippingOptions from '@salesforce/retail-react-app/app/pages/checkout-one-click/partials/one-click-shipping-options'
import Payment from '@salesforce/retail-react-app/app/pages/checkout-one-click/partials/one-click-payment'
import {useCurrentCustomer} from '@salesforce/retail-react-app/app/hooks/use-current-customer'
import CheckoutSkeleton from '@salesforce/retail-react-app/app/pages/checkout-one-click/partials/one-click-checkout-skeleton'
import UnavailableProductConfirmationModal from '@salesforce/retail-react-app/app/components/unavailable-product-confirmation-modal'
import LoadingSpinner from '@salesforce/retail-react-app/app/components/loading-spinner'
import {isPickupShipment} from '@salesforce/retail-react-app/app/utils/shipment-utils'
import OrderSummary from '@salesforce/retail-react-app/app/components/order-summary'
import {useCurrentBasket} from '@salesforce/retail-react-app/app/hooks/use-current-basket'
import {useMultiship} from '@salesforce/retail-react-app/app/hooks/use-multiship'
import {
API_ERROR_MESSAGE,
TOAST_MESSAGE_REMOVED_ITEM_FROM_CART
} from '@salesforce/retail-react-app/app/constants'
import {getConfig} from '@salesforce/pwa-kit-runtime/utils/ssr-config'
import {
getPaymentInstrumentCardType,
getMaskCreditCardNumber
} from '@salesforce/retail-react-app/app/utils/cc-utils'
import {nanoid} from 'nanoid'
const CheckoutOneClick = () => {
const {formatMessage} = useIntl()
const navigate = useNavigation()
const {step, STEPS, contactPhone} = useCheckout()
const showToast = useToast()
const [isLoading, setIsLoading] = useState(false)
const [enableUserRegistration, setEnableUserRegistration] = useState(false)
const [registeredUserChoseGuest, setRegisteredUserChoseGuest] = useState(false)
const [shouldSavePaymentMethod, setShouldSavePaymentMethod] = useState(false)
const [isOtpLoading, setIsOtpLoading] = useState(false)
const [isPlacingOrder, setIsPlacingOrder] = useState(false)
const currentBasketQuery = useCurrentBasket()
const {data: basket} = currentBasketQuery
const {data: currentCustomer} = useCurrentCustomer()
const {removeEmptyShipments} = useMultiship(basket)
const [error] = useState()
const {social = {}} = getConfig().app.login || {}
const idps = social?.idps
const isSocialEnabled = !!social?.enabled
const createCustomerPaymentInstruments = useShopperCustomersMutation(
'createCustomerPaymentInstrument'
)
// The last applied payment instrument on the card. We need to track to save it on the customer profile upon registration
// as the payment instrument on order only contains the masked number.
const [selectedPaymentMethod, setSelectedPaymentMethod] = useState(null)
const [isEditingPayment, setIsEditingPayment] = useState(false)
// Compute shipment types (consider only shipments that have items assigned)
const allShipments = basket?.shipments || []
const productItems = basket?.productItems || []
const shipmentsWithItems = allShipments.filter((s) =>
productItems.some((i) => i.shipmentId === s.shipmentId)
)
const pickupShipments = shipmentsWithItems.filter(
(s) => isPickupShipment(s) || !!s.c_fromStoreId
)
const deliveryShipments = shipmentsWithItems.filter((s) => !isPickupShipment(s))
const hasPickupShipments = pickupShipments.length > 0
const hasDeliveryShipments = deliveryShipments.length > 0
const isPickupOnly = hasPickupShipments && !hasDeliveryShipments
const [billingSameAsShipping, setBillingSameAsShipping] = useState(true)
// For billing=shipping, align with legacy: use the first delivery shipment's address
const selectedShippingAddress =
deliveryShipments.length > 0 ? deliveryShipments[0]?.shippingAddress : null
const selectedBillingAddress = basket?.billingAddress
// appliedPayment includes both manually entered payment instruments and saved payment instruments
// that have been applied to the basket via addPaymentInstrumentToBasket
const appliedPayment = basket?.paymentInstruments && basket?.paymentInstruments[0]
const {mutateAsync: addPaymentInstrumentToBasket} = useShopperBasketsMutation(
ShopperBasketsMutations.AddPaymentInstrumentToBasket
)
const {mutateAsync: removePaymentInstrumentFromBasket} = useShopperBasketsMutation(
ShopperBasketsMutations.RemovePaymentInstrumentFromBasket
)
const {mutateAsync: updateBillingAddressForBasket} = useShopperBasketsMutation(
ShopperBasketsMutations.UpdateBillingAddressForBasket
)
const {mutateAsync: createOrder} = useShopperOrdersMutation(ShopperOrdersMutations.CreateOrder)
const createCustomerAddress = useShopperCustomersMutation('createCustomerAddress')
const updateCustomer = useShopperCustomersMutation('updateCustomer')
const handleSavePreferenceChange = (shouldSave) => {
setShouldSavePaymentMethod(shouldSave)
}
const showError = (message) => {
showToast({
title: message || formatMessage(API_ERROR_MESSAGE),
status: 'error'
})
}
// Remove any empty shipments whenever navigating to the checkout page
// Using basketId ensures that the basket is in a valid state before removing empty shipments
useEffect(() => {
if (basket?.shipments?.length > 1) {
removeEmptyShipments(basket)
}
}, [basket?.basketId])
// Form for payment method
const paymentMethodForm = useForm({
mode: 'onChange',
shouldUnregister: false,
defaultValues: {
holder: '',
number: '',
cardType: '',
expiry: ''
}
})
// Form for billing address
const billingAddressForm = useForm({
mode: 'onTouched',
reValidateMode: 'onChange',
shouldUnregister: false,
defaultValues: {...selectedBillingAddress}
})
const onPaymentSubmit = async (formValue) => {
// The form gives us the expiration date as `MM/YY` - so we need to split it into
// month and year to submit them as individual fields.
const [expirationMonth, expirationYear] = formValue.expiry.split('/')
const paymentInstrument = {
amount: basket?.orderTotal || 0,
paymentMethodId: 'CREDIT_CARD',
paymentCard: {
holder: formValue.holder,
maskedNumber: getMaskCreditCardNumber(formValue.number),
cardType: getPaymentInstrumentCardType(formValue.cardType),
expirationMonth: parseInt(expirationMonth),
expirationYear: parseInt(`20${expirationYear}`)
}
}
return addPaymentInstrumentToBasket({
parameters: {basketId: basket?.basketId},
body: paymentInstrument
})
}
// Reset guest checkout flag when step changes (user goes back to edit)
useEffect(() => {
if (step === 0) {
setRegisteredUserChoseGuest(false)
}
}, [step])
// Ensure saved payment radio is selected when entering Payment with an applied instrument
useEffect(() => {
if (step === STEPS.PAYMENT && appliedPayment?.customerPaymentInstrumentId) {
setSelectedPaymentMethod(appliedPayment.customerPaymentInstrumentId)
}
}, [step, appliedPayment?.customerPaymentInstrumentId, STEPS.PAYMENT])
// Clamp when cart becomes pickup-only; preserve shopper choice otherwise
useEffect(() => {
if (isPickupOnly) {
setBillingSameAsShipping(false)
}
}, [isPickupOnly])
const onBillingSubmit = async () => {
let billingAddress
if (billingSameAsShipping && selectedShippingAddress) {
billingAddress = selectedShippingAddress
// Validate that shipping address has required address fields
if (!billingAddress?.address1) {
showError(
formatMessage({
id: 'checkout.error.billing_address_required',
defaultMessage: 'Please enter a billing address.'
})
)
return
}
} else {
// Validate all required address fields (excluding phone for billing)
const fieldsToValidate = [
'address1',
'firstName',
'lastName',
'city',
'stateCode',
'postalCode',
'countryCode'
]
// First, mark all fields as touched so errors will be displayed when validation runs
// This must happen BEFORE trigger() so errors show immediately
fieldsToValidate.forEach((field) => {
const currentValue = billingAddressForm.getValues(field) || ''
billingAddressForm.setValue(field, currentValue, {
shouldValidate: false,
shouldTouch: true
})
})
// Now trigger validation - errors will show because fields are already touched
const isFormValid = await billingAddressForm.trigger(fieldsToValidate)
if (!isFormValid) {
// Payment section should already be open from onPlaceOrder
// Focus on the first name field (first field in the form)
setTimeout(() => {
billingAddressForm.setFocus('firstName')
}, 100)
return
}
billingAddress = billingAddressForm.getValues()
// Double-check that address is present
if (!billingAddress?.address1) {
showError(
formatMessage({
id: 'checkout.error.billing_address_required',
defaultMessage: 'Please enter a billing address.'
})
)
setIsEditingPayment(true)
return
}
}
const latestBasketId = currentBasketQuery.data?.basketId || basket.basketId
return await updateBillingAddressForBasket({
body: billingAddress,
parameters: {basketId: latestBasketId}
})
}
const submitOrder = async (fullCardDetails) => {
const savePaymentInstrumentWithDetails = async (
customerId,
paymentMethodId,
fullCardDetails
) => {
try {
// Set as default only for newly registered users (guests who just registered)
const isNewlyRegisteredUser =
enableUserRegistration &&
currentCustomer?.isRegistered &&
!registeredUserChoseGuest
const paymentInstrument = {
paymentMethodId: paymentMethodId,
default: isNewlyRegisteredUser,
paymentCard: {
holder: fullCardDetails.holder,
number: fullCardDetails.number,
cardType: fullCardDetails.cardType,
expirationMonth: fullCardDetails.expirationMonth,
expirationYear: fullCardDetails.expirationYear
}
}
await createCustomerPaymentInstruments.mutateAsync({
body: paymentInstrument,
parameters: {customerId: customerId}
})
} catch (error) {
if (shouldSavePaymentMethod) {
showError(
formatMessage({
id: 'checkout_payment.error.cannot_save_payment',
defaultMessage: 'Could not save payment method. Please try again.'
})
)
}
}
}
// Save payment instrument for existing registered users if they checked the save box
const savePaymentInstrumentForRegisteredUser = async (
customerId,
orderPaymentInstrument,
fullCardDetails
) => {
try {
if (orderPaymentInstrument && fullCardDetails) {
await savePaymentInstrumentWithDetails(
customerId,
orderPaymentInstrument.paymentMethodId,
fullCardDetails
)
}
} catch (error) {
console.error(
'Debug - Failed to save payment instrument for registered user:',
error
)
// Fail silently
}
}
setIsLoading(true)
try {
// Ensure we are using the freshest basket id
const refreshed = await currentBasketQuery.refetch()
const latestBasketId = refreshed.data?.basketId || basket.basketId
// Create order with the latest basket
const order = await createOrder({
body: {basketId: latestBasketId}
})
// If user is registered at this point, optionally save payment method
{
// For existing registered users, save payment instrument if they checked the save box
// Only save if we have full card details (i.e., user entered a new card)
if (
currentCustomer?.isRegistered &&
!registeredUserChoseGuest &&
shouldSavePaymentMethod &&
order.paymentInstruments?.[0] &&
fullCardDetails
) {
const paymentInstrument = order.paymentInstruments[0]
await savePaymentInstrumentForRegisteredUser(
order.customerInfo.customerId,
paymentInstrument,
fullCardDetails
)
}
// For newly registered guests only, persist shipping address when billing same as shipping
// Skip saving pickup/store addresses - only save delivery addresses
// For multi-shipment orders, save all delivery addresses with the first one as default
if (
enableUserRegistration &&
currentCustomer?.isRegistered &&
!registeredUserChoseGuest
) {
try {
const customerId = order.customerInfo?.customerId
if (!customerId) return
// Get all delivery shipments (not pickup) from the order
// This handles both single delivery and multi-shipment orders
// For BOPIS orders, pickup shipments are filtered out
const deliveryShipments =
order?.shipments?.filter(
(shipment) =>
!isPickupShipment(shipment) && shipment.shippingAddress
) || []
if (deliveryShipments.length > 0) {
// Save all delivery addresses, with the first one as preferred
for (let i = 0; i < deliveryShipments.length; i++) {
const shipment = deliveryShipments[i]
const shipping = shipment.shippingAddress
if (!shipping) continue
// Whitelist fields and strip non-customer fields (e.g., id, _type)
const {
address1,
address2,
city,
countryCode,
firstName,
lastName,
phone,
postalCode,
stateCode
} = shipping || {}
await createCustomerAddress.mutateAsync({
parameters: {customerId},
body: {
addressId: nanoid(),
preferred: i === 0, // First address is preferred
address1,
address2,
city,
countryCode,
firstName,
lastName,
phone,
postalCode,
stateCode
}
})
}
}
// Persist phone number as phoneHome for newly registered guest shoppers
const phoneHome = basket?.billingAddress?.phone || contactPhone
if (phoneHome) {
await updateCustomer.mutateAsync({
parameters: {customerId},
body: {phoneHome}
})
}
} catch (_e) {
// Only surface error if shopper opted to register/save details; otherwise fail silently
showError(
formatMessage({
id: 'checkout.error.cannot_save_address',
defaultMessage: 'Could not save shipping address.'
})
)
}
}
}
navigate(`/checkout/confirmation/${order.orderNo}`)
} catch (error) {
const message = formatMessage({
id: 'checkout.message.generic_error',
defaultMessage: 'An unexpected error occurred during checkout.'
})
showError(message)
setIsPlacingOrder(false)
} finally {
setIsLoading(false)
}
}
const onPlaceOrder = async () => {
// Show overlay immediately to prevent double-clicking
setIsPlacingOrder(true)
try {
// Check if we have form values (new card entered)
const paymentFormValues = paymentMethodForm.getValues()
const hasFormValues = paymentFormValues && paymentFormValues.expiry
// Check if user selected to enter a new card (vs using a saved payment)
const isEnteringNewCard = selectedPaymentMethod === 'cc' || !selectedPaymentMethod
// If using a new card (either no applied payment OR user selected 'cc' and entered form values), validate fields
const isUsingNewCard = !appliedPayment || (isEnteringNewCard && hasFormValues)
if (isUsingNewCard) {
const isValid = await paymentMethodForm.trigger()
if (!isValid) {
// Keep payment section open and show field errors
setIsEditingPayment(true)
setIsPlacingOrder(false)
return
}
}
// Prepare full card details for saving (only if we have form values for new cards)
let fullCardDetails = null
if (hasFormValues) {
const [expirationMonth, expirationYear] = paymentFormValues.expiry.split('/')
fullCardDetails = {
holder: paymentFormValues.holder,
number: paymentFormValues.number, // Full card number from form
cardType: getPaymentInstrumentCardType(paymentFormValues.cardType),
expirationMonth: parseInt(expirationMonth),
expirationYear: parseInt(`20${expirationYear}`)
}
}
// For saved payments (appliedPayment), we don't need fullCardDetails
// because we're not saving them again - they're already saved
// Handle payment submission
if (isEnteringNewCard && hasFormValues) {
// User entered a new card - need to replace existing payment if one exists
if (appliedPayment) {
// Remove the existing payment before adding the new one
try {
await removePaymentInstrumentFromBasket({
parameters: {
basketId: basket?.basketId,
paymentInstrumentId: appliedPayment.paymentInstrumentId
}
})
// Refetch basket to ensure we have the latest state
await currentBasketQuery.refetch()
} catch (error) {
showError(
formatMessage({
defaultMessage:
'Could not remove the applied payment. Please try again or use the current payment to place your order.',
id: 'checkout_payment.error.cannot_remove_applied_payment'
})
)
setIsPlacingOrder(false)
return
}
}
// Add the new payment instrument
await onPaymentSubmit(paymentFormValues)
} else if (!appliedPayment) {
// No payment applied yet - this shouldn't happen if validation passed,
// but handle it as a safety check
if (hasFormValues) {
await onPaymentSubmit(paymentFormValues)
}
}
// Ensure payment section is open before validating billing address
// This ensures the billing form is rendered and visible when we validate
setIsEditingPayment(true)
// Wait for the payment section to open and billing form to render
await new Promise((resolve) => setTimeout(resolve, 0))
// If successful `onBillingSubmit` returns the updated basket. If the form was invalid on
// submit, `undefined` is returned.
const updatedBasket = await onBillingSubmit()
if (updatedBasket) {
await submitOrder(fullCardDetails)
} else {
// Billing validation failed, clear overlay
setIsPlacingOrder(false)
}
} catch (error) {
showError()
setIsPlacingOrder(false)
}
}
useEffect(() => {
if (error || step === 4) {
window.scrollTo({top: 0})
}
}, [error, step])
return (
<Box background="gray.50" flex="1">
<Container
data-testid="sf-checkout-container"
maxWidth="container.xl"
py={{base: 7, lg: 16}}
px={{base: 0, lg: 8}}
>
<Grid templateColumns={{base: '1fr', lg: '66% 1fr'}} gap={{base: 10, xl: 20}}>
<GridItem>
<Stack spacing={4}>
{error && (
<Alert status="error" variant="left-accent">
<AlertIcon />
{error}
</Alert>
)}
<ContactInfo
isSocialEnabled={isSocialEnabled}
idps={idps}
onRegisteredUserChoseGuest={setRegisteredUserChoseGuest}
/>
{hasPickupShipments && <PickupAddress />}
{hasDeliveryShipments && (
<ShippingAddress enableUserRegistration={enableUserRegistration} />
)}
{hasDeliveryShipments && <ShippingOptions />}
<Payment
enableUserRegistration={enableUserRegistration}
setEnableUserRegistration={setEnableUserRegistration}
paymentMethodForm={paymentMethodForm}
billingAddressForm={billingAddressForm}
registeredUserChoseGuest={registeredUserChoseGuest}
onSavePreferenceChange={handleSavePreferenceChange}
onPaymentSubmitted={onPaymentSubmit}
selectedPaymentMethod={selectedPaymentMethod}
isEditing={isEditingPayment}
onSelectedPaymentMethodChange={setSelectedPaymentMethod}
onIsEditingChange={setIsEditingPayment}
billingSameAsShipping={billingSameAsShipping}
setBillingSameAsShipping={setBillingSameAsShipping}
onOtpLoadingChange={setIsOtpLoading}
onBillingSubmit={onBillingSubmit}
/>
{step >= STEPS.PAYMENT && (
<Box display="flex" bottom="0" px={4} pt={2} pb={4}>
<Container variant="form">
<Button
w="full"
onClick={onPlaceOrder}
isLoading={isLoading}
disabled={isOtpLoading || isPlacingOrder}
data-testid="place-order-button"
size="lg"
px={8}
minW="200px"
>
<FormattedMessage
defaultMessage="Place Order"
id="checkout_payment.button.place_order"
/>
</Button>
</Container>
</Box>
)}
</Stack>
</GridItem>
<GridItem py={6} px={[4, 4, 4, 0]}>
<OrderSummary
basket={basket}
showTaxEstimationForm={false}
showCartItems={true}
/>
</GridItem>
</Grid>
</Container>
{/* Loading overlay when Place Order is clicked */}
{isPlacingOrder && (
<Portal>
<Box
position="fixed"
top="0"
left="0"
right="0"
bottom="0"
bg="blackAlpha.600"
zIndex={9999}
data-testid="sf-place-order-loading-overlay"
>
<Center h="100%">
<Spinner size="xl" color="white" thickness="4px" />
</Center>
</Box>
</Portal>
)}
</Box>
)
}
const CheckoutContainer = () => {
const {data: customer} = useCurrentCustomer()
const {data: basket} = useCurrentBasket()
const {formatMessage} = useIntl()
const removeItemFromBasketMutation = useShopperBasketsMutation('removeItemFromBasket')
const toast = useToast()
const [isDeletingUnavailableItem, setIsDeletingUnavailableItem] = useState(false)
const handleRemoveItem = async (product) => {
await removeItemFromBasketMutation.mutateAsync(
{
parameters: {basketId: basket.basketId, itemId: product.itemId}
},
{
onSuccess: () => {
toast({
title: formatMessage(TOAST_MESSAGE_REMOVED_ITEM_FROM_CART, {quantity: 1}),
status: 'success'
})
},
onError: () => {
toast({
title: formatMessage(API_ERROR_MESSAGE),
status: 'error'
})
}
}
)
}
const handleUnavailableProducts = async (unavailableProductIds) => {
setIsDeletingUnavailableItem(true)
const productItems = basket?.productItems?.filter((item) =>
unavailableProductIds?.includes(item.productId)
)
for (let item of productItems) {
await handleRemoveItem(item)
}
setIsDeletingUnavailableItem(false)
}
if (!customer || !customer.customerId || !basket || !basket.basketId) {
return <CheckoutSkeleton />
}
return (
<CheckoutProvider>
{isDeletingUnavailableItem && <LoadingSpinner wrapperStyles={{height: '100vh'}} />}
<CheckoutOneClick />
<UnavailableProductConfirmationModal
productItems={basket?.productItems}
handleUnavailableProducts={handleUnavailableProducts}
/>
</CheckoutProvider>
)
}
export default CheckoutContainer