'use client'; import { Suspense, useEffect, useState } from 'react'; import { useSearchParams } from 'next/navigation'; import { CdnImage as Image } from '@/ui/shared/cdn-image'; import { Link } from '@/core/lib/navigation'; import type { Order, OrderDownloadLink, PaymentReturnResult } from 'brainerce'; import { formatPrice } from 'brainerce'; import { getClient } from '@/core/lib/brainerce'; import { useCartStore } from '@/core/providers/store-provider'; import { useCurrency } from '@/core/lib/use-currency'; import { OrderCustomizations } from '@/components/account/order-customizations'; import { LoadingSpinner } from '@/ui/shared/loading-spinner'; import { useTranslations } from '@/core/lib/translations'; import { trackPurchase } from '@/core/lib/tracking'; import { orderLineBrands } from '@/core/lib/sdk-compat'; import { isValidCheckoutId } from '@/core/lib/safe-redirect'; import { GoogleCustomerReviewsOptIn } from '@/components/google-customer-reviews-optin'; // One `completePaymentReturn` round waits up to this long for the order. const ORDER_WAIT_MS = 30000; // A held payment (some providers answer `processing` for minutes while they settle) is // NOT a failure: after the first round this page shows the "being processed" state and // keeps asking for the order for a few more rounds. Bounded, so a tab left open stops. const HELD_PAYMENT_EXTRA_ROUNDS = 6; function OrderConfirmationContent() { const searchParams = useSearchParams(); const checkoutId = searchParams.get('checkout_id'); // The stable store handle (not `useCart()`, whose object changes with every cart // update and would re-run the effect below). const cartStore = useCartStore(); const t = useTranslations('orderConfirmation'); const tc = useTranslations('common'); // `succeeded` = the server has the order. `pending` = paid or still settling, the order is // on its way. `failed` / `canceled` = the payment did not go through; the checkout is still valid. const [result, setResult] = useState(null); // The real Order behind the checkout. `completePaymentReturn` resolves to a status // envelope that carries no line items at all, so this second fetch is the // only way this page can show what was actually bought. const [order, setOrder] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { if (!checkoutId) { setError(t('missingCheckoutInfo')); setLoading(false); return; } // Effect cleanup flips this: React Strict Mode runs the effect twice in development, and // a navigation away must not set state on an unmounted page. let alive = true; async function confirmPayment() { try { const client = getClient(); // `completePaymentReturn` hands the provider's return parameters to the server // (CardCom: lowprofilecode; PayPal: token + PayerID; Stripe needs none) for // server-side verification, then waits for the ORDER. The URL alone proves // nothing. It also answers `?canceled=true` / `?failed=true` straight away. It never // creates a payment: retrying a held payment would let the shopper pay twice. let outcome = await client.completePaymentReturn(checkoutId!, { maxWaitMs: ORDER_WAIT_MS, }); if (!alive) return; // Held payment: show the "being processed" state now and keep asking for the order. // `search: ''` on the later rounds skips the one-off provider confirm call, so they // only wait for the order. for ( let round = 0; outcome.status === 'pending' && round < HELD_PAYMENT_EXTRA_ROUNDS; round++ ) { setResult(outcome); setLoading(false); outcome = await client.completePaymentReturn(checkoutId!, { search: '', maxWaitMs: ORDER_WAIT_MS, }); if (!alive) return; } setResult(outcome); // Only a payment that went through empties the cart. A failed or canceled one keeps // it: the shopper is sent back to this same checkout, and an empty cart would end // that at "your cart is empty". // // handlePaymentSuccess is SYNCHRONOUS: it returns the outcome rather than a // promise, so there is nothing to await. Read the result, then reset the cart // store AFTER it, or the header badge can be repopulated from the pre-clear cart. // // mode 'full' - whole cart cleared // mode 'partial' - only the purchased items were removed (partial // checkout); whatever is left is still for sale // mode 'none' - nothing to clear. Usually the SDK's idempotency // guard: a refresh of this URL hits it. On a good // order this is expected, so it must never become a // warning to the shopper. // // The order is complete, so the cart store starts over: it drops the // remembered item count (the header badge goes to 0 now, not after the // next request), abandons any request still in flight for the old cart, // and loads whatever is left. It is not awaited: the confirmation below // does not depend on it. if (outcome.status === 'succeeded') { const clearResult = client.handlePaymentSuccess(checkoutId!); if (clearResult.mode !== 'none') cartStore.reset('order-complete'); if (!clearResult.cleared && clearResult.mode !== 'none') { // A clear that neither succeeded nor was skipped leaves purchased // items in the badge. Nothing the shopper can act on, but a silent // gap here looks exactly like a working cart. console.warn('Cart not cleared after payment:', clearResult); } // `purchase` — the one event ad platforms optimize campaigns on. // Read the real order rather than the pre-payment cart so value, tax, // shipping and coupon match what was actually charged; `trackPurchase` // de-duplicates on the order id, so a refresh cannot double-count it. // // The same Order is what this page renders its line items from, so // keep it rather than discarding it after the conversion call. // `getOrderByCheckout` is typed `Promise` and REJECTS on 404 — // it never resolves to null — so the catch below is what degrades this // page to the order-number-only view instead of breaking it. try { const fetchedOrder = await client.getOrderByCheckout(checkoutId!); if (!alive) return; setOrder(fetchedOrder); trackPurchase(fetchedOrder); } catch (err) { // A conversion we failed to report must never break the page the // shopper is looking at — but it should be visible, because a // silent gap here looks identical to "no sales" in ad reporting. console.warn('Purchase conversion not reported:', err); } } } catch (err) { if (!alive) return; const message = err instanceof Error ? err.message : 'Failed to confirm order'; setError(message); } finally { if (alive) setLoading(false); } } void confirmPayment(); return () => { alive = false; }; }, [checkoutId, cartStore]); if (loading) { return (

