-
Notifications
You must be signed in to change notification settings - Fork 214
Expand file tree
/
Copy pathuse-basket-recovery.js
More file actions
178 lines (167 loc) · 7.07 KB
/
use-basket-recovery.js
File metadata and controls
178 lines (167 loc) · 7.07 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
/*
* 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'
/**
* 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 currentBasketQuery = useCurrentBasket()
const mergeBasket = useShopperBasketsMutation('mergeBasket')
const createBasket = useShopperBasketsMutation('createBasket')
const addItemToBasket = useShopperBasketsMutation('addItemToBasket')
const updateShippingAddressForShipment = useShopperBasketsMutation(
'updateShippingAddressForShipment'
)
const updateShippingMethodForShipment = useShopperBasketsMutation(
'updateShippingMethodForShipment'
)
const copyItemsAndShipping = async (
destBasketId,
items = [],
shipmentSnapshot = 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: destBasketId}, body: payload})
}
if (shipmentSnapshot) {
const shippingAddress = shipmentSnapshot.shippingAddress
if (shippingAddress) {
await updateShippingAddressForShipment.mutateAsync({
parameters: {basketId: destBasketId, 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 = shipmentSnapshot?.shippingMethod?.id
if (methodId) {
await updateShippingMethodForShipment.mutateAsync({
parameters: {basketId: destBasketId, shipmentId},
body: {id: methodId}
})
}
}
}
const recoverBasketAfterAuth = async ({
preLoginItems = [],
shipmentSnapshot = null,
doMerge = true
} = {}) => {
// Ensure fresh token in provider
await auth.refreshAccessToken()
// Defer invalidation to the end to avoid duplicate basket/shipping-method refetches
let destId
if (doMerge) {
try {
const merged = await mergeBasket.mutateAsync({
parameters: {createDestinationBasket: true}
})
destId = merged?.basketId || merged?.basket_id || merged?.id
} catch (_e) {
/* noop */
}
}
if (!destId) {
try {
const list = await api.shopperCustomers.getCustomerBaskets({
parameters: {customerId: 'me'}
})
destId = list?.baskets?.[0]?.basketId
} catch (_e) {
/* noop */
}
}
if (destId) {
// 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: destId}
})
} catch (_e) {
hydrated = null
}
if (!hydrated) {
try {
const created = await createBasket.mutateAsync({})
destId = created?.basketId || created?.basket_id || created?.id || destId
await copyItemsAndShipping(destId, preLoginItems, shipmentSnapshot)
} catch (_e) {
/* noop */
}
} else if (shipmentSnapshot) {
// PII (shipping address/method) is not merged by API; re-apply from snapshot
try {
const effectiveDestId = hydrated?.basketId || destId
const destShipmentId =
hydrated?.shipments?.[0]?.shipmentId || hydrated?.shipments?.[0]?.id || 'me'
await copyItemsAndShipping(
effectiveDestId,
[],
shipmentSnapshot,
destShipmentId
)
} catch (_e) {
/* noop */
}
}
} else {
try {
const created = await createBasket.mutateAsync({})
destId = created?.basketId || created?.basket_id || created?.id
await copyItemsAndShipping(destId, preLoginItems, shipmentSnapshot)
} catch (_e) {
/* noop */
}
}
return destId
}
return {recoverBasketAfterAuth}
}
export default useBasketRecovery