-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathuse-pickup-shipment.js
More file actions
265 lines (238 loc) · 10 KB
/
use-pickup-shipment.js
File metadata and controls
265 lines (238 loc) · 10 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
/*
* Copyright (c) 2022, 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 {
useShopperBasketsMutation,
useShippingMethodsForShipment
} from '@salesforce/commerce-sdk-react'
import {STORE_LOCATOR_IS_ENABLED} from '@salesforce/retail-react-app/app/constants'
/**
* Custom hook to handle pickup in store shipment configuration
* @returns {Object} Object containing helper functions for pickup shipment management
*/
export const usePickupShipment = (basket) => {
// Only enable BOPIS functionality if the feature toggle is on
const isBopisEnabled = STORE_LOCATOR_IS_ENABLED
const updateShipmentForBasketMutation = useShopperBasketsMutation('updateShipmentForBasket')
// Hook for shipping methods - we'll use refetch when needed
const {refetch: refetchShippingMethods} = useShippingMethodsForShipment(
{
parameters: {
basketId: basket?.basketId,
shipmentId: 'me'
}
},
{
enabled: false // Disable automatic fetching, we'll fetch manually when needed
}
)
/**
* Gets the shipping method ID for pickup in store
* @param {Object} shippingMethods - The shipping methods for the shipment
* @returns {string|null} The shipping method ID for pickup in store, or null if not found
*/
const getPickupShippingMethodId = (shippingMethods) => {
if (!isBopisEnabled || !shippingMethods?.applicableShippingMethods) {
return null
}
const pickupMethod = shippingMethods.applicableShippingMethods.find(
(method) => method.c_storePickupEnabled === true
)
return pickupMethod?.id || null
}
/**
* Gets the default shipping method ID (non-pickup)
* @param {Object} shippingMethods - The shipping methods for the shipment
* @returns {string|null} The default shipping method ID, or null if not found
*/
const getDefaultShippingMethodId = (shippingMethods) => {
return shippingMethods?.defaultShippingMethodId || null
}
/**
* Checks if the current shipping method is already a pickup method
* @param {Object} currentShippingMethod - The current shipping method on the basket
* @returns {boolean} True if the current shipping method is a pickup method
*/
const isCurrentShippingMethodPickup = (currentShippingMethod) => {
return isBopisEnabled && currentShippingMethod?.c_storePickupEnabled === true
}
/**
* Ensures pickup shipment is properly configured for the basket
* @param {string} basketId - The basket ID
* @param {Array} productItems - Array of product items being added
* @param {Object} storeInfo - Store information object containing id and inventoryId
* @param {Object} options - Configuration options
* @param {string} options.pickupShippingMethodId - Shipping method ID for pickup (default: '005')
* @param {boolean} options.throwOnError - Whether to throw on error (default: false)
*/
const updatePickupShipment = async (basketId, productItems, storeInfo, options = {}) => {
if (!isBopisEnabled) return
const defaultPickupShippingMethodId = '005'
const {pickupShippingMethodId = defaultPickupShippingMethodId, throwOnError = false} =
options
try {
const pickupItems = productItems.filter((item) => item.inventoryId)
if (pickupItems.length === 0) return
if (!storeInfo) {
if (throwOnError) throw new Error('Failed to retrieve store information')
return
}
if (!storeInfo?.inventoryId) {
if (throwOnError) throw new Error('No store inventory ID found')
return
}
// Update shipment to ensure pickup configuration
await updateShipmentForBasketMutation.mutateAsync({
parameters: {
basketId,
shipmentId: 'me'
},
body: {
shippingMethod: {
id: pickupShippingMethodId
},
c_fromStoreId: storeInfo.id
}
})
} catch (error) {
if (throwOnError) {
throw error
} else {
// Log error but don't block the add to cart flow
console.warn('Failed to configure pickup shipment:', error)
}
}
}
/**
* Configures regular shipping method for the basket
* @param {string} basketId - The basket ID
* @param {string} shippingMethodId - The shipping method ID to set
* @param {boolean} throwOnError - Whether to throw on error (default: false)
*/
const updateRegularShippingMethod = async (
basketId,
shippingMethodId,
throwOnError = false
) => {
try {
await updateShipmentForBasketMutation.mutateAsync({
parameters: {
basketId,
shipmentId: 'me'
},
body: {
shippingMethod: {
id: shippingMethodId
}
}
})
} catch (error) {
if (throwOnError) {
throw error
} else {
// Log error but don't block the add to cart flow
console.warn('Failed to configure regular shipping method:', error)
}
}
}
/**
* Checks if any items in the selection require pickup configuration
* @param {Array} productSelectionValues - Array of product selection values
* @param {Object} pickupInStoreMap - Map of product IDs to pickup flags
* @param {Object} mainProduct - Main product object (for fallback)
* @returns {boolean} True if any items are pickup items
*/
const hasPickupItems = (productSelectionValues, pickupInStoreMap, mainProduct) => {
if (!isBopisEnabled) return false
return productSelectionValues.some((item) => {
const prodKey =
(item.variant || item.product || mainProduct).productId ||
(item.variant || item.product || mainProduct).id
return pickupInStoreMap[prodKey]
})
}
/**
* Adds inventory ID to product items that have pickup selected
* @param {Array} productItems - Array of product items
* @param {Object} pickupInStoreMap - Map of product IDs to pickup flags
* @param {Object} storeInfo - Store information object containing inventoryId
* @returns {Array} Updated product items with inventory IDs
*/
const addInventoryIdsToPickupItems = (productItems, pickupInStoreMap, storeInfo) => {
if (!isBopisEnabled || !storeInfo?.inventoryId) return productItems
return productItems.map((item) => {
const prodKey = item.productId || item.id
if (pickupInStoreMap[prodKey]) {
return {
...item,
inventoryId: storeInfo.inventoryId
}
}
return item
})
}
/**
* Configure shipping method based on pickup selection
* @param {Object} basketResponse - The basket response from adding items
* @param {Array} productItems - Array of product items that were added
* @param {boolean} hasAnyPickupSelected - Whether any items have pickup selected
* @param {Object} selectedStore - The selected store information
* @returns {Promise<void>}
*/
const updateShippingMethodIfNeeded = async (
basketResponse,
productItems,
hasAnyPickupSelected,
selectedStore
) => {
if (!isBopisEnabled || !basketResponse?.basketId || !basketResponse.shipments.length) {
return
}
const currentShippingMethod = basketResponse.shipments[0].shippingMethod
const isCurrentlyPickup = isCurrentShippingMethodPickup(currentShippingMethod)
// Only configure if there's a mismatch between pickup selection and current method
if (
(hasAnyPickupSelected && !isCurrentlyPickup) ||
(!hasAnyPickupSelected && isCurrentlyPickup)
) {
// Clear shipping address when there's a mismatch by updating shipment without shippingAddress
await updateShipmentForBasketMutation.mutateAsync({
parameters: {
basketId: basketResponse.basketId,
shipmentId: 'me'
},
body: {
shippingAddress: {}
}
})
// Fetch shipping methods to get available options
const {data: fetchedShippingMethods} = await refetchShippingMethods()
if (hasAnyPickupSelected && !isCurrentlyPickup) {
// Configure pickup shipment if pickup is selected but current method is not pickup
const pickupShippingMethodId = getPickupShippingMethodId(fetchedShippingMethods)
await updatePickupShipment(basketResponse.basketId, productItems, selectedStore, {
pickupShippingMethodId
})
} else if (!hasAnyPickupSelected && isCurrentlyPickup) {
// Configure regular shipping if pickup is not selected but current method is pickup
const defaultShippingMethodId = getDefaultShippingMethodId(fetchedShippingMethods)
await updateRegularShippingMethod(basketResponse.basketId, defaultShippingMethodId)
}
}
}
return {
updatePickupShipment,
updateRegularShippingMethod,
updateShippingMethodIfNeeded,
hasPickupItems,
addInventoryIdsToPickupItems,
getPickupShippingMethodId,
getDefaultShippingMethodId,
isCurrentShippingMethodPickup,
updateShipmentForBasketMutation
}
}
export default usePickupShipment