{t('confirming')}

{t('confirmingHint')}

); } if (error) { return (

{t('errorTitle')}

{error}

{t('errorChargedHint')}

{t('returnHome')}
); } // Order was created successfully if (result?.status === 'succeeded') { const orderNumber = result.orderNumber; return (

{t('thankYou')}

{orderNumber && (

{t('orderNumber')} {orderNumber}

)}

{t('confirmationEmail')}

{/* What was actually bought. Renders nothing at all when the order fetch failed or came back with no lines, leaving the number-only view above intact. */} {result.orderId && ( )} {/* Renders no visible markup. Self-gates entirely on whether the merchant enabled Google Customer Reviews and this order has the data the survey needs — see the component's own doc comment. */}
{tc('continueShopping')} {t('viewOrders')}
); } // The payment did not go through (`failed`) or the shopper backed out (`canceled`). NO order // exists. The checkout is still valid, so the way forward is back to it (same `checkout_id`, // the cart was kept) to pay again. This must never fall through to the "payment received" // screen below: that one tells the shopper an order is on its way. if (result?.status === 'failed' || result?.status === 'canceled') { const canceled = result.status === 'canceled'; const checkoutHref = checkoutId && isValidCheckoutId(checkoutId) ? `/checkout?checkout_id=${encodeURIComponent(checkoutId)}` : '/checkout'; return (

{canceled ? t('paymentCanceledTitle') : t('paymentFailedTitle')}

{canceled ? t('paymentCanceledDesc') : t('paymentFailedDesc')}

{t('backToCheckout')} {t('viewCart')}
); } // `pending`: the order is not there yet (a held payment, or the webhook is still on its way). // Still show "payment received, being processed". Never a failure and never a new payment. return (

{t('paymentReceived')}

{t('orderProcessing')}

