-
Notifications
You must be signed in to change notification settings - Fork 214
Expand file tree
/
Copy pathuse-product-detail-data.js
More file actions
333 lines (293 loc) · 12.2 KB
/
use-product-detail-data.js
File metadata and controls
333 lines (293 loc) · 12.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
/*
* Copyright (c) 2025, 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, {useCallback, useEffect, useState} from 'react'
import {keepPreviousData} from '@tanstack/react-query'
import {HTTPNotFound, HTTPError} from '@salesforce/pwa-kit-react-sdk/ssr/universal/errors'
import {
useProduct,
useProducts,
useCategory,
useShopperBasketsMutation,
useShopperBasketsMutationHelper
} from '@salesforce/commerce-sdk-react'
import {useHistory, useLocation, useParams} from 'react-router-dom'
import {useCurrentBasket, useVariant} from '../../hooks'
import useEinstein from '../../hooks/use-einstein'
import {useProductDetailWishlist} from './use-product-detail-wishlist'
import {normalizeSetBundleProduct, getUpdateBundleChildArray} from '../../utils/product-utils'
import {useErrorHandler} from '../../utils/error-utils'
import {rebuildPathWithParams} from '../../utils/url'
export const useProductDetailData = () => {
const history = useHistory()
const location = useLocation()
const einstein = useEinstein()
const showError = useErrorHandler()
const {handleAddToWishlist, isWishlistLoading} = useProductDetailWishlist()
/****************************** Basket *********************************/
const {isLoading: isBasketLoading} = useCurrentBasket()
const {addItemToNewOrExistingBasket} = useShopperBasketsMutationHelper()
const updateItemsInBasketMutation = useShopperBasketsMutation('updateItemsInBasket')
/*************************** Product Detail and Category ********************/
const {productId} = useParams()
const urlParams = new URLSearchParams(location.search)
const {
data: product,
isLoading: isProductLoading,
isError: isProductError,
error: productError
} = useProduct(
{
parameters: {
id: urlParams.get('pid') || productId,
perPricebook: true,
expand: [
'availability',
'promotions',
'options',
'images',
'prices',
'variations',
'set_products',
'bundled_products',
'page_meta_tags'
],
allImages: true
}
},
{
// When shoppers select a different variant (and the app fetches the new data),
// the old data is still rendered (and not the skeletons).
placeholderData: keepPreviousData
}
)
// Note: Since category needs id from product detail, it can't be server side rendered atm
// until we can do dependent query on server
const {
data: category,
isError: isCategoryError,
error: categoryError
} = useCategory({
parameters: {
id: product?.primaryCategoryId,
levels: 1
}
})
/****************************** Sets and Bundles *********************************/
const [childProductSelection, setChildProductSelection] = useState({})
const [childProductOrderability, setChildProductOrderability] = useState({})
const [selectedBundleQuantity, setSelectedBundleQuantity] = useState(1)
const childProductRefs = React.useRef({})
const isProductASet = product?.type.set
const isProductABundle = product?.type.bundle
let bundleChildVariantIds = ''
if (isProductABundle)
bundleChildVariantIds = Object.keys(childProductSelection)
?.map((key) => childProductSelection[key].variant.productId)
.join(',')
const {data: bundleChildrenData} = useProducts(
{
parameters: {
ids: bundleChildVariantIds,
allImages: false,
expand: ['availability', 'variations'],
select: '(data.(id,inventory,master))'
}
},
{
enabled: bundleChildVariantIds?.length > 0,
placeholderData: keepPreviousData
}
)
if (isProductABundle && bundleChildrenData) {
// Loop through the bundle children and update the inventory for variant selection
product.bundledProducts.forEach(({product: childProduct}, index) => {
const matchingChildProduct = bundleChildrenData.data.find(
(bundleChild) => bundleChild.master.masterId === childProduct.id
)
if (matchingChildProduct) {
product.bundledProducts[index].product = {
...childProduct,
inventory: matchingChildProduct.inventory
}
}
})
}
const comboProduct = isProductASet || isProductABundle ? normalizeSetBundleProduct(product) : {}
/**************** Error Handling ****************/
if (isProductError) {
const errorStatus = productError?.response?.status
switch (errorStatus) {
case 404:
throw new HTTPNotFound('Product Not Found.')
default:
throw new HTTPError(errorStatus, `HTTP Error ${errorStatus} occurred.`)
}
}
if (isCategoryError) {
const errorStatus = categoryError?.response?.status
switch (errorStatus) {
case 404:
throw new HTTPNotFound('Category Not Found.')
default:
throw new HTTPError(errorStatus, `HTTP Error ${errorStatus} occurred.`)
}
}
const [primaryCategory, setPrimaryCategory] = useState(category)
const variant = useVariant(product)
// This page uses the `primaryCategoryId` to retrieve the category data. This attribute
// is only available on `master` products. Since a variation will be loaded once all the
// attributes are selected (to get the correct inventory values), the category information
// is overridden. This will allow us to keep the initial category around until a different
// master product is loaded.
useEffect(() => {
if (category) {
setPrimaryCategory(category)
}
}, [category])
/**************** Product Variant ****************/
useEffect(() => {
if (!variant) {
return
}
// update the variation attributes parameter on
// the url accordingly as the variant changes
const updatedUrl = rebuildPathWithParams(`${location.pathname}${location.search}`, {
pid: variant?.productId
})
history.replace(updatedUrl)
}, [variant])
/**************** Add To Cart ****************/
const handleAddToCart = async (productSelectionValues) => {
try {
const productItems = productSelectionValues.map(({variant, quantity}) => ({
productId: variant.productId,
price: variant.price,
quantity
}))
await addItemToNewOrExistingBasket(productItems)
einstein.sendAddToCart(productItems)
// If the items were successfully added, set the return value to be used
// by the add to cart modal.
return productSelectionValues
} catch (error) {
console.log('error', error)
showError(error)
}
}
/**************** Product Set/Bundles Handlers ****************/
const handleChildProductValidation = useCallback(() => {
// Run validation for all child products. This will ensure the error
// messages are shown.
Object.values(childProductRefs.current).forEach(({validateOrderability}) => {
validateOrderability({scrollErrorIntoView: false})
})
// Using ot state for which child products are selected, scroll to the first
// one that isn't selected.
const selectedProductIds = Object.keys(childProductSelection)
const firstUnselectedProduct = comboProduct.childProducts.find(
({product: childProduct}) => !selectedProductIds.includes(childProduct.id)
)?.product
if (firstUnselectedProduct) {
// Get the reference to the product view and scroll to it.
const {ref} = childProductRefs.current[firstUnselectedProduct.id]
if (ref.scrollIntoView) {
ref.scrollIntoView({
behavior: 'smooth',
block: 'end'
})
}
return false
}
return true
}, [product, childProductSelection])
/**************** Product Set Handlers ****************/
const handleProductSetAddToCart = () => {
// Get all the selected products, and pass them to the addToCart handler which
// accepts an array.
const productSelectionValues = Object.values(childProductSelection)
return handleAddToCart(productSelectionValues)
}
/**************** Product Bundle Handlers ****************/
// Top level bundle does not have variants
const handleProductBundleAddToCart = async (variant, selectedQuantity) => {
try {
const childProductSelections = Object.values(childProductSelection)
const productItems = [
{
productId: product.id,
price: product.price,
quantity: selectedQuantity,
// The add item endpoint in the shopper baskets API does not respect variant selections
// for bundle children, so we have to make a follow up call to update the basket
// with the chosen variant selections
bundledProductItems: childProductSelections.map((child) => {
return {
productId: child.variant.productId,
quantity: child.quantity
}
})
}
]
const res = await addItemToNewOrExistingBasket(productItems)
const bundleChildMasterIds = childProductSelections.map((child) => {
return child.product.id
})
// since the returned data includes all products in basket
// here we compare list of productIds in bundleProductItems of each productItem to filter out the
// current bundle that was last added into cart
const currentBundle = res.productItems.find((productItem) => {
if (!productItem.bundledProductItems?.length) return
const bundleChildIds = productItem.bundledProductItems?.map((item) => {
// seek out the bundle child that still uses masterId as product id
return item.productId
})
return bundleChildIds.every((id) => bundleChildMasterIds.includes(id))
})
const itemsToBeUpdated = getUpdateBundleChildArray(
currentBundle,
childProductSelections
)
if (itemsToBeUpdated.length) {
// make a follow up call to update child variant selection for product bundle
// since add item endpoint doesn't currently consider product bundle child variants
await updateItemsInBasketMutation.mutateAsync({
method: 'PATCH',
parameters: {
basketId: res.basketId
},
body: itemsToBeUpdated
})
}
einstein.sendAddToCart(productItems)
return childProductSelections
} catch (error) {
showError(error)
}
}
return {
product,
isProductLoading,
primaryCategory,
isProductASet,
isProductABundle,
comboProduct,
childProductRefs,
childProductSelection,
setChildProductSelection,
childProductOrderability,
setChildProductOrderability,
selectedBundleQuantity,
setSelectedBundleQuantity,
handleAddToCart,
handleAddToWishlist,
handleProductSetAddToCart,
handleProductBundleAddToCart,
handleChildProductValidation,
isBasketLoading,
isWishlistLoading
}
}