-
Notifications
You must be signed in to change notification settings - Fork 214
Expand file tree
/
Copy pathuse-basket-recovery.js
More file actions
192 lines (180 loc) · 7.8 KB
/
use-basket-recovery.js
File metadata and controls
192 lines (180 loc) · 7.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
/*
* 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 {useCommerceApi} from '@salesforce/commerce-sdk-react'
import useAuthContext from '@salesforce/commerce-sdk-react/hooks/useAuthContext'
import {useShopperBasketsMutation} from '@salesforce/commerce-sdk-react'
// Dev-only debug logger to keep recovery silent in production
const devDebug = (...args) => {
if (process.env.NODE_ENV !== 'production') {
console.debug(...args)
}
}
/**
* Reusable basket recovery hook to stabilize basket after OTP/auth swap.
* - Attempts merge (if caller already merged, pass skipMerge=true)
* - Hydrates destination basket by id with retry
* - Fallbacks to create/copy items and re-apply shipping
*/
const useBasketRecovery = () => {
const api = useCommerceApi()
const auth = useAuthContext()
const mergeBasket = useShopperBasketsMutation('mergeBasket')
const createBasket = useShopperBasketsMutation('createBasket')
const addItemToBasket = useShopperBasketsMutation('addItemToBasket')
const updateShippingAddressForShipment = useShopperBasketsMutation(
'updateShippingAddressForShipment'
)
const updateShippingMethodForShipment = useShopperBasketsMutation(
'updateShippingMethodForShipment'
)
const copyItemsAndShipping = async (
destinationBasketId,
items = [],
shipment = null,
shipmentId = 'me'
) => {
if (items?.length) {
const payload = items.map((item) => {
const productId = item.productId || item.product_id || item.id || item.product?.id
const quantity = item.quantity || item.amount || 1
const variationAttributes =
item.variationAttributes || item.variation_attributes || []
const optionItems = item.optionItems || item.option_items || []
const mappedVariations = Array.isArray(variationAttributes)
? variationAttributes.map((v) => ({
attributeId: v.attributeId || v.attribute_id || v.id,
valueId: v.valueId || v.value_id || v.value
}))
: []
const mappedOptions = Array.isArray(optionItems)
? optionItems.map((o) => ({
optionId: o.optionId || o.option_id || o.id,
optionValueId:
o.optionValueId || o.optionValue || o.option_value || o.value
}))
: []
const obj = {productId, quantity}
if (mappedVariations.length) obj.variationAttributes = mappedVariations
if (mappedOptions.length) obj.optionItems = mappedOptions
return obj
})
await addItemToBasket.mutateAsync({
parameters: {basketId: destinationBasketId},
body: payload
})
}
if (shipment) {
const shippingAddress = shipment.shippingAddress
if (shippingAddress) {
await updateShippingAddressForShipment.mutateAsync({
parameters: {basketId: destinationBasketId, shipmentId},
body: {
address1: shippingAddress.address1,
address2: shippingAddress.address2,
city: shippingAddress.city,
countryCode: shippingAddress.countryCode,
firstName: shippingAddress.firstName,
lastName: shippingAddress.lastName,
phone: shippingAddress.phone,
postalCode: shippingAddress.postalCode,
stateCode: shippingAddress.stateCode
}
})
}
const methodId = shipment?.shippingMethod?.id
if (methodId) {
await updateShippingMethodForShipment.mutateAsync({
parameters: {basketId: destinationBasketId, shipmentId},
body: {id: methodId}
})
}
}
}
const recoverBasketAfterAuth = async ({
preLoginItems = [],
shipment = null,
doMerge = true
} = {}) => {
// Ensure fresh token in provider
await auth.refreshAccessToken()
let destinationBasketId
if (doMerge) {
try {
const merged = await mergeBasket.mutateAsync({
parameters: {createDestinationBasket: true}
})
destinationBasketId = merged?.basketId || merged?.basket_id || merged?.id
} catch (_e) {
devDebug('useBasketRecovery: mergeBasket failed; proceeding without merge', _e)
}
}
if (!destinationBasketId) {
try {
const list = await api.shopperCustomers.getCustomerBaskets({
parameters: {customerId: 'me'}
})
destinationBasketId = list?.baskets?.[0]?.basketId
} catch (_e) {
devDebug(
'useBasketRecovery: getCustomerBaskets failed; will attempt hydration/create',
_e
)
}
}
if (destinationBasketId) {
// Avoid triggering a hook-level refetch that can cause UI remounts.
// Instead, probe the destination basket directly for shipment id.
let hydrated = null
try {
hydrated = await api.shopperBaskets.getBasket({
headers: {authorization: `Bearer ${auth.get('access_token')}`},
parameters: {basketId: destinationBasketId}
})
} catch (_e) {
devDebug('useBasketRecovery: getBasket hydration failed', _e)
hydrated = null
}
if (!hydrated) {
try {
const created = await createBasket.mutateAsync({})
destinationBasketId =
created?.basketId ||
created?.basket_id ||
created?.id ||
destinationBasketId
await copyItemsAndShipping(destinationBasketId, preLoginItems, shipment)
} catch (_e) {
devDebug(
'useBasketRecovery: createBasket/copyItems failed during hydration path',
_e
)
}
} else if (shipment) {
// PII (shipping address/method) is not merged by API; re-apply from snapshot
try {
const effectiveDestId = hydrated?.basketId || destinationBasketId
const destShipmentId =
hydrated?.shipments?.[0]?.shipmentId || hydrated?.shipments?.[0]?.id || 'me'
await copyItemsAndShipping(effectiveDestId, [], shipment, destShipmentId)
} catch (_e) {
devDebug('useBasketRecovery: re-applying shipping from snapshot failed', _e)
}
}
} else {
try {
const created = await createBasket.mutateAsync({})
destinationBasketId = created?.basketId || created?.basket_id || created?.id
await copyItemsAndShipping(destinationBasketId, preLoginItems, shipment)
} catch (_e) {
devDebug('useBasketRecovery: createBasket/copyItems failed in fallback path', _e)
}
}
return destinationBasketId
}
return {recoverBasketAfterAuth}
}
export default useBasketRecovery