'use client'; import { Suspense, useEffect, useState, useCallback, useRef } from 'react'; import { useRouter, useSearchParams } from 'next/navigation'; import { CdnImage as Image } from '@/ui/shared/cdn-image'; import { Link } from '@/core/lib/navigation'; import type { Checkout, ShippingRate, SetShippingAddressDto, ShippingDestinations, PickupLocation, CheckoutBumpsResponse, CheckoutCustomFieldDefinition, } from 'brainerce'; import { formatPrice } from 'brainerce'; import { getClient } from '@/core/lib/brainerce'; import { useStoreInfo, useCart, useAuth, useRegion, useStoreCapabilities, } from '@/core/providers/store-provider'; import { useCurrency } from '@/core/lib/use-currency'; import { CheckoutForm } from '@/components/checkout/checkout-form'; import { ShippingStep } from '@/components/checkout/shipping-step'; import { PickupPointStep } from '@/components/checkout/pickup-point-step'; import { PaymentStep } from '@/components/checkout/payment-step'; import { DeliveryMethodStep } from '@/components/checkout/delivery-method-step'; import { PickupStep } from '@/components/checkout/pickup-step'; import { CustomFieldsStep } from '@/components/checkout/custom-fields-step'; import { TaxDisplay } from '@/components/checkout/tax-display'; import { OrderBumpCard } from '@/components/checkout/order-bump-card'; import { OrderCustomizations } from '@/components/account/order-customizations'; import { CouponInput } from '@/ui/cart/coupon-input'; import { GiftCardInput } from '@/ui/cart/gift-card-input'; import { LoyaltyCreditInput } from '@/ui/cart/loyalty-credit-input'; import { ReservationCountdown } from '@/ui/cart/reservation-countdown'; import { LoadingSpinner } from '@/ui/shared/loading-spinner'; import { useTranslations } from '@/core/lib/translations'; import { addToCartErrorMessageKey, toAddToCartError, type AddToCartError, } from '@/core/lib/add-to-cart-error'; import { cn } from '@/core/lib/utils'; import { linePresentmentUnitPrice } from '@/core/lib/display-price'; import { isValidCheckoutId } from '@/core/lib/safe-redirect'; import { confirmCheckoutCompleted, isUncertainCompleteFailure } from '@/core/lib/complete-recovery'; import { trackBeginCheckout } from '@/core/lib/tracking'; import { judgeAgreement, judgeTaken, parsePriceDrift, parsePricesChanged, takeAgreedPrices, type PriceDriftLine, } from '@/core/lib/price-drift'; // Remembers which checkout belongs to which cart for this browser tab, so a // shopper who leaves /checkout and comes back (the bare link has no // `?checkout_id=`) resumes the same checkout instead of re-entering everything. const CHECKOUT_RESUME_PREFIX = 'brainerce:checkout:'; function readStoredCheckoutId(cartId: string): string | null { try { const raw = window.sessionStorage.getItem(CHECKOUT_RESUME_PREFIX + cartId); return isValidCheckoutId(raw) ? raw : null; } catch { return null; } } function storeCheckoutId(cartId: string, checkoutId: string): void { try { window.sessionStorage.setItem(CHECKOUT_RESUME_PREFIX + cartId, checkoutId); } catch { // Private mode / blocked storage: resuming is a convenience, never required. } } function clearStoredCheckoutId(cartId: string): void { try { window.sessionStorage.removeItem(CHECKOUT_RESUME_PREFIX + cartId); } catch { // ignore } } // A checkout the shopper can still continue. COMPLETED, FAILED and EXPIRED are over. // The two payment statuses stay in: a shopper who backs out of (or fails) the provider's // page returns to `/checkout?checkout_id=...` with the checkout in exactly that state. const RESUMABLE_STATUSES: ReadonlySet = new Set([ 'PENDING', 'SHIPPING_SET', 'PAYMENT_PENDING', 'PAYMENT_PROCESSING', ]); type LineKeyed = { productId: string; variantId?: string | null; quantity: number }; const lineKey = (i: LineKeyed) => `${i.productId}:${i.variantId ?? ''}:${i.quantity}`; /** * ⛔ EVERY checkout the page did not create a moment ago passes through this before it is * shown: the one remembered in sessionStorage AND the one named by `?checkout_id=`. A link * carries no proof it still fits. The browser autocompletes old checkout links into the * address bar, so a shopper with a brand-new cart lands on a checkout from yesterday: old * lines, an old shipping rate, sometimes an old currency. The payment step then answers 409 * (`currency_not_enabled`) and the page reads "Payment Not Configured". * * Reused only while ALL hold: * - it is still open (see RESUMABLE_STATUSES); * - it has not expired (`expiresAt`); * - it is in the currency the store charges now (a store that switched currency leaves * every older checkout unpayable); * - every one of its lines (product, variant, quantity) is in the cart now. * * `allowPartial` decides what "in the cart" means. A checkout opened from the cart page with * `?items=` covers only some lines, so a link may name a SUBSET of the cart. A checkout * remembered in sessionStorage is always a whole-cart one and must match it exactly: a line * added since would otherwise be left out of what the shopper pays for. */ function isResumableCheckout( prior: Checkout, cart: { items: LineKeyed[] }, currency: string | undefined, allowPartial: boolean ): boolean { if (!RESUMABLE_STATUSES.has(prior.status)) return false; if (prior.expiresAt) { const expires = Date.parse(prior.expiresAt); if (Number.isFinite(expires) && expires <= Date.now()) return false; } // Unknown current currency (store info not loaded, empty guest cart): do not guess. if (currency && prior.currency && prior.currency !== currency) return false; if (prior.lineItems.length === 0) return false; const checkoutLines = prior.lineItems.map(lineKey); const cartLines = cart.items.map(lineKey); if (!allowPartial) { const a = [...checkoutLines].sort(); const b = [...cartLines].sort(); return a.length === b.length && a.every((v, i) => v === b[i]); } const inCart = new Set(cartLines); return checkoutLines.every((line) => inCart.has(line)); } /** True when the checkout's lines are exactly the cart's lines (not a `?items=` subset). */ function coversWholeCart(prior: Checkout, cart: { items: LineKeyed[] }): boolean { return isResumableCheckout(prior, cart, undefined, false); } type CheckoutStep = | 'method' | 'address' | 'shipping' | 'pickup-point' | 'pickup' | 'custom-fields' | 'payment'; function CheckoutContent() { const searchParams = useSearchParams(); const { storeInfo } = useStoreInfo(); const { capabilities } = useStoreCapabilities(); // `status`, not `cart === null`: an empty guest cart has no id and `loading` // has no cart yet, and the page must tell "still loading", "could not load" // and "nothing in the cart" apart. `refreshCart` is kept ONLY for changes the // cart store did not make itself (see the three call sites below). const { cart, status, refreshCart, retry, flush, store } = useCart(); const { isLoggedIn } = useAuth(); // The shopper's "save my card" consent from the details step (unchecked by default). const [saveCardConsent, setSaveCardConsent] = useState(false); // Offer that consent only when the store's payment provider can actually // save a card here — a box that saves nothing misleads the shopper. const [savedCardsAvailable, setSavedCardsAvailable] = useState(false); useEffect(() => { if (!isLoggedIn) return; let cancelled = false; getClient() .getPaymentProviders() .then((res) => { // Read loosely: older published SDKs do not type this field yet. const provider = res.defaultProvider as { supportsSavedCards?: boolean } | undefined; if (!cancelled) setSavedCardsAvailable(provider?.supportsSavedCards === true); }) .catch(() => { // No providers info → no offer; checkout itself is unaffected. }); return () => { cancelled = true; }; }, [isLoggedIn]); // ⛔ THE call the region feature exists for. Product reads alone and the // shopper is SHOWN one price and CHARGED another: the checkout records the // region for reporting and for scoping which payment providers are offered. // `undefined` on a store with no regions, and the field is then omitted. const { regionId } = useRegion(); const currency = useCurrency(); const router = useRouter(); const t = useTranslations('checkout'); const tc = useTranslations('common'); const tr = useTranslations('reservation'); const tp = useTranslations('productDetail'); const [step, setStep] = useState('address'); const [checkout, setCheckout] = useState(null); const [placing, setPlacing] = useState(false); const [placeError, setPlaceError] = useState(null); const [shippingRates, setShippingRates] = useState([]); const [selectedRateId, setSelectedRateId] = useState(null); const [loading, setLoading] = useState(false); const [initializing, setInitializing] = useState(true); const [error, setError] = useState(null); const [destinations, setDestinations] = useState(null); const [pickupLocations, setPickupLocations] = useState([]); const [deliveryType, setDeliveryType] = useState<'shipping' | 'pickup'>('shipping'); const [isAllDigital, setIsAllDigital] = useState(false); const [prefillAddress, setPrefillAddress] = useState(null); const [prefillCustomer, setPrefillCustomer] = useState<{ email: string; firstName?: string; lastName?: string; phone?: string; } | null>(null); const [hasSavedAddress, setHasSavedAddress] = useState(false); const [orderBumps, setOrderBumps] = useState(null); const [addedBumpIds, setAddedBumpIds] = useState>(new Set()); const [bumpLoading, setBumpLoading] = useState(null); const [bumpError, setBumpError] = useState(null); const [customFields, setCustomFields] = useState([]); const [customFieldValues, setCustomFieldValues] = useState>({}); const [customFieldsLoading, setCustomFieldsLoading] = useState(false); // ---- A price moved since an item was added ---- // // `createCheckout` refuses a cart in which a line costs something else now (400 PRICE_DRIFT). // Charging the new price unseen is the risk the refusal exists for, so the shopper is shown which // lines moved (old and new price) and chooses: accept the new prices (the cart takes them, the // checkout is created again) or go back to the cart. `initNonce` re-runs the init effect below. const [priceDrift, setPriceDrift] = useState(null); const [acceptingPrices, setAcceptingPrices] = useState(false); const [priceDriftFailed, setPriceDriftFailed] = useState(false); // The price moved AGAIN after the shopper was shown it: shown again, and asked again. const [priceDriftChangedAgain, setPriceDriftChangedAgain] = useState(false); const [initNonce, setInitNonce] = useState(0); // ---- Reservation expiry blocks payment ---- // // When the reservation window runs out the held stock goes back on sale, so // the amount and the line items on this page may no longer be deliverable. // Payment is blocked until the shopper revisits the cart. Both pieces of // state key on the reservation's `expiresAt` rather than a bare boolean, so // the block survives a remount of the countdown and the ref stops the cart // refresh from looping. This page does not refetch the checkout, so the // block stands for the rest of the session once it closes. const reservationExpiresAt = checkout?.reservation?.expiresAt ?? null; const handledExpiryRef = useRef(null); const [expiredWindow, setExpiredWindow] = useState(null); const reservationExpired = expiredWindow !== null && expiredWindow === reservationExpiresAt; const handleReservationExpired = useCallback(() => { if (!reservationExpiresAt) return; setExpiredWindow(reservationExpiresAt); if (handledExpiryRef.current === reservationExpiresAt) return; handledExpiryRef.current = reservationExpiresAt; // Keep the header badge honest: the server may have dropped lines that // are no longer purchasable. A real refresh is right here: the server // changed the cart on its own clock, not through a store action. void refreshCart(); }, [reservationExpiresAt, refreshCart]); // ---- Payment step follows the cart ---- // // A payment intent is minted for the total at the moment the payment step // mounts. An order bump, a coupon or a gift card changes the cart (and the // total) after that, so the mounted `PaymentStep` would let the shopper pay an // intent for the OLD total while the cart holds different lines; the server now // refuses such an order and the payment has to be refunded. So every such change // (1) unmounts the payment step the moment it starts, (2) re-reads the checkout, // which makes the server re-quote the total from the cart lines, and (3) mounts a // NEW `PaymentStep` (new `key`) that asks for a fresh intent for that total. // Until all of that is done there is no pay button on the page. const [pendingCartSyncs, setPendingCartSyncs] = useState(0); const [paymentKey, setPaymentKey] = useState(0); const [paymentSyncFailed, setPaymentSyncFailed] = useState(false); // The total the shopper explicitly accepted after a CHECKOUT_TOTAL_CHANGED. The next payment step // is started WITH it, so if the total moved again meanwhile the platform answers a new 409 and the // shopper confirms that figure too. Cleared by every other reload (a cart change shows the buyer // the new total on the page itself). const [confirmedTotal, setConfirmedTotal] = useState(null); // Only the newest reload may write the checkout: two quick changes (a bump, // then a coupon) must not let the older answer overwrite the newer one. const checkoutSyncSeqRef = useRef(0); const beginPaymentSync = useCallback(() => setPendingCartSyncs((n) => n + 1), []); const endPaymentSync = useCallback(() => setPendingCartSyncs((n) => Math.max(0, n - 1)), []); // Re-read the checkout so the totals shown (and the next intent) are the // re-quoted ones, then force a fresh `PaymentStep`. Never throws: a failed // read leaves `paymentSyncFailed` set, and the payment step stays unmounted // behind a retry rather than offering a stale intent. const reloadCheckoutForPayment = useCallback(async (checkoutId: string, accepted?: number) => { const seq = ++checkoutSyncSeqRef.current; try { const updated = await getClient().getCheckout(checkoutId); if (seq !== checkoutSyncSeqRef.current) return; setCheckout(updated); setPaymentSyncFailed(false); setConfirmedTotal( typeof accepted === 'number' && Number.isFinite(accepted) ? accepted : null ); setPaymentKey((k) => k + 1); } catch (err) { console.error('Failed to reload checkout after a cart change:', err); if (seq === checkoutSyncSeqRef.current) setPaymentSyncFailed(true); } }, []); // `begin_checkout` — fired once the cart is loaded, guarded by a ref so a // re-render (or the shopper returning from a canceled payment) doesn't // report a second checkout start for the same cart. const beganCheckoutForCartRef = useRef(null); useEffect(() => { if (!cart?.id || !cart.items?.length) return; if (beganCheckoutForCartRef.current === cart.id) return; beganCheckoutForCartRef.current = cart.id; trackBeginCheckout(cart, currency); }, [cart, currency]); /** * Whether gift cards already cover the whole order. * * Read from `providerAmountDue`, which the SERVER computes — never from a * subtraction done here. The total is deliberately unchanged by a gift card, * so any figure derived in the browser would have to re-implement the tender * arithmetic and could disagree with what the backend will actually charge. */ const isFullyCovered = !!checkout && parseFloat(checkout.providerAmountDue ?? checkout.total) <= 0; const handlePlaceFreeOrder = async () => { if (!checkout || placing) return; try { setPlacing(true); setPlaceError(null); await getClient().completeCheckout(checkout.id); // `checkout_id`, NOT the order id. The confirmation page reads // `checkout_id` and every other caller (payment-step, all three of its // redirect paths) sends that. Sending the order id instead meant the page // found no parameter it recognised, made zero requests, and rendered its // "missing payment information" state over an order that had just been // placed and paid for — with the cart still full. // // The order id `completeCheckout` returns is deliberately not used: the // page resolves the order from the checkout, which is also what makes a // reload of the confirmation URL work. router.push(`/order-confirmation?checkout_id=${encodeURIComponent(checkout.id)}`); } catch (err) { // A 502/503/504 or a dropped connection does not say whether the order was created (the // server may have finished and emptied the cart). Ask the checkout before showing a failure, // so the shopper is never told "could not place" about an order that exists. if (isUncertainCompleteFailure(err)) { const completed = await confirmCheckoutCompleted(() => getClient().getCheckout(checkout.id) ); if (completed) { router.push(`/order-confirmation?checkout_id=${encodeURIComponent(checkout.id)}`); return; } // Never the raw "Request failed with status 502". Trying again is safe: completing a // checkout is idempotent on the server. setPlaceError(t('placeFailed')); setPlacing(false); return; } // The cart changed after this checkout was quoted (a line edited in another tab): no order // was created. Re-read the checkout so the total shown is the current one, then the buyer // can place the order again. const refusal = err as { statusCode?: number; details?: { code?: string } } | null; if (refusal?.statusCode === 400 && refusal.details?.code === 'CHECKOUT_CART_CHANGED') { void reloadCheckoutForPayment(checkout.id); } // Said out loud. A silent failure here leaves someone staring at a button // that did nothing, holding a card they believe they have already spent. setPlaceError(err instanceof Error ? err.message : t('placeFailed')); setPlacing(false); } }; // Check for returning from canceled payment const canceled = searchParams.get('canceled') === 'true'; const checkoutIdParam = searchParams.get('checkout_id'); const existingCheckoutId = isValidCheckoutId(checkoutIdParam) ? checkoutIdParam : null; // ---- Partial checkout ---- // // The cart page hands the ticked lines over as `?items=id1,id2` and omits // the param entirely for a full cart. Read as a raw string here and resolved // against the live cart inside initCheckout: it is URL input, so it is only // ever used after filtering against ids the cart actually has, and it is // read once at init rather than added to the effect's deps — a change must // not silently create a SECOND checkout for the same cart. const selectedItemsParam = searchParams.get('items'); // Pre-fill address and customer data from profile when logged in useEffect(() => { if (!isLoggedIn) return; getClient() .getCheckoutPrefillData() .then((data) => { if (data.customer) setPrefillCustomer(data.customer); if (data.shippingAddress) { setPrefillAddress(data.shippingAddress); setHasSavedAddress(true); } }) .catch(() => {}); }, [isLoggedIn]); // Initialize or resume checkout (only once) const checkoutInitRef = useRef(false); const cartIdRef = useRef(null); useEffect(() => { // Only init once, or if cart ID actually changed (e.g. cart was replaced) if (!cart?.id) return; if (checkoutInitRef.current && cartIdRef.current === cart.id) return; checkoutInitRef.current = true; cartIdRef.current = cart.id; const initCheckout = async () => { try { setInitializing(true); setError(null); const client = getClient(); // A checkout is created from what the SERVER holds. If a quantity tap or // an add is still on its way (the shopper clicked through from the cart a // moment after editing it), wait for it, or the checkout charges for // lines they no longer see. Then work from the cart as it is NOW: the // `cart` this effect closed over may predate the change. const flushed = await flush(); if (!flushed.ok) { setError(t('failedToInitCheckout')); return; } const liveCart = store.getSnapshot().cart ?? cart; // Fetch shipping destinations and pickup locations in parallel client .getShippingDestinations() .then(setDestinations) .catch(() => {}); const locations = await client.getPickupLocations().catch(() => [] as PickupLocation[]); setPickupLocations(locations); // The bare /checkout link carries no id. Look for the one this tab already // opened for this very cart, and use it only while it still matches the // cart. A shopper choosing a subset of lines always starts a fresh one. // // ⛔ The id in the address bar gets the SAME vetting (`isResumableCheckout`): a link is // not proof the checkout still fits this cart, this currency, this moment. One that // fails is dropped and a fresh checkout is created below, exactly as when the link // carries no id at all. Currency: what the store charges NOW, else the cart's (a checkout // is created in its cart's currency). Never the `'USD'` fallback of `useCurrency()`, // which a page still loading store info would trip over. const currentCurrency = storeInfo?.currency ?? liveCart.currency; let resumed: Checkout | null = null; if (existingCheckoutId) { try { const prior = await client.getCheckout(existingCheckoutId); // A link may name a partial (`?items=`) checkout, so a subset of the cart is fine. if (isResumableCheckout(prior, liveCart, currentCurrency, true)) resumed = prior; } catch { // 404 / not this shopper's: same as a stale one. } if (!resumed) clearStoredCheckoutId(liveCart.id); } else if (!selectedItemsParam) { const storedId = readStoredCheckoutId(liveCart.id); if (storedId) { try { const prior = await client.getCheckout(storedId); if (isResumableCheckout(prior, liveCart, currentCurrency, false)) resumed = prior; else clearStoredCheckoutId(liveCart.id); } catch { clearStoredCheckoutId(liveCart.id); } } } // Resume what passed the check above if (resumed) { const existing = resumed; // Remember it for a bare `/checkout` link only when it is the WHOLE cart's checkout. if (coversWholeCart(existing, liveCart)) storeCheckoutId(liveCart.id, existing.id); setCheckout(existing); // Preload custom field definitions and any existing values so the // step indicator and "change options" affordance work on resume. client .getCheckoutCustomFields(existing.id) .then((fields) => { setCustomFields(fields); const existingValues = ( existing as unknown as { customFieldValues?: Record | null; } ).customFieldValues; if (existingValues) setCustomFieldValues(existingValues); }) .catch(() => { setCustomFields([]); }); // Determine step based on checkout state const allDigital = existing.lineItems.every( (i) => (i.product as unknown as { isDownloadable?: boolean }).isDownloadable ); setIsAllDigital(allDigital); if (allDigital) { // Digital products: show contact info step if email not set, else payment setStep(existing.email ? 'payment' : 'address'); } else if (existing.deliveryType === 'pickup' && existing.pickupLocation) { setDeliveryType('pickup'); setStep('payment'); } else if ( existing.shippingAddress && existing.shippingRateId && existing.shippingMethod?.requiresPickupPoint && !existing.pickupPoint ) { // A rate that delivers to a pickup point is chosen, the point is not: payment would be refused. setStep('pickup-point'); } else if (existing.shippingAddress && existing.shippingRateId) { setStep('payment'); } else if (existing.shippingAddress) { // Fetch shipping rates const rates = await client.getShippingRates(existing.id); setShippingRates(rates); setStep('shipping'); } else if (locations.length > 0) { setStep('method'); } return; } // Create new checkout — cart is always server-side now. // // `selectedItemIds` scopes the checkout to a subset of the cart: after // payment those lines are removed and the rest stay in the still-ACTIVE // cart. Sent ONLY when the shopper picked a strict, non-empty subset — // an empty result (a stale link, or ids from another cart) and a // full-cart selection both fall through to the normal whole-cart call, // because omitting the field is what "check out everything" means. const cartItemIds = new Set(liveCart.items.map((item) => item.id)); const requestedItemIds = (selectedItemsParam ?? '') .split(',') .map((id) => id.trim()) .filter((id) => cartItemIds.has(id)); const isStrictSubset = requestedItemIds.length > 0 && requestedItemIds.length < cartItemIds.size; const newCheckout = await client.createCheckout({ cartId: liveCart.id, ...(isStrictSubset ? { selectedItemIds: requestedItemIds } : {}), ...(regionId ? { regionId } : {}), }); setCheckout(newCheckout); // A subset checkout belongs to those lines only, never to the whole cart. if (!isStrictSubset) storeCheckoutId(liveCart.id, newCheckout.id); // Put the id in the URL so a RELOAD resumes instead of starting over. // // The resume path above already reads `?checkout_id=`, but until now only // a payment provider's return URL ever set it. A shopper who refreshed // lost their address, their shipping choice, and — visibly — any gift // card they had applied, because a fresh checkout cannot see holds that // belong to the abandoned one. The money was never lost, but it looked // lost, and re-entering the same code was correctly refused because the // old hold still reserved it. // // `replaceState`, not router.replace: this is the same page and the same // checkout, so it must not push history, re-render, or move the scroll // position out from under someone mid-form. if (typeof window !== 'undefined') { const url = new URL(window.location.href); url.searchParams.set('checkout_id', newCheckout.id); window.history.replaceState(window.history.state, '', url); } // If all items are downloadable, skip shipping — show contact info step const allDigital = newCheckout.lineItems.every( (i) => (i.product as unknown as { isDownloadable?: boolean }).isDownloadable ); setIsAllDigital(allDigital); if (allDigital) { setStep('address'); return; } // If pickup locations exist, start with delivery method selection if (locations.length > 0) { setStep('method'); } } catch (err) { // A price moved since an item was added: not a failure, a question for the shopper. const drift = parsePriceDrift(err); if (drift) { setPriceDrift(drift); return; } // A store that is at its plan's order cap, or suspended, refuses to open a // checkout at all (402 PLAN_ORDERS_EXHAUSTED / STORE_SUSPENDED). Their // `message` is written for the merchant ("must upgrade their plan"), so the // shopper gets a plain sentence instead. `details.code` is the response // body's machine code (the same value as `BrainerceError.code`). const body = (err as { details?: { code?: unknown } } | null)?.details; const code = typeof body?.code === 'string' ? body.code : undefined; if (code === 'PLAN_ORDERS_EXHAUSTED' || code === 'STORE_SUSPENDED') { setError(t('storeNotAcceptingOrders')); } else { setError(err instanceof Error ? err.message : t('failedToInitCheckout')); } } finally { setInitializing(false); } }; initCheckout(); // `regionId` is a dependency because a checkout is created ONCE per cart: // if the shopper switches region on the cart page and lands here, the // effect has to re-run or the checkout is stamped with the region they // just left. }, [cart?.id, existingCheckoutId, regionId, initNonce]); // The shopper accepted the new prices THEY WERE SHOWN: the server takes them into the cart's // lines, the cart store re-reads, and the init effect creates the checkout again. What they // agreed to is a CEILING per line (a price no higher than the one shown; see `judgeAgreement`), // and the shop can move a price again between the moment it was shown and the moment it is // taken, so: the cart is judged before taking, the prices are sent to the server (which refuses // with 409 PRICES_CHANGED and changes nothing if one is above them), and the cart is judged // again after (a server that predates the rule ignores what was sent). Whenever a price breaks // the agreement, EVERY changed line is shown again and the shopper is asked again, never taken // on a consent that was for another number. A failure leaves everything as it was and says so. const acceptNewPrices = async () => { if (!cart?.id || acceptingPrices || !priceDrift) return; setAcceptingPrices(true); setPriceDriftFailed(false); try { const client = getClient(); const live = await client.getCart(cart.id); const liveItems = live.items ?? []; const verdict = judgeAgreement(priceDrift, liveItems); if (verdict.breaks) { setPriceDrift(verdict.lines); // A refusal whose lines could not be read had nothing shown yet: this IS the first list. setPriceDriftChangedAgain(priceDrift.length > 0); return; } // Nothing moved (the prices went back, and none is above what was agreed): nothing to take, // so the server is not called at all. if (liveItems.some((item) => item.priceChanged)) { let taken; try { taken = await takeAgreedPrices(client, cart.id, priceDrift); } catch (err) { const refused = parsePricesChanged(err); if (refused && refused.length > 0) { // The server saw a price above what was agreed and changed nothing: show its lines. setPriceDrift(refused); setPriceDriftChangedAgain(true); return; } throw err; } await refreshCart(); const afterTake = judgeTaken(liveItems, taken.items ?? [], priceDrift); if (afterTake.breaks) { // What was agreed and what was taken differ: say so, and the next click agrees to the // price now held (the check before taking then finds nothing left to take). setPriceDrift(afterTake.lines); setPriceDriftChangedAgain(true); return; } } setPriceDrift(null); setPriceDriftChangedAgain(false); checkoutInitRef.current = false; setInitNonce((n) => n + 1); } catch { setPriceDriftFailed(true); } finally { setAcceptingPrices(false); } }; // Load order bumps when checkout is available useEffect(() => { if (!checkout?.id || storeInfo?.upsell?.checkoutOrderBumpEnabled === false) { setOrderBumps(null); return; } const client = getClient(); client .getCheckoutBumps(checkout.id) .then((data) => { setOrderBumps(data); // Detect already-added bumps from cart if (cart?.items) { const existingBumpIds = new Set(); for (const item of cart.items) { const meta = item.metadata as Record | undefined; if (meta?.isOrderBump && meta?.orderBumpId) { existingBumpIds.add(meta.orderBumpId as string); } } setAddedBumpIds(existingBumpIds); } }) .catch(() => {}); }, [checkout?.id, storeInfo?.upsell?.checkoutOrderBumpEnabled]); // Handle bump toggle async function handleBumpToggle(bumpId: string, add: boolean, variantId?: string) { if (!cart?.id || bumpLoading) return; setBumpError(null); // The payment step comes off the page BEFORE the cart changes, so there is // no moment where the old intent can still be paid against the new lines. beginPaymentSync(); try { setBumpLoading(bumpId); const client = getClient(); if (add) { await client.addOrderBump(cart.id, bumpId, variantId); setAddedBumpIds((prev) => new Set([...prev, bumpId])); } else { await client.removeOrderBump(cart.id, bumpId); setAddedBumpIds((prev) => { const next = new Set(prev); next.delete(bumpId); return next; }); } // A refresh is right here: an order bump is added or // removed with its own SDK call, which the cart store does not know about, // so its view has to be told to re-read. await refreshCart(); } catch (err) { // A bump is an extra cart line, so it can be refused by the 50-line cap // like any other add. Logging alone left the checkbox springing back with // no explanation, at the least forgiving point in the flow. setBumpError(toAddToCartError(err)); console.error('Failed to toggle order bump:', err); } finally { // Re-quote the checkout and remount the payment step even when the toggle // failed: after a refused add the cart is unchanged and the server hands // back the same open intent, and after a half-applied one this is what // keeps a stale intent off the page. if (checkout?.id) await reloadCheckoutForPayment(checkout.id); endPaymentSync(); setBumpLoading(null); } } // Handle shipping address submission async function handleAddressSubmit( address: SetShippingAddressDto, consent: { acceptsMarketing: boolean; saveDetails: boolean; saveCard: boolean } ) { if (!checkout) return; // Held for the payment step: the card is vaulted only when the shopper // ticked the consent box on THIS checkout (lost on reload → not saved). setSaveCardConsent(consent.saveCard); try { setLoading(true); setError(null); const client = getClient(); if (isAllDigital) { // Digital products: set customer info only, skip shipping const updated = await client.setCheckoutCustomer(checkout.id, { email: address.email, firstName: address.firstName, lastName: address.lastName, phone: address.phone, acceptsMarketing: consent.acceptsMarketing, notes: address.notes, }); setCheckout(updated); setStep('payment'); } else { const response = await client.setShippingAddress(checkout.id, address); setCheckout(response.checkout); setShippingRates(response.rates); setStep('shipping'); } // Update marketing preference for logged-in users if (isLoggedIn) { try { await client.updateMyProfile({ acceptsMarketing: consent.acceptsMarketing }); } catch { // non-critical } } // Save address to profile if checkbox was checked and no existing saved address if (isLoggedIn && consent.saveDetails && !hasSavedAddress && !isAllDigital) { try { await client.addMyAddress({ firstName: address.firstName, lastName: address.lastName, line1: address.line1, line2: address.line2, city: address.city, region: address.region, postalCode: address.postalCode, country: address.country, phone: address.phone, isDefault: true, }); } catch { // non-critical } } } catch (err) { const message = err instanceof Error ? err.message : t('failedToSaveAddress'); setError(message); } finally { setLoading(false); } } // After shipping/pickup is set, decide whether to show the custom-fields step // or jump straight to payment. Returns the next step. async function loadCustomFieldsOrSkip(checkoutId: string): Promise { try { const fields = await getClient().getCheckoutCustomFields(checkoutId); setCustomFields(fields); return fields.length > 0 ? 'custom-fields' : 'payment'; } catch { // If the endpoint isn't available or fails, fall through to payment // rather than blocking the customer. setCustomFields([]); return 'payment'; } } // Handle shipping method selection async function handleShippingSelect(rateId: string) { if (!checkout) return; try { setLoading(true); setError(null); setSelectedRateId(rateId); const client = getClient(); const updated = await client.selectShippingMethod(checkout.id, rateId); setCheckout(updated); // A rate that delivers to a carrier pickup point needs the shopper to choose the point first. if (shippingRates.find((rate) => rate.id === rateId)?.requiresPickupPoint) { setStep('pickup-point'); return; } setStep(await loadCustomFieldsOrSkip(updated.id)); } catch (err) { const message = err instanceof Error ? err.message : t('failedToSelectShipping'); setError(message); } finally { setLoading(false); } } // The shopper chose a carrier pickup point: the server returned the checkout with it stored. async function handlePickupPointChosen(updated: Checkout) { try { setLoading(true); setError(null); setCheckout(updated); setStep(await loadCustomFieldsOrSkip(updated.id)); } finally { setLoading(false); } } // Submit custom fields async function handleCustomFieldsApply() { if (!checkout) return; try { setCustomFieldsLoading(true); setError(null); const updated = await getClient().setCheckoutCustomFields(checkout.id, customFieldValues); setCheckout(updated); setStep('payment'); } catch (err) { const message = err instanceof Error ? err.message : t('customFieldsFailed'); setError(message); } finally { setCustomFieldsLoading(false); } } // Handle delivery method selection async function handleDeliveryTypeSelect(method: 'shipping' | 'pickup') { if (!checkout) return; try { setLoading(true); setError(null); setDeliveryType(method); const client = getClient(); await client.setDeliveryType(checkout.id, method); if (method === 'shipping') { setStep('address'); } else { setStep('pickup'); } } catch (err) { const message = err instanceof Error ? err.message : t('failedToSetDeliveryMethod'); setError(message); } finally { setLoading(false); } } // Handle pickup location selection async function handlePickupSelect( locationId: string, customerInfo: { email: string; firstName?: string; lastName?: string; phone?: string } ) { if (!checkout) return; try { setLoading(true); setError(null); const client = getClient(); const updated = await client.selectPickupLocation(checkout.id, { pickupRateId: locationId, email: customerInfo.email, firstName: customerInfo.firstName, lastName: customerInfo.lastName, phone: customerInfo.phone, }); setCheckout(updated); setStep(await loadCustomFieldsOrSkip(updated.id)); } catch (err) { const message = err instanceof Error ? err.message : t('failedToSelectPickup'); setError(message); } finally { setLoading(false); } } // Re-read the cart and the checkout after a coupon apply/remove. // Here (and only here) a refresh is right: on this page the coupon goes through // applyCheckoutCoupon/removeCheckoutCoupon, which change the cart without the // cart store knowing. The checkout // totals are updated server-side, so the checkout is re-fetched too, to get the // updated discountAmount and total. // // The same handler serves the gift-card field. A coupon or a gift card moves the // total the open payment intent was minted for, so the payment step is unmounted // while this runs and remounted (fresh intent) once the checkout is re-read. const handleCouponUpdate = useCallback(async () => { beginPaymentSync(); try { await refreshCart(); } catch (err) { console.error('Failed to refresh cart after coupon update:', err); } try { if (checkout) await reloadCheckoutForPayment(checkout.id); } finally { endPaymentSync(); } }, [checkout, refreshCart, beginPaymentSync, endPaymentSync, reloadCheckoutForPayment]); // Branch on the cart store's `status`. Reading `cart === null` here conflated // three different things: a spinner that never ends for an empty guest cart // (it has no id, so the checkout never initialises and `initializing` never // clears), a blank "empty cart" flash while the cart was still loading, and // an "empty cart" lie when the cart simply failed to load. if (status === 'loading' || (initializing && status === 'ready')) { return (
); } if (status === 'error') { return (

{t('errorTitle')}

{t('failedToInitCheckout')}

{t('returnToCart')}
); } // Empty cart if (!cart || cart.items.length === 0) { return (

