|
| 1 | +/* |
| 2 | + * Copyright (c) 2025, Salesforce, Inc. |
| 3 | + * All rights reserved. |
| 4 | + * SPDX-License-Identifier: BSD-3-Clause |
| 5 | + * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause |
| 6 | + */ |
| 7 | +import {useCommerceApi} from '@salesforce/commerce-sdk-react' |
| 8 | +import useAuthContext from '@salesforce/commerce-sdk-react/hooks/useAuthContext' |
| 9 | +import {useShopperBasketsMutation} from '@salesforce/commerce-sdk-react' |
| 10 | + |
| 11 | +// Dev-only debug logger to keep recovery silent in production |
| 12 | +const devDebug = (...args) => { |
| 13 | + if (process.env.NODE_ENV !== 'production') { |
| 14 | + console.debug(...args) |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +/** |
| 19 | + * Reusable basket recovery hook to stabilize basket after OTP/auth swap. |
| 20 | + * - Attempts merge (if caller already merged, pass skipMerge=true) |
| 21 | + * - Hydrates destination basket by id with retry |
| 22 | + * - Fallbacks to create/copy items and re-apply shipping |
| 23 | + */ |
| 24 | +const useBasketRecovery = () => { |
| 25 | + const api = useCommerceApi() |
| 26 | + const auth = useAuthContext() |
| 27 | + |
| 28 | + const mergeBasket = useShopperBasketsMutation('mergeBasket') |
| 29 | + const createBasket = useShopperBasketsMutation('createBasket') |
| 30 | + const addItemToBasket = useShopperBasketsMutation('addItemToBasket') |
| 31 | + const updateShippingAddressForShipment = useShopperBasketsMutation( |
| 32 | + 'updateShippingAddressForShipment' |
| 33 | + ) |
| 34 | + const updateShippingMethodForShipment = useShopperBasketsMutation( |
| 35 | + 'updateShippingMethodForShipment' |
| 36 | + ) |
| 37 | + |
| 38 | + const copyItemsAndShipping = async ( |
| 39 | + destinationBasketId, |
| 40 | + items = [], |
| 41 | + shipment = null, |
| 42 | + shipmentId = 'me' |
| 43 | + ) => { |
| 44 | + if (items?.length) { |
| 45 | + const payload = items.map((item) => { |
| 46 | + const productId = item.productId || item.product_id || item.id || item.product?.id |
| 47 | + const quantity = item.quantity || item.amount || 1 |
| 48 | + const variationAttributes = |
| 49 | + item.variationAttributes || item.variation_attributes || [] |
| 50 | + const optionItems = item.optionItems || item.option_items || [] |
| 51 | + const mappedVariations = Array.isArray(variationAttributes) |
| 52 | + ? variationAttributes.map((v) => ({ |
| 53 | + attributeId: v.attributeId || v.attribute_id || v.id, |
| 54 | + valueId: v.valueId || v.value_id || v.value |
| 55 | + })) |
| 56 | + : [] |
| 57 | + const mappedOptions = Array.isArray(optionItems) |
| 58 | + ? optionItems.map((o) => ({ |
| 59 | + optionId: o.optionId || o.option_id || o.id, |
| 60 | + optionValueId: |
| 61 | + o.optionValueId || o.optionValue || o.option_value || o.value |
| 62 | + })) |
| 63 | + : [] |
| 64 | + const obj = {productId, quantity} |
| 65 | + if (mappedVariations.length) obj.variationAttributes = mappedVariations |
| 66 | + if (mappedOptions.length) obj.optionItems = mappedOptions |
| 67 | + return obj |
| 68 | + }) |
| 69 | + await addItemToBasket.mutateAsync({ |
| 70 | + parameters: {basketId: destinationBasketId}, |
| 71 | + body: payload |
| 72 | + }) |
| 73 | + } |
| 74 | + |
| 75 | + if (shipment) { |
| 76 | + const shippingAddress = shipment.shippingAddress |
| 77 | + if (shippingAddress) { |
| 78 | + await updateShippingAddressForShipment.mutateAsync({ |
| 79 | + parameters: {basketId: destinationBasketId, shipmentId}, |
| 80 | + body: { |
| 81 | + address1: shippingAddress.address1, |
| 82 | + address2: shippingAddress.address2, |
| 83 | + city: shippingAddress.city, |
| 84 | + countryCode: shippingAddress.countryCode, |
| 85 | + firstName: shippingAddress.firstName, |
| 86 | + lastName: shippingAddress.lastName, |
| 87 | + phone: shippingAddress.phone, |
| 88 | + postalCode: shippingAddress.postalCode, |
| 89 | + stateCode: shippingAddress.stateCode |
| 90 | + } |
| 91 | + }) |
| 92 | + } |
| 93 | + const methodId = shipment?.shippingMethod?.id |
| 94 | + if (methodId) { |
| 95 | + await updateShippingMethodForShipment.mutateAsync({ |
| 96 | + parameters: {basketId: destinationBasketId, shipmentId}, |
| 97 | + body: {id: methodId} |
| 98 | + }) |
| 99 | + } |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + const recoverBasketAfterAuth = async ({ |
| 104 | + preLoginItems = [], |
| 105 | + shipment = null, |
| 106 | + doMerge = true |
| 107 | + } = {}) => { |
| 108 | + // Ensure fresh token in provider |
| 109 | + await auth.refreshAccessToken() |
| 110 | + |
| 111 | + let destinationBasketId |
| 112 | + if (doMerge) { |
| 113 | + try { |
| 114 | + const merged = await mergeBasket.mutateAsync({ |
| 115 | + parameters: {createDestinationBasket: true} |
| 116 | + }) |
| 117 | + destinationBasketId = merged?.basketId || merged?.basket_id || merged?.id |
| 118 | + } catch (_e) { |
| 119 | + devDebug('useBasketRecovery: mergeBasket failed; proceeding without merge', _e) |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + if (!destinationBasketId) { |
| 124 | + try { |
| 125 | + const list = await api.shopperCustomers.getCustomerBaskets({ |
| 126 | + parameters: {customerId: 'me'} |
| 127 | + }) |
| 128 | + destinationBasketId = list?.baskets?.[0]?.basketId |
| 129 | + } catch (_e) { |
| 130 | + devDebug( |
| 131 | + 'useBasketRecovery: getCustomerBaskets failed; will attempt hydration/create', |
| 132 | + _e |
| 133 | + ) |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + if (destinationBasketId) { |
| 138 | + // Avoid triggering a hook-level refetch that can cause UI remounts. |
| 139 | + // Instead, probe the destination basket directly for shipment id. |
| 140 | + let hydrated = null |
| 141 | + try { |
| 142 | + hydrated = await api.shopperBaskets.getBasket({ |
| 143 | + headers: {authorization: `Bearer ${auth.get('access_token')}`}, |
| 144 | + parameters: {basketId: destinationBasketId} |
| 145 | + }) |
| 146 | + } catch (_e) { |
| 147 | + devDebug('useBasketRecovery: getBasket hydration failed', _e) |
| 148 | + hydrated = null |
| 149 | + } |
| 150 | + if (!hydrated) { |
| 151 | + try { |
| 152 | + const created = await createBasket.mutateAsync({}) |
| 153 | + destinationBasketId = |
| 154 | + created?.basketId || |
| 155 | + created?.basket_id || |
| 156 | + created?.id || |
| 157 | + destinationBasketId |
| 158 | + await copyItemsAndShipping(destinationBasketId, preLoginItems, shipment) |
| 159 | + } catch (_e) { |
| 160 | + devDebug( |
| 161 | + 'useBasketRecovery: createBasket/copyItems failed during hydration path', |
| 162 | + _e |
| 163 | + ) |
| 164 | + } |
| 165 | + } else if (shipment) { |
| 166 | + // PII (shipping address/method) is not merged by API; re-apply from snapshot |
| 167 | + try { |
| 168 | + const effectiveDestId = hydrated?.basketId || destinationBasketId |
| 169 | + const destShipmentId = |
| 170 | + hydrated?.shipments?.[0]?.shipmentId || hydrated?.shipments?.[0]?.id || 'me' |
| 171 | + await copyItemsAndShipping(effectiveDestId, [], shipment, destShipmentId) |
| 172 | + } catch (_e) { |
| 173 | + devDebug('useBasketRecovery: re-applying shipping from snapshot failed', _e) |
| 174 | + } |
| 175 | + } |
| 176 | + } else { |
| 177 | + try { |
| 178 | + const created = await createBasket.mutateAsync({}) |
| 179 | + destinationBasketId = created?.basketId || created?.basket_id || created?.id |
| 180 | + await copyItemsAndShipping(destinationBasketId, preLoginItems, shipment) |
| 181 | + } catch (_e) { |
| 182 | + devDebug('useBasketRecovery: createBasket/copyItems failed in fallback path', _e) |
| 183 | + } |
| 184 | + } |
| 185 | + |
| 186 | + return destinationBasketId |
| 187 | + } |
| 188 | + |
| 189 | + return {recoverBasketAfterAuth} |
| 190 | +} |
| 191 | + |
| 192 | +export default useBasketRecovery |
0 commit comments