{tc('continueShopping')} {t('viewOrders')}
); } /** * Line items on the confirmation page. * * `OrderItem` is FLAT — `item.name`, `item.price`, `item.image` — unlike the * nested `CartItem` / `CheckoutLineItem` shapes used elsewhere in this * storefront. Do not copy a cart row renderer here; `item.product.name` does * not exist on an order. * * Auto-hides: returns null when the order fetch failed (`order === null`) or * the order carries no lines, so the number-only confirmation still renders. */ function ConfirmationLineItems({ order }: { order: Order | null }) { // Named `tch` rather than `t` on purpose: the other components in this file // bind `t` to the `orderConfirmation` namespace, and a same-named alias on a // different namespace is how a wrong-namespace key slips through review. const tch = useTranslations('checkout'); const ta = useTranslations('account'); const tc = useTranslations('common'); const currency = useCurrency(order?.currency); if (!order || !order.items || order.items.length === 0) return null; const totalAmount = order.totalAmount || order.total || '0'; return (

{tch('orderSummary')}

{order.items.map((item, index) => (
{item.image ? ( {item.name ) : null}

{item.name || ta('productFallback')}

{/* The product's brands as they were at the sale. Absent on old orders and on products without a brand, so nothing renders for those. */} {(orderLineBrands(item)?.length ?? 0) > 0 && (

{orderLineBrands(item)! .map((brand) => brand.name) .join(', ')}

)}

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

{formatPrice(parseFloat(item.price), { currency }) as string}
{/* What the buyer typed / uploaded / picked, with the merchant's own labels. Renders nothing when the line has none. */} {item.customizations && }
))}
{tc('total')} {formatPrice(parseFloat(totalAmount), { currency }) as string}
{/* What the card was actually charged, when that is not the order's own currency. A region that charges its currency (FX presentment) records the order in the store's base currency, so the total above can be $25.94 while the buyer paid €23.78. Shown only then, and only when no gift card is involved (that block below states the charged amount itself). */} {(!order.tenders || order.tenders.length === 0) && order.paymentAmount && order.paymentCurrency && order.paymentCurrency.toUpperCase() !== (order.currency || '').toUpperCase() && (
{tc('amountCharged')} { formatPrice(parseFloat(order.paymentAmount), { currency: order.paymentCurrency, }) as string }
)} {/* What actually paid. This is the first screen a customer sees after handing over money, and a total with no gift-card line tells them they paid an amount they did not. The total above is what the order was WORTH and stays unreduced — tax was calculated on it — so the cards sit below it, followed by what the card or wallet was really charged. */} {order.tenders && order.tenders.length > 0 && ( <> {order.tenders.map((tender) => (
{tender.giftCard?.codeLast4 ? `${tc('giftCard')} ····${tender.giftCard.codeLast4}` : tc('giftCard')} -{formatPrice(parseFloat(tender.amountBase), { currency }) as string}
))}
{tc('amountCharged')} { formatPrice( order.tenders.reduce( (due, tn) => due - parseFloat(tn.amountBase), parseFloat(totalAmount) ), { currency } ) as string }
)}
); } function ConfirmationDownloads({ orderId, checkoutId }: { orderId: string; checkoutId: string }) { const t = useTranslations('orderConfirmation'); const [downloads, setDownloads] = useState(null); useEffect(() => { let cancelled = false; async function fetchDownloads() { const client = getClient(); // Retry a few times — the worker may still be writing downloadMeta for (let attempt = 0; attempt < 3; attempt++) { try { const links = await client.getOrderDownloads(orderId, { checkoutId }); if (!cancelled && links.length > 0) { setDownloads(links); return; } } catch { // Not all orders have downloads } if (attempt < 2 && !cancelled) { await new Promise((r) => setTimeout(r, 1500)); } } } fetchDownloads(); return () => { cancelled = true; }; }, [orderId, checkoutId]); if (!downloads || downloads.length === 0) return null; return (

{t('yourDownloads')}

{downloads.map((link, idx) => (

{link.fileName}

{link.productName}

{t('download')}
))}
); } export default function OrderConfirmationPage() { return ( } > ); }