@fayz-ai/storefront 0.84.3 → 0.84.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/CheckoutPage-4MFKLBEI.js +12 -0
- package/dist/{CheckoutPage-G5NYJF3Z.js.map → CheckoutPage-4MFKLBEI.js.map} +1 -1
- package/dist/MyPurchasesPage-F25MIFXT.js +11 -0
- package/dist/{MyPurchasesPage-GOK2RO7K.js.map → MyPurchasesPage-F25MIFXT.js.map} +1 -1
- package/dist/OrderConfirmationPage-SOQDD767.js +10 -0
- package/dist/{OrderConfirmationPage-DGLW5W75.js.map → OrderConfirmationPage-SOQDD767.js.map} +1 -1
- package/dist/{chunk-P4RRFQQX.js → chunk-BR3XHNVM.js} +5 -5
- package/dist/{chunk-P4RRFQQX.js.map → chunk-BR3XHNVM.js.map} +1 -1
- package/dist/{chunk-RZWTEC6H.js → chunk-C4XATNI2.js} +3 -3
- package/dist/{chunk-RZWTEC6H.js.map → chunk-C4XATNI2.js.map} +1 -1
- package/dist/{chunk-45R7CIEA.js → chunk-CE4U65TZ.js} +4 -4
- package/dist/{chunk-45R7CIEA.js.map → chunk-CE4U65TZ.js.map} +1 -1
- package/dist/{chunk-2D5BEM43.js → chunk-EFHQ5MAJ.js} +3 -3
- package/dist/{chunk-2D5BEM43.js.map → chunk-EFHQ5MAJ.js.map} +1 -1
- package/dist/{chunk-UJ2TIM4V.js → chunk-ELW7QWDJ.js} +13 -12
- package/dist/chunk-ELW7QWDJ.js.map +1 -0
- package/dist/{chunk-F3U4KZC7.js → chunk-IUP5SDTX.js} +5 -5
- package/dist/{chunk-F3U4KZC7.js.map → chunk-IUP5SDTX.js.map} +1 -1
- package/dist/{chunk-ZSNKJGE5.js → chunk-NS6UPIJ3.js} +3 -3
- package/dist/{chunk-ZSNKJGE5.js.map → chunk-NS6UPIJ3.js.map} +1 -1
- package/dist/{chunk-FPFGRUCS.js → chunk-OOQRYH3N.js} +6 -6
- package/dist/{chunk-FPFGRUCS.js.map → chunk-OOQRYH3N.js.map} +1 -1
- package/dist/{chunk-GVZ2SAOI.js → chunk-PSDR5TZD.js} +3 -2
- package/dist/chunk-PSDR5TZD.js.map +1 -0
- package/dist/{chunk-PURHMU2W.js → chunk-RJUEUMR6.js} +4 -4
- package/dist/{chunk-PURHMU2W.js.map → chunk-RJUEUMR6.js.map} +1 -1
- package/dist/{chunk-BKO2AQ3Q.js → chunk-SLJ4BRXD.js} +3 -3
- package/dist/{chunk-BKO2AQ3Q.js.map → chunk-SLJ4BRXD.js.map} +1 -1
- package/dist/{chunk-YSQBZ3RM.js → chunk-YCAWAON6.js} +7 -7
- package/dist/{chunk-YSQBZ3RM.js.map → chunk-YCAWAON6.js.map} +1 -1
- package/dist/{chunk-554XAQWK.js → chunk-YDZU2SZL.js} +4 -4
- package/dist/{chunk-554XAQWK.js.map → chunk-YDZU2SZL.js.map} +1 -1
- package/dist/{chunk-WSHCQ3Y6.js → chunk-Z5JT7T4I.js} +8 -8
- package/dist/{chunk-WSHCQ3Y6.js.map → chunk-Z5JT7T4I.js.map} +1 -1
- package/dist/components/delivery/StoreCover.d.ts.map +1 -1
- package/dist/document/config.d.ts +8 -0
- package/dist/document/config.d.ts.map +1 -1
- package/dist/host.js +4 -4
- package/dist/index.js +22 -22
- package/dist/render.js +9 -9
- package/dist/tanstack.js +8 -8
- package/package.json +2 -2
- package/dist/CheckoutPage-G5NYJF3Z.js +0 -12
- package/dist/MyPurchasesPage-GOK2RO7K.js +0 -11
- package/dist/OrderConfirmationPage-DGLW5W75.js +0 -10
- package/dist/chunk-GVZ2SAOI.js.map +0 -1
- package/dist/chunk-UJ2TIM4V.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/errors.ts","../src/workflows/checkout.ts","../src/components/checkout/CheckoutSteps.tsx","../src/components/checkout/CardBrick.tsx","../src/components/checkout/CheckoutPayment.tsx","../src/hooks/use-known-customer.ts","../src/components/checkout/CheckoutField.tsx","../src/components/checkout/AddressForm.tsx","../src/components/checkout/ContactSummary.tsx","../src/lib/checkout-address.ts","../src/components/delivery/DeliverToPicker.tsx","../src/views/CheckoutPage.tsx"],"names":["jsx","jsxs","React","useState","useRef","getShopProvider","describeError","useEffect","Check","document","getCountrySchema","documentDigits","normalizePostalCode","Lock","CreditCard"],"mappings":";;;;;;;;;;;;;;;;AAOO,SAAS,aAAa,GAAA,EAAsB;AACjD,EAAA,IAAI,GAAA,YAAe,KAAA,EAAO,OAAO,GAAA,CAAI,OAAA;AACrC,EAAA,IAAI,OAAO,OAAO,GAAA,KAAQ,YAAY,OAAQ,GAAA,CAA8B,YAAY,QAAA,EAAU;AAChG,IAAA,OAAQ,GAAA,CAA4B,OAAA;AAAA,EACtC;AACA,EAAA,OAAO,EAAA;AACT;;;ACkDA,SAAS,mBAAA,CACP,SACA,eAAA,EACoB;AACpB,EAAA,IAAI,SAAS,KAAA,EAAO,IAAA,IAAQ,OAAO,OAAA,CAAQ,MAAM,IAAA,EAAK;AAGtD,EAAA,IAAI,iBAAiB,OAAO,MAAA;AAE5B,EAAA,IAAI,CAAC,SAAS,OAAO,MAAA;AACrB,EAAA,MAAM,QAAQ,CAAC,OAAA,CAAQ,MAAA,EAAQ,OAAA,CAAQ,MAAM,OAAA,CAAQ,GAAG,CAAA,CACrD,GAAA,CAAI,CAAC,IAAA,KAAS,IAAA,EAAM,MAAM,CAAA,CAC1B,OAAO,OAAO,CAAA;AAEjB,EAAA,OAAO,KAAA,CAAM,SAAS,CAAA,GAAI,CAAA,SAAA,EAAY,MAAM,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA,GAAK,MAAA;AAC7D;AAGA,SAAS,qBAAqB,GAAA,EAAuB;AACnD,EAAA,MAAM,OAAA,GAAU,YAAA,CAAa,GAAG,CAAA,CAAE,WAAA,EAAY;AAC9C,EAAA,OAAO,OAAA,CAAQ,QAAA,CAAS,yBAAyB,CAAA,IAC5C,OAAA,CAAQ,SAAS,wCAAw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4DAAA,EACb,QAAA,EAAA;AAAA,0BAAAD,GAAAA,CAAC,WAAA,EAAA,EAAY,SAAA,EAAU,sBAAA,EAAuB,CAAA;AAAA,UAC7C,EAAE,mBAAmB;AAAA,SAAA,EACxB,CAAA;AAAA,wBAKAA,GAAAA,CAAC,KAAA,EAAA,EAAI,SAAA,EAAU,sBACb,QAAA,kBAAAA,GAAAA,CAAC,IAAA,EAAA,EAAK,IAAA,EAAK,UAAA,EAAW,IAAA,EAAK,WAAA,EAAY,OAAA,EAAS,qBAAqB,CAAA,EACvE;AAAA,OAAA,EACF,CAAA;AAAA,sBAQAC,IAAAA,CAAC,QAAA,EAAA,EAAO,SAAA,EAAU,gFAAA,EAChB,QAAA,EAAA;AAAA,wBAAAD,GAAAA,CAAC,QAAK,EAAA,EAAG,UAAA,EAAW,WAAU,uBAAA,EAAyB,QAAA,EAAA,CAAA,CAAE,eAAe,CAAA,EAAE,CAAA;AAAA,wBAC1EA,IAAC,IAAA,EAAA,EAAK,EAAA,EAAG,UAAS,SAAA,EAAU,uBAAA,EAAyB,QAAA,EAAA,CAAA,CAAE,aAAa,CAAA,EAAE,CAAA;AAAA,wBACtEA,IAAC,IAAA,EAAA,EAAK,EAAA,EAAG,YAAW,SAAA,EAAU,uBAAA,EAAyB,QAAA,EAAA,CAAA,CAAE,eAAe,CAAA,EAAE;AAAA,OAAA,EAC5E;AAAA,KAAA,EACF;AAAA,GAAA,EACF,CAAA;AAEJ","file":"chunk-YSQBZ3RM.js","sourcesContent":["/**\n * The message inside a thrown value.\n *\n * `err instanceof Error` is not enough here: the Supabase provider rethrows\n * PostgrestError, a plain object with `message`, so every `instanceof` check in\n * the storefront fell through to a generic sentence and lost what the server said.\n */\nexport function errorMessage(err: unknown): string {\n if (err instanceof Error) return err.message\n if (err && typeof err === 'object' && typeof (err as { message?: unknown }).message === 'string') {\n return (err as { message: string }).message\n }\n return ''\n}\n","import { getShopProvider } from '@fayz-ai/shop/runtime'\nimport type { Order, ShippingAddressInput, PaymentMethodKind, FulfillmentType } from '@fayz-ai/shop/types'\nimport { establishCustomerSession } from '../data/auth'\nimport { collectOrderMetadata, runBeforePlaceOrderValve } from '../extend/extension-points'\nimport type { ResolvedStorefrontConfig } from '../document/config'\nimport type { CartState } from '../stores/cart.store'\nimport { selectShipping } from '../stores/cart.store'\nimport type { SessionState } from '../stores/session.store'\nimport { rememberLocalOrder } from '../data/local-orders'\nimport { errorMessage } from '../lib/errors'\n\nexport interface StorefrontCheckoutCustomer {\n email: string\n name: string\n}\n\nexport interface StorefrontCheckoutAddress {\n street?: string\n city?: string\n zip?: string\n notes?: string\n}\n\nexport interface PlaceStorefrontOrderInput {\n config: ResolvedStorefrontConfig\n cart: Pick<CartState, 'lines' | 'discountCode' | 'discountPercent'>\n & Partial<Pick<CartState, 'discountFreeShipping'>>\n session?: Pick<SessionState, 'customerId' | 'email'>\n customer: StorefrontCheckoutCustomer\n address?: StorefrontCheckoutAddress\n /** Structured address; without it the order keeps only the free-text note. */\n shippingAddress?: ShippingAddressInput\n paymentMethod?: PaymentMethodKind\n markPaid?: boolean\n /**\n * Entrega ou retirada (0094). Ausente lê como entrega — que é o que todo\n * checkout anterior a esta migration fazia.\n *\n * Na RETIRADA quem chama manda o endereço da PRÓPRIA LOJA em\n * `shippingAddress`. Não é contorno: `shop_place_order` exige CEP quando a\n * loja tem zonas, e essa checagem roda antes de qualquer trigger de linha —\n * então o pedido precisa de um endereço válido, e o endereço válido de uma\n * retirada é o balcão. O trigger reconhece o modo e zera o frete.\n */\n fulfillmentType?: FulfillmentType\n /** Início da janela agendada (ISO). O servidor recusa fora de janela real. */\n scheduledFor?: string\n}\n\nexport interface PlaceStorefrontOrderResult {\n order: Order\n customerId: string\n}\n\n/**\n * `notes` is the buyer's free-text message to the store — nothing else.\n *\n * It used to double as the delivery address, from back when the order had\n * nowhere structured to put one. Now that the address is a real snapshot plus a\n * row in the address book, repeating it here only creates a second copy that\n * can disagree with the first (it did: it dropped number and district). When a\n * structured address is present, notes carries only what the customer wrote.\n */\nfunction formatDeliveryNotes(\n address: StorefrontCheckoutAddress | undefined,\n shippingAddress?: ShippingAddressInput,\n): string | undefined {\n if (address?.notes?.trim()) return address.notes.trim()\n\n // Structured address present → the order already knows where to deliver.\n if (shippingAddress) return undefined\n\n if (!address) return undefined\n const parts = [address.street, address.city, address.zip]\n .map((part) => part?.trim())\n .filter(Boolean)\n\n return parts.length > 0 ? `Entrega: ${parts.join(', ')}` : undefined\n}\n\n/** shop_place_order's three refusals of a customer id we sent (all 42501). */\nfunction isStaleCustomerError(err: unknown): boolean {\n const message = errorMessage(err).toLowerCase()\n return message.includes('customer email mismatch')\n || message.includes('customer does not belong to this store')\n || message.includes('customer belongs to another account')\n}\n\n/**\n * Storefront checkout primitive for custom/generated checkout screens.\n * It owns the order payload math and customer-session handshake so app-owned\n * routes can customize UX without copying provider/business logic.\n */\nexport async function placeStorefrontOrder({\n config,\n cart,\n session,\n customer,\n address,\n shippingAddress,\n fulfillmentType,\n scheduledFor,\n paymentMethod,\n markPaid = false,\n}: PlaceStorefrontOrderInput): Promise<PlaceStorefrontOrderResult> {\n const email = customer.email.trim().toLowerCase()\n const name = customer.name.trim()\n const provider = getShopProvider()\n\n let customerId = session?.customerId ?? null\n // Normalized on both sides: the session email is stored as the buyer typed it,\n // so \"Vini@Gmail.com\" vs \"vini@gmail.com\" used to re-resolve on every order.\n if (!customerId || session?.email?.trim().toLowerCase() !== email) {\n const established = await establishCustomerSession(email, { name })\n customerId = established.customerId\n }\n\n const notes = formatDeliveryNotes(address, shippingAddress)\n const items = cart.lines.map((line) => ({\n productId: line.productId,\n // The variant the shopper picked (spine M5): the server prices the line\n // from it and decrements ITS stock, so two sizes never share a counter.\n variantId: line.variantId || undefined,\n quantity: line.quantity,\n optionsLabel: line.optionsLabel || undefined,\n // A observação da linha (0094). Vai por item porque é por item: duas\n // unidades do mesmo prato com pedidos diferentes são duas linhas.\n notes: line.notes || undefined,\n }))\n // Retirada não paga frete. O cliente já não é confiado para isso — o servidor\n // zera de qualquer jeito (0094) — mas mandar o número certo evita que a tela\n // mostre um total e o pedido nasça com outro.\n const shippingTotal = fulfillmentType === 'pickup' ? 0 : selectShipping(cart, config)\n\n // THE escape valve (spine I4, M7): exactly one registrant may replace the\n // entire default order creation — external OMS, quote-first flows. Null (or\n // no registrant, the overwhelmingly common case) takes the default path.\n const replaced = await runBeforePlaceOrderValve<Order>({\n items,\n customer: { name, email },\n currency: config.currency,\n discountCode: cart.discountCode ?? undefined,\n shippingTotal,\n notes,\n customerId: customerId ?? undefined,\n })\n if (replaced) return { order: replaced, customerId: customerId ?? replaced.customerId ?? '' }\n\n // Extension contributions (spine M7's order.metadata point), namespaced by\n // handler id so two extensions can never collide on a key.\n const contributed = await collectOrderMetadata({\n items: cart.lines.map((line) => ({\n productId: line.productId,\n quantity: line.quantity,\n unitPrice: line.unitPrice,\n })),\n subtotal: cart.lines.reduce((sum, line) => sum + line.unitPrice * line.quantity, 0),\n customerEmail: email,\n })\n // The market the buyer shopped in (0116): shop_place_order prices, ships and\n // charges in it. Absent = the default market, as every store before markets.\n const metadata = config.market\n ? { ...(contributed ?? {}), market: config.market.code }\n : contributed\n\n // Trusted placement: send only product ids + quantities. The provider\n // (shop_place_order RPC on Supabase, in-memory provider in mock) re-reads\n // prices, validates the discount, and decrements inventory server-side.\n const place = (withCustomerId: string | undefined) => provider.placeOrder({\n customerId: withCustomerId,\n customer: { name, email },\n currency: config.currency,\n notes,\n discountCode: cart.discountCode ?? undefined,\n shippingTotal,\n // Structured address + method are what populate public.addresses and the\n // transactions ledger. `notes` stays for backwards compatibility with\n // checkouts that have not been updated yet.\n shippingAddress,\n paymentMethod,\n metadata,\n fulfillmentType,\n scheduledFor,\n items,\n })\n\n let order: Order\n try {\n order = await place(customerId ?? undefined)\n } catch (err) {\n // The customer id lives in localStorage, shared by every store on the\n // origin and never re-verified, so it can point at a row that is not this\n // buyer's (another tenant, another account, an email edited since). The\n // server is right to refuse it — but the id is ours, not a credential, so\n // dropping it and letting the RPC resolve the customer from the typed email\n // is the fix. Without this the buyer is stuck on a raw 42501 forever: the\n // stale id survives every reload.\n if (!customerId || !isStaleCustomerError(err)) throw err\n customerId = null\n order = await place(undefined)\n }\n\n if (markPaid) {\n // Prefer the RPC seam — anon storefronts have no UPDATE grant on the\n // orders table, so a direct updateOrder 401s on pool backends.\n if (provider.confirmPayment) await provider.confirmPayment(order.id)\n else await provider.updateOrder(order.id, { financialStatus: 'paid' })\n }\n\n // Guardado localmente para que \"Minhas compras\" funcione sem que o servidor\n // precise responder \"o que é deste cliente?\" — ver data/local-orders.ts.\n rememberLocalOrder(order.id)\n\n return { order, customerId: customerId ?? order.customerId ?? '' }\n}\n","import React from 'react'\nimport { Check } from 'lucide-react'\nimport { TID } from '../../lib/testids'\nimport { useT } from '../../locales'\nimport type { MessageKey } from '../../locales/messages'\n\n// ---------------------------------------------------------------------------\n// Onde a pessoa está, e para onde ela pode voltar.\n//\n// Antes isto era três palavras soltas (\"Informações / Entrega / Pagamento\") que\n// nunca mudavam: um enfeite que dizia sempre a mesma coisa enquanto o formulário\n// inteiro estava numa página só. Agora é o mapa do que já ficou pronto.\n//\n// Passo concluído é CLICÁVEL e o que vem à frente não é — voltar para corrigir o\n// endereço é normal; pular para o pagamento sem endereço não existe.\n// ---------------------------------------------------------------------------\n\nexport type CheckoutStep = 1 | 2 | 3 | 4\n\nconst LABELS: Record<CheckoutStep, MessageKey> = {\n 1: 'checkout.steps.1',\n 2: 'checkout.steps.2',\n 3: 'checkout.steps.3',\n 4: 'checkout.steps.4',\n}\n\nexport interface CheckoutStepsProps {\n current: CheckoutStep\n /** Ausente no passo 4: depois de pago não há para onde voltar. */\n onGoBackTo?: (step: CheckoutStep) => void\n /**\n * Passos que este pedido não tem. Na RETIRADA o passo 2 (Entrega) não existe:\n * o endereço é o balcão (0094).\n *\n * Some da régua em vez de ficar cinza para sempre: um passo que nunca vai\n * acontecer, desenhado como \"pendente\", promete uma etapa a mais do que o\n * pedido tem — e a régua existe justamente para dizer quanto falta.\n */\n omit?: readonly CheckoutStep[]\n}\n\nexport function CheckoutSteps({ current, onGoBackTo, omit }: CheckoutStepsProps) {\n const t = useT()\n const steps: CheckoutStep[] = ([1, 2, 3, 4] as CheckoutStep[])\n .filter((s) => !omit?.includes(s))\n\n return (\n <nav data-testid={TID.checkoutSteps} aria-label={t('checkout.steps.label')} className=\"mb-8\">\n <ol className=\"flex items-center gap-1.5 sm:gap-2\">\n {steps.map((step, index) => {\n const done = step < current\n const active = step === current\n const canGoBack = done && !!onGoBackTo\n const Tag = canGoBack ? 'button' : 'div'\n\n return (\n // `flex-1` só em quem TEM traço. O último passo não tem, e com\n // flex-1 ele reservava uma fatia inteira para desenhar apenas a\n // bolinha — que então parava no começo da fatia em vez do fim, e a\n // régua saía torta. Sem flex-1, o traço absorve a sobra e as\n // bolinhas encostam nas pontas.\n <li\n key={step}\n className={`flex min-w-0 items-center gap-1.5 sm:gap-2 ${\n index < steps.length - 1 ? 'flex-1' : ''\n }`}\n >\n <Tag\n {...(canGoBack\n ? { type: 'button' as const, onClick: () => onGoBackTo(step) }\n : {})}\n data-testid={TID.checkoutStep(step)}\n data-state={done ? 'done' : active ? 'current' : 'pending'}\n aria-current={active ? 'step' : undefined}\n className={[\n 'flex min-w-0 items-center gap-2 rounded-lg px-2 py-1.5 text-left transition',\n canGoBack ? 'hover:bg-muted' : '',\n active ? 'text-foreground' : done ? 'text-foreground' : 'text-muted-foreground',\n ].join(' ')}\n >\n <span\n className={[\n 'grid h-7 w-7 shrink-0 place-items-center rounded-full border text-xs font-semibold',\n done\n ? 'border-primary bg-primary text-primary-foreground'\n : active\n // Contornado, não preenchido: em andamento não é concluído.\n // Foi o mesmo engano na linha do tempo do pedido, onde um\n // pagamento pendente exibia um tique.\n ? 'border-primary bg-background text-primary'\n : 'border-muted-foreground/30 bg-background',\n ].join(' ')}\n >\n {/* A POSIÇÃO, não o id interno: com a Entrega fora (retirada),\n numerar pelo id mostraria \"1, 3, 4\" a quem só tem três\n passos — a régua contaria uma etapa que não existe. */}\n {done ? <Check className=\"h-3.5 w-3.5\" /> : index + 1}\n </span>\n <span className={`hidden truncate text-sm sm:inline ${active ? 'font-semibold' : ''}`}>\n {t(LABELS[step])}\n </span>\n </Tag>\n {index < steps.length - 1 && (\n <span aria-hidden className={`h-px flex-1 ${done ? 'bg-primary' : 'bg-border'}`} />\n )}\n </li>\n )\n })}\n </ol>\n {/* No celular o rótulo do passo some para o traço caber; sem esta linha a\n pessoa vê números sem saber o que eles são. */}\n <p className=\"mt-2 text-sm font-semibold sm:hidden\">\n {/* A posição, igual à bolinha. Numerar pelo id faria a legenda dizer\n \"3.\" embaixo de uma bolinha marcada \"2\" quando a Entrega está fora. */}\n {steps.indexOf(current) + 1}. {t(LABELS[current])}\n </p>\n </nav>\n )\n}\n","import React, { useEffect, useRef, useState } from 'react'\nimport { Skeleton, SkeletonGroup } from '../Skeleton'\nimport { describeError } from '@fayz-ai/core'\n\n/**\n * Mercado Pago's Card Payment Brick, mounted in the store's own checkout.\n *\n * WHY THIS COMPONENT EXISTS AT ALL\n *\n * Every other acquirer in this repo sends a card buyer to a hosted page, and not\n * for taste: AbacatePay's and Vindi's transparent calls want the card number (or\n * the CVV) inside a request the edge function makes, which would put the pool in\n * PCI scope. Mercado Pago tokenises HERE — the fields below live in their\n * iframes, not in this DOM — so the store never touches a card number and the\n * buyer never leaves. The only thing this component hands upward is a\n * single-use token.\n *\n * So the guarantee is structural, not a promise: there is no state in this file\n * that could hold a PAN, because the inputs are not ours to read.\n */\n\n/** The slice of their SDK this file uses. Declared rather than `any`, so a\n * change in their shape is a type error here and not a runtime one. */\ninterface BricksBuilder {\n create(\n brick: 'cardPayment',\n containerId: string,\n settings: Record<string, unknown>,\n ): Promise<{ unmount: () => void }>\n}\ninterface MercadoPagoSdk {\n bricks(): BricksBuilder\n}\ndeclare global {\n interface Window {\n MercadoPago?: new (publicKey: string, options?: { locale?: string }) => MercadoPagoSdk\n }\n}\n\nconst SDK_URL = 'https://sdk.mercadopago.com/js/v2'\nconst CONTAINER_ID = 'fayz-mp-card-brick'\n\n/**\n * Their device-fingerprint script, and the global it defines.\n *\n * Mercado Pago's first recommendation for improving approval rates: load this\n * on the checkout page, and send the resulting `MP_DEVICE_SESSION_ID` as the\n * `X-meli-session-id` header when the charge is created. Without it a legitimate\n * buyer looks anonymous to their anti-fraud and gets declined more often — a\n * cost that never shows up as an error, only as a lower approval rate.\n */\nconst DEVICE_SCRIPT_URL = 'https://www.mercadopago.com/v2/security.js'\nconst DEVICE_VIEW = 'checkout'\n\ndeclare global {\n // eslint-disable-next-line no-var\n var MP_DEVICE_SESSION_ID: string | undefined\n}\n\n/** Load the security script once; the global appears shortly after it runs. */\nfunction loadDeviceScript(): void {\n if (typeof document === 'undefined') return\n if (document.querySelector(`script[src=\"${DEVICE_SCRIPT_URL}\"]`)) return\n const script = document.createElement('script')\n script.src = DEVICE_SCRIPT_URL\n script.setAttribute('view', DEVICE_VIEW)\n script.async = true\n document.body.appendChild(script)\n}\n\n/** Whatever the script has produced by now — never a fabricated value. */\nexport function deviceSessionId(): string | null {\n if (typeof window === 'undefined') return null\n const id = window.MP_DEVICE_SESSION_ID\n return typeof id === 'string' && id.trim() ? id.trim() : null\n}\n\n/**\n * Load their SDK once per page, and let every caller await the same load.\n *\n * A second <script> would re-register the global and re-mount the bricks\n * builder underneath a Brick that is already alive; the promise is the lock.\n */\nlet sdkPromise: Promise<void> | null = null\nfunction loadSdk(): Promise<void> {\n if (typeof window === 'undefined') return Promise.reject(new Error('no window'))\n if (window.MercadoPago) return Promise.resolve()\n if (sdkPromise) return sdkPromise\n\n sdkPromise = new Promise<void>((resolve, reject) => {\n const existing = document.querySelector<HTMLScriptElement>(`script[src=\"${SDK_URL}\"]`)\n const script = existing ?? document.createElement('script')\n script.src = SDK_URL\n script.async = true\n script.addEventListener('load', () => resolve())\n script.addEventListener('error', () => {\n // Reset, so a buyer who retries on a flaky connection gets a real second\n // attempt rather than the rejected promise from the first.\n sdkPromise = null\n reject(new Error('Não conseguimos carregar o pagamento com cartão.'))\n })\n if (!existing) document.body.appendChild(script)\n })\n return sdkPromise\n}\n\nexport interface CardBrickResult {\n token: string\n paymentMethodId: string | null\n issuerId: string | null\n installments: number\n /** What the Brick collected, which may differ from the checkout's own copy. */\n email: string | null\n document: { type: string; number: string } | null\n}\n\nexport interface CardBrickProps {\n publicKey: string\n /** In reais, as their SDK wants it — it prices the installment options. */\n amount: number\n /** Prefilled so the buyer does not retype what the checkout already asked. */\n email?: string | null\n /** Called with the token. Rejecting keeps the Brick mounted and its form filled. */\n onSubmit: (result: CardBrickResult) => Promise<void>\n onError?: (message: string) => void\n}\n\nexport function CardBrick({ publicKey, amount, email, onSubmit, onError }: CardBrickProps) {\n const [ready, setReady] = useState(false)\n const [failed, setFailed] = useState<string | null>(null)\n // The Brick is mounted ONCE. React 18 runs effects twice in development, and\n // a second create() on the same container leaves two forms stacked.\n const mounted = useRef(false)\n const controller = useRef<{ unmount: () => void } | null>(null)\n // The callback the Brick captured at create() time would otherwise be the\n // first render's — a stale closure over an old cart total.\n const submitRef = useRef(onSubmit)\n submitRef.current = onSubmit\n\n useEffect(() => {\n if (mounted.current) return\n mounted.current = true\n let cancelled = false\n\n // Started before the SDK, because it needs a moment to fingerprint and the\n // value is only read when the buyer submits.\n loadDeviceScript()\n\n void (async () => {\n try {\n await loadSdk()\n if (cancelled || !window.MercadoPago) return\n const mp = new window.MercadoPago(publicKey, { locale: 'pt-BR' })\n const builder = mp.bricks()\n\n controller.current = await builder.create('cardPayment', CONTAINER_ID, {\n initialization: {\n amount,\n ...(email ? { payer: { email } } : {}),\n },\n customization: {\n visual: { style: { theme: 'default' } },\n paymentMethods: { maxInstallments: 12 },\n },\n callbacks: {\n onReady: () => { if (!cancelled) setReady(true) },\n onSubmit: (formData: Record<string, any>) =>\n // Their contract: resolve when the payment is handled, reject to\n // keep the form up. Rejecting is what lets a declined card be\n // corrected in place instead of re-typed from scratch.\n submitRef.current({\n token: String(formData?.token ?? ''),\n paymentMethodId: formData?.payment_method_id ?? null,\n issuerId: formData?.issuer_id == null ? null : String(formData.issuer_id),\n installments: Number(formData?.installments) || 1,\n email: formData?.payer?.email ?? null,\n document: formData?.payer?.identification?.number\n ? {\n type: String(formData.payer.identification.type ?? 'CPF'),\n number: String(formData.payer.identification.number),\n }\n : null,\n }),\n onError: (brickError: { message?: string }) => {\n // Their validation errors are for the buyer and already shown in\n // the form; this is for the ones that stop it working at all.\n const message = brickError?.message ?? 'Não conseguimos carregar o formulário do cartão.'\n if (!cancelled) onError?.(message)\n },\n },\n })\n } catch (err) {\n if (cancelled) return\n const message = describeError(err, 'Não conseguimos carregar o pagamento com cartão.')\n setFailed(message)\n onError?.(message)\n }\n })()\n\n return () => {\n cancelled = true\n try { controller.current?.unmount() } catch { /* already gone with the DOM */ }\n controller.current = null\n mounted.current = false\n }\n // Deliberately once: their Brick prices installments from the amount it was\n // created with, and a cart that changed has already sent the buyer back a\n // step. Re-creating under a filled-in form would clear the card fields.\n }, []) // eslint-disable-line react-hooks/exhaustive-deps\n\n if (failed) {\n return (\n <p className=\"rounded-lg border border-destructive/40 bg-destructive/5 p-4 text-sm text-destructive\">\n {failed}\n </p>\n )\n }\n\n return (\n <div className=\"space-y-3\">\n {!ready && (\n <SkeletonGroup label=\"Carregando o formulário do cartão\" className=\"space-y-3\">\n <Skeleton className=\"h-11 w-full rounded-lg\" />\n <div className=\"grid grid-cols-2 gap-3\">\n <Skeleton className=\"h-11 w-full rounded-lg\" />\n <Skeleton className=\"h-11 w-full rounded-lg\" />\n </div>\n <Skeleton className=\"h-11 w-full rounded-lg\" />\n </SkeletonGroup>\n )}\n {/* Their iframes mount in here. Kept in the tree while loading so the\n container exists when create() runs — hidden, not unmounted. */}\n <div id={CONTAINER_ID} className={ready ? '' : 'hidden'} />\n </div>\n )\n}\n","import React, { useCallback, useEffect, useRef, useState } from 'react'\nimport { Check, Copy, CreditCard, Lock, QrCode } from 'lucide-react'\nimport { getShopProvider } from '@fayz-ai/shop/runtime'\nimport { gatewayLabel } from '@fayz-ai/shop'\nimport { CardBrick, deviceSessionId, type CardBrickResult } from './CardBrick'\nimport type { CheckoutSessionInput, PaymentCharge } from '@fayz-ai/shop/types'\nimport { TID } from '../../lib/testids'\nimport { toast } from '../../stores/toast.store'\nimport { PulseDot, Skeleton, SkeletonGroup } from '../Skeleton'\nimport { describeError } from '@fayz-ai/core'\n\n// ---------------------------------------------------------------------------\n// O passo 3, e a razão de ele existir.\n//\n// O pedido NÃO existe enquanto esta tela estiver aberta. O que existe é uma\n// sessão de checkout: o servidor congelou o carrinho com os preços que ele mesmo\n// recalculou e abriu a cobrança. Quando o provedor diz que o dinheiro entrou, é\n// o SERVIDOR quem cria o pedido a partir desse congelado — e só então a tela\n// avança.\n//\n// Isso é o oposto do que a loja fazia: criar o pedido, comemorar com confete, e\n// esperar que alguém pagasse depois.\n// ---------------------------------------------------------------------------\n\n/** Curto o bastante para parecer vivo, longo o bastante para não brigar com a\n * rede nem com o limite do provedor. */\nconst POLL_MS = 3_000\n\n/**\n * O que sobrevive à ida ao adquirente.\n *\n * A URL de volta carrega o id da sessão — é ela que o servidor consulta —, mas\n * não o adquirente, e a consulta tem que bater na função DELE. O adquirente é\n * um detalhe da loja, não do comprador, então fica aqui e não na barra de\n * endereço. `sessionStorage` porque isto vale para esta aba e esta compra: uma\n * sessão vazada para outra guia seria a tela consultando a cobrança errada.\n */\nconst RESUME_KEY = 'fz.checkout.resume'\n\n/**\n * How much longer this charge is good for.\n *\n * The charge really does expire: the open request sends `expiresIn` and the\n * provider answers with an absolute `expiresAt`, which is what gets stored — the\n * clock that counts is theirs, not ours.\n *\n * It exists because the code is now STABLE. It used to change on every return to\n * this screen, and that change was itself the signal that the old one was no\n * longer good; now it stays, and without a countdown nothing separates a live\n * code from one that died while the tab sat open. Copying a dead code pays\n * nobody.\n *\n * Returns null when no deadline is known — then nothing is promised.\n */\nfunction useExpiry(expiresAt: string | null | undefined): { secondsLeft: number | null; expired: boolean } {\n const target = React.useMemo(() => {\n if (!expiresAt) return null\n const t = new Date(expiresAt).getTime()\n return Number.isFinite(t) ? t : null\n }, [expiresAt])\n\n const [now, setNow] = React.useState(() => Date.now())\n React.useEffect(() => {\n if (target === null) return\n const id = setInterval(() => setNow(Date.now()), 1000)\n return () => clearInterval(id)\n }, [target])\n\n if (target === null) return { secondsLeft: null, expired: false }\n const secondsLeft = Math.max(0, Math.round((target - now) / 1000))\n return { secondsLeft, expired: secondsLeft === 0 }\n}\n\n/** mm:ss, para um prazo que o comprador lê de relance. */\nfunction formatCountdown(seconds: number): string {\n const m = Math.floor(seconds / 60)\n const s = seconds % 60\n return `${m}:${String(s).padStart(2, '0')}`\n}\n\n/** True when the text reached the clipboard, by whichever route works here. */\nasync function copyText(text: string): Promise<boolean> {\n try {\n if (navigator.clipboard?.writeText) {\n await navigator.clipboard.writeText(text)\n return true\n }\n } catch {\n // Falls through: a rejected promise here (permission, insecure origin) is\n // not a reason to give up while the older API is still available.\n }\n try {\n const area = document.createElement('textarea')\n area.value = text\n // Off-screen rather than hidden: `display:none` is not selectable, and the\n // selection is what execCommand copies.\n area.setAttribute('readonly', '')\n area.style.position = 'fixed'\n area.style.top = '-1000px'\n area.style.opacity = '0'\n document.body.appendChild(area)\n area.select()\n area.setSelectionRange(0, text.length)\n const ok = document.execCommand('copy')\n document.body.removeChild(area)\n return ok\n } catch {\n return false\n }\n}\n\nfunction rememberSession(sessionId: string, provider: string | null) {\n try {\n sessionStorage.setItem(RESUME_KEY, JSON.stringify({ sessionId, provider }))\n } catch {\n // Sem sessionStorage a volta ainda funciona: o id vem na URL e a consulta\n // cai no adquirente padrão. Perder isto atrasa uma compra, não a perde.\n }\n}\n\n/** O adquirente guardado para ESTA sessão, se for a mesma que voltou. */\nexport function recallSessionProvider(sessionId: string): string | null {\n try {\n const raw = JSON.parse(sessionStorage.getItem(RESUME_KEY) ?? 'null')\n return raw?.sessionId === sessionId ? (raw.provider ?? null) : null\n } catch {\n return null\n }\n}\n\nexport interface CheckoutPaymentProps {\n input: CheckoutSessionInput\n /** Chamado uma vez, com o pedido que o servidor criou. */\n onPaid: (orderId: string) => void\n onBack: () => void\n money: (value: number) => string\n /**\n * Uma sessão que JÁ existe, para retomar em vez de abrir outra.\n *\n * É o comprador voltando da página do adquirente depois de pagar com cartão:\n * a página recarregou do zero, o formulário e o passo se perderam, e a única\n * coisa que sobrevive é o id que veio na URL. Com ele a tela não abre cobrança\n * nenhuma — só pergunta se o dinheiro entrou.\n */\n resume?: { sessionId: string; provider?: string | null; chargeToken?: string | null } | null\n /**\n * A loja não tem adquirente — não é um erro do comprador, e ele não pode\n * fazer nada a respeito. Quem sabe disso é o servidor, então em vez de pintar\n * um erro na tela avisamos o checkout para oferecer o pedido sem cobrança.\n */\n onUnavailable?: () => void\n /**\n * The cart total as the page already shows it.\n *\n * Only an in-store card form needs it: that mounts before any charge exists,\n * and the acquirer's SDK prices installments from the amount it was created\n * with. Every other flow learns the total from the opened session, which is\n * the figure the server will actually charge.\n */\n amount?: number\n}\n\ntype Phase = 'opening' | 'card' | 'redirect' | 'waiting' | 'settling' | 'error'\n\nexport function CheckoutPayment({ input, onPaid, onBack, money, onUnavailable, resume, amount }: CheckoutPaymentProps) {\n const [phase, setPhase] = useState<Phase>('opening')\n const [charge, setCharge] = useState<PaymentCharge | null>(null)\n const expiry = useExpiry(charge?.expiresAt)\n const [total, setTotal] = useState<number | null>(null)\n const [redirectUrl, setRedirectUrl] = useState<string | null>(null)\n /** The acquirer's browser key, for a card typed in the store. */\n const [brickKey, setBrickKey] = useState<string | null>(null)\n const [sessionId, setSessionId] = useState<string | null>(resume?.sessionId ?? null)\n /** Quem abriu a cobrança. A consulta tem que bater na função DESTE gateway —\n * reler os ajustes agora perguntaria ao adquirente novo por uma transação\n * que está no antigo. */\n const [provider, setProvider] = useState<string | null>(resume?.provider ?? null)\n const [error, setError] = useState<string | null>(null)\n const [copied, setCopied] = useState(false)\n /** \"Já paguei\" em andamento — a consulta que a pessoa pediu, não a do relógio. */\n const [checking, setChecking] = useState(false)\n const settled = useRef(false)\n // A sessão é aberta UMA vez. Sem esta trava, qualquer re-render com um objeto\n // de entrada novo abriria uma segunda cobrança para o mesmo carrinho.\n const opened = useRef(false)\n\n const open = useCallback(async () => {\n const shop = getShopProvider()\n if (!shop.openCheckoutSession) {\n setError('Esta loja ainda não recebe pagamento online.')\n setPhase('error')\n return\n }\n setPhase('opening')\n setError(null)\n try {\n // CARD TYPED IN THE STORE, where the acquirer supports it.\n //\n // Mercado Pago tokenises in the browser, so there is nothing to open until\n // the buyer has filled the card in: the charge is created FROM the token,\n // not before it. Asking for the key is how we learn whether this acquirer\n // works that way — a null answer means it does not, and the flow below is\n // the redirect or QR every other provider uses.\n if (input.paymentMethod === 'credit_card' && shop.paymentPublicKey) {\n const providerSlug = input.provider ?? null\n const publicKey = providerSlug ? await shop.paymentPublicKey(providerSlug) : null\n if (publicKey) {\n setProvider(providerSlug)\n setBrickKey(publicKey)\n setPhase('card')\n return\n }\n }\n\n const session = await shop.openCheckoutSession({\n ...input,\n // Para onde o adquirente devolve o comprador. É esta página, com o id da\n // sessão pendurado: quem volta volta em página nova, sem estado nenhum.\n returnUrl: typeof window === 'undefined' ? null : window.location.href.split('?')[0],\n })\n setSessionId(session.sessionId)\n setProvider(session.provider ?? input.provider ?? null)\n setTotal(session.total)\n setCharge(session.charge)\n\n // PAID OFF-SITE, and the test is whether there is anything to draw HERE.\n //\n // The condition used to be `session.paymentUrl` alone, which was true of\n // more charges than it should have been: Vindi answers a Pix with a QR\n // code AND a `url_payment`, the latter being a page for a merchant to send\n // someone, not a place to push the buyer. So a Pix that had a perfectly\n // good code to show redirected off the store instead — and Yapay's page\n // then bounces on again, landing the buyer on a bare SVG of the QR with no\n // way back and no session.\n //\n // A charge with an inline payload is drawn; only a charge with nothing to\n // draw sends the person away. The session is remembered because coming\n // back is a fresh load and React does not survive it.\n if (session.paymentUrl && !session.charge) {\n // The buyer PRESSES the button; the page does not move under them.\n //\n // Leaving on load meant the store vanished mid-checkout with no warning\n // and no way back, and whatever the acquirer's page says at the top is\n // the first hint of where they are. A named button turns the same\n // journey into something they chose, which is also what makes an\n // unfamiliar domain in the address bar read as expected rather than as a\n // hijack. The session is remembered at the click, because the return\n // trip is a fresh load and React does not survive it.\n setRedirectUrl(session.paymentUrl)\n setPhase('redirect')\n return\n }\n\n setPhase(session.charge ? 'waiting' : 'error')\n if (!session.charge) setError('Não conseguimos abrir a cobrança agora.')\n } catch (err) {\n // 404 aqui é \"esta loja não cobra online\", não uma falha da cobrança.\n // 409 method_unavailable é \"esta loja não aceita ESTA forma\" — a mesma\n // saída, porque o desfecho para o comprador é o mesmo: pedido sem\n // cobrança online, como sempre foi para quem escolhia maquininha.\n const status = (err as { status?: number })?.status\n const code = (err as { code?: string })?.code\n if (status === 404 || code === 'method_unavailable') {\n onUnavailable?.()\n return\n }\n setError(describeError(err, 'Não conseguimos abrir a cobrança agora.'))\n setPhase('error')\n }\n }, [input, onUnavailable])\n\n useEffect(() => {\n if (opened.current) return\n opened.current = true\n // Retomar NÃO é abrir: a cobrança dessa sessão já existe, e abrir outra aqui\n // seria uma segunda cobrança para quem acabou de pagar a primeira.\n if (resume?.sessionId) {\n setPhase('waiting')\n return\n }\n void open()\n }, [open, resume?.sessionId])\n\n /**\n * Pergunta ao servidor se o dinheiro entrou.\n *\n * A MESMA consulta serve ao relógio e ao botão \"Já paguei\" — duas portas para\n * a única pergunta que importa. `settled` garante que a resposta só vale uma\n * vez, mesmo que as duas cheguem juntas.\n */\n const check = useCallback(async (): Promise<boolean> => {\n if (!sessionId || settled.current) return false\n const shop = getShopProvider()\n if (!shop.settleCheckoutSession) return false\n try {\n // A pista que o adquirente pendurou na volta. Ela não decide nada — o\n // servidor confere com o adquirente antes de aceitar — mas fecha a compra\n // na hora em que a pessoa volta, em vez de esperar um webhook.\n const result = await shop.settleCheckoutSession(sessionId, provider, resume?.chargeToken ?? null)\n if (settled.current) return false\n if (result.state === 'paid' && result.orderId) {\n settled.current = true\n setPhase('settling')\n onPaid(result.orderId)\n return true\n }\n if (result.state === 'failed' || result.state === 'expired') {\n setError(\n result.reason\n ?? (result.state === 'expired'\n ? 'O código expirou. Gere um novo para continuar.'\n : 'O pagamento não foi concluído.'),\n )\n setPhase('error')\n }\n return false\n } catch {\n // Uma consulta que falhou não é um pagamento que falhou. Segue tentando.\n return false\n }\n }, [sessionId, provider, resume?.chargeToken, onPaid])\n\n useEffect(() => {\n if (phase !== 'waiting' || !sessionId) return\n let stopped = false\n const timer = setInterval(() => { if (!stopped) void check() }, POLL_MS)\n return () => { stopped = true; clearInterval(timer) }\n }, [phase, sessionId, check])\n\n async function confirmPaid() {\n setChecking(true)\n const paid = await check()\n // Só devolve o botão se NÃO pagou: se pagou, a tela já está indo embora e\n // um \"confirmando…\" que vira \"já paguei\" outra vez pisca à toa.\n if (!paid) setChecking(false)\n }\n\n /**\n * Copy the Pix code, including where `navigator.clipboard` does not exist.\n *\n * The clipboard API is only exposed in a SECURE CONTEXT: https, or localhost.\n * A store opened by IP on the local network, inside an app webview, or behind\n * a proxy without TLS does not have it — and there the button answered \"copy\n * it by hand\" in front of a 200-character code nobody copies by hand. The\n * whole checkout leans on that copy: without it the buyer does not pay.\n *\n * So the old road stays here as the fallback. `execCommand('copy')` is\n * deprecated and works on an insecure origin, which is exactly where the new\n * one fails.\n */\n async function copy() {\n if (!charge?.emv) return\n if (await copyText(charge.emv)) {\n setCopied(true)\n setTimeout(() => setCopied(false), 2400)\n return\n }\n toast.error('Copie o código manualmente')\n }\n\n if (phase === 'card' && brickKey) {\n const acquirer = gatewayLabel(provider)\n return (\n <div data-testid={TID.checkoutPayment} className=\"space-y-4 rounded-xl border bg-card p-6\">\n <div className=\"flex items-center gap-2\">\n <CreditCard className=\"h-5 w-5 text-primary\" />\n <h2 className=\"text-lg font-semibold\">Pague com cartão sem sair da loja</h2>\n </div>\n <p className=\"text-sm text-muted-foreground\">\n {acquirer\n ? `Os campos do cartão são da ${acquirer} e o número não passa por esta loja. Seu pedido é criado assim que o pagamento for aprovado.`\n : 'O número do cartão não passa por esta loja. Seu pedido é criado assim que o pagamento for aprovado.'}\n </p>\n {(total ?? amount) != null && (\n <p className=\"text-sm\">\n Valor: <strong data-testid={TID.checkoutPaymentTotal}>{money((total ?? amount)!)}</strong>\n </p>\n )}\n <CardBrick\n publicKey={brickKey}\n // Their SDK prices the installment options from this, so it must be\n // the total the server will actually charge — which is what the\n // page already shows and what a reprice would have sent us back a\n // step to correct.\n amount={total ?? amount ?? 0}\n email={input.customer?.email ?? null}\n onError={(message) => setError(message)}\n onSubmit={async (result: CardBrickResult) => {\n // Their contract: RESOLVE when the payment is handled, REJECT to keep\n // the form up. Rejecting is what lets a declined card be corrected in\n // place — a resolve here would tear the filled-in form down.\n const shop = getShopProvider()\n if (!shop.openCheckoutSession) throw new Error('sem gateway')\n try {\n const session = await shop.openCheckoutSession({\n ...input,\n cardToken: result.token,\n installments: result.installments,\n paymentMethodId: result.paymentMethodId,\n issuerId: result.issuerId,\n // Their anti-fraud reads this, and a card charged without it is\n // declined more often for no visible reason.\n deviceId: deviceSessionId(),\n })\n setSessionId(session.sessionId)\n setProvider(session.provider ?? input.provider ?? null)\n setTotal(session.total)\n\n // Approved on the spot is the common case for a card, so the order\n // already exists and there is nothing to poll.\n const orderId = (session as { orderId?: string | null }).orderId ?? null\n if (orderId) {\n settled.current = true\n setPhase('settling')\n onPaid(orderId)\n return\n }\n // In review: the page waits, and the webhook or the next tick\n // finishes it. Nothing is charged twice either way.\n setPhase('waiting')\n } catch (err) {\n const message = describeError(err, 'O pagamento não foi aprovado.')\n setError(message)\n // Rethrow so the Brick keeps the form — see above.\n throw err\n }\n }}\n />\n {error && (\n <p className=\"rounded-lg border border-destructive/40 bg-destructive/5 p-3 text-sm text-destructive\">\n {error}\n </p>\n )}\n <button\n type=\"button\"\n onClick={onBack}\n className=\"inline-flex min-h-11 items-center rounded-lg border px-4 py-2.5 text-sm font-medium transition hover:bg-muted\"\n >\n Voltar\n </button>\n </div>\n )\n }\n\n if (phase === 'redirect' && redirectUrl) {\n // Named where the rest of the acquirer's facts live, so this screen keeps no\n // map of its own; an acquirer the table does not carry gets a plain verb\n // rather than its slug printed at a buyer.\n const acquirer = gatewayLabel(provider)\n return (\n <div data-testid={TID.checkoutPayment} className=\"space-y-4 rounded-xl border bg-card p-6\">\n <div className=\"flex items-center gap-2\">\n <CreditCard className=\"h-5 w-5 text-primary\" />\n <h2 className=\"text-lg font-semibold\">\n {acquirer ? `Pague com cartão na página da ${acquirer}` : 'Pague com cartão'}\n </h2>\n </div>\n <p className=\"text-sm text-muted-foreground\">\n {acquirer\n ? `Os dados do cartão são digitados no ambiente seguro da ${acquirer} — a loja não vê o número. Ao terminar, você volta para cá e o pedido é criado.`\n : 'Os dados do cartão são digitados no ambiente seguro do provedor — a loja não vê o número. Ao terminar, você volta para cá e o pedido é criado.'}\n </p>\n {total != null && (\n <p className=\"text-sm\">\n Valor: <strong data-testid={TID.checkoutPaymentTotal}>{money(total)}</strong>\n </p>\n )}\n <div className=\"flex flex-wrap gap-2\">\n <button\n type=\"button\"\n onClick={() => {\n if (sessionId) rememberSession(sessionId, provider)\n window.location.assign(redirectUrl)\n }}\n className=\"inline-flex min-h-11 items-center gap-2 rounded-lg bg-primary px-5 py-2.5 text-sm font-semibold text-primary-foreground transition hover:opacity-90\"\n >\n <Lock className=\"h-4 w-4\" />\n {acquirer ? `Pagar com ${acquirer}` : 'Pagar com cartão'}\n </button>\n <button\n type=\"button\"\n onClick={onBack}\n className=\"inline-flex min-h-11 items-center rounded-lg border px-4 py-2.5 text-sm font-medium transition hover:bg-muted\"\n >\n Voltar\n </button>\n </div>\n </div>\n )\n }\n\n if (phase === 'opening') {\n return (\n // Same layout as the charge below, so nothing jumps when it arrives.\n <SkeletonGroup\n label=\"Preparando seu pagamento\"\n data-testid={TID.checkoutPayment}\n className=\"rounded-xl border bg-card p-6\"\n >\n <div className=\"flex items-center gap-2\">\n <Skeleton className=\"h-5 w-5 rounded-md\" />\n <Skeleton className=\"h-5 w-64 max-w-[70%]\" />\n </div>\n <Skeleton className=\"mt-2 h-3.5 w-full max-w-sm\" />\n <div className=\"mt-5 grid gap-5 sm:grid-cols-[auto_minmax(0,1fr)] sm:items-start\">\n <Skeleton className=\"mx-auto h-44 w-44 rounded-lg\" />\n <div className=\"min-w-0\">\n <Skeleton className=\"h-4 w-32\" />\n <Skeleton className=\"mt-4 h-3 w-28\" />\n <Skeleton className=\"mt-1 h-16 w-full rounded-lg\" />\n <div className=\"mt-3 flex flex-wrap items-center gap-3\">\n <Skeleton className=\"h-11 w-40 rounded-lg\" />\n <Skeleton className=\"h-11 w-32 rounded-lg\" />\n </div>\n </div>\n </div>\n </SkeletonGroup>\n )\n }\n\n if (phase === 'error') {\n return (\n <div data-testid={TID.checkoutPayment} className=\"space-y-3 rounded-xl border bg-card p-6\">\n <p data-testid={TID.checkoutError} className=\"rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive\">\n {error ?? 'Não conseguimos abrir a cobrança agora.'}\n </p>\n <div className=\"flex gap-2\">\n <button\n type=\"button\"\n onClick={() => { opened.current = false; void open() }}\n className=\"rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground transition hover:opacity-90\"\n >\n Tentar de novo\n </button>\n <button\n type=\"button\"\n onClick={onBack}\n className=\"rounded-lg border px-4 py-2.5 text-sm font-medium transition hover:bg-muted\"\n >\n Voltar\n </button>\n </div>\n </div>\n )\n }\n\n // A VOLTA do adquirente. Não há QR aqui e não deve haver: o pagamento\n // aconteceu na página deles, e o que falta é a loja confirmar. A tela avança\n // sozinha quando o dinheiro é confirmado, e continua tentando enquanto não é —\n // um cartão em análise leva minutos, não segundos.\n if (!charge) {\n return (\n <div data-testid={TID.checkoutPayment} className=\"space-y-3 rounded-xl border bg-card p-6\" aria-live=\"polite\">\n <div className=\"flex items-center gap-2\">\n <PulseDot />\n <h2 className=\"text-lg font-semibold\">Confirmando seu pagamento…</h2>\n </div>\n <p className=\"text-sm text-muted-foreground\">\n Assim que o pagamento for confirmado, seu pedido aparece aqui. Pode deixar esta tela aberta.\n </p>\n <button\n type=\"button\"\n onClick={() => { void confirmPaid() }}\n disabled={checking}\n className=\"inline-flex min-h-11 items-center gap-2 rounded-lg border border-primary px-4 py-2.5 text-sm font-semibold text-primary transition hover:bg-primary/5 disabled:opacity-60\"\n >\n {checking ? <PulseDot /> : <Check className=\"h-4 w-4\" />}\n {checking ? 'Verificando…' : 'Já paguei'}\n </button>\n </div>\n )\n }\n\n return (\n <div data-testid={TID.checkoutPayment} className=\"space-y-4\" aria-live=\"polite\">\n <div className=\"rounded-xl border bg-card p-6\">\n <div className=\"flex items-center gap-2\">\n <QrCode className=\"h-5 w-5 text-primary\" />\n <h2 className=\"text-lg font-semibold\">Pague com Pix para fechar o pedido</h2>\n </div>\n <p className=\"mt-1 text-sm text-muted-foreground\">\n {/* Dito antes de a pessoa esperar, não depois: é isto que diferencia\n este checkout do anterior, onde o pedido já existia. */}\n Seu pedido é criado assim que o pagamento entrar. Pode deixar esta tela aberta.\n </p>\n\n <div className=\"mt-5 grid gap-5 sm:grid-cols-[auto_minmax(0,1fr)] sm:items-start\">\n {/* Base64 bytes or a hosted URL, depending on the acquirer — one <img>\n either way, because to the buyer it is the same square.\n \n SIZED FOR A SCANNER, not for the layout. A QR is a grid, and what\n decides whether a phone reads it is how many whole pixels each\n module gets. Vindi's code is 69 modules wide, and at the 176px this\n used to be that is 2.55 px per module: every module edge lands mid\n pixel, the browser anti-aliases it, and the camera sees grey mush.\n 276px is exactly 4 px per module, so every edge falls on a pixel\n boundary and the code is sharp.\n \n The padding is the QUIET ZONE and not decoration. The spec asks for\n four clear modules on every side, and this SVG ships with none —\n its first rect sits at 0,0 — so the white p-4 (16px = 4 modules at\n this scale) is what a scanner needs to find the code's edges at all.\n \n `box-content` is load-bearing: Tailwind sizes border-box by default,\n so without it the padding would eat INTO the 276 and leave 244 —\n 3.54 px per module, the very problem this is fixing.\n \n `max-w-full` keeps a narrow phone from overflowing; there the square\n shrinks and the copy-and-paste code carries the payment anyway. */}\n {(charge?.qrcodeBase64 || charge?.qrcodeUrl) && (\n <img\n src={charge.qrcodeBase64\n ? `data:image/png;base64,${charge.qrcodeBase64}`\n : charge.qrcodeUrl!}\n alt=\"QR code do Pix\"\n width={276}\n height={276}\n className=\"mx-auto box-content h-[276px] w-[276px] max-w-full rounded-lg border bg-white p-4\"\n />\n )}\n <div className=\"min-w-0\">\n {total != null && (\n <p className=\"text-sm\">\n Valor: <strong data-testid={TID.checkoutPaymentTotal}>{money(total)}</strong>\n </p>\n )}\n <p className=\"mt-3 text-xs font-medium uppercase tracking-wide text-muted-foreground\">\n Pix copia e cola\n </p>\n <p\n data-testid={TID.pixCode}\n className=\"mt-1 max-h-24 overflow-y-auto break-all rounded-lg border bg-muted/40 p-3 font-mono text-xs\"\n >\n {charge?.emv}\n </p>\n {/* Quanto o código ainda vale. Só aparece quando o provedor deu um\n prazo — nada de inventar um relógio que ele não prometeu. */}\n {expiry.secondsLeft !== null && !expiry.expired && (\n <p className=\"mt-2 text-xs text-muted-foreground\">\n Este código vale por mais{' '}\n <span className=\"font-medium tabular-nums text-foreground\">\n {formatCountdown(expiry.secondsLeft)}\n </span>\n </p>\n )}\n\n {/* Expirado, o código na tela é papel velho: quem copiou e pagar agora\n paga em lugar nenhum. Então some, e no lugar fica a única ação que faz\n sentido — pedir outro. Aqui uma cobrança nova está CERTA: a antiga\n morreu, e o reaproveitamento no servidor só devolve a mesma enquanto\n ela estiver de pé. */}\n {expiry.expired && (\n <div className=\"mt-3 space-y-2\">\n <p data-testid={TID.checkoutExpired} className=\"text-sm text-muted-foreground\">\n O prazo deste código acabou. Gere outro para pagar.\n </p>\n <button\n type=\"button\"\n onClick={() => { opened.current = false; setCharge(null); void open() }}\n className=\"inline-flex min-h-11 items-center gap-2 rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground transition hover:opacity-90\"\n >\n Gerar novo código\n </button>\n </div>\n )}\n\n {/* \"Já paguei\" confirms nothing — it only hurries the same poll the\n screen already runs; the bank still answers. */}\n <div className=\"mt-3 flex flex-wrap items-center gap-3\" hidden={expiry.expired}>\n <button\n type=\"button\"\n onClick={copy}\n data-testid={TID.pixCopy}\n className=\"inline-flex min-h-11 items-center gap-2 rounded-lg bg-primary px-4 py-2.5 text-sm font-medium text-primary-foreground transition hover:opacity-90\"\n >\n {copied ? <Check className=\"h-4 w-4\" /> : <Copy className=\"h-4 w-4\" />}\n {copied ? 'Código copiado' : 'Copiar código'}\n </button>\n <button\n type=\"button\"\n onClick={() => { void confirmPaid() }}\n disabled={checking || phase === 'settling'}\n data-testid={TID.pixConfirm}\n className=\"inline-flex min-h-11 items-center gap-2 rounded-lg border border-primary px-4 py-2.5 text-sm font-semibold text-primary transition hover:bg-primary/5 disabled:opacity-60\"\n >\n {checking || phase === 'settling'\n ? <PulseDot />\n : <Check className=\"h-4 w-4\" />}\n {phase === 'settling' ? 'Confirmando…' : checking ? 'Verificando…' : 'Já paguei'}\n </button>\n </div>\n </div>\n </div>\n </div>\n\n <button\n type=\"button\"\n onClick={onBack}\n className=\"text-sm text-muted-foreground underline hover:text-foreground\"\n >\n Voltar e revisar o pedido\n </button>\n </div>\n )\n}\n","import { useEffect, useState } from 'react'\nimport { getShopProvider } from '@fayz-ai/shop/runtime'\nimport type { Order, ShippingAddressInput } from '@fayz-ai/shop/types'\nimport { useSessionStore } from '../stores/session.store'\nimport { hasCustomerAuth, relinkCustomer } from '../data/auth'\nimport { useMyOrders } from './use-my-orders'\n\n/**\n * What the store already knows about the person filling this checkout in.\n *\n * A signed-in buyer typed their CPF, their phone and their address the last time\n * they bought something, and every one of those is stored: the document and the\n * phone on their customer row, the address frozen on the order. Asking again is\n * asking someone to prove twice that they are themselves — and the CPF is the\n * field AbacatePay needs to create a client at all, so a blank one is also a\n * charge with no customer attached to it.\n *\n * Two sources because they are two different facts. The document belongs to the\n * PERSON and lives on the customer row; the address belongs to an ORDER and is\n * whatever they last shipped to. Reading the customer row is allowed by the\n * `plg_shop_customers_self_read` policy (`auth_user_id = auth.uid()`), so this\n * needs no new endpoint and no new grant — a guest simply resolves to nothing.\n */\nexport interface KnownCustomer {\n phone: string | null\n document: string | null\n address: ShippingAddressInput | null\n /** False until both lookups have settled, so a prefill never races typing. */\n ready: boolean\n}\n\nexport function useKnownCustomer(): KnownCustomer {\n const customerId = useSessionStore((s) => s.customerId)\n const { orders, loading: ordersLoading } = useMyOrders()\n const [contact, setContact] = useState<{ phone: string | null; document: string | null } | null>(null)\n const [checked, setChecked] = useState(false)\n\n useEffect(() => {\n if (!customerId) {\n setContact(null)\n setChecked(true)\n return\n }\n let cancelled = false\n const shop = getShopProvider()\n Promise.resolve(shop.getCustomer?.(customerId))\n // Signed in but nothing readable: the id is stale or the row unlinked, and\n // RLS answers both with an empty result. Re-resolve links it and returns it.\n .then(async (customer) => {\n if (customer || !hasCustomerAuth()) return customer ? { phone: customer.phone ?? null, document: customer.document ?? null } : null\n const relinked = await relinkCustomer()\n return relinked ? { phone: relinked.phone, document: relinked.document } : null\n })\n .then((found) => {\n if (cancelled) return\n setContact(found)\n })\n // A buyer who cannot be read is a buyer who fills the form in, which is\n // exactly what happened before this existed. Never a blocking error.\n .catch(() => { if (!cancelled) setContact(null) })\n .finally(() => { if (!cancelled) setChecked(true) })\n return () => { cancelled = true }\n }, [customerId])\n\n // The most recent order that actually shipped somewhere. An order without an\n // address (a pickup, a failed session) says nothing about where to deliver.\n const lastAddress = pickLastAddress(orders)\n\n return {\n phone: contact?.phone ?? null,\n document: contact?.document ?? null,\n address: lastAddress,\n ready: checked && !ordersLoading,\n }\n}\n\nfunction pickLastAddress(orders: readonly Order[]): ShippingAddressInput | null {\n for (const order of orders) {\n const address = (order as { shippingAddress?: ShippingAddressInput | null }).shippingAddress\n if (address && (address.postalCode || address.street)) return address\n }\n return null\n}\n","import React from 'react'\n\n/**\n * A checkout input with its label VISIBLE, not `sr-only`.\n *\n * A field whose name only lives in the placeholder loses it the moment someone\n * starts typing — which is exactly when they need to check they are in the\n * right one. Someone coming back to the form after an error finds four filled\n * boxes and nothing saying what they are.\n */\nexport function checkoutField(\n label: string,\n testId: string,\n value: string,\n onChange: (value: string) => void,\n props?: React.InputHTMLAttributes<HTMLInputElement>,\n) {\n return (\n <label className=\"block\">\n <span className=\"mb-1.5 block text-xs font-medium text-muted-foreground\">{label}</span>\n <input\n data-testid={testId}\n aria-label={label}\n value={value}\n onChange={(event) => onChange(event.target.value)}\n className=\"w-full rounded-lg border bg-background px-3.5 py-3 text-sm outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/10\"\n {...props}\n />\n </label>\n )\n}\n\n/** The same label and box, as a list (a region the country enumerates). */\nexport function checkoutSelect(\n label: string,\n testId: string,\n value: string,\n onChange: (value: string) => void,\n options: readonly { value: string; label: string }[],\n placeholder: string,\n props?: React.SelectHTMLAttributes<HTMLSelectElement>,\n) {\n return (\n <label className=\"block\">\n <span className=\"mb-1.5 block text-xs font-medium text-muted-foreground\">{label}</span>\n <select\n data-testid={testId}\n aria-label={label}\n value={value}\n onChange={(event) => onChange(event.target.value)}\n className=\"w-full rounded-lg border bg-background px-3.5 py-3 text-sm outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/10\"\n {...props}\n >\n <option value=\"\">{placeholder}</option>\n {options.map((option) => (\n <option key={option.value} value={option.value}>{option.label}</option>\n ))}\n </select>\n </label>\n )\n}\n","import React from 'react'\nimport { getCountrySchema, type AddressFieldKey, type AddressFieldSpec } from '@fayz-ai/core'\nimport { TID } from '../../lib/testids'\nimport { Skeleton, SkeletonGroup } from '../Skeleton'\nimport { useT } from '../../locales'\nimport type { StorefrontLanguage } from '../../locales/messages'\nimport { checkoutField, checkoutSelect } from './CheckoutField'\n\n/** The address as the form holds it. `state` is the region (UF, province). */\nexport interface AddressDraft {\n zip: string\n street: string\n number: string\n complement: string\n district: string\n city: string\n state: string\n}\n\nexport type PostalLookupState = 'idle' | 'loading' | 'found' | 'not-found'\n\nexport interface AddressFormProps {\n /** ISO2. The form takes this country's fields, order, labels and formats. */\n country: string\n language: StorefrontLanguage\n value: AddressDraft\n onChange(key: keyof AddressDraft, value: string): void\n /** The postal code field. The caller masks, looks up and fills the rest. */\n onPostalCode(value: string): void\n lookup: PostalLookupState\n /** The store's checkout policy for the one optional field it governs. */\n complement?: { visible: boolean; required: boolean }\n}\n\nconst DRAFT_KEY: Record<AddressFieldKey, keyof AddressDraft> = {\n postalCode: 'zip',\n street: 'street',\n number: 'number',\n complement: 'complement',\n district: 'district',\n city: 'city',\n region: 'state',\n}\n\n// The test ids every store's e2e suite already targets.\nconst TEST_ID: Record<AddressFieldKey, string> = {\n postalCode: TID.checkoutZip,\n street: TID.checkoutStreet,\n number: 'checkout-number',\n complement: 'checkout-complement',\n district: 'checkout-district',\n city: TID.checkoutCity,\n region: 'checkout-state',\n}\n\n/**\n * The delivery address, in the shape of the country it ships to.\n *\n * Brazil renders exactly the form the checkout always had: CEP first (it fills\n * the fields below it), number beside complement, bairro beside UF. Spain has\n * no number or bairro, takes a five-digit postal code and picks the province\n * from a list the postal code pre-selects. Any other country gets the generic\n * shape. The layout is the schema's `rows`; nothing here names a country.\n */\nexport function AddressForm({ country, language, value, onChange, onPostalCode, lookup, complement }: AddressFormProps) {\n const t = useT()\n const schema = getCountrySchema(country)\n const specs = new Map(schema.fields.map((spec) => [spec.key, spec]))\n const showComplement = complement?.visible !== false\n const requireComplement = complement?.required === true\n\n function input(spec: AddressFieldSpec) {\n const key = DRAFT_KEY[spec.key]\n const label = spec.label[language]\n const required = spec.required || (spec.key === 'complement' && requireComplement)\n const basePlaceholder = spec.placeholder?.[language] ?? label\n const placeholder = required ? basePlaceholder : t('checkout.address.optional', { label: basePlaceholder })\n\n if (spec.key === 'postalCode') {\n return checkoutField(label, TEST_ID.postalCode, value.zip, onPostalCode, {\n placeholder,\n inputMode: schema.postal.inputMode,\n autoComplete: 'postal-code',\n })\n }\n if (spec.key === 'region' && schema.region.input === 'select' && schema.regions) {\n return checkoutSelect(\n label,\n TEST_ID.region,\n value.state,\n (next) => onChange('state', next),\n schema.regions.map((region) => ({\n value: schema.region.stores === 'code' ? region.code : region.name,\n label: region.name,\n })),\n t('checkout.address.choose'),\n { autoComplete: spec.autoComplete },\n )\n }\n return checkoutField(label, TEST_ID[spec.key], value[key], (next) => onChange(key, next), {\n placeholder,\n ...(spec.autoComplete ? { autoComplete: spec.autoComplete } : {}),\n })\n }\n\n function postalHint(): React.ReactNode {\n if (lookup === 'loading') {\n return (\n <SkeletonGroup label={t('checkout.address.lookingUp')} className=\"grid gap-1.5 px-1\">\n <Skeleton className=\"h-2.5 w-40\" />\n <Skeleton className=\"h-2.5 w-24\" />\n </SkeletonGroup>\n )\n }\n if (schema.postal.lookup === 'viacep') {\n return (\n <p className=\"px-1 text-xs text-muted-foreground\">\n {lookup === 'not-found' ? t('checkout.address.notFound') : t('checkout.address.filled')}\n </p>\n )\n }\n if (schema.postal.lookup === 'prefix' && lookup === 'found') {\n return <p className=\"px-1 text-xs text-muted-foreground\">{t('checkout.address.regionFromPostal')}</p>\n }\n return null\n }\n\n return (\n <div className=\"grid gap-3\">\n {schema.rows.map((row) => {\n const cells = row.filter((key) => specs.has(key) && (key !== 'complement' || showComplement))\n if (cells.length === 0) return null\n if (cells.length === 1 && cells[0] === 'postalCode') {\n // CEP first, because it FILLS the fields below it. With it at the\n // bottom the buyer typed street, district, city and UF by hand and\n // only then reached the one field that would have supplied all four.\n return (\n <div key=\"postalCode\" className=\"grid gap-1 sm:grid-cols-[200px_1fr] sm:items-center\">\n {input(specs.get('postalCode')!)}\n {postalHint()}\n </div>\n )\n }\n // A paired row keeps its two columns when the store hides one of the\n // pair (the complement), as the form always did.\n if (row.length === 1) return <React.Fragment key={cells[0]}>{input(specs.get(cells[0]!)!)}</React.Fragment>\n return (\n <div key={cells.join('-')} className=\"grid grid-cols-2 gap-3\">\n {cells.map((key) => <React.Fragment key={key}>{input(specs.get(key)!)}</React.Fragment>)}\n </div>\n )\n })}\n </div>\n )\n}\n","import React from 'react'\nimport { Check } from 'lucide-react'\nimport { documentDigits } from '@fayz-ai/shop'\n\n/**\n * A signed-in buyer's contact, as one card instead of four boxes.\n *\n * Whoever is signed in and already gave their name, phone and CPF has nothing\n * to type in step 1: the store knows it all (profile, last order). Showing the\n * full form made them re-read and re-confirm it on every order. The card says\n * who is buying; «Alterar» brings the fields back.\n *\n * The CPF is masked (***.170.431-**), the same convention receipts and the\n * Nota Fiscal use: the screen can be seen by whoever stands behind the buyer,\n * and the digits shown are still enough to recognise one's own. A CNPJ is a\n * company's public id and shows whole.\n */\nexport function maskDocument(raw: string): string {\n const d = documentDigits(raw)\n if (d.length === 11) return `***.${d.slice(3, 6)}.${d.slice(6, 9)}-**`\n if (d.length === 14) return `${d.slice(0, 2)}.${d.slice(2, 5)}.${d.slice(5, 8)}/${d.slice(8, 12)}-${d.slice(12)}`\n return raw\n}\n\n/** (21) 97122-1016 / (21) 3333-4444; a +55 prefix is dropped. */\nexport function formatBrPhone(raw: string): string {\n let d = raw.replace(/\\D/g, '')\n if (d.startsWith('55') && (d.length === 12 || d.length === 13)) d = d.slice(2)\n if (d.length === 11) return `(${d.slice(0, 2)}) ${d.slice(2, 7)}-${d.slice(7)}`\n if (d.length === 10) return `(${d.slice(0, 2)}) ${d.slice(2, 6)}-${d.slice(6)}`\n return raw\n}\n\nexport function ContactSummary({ name, email, phone, document, onEdit, onSignOut, labels }: {\n name: string\n email: string\n phone?: string\n document?: string\n onEdit: () => void\n onSignOut: () => void\n labels: { edit: string; notYou: string; signOut: string }\n}) {\n const line = [phone ? formatBrPhone(phone) : null, document ? maskDocument(document) : null].filter(Boolean).join(' · ')\n return (\n <div data-testid=\"checkout-contact-summary\" className=\"rounded-xl border bg-card p-4\">\n <div className=\"flex items-start gap-3\">\n <span className=\"mt-0.5 grid h-6 w-6 shrink-0 place-items-center rounded-full bg-primary/15 text-primary\" aria-hidden>\n <Check className=\"h-3.5 w-3.5\" />\n </span>\n <div className=\"min-w-0 flex-1\">\n <p className=\"truncate text-sm font-semibold\">{name}</p>\n <p className=\"truncate text-sm text-muted-foreground\">{email}</p>\n {line && <p className=\"truncate text-sm text-muted-foreground\">{line}</p>}\n </div>\n <button\n type=\"button\"\n onClick={onEdit}\n data-testid=\"checkout-contact-edit\"\n className=\"shrink-0 text-sm font-medium text-primary hover:underline\"\n >\n {labels.edit}\n </button>\n </div>\n <p className=\"mt-3 border-t pt-3 text-xs text-muted-foreground\">\n {labels.notYou}{' '}\n <button\n type=\"button\"\n onClick={onSignOut}\n data-testid=\"checkout-contact-sign-out\"\n className=\"font-medium text-foreground hover:underline\"\n >\n {labels.signOut}\n </button>\n </p>\n </div>\n )\n}\n","import { getCountrySchema, normalizePostalCode } from '@fayz-ai/core'\nimport { documentDigits } from '@fayz-ai/shop'\nimport type { ShippingAddressInput } from '@fayz-ai/shop/types'\n\nexport interface CheckoutAddressFields {\n zip: string\n street: string\n number: string\n complement: string\n district: string\n city: string\n state: string\n phone: string\n document: string\n}\n\n/**\n * What the buyer typed, as the order stores it, with the country it is in.\n *\n * Only the fields the country's form has travel: a Spanish address has no\n * number or bairro of its own (the number is in the street line). Brazil keeps\n * exactly the payload it always sent, plus `country: 'BR'`.\n */\nexport function toShippingAddress(form: CheckoutAddressFields, country: string): ShippingAddressInput {\n const schema = getCountrySchema(country)\n const isBrazil = schema.iso2 === 'BR'\n const has = (key: 'number' | 'district') => schema.fields.some((f) => f.key === key)\n return {\n postalCode: isBrazil ? form.zip.trim() : normalizePostalCode(form.zip, country),\n street: form.street.trim(),\n number: has('number') ? form.number.trim() || undefined : undefined,\n complement: form.complement.trim() || undefined,\n district: has('district') ? form.district.trim() || undefined : undefined,\n city: form.city.trim(),\n // A UF is a code and is upper-cased; a province is a name and keeps its case.\n state: schema.region.stores === 'code' ? form.state.trim().toUpperCase() : form.state.trim(),\n country: schema.iso2,\n phone: form.phone.trim() || undefined,\n document: (isBrazil ? documentDigits(form.document) : form.document.trim().toUpperCase()) || undefined,\n }\n}\n","import React from 'react'\nimport { MapPin } from 'lucide-react'\nimport { countryName } from '@fayz-ai/core'\nimport { useStorefrontConfig } from '../../document/config'\nimport { useBuyerCountry } from '../../hooks/use-buyer-country'\nimport { useT } from '../../locales'\n\nfunction flag(iso2: string): string {\n return iso2\n .toUpperCase()\n .replace(/[^A-Z]/g, '')\n .split('')\n .map((c) => String.fromCodePoint(0x1f1e6 + c.charCodeAt(0) - 65))\n .join('')\n}\n\n/**\n * \"Ship to: 🇪🇸 Spain\", as a native select: the platform's own list is the\n * most accessible country picker there is, on every device.\n */\nexport function CountrySelect({ country, allowed, onChange, className }: {\n country: string\n allowed: readonly string[]\n onChange(country: string): void\n className?: string\n}) {\n const t = useT()\n const config = useStorefrontConfig()\n return (\n <label className={`flex items-center gap-2 text-sm ${className ?? ''}`}>\n <MapPin className=\"h-4 w-4 shrink-0 text-muted-foreground\" aria-hidden />\n <span className=\"text-muted-foreground\">{t('country.deliverTo')}</span>\n <select\n data-testid=\"deliver-to-country\"\n aria-label={t('country.label')}\n value={country}\n onChange={(event) => onChange(event.target.value)}\n className=\"rounded-lg border bg-background px-2.5 py-1.5 text-sm font-medium outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/10\"\n >\n {allowed.map((iso2) => (\n <option key={iso2} value={iso2}>\n {flag(iso2)} {countryName(iso2, config.language)}\n </option>\n ))}\n </select>\n </label>\n )\n}\n\n/**\n * The store-wide \"Deliver to\" control, for a header. Renders nothing for a\n * store that ships to one country, so dropping it into any chrome is safe.\n */\nexport function DeliverToPicker({ className }: { className?: string }) {\n const buyer = useBuyerCountry()\n if (buyer.allowed.length < 2) return null\n return <CountrySelect className={className} country={buyer.country} allowed={buyer.allowed} onChange={buyer.setCountry} />\n}\n","import React, { useEffect, useState } from 'react'\nimport { identifyStorefrontBuyer, trackStorefront } from '../analytics/bus'\nimport { CreditCard, Lock, ShieldCheck } from 'lucide-react'\nimport { getShopProvider } from '@fayz-ai/shop/runtime'\nimport { documentDigits, formatDocument, isChargeableProvider, isValidDocument, supportsCard } from '@fayz-ai/shop'\nimport { formatPostalCode, normalizePostalCode, lookupPostalCode, getCountrySchema, validateAddress } from '@fayz-ai/core'\nimport type { CustomerAddress, PaymentMethodKind, ShippingAddressInput } from '@fayz-ai/shop/types'\nimport { prefersReducedMotion } from '../lib/motion'\nimport {\n useCartStore,\n selectSubtotal,\n selectDiscountTotal,\n selectShipping,\n selectRequiresShipping,\n selectTotal,\n} from '../stores/cart.store'\nimport { useSessionStore } from '../stores/session.store'\nimport { useDeliveryStore } from '../stores/delivery.store'\nimport { useStorefrontConfig } from '../document/config'\nimport { returnPath } from '../app/return-path'\nimport { Link, navigateTo } from '../app/router'\nimport { formatMoney } from '../lib/format'\nimport { TID } from '../lib/testids'\nimport { useDiscountValidator } from '../hooks/use-discount-validator'\nimport { toast } from '../stores/toast.store'\nimport { useStorefrontHead } from '../hooks/use-storefront-head'\nimport { SignInModal } from '../components/account/SignInModal'\nimport { SmoothImage } from '../components/SmoothImage'\nimport { Slot } from '../extend/slots'\nimport { placeStorefrontOrder } from '../workflows/checkout'\nimport { CheckoutSteps, type CheckoutStep } from '../components/checkout/CheckoutSteps'\nimport { CheckoutPayment, recallSessionProvider } from '../components/checkout/CheckoutPayment'\nimport { SuccessMark } from '../components/order/SuccessMark'\nimport { Skeleton, SkeletonGroup } from '../components/Skeleton'\nimport { errorMessage } from '../lib/errors'\nimport { useKnownCustomer } from '../hooks/use-known-customer'\nimport { useBuyerCountry } from '../hooks/use-buyer-country'\nimport { AddressForm } from '../components/checkout/AddressForm'\nimport { checkoutField as field } from '../components/checkout/CheckoutField'\nimport { ContactSummary } from '../components/checkout/ContactSummary'\nimport { signOutCustomer } from '../data/auth'\nimport { toShippingAddress } from '../lib/checkout-address'\nimport { CountrySelect } from '../components/delivery/DeliverToPicker'\nimport { useT } from '../locales'\nimport type { MessageKey } from '../locales/messages'\n\ninterface CheckoutForm {\n email: string\n name: string\n phone: string\n document: string\n street: string\n city: string\n zip: string\n number: string\n complement: string\n district: string\n state: string\n}\n\ntype AddressMode = 'saved' | 'new'\n\n/**\n * There is no payment service provider connected, so the checkout does not ask\n * for a card number. It used to, prefilled with 4242 4242 4242 4242, and the\n * digits were validated and then thrown away — a PAN typed into React state\n * that reaches no processor is a liability with no upside. The buyer states how\n * they intend to pay; the order stays `pending` until the merchant confirms the\n * money arrived (shop_confirm_payment, which since 0019 only they can call).\n */\nconst PAYMENT_LABELS: Record<PaymentMethodKind, { label: MessageKey; hint: MessageKey }> = {\n pix: { label: 'payment.pix.label', hint: 'payment.pix.hint' },\n // O cartão tem DOIS significados agora, e o texto muda com a loja: sem\n // adquirente é a maquininha do entregador; com adquirente é a página segura\n // dele — prometer \"maquininha\" para quem vai ser redirecionado é a loja\n // mentindo sobre a própria entrega.\n credit_card: { label: 'payment.credit_card.label', hint: 'payment.credit_card.hint' },\n debit_card: { label: 'payment.debit_card.label', hint: 'payment.debit_card.hint' },\n boleto: { label: 'payment.boleto.label', hint: 'payment.boleto.hint' },\n cash: { label: 'payment.cash.label', hint: 'payment.cash.hint' },\n other: { label: 'payment.other.label', hint: 'payment.other.hint' },\n}\n\n/** Payment rails that exist only in Brazil. */\nconst BRAZIL_ONLY: readonly PaymentMethodKind[] = ['pix', 'boleto']\n\n/**\n * What the buyer reads when shop_place_order refuses.\n *\n * The RPC's messages are written for whoever reads the logs (\"shop_place_order:\n * customer email mismatch\", prefix and all), and PostgrestError is not an Error\n * instance, so the old check showed nothing useful either way.\n */\nfunction placeOrderMessage(err: unknown, t: ReturnType<typeof useT>): string {\n const message = errorMessage(err)\n if (/customer (email mismatch|does not belong|belongs to another)/i.test(message)) {\n return t('error.sessionMismatch')\n }\n if (/out of stock|insufficient|estoque/i.test(message)) {\n return t('error.outOfStock')\n }\n if (/delivery not available|postal code/i.test(message)) {\n return t('error.unserved')\n }\n return message.replace(/^shop_[a-z_]+:\\s*/i, '') || t('error.placeOrder')\n}\n\n/**\n * Build de desenvolvimento? Mesmo cast defensivo do `isDevBuild()` do core: o\n * SDK também é carregado em Node (testes, render headless), onde\n * `import.meta.env` simplesmente não existe e o acesso direto explode.\n */\nconst DEV_BUILD: boolean = (() => {\n try {\n return (import.meta as unknown as { env?: { DEV?: boolean } }).env?.DEV === true\n } catch {\n return false\n }\n})()\n\n\nconst CHECKOUT_STEP_NAMES: Record<CheckoutStep, string> = { 1: 'contact', 2: 'delivery', 3: 'payment', 4: 'done' }\n\nexport function CheckoutPage() {\n const config = useStorefrontConfig()\n const cart = useCartStore()\n const session = useSessionStore()\n const delivery = useDeliveryStore()\n const validateDiscount = useDiscountValidator()\n const t = useT()\n useStorefrontHead({ title: t('checkout.title', { store: config.name }) })\n\n // Where it ships decides the address form, its checks and which payment\n // rails exist: Pix and boleto are Brazilian, and offering them to a Spanish\n // address is offering a way to pay that cannot work.\n const buyer = useBuyerCountry()\n const country = buyer.country\n const isBrazil = country === 'BR'\n const countrySchema = getCountrySchema(country)\n const paymentMethods = isBrazil\n ? config.payments.methods\n : config.payments.methods.filter((method) => !BRAZIL_ONLY.includes(method))\n\n /**\n * The merchant's checkout policy, if they have saved one.\n *\n * `requiresAccount` is the storefront half of a rule the SERVER enforces\n * (0045's trigger refuses a guest order outright), which is why it gates the\n * button rather than merely hiding the \"entrar\" link: collecting a whole form\n * and failing at the last click is the worst possible way to tell someone they\n * need an account.\n *\n * The optional fields default to VISIBLE-AND-OPTIONAL when nothing is saved,\n * which is exactly how the form behaved before this policy existed.\n */\n const policy = config.policy\n const requiresAccount = policy?.guestCheckout === false\n const fieldPolicy = policy?.checkoutFields ?? {}\n type OptionalField = 'phone' | 'complement' | 'document'\n /**\n * A connected acquirer needs the buyer's CPF to mint the charge, so with a\n * gateway on, \"document\" stops being the merchant's preference: hiding it\n * would only move the failure to the gateway's opaque rejection.\n *\n * Either signal counts. `paymentProvider` is what the merchant picks in\n * Pagamentos and is the only one they can actually change; `mode` is written\n * into the app's own store document and no screen edits it.\n */\n const gatewayCheckout = config.payments.mode === 'gateway' || !!policy?.paymentProvider\n /**\n * `document` defaults to HIDDEN, unlike every other optional field.\n *\n * The others default to visible because they always were. This one is new, and\n * \"visible unless turned off\" would have made a CPF box appear on every\n * storefront in the fleet the moment this shipped — a product change no\n * merchant asked for. It shows when the store opts in, or when a gateway makes\n * it unavoidable.\n */\n const shows = (key: OptionalField) =>\n key === 'document'\n ? (isBrazil && gatewayCheckout) || fieldPolicy.document?.visible === true\n : fieldPolicy[key]?.visible !== false\n const requires = (key: OptionalField) =>\n // A CPF is Brazil's; elsewhere the tax id is the buyer's to give or not.\n key === 'document' && !isBrazil\n ? countrySchema.taxId?.required === 'always'\n : key === 'document' || key === 'phone'\n // Both are the acquirer's demand rather than the merchant's preference.\n // The CPF was always this; the phone joined it once a real charge proved\n // it: Vindi refuses a customer carrying no contact at all with\n // \"person_contacts.value: não é válido\", and AbacatePay's customer block is\n // all-or-nothing, so a missing phone silently costs the customer record.\n // Asking on the form beats a rejection the buyer cannot act on.\n ? gatewayCheckout || (fieldPolicy[key]?.visible === true && fieldPolicy[key]?.required === true)\n : fieldPolicy[key]?.visible !== false && fieldPolicy[key]?.required === true\n\n const [selectedAddressId, setSelectedAddressId] = useState('new')\n const [savedAddresses, setSavedAddresses] = useState<CustomerAddress[]>([])\n // False by default: a guest has no address book to wait for.\n const [addressesLoading, setAddressesLoading] = useState(false)\n // 'new' until the address book actually loads: an empty book must show an\n // empty form, never a placeholder address belonging to nobody.\n const [addressMode, setAddressMode] = useState<AddressMode>('new')\n /**\n * A VOLTA de quem pagou com cartão na página do adquirente.\n *\n * Lido uma vez, na montagem, porque é uma página nova: o formulário, o passo e\n * o método escolhido morreram no redirecionamento, e o que sobrou foi o id da\n * sessão na URL. Com ele o checkout não recomeça — ele confirma.\n *\n * A pista do adquirente (`token_transaction`) vem junto quando ele a\n * pendura na volta. Ela não prova nada aqui: o servidor confere com o\n * adquirente antes de aceitá-la. Serve para fechar a compra na hora, em vez de\n * esperar o webhook.\n */\n const [resume] = useState(() => {\n if (typeof window === 'undefined') return null\n const params = new URLSearchParams(window.location.search)\n const sessionId = params.get('vindi_session') ?? params.get('pay_session')\n if (!sessionId) return null\n return {\n sessionId,\n provider: recallSessionProvider(sessionId),\n chargeToken: params.get('token_transaction'),\n }\n })\n const [paymentMethod, setPaymentMethod] = useState<PaymentMethodKind>(\n resume ? 'credit_card' : paymentMethods[0] ?? 'pix')\n // The country can change mid-checkout; a method it does not offer must not stay picked.\n useEffect(() => {\n if (!paymentMethods.includes(paymentMethod) && paymentMethods[0]) setPaymentMethod(paymentMethods[0])\n }, [paymentMethods, paymentMethod])\n // What the store already knows about whoever is signed in: document and phone\n // from their record, address from their last order. It fills only what is empty\n // (see the effect below) — anyone arriving signed out sees no difference.\n const known = useKnownCustomer()\n const [form, setForm] = useState<CheckoutForm>({\n email: session.email ?? '',\n name: session.name ?? '',\n phone: '',\n document: '',\n street: '',\n city: '',\n zip: '',\n number: '',\n complement: '',\n district: '',\n state: '',\n })\n\n // Applied afterwards, and only where the field is still blank: the read is\n // async and the person may already be typing when it lands. Overwriting there\n // would erase what they had just written.\n React.useEffect(() => {\n if (!known.ready) return\n setForm((current) => ({\n ...current,\n phone: current.phone || known.phone || '',\n document: current.document || known.document || '',\n zip: current.zip || known.address?.postalCode || '',\n street: current.street || known.address?.street || '',\n number: current.number || known.address?.number || '',\n complement: current.complement || known.address?.complement || '',\n district: current.district || known.address?.district || '',\n city: current.city || known.address?.city || '',\n state: current.state || known.address?.state || '',\n }))\n }, [known.ready, known.phone, known.document, known.address])\n /**\n * Em que passo a pessoa está.\n *\n * O checkout era uma página só: todos os campos de uma vez, um botão\n * \"Comprar agora\" no fim, e a animação de sucesso disparando antes de existir\n * pagamento. Agora são quatro — dados, entrega, pagamento, pronto — e o\n * quarto só chega quando o dinheiro entrou.\n */\n // Quem volta do adquirente volta no passo do pagamento, não no primeiro:\n // os dados já foram dados, a cobrança já foi feita, e recomeçar do zero\n // pediria de novo tudo o que a pessoa acabou de preencher.\n const [step, setStep] = useState<CheckoutStep>(resume ? 3 : 1)\n const reportedStart = React.useRef(false)\n useEffect(() => {\n if (reportedStart.current) return\n reportedStart.current = true\n if (!resume) {\n trackStorefront('checkout_started', {\n cart_count: cart.lines.reduce((n, l) => n + l.quantity, 0),\n // What the cart is worth when the checkout opens: the value an ad\n // platform optimises InitiateCheckout for.\n cart_subtotal: Math.round(cart.lines.reduce((sum, l) => sum + l.unitPrice * l.quantity, 0) * 100) / 100,\n })\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n // Each step the buyer reaches is a step of the conversion funnel, and the\n // e-mail typed in «Dados» is what ties this visit to the order the server\n // reports (hashed, see storeBuyerId).\n const reportedStep = React.useRef<CheckoutStep | null>(null)\n useEffect(() => {\n if (reportedStep.current === step) return\n reportedStep.current = step\n trackStorefront('checkout_step_viewed', { step, step_name: CHECKOUT_STEP_NAMES[step], resume: Boolean(resume) })\n if (step >= 2 && /.+@.+\\..+/.test(form.email)) identifyStorefrontBuyer(form.email)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [step])\n // A signed-in buyer whose contact is complete sees a card, not the form,\n // and starts on «Entrega» (see ContactSummary). `contactKnown` turns true\n // once the profile read answered; `editingContact` is «Alterar».\n const [contactKnown, setContactKnown] = useState(false)\n const [editingContact, setEditingContact] = useState(false)\n const skippedContact = React.useRef(false)\n\n // Retirada (0094). O modo vem da mesma store que a barra do cardápio usa, e\n // por isso não há como as duas telas discordarem sobre o que a pessoa marcou.\n const fulfillmentType = useDeliveryStore((s) => s.fulfillmentType)\n const scheduledFor = useDeliveryStore((s) => s.scheduledFor)\n /** O ponto de referência do endereço escolhido no cardápio, se houver. */\n const deliveryReference = useDeliveryStore((s) => {\n const kept = s.savedAddresses.find((a) => a.id === s.selectedAddressId)\n return kept?.reference?.trim() || ''\n })\n const isPickup = fulfillmentType === 'pickup'\n const [dbPickup, setDbPickup] = useState<ShippingAddressInput | null>(null)\n useEffect(() => {\n if (!isPickup) return\n let alive = true\n void (async () => {\n // Prefere o banco; cai para a config. Ver o comentário em\n // StorefrontDeliveryConfig.pickupAddress para por que ainda há um fallback.\n const settings = await getShopProvider().getPublicStoreSettings?.().catch(() => null)\n if (alive && settings?.pickupAddress) setDbPickup(settings.pickupAddress)\n })()\n return () => { alive = false }\n }, [isPickup])\n const pickupAddress: ShippingAddressInput | null =\n dbPickup ?? (config.delivery?.pickupAddress as ShippingAddressInput | undefined) ?? null\n const [paidOrderId, setPaidOrderId] = useState<string | null>(null)\n const [error, setError] = useState<string | null>(null)\n const [discountCode, setDiscountCode] = useState('')\n const [discountError, setDiscountError] = useState<string | null>(null)\n const [discountSuccess, setDiscountSuccess] = useState<string | null>(null)\n const [applyingDiscount, setApplyingDiscount] = useState(false)\n const [showSignin, setShowSignin] = useState(false)\n const [placing, setPlacing] = useState(false)\n /**\n * Um pedido foi criado e a tela está indo embora — ver a guarda do carrinho\n * vazio. É um REF, não estado: `cart.clear()` re-renderiza pela assinatura do\n * zustand, fora do lote do React, então um `setState` aqui ainda não teria\n * sido aplicado quando a guarda rodasse — e o comprador ia parar no catálogo\n * com o pedido feito.\n */\n const leaving = React.useRef(false)\n const [zipLookup, setZipLookup] = useState<'idle' | 'loading' | 'found' | 'not-found'>('idle')\n\n const subtotal = selectSubtotal(cart)\n const discountTotal = selectDiscountTotal(cart)\n // Na retirada não há frete, e o número mostrado tem de ser o número cobrado:\n // o trigger da 0094 zera o frete no servidor, então uma tela que ainda somasse\n // a taxa prometeria um total que o pedido não teria — e o comprador veria a\n // diferença só no fim.\n const shippingRaw = selectShipping(cart, config)\n const shipping = isPickup ? 0 : shippingRaw\n const total = selectTotal(cart, config) - (isPickup ? shippingRaw : 0)\n\n const checkoutSlotContext = { subtotal, total }\n\n /**\n * Só existe cobrança quando há adquirente E o método escolhido é um que ele\n * sabe cobrar. Hoje isso é Pix: o cartão da AbacatePay não é transparente\n * (o /transparents/create recusa `CARD` com 422), então prometer cartão aqui\n * seria vender um caminho que termina em erro.\n *\n * \"Há adquirente\" olha PRIMEIRO para o que o lojista escolheu em Pagamentos\n * (`paymentProvider`) e só depois para o `mode` do documento da loja. O modo\n * é escrito no arquivo do app e nenhuma tela o edita — quem colasse a chave\n * do provedor veria absolutamente nada mudar, que é um beco sem saída.\n */\n /** O que a sessão de checkout congela. Memoizado porque `CheckoutPayment`\n * abre a cobrança UMA vez e um objeto novo a cada render abriria outra. */\n const checkoutSessionInput = React.useMemo(() => ({\n items: cart.lines.map((line) => ({\n productId: line.productId,\n variantId: line.variantId ?? null,\n quantity: line.quantity,\n optionsLabel: line.optionsLabel ?? null,\n })),\n // The document and the phone travel WITH the buyer, not only inside the\n // address.\n //\n // The acquirer charges a PERSON: Vindi refuses a charge with no document\n // (\"Informe o CPF ou CNPJ do comprador\"), and AbacatePay's customer block is\n // all-or-nothing — name, email, taxId and cellphone, or no customer at all.\n // With two of the four it had been opening charges while registering nobody,\n // which is the \"no client was created\" the store saw in the provider account.\n //\n // The field was already asked for on screen: with an acquirer connected,\n // `requires('document')` is true and nobody gets past step 1 without filling\n // it in. What was missing was forwarding it to whoever charges. On the ORDER\n // it still travels inside the address, because of shop_place_order's\n // signature — different roads.\n customer: {\n name: form.name.trim(),\n email: form.email.trim(),\n document: documentDigits(form.document) || undefined,\n phone: form.phone.trim() || undefined,\n },\n shippingAddress: deliveryAddress(),\n discountCode: cart.discountCode ?? null,\n paymentMethod,\n // Qual adquirente cobra. Sai dos ajustes da loja e não de uma escolha do\n // comprador — a função reconfere de qualquer forma, mas mandar daqui é o\n // que faz o clique bater na função do gateway que a loja realmente conectou.\n provider: policy?.paymentProvider ?? null,\n // The market (0116) the acquirer's open function prices and charges in.\n market: config.market?.code ?? null,\n country,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), [cart.lines, cart.discountCode, form, paymentMethod, policy?.paymentProvider, country, config.market?.code])\n\n /**\n * Quem sabe se a loja cobra é o SERVIDOR, e a resposta dele é o que vale.\n *\n * Antes isto dependia de duas configurações que o lojista tinha que acertar\n * em telas diferentes — o modo no documento do app e o provedor em\n * Pagamentos. Ele conectava a AbacatePay, voltava à loja e nada acontecia,\n * sem nenhuma pista do porquê. Agora o checkout TENTA abrir a cobrança e o\n * servidor responde; se não houver adquirente, ele avisa e a tela oferece o\n * pedido sem cobrança.\n *\n * A única configuração que ainda manda é a explícita: se o lojista nomeou um\n * provedor que a função não sabe cobrar, respeitamos a escolha dele.\n */\n /**\n * Formas que o servidor RECUSOU, por método e não em bloco.\n *\n * Era um booleano só, e virou este conjunto quando o cartão passou a poder ser\n * cobrado: \"a loja não aceita cartão\" desligava também o Pix, que a mesma loja\n * aceitava — e o comprador ficava sem a forma que funcionava por causa da que\n * não funcionava.\n */\n const [unavailable, setUnavailable] = useState<readonly PaymentMethodKind[]>([])\n /**\n * O cartão desta loja é cobrado online?\n *\n * Otimista de propósito: a loja tem adquirente e ninguém disse que não. Se o\n * adquirente recusar cartão — o lojista não habilitou —, a tela cai no pedido\n * sem cobrança, que é o que sempre fez, e este texto some junto.\n */\n const cardIsCharged =\n // Outside Brazil a card is charged online only by a real acquirer: with no\n // provider the online panel is the mock's Pix, which a Spanish buyer cannot\n // pay. Without one the order is placed pending, as an offline payment is.\n (isBrazil || !!policy?.paymentProvider)\n && !unavailable.includes('credit_card')\n && (!policy?.paymentProvider || isChargeableProvider(policy.paymentProvider))\n // ...and the acquirer has to charge CARDS, not merely exist. AbacatePay shut\n // card down for new accounts: asking anyway does not answer \"no card\", it\n // answers with an error — and before this line the buyer only found out after\n // choosing, waiting, and taking a refusal in the face.\n && (!policy?.paymentProvider || supportsCard(policy.paymentProvider))\n const acquirerMissing = unavailable.includes(paymentMethod)\n const chargesOnline =\n // Pix é cobrado dentro da loja; cartão é pago na página do adquirente e\n // volta para cá. Débito, dinheiro e \"combinar\" nunca foram cobrança online.\n // `cardIsCharged` rather than a bare `credit_card`: card is charged online\n // only where the acquirer charges cards. Where it does not, this screen\n // offers the order without a charge — the card-reader road, as it always was.\n (paymentMethod === 'pix' || (paymentMethod === 'credit_card' && cardIsCharged))\n && !acquirerMissing\n // A lista deixou de morar aqui: cada adquirente tem UM par de funções, e a\n // tabela que diz qual é qual vive no @fayz-ai/shop, ao lado de quem as chama.\n // Duas cópias eram uma vitrine que oferece QR para um gateway que o provider\n // não sabe acionar, ou o contrário.\n && (!policy?.paymentProvider || isChargeableProvider(policy.paymentProvider))\n const money = (value: number) => formatMoney(value, config.currency, config.locale)\n\n useEffect(() => {\n // Os dois desfechos esvaziam o carrinho de propósito — o passo 4 e o pedido\n // sem cobrança — e sem esta guarda o comprador era mandado ao catálogo no\n // instante em que a compra deu certo, em vez da tela do pedido dele.\n // `resume` segura a guarda: o carrinho pode ter sido esvaziado nesta aba\n // enquanto a pessoa pagava na outra, e mandar para o catálogo alguém que\n // está voltando de um pagamento é perder a compra na porta.\n if (cart.lines.length === 0 && !paidOrderId && !leaving.current && !resume) navigateTo(config.catalogPath)\n }, [cart.lines.length, config.catalogPath, paidOrderId, resume])\n\n\n /**\n * Editar qualquer campo apaga o erro na hora.\n *\n * Sem isto a mensagem sobrevivia ao conserto: o CEP preenchia a UF sozinho e\n * \"Informe a UF com duas letras\" continuava em vermelho embaixo de um campo\n * escrito SP, até a pessoa clicar em continuar de novo para descobrir que já\n * estava certo.\n */\n const set = (key: keyof CheckoutForm) => (value: string) => {\n setError(null)\n setForm((current) => ({ ...current, [key]: value }))\n }\n\n /**\n * Editing the CEP re-fetches the address and refills what the postal service\n * knows, leaving number and complement alone — those are the buyer's and must\n * survive a correction to the postcode.\n *\n * Only what the lookup can supply is overwritten. Silently keeping a stale\n * street from a previous CEP is worse than an empty one: the parcel goes to\n * the wrong place and everything on screen looks filled in.\n */\n async function setZip(value: string) {\n const masked = formatPostalCode(value, country)\n setError(null)\n setForm((current) => ({ ...current, zip: masked }))\n if (!countrySchema.postal.pattern.test(normalizePostalCode(masked, country))) {\n setZipLookup('idle')\n return\n }\n setZipLookup('loading')\n // Pergunta à loja se ela entrega aí, e não só ao serviço postal.\n //\n // O checkout apenas LIA a resposta que o simulador da vitrine tinha deixado\n // no caminho — quem digitava o CEP direto aqui passava batido pelo aviso e\n // só descobria a recusa no fim, quando o servidor negava o pedido. É a\n // mesma pergunta que a loja já faz na página do produto, feita no momento\n // em que a pessoa escreve o endereço.\n void delivery.resolve(masked, subtotal, country)\n try {\n const found = await lookupPostalCode(masked, country)\n if (!found) {\n setZipLookup('not-found')\n return\n }\n setZipLookup('found')\n setForm((current) => ({\n ...current,\n street: found.street || current.street,\n district: found.district || current.district,\n city: found.city || current.city,\n state: found.state,\n }))\n } catch {\n // Offline or the provider is down — the buyer can still type it out.\n setZipLookup('idle')\n }\n }\n\n async function applyDiscountCode() {\n setApplyingDiscount(true)\n setDiscountError(null)\n setDiscountSuccess(null)\n try {\n const appliedCode = discountCode.trim().toUpperCase()\n const result = await validateDiscount(discountCode)\n if (result.valid) {\n cart.applyDiscount(appliedCode, result.percent, { freeShipping: result.freeShipping })\n setDiscountCode(appliedCode)\n // What the coupon actually does. A free_shipping code discounts 0% of\n // the subtotal, so announcing a percentage would read as a bug.\n const effect = result.freeShipping ? t('discount.freeShipping') : t('discount.percentOff', { percent: result.percent })\n setDiscountSuccess(t('discount.applied', { code: appliedCode, effect }))\n toast.success(t('discount.appliedToast'), `${appliedCode} • ${effect}`)\n } else {\n setDiscountError(result.message ?? t('discount.invalid'))\n toast.error(t('discount.invalidToast'), result.message ?? t('discount.checkCode'))\n }\n } finally {\n setApplyingDiscount(false)\n }\n }\n\n function clearDiscountCode() {\n cart.clearDiscount()\n setDiscountCode('')\n setDiscountSuccess(null)\n setDiscountError(null)\n }\n\n // The signed-in shopper's real address book. RLS scopes it to them, so a\n // guest (or a customer whose account was never linked to an auth identity)\n // simply gets nothing back and types their address.\n useEffect(() => {\n const customerId = session.customerId\n if (!customerId) {\n setSavedAddresses([])\n setAddressMode('new')\n setAddressesLoading(false)\n return\n }\n let cancelled = false\n const provider = getShopProvider()\n // Checked before showing the skeleton: `?.` short-circuits the whole chain,\n // so a provider without an address book would never reach `.finally`.\n const listAddresses = provider.listCustomerAddresses?.bind(provider)\n if (!listAddresses) {\n setAddressesLoading(false)\n return\n }\n setAddressesLoading(true)\n void listAddresses(customerId)\n .then((addresses) => {\n if (cancelled || addresses.length === 0) return\n setSavedAddresses(addresses)\n const here = addresses.find((address) => (address.country ?? 'BR') === country)\n if (here) applySavedAddress(here)\n })\n .catch(() => {})\n .finally(() => {\n if (!cancelled) setAddressesLoading(false)\n })\n return () => {\n cancelled = true\n }\n }, [session.customerId])\n\n // Telefone e CPF de quem entrou.\n //\n // A sessão guarda `customerId`, `email` e `name` e nada mais, então entrar\n // preenchia duas caixas e deixava as outras duas em branco — todas as vezes,\n // para a mesma pessoa, que já as tinha digitado no pedido anterior. Não é um\n // campo esquecido num `setForm`: o contrato de `onSignedIn` tem só dois\n // campos, e por isso o buraco volta sempre que alguém adiciona um terceiro.\n //\n // Buscado pelo id em vez de guardado na sessão de propósito: a sessão é\n // persistida em localStorage (`fayz.storefront.session.v1`), e CPF é\n // exatamente o tipo de dado que não deve ficar lá para qualquer script da\n // página ler. O banco já tem, e a RLS já responde só sobre o próprio cliente.\n //\n // Só preenche o que está VAZIO: quem está digitando quando a resposta chega\n // não pode ver o que escreveu ser substituído.\n useEffect(() => {\n const customerId = session.customerId\n setContactKnown(false)\n if (!customerId) return\n const provider = getShopProvider()\n const getCustomer = provider.getCustomer?.bind(provider)\n // The profile (shop 0133) answers for the signed-in buyer even where the\n // customer table is not readable to them, and it already folds in the\n // phone and CPF of the last order. The customer read stays as the fallback.\n const getMyProfile = provider.getMyProfile?.bind(provider)\n let cancelled = false\n const fill = (c: { firstName?: string | null; lastName?: string | null; email?: string | null; phone?: string | null; document?: string | null } | null) => {\n if (cancelled || !c) return\n setForm((current) => ({\n ...current,\n phone: current.phone || c.phone || '',\n document: current.document || (c.document ? formatDocument(c.document) : ''),\n email: current.email || c.email || '',\n name:\n current.name ||\n [c.firstName, c.lastName].filter(Boolean).join(' ').trim(),\n }))\n }\n void (async () => {\n const profile = getMyProfile ? await getMyProfile().catch(() => null) : null\n fill(profile)\n if (getCustomer && (!profile || !profile.phone || !profile.document)) {\n fill(await getCustomer(customerId).catch(() => null))\n }\n if (!cancelled) setContactKnown(true)\n })()\n return () => {\n cancelled = true\n }\n }, [session.customerId])\n\n // A Spanish address is not a Brazilian one with a different label: switching\n // country empties the address and lets the new country's form start clean.\n // Declared BEFORE the prefill below on purpose: effects run in order, so a\n // switch clears first and the prefill then refills with this country's code.\n const shownCountry = React.useRef(country)\n useEffect(() => {\n if (shownCountry.current === country) return\n shownCountry.current = country\n setZipLookup('idle')\n addNewAddress()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [country])\n const addressesHere = savedAddresses.filter((address) => (address.country ?? 'BR') === country)\n\n /**\n * The CEP given back on the product page lands here.\n *\n * This is the payoff of the whole delivery flow: street, district, city and\n * UF arrive filled and the buyer types a house number. It only fires when no\n * saved address was selected — a signed-in shopper's own address book still\n * wins over a postcode lookup, because it also knows their number and\n * complement, which no postal service can supply.\n */\n useEffect(() => {\n if (addressMode !== 'new') return\n // O endereço que a pessoa SALVOU no cardápio vem primeiro: ele traz número\n // e complemento, que consulta de CEP nenhuma devolve — e são justamente os\n // dois campos que sobravam para digitar. Sem isto, salvar endereço no\n // cardápio economizava a rua e cobrava o resto de novo no checkout.\n const keptAny = delivery.savedAddresses.find((a) => a.id === delivery.selectedAddressId)\n const kept = keptAny && (keptAny.country ?? 'BR') === country ? keptAny : undefined\n const looked = delivery.address && (delivery.address.country || 'BR') === country ? delivery.address : null\n if (!kept && !looked) return\n setForm((current) => {\n if (current.zip.trim() || current.street.trim()) return current\n if (kept) {\n return {\n ...current,\n zip: formatPostalCode(kept.postalCode, country),\n street: kept.street,\n number: kept.number,\n complement: kept.complement ?? '',\n district: kept.district,\n city: kept.city,\n state: kept.state,\n }\n }\n return {\n ...current,\n zip: formatPostalCode(looked!.postalCode, country),\n street: looked!.street,\n district: looked!.district,\n city: looked!.city,\n state: looked!.state,\n }\n })\n }, [delivery.address, delivery.savedAddresses, delivery.selectedAddressId, addressMode, country])\n\n function applySavedAddress(address: CustomerAddress) {\n setAddressMode('saved')\n setSelectedAddressId(address.id)\n setForm((current) => ({\n ...current,\n street: address.street,\n city: address.city,\n zip: address.postalCode,\n number: address.number ?? '',\n complement: address.complement ?? '',\n district: address.district ?? '',\n state: address.state,\n // Kept from the book when it has one, and NOT cleared when it does not:\n // a shopper who just typed their phone should not lose it by picking a\n // saved address that predates the field.\n phone: address.phone ?? current.phone,\n }))\n }\n\n function selectAddress(addressId: string) {\n const address = savedAddresses.find((item) => item.id === addressId)\n if (address) applySavedAddress(address)\n }\n\n function addNewAddress() {\n setAddressMode('new')\n setSelectedAddressId('new')\n setForm((current) => ({ ...current, street: '', city: '', zip: '', number: '', complement: '', district: '', state: '' }))\n }\n\n /**\n * Diz o que está errado E leva o comprador até lá.\n *\n * A mensagem sozinha não bastava: num formulário desta altura o campo com\n * problema fica fora da tela (medido: o e-mail em y=-139 com o erro visível\n * embaixo), e o foco ficava no `body`. A pessoa lia \"informe um e-mail\n * válido\" e tinha que caçar qual campo. É a regra de focus-management do\n * WCAG, e aqui ela é a diferença entre corrigir e desistir.\n */\n function fail(message: string, testId?: string): false {\n setError(message)\n trackStorefront('checkout_error', { step, field: testId ?? null, reason: message })\n if (testId) {\n const field = document.querySelector<HTMLElement>(`[data-testid=\"${testId}\"]`)\n field?.scrollIntoView({ block: 'center', behavior: prefersReducedMotion() ? 'auto' : 'smooth' })\n field?.focus({ preventScroll: true })\n }\n return false\n }\n\n /**\n * O passo 1 valida só o que o passo 1 pede.\n *\n * Antes tudo era validado no último clique, então quem errava o e-mail\n * descobria depois de preencher o endereço inteiro. Cada passo agora responde\n * pelo que ele mesmo coletou — e `validate()` continua rodando inteiro antes\n * de cobrar, porque o servidor não confia na navegação.\n */\n function validateContact(): boolean {\n setError(null)\n if (requiresAccount && !session.customerId) {\n setShowSignin(true)\n return fail(t('error.requiresAccount'))\n }\n if (!form.email.trim() || !/.+@.+\\..+/.test(form.email)) {\n return fail(t('error.email'), TID.checkoutEmail)\n }\n if (!form.name.trim()) return fail(t('error.name'), TID.checkoutName)\n if (requires('phone') && !form.phone.trim()) {\n return fail(t('error.phone'), 'checkout-phone')\n }\n return validateDocument()\n }\n\n /** Step 1 already holds everything it asks for — the same rules as\n * validateContact, without raising an error. */\n function contactComplete(): boolean {\n if (!session.customerId) return false\n if (!form.email.trim() || !/.+@.+\\..+/.test(form.email)) return false\n if (!form.name.trim()) return false\n const phone = form.phone.replace(/\\D/g, '')\n if (requires('phone') && phone.length < 10) return false\n if (shows('phone') && !phone) return false\n if (isBrazil) {\n if (requires('document') && !isValidDocument(form.document)) return false\n if (shows('document') && !isValidDocument(form.document)) return false\n }\n return true\n }\n const contactAsCard = !editingContact && contactKnown && contactComplete()\n // Nothing to type in «Dados»: open on «Entrega» (or «Pagamento» for a\n // pickup), once. «Dados» stays a completed step the buyer can reopen.\n useEffect(() => {\n if (skippedContact.current || step !== 1 || !contactAsCard) return\n skippedContact.current = true\n setStep(isPickup ? 3 : 2)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [contactAsCard, step])\n\n /** The buyer's tax id, by the country's rule: a CPF/CNPJ in Brazil when the\n * store needs one; elsewhere checked only if the buyer gave it. */\n function validateDocument(): boolean {\n if (isBrazil) {\n if (requires('document') && !isValidDocument(form.document)) {\n return fail(\n form.document.trim() ? t('error.documentInvalid') : t('error.documentMissing'),\n TID.checkoutDocument,\n )\n }\n return true\n }\n const taxId = countrySchema.taxId\n if (!form.document.trim()) {\n return requires('document') ? fail(t('error.documentMissing'), TID.checkoutDocument) : true\n }\n if (taxId && !taxId.validate(form.document)) return fail(t('error.taxIdInvalid'), TID.checkoutDocument)\n return true\n }\n\n /**\n * The address, by the country's form. Brazil keeps its own checks and\n * messages, in their order; other countries read their schema.\n */\n function validateAddressFields(): boolean {\n if (isBrazil) {\n if (!form.street.trim() || !form.city.trim() || !form.zip.trim() || !form.district.trim()) {\n return fail(t('error.address'), TID.checkoutStreet)\n }\n if (!form.number.trim()) return fail(t('error.number'), 'checkout-number')\n if (requires('complement') && !form.complement.trim()) {\n return fail(t('error.complement'), 'checkout-complement')\n }\n if (!/^[A-Za-z]{2}$/.test(form.state.trim())) {\n return fail(t('error.state'), 'checkout-state')\n }\n return true\n }\n const errors = validateAddress(\n { postalCode: form.zip, street: form.street, complement: form.complement, city: form.city, state: form.state },\n country,\n { complement: requires('complement') },\n )\n if (errors.postalCode === 'invalid') {\n return fail(t('error.postalInvalid', { example: countrySchema.postal.example }), TID.checkoutZip)\n }\n if (errors.postalCode || errors.street || errors.city) return fail(t('error.address'), errors.postalCode ? TID.checkoutZip : TID.checkoutStreet)\n if (errors.complement) return fail(t('error.complement'), 'checkout-complement')\n if (errors.region) {\n const label = countrySchema.fields.find((f) => f.key === 'region')?.label[config.language] ?? ''\n return fail(t('error.region', { label: label.toLowerCase() }), 'checkout-state')\n }\n return true\n }\n\n /** O passo 2: para onde vai, e se a loja entrega lá. */\n function validateDelivery(): boolean {\n setError(null)\n if (isPickup) return true\n if (!selectRequiresShipping(cart)) return true\n if (!validateAddressFields()) return false\n if (\n delivery.status === 'unserved'\n && delivery.postalCode === normalizePostalCode(form.zip, country)\n ) {\n return fail(delivery.refusedZone ? t('error.refusedZone') : t('error.unserved'), TID.checkoutZip)\n }\n return true\n }\n\n function goToStep(next: CheckoutStep) {\n setError(null)\n setStep(next)\n // O topo, sempre: o passo seguinte começa onde os olhos já estão.\n if (typeof window !== 'undefined') window.scrollTo({ top: 0, behavior: 'smooth' })\n }\n\n\n /**\n * O endereço que vai no pedido.\n *\n * Na RETIRADA é o balcão da loja, e isso não é um contorno: `shop_place_order`\n * exige CEP quando a loja tem zonas (0021) e essa checagem roda ANTES de\n * qualquer trigger de linha, então o pedido precisa de um endereço válido —\n * e o endereço válido de uma retirada é o lugar onde a mercadoria vai ficar\n * esperando. O trigger da 0094 reconhece o modo e zera o frete.\n *\n * Sem balcão declarado a retirada não deveria ter sido oferecida; cai no que\n * o comprador digitou em vez de mandar um endereço vazio.\n */\n function orderAddress(): ShippingAddressInput {\n if (isPickup && pickupAddress) {\n return {\n ...pickupAddress,\n phone: form.phone.trim() || undefined,\n document: documentDigits(form.document) || undefined,\n }\n }\n return deliveryAddress()\n }\n\n function deliveryAddress(): ShippingAddressInput {\n return toShippingAddress(form, country)\n }\n\n function advance() {\n if (step === 1 && validateContact()) {\n // «Alterar» saved: the profile learns it, so the next checkout starts on\n // the card again. Fire-and-forget like the contact memory below.\n if (editingContact && session.customerId) {\n void getShopProvider().saveMyProfile?.({\n name: form.name.trim(),\n phone: form.phone.trim() || null,\n document: documentDigits(form.document) || null,\n }).catch(() => {})\n setEditingContact(false)\n }\n // Remember the contact BEFORE the sale, not after it. The store used to\n // learn a buyer's document only when an order completed and never learned\n // their phone at all, so a signed-in customer retyped both on every visit —\n // and an abandoned checkout taught it nothing. Fire-and-forget: a store\n // that cannot remember must still be able to sell.\n void getShopProvider().saveCustomerContact?.({\n phone: form.phone.trim() || null,\n document: documentDigits(form.document) || null,\n })\n // Na retirada não existe passo de entrega: o endereço é o balcão, e a\n // loja já sabe onde ele fica. Perguntar o CEP de quem vem buscar é pedir\n // um dado que ninguém vai usar.\n goToStep(isPickup ? 3 : 2)\n }\n else if (step === 2 && validateDelivery()) goToStep(3)\n }\n\n /**\n * O pedido sem cobrança online.\n *\n * Não é um caminho de segunda: é o de quase toda a frota — dinheiro na\n * entrega, maquininha do entregador, \"combinar com a loja\". O pedido nasce\n * `pending` e ninguém comemora; quem confirma que o dinheiro entrou é o\n * lojista, na tela dele.\n */\n async function confirmWithoutCharge() {\n if (!validate()) return\n setPlacing(true)\n try {\n const { order, customerId } = await placeStorefrontOrder({\n config,\n cart,\n session,\n customer: { email: form.email, name: form.name },\n // `notes` é o recado do comprador para a loja, e o ponto de referência\n // é exatamente isso: \"portão azul, ao lado da padaria\" não cabe em\n // nenhum campo estruturado do endereço e é o que o entregador lê.\n address: {\n street: form.street,\n city: form.city,\n zip: form.zip,\n notes: deliveryReference || undefined,\n },\n // Viaja com o `document` dentro: a assinatura do shop_place_order não\n // pode ganhar parâmetro sem DROP (0050), e uma trigger o levanta para a\n // coluna. Na retirada este endereço é o balcão — ver orderAddress().\n shippingAddress: orderAddress(),\n // Entrega/retirada e agendamento (0094) vão AQUI porque esta tela chama\n // placeStorefrontOrder direto, sem passar pelo useCheckout — e sem esta\n // linha o pedido nascia sem `fulfillment_type`, com a retirada\n // indistinguível de uma entrega e o frete cobrado assim mesmo. Foi um\n // pedido de teste real (#1379) que mostrou isso.\n fulfillmentType,\n scheduledFor: scheduledFor ?? undefined,\n paymentMethod,\n })\n // placeStorefrontOrder resolve/cria o cliente mas não guarda a sessão —\n // sem isto \"Minhas compras\" logo depois consulta por e-mail, que anon não\n // lê sob RLS, e volta vazio.\n if (customerId) session.setSession({ customerId, email: form.email, name: form.name })\n leaving.current = true\n trackStorefront('checkout_completed', {\n order_id: order.id,\n payment_method: paymentMethod,\n fulfillment: fulfillmentType ?? 'delivery',\n total,\n online_payment: false,\n })\n cart.clear()\n navigateTo(`/order/${order.id}`)\n } catch (err) {\n setError(placeOrderMessage(err, t))\n trackStorefront('checkout_error', { step, field: 'place_order', reason: placeOrderMessage(err, t) })\n setPlacing(false)\n }\n }\n\n function validate(): boolean {\n setError(null)\n // Checked FIRST: it is the only refusal the server will also make, so\n // finding it out here saves the shopper a completed form and a raw SQL error.\n if (requiresAccount && !session.customerId) {\n setShowSignin(true)\n return fail(t('error.requiresAccount'))\n }\n if (!form.email.trim() || !/.+@.+\\..+/.test(form.email)) {\n return fail(t('error.email'), TID.checkoutEmail)\n }\n if (requires('phone') && !form.phone.trim()) {\n return fail(t('error.phone'), 'checkout-phone')\n }\n if (!form.name.trim()) {\n return fail(t('error.name'), TID.checkoutName)\n }\n // Checked here rather than at the gateway: a wrong CPF comes back from the\n // acquirer as a generic decline, and the buyer has no way to know which\n // field to fix.\n if (!validateDocument()) return false\n // Na RETIRADA não há endereço a validar: o pedido vai para o balcão, e o\n // formulário de entrega nunca foi mostrado.\n if (isPickup) return true\n // Number, district and UF are required in Brazil because a courier cannot\n // deliver without them; other countries require what their form has.\n if (!validateAddressFields()) return false\n // Coverage. shop_place_order refuses an unserved postal code anyway (0021),\n // so this only turns a raw SQL error into a sentence the buyer can act on.\n // A cart that ships nothing never quotes, so \"unserved\" here means \"nobody\n // asked\", not \"we don't go there\".\n if (\n selectRequiresShipping(cart) &&\n delivery.status === 'unserved' &&\n delivery.postalCode === normalizePostalCode(form.zip, country)\n ) {\n // An EXCLUDED region reads differently on purpose (0048): \"ainda não\" is a\n // promise about the future, and a store that deliberately refuses a region\n // is not making it.\n return fail(delivery.refusedZone ? t('error.refusedZone') : t('error.unserved'), TID.checkoutZip)\n }\n return true\n }\n\n\n return (\n <main className=\"min-h-screen bg-background\">\n <Slot area=\"checkout\" name=\"beforeForm\" context={checkoutSlotContext} />\n {showSignin && !session.email && (\n <SignInModal\n defaultEmail={form.email}\n onClose={() => setShowSignin(false)}\n onSignedIn={(signed) =>\n setForm((current) => ({ ...current, email: signed.email ?? current.email, name: signed.name || current.name }))\n }\n />\n )}\n <header className=\"border-b bg-background\">\n <div className=\"mx-auto flex max-w-6xl items-center justify-between gap-4 px-4 py-6 sm:px-6\">\n <Link to={returnPath(config)} className=\"text-sm text-muted-foreground hover:text-foreground\">\n {t('checkout.backToStore')}\n </Link>\n <div className=\"text-center\">\n <div className=\"sf-heading text-2xl font-bold tracking-tight\">{config.logo ?? config.name}</div>\n <div className=\"mt-2 flex items-center justify-center gap-2 text-xs text-muted-foreground\">\n <Lock className=\"h-3.5 w-3.5\" />\n {t('checkout.secure')}\n </div>\n </div>\n <a href=\"mailto:suporte@example.com\" className=\"text-sm text-muted-foreground hover:text-foreground\">\n {t('checkout.help')}\n </a>\n </div>\n </header>\n\n <div className=\"mx-auto grid max-w-6xl grid-cols-1 gap-8 px-4 py-8 sm:px-6 lg:grid-cols-5 lg:px-6\">\n <section className=\"lg:col-span-3 lg:pr-10\">\n <CheckoutSteps\n current={step}\n omit={isPickup ? [2] : undefined}\n // Na retirada o passo 2 não existe: voltar para ele cairia num\n // formulário de endereço que a própria tela acabou de dizer que não\n // era necessário. Volta para os dados.\n onGoBackTo={\n step === 4\n ? undefined\n : (target) => goToStep(isPickup && target === 2 ? 1 : target)\n }\n />\n\n {/* Um <form> de verdade: é ele que faz o Enter num campo avançar o\n passo, em vez de não fazer nada. O passo 3 não submete — quem manda\n ali é a cobrança. */}\n <form\n className=\"space-y-8\"\n onSubmit={(event) => {\n event.preventDefault()\n advance()\n }}\n >\n {step === 1 && (\n <section>\n <div className=\"mb-3 flex items-center justify-between gap-4\">\n <h1 className=\"text-xl font-semibold tracking-tight\">{t('checkout.contact.title')}</h1>\n {session.email ? (\n <span className=\"text-sm text-muted-foreground\">{t('checkout.contact.signedInAs', { email: session.email })}</span>\n ) : (\n <button\n type=\"button\"\n onClick={() => setShowSignin((value) => !value)}\n className=\"text-sm font-medium text-primary hover:underline\"\n >\n {t('checkout.contact.haveAccount')}\n </button>\n )}\n </div>\n {contactAsCard ? (\n <ContactSummary\n name={form.name}\n email={form.email}\n phone={shows('phone') ? form.phone : undefined}\n document={shows('document') ? form.document : undefined}\n onEdit={() => setEditingContact(true)}\n onSignOut={() => {\n void signOutCustomer().finally(() => {\n setForm((current) => ({ ...current, email: '', name: '', phone: '', document: '' }))\n setEditingContact(false)\n })\n }}\n labels={{ edit: t('checkout.contact.edit'), notYou: t('checkout.contact.notYou'), signOut: t('checkout.contact.signOut') }}\n />\n ) : (\n <div className=\"grid gap-3 sm:grid-cols-2\">\n {field(t('checkout.contact.email'), TID.checkoutEmail, form.email, set('email'), {\n type: 'email',\n placeholder: t('checkout.contact.email'),\n // The account's address: an order under another e-mail would\n // not show up in this buyer's «Meus pedidos».\n ...(session.customerId && session.email ? { readOnly: true, title: t('checkout.contact.emailLocked'), className: 'w-full rounded-lg border bg-muted/40 px-3.5 py-3 text-sm text-muted-foreground outline-none' } : {}),\n })}\n {field(t('checkout.contact.name'), TID.checkoutName, form.name, set('name'), {\n placeholder: t('checkout.contact.name'),\n })}\n {shows('phone') && field(t('checkout.contact.phone'), 'checkout-phone', form.phone, set('phone'), {\n type: 'tel',\n autoComplete: 'tel',\n placeholder: requires('phone') ? t('checkout.contact.phone') : t('checkout.contact.phoneOptional'),\n })}\n {shows('document') && (isBrazil ? field(\n t('checkout.contact.document'),\n TID.checkoutDocument,\n form.document,\n (value) => {\n setError(null)\n setForm((current) => ({ ...current, document: formatDocument(value) }))\n },\n {\n // `inputMode` and not `type=\"number\"`: the mask writes dots\n // and a dash, which a number input silently refuses to hold.\n inputMode: 'numeric',\n autoComplete: 'off',\n placeholder: requires('document') ? t('checkout.contact.document') : t('checkout.contact.documentOptional'),\n },\n ) : field(\n // The country's own tax id (Spain: NIF/NIE), unmasked: it has letters.\n countrySchema.taxId?.label[config.language] ?? t('checkout.contact.documentOptional'),\n TID.checkoutDocument,\n form.document,\n set('document'),\n { autoComplete: 'off', placeholder: countrySchema.taxId?.label[config.language] ?? '' },\n ))}\n </div>\n )}\n {requiresAccount && !session.customerId && (\n <p className=\"mt-3 rounded-lg border border-primary/30 bg-primary/5 px-3 py-2 text-sm\">\n {t('checkout.contact.requiresAccount')}{' '}\n <button\n type=\"button\"\n onClick={() => setShowSignin(true)}\n className=\"font-semibold text-primary hover:underline\"\n >\n {t('checkout.contact.signInOrCreate')}\n </button>\n </p>\n )}\n </section>\n )}\n\n {step === 2 && (\n <section>\n <h2 className=\"mb-3 text-xl font-semibold tracking-tight\">{t('checkout.address.title')}</h2>\n {buyer.allowed.length > 1 && (\n <CountrySelect className=\"mb-3\" country={country} allowed={buyer.allowed} onChange={buyer.setCountry} />\n )}\n <div className=\"mb-3 grid gap-3\">\n {addressesLoading && savedAddresses.length === 0 && (\n <SkeletonGroup label={t('checkout.address.loadingSaved')} className=\"grid gap-3\">\n {[0, 1].map((row) => (\n <div key={row} className=\"rounded-lg border p-3\">\n <Skeleton className=\"h-4 w-28\" />\n <Skeleton className=\"mt-2 h-3 w-3/4\" />\n <Skeleton className=\"mt-1.5 h-3 w-1/2\" />\n </div>\n ))}\n </SkeletonGroup>\n )}\n {addressesHere.map((address) => (\n <div\n key={address.id}\n className={`group relative rounded-lg border p-3 pr-11 text-left text-sm transition hover:bg-muted/40 ${\n selectedAddressId === address.id ? 'border-primary bg-primary/5' : 'border-border bg-background'\n }`}\n >\n <button type=\"button\" onClick={() => selectAddress(address.id)} className=\"block w-full text-left\">\n <span className=\"flex items-center justify-between gap-3 font-semibold\">\n {address.label}\n {addressMode === 'saved' && selectedAddressId === address.id && (\n <span className=\"rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-bold text-primary\">{t('checkout.address.selected')}</span>\n )}\n </span>\n <span className=\"mt-1 block text-muted-foreground\">\n {[address.street, address.number].filter(Boolean).join(', ')}\n {address.complement ? ` — ${address.complement}` : ''}\n </span>\n <span className=\"block text-muted-foreground\">\n {[address.district, address.city, address.state].filter(Boolean).join(' · ')} — {address.postalCode}\n </span>\n </button>\n </div>\n ))}\n <button\n type=\"button\"\n onClick={addNewAddress}\n className={`rounded-lg border border-dashed p-3 text-left text-sm transition hover:bg-muted/40 ${\n addressMode === 'new' ? 'border-primary bg-primary/5' : 'border-border bg-muted/20'\n }`}\n >\n <span className=\"block font-semibold text-primary\">\n {addressesHere.length > 0 ? t('checkout.address.addNew') : t('checkout.address.enter')}\n </span>\n <span className=\"mt-1 block text-muted-foreground\">{t('checkout.address.enterHint')}</span>\n </button>\n </div>\n {addressMode === 'new' && (\n <AddressForm\n country={country}\n language={config.language}\n value={form}\n onChange={(key, value) => set(key)(value)}\n onPostalCode={setZip}\n lookup={zipLookup}\n complement={{ visible: shows('complement'), required: requires('complement') }}\n />\n )}\n </section>\n )}\n\n {/* While the server creates the order, the screen is the shape of the\n order page it is about to land on. */}\n {step === 3 && placing && (\n <section>\n <h2 className=\"mb-3 text-xl font-semibold tracking-tight\">{t('checkout.confirming.title')}</h2>\n <SkeletonGroup label={t('checkout.confirming.label')} className=\"rounded-xl border bg-card p-6 sm:p-8\">\n <div className=\"grid gap-6 border-b pb-6 sm:grid-cols-[120px_minmax(0,1fr)]\">\n <Skeleton className=\"mx-auto h-24 w-24 rounded-full\" />\n <div>\n <Skeleton className=\"h-7 w-56 max-w-full\" />\n <Skeleton className=\"mt-2 h-3.5 w-full max-w-sm\" />\n <Skeleton className=\"mt-4 h-5 w-40\" />\n </div>\n </div>\n <div className=\"mt-6 grid gap-4 rounded-xl border bg-muted/20 p-4 sm:grid-cols-3\">\n {[0, 1, 2].map((column) => (\n <div key={column}>\n <Skeleton className=\"h-3 w-16\" />\n <Skeleton className=\"mt-2 h-4 w-24\" />\n </div>\n ))}\n </div>\n <div className=\"mt-8 space-y-3\">\n {cart.lines.slice(0, 3).map((line) => (\n <div key={line.lineId ?? line.productId} className=\"flex items-center gap-3\">\n <Skeleton className=\"h-12 w-12 rounded-lg\" />\n <Skeleton className=\"h-3.5 flex-1\" />\n <Skeleton className=\"h-3.5 w-16\" />\n </div>\n ))}\n </div>\n </SkeletonGroup>\n <p className=\"mt-3 text-center text-sm text-muted-foreground\">\n {t('checkout.confirming.keepOpen')}\n </p>\n </section>\n )}\n\n {step === 3 && !placing && (\n <section>\n <h2 className=\"mb-3 text-xl font-semibold tracking-tight\">{t('checkout.payment.title')}</h2>\n <div className=\"mb-3 grid gap-3\" role=\"radiogroup\" aria-label={t('checkout.payment.label')}>\n {paymentMethods.map((method) => {\n const base = { label: t(PAYMENT_LABELS[method].label), hint: t(PAYMENT_LABELS[method].hint) }\n // A loja que tem adquirente cobra o cartão na página segura\n // dele; a que não tem, cobra na entrega. É a mesma opção com\n // dois desfechos, e o comprador tem que ler o certo antes de\n // escolher — não depois, quando a tela redirecionar.\n const copy = method === 'credit_card' && cardIsCharged\n ? { ...base, hint: t('checkout.payment.cardOnline') }\n : base\n const selected = paymentMethod === method\n return (\n // Cada forma de pagamento abre o que ELA pede, embaixo dela\n // mesma. Antes o painel do Pix ficava no fim da lista, longe\n // do cartão escolhido, e escolher parecia não fazer nada.\n <div key={method}>\n <button\n type=\"button\"\n role=\"radio\"\n aria-checked={selected}\n data-testid={`checkout-payment-${method}`}\n onClick={() => {\n setPaymentMethod(method)\n if (method !== paymentMethod) trackStorefront('checkout_payment_selected', { payment_method: method })\n }}\n className={`w-full rounded-lg border p-3 text-left text-sm transition hover:bg-muted/40 ${\n selected ? 'border-primary bg-primary/5' : 'border-border bg-background'\n }`}\n >\n <span className=\"flex items-center justify-between gap-3 font-semibold\">\n <span className=\"flex items-center gap-2\"><CreditCard className=\"h-4 w-4\" />{copy.label}</span>\n {selected && (\n <span className=\"rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-bold text-primary\">{t('checkout.address.selected')}</span>\n )}\n </span>\n <span className=\"mt-1 block text-muted-foreground\">{copy.hint}</span>\n </button>\n {selected && chargesOnline && (\n <div className=\"mt-3\">\n <CheckoutPayment\n input={checkoutSessionInput}\n money={money}\n // The cart's own total, needed BEFORE a charge exists:\n // an in-store card form prices its installment options\n // from it, and the server recomputes the real figure\n // when the token is spent.\n amount={total}\n onBack={() => goToStep(2)}\n resume={resume}\n onUnavailable={() => setUnavailable((list) =>\n list.includes(method) ? list : [...list, method])}\n onPaid={(orderId) => {\n // O ref ANTES do clear: `paidOrderId` é estado do\n // React e o carrinho re-renderiza fora do lote,\n // então a guarda podia mandar para o catálogo\n // alguém que acabou de pagar.\n leaving.current = true\n setPaidOrderId(orderId)\n trackStorefront('checkout_completed', {\n order_id: orderId,\n payment_method: method,\n fulfillment: fulfillmentType ?? 'delivery',\n total,\n online_payment: true,\n })\n goToStep(4)\n cart.clear()\n }}\n />\n </div>\n )}\n </div>\n )\n })}\n </div>\n <Slot area=\"checkout\" name=\"afterPaymentMethods\" context={checkoutSlotContext} />\n\n {/* Loja que NÃO cobra online — dinheiro na entrega, maquininha,\n combinar com a loja. Ela é a maioria da frota, e abrir uma\n cobrança aqui só produziria \"esta loja não recebe pagamento\n online\" no lugar do botão de comprar. O pedido nasce pendente,\n como sempre nasceu, e a tela do pedido diz isso com todas as\n letras em vez de comemorar. */}\n {!chargesOnline && (\n <div className=\"mt-5\">\n <button\n type=\"button\"\n data-testid={TID.placeOrder}\n disabled={placing}\n onClick={() => { void confirmWithoutCharge() }}\n className=\"min-h-12 w-full rounded-xl bg-primary px-6 py-3 font-semibold text-primary-foreground transition hover:opacity-90 disabled:opacity-60\"\n >\n {t('checkout.payment.placeOrder', { total: money(total) })}\n </button>\n <p className=\"mt-2 text-center text-xs text-muted-foreground\">\n {t('checkout.payment.pendingNote')}\n </p>\n </div>\n )}\n\n {/*\n * Atalho de DESENVOLVIMENTO: cria o pedido sem passar pelo\n * adquirente.\n *\n * Testar o fluxo inteiro numa loja com gateway ligado exigia ou\n * credenciais válidas ou mexer nos ajustes da loja no banco — as\n * duas coisas caras para conferir uma tela. Este botão chama o\n * MESMO `confirmWithoutCharge()` que uma loja sem gateway usa\n * todo dia, então ele não inventa um caminho: usa o que já\n * existe, pulando só a cobrança.\n *\n * A guarda é `import.meta.env.DEV`, lida com o mesmo cast\n * defensivo do isDevBuild() do core (o SDK compila para consumo\n * em Node também, onde `import.meta.env` não existe).\n *\n * O que isso garante: num build de produção o valor é `false` e o\n * bloco NUNCA renderiza. O que NÃO vou afirmar: que o bundler o\n * remove — com o cast a expressão deixa de ser o literal que o\n * Vite substitui estaticamente, então a eliminação de código\n * morto não está garantida. O botão não aparece; o código pode\n * viajar junto.\n */}\n {DEV_BUILD && chargesOnline && (\n <div className=\"mt-6 rounded-xl border border-dashed border-amber-500/60 bg-amber-500/5 p-4\">\n <p className=\"text-xs font-semibold uppercase tracking-wide text-amber-600\">\n Somente em desenvolvimento\n </p>\n <button\n type=\"button\"\n data-testid={TID.devPlaceOrderWithoutCharge}\n disabled={placing}\n onClick={() => { void confirmWithoutCharge() }}\n className=\"mt-2 min-h-11 w-full rounded-lg border border-amber-500/60 px-4 py-2.5 text-sm font-medium text-amber-700 transition hover:bg-amber-500/10 disabled:opacity-60\"\n >\n {`Criar pedido sem cobrar — ${money(total)}`}\n </button>\n <p className=\"mt-2 text-xs text-muted-foreground\">\n Pula o adquirente e grava o pedido como <code>pending</code>, igual a uma\n loja que confirma o pagamento à mão. Este bloco não vai para produção.\n </p>\n </div>\n )}\n\n </section>\n )}\n\n {step === 4 && paidOrderId && (\n <section data-testid={TID.checkoutDone} className=\"rounded-xl border bg-card p-8 text-center\">\n <SuccessMark />\n <h2 className=\"mt-4 text-2xl font-bold tracking-tight\">{t('checkout.done.title')}</h2>\n <p className=\"mt-2 text-muted-foreground\">\n {t('checkout.done.text')}\n </p>\n <button\n type=\"button\"\n onClick={() => navigateTo(`/order/${paidOrderId}`)}\n className=\"mt-6 inline-flex min-h-11 items-center rounded-lg bg-primary px-6 py-3 text-sm font-semibold text-primary-foreground transition hover:opacity-90\"\n >\n {t('checkout.done.viewOrder')}\n </button>\n </section>\n )}\n\n {error && (\n <p data-testid={TID.checkoutError} className=\"rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive\">\n {error}\n </p>\n )}\n\n {/* Embaixo do formulário, onde a mão já está — e dentro do <form>,\n para que Enter em qualquer campo avance o passo. Digitar o CEP e\n apertar Enter é o gesto natural; antes ele não fazia nada e o\n botão estava do outro lado da tela. */}\n {(step === 1 || step === 2) && (\n <div className=\"grid gap-3 border-t pt-5\">\n <button\n type=\"submit\"\n data-testid={TID.checkoutContinue}\n className=\"min-h-12 rounded-lg bg-primary px-6 py-4 text-sm font-bold text-primary-foreground transition hover:opacity-90\"\n >\n {step === 1\n // Na retirada o passo seguinte É o pagamento — prometer\n // \"a entrega\" mandaria a pessoa para uma etapa que o\n // pedido dela não tem.\n ? (isPickup ? t('checkout.goToPayment', { total: money(total) }) : t('checkout.continueToDelivery'))\n : t('checkout.goToPayment', { total: money(total) })}\n </button>\n {step === 2 && (\n <button\n type=\"button\"\n data-testid={TID.checkoutBack}\n onClick={() => goToStep(1)}\n className=\"min-h-11 rounded-lg border px-6 py-3 text-sm font-medium transition hover:bg-muted\"\n >\n {t('checkout.backToContact')}\n </button>\n )}\n <Link to={returnPath(config)} className=\"text-center text-sm text-muted-foreground hover:text-foreground\">\n {t('checkout.backToCart')}\n </Link>\n </div>\n )}\n\n </form>\n\n </section>\n\n <aside className=\"rounded-xl border bg-muted/20 p-5 lg:sticky lg:top-6 lg:col-span-2 lg:self-start\">\n <h2 className=\"sr-only\">{t('summary.title')}</h2>\n <ul className=\"space-y-4\">\n {cart.lines.map((line) => (\n <li key={line.lineId ?? line.productId} className=\"flex gap-3 text-sm\">\n <div className=\"relative h-16 w-16 flex-none overflow-hidden rounded-lg border bg-background\">\n {line.imageUrl && <SmoothImage src={line.imageUrl} alt={line.name} className=\"h-full w-full object-cover\" variant={{ width: 96 }} />}\n <span className=\"absolute -right-1 -top-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-muted-foreground px-1.5 text-[10px] font-bold text-background\">\n {line.quantity}\n </span>\n </div>\n <div className=\"min-w-0 flex-1\">\n <p className=\"truncate font-medium\">{line.name}</p>\n {line.sku && <p className=\"text-xs text-muted-foreground\">{line.sku}</p>}\n {line.optionsLabel && <p className=\"text-xs text-muted-foreground\">{line.optionsLabel}</p>}\n {/* O recado do item aparece também aqui: é a última tela antes\n de pagar, e é onde alguém confere o que pediu. */}\n {line.notes && <p className=\"text-xs italic text-muted-foreground\">“{line.notes}”</p>}\n </div>\n <span data-price={(line.unitPrice * line.quantity).toFixed(2)}>\n {money(line.unitPrice * line.quantity)}\n </span>\n </li>\n ))}\n </ul>\n {config.features.discounts && (\n <div className=\"mt-5 space-y-2 border-t pt-5\">\n <div className=\"flex gap-2\">\n <input\n data-testid={TID.discountInput}\n type=\"text\"\n placeholder={t('discount.placeholder')}\n value={discountCode}\n onChange={(event) => {\n setDiscountCode(event.target.value)\n setDiscountSuccess(null)\n setDiscountError(null)\n }}\n className=\"min-w-0 flex-1 rounded-lg border bg-background px-3 py-2 text-sm uppercase\"\n />\n <button\n type=\"button\"\n data-testid={TID.discountApply}\n onClick={applyDiscountCode}\n disabled={applyingDiscount || !discountCode.trim()}\n className=\"rounded-lg border px-3 py-2 text-sm font-semibold hover:bg-muted disabled:opacity-50\"\n >\n {t('discount.apply')}\n </button>\n </div>\n {discountError && (\n <p data-testid={TID.discountError} className=\"text-xs text-destructive\">\n {discountError}\n </p>\n )}\n {discountSuccess && (\n <p className=\"text-xs font-semibold text-emerald-700\">\n {discountSuccess}\n </p>\n )}\n </div>\n )}\n <dl className=\"mt-8 space-y-3 border-t pt-6 text-sm\">\n <div className=\"flex justify-between\">\n <dt className=\"text-muted-foreground\">{t('summary.subtotal')}</dt>\n <dd data-price={subtotal.toFixed(2)}>{money(subtotal)}</dd>\n </div>\n {discountTotal > 0 && (\n <div className=\"flex justify-between text-emerald-700\" data-testid={TID.discountRow}>\n <dt>\n {t('summary.discount')}{' '}\n <button\n type=\"button\"\n onClick={clearDiscountCode}\n className=\"text-xs text-muted-foreground underline\"\n >\n ({cart.discountCode} ×)\n </button>\n </dt>\n <dd data-price={discountTotal.toFixed(2)}>-{money(discountTotal)}</dd>\n </div>\n )}\n <div className=\"flex justify-between\">\n <dt className={cart.discountFreeShipping ? 'text-emerald-700' : 'text-muted-foreground'}>\n {/* Numa retirada não há entrega. \"Entrega — Grátis\" leria como um\n brinde que a loja deu, quando na verdade é a pessoa que vai\n buscar. */}\n {isPickup ? t('summary.pickup') : t('summary.delivery')}\n {cart.discountFreeShipping && (\n <button\n type=\"button\"\n onClick={clearDiscountCode}\n className=\"ml-1 text-xs text-muted-foreground underline\"\n >\n ({cart.discountCode} ×)\n </button>\n )}\n </dt>\n <dd data-price={shipping.toFixed(2)}>\n {isPickup ? t('summary.noFee') : shipping === 0 ? t('summary.free') : money(shipping)}\n </dd>\n </div>\n <div className=\"flex justify-between border-t pt-5 text-lg font-bold\">\n <dt>{t('summary.total')}</dt>\n <dd data-price={total.toFixed(2)}>{money(total)}</dd>\n </div>\n </dl>\n <div className=\"mt-6 flex items-center gap-2 text-xs text-muted-foreground\">\n <ShieldCheck className=\"h-4 w-4 text-primary\" />\n {t('summary.protected')}\n </div>\n {/* O botão de avançar NÃO mora aqui — ele vive embaixo do formulário,\n onde a mão está. O resumo é o que a pessoa confere, não onde ela\n age; a distância entre o último campo e o botão do outro lado da\n tela era uma travessia a cada passo. */}\n <div className=\"mt-6 border-t pt-5\">\n <Slot area=\"checkout\" name=\"afterForm\" context={checkoutSlotContext} />\n </div>\n </aside>\n\n {/* Fora das duas colunas de propósito.\n Dentro da <section> do formulário, no empilhamento do mobile esta\n tira caía ENTRE o botão de continuar e o resumo do pedido — links\n institucionais separando a pessoa dos itens que ela está comprando.\n Aqui ela é o último elemento da página nos dois layouts, que é onde\n um rodapé legal pertence. */}\n <footer className=\"flex flex-wrap gap-4 border-t pt-5 text-xs text-muted-foreground lg:col-span-5\">\n <Link to=\"/privacy\" className=\"hover:text-foreground\">{t('legal.privacy')}</Link>\n <Link to=\"/terms\" className=\"hover:text-foreground\">{t('legal.terms')}</Link>\n <Link to=\"/refunds\" className=\"hover:text-foreground\">{t('legal.refunds')}</Link>\n </footer>\n </div>\n </main>\n )\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/lib/errors.ts","../src/workflows/checkout.ts","../src/components/checkout/CheckoutSteps.tsx","../src/components/checkout/CardBrick.tsx","../src/components/checkout/CheckoutPayment.tsx","../src/hooks/use-known-customer.ts","../src/components/checkout/CheckoutField.tsx","../src/components/checkout/AddressForm.tsx","../src/components/checkout/ContactSummary.tsx","../src/lib/checkout-address.ts","../src/components/delivery/DeliverToPicker.tsx","../src/views/CheckoutPage.tsx"],"names":["jsx","jsxs","React","useState","useRef","getShopProvider","describeError","useEffect","Check","document","getCountrySchema","documentDigits","normalizePostalCode","Lock","CreditCard"],"mappings":";;;;;;;;;;;;;;;;AAOO,SAAS,aAAa,GAAA,EAAsB;AACjD,EAAA,IAAI,GAAA,YAA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WAAA,EAAY,OAAA,EAAS,qBAAqB,CAAA,EACvE;AAAA,OAAA,EACF,CAAA;AAAA,sBAQAC,IAAAA,CAAC,QAAA,EAAA,EAAO,SAAA,EAAU,gFAAA,EAChB,QAAA,EAAA;AAAA,wBAAAD,GAAAA,CAAC,QAAK,EAAA,EAAG,UAAA,EAAW,WAAU,uBAAA,EAAyB,QAAA,EAAA,CAAA,CAAE,eAAe,CAAA,EAAE,CAAA;AAAA,wBAC1EA,IAAC,IAAA,EAAA,EAAK,EAAA,EAAG,UAAS,SAAA,EAAU,uBAAA,EAAyB,QAAA,EAAA,CAAA,CAAE,aAAa,CAAA,EAAE,CAAA;AAAA,wBACtEA,IAAC,IAAA,EAAA,EAAK,EAAA,EAAG,YAAW,SAAA,EAAU,uBAAA,EAAyB,QAAA,EAAA,CAAA,CAAE,eAAe,CAAA,EAAE;AAAA,OAAA,EAC5E;AAAA,KAAA,EACF;AAAA,GAAA,EACF,CAAA;AAEJ","file":"chunk-YCAWAON6.js","sourcesContent":["/**\n * The message inside a thrown value.\n *\n * `err instanceof Error` is not enough here: the Supabase provider rethrows\n * PostgrestError, a plain object with `message`, so every `instanceof` check in\n * the storefront fell through to a generic sentence and lost what the server said.\n */\nexport function errorMessage(err: unknown): string {\n if (err instanceof Error) return err.message\n if (err && typeof err === 'object' && typeof (err as { message?: unknown }).message === 'string') {\n return (err as { message: string }).message\n }\n return ''\n}\n","import { getShopProvider } from '@fayz-ai/shop/runtime'\nimport type { Order, ShippingAddressInput, PaymentMethodKind, FulfillmentType } from '@fayz-ai/shop/types'\nimport { establishCustomerSession } from '../data/auth'\nimport { collectOrderMetadata, runBeforePlaceOrderValve } from '../extend/extension-points'\nimport type { ResolvedStorefrontConfig } from '../document/config'\nimport type { CartState } from '../stores/cart.store'\nimport { selectShipping } from '../stores/cart.store'\nimport type { SessionState } from '../stores/session.store'\nimport { rememberLocalOrder } from '../data/local-orders'\nimport { errorMessage } from '../lib/errors'\n\nexport interface StorefrontCheckoutCustomer {\n email: string\n name: string\n}\n\nexport interface StorefrontCheckoutAddress {\n street?: string\n city?: string\n zip?: string\n notes?: string\n}\n\nexport interface PlaceStorefrontOrderInput {\n config: ResolvedStorefrontConfig\n cart: Pick<CartState, 'lines' | 'discountCode' | 'discountPercent'>\n & Partial<Pick<CartState, 'discountFreeShipping'>>\n session?: Pick<SessionState, 'customerId' | 'email'>\n customer: StorefrontCheckoutCustomer\n address?: StorefrontCheckoutAddress\n /** Structured address; without it the order keeps only the free-text note. */\n shippingAddress?: ShippingAddressInput\n paymentMethod?: PaymentMethodKind\n markPaid?: boolean\n /**\n * Entrega ou retirada (0094). Ausente lê como entrega — que é o que todo\n * checkout anterior a esta migration fazia.\n *\n * Na RETIRADA quem chama manda o endereço da PRÓPRIA LOJA em\n * `shippingAddress`. Não é contorno: `shop_place_order` exige CEP quando a\n * loja tem zonas, e essa checagem roda antes de qualquer trigger de linha —\n * então o pedido precisa de um endereço válido, e o endereço válido de uma\n * retirada é o balcão. O trigger reconhece o modo e zera o frete.\n */\n fulfillmentType?: FulfillmentType\n /** Início da janela agendada (ISO). O servidor recusa fora de janela real. */\n scheduledFor?: string\n}\n\nexport interface PlaceStorefrontOrderResult {\n order: Order\n customerId: string\n}\n\n/**\n * `notes` is the buyer's free-text message to the store — nothing else.\n *\n * It used to double as the delivery address, from back when the order had\n * nowhere structured to put one. Now that the address is a real snapshot plus a\n * row in the address book, repeating it here only creates a second copy that\n * can disagree with the first (it did: it dropped number and district). When a\n * structured address is present, notes carries only what the customer wrote.\n */\nfunction formatDeliveryNotes(\n address: StorefrontCheckoutAddress | undefined,\n shippingAddress?: ShippingAddressInput,\n): string | undefined {\n if (address?.notes?.trim()) return address.notes.trim()\n\n // Structured address present → the order already knows where to deliver.\n if (shippingAddress) return undefined\n\n if (!address) return undefined\n const parts = [address.street, address.city, address.zip]\n .map((part) => part?.trim())\n .filter(Boolean)\n\n return parts.length > 0 ? `Entrega: ${parts.join(', ')}` : undefined\n}\n\n/** shop_place_order's three refusals of a customer id we sent (all 42501). */\nfunction isStaleCustomerError(err: unknown): boolean {\n const message = errorMessage(err).toLowerCase()\n return message.includes('customer email mismatch')\n || message.includes('customer does not belong to this store')\n || message.includes('customer belongs to another account')\n}\n\n/**\n * Storefront checkout primitive for custom/generated checkout screens.\n * It owns the order payload math and customer-session handshake so app-owned\n * routes can customize UX without copying provider/business logic.\n */\nexport async function placeStorefrontOrder({\n config,\n cart,\n session,\n customer,\n address,\n shippingAddress,\n fulfillmentType,\n scheduledFor,\n paymentMethod,\n markPaid = false,\n}: PlaceStorefrontOrderInput): Promise<PlaceStorefrontOrderResult> {\n const email = customer.email.trim().toLowerCase()\n const name = customer.name.trim()\n const provider = getShopProvider()\n\n let customerId = session?.customerId ?? null\n // Normalized on both sides: the session email is stored as the buyer typed it,\n // so \"Vini@Gmail.com\" vs \"vini@gmail.com\" used to re-resolve on every order.\n if (!customerId || session?.email?.trim().toLowerCase() !== email) {\n const established = await establishCustomerSession(email, { name })\n customerId = established.customerId\n }\n\n const notes = formatDeliveryNotes(address, shippingAddress)\n const items = cart.lines.map((line) => ({\n productId: line.productId,\n // The variant the shopper picked (spine M5): the server prices the line\n // from it and decrements ITS stock, so two sizes never share a counter.\n variantId: line.variantId || undefined,\n quantity: line.quantity,\n optionsLabel: line.optionsLabel || undefined,\n // A observação da linha (0094). Vai por item porque é por item: duas\n // unidades do mesmo prato com pedidos diferentes são duas linhas.\n notes: line.notes || undefined,\n }))\n // Retirada não paga frete. O cliente já não é confiado para isso — o servidor\n // zera de qualquer jeito (0094) — mas mandar o número certo evita que a tela\n // mostre um total e o pedido nasça com outro.\n const shippingTotal = fulfillmentType === 'pickup' ? 0 : selectShipping(cart, config)\n\n // THE escape valve (spine I4, M7): exactly one registrant may replace the\n // entire default order creation — external OMS, quote-first flows. Null (or\n // no registrant, the overwhelmingly common case) takes the default path.\n const replaced = await runBeforePlaceOrderValve<Order>({\n items,\n customer: { name, email },\n currency: config.currency,\n discountCode: cart.discountCode ?? undefined,\n shippingTotal,\n notes,\n customerId: customerId ?? undefined,\n })\n if (replaced) return { order: replaced, customerId: customerId ?? replaced.customerId ?? '' }\n\n // Extension contributions (spine M7's order.metadata point), namespaced by\n // handler id so two extensions can never collide on a key.\n const contributed = await collectOrderMetadata({\n items: cart.lines.map((line) => ({\n productId: line.productId,\n quantity: line.quantity,\n unitPrice: line.unitPrice,\n })),\n subtotal: cart.lines.reduce((sum, line) => sum + line.unitPrice * line.quantity, 0),\n customerEmail: email,\n })\n // The market the buyer shopped in (0116): shop_place_order prices, ships and\n // charges in it. Absent = the default market, as every store before markets.\n const metadata = config.market\n ? { ...(contributed ?? {}), market: config.market.code }\n : contributed\n\n // Trusted placement: send only product ids + quantities. The provider\n // (shop_place_order RPC on Supabase, in-memory provider in mock) re-reads\n // prices, validates the discount, and decrements inventory server-side.\n const place = (withCustomerId: string | undefined) => provider.placeOrder({\n customerId: withCustomerId,\n customer: { name, email },\n currency: config.currency,\n notes,\n discountCode: cart.discountCode ?? undefined,\n shippingTotal,\n // Structured address + method are what populate public.addresses and the\n // transactions ledger. `notes` stays for backwards compatibility with\n // checkouts that have not been updated yet.\n shippingAddress,\n paymentMethod,\n metadata,\n fulfillmentType,\n scheduledFor,\n items,\n })\n\n let order: Order\n try {\n order = await place(customerId ?? undefined)\n } catch (err) {\n // The customer id lives in localStorage, shared by every store on the\n // origin and never re-verified, so it can point at a row that is not this\n // buyer's (another tenant, another account, an email edited since). The\n // server is right to refuse it — but the id is ours, not a credential, so\n // dropping it and letting the RPC resolve the customer from the typed email\n // is the fix. Without this the buyer is stuck on a raw 42501 forever: the\n // stale id survives every reload.\n if (!customerId || !isStaleCustomerError(err)) throw err\n customerId = null\n order = await place(undefined)\n }\n\n if (markPaid) {\n // Prefer the RPC seam — anon storefronts have no UPDATE grant on the\n // orders table, so a direct updateOrder 401s on pool backends.\n if (provider.confirmPayment) await provider.confirmPayment(order.id)\n else await provider.updateOrder(order.id, { financialStatus: 'paid' })\n }\n\n // Guardado localmente para que \"Minhas compras\" funcione sem que o servidor\n // precise responder \"o que é deste cliente?\" — ver data/local-orders.ts.\n rememberLocalOrder(order.id)\n\n return { order, customerId: customerId ?? order.customerId ?? '' }\n}\n","import React from 'react'\nimport { Check } from 'lucide-react'\nimport { TID } from '../../lib/testids'\nimport { useT } from '../../locales'\nimport type { MessageKey } from '../../locales/messages'\n\n// ---------------------------------------------------------------------------\n// Onde a pessoa está, e para onde ela pode voltar.\n//\n// Antes isto era três palavras soltas (\"Informações / Entrega / Pagamento\") que\n// nunca mudavam: um enfeite que dizia sempre a mesma coisa enquanto o formulário\n// inteiro estava numa página só. Agora é o mapa do que já ficou pronto.\n//\n// Passo concluído é CLICÁVEL e o que vem à frente não é — voltar para corrigir o\n// endereço é normal; pular para o pagamento sem endereço não existe.\n// ---------------------------------------------------------------------------\n\nexport type CheckoutStep = 1 | 2 | 3 | 4\n\nconst LABELS: Record<CheckoutStep, MessageKey> = {\n 1: 'checkout.steps.1',\n 2: 'checkout.steps.2',\n 3: 'checkout.steps.3',\n 4: 'checkout.steps.4',\n}\n\nexport interface CheckoutStepsProps {\n current: CheckoutStep\n /** Ausente no passo 4: depois de pago não há para onde voltar. */\n onGoBackTo?: (step: CheckoutStep) => void\n /**\n * Passos que este pedido não tem. Na RETIRADA o passo 2 (Entrega) não existe:\n * o endereço é o balcão (0094).\n *\n * Some da régua em vez de ficar cinza para sempre: um passo que nunca vai\n * acontecer, desenhado como \"pendente\", promete uma etapa a mais do que o\n * pedido tem — e a régua existe justamente para dizer quanto falta.\n */\n omit?: readonly CheckoutStep[]\n}\n\nexport function CheckoutSteps({ current, onGoBackTo, omit }: CheckoutStepsProps) {\n const t = useT()\n const steps: CheckoutStep[] = ([1, 2, 3, 4] as CheckoutStep[])\n .filter((s) => !omit?.includes(s))\n\n return (\n <nav data-testid={TID.checkoutSteps} aria-label={t('checkout.steps.label')} className=\"mb-8\">\n <ol className=\"flex items-center gap-1.5 sm:gap-2\">\n {steps.map((step, index) => {\n const done = step < current\n const active = step === current\n const canGoBack = done && !!onGoBackTo\n const Tag = canGoBack ? 'button' : 'div'\n\n return (\n // `flex-1` só em quem TEM traço. O último passo não tem, e com\n // flex-1 ele reservava uma fatia inteira para desenhar apenas a\n // bolinha — que então parava no começo da fatia em vez do fim, e a\n // régua saía torta. Sem flex-1, o traço absorve a sobra e as\n // bolinhas encostam nas pontas.\n <li\n key={step}\n className={`flex min-w-0 items-center gap-1.5 sm:gap-2 ${\n index < steps.length - 1 ? 'flex-1' : ''\n }`}\n >\n <Tag\n {...(canGoBack\n ? { type: 'button' as const, onClick: () => onGoBackTo(step) }\n : {})}\n data-testid={TID.checkoutStep(step)}\n data-state={done ? 'done' : active ? 'current' : 'pending'}\n aria-current={active ? 'step' : undefined}\n className={[\n 'flex min-w-0 items-center gap-2 rounded-lg px-2 py-1.5 text-left transition',\n canGoBack ? 'hover:bg-muted' : '',\n active ? 'text-foreground' : done ? 'text-foreground' : 'text-muted-foreground',\n ].join(' ')}\n >\n <span\n className={[\n 'grid h-7 w-7 shrink-0 place-items-center rounded-full border text-xs font-semibold',\n done\n ? 'border-primary bg-primary text-primary-foreground'\n : active\n // Contornado, não preenchido: em andamento não é concluído.\n // Foi o mesmo engano na linha do tempo do pedido, onde um\n // pagamento pendente exibia um tique.\n ? 'border-primary bg-background text-primary'\n : 'border-muted-foreground/30 bg-background',\n ].join(' ')}\n >\n {/* A POSIÇÃO, não o id interno: com a Entrega fora (retirada),\n numerar pelo id mostraria \"1, 3, 4\" a quem só tem três\n passos — a régua contaria uma etapa que não existe. */}\n {done ? <Check className=\"h-3.5 w-3.5\" /> : index + 1}\n </span>\n <span className={`hidden truncate text-sm sm:inline ${active ? 'font-semibold' : ''}`}>\n {t(LABELS[step])}\n </span>\n </Tag>\n {index < steps.length - 1 && (\n <span aria-hidden className={`h-px flex-1 ${done ? 'bg-primary' : 'bg-border'}`} />\n )}\n </li>\n )\n })}\n </ol>\n {/* No celular o rótulo do passo some para o traço caber; sem esta linha a\n pessoa vê números sem saber o que eles são. */}\n <p className=\"mt-2 text-sm font-semibold sm:hidden\">\n {/* A posição, igual à bolinha. Numerar pelo id faria a legenda dizer\n \"3.\" embaixo de uma bolinha marcada \"2\" quando a Entrega está fora. */}\n {steps.indexOf(current) + 1}. {t(LABELS[current])}\n </p>\n </nav>\n )\n}\n","import React, { useEffect, useRef, useState } from 'react'\nimport { Skeleton, SkeletonGroup } from '../Skeleton'\nimport { describeError } from '@fayz-ai/core'\n\n/**\n * Mercado Pago's Card Payment Brick, mounted in the store's own checkout.\n *\n * WHY THIS COMPONENT EXISTS AT ALL\n *\n * Every other acquirer in this repo sends a card buyer to a hosted page, and not\n * for taste: AbacatePay's and Vindi's transparent calls want the card number (or\n * the CVV) inside a request the edge function makes, which would put the pool in\n * PCI scope. Mercado Pago tokenises HERE — the fields below live in their\n * iframes, not in this DOM — so the store never touches a card number and the\n * buyer never leaves. The only thing this component hands upward is a\n * single-use token.\n *\n * So the guarantee is structural, not a promise: there is no state in this file\n * that could hold a PAN, because the inputs are not ours to read.\n */\n\n/** The slice of their SDK this file uses. Declared rather than `any`, so a\n * change in their shape is a type error here and not a runtime one. */\ninterface BricksBuilder {\n create(\n brick: 'cardPayment',\n containerId: string,\n settings: Record<string, unknown>,\n ): Promise<{ unmount: () => void }>\n}\ninterface MercadoPagoSdk {\n bricks(): BricksBuilder\n}\ndeclare global {\n interface Window {\n MercadoPago?: new (publicKey: string, options?: { locale?: string }) => MercadoPagoSdk\n }\n}\n\nconst SDK_URL = 'https://sdk.mercadopago.com/js/v2'\nconst CONTAINER_ID = 'fayz-mp-card-brick'\n\n/**\n * Their device-fingerprint script, and the global it defines.\n *\n * Mercado Pago's first recommendation for improving approval rates: load this\n * on the checkout page, and send the resulting `MP_DEVICE_SESSION_ID` as the\n * `X-meli-session-id` header when the charge is created. Without it a legitimate\n * buyer looks anonymous to their anti-fraud and gets declined more often — a\n * cost that never shows up as an error, only as a lower approval rate.\n */\nconst DEVICE_SCRIPT_URL = 'https://www.mercadopago.com/v2/security.js'\nconst DEVICE_VIEW = 'checkout'\n\ndeclare global {\n // eslint-disable-next-line no-var\n var MP_DEVICE_SESSION_ID: string | undefined\n}\n\n/** Load the security script once; the global appears shortly after it runs. */\nfunction loadDeviceScript(): void {\n if (typeof document === 'undefined') return\n if (document.querySelector(`script[src=\"${DEVICE_SCRIPT_URL}\"]`)) return\n const script = document.createElement('script')\n script.src = DEVICE_SCRIPT_URL\n script.setAttribute('view', DEVICE_VIEW)\n script.async = true\n document.body.appendChild(script)\n}\n\n/** Whatever the script has produced by now — never a fabricated value. */\nexport function deviceSessionId(): string | null {\n if (typeof window === 'undefined') return null\n const id = window.MP_DEVICE_SESSION_ID\n return typeof id === 'string' && id.trim() ? id.trim() : null\n}\n\n/**\n * Load their SDK once per page, and let every caller await the same load.\n *\n * A second <script> would re-register the global and re-mount the bricks\n * builder underneath a Brick that is already alive; the promise is the lock.\n */\nlet sdkPromise: Promise<void> | null = null\nfunction loadSdk(): Promise<void> {\n if (typeof window === 'undefined') return Promise.reject(new Error('no window'))\n if (window.MercadoPago) return Promise.resolve()\n if (sdkPromise) return sdkPromise\n\n sdkPromise = new Promise<void>((resolve, reject) => {\n const existing = document.querySelector<HTMLScriptElement>(`script[src=\"${SDK_URL}\"]`)\n const script = existing ?? document.createElement('script')\n script.src = SDK_URL\n script.async = true\n script.addEventListener('load', () => resolve())\n script.addEventListener('error', () => {\n // Reset, so a buyer who retries on a flaky connection gets a real second\n // attempt rather than the rejected promise from the first.\n sdkPromise = null\n reject(new Error('Não conseguimos carregar o pagamento com cartão.'))\n })\n if (!existing) document.body.appendChild(script)\n })\n return sdkPromise\n}\n\nexport interface CardBrickResult {\n token: string\n paymentMethodId: string | null\n issuerId: string | null\n installments: number\n /** What the Brick collected, which may differ from the checkout's own copy. */\n email: string | null\n document: { type: string; number: string } | null\n}\n\nexport interface CardBrickProps {\n publicKey: string\n /** In reais, as their SDK wants it — it prices the installment options. */\n amount: number\n /** Prefilled so the buyer does not retype what the checkout already asked. */\n email?: string | null\n /** Called with the token. Rejecting keeps the Brick mounted and its form filled. */\n onSubmit: (result: CardBrickResult) => Promise<void>\n onError?: (message: string) => void\n}\n\nexport function CardBrick({ publicKey, amount, email, onSubmit, onError }: CardBrickProps) {\n const [ready, setReady] = useState(false)\n const [failed, setFailed] = useState<string | null>(null)\n // The Brick is mounted ONCE. React 18 runs effects twice in development, and\n // a second create() on the same container leaves two forms stacked.\n const mounted = useRef(false)\n const controller = useRef<{ unmount: () => void } | null>(null)\n // The callback the Brick captured at create() time would otherwise be the\n // first render's — a stale closure over an old cart total.\n const submitRef = useRef(onSubmit)\n submitRef.current = onSubmit\n\n useEffect(() => {\n if (mounted.current) return\n mounted.current = true\n let cancelled = false\n\n // Started before the SDK, because it needs a moment to fingerprint and the\n // value is only read when the buyer submits.\n loadDeviceScript()\n\n void (async () => {\n try {\n await loadSdk()\n if (cancelled || !window.MercadoPago) return\n const mp = new window.MercadoPago(publicKey, { locale: 'pt-BR' })\n const builder = mp.bricks()\n\n controller.current = await builder.create('cardPayment', CONTAINER_ID, {\n initialization: {\n amount,\n ...(email ? { payer: { email } } : {}),\n },\n customization: {\n visual: { style: { theme: 'default' } },\n paymentMethods: { maxInstallments: 12 },\n },\n callbacks: {\n onReady: () => { if (!cancelled) setReady(true) },\n onSubmit: (formData: Record<string, any>) =>\n // Their contract: resolve when the payment is handled, reject to\n // keep the form up. Rejecting is what lets a declined card be\n // corrected in place instead of re-typed from scratch.\n submitRef.current({\n token: String(formData?.token ?? ''),\n paymentMethodId: formData?.payment_method_id ?? null,\n issuerId: formData?.issuer_id == null ? null : String(formData.issuer_id),\n installments: Number(formData?.installments) || 1,\n email: formData?.payer?.email ?? null,\n document: formData?.payer?.identification?.number\n ? {\n type: String(formData.payer.identification.type ?? 'CPF'),\n number: String(formData.payer.identification.number),\n }\n : null,\n }),\n onError: (brickError: { message?: string }) => {\n // Their validation errors are for the buyer and already shown in\n // the form; this is for the ones that stop it working at all.\n const message = brickError?.message ?? 'Não conseguimos carregar o formulário do cartão.'\n if (!cancelled) onError?.(message)\n },\n },\n })\n } catch (err) {\n if (cancelled) return\n const message = describeError(err, 'Não conseguimos carregar o pagamento com cartão.')\n setFailed(message)\n onError?.(message)\n }\n })()\n\n return () => {\n cancelled = true\n try { controller.current?.unmount() } catch { /* already gone with the DOM */ }\n controller.current = null\n mounted.current = false\n }\n // Deliberately once: their Brick prices installments from the amount it was\n // created with, and a cart that changed has already sent the buyer back a\n // step. Re-creating under a filled-in form would clear the card fields.\n }, []) // eslint-disable-line react-hooks/exhaustive-deps\n\n if (failed) {\n return (\n <p className=\"rounded-lg border border-destructive/40 bg-destructive/5 p-4 text-sm text-destructive\">\n {failed}\n </p>\n )\n }\n\n return (\n <div className=\"space-y-3\">\n {!ready && (\n <SkeletonGroup label=\"Carregando o formulário do cartão\" className=\"space-y-3\">\n <Skeleton className=\"h-11 w-full rounded-lg\" />\n <div className=\"grid grid-cols-2 gap-3\">\n <Skeleton className=\"h-11 w-full rounded-lg\" />\n <Skeleton className=\"h-11 w-full rounded-lg\" />\n </div>\n <Skeleton className=\"h-11 w-full rounded-lg\" />\n </SkeletonGroup>\n )}\n {/* Their iframes mount in here. Kept in the tree while loading so the\n container exists when create() runs — hidden, not unmounted. */}\n <div id={CONTAINER_ID} className={ready ? '' : 'hidden'} />\n </div>\n )\n}\n","import React, { useCallback, useEffect, useRef, useState } from 'react'\nimport { Check, Copy, CreditCard, Lock, QrCode } from 'lucide-react'\nimport { getShopProvider } from '@fayz-ai/shop/runtime'\nimport { gatewayLabel } from '@fayz-ai/shop'\nimport { CardBrick, deviceSessionId, type CardBrickResult } from './CardBrick'\nimport type { CheckoutSessionInput, PaymentCharge } from '@fayz-ai/shop/types'\nimport { TID } from '../../lib/testids'\nimport { toast } from '../../stores/toast.store'\nimport { PulseDot, Skeleton, SkeletonGroup } from '../Skeleton'\nimport { describeError } from '@fayz-ai/core'\n\n// ---------------------------------------------------------------------------\n// O passo 3, e a razão de ele existir.\n//\n// O pedido NÃO existe enquanto esta tela estiver aberta. O que existe é uma\n// sessão de checkout: o servidor congelou o carrinho com os preços que ele mesmo\n// recalculou e abriu a cobrança. Quando o provedor diz que o dinheiro entrou, é\n// o SERVIDOR quem cria o pedido a partir desse congelado — e só então a tela\n// avança.\n//\n// Isso é o oposto do que a loja fazia: criar o pedido, comemorar com confete, e\n// esperar que alguém pagasse depois.\n// ---------------------------------------------------------------------------\n\n/** Curto o bastante para parecer vivo, longo o bastante para não brigar com a\n * rede nem com o limite do provedor. */\nconst POLL_MS = 3_000\n\n/**\n * O que sobrevive à ida ao adquirente.\n *\n * A URL de volta carrega o id da sessão — é ela que o servidor consulta —, mas\n * não o adquirente, e a consulta tem que bater na função DELE. O adquirente é\n * um detalhe da loja, não do comprador, então fica aqui e não na barra de\n * endereço. `sessionStorage` porque isto vale para esta aba e esta compra: uma\n * sessão vazada para outra guia seria a tela consultando a cobrança errada.\n */\nconst RESUME_KEY = 'fz.checkout.resume'\n\n/**\n * How much longer this charge is good for.\n *\n * The charge really does expire: the open request sends `expiresIn` and the\n * provider answers with an absolute `expiresAt`, which is what gets stored — the\n * clock that counts is theirs, not ours.\n *\n * It exists because the code is now STABLE. It used to change on every return to\n * this screen, and that change was itself the signal that the old one was no\n * longer good; now it stays, and without a countdown nothing separates a live\n * code from one that died while the tab sat open. Copying a dead code pays\n * nobody.\n *\n * Returns null when no deadline is known — then nothing is promised.\n */\nfunction useExpiry(expiresAt: string | null | undefined): { secondsLeft: number | null; expired: boolean } {\n const target = React.useMemo(() => {\n if (!expiresAt) return null\n const t = new Date(expiresAt).getTime()\n return Number.isFinite(t) ? t : null\n }, [expiresAt])\n\n const [now, setNow] = React.useState(() => Date.now())\n React.useEffect(() => {\n if (target === null) return\n const id = setInterval(() => setNow(Date.now()), 1000)\n return () => clearInterval(id)\n }, [target])\n\n if (target === null) return { secondsLeft: null, expired: false }\n const secondsLeft = Math.max(0, Math.round((target - now) / 1000))\n return { secondsLeft, expired: secondsLeft === 0 }\n}\n\n/** mm:ss, para um prazo que o comprador lê de relance. */\nfunction formatCountdown(seconds: number): string {\n const m = Math.floor(seconds / 60)\n const s = seconds % 60\n return `${m}:${String(s).padStart(2, '0')}`\n}\n\n/** True when the text reached the clipboard, by whichever route works here. */\nasync function copyText(text: string): Promise<boolean> {\n try {\n if (navigator.clipboard?.writeText) {\n await navigator.clipboard.writeText(text)\n return true\n }\n } catch {\n // Falls through: a rejected promise here (permission, insecure origin) is\n // not a reason to give up while the older API is still available.\n }\n try {\n const area = document.createElement('textarea')\n area.value = text\n // Off-screen rather than hidden: `display:none` is not selectable, and the\n // selection is what execCommand copies.\n area.setAttribute('readonly', '')\n area.style.position = 'fixed'\n area.style.top = '-1000px'\n area.style.opacity = '0'\n document.body.appendChild(area)\n area.select()\n area.setSelectionRange(0, text.length)\n const ok = document.execCommand('copy')\n document.body.removeChild(area)\n return ok\n } catch {\n return false\n }\n}\n\nfunction rememberSession(sessionId: string, provider: string | null) {\n try {\n sessionStorage.setItem(RESUME_KEY, JSON.stringify({ sessionId, provider }))\n } catch {\n // Sem sessionStorage a volta ainda funciona: o id vem na URL e a consulta\n // cai no adquirente padrão. Perder isto atrasa uma compra, não a perde.\n }\n}\n\n/** O adquirente guardado para ESTA sessão, se for a mesma que voltou. */\nexport function recallSessionProvider(sessionId: string): string | null {\n try {\n const raw = JSON.parse(sessionStorage.getItem(RESUME_KEY) ?? 'null')\n return raw?.sessionId === sessionId ? (raw.provider ?? null) : null\n } catch {\n return null\n }\n}\n\nexport interface CheckoutPaymentProps {\n input: CheckoutSessionInput\n /** Chamado uma vez, com o pedido que o servidor criou. */\n onPaid: (orderId: string) => void\n onBack: () => void\n money: (value: number) => string\n /**\n * Uma sessão que JÁ existe, para retomar em vez de abrir outra.\n *\n * É o comprador voltando da página do adquirente depois de pagar com cartão:\n * a página recarregou do zero, o formulário e o passo se perderam, e a única\n * coisa que sobrevive é o id que veio na URL. Com ele a tela não abre cobrança\n * nenhuma — só pergunta se o dinheiro entrou.\n */\n resume?: { sessionId: string; provider?: string | null; chargeToken?: string | null } | null\n /**\n * A loja não tem adquirente — não é um erro do comprador, e ele não pode\n * fazer nada a respeito. Quem sabe disso é o servidor, então em vez de pintar\n * um erro na tela avisamos o checkout para oferecer o pedido sem cobrança.\n */\n onUnavailable?: () => void\n /**\n * The cart total as the page already shows it.\n *\n * Only an in-store card form needs it: that mounts before any charge exists,\n * and the acquirer's SDK prices installments from the amount it was created\n * with. Every other flow learns the total from the opened session, which is\n * the figure the server will actually charge.\n */\n amount?: number\n}\n\ntype Phase = 'opening' | 'card' | 'redirect' | 'waiting' | 'settling' | 'error'\n\nexport function CheckoutPayment({ input, onPaid, onBack, money, onUnavailable, resume, amount }: CheckoutPaymentProps) {\n const [phase, setPhase] = useState<Phase>('opening')\n const [charge, setCharge] = useState<PaymentCharge | null>(null)\n const expiry = useExpiry(charge?.expiresAt)\n const [total, setTotal] = useState<number | null>(null)\n const [redirectUrl, setRedirectUrl] = useState<string | null>(null)\n /** The acquirer's browser key, for a card typed in the store. */\n const [brickKey, setBrickKey] = useState<string | null>(null)\n const [sessionId, setSessionId] = useState<string | null>(resume?.sessionId ?? null)\n /** Quem abriu a cobrança. A consulta tem que bater na função DESTE gateway —\n * reler os ajustes agora perguntaria ao adquirente novo por uma transação\n * que está no antigo. */\n const [provider, setProvider] = useState<string | null>(resume?.provider ?? null)\n const [error, setError] = useState<string | null>(null)\n const [copied, setCopied] = useState(false)\n /** \"Já paguei\" em andamento — a consulta que a pessoa pediu, não a do relógio. */\n const [checking, setChecking] = useState(false)\n const settled = useRef(false)\n // A sessão é aberta UMA vez. Sem esta trava, qualquer re-render com um objeto\n // de entrada novo abriria uma segunda cobrança para o mesmo carrinho.\n const opened = useRef(false)\n\n const open = useCallback(async () => {\n const shop = getShopProvider()\n if (!shop.openCheckoutSession) {\n setError('Esta loja ainda não recebe pagamento online.')\n setPhase('error')\n return\n }\n setPhase('opening')\n setError(null)\n try {\n // CARD TYPED IN THE STORE, where the acquirer supports it.\n //\n // Mercado Pago tokenises in the browser, so there is nothing to open until\n // the buyer has filled the card in: the charge is created FROM the token,\n // not before it. Asking for the key is how we learn whether this acquirer\n // works that way — a null answer means it does not, and the flow below is\n // the redirect or QR every other provider uses.\n if (input.paymentMethod === 'credit_card' && shop.paymentPublicKey) {\n const providerSlug = input.provider ?? null\n const publicKey = providerSlug ? await shop.paymentPublicKey(providerSlug) : null\n if (publicKey) {\n setProvider(providerSlug)\n setBrickKey(publicKey)\n setPhase('card')\n return\n }\n }\n\n const session = await shop.openCheckoutSession({\n ...input,\n // Para onde o adquirente devolve o comprador. É esta página, com o id da\n // sessão pendurado: quem volta volta em página nova, sem estado nenhum.\n returnUrl: typeof window === 'undefined' ? null : window.location.href.split('?')[0],\n })\n setSessionId(session.sessionId)\n setProvider(session.provider ?? input.provider ?? null)\n setTotal(session.total)\n setCharge(session.charge)\n\n // PAID OFF-SITE, and the test is whether there is anything to draw HERE.\n //\n // The condition used to be `session.paymentUrl` alone, which was true of\n // more charges than it should have been: Vindi answers a Pix with a QR\n // code AND a `url_payment`, the latter being a page for a merchant to send\n // someone, not a place to push the buyer. So a Pix that had a perfectly\n // good code to show redirected off the store instead — and Yapay's page\n // then bounces on again, landing the buyer on a bare SVG of the QR with no\n // way back and no session.\n //\n // A charge with an inline payload is drawn; only a charge with nothing to\n // draw sends the person away. The session is remembered because coming\n // back is a fresh load and React does not survive it.\n if (session.paymentUrl && !session.charge) {\n // The buyer PRESSES the button; the page does not move under them.\n //\n // Leaving on load meant the store vanished mid-checkout with no warning\n // and no way back, and whatever the acquirer's page says at the top is\n // the first hint of where they are. A named button turns the same\n // journey into something they chose, which is also what makes an\n // unfamiliar domain in the address bar read as expected rather than as a\n // hijack. The session is remembered at the click, because the return\n // trip is a fresh load and React does not survive it.\n setRedirectUrl(session.paymentUrl)\n setPhase('redirect')\n return\n }\n\n setPhase(session.charge ? 'waiting' : 'error')\n if (!session.charge) setError('Não conseguimos abrir a cobrança agora.')\n } catch (err) {\n // 404 aqui é \"esta loja não cobra online\", não uma falha da cobrança.\n // 409 method_unavailable é \"esta loja não aceita ESTA forma\" — a mesma\n // saída, porque o desfecho para o comprador é o mesmo: pedido sem\n // cobrança online, como sempre foi para quem escolhia maquininha.\n const status = (err as { status?: number })?.status\n const code = (err as { code?: string })?.code\n if (status === 404 || code === 'method_unavailable') {\n onUnavailable?.()\n return\n }\n setError(describeError(err, 'Não conseguimos abrir a cobrança agora.'))\n setPhase('error')\n }\n }, [input, onUnavailable])\n\n useEffect(() => {\n if (opened.current) return\n opened.current = true\n // Retomar NÃO é abrir: a cobrança dessa sessão já existe, e abrir outra aqui\n // seria uma segunda cobrança para quem acabou de pagar a primeira.\n if (resume?.sessionId) {\n setPhase('waiting')\n return\n }\n void open()\n }, [open, resume?.sessionId])\n\n /**\n * Pergunta ao servidor se o dinheiro entrou.\n *\n * A MESMA consulta serve ao relógio e ao botão \"Já paguei\" — duas portas para\n * a única pergunta que importa. `settled` garante que a resposta só vale uma\n * vez, mesmo que as duas cheguem juntas.\n */\n const check = useCallback(async (): Promise<boolean> => {\n if (!sessionId || settled.current) return false\n const shop = getShopProvider()\n if (!shop.settleCheckoutSession) return false\n try {\n // A pista que o adquirente pendurou na volta. Ela não decide nada — o\n // servidor confere com o adquirente antes de aceitar — mas fecha a compra\n // na hora em que a pessoa volta, em vez de esperar um webhook.\n const result = await shop.settleCheckoutSession(sessionId, provider, resume?.chargeToken ?? null)\n if (settled.current) return false\n if (result.state === 'paid' && result.orderId) {\n settled.current = true\n setPhase('settling')\n onPaid(result.orderId)\n return true\n }\n if (result.state === 'failed' || result.state === 'expired') {\n setError(\n result.reason\n ?? (result.state === 'expired'\n ? 'O código expirou. Gere um novo para continuar.'\n : 'O pagamento não foi concluído.'),\n )\n setPhase('error')\n }\n return false\n } catch {\n // Uma consulta que falhou não é um pagamento que falhou. Segue tentando.\n return false\n }\n }, [sessionId, provider, resume?.chargeToken, onPaid])\n\n useEffect(() => {\n if (phase !== 'waiting' || !sessionId) return\n let stopped = false\n const timer = setInterval(() => { if (!stopped) void check() }, POLL_MS)\n return () => { stopped = true; clearInterval(timer) }\n }, [phase, sessionId, check])\n\n async function confirmPaid() {\n setChecking(true)\n const paid = await check()\n // Só devolve o botão se NÃO pagou: se pagou, a tela já está indo embora e\n // um \"confirmando…\" que vira \"já paguei\" outra vez pisca à toa.\n if (!paid) setChecking(false)\n }\n\n /**\n * Copy the Pix code, including where `navigator.clipboard` does not exist.\n *\n * The clipboard API is only exposed in a SECURE CONTEXT: https, or localhost.\n * A store opened by IP on the local network, inside an app webview, or behind\n * a proxy without TLS does not have it — and there the button answered \"copy\n * it by hand\" in front of a 200-character code nobody copies by hand. The\n * whole checkout leans on that copy: without it the buyer does not pay.\n *\n * So the old road stays here as the fallback. `execCommand('copy')` is\n * deprecated and works on an insecure origin, which is exactly where the new\n * one fails.\n */\n async function copy() {\n if (!charge?.emv) return\n if (await copyText(charge.emv)) {\n setCopied(true)\n setTimeout(() => setCopied(false), 2400)\n return\n }\n toast.error('Copie o código manualmente')\n }\n\n if (phase === 'card' && brickKey) {\n const acquirer = gatewayLabel(provider)\n return (\n <div data-testid={TID.checkoutPayment} className=\"space-y-4 rounded-xl border bg-card p-6\">\n <div className=\"flex items-center gap-2\">\n <CreditCard className=\"h-5 w-5 text-primary\" />\n <h2 className=\"text-lg font-semibold\">Pague com cartão sem sair da loja</h2>\n </div>\n <p className=\"text-sm text-muted-foreground\">\n {acquirer\n ? `Os campos do cartão são da ${acquirer} e o número não passa por esta loja. Seu pedido é criado assim que o pagamento for aprovado.`\n : 'O número do cartão não passa por esta loja. Seu pedido é criado assim que o pagamento for aprovado.'}\n </p>\n {(total ?? amount) != null && (\n <p className=\"text-sm\">\n Valor: <strong data-testid={TID.checkoutPaymentTotal}>{money((total ?? amount)!)}</strong>\n </p>\n )}\n <CardBrick\n publicKey={brickKey}\n // Their SDK prices the installment options from this, so it must be\n // the total the server will actually charge — which is what the\n // page already shows and what a reprice would have sent us back a\n // step to correct.\n amount={total ?? amount ?? 0}\n email={input.customer?.email ?? null}\n onError={(message) => setError(message)}\n onSubmit={async (result: CardBrickResult) => {\n // Their contract: RESOLVE when the payment is handled, REJECT to keep\n // the form up. Rejecting is what lets a declined card be corrected in\n // place — a resolve here would tear the filled-in form down.\n const shop = getShopProvider()\n if (!shop.openCheckoutSession) throw new Error('sem gateway')\n try {\n const session = await shop.openCheckoutSession({\n ...input,\n cardToken: result.token,\n installments: result.installments,\n paymentMethodId: result.paymentMethodId,\n issuerId: result.issuerId,\n // Their anti-fraud reads this, and a card charged without it is\n // declined more often for no visible reason.\n deviceId: deviceSessionId(),\n })\n setSessionId(session.sessionId)\n setProvider(session.provider ?? input.provider ?? null)\n setTotal(session.total)\n\n // Approved on the spot is the common case for a card, so the order\n // already exists and there is nothing to poll.\n const orderId = (session as { orderId?: string | null }).orderId ?? null\n if (orderId) {\n settled.current = true\n setPhase('settling')\n onPaid(orderId)\n return\n }\n // In review: the page waits, and the webhook or the next tick\n // finishes it. Nothing is charged twice either way.\n setPhase('waiting')\n } catch (err) {\n const message = describeError(err, 'O pagamento não foi aprovado.')\n setError(message)\n // Rethrow so the Brick keeps the form — see above.\n throw err\n }\n }}\n />\n {error && (\n <p className=\"rounded-lg border border-destructive/40 bg-destructive/5 p-3 text-sm text-destructive\">\n {error}\n </p>\n )}\n <button\n type=\"button\"\n onClick={onBack}\n className=\"inline-flex min-h-11 items-center rounded-lg border px-4 py-2.5 text-sm font-medium transition hover:bg-muted\"\n >\n Voltar\n </button>\n </div>\n )\n }\n\n if (phase === 'redirect' && redirectUrl) {\n // Named where the rest of the acquirer's facts live, so this screen keeps no\n // map of its own; an acquirer the table does not carry gets a plain verb\n // rather than its slug printed at a buyer.\n const acquirer = gatewayLabel(provider)\n return (\n <div data-testid={TID.checkoutPayment} className=\"space-y-4 rounded-xl border bg-card p-6\">\n <div className=\"flex items-center gap-2\">\n <CreditCard className=\"h-5 w-5 text-primary\" />\n <h2 className=\"text-lg font-semibold\">\n {acquirer ? `Pague com cartão na página da ${acquirer}` : 'Pague com cartão'}\n </h2>\n </div>\n <p className=\"text-sm text-muted-foreground\">\n {acquirer\n ? `Os dados do cartão são digitados no ambiente seguro da ${acquirer} — a loja não vê o número. Ao terminar, você volta para cá e o pedido é criado.`\n : 'Os dados do cartão são digitados no ambiente seguro do provedor — a loja não vê o número. Ao terminar, você volta para cá e o pedido é criado.'}\n </p>\n {total != null && (\n <p className=\"text-sm\">\n Valor: <strong data-testid={TID.checkoutPaymentTotal}>{money(total)}</strong>\n </p>\n )}\n <div className=\"flex flex-wrap gap-2\">\n <button\n type=\"button\"\n onClick={() => {\n if (sessionId) rememberSession(sessionId, provider)\n window.location.assign(redirectUrl)\n }}\n className=\"inline-flex min-h-11 items-center gap-2 rounded-lg bg-primary px-5 py-2.5 text-sm font-semibold text-primary-foreground transition hover:opacity-90\"\n >\n <Lock className=\"h-4 w-4\" />\n {acquirer ? `Pagar com ${acquirer}` : 'Pagar com cartão'}\n </button>\n <button\n type=\"button\"\n onClick={onBack}\n className=\"inline-flex min-h-11 items-center rounded-lg border px-4 py-2.5 text-sm font-medium transition hover:bg-muted\"\n >\n Voltar\n </button>\n </div>\n </div>\n )\n }\n\n if (phase === 'opening') {\n return (\n // Same layout as the charge below, so nothing jumps when it arrives.\n <SkeletonGroup\n label=\"Preparando seu pagamento\"\n data-testid={TID.checkoutPayment}\n className=\"rounded-xl border bg-card p-6\"\n >\n <div className=\"flex items-center gap-2\">\n <Skeleton className=\"h-5 w-5 rounded-md\" />\n <Skeleton className=\"h-5 w-64 max-w-[70%]\" />\n </div>\n <Skeleton className=\"mt-2 h-3.5 w-full max-w-sm\" />\n <div className=\"mt-5 grid gap-5 sm:grid-cols-[auto_minmax(0,1fr)] sm:items-start\">\n <Skeleton className=\"mx-auto h-44 w-44 rounded-lg\" />\n <div className=\"min-w-0\">\n <Skeleton className=\"h-4 w-32\" />\n <Skeleton className=\"mt-4 h-3 w-28\" />\n <Skeleton className=\"mt-1 h-16 w-full rounded-lg\" />\n <div className=\"mt-3 flex flex-wrap items-center gap-3\">\n <Skeleton className=\"h-11 w-40 rounded-lg\" />\n <Skeleton className=\"h-11 w-32 rounded-lg\" />\n </div>\n </div>\n </div>\n </SkeletonGroup>\n )\n }\n\n if (phase === 'error') {\n return (\n <div data-testid={TID.checkoutPayment} className=\"space-y-3 rounded-xl border bg-card p-6\">\n <p data-testid={TID.checkoutError} className=\"rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive\">\n {error ?? 'Não conseguimos abrir a cobrança agora.'}\n </p>\n <div className=\"flex gap-2\">\n <button\n type=\"button\"\n onClick={() => { opened.current = false; void open() }}\n className=\"rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground transition hover:opacity-90\"\n >\n Tentar de novo\n </button>\n <button\n type=\"button\"\n onClick={onBack}\n className=\"rounded-lg border px-4 py-2.5 text-sm font-medium transition hover:bg-muted\"\n >\n Voltar\n </button>\n </div>\n </div>\n )\n }\n\n // A VOLTA do adquirente. Não há QR aqui e não deve haver: o pagamento\n // aconteceu na página deles, e o que falta é a loja confirmar. A tela avança\n // sozinha quando o dinheiro é confirmado, e continua tentando enquanto não é —\n // um cartão em análise leva minutos, não segundos.\n if (!charge) {\n return (\n <div data-testid={TID.checkoutPayment} className=\"space-y-3 rounded-xl border bg-card p-6\" aria-live=\"polite\">\n <div className=\"flex items-center gap-2\">\n <PulseDot />\n <h2 className=\"text-lg font-semibold\">Confirmando seu pagamento…</h2>\n </div>\n <p className=\"text-sm text-muted-foreground\">\n Assim que o pagamento for confirmado, seu pedido aparece aqui. Pode deixar esta tela aberta.\n </p>\n <button\n type=\"button\"\n onClick={() => { void confirmPaid() }}\n disabled={checking}\n className=\"inline-flex min-h-11 items-center gap-2 rounded-lg border border-primary px-4 py-2.5 text-sm font-semibold text-primary transition hover:bg-primary/5 disabled:opacity-60\"\n >\n {checking ? <PulseDot /> : <Check className=\"h-4 w-4\" />}\n {checking ? 'Verificando…' : 'Já paguei'}\n </button>\n </div>\n )\n }\n\n return (\n <div data-testid={TID.checkoutPayment} className=\"space-y-4\" aria-live=\"polite\">\n <div className=\"rounded-xl border bg-card p-6\">\n <div className=\"flex items-center gap-2\">\n <QrCode className=\"h-5 w-5 text-primary\" />\n <h2 className=\"text-lg font-semibold\">Pague com Pix para fechar o pedido</h2>\n </div>\n <p className=\"mt-1 text-sm text-muted-foreground\">\n {/* Dito antes de a pessoa esperar, não depois: é isto que diferencia\n este checkout do anterior, onde o pedido já existia. */}\n Seu pedido é criado assim que o pagamento entrar. Pode deixar esta tela aberta.\n </p>\n\n <div className=\"mt-5 grid gap-5 sm:grid-cols-[auto_minmax(0,1fr)] sm:items-start\">\n {/* Base64 bytes or a hosted URL, depending on the acquirer — one <img>\n either way, because to the buyer it is the same square.\n \n SIZED FOR A SCANNER, not for the layout. A QR is a grid, and what\n decides whether a phone reads it is how many whole pixels each\n module gets. Vindi's code is 69 modules wide, and at the 176px this\n used to be that is 2.55 px per module: every module edge lands mid\n pixel, the browser anti-aliases it, and the camera sees grey mush.\n 276px is exactly 4 px per module, so every edge falls on a pixel\n boundary and the code is sharp.\n \n The padding is the QUIET ZONE and not decoration. The spec asks for\n four clear modules on every side, and this SVG ships with none —\n its first rect sits at 0,0 — so the white p-4 (16px = 4 modules at\n this scale) is what a scanner needs to find the code's edges at all.\n \n `box-content` is load-bearing: Tailwind sizes border-box by default,\n so without it the padding would eat INTO the 276 and leave 244 —\n 3.54 px per module, the very problem this is fixing.\n \n `max-w-full` keeps a narrow phone from overflowing; there the square\n shrinks and the copy-and-paste code carries the payment anyway. */}\n {(charge?.qrcodeBase64 || charge?.qrcodeUrl) && (\n <img\n src={charge.qrcodeBase64\n ? `data:image/png;base64,${charge.qrcodeBase64}`\n : charge.qrcodeUrl!}\n alt=\"QR code do Pix\"\n width={276}\n height={276}\n className=\"mx-auto box-content h-[276px] w-[276px] max-w-full rounded-lg border bg-white p-4\"\n />\n )}\n <div className=\"min-w-0\">\n {total != null && (\n <p className=\"text-sm\">\n Valor: <strong data-testid={TID.checkoutPaymentTotal}>{money(total)}</strong>\n </p>\n )}\n <p className=\"mt-3 text-xs font-medium uppercase tracking-wide text-muted-foreground\">\n Pix copia e cola\n </p>\n <p\n data-testid={TID.pixCode}\n className=\"mt-1 max-h-24 overflow-y-auto break-all rounded-lg border bg-muted/40 p-3 font-mono text-xs\"\n >\n {charge?.emv}\n </p>\n {/* Quanto o código ainda vale. Só aparece quando o provedor deu um\n prazo — nada de inventar um relógio que ele não prometeu. */}\n {expiry.secondsLeft !== null && !expiry.expired && (\n <p className=\"mt-2 text-xs text-muted-foreground\">\n Este código vale por mais{' '}\n <span className=\"font-medium tabular-nums text-foreground\">\n {formatCountdown(expiry.secondsLeft)}\n </span>\n </p>\n )}\n\n {/* Expirado, o código na tela é papel velho: quem copiou e pagar agora\n paga em lugar nenhum. Então some, e no lugar fica a única ação que faz\n sentido — pedir outro. Aqui uma cobrança nova está CERTA: a antiga\n morreu, e o reaproveitamento no servidor só devolve a mesma enquanto\n ela estiver de pé. */}\n {expiry.expired && (\n <div className=\"mt-3 space-y-2\">\n <p data-testid={TID.checkoutExpired} className=\"text-sm text-muted-foreground\">\n O prazo deste código acabou. Gere outro para pagar.\n </p>\n <button\n type=\"button\"\n onClick={() => { opened.current = false; setCharge(null); void open() }}\n className=\"inline-flex min-h-11 items-center gap-2 rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground transition hover:opacity-90\"\n >\n Gerar novo código\n </button>\n </div>\n )}\n\n {/* \"Já paguei\" confirms nothing — it only hurries the same poll the\n screen already runs; the bank still answers. */}\n <div className=\"mt-3 flex flex-wrap items-center gap-3\" hidden={expiry.expired}>\n <button\n type=\"button\"\n onClick={copy}\n data-testid={TID.pixCopy}\n className=\"inline-flex min-h-11 items-center gap-2 rounded-lg bg-primary px-4 py-2.5 text-sm font-medium text-primary-foreground transition hover:opacity-90\"\n >\n {copied ? <Check className=\"h-4 w-4\" /> : <Copy className=\"h-4 w-4\" />}\n {copied ? 'Código copiado' : 'Copiar código'}\n </button>\n <button\n type=\"button\"\n onClick={() => { void confirmPaid() }}\n disabled={checking || phase === 'settling'}\n data-testid={TID.pixConfirm}\n className=\"inline-flex min-h-11 items-center gap-2 rounded-lg border border-primary px-4 py-2.5 text-sm font-semibold text-primary transition hover:bg-primary/5 disabled:opacity-60\"\n >\n {checking || phase === 'settling'\n ? <PulseDot />\n : <Check className=\"h-4 w-4\" />}\n {phase === 'settling' ? 'Confirmando…' : checking ? 'Verificando…' : 'Já paguei'}\n </button>\n </div>\n </div>\n </div>\n </div>\n\n <button\n type=\"button\"\n onClick={onBack}\n className=\"text-sm text-muted-foreground underline hover:text-foreground\"\n >\n Voltar e revisar o pedido\n </button>\n </div>\n )\n}\n","import { useEffect, useState } from 'react'\nimport { getShopProvider } from '@fayz-ai/shop/runtime'\nimport type { Order, ShippingAddressInput } from '@fayz-ai/shop/types'\nimport { useSessionStore } from '../stores/session.store'\nimport { hasCustomerAuth, relinkCustomer } from '../data/auth'\nimport { useMyOrders } from './use-my-orders'\n\n/**\n * What the store already knows about the person filling this checkout in.\n *\n * A signed-in buyer typed their CPF, their phone and their address the last time\n * they bought something, and every one of those is stored: the document and the\n * phone on their customer row, the address frozen on the order. Asking again is\n * asking someone to prove twice that they are themselves — and the CPF is the\n * field AbacatePay needs to create a client at all, so a blank one is also a\n * charge with no customer attached to it.\n *\n * Two sources because they are two different facts. The document belongs to the\n * PERSON and lives on the customer row; the address belongs to an ORDER and is\n * whatever they last shipped to. Reading the customer row is allowed by the\n * `plg_shop_customers_self_read` policy (`auth_user_id = auth.uid()`), so this\n * needs no new endpoint and no new grant — a guest simply resolves to nothing.\n */\nexport interface KnownCustomer {\n phone: string | null\n document: string | null\n address: ShippingAddressInput | null\n /** False until both lookups have settled, so a prefill never races typing. */\n ready: boolean\n}\n\nexport function useKnownCustomer(): KnownCustomer {\n const customerId = useSessionStore((s) => s.customerId)\n const { orders, loading: ordersLoading } = useMyOrders()\n const [contact, setContact] = useState<{ phone: string | null; document: string | null } | null>(null)\n const [checked, setChecked] = useState(false)\n\n useEffect(() => {\n if (!customerId) {\n setContact(null)\n setChecked(true)\n return\n }\n let cancelled = false\n const shop = getShopProvider()\n Promise.resolve(shop.getCustomer?.(customerId))\n // Signed in but nothing readable: the id is stale or the row unlinked, and\n // RLS answers both with an empty result. Re-resolve links it and returns it.\n .then(async (customer) => {\n if (customer || !hasCustomerAuth()) return customer ? { phone: customer.phone ?? null, document: customer.document ?? null } : null\n const relinked = await relinkCustomer()\n return relinked ? { phone: relinked.phone, document: relinked.document } : null\n })\n .then((found) => {\n if (cancelled) return\n setContact(found)\n })\n // A buyer who cannot be read is a buyer who fills the form in, which is\n // exactly what happened before this existed. Never a blocking error.\n .catch(() => { if (!cancelled) setContact(null) })\n .finally(() => { if (!cancelled) setChecked(true) })\n return () => { cancelled = true }\n }, [customerId])\n\n // The most recent order that actually shipped somewhere. An order without an\n // address (a pickup, a failed session) says nothing about where to deliver.\n const lastAddress = pickLastAddress(orders)\n\n return {\n phone: contact?.phone ?? null,\n document: contact?.document ?? null,\n address: lastAddress,\n ready: checked && !ordersLoading,\n }\n}\n\nfunction pickLastAddress(orders: readonly Order[]): ShippingAddressInput | null {\n for (const order of orders) {\n const address = (order as { shippingAddress?: ShippingAddressInput | null }).shippingAddress\n if (address && (address.postalCode || address.street)) return address\n }\n return null\n}\n","import React from 'react'\n\n/**\n * A checkout input with its label VISIBLE, not `sr-only`.\n *\n * A field whose name only lives in the placeholder loses it the moment someone\n * starts typing — which is exactly when they need to check they are in the\n * right one. Someone coming back to the form after an error finds four filled\n * boxes and nothing saying what they are.\n */\nexport function checkoutField(\n label: string,\n testId: string,\n value: string,\n onChange: (value: string) => void,\n props?: React.InputHTMLAttributes<HTMLInputElement>,\n) {\n return (\n <label className=\"block\">\n <span className=\"mb-1.5 block text-xs font-medium text-muted-foreground\">{label}</span>\n <input\n data-testid={testId}\n aria-label={label}\n value={value}\n onChange={(event) => onChange(event.target.value)}\n className=\"w-full rounded-lg border bg-background px-3.5 py-3 text-sm outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/10\"\n {...props}\n />\n </label>\n )\n}\n\n/** The same label and box, as a list (a region the country enumerates). */\nexport function checkoutSelect(\n label: string,\n testId: string,\n value: string,\n onChange: (value: string) => void,\n options: readonly { value: string; label: string }[],\n placeholder: string,\n props?: React.SelectHTMLAttributes<HTMLSelectElement>,\n) {\n return (\n <label className=\"block\">\n <span className=\"mb-1.5 block text-xs font-medium text-muted-foreground\">{label}</span>\n <select\n data-testid={testId}\n aria-label={label}\n value={value}\n onChange={(event) => onChange(event.target.value)}\n className=\"w-full rounded-lg border bg-background px-3.5 py-3 text-sm outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/10\"\n {...props}\n >\n <option value=\"\">{placeholder}</option>\n {options.map((option) => (\n <option key={option.value} value={option.value}>{option.label}</option>\n ))}\n </select>\n </label>\n )\n}\n","import React from 'react'\nimport { getCountrySchema, type AddressFieldKey, type AddressFieldSpec } from '@fayz-ai/core'\nimport { TID } from '../../lib/testids'\nimport { Skeleton, SkeletonGroup } from '../Skeleton'\nimport { useT } from '../../locales'\nimport type { StorefrontLanguage } from '../../locales/messages'\nimport { checkoutField, checkoutSelect } from './CheckoutField'\n\n/** The address as the form holds it. `state` is the region (UF, province). */\nexport interface AddressDraft {\n zip: string\n street: string\n number: string\n complement: string\n district: string\n city: string\n state: string\n}\n\nexport type PostalLookupState = 'idle' | 'loading' | 'found' | 'not-found'\n\nexport interface AddressFormProps {\n /** ISO2. The form takes this country's fields, order, labels and formats. */\n country: string\n language: StorefrontLanguage\n value: AddressDraft\n onChange(key: keyof AddressDraft, value: string): void\n /** The postal code field. The caller masks, looks up and fills the rest. */\n onPostalCode(value: string): void\n lookup: PostalLookupState\n /** The store's checkout policy for the one optional field it governs. */\n complement?: { visible: boolean; required: boolean }\n}\n\nconst DRAFT_KEY: Record<AddressFieldKey, keyof AddressDraft> = {\n postalCode: 'zip',\n street: 'street',\n number: 'number',\n complement: 'complement',\n district: 'district',\n city: 'city',\n region: 'state',\n}\n\n// The test ids every store's e2e suite already targets.\nconst TEST_ID: Record<AddressFieldKey, string> = {\n postalCode: TID.checkoutZip,\n street: TID.checkoutStreet,\n number: 'checkout-number',\n complement: 'checkout-complement',\n district: 'checkout-district',\n city: TID.checkoutCity,\n region: 'checkout-state',\n}\n\n/**\n * The delivery address, in the shape of the country it ships to.\n *\n * Brazil renders exactly the form the checkout always had: CEP first (it fills\n * the fields below it), number beside complement, bairro beside UF. Spain has\n * no number or bairro, takes a five-digit postal code and picks the province\n * from a list the postal code pre-selects. Any other country gets the generic\n * shape. The layout is the schema's `rows`; nothing here names a country.\n */\nexport function AddressForm({ country, language, value, onChange, onPostalCode, lookup, complement }: AddressFormProps) {\n const t = useT()\n const schema = getCountrySchema(country)\n const specs = new Map(schema.fields.map((spec) => [spec.key, spec]))\n const showComplement = complement?.visible !== false\n const requireComplement = complement?.required === true\n\n function input(spec: AddressFieldSpec) {\n const key = DRAFT_KEY[spec.key]\n const label = spec.label[language]\n const required = spec.required || (spec.key === 'complement' && requireComplement)\n const basePlaceholder = spec.placeholder?.[language] ?? label\n const placeholder = required ? basePlaceholder : t('checkout.address.optional', { label: basePlaceholder })\n\n if (spec.key === 'postalCode') {\n return checkoutField(label, TEST_ID.postalCode, value.zip, onPostalCode, {\n placeholder,\n inputMode: schema.postal.inputMode,\n autoComplete: 'postal-code',\n })\n }\n if (spec.key === 'region' && schema.region.input === 'select' && schema.regions) {\n return checkoutSelect(\n label,\n TEST_ID.region,\n value.state,\n (next) => onChange('state', next),\n schema.regions.map((region) => ({\n value: schema.region.stores === 'code' ? region.code : region.name,\n label: region.name,\n })),\n t('checkout.address.choose'),\n { autoComplete: spec.autoComplete },\n )\n }\n return checkoutField(label, TEST_ID[spec.key], value[key], (next) => onChange(key, next), {\n placeholder,\n ...(spec.autoComplete ? { autoComplete: spec.autoComplete } : {}),\n })\n }\n\n function postalHint(): React.ReactNode {\n if (lookup === 'loading') {\n return (\n <SkeletonGroup label={t('checkout.address.lookingUp')} className=\"grid gap-1.5 px-1\">\n <Skeleton className=\"h-2.5 w-40\" />\n <Skeleton className=\"h-2.5 w-24\" />\n </SkeletonGroup>\n )\n }\n if (schema.postal.lookup === 'viacep') {\n return (\n <p className=\"px-1 text-xs text-muted-foreground\">\n {lookup === 'not-found' ? t('checkout.address.notFound') : t('checkout.address.filled')}\n </p>\n )\n }\n if (schema.postal.lookup === 'prefix' && lookup === 'found') {\n return <p className=\"px-1 text-xs text-muted-foreground\">{t('checkout.address.regionFromPostal')}</p>\n }\n return null\n }\n\n return (\n <div className=\"grid gap-3\">\n {schema.rows.map((row) => {\n const cells = row.filter((key) => specs.has(key) && (key !== 'complement' || showComplement))\n if (cells.length === 0) return null\n if (cells.length === 1 && cells[0] === 'postalCode') {\n // CEP first, because it FILLS the fields below it. With it at the\n // bottom the buyer typed street, district, city and UF by hand and\n // only then reached the one field that would have supplied all four.\n return (\n <div key=\"postalCode\" className=\"grid gap-1 sm:grid-cols-[200px_1fr] sm:items-center\">\n {input(specs.get('postalCode')!)}\n {postalHint()}\n </div>\n )\n }\n // A paired row keeps its two columns when the store hides one of the\n // pair (the complement), as the form always did.\n if (row.length === 1) return <React.Fragment key={cells[0]}>{input(specs.get(cells[0]!)!)}</React.Fragment>\n return (\n <div key={cells.join('-')} className=\"grid grid-cols-2 gap-3\">\n {cells.map((key) => <React.Fragment key={key}>{input(specs.get(key)!)}</React.Fragment>)}\n </div>\n )\n })}\n </div>\n )\n}\n","import React from 'react'\nimport { Check } from 'lucide-react'\nimport { documentDigits } from '@fayz-ai/shop'\n\n/**\n * A signed-in buyer's contact, as one card instead of four boxes.\n *\n * Whoever is signed in and already gave their name, phone and CPF has nothing\n * to type in step 1: the store knows it all (profile, last order). Showing the\n * full form made them re-read and re-confirm it on every order. The card says\n * who is buying; «Alterar» brings the fields back.\n *\n * The CPF is masked (***.170.431-**), the same convention receipts and the\n * Nota Fiscal use: the screen can be seen by whoever stands behind the buyer,\n * and the digits shown are still enough to recognise one's own. A CNPJ is a\n * company's public id and shows whole.\n */\nexport function maskDocument(raw: string): string {\n const d = documentDigits(raw)\n if (d.length === 11) return `***.${d.slice(3, 6)}.${d.slice(6, 9)}-**`\n if (d.length === 14) return `${d.slice(0, 2)}.${d.slice(2, 5)}.${d.slice(5, 8)}/${d.slice(8, 12)}-${d.slice(12)}`\n return raw\n}\n\n/** (21) 97122-1016 / (21) 3333-4444; a +55 prefix is dropped. */\nexport function formatBrPhone(raw: string): string {\n let d = raw.replace(/\\D/g, '')\n if (d.startsWith('55') && (d.length === 12 || d.length === 13)) d = d.slice(2)\n if (d.length === 11) return `(${d.slice(0, 2)}) ${d.slice(2, 7)}-${d.slice(7)}`\n if (d.length === 10) return `(${d.slice(0, 2)}) ${d.slice(2, 6)}-${d.slice(6)}`\n return raw\n}\n\nexport function ContactSummary({ name, email, phone, document, onEdit, onSignOut, labels }: {\n name: string\n email: string\n phone?: string\n document?: string\n onEdit: () => void\n onSignOut: () => void\n labels: { edit: string; notYou: string; signOut: string }\n}) {\n const line = [phone ? formatBrPhone(phone) : null, document ? maskDocument(document) : null].filter(Boolean).join(' · ')\n return (\n <div data-testid=\"checkout-contact-summary\" className=\"rounded-xl border bg-card p-4\">\n <div className=\"flex items-start gap-3\">\n <span className=\"mt-0.5 grid h-6 w-6 shrink-0 place-items-center rounded-full bg-primary/15 text-primary\" aria-hidden>\n <Check className=\"h-3.5 w-3.5\" />\n </span>\n <div className=\"min-w-0 flex-1\">\n <p className=\"truncate text-sm font-semibold\">{name}</p>\n <p className=\"truncate text-sm text-muted-foreground\">{email}</p>\n {line && <p className=\"truncate text-sm text-muted-foreground\">{line}</p>}\n </div>\n <button\n type=\"button\"\n onClick={onEdit}\n data-testid=\"checkout-contact-edit\"\n className=\"shrink-0 text-sm font-medium text-primary hover:underline\"\n >\n {labels.edit}\n </button>\n </div>\n <p className=\"mt-3 border-t pt-3 text-xs text-muted-foreground\">\n {labels.notYou}{' '}\n <button\n type=\"button\"\n onClick={onSignOut}\n data-testid=\"checkout-contact-sign-out\"\n className=\"font-medium text-foreground hover:underline\"\n >\n {labels.signOut}\n </button>\n </p>\n </div>\n )\n}\n","import { getCountrySchema, normalizePostalCode } from '@fayz-ai/core'\nimport { documentDigits } from '@fayz-ai/shop'\nimport type { ShippingAddressInput } from '@fayz-ai/shop/types'\n\nexport interface CheckoutAddressFields {\n zip: string\n street: string\n number: string\n complement: string\n district: string\n city: string\n state: string\n phone: string\n document: string\n}\n\n/**\n * What the buyer typed, as the order stores it, with the country it is in.\n *\n * Only the fields the country's form has travel: a Spanish address has no\n * number or bairro of its own (the number is in the street line). Brazil keeps\n * exactly the payload it always sent, plus `country: 'BR'`.\n */\nexport function toShippingAddress(form: CheckoutAddressFields, country: string): ShippingAddressInput {\n const schema = getCountrySchema(country)\n const isBrazil = schema.iso2 === 'BR'\n const has = (key: 'number' | 'district') => schema.fields.some((f) => f.key === key)\n return {\n postalCode: isBrazil ? form.zip.trim() : normalizePostalCode(form.zip, country),\n street: form.street.trim(),\n number: has('number') ? form.number.trim() || undefined : undefined,\n complement: form.complement.trim() || undefined,\n district: has('district') ? form.district.trim() || undefined : undefined,\n city: form.city.trim(),\n // A UF is a code and is upper-cased; a province is a name and keeps its case.\n state: schema.region.stores === 'code' ? form.state.trim().toUpperCase() : form.state.trim(),\n country: schema.iso2,\n phone: form.phone.trim() || undefined,\n document: (isBrazil ? documentDigits(form.document) : form.document.trim().toUpperCase()) || undefined,\n }\n}\n","import React from 'react'\nimport { MapPin } from 'lucide-react'\nimport { countryName } from '@fayz-ai/core'\nimport { useStorefrontConfig } from '../../document/config'\nimport { useBuyerCountry } from '../../hooks/use-buyer-country'\nimport { useT } from '../../locales'\n\nfunction flag(iso2: string): string {\n return iso2\n .toUpperCase()\n .replace(/[^A-Z]/g, '')\n .split('')\n .map((c) => String.fromCodePoint(0x1f1e6 + c.charCodeAt(0) - 65))\n .join('')\n}\n\n/**\n * \"Ship to: 🇪🇸 Spain\", as a native select: the platform's own list is the\n * most accessible country picker there is, on every device.\n */\nexport function CountrySelect({ country, allowed, onChange, className }: {\n country: string\n allowed: readonly string[]\n onChange(country: string): void\n className?: string\n}) {\n const t = useT()\n const config = useStorefrontConfig()\n return (\n <label className={`flex items-center gap-2 text-sm ${className ?? ''}`}>\n <MapPin className=\"h-4 w-4 shrink-0 text-muted-foreground\" aria-hidden />\n <span className=\"text-muted-foreground\">{t('country.deliverTo')}</span>\n <select\n data-testid=\"deliver-to-country\"\n aria-label={t('country.label')}\n value={country}\n onChange={(event) => onChange(event.target.value)}\n className=\"rounded-lg border bg-background px-2.5 py-1.5 text-sm font-medium outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/10\"\n >\n {allowed.map((iso2) => (\n <option key={iso2} value={iso2}>\n {flag(iso2)} {countryName(iso2, config.language)}\n </option>\n ))}\n </select>\n </label>\n )\n}\n\n/**\n * The store-wide \"Deliver to\" control, for a header. Renders nothing for a\n * store that ships to one country, so dropping it into any chrome is safe.\n */\nexport function DeliverToPicker({ className }: { className?: string }) {\n const buyer = useBuyerCountry()\n if (buyer.allowed.length < 2) return null\n return <CountrySelect className={className} country={buyer.country} allowed={buyer.allowed} onChange={buyer.setCountry} />\n}\n","import React, { useEffect, useState } from 'react'\nimport { identifyStorefrontBuyer, trackStorefront } from '../analytics/bus'\nimport { CreditCard, Lock, ShieldCheck } from 'lucide-react'\nimport { getShopProvider } from '@fayz-ai/shop/runtime'\nimport { documentDigits, formatDocument, isChargeableProvider, isValidDocument, supportsCard } from '@fayz-ai/shop'\nimport { formatPostalCode, normalizePostalCode, lookupPostalCode, getCountrySchema, validateAddress } from '@fayz-ai/core'\nimport type { CustomerAddress, PaymentMethodKind, ShippingAddressInput } from '@fayz-ai/shop/types'\nimport { prefersReducedMotion } from '../lib/motion'\nimport {\n useCartStore,\n selectSubtotal,\n selectDiscountTotal,\n selectShipping,\n selectRequiresShipping,\n selectTotal,\n} from '../stores/cart.store'\nimport { useSessionStore } from '../stores/session.store'\nimport { useDeliveryStore } from '../stores/delivery.store'\nimport { useStorefrontConfig } from '../document/config'\nimport { returnPath } from '../app/return-path'\nimport { Link, navigateTo } from '../app/router'\nimport { formatMoney } from '../lib/format'\nimport { TID } from '../lib/testids'\nimport { useDiscountValidator } from '../hooks/use-discount-validator'\nimport { toast } from '../stores/toast.store'\nimport { useStorefrontHead } from '../hooks/use-storefront-head'\nimport { SignInModal } from '../components/account/SignInModal'\nimport { SmoothImage } from '../components/SmoothImage'\nimport { Slot } from '../extend/slots'\nimport { placeStorefrontOrder } from '../workflows/checkout'\nimport { CheckoutSteps, type CheckoutStep } from '../components/checkout/CheckoutSteps'\nimport { CheckoutPayment, recallSessionProvider } from '../components/checkout/CheckoutPayment'\nimport { SuccessMark } from '../components/order/SuccessMark'\nimport { Skeleton, SkeletonGroup } from '../components/Skeleton'\nimport { errorMessage } from '../lib/errors'\nimport { useKnownCustomer } from '../hooks/use-known-customer'\nimport { useBuyerCountry } from '../hooks/use-buyer-country'\nimport { AddressForm } from '../components/checkout/AddressForm'\nimport { checkoutField as field } from '../components/checkout/CheckoutField'\nimport { ContactSummary } from '../components/checkout/ContactSummary'\nimport { signOutCustomer } from '../data/auth'\nimport { toShippingAddress } from '../lib/checkout-address'\nimport { CountrySelect } from '../components/delivery/DeliverToPicker'\nimport { useT } from '../locales'\nimport type { MessageKey } from '../locales/messages'\n\ninterface CheckoutForm {\n email: string\n name: string\n phone: string\n document: string\n street: string\n city: string\n zip: string\n number: string\n complement: string\n district: string\n state: string\n}\n\ntype AddressMode = 'saved' | 'new'\n\n/**\n * There is no payment service provider connected, so the checkout does not ask\n * for a card number. It used to, prefilled with 4242 4242 4242 4242, and the\n * digits were validated and then thrown away — a PAN typed into React state\n * that reaches no processor is a liability with no upside. The buyer states how\n * they intend to pay; the order stays `pending` until the merchant confirms the\n * money arrived (shop_confirm_payment, which since 0019 only they can call).\n */\nconst PAYMENT_LABELS: Record<PaymentMethodKind, { label: MessageKey; hint: MessageKey }> = {\n pix: { label: 'payment.pix.label', hint: 'payment.pix.hint' },\n // O cartão tem DOIS significados agora, e o texto muda com a loja: sem\n // adquirente é a maquininha do entregador; com adquirente é a página segura\n // dele — prometer \"maquininha\" para quem vai ser redirecionado é a loja\n // mentindo sobre a própria entrega.\n credit_card: { label: 'payment.credit_card.label', hint: 'payment.credit_card.hint' },\n debit_card: { label: 'payment.debit_card.label', hint: 'payment.debit_card.hint' },\n boleto: { label: 'payment.boleto.label', hint: 'payment.boleto.hint' },\n cash: { label: 'payment.cash.label', hint: 'payment.cash.hint' },\n other: { label: 'payment.other.label', hint: 'payment.other.hint' },\n}\n\n/** Payment rails that exist only in Brazil. */\nconst BRAZIL_ONLY: readonly PaymentMethodKind[] = ['pix', 'boleto']\n\n/**\n * What the buyer reads when shop_place_order refuses.\n *\n * The RPC's messages are written for whoever reads the logs (\"shop_place_order:\n * customer email mismatch\", prefix and all), and PostgrestError is not an Error\n * instance, so the old check showed nothing useful either way.\n */\nfunction placeOrderMessage(err: unknown, t: ReturnType<typeof useT>): string {\n const message = errorMessage(err)\n if (/customer (email mismatch|does not belong|belongs to another)/i.test(message)) {\n return t('error.sessionMismatch')\n }\n if (/out of stock|insufficient|estoque/i.test(message)) {\n return t('error.outOfStock')\n }\n if (/delivery not available|postal code/i.test(message)) {\n return t('error.unserved')\n }\n return message.replace(/^shop_[a-z_]+:\\s*/i, '') || t('error.placeOrder')\n}\n\n/**\n * Build de desenvolvimento? Mesmo cast defensivo do `isDevBuild()` do core: o\n * SDK também é carregado em Node (testes, render headless), onde\n * `import.meta.env` simplesmente não existe e o acesso direto explode.\n */\nconst DEV_BUILD: boolean = (() => {\n try {\n return (import.meta as unknown as { env?: { DEV?: boolean } }).env?.DEV === true\n } catch {\n return false\n }\n})()\n\n\nconst CHECKOUT_STEP_NAMES: Record<CheckoutStep, string> = { 1: 'contact', 2: 'delivery', 3: 'payment', 4: 'done' }\n\nexport function CheckoutPage() {\n const config = useStorefrontConfig()\n const cart = useCartStore()\n const session = useSessionStore()\n const delivery = useDeliveryStore()\n const validateDiscount = useDiscountValidator()\n const t = useT()\n useStorefrontHead({ title: t('checkout.title', { store: config.name }) })\n\n // Where it ships decides the address form, its checks and which payment\n // rails exist: Pix and boleto are Brazilian, and offering them to a Spanish\n // address is offering a way to pay that cannot work.\n const buyer = useBuyerCountry()\n const country = buyer.country\n const isBrazil = country === 'BR'\n const countrySchema = getCountrySchema(country)\n const paymentMethods = isBrazil\n ? config.payments.methods\n : config.payments.methods.filter((method) => !BRAZIL_ONLY.includes(method))\n\n /**\n * The merchant's checkout policy, if they have saved one.\n *\n * `requiresAccount` is the storefront half of a rule the SERVER enforces\n * (0045's trigger refuses a guest order outright), which is why it gates the\n * button rather than merely hiding the \"entrar\" link: collecting a whole form\n * and failing at the last click is the worst possible way to tell someone they\n * need an account.\n *\n * The optional fields default to VISIBLE-AND-OPTIONAL when nothing is saved,\n * which is exactly how the form behaved before this policy existed.\n */\n const policy = config.policy\n const requiresAccount = policy?.guestCheckout === false\n const fieldPolicy = policy?.checkoutFields ?? {}\n type OptionalField = 'phone' | 'complement' | 'document'\n /**\n * A connected acquirer needs the buyer's CPF to mint the charge, so with a\n * gateway on, \"document\" stops being the merchant's preference: hiding it\n * would only move the failure to the gateway's opaque rejection.\n *\n * Either signal counts. `paymentProvider` is what the merchant picks in\n * Pagamentos and is the only one they can actually change; `mode` is written\n * into the app's own store document and no screen edits it.\n */\n const gatewayCheckout = config.payments.mode === 'gateway' || !!policy?.paymentProvider\n /**\n * `document` defaults to HIDDEN, unlike every other optional field.\n *\n * The others default to visible because they always were. This one is new, and\n * \"visible unless turned off\" would have made a CPF box appear on every\n * storefront in the fleet the moment this shipped — a product change no\n * merchant asked for. It shows when the store opts in, or when a gateway makes\n * it unavoidable.\n */\n const shows = (key: OptionalField) =>\n key === 'document'\n ? (isBrazil && gatewayCheckout) || fieldPolicy.document?.visible === true\n : fieldPolicy[key]?.visible !== false\n const requires = (key: OptionalField) =>\n // A CPF is Brazil's; elsewhere the tax id is the buyer's to give or not.\n key === 'document' && !isBrazil\n ? countrySchema.taxId?.required === 'always'\n : key === 'document' || key === 'phone'\n // Both are the acquirer's demand rather than the merchant's preference.\n // The CPF was always this; the phone joined it once a real charge proved\n // it: Vindi refuses a customer carrying no contact at all with\n // \"person_contacts.value: não é válido\", and AbacatePay's customer block is\n // all-or-nothing, so a missing phone silently costs the customer record.\n // Asking on the form beats a rejection the buyer cannot act on.\n ? gatewayCheckout || (fieldPolicy[key]?.visible === true && fieldPolicy[key]?.required === true)\n : fieldPolicy[key]?.visible !== false && fieldPolicy[key]?.required === true\n\n const [selectedAddressId, setSelectedAddressId] = useState('new')\n const [savedAddresses, setSavedAddresses] = useState<CustomerAddress[]>([])\n // False by default: a guest has no address book to wait for.\n const [addressesLoading, setAddressesLoading] = useState(false)\n // 'new' until the address book actually loads: an empty book must show an\n // empty form, never a placeholder address belonging to nobody.\n const [addressMode, setAddressMode] = useState<AddressMode>('new')\n /**\n * A VOLTA de quem pagou com cartão na página do adquirente.\n *\n * Lido uma vez, na montagem, porque é uma página nova: o formulário, o passo e\n * o método escolhido morreram no redirecionamento, e o que sobrou foi o id da\n * sessão na URL. Com ele o checkout não recomeça — ele confirma.\n *\n * A pista do adquirente (`token_transaction`) vem junto quando ele a\n * pendura na volta. Ela não prova nada aqui: o servidor confere com o\n * adquirente antes de aceitá-la. Serve para fechar a compra na hora, em vez de\n * esperar o webhook.\n */\n const [resume] = useState(() => {\n if (typeof window === 'undefined') return null\n const params = new URLSearchParams(window.location.search)\n const sessionId = params.get('vindi_session') ?? params.get('pay_session')\n if (!sessionId) return null\n return {\n sessionId,\n provider: recallSessionProvider(sessionId),\n chargeToken: params.get('token_transaction'),\n }\n })\n const [paymentMethod, setPaymentMethod] = useState<PaymentMethodKind>(\n resume ? 'credit_card' : paymentMethods[0] ?? 'pix')\n // The country can change mid-checkout; a method it does not offer must not stay picked.\n useEffect(() => {\n if (!paymentMethods.includes(paymentMethod) && paymentMethods[0]) setPaymentMethod(paymentMethods[0])\n }, [paymentMethods, paymentMethod])\n // What the store already knows about whoever is signed in: document and phone\n // from their record, address from their last order. It fills only what is empty\n // (see the effect below) — anyone arriving signed out sees no difference.\n const known = useKnownCustomer()\n const [form, setForm] = useState<CheckoutForm>({\n email: session.email ?? '',\n name: session.name ?? '',\n phone: '',\n document: '',\n street: '',\n city: '',\n zip: '',\n number: '',\n complement: '',\n district: '',\n state: '',\n })\n\n // Applied afterwards, and only where the field is still blank: the read is\n // async and the person may already be typing when it lands. Overwriting there\n // would erase what they had just written.\n React.useEffect(() => {\n if (!known.ready) return\n setForm((current) => ({\n ...current,\n phone: current.phone || known.phone || '',\n document: current.document || known.document || '',\n zip: current.zip || known.address?.postalCode || '',\n street: current.street || known.address?.street || '',\n number: current.number || known.address?.number || '',\n complement: current.complement || known.address?.complement || '',\n district: current.district || known.address?.district || '',\n city: current.city || known.address?.city || '',\n state: current.state || known.address?.state || '',\n }))\n }, [known.ready, known.phone, known.document, known.address])\n /**\n * Em que passo a pessoa está.\n *\n * O checkout era uma página só: todos os campos de uma vez, um botão\n * \"Comprar agora\" no fim, e a animação de sucesso disparando antes de existir\n * pagamento. Agora são quatro — dados, entrega, pagamento, pronto — e o\n * quarto só chega quando o dinheiro entrou.\n */\n // Quem volta do adquirente volta no passo do pagamento, não no primeiro:\n // os dados já foram dados, a cobrança já foi feita, e recomeçar do zero\n // pediria de novo tudo o que a pessoa acabou de preencher.\n const [step, setStep] = useState<CheckoutStep>(resume ? 3 : 1)\n const reportedStart = React.useRef(false)\n useEffect(() => {\n if (reportedStart.current) return\n reportedStart.current = true\n if (!resume) {\n trackStorefront('checkout_started', {\n cart_count: cart.lines.reduce((n, l) => n + l.quantity, 0),\n // What the cart is worth when the checkout opens: the value an ad\n // platform optimises InitiateCheckout for.\n cart_subtotal: Math.round(cart.lines.reduce((sum, l) => sum + l.unitPrice * l.quantity, 0) * 100) / 100,\n })\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n // Each step the buyer reaches is a step of the conversion funnel, and the\n // e-mail typed in «Dados» is what ties this visit to the order the server\n // reports (hashed, see storeBuyerId).\n const reportedStep = React.useRef<CheckoutStep | null>(null)\n useEffect(() => {\n if (reportedStep.current === step) return\n reportedStep.current = step\n trackStorefront('checkout_step_viewed', { step, step_name: CHECKOUT_STEP_NAMES[step], resume: Boolean(resume) })\n if (step >= 2 && /.+@.+\\..+/.test(form.email)) identifyStorefrontBuyer(form.email)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [step])\n // A signed-in buyer whose contact is complete sees a card, not the form,\n // and starts on «Entrega» (see ContactSummary). `contactKnown` turns true\n // once the profile read answered; `editingContact` is «Alterar».\n const [contactKnown, setContactKnown] = useState(false)\n const [editingContact, setEditingContact] = useState(false)\n const skippedContact = React.useRef(false)\n\n // Retirada (0094). O modo vem da mesma store que a barra do cardápio usa, e\n // por isso não há como as duas telas discordarem sobre o que a pessoa marcou.\n const fulfillmentType = useDeliveryStore((s) => s.fulfillmentType)\n const scheduledFor = useDeliveryStore((s) => s.scheduledFor)\n /** O ponto de referência do endereço escolhido no cardápio, se houver. */\n const deliveryReference = useDeliveryStore((s) => {\n const kept = s.savedAddresses.find((a) => a.id === s.selectedAddressId)\n return kept?.reference?.trim() || ''\n })\n const isPickup = fulfillmentType === 'pickup'\n const [dbPickup, setDbPickup] = useState<ShippingAddressInput | null>(null)\n useEffect(() => {\n if (!isPickup) return\n let alive = true\n void (async () => {\n // Prefere o banco; cai para a config. Ver o comentário em\n // StorefrontDeliveryConfig.pickupAddress para por que ainda há um fallback.\n const settings = await getShopProvider().getPublicStoreSettings?.().catch(() => null)\n if (alive && settings?.pickupAddress) setDbPickup(settings.pickupAddress)\n })()\n return () => { alive = false }\n }, [isPickup])\n const pickupAddress: ShippingAddressInput | null =\n dbPickup ?? (config.delivery?.pickupAddress as ShippingAddressInput | undefined) ?? null\n const [paidOrderId, setPaidOrderId] = useState<string | null>(null)\n const [error, setError] = useState<string | null>(null)\n const [discountCode, setDiscountCode] = useState('')\n const [discountError, setDiscountError] = useState<string | null>(null)\n const [discountSuccess, setDiscountSuccess] = useState<string | null>(null)\n const [applyingDiscount, setApplyingDiscount] = useState(false)\n const [showSignin, setShowSignin] = useState(false)\n const [placing, setPlacing] = useState(false)\n /**\n * Um pedido foi criado e a tela está indo embora — ver a guarda do carrinho\n * vazio. É um REF, não estado: `cart.clear()` re-renderiza pela assinatura do\n * zustand, fora do lote do React, então um `setState` aqui ainda não teria\n * sido aplicado quando a guarda rodasse — e o comprador ia parar no catálogo\n * com o pedido feito.\n */\n const leaving = React.useRef(false)\n const [zipLookup, setZipLookup] = useState<'idle' | 'loading' | 'found' | 'not-found'>('idle')\n\n const subtotal = selectSubtotal(cart)\n const discountTotal = selectDiscountTotal(cart)\n // Na retirada não há frete, e o número mostrado tem de ser o número cobrado:\n // o trigger da 0094 zera o frete no servidor, então uma tela que ainda somasse\n // a taxa prometeria um total que o pedido não teria — e o comprador veria a\n // diferença só no fim.\n const shippingRaw = selectShipping(cart, config)\n const shipping = isPickup ? 0 : shippingRaw\n const total = selectTotal(cart, config) - (isPickup ? shippingRaw : 0)\n\n const checkoutSlotContext = { subtotal, total }\n\n /**\n * Só existe cobrança quando há adquirente E o método escolhido é um que ele\n * sabe cobrar. Hoje isso é Pix: o cartão da AbacatePay não é transparente\n * (o /transparents/create recusa `CARD` com 422), então prometer cartão aqui\n * seria vender um caminho que termina em erro.\n *\n * \"Há adquirente\" olha PRIMEIRO para o que o lojista escolheu em Pagamentos\n * (`paymentProvider`) e só depois para o `mode` do documento da loja. O modo\n * é escrito no arquivo do app e nenhuma tela o edita — quem colasse a chave\n * do provedor veria absolutamente nada mudar, que é um beco sem saída.\n */\n /** O que a sessão de checkout congela. Memoizado porque `CheckoutPayment`\n * abre a cobrança UMA vez e um objeto novo a cada render abriria outra. */\n const checkoutSessionInput = React.useMemo(() => ({\n items: cart.lines.map((line) => ({\n productId: line.productId,\n variantId: line.variantId ?? null,\n quantity: line.quantity,\n optionsLabel: line.optionsLabel ?? null,\n })),\n // The document and the phone travel WITH the buyer, not only inside the\n // address.\n //\n // The acquirer charges a PERSON: Vindi refuses a charge with no document\n // (\"Informe o CPF ou CNPJ do comprador\"), and AbacatePay's customer block is\n // all-or-nothing — name, email, taxId and cellphone, or no customer at all.\n // With two of the four it had been opening charges while registering nobody,\n // which is the \"no client was created\" the store saw in the provider account.\n //\n // The field was already asked for on screen: with an acquirer connected,\n // `requires('document')` is true and nobody gets past step 1 without filling\n // it in. What was missing was forwarding it to whoever charges. On the ORDER\n // it still travels inside the address, because of shop_place_order's\n // signature — different roads.\n customer: {\n name: form.name.trim(),\n email: form.email.trim(),\n document: documentDigits(form.document) || undefined,\n phone: form.phone.trim() || undefined,\n },\n shippingAddress: deliveryAddress(),\n discountCode: cart.discountCode ?? null,\n paymentMethod,\n // Qual adquirente cobra. Sai dos ajustes da loja e não de uma escolha do\n // comprador — a função reconfere de qualquer forma, mas mandar daqui é o\n // que faz o clique bater na função do gateway que a loja realmente conectou.\n provider: policy?.paymentProvider ?? null,\n // The market (0116) the acquirer's open function prices and charges in.\n market: config.market?.code ?? null,\n country,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), [cart.lines, cart.discountCode, form, paymentMethod, policy?.paymentProvider, country, config.market?.code])\n\n /**\n * Quem sabe se a loja cobra é o SERVIDOR, e a resposta dele é o que vale.\n *\n * Antes isto dependia de duas configurações que o lojista tinha que acertar\n * em telas diferentes — o modo no documento do app e o provedor em\n * Pagamentos. Ele conectava a AbacatePay, voltava à loja e nada acontecia,\n * sem nenhuma pista do porquê. Agora o checkout TENTA abrir a cobrança e o\n * servidor responde; se não houver adquirente, ele avisa e a tela oferece o\n * pedido sem cobrança.\n *\n * A única configuração que ainda manda é a explícita: se o lojista nomeou um\n * provedor que a função não sabe cobrar, respeitamos a escolha dele.\n */\n /**\n * Formas que o servidor RECUSOU, por método e não em bloco.\n *\n * Era um booleano só, e virou este conjunto quando o cartão passou a poder ser\n * cobrado: \"a loja não aceita cartão\" desligava também o Pix, que a mesma loja\n * aceitava — e o comprador ficava sem a forma que funcionava por causa da que\n * não funcionava.\n */\n const [unavailable, setUnavailable] = useState<readonly PaymentMethodKind[]>([])\n /**\n * O cartão desta loja é cobrado online?\n *\n * Otimista de propósito: a loja tem adquirente e ninguém disse que não. Se o\n * adquirente recusar cartão — o lojista não habilitou —, a tela cai no pedido\n * sem cobrança, que é o que sempre fez, e este texto some junto.\n */\n const cardIsCharged =\n // Outside Brazil a card is charged online only by a real acquirer: with no\n // provider the online panel is the mock's Pix, which a Spanish buyer cannot\n // pay. Without one the order is placed pending, as an offline payment is.\n (isBrazil || !!policy?.paymentProvider)\n && !unavailable.includes('credit_card')\n && (!policy?.paymentProvider || isChargeableProvider(policy.paymentProvider))\n // ...and the acquirer has to charge CARDS, not merely exist. AbacatePay shut\n // card down for new accounts: asking anyway does not answer \"no card\", it\n // answers with an error — and before this line the buyer only found out after\n // choosing, waiting, and taking a refusal in the face.\n && (!policy?.paymentProvider || supportsCard(policy.paymentProvider))\n const acquirerMissing = unavailable.includes(paymentMethod)\n const chargesOnline =\n // Pix é cobrado dentro da loja; cartão é pago na página do adquirente e\n // volta para cá. Débito, dinheiro e \"combinar\" nunca foram cobrança online.\n // `cardIsCharged` rather than a bare `credit_card`: card is charged online\n // only where the acquirer charges cards. Where it does not, this screen\n // offers the order without a charge — the card-reader road, as it always was.\n (paymentMethod === 'pix' || (paymentMethod === 'credit_card' && cardIsCharged))\n && !acquirerMissing\n // A lista deixou de morar aqui: cada adquirente tem UM par de funções, e a\n // tabela que diz qual é qual vive no @fayz-ai/shop, ao lado de quem as chama.\n // Duas cópias eram uma vitrine que oferece QR para um gateway que o provider\n // não sabe acionar, ou o contrário.\n && (!policy?.paymentProvider || isChargeableProvider(policy.paymentProvider))\n const money = (value: number) => formatMoney(value, config.currency, config.locale)\n\n useEffect(() => {\n // Os dois desfechos esvaziam o carrinho de propósito — o passo 4 e o pedido\n // sem cobrança — e sem esta guarda o comprador era mandado ao catálogo no\n // instante em que a compra deu certo, em vez da tela do pedido dele.\n // `resume` segura a guarda: o carrinho pode ter sido esvaziado nesta aba\n // enquanto a pessoa pagava na outra, e mandar para o catálogo alguém que\n // está voltando de um pagamento é perder a compra na porta.\n if (cart.lines.length === 0 && !paidOrderId && !leaving.current && !resume) navigateTo(config.catalogPath)\n }, [cart.lines.length, config.catalogPath, paidOrderId, resume])\n\n\n /**\n * Editar qualquer campo apaga o erro na hora.\n *\n * Sem isto a mensagem sobrevivia ao conserto: o CEP preenchia a UF sozinho e\n * \"Informe a UF com duas letras\" continuava em vermelho embaixo de um campo\n * escrito SP, até a pessoa clicar em continuar de novo para descobrir que já\n * estava certo.\n */\n const set = (key: keyof CheckoutForm) => (value: string) => {\n setError(null)\n setForm((current) => ({ ...current, [key]: value }))\n }\n\n /**\n * Editing the CEP re-fetches the address and refills what the postal service\n * knows, leaving number and complement alone — those are the buyer's and must\n * survive a correction to the postcode.\n *\n * Only what the lookup can supply is overwritten. Silently keeping a stale\n * street from a previous CEP is worse than an empty one: the parcel goes to\n * the wrong place and everything on screen looks filled in.\n */\n async function setZip(value: string) {\n const masked = formatPostalCode(value, country)\n setError(null)\n setForm((current) => ({ ...current, zip: masked }))\n if (!countrySchema.postal.pattern.test(normalizePostalCode(masked, country))) {\n setZipLookup('idle')\n return\n }\n setZipLookup('loading')\n // Pergunta à loja se ela entrega aí, e não só ao serviço postal.\n //\n // O checkout apenas LIA a resposta que o simulador da vitrine tinha deixado\n // no caminho — quem digitava o CEP direto aqui passava batido pelo aviso e\n // só descobria a recusa no fim, quando o servidor negava o pedido. É a\n // mesma pergunta que a loja já faz na página do produto, feita no momento\n // em que a pessoa escreve o endereço.\n void delivery.resolve(masked, subtotal, country)\n try {\n const found = await lookupPostalCode(masked, country)\n if (!found) {\n setZipLookup('not-found')\n return\n }\n setZipLookup('found')\n setForm((current) => ({\n ...current,\n street: found.street || current.street,\n district: found.district || current.district,\n city: found.city || current.city,\n state: found.state,\n }))\n } catch {\n // Offline or the provider is down — the buyer can still type it out.\n setZipLookup('idle')\n }\n }\n\n async function applyDiscountCode() {\n setApplyingDiscount(true)\n setDiscountError(null)\n setDiscountSuccess(null)\n try {\n const appliedCode = discountCode.trim().toUpperCase()\n const result = await validateDiscount(discountCode)\n if (result.valid) {\n cart.applyDiscount(appliedCode, result.percent, { freeShipping: result.freeShipping })\n setDiscountCode(appliedCode)\n // What the coupon actually does. A free_shipping code discounts 0% of\n // the subtotal, so announcing a percentage would read as a bug.\n const effect = result.freeShipping ? t('discount.freeShipping') : t('discount.percentOff', { percent: result.percent })\n setDiscountSuccess(t('discount.applied', { code: appliedCode, effect }))\n toast.success(t('discount.appliedToast'), `${appliedCode} • ${effect}`)\n } else {\n setDiscountError(result.message ?? t('discount.invalid'))\n toast.error(t('discount.invalidToast'), result.message ?? t('discount.checkCode'))\n }\n } finally {\n setApplyingDiscount(false)\n }\n }\n\n function clearDiscountCode() {\n cart.clearDiscount()\n setDiscountCode('')\n setDiscountSuccess(null)\n setDiscountError(null)\n }\n\n // The signed-in shopper's real address book. RLS scopes it to them, so a\n // guest (or a customer whose account was never linked to an auth identity)\n // simply gets nothing back and types their address.\n useEffect(() => {\n const customerId = session.customerId\n if (!customerId) {\n setSavedAddresses([])\n setAddressMode('new')\n setAddressesLoading(false)\n return\n }\n let cancelled = false\n const provider = getShopProvider()\n // Checked before showing the skeleton: `?.` short-circuits the whole chain,\n // so a provider without an address book would never reach `.finally`.\n const listAddresses = provider.listCustomerAddresses?.bind(provider)\n if (!listAddresses) {\n setAddressesLoading(false)\n return\n }\n setAddressesLoading(true)\n void listAddresses(customerId)\n .then((addresses) => {\n if (cancelled || addresses.length === 0) return\n setSavedAddresses(addresses)\n const here = addresses.find((address) => (address.country ?? 'BR') === country)\n if (here) applySavedAddress(here)\n })\n .catch(() => {})\n .finally(() => {\n if (!cancelled) setAddressesLoading(false)\n })\n return () => {\n cancelled = true\n }\n }, [session.customerId])\n\n // Telefone e CPF de quem entrou.\n //\n // A sessão guarda `customerId`, `email` e `name` e nada mais, então entrar\n // preenchia duas caixas e deixava as outras duas em branco — todas as vezes,\n // para a mesma pessoa, que já as tinha digitado no pedido anterior. Não é um\n // campo esquecido num `setForm`: o contrato de `onSignedIn` tem só dois\n // campos, e por isso o buraco volta sempre que alguém adiciona um terceiro.\n //\n // Buscado pelo id em vez de guardado na sessão de propósito: a sessão é\n // persistida em localStorage (`fayz.storefront.session.v1`), e CPF é\n // exatamente o tipo de dado que não deve ficar lá para qualquer script da\n // página ler. O banco já tem, e a RLS já responde só sobre o próprio cliente.\n //\n // Só preenche o que está VAZIO: quem está digitando quando a resposta chega\n // não pode ver o que escreveu ser substituído.\n useEffect(() => {\n const customerId = session.customerId\n setContactKnown(false)\n if (!customerId) return\n const provider = getShopProvider()\n const getCustomer = provider.getCustomer?.bind(provider)\n // The profile (shop 0133) answers for the signed-in buyer even where the\n // customer table is not readable to them, and it already folds in the\n // phone and CPF of the last order. The customer read stays as the fallback.\n const getMyProfile = provider.getMyProfile?.bind(provider)\n let cancelled = false\n const fill = (c: { firstName?: string | null; lastName?: string | null; email?: string | null; phone?: string | null; document?: string | null } | null) => {\n if (cancelled || !c) return\n setForm((current) => ({\n ...current,\n phone: current.phone || c.phone || '',\n document: current.document || (c.document ? formatDocument(c.document) : ''),\n email: current.email || c.email || '',\n name:\n current.name ||\n [c.firstName, c.lastName].filter(Boolean).join(' ').trim(),\n }))\n }\n void (async () => {\n const profile = getMyProfile ? await getMyProfile().catch(() => null) : null\n fill(profile)\n if (getCustomer && (!profile || !profile.phone || !profile.document)) {\n fill(await getCustomer(customerId).catch(() => null))\n }\n if (!cancelled) setContactKnown(true)\n })()\n return () => {\n cancelled = true\n }\n }, [session.customerId])\n\n // A Spanish address is not a Brazilian one with a different label: switching\n // country empties the address and lets the new country's form start clean.\n // Declared BEFORE the prefill below on purpose: effects run in order, so a\n // switch clears first and the prefill then refills with this country's code.\n const shownCountry = React.useRef(country)\n useEffect(() => {\n if (shownCountry.current === country) return\n shownCountry.current = country\n setZipLookup('idle')\n addNewAddress()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [country])\n const addressesHere = savedAddresses.filter((address) => (address.country ?? 'BR') === country)\n\n /**\n * The CEP given back on the product page lands here.\n *\n * This is the payoff of the whole delivery flow: street, district, city and\n * UF arrive filled and the buyer types a house number. It only fires when no\n * saved address was selected — a signed-in shopper's own address book still\n * wins over a postcode lookup, because it also knows their number and\n * complement, which no postal service can supply.\n */\n useEffect(() => {\n if (addressMode !== 'new') return\n // O endereço que a pessoa SALVOU no cardápio vem primeiro: ele traz número\n // e complemento, que consulta de CEP nenhuma devolve — e são justamente os\n // dois campos que sobravam para digitar. Sem isto, salvar endereço no\n // cardápio economizava a rua e cobrava o resto de novo no checkout.\n const keptAny = delivery.savedAddresses.find((a) => a.id === delivery.selectedAddressId)\n const kept = keptAny && (keptAny.country ?? 'BR') === country ? keptAny : undefined\n const looked = delivery.address && (delivery.address.country || 'BR') === country ? delivery.address : null\n if (!kept && !looked) return\n setForm((current) => {\n if (current.zip.trim() || current.street.trim()) return current\n if (kept) {\n return {\n ...current,\n zip: formatPostalCode(kept.postalCode, country),\n street: kept.street,\n number: kept.number,\n complement: kept.complement ?? '',\n district: kept.district,\n city: kept.city,\n state: kept.state,\n }\n }\n return {\n ...current,\n zip: formatPostalCode(looked!.postalCode, country),\n street: looked!.street,\n district: looked!.district,\n city: looked!.city,\n state: looked!.state,\n }\n })\n }, [delivery.address, delivery.savedAddresses, delivery.selectedAddressId, addressMode, country])\n\n function applySavedAddress(address: CustomerAddress) {\n setAddressMode('saved')\n setSelectedAddressId(address.id)\n setForm((current) => ({\n ...current,\n street: address.street,\n city: address.city,\n zip: address.postalCode,\n number: address.number ?? '',\n complement: address.complement ?? '',\n district: address.district ?? '',\n state: address.state,\n // Kept from the book when it has one, and NOT cleared when it does not:\n // a shopper who just typed their phone should not lose it by picking a\n // saved address that predates the field.\n phone: address.phone ?? current.phone,\n }))\n }\n\n function selectAddress(addressId: string) {\n const address = savedAddresses.find((item) => item.id === addressId)\n if (address) applySavedAddress(address)\n }\n\n function addNewAddress() {\n setAddressMode('new')\n setSelectedAddressId('new')\n setForm((current) => ({ ...current, street: '', city: '', zip: '', number: '', complement: '', district: '', state: '' }))\n }\n\n /**\n * Diz o que está errado E leva o comprador até lá.\n *\n * A mensagem sozinha não bastava: num formulário desta altura o campo com\n * problema fica fora da tela (medido: o e-mail em y=-139 com o erro visível\n * embaixo), e o foco ficava no `body`. A pessoa lia \"informe um e-mail\n * válido\" e tinha que caçar qual campo. É a regra de focus-management do\n * WCAG, e aqui ela é a diferença entre corrigir e desistir.\n */\n function fail(message: string, testId?: string): false {\n setError(message)\n trackStorefront('checkout_error', { step, field: testId ?? null, reason: message })\n if (testId) {\n const field = document.querySelector<HTMLElement>(`[data-testid=\"${testId}\"]`)\n field?.scrollIntoView({ block: 'center', behavior: prefersReducedMotion() ? 'auto' : 'smooth' })\n field?.focus({ preventScroll: true })\n }\n return false\n }\n\n /**\n * O passo 1 valida só o que o passo 1 pede.\n *\n * Antes tudo era validado no último clique, então quem errava o e-mail\n * descobria depois de preencher o endereço inteiro. Cada passo agora responde\n * pelo que ele mesmo coletou — e `validate()` continua rodando inteiro antes\n * de cobrar, porque o servidor não confia na navegação.\n */\n function validateContact(): boolean {\n setError(null)\n if (requiresAccount && !session.customerId) {\n setShowSignin(true)\n return fail(t('error.requiresAccount'))\n }\n if (!form.email.trim() || !/.+@.+\\..+/.test(form.email)) {\n return fail(t('error.email'), TID.checkoutEmail)\n }\n if (!form.name.trim()) return fail(t('error.name'), TID.checkoutName)\n if (requires('phone') && !form.phone.trim()) {\n return fail(t('error.phone'), 'checkout-phone')\n }\n return validateDocument()\n }\n\n /** Step 1 already holds everything it asks for — the same rules as\n * validateContact, without raising an error. */\n function contactComplete(): boolean {\n if (!session.customerId) return false\n if (!form.email.trim() || !/.+@.+\\..+/.test(form.email)) return false\n if (!form.name.trim()) return false\n const phone = form.phone.replace(/\\D/g, '')\n if (requires('phone') && phone.length < 10) return false\n if (shows('phone') && !phone) return false\n if (isBrazil) {\n if (requires('document') && !isValidDocument(form.document)) return false\n if (shows('document') && !isValidDocument(form.document)) return false\n }\n return true\n }\n const contactAsCard = !editingContact && contactKnown && contactComplete()\n // Nothing to type in «Dados»: open on «Entrega» (or «Pagamento» for a\n // pickup), once. «Dados» stays a completed step the buyer can reopen.\n useEffect(() => {\n if (skippedContact.current || step !== 1 || !contactAsCard) return\n skippedContact.current = true\n setStep(isPickup ? 3 : 2)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [contactAsCard, step])\n\n /** The buyer's tax id, by the country's rule: a CPF/CNPJ in Brazil when the\n * store needs one; elsewhere checked only if the buyer gave it. */\n function validateDocument(): boolean {\n if (isBrazil) {\n if (requires('document') && !isValidDocument(form.document)) {\n return fail(\n form.document.trim() ? t('error.documentInvalid') : t('error.documentMissing'),\n TID.checkoutDocument,\n )\n }\n return true\n }\n const taxId = countrySchema.taxId\n if (!form.document.trim()) {\n return requires('document') ? fail(t('error.documentMissing'), TID.checkoutDocument) : true\n }\n if (taxId && !taxId.validate(form.document)) return fail(t('error.taxIdInvalid'), TID.checkoutDocument)\n return true\n }\n\n /**\n * The address, by the country's form. Brazil keeps its own checks and\n * messages, in their order; other countries read their schema.\n */\n function validateAddressFields(): boolean {\n if (isBrazil) {\n if (!form.street.trim() || !form.city.trim() || !form.zip.trim() || !form.district.trim()) {\n return fail(t('error.address'), TID.checkoutStreet)\n }\n if (!form.number.trim()) return fail(t('error.number'), 'checkout-number')\n if (requires('complement') && !form.complement.trim()) {\n return fail(t('error.complement'), 'checkout-complement')\n }\n if (!/^[A-Za-z]{2}$/.test(form.state.trim())) {\n return fail(t('error.state'), 'checkout-state')\n }\n return true\n }\n const errors = validateAddress(\n { postalCode: form.zip, street: form.street, complement: form.complement, city: form.city, state: form.state },\n country,\n { complement: requires('complement') },\n )\n if (errors.postalCode === 'invalid') {\n return fail(t('error.postalInvalid', { example: countrySchema.postal.example }), TID.checkoutZip)\n }\n if (errors.postalCode || errors.street || errors.city) return fail(t('error.address'), errors.postalCode ? TID.checkoutZip : TID.checkoutStreet)\n if (errors.complement) return fail(t('error.complement'), 'checkout-complement')\n if (errors.region) {\n const label = countrySchema.fields.find((f) => f.key === 'region')?.label[config.language] ?? ''\n return fail(t('error.region', { label: label.toLowerCase() }), 'checkout-state')\n }\n return true\n }\n\n /** O passo 2: para onde vai, e se a loja entrega lá. */\n function validateDelivery(): boolean {\n setError(null)\n if (isPickup) return true\n if (!selectRequiresShipping(cart)) return true\n if (!validateAddressFields()) return false\n if (\n delivery.status === 'unserved'\n && delivery.postalCode === normalizePostalCode(form.zip, country)\n ) {\n return fail(delivery.refusedZone ? t('error.refusedZone') : t('error.unserved'), TID.checkoutZip)\n }\n return true\n }\n\n function goToStep(next: CheckoutStep) {\n setError(null)\n setStep(next)\n // O topo, sempre: o passo seguinte começa onde os olhos já estão.\n if (typeof window !== 'undefined') window.scrollTo({ top: 0, behavior: 'smooth' })\n }\n\n\n /**\n * O endereço que vai no pedido.\n *\n * Na RETIRADA é o balcão da loja, e isso não é um contorno: `shop_place_order`\n * exige CEP quando a loja tem zonas (0021) e essa checagem roda ANTES de\n * qualquer trigger de linha, então o pedido precisa de um endereço válido —\n * e o endereço válido de uma retirada é o lugar onde a mercadoria vai ficar\n * esperando. O trigger da 0094 reconhece o modo e zera o frete.\n *\n * Sem balcão declarado a retirada não deveria ter sido oferecida; cai no que\n * o comprador digitou em vez de mandar um endereço vazio.\n */\n function orderAddress(): ShippingAddressInput {\n if (isPickup && pickupAddress) {\n return {\n ...pickupAddress,\n phone: form.phone.trim() || undefined,\n document: documentDigits(form.document) || undefined,\n }\n }\n return deliveryAddress()\n }\n\n function deliveryAddress(): ShippingAddressInput {\n return toShippingAddress(form, country)\n }\n\n function advance() {\n if (step === 1 && validateContact()) {\n // «Alterar» saved: the profile learns it, so the next checkout starts on\n // the card again. Fire-and-forget like the contact memory below.\n if (editingContact && session.customerId) {\n void getShopProvider().saveMyProfile?.({\n name: form.name.trim(),\n phone: form.phone.trim() || null,\n document: documentDigits(form.document) || null,\n }).catch(() => {})\n setEditingContact(false)\n }\n // Remember the contact BEFORE the sale, not after it. The store used to\n // learn a buyer's document only when an order completed and never learned\n // their phone at all, so a signed-in customer retyped both on every visit —\n // and an abandoned checkout taught it nothing. Fire-and-forget: a store\n // that cannot remember must still be able to sell.\n void getShopProvider().saveCustomerContact?.({\n phone: form.phone.trim() || null,\n document: documentDigits(form.document) || null,\n })\n // Na retirada não existe passo de entrega: o endereço é o balcão, e a\n // loja já sabe onde ele fica. Perguntar o CEP de quem vem buscar é pedir\n // um dado que ninguém vai usar.\n goToStep(isPickup ? 3 : 2)\n }\n else if (step === 2 && validateDelivery()) goToStep(3)\n }\n\n /**\n * O pedido sem cobrança online.\n *\n * Não é um caminho de segunda: é o de quase toda a frota — dinheiro na\n * entrega, maquininha do entregador, \"combinar com a loja\". O pedido nasce\n * `pending` e ninguém comemora; quem confirma que o dinheiro entrou é o\n * lojista, na tela dele.\n */\n async function confirmWithoutCharge() {\n if (!validate()) return\n setPlacing(true)\n try {\n const { order, customerId } = await placeStorefrontOrder({\n config,\n cart,\n session,\n customer: { email: form.email, name: form.name },\n // `notes` é o recado do comprador para a loja, e o ponto de referência\n // é exatamente isso: \"portão azul, ao lado da padaria\" não cabe em\n // nenhum campo estruturado do endereço e é o que o entregador lê.\n address: {\n street: form.street,\n city: form.city,\n zip: form.zip,\n notes: deliveryReference || undefined,\n },\n // Viaja com o `document` dentro: a assinatura do shop_place_order não\n // pode ganhar parâmetro sem DROP (0050), e uma trigger o levanta para a\n // coluna. Na retirada este endereço é o balcão — ver orderAddress().\n shippingAddress: orderAddress(),\n // Entrega/retirada e agendamento (0094) vão AQUI porque esta tela chama\n // placeStorefrontOrder direto, sem passar pelo useCheckout — e sem esta\n // linha o pedido nascia sem `fulfillment_type`, com a retirada\n // indistinguível de uma entrega e o frete cobrado assim mesmo. Foi um\n // pedido de teste real (#1379) que mostrou isso.\n fulfillmentType,\n scheduledFor: scheduledFor ?? undefined,\n paymentMethod,\n })\n // placeStorefrontOrder resolve/cria o cliente mas não guarda a sessão —\n // sem isto \"Minhas compras\" logo depois consulta por e-mail, que anon não\n // lê sob RLS, e volta vazio.\n if (customerId) session.setSession({ customerId, email: form.email, name: form.name })\n leaving.current = true\n trackStorefront('checkout_completed', {\n order_id: order.id,\n payment_method: paymentMethod,\n fulfillment: fulfillmentType ?? 'delivery',\n total,\n online_payment: false,\n })\n cart.clear()\n navigateTo(`/order/${order.id}`)\n } catch (err) {\n setError(placeOrderMessage(err, t))\n trackStorefront('checkout_error', { step, field: 'place_order', reason: placeOrderMessage(err, t) })\n setPlacing(false)\n }\n }\n\n function validate(): boolean {\n setError(null)\n // Checked FIRST: it is the only refusal the server will also make, so\n // finding it out here saves the shopper a completed form and a raw SQL error.\n if (requiresAccount && !session.customerId) {\n setShowSignin(true)\n return fail(t('error.requiresAccount'))\n }\n if (!form.email.trim() || !/.+@.+\\..+/.test(form.email)) {\n return fail(t('error.email'), TID.checkoutEmail)\n }\n if (requires('phone') && !form.phone.trim()) {\n return fail(t('error.phone'), 'checkout-phone')\n }\n if (!form.name.trim()) {\n return fail(t('error.name'), TID.checkoutName)\n }\n // Checked here rather than at the gateway: a wrong CPF comes back from the\n // acquirer as a generic decline, and the buyer has no way to know which\n // field to fix.\n if (!validateDocument()) return false\n // Na RETIRADA não há endereço a validar: o pedido vai para o balcão, e o\n // formulário de entrega nunca foi mostrado.\n if (isPickup) return true\n // Number, district and UF are required in Brazil because a courier cannot\n // deliver without them; other countries require what their form has.\n if (!validateAddressFields()) return false\n // Coverage. shop_place_order refuses an unserved postal code anyway (0021),\n // so this only turns a raw SQL error into a sentence the buyer can act on.\n // A cart that ships nothing never quotes, so \"unserved\" here means \"nobody\n // asked\", not \"we don't go there\".\n if (\n selectRequiresShipping(cart) &&\n delivery.status === 'unserved' &&\n delivery.postalCode === normalizePostalCode(form.zip, country)\n ) {\n // An EXCLUDED region reads differently on purpose (0048): \"ainda não\" is a\n // promise about the future, and a store that deliberately refuses a region\n // is not making it.\n return fail(delivery.refusedZone ? t('error.refusedZone') : t('error.unserved'), TID.checkoutZip)\n }\n return true\n }\n\n\n return (\n <main className=\"min-h-screen bg-background\">\n <Slot area=\"checkout\" name=\"beforeForm\" context={checkoutSlotContext} />\n {showSignin && !session.email && (\n <SignInModal\n defaultEmail={form.email}\n onClose={() => setShowSignin(false)}\n onSignedIn={(signed) =>\n setForm((current) => ({ ...current, email: signed.email ?? current.email, name: signed.name || current.name }))\n }\n />\n )}\n <header className=\"border-b bg-background\">\n <div className=\"mx-auto flex max-w-6xl items-center justify-between gap-4 px-4 py-6 sm:px-6\">\n <Link to={returnPath(config)} className=\"text-sm text-muted-foreground hover:text-foreground\">\n {t('checkout.backToStore')}\n </Link>\n <div className=\"text-center\">\n <div className=\"sf-heading text-2xl font-bold tracking-tight\">{config.logo ?? config.name}</div>\n <div className=\"mt-2 flex items-center justify-center gap-2 text-xs text-muted-foreground\">\n <Lock className=\"h-3.5 w-3.5\" />\n {t('checkout.secure')}\n </div>\n </div>\n <a href=\"mailto:suporte@example.com\" className=\"text-sm text-muted-foreground hover:text-foreground\">\n {t('checkout.help')}\n </a>\n </div>\n </header>\n\n <div className=\"mx-auto grid max-w-6xl grid-cols-1 gap-8 px-4 py-8 sm:px-6 lg:grid-cols-5 lg:px-6\">\n <section className=\"lg:col-span-3 lg:pr-10\">\n <CheckoutSteps\n current={step}\n omit={isPickup ? [2] : undefined}\n // Na retirada o passo 2 não existe: voltar para ele cairia num\n // formulário de endereço que a própria tela acabou de dizer que não\n // era necessário. Volta para os dados.\n onGoBackTo={\n step === 4\n ? undefined\n : (target) => goToStep(isPickup && target === 2 ? 1 : target)\n }\n />\n\n {/* Um <form> de verdade: é ele que faz o Enter num campo avançar o\n passo, em vez de não fazer nada. O passo 3 não submete — quem manda\n ali é a cobrança. */}\n <form\n className=\"space-y-8\"\n onSubmit={(event) => {\n event.preventDefault()\n advance()\n }}\n >\n {step === 1 && (\n <section>\n <div className=\"mb-3 flex items-center justify-between gap-4\">\n <h1 className=\"text-xl font-semibold tracking-tight\">{t('checkout.contact.title')}</h1>\n {session.email ? (\n <span className=\"text-sm text-muted-foreground\">{t('checkout.contact.signedInAs', { email: session.email })}</span>\n ) : (\n <button\n type=\"button\"\n onClick={() => setShowSignin((value) => !value)}\n className=\"text-sm font-medium text-primary hover:underline\"\n >\n {t('checkout.contact.haveAccount')}\n </button>\n )}\n </div>\n {contactAsCard ? (\n <ContactSummary\n name={form.name}\n email={form.email}\n phone={shows('phone') ? form.phone : undefined}\n document={shows('document') ? form.document : undefined}\n onEdit={() => setEditingContact(true)}\n onSignOut={() => {\n void signOutCustomer().finally(() => {\n setForm((current) => ({ ...current, email: '', name: '', phone: '', document: '' }))\n setEditingContact(false)\n })\n }}\n labels={{ edit: t('checkout.contact.edit'), notYou: t('checkout.contact.notYou'), signOut: t('checkout.contact.signOut') }}\n />\n ) : (\n <div className=\"grid gap-3 sm:grid-cols-2\">\n {field(t('checkout.contact.email'), TID.checkoutEmail, form.email, set('email'), {\n type: 'email',\n placeholder: t('checkout.contact.email'),\n // The account's address: an order under another e-mail would\n // not show up in this buyer's «Meus pedidos».\n ...(session.customerId && session.email ? { readOnly: true, title: t('checkout.contact.emailLocked'), className: 'w-full rounded-lg border bg-muted/40 px-3.5 py-3 text-sm text-muted-foreground outline-none' } : {}),\n })}\n {field(t('checkout.contact.name'), TID.checkoutName, form.name, set('name'), {\n placeholder: t('checkout.contact.name'),\n })}\n {shows('phone') && field(t('checkout.contact.phone'), 'checkout-phone', form.phone, set('phone'), {\n type: 'tel',\n autoComplete: 'tel',\n placeholder: requires('phone') ? t('checkout.contact.phone') : t('checkout.contact.phoneOptional'),\n })}\n {shows('document') && (isBrazil ? field(\n t('checkout.contact.document'),\n TID.checkoutDocument,\n form.document,\n (value) => {\n setError(null)\n setForm((current) => ({ ...current, document: formatDocument(value) }))\n },\n {\n // `inputMode` and not `type=\"number\"`: the mask writes dots\n // and a dash, which a number input silently refuses to hold.\n inputMode: 'numeric',\n autoComplete: 'off',\n placeholder: requires('document') ? t('checkout.contact.document') : t('checkout.contact.documentOptional'),\n },\n ) : field(\n // The country's own tax id (Spain: NIF/NIE), unmasked: it has letters.\n countrySchema.taxId?.label[config.language] ?? t('checkout.contact.documentOptional'),\n TID.checkoutDocument,\n form.document,\n set('document'),\n { autoComplete: 'off', placeholder: countrySchema.taxId?.label[config.language] ?? '' },\n ))}\n </div>\n )}\n {requiresAccount && !session.customerId && (\n <p className=\"mt-3 rounded-lg border border-primary/30 bg-primary/5 px-3 py-2 text-sm\">\n {t('checkout.contact.requiresAccount')}{' '}\n <button\n type=\"button\"\n onClick={() => setShowSignin(true)}\n className=\"font-semibold text-primary hover:underline\"\n >\n {t('checkout.contact.signInOrCreate')}\n </button>\n </p>\n )}\n </section>\n )}\n\n {step === 2 && (\n <section>\n <h2 className=\"mb-3 text-xl font-semibold tracking-tight\">{t('checkout.address.title')}</h2>\n {buyer.allowed.length > 1 && (\n <CountrySelect className=\"mb-3\" country={country} allowed={buyer.allowed} onChange={buyer.setCountry} />\n )}\n <div className=\"mb-3 grid gap-3\">\n {addressesLoading && savedAddresses.length === 0 && (\n <SkeletonGroup label={t('checkout.address.loadingSaved')} className=\"grid gap-3\">\n {[0, 1].map((row) => (\n <div key={row} className=\"rounded-lg border p-3\">\n <Skeleton className=\"h-4 w-28\" />\n <Skeleton className=\"mt-2 h-3 w-3/4\" />\n <Skeleton className=\"mt-1.5 h-3 w-1/2\" />\n </div>\n ))}\n </SkeletonGroup>\n )}\n {addressesHere.map((address) => (\n <div\n key={address.id}\n className={`group relative rounded-lg border p-3 pr-11 text-left text-sm transition hover:bg-muted/40 ${\n selectedAddressId === address.id ? 'border-primary bg-primary/5' : 'border-border bg-background'\n }`}\n >\n <button type=\"button\" onClick={() => selectAddress(address.id)} className=\"block w-full text-left\">\n <span className=\"flex items-center justify-between gap-3 font-semibold\">\n {address.label}\n {addressMode === 'saved' && selectedAddressId === address.id && (\n <span className=\"rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-bold text-primary\">{t('checkout.address.selected')}</span>\n )}\n </span>\n <span className=\"mt-1 block text-muted-foreground\">\n {[address.street, address.number].filter(Boolean).join(', ')}\n {address.complement ? ` — ${address.complement}` : ''}\n </span>\n <span className=\"block text-muted-foreground\">\n {[address.district, address.city, address.state].filter(Boolean).join(' · ')} — {address.postalCode}\n </span>\n </button>\n </div>\n ))}\n <button\n type=\"button\"\n onClick={addNewAddress}\n className={`rounded-lg border border-dashed p-3 text-left text-sm transition hover:bg-muted/40 ${\n addressMode === 'new' ? 'border-primary bg-primary/5' : 'border-border bg-muted/20'\n }`}\n >\n <span className=\"block font-semibold text-primary\">\n {addressesHere.length > 0 ? t('checkout.address.addNew') : t('checkout.address.enter')}\n </span>\n <span className=\"mt-1 block text-muted-foreground\">{t('checkout.address.enterHint')}</span>\n </button>\n </div>\n {addressMode === 'new' && (\n <AddressForm\n country={country}\n language={config.language}\n value={form}\n onChange={(key, value) => set(key)(value)}\n onPostalCode={setZip}\n lookup={zipLookup}\n complement={{ visible: shows('complement'), required: requires('complement') }}\n />\n )}\n </section>\n )}\n\n {/* While the server creates the order, the screen is the shape of the\n order page it is about to land on. */}\n {step === 3 && placing && (\n <section>\n <h2 className=\"mb-3 text-xl font-semibold tracking-tight\">{t('checkout.confirming.title')}</h2>\n <SkeletonGroup label={t('checkout.confirming.label')} className=\"rounded-xl border bg-card p-6 sm:p-8\">\n <div className=\"grid gap-6 border-b pb-6 sm:grid-cols-[120px_minmax(0,1fr)]\">\n <Skeleton className=\"mx-auto h-24 w-24 rounded-full\" />\n <div>\n <Skeleton className=\"h-7 w-56 max-w-full\" />\n <Skeleton className=\"mt-2 h-3.5 w-full max-w-sm\" />\n <Skeleton className=\"mt-4 h-5 w-40\" />\n </div>\n </div>\n <div className=\"mt-6 grid gap-4 rounded-xl border bg-muted/20 p-4 sm:grid-cols-3\">\n {[0, 1, 2].map((column) => (\n <div key={column}>\n <Skeleton className=\"h-3 w-16\" />\n <Skeleton className=\"mt-2 h-4 w-24\" />\n </div>\n ))}\n </div>\n <div className=\"mt-8 space-y-3\">\n {cart.lines.slice(0, 3).map((line) => (\n <div key={line.lineId ?? line.productId} className=\"flex items-center gap-3\">\n <Skeleton className=\"h-12 w-12 rounded-lg\" />\n <Skeleton className=\"h-3.5 flex-1\" />\n <Skeleton className=\"h-3.5 w-16\" />\n </div>\n ))}\n </div>\n </SkeletonGroup>\n <p className=\"mt-3 text-center text-sm text-muted-foreground\">\n {t('checkout.confirming.keepOpen')}\n </p>\n </section>\n )}\n\n {step === 3 && !placing && (\n <section>\n <h2 className=\"mb-3 text-xl font-semibold tracking-tight\">{t('checkout.payment.title')}</h2>\n <div className=\"mb-3 grid gap-3\" role=\"radiogroup\" aria-label={t('checkout.payment.label')}>\n {paymentMethods.map((method) => {\n const base = { label: t(PAYMENT_LABELS[method].label), hint: t(PAYMENT_LABELS[method].hint) }\n // A loja que tem adquirente cobra o cartão na página segura\n // dele; a que não tem, cobra na entrega. É a mesma opção com\n // dois desfechos, e o comprador tem que ler o certo antes de\n // escolher — não depois, quando a tela redirecionar.\n const copy = method === 'credit_card' && cardIsCharged\n ? { ...base, hint: t('checkout.payment.cardOnline') }\n : base\n const selected = paymentMethod === method\n return (\n // Cada forma de pagamento abre o que ELA pede, embaixo dela\n // mesma. Antes o painel do Pix ficava no fim da lista, longe\n // do cartão escolhido, e escolher parecia não fazer nada.\n <div key={method}>\n <button\n type=\"button\"\n role=\"radio\"\n aria-checked={selected}\n data-testid={`checkout-payment-${method}`}\n onClick={() => {\n setPaymentMethod(method)\n if (method !== paymentMethod) trackStorefront('checkout_payment_selected', { payment_method: method })\n }}\n className={`w-full rounded-lg border p-3 text-left text-sm transition hover:bg-muted/40 ${\n selected ? 'border-primary bg-primary/5' : 'border-border bg-background'\n }`}\n >\n <span className=\"flex items-center justify-between gap-3 font-semibold\">\n <span className=\"flex items-center gap-2\"><CreditCard className=\"h-4 w-4\" />{copy.label}</span>\n {selected && (\n <span className=\"rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-bold text-primary\">{t('checkout.address.selected')}</span>\n )}\n </span>\n <span className=\"mt-1 block text-muted-foreground\">{copy.hint}</span>\n </button>\n {selected && chargesOnline && (\n <div className=\"mt-3\">\n <CheckoutPayment\n input={checkoutSessionInput}\n money={money}\n // The cart's own total, needed BEFORE a charge exists:\n // an in-store card form prices its installment options\n // from it, and the server recomputes the real figure\n // when the token is spent.\n amount={total}\n onBack={() => goToStep(2)}\n resume={resume}\n onUnavailable={() => setUnavailable((list) =>\n list.includes(method) ? list : [...list, method])}\n onPaid={(orderId) => {\n // O ref ANTES do clear: `paidOrderId` é estado do\n // React e o carrinho re-renderiza fora do lote,\n // então a guarda podia mandar para o catálogo\n // alguém que acabou de pagar.\n leaving.current = true\n setPaidOrderId(orderId)\n trackStorefront('checkout_completed', {\n order_id: orderId,\n payment_method: method,\n fulfillment: fulfillmentType ?? 'delivery',\n total,\n online_payment: true,\n })\n goToStep(4)\n cart.clear()\n }}\n />\n </div>\n )}\n </div>\n )\n })}\n </div>\n <Slot area=\"checkout\" name=\"afterPaymentMethods\" context={checkoutSlotContext} />\n\n {/* Loja que NÃO cobra online — dinheiro na entrega, maquininha,\n combinar com a loja. Ela é a maioria da frota, e abrir uma\n cobrança aqui só produziria \"esta loja não recebe pagamento\n online\" no lugar do botão de comprar. O pedido nasce pendente,\n como sempre nasceu, e a tela do pedido diz isso com todas as\n letras em vez de comemorar. */}\n {!chargesOnline && (\n <div className=\"mt-5\">\n <button\n type=\"button\"\n data-testid={TID.placeOrder}\n disabled={placing}\n onClick={() => { void confirmWithoutCharge() }}\n className=\"min-h-12 w-full rounded-xl bg-primary px-6 py-3 font-semibold text-primary-foreground transition hover:opacity-90 disabled:opacity-60\"\n >\n {t('checkout.payment.placeOrder', { total: money(total) })}\n </button>\n <p className=\"mt-2 text-center text-xs text-muted-foreground\">\n {t('checkout.payment.pendingNote')}\n </p>\n </div>\n )}\n\n {/*\n * Atalho de DESENVOLVIMENTO: cria o pedido sem passar pelo\n * adquirente.\n *\n * Testar o fluxo inteiro numa loja com gateway ligado exigia ou\n * credenciais válidas ou mexer nos ajustes da loja no banco — as\n * duas coisas caras para conferir uma tela. Este botão chama o\n * MESMO `confirmWithoutCharge()` que uma loja sem gateway usa\n * todo dia, então ele não inventa um caminho: usa o que já\n * existe, pulando só a cobrança.\n *\n * A guarda é `import.meta.env.DEV`, lida com o mesmo cast\n * defensivo do isDevBuild() do core (o SDK compila para consumo\n * em Node também, onde `import.meta.env` não existe).\n *\n * O que isso garante: num build de produção o valor é `false` e o\n * bloco NUNCA renderiza. O que NÃO vou afirmar: que o bundler o\n * remove — com o cast a expressão deixa de ser o literal que o\n * Vite substitui estaticamente, então a eliminação de código\n * morto não está garantida. O botão não aparece; o código pode\n * viajar junto.\n */}\n {DEV_BUILD && chargesOnline && (\n <div className=\"mt-6 rounded-xl border border-dashed border-amber-500/60 bg-amber-500/5 p-4\">\n <p className=\"text-xs font-semibold uppercase tracking-wide text-amber-600\">\n Somente em desenvolvimento\n </p>\n <button\n type=\"button\"\n data-testid={TID.devPlaceOrderWithoutCharge}\n disabled={placing}\n onClick={() => { void confirmWithoutCharge() }}\n className=\"mt-2 min-h-11 w-full rounded-lg border border-amber-500/60 px-4 py-2.5 text-sm font-medium text-amber-700 transition hover:bg-amber-500/10 disabled:opacity-60\"\n >\n {`Criar pedido sem cobrar — ${money(total)}`}\n </button>\n <p className=\"mt-2 text-xs text-muted-foreground\">\n Pula o adquirente e grava o pedido como <code>pending</code>, igual a uma\n loja que confirma o pagamento à mão. Este bloco não vai para produção.\n </p>\n </div>\n )}\n\n </section>\n )}\n\n {step === 4 && paidOrderId && (\n <section data-testid={TID.checkoutDone} className=\"rounded-xl border bg-card p-8 text-center\">\n <SuccessMark />\n <h2 className=\"mt-4 text-2xl font-bold tracking-tight\">{t('checkout.done.title')}</h2>\n <p className=\"mt-2 text-muted-foreground\">\n {t('checkout.done.text')}\n </p>\n <button\n type=\"button\"\n onClick={() => navigateTo(`/order/${paidOrderId}`)}\n className=\"mt-6 inline-flex min-h-11 items-center rounded-lg bg-primary px-6 py-3 text-sm font-semibold text-primary-foreground transition hover:opacity-90\"\n >\n {t('checkout.done.viewOrder')}\n </button>\n </section>\n )}\n\n {error && (\n <p data-testid={TID.checkoutError} className=\"rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive\">\n {error}\n </p>\n )}\n\n {/* Embaixo do formulário, onde a mão já está — e dentro do <form>,\n para que Enter em qualquer campo avance o passo. Digitar o CEP e\n apertar Enter é o gesto natural; antes ele não fazia nada e o\n botão estava do outro lado da tela. */}\n {(step === 1 || step === 2) && (\n <div className=\"grid gap-3 border-t pt-5\">\n <button\n type=\"submit\"\n data-testid={TID.checkoutContinue}\n className=\"min-h-12 rounded-lg bg-primary px-6 py-4 text-sm font-bold text-primary-foreground transition hover:opacity-90\"\n >\n {step === 1\n // Na retirada o passo seguinte É o pagamento — prometer\n // \"a entrega\" mandaria a pessoa para uma etapa que o\n // pedido dela não tem.\n ? (isPickup ? t('checkout.goToPayment', { total: money(total) }) : t('checkout.continueToDelivery'))\n : t('checkout.goToPayment', { total: money(total) })}\n </button>\n {step === 2 && (\n <button\n type=\"button\"\n data-testid={TID.checkoutBack}\n onClick={() => goToStep(1)}\n className=\"min-h-11 rounded-lg border px-6 py-3 text-sm font-medium transition hover:bg-muted\"\n >\n {t('checkout.backToContact')}\n </button>\n )}\n <Link to={returnPath(config)} className=\"text-center text-sm text-muted-foreground hover:text-foreground\">\n {t('checkout.backToCart')}\n </Link>\n </div>\n )}\n\n </form>\n\n </section>\n\n <aside className=\"rounded-xl border bg-muted/20 p-5 lg:sticky lg:top-6 lg:col-span-2 lg:self-start\">\n <h2 className=\"sr-only\">{t('summary.title')}</h2>\n <ul className=\"space-y-4\">\n {cart.lines.map((line) => (\n <li key={line.lineId ?? line.productId} className=\"flex gap-3 text-sm\">\n <div className=\"relative h-16 w-16 flex-none overflow-hidden rounded-lg border bg-background\">\n {line.imageUrl && <SmoothImage src={line.imageUrl} alt={line.name} className=\"h-full w-full object-cover\" variant={{ width: 96 }} />}\n <span className=\"absolute -right-1 -top-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-muted-foreground px-1.5 text-[10px] font-bold text-background\">\n {line.quantity}\n </span>\n </div>\n <div className=\"min-w-0 flex-1\">\n <p className=\"truncate font-medium\">{line.name}</p>\n {line.sku && <p className=\"text-xs text-muted-foreground\">{line.sku}</p>}\n {line.optionsLabel && <p className=\"text-xs text-muted-foreground\">{line.optionsLabel}</p>}\n {/* O recado do item aparece também aqui: é a última tela antes\n de pagar, e é onde alguém confere o que pediu. */}\n {line.notes && <p className=\"text-xs italic text-muted-foreground\">“{line.notes}”</p>}\n </div>\n <span data-price={(line.unitPrice * line.quantity).toFixed(2)}>\n {money(line.unitPrice * line.quantity)}\n </span>\n </li>\n ))}\n </ul>\n {config.features.discounts && (\n <div className=\"mt-5 space-y-2 border-t pt-5\">\n <div className=\"flex gap-2\">\n <input\n data-testid={TID.discountInput}\n type=\"text\"\n placeholder={t('discount.placeholder')}\n value={discountCode}\n onChange={(event) => {\n setDiscountCode(event.target.value)\n setDiscountSuccess(null)\n setDiscountError(null)\n }}\n className=\"min-w-0 flex-1 rounded-lg border bg-background px-3 py-2 text-sm uppercase\"\n />\n <button\n type=\"button\"\n data-testid={TID.discountApply}\n onClick={applyDiscountCode}\n disabled={applyingDiscount || !discountCode.trim()}\n className=\"rounded-lg border px-3 py-2 text-sm font-semibold hover:bg-muted disabled:opacity-50\"\n >\n {t('discount.apply')}\n </button>\n </div>\n {discountError && (\n <p data-testid={TID.discountError} className=\"text-xs text-destructive\">\n {discountError}\n </p>\n )}\n {discountSuccess && (\n <p className=\"text-xs font-semibold text-emerald-700\">\n {discountSuccess}\n </p>\n )}\n </div>\n )}\n <dl className=\"mt-8 space-y-3 border-t pt-6 text-sm\">\n <div className=\"flex justify-between\">\n <dt className=\"text-muted-foreground\">{t('summary.subtotal')}</dt>\n <dd data-price={subtotal.toFixed(2)}>{money(subtotal)}</dd>\n </div>\n {discountTotal > 0 && (\n <div className=\"flex justify-between text-emerald-700\" data-testid={TID.discountRow}>\n <dt>\n {t('summary.discount')}{' '}\n <button\n type=\"button\"\n onClick={clearDiscountCode}\n className=\"text-xs text-muted-foreground underline\"\n >\n ({cart.discountCode} ×)\n </button>\n </dt>\n <dd data-price={discountTotal.toFixed(2)}>-{money(discountTotal)}</dd>\n </div>\n )}\n <div className=\"flex justify-between\">\n <dt className={cart.discountFreeShipping ? 'text-emerald-700' : 'text-muted-foreground'}>\n {/* Numa retirada não há entrega. \"Entrega — Grátis\" leria como um\n brinde que a loja deu, quando na verdade é a pessoa que vai\n buscar. */}\n {isPickup ? t('summary.pickup') : t('summary.delivery')}\n {cart.discountFreeShipping && (\n <button\n type=\"button\"\n onClick={clearDiscountCode}\n className=\"ml-1 text-xs text-muted-foreground underline\"\n >\n ({cart.discountCode} ×)\n </button>\n )}\n </dt>\n <dd data-price={shipping.toFixed(2)}>\n {isPickup ? t('summary.noFee') : shipping === 0 ? t('summary.free') : money(shipping)}\n </dd>\n </div>\n <div className=\"flex justify-between border-t pt-5 text-lg font-bold\">\n <dt>{t('summary.total')}</dt>\n <dd data-price={total.toFixed(2)}>{money(total)}</dd>\n </div>\n </dl>\n <div className=\"mt-6 flex items-center gap-2 text-xs text-muted-foreground\">\n <ShieldCheck className=\"h-4 w-4 text-primary\" />\n {t('summary.protected')}\n </div>\n {/* O botão de avançar NÃO mora aqui — ele vive embaixo do formulário,\n onde a mão está. O resumo é o que a pessoa confere, não onde ela\n age; a distância entre o último campo e o botão do outro lado da\n tela era uma travessia a cada passo. */}\n <div className=\"mt-6 border-t pt-5\">\n <Slot area=\"checkout\" name=\"afterForm\" context={checkoutSlotContext} />\n </div>\n </aside>\n\n {/* Fora das duas colunas de propósito.\n Dentro da <section> do formulário, no empilhamento do mobile esta\n tira caía ENTRE o botão de continuar e o resumo do pedido — links\n institucionais separando a pessoa dos itens que ela está comprando.\n Aqui ela é o último elemento da página nos dois layouts, que é onde\n um rodapé legal pertence. */}\n <footer className=\"flex flex-wrap gap-4 border-t pt-5 text-xs text-muted-foreground lg:col-span-5\">\n <Link to=\"/privacy\" className=\"hover:text-foreground\">{t('legal.privacy')}</Link>\n <Link to=\"/terms\" className=\"hover:text-foreground\">{t('legal.terms')}</Link>\n <Link to=\"/refunds\" className=\"hover:text-foreground\">{t('legal.refunds')}</Link>\n </footer>\n </div>\n </main>\n )\n}\n"]}
|