-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseDeliveryPromise.ts
More file actions
1118 lines (918 loc) · 31.2 KB
/
Copy pathuseDeliveryPromise.ts
File metadata and controls
1118 lines (918 loc) · 31.2 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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable no-restricted-globals */
import { useRuntime, useSSR } from 'vtex.render-runtime'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useIntl } from 'react-intl'
import { useApolloClient } from 'react-apollo'
import { useOrderItems } from 'vtex.order-items/OrderItems'
import { usePixel, usePixelEventCallback } from 'vtex.pixel-manager'
import { useRenderSession } from 'vtex.session-client'
import {
getAddress,
getCatalogCount,
getPickups,
updateOrderForm,
clearOrderFormShipping,
updateSession,
clearShippingSession,
getCartProducts,
orderFormItemsToAvailabilityItems,
validateProductAvailability,
validateProductAvailabilityByPickup,
validateProductAvailabilityByDelivery,
} from '../client'
import {
getNearestPickup,
persistPickupPreference,
resolvePickupForShippingSession,
} from '../pickupInPointPreference'
import type { AvailabilityItem, ResolvedAddress } from '../client'
import type { CartItem, CartProduct } from '../components/UnavailableItemsModal'
import type { OrderFormCartLine } from '../modules/pixelHelper'
import { mapCartItemToPixel } from '../modules/pixelHelper'
import { refetchAllowlistedQueries } from '../modules/refetchAllowlistedQueries'
import { getCountryCode, getFacetsData, getOrderFormId } from '../utils/cookie'
import {
getPostalCodeFormat,
isPostalCodeComplete,
} from '../utils/postalCodeFormat'
import messages from '../messages'
import type {
ShippingMethod,
DeliveryPromiseActions,
ZipCodeError,
DeliveryPromiseUiRegistry,
} from './DeliveryPromiseContext'
import {
SHOPPER_LOCATION_MODAL_PIXEL_EVENT_ID,
PRODUCTS_NOT_FOUND_ERROR_CODE,
DEFAULT_TRADE_POLICY,
} from '../constants'
import {
clearSuppressAutoGeolocation,
setSuppressAutoGeolocation,
} from '../modules/suppressAutoGeolocationSession'
// Local `Promise.allSettled` shim — the repo's TS lib target is `es2017`,
// which does not declare `Promise.allSettled`. The runtime supports it
// (modern browsers / Node 12+), but we wrap each promise in `Promise.all`
// to keep the type system happy without bumping the platform-managed
// tsconfig.
type SettledResult<T> =
| { status: 'fulfilled'; value: T }
| { status: 'rejected'; reason: unknown }
const settle = <T>(promise: Promise<T>): Promise<SettledResult<T>> =>
promise.then(
(value) => ({ status: 'fulfilled' as const, value }),
(reason) => ({ status: 'rejected' as const, reason })
)
export const useDeliveryPromise = () => {
const [zipcode, setZipCode] = useState<string>()
const [isLoading, setIsLoading] = useState(true)
const [countryCode, setCountryCode] = useState<string>()
const [submitErrorMessage, setSubmitErrorMessage] = useState<ZipCodeError>()
const [city, setCity] = useState<string>()
const [pickups, setPickups] = useState<Pickup[]>([])
const [pickupSuggestion, setPickupSuggestion] = useState<Pickup>()
const [selectedPickup, setSelectedPickup] = useState<Pickup>()
const [geoCoordinates, setGeoCoordinates] = useState<number[]>()
const [addressLabel, setAddressLabel] = useState<string>()
const [deliveryPromiseMethod, setDeliveryPromiseMethod] =
useState<ShippingMethod>()
const [unavailableCartItems, setUnavailableCartItems] = useState<CartItem[]>(
[]
)
const [pendingAddToCartItem, setPendingAddToCartItem] = useState<any>()
const [unavailabilityMessage, setUnavailabilityMessage] = useState<string>()
/** Stores a thunk: setState(updater) must return the callback, hence `() => () => run()`. */
const [
actionInterruptedByCartValidation,
setActionInterruptedByCartValidation,
] = useState<(() => () => void | Promise<void | boolean>) | undefined>()
const [uiRegistry, setUiRegistry] = useState<DeliveryPromiseUiRegistry>({})
const [shippingMethodModalRequestId, setShippingMethodModalRequestId] =
useState(0)
const [fulfillmentSelectionAppliedId, setFulfillmentSelectionAppliedId] =
useState(0)
const uiRegistryRef = useRef(uiRegistry)
uiRegistryRef.current = uiRegistry
const dispatchImplRef = useRef<
(action: DeliveryPromiseActions) => Promise<boolean | undefined>
>(async () => undefined)
const { account, query: runtimeQuery, setQuery } = useRuntime()
const { session, loading: isSessionLoading } = useRenderSession()
const isSSR = useSSR()
const intl = useIntl()
const { addItems, removeItem } = useOrderItems()
const { push } = usePixel()
const apolloClient = useApolloClient()
/**
* Refreshes the storefront after a session write. The session POST sets a
* new `vtex_segment` cookie (which carries the delivery / pickup hashes) in
* the response, so by the time we land here every cached observable query
* is one network round trip away from the new shopper context. Rather than
* tearing the React tree down with a hard reload, we refetch *only* the
* allowlisted store-resources queries that vary by `@withSegment`
* (productSearch, facets, products, recommendations, sponsored), resetting
* `productSearchV3` to page 1.
*
* Falls back to `location.reload()` when Apollo is unavailable (e.g. the
* provider isn't mounted in tests / custom hosts), when the QueryManager
* internals are inaccessible, or when a targeted refetch throws — a hard
* reload is always a correct, if expensive, way to converge on the
* post-session state.
*/
const refreshStorefront = useCallback(async (): Promise<void> => {
// A location change resets the PLP to the first page. Drop the `page` query
// param *through render-runtime* (not history.replaceState): vtex.search-result
// reads `useRuntime().query.page` and resets its "load more" pagination reducer
// when it observes the param returning to page 1, so the next "load more" goes
// to page 2 instead of resuming from the stale page. Gate on page > 1 so non-PLP
// and already-first-page URLs are left untouched.
const currentPageParam = Number(runtimeQuery?.page)
if (typeof setQuery === 'function' && currentPageParam > 1) {
setQuery({ page: undefined }, { replace: true })
}
if (!apolloClient) {
window.location.reload()
return
}
try {
const { failed } = await refetchAllowlistedQueries(apolloClient)
if (failed) {
window.location.reload()
return
}
setIsLoading(false)
} catch {
window.location.reload()
}
}, [apolloClient, runtimeQuery, setQuery])
const orderItemsUpdateOptions = {
allowedOutdatedData: ['paymentData'] as const,
splitItem: true,
}
const salesChannel = isSessionLoading
? undefined
: session?.namespaces?.store?.channel?.value ?? DEFAULT_TRADE_POLICY
const [pendingPickupsFetch, setPendingPickupsFetch] = useState<{
country: string
selectedZipcode: string
coordinates: number[]
shippingMethod?: ShippingMethod
keepLoading?: boolean
} | null>(null)
usePixelEventCallback({
eventId: SHOPPER_LOCATION_MODAL_PIXEL_EVENT_ID,
handler: (event: any) => {
setPendingAddToCartItem(event.data.addToCartInfo)
},
})
// Shared pickup-state sync used by both applyPickupsResult (fetchPickups
// consumers) and the submitZipcode session-write block. Updates the
// pickup-related local state from a getPickups response and returns the
// pickup that the next session write should carry (and a flag indicating
// whether any active pickup was returned, so callers can preserve their
// own conditional updateSession semantics).
const syncPickupsState = useCallback(
(
responsePickups: { items?: Pickup[] } | null | undefined,
selectedZipcode: string,
shippingMethod?: ShippingMethod
): { pickupForSession: Pickup | undefined; hasAnyPickup: boolean } => {
const pickupsFormatted =
responsePickups?.items?.filter(
(pickup: Pickup) => pickup.pickupPoint.isActive
) ?? []
setPickups(pickupsFormatted)
if (pickupsFormatted.length === 0) {
setPickupSuggestion(undefined)
setSelectedPickup(undefined)
return { pickupForSession: undefined, hasAnyPickup: false }
}
const nearest = getNearestPickup(pickupsFormatted)
setPickupSuggestion(nearest)
const segmentPickupId = getFacetsData('pickupPoint')
const pickupForSession = resolvePickupForShippingSession(
pickupsFormatted,
selectedZipcode,
segmentPickupId,
shippingMethod
)
setSelectedPickup(pickupForSession)
return { pickupForSession, hasAnyPickup: true }
},
[]
)
// Post-fetch processing for fetchPickups consumers. When the response
// carries no active pickups, the session write is skipped so callers
// (segment-restoration useEffect, pendingPickupsFetch effect) keep their
// "don't re-write an already-correct session" behavior.
const applyPickupsResult = useCallback(
async (
country: string,
selectedZipcode: string,
coordinates: number[],
responsePickups: { items?: Pickup[] } | null | undefined,
shippingMethod?: ShippingMethod,
keepLoading = false
) => {
const { pickupForSession, hasAnyPickup } = syncPickupsState(
responsePickups,
selectedZipcode,
shippingMethod
)
if (!hasAnyPickup) {
if (!keepLoading) {
setIsLoading(false)
}
return
}
await updateSession(
country,
selectedZipcode,
coordinates,
pickupForSession,
shippingMethod
)
if (!keepLoading) {
setIsLoading(false)
}
},
[syncPickupsState]
)
const fetchPickups = useCallback(
async (
country: string,
selectedZipcode: string,
coordinates: number[],
shippingMethod?: ShippingMethod,
keepLoading = false
) => {
if (!salesChannel) {
setPendingPickupsFetch({
country,
selectedZipcode,
coordinates,
shippingMethod,
keepLoading,
})
return
}
const responsePickups = await getPickups(
country,
selectedZipcode,
account,
salesChannel
)
await applyPickupsResult(
country,
selectedZipcode,
coordinates,
responsePickups,
shippingMethod,
keepLoading
)
},
[account, salesChannel, applyPickupsResult]
)
useEffect(() => {
if (isSSR || isSessionLoading) {
return
}
if (!pendingPickupsFetch) {
return
}
const { country, selectedZipcode, coordinates, shippingMethod } =
pendingPickupsFetch
setPendingPickupsFetch(null)
fetchPickups(country, selectedZipcode, coordinates, shippingMethod, false)
}, [fetchPickups, isSSR, isSessionLoading, pendingPickupsFetch])
useEffect(() => {
if (isSSR) {
return
}
const segmentZipCode = getFacetsData('zip-code')
const segmentCountryCode = getCountryCode()
const segmentShippingMethod = getFacetsData('shipping') as ShippingMethod
setZipCode(segmentZipCode)
setDeliveryPromiseMethod(segmentShippingMethod)
setCountryCode(segmentCountryCode)
if (segmentZipCode) {
try {
getAddress(segmentCountryCode, segmentZipCode, account).then((res) => {
setCity(res.city)
setGeoCoordinates(res.geoCoordinates)
fetchPickups(
segmentCountryCode,
segmentZipCode,
res.geoCoordinates,
segmentShippingMethod
)
})
} catch {
setIsLoading(false)
}
} else {
setIsLoading(false)
}
}, [account, isSSR, fetchPickups])
const onError = (code: string, message: string) => {
setSubmitErrorMessage({ code, message })
setIsLoading(false)
setTimeout(() => {
setSubmitErrorMessage(undefined)
}, 8000)
}
const validateCartItems = async (
validationHandler: (items: AvailabilityItem[]) => Promise<any>
) => {
setIsLoading(true)
try {
const orderFormId = getOrderFormId()
const orderLines = await getCartProducts(orderFormId)
// Skip the BFF availability call entirely for empty carts. Keep loading
// on: the caller proceeds with the action and owns the loading lifecycle
// through the soft refresh (avoids a loading → idle → loading flicker).
if (orderLines.length === 0) {
return []
}
const availabilityItems = orderFormItemsToAvailabilityItems(orderLines)
const { unavailableItemIds } = await validationHandler(availabilityItems)
const unavailableSkuIds = new Set(
Array.isArray(unavailableItemIds) ? unavailableItemIds.map(String) : []
)
const unavailableItems = orderLines
.map((line: CartProduct, id: number) => ({
cartItemIndex: id,
product: line,
}))
.filter((item: any) => unavailableSkuIds.has(String(item.product.id)))
setUnavailableCartItems(unavailableItems)
// Only stop loading when surfacing the unavailable-items modal (so it is
// interactive). When everything is available the caller continues the
// action and owns the loading lifecycle until the soft refresh completes.
if (unavailableItems.length > 0) {
setIsLoading(false)
}
return unavailableItems
} catch {
// Degraded path: proceed with the action. Keep loading on so the caller's
// continuation owns a single loading cycle.
setUnavailableCartItems([])
return []
}
}
const resetUnavailableCartItems = async () => {
setUnavailableCartItems([])
}
const removeUnavailableItems = async () => {
await unavailableCartItems.reduce<Promise<void>>(
async (previous, { product }) => {
await previous
const line = product as unknown as OrderFormCartLine
push({
event: 'removeFromCart',
items: [mapCartItemToPixel(line)],
})
await removeItem({ uniqueId: line.uniqueId }, orderItemsUpdateOptions)
},
Promise.resolve()
)
const outer = actionInterruptedByCartValidation
if (typeof outer !== 'function') {
return
}
const inner = outer()
if (typeof inner === 'function') {
await inner()
}
}
const submitZipcode = async (
selectedZipcode: string,
resolvedAddress: ResolvedAddress,
reload = true
): Promise<boolean> => {
if (!countryCode) {
return false
}
setIsLoading(true)
try {
const { geoCoordinates: coordinates, city: cityName } = resolvedAddress
const orderFormId = getOrderFormId()
// Run the three independent calls in parallel. getCatalogCount stays
// on the critical path (UX gate) but no longer blocks updateOrderForm
// and getPickups behind it.
const catalogCountPromise = getCatalogCount(selectedZipcode, coordinates)
const updateOrderFormPromise = orderFormId
? updateOrderForm(countryCode, selectedZipcode, orderFormId)
: Promise.resolve()
const pickupsPromise = salesChannel
? getPickups(countryCode, selectedZipcode, account, salesChannel)
: Promise.resolve(null)
const [catalogCountResult, updateOrderFormResult, pickupsResult] =
await Promise.all([
settle(catalogCountPromise),
settle(updateOrderFormPromise),
settle(pickupsPromise),
])
// Catalog-count rejection keeps the existing INVALID_POSTAL_CODE path.
if (catalogCountResult.status === 'rejected') {
throw catalogCountResult.reason
}
const { total } = catalogCountResult.value
if (total === 0) {
onError(
PRODUCTS_NOT_FOUND_ERROR_CODE,
intl.formatMessage(
messages.shopperLocationModalNoPickupPointStateDescription,
{
postalCode: ` ${selectedZipcode}`,
}
)
)
return false
}
// updateOrderForm is best-effort: log and continue on failure.
if (updateOrderFormResult.status === 'rejected') {
console.error(
'delivery-promise: updateOrderForm failed during UPDATE_ZIPCODE',
updateOrderFormResult.reason
)
}
setCity(cityName)
setGeoCoordinates(coordinates)
setZipCode(selectedZipcode)
setDeliveryPromiseMethod(undefined)
setSelectedPickup(undefined)
// Single session write per dispatch. Pickup resolution happens before
// the write so the single write carries the resolved pickup (or
// undefined when there are no active pickups, when getPickups rejected,
// or when salesChannel is not yet loaded and pickup fetching is
// deferred).
let pickupForSession: Pickup | undefined
if (!salesChannel) {
// Deferral path preserved: pendingPickupsFetch will run once the
// session loads. The session still gets the zipcode/coordinates
// immediately via the single write below.
setPendingPickupsFetch({
country: countryCode,
selectedZipcode,
coordinates,
shippingMethod: undefined,
keepLoading: true,
})
} else {
const pickupsValue =
pickupsResult.status === 'fulfilled' ? pickupsResult.value : null
pickupForSession = syncPickupsState(
pickupsValue,
selectedZipcode,
undefined
).pickupForSession
}
await updateSession(
countryCode,
selectedZipcode,
coordinates,
pickupForSession
)
} catch {
onError(
'INVALID_POSTAL_CODE',
intl.formatMessage(messages.shopperLocationPostalCodeInputError)
)
return false
}
const registry = uiRegistryRef.current
const shippingMethodRequired = registry.shippingMethod?.required === true
const shopperLocationRequired = registry.shopperLocation?.required === true
const effectiveReload = reload && !shippingMethodRequired
if (!effectiveReload) {
setIsLoading(false)
}
if (
reload &&
shippingMethodRequired &&
!(shopperLocationRequired && shippingMethodRequired)
) {
setShippingMethodModalRequestId((n) => n + 1)
}
clearSuppressAutoGeolocation()
if (effectiveReload) {
setIsLoading(true)
await refreshStorefront()
}
return true
}
const selectPickup = async (pickup: Pickup, canUnselect = true) => {
if (!countryCode || !zipcode || !geoCoordinates) {
setIsLoading(false)
return
}
let shippingOption: ShippingMethod | undefined = 'pickup-in-point'
let pickupUpdated: Pickup | undefined = pickup
if (
canUnselect &&
deliveryPromiseMethod === 'pickup-in-point' &&
pickup.pickupPoint.id === selectedPickup?.pickupPoint.id
) {
shippingOption = undefined
pickupUpdated = undefined
}
const previousPickup = selectedPickup
const previousMethod = deliveryPromiseMethod
// Optimistically update the fulfillment state the reload used to re-derive
// from the segment on remount, and signal blocks to close the modal.
setSelectedPickup(pickupUpdated)
setDeliveryPromiseMethod(shippingOption)
setFulfillmentSelectionAppliedId((n) => n + 1)
try {
await updateSession(
countryCode,
zipcode!,
geoCoordinates!,
pickupUpdated,
shippingOption
)
} catch (error) {
// The session was never written: roll the optimistic state back so the
// UI does not claim a selection that does not exist, and release the
// loading flag the cart-availability check left on.
setSelectedPickup(previousPickup)
setDeliveryPromiseMethod(previousMethod)
setIsLoading(false)
console.error(
'delivery-promise: updateSession failed during pickup selection',
error
)
return
}
// Persist only after the session write succeeds, so a failed write does
// not poison the PLP's stored pickup preference.
if (
shippingOption === 'pickup-in-point' &&
pickupUpdated?.pickupPoint?.id
) {
persistPickupPreference(pickupUpdated, zipcode!)
}
setIsLoading(true)
await refreshStorefront()
}
const selectDeliveryShippingOption = async () => {
if (!countryCode || !zipcode || !geoCoordinates) {
setIsLoading(false)
return
}
const previousPickup = selectedPickup
const previousMethod = deliveryPromiseMethod
// Optimistically update the fulfillment state the reload used to re-derive
// from the segment on remount, and signal blocks to close the modal.
setDeliveryPromiseMethod('delivery')
setSelectedPickup(undefined)
setFulfillmentSelectionAppliedId((n) => n + 1)
try {
await updateSession(
countryCode,
zipcode,
geoCoordinates,
undefined,
'delivery'
)
} catch (error) {
setDeliveryPromiseMethod(previousMethod)
setSelectedPickup(previousPickup)
setIsLoading(false)
console.error(
'delivery-promise: updateSession failed during delivery selection',
error
)
return
}
setIsLoading(true)
await refreshStorefront()
}
useEffect(() => {
setAddressLabel(city ? `${city}, ${zipcode}` : zipcode)
}, [zipcode, city])
dispatchImplRef.current = async (action: DeliveryPromiseActions) => {
switch (action.type) {
case 'REGISTER_SHOPPER_LOCATION_BLOCK':
setUiRegistry((prev) => ({
...prev,
shopperLocation: { required: action.args.required },
}))
return
case 'UNREGISTER_SHOPPER_LOCATION_BLOCK':
setUiRegistry((prev) => {
const next = { ...prev }
delete next.shopperLocation
return next
})
return
case 'REGISTER_SHIPPING_METHOD_BLOCK':
setUiRegistry((prev) => ({
...prev,
shippingMethod: { required: action.args.required },
}))
return
case 'UNREGISTER_SHIPPING_METHOD_BLOCK':
setUiRegistry((prev) => {
const next = { ...prev }
delete next.shippingMethod
return next
})
return
case 'REGISTER_PICKUP_POINT_BLOCK':
setUiRegistry((prev) => ({
...prev,
pickupPoint: { required: action.args.required },
}))
return
case 'UNREGISTER_PICKUP_POINT_BLOCK':
setUiRegistry((prev) => {
const next = { ...prev }
delete next.pickupPoint
return next
})
return
case 'REQUEST_OPEN_SHIPPING_METHOD_MODAL':
setShippingMethodModalRequestId((n) => n + 1)
return
case 'UPDATE_ZIPCODE': {
const {
zipcode: zipcodeSelected,
reload,
onAppliedWithoutReload,
cartAvailability = 'deliveryorpickup',
} = action.args
if (!zipcodeSelected) {
onError(
'POSTAL_CODE_NOT_FOUND',
intl.formatMessage(
messages.shopperLocationPostalCodeInputPlaceholder
)
)
return false
}
if (!countryCode) {
return false
}
// Reject a partially typed postal code before spending a getAddress /
// BFF round-trip. For masked countries the expected length is derived
// from the mask; mask-less markets are never blocked. This is the
// single choke point for every submit path (Enter, popover form,
// submit button), so the guard doesn't need to live in the input.
if (
!isPostalCodeComplete(
zipcodeSelected,
getPostalCodeFormat(countryCode)
)
) {
onError(
'INVALID_POSTAL_CODE',
intl.formatMessage(messages.shopperLocationPostalCodeInputInvalid)
)
return false
}
setIsLoading(true)
// Resolve the address ONCE; every downstream step reuses it.
// On failure, surface INVALID_POSTAL_CODE without attempting the
// BFF availability call or any further getAddress retry.
let resolvedAddress: ResolvedAddress
try {
resolvedAddress = await getAddress(
countryCode,
zipcodeSelected,
account
)
} catch {
onError(
'INVALID_POSTAL_CODE',
intl.formatMessage(messages.shopperLocationPostalCodeInputError)
)
return false
}
if (
!resolvedAddress.geoCoordinates ||
resolvedAddress.geoCoordinates.length === 0
) {
onError(
'INVALID_POSTAL_CODE',
intl.formatMessage(messages.shopperLocationPostalCodeInputError)
)
return false
}
const validateZipCartAvailability = (
items: AvailabilityItem[]
): Promise<unknown> =>
cartAvailability === 'delivery'
? validateProductAvailabilityByDelivery(
zipcodeSelected,
countryCode,
items,
account,
salesChannel,
{ address: resolvedAddress }
)
: validateProductAvailability(
zipcodeSelected,
countryCode,
items,
account,
salesChannel,
{ address: resolvedAddress }
)
const applyZipAndFacetCallback = async () => {
const applied = await submitZipcode(
zipcodeSelected,
resolvedAddress,
reload
)
if (applied && reload === false && onAppliedWithoutReload) {
// Close unavailable-items UI before client navigation so the modal is not left
// loading if navigate interrupts the follow-up ABORT from the modal.
await resetUnavailableCartItems()
setActionInterruptedByCartValidation(undefined)
setUnavailabilityMessage(undefined)
onAppliedWithoutReload()
}
return applied
}
const unavailableItems = await validateCartItems(
validateZipCartAvailability
)
if (unavailableItems.length === 0) {
return applyZipAndFacetCallback()
}
setUnavailabilityMessage(
intl.formatMessage(messages.unavailableItemsModalDescription, {
addressLabel: zipcodeSelected,
})
)
setActionInterruptedByCartValidation(
() => () => applyZipAndFacetCallback()
)
return false
}
case 'UPDATE_PICKUP': {
const { pickup, canUnselect } = action.args
setUnavailabilityMessage('pickup')
const unavailableItems = await validateCartItems(
async (items: AvailabilityItem[]) =>
validateProductAvailabilityByPickup(
pickup.pickupPoint.id,
items,
zipcode!,
countryCode!,
account,
salesChannel
)
)
if (unavailableItems.length === 0) {
selectPickup(pickup, canUnselect)
if (pendingAddToCartItem) {
await addItems(
pendingAddToCartItem.skuItems,
pendingAddToCartItem.options
)
setPendingAddToCartItem(undefined)
}
break
}
setUnavailabilityMessage(
intl.formatMessage(
messages.unavailableItemsModalForPickupPointDescription,
{
pickupLabel: selectedPickup?.pickupPoint.friendlyName,
}
)
)
setActionInterruptedByCartValidation(() => () => selectPickup(pickup))
break
}
case 'SELECT_DELIVERY_SHIPPING_OPTION': {
setUnavailabilityMessage('delivery')
const unavailableItems = await validateCartItems(
async (items: AvailabilityItem[]) =>
validateProductAvailabilityByDelivery(
zipcode!,
countryCode!,
items,
account,
salesChannel
)
)
if (unavailableItems.length === 0) {
selectDeliveryShippingOption()
if (pendingAddToCartItem) {
await addItems(
pendingAddToCartItem.skuItems,
pendingAddToCartItem.options
)
setPendingAddToCartItem(undefined)
}
break
}
setUnavailabilityMessage(
intl.formatMessage(
messages.unavailableItemsModalForDeliveryDescription,
{
addressLabel,
}
)
)
setActionInterruptedByCartValidation(