{t('emptyCart')}

{t('emptyCartSubtitle')}

{tc('shopNow')}
); } if (priceDrift && !checkout) { return (

{t('priceDriftTitle')}

{t('priceDriftIntro')}

{priceDriftChangedAgain && (

{t('priceDriftChangedAgain')}

)} {priceDrift.length > 0 && (
    {priceDrift.map((line) => { const item = cart?.items.find((i) => i.id === line.itemId); const name = item ? `${item.product.name}${item.variant?.name ? ` (${item.variant.name})` : ''}` : t('priceDriftUnknownItem'); return (
  • {name} {formatPrice(parseFloat(line.from), { currency }) as string} {' '} {formatPrice(parseFloat(line.to), { currency }) as string}
  • ); })}
)} {priceDriftFailed && (

{t('priceDriftFailed')}

)}
{t('returnToCart')}
); } if (error && !checkout) { return (

{t('errorTitle')}

{error}

{t('returnToCart')}
); } const customFieldsStep = customFields.length > 0 ? [{ key: 'custom-fields' as CheckoutStep, label: t('stepCustomFields') }] : []; const steps: { key: CheckoutStep; label: string }[] = isAllDigital ? [ { key: 'address', label: t('stepContactInfo') }, ...customFieldsStep, { key: 'payment', label: t('stepPayment') }, ] : pickupLocations.length > 0 ? deliveryType === 'pickup' ? [ { key: 'method', label: t('stepMethod') }, { key: 'pickup', label: t('stepPickup') }, ...customFieldsStep, { key: 'payment', label: t('stepPayment') }, ] : [ { key: 'method', label: t('stepMethod') }, { key: 'address', label: t('stepAddress') }, { key: 'shipping', label: t('stepShipping') }, ...customFieldsStep, { key: 'payment', label: t('stepPayment') }, ] : [ { key: 'address', label: t('stepAddress') }, { key: 'shipping', label: t('stepShipping') }, ...customFieldsStep, { key: 'payment', label: t('stepPayment') }, ]; const currentStepIndex = steps.findIndex((s) => s.key === step); // FX-at-checkout. When the region charges in its own currency the checkout carries `presentment` (the amounts // the buyer is CHARGED) and each line a `presentmentUnitPrice`. The whole summary is then shown in that one // currency, as the SDK docs instruct, so the shopper never reads dollars on the lines and euros only at the // bottom. It is used only when EVERY line has its presentment price and no gift card is applied (a card is held // in the store currency and leaves a different amount for the provider): otherwise the rows keep the store // currency and the "Amount charged" row below states the charged number. const presentment = checkout?.presentment ?? null; const showInPresentment = presentment !== null && (checkout?.lineItems?.length ?? 0) > 0 && (checkout?.lineItems ?? []).every((li) => linePresentmentUnitPrice(li) !== undefined) && (checkout?.tenders?.length ?? 0) === 0; const summaryCurrency = showInPresentment && presentment ? presentment.currency : currency; /** The amount in the summary currency: the presentment figure when shown, else the store-currency one. */ const inSummary = (storeAmount: string, presentmentAmount: string | undefined): number => parseFloat(showInPresentment && presentmentAmount != null ? presentmentAmount : storeAmount); return (

