-
Notifications
You must be signed in to change notification settings - Fork 214
Expand file tree
/
Copy pathone-click-shipping-options.jsx
More file actions
676 lines (636 loc) · 28.5 KB
/
one-click-shipping-options.jsx
File metadata and controls
676 lines (636 loc) · 28.5 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
/*
* 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, useMemo} from 'react'
import {FormattedMessage, FormattedNumber, useIntl} from 'react-intl'
import {
Box,
Button,
Container,
Flex,
Radio,
RadioGroup,
Stack,
Text
} from '@salesforce/retail-react-app/app/components/shared/ui'
import {useForm, Controller} from 'react-hook-form'
import {useCheckout} from '@salesforce/retail-react-app/app/pages/checkout-one-click/util/checkout-context'
import {ChevronDownIcon} from '@salesforce/retail-react-app/app/components/icons'
import {
ToggleCard,
ToggleCardEdit,
ToggleCardSummary
} from '@salesforce/retail-react-app/app/components/toggle-card'
import {
useShippingMethodsForShipment,
useShopperBasketsMutation
} from '@salesforce/commerce-sdk-react'
import {useCurrentBasket} from '@salesforce/retail-react-app/app/hooks/use-current-basket'
import {useCurrentCustomer} from '@salesforce/retail-react-app/app/hooks/use-current-customer'
import {useCurrency} from '@salesforce/retail-react-app/app/hooks'
import {isPickupShipment} from '@salesforce/retail-react-app/app/utils/shipment-utils'
import PropTypes from 'prop-types'
import {useToast} from '@salesforce/retail-react-app/app/hooks/use-toast'
export default function ShippingOptions() {
const {formatMessage} = useIntl()
const {step, STEPS, goToStep, goToNextStep} = useCheckout()
const {
data: basket,
derivedData: {totalShippingCost}
} = useCurrentBasket()
const {data: customer} = useCurrentCustomer()
const {currency} = useCurrency()
const updateShippingMethod = useShopperBasketsMutation('updateShippingMethodForShipment')
const [hasAutoSelected, setHasAutoSelected] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const showToast = useToast()
const [noMethodsToastShown, setNoMethodsToastShown] = useState(false)
// Identify delivery shipments (exclude pickup and those without shipping addresses)
const deliveryShipments =
basket?.shipments?.filter((s) => s.shippingAddress && !isPickupShipment(s)) || []
const hasMultipleDeliveryShipments = deliveryShipments.length > 1
const targetDeliveryShipment = hasMultipleDeliveryShipments ? null : deliveryShipments[0]
const {data: shippingMethods} = useShippingMethodsForShipment(
{
parameters: {
basketId: basket?.basketId,
shipmentId: targetDeliveryShipment?.shipmentId || 'me'
}
},
{
enabled:
Boolean(basket?.basketId) &&
step === STEPS.SHIPPING_OPTIONS &&
!hasMultipleDeliveryShipments,
onSuccess: (data) => {
const noMethods =
!data?.applicableShippingMethods || data.applicableShippingMethods.length === 0
if (
step === STEPS.SHIPPING_OPTIONS &&
!hasMultipleDeliveryShipments &&
noMethods &&
!noMethodsToastShown
) {
showToast({
title: formatMessage({
defaultMessage:
'No shipping methods are available for this address. Please enter a different address.',
id: 'shipping_options.error.no_shipping_methods'
}),
status: 'error'
})
setNoMethodsToastShown(true)
}
}
}
)
const selectedShippingMethod = targetDeliveryShipment?.shippingMethod
const selectedShippingAddress = targetDeliveryShipment?.shippingAddress
// Calculate if we should show loading state immediately for auto-selection
const shouldShowInitialLoading = useMemo(() => {
return (
step === STEPS.SHIPPING_OPTIONS &&
!hasAutoSelected &&
customer?.isRegistered &&
!selectedShippingMethod?.id &&
shippingMethods?.applicableShippingMethods?.length &&
shippingMethods.defaultShippingMethodId &&
shippingMethods.applicableShippingMethods.find(
(method) => method.id === shippingMethods.defaultShippingMethodId
)
)
}, [step, hasAutoSelected, customer, selectedShippingMethod, shippingMethods])
// Use calculated loading state or manual loading state
const effectiveIsLoading = Boolean(isLoading) || Boolean(shouldShowInitialLoading)
const form = useForm({
shouldUnregister: false,
defaultValues: {
shippingMethodId: selectedShippingMethod?.id || shippingMethods?.defaultShippingMethodId
}
})
useEffect(() => {
const defaultMethodId = shippingMethods?.defaultShippingMethodId
const methodId = form.getValues().shippingMethodId
if (!selectedShippingMethod && !methodId && defaultMethodId) {
form.reset({shippingMethodId: defaultMethodId})
}
if (selectedShippingMethod && methodId !== selectedShippingMethod.id) {
form.reset({shippingMethodId: selectedShippingMethod.id})
}
// If there are no applicable methods for the current address, clear the form selection
if (!shippingMethods?.applicableShippingMethods?.length && methodId) {
form.reset({shippingMethodId: ''})
}
}, [selectedShippingMethod, shippingMethods])
// Validate existing shipping method for new address or auto-select default for authenticated users
useEffect(() => {
const handleShippingMethodForReturningShopper = async () => {
// Only auto-select when on this step and haven't already auto-selected
if (step !== STEPS.SHIPPING_OPTIONS || hasAutoSelected || isLoading) {
return
}
// Wait for shipping methods to load
if (!shippingMethods?.applicableShippingMethods?.length) {
return
}
const applicable = shippingMethods.applicableShippingMethods
// If we already have a shipping method on the basket, validate it against the new address' methods.
if (selectedShippingMethod?.id) {
const stillValid = applicable.some((m) => m.id === selectedShippingMethod.id)
setHasAutoSelected(true)
if (stillValid) {
// Do not update the basket – keep existing method and proceed to payment
goToNextStep()
return
}
// If existing method is no longer valid, fall through to select/apply a default
}
// Only proceed with auto-apply for authenticated users when no valid method is present
if (!customer?.isRegistered) {
return
}
const defaultMethodId = shippingMethods.defaultShippingMethodId
const defaultMethod =
applicable.find((method) => method.id === defaultMethodId) || applicable[0]
if (defaultMethod) {
//Auto-selecting default shipping method
setHasAutoSelected(true)
setIsLoading(true) // Show loading state immediately
try {
// Apply the default shipping method and continue to next step
await updateShippingMethod.mutateAsync({
parameters: {
basketId: basket.basketId,
shipmentId: targetDeliveryShipment?.shipmentId || 'me'
},
body: {
id: defaultMethodId
}
})
//Default shipping method auto-applied successfully
setIsLoading(false) // Clear loading state before navigation
goToNextStep()
} catch (error) {
// Reset on error so user can manually select
setHasAutoSelected(false)
setIsLoading(false) // Hide loading state on error
}
}
}
handleShippingMethodForReturningShopper()
}, [
step,
selectedShippingMethod,
customer,
shippingMethods,
hasAutoSelected,
basket?.basketId,
isLoading,
goToNextStep,
updateShippingMethod
])
const submitForm = async ({shippingMethodId}) => {
await updateShippingMethod.mutateAsync({
parameters: {
basketId: basket.basketId,
shipmentId: targetDeliveryShipment?.shipmentId || 'me'
},
body: {
id: shippingMethodId
}
})
goToNextStep()
}
const shippingItem = basket?.shippingItems?.[0]
const selectedMethodDisplayPrice = Math.min(
shippingItem?.price || 0,
shippingItem?.priceAfterItemDiscount || 0
)
const hasApplicableMethods = Boolean(
shippingMethods?.applicableShippingMethods &&
shippingMethods.applicableShippingMethods.length > 0
)
const isSelectedMethodValid =
hasApplicableMethods &&
Boolean(
selectedShippingMethod?.id &&
shippingMethods.applicableShippingMethods?.some(
(m) => m.id === selectedShippingMethod.id
)
)
const freeLabel = formatMessage({
defaultMessage: 'Free',
id: 'checkout_confirmation.label.free'
})
const shippingPriceLabel =
selectedMethodDisplayPrice === 0
? freeLabel
: formatMessage(
{
defaultMessage: '{price}',
id: 'checkout_confirmation.label.shipping.price'
},
{
price: selectedMethodDisplayPrice
}
)
return (
<ToggleCard
id="step-2"
title={formatMessage({
defaultMessage: 'Shipping Options',
id: 'shipping_options.title.shipping_method'
})}
editing={step === STEPS.SHIPPING_OPTIONS}
isLoading={form.formState.isSubmitting || effectiveIsLoading}
disabled={
(!hasMultipleDeliveryShipments &&
(selectedShippingMethod == null || !selectedShippingAddress)) ||
effectiveIsLoading
}
onEdit={() => goToStep(STEPS.SHIPPING_OPTIONS)}
editLabel={formatMessage({
defaultMessage: 'Edit Shipping Options',
id: 'toggle_card.action.editShippingOptions'
})}
>
<ToggleCardEdit>
{hasMultipleDeliveryShipments ? (
<Stack spacing={8}>
{deliveryShipments.map((shipment, idx) => (
<ShipmentMethods
key={shipment.shipmentId}
index={idx + 1}
shipment={shipment}
currency={currency}
/>
))}
<Box>
<Container variant="form">
<Button w="full" onClick={() => goToNextStep()}>
<FormattedMessage
defaultMessage="Continue to Payment"
id="shipping_options.button.continue_to_payment"
/>
</Button>
</Container>
</Box>
</Stack>
) : (
<form
onSubmit={form.handleSubmit(submitForm)}
data-testid="sf-checkout-shipping-options-form"
>
<Stack spacing={6}>
{shippingMethods?.applicableShippingMethods?.length > 0 && (
<Controller
name="shippingMethodId"
control={form.control}
defaultValue=""
render={({field: {value, onChange}}) => (
<RadioGroup
name="shipping-options-radiogroup"
value={value}
onChange={onChange}
>
<Stack spacing={5}>
{shippingMethods.applicableShippingMethods.map(
(opt) => (
<Radio value={opt.id} key={opt.id}>
<Flex justify="space-between" w="full">
<Box>
<Text>{opt.name}</Text>
<Text
fontSize="sm"
color="gray.600"
>
{opt.description}
</Text>
</Box>
<Text fontWeight="bold">
<FormattedNumber
value={opt.price}
style="currency"
currency={currency}
/>
</Text>
</Flex>
{opt.shippingPromotions?.map(
(promo) => (
<Text
key={promo.promotionId}
fontSize="sm"
color="green.600"
>
{promo.calloutMsg}
</Text>
)
)}
</Radio>
)
)}
</Stack>
</RadioGroup>
)}
/>
)}
{shippingMethods?.applicableShippingMethods?.length > 0 && (
<Box>
<Container variant="form">
<Button w="full" type="submit">
<FormattedMessage
defaultMessage="Continue to Payment"
id="shipping_options.button.continue_to_payment"
/>
</Button>
</Container>
</Box>
)}
</Stack>
</form>
)}
</ToggleCardEdit>
{!effectiveIsLoading && hasMultipleDeliveryShipments && (
<MultiShipmentSummary
deliveryShipments={deliveryShipments}
totalShippingCost={totalShippingCost}
currency={currency}
freeLabel={freeLabel}
/>
)}
{!hasMultipleDeliveryShipments &&
!effectiveIsLoading &&
isSelectedMethodValid &&
selectedShippingAddress && (
<SingleShipmentSummary
selectedShippingMethod={selectedShippingMethod}
selectedMethodDisplayPrice={selectedMethodDisplayPrice}
shippingPriceLabel={shippingPriceLabel}
currency={currency}
freeLabel={freeLabel}
/>
)}
</ToggleCard>
)
}
// Child component for multi-shipment summary
const MultiShipmentSummary = ({deliveryShipments, totalShippingCost, currency, freeLabel}) => {
const {formatMessage} = useIntl()
return (
<ToggleCardSummary>
<Stack spacing={2}>
{deliveryShipments.map((shipment) => {
// Use shipment.shippingTotal to include all costs (base + promotions + surcharges + other fees)
const itemCost = shipment.shippingTotal || 0
return (
<Box key={shipment.shipmentId}>
<Flex justify="space-between" w="full">
<Box flex="1">
{shipment.shippingMethod ? (
<>
<Text mt={2}>{shipment.shippingMethod.name}</Text>
<Text fontSize="sm" color="gray.700">
{shipment.shippingMethod.description}
</Text>
</>
) : (
<Text mt={2} fontSize="sm" color="gray.500">
{formatMessage({
defaultMessage: 'No shipping method selected',
id: 'shipping_options.label.no_method_selected'
})}
</Text>
)}
</Box>
<Text fontWeight="bold" fontSize="sm">
{itemCost === 0 ? (
freeLabel
) : (
<FormattedNumber
value={itemCost}
style="currency"
currency={currency}
/>
)}
</Text>
</Flex>
</Box>
)
})}
{deliveryShipments.length > 1 && (
<Box borderTopWidth="1px" pt={2} mt={2}>
<Flex justify="space-between" w="full">
<Text fontWeight="semibold">
{formatMessage({
defaultMessage: 'Total Shipping',
id: 'shipping_options.label.total_shipping'
})}
</Text>
<Text fontWeight="bold">
<FormattedNumber
value={totalShippingCost}
style="currency"
currency={currency}
/>
</Text>
</Flex>
</Box>
)}
</Stack>
</ToggleCardSummary>
)
}
MultiShipmentSummary.propTypes = {
deliveryShipments: PropTypes.arrayOf(
PropTypes.shape({
shipmentId: PropTypes.string.isRequired,
shippingMethod: PropTypes.shape({
name: PropTypes.string,
description: PropTypes.string
}),
shippingTotal: PropTypes.number
})
).isRequired,
totalShippingCost: PropTypes.number.isRequired,
currency: PropTypes.string.isRequired,
freeLabel: PropTypes.string.isRequired
}
// Child component for single-shipment summary
const SingleShipmentSummary = ({
selectedShippingMethod,
selectedMethodDisplayPrice,
shippingPriceLabel,
currency,
freeLabel
}) => {
return (
<ToggleCardSummary>
<Flex justify="space-between" w="full">
<Text>{selectedShippingMethod.name}</Text>
<Text fontWeight="bold" aria-label={shippingPriceLabel}>
{selectedMethodDisplayPrice === 0 ? (
freeLabel
) : (
<FormattedNumber
value={selectedMethodDisplayPrice}
style="currency"
currency={currency}
/>
)}
</Text>
</Flex>
<Text fontSize="sm" color="gray.700">
{selectedShippingMethod.description}
</Text>
</ToggleCardSummary>
)
}
SingleShipmentSummary.propTypes = {
selectedShippingMethod: PropTypes.shape({
name: PropTypes.string.isRequired,
description: PropTypes.string
}).isRequired,
selectedMethodDisplayPrice: PropTypes.number.isRequired,
shippingPriceLabel: PropTypes.string.isRequired,
currency: PropTypes.string.isRequired,
freeLabel: PropTypes.string.isRequired
}
const ShipmentMethods = ({shipment, index, currency}) => {
const {formatMessage} = useIntl()
const {data: basket} = useCurrentBasket()
const updateShippingMethod = useShopperBasketsMutation('updateShippingMethodForShipment')
const {data: methods} = useShippingMethodsForShipment(
{
parameters: {
basketId: basket?.basketId,
shipmentId: shipment.shipmentId
}
},
{enabled: Boolean(basket?.basketId && shipment?.shipmentId)}
)
const [selected, setSelected] = useState(shipment?.shippingMethod?.id || undefined)
const [hasAutoSelected, setHasAutoSelected] = useState(false)
useEffect(() => {
// Only attempt auto-select when there are applicable methods available and we haven't already auto-selected
const applicableMethods = methods?.applicableShippingMethods || []
const applicableIds = applicableMethods.map((m) => m.id)
if (!applicableIds.length || hasAutoSelected) {
return
}
// Determine the method to select:
// 1. Use existing shipment method if still valid
// 2. Use default shipping method if available
// 3. Fall back to first available method
const existingMethodId =
shipment?.shippingMethod?.id && applicableIds.includes(shipment.shippingMethod.id)
? shipment.shippingMethod.id
: undefined
const defaultMethodId =
methods?.defaultShippingMethodId &&
applicableIds.includes(methods.defaultShippingMethodId)
? methods.defaultShippingMethodId
: undefined
const firstMethodId = applicableMethods[0]?.id
const methodToSelect = existingMethodId || defaultMethodId || firstMethodId
if (methodToSelect && methodToSelect !== shipment?.shippingMethod?.id) {
setSelected(methodToSelect)
setHasAutoSelected(true)
updateShippingMethod
.mutateAsync({
parameters: {basketId: basket.basketId, shipmentId: shipment.shipmentId},
body: {id: methodToSelect}
})
.catch(() => {
// Ignore; user can manually select another method
})
} else if (methodToSelect) {
// Method already set on shipment, just update local state
setSelected(methodToSelect)
setHasAutoSelected(true)
}
}, [
methods?.applicableShippingMethods,
methods?.defaultShippingMethodId,
shipment?.shippingMethod?.id,
hasAutoSelected,
basket?.basketId,
shipment?.shipmentId
])
const address = shipment?.shippingAddress
const addressLine = address
? `${address.firstName} ${address.lastName}, ${address.address1}, ${address.city}, ${address.stateCode}, ${address.postalCode}`
: ''
return (
<Box>
<Text fontWeight="bold" mb={2}>
{formatMessage(
{
defaultMessage: 'Shipment {index}:',
id: 'shipping_options.label.shipment_number'
},
{index}
)}
</Text>
{addressLine && (
<Text color="gray.700" mb={3}>
{addressLine}
</Text>
)}
{methods?.applicableShippingMethods?.length > 0 && (
<RadioGroup
name={`shipping-options-${shipment.shipmentId}`}
value={selected}
onChange={async (val) => {
setSelected(val)
try {
await updateShippingMethod.mutateAsync({
parameters: {
basketId: basket.basketId,
shipmentId: shipment.shipmentId
},
body: {id: val}
})
} catch {
// Ignore; allow user to retry selection
}
}}
>
<Stack spacing={5}>
{methods.applicableShippingMethods.map((opt) => (
<Radio value={opt.id} key={opt.id}>
<Flex justify="space-between" w="full">
<Box>
<Text>{opt.name}</Text>
<Text fontSize="sm" color="gray.600">
{opt.description}
</Text>
</Box>
<Text fontWeight="bold">
<FormattedNumber
value={opt.price}
style="currency"
currency={currency}
/>
</Text>
</Flex>
{opt.shippingPromotions?.map((promo) => (
<Text key={promo.promotionId} fontSize="sm" color="green.600">
{promo.calloutMsg}
</Text>
))}
</Radio>
))}
</Stack>
</RadioGroup>
)}
</Box>
)
}
ShipmentMethods.propTypes = {
shipment: PropTypes.object.isRequired,
index: PropTypes.number.isRequired,
currency: PropTypes.string.isRequired
}