@aglyn/plugins-commerce 1.20.3 → 1.22.0
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/package.json +16 -16
- package/src/lib/components/cart-fulfillment.js +19 -8
- package/src/lib/components/cart-fulfillment.js.map +1 -1
- package/src/lib/components/cart.js +106 -9
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/console/catalog-organization-card.component.js +102 -32
- package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
- package/src/lib/components/console/discounts-card.component.js +39 -5
- package/src/lib/components/console/discounts-card.component.js.map +1 -1
- package/src/lib/components/console/local-delivery-settings-card.component.js +34 -9
- package/src/lib/components/console/local-delivery-settings-card.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +72 -46
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/products-hub-card.component.js +43 -6
- package/src/lib/components/console/products-hub-card.component.js.map +1 -1
- package/src/lib/components/console/quote-settings-card.component.js +31 -8
- package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
- package/src/lib/components/console/reservations-card.component.js +39 -4
- package/src/lib/components/console/reservations-card.component.js.map +1 -1
- package/src/lib/components/console/return-settings-card.component.js +39 -17
- package/src/lib/components/console/return-settings-card.component.js.map +1 -1
- package/src/lib/components/console/shipping-settings-card.component.js +34 -10
- package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
- package/src/lib/components/console/store-settings-card.component.js +38 -13
- package/src/lib/components/console/store-settings-card.component.js.map +1 -1
- package/src/lib/components/console/suppliers-card.component.js +49 -15
- package/src/lib/components/console/suppliers-card.component.js.map +1 -1
- package/src/lib/components/console/tax-settings-card.component.js +36 -12
- package/src/lib/components/console/tax-settings-card.component.js.map +1 -1
- package/src/lib/model/commerce-pos-offline.d.ts +21 -3
- package/src/lib/model/commerce-pos-offline.js +17 -5
- package/src/lib/model/commerce-pos-offline.js.map +1 -1
- package/src/lib/server/cart.js +57 -0
- package/src/lib/server/cart.js.map +1 -1
- package/src/lib/server/pos-offline-card-order.d.ts +2 -0
- package/src/lib/server/pos-offline-card-order.js +6 -2
- package/src/lib/server/pos-offline-card-order.js.map +1 -1
- package/src/lib/server/pos-offline-card-reconcile.d.ts +5 -1
- package/src/lib/server/pos-offline-card-reconcile.js +42 -10
- package/src/lib/server/pos-offline-card-reconcile.js.map +1 -1
- package/src/lib/server/pos-offline-sync.d.ts +48 -6
- package/src/lib/server/pos-offline-sync.js +142 -31
- package/src/lib/server/pos-offline-sync.js.map +1 -1
- package/src/lib/server/pos-stripe.d.ts +11 -0
- package/src/lib/server/pos-stripe.js +14 -0
- package/src/lib/server/pos-stripe.js.map +1 -1
- package/src/lib/server/pos-terminal.d.ts +21 -1
- package/src/lib/server/pos-terminal.js +41 -7
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/transfer/product-transfer.js +15 -1
- package/src/lib/transfer/product-transfer.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/cart.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { advertisingConsentField } from '@aglyn/aglyn/app-utils/advertising-consent'\nimport * as Aglyn from '@aglyn/aglyn'\nimport {\n buildBeginCheckoutParams,\n buildViewCartParams,\n trackEvent,\n trackEventBeforeNavigation,\n type AnalyticsItem,\n} from '@aglyn/aglyn/app-utils/analytics-events'\nimport { isPaymentsNotConfigured } from '@aglyn/aglyn/app-utils/payments-configured'\nimport { storefrontPaymentsNotConfiguredText } from '../constants/storefront-payments'\nimport * as CommerceModel from '../model'\n// From the pure module, not the model barrel: through the barrel the name\n// resolves via `commerce-check-in.ts`, and that re-export alone makes the\n// check-in window, the POS helpers and the receipt eager (check:plugin-budgets).\nimport { checkInDayLabel } from '../model/commerce-check-in-product'\nimport { mdiCartOutline } from '@aglyn/shared-data-mdi'\nimport Alert from '@mui/material/Alert'\nimport Badge from '@mui/material/Badge'\nimport Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\nimport Checkbox from '@mui/material/Checkbox'\nimport Drawer from '@mui/material/Drawer'\nimport FormControlLabel from '@mui/material/FormControlLabel'\nimport IconButton from '@mui/material/IconButton'\nimport MenuItem from '@mui/material/MenuItem'\nimport SvgIcon from '@mui/material/SvgIcon'\nimport TextField from '@mui/material/TextField'\nimport Typography from '@mui/material/Typography'\nimport {\n Suspense,\n forwardRef,\n lazy,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport { StorefrontPaymentElementFallback } from './storefront-payment-element-fallback'\nimport { CheckoutReturnNotice } from './checkout-return-notice'\nimport { CartExtras, useCartExtras } from './cart-extras'\nimport { CartFulfillmentChoice, useCartFulfillment } from './cart-fulfillment'\nimport {\n HardwareTermsConsent,\n hardwareTermsAnswered,\n NO_HARDWARE_TERMS_ANSWER,\n type HardwareTermsAnswer,\n} from './hardware-terms-consent'\n\n/**\n * The Payment Element (AGL-1944), lazily. Stripe.js and its React wrapper are\n * a large dependency and the flag is OFF, so a static import would ship the\n * whole SDK in the bundle of every page carrying a cart — which is most pages\n * on a storefront — to serve a path no shopper currently reaches.\n */\nconst StorefrontPaymentElement = lazy(() =>\n import('./storefront-payment-element').then((module) => ({\n default: module.StorefrontPaymentElement,\n })),\n)\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { CART_UPDATED_EVENT } from '../constants/cart-events'\nimport { generatePresetId } from '../utils/generate-preset-id'\nimport { useStorefrontPurchaseEvent } from '../utils/use-storefront-purchase-event'\n\n// Component ids are persisted in screen documents; never rename.\nexport const ID: Aglyn.ComponentId = 'cart'\n\n/** Blocks dispatch this after mutating the cart so badges refresh. */\nexport { CART_UPDATED_EVENT }\n\nexport interface CartProps {\n /** 'button' = app-bar icon + drawer; 'inline' = full cart in place. */\n variant?: 'button' | 'inline'\n checkoutLabel?: string\n /** Show the coupon-code field above checkout. */\n showCoupon?: boolean\n emptyText?: string\n}\n\ninterface CartLineView {\n productId: string\n variantId?: string\n /** The day the shopper chose to use a check-in item (AGL-4043). */\n useDayKey?: string\n /** The add-ons chosen with it (AGL-4100), ids only: part of the line's identity. */\n modifiers?: CommerceModel.ModifierSelection[]\n quantity: number\n name: string\n variantLabel?: string\n unitAmountCents: number\n imageUrl?: string\n unavailable?: boolean\n /** What to do about an unavailable line, when the server can say (AGL-4100). */\n problem?: string\n}\n\ninterface CartView {\n lines: CartLineView[]\n count: number\n subtotalCents: number\n /** The cart holds card reader hardware the platform's own store sells (AGL-4038). */\n hardwareTerms?: boolean\n}\n\nconst usd = (cents: number) => `$${(cents / 100).toFixed(2)}`\n\n/**\n * The cart's lines as GA4 `items`.\n *\n * One mapping for every event this file sends — `view_cart` and both\n * `begin_checkout` branches — because the `item_id` is what joins them into a\n * single per-product funnel with the `view_item` and `add_to_cart` the product\n * blocks send. Three hand-written copies of the same map are three chances for\n * one step to start reporting a variant id, or a name, or a different price\n * basis, and a funnel whose steps disagree about the product silently reports\n * a drop that never happened.\n */\nfunction cartAnalyticsItems(cart: CartView | null): AnalyticsItem[] {\n return (cart?.lines ?? []).map((line) => ({\n item_id: line.productId,\n item_name: line.name,\n price: line.unitAmountCents / 100,\n quantity: line.quantity,\n }))\n}\n\nfunction CartLines(props: {\n hostId: string\n cart: CartView | null\n showCoupon?: boolean\n checkoutLabel?: string\n emptyText?: string\n onMutate: (body: Record<string, unknown>) => Promise<void>\n}) {\n const { hostId, cart, showCoupon, checkoutLabel, emptyText, onMutate } =\n props\n const siteFetch = Aglyn.useSiteFetch()\n const [coupon, setCoupon] = useState('')\n const [email, setEmail] = useState('')\n const [optIn, setOptIn] = useState(false)\n const [giftCard, setGiftCard] = useState('')\n // A rewards or referral code (AGL-3640), asked only where the store takes one.\n const [creditCode, setCreditCode] = useState('')\n // Where the parcel is going (AGL-1721). Asked ONLY when the server says it\n // cannot price shipping without it — a merchant with one zone, one\n // rest-of-world zone, or no shipping at all never sees this field, which is\n // the common configuration. `null` is \"not asked\", so the field appearing is\n // itself the server's answer rather than a guess made here.\n const [shipTo, setShipTo] = useState('')\n const [shipCountries, setShipCountries] = useState<string[] | null>(null)\n // Live carrier rates price by postal code (AGL-3612): asked only when the\n // store prices that way and the server says so.\n const [shipPostal, setShipPostal] = useState('')\n const [askPostal, setAskPostal] = useState(false)\n // `paused` is its own state, not an `error` with gentler words (AGL-1511):\n // the two need different severities, and a shopper told in red that\n // checkout failed does not read the sentence explaining it did not. `ask` is\n // the same argument again: being asked for a destination is not a failure.\n // `unconfigured` is the third instance (AGL-2019): a store with no Stripe key\n // answers 501, and before this that fell through to the error tail below and\n // rendered RED. It is also the only one of the five that is TERMINAL — the\n // others can succeed on a retry, this one cannot until the operator acts, so\n // it latches the buy control off instead of inviting another click.\n const [status, setStatus] = useState<\n 'idle' | 'sending' | 'error' | 'paused' | 'ask' | 'unconfigured'\n >('idle')\n const [message, setMessage] = useState('')\n // The terms of sale and business use, for card reader hardware (AGL-4038):\n // asked when the cart says it holds some, or when a checkout was refused\n // for want of them.\n const [hardwareTerms, setHardwareTerms] = useState<HardwareTermsAnswer>(NO_HARDWARE_TERMS_ANSWER)\n const [hardwareTermsAsked, setHardwareTermsAsked] = useState(false)\n /**\n * The in-page checkout session (AGL-1944). Null unless the server chose\n * native mode, which needs both the release flag and a publishable key.\n */\n const [nativeCheckout, setNativeCheckout] = useState<{\n clientSecret: string\n publishableKey: string\n /** The seller's account for a direct-charge session. */\n stripeAccount?: string\n /** The wallets the merchant hid (AGL-3629). */\n wallets?: CommerceModel.StorefrontCheckoutWallets\n } | null>(null)\n /**\n * In-progress quantity edits, keyed by line, as the raw field text\n * (AGL-1772). The field used to POST /api/commerce/cart on every\n * keystroke — typing \"100\" was three Firestore writes, and clearing the\n * field to retype passed through `\"\"` → 0, which is the REMOVE path, so a\n * select-all-and-retype could delete the line mid-edit (and the response\n * replacing `cart` state then fought the input).\n *\n * The repo convention for quantity inputs is local state committed on an\n * explicit settle — the PDP's Qty field (product-detail.tsx) holds\n * `useState` and sends nothing until the buy click, and besigner\n * attributes commit on blur. So: keystrokes only edit the draft; blur or\n * Enter commits ONE write; an empty or unparsable draft is a pending\n * state that reverts to the server's quantity, never a 0-as-remove. A\n * genuine remove still works both ways — the ✕ button, and typing an\n * actual 0 then leaving the field.\n */\n const [quantityDrafts, setQuantityDrafts] = useState<Record<string, string>>(\n {},\n )\n const lineKey = (line: CartLineView) => CommerceModel.cartLineKey(line)\n const commitQuantity = (line: CartLineView) => {\n const key = lineKey(line)\n const draft = quantityDrafts[key]\n if (draft === undefined) return\n // Drops the draft, but only if it is still THIS one — a keystroke that\n // lands while the write is in flight starts a new edit, and clearing it\n // here would erase what the shopper is typing.\n const settle = () =>\n setQuantityDrafts((drafts) => {\n if (drafts[key] !== draft) return drafts\n const { [key]: _settled, ...rest } = drafts\n return rest\n })\n // `Number('')` is 0 — exactly the misreading that turned a cleared\n // field into a remove. Empty means \"no answer\": show the server's\n // quantity again and write nothing. NaN (letters) reverts the same way.\n if (draft.trim() === '') return settle()\n const parsed = Math.round(Number(draft))\n if (!Number.isFinite(parsed)) return settle()\n const quantity = Math.max(0, parsed)\n // A settled value equal to the server's is not an edit.\n if (quantity === line.quantity) return settle()\n // The draft keeps rendering until the response lands, so the field does\n // not flash the superseded quantity during the round-trip; the server's\n // answer (via the replaced `cart`) takes over when it arrives.\n void onMutate({\n action: 'set',\n productId: line.productId,\n variantId: line.variantId,\n ...(line.useDayKey ? { useDayKey: line.useDayKey } : {}),\n ...(line.modifiers?.length ? { modifiers: line.modifiers } : {}),\n quantity,\n }).finally(settle)\n }\n\n /**\n * Idempotency key for ONE checkout attempt (AGL-1697).\n *\n * Minted lazily on the first checkout click, retired whenever the attempt\n * changes shape — different lines, codes, email or destination are a\n * different checkout. Keyed off a CONTENT signature of the lines rather\n * than the `cart` object, whose identity changes on every refetch: retiring\n * on identity would hand a genuine retry a fresh key, which is exactly the\n * double-session this exists to prevent.\n */\n const attemptKey = useRef('')\n const cartSignature = useMemo(\n () =>\n JSON.stringify(\n (cart?.lines ?? []).map((line) => [\n line.productId,\n line.variantId ?? '',\n line.useDayKey ?? '',\n // Different add-ons are a different basket (AGL-4100).\n CommerceModel.modifierSelectionKey(line.modifiers),\n line.quantity,\n ]),\n ),\n [cart],\n )\n // Optional lines another plugin offers (AGL-3635), asked while the cart is shown.\n const extras = useCartExtras(hostId, cartSignature)\n const extrasSignature = extras.chosenIds.join(',')\n // Shipped, picked up, or the store's own delivery (AGL-3624).\n const fulfillment = useCartFulfillment(hostId, cartSignature)\n useEffect(() => {\n attemptKey.current = ''\n }, [cartSignature, email, coupon, giftCard, creditCode, shipTo, shipPostal, extrasSignature, fulfillment.signature])\n\n const handleCheckout = useCallback(async () => {\n if (status === 'sending') return\n setStatus('sending')\n setMessage('')\n if (!attemptKey.current) {\n attemptKey.current =\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now()}-${Math.random().toString(36).slice(2)}`\n }\n try {\n const response = await siteFetch('/api/commerce/cart-checkout', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n // Stable across a retry of THIS attempt (AGL-1697), so a\n // double-click cannot spawn a second session from one cart.\n 'Idempotency-Key': attemptKey.current,\n },\n body: JSON.stringify({\n hostId,\n ...(email.trim() ? { email: email.trim() } : {}),\n ...(optIn ? { marketingOptIn: true } : {}),\n ...(coupon.trim() ? { couponCode: coupon.trim() } : {}),\n ...(giftCard.trim() ? { giftCardCode: giftCard.trim() } : {}),\n ...(creditCode.trim() && extras.credits.length ? { creditCode: creditCode.trim() } : {}),\n // A request, never an instruction: the server resolves the rates\n // for this country AND restricts the session's collectable\n // addresses to it, so declaring one cannot buy a cheaper zone's\n // rate than the address the shopper then enters (AGL-1721).\n ...(shipTo && !fulfillment.request ? { shippingCountry: shipTo } : {}),\n ...(shipPostal.trim() && !fulfillment.request ? { shippingPostalCode: shipPostal.trim() } : {}),\n // Which offers, never their price: the server asks the provider again.\n ...(extras.chosenIds.length ? { extras: extras.chosenIds } : {}),\n // The buyer's answers, never trusted for what the cart holds: the\n // server reads the products and refuses hardware without both.\n ...(cart?.hardwareTerms || hardwareTermsAsked ? { hardwareTerms } : {}),\n // Where and when, never the fee: the server decides it again.\n ...(fulfillment.request ? { fulfillment: fulfillment.request } : {}),\n // The visitor's advertising consent and the vendors' browser ids, only\n // where that consent grants advertising (AGL-3694); absent otherwise.\n ...advertisingConsentField(hostId),\n }),\n })\n const payload = await response.json().catch(() => ({}))\n // In-page payment (AGL-1944). Checked BEFORE the redirect branch: a\n // native session carries a client secret and no url, and if a server ever\n // sent both, navigating away would silently discard the form.\n //\n // `begin_checkout` is reported on BOTH paths, and from the same place, so\n // the GA4 funnel does not develop a hole the day the flag flips — a\n // storefront whose `begin_checkout` count halved would look like a\n // conversion collapse rather than a checkout that stopped redirecting.\n if (response.ok && payload?.clientSecret && payload?.publishableKey) {\n trackEvent(\n 'begin_checkout',\n buildBeginCheckoutParams({\n value: (cart?.subtotalCents ?? 0) / 100,\n items: cartAnalyticsItems(cart),\n }),\n )\n setNativeCheckout({\n clientSecret: String(payload.clientSecret),\n publishableKey: String(payload.publishableKey),\n ...(payload.stripeAccount\n ? { stripeAccount: String(payload.stripeAccount) }\n : {}),\n wallets: CommerceModel.readStorefrontCheckoutWallets(payload.wallets),\n })\n setStatus('idle')\n return\n }\n if (response.ok && payload?.url) {\n // GA4 checkout funnel (AGL-1561, converted by AGL-1591). This used to\n // call `window.gtag` raw with `value`/`currency` only, so the same\n // event name arrived from this surface and from the console's plan\n // checkout in two different shapes — and this half carried no `items`,\n // which is the field GA4's ecommerce funnel is actually built on.\n //\n // The item ids are the PRODUCT ids `view_item` and `add_to_cart`\n // already send, so the three now join into one per-product funnel.\n // `value` is stated rather than derived because the cart subtotal is\n // authoritative after a coupon or gift card, which the line prices\n // below are not. No `billing_interval`: a storefront cart is not a\n // subscription.\n //\n // AWAITED before the redirect (AGL-1580). This surface registers no\n // transport, so delivery is a synchronous `window.gtag` call and the\n // await resolves immediately — a storefront checkout is not slowed by\n // one microtask. It is written this way anyway because the property\n // that makes it safe is invisible from here: the day this bundle grows\n // an async transport, or a host registers one for it, the bare call\n // would start losing the event on exactly the branch that navigates,\n // and nothing at this call site would look different.\n await trackEventBeforeNavigation(\n 'begin_checkout',\n buildBeginCheckoutParams({\n value: (cart?.subtotalCents ?? 0) / 100,\n items: cartAnalyticsItems(cart),\n }),\n )\n window.location.assign(payload.url)\n return\n }\n // A read-only lockdown answers 423 with the visitor pause copy\n // (AGL-1511). Rendering `payload.error` here would print the wire\n // token \"locked\" at a shopper, and the `severity=\"error\"` styling\n // would tell them their payment failed — the one thing this copy\n // exists to never say. So the refusal is parsed and shown as a calm\n // notice instead.\n const paused = Aglyn.parseLockdownRefusal(response.status, payload)\n if (paused) {\n setMessage(Aglyn.lockdownRefusalText(paused))\n setStatus('paused')\n return\n }\n // A store that never had payments configured (AGL-2019). The server's\n // own words are NOT rendered here even though they are safe today:\n // this is a visitor-facing surface, the 501 bodies differ between the\n // cart and buy-now doors, and one of them could grow a variable name\n // without anyone thinking about who reads it.\n // An offer the shopper ticked changed or went away (AGL-3635): show\n // what is offered now and let them decide again.\n if (payload?.extrasChanged) {\n extras.reload()\n setMessage(String(payload?.error ?? ''))\n setStatus('error')\n return\n }\n // Card reader hardware needs the terms of sale ticked (AGL-4038): show\n // the boxes with the server's sentence.\n if (payload?.needsHardwareTerms) {\n setHardwareTermsAsked(true)\n setMessage(String(payload?.error ?? ''))\n setStatus('ask')\n return\n }\n // The pickup location or delivery time went away while the cart was\n // open (AGL-3624): ask again and let the shopper choose.\n if (payload?.fulfillmentChanged) {\n fulfillment.reload()\n setMessage(String(payload?.error ?? ''))\n setStatus('error')\n return\n }\n if (isPaymentsNotConfigured(response.status)) {\n setMessage(storefrontPaymentsNotConfiguredText())\n setStatus('unconfigured')\n return\n }\n // The merchant's rates differ by destination, so the server will not\n // price this cart until it knows one (AGL-1721). Reveal the field and\n // let the shopper answer; a store that never sends this never shows it.\n if (payload?.needsShippingCountry) {\n if (payload?.needsShippingPostalCode) setAskPostal(true)\n setShipCountries(\n (payload.shippingCountries as string[] | undefined)?.length\n ? (payload.shippingCountries as string[])\n : [...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES],\n )\n setMessage(String(payload?.error ?? ''))\n // An unserved destination is a real refusal and reads as one; being\n // asked the first time is not.\n setStatus(shipTo ? 'error' : 'ask')\n return\n }\n setMessage(String(payload?.error ?? ''))\n setStatus('error')\n } catch {\n setStatus('error')\n }\n // `cart` is a dependency because the payload above reads it: without it\n // the handler closes over whichever cart was current when it was created,\n // and a checkout started after a quantity change would report the OLD\n // subtotal and the OLD lines. The pre-AGL-1591 raw call had the same bug\n // in the `value` alone, where a wrong number is indistinguishable from a\n // right one.\n }, [hostId, cart, coupon, email, optIn, giftCard, creditCode, shipTo, shipPostal, status, siteFetch, extras.chosenIds, extras.reload, extras.credits.length, fulfillment.request, fulfillment.reload, hardwareTerms, hardwareTermsAsked])\n\n if (!cart || cart.lines.length === 0) {\n return (\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ p: 2 }}>\n {emptyText || 'Your cart is empty.'}\n </Typography>\n )\n }\n return (\n <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, p: 2 }}>\n {cart.lines.map((line) => {\n // AGL-1726: resolve BEFORE the guard, never inside the `src`. A\n // stored value can be truthy and still resolve to nothing (a\n // malformed `media:` reference), and testing the raw string would\n // turn \"no image\" into an `<img>` with no `src` — a broken-image\n // icon where the placeholder belongs.\n const imageUrl = Aglyn.siteRelativeMediaSrc(line.imageUrl, { hostId })\n return (\n <Box\n key={lineKey(line)}\n sx={{ display: 'flex', gap: 1.5, alignItems: 'center' }}\n >\n {imageUrl ? (\n <Box\n component=\"img\"\n src={imageUrl}\n alt=\"\"\n sx={{\n width: 48,\n height: 48,\n objectFit: 'cover',\n borderRadius: 1,\n }}\n // Deferred (AGL-2486). A 48px cart-line thumbnail is the\n // clearest case of the set: it can never be the LCP, and a\n // cart is usually below the fold or inside a panel.\n {...Aglyn.DEFERRED_IMAGE_ATTRIBUTES}\n />\n ) : (\n <Box\n sx={{\n width: 48,\n height: 48,\n bgcolor: 'action.hover',\n borderRadius: 1,\n }}\n />\n )}\n <Box sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {line.name}\n {line.variantLabel ? ` — ${line.variantLabel}` : ''}\n </Typography>\n {line.useDayKey ? (\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\">\n {`For ${checkInDayLabel(line.useDayKey)}`}\n </Typography>\n ) : null}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {line.unavailable\n ? (line.problem ?? 'No longer available')\n : usd(line.unitAmountCents)}\n </Typography>\n </Box>\n <TextField\n value={quantityDrafts[lineKey(line)] ?? line.quantity}\n onChange={(event) =>\n setQuantityDrafts((drafts) => ({\n ...drafts,\n [lineKey(line)]: event.target.value,\n }))\n }\n onBlur={() => commitQuantity(line)}\n onKeyDown={(event) => {\n if (event.key === 'Enter') commitQuantity(line)\n }}\n size=\"small\"\n // Four digits fit (AGL-4205): a line goes up to 9,999.\n sx={{ width: (theme) => theme.spacing(10) }}\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n <Button\n size=\"small\"\n color=\"error\"\n onClick={() =>\n void onMutate({\n action: 'remove',\n productId: line.productId,\n variantId: line.variantId,\n ...(line.useDayKey ? { useDayKey: line.useDayKey } : {}),\n ...(line.modifiers?.length ? { modifiers: line.modifiers } : {}),\n })\n }\n >\n {'✕'}\n </Button>\n </Box>\n )\n })}\n <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>\n <Typography variant=\"subtitle2\">{'Subtotal'}</Typography>\n <Typography variant=\"subtitle2\">{usd(cart.subtotalCents)}</Typography>\n </Box>\n <CartExtras\n offers={extras.offers}\n chosen={extras.chosen}\n onToggle={extras.toggle}\n formatCents={usd}\n />\n <CartFulfillmentChoice state={fulfillment} formatCents={usd} />\n <Typography variant=\"caption\" color=\"text.secondary\">\n {fulfillment.method === 'shipping'\n ? 'Shipping and taxes are calculated at checkout.'\n : 'Taxes are calculated at checkout.'}\n </Typography>\n <TextField\n label=\"Email\"\n type=\"email\"\n value={email}\n onChange={(event) => setEmail(event.target.value)}\n size=\"small\"\n helperText=\"For your receipt and order updates\"\n />\n <FormControlLabel\n control={\n <Checkbox\n size=\"small\"\n checked={optIn}\n onChange={(event) => setOptIn(event.target.checked)}\n />\n }\n label={\n <Typography variant=\"caption\">\n {'Email me news and offers'}\n </Typography>\n }\n />\n {showCoupon ? (\n <>\n <TextField\n label=\"Coupon code\"\n value={coupon}\n onChange={(event) => setCoupon(event.target.value)}\n size=\"small\"\n />\n <TextField\n label=\"Gift card\"\n value={giftCard}\n onChange={(event) => setGiftCard(event.target.value)}\n size=\"small\"\n placeholder=\"GC-…\"\n />\n </>\n ) : null}\n {extras.credits.length ? (\n // Drawn wherever the store takes a code, coupon field or not: a\n // member was emailed theirs and comes here to spend it (AGL-3640).\n <TextField\n label={`${extras.credits[0].label} code`}\n value={creditCode}\n onChange={(event) => setCreditCode(event.target.value)}\n size=\"small\"\n slotProps={{ htmlInput: { 'data-testid': 'cart-credit-code' } }}\n />\n ) : null}\n {shipCountries && fulfillment.method === 'shipping' ? (\n <TextField\n select\n label=\"Ship to\"\n value={shipTo}\n onChange={(event) => setShipTo(event.target.value)}\n size=\"small\"\n helperText=\"Shipping rates depend on where this is going\"\n >\n {shipCountries.map((code) => (\n <MenuItem key={code} value={code}>\n {CommerceModel.CHECKOUT_SHIPPING_COUNTRY_NAMES[code] ?? code}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n {askPostal && fulfillment.method === 'shipping' ? (\n <TextField\n label=\"Postal code\"\n value={shipPostal}\n onChange={(event) => setShipPostal(event.target.value)}\n size=\"small\"\n helperText=\"Carrier rates depend on the postal code\"\n slotProps={{ htmlInput: { autoComplete: 'shipping postal-code', maxLength: 12 } }}\n />\n ) : null}\n {cart.hardwareTerms || hardwareTermsAsked ? (\n <HardwareTermsConsent answer={hardwareTerms} onChange={setHardwareTerms} />\n ) : null}\n {status === 'paused' || status === 'ask' || status === 'unconfigured' ? (\n <Alert severity=\"info\">{message}</Alert>\n ) : null}\n {status === 'error' ? (\n <Alert severity=\"error\">\n {message || 'Checkout is unavailable right now.'}\n </Alert>\n ) : null}\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={\n status === 'sending' ||\n cart.lines.every((line) => line.unavailable) ||\n // No payments on this deployment: every further click gets the same\n // 501, so the control latches off rather than inviting a retry that\n // cannot succeed (AGL-2019).\n status === 'unconfigured' ||\n // Asked but unanswered: the server would only refuse again.\n (fulfillment.method === 'shipping' && shipCountries !== null && !shipTo) ||\n (fulfillment.method === 'shipping' && askPostal && !shipPostal.trim()) ||\n // Pickup needs a location, delivery a zone and a time (AGL-3624).\n !fulfillment.ready ||\n // Card reader hardware: both boxes ticked (AGL-4038).\n ((Boolean(cart.hardwareTerms) || hardwareTermsAsked) && !hardwareTermsAnswered(hardwareTerms))\n }\n onClick={handleCheckout}\n >\n {status === 'sending'\n ? // \"Redirecting\" stops being true the moment the form opens in\n // place (AGL-1944).\n nativeCheckout\n ? 'Opening…'\n : 'Redirecting…'\n : checkoutLabel || 'Checkout'}\n </Button>\n {nativeCheckout ? (\n <Suspense fallback={<StorefrontPaymentElementFallback />}>\n <StorefrontPaymentElement\n clientSecret={nativeCheckout.clientSecret}\n publishableKey={nativeCheckout.publishableKey}\n stripeAccount={nativeCheckout.stripeAccount}\n wallets={nativeCheckout.wallets}\n payLabel={checkoutLabel || 'Pay now'}\n defaultEmail={email}\n // An expired or unloadable session is replaced, never replayed:\n // the old attempt key would hand back the dead session.\n onRestart={() => {\n attemptKey.current = ''\n setNativeCheckout(null)\n void handleCheckout()\n }}\n // The session is left open on cancel, deliberately: it is what the\n // AGL-323 abandoned-cart recovery emails are built on, and expiring\n // it would be a write against the merchant's Stripe account made\n // from a browser.\n onCancel={() => setNativeCheckout(null)}\n />\n </Suspense>\n ) : null}\n </Box>\n )\n}\n\n/**\n * Cart block (AGL-293): 'button' renders a badge icon + slide-out\n * drawer for app bars; 'inline' renders the full cart for a cart page.\n * Lines live server-side (cookie cart); every mutation re-resolves\n * prices. Other blocks broadcast CART_UPDATED_EVENT to refresh badges.\n */\nconst Cart = forwardRef<HTMLDivElement, CartProps>((props, ref) => {\n const { variant, checkoutLabel, showCoupon, emptyText, ...rest } = props\n // Node styles ride the renderer-merged sx; recompose (stack.ts pattern).\n const nodeSx = Array.isArray(props['sx']) ? props['sx'] : [props['sx']]\n const { hostId } = Aglyn.useSite()\n const siteFetch = Aglyn.useSiteFetch()\n const [cart, setCart] = useState<CartView | null>(null)\n const [open, setOpen] = useState(false)\n\n // Closes the merchant's ecommerce funnel (AGL-1641). Stripe returns a cart\n // checkout to the page it started on — this one — so the `purchase` that\n // `begin_checkout` above has never had a counterpart to is reported here.\n // No-ops on every ordinary render: the hook returns immediately unless the\n // URL carries `?order=success&session_id=…`.\n useStorefrontPurchaseEvent(hostId, siteFetch)\n\n const refresh = useCallback(async () => {\n if (!hostId) return\n try {\n const response = await fetch(\n `/api/commerce/cart?hostId=${encodeURIComponent(hostId)}`,\n )\n if (response.ok) setCart(await response.json())\n } catch {\n // Badge silently stays stale offline.\n }\n }, [hostId])\n\n useEffect(() => {\n void refresh()\n const handler = () => void refresh()\n window.addEventListener(CART_UPDATED_EVENT, handler)\n return () => window.removeEventListener(CART_UPDATED_EVENT, handler)\n }, [refresh])\n\n /**\n * Has THIS opening of the cart already been reported? A drawer that is\n * closed and reopened is a second view; a re-render, a badge refresh or a\n * quantity edit inside an already-open drawer is not.\n */\n const viewReported = useRef(false)\n\n /**\n * `view_cart` — the funnel step between `add_to_cart` and `begin_checkout`.\n *\n * Fired on the cart being SEEN, which is why it hangs off `open` rather off\n * mount: the button variant renders a badge on every page of a storefront,\n * and reporting a view there would have made \"opened the cart\" a synonym for\n * \"loaded a page\" and the checkout rate a fraction of pageviews.\n *\n * Deferred until the lines have actually arrived. The cart is fetched, so a\n * drawer opened while that request is in flight has nothing to describe yet\n * — reporting then would send an empty `items` and a zero `value` for a cart\n * that in fact had both. An empty cart never reports at all: there is no\n * view of nothing, and counting it would put every idle badge click into the\n * denominator of the checkout rate.\n */\n useEffect(() => {\n const onScreen = variant === 'inline' || open\n if (!onScreen) {\n viewReported.current = false\n return\n }\n if (viewReported.current || !cart || cart.lines.length === 0) return\n viewReported.current = true\n trackEvent(\n 'view_cart',\n buildViewCartParams({\n // The server's subtotal, so this and the `begin_checkout` the same\n // cart sends describe one cart at one size.\n value: cart.subtotalCents / 100,\n items: cartAnalyticsItems(cart),\n }),\n )\n }, [variant, open, cart])\n\n const mutate = useCallback(\n async (body: Record<string, unknown>) => {\n if (!hostId) return\n const response = await siteFetch('/api/commerce/cart', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, ...body }),\n })\n if (response.ok) {\n setCart(await response.json())\n window.dispatchEvent(new Event(CART_UPDATED_EVENT))\n }\n },\n [hostId, siteFetch],\n )\n\n if (!hostId) {\n return (\n <Box\n ref={ref}\n {...rest}\n sx={[\n {\n p: variant === 'inline' ? 3 : 1,\n border: '1px dashed',\n borderColor: 'divider',\n borderRadius: 1,\n color: 'text.secondary',\n fontSize: 13,\n fontFamily: 'system-ui, sans-serif',\n display: 'inline-block',\n },\n ...nodeSx,\n ]}\n >\n {variant === 'inline' ? 'Cart — lines render here' : '🛒 Cart'}\n </Box>\n )\n }\n\n if (variant === 'inline') {\n return (\n <Box ref={ref} {...rest}>\n <CheckoutReturnNotice hostId={hostId} siteFetch={siteFetch} />\n <CartLines\n hostId={hostId}\n cart={cart}\n showCoupon={showCoupon}\n checkoutLabel={checkoutLabel}\n emptyText={emptyText}\n onMutate={mutate}\n />\n </Box>\n )\n }\n\n return (\n <Box ref={ref} {...rest} sx={[{ display: 'inline-flex' }, ...nodeSx]}>\n <CheckoutReturnNotice hostId={hostId} siteFetch={siteFetch} />\n {/* Inherits the color around it, as the header's other icons do:\n the default gray vanished on a dark photo and ignored a header's\n own color (AGL-4200). */}\n <IconButton aria-label=\"Cart\" color=\"inherit\" onClick={() => setOpen(true)}>\n <Badge badgeContent={cart?.count ?? 0} color=\"primary\">\n <SvgIcon>\n <path d={mdiCartOutline.path} />\n </SvgIcon>\n </Badge>\n </IconButton>\n <Drawer anchor=\"right\" open={open} onClose={() => setOpen(false)}>\n <Box sx={{ width: { xs: '85vw', sm: 380 } }}>\n <Typography variant=\"h6\" sx={{ p: 2, pb: 0 }}>\n {'Your cart'}\n </Typography>\n <CartLines\n hostId={hostId}\n cart={cart}\n showCoupon={showCoupon}\n checkoutLabel={checkoutLabel}\n emptyText={emptyText}\n onMutate={mutate}\n />\n </Box>\n </Drawer>\n </Box>\n )\n})\nCart.displayName = 'AglynCart'\n\nexport const schema: Aglyn.ComponentSchema<CartProps> = {\n $id: ID,\n pluginId: BUNDLE_ID,\n displayName: 'Cart',\n description:\n 'The shopping cart — a badge icon with a slide-out drawer, or the full cart page.',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiCartOutline.path, sx: { color: '#2e7d32' } },\n flags: { selfClosing: Aglyn.FEATURE_FLAG.ENABLED },\n attributes: [\n {\n name: 'variant',\n label: 'Style',\n description: 'Icon-with-drawer for app bars, or the full inline cart.',\n component: Aglyn.FieldComponentType.SELECT,\n options: [\n { value: 'button', label: 'Icon + drawer' },\n { value: 'inline', label: 'Inline (cart page)' },\n ],\n },\n {\n name: 'checkoutLabel',\n label: 'Checkout label',\n description: 'Defaults to \"Checkout\".',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n },\n {\n // The PROP KEY stays `showCoupon` — it is persisted in every saved page\n // that uses this component, and renaming it would blank the control on\n // all of them. Only what the merchant reads changes.\n name: 'showCoupon',\n // ONE CONTROL, TWO FEATURES, AND IT ONLY NAMED ONE. This checkbox gates\n // the gift-card field as well as the coupon field, so a merchant who\n // wanted gift cards had no reason to look here — gift cards are only\n // redeemable in the cart, and this is the switch that shows the box.\n // A control named for one feature that also gates another is how a\n // shipped feature stays invisible.\n label: 'Show coupon and gift card fields',\n description:\n 'One checkbox for both. Coupon codes and gift cards are managed on ' +\n 'the Products page.',\n component: Aglyn.FieldComponentType.CHECKBOX,\n },\n {\n name: 'emptyText',\n label: 'Empty text',\n description: 'Copy when the cart is empty.',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n },\n ],\n}\n\nexport const presets: Aglyn.PresetSchema[] = [\n {\n $id: generatePresetId(ID, 'button'),\n type: Aglyn.NodeType.PRESET,\n displayName: 'Cart button',\n pluginId: BUNDLE_ID,\n description: 'Badge icon with a slide-out cart drawer',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiCartOutline.path, sx: { color: '#2e7d32' } },\n data: {\n $id: null,\n componentId: ID,\n pluginId: BUNDLE_ID,\n props: { variant: 'button' },\n },\n },\n {\n $id: generatePresetId(ID, 'inline'),\n type: Aglyn.NodeType.PRESET,\n displayName: 'Cart page',\n pluginId: BUNDLE_ID,\n description:\n 'Full cart with quantities, coupon, gift card, and checkout',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiCartOutline.path, sx: { color: '#2e7d32' } },\n data: {\n $id: null,\n componentId: ID,\n pluginId: BUNDLE_ID,\n props: { variant: 'inline', showCoupon: true },\n },\n },\n]\n\nexport default Cart\n"],"names":["advertisingConsentField","Aglyn","buildBeginCheckoutParams","buildViewCartParams","trackEvent","trackEventBeforeNavigation","isPaymentsNotConfigured","storefrontPaymentsNotConfiguredText","CommerceModel","checkInDayLabel","mdiCartOutline","Alert","Badge","Box","Button","Checkbox","Drawer","FormControlLabel","IconButton","MenuItem","SvgIcon","TextField","Typography","Suspense","forwardRef","lazy","useCallback","useEffect","useMemo","useRef","useState","StorefrontPaymentElementFallback","CheckoutReturnNotice","CartExtras","useCartExtras","CartFulfillmentChoice","useCartFulfillment","HardwareTermsConsent","hardwareTermsAnswered","NO_HARDWARE_TERMS_ANSWER","StorefrontPaymentElement","then","module","default","BUNDLE_ID","CART_UPDATED_EVENT","generatePresetId","useStorefrontPurchaseEvent","ID","usd","cents","toFixed","cartAnalyticsItems","cart","lines","map","line","item_id","productId","item_name","name","price","unitAmountCents","quantity","CartLines","props","hostId","showCoupon","checkoutLabel","emptyText","onMutate","siteFetch","useSiteFetch","coupon","setCoupon","email","setEmail","optIn","setOptIn","giftCard","setGiftCard","creditCode","setCreditCode","shipTo","setShipTo","shipCountries","setShipCountries","shipPostal","setShipPostal","askPostal","setAskPostal","status","setStatus","message","setMessage","hardwareTerms","setHardwareTerms","hardwareTermsAsked","setHardwareTermsAsked","nativeCheckout","setNativeCheckout","quantityDrafts","setQuantityDrafts","lineKey","cartLineKey","commitQuantity","key","draft","undefined","settle","drafts","_settled","rest","trim","parsed","Math","round","Number","isFinite","max","action","variantId","useDayKey","modifiers","length","finally","attemptKey","cartSignature","JSON","stringify","modifierSelectionKey","extras","extrasSignature","chosenIds","join","fulfillment","current","signature","handleCheckout","globalThis","crypto","randomUUID","Date","now","random","toString","slice","response","method","headers","body","marketingOptIn","couponCode","giftCardCode","credits","request","shippingCountry","shippingPostalCode","payload","json","catch","ok","clientSecret","publishableKey","value","subtotalCents","items","String","stripeAccount","wallets","readStorefrontCheckoutWallets","url","window","location","assign","paused","parseLockdownRefusal","lockdownRefusalText","extrasChanged","reload","error","needsHardwareTerms","fulfillmentChanged","needsShippingCountry","needsShippingPostalCode","shippingCountries","CHECKOUT_SHIPPING_COUNTRIES","variant","color","sx","p","display","flexDirection","gap","imageUrl","siteRelativeMediaSrc","alignItems","component","src","alt","width","height","objectFit","borderRadius","DEFERRED_IMAGE_ATTRIBUTES","bgcolor","flex","minWidth","noWrap","variantLabel","unavailable","problem","onChange","event","target","onBlur","onKeyDown","size","theme","spacing","slotProps","htmlInput","inputMode","onClick","justifyContent","offers","chosen","onToggle","toggle","formatCents","state","label","type","helperText","control","checked","placeholder","select","code","CHECKOUT_SHIPPING_COUNTRY_NAMES","autoComplete","maxLength","answer","severity","disabled","every","ready","Boolean","fallback","payLabel","defaultEmail","onRestart","onCancel","Cart","ref","nodeSx","Array","isArray","useSite","setCart","open","setOpen","refresh","fetch","encodeURIComponent","handler","addEventListener","removeEventListener","viewReported","onScreen","mutate","dispatchEvent","Event","border","borderColor","fontSize","fontFamily","aria-label","badgeContent","count","path","d","anchor","onClose","xs","sm","pb","displayName","schema","$id","pluginId","description","category","ComponentCategory","COMMERCE","icon","flags","selfClosing","FEATURE_FLAG","ENABLED","attributes","FieldComponentType","SELECT","options","TEXT_FIELD","CHECKBOX","presets","NodeType","PRESET","data","componentId"],"mappings":";;;;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,uBAAuB,QAAQ,6CAA4C;AACpF,YAAYC,WAAW,eAAc;AACrC,SACEC,wBAAwB,EACxBC,mBAAmB,EACnBC,UAAU,EACVC,0BAA0B,QAErB,0CAAyC;AAChD,SAASC,uBAAuB,QAAQ,6CAA4C;AACpF,SAASC,mCAAmC,QAAQ,sCAAkC;AACtF,YAAYC,mBAAmB,oBAAU;AACzC,0EAA0E;AAC1E,0EAA0E;AAC1E,iFAAiF;AACjF,SAASC,eAAe,QAAQ,wCAAoC;AACpE,SAASC,cAAc,QAAQ,yBAAwB;AACvD,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,SAAS,oBAAmB;AACnC,OAAOC,YAAY,uBAAsB;AACzC,OAAOC,cAAc,yBAAwB;AAC7C,OAAOC,YAAY,uBAAsB;AACzC,OAAOC,sBAAsB,iCAAgC;AAC7D,OAAOC,gBAAgB,2BAA0B;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D,aAAa;YACb9F,WAAWpM,MAAM4S,kBAAkB,CAACG,UAAU;QAChD;KACD;AACH,EAAC;AAED,OAAO,MAAME,UAAgC;IAC3C;QACEjB,KAAKnP,iBAAiBE,IAAI;QAC1BwL,MAAMvO,MAAMkT,QAAQ,CAACC,MAAM;QAC3BrB,aAAa;QACbG,UAAUtP;QACVuP,aAAa;QACbC,UAAUnS,MAAMoS,iBAAiB,CAACC,QAAQ;QAC1CC,MAAM;YAAEf,MAAM9Q,eAAe8Q,IAAI;YAAE3F,IAAI;gBAAED,OAAO;YAAU;QAAE;QAC5DyH,MAAM;YACJpB,KAAK;YACLqB,aAAatQ;YACbkP,UAAUtP;YACVqB,OAAO;gBAAE0H,SAAS;YAAS;QAC7B;IACF;IACA;QACEsG,KAAKnP,iBAAiBE,IAAI;QAC1BwL,MAAMvO,MAAMkT,QAAQ,CAACC,MAAM;QAC3BrB,aAAa;QACbG,UAAUtP;QACVuP,aACE;QACFC,UAAUnS,MAAMoS,iBAAiB,CAACC,QAAQ;QAC1CC,MAAM;YAAEf,MAAM9Q,eAAe8Q,IAAI;YAAE3F,IAAI;gBAAED,OAAO;YAAU;QAAE;QAC5DyH,MAAM;YACJpB,KAAK;YACLqB,aAAatQ;YACbkP,UAAUtP;YACVqB,OAAO;gBAAE0H,SAAS;gBAAUxH,YAAY;YAAK;QAC/C;IACF;CACD,CAAA;AAED,eAAe0L,KAAI"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/cart.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { advertisingConsentField } from '@aglyn/aglyn/app-utils/advertising-consent'\nimport * as Aglyn from '@aglyn/aglyn'\nimport {\n buildBeginCheckoutParams,\n buildViewCartParams,\n trackEvent,\n trackEventBeforeNavigation,\n type AnalyticsItem,\n} from '@aglyn/aglyn/app-utils/analytics-events'\nimport { isPaymentsNotConfigured } from '@aglyn/aglyn/app-utils/payments-configured'\nimport { storefrontPaymentsNotConfiguredText } from '../constants/storefront-payments'\nimport * as CommerceModel from '../model'\n// From the pure module, not the model barrel: through the barrel the name\n// resolves via `commerce-check-in.ts`, and that re-export alone makes the\n// check-in window, the POS helpers and the receipt eager (check:plugin-budgets).\nimport { checkInDayLabel } from '../model/commerce-check-in-product'\nimport { mdiCartOutline } from '@aglyn/shared-data-mdi'\nimport Alert from '@mui/material/Alert'\nimport Badge from '@mui/material/Badge'\nimport Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\nimport Checkbox from '@mui/material/Checkbox'\nimport CircularProgress from '@mui/material/CircularProgress'\nimport Drawer from '@mui/material/Drawer'\nimport FormControlLabel from '@mui/material/FormControlLabel'\nimport IconButton from '@mui/material/IconButton'\nimport MenuItem from '@mui/material/MenuItem'\nimport SvgIcon from '@mui/material/SvgIcon'\nimport TextField from '@mui/material/TextField'\nimport Typography from '@mui/material/Typography'\nimport {\n Suspense,\n forwardRef,\n lazy,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport { StorefrontPaymentElementFallback } from './storefront-payment-element-fallback'\nimport { CheckoutReturnNotice } from './checkout-return-notice'\nimport { CartExtras, useCartExtras } from './cart-extras'\nimport { CartFulfillmentChoice, useCartFulfillment } from './cart-fulfillment'\nimport {\n HardwareTermsConsent,\n hardwareTermsAnswered,\n NO_HARDWARE_TERMS_ANSWER,\n type HardwareTermsAnswer,\n} from './hardware-terms-consent'\n\n/**\n * The Payment Element (AGL-1944), lazily. Stripe.js and its React wrapper are\n * a large dependency and the flag is OFF, so a static import would ship the\n * whole SDK in the bundle of every page carrying a cart — which is most pages\n * on a storefront — to serve a path no shopper currently reaches.\n */\nconst StorefrontPaymentElement = lazy(() =>\n import('./storefront-payment-element').then((module) => ({\n default: module.StorefrontPaymentElement,\n })),\n)\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { CART_UPDATED_EVENT } from '../constants/cart-events'\nimport { generatePresetId } from '../utils/generate-preset-id'\nimport { useStorefrontPurchaseEvent } from '../utils/use-storefront-purchase-event'\n\n// Component ids are persisted in screen documents; never rename.\nexport const ID: Aglyn.ComponentId = 'cart'\n\n/** Blocks dispatch this after mutating the cart so badges refresh. */\nexport { CART_UPDATED_EVENT }\n\nexport interface CartProps {\n /** 'button' = app-bar icon + drawer; 'inline' = full cart in place. */\n variant?: 'button' | 'inline'\n checkoutLabel?: string\n /** Show the coupon-code field above checkout. */\n showCoupon?: boolean\n emptyText?: string\n}\n\ninterface CartLineView {\n productId: string\n variantId?: string\n /** The day the shopper chose to use a check-in item (AGL-4043). */\n useDayKey?: string\n /** The add-ons chosen with it (AGL-4100), ids only: part of the line's identity. */\n modifiers?: CommerceModel.ModifierSelection[]\n quantity: number\n name: string\n variantLabel?: string\n unitAmountCents: number\n imageUrl?: string\n unavailable?: boolean\n /** What to do about an unavailable line, when the server can say (AGL-4100). */\n problem?: string\n}\n\ninterface CartView {\n lines: CartLineView[]\n count: number\n subtotalCents: number\n /** The cart holds card reader hardware the platform's own store sells (AGL-4038). */\n hardwareTerms?: boolean\n /**\n * Checkout will need to know where this cart is going (AGL-1721), so the\n * cart asks with its other fields instead of after the first press.\n */\n needsShippingCountry?: boolean\n shippingCountries?: string[]\n}\n\n/**\n * Where the stored cart is: still being read, read, or unreadable. The cart is\n * fetched, and until the first answer lands there is nothing to say about it:\n * rendering \"Your cart is empty.\" for that time told a shopper with two items\n * in it that they had none.\n */\ntype CartLoad = 'loading' | 'loaded' | 'failed'\n\nconst usd = (cents: number) => `$${(cents / 100).toFixed(2)}`\n\n/**\n * The stored cart's read: one URL for the preload hint and the fetch, so the\n * browser hands the fetch the response it already has.\n */\nfunction cartReadUrl(hostId: string): string {\n return `/api/commerce/cart?hostId=${encodeURIComponent(hostId)}`\n}\n\n/**\n * Starts the cart page's read while the HTML is still arriving (AGL-4047).\n *\n * The read is a client fetch, and a client effect runs only once the whole\n * page has hydrated: on aglyn.com/cart that was 0.5–4.3 s after the HTML\n * landed, and the cart's own request (0.3–0.75 s) only started then.\n * Rendered on the server, this hint has the browser make the same request as\n * soon as it parses the page, so when the cart mounts its fetch is answered\n * from the response already in hand. `crossOrigin=\"anonymous\"` is what lets a\n * `fetch()` with its defaults (cors, same-origin cookies) match it; without it\n * the browser would read the cart twice.\n *\n * The cart page only: a badge in a header is on every page of the store and\n * has nothing on screen waiting for its count.\n */\nfunction CartReadPreload({ hostId }: { hostId: string }) {\n return (\n <link rel=\"preload\" as=\"fetch\" href={cartReadUrl(hostId)} crossOrigin=\"anonymous\" />\n )\n}\n\n/**\n * The cart's lines as GA4 `items`.\n *\n * One mapping for every event this file sends — `view_cart` and both\n * `begin_checkout` branches — because the `item_id` is what joins them into a\n * single per-product funnel with the `view_item` and `add_to_cart` the product\n * blocks send. Three hand-written copies of the same map are three chances for\n * one step to start reporting a variant id, or a name, or a different price\n * basis, and a funnel whose steps disagree about the product silently reports\n * a drop that never happened.\n */\nfunction cartAnalyticsItems(cart: CartView | null): AnalyticsItem[] {\n return (cart?.lines ?? []).map((line) => ({\n item_id: line.productId,\n item_name: line.name,\n price: line.unitAmountCents / 100,\n quantity: line.quantity,\n }))\n}\n\nfunction CartLines(props: {\n hostId: string\n cart: CartView | null\n load: CartLoad\n showCoupon?: boolean\n checkoutLabel?: string\n emptyText?: string\n onMutate: (body: Record<string, unknown>) => Promise<void>\n}) {\n const { hostId, cart, load, showCoupon, checkoutLabel, emptyText, onMutate } =\n props\n const siteFetch = Aglyn.useSiteFetch()\n const [coupon, setCoupon] = useState('')\n const [email, setEmail] = useState('')\n const [optIn, setOptIn] = useState(false)\n const [giftCard, setGiftCard] = useState('')\n // A rewards or referral code (AGL-3640), asked only where the store takes one.\n const [creditCode, setCreditCode] = useState('')\n // Where the parcel is going (AGL-1721). Asked ONLY when the server says it\n // cannot price shipping without it — a merchant with one zone, one\n // rest-of-world zone, or no shipping at all never sees this field, which is\n // the common configuration. `null` is \"not asked\", so the field appearing is\n // itself the server's answer rather than a guess made here.\n const [shipTo, setShipTo] = useState('')\n const [shipCountries, setShipCountries] = useState<string[] | null>(null)\n // The cart itself can say so before any press, and then the field is shown\n // from the start with the others; a checkout answer still wins.\n const askedCountries =\n shipCountries ??\n (cart?.needsShippingCountry\n ? cart.shippingCountries?.length\n ? cart.shippingCountries\n : [...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES]\n : null)\n // Live carrier rates price by postal code (AGL-3612): asked only when the\n // store prices that way and the server says so.\n const [shipPostal, setShipPostal] = useState('')\n const [askPostal, setAskPostal] = useState(false)\n // `paused` is its own state, not an `error` with gentler words (AGL-1511):\n // the two need different severities, and a shopper told in red that\n // checkout failed does not read the sentence explaining it did not. `ask` is\n // the same argument again: being asked for a destination is not a failure.\n // `unconfigured` is the third instance (AGL-2019): a store with no Stripe key\n // answers 501, and before this that fell through to the error tail below and\n // rendered RED. It is also the only one of the five that is TERMINAL — the\n // others can succeed on a retry, this one cannot until the operator acts, so\n // it latches the buy control off instead of inviting another click.\n const [status, setStatus] = useState<\n 'idle' | 'sending' | 'error' | 'paused' | 'ask' | 'unconfigured'\n >('idle')\n const [message, setMessage] = useState('')\n // The notice is about the destination (\"Choose where you're shipping to.\",\n // a country not served, a postal code), so answering it clears it.\n const [messageForShipping, setMessageForShipping] = useState(false)\n const answerShipping = () => {\n if (!messageForShipping) return\n setMessageForShipping(false)\n setMessage('')\n setStatus('idle')\n }\n // The terms of sale and business use, for card reader hardware (AGL-4038):\n // asked when the cart says it holds some, or when a checkout was refused\n // for want of them.\n const [hardwareTerms, setHardwareTerms] = useState<HardwareTermsAnswer>(NO_HARDWARE_TERMS_ANSWER)\n const [hardwareTermsAsked, setHardwareTermsAsked] = useState(false)\n /**\n * The in-page checkout session (AGL-1944). Null unless the server chose\n * native mode, which needs both the release flag and a publishable key.\n */\n const [nativeCheckout, setNativeCheckout] = useState<{\n clientSecret: string\n publishableKey: string\n /** The seller's account for a direct-charge session. */\n stripeAccount?: string\n /** The wallets the merchant hid (AGL-3629). */\n wallets?: CommerceModel.StorefrontCheckoutWallets\n } | null>(null)\n /**\n * In-progress quantity edits, keyed by line, as the raw field text\n * (AGL-1772). The field used to POST /api/commerce/cart on every\n * keystroke — typing \"100\" was three Firestore writes, and clearing the\n * field to retype passed through `\"\"` → 0, which is the REMOVE path, so a\n * select-all-and-retype could delete the line mid-edit (and the response\n * replacing `cart` state then fought the input).\n *\n * The repo convention for quantity inputs is local state committed on an\n * explicit settle — the PDP's Qty field (product-detail.tsx) holds\n * `useState` and sends nothing until the buy click, and besigner\n * attributes commit on blur. So: keystrokes only edit the draft; blur or\n * Enter commits ONE write; an empty or unparsable draft is a pending\n * state that reverts to the server's quantity, never a 0-as-remove. A\n * genuine remove still works both ways — the ✕ button, and typing an\n * actual 0 then leaving the field.\n */\n const [quantityDrafts, setQuantityDrafts] = useState<Record<string, string>>(\n {},\n )\n const lineKey = (line: CartLineView) => CommerceModel.cartLineKey(line)\n const commitQuantity = (line: CartLineView) => {\n const key = lineKey(line)\n const draft = quantityDrafts[key]\n if (draft === undefined) return\n // Drops the draft, but only if it is still THIS one — a keystroke that\n // lands while the write is in flight starts a new edit, and clearing it\n // here would erase what the shopper is typing.\n const settle = () =>\n setQuantityDrafts((drafts) => {\n if (drafts[key] !== draft) return drafts\n const { [key]: _settled, ...rest } = drafts\n return rest\n })\n // `Number('')` is 0 — exactly the misreading that turned a cleared\n // field into a remove. Empty means \"no answer\": show the server's\n // quantity again and write nothing. NaN (letters) reverts the same way.\n if (draft.trim() === '') return settle()\n const parsed = Math.round(Number(draft))\n if (!Number.isFinite(parsed)) return settle()\n const quantity = Math.max(0, parsed)\n // A settled value equal to the server's is not an edit.\n if (quantity === line.quantity) return settle()\n // The draft keeps rendering until the response lands, so the field does\n // not flash the superseded quantity during the round-trip; the server's\n // answer (via the replaced `cart`) takes over when it arrives.\n void onMutate({\n action: 'set',\n productId: line.productId,\n variantId: line.variantId,\n ...(line.useDayKey ? { useDayKey: line.useDayKey } : {}),\n ...(line.modifiers?.length ? { modifiers: line.modifiers } : {}),\n quantity,\n }).finally(settle)\n }\n\n /**\n * Idempotency key for ONE checkout attempt (AGL-1697).\n *\n * Minted lazily on the first checkout click, retired whenever the attempt\n * changes shape — different lines, codes, email or destination are a\n * different checkout. Keyed off a CONTENT signature of the lines rather\n * than the `cart` object, whose identity changes on every refetch: retiring\n * on identity would hand a genuine retry a fresh key, which is exactly the\n * double-session this exists to prevent.\n */\n const attemptKey = useRef('')\n const cartSignature = useMemo(\n () =>\n JSON.stringify(\n (cart?.lines ?? []).map((line) => [\n line.productId,\n line.variantId ?? '',\n line.useDayKey ?? '',\n // Different add-ons are a different basket (AGL-4100).\n CommerceModel.modifierSelectionKey(line.modifiers),\n line.quantity,\n ]),\n ),\n [cart],\n )\n // Optional lines another plugin offers (AGL-3635), asked while the cart is shown.\n const extras = useCartExtras(hostId, cartSignature)\n const extrasSignature = extras.chosenIds.join(',')\n // Shipped, picked up, or the store's own delivery (AGL-3624).\n const fulfillment = useCartFulfillment(hostId, cartSignature)\n useEffect(() => {\n attemptKey.current = ''\n }, [cartSignature, email, coupon, giftCard, creditCode, shipTo, shipPostal, extrasSignature, fulfillment.signature])\n\n const handleCheckout = useCallback(async () => {\n if (status === 'sending') return\n setStatus('sending')\n setMessage('')\n setMessageForShipping(false)\n if (!attemptKey.current) {\n attemptKey.current =\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now()}-${Math.random().toString(36).slice(2)}`\n }\n try {\n const response = await siteFetch('/api/commerce/cart-checkout', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n // Stable across a retry of THIS attempt (AGL-1697), so a\n // double-click cannot spawn a second session from one cart.\n 'Idempotency-Key': attemptKey.current,\n },\n body: JSON.stringify({\n hostId,\n ...(email.trim() ? { email: email.trim() } : {}),\n ...(optIn ? { marketingOptIn: true } : {}),\n ...(coupon.trim() ? { couponCode: coupon.trim() } : {}),\n ...(giftCard.trim() ? { giftCardCode: giftCard.trim() } : {}),\n ...(creditCode.trim() && extras.credits.length ? { creditCode: creditCode.trim() } : {}),\n // A request, never an instruction: the server resolves the rates\n // for this country AND restricts the session's collectable\n // addresses to it, so declaring one cannot buy a cheaper zone's\n // rate than the address the shopper then enters (AGL-1721).\n ...(shipTo && !fulfillment.request ? { shippingCountry: shipTo } : {}),\n ...(shipPostal.trim() && !fulfillment.request ? { shippingPostalCode: shipPostal.trim() } : {}),\n // Which offers, never their price: the server asks the provider again.\n ...(extras.chosenIds.length ? { extras: extras.chosenIds } : {}),\n // The buyer's answers, never trusted for what the cart holds: the\n // server reads the products and refuses hardware without both.\n ...(cart?.hardwareTerms || hardwareTermsAsked ? { hardwareTerms } : {}),\n // Where and when, never the fee: the server decides it again.\n ...(fulfillment.request ? { fulfillment: fulfillment.request } : {}),\n // The visitor's advertising consent and the vendors' browser ids, only\n // where that consent grants advertising (AGL-3694); absent otherwise.\n ...advertisingConsentField(hostId),\n }),\n })\n const payload = await response.json().catch(() => ({}))\n // In-page payment (AGL-1944). Checked BEFORE the redirect branch: a\n // native session carries a client secret and no url, and if a server ever\n // sent both, navigating away would silently discard the form.\n //\n // `begin_checkout` is reported on BOTH paths, and from the same place, so\n // the GA4 funnel does not develop a hole the day the flag flips — a\n // storefront whose `begin_checkout` count halved would look like a\n // conversion collapse rather than a checkout that stopped redirecting.\n if (response.ok && payload?.clientSecret && payload?.publishableKey) {\n trackEvent(\n 'begin_checkout',\n buildBeginCheckoutParams({\n value: (cart?.subtotalCents ?? 0) / 100,\n items: cartAnalyticsItems(cart),\n }),\n )\n setNativeCheckout({\n clientSecret: String(payload.clientSecret),\n publishableKey: String(payload.publishableKey),\n ...(payload.stripeAccount\n ? { stripeAccount: String(payload.stripeAccount) }\n : {}),\n wallets: CommerceModel.readStorefrontCheckoutWallets(payload.wallets),\n })\n setStatus('idle')\n return\n }\n if (response.ok && payload?.url) {\n // GA4 checkout funnel (AGL-1561, converted by AGL-1591). This used to\n // call `window.gtag` raw with `value`/`currency` only, so the same\n // event name arrived from this surface and from the console's plan\n // checkout in two different shapes — and this half carried no `items`,\n // which is the field GA4's ecommerce funnel is actually built on.\n //\n // The item ids are the PRODUCT ids `view_item` and `add_to_cart`\n // already send, so the three now join into one per-product funnel.\n // `value` is stated rather than derived because the cart subtotal is\n // authoritative after a coupon or gift card, which the line prices\n // below are not. No `billing_interval`: a storefront cart is not a\n // subscription.\n //\n // AWAITED before the redirect (AGL-1580). This surface registers no\n // transport, so delivery is a synchronous `window.gtag` call and the\n // await resolves immediately — a storefront checkout is not slowed by\n // one microtask. It is written this way anyway because the property\n // that makes it safe is invisible from here: the day this bundle grows\n // an async transport, or a host registers one for it, the bare call\n // would start losing the event on exactly the branch that navigates,\n // and nothing at this call site would look different.\n await trackEventBeforeNavigation(\n 'begin_checkout',\n buildBeginCheckoutParams({\n value: (cart?.subtotalCents ?? 0) / 100,\n items: cartAnalyticsItems(cart),\n }),\n )\n window.location.assign(payload.url)\n return\n }\n // A read-only lockdown answers 423 with the visitor pause copy\n // (AGL-1511). Rendering `payload.error` here would print the wire\n // token \"locked\" at a shopper, and the `severity=\"error\"` styling\n // would tell them their payment failed — the one thing this copy\n // exists to never say. So the refusal is parsed and shown as a calm\n // notice instead.\n const paused = Aglyn.parseLockdownRefusal(response.status, payload)\n if (paused) {\n setMessage(Aglyn.lockdownRefusalText(paused))\n setStatus('paused')\n return\n }\n // A store that never had payments configured (AGL-2019). The server's\n // own words are NOT rendered here even though they are safe today:\n // this is a visitor-facing surface, the 501 bodies differ between the\n // cart and buy-now doors, and one of them could grow a variable name\n // without anyone thinking about who reads it.\n // An offer the shopper ticked changed or went away (AGL-3635): show\n // what is offered now and let them decide again.\n if (payload?.extrasChanged) {\n extras.reload()\n setMessage(String(payload?.error ?? ''))\n setStatus('error')\n return\n }\n // Card reader hardware needs the terms of sale ticked (AGL-4038): show\n // the boxes with the server's sentence.\n if (payload?.needsHardwareTerms) {\n setHardwareTermsAsked(true)\n setMessage(String(payload?.error ?? ''))\n setStatus('ask')\n return\n }\n // The pickup location or delivery time went away while the cart was\n // open (AGL-3624): ask again and let the shopper choose.\n if (payload?.fulfillmentChanged) {\n fulfillment.reload()\n setMessage(String(payload?.error ?? ''))\n setStatus('error')\n return\n }\n if (isPaymentsNotConfigured(response.status)) {\n setMessage(storefrontPaymentsNotConfiguredText())\n setStatus('unconfigured')\n return\n }\n // The merchant's rates differ by destination, so the server will not\n // price this cart until it knows one (AGL-1721). Reveal the field and\n // let the shopper answer; a store that never sends this never shows it.\n if (payload?.needsShippingCountry) {\n if (payload?.needsShippingPostalCode) setAskPostal(true)\n setShipCountries(\n (payload.shippingCountries as string[] | undefined)?.length\n ? (payload.shippingCountries as string[])\n : [...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES],\n )\n setMessage(String(payload?.error ?? ''))\n setMessageForShipping(true)\n // An unserved destination is a real refusal and reads as one; being\n // asked the first time is not.\n setStatus(shipTo ? 'error' : 'ask')\n return\n }\n setMessage(String(payload?.error ?? ''))\n setStatus('error')\n } catch {\n setStatus('error')\n }\n // `cart` is a dependency because the payload above reads it: without it\n // the handler closes over whichever cart was current when it was created,\n // and a checkout started after a quantity change would report the OLD\n // subtotal and the OLD lines. The pre-AGL-1591 raw call had the same bug\n // in the `value` alone, where a wrong number is indistinguishable from a\n // right one.\n }, [hostId, cart, coupon, email, optIn, giftCard, creditCode, shipTo, shipPostal, status, siteFetch, extras.chosenIds, extras.reload, extras.credits.length, fulfillment.request, fulfillment.reload, hardwareTerms, hardwareTermsAsked])\n\n if (!cart && load === 'loading') {\n return (\n <Box\n role=\"status\"\n aria-busy=\"true\"\n sx={{ display: 'flex', alignItems: 'center', gap: 1.5, p: 2 }}\n >\n <CircularProgress size={18} />\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Loading your cart…'}\n </Typography>\n </Box>\n )\n }\n if (!cart && load === 'failed') {\n return (\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ p: 2 }}>\n {'Your cart could not be loaded. Refresh the page to try again.'}\n </Typography>\n )\n }\n if (!cart || cart.lines.length === 0) {\n return (\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ p: 2 }}>\n {emptyText || 'Your cart is empty.'}\n </Typography>\n )\n }\n return (\n <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, p: 2 }}>\n {cart.lines.map((line) => {\n // AGL-1726: resolve BEFORE the guard, never inside the `src`. A\n // stored value can be truthy and still resolve to nothing (a\n // malformed `media:` reference), and testing the raw string would\n // turn \"no image\" into an `<img>` with no `src` — a broken-image\n // icon where the placeholder belongs.\n const imageUrl = Aglyn.siteRelativeMediaSrc(line.imageUrl, { hostId })\n return (\n <Box\n key={lineKey(line)}\n sx={{ display: 'flex', gap: 1.5, alignItems: 'center' }}\n >\n {imageUrl ? (\n <Box\n component=\"img\"\n src={imageUrl}\n alt=\"\"\n sx={{\n width: 48,\n height: 48,\n objectFit: 'cover',\n borderRadius: 1,\n }}\n // Deferred (AGL-2486). A 48px cart-line thumbnail is the\n // clearest case of the set: it can never be the LCP, and a\n // cart is usually below the fold or inside a panel.\n {...Aglyn.DEFERRED_IMAGE_ATTRIBUTES}\n />\n ) : (\n <Box\n sx={{\n width: 48,\n height: 48,\n bgcolor: 'action.hover',\n borderRadius: 1,\n }}\n />\n )}\n <Box sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {line.name}\n {line.variantLabel ? ` — ${line.variantLabel}` : ''}\n </Typography>\n {line.useDayKey ? (\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\">\n {`For ${checkInDayLabel(line.useDayKey)}`}\n </Typography>\n ) : null}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {line.unavailable\n ? (line.problem ?? 'No longer available')\n : usd(line.unitAmountCents)}\n </Typography>\n </Box>\n <TextField\n value={quantityDrafts[lineKey(line)] ?? line.quantity}\n onChange={(event) =>\n setQuantityDrafts((drafts) => ({\n ...drafts,\n [lineKey(line)]: event.target.value,\n }))\n }\n onBlur={() => commitQuantity(line)}\n onKeyDown={(event) => {\n if (event.key === 'Enter') commitQuantity(line)\n }}\n size=\"small\"\n // Four digits fit (AGL-4205): a line goes up to 9,999.\n sx={{ width: (theme) => theme.spacing(10) }}\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n <Button\n size=\"small\"\n color=\"error\"\n onClick={() =>\n void onMutate({\n action: 'remove',\n productId: line.productId,\n variantId: line.variantId,\n ...(line.useDayKey ? { useDayKey: line.useDayKey } : {}),\n ...(line.modifiers?.length ? { modifiers: line.modifiers } : {}),\n })\n }\n >\n {'✕'}\n </Button>\n </Box>\n )\n })}\n <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>\n <Typography variant=\"subtitle2\">{'Subtotal'}</Typography>\n <Typography variant=\"subtitle2\">{usd(cart.subtotalCents)}</Typography>\n </Box>\n <CartExtras\n offers={extras.offers}\n chosen={extras.chosen}\n onToggle={extras.toggle}\n formatCents={usd}\n />\n <CartFulfillmentChoice state={fulfillment} formatCents={usd} />\n <Typography variant=\"caption\" color=\"text.secondary\">\n {fulfillment.method === 'shipping'\n ? 'Shipping and taxes are calculated at checkout.'\n : 'Taxes are calculated at checkout.'}\n </Typography>\n <TextField\n label=\"Email\"\n type=\"email\"\n value={email}\n onChange={(event) => setEmail(event.target.value)}\n size=\"small\"\n helperText=\"For your receipt and order updates\"\n />\n <FormControlLabel\n control={\n <Checkbox\n size=\"small\"\n checked={optIn}\n onChange={(event) => setOptIn(event.target.checked)}\n />\n }\n label={\n <Typography variant=\"caption\">\n {'Email me news and offers'}\n </Typography>\n }\n />\n {showCoupon ? (\n <>\n <TextField\n label=\"Coupon code\"\n value={coupon}\n onChange={(event) => setCoupon(event.target.value)}\n size=\"small\"\n />\n <TextField\n label=\"Gift card\"\n value={giftCard}\n onChange={(event) => setGiftCard(event.target.value)}\n size=\"small\"\n placeholder=\"GC-…\"\n />\n </>\n ) : null}\n {extras.credits.length ? (\n // Drawn wherever the store takes a code, coupon field or not: a\n // member was emailed theirs and comes here to spend it (AGL-3640).\n <TextField\n label={`${extras.credits[0].label} code`}\n value={creditCode}\n onChange={(event) => setCreditCode(event.target.value)}\n size=\"small\"\n slotProps={{ htmlInput: { 'data-testid': 'cart-credit-code' } }}\n />\n ) : null}\n {askedCountries && fulfillment.method === 'shipping' ? (\n <TextField\n select\n required\n label=\"Ship to\"\n value={shipTo}\n onChange={(event) => {\n setShipTo(event.target.value)\n answerShipping()\n }}\n size=\"small\"\n helperText=\"Shipping rates depend on where this is going\"\n >\n {askedCountries.map((code) => (\n <MenuItem key={code} value={code}>\n {CommerceModel.CHECKOUT_SHIPPING_COUNTRY_NAMES[code] ?? code}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n {askPostal && fulfillment.method === 'shipping' ? (\n <TextField\n label=\"Postal code\"\n value={shipPostal}\n onChange={(event) => {\n setShipPostal(event.target.value)\n answerShipping()\n }}\n size=\"small\"\n helperText=\"Carrier rates depend on the postal code\"\n slotProps={{ htmlInput: { autoComplete: 'shipping postal-code', maxLength: 12 } }}\n />\n ) : null}\n {cart.hardwareTerms || hardwareTermsAsked ? (\n <HardwareTermsConsent answer={hardwareTerms} onChange={setHardwareTerms} />\n ) : null}\n {status === 'paused' || status === 'ask' || status === 'unconfigured' ? (\n <Alert severity=\"info\">{message}</Alert>\n ) : null}\n {status === 'error' ? (\n <Alert severity=\"error\">\n {message || 'Checkout is unavailable right now.'}\n </Alert>\n ) : null}\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={\n status === 'sending' ||\n cart.lines.every((line) => line.unavailable) ||\n // No payments on this deployment: every further click gets the same\n // 501, so the control latches off rather than inviting a retry that\n // cannot succeed (AGL-2019).\n status === 'unconfigured' ||\n // Asked but unanswered: the server would only refuse again.\n (fulfillment.method === 'shipping' && askedCountries !== null && !shipTo) ||\n (fulfillment.method === 'shipping' && askPostal && !shipPostal.trim()) ||\n // Pickup needs a location, delivery a zone and a time (AGL-3624).\n !fulfillment.ready ||\n // Card reader hardware: both boxes ticked (AGL-4038).\n ((Boolean(cart.hardwareTerms) || hardwareTermsAsked) && !hardwareTermsAnswered(hardwareTerms))\n }\n onClick={handleCheckout}\n >\n {status === 'sending'\n ? // \"Redirecting\" stops being true the moment the form opens in\n // place (AGL-1944).\n nativeCheckout\n ? 'Opening…'\n : 'Redirecting…'\n : checkoutLabel || 'Checkout'}\n </Button>\n {nativeCheckout ? (\n <Suspense fallback={<StorefrontPaymentElementFallback />}>\n <StorefrontPaymentElement\n clientSecret={nativeCheckout.clientSecret}\n publishableKey={nativeCheckout.publishableKey}\n stripeAccount={nativeCheckout.stripeAccount}\n wallets={nativeCheckout.wallets}\n payLabel={checkoutLabel || 'Pay now'}\n defaultEmail={email}\n // An expired or unloadable session is replaced, never replayed:\n // the old attempt key would hand back the dead session.\n onRestart={() => {\n attemptKey.current = ''\n setNativeCheckout(null)\n void handleCheckout()\n }}\n // The session is left open on cancel, deliberately: it is what the\n // AGL-323 abandoned-cart recovery emails are built on, and expiring\n // it would be a write against the merchant's Stripe account made\n // from a browser.\n onCancel={() => setNativeCheckout(null)}\n />\n </Suspense>\n ) : null}\n </Box>\n )\n}\n\n/**\n * Cart block (AGL-293): 'button' renders a badge icon + slide-out\n * drawer for app bars; 'inline' renders the full cart for a cart page.\n * Lines live server-side (cookie cart); every mutation re-resolves\n * prices. Other blocks broadcast CART_UPDATED_EVENT to refresh badges.\n */\nconst Cart = forwardRef<HTMLDivElement, CartProps>((props, ref) => {\n const { variant, checkoutLabel, showCoupon, emptyText, ...rest } = props\n // Node styles ride the renderer-merged sx; recompose (stack.ts pattern).\n const nodeSx = Array.isArray(props['sx']) ? props['sx'] : [props['sx']]\n const { hostId } = Aglyn.useSite()\n const siteFetch = Aglyn.useSiteFetch()\n const [cart, setCart] = useState<CartView | null>(null)\n const [load, setLoad] = useState<CartLoad>('loading')\n const [open, setOpen] = useState(false)\n\n // Closes the merchant's ecommerce funnel (AGL-1641). Stripe returns a cart\n // checkout to the page it started on — this one — so the `purchase` that\n // `begin_checkout` above has never had a counterpart to is reported here.\n // No-ops on every ordinary render: the hook returns immediately unless the\n // URL carries `?order=success&session_id=…`.\n useStorefrontPurchaseEvent(hostId, siteFetch)\n\n const refresh = useCallback(async () => {\n if (!hostId) return\n try {\n const response = await fetch(cartReadUrl(hostId))\n if (response.ok) {\n setCart(await response.json())\n setLoad('loaded')\n } else {\n setLoad((current) => (current === 'loaded' ? current : 'failed'))\n }\n } catch {\n // Badge silently stays stale offline; a cart never read says so.\n setLoad((current) => (current === 'loaded' ? current : 'failed'))\n }\n }, [hostId])\n\n useEffect(() => {\n void refresh()\n const handler = () => void refresh()\n window.addEventListener(CART_UPDATED_EVENT, handler)\n return () => window.removeEventListener(CART_UPDATED_EVENT, handler)\n }, [refresh])\n\n /**\n * Has THIS opening of the cart already been reported? A drawer that is\n * closed and reopened is a second view; a re-render, a badge refresh or a\n * quantity edit inside an already-open drawer is not.\n */\n const viewReported = useRef(false)\n\n /**\n * `view_cart` — the funnel step between `add_to_cart` and `begin_checkout`.\n *\n * Fired on the cart being SEEN, which is why it hangs off `open` rather off\n * mount: the button variant renders a badge on every page of a storefront,\n * and reporting a view there would have made \"opened the cart\" a synonym for\n * \"loaded a page\" and the checkout rate a fraction of pageviews.\n *\n * Deferred until the lines have actually arrived. The cart is fetched, so a\n * drawer opened while that request is in flight has nothing to describe yet\n * — reporting then would send an empty `items` and a zero `value` for a cart\n * that in fact had both. An empty cart never reports at all: there is no\n * view of nothing, and counting it would put every idle badge click into the\n * denominator of the checkout rate.\n */\n useEffect(() => {\n const onScreen = variant === 'inline' || open\n if (!onScreen) {\n viewReported.current = false\n return\n }\n if (viewReported.current || !cart || cart.lines.length === 0) return\n viewReported.current = true\n trackEvent(\n 'view_cart',\n buildViewCartParams({\n // The server's subtotal, so this and the `begin_checkout` the same\n // cart sends describe one cart at one size.\n value: cart.subtotalCents / 100,\n items: cartAnalyticsItems(cart),\n }),\n )\n }, [variant, open, cart])\n\n const mutate = useCallback(\n async (body: Record<string, unknown>) => {\n if (!hostId) return\n const response = await siteFetch('/api/commerce/cart', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, ...body }),\n })\n if (response.ok) {\n setCart(await response.json())\n window.dispatchEvent(new Event(CART_UPDATED_EVENT))\n }\n },\n [hostId, siteFetch],\n )\n\n if (!hostId) {\n return (\n <Box\n ref={ref}\n {...rest}\n sx={[\n {\n p: variant === 'inline' ? 3 : 1,\n border: '1px dashed',\n borderColor: 'divider',\n borderRadius: 1,\n color: 'text.secondary',\n fontSize: 13,\n fontFamily: 'system-ui, sans-serif',\n display: 'inline-block',\n },\n ...nodeSx,\n ]}\n >\n {variant === 'inline' ? 'Cart — lines render here' : '🛒 Cart'}\n </Box>\n )\n }\n\n if (variant === 'inline') {\n return (\n <Box ref={ref} {...rest}>\n <CartReadPreload hostId={hostId} />\n <CheckoutReturnNotice hostId={hostId} siteFetch={siteFetch} />\n <CartLines\n hostId={hostId}\n cart={cart}\n load={load}\n showCoupon={showCoupon}\n checkoutLabel={checkoutLabel}\n emptyText={emptyText}\n onMutate={mutate}\n />\n </Box>\n )\n }\n\n return (\n <Box ref={ref} {...rest} sx={[{ display: 'inline-flex' }, ...nodeSx]}>\n <CheckoutReturnNotice hostId={hostId} siteFetch={siteFetch} />\n {/* Inherits the color around it, as the header's other icons do:\n the default gray vanished on a dark photo and ignored a header's\n own color (AGL-4200). */}\n <IconButton aria-label=\"Cart\" color=\"inherit\" onClick={() => setOpen(true)}>\n <Badge badgeContent={cart?.count ?? 0} color=\"primary\">\n <SvgIcon>\n <path d={mdiCartOutline.path} />\n </SvgIcon>\n </Badge>\n </IconButton>\n <Drawer anchor=\"right\" open={open} onClose={() => setOpen(false)}>\n <Box sx={{ width: { xs: '85vw', sm: 380 } }}>\n <Typography variant=\"h6\" sx={{ p: 2, pb: 0 }}>\n {'Your cart'}\n </Typography>\n <CartLines\n hostId={hostId}\n cart={cart}\n load={load}\n showCoupon={showCoupon}\n checkoutLabel={checkoutLabel}\n emptyText={emptyText}\n onMutate={mutate}\n />\n </Box>\n </Drawer>\n </Box>\n )\n})\nCart.displayName = 'AglynCart'\n\nexport const schema: Aglyn.ComponentSchema<CartProps> = {\n $id: ID,\n pluginId: BUNDLE_ID,\n displayName: 'Cart',\n description:\n 'The shopping cart — a badge icon with a slide-out drawer, or the full cart page.',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiCartOutline.path, sx: { color: '#2e7d32' } },\n flags: { selfClosing: Aglyn.FEATURE_FLAG.ENABLED },\n attributes: [\n {\n name: 'variant',\n label: 'Style',\n description: 'Icon-with-drawer for app bars, or the full inline cart.',\n component: Aglyn.FieldComponentType.SELECT,\n options: [\n { value: 'button', label: 'Icon + drawer' },\n { value: 'inline', label: 'Inline (cart page)' },\n ],\n },\n {\n name: 'checkoutLabel',\n label: 'Checkout label',\n description: 'Defaults to \"Checkout\".',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n },\n {\n // The PROP KEY stays `showCoupon` — it is persisted in every saved page\n // that uses this component, and renaming it would blank the control on\n // all of them. Only what the merchant reads changes.\n name: 'showCoupon',\n // ONE CONTROL, TWO FEATURES, AND IT ONLY NAMED ONE. This checkbox gates\n // the gift-card field as well as the coupon field, so a merchant who\n // wanted gift cards had no reason to look here — gift cards are only\n // redeemable in the cart, and this is the switch that shows the box.\n // A control named for one feature that also gates another is how a\n // shipped feature stays invisible.\n label: 'Show coupon and gift card fields',\n description:\n 'One checkbox for both. Coupon codes and gift cards are managed on ' +\n 'the Products page.',\n component: Aglyn.FieldComponentType.CHECKBOX,\n },\n {\n name: 'emptyText',\n label: 'Empty text',\n description: 'Copy when the cart is empty.',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n },\n ],\n}\n\nexport const presets: Aglyn.PresetSchema[] = [\n {\n $id: generatePresetId(ID, 'button'),\n type: Aglyn.NodeType.PRESET,\n displayName: 'Cart button',\n pluginId: BUNDLE_ID,\n description: 'Badge icon with a slide-out cart drawer',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiCartOutline.path, sx: { color: '#2e7d32' } },\n data: {\n $id: null,\n componentId: ID,\n pluginId: BUNDLE_ID,\n props: { variant: 'button' },\n },\n },\n {\n $id: generatePresetId(ID, 'inline'),\n type: Aglyn.NodeType.PRESET,\n displayName: 'Cart page',\n pluginId: BUNDLE_ID,\n description:\n 'Full cart with quantities, coupon, gift card, and checkout',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiCartOutline.path, sx: { color: '#2e7d32' } },\n data: {\n $id: null,\n componentId: ID,\n pluginId: BUNDLE_ID,\n props: { variant: 'inline', showCoupon: true },\n },\n },\n]\n\nexport default Cart\n"],"names":["advertisingConsentField","Aglyn","buildBeginCheckoutParams","buildViewCartParams","trackEvent","trackEventBeforeNavigation","isPaymentsNotConfigured","storefrontPaymentsNotConfiguredText","CommerceModel","checkInDayLabel","mdiCartOutline","Alert","Badge","Box","Button","Checkbox","CircularProgress","Drawer","FormControlLabel","IconButton","MenuItem","SvgIcon","TextField","Typography","Suspense","forwardRef","lazy","useCallback","useEffect","useMemo","useRef","useState","StorefrontPaymentElementFallback","CheckoutReturnNotice","CartExtras","useCartExtras","CartFulfillmentChoice","useCartFulfillment","HardwareTermsConsent","hardwareTermsAnswered","NO_HARDWARE_TERMS_ANSWER","StorefrontPaymentElement","then","module","default","BUNDLE_ID","CART_UPDATED_EVENT","generatePresetId","useStorefrontPurchaseEvent","ID","usd","cents","toFixed","cartReadUrl","hostId","encodeURIComponent","CartReadPreload","link","rel","as","href","crossOrigin","cartAnalyticsItems","cart","lines","map","line","item_id","productId","item_name","name","price","unitAmountCents","quantity","CartLines","props","load","showCoupon","checkoutLabel","emptyText","onMutate","siteFetch","useSiteFetch","coupon","setCoupon","email","setEmail","optIn","setOptIn","giftCard","setGiftCard","creditCode","setCreditCode","shipTo","setShipTo","shipCountries","setShipCountries","askedCountries","needsShippingCountry","shippingCountries","length","CHECKOUT_SHIPPING_COUNTRIES","shipPostal","setShipPostal","askPostal","setAskPostal","status","setStatus","message","setMessage","messageForShipping","setMessageForShipping","answerShipping","hardwareTerms","setHardwareTerms","hardwareTermsAsked","setHardwareTermsAsked","nativeCheckout","setNativeCheckout","quantityDrafts","setQuantityDrafts","lineKey","cartLineKey","commitQuantity","key","draft","undefined","settle","drafts","_settled","rest","trim","parsed","Math","round","Number","isFinite","max","action","variantId","useDayKey","modifiers","finally","attemptKey","cartSignature","JSON","stringify","modifierSelectionKey","extras","extrasSignature","chosenIds","join","fulfillment","current","signature","handleCheckout","globalThis","crypto","randomUUID","Date","now","random","toString","slice","response","method","headers","body","marketingOptIn","couponCode","giftCardCode","credits","request","shippingCountry","shippingPostalCode","payload","json","catch","ok","clientSecret","publishableKey","value","subtotalCents","items","String","stripeAccount","wallets","readStorefrontCheckoutWallets","url","window","location","assign","paused","parseLockdownRefusal","lockdownRefusalText","extrasChanged","reload","error","needsHardwareTerms","fulfillmentChanged","needsShippingPostalCode","role","aria-busy","sx","display","alignItems","gap","p","size","variant","color","flexDirection","imageUrl","siteRelativeMediaSrc","component","src","alt","width","height","objectFit","borderRadius","DEFERRED_IMAGE_ATTRIBUTES","bgcolor","flex","minWidth","noWrap","variantLabel","unavailable","problem","onChange","event","target","onBlur","onKeyDown","theme","spacing","slotProps","htmlInput","inputMode","onClick","justifyContent","offers","chosen","onToggle","toggle","formatCents","state","label","type","helperText","control","checked","placeholder","select","required","code","CHECKOUT_SHIPPING_COUNTRY_NAMES","autoComplete","maxLength","answer","severity","disabled","every","ready","Boolean","fallback","payLabel","defaultEmail","onRestart","onCancel","Cart","ref","nodeSx","Array","isArray","useSite","setCart","setLoad","open","setOpen","refresh","fetch","handler","addEventListener","removeEventListener","viewReported","onScreen","mutate","dispatchEvent","Event","border","borderColor","fontSize","fontFamily","aria-label","badgeContent","count","path","d","anchor","onClose","xs","sm","pb","displayName","schema","$id","pluginId","description","category","ComponentCategory","COMMERCE","icon","flags","selfClosing","FEATURE_FLAG","ENABLED","attributes","FieldComponentType","SELECT","options","TEXT_FIELD","CHECKBOX","presets","NodeType","PRESET","data","componentId"],"mappings":";;;;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,uBAAuB,QAAQ,6CAA4C;AACpF,YAAYC,WAAW,eAAc;AACrC,SACEC,wBAAwB,EACxBC,mBAAmB,EACnBC,UAAU,EACVC,0BAA0B,QAErB,0CAAyC;AAChD,SAASC,uBAAuB,QAAQ,6CAA4C;AACpF,SAASC,mCAAmC,QAAQ,sCAAkC;AACtF,YAAYC,mBAAmB,oBAAU;AACzC,0EAA0E;AAC1E,0EAA0E;AAC1E,iFAAiF;AACjF,SAASC,eAAe,QAAQ,wCAAoC;AACpE,SAASC,cAAc,QAAQ,yBAAwB;AACvD,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,SAAS,oBAAmB;AACnC,OAAOC,YAAY,uBAAsB;AACzC,OAAOC,cAAc,yBAAwB;AAC7C,OAAOC,sBAAsB,iCAAgC;AAC7D,OAAOC,YAAY,uBAAsB;AACzC,OAAOC,sBAAsB,iCAAgC;AAC7D,OAAOC,gBAAgB,2BAA0B;AACjD,OAAOC,cAAc,yBAAwB;AAC7C,OAAOC,aAAa,wBAAuB;AAC3C,OAAOC,eAAe,0BAAyB;AAC/C,OAAOC,gBAAgB,2BAA0B;AACjD,SACEC,QAAQ,EACRC,UAAU,EACVC,IAAI,EACJC,WAAW,EACXC,SAAS,EACTC,OAAO,EACPC,MAAM,EACNC,QAAQ,QACH,QAAO;AACd,SAASC,gCAAgC,QAAQ,2CAAuC;AACxF,SAASC,oBAAoB,QAAQ,8BAA0B;AAC/D,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C1BuM,MAAMvP,MAAMmU,QAAQ,CAACC,MAAM;QAC3BrB,aAAa;QACbG,UAAUtQ;QACVuQ,aAAa;QACbC,UAAUpT,MAAMqT,iBAAiB,CAACC,QAAQ;QAC1CC,MAAM;YAAEf,MAAM/R,eAAe+R,IAAI;YAAE9F,IAAI;gBAAEO,OAAO;YAAU;QAAE;QAC5DoH,MAAM;YACJpB,KAAK;YACLqB,aAAatR;YACbkQ,UAAUtQ;YACV8B,OAAO;gBAAEsI,SAAS;YAAS;QAC7B;IACF;IACA;QACEiG,KAAKnQ,iBAAiBE,IAAI;QAC1BuM,MAAMvP,MAAMmU,QAAQ,CAACC,MAAM;QAC3BrB,aAAa;QACbG,UAAUtQ;QACVuQ,aACE;QACFC,UAAUpT,MAAMqT,iBAAiB,CAACC,QAAQ;QAC1CC,MAAM;YAAEf,MAAM/R,eAAe+R,IAAI;YAAE9F,IAAI;gBAAEO,OAAO;YAAU;QAAE;QAC5DoH,MAAM;YACJpB,KAAK;YACLqB,aAAatR;YACbkQ,UAAUtQ;YACV8B,OAAO;gBAAEsI,SAAS;gBAAUpI,YAAY;YAAK;QAC/C;IACF;CACD,CAAA;AAED,eAAeiM,KAAI"}
|
|
@@ -30,6 +30,8 @@ import { ceilingedWindow, collectionCeiling, useFirestoreCollection, writeGuarde
|
|
|
30
30
|
import { ListPagination } from "@aglyn/shared-ui-jsx/components/list-pagination.component";
|
|
31
31
|
import { TABLE_PAGE_SIZE_DEFAULT } from "@aglyn/shared-ui-jsx/const/table-pagination";
|
|
32
32
|
import { pluginDocsHelp } from "@aglyn/aglyn";
|
|
33
|
+
import { isSeedChecking, seedCheckingText, useHeldSave } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
|
|
34
|
+
import { useSeedDraft } from "@aglyn/tenant-feature-instance/hooks/use-seed-draft";
|
|
33
35
|
import { authorizedFetch } from "@aglyn/shared-util-http/authorized-token";
|
|
34
36
|
import TransferHeaderActions from "../../transfer/transfer-header-actions.component.js";
|
|
35
37
|
import { COMMERCE_CATEGORIES_TRANSFER } from "../../transfer/transfer-keys.js";
|
|
@@ -121,6 +123,35 @@ const sameProduct = (option, value)=>option.$id === value.$id;
|
|
|
121
123
|
}))
|
|
122
124
|
});
|
|
123
125
|
});
|
|
126
|
+
/** A stored category as its editor holds it. */ function categoryDraftOf(category) {
|
|
127
|
+
var _category_parentId;
|
|
128
|
+
return {
|
|
129
|
+
id: category.$id,
|
|
130
|
+
name: category.name,
|
|
131
|
+
parentId: (_category_parentId = category.parentId) != null ? _category_parentId : ''
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
/** A stored catalog collection as its editor holds it. */ function collectionDraftOf(row) {
|
|
135
|
+
var _row_slug, _row_mode, _row_productIds, _row_rules;
|
|
136
|
+
return {
|
|
137
|
+
id: row.$id,
|
|
138
|
+
name: row.name,
|
|
139
|
+
slug: (_row_slug = row.slug) != null ? _row_slug : '',
|
|
140
|
+
mode: (_row_mode = row.mode) != null ? _row_mode : 'manual',
|
|
141
|
+
productIds: (_row_productIds = row.productIds) != null ? _row_productIds : [],
|
|
142
|
+
rules: (_row_rules = row.rules) != null ? _row_rules : [],
|
|
143
|
+
matchAll: row.matchAll !== false
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/** Says why a held control is off, while the server has not answered. */ function CheckingNote(props) {
|
|
147
|
+
return props.text ? /*#__PURE__*/ _jsx(Typography, {
|
|
148
|
+
variant: "body2",
|
|
149
|
+
color: "text.secondary",
|
|
150
|
+
role: "status",
|
|
151
|
+
sx: props.sx,
|
|
152
|
+
children: props.text
|
|
153
|
+
}) : null;
|
|
154
|
+
}
|
|
124
155
|
/**
|
|
125
156
|
* A text field that redraws only when what it shows changes (AGL-3423).
|
|
126
157
|
*
|
|
@@ -137,6 +168,9 @@ const sameProduct = (option, value)=>option.$id === value.$id;
|
|
|
137
168
|
const FIRST_FIELD = {
|
|
138
169
|
mt: 1
|
|
139
170
|
};
|
|
171
|
+
const HELD_NOTE = {
|
|
172
|
+
mr: 'auto'
|
|
173
|
+
};
|
|
140
174
|
const RULE_FIELD = {
|
|
141
175
|
width: 130
|
|
142
176
|
};
|
|
@@ -165,13 +199,16 @@ const RULE_OP_MENU = RULE_OPS.map((op)=>/*#__PURE__*/ _jsx(MenuItem, {
|
|
|
165
199
|
children: op.label
|
|
166
200
|
}, op.value));
|
|
167
201
|
/** The category tree, a page at a time, and the button that adds one. */ const CategoriesSection = /*#__PURE__*/ memo(function CategoriesSection(props) {
|
|
168
|
-
const { categories, visible, onEdit, onDelete } = props;
|
|
202
|
+
const { categories, visible, onEdit, onDelete, deleteCheckingText } = props;
|
|
169
203
|
return /*#__PURE__*/ _jsxs(_Fragment, {
|
|
170
204
|
children: [
|
|
171
205
|
/*#__PURE__*/ _jsx(Typography, {
|
|
172
206
|
variant: "subtitle2",
|
|
173
207
|
children: 'Categories'
|
|
174
208
|
}),
|
|
209
|
+
categories.length === 0 ? null : /*#__PURE__*/ _jsx(CheckingNote, {
|
|
210
|
+
text: deleteCheckingText
|
|
211
|
+
}),
|
|
175
212
|
categories.length === 0 ? /*#__PURE__*/ _jsx(Typography, {
|
|
176
213
|
variant: "body2",
|
|
177
214
|
color: "text.secondary",
|
|
@@ -202,19 +239,13 @@ const RULE_OP_MENU = RULE_OPS.map((op)=>/*#__PURE__*/ _jsx(MenuItem, {
|
|
|
202
239
|
}),
|
|
203
240
|
/*#__PURE__*/ _jsx(Button, {
|
|
204
241
|
size: "small",
|
|
205
|
-
onClick: ()=>
|
|
206
|
-
var _category_parentId;
|
|
207
|
-
return onEdit({
|
|
208
|
-
id: category.$id,
|
|
209
|
-
name: category.name,
|
|
210
|
-
parentId: (_category_parentId = category.parentId) != null ? _category_parentId : ''
|
|
211
|
-
});
|
|
212
|
-
},
|
|
242
|
+
onClick: ()=>onEdit(categoryDraftOf(category)),
|
|
213
243
|
children: 'Edit'
|
|
214
244
|
}),
|
|
215
245
|
/*#__PURE__*/ _jsx(Button, {
|
|
216
246
|
size: "small",
|
|
217
247
|
color: "error",
|
|
248
|
+
disabled: Boolean(deleteCheckingText),
|
|
218
249
|
onClick: onDelete(category),
|
|
219
250
|
children: 'Delete'
|
|
220
251
|
})
|
|
@@ -292,18 +323,7 @@ const RULE_OP_MENU = RULE_OPS.map((op)=>/*#__PURE__*/ _jsx(MenuItem, {
|
|
|
292
323
|
}),
|
|
293
324
|
/*#__PURE__*/ _jsx(Button, {
|
|
294
325
|
size: "small",
|
|
295
|
-
onClick: ()=>
|
|
296
|
-
var _row_slug, _row_mode, _row_productIds, _row_rules;
|
|
297
|
-
return onEdit({
|
|
298
|
-
id: row.$id,
|
|
299
|
-
name: row.name,
|
|
300
|
-
slug: (_row_slug = row.slug) != null ? _row_slug : '',
|
|
301
|
-
mode: (_row_mode = row.mode) != null ? _row_mode : 'manual',
|
|
302
|
-
productIds: (_row_productIds = row.productIds) != null ? _row_productIds : [],
|
|
303
|
-
rules: (_row_rules = row.rules) != null ? _row_rules : [],
|
|
304
|
-
matchAll: row.matchAll !== false
|
|
305
|
-
});
|
|
306
|
-
},
|
|
326
|
+
onClick: ()=>onEdit(collectionDraftOf(row)),
|
|
307
327
|
children: 'Edit'
|
|
308
328
|
}),
|
|
309
329
|
/*#__PURE__*/ _jsx(Button, {
|
|
@@ -351,7 +371,7 @@ const RULE_OP_MENU = RULE_OPS.map((op)=>/*#__PURE__*/ _jsx(MenuItem, {
|
|
|
351
371
|
});
|
|
352
372
|
/** The category editor: a name and a parent. */ const CategoryDialog = /*#__PURE__*/ memo(function CategoryDialog(props) {
|
|
353
373
|
var _ref, _ref1;
|
|
354
|
-
const { draft, categories, setDraft } = props;
|
|
374
|
+
const { draft, categories, setDraft, checkingText } = props;
|
|
355
375
|
const draftId = draft == null ? void 0 : draft.id;
|
|
356
376
|
const close = useCallback(()=>setDraft(null), [
|
|
357
377
|
setDraft
|
|
@@ -418,6 +438,10 @@ const RULE_OP_MENU = RULE_OPS.map((op)=>/*#__PURE__*/ _jsx(MenuItem, {
|
|
|
418
438
|
}),
|
|
419
439
|
/*#__PURE__*/ _jsxs(DialogActions, {
|
|
420
440
|
children: [
|
|
441
|
+
/*#__PURE__*/ _jsx(CheckingNote, {
|
|
442
|
+
text: checkingText,
|
|
443
|
+
sx: HELD_NOTE
|
|
444
|
+
}),
|
|
421
445
|
/*#__PURE__*/ _jsx(Button, {
|
|
422
446
|
onClick: close,
|
|
423
447
|
children: 'Cancel'
|
|
@@ -425,9 +449,9 @@ const RULE_OP_MENU = RULE_OPS.map((op)=>/*#__PURE__*/ _jsx(MenuItem, {
|
|
|
425
449
|
/*#__PURE__*/ _jsx(Button, {
|
|
426
450
|
variant: "contained",
|
|
427
451
|
color: "primary",
|
|
428
|
-
disabled: !(draft == null ? void 0 : draft.name.trim()),
|
|
452
|
+
disabled: props.saving || !(draft == null ? void 0 : draft.name.trim()),
|
|
429
453
|
onClick: props.onSave,
|
|
430
|
-
children: 'Save'
|
|
454
|
+
children: props.saving ? 'Saving…' : 'Save'
|
|
431
455
|
})
|
|
432
456
|
]
|
|
433
457
|
})
|
|
@@ -592,7 +616,7 @@ const CollectionRuleRow = /*#__PURE__*/ memo(function CollectionRuleRow(props) {
|
|
|
592
616
|
});
|
|
593
617
|
/** The collection editor: a name, a mode, and the products or rules it holds. */ const CollectionDialog = /*#__PURE__*/ memo(function CollectionDialog(props) {
|
|
594
618
|
var _ref, _ref1, _ref2;
|
|
595
|
-
const { draft, error, setDraft } = props;
|
|
619
|
+
const { draft, error, setDraft, checkingText } = props;
|
|
596
620
|
const close = useCallback(()=>setDraft(null), [
|
|
597
621
|
setDraft
|
|
598
622
|
]);
|
|
@@ -663,6 +687,10 @@ const CollectionRuleRow = /*#__PURE__*/ memo(function CollectionRuleRow(props) {
|
|
|
663
687
|
}),
|
|
664
688
|
/*#__PURE__*/ _jsxs(DialogActions, {
|
|
665
689
|
children: [
|
|
690
|
+
/*#__PURE__*/ _jsx(CheckingNote, {
|
|
691
|
+
text: checkingText,
|
|
692
|
+
sx: HELD_NOTE
|
|
693
|
+
}),
|
|
666
694
|
/*#__PURE__*/ _jsx(Button, {
|
|
667
695
|
onClick: close,
|
|
668
696
|
children: 'Cancel'
|
|
@@ -670,9 +698,9 @@ const CollectionRuleRow = /*#__PURE__*/ memo(function CollectionRuleRow(props) {
|
|
|
670
698
|
/*#__PURE__*/ _jsx(Button, {
|
|
671
699
|
variant: "contained",
|
|
672
700
|
color: "primary",
|
|
673
|
-
disabled: !(draft == null ? void 0 : draft.name.trim()) || Boolean(error),
|
|
701
|
+
disabled: props.saving || !(draft == null ? void 0 : draft.name.trim()) || Boolean(error),
|
|
674
702
|
onClick: props.onSave,
|
|
675
|
-
children: 'Save'
|
|
703
|
+
children: props.saving ? 'Saving…' : 'Save'
|
|
676
704
|
})
|
|
677
705
|
]
|
|
678
706
|
})
|
|
@@ -848,8 +876,28 @@ const CollectionRuleRow = /*#__PURE__*/ memo(function CollectionRuleRow(props) {
|
|
|
848
876
|
collectionPage,
|
|
849
877
|
collectionPageSize
|
|
850
878
|
]);
|
|
851
|
-
|
|
852
|
-
|
|
879
|
+
/*
|
|
880
|
+
* Each editor's draft, kept as EDITS over the row as the list has it now
|
|
881
|
+
* (AGL-4047): opened from the cache's row, the server's copy replaces it
|
|
882
|
+
* under every field nobody touched (a category's parent, a collection's
|
|
883
|
+
* membership), and Save is held until it has.
|
|
884
|
+
*/ const [categoryDraft, setCategoryDraft] = useSeedDraft((opened)=>{
|
|
885
|
+
const row = opened.id ? categoryDocs == null ? void 0 : categoryDocs.find((category)=>category.$id === opened.id) : undefined;
|
|
886
|
+
return row ? categoryDraftOf(row) : undefined;
|
|
887
|
+
});
|
|
888
|
+
const [collectionDraft, setCollectionDraft] = useSeedDraft((opened)=>{
|
|
889
|
+
const row = opened.id ? collectionDocs == null ? void 0 : collectionDocs.find((collection)=>collection.$id === opened.id) : undefined;
|
|
890
|
+
return row ? collectionDraftOf(row) : undefined;
|
|
891
|
+
});
|
|
892
|
+
const categoriesChecking = isSeedChecking({
|
|
893
|
+
fromCache: categoriesFromCache,
|
|
894
|
+
unreadable: categoriesStatus === 'error'
|
|
895
|
+
}) ? seedCheckingText('categories') : undefined;
|
|
896
|
+
const categoryChecking = (categoryDraft == null ? void 0 : categoryDraft.id) ? categoriesChecking && seedCheckingText('category') : undefined;
|
|
897
|
+
const collectionChecking = (collectionDraft == null ? void 0 : collectionDraft.id) && isSeedChecking({
|
|
898
|
+
fromCache: collectionsFromCache,
|
|
899
|
+
unreadable: collectionsStatus === 'error'
|
|
900
|
+
}) ? seedCheckingText('collection') : undefined;
|
|
853
901
|
const handleCategorySave = useCallback(async ()=>{
|
|
854
902
|
var _categoryDraft_id;
|
|
855
903
|
if (!(categoryDraft == null ? void 0 : categoryDraft.name.trim())) return;
|
|
@@ -1275,6 +1323,23 @@ const CollectionRuleRow = /*#__PURE__*/ memo(function CollectionRuleRow(props) {
|
|
|
1275
1323
|
rules
|
|
1276
1324
|
}));
|
|
1277
1325
|
}, []);
|
|
1326
|
+
// A press while Save is held is kept, and saves once confirmed (AGL-4047).
|
|
1327
|
+
const categoryHeld = useHeldSave(handleCategorySave, {
|
|
1328
|
+
checking: Boolean(categoryChecking),
|
|
1329
|
+
subject: 'category',
|
|
1330
|
+
onRefused: (message)=>enqueueSnackbar(message, {
|
|
1331
|
+
variant: 'warning',
|
|
1332
|
+
persist: false
|
|
1333
|
+
})
|
|
1334
|
+
});
|
|
1335
|
+
const collectionHeld = useHeldSave(handleCollectionSave, {
|
|
1336
|
+
checking: Boolean(collectionChecking),
|
|
1337
|
+
subject: 'collection',
|
|
1338
|
+
onRefused: (message)=>enqueueSnackbar(message, {
|
|
1339
|
+
variant: 'warning',
|
|
1340
|
+
persist: false
|
|
1341
|
+
})
|
|
1342
|
+
});
|
|
1278
1343
|
return /*#__PURE__*/ _jsxs(CardDisplay, {
|
|
1279
1344
|
header: 'Categories & collections',
|
|
1280
1345
|
HeaderProps: {
|
|
@@ -1302,7 +1367,8 @@ const CollectionRuleRow = /*#__PURE__*/ memo(function CollectionRuleRow(props) {
|
|
|
1302
1367
|
onPageChange: setCategoryPage,
|
|
1303
1368
|
onPageSizeChange: setCategoryPageSize,
|
|
1304
1369
|
onEdit: setCategoryDraft,
|
|
1305
|
-
onDelete: handleCategoryDelete
|
|
1370
|
+
onDelete: handleCategoryDelete,
|
|
1371
|
+
deleteCheckingText: categoriesChecking
|
|
1306
1372
|
}),
|
|
1307
1373
|
/*#__PURE__*/ _jsx(Divider, {
|
|
1308
1374
|
sx: {
|
|
@@ -1328,7 +1394,9 @@ const CollectionRuleRow = /*#__PURE__*/ memo(function CollectionRuleRow(props) {
|
|
|
1328
1394
|
draft: categoryDraft,
|
|
1329
1395
|
categories: categories,
|
|
1330
1396
|
setDraft: setCategoryDraft,
|
|
1331
|
-
onSave:
|
|
1397
|
+
onSave: categoryHeld.press,
|
|
1398
|
+
checkingText: categoryChecking,
|
|
1399
|
+
saving: categoryHeld.saving
|
|
1332
1400
|
}),
|
|
1333
1401
|
/*#__PURE__*/ _jsx(CollectionDialog, {
|
|
1334
1402
|
draft: collectionDraft,
|
|
@@ -1343,7 +1411,9 @@ const CollectionRuleRow = /*#__PURE__*/ memo(function CollectionRuleRow(props) {
|
|
|
1343
1411
|
setDraft: setCollectionDraft,
|
|
1344
1412
|
onProducts: setCollectionProducts,
|
|
1345
1413
|
onRule: updateRule,
|
|
1346
|
-
onSave:
|
|
1414
|
+
onSave: collectionHeld.press,
|
|
1415
|
+
checkingText: collectionChecking,
|
|
1416
|
+
saving: collectionHeld.saving
|
|
1347
1417
|
})
|
|
1348
1418
|
]
|
|
1349
1419
|
});
|