{t('title')}

{/* Canceled payment banner */} {canceled && (
{t('paymentCanceledBanner')}
)} {/* Reservation countdown. onExpire is what blocks payment below. */} {checkout?.reservation?.hasReservation && ( )} {/* Expired reservation: payment is off the table until the cart is reviewed, so say so on every step, not only on the payment step. */} {reservationExpired && (

{tr('expiredCheckout')}

{tr('backToCart')}
)} {/* Step indicator */}
{steps.map((s, index) => (
{index > 0 && (
)}
{index < currentStepIndex ? ( ) : ( index + 1 )}
{s.label}
))}
{/* Error banner */} {error && checkout && (
{error}
)}
{/* Main content */}
{/* Delivery Method */} {step === 'method' && (

{t('deliveryMethod')}

)} {/* Address */} {step === 'address' && (

{isAllDigital ? t('contactInfo') : t('shippingAddress')}

{!isAllDigital && pickupLocations.length > 0 && ( )}
)} {/* Step 2: Shipping */} {step === 'shipping' && (

{t('shippingMethod')}

)} {/* Carrier pickup point: where the parcel goes, for a rate that delivers to one */} {step === 'pickup-point' && checkout && (

{t('pickupPointTitle')}

)} {/* Pickup */} {step === 'pickup' && (

{t('pickupLocation')}

)} {/* Custom Fields (optional, between shipping/pickup and payment) */} {step === 'custom-fields' && checkout && (

{t('customFieldsTitle')}

setCustomFieldValues((prev) => ({ ...prev, [key]: value })) } onApply={handleCustomFieldsApply} onUploadFile={(file) => getClient().uploadCustomizationFile(file)} timezone={storeInfo?.timezone} loading={customFieldsLoading} />
)} {/* Payment */} {step === 'payment' && checkout && (

{t('payment')}

{customFields.length > 0 ? ( ) : ( !isAllDigital && ( ) )}
{/* Never mount the payment form on an expired reservation: the stock behind these lines is back on sale, so a charge here can take money for something that cannot ship. */} {reservationExpired ? (

{tr('expired')}

{tr('expiredCheckout')}

{tr('backToCart')}
) : isFullyCovered ? ( /* Nothing left for a provider to charge. Gift cards can cover an order completely, and demanding a card for 0.00 is not a formality — most providers reject a zero-amount charge outright, so the shopper is stuck holding a paid-for order they cannot place. The backend already derives this server-side (`isZeroDue`) and completes without a payment, so the only thing missing was a way to ask. */

{t('fullyCovered')}

{t('fullyCoveredHint')}

{placeError && (

{placeError}

)}
) : pendingCartSyncs > 0 ? ( /* The cart is changing (order bump, coupon, gift card), so the intent the payment step minted is for a total that is about to be wrong. No pay button until the checkout is re-quoted. */

{t('preparingPayment')}

) : paymentSyncFailed ? (

{t('failedToStartCheckout')}

) : ( // `key`: a new total needs a new intent. The step mints one when it // mounts, so a remount is how it is told the cart changed. void reloadCheckoutForPayment(checkout.id, accepted) } /> )}
)}
{/* Order summary sidebar */}

{t('orderSummary')}

{/* Line items */} {checkout?.lineItems && checkout.lineItems.length > 0 ? (
{checkout.lineItems.map((item) => { const imageUrl = item.product.images?.[0]?.url || null; const name = item.variant?.name || item.product.name; const lineTotal = inSummary(item.unitPrice, linePresentmentUnitPrice(item)) * item.quantity; return (
{imageUrl ? ( {name} ) : (
)}

{name}

{tc('qty')} {item.quantity}

{formatPrice(lineTotal, { currency: summaryCurrency }) as string}
{/* The buyer's own input on this line — engraving text, uploaded photo, picked colour — so it can be checked before paying. `CheckoutLineItem.customizations` is the SDK's resolved label/value/type map, absent on a line with no customization, so a plain order renders exactly as before. */} {item.customizations && ( )}
); })}
) : ( // Fallback to cart items if checkout line items aren't loaded yet cart && (

{cart.items.length} {cart.items.length === 1 ? tc('item') : tc('items')}

) )} {/* Order bumps */} {orderBumps?.bumps && orderBumps.bumps.length > 0 && (

{t('addToYourOrder')}

{orderBumps.bumps.map((bump) => ( ))} {/* Why the bump was refused. Without it the checkbox just springs back and the shopper is left guessing at checkout. */} {bumpError && (

{tp(addToCartErrorMessageKey(bumpError))}

)}
)} {/* Coupon input — show from shipping/pickup step onwards (or immediately if digital) */} {cart && (isAllDigital || step === 'shipping' || step === 'pickup' || step === 'payment') && (
{/* Beside the coupon field, and deliberately NOT inside it. A coupon reduces what the order is worth; a gift card pays for an order still worth the same. They look adjacent because a shopper reaches for them at the same moment, and they behave differently because they are different things. */} {/* Hidden while the store has gift cards off (`hasGiftCards`), so the shopper is not offered a box that can never accept a code. A card already applied keeps the field so it can still be removed. */} {checkout?.id && (capabilities?.features.hasGiftCards === true || (checkout.tenders?.length ?? 0) > 0) && ( formatPrice(parseFloat(value), { currency }) as string } onUpdate={handleCouponUpdate} /> )} {/* The club balance of a CASHBACK club. Unlike the gift card above it IS a discount: the total and the tax drop, the way a coupon's do. Only a signed-in shopper on a store that runs the club is offered it; the control hides itself when there is nothing to spend. */} {checkout?.id && isLoggedIn && capabilities?.features.hasCashbackClub === true && ( formatPrice(parseFloat(value), { currency }) as string} onUpdate={handleCouponUpdate} /> )}
)} {/* Totals */} {checkout && (() => { // Every row in this column is GROSS, and the tax row below is // informational. That is how a VAT receipt reads, it is what // `TaxDisplay` already says on its own line ("VAT 18% included"), // and it is exactly what the order-history summary renders — one // convention across all three, so a shopper who compares the // checkout against the order they later open sees the same // arithmetic twice. // // This deliberately drops an earlier attempt to show a NET // subtotal for inclusive stores. Two things were wrong with it. // It read `taxBreakdown.subtotal`, which is the net of every // TAXED LINE — shipping included — and then added // `shippingAmount` below, counting shipping twice: a real // checkout printed 54.06 + 9.99 + 7.93 beside a 61.99 total. // And a net subtotal cannot coexist with a tax row labelled // "included": either the shopper adds the tax, contradicting the // label, or they do not, and the column falls short of the total // by the whole VAT. Subtracting the shipping net back out fixes // the arithmetic and leaves the contradiction, so the row that // has to go is the special case itself. // // Gross + gross = total, with the VAT stated beneath it: // 52.00 + 9.99 = 61.99, "VAT 18% included 7.93". const displayedSubtotal = inSummary(checkout.subtotal, presentment?.subtotal); const subtotalLabel = tc('subtotal'); return (
{subtotalLabel} {formatPrice(displayedSubtotal, { currency: summaryCurrency }) as string}
{(() => { const totalDiscount = inSummary( checkout.discountAmount, presentment?.discountAmount ); const ruleAmt = parseFloat(checkout.ruleDiscountAmount || '0'); const couponAmt = totalDiscount - ruleAmt; const rules = cart?.appliedDiscounts; if (totalDiscount <= 0) return null; // The per-rule and coupon amounts are stored in the store currency, so a summary in the // charged currency shows the discount as one row it can state exactly. if (showInPresentment) { return (
{tc('discount')} - { formatPrice(totalDiscount, { currency: summaryCurrency, }) as string }
); } return ( <> {rules && rules.length > 0 ? rules.map((rule) => (
{rule.ruleName} - { formatPrice(parseFloat(rule.discountAmount), { currency, }) as string }
)) : ruleAmt > 0 && (
{tc('generalDiscount')} -{formatPrice(ruleAmt, { currency }) as string}
)} {checkout.couponCode && couponAmt > 0 && (
{tc('couponDiscount')} ({checkout.couponCode}) -{formatPrice(couponAmt, { currency }) as string}
)} {!checkout.couponCode && ruleAmt <= 0 && (!rules || rules.length === 0) && (
{tc('discount')} -{formatPrice(totalDiscount, { currency }) as string}
)} ); })()} {(parseFloat(checkout.shippingAmount) > 0 || checkout.deliveryType === 'pickup') && (
{checkout.deliveryType === 'pickup' ? tc('pickup') : tc('shipping')} {parseFloat(checkout.shippingAmount) === 0 ? tc('free') : (formatPrice( inSummary(checkout.shippingAmount, presentment?.shippingAmount), { currency: summaryCurrency } ) as string)}
)} {/* Custom field surcharges (one line per applied surcharge) */} {showInPresentment && checkout.appliedSurcharges && checkout.appliedSurcharges.length > 0 && inSummary('0', presentment?.surchargeAmount) > 0 && (
{checkout.appliedSurcharges.map((s) => s.name).join(', ')} { formatPrice(inSummary('0', presentment?.surchargeAmount), { currency: summaryCurrency, }) as string }
)} {!showInPresentment && checkout.appliedSurcharges && checkout.appliedSurcharges.length > 0 && ( <> {checkout.appliedSurcharges.map((s) => (
{s.name} {formatPrice(Number(s.amount), { currency }) as string}
))} )}
{tc('total')} { formatPrice(inSummary(checkout.total, presentment?.total), { currency: summaryCurrency, }) as string }
{showInPresentment && presentment && (

{t('chargedInCurrency', { currency: presentment.currency })}

)} {/* Gift cards sit BELOW the total, not among the discounts above it. The total is what the order is worth and does not move; what changes is only what the card leaves for the payment provider to charge. Putting this in the discount block would understate the taxable base to the shopper and on the receipt. */} {checkout.tenders && checkout.tenders.length > 0 && ( <> {checkout.tenders.map((tender) => (
{tc('giftCard')} - { formatPrice(parseFloat(tender.amountApplied), { currency, }) as string }
))}
{tc('amountDue')} { formatPrice( parseFloat(checkout.providerAmountDue ?? checkout.total), { currency, } ) as string }
)} {/* FX-at-checkout presentment overlay (see SDK `Checkout.presentment` docs). Normally the rows above are already in the charged currency (`showInPresentment`) and this row stays out. It appears only when they could not be converted (a line without its presentment price, or a gift card in the store currency): then it is the one number the payment provider actually charges. */} {checkout.presentment && !showInPresentment && (
{tc('amountCharged')} ({checkout.presentment.currency}) { formatPrice(parseFloat(checkout.presentment.total), { currency: checkout.presentment.currency, }) as string }
)}
); })()}
); } export default function CheckoutPage() { return (
} > ); }