-
Notifications
You must be signed in to change notification settings - Fork 214
Expand file tree
/
Copy pathindex.jsx
More file actions
1507 lines (1390 loc) · 74.8 KB
/
index.jsx
File metadata and controls
1507 lines (1390 loc) · 74.8 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
/*
* Copyright (c) 2023, Salesforce, 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, {useState, useMemo, useEffect} from 'react'
import {FormattedMessage, useIntl} from 'react-intl'
// Chakra Components
import {
Box,
Button,
Stack,
Grid,
GridItem,
Container,
useDisclosure,
Heading
} from '@salesforce/retail-react-app/app/components/shared/ui'
// Project Components
import BonusProductsTitle from '@salesforce/retail-react-app/app/pages/cart/partials/bonus-products-title'
import CartCta from '@salesforce/retail-react-app/app/pages/cart/partials/cart-cta'
import CartSecondaryButtonGroup from '@salesforce/retail-react-app/app/pages/cart/partials/cart-secondary-button-group'
import CartSkeleton from '@salesforce/retail-react-app/app/pages/cart/partials/cart-skeleton'
import CartTitle from '@salesforce/retail-react-app/app/pages/cart/partials/cart-title'
import ConfirmationModal from '@salesforce/retail-react-app/app/components/confirmation-modal'
import EmptyCart from '@salesforce/retail-react-app/app/pages/cart/partials/empty-cart'
import OrderSummary from '@salesforce/retail-react-app/app/components/order-summary'
import OrderTypeDisplay from '@salesforce/retail-react-app/app/pages/cart/partials/order-type-display'
import PickupOrDelivery from '@salesforce/retail-react-app/app/components/pickup-or-delivery'
import ProductItemList from '@salesforce/retail-react-app/app/components/product-item-list'
import ProductViewModal from '@salesforce/retail-react-app/app/components/product-view-modal'
import BundleProductViewModal from '@salesforce/retail-react-app/app/components/product-view-modal/bundle'
import RecommendedProducts from '@salesforce/retail-react-app/app/components/recommended-products'
import CartProductListWithGroupedBonusProducts from '@salesforce/retail-react-app/app/pages/cart/partials/cart-product-list-with-grouped-bonus-products'
import SelectBonusProductsCard from '@salesforce/retail-react-app/app/pages/cart/partials/select-bonus-products-card'
import {DELIVERY_OPTIONS} from '@salesforce/retail-react-app/app/components/pickup-or-delivery'
// Hooks
import {useToast} from '@salesforce/retail-react-app/app/hooks/use-toast'
import useNavigation from '@salesforce/retail-react-app/app/hooks/use-navigation'
import {useWishList} from '@salesforce/retail-react-app/app/hooks/use-wish-list'
import {useStoreLocatorModal} from '@salesforce/retail-react-app/app/hooks/use-store-locator'
// Bonus Product Utilities
import {
useBasketProductsWithPromotions,
getPromotionCalloutText,
findAllBonusProductItemsToRemove,
getBonusProductsForSpecificCartItem
} from '@salesforce/retail-react-app/app/utils/bonus-product'
import {useBonusProductViewModal} from '@salesforce/retail-react-app/app/hooks/use-bonus-product-view-modal'
import {useBonusProductSelectionModalContext} from '@salesforce/retail-react-app/app/hooks/use-bonus-product-selection-modal'
import BonusProductViewModal from '@salesforce/retail-react-app/app/components/bonus-product-view-modal'
// Constants
import {
API_ERROR_MESSAGE,
EINSTEIN_RECOMMENDERS,
TOAST_ACTION_VIEW_WISHLIST,
TOAST_MESSAGE_ADDED_TO_WISHLIST,
TOAST_MESSAGE_REMOVED_ITEM_FROM_CART,
TOAST_MESSAGE_ALREADY_IN_WISHLIST,
TOAST_MESSAGE_STORE_INSUFFICIENT_INVENTORY,
STORE_LOCATOR_IS_ENABLED
} from '@salesforce/retail-react-app/app/constants'
import {getConfig} from '@salesforce/pwa-kit-runtime/utils/ssr-config'
import {REMOVE_CART_ITEM_CONFIRMATION_DIALOG_CONFIG} from '@salesforce/retail-react-app/app/pages/cart/partials/cart-secondary-button-group'
// Utilities
import debounce from 'lodash/debounce'
import {useCurrentBasket} from '@salesforce/retail-react-app/app/hooks/use-current-basket'
import {
useShopperBasketsMutation,
useProducts,
useShopperCustomersMutation,
useStores
} from '@salesforce/commerce-sdk-react'
import {useCurrentCustomer} from '@salesforce/retail-react-app/app/hooks/use-current-customer'
import UnavailableProductConfirmationModal from '@salesforce/retail-react-app/app/components/unavailable-product-confirmation-modal'
import {getUpdateBundleChildArray} from '@salesforce/retail-react-app/app/utils/product-utils'
import {isPickupShipment} from '@salesforce/retail-react-app/app/utils/shipment-utils'
import {useSelectedStore} from '@salesforce/retail-react-app/app/hooks/use-selected-store'
import {useMultiship} from '@salesforce/retail-react-app/app/hooks/use-multiship'
const DEBOUNCE_WAIT = 750
const Cart = () => {
const {data: basket, isLoading, derivedData} = useCurrentBasket()
const multishipEnabled = getConfig()?.app?.multishipEnabled ?? true
const storeLocatorEnabled = getConfig()?.app?.storeLocatorEnabled ?? STORE_LOCATOR_IS_ENABLED
// State for tracking items being removed (for UI feedback)
const [removingItemIds, setRemovingItemIds] = React.useState([])
// Get configuration for bonus product grouping
const config = getConfig()
const groupBonusProductsWithQualifyingProduct =
config.app?.pages?.cart?.groupBonusProductsWithQualifyingProduct ?? true
// Pickup in Store - inventory at current store and all unique store IDs from all shipments
const {selectedStore} = useSelectedStore()
const selectedInventoryId = selectedStore?.inventoryId || null
const allStoreIds = derivedData?.pickupStoreIds?.join(',') ?? ''
const {data: storeData} = useStores(
{
parameters: {
ids: allStoreIds
}
},
{
enabled: !!allStoreIds && storeLocatorEnabled
}
)
const uniqueInventoryIds = [
...new Set(
[selectedInventoryId]
.concat(storeData?.data?.map((store) => store.inventoryId))
.filter(Boolean)
)
].join(',')
const {
updateDeliveryOption,
updateShipmentsWithoutMethods,
getItemsForShipment,
findOrCreatePickupShipment,
moveItemsToPickupShipment
} = useMultiship(basket)
const productIds = basket?.productItems?.map(({productId}) => productId).join(',') ?? ''
// Bonus Product Logic
const {
data: productsWithPromotions,
ruleBasedQualifyingProductsMap,
isLoading: isPromotionDataLoading
} = useBasketProductsWithPromotions(basket)
const bonusProductViewModal = useBonusProductViewModal()
const {onOpen: openBonusSelectionModal} = useBonusProductSelectionModalContext()
// Handle opening bonus product selection modal (not the view modal directly)
const handleSelectBonusProducts = () => {
const bonusDiscountLineItems = basket?.bonusDiscountLineItems || []
if (bonusDiscountLineItems.length > 0) {
openBonusSelectionModal({
bonusDiscountLineItems: bonusDiscountLineItems
})
}
}
const {data: products, isLoading: isProductsLoading} = useProducts(
{
parameters: {
ids: productIds,
allImages: true,
perPricebook: true,
...(uniqueInventoryIds ? {inventoryIds: uniqueInventoryIds} : {})
}
},
{
enabled: Boolean(productIds),
select: (result) => {
return result?.data?.reduce((result, item) => {
const key = item.id
result[key] = item
return result
}, {})
}
}
)
const {data: customer} = useCurrentCustomer()
const {customerId, isRegistered} = customer
/***************** Product Bundles ************************/
const bundleChildVariantIds = []
basket?.productItems?.forEach((productItem) => {
productItem?.bundledProductItems?.forEach((childProduct) => {
bundleChildVariantIds.push(childProduct.productId)
})
})
const {data: bundleChildProductData} = useProducts(
{
parameters: {
ids: bundleChildVariantIds?.join(','),
allImages: false,
...(uniqueInventoryIds ? {inventoryIds: uniqueInventoryIds} : {}),
expand: ['availability', 'variations'],
select: '(data.(id,inventory,inventories,master))'
}
},
{
enabled: bundleChildVariantIds?.length > 0,
keepPreviousData: true,
select: (result) => {
return result?.data?.reduce((result, item) => {
const key = item.id
result[key] = item
return result
}, {})
}
}
)
// We use the `products` object to reference products by itemId instead of productId
// Since with product bundles, even though the parent productId is the same,
// variant selection of the bundle children can be different,
// and require unique references to each product bundle
const productsByItemId = useMemo(() => {
const getLowestStockInfo = (
parentProduct,
productItem,
bundleChildProductData,
inventoryId = null
) => {
const isDefaultInventory = !inventoryId
const parentInventory = isDefaultInventory
? parentProduct.inventory
: parentProduct.inventories?.find((inv) => inv.id === inventoryId)
let lowestStockLevel = parentInventory?.stockLevel ?? Number.MAX_SAFE_INTEGER
let productWithLowestInventory = ''
productItem.bundledProductItems.forEach((bundleChild) => {
const childProduct = bundleChildProductData[bundleChild.productId]
const childInventory = isDefaultInventory
? childProduct?.inventory
: childProduct?.inventories?.find((inv) => inv.id === inventoryId)
const childStockLevel = childInventory?.stockLevel ?? Number.MAX_SAFE_INTEGER
if (childStockLevel < lowestStockLevel) {
lowestStockLevel = childStockLevel
productWithLowestInventory = bundleChild.productName
}
})
return {lowestStockLevel, productWithLowestInventory}
}
const updateProductsByItemId = {}
basket?.productItems?.forEach((productItem) => {
let currentProduct = products?.[productItem?.productId]
if (currentProduct && productItem?.bundledProductItems && bundleChildProductData) {
// Calculate and update the default inventory for the bundle.
if (currentProduct.inventory) {
const {lowestStockLevel, productWithLowestInventory} = getLowestStockInfo(
currentProduct,
productItem,
bundleChildProductData
)
currentProduct = {
...currentProduct,
inventory: {
...currentProduct.inventory,
stockLevel: lowestStockLevel,
lowestStockLevelProductName: productWithLowestInventory
}
}
}
// Calculate and update in-store inventories for the bundle.
if (currentProduct.inventories) {
const updatedInventories = currentProduct.inventories.map((inventory) => {
const {
lowestStockLevel: lowestInStoreStockLevel,
productWithLowestInventory: productWithLowestInventoryForStore
} = getLowestStockInfo(
currentProduct,
productItem,
bundleChildProductData,
inventory.id
)
return {
...inventory,
stockLevel: lowestInStoreStockLevel,
lowestStockLevelProductName: productWithLowestInventoryForStore
}
})
currentProduct = {
...currentProduct,
inventories: updatedInventories
}
}
}
updateProductsByItemId[productItem.itemId] = currentProduct
})
return updateProductsByItemId
}, [basket, products, bundleChildProductData])
/*****************Basket Mutation************************/
const updateItemInBasketMutation = useShopperBasketsMutation('updateItemInBasket')
const updateItemsInBasketMutation = useShopperBasketsMutation('updateItemsInBasket')
const removeItemFromBasketMutation = useShopperBasketsMutation('removeItemFromBasket')
/*****************Basket Mutation************************/
const [selectedItem, setSelectedItem] = useState(undefined)
const [localQuantity, setLocalQuantity] = useState({})
const [localIsGiftItems, setLocalIsGiftItems] = useState({})
const [isCartItemLoading, setCartItemLoading] = useState(false)
const [isProcessingShippingMethods, setIsProcessingShippingMethods] = useState(false)
const {isOpen, onOpen, onClose} = useDisclosure()
const {formatMessage} = useIntl()
const toast = useToast()
const navigate = useNavigation()
const modalProps = useDisclosure()
const storeLocatorModal = useStoreLocatorModal()
// Custom handler for opening store locator from cart's "Change Store" button
const handleChangeStoreFromCart = async (shipmentInfo) => {
if (
!isProductsLoading &&
selectedStore?.id &&
selectedStore.inventoryId &&
shipmentInfo.store?.id !== selectedStore.id &&
shipmentInfo.shipment?.shipmentId
) {
try {
setCartItemLoading(true)
// Get all items from the source shipment that have inventory at the new store
const itemsInShipment = getItemsForShipment(
basket,
shipmentInfo.shipment?.shipmentId
)
const itemsToMove = itemsInShipment.filter(
(productItem) =>
productsByItemId?.[productItem.itemId]?.inventories?.find(
(inventory) => inventory.id === selectedStore?.inventoryId
)?.stockLevel >= productItem.quantity
)
if (itemsToMove.length) {
const targetShipment = await findOrCreatePickupShipment(selectedStore)
await moveItemsToPickupShipment(
itemsToMove,
targetShipment?.shipmentId,
selectedStore.inventoryId
)
}
if (itemsInShipment.length !== itemsToMove.length) {
toast({
title: formatMessage(TOAST_MESSAGE_STORE_INSUFFICIENT_INVENTORY),
status: 'error'
})
}
} catch (error) {
console.error('Failed to change store for pickup shipment:', error)
showError()
} finally {
setCartItemLoading(false)
}
}
}
/******************* Assign Default Shipping Methods to Shipments *******************/
// Assign default shipping methods to any shipments that don't have one
// This runs when the basket is first loaded and whenever shipments change
useEffect(() => {
const assignDefaultShippingMethods = async () => {
if (isProcessingShippingMethods || !basket?.basketId) {
return
}
// Check if any shipments need shipping methods to avoid unnecessary processing
const hasShipmentsWithoutMethod = basket.shipments?.some(
(shipment) => !shipment.shippingMethod
)
if (!hasShipmentsWithoutMethod) {
return
}
// Don't assign methods until at least one delivery shipment has an address
const deliveryShipments = basket.shipments?.filter((s) => !isPickupShipment(s)) || []
const hasDeliveryWithAddress = deliveryShipments.some(
(s) => s.shippingAddress?.address1
)
if (deliveryShipments.length > 0 && !hasDeliveryWithAddress) {
return
}
setIsProcessingShippingMethods(true)
try {
await updateShipmentsWithoutMethods()
} catch (error) {
console.error('Failed to assign default shipping methods:', error)
} finally {
setIsProcessingShippingMethods(false)
}
}
assignDefaultShippingMethods()
}, [basket?.basketId, basket?.shipments?.length, isProcessingShippingMethods])
/************************* Error handling ***********************/
const showError = () => {
toast({
title: formatMessage(API_ERROR_MESSAGE),
status: 'error'
})
}
/************************* Error handling ***********************/
/**************** Wishlist ****************/
const {data: wishlist} = useWishList()
const createCustomerProductListItem = useShopperCustomersMutation(
'createCustomerProductListItem'
)
const handleAddToWishlist = async (product) => {
try {
if (!customerId || !wishlist) {
return
}
const isItemInWishlist = wishlist?.customerProductListItems?.find(
(i) => i.productId === product?.id
)
if (!isItemInWishlist) {
await createCustomerProductListItem.mutateAsync({
parameters: {
listId: wishlist.id,
customerId
},
body: {
// NOTE: APi does not respect quantity, it always adds 1
quantity: product.quantity,
productId: product.productId,
public: false,
priority: 1,
type: 'product'
}
})
toast({
title: formatMessage(TOAST_MESSAGE_ADDED_TO_WISHLIST, {quantity: 1}),
status: 'success',
action: (
// it would be better if we could use <Button as={Link}>
// but unfortunately the Link component is not compatible
// with Chakra Toast, since the ToastManager is rendered via portal
// and the toast doesn't have access to intl provider, which is a
// requirement of the Link component.
<Button variant="link" onClick={() => navigate('/account/wishlist')}>
{formatMessage(TOAST_ACTION_VIEW_WISHLIST)}
</Button>
)
})
} else {
toast({
title: formatMessage(TOAST_MESSAGE_ALREADY_IN_WISHLIST),
status: 'info',
action: (
<Button variant="link" onClick={() => navigate('/account/wishlist')}>
{formatMessage(TOAST_ACTION_VIEW_WISHLIST)}
</Button>
)
})
}
} catch {
showError()
}
}
/**************** Wishlist ****************/
/***************************** Update Cart **************************/
const handleUpdateCart = async (variant, quantity) => {
// close the modal before handle the change
onClose()
// using try-catch is better than using onError callback since we have many mutation calls logic here
try {
setCartItemLoading(true)
const productIds = basket.productItems.map(({productId}) => productId)
// The user is selecting different variant, and it has not existed in basket
if (selectedItem.id !== variant.productId && !productIds.includes(variant.productId)) {
const item = {
productId: variant.productId,
quantity,
price: variant.price
}
return await updateItemInBasketMutation.mutateAsync({
parameters: {
basketId: basket.basketId,
itemId: selectedItem.itemId
},
body: item
})
}
// The user is selecting different variant, and it has existed in basket
// remove this item in the basket, change the quantity for the new selected variant in the basket
if (selectedItem.id !== variant.productId && productIds.includes(variant.productId)) {
await removeItemFromBasketMutation.mutateAsync({
parameters: {
basketId: basket.basketId,
itemId: selectedItem.itemId
}
})
const basketItem = basket.productItems.find(
({productId}) => productId === variant.productId
)
const newQuantity = quantity + basketItem.quantity
return await changeItemQuantity(newQuantity, basketItem)
}
// the user only changes quantity of the same variant
if (selectedItem.quantity !== quantity) {
return await changeItemQuantity(quantity, selectedItem)
}
} catch {
showError()
} finally {
setCartItemLoading(false)
setSelectedItem(undefined)
}
}
const handleUpdateBundle = async (bundle, bundleQuantity, childProducts) => {
// close the modal before handle the change
onClose()
try {
setCartItemLoading(true)
const itemsToBeUpdated = getUpdateBundleChildArray(bundle, childProducts)
// We only update the parent bundle when the quantity changes
// Since top level bundles don't have variants
if (bundle.quantity !== bundleQuantity) {
itemsToBeUpdated.unshift({
itemId: bundle.itemId,
productId: bundle.productId,
quantity: bundleQuantity
})
}
if (itemsToBeUpdated.length) {
await updateItemsInBasketMutation.mutateAsync({
method: 'PATCH',
parameters: {
basketId: basket.basketId
},
body: itemsToBeUpdated
})
}
} catch {
showError()
} finally {
setCartItemLoading(false)
setSelectedItem(undefined)
}
}
const handleIsAGiftChange = async (product, checked) => {
try {
const previousVal = localIsGiftItems[product.itemId]
setLocalIsGiftItems({
...localIsGiftItems,
[product.itemId]: checked
})
setCartItemLoading(true)
setSelectedItem(product)
await updateItemInBasketMutation.mutateAsync(
{
parameters: {basketId: basket?.basketId, itemId: product.itemId},
body: {
productId: product.id,
quantity: parseInt(product.quantity),
gift: checked
}
},
{
onSettled: () => {
// reset the state
setCartItemLoading(false)
setSelectedItem(undefined)
},
onSuccess: () => {
setLocalIsGiftItems({...localIsGiftItems, [product.itemId]: undefined})
},
onError: () => {
// reset the quantity to the previous value
setLocalIsGiftItems({...localIsGiftItems, [product.itemId]: previousVal})
showError()
}
}
)
} catch (e) {
showError()
} finally {
setCartItemLoading(false)
setSelectedItem(undefined)
}
}
const handleUnavailableProducts = async (unavailableProductIds) => {
const productItems = basket?.productItems?.filter((item) =>
unavailableProductIds?.includes(item.productId)
)
await Promise.all(
productItems.map(async (item) => {
await handleRemoveItem(item)
})
)
}
/***************************** Update Cart **************************/
/***************************** Update quantity **************************/
const changeItemQuantity = debounce(async (quantity, product) => {
// This local state allows the dropdown to show the desired quantity
// while the API call to update it is happening.
const previousQuantity = localQuantity[product.itemId]
setLocalQuantity({...localQuantity, [product.itemId]: quantity})
setCartItemLoading(true)
setSelectedItem(product)
await updateItemInBasketMutation.mutateAsync(
{
parameters: {basketId: basket?.basketId, itemId: product.itemId},
body: {
productId: product.id,
quantity: parseInt(quantity)
}
},
{
onSettled: () => {
// reset the state
setCartItemLoading(false)
setSelectedItem(undefined)
},
onSuccess: () => {
setLocalQuantity({...localQuantity, [product.itemId]: undefined})
},
onError: () => {
// reset the quantity to the previous value
setLocalQuantity({...localQuantity, [product.itemId]: previousQuantity})
showError()
}
}
)
}, DEBOUNCE_WAIT)
const handleChangeItemQuantity = async (product, value) => {
const productItemInventory =
productsByItemId?.[product.itemId]?.inventories?.find(
(inventory) => inventory.id === product.inventoryId
) || productsByItemId?.[product.itemId]?.inventory
const stockLevel = productItemInventory?.stockLevel ?? 1
// Handle removing of the items when 0 is selected.
if (value === 0) {
// Flush last call to keep ui in sync with data.
changeItemQuantity.flush()
// Set the selected item to the current product to the modal acts on it.
setSelectedItem(product)
// Show the modal.
modalProps.onOpen()
// Return false as 0 isn't valid section.
return false
}
// Cancel any pending handlers.
changeItemQuantity.cancel()
// Allow use to selected values above the inventory.
if (value > stockLevel || value === product.quantity) {
return true
}
// Take action.
changeItemQuantity(value, product)
return true
}
/***************************** Update quantity **************************/
/***************************** Remove Item from basket **************************/
const handleRemoveItem = (product) => {
setSelectedItem(product)
setCartItemLoading(true)
// Check if this is a bonus product that needs bulk removal
if (product.bonusProductLineItem) {
// Find all bonus product items that should be removed together
const itemsToRemove = findAllBonusProductItemsToRemove(basket, product)
if (itemsToRemove.length > 1) {
// Set removing state for UI feedback
const itemIdsToRemove = itemsToRemove.map((item) => item.itemId)
setRemovingItemIds(itemIdsToRemove)
// Track removal progress
let index = 0
let successfulRemovals = 0
// Sequential removal function to avoid race conditions
const removeNextItem = () => {
if (index >= itemsToRemove.length) {
// All items processed
setCartItemLoading(false)
setSelectedItem(undefined)
setRemovingItemIds([])
// Show success toast for successful removals
if (successfulRemovals > 0) {
const totalQuantity = itemsToRemove
.slice(0, successfulRemovals)
.reduce((total, item) => total + (item.quantity || 0), 0)
toast({
title: formatMessage(TOAST_MESSAGE_REMOVED_ITEM_FROM_CART, {
quantity: totalQuantity
}),
status: 'success'
})
}
return
}
const currentItem = itemsToRemove[index]
removeItemFromBasketMutation.mutate(
{
parameters: {basketId: basket.basketId, itemId: currentItem.itemId}
},
{
onSettled: () => {
index++
// Process next item after this one settles
setTimeout(removeNextItem, 100)
},
onSuccess: () => {
successfulRemovals++
},
onError: (error) => {
console.error('Item removal error:', error)
}
}
)
}
removeNextItem()
} else {
// Single bonus product item
removeItemFromBasketMutation.mutate(
{
parameters: {basketId: basket.basketId, itemId: product.itemId}
},
{
onSettled: () => {
setCartItemLoading(false)
setSelectedItem(undefined)
},
onSuccess: () => {
toast({
title: formatMessage(TOAST_MESSAGE_REMOVED_ITEM_FROM_CART, {
quantity: 1
}),
status: 'success'
})
},
onError: (error) => {
console.error('Bonus product removal error:', error)
showError()
}
}
)
}
} else {
// Regular (non-bonus) product removal
removeItemFromBasketMutation.mutate(
{
parameters: {basketId: basket.basketId, itemId: product.itemId}
},
{
onSettled: () => {
setCartItemLoading(false)
setSelectedItem(undefined)
},
onSuccess: () => {
toast({
title: formatMessage(TOAST_MESSAGE_REMOVED_ITEM_FROM_CART, {
quantity: 1
}),
status: 'success'
})
},
onError: (error) => {
console.error('Product removal error:', error)
showError()
}
}
)
}
}
// Create shipment-specific data, but group all qualifying products together for bonus product grouping
const shipmentData = useMemo(() => {
if (!basket?.shipments?.length) return []
const pickupShipments = []
const deliveryShipments = []
// Separate pickup and delivery shipments
basket.shipments.forEach((shipment) => {
const isPickupOrder = storeLocatorEnabled && isPickupShipment(shipment)
const storeId = shipment?.c_fromStoreId
const store = storeData?.data?.find((store) => store.id === storeId)
// Filter products for this shipment
const shipmentProducts =
basket.productItems?.filter(
(productItem) => productItem.shipmentId === shipment.shipmentId
) || []
// Categorize products into regular and bonus for this shipment
const categorizedProducts = shipmentProducts.reduce(
(acc, productItem) => {
// All bonus products go to bonusProducts array (both grouped and orphaned)
if (productItem.bonusProductLineItem) {
acc.bonusProducts.push(productItem)
} else {
// Only non-bonus products go to regular products
acc.regularProducts.push(productItem)
}
return acc
},
{regularProducts: [], bonusProducts: []}
)
const shipmentData = {
shipment,
isPickupOrder,
store,
categorizedProducts,
itemsInShipment:
categorizedProducts.regularProducts.length +
categorizedProducts.bonusProducts.length
}
// Only add shipments that have regular products
if (shipmentData.categorizedProducts.regularProducts.length > 0) {
if (isPickupOrder) {
pickupShipments.push(shipmentData)
} else {
deliveryShipments.push(shipmentData)
}
}
})
const result = [...pickupShipments]
// Combine all delivery shipments into one for display purposes
if (deliveryShipments.length > 0) {
const combinedDeliveryProducts = deliveryShipments.reduce(
(acc, shipmentData) => {
acc.regularProducts.push(...shipmentData.categorizedProducts.regularProducts)
acc.bonusProducts.push(...shipmentData.categorizedProducts.bonusProducts)
return acc
},
{regularProducts: [], bonusProducts: []}
)
result.push({
shipment: null, // No specific shipment for combined delivery
isPickupOrder: false,
store: null, // No specific store for combined delivery
categorizedProducts: combinedDeliveryProducts,
itemsInShipment:
combinedDeliveryProducts.regularProducts.length +
combinedDeliveryProducts.bonusProducts.length
})
}
return result
}, [basket?.shipments, basket?.productItems, storeData])
// Helper function to get shipment info for a product
const getShipmentInfoForProduct = (productItem) => {
const shipment = basket?.shipments?.find((s) => s.shipmentId === productItem.shipmentId)
if (!shipment) return null
const isPickupOrder = storeLocatorEnabled && isPickupShipment(shipment)
const storeId = shipment?.c_fromStoreId
const store = storeData?.data?.find((store) => store.id === storeId)
return {
shipment,
isPickupOrder,
store
}
}
/***************************** Delivery Options **************************/
const onDeliveryOptionChange = async (productItem, selectedDeliveryOption) => {
try {
setCartItemLoading(true)
setSelectedItem(productItem)
const selectedPickup = selectedDeliveryOption === DELIVERY_OPTIONS.PICKUP
// If the user selects pickup and no store is selected, open the store locator modal
if (selectedPickup && !selectedStore) {
storeLocatorModal.onOpen()
return
}
const productData = products?.[productItem.productId]
const defaultInventoryId = productData?.inventory?.id
if (!defaultInventoryId) {
throw new Error(`No inventory ID found for product ${productItem.productId}`)
}
await updateDeliveryOption(
productItem,
selectedPickup,
selectedStore,
defaultInventoryId
)
} catch (error) {
console.error('Error changing delivery option:', error)
showError()
} finally {
setCartItemLoading(false)
setSelectedItem(undefined)
}
}
// Function to render deliveryActions
const renderDeliveryActions = (productItem, shipmentInfo) => {
const showDeliveryOptions = storeLocatorEnabled && multishipEnabled
if (!showDeliveryOptions) {
return null
}
// Check if this product has bonus products associated with it
// If it does, hide the delivery group selector
const hasBonusProducts =
getBonusProductsForSpecificCartItem(
basket,
productItem,
productsWithPromotions,
ruleBasedQualifyingProductsMap
).length > 0
if (hasBonusProducts) {
return null
}
const deliveryOption = shipmentInfo.isPickupOrder
? DELIVERY_OPTIONS.PICKUP
: DELIVERY_OPTIONS.DELIVERY
const selectedStoreInventoryAvailable =
productsByItemId?.[productItem.itemId]?.inventories?.find(
(inventory) => inventory.id === selectedInventoryId
)?.stockLevel >= productItem.quantity
const defaultInventoryAvailable =
productsByItemId?.[productItem.itemId]?.inventory?.stockLevel >= productItem.quantity
const isPickupDisabled = !shipmentInfo.isPickupOrder && !selectedStoreInventoryAvailable
const isShipDisabled = shipmentInfo.isPickupOrder && !defaultInventoryAvailable
return (
<PickupOrDelivery
isPickupDisabled={isPickupDisabled}
isShipDisabled={isShipDisabled}
value={deliveryOption}
onChange={(selectedValue) => onDeliveryOptionChange(productItem, selectedValue)}
/>
)
}
// Function to render secondary actions for product items
const renderSecondaryActions = ({isAGift}) => (
<CartSecondaryButtonGroup
isAGift={isAGift}
onIsAGiftChange={handleIsAGiftChange}
onAddToWishlistClick={handleAddToWishlist}
onEditClick={(product) => {
setSelectedItem(product)
onOpen()
}}
onRemoveItemClick={handleRemoveItem}
/>
)
/********* Rendering UI **********/
if (isLoading) {