@aglyn/plugins-commerce 1.15.0 → 1.15.1
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 +13 -13
- package/src/lib/components/cart.js +8 -3
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/console/payments-settings-card.component.js +1 -1
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/subscription-detail-dialog.component.js +2 -2
- package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -1
- package/src/lib/components/console/subscriptions-card.component.js +4 -2
- package/src/lib/components/console/subscriptions-card.component.js.map +1 -1
- package/src/lib/components/product-detail.js +7 -3
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/quote-page-body.js +7 -3
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/components/related-products.js +6 -3
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/components/storefront-payment-element.d.ts +7 -1
- package/src/lib/components/storefront-payment-element.js +11 -7
- package/src/lib/components/storefront-payment-element.js.map +1 -1
- package/src/lib/model/commerce-payment-methods.d.ts +26 -39
- package/src/lib/model/commerce-payment-methods.js +11 -118
- package/src/lib/model/commerce-payment-methods.js.map +1 -1
- package/src/lib/server/billing-webhook.d.ts +23 -0
- package/src/lib/server/billing-webhook.js +162 -30
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cancel-order.js +4 -3
- package/src/lib/server/cancel-order.js.map +1 -1
- package/src/lib/server/cart-checkout.js +61 -14
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/catalog.js +58 -22
- package/src/lib/server/catalog.js.map +1 -1
- package/src/lib/server/checkout-session-expiry.d.ts +1 -1
- package/src/lib/server/checkout-session-expiry.js +19 -5
- package/src/lib/server/checkout-session-expiry.js.map +1 -1
- package/src/lib/server/checkout-status.js +4 -3
- package/src/lib/server/checkout-status.js.map +1 -1
- package/src/lib/server/checkout.js +42 -12
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/connect.js +42 -11
- package/src/lib/server/connect.js.map +1 -1
- package/src/lib/server/draft-order.js +37 -12
- package/src/lib/server/draft-order.js.map +1 -1
- package/src/lib/server/manual-tax-rate.d.ts +11 -3
- package/src/lib/server/manual-tax-rate.js +10 -6
- package/src/lib/server/manual-tax-rate.js.map +1 -1
- package/src/lib/server/native-checkout.d.ts +10 -3
- package/src/lib/server/native-checkout.js +8 -3
- package/src/lib/server/native-checkout.js.map +1 -1
- package/src/lib/server/payment-method-domains.d.ts +50 -9
- package/src/lib/server/payment-method-domains.js +150 -51
- package/src/lib/server/payment-method-domains.js.map +1 -1
- package/src/lib/server/payment-methods.js +3 -2
- package/src/lib/server/payment-methods.js.map +1 -1
- package/src/lib/server/pos-order.js +5 -1
- package/src/lib/server/pos-order.js.map +1 -1
- package/src/lib/server/pos-stripe.d.ts +7 -7
- package/src/lib/server/pos-stripe.js +15 -13
- package/src/lib/server/pos-stripe.js.map +1 -1
- package/src/lib/server/pos-terminal.js +11 -3
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/server/quote-pay.d.ts +23 -1
- package/src/lib/server/quote-pay.js +112 -32
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote.d.ts +2 -1
- package/src/lib/server/quote.js +12 -11
- package/src/lib/server/quote.js.map +1 -1
- package/src/lib/server/refund.js +13 -6
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server/related.js +10 -3
- package/src/lib/server/related.js.map +1 -1
- package/src/lib/server/reserve.js +19 -6
- package/src/lib/server/reserve.js.map +1 -1
- package/src/lib/server/revenue-source.d.ts +6 -0
- package/src/lib/server/revenue-source.js +25 -9
- package/src/lib/server/revenue-source.js.map +1 -1
- package/src/lib/server/seller-stripe-account.d.ts +45 -0
- package/src/lib/server/seller-stripe-account.js +99 -0
- package/src/lib/server/seller-stripe-account.js.map +1 -0
- package/src/lib/server/storefront-tax-record.js +6 -1
- package/src/lib/server/storefront-tax-record.js.map +1 -1
- package/src/lib/server/storefront-tax.d.ts +33 -2
- package/src/lib/server/storefront-tax.js +39 -3
- package/src/lib/server/storefront-tax.js.map +1 -1
- package/src/lib/server/stripe-refund.d.ts +15 -0
- package/src/lib/server/stripe-refund.js +54 -26
- package/src/lib/server/stripe-refund.js.map +1 -1
- package/src/lib/server/subscription-portal.js +8 -3
- package/src/lib/server/subscription-portal.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/plugins-commerce",
|
|
3
|
-
"version": "1.15.
|
|
3
|
+
"version": "1.15.1",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,18 +25,18 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.15.
|
|
29
|
-
"@aglyn/shared-data-mdi": "1.15.
|
|
30
|
-
"@aglyn/shared-ui-jsx": "1.15.
|
|
31
|
-
"@aglyn/shared-ui-next": "1.15.
|
|
32
|
-
"@aglyn/shared-ui-snackstack": "1.15.
|
|
33
|
-
"@aglyn/shared-util-email": "1.15.
|
|
34
|
-
"@aglyn/shared-util-http": "1.15.
|
|
35
|
-
"@aglyn/shared-util-timestamp": "1.15.
|
|
36
|
-
"@aglyn/shared-util-tools": "1.15.
|
|
37
|
-
"@aglyn/tenant-data-admin": "1.15.
|
|
38
|
-
"@aglyn/tenant-feature-instance": "1.15.
|
|
39
|
-
"@aglyn/tenant-runtime": "1.15.
|
|
28
|
+
"@aglyn/aglyn": "1.15.1",
|
|
29
|
+
"@aglyn/shared-data-mdi": "1.15.1",
|
|
30
|
+
"@aglyn/shared-ui-jsx": "1.15.1",
|
|
31
|
+
"@aglyn/shared-ui-next": "1.15.1",
|
|
32
|
+
"@aglyn/shared-ui-snackstack": "1.15.1",
|
|
33
|
+
"@aglyn/shared-util-email": "1.15.1",
|
|
34
|
+
"@aglyn/shared-util-http": "1.15.1",
|
|
35
|
+
"@aglyn/shared-util-timestamp": "1.15.1",
|
|
36
|
+
"@aglyn/shared-util-tools": "1.15.1",
|
|
37
|
+
"@aglyn/tenant-data-admin": "1.15.1",
|
|
38
|
+
"@aglyn/tenant-feature-instance": "1.15.1",
|
|
39
|
+
"@aglyn/tenant-runtime": "1.15.1",
|
|
40
40
|
"@stripe/react-stripe-js": "^6.12.0",
|
|
41
41
|
"@stripe/stripe-js": "^9.17.0",
|
|
42
42
|
"@swc/helpers": "0.5.23",
|
|
@@ -280,11 +280,14 @@ function CartLines(props) {
|
|
|
280
280
|
value: ((_ref2 = cart == null ? void 0 : cart.subtotalCents) != null ? _ref2 : 0) / 100,
|
|
281
281
|
items: cartAnalyticsItems(cart)
|
|
282
282
|
}));
|
|
283
|
-
setNativeCheckout({
|
|
283
|
+
setNativeCheckout(_extends({
|
|
284
284
|
clientSecret: String(payload.clientSecret),
|
|
285
|
-
publishableKey: String(payload.publishableKey)
|
|
285
|
+
publishableKey: String(payload.publishableKey)
|
|
286
|
+
}, payload.stripeAccount ? {
|
|
287
|
+
stripeAccount: String(payload.stripeAccount)
|
|
288
|
+
} : {}, {
|
|
286
289
|
wallets: CommerceModel.readStorefrontCheckoutWallets(payload.wallets)
|
|
287
|
-
});
|
|
290
|
+
}));
|
|
288
291
|
setStatus('idle');
|
|
289
292
|
return;
|
|
290
293
|
}
|
|
@@ -672,6 +675,7 @@ function CartLines(props) {
|
|
|
672
675
|
children: /*#__PURE__*/ _jsx(StorefrontPaymentElement, {
|
|
673
676
|
clientSecret: nativeCheckout.clientSecret,
|
|
674
677
|
publishableKey: nativeCheckout.publishableKey,
|
|
678
|
+
stripeAccount: nativeCheckout.stripeAccount,
|
|
675
679
|
wallets: nativeCheckout.wallets,
|
|
676
680
|
payLabel: checkoutLabel || 'Pay now',
|
|
677
681
|
defaultEmail: email,
|
|
@@ -851,6 +855,7 @@ function CartLines(props) {
|
|
|
851
855
|
}),
|
|
852
856
|
/*#__PURE__*/ _jsx(IconButton, {
|
|
853
857
|
"aria-label": "Cart",
|
|
858
|
+
color: "inherit",
|
|
854
859
|
onClick: ()=>setOpen(true),
|
|
855
860
|
children: /*#__PURE__*/ _jsx(Badge, {
|
|
856
861
|
badgeContent: (_ref = cart == null ? void 0 : cart.count) != null ? _ref : 0,
|
|
@@ -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 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 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 sx={{ width: 60 }}\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 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 <IconButton aria-label=\"Cart\" 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","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","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","PR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,OAAO;gBAAEyH,SAAS;gBAAUvH,YAAY;YAAK;QAC/C;IACF;CACD,CAAA;AAED,eAAeuL,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 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 sx={{ width: 60 }}\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","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","CHEC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;QAC1CC,MAAM;YAAEf,MAAM5Q,eAAe4Q,IAAI;YAAEzF,IAAI;gBAAED,OAAO;YAAU;QAAE;QAC5DuH,MAAM;YACJpB,KAAK;YACLqB,aAAapQ;YACbgP,UAAUpP;YACVqB,OAAO;gBAAE0H,SAAS;gBAAUxH,YAAY;YAAK;QAC/C;IACF;CACD,CAAA;AAED,eAAewL,KAAI"}
|
|
@@ -247,7 +247,7 @@ import { useCommerceEntitlement } from "./entitlement-gate.component.js";
|
|
|
247
247
|
/*#__PURE__*/ _jsx(Typography, {
|
|
248
248
|
variant: "body2",
|
|
249
249
|
color: "text.secondary",
|
|
250
|
-
children: 'Card processing is passed through at cost on top of that: ' + `${Aglyn.
|
|
250
|
+
children: 'Card processing is passed through at cost on top of that: ' + `${Aglyn.SALE_PROCESSING_PERCENT}% + ${Aglyn.SALE_PROCESSING_FIXED_CENTS}¢ per card sale, ` + 'online or on a card reader, what Stripe charges to take the payment. It is not a ' + `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} margin. Where the platform fee is smaller than ` + `what Stripe charges to pay you out (${Aglyn.CONNECT_PAYOUT_PERCENT}% + ` + `${Aglyn.CONNECT_PAYOUT_FIXED_CENTS}¢ a payout, and ${Aglyn.STRIPE_TAX_PERCENT}% where ` + 'Stripe Tax works out the tax), the fee is that cost instead.'
|
|
251
251
|
}),
|
|
252
252
|
physicalPct > 0 || digitalPct > 0 ? /*#__PURE__*/ _jsx(Typography, {
|
|
253
253
|
variant: "body2",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/payments-settings-card.component.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'use client'\n\nimport { trackEvent } from '@aglyn/aglyn/app-utils/analytics-events'\nimport * as Aglyn from '@aglyn/aglyn'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Alert, Button, Chip, Stack, Typography } from '@mui/material'\nimport { doc } from 'firebase/firestore'\nimport { useCallback, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { useFirestoreDoc } from '@aglyn/tenant-feature-instance'\nimport { useOrgPlan } from '@aglyn/tenant-feature-instance'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { PrerequisiteNotice } from '@aglyn/shared-ui-jsx/components/prerequisite-notice.component'\nimport { useCommerceEntitlement } from './entitlement-gate.component'\n\nexport interface PaymentsSettingsCardProps {\n hostId: string\n}\n\n/** The element id the Payments card carries, for a link on the same page that lands on it (AGL-3982). */\nexport const PAYMENTS_SETTINGS_ANCHOR = 'store-payments'\n\n/**\n * Merchant payments card (AGL-284): Stripe Connect Express onboarding\n * status for the org owner + the plan's transaction-fee ladder so the\n * \"upgrade to kill fees\" motion (AGL-278) is visible where it matters.\n */\nexport function PaymentsSettingsCard(props: PaymentsSettingsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const [busy, setBusy] = useState(false)\n /**\n * A one-time Stripe Express dashboard link, minted by the connect route on\n * request. Not persisted: login links are single-use and short-lived, so a\n * stored one would be a button that fails the second time it is pressed.\n */\n const [dashboardUrl, setDashboardUrl] = useState<string | null>(null)\n const { org, ready: planReady } = useOrgPlan(hostId)\n /** Bumped by Retry to re-subscribe the profile listen (AGL-1380). */\n const [retryNonce, setRetryNonce] = useState(0)\n const { upgradeHref } = useCommerceEntitlement(hostId, 'commerce')\n /**\n * The OWNER's profile: the Stripe account every money route charges\n * against is the one on the workspace owner's profile. Reading the\n * signed-in member's instead told an admin who is not the owner that a\n * connected store was not set up.\n */\n const ownerUid =\n typeof org?.ownerUid === 'string' && org.ownerUid ? org.ownerUid : undefined\n const { data: profile, status: profileStatus } = useFirestoreDoc<any>(\n // Held at null rather than addressed as `profiles/-pending-` — that\n // sentinel issued a guaranteed-denied read on every pre-auth mount, and\n // a denial lands in `status: 'error'`, which now means something.\n () => (ownerUid ? doc(firestore, 'profiles', ownerUid) : null),\n [firestore, ownerUid, retryNonce],\n )\n const isOwner = Boolean(\n org?.ownerUid && (user as any)?.uid === org.ownerUid,\n )\n /**\n * Three outcomes, not two (AGL-1380). An absent profile doc is the value\n * BEFORE an answer as much as it is the value of a merchant who never\n * connected Stripe, so \"Not set up\" off a falsy `stripeChargesEnabled` is a\n * claim about this org's payment setup made without having heard back. It\n * is wrong in the direction that provokes action: the same falsy value\n * turns the button into \"Set up payments\", which sends a merchant who is\n * already taking money into Stripe onboarding.\n */\n const stripeState: 'pending' | 'error' | 'loaded' =\n !planReady || (ownerUid && profileStatus === 'loading')\n ? 'pending'\n : profileStatus === 'error'\n ? 'error'\n : 'loaded'\n /**\n * WHICH STRIPE WORLD THE STORED ACCOUNT BELONGS TO (AGL-2471).\n *\n * `stripeChargesEnabled: true` was the whole readiness claim, and a\n * production profile carrying it named a TEST-mode account: this card said\n * \"Charges enabled\" about three storefronts that could not take a single\n * payment. Only a literal boolean counts as recorded — the same\n * three-valued reading `merchantAccountIsReady` uses on the server, so the\n * chip and the checkout cannot disagree.\n */\n const modeVerified = typeof profile?.stripeAccountLivemode === 'boolean'\n const chargesConnected =\n stripeState === 'loaded' && Boolean(profile?.stripeChargesEnabled)\n const modeUnverified = chargesConnected && !modeVerified\n const chargesEnabled = chargesConnected && modeVerified\n const physicalPct = Aglyn.resolveTransactionFeePct(org, 'physical')\n const digitalPct = Aglyn.resolveTransactionFeePct(org, 'digital')\n const commerceEnabled = Aglyn.checkEntitlement(org, 'commerce')\n\n const handleConnect = useCallback(async () => {\n setBusy(true)\n try {\n const response = await authorizedFetch(user, '/api/commerce/connect', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId }),\n })\n const payload = await response.json()\n if (response.status === 501) {\n return void enqueueSnackbar(\n 'Payments are not configured on this deployment',\n { variant: 'info', persist: false },\n )\n }\n if (!response.ok) {\n return void enqueueSnackbar(payload?.error ?? 'Payment setup failed', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n if (payload.chargesEnabled) {\n // \"% who connect Stripe\" — a GTM plan §6 activation metric\n // (AGL-1561). Gated on the TRANSITION, not the state: this handler\n // is a re-entrant create-or-resume, so it answers `chargesEnabled:\n // true` on every subsequent visit to a connected account, and a bare\n // event here would count one merchant once per click forever.\n // `chargesEnabled` is the state read from the profile BEFORE this\n // request, so the event fires only when onboarding actually completed.\n if (!chargesEnabled) trackEvent('stripe_connected', {})\n // CHARGES AND PAYOUTS ARE TWO FLAGS, AND ONLY ONE OF THEM IS THIS\n // SENTENCE (AGL-1997). `chargesEnabled` says Stripe will let the\n // account take money; whether the money can LEAVE is `payoutsEnabled`,\n // which the route answers alongside it. Charges-yes/payouts-no is an\n // ordinary Stripe state — verification pending or lapsed, no payout\n // method — and announcing \"Payments are enabled\" in it is false in the\n // direction that costs the merchant: they sell believing they are\n // paid, and the funds sit in a Connect account that cannot release\n // them. Read three-valued, so only a literal `false` from Stripe\n // downgrades the claim; an absent flag means unasked, not off.\n const payoutsBlocked = payload.payoutsEnabled === false\n // A WARNING THAT NAMES A PROBLEM MUST OFFER THE FIX.\n //\n // Stripe is the only place payouts can be released — an Express\n // account has no password and no direct login — so telling the\n // merchant their funds are stranded and then keeping them here is half\n // an answer. The route now mints the remediation link for exactly this\n // state; going there is the whole point of pressing the button.\n if (payoutsBlocked && payload.url) {\n return void window.location.assign(payload.url)\n }\n // Payouts are flowing, so the link is the Express dashboard: balance,\n // payout schedule, and the reason a payout failed. Held in state\n // rather than followed, because this click was a status check and\n // navigating away from one nobody asked to leave is its own defect.\n if (!payoutsBlocked && typeof payload.dashboardUrl === 'string') {\n setDashboardUrl(payload.dashboardUrl)\n }\n return void enqueueSnackbar(\n payoutsBlocked\n ? 'Connected — payouts are not released yet'\n : 'Payments are enabled',\n {\n variant: payoutsBlocked ? 'warning' : 'success',\n persist: false,\n },\n )\n }\n if (payload.url) window.location.assign(payload.url)\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }, [user, hostId, chargesEnabled, enqueueSnackbar])\n\n return (\n <CardDisplay\n id={PAYMENTS_SETTINGS_ANCHOR}\n header={'Payments'}\n help={pluginDocsHelp('commerceEndToEnd', {\n anchor: '#1-connect-payments',\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"body2\" sx={{ flex: 1 }}>\n {'Stripe account'}\n </Typography>\n {/*\n No chip at all on error: both labels it could carry — \"Charges\n enabled\" and \"Not set up\" — assert something we failed to find\n out. Whatever Stripe is doing right now it carries on doing.\n */}\n {stripeState === 'error' ? null : (\n <Chip\n size=\"small\"\n label={\n stripeState === 'pending'\n ? 'Checking…'\n : chargesEnabled\n ? 'Charges enabled'\n : modeUnverified\n ? 'Not verified'\n : 'Not set up'\n }\n color={\n stripeState === 'pending'\n ? 'default'\n : chargesEnabled\n ? 'success'\n : modeUnverified\n ? 'error'\n : 'warning'\n }\n variant=\"outlined\"\n />\n )}\n </Stack>\n {stripeState === 'error' ? (\n <Alert\n severity=\"error\"\n action={\n <Button\n color=\"inherit\"\n size=\"small\"\n onClick={() => setRetryNonce((n) => n + 1)}\n >\n {'Retry'}\n </Button>\n }\n >\n {'We couldn’t load your payment setup. This says nothing about ' +\n 'whether payments are on — we could not reach the setting to ' +\n 'find out. Nothing has changed.'}\n </Alert>\n ) : null}\n {/*\n Every line below reads the plan, and an org doc still in flight\n resolves to the FREE tier (AGL-1064) — which would flash \"Selling\n requires a paid plan\" and the wrong fee percentages at a paying\n seller, then correct itself. Say nothing until it is known.\n */}\n {!planReady ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Checking your plan…'}\n </Typography>\n ) : (\n <>\n {!commerceEnabled ? (\n <PrerequisiteNotice href={upgradeHref} actionLabel=\"See plans\">\n {'Selling needs a paid plan. Choose one on Billing, then connect Stripe here.'}\n </PrerequisiteNotice>\n ) : null}\n {/*\n THE LEGAL NAME, not the org's resolved `productName`\n (AGL-2351). This sentence says who takes money off the\n merchant's own Stripe account, and the application fee lands in\n the platform Stripe account — held by the operating entity, not\n by a white-label agency reselling the console. Naming the\n agency here would assert a fee relationship that does not\n exist. `PLATFORM_BRAND_LEGAL_NAME` still configures cleanly for\n a self-host operator, who really is the entity collecting it.\n */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Buyers pay on your own Stripe account; ' +\n `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} collects a platform fee ` +\n 'per sale based on your plan:'}\n </Typography>\n {/* The DIGITAL rate is not products-only (AGL-2315). A paid\n booking is a service sale and resolves through the same\n `'service'`/digital axis, so a bookings-only merchant pays this\n exact number — and this card was the one place they could read\n their own rate while naming only \"products\". Stated here rather\n than adding a third figure: it is one rate, not two. */}\n <Typography variant=\"body2\">\n {`Physical products: ${physicalPct}% · Digital products, ` +\n `services & bookings: ${digitalPct}%`}\n {physicalPct > 0 || digitalPct > 0 ? (\n <Typography\n component=\"span\"\n variant=\"caption\"\n color=\"text.secondary\"\n >\n {' — higher plans reduce fees to 0%'}\n </Typography>\n ) : null}\n </Typography>\n {/* CARD PROCESSING, PASSED THROUGH AT COST (AGL-2152).\n\n Unconditional, including on the 0% plans, because it is\n exactly those plans where the merchant would otherwise read\n \"0%\" and be surprised by a deduction. Their PLATFORM fee\n really is zero — the figure below is Stripe's own charge for\n taking the payment, which every storefront sale incurs and\n which used to be absorbed silently out of the platform's\n balance rather than passed through.\n\n Named as a range rather than one number because the buyer\n chooses the payment method after the session is created:\n cards settle at the low end, buy-now-pay-later at the high\n end, and the deduction is sized for the dearest so a sale can\n never cost more to process than it collects. A quote's or an\n invoice's pay link offers no buy-now-pay-later, so it carries\n the card rate alone (`PAY_LINK_PROCESSING_PERCENT`). */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Card processing is passed through at cost on top of that: ' +\n `${Aglyn.CARD_PROCESSING_PERCENT}–` +\n `${Aglyn.BNPL_PROCESSING_PERCENT}% + ` +\n `${Aglyn.PROCESSING_FIXED_CENTS}¢ per online ` +\n 'sale, what Stripe charges to take the payment. It is not a ' +\n `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} margin. Quotes and invoices ` +\n 'are paid by card or wallet, never buy-now-pay-later, so they carry ' +\n `${Aglyn.PAY_LINK_PROCESSING_PERCENT}% + ` +\n `${Aglyn.PROCESSING_FIXED_CENTS}¢.`}\n </Typography>\n {/* WHICH REGISTER TENDERS CARRY THE FEE, AND HOW EACH IS\n COLLECTED (AGL-2111, AGL-4036).\n\n Card and room-charge payments at the register carry the fee;\n cash, gift cards and store credit carry none\n (`CommerceModel.paymentCarriesPlatformFee`). A room charge's\n fee leaves by a door the merchant has never seen money leave\n by, their monthly invoice, so it is said here BEFORE it\n appears there.\n\n Shown only when a rate actually applies: on a 0% plan there is\n nothing to collect either way, and the paragraph would be noise\n on the card of the merchants who upgraded to escape fees. */}\n {physicalPct > 0 || digitalPct > 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'At the register, cash, gift card and store credit payments ' +\n 'carry no fee. On card payments it is deducted from your ' +\n 'Stripe payout; on room-charge payments there is no payout to ' +\n 'deduct from, so it is added to your monthly ' +\n `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} invoice instead.`}\n </Typography>\n ) : null}\n </>\n )}\n {/*\n AGL-2471: connected, and refused by every money door because the\n account was never verified against this deployment's Stripe mode.\n \"Not set up\" would be a lie in the other direction — the merchant\n did set something up — so the card names what is actually wrong and\n what to do about it.\n */}\n {modeUnverified ? (\n <Alert severity=\"error\">\n {'Your Stripe account has not been verified for payments on ' +\n 'this site, so sales will be refused. Set up payments again ' +\n 'to verify it — if it was connected against Stripe test mode, ' +\n 'you will need to connect a live account.'}\n </Alert>\n ) : null}\n {/*\n The button's own label is a claim — \"Set up payments\" tells the\n owner they have none. Withheld until the answer is in, for the same\n reason as the chip (AGL-1380); on error the Retry above is the only\n action offered, because acting on a setup we could not read is how\n a connected merchant gets sent back through onboarding.\n */}\n {/*\n WHERE THE MONEY STOPPED. Mirrored onto this profile by the\n `payout.failed` handler and retired by the next successful payout, so\n it names a live problem rather than a scar. Without it a merchant sold\n into an account that could not release the funds and the card said\n \"Payments are enabled\" the whole time — the storefront looked healthy\n from every angle available to them.\n */}\n {stripeState === 'loaded' && profile?.lastPayoutFailureAtMs ? (\n <Alert severity=\"warning\" variant=\"outlined\">\n {`A payout of $${(\n Number(profile.lastPayoutFailureCents ?? 0) / 100\n ).toFixed(2)} did not reach your bank on ${new Date(\n Number(profile.lastPayoutFailureAtMs),\n ).toLocaleDateString()} — ${String(\n profile.lastPayoutFailureReason ?? 'Stripe did not say why',\n )} The money is still in your Stripe account. Open Stripe to fix your payout details.`}\n </Alert>\n ) : null}\n {!planReady || stripeState !== 'loaded' ? null : isOwner ? (\n <>\n <Button\n size=\"small\"\n variant={chargesEnabled ? 'text' : 'contained'}\n color=\"primary\"\n disabled={busy}\n onClick={handleConnect}\n sx={{ alignSelf: 'flex-start' }}\n >\n {chargesEnabled\n ? 'Refresh status'\n : busy\n ? 'Opening Stripe…'\n : 'Set up payments'}\n </Button>\n {/*\n Where the money actually is. Aglyn records none of it —\n no balance, no payout schedule, and no `payout.failed` handling\n anywhere — so a merchant whose payout bounced has no way to learn\n that from this console. An Express account has no direct login\n either, which leaves a link minted by the platform as the only\n route in. `target=\"_blank\"` because it leaves the app entirely.\n */}\n {dashboardUrl ? (\n <Button\n size=\"small\"\n variant=\"text\"\n color=\"primary\"\n href={dashboardUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n sx={{ alignSelf: 'flex-start' }}\n >\n {'View payouts in Stripe'}\n </Button>\n ) : null}\n </>\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Only the organization owner can set up payments.'}\n </Typography>\n )}\n </Stack>\n </CardDisplay>\n )\n}\nPaymentsSettingsCard.displayName = 'PaymentsSettingsCard'\n\nexport default PaymentsSettingsCard\n"],"names":["trackEvent","Aglyn","CardDisplay","useSnackbar","Alert","Button","Chip","Stack","Typography","doc","useCallback","useState","useFirestore","useUser","useFirestoreDoc","useOrgPlan","pluginDocsHelp","authorizedFetch","PrerequisiteNotice","useCommerceEntitlement","PAYMENTS_SETTINGS_ANCHOR","PaymentsSettingsCard","props","profile","hostId","firestore","data","user","enqueueSnackbar","busy","setBusy","dashboardUrl","setDashboardUrl","org","ready","planReady","retryNonce","setRetryNonce","upgradeHref","ownerUid","undefined","status","profileStatus","isOwner","Boolean","uid","stripeState","modeVerified","stripeAccountLivemode","chargesConnected","stripeChargesEnabled","modeUnverified","chargesEnabled","physicalPct","resolveTransactionFeePct","digitalPct","commerceEnabled","checkEntitlement","handleConnect","response","method","headers","body","JSON","stringify","payload","json","variant","persist","ok","error","allowDuplicate","payoutsBlocked","payoutsEnabled","url","window","location","assign","console","id","header","help","anchor","contentGutterX","contentGutterY","spacing","direction","sx","alignItems","flex","size","label","color","severity","action","onClick","n","href","actionLabel","PLATFORM_BRAND_LEGAL_NAME","component","CARD_PROCESSING_PERCENT","BNPL_PROCESSING_PERCENT","PROCESSING_FIXED_CENTS","PAY_LINK_PROCESSING_PERCENT","lastPayoutFailureAtMs","Number","lastPayoutFailureCents","toFixed","Date","toLocaleDateString","String","lastPayoutFailureReason","disabled","alignSelf","target","rel","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA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;;wBAUPE,6BACC,KAAC1B;4BACCqF,MAAK;4BACLvB,SAAQ;4BACRyB,OAAM;4BACNK,MAAMlE;4BACNoF,QAAO;4BACPC,KAAI;4BACJ7B,IAAI;gCAAE2B,WAAW;4BAAa;sCAE7B;6BAED;;mCAGN,KAAC1G;oBAAW2D,SAAQ;oBAAUyB,OAAM;8BACjC;;;;;AAMb;AACAvE,qBAAqBgG,WAAW,GAAG;AAEnC,eAAehG,qBAAoB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/payments-settings-card.component.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'use client'\n\nimport { trackEvent } from '@aglyn/aglyn/app-utils/analytics-events'\nimport * as Aglyn from '@aglyn/aglyn'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Alert, Button, Chip, Stack, Typography } from '@mui/material'\nimport { doc } from 'firebase/firestore'\nimport { useCallback, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { useFirestoreDoc } from '@aglyn/tenant-feature-instance'\nimport { useOrgPlan } from '@aglyn/tenant-feature-instance'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { PrerequisiteNotice } from '@aglyn/shared-ui-jsx/components/prerequisite-notice.component'\nimport { useCommerceEntitlement } from './entitlement-gate.component'\n\nexport interface PaymentsSettingsCardProps {\n hostId: string\n}\n\n/** The element id the Payments card carries, for a link on the same page that lands on it (AGL-3982). */\nexport const PAYMENTS_SETTINGS_ANCHOR = 'store-payments'\n\n/**\n * Merchant payments card (AGL-284): Stripe Connect Express onboarding\n * status for the org owner + the plan's transaction-fee ladder so the\n * \"upgrade to kill fees\" motion (AGL-278) is visible where it matters.\n */\nexport function PaymentsSettingsCard(props: PaymentsSettingsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const [busy, setBusy] = useState(false)\n /**\n * A one-time Stripe Express dashboard link, minted by the connect route on\n * request. Not persisted: login links are single-use and short-lived, so a\n * stored one would be a button that fails the second time it is pressed.\n */\n const [dashboardUrl, setDashboardUrl] = useState<string | null>(null)\n const { org, ready: planReady } = useOrgPlan(hostId)\n /** Bumped by Retry to re-subscribe the profile listen (AGL-1380). */\n const [retryNonce, setRetryNonce] = useState(0)\n const { upgradeHref } = useCommerceEntitlement(hostId, 'commerce')\n /**\n * The OWNER's profile: the Stripe account every money route charges\n * against is the one on the workspace owner's profile. Reading the\n * signed-in member's instead told an admin who is not the owner that a\n * connected store was not set up.\n */\n const ownerUid =\n typeof org?.ownerUid === 'string' && org.ownerUid ? org.ownerUid : undefined\n const { data: profile, status: profileStatus } = useFirestoreDoc<any>(\n // Held at null rather than addressed as `profiles/-pending-` — that\n // sentinel issued a guaranteed-denied read on every pre-auth mount, and\n // a denial lands in `status: 'error'`, which now means something.\n () => (ownerUid ? doc(firestore, 'profiles', ownerUid) : null),\n [firestore, ownerUid, retryNonce],\n )\n const isOwner = Boolean(\n org?.ownerUid && (user as any)?.uid === org.ownerUid,\n )\n /**\n * Three outcomes, not two (AGL-1380). An absent profile doc is the value\n * BEFORE an answer as much as it is the value of a merchant who never\n * connected Stripe, so \"Not set up\" off a falsy `stripeChargesEnabled` is a\n * claim about this org's payment setup made without having heard back. It\n * is wrong in the direction that provokes action: the same falsy value\n * turns the button into \"Set up payments\", which sends a merchant who is\n * already taking money into Stripe onboarding.\n */\n const stripeState: 'pending' | 'error' | 'loaded' =\n !planReady || (ownerUid && profileStatus === 'loading')\n ? 'pending'\n : profileStatus === 'error'\n ? 'error'\n : 'loaded'\n /**\n * WHICH STRIPE WORLD THE STORED ACCOUNT BELONGS TO (AGL-2471).\n *\n * `stripeChargesEnabled: true` was the whole readiness claim, and a\n * production profile carrying it named a TEST-mode account: this card said\n * \"Charges enabled\" about three storefronts that could not take a single\n * payment. Only a literal boolean counts as recorded — the same\n * three-valued reading `merchantAccountIsReady` uses on the server, so the\n * chip and the checkout cannot disagree.\n */\n const modeVerified = typeof profile?.stripeAccountLivemode === 'boolean'\n const chargesConnected =\n stripeState === 'loaded' && Boolean(profile?.stripeChargesEnabled)\n const modeUnverified = chargesConnected && !modeVerified\n const chargesEnabled = chargesConnected && modeVerified\n const physicalPct = Aglyn.resolveTransactionFeePct(org, 'physical')\n const digitalPct = Aglyn.resolveTransactionFeePct(org, 'digital')\n const commerceEnabled = Aglyn.checkEntitlement(org, 'commerce')\n\n const handleConnect = useCallback(async () => {\n setBusy(true)\n try {\n const response = await authorizedFetch(user, '/api/commerce/connect', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId }),\n })\n const payload = await response.json()\n if (response.status === 501) {\n return void enqueueSnackbar(\n 'Payments are not configured on this deployment',\n { variant: 'info', persist: false },\n )\n }\n if (!response.ok) {\n return void enqueueSnackbar(payload?.error ?? 'Payment setup failed', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n if (payload.chargesEnabled) {\n // \"% who connect Stripe\" — a GTM plan §6 activation metric\n // (AGL-1561). Gated on the TRANSITION, not the state: this handler\n // is a re-entrant create-or-resume, so it answers `chargesEnabled:\n // true` on every subsequent visit to a connected account, and a bare\n // event here would count one merchant once per click forever.\n // `chargesEnabled` is the state read from the profile BEFORE this\n // request, so the event fires only when onboarding actually completed.\n if (!chargesEnabled) trackEvent('stripe_connected', {})\n // CHARGES AND PAYOUTS ARE TWO FLAGS, AND ONLY ONE OF THEM IS THIS\n // SENTENCE (AGL-1997). `chargesEnabled` says Stripe will let the\n // account take money; whether the money can LEAVE is `payoutsEnabled`,\n // which the route answers alongside it. Charges-yes/payouts-no is an\n // ordinary Stripe state — verification pending or lapsed, no payout\n // method — and announcing \"Payments are enabled\" in it is false in the\n // direction that costs the merchant: they sell believing they are\n // paid, and the funds sit in a Connect account that cannot release\n // them. Read three-valued, so only a literal `false` from Stripe\n // downgrades the claim; an absent flag means unasked, not off.\n const payoutsBlocked = payload.payoutsEnabled === false\n // A WARNING THAT NAMES A PROBLEM MUST OFFER THE FIX.\n //\n // Stripe is the only place payouts can be released — an Express\n // account has no password and no direct login — so telling the\n // merchant their funds are stranded and then keeping them here is half\n // an answer. The route now mints the remediation link for exactly this\n // state; going there is the whole point of pressing the button.\n if (payoutsBlocked && payload.url) {\n return void window.location.assign(payload.url)\n }\n // Payouts are flowing, so the link is the Express dashboard: balance,\n // payout schedule, and the reason a payout failed. Held in state\n // rather than followed, because this click was a status check and\n // navigating away from one nobody asked to leave is its own defect.\n if (!payoutsBlocked && typeof payload.dashboardUrl === 'string') {\n setDashboardUrl(payload.dashboardUrl)\n }\n return void enqueueSnackbar(\n payoutsBlocked\n ? 'Connected — payouts are not released yet'\n : 'Payments are enabled',\n {\n variant: payoutsBlocked ? 'warning' : 'success',\n persist: false,\n },\n )\n }\n if (payload.url) window.location.assign(payload.url)\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }, [user, hostId, chargesEnabled, enqueueSnackbar])\n\n return (\n <CardDisplay\n id={PAYMENTS_SETTINGS_ANCHOR}\n header={'Payments'}\n help={pluginDocsHelp('commerceEndToEnd', {\n anchor: '#1-connect-payments',\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"body2\" sx={{ flex: 1 }}>\n {'Stripe account'}\n </Typography>\n {/*\n No chip at all on error: both labels it could carry — \"Charges\n enabled\" and \"Not set up\" — assert something we failed to find\n out. Whatever Stripe is doing right now it carries on doing.\n */}\n {stripeState === 'error' ? null : (\n <Chip\n size=\"small\"\n label={\n stripeState === 'pending'\n ? 'Checking…'\n : chargesEnabled\n ? 'Charges enabled'\n : modeUnverified\n ? 'Not verified'\n : 'Not set up'\n }\n color={\n stripeState === 'pending'\n ? 'default'\n : chargesEnabled\n ? 'success'\n : modeUnverified\n ? 'error'\n : 'warning'\n }\n variant=\"outlined\"\n />\n )}\n </Stack>\n {stripeState === 'error' ? (\n <Alert\n severity=\"error\"\n action={\n <Button\n color=\"inherit\"\n size=\"small\"\n onClick={() => setRetryNonce((n) => n + 1)}\n >\n {'Retry'}\n </Button>\n }\n >\n {'We couldn’t load your payment setup. This says nothing about ' +\n 'whether payments are on — we could not reach the setting to ' +\n 'find out. Nothing has changed.'}\n </Alert>\n ) : null}\n {/*\n Every line below reads the plan, and an org doc still in flight\n resolves to the FREE tier (AGL-1064) — which would flash \"Selling\n requires a paid plan\" and the wrong fee percentages at a paying\n seller, then correct itself. Say nothing until it is known.\n */}\n {!planReady ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Checking your plan…'}\n </Typography>\n ) : (\n <>\n {!commerceEnabled ? (\n <PrerequisiteNotice href={upgradeHref} actionLabel=\"See plans\">\n {'Selling needs a paid plan. Choose one on Billing, then connect Stripe here.'}\n </PrerequisiteNotice>\n ) : null}\n {/*\n THE LEGAL NAME, not the org's resolved `productName`\n (AGL-2351). This sentence says who takes money off the\n merchant's own Stripe account, and the application fee lands in\n the platform Stripe account — held by the operating entity, not\n by a white-label agency reselling the console. Naming the\n agency here would assert a fee relationship that does not\n exist. `PLATFORM_BRAND_LEGAL_NAME` still configures cleanly for\n a self-host operator, who really is the entity collecting it.\n */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Buyers pay on your own Stripe account; ' +\n `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} collects a platform fee ` +\n 'per sale based on your plan:'}\n </Typography>\n {/* The DIGITAL rate is not products-only (AGL-2315). A paid\n booking is a service sale and resolves through the same\n `'service'`/digital axis, so a bookings-only merchant pays this\n exact number — and this card was the one place they could read\n their own rate while naming only \"products\". Stated here rather\n than adding a third figure: it is one rate, not two. */}\n <Typography variant=\"body2\">\n {`Physical products: ${physicalPct}% · Digital products, ` +\n `services & bookings: ${digitalPct}%`}\n {physicalPct > 0 || digitalPct > 0 ? (\n <Typography\n component=\"span\"\n variant=\"caption\"\n color=\"text.secondary\"\n >\n {' — higher plans reduce fees to 0%'}\n </Typography>\n ) : null}\n </Typography>\n {/* CARD PROCESSING, PASSED THROUGH AT COST (AGL-2152).\n\n Unconditional, including on the 0% plans, because it is\n exactly those plans where the merchant would otherwise read\n \"0%\" and be surprised by a deduction. Their PLATFORM fee\n really is zero — the figure below is Stripe's own charge for\n taking the payment, which every storefront sale incurs and\n which used to be absorbed silently out of the platform's\n balance rather than passed through.\n\n One rate, online and on a card reader (AGL-4198): no checkout\n on a site offers buy-now-pay-later. Stripe's payout charge and\n Stripe Tax come out of the platform fee first; a fee too small\n to cover them is topped up to what Stripe charges, never more. */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Card processing is passed through at cost on top of that: ' +\n `${Aglyn.SALE_PROCESSING_PERCENT}% + ${Aglyn.SALE_PROCESSING_FIXED_CENTS}¢ per card sale, ` +\n 'online or on a card reader, what Stripe charges to take the payment. It is not a ' +\n `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} margin. Where the platform fee is smaller than ` +\n `what Stripe charges to pay you out (${Aglyn.CONNECT_PAYOUT_PERCENT}% + ` +\n `${Aglyn.CONNECT_PAYOUT_FIXED_CENTS}¢ a payout, and ${Aglyn.STRIPE_TAX_PERCENT}% where ` +\n 'Stripe Tax works out the tax), the fee is that cost instead.'}\n </Typography>\n {/* WHICH REGISTER TENDERS CARRY THE FEE, AND HOW EACH IS\n COLLECTED (AGL-2111, AGL-4036).\n\n Card and room-charge payments at the register carry the fee;\n cash, gift cards and store credit carry none\n (`CommerceModel.paymentCarriesPlatformFee`). A room charge's\n fee leaves by a door the merchant has never seen money leave\n by, their monthly invoice, so it is said here BEFORE it\n appears there.\n\n Shown only when a rate actually applies: on a 0% plan there is\n nothing to collect either way, and the paragraph would be noise\n on the card of the merchants who upgraded to escape fees. */}\n {physicalPct > 0 || digitalPct > 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'At the register, cash, gift card and store credit payments ' +\n 'carry no fee. On card payments it is deducted from your ' +\n 'Stripe payout; on room-charge payments there is no payout to ' +\n 'deduct from, so it is added to your monthly ' +\n `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} invoice instead.`}\n </Typography>\n ) : null}\n </>\n )}\n {/*\n AGL-2471: connected, and refused by every money door because the\n account was never verified against this deployment's Stripe mode.\n \"Not set up\" would be a lie in the other direction — the merchant\n did set something up — so the card names what is actually wrong and\n what to do about it.\n */}\n {modeUnverified ? (\n <Alert severity=\"error\">\n {'Your Stripe account has not been verified for payments on ' +\n 'this site, so sales will be refused. Set up payments again ' +\n 'to verify it — if it was connected against Stripe test mode, ' +\n 'you will need to connect a live account.'}\n </Alert>\n ) : null}\n {/*\n The button's own label is a claim — \"Set up payments\" tells the\n owner they have none. Withheld until the answer is in, for the same\n reason as the chip (AGL-1380); on error the Retry above is the only\n action offered, because acting on a setup we could not read is how\n a connected merchant gets sent back through onboarding.\n */}\n {/*\n WHERE THE MONEY STOPPED. Mirrored onto this profile by the\n `payout.failed` handler and retired by the next successful payout, so\n it names a live problem rather than a scar. Without it a merchant sold\n into an account that could not release the funds and the card said\n \"Payments are enabled\" the whole time — the storefront looked healthy\n from every angle available to them.\n */}\n {stripeState === 'loaded' && profile?.lastPayoutFailureAtMs ? (\n <Alert severity=\"warning\" variant=\"outlined\">\n {`A payout of $${(\n Number(profile.lastPayoutFailureCents ?? 0) / 100\n ).toFixed(2)} did not reach your bank on ${new Date(\n Number(profile.lastPayoutFailureAtMs),\n ).toLocaleDateString()} — ${String(\n profile.lastPayoutFailureReason ?? 'Stripe did not say why',\n )} The money is still in your Stripe account. Open Stripe to fix your payout details.`}\n </Alert>\n ) : null}\n {!planReady || stripeState !== 'loaded' ? null : isOwner ? (\n <>\n <Button\n size=\"small\"\n variant={chargesEnabled ? 'text' : 'contained'}\n color=\"primary\"\n disabled={busy}\n onClick={handleConnect}\n sx={{ alignSelf: 'flex-start' }}\n >\n {chargesEnabled\n ? 'Refresh status'\n : busy\n ? 'Opening Stripe…'\n : 'Set up payments'}\n </Button>\n {/*\n Where the money actually is. Aglyn records none of it —\n no balance, no payout schedule, and no `payout.failed` handling\n anywhere — so a merchant whose payout bounced has no way to learn\n that from this console. An Express account has no direct login\n either, which leaves a link minted by the platform as the only\n route in. `target=\"_blank\"` because it leaves the app entirely.\n */}\n {dashboardUrl ? (\n <Button\n size=\"small\"\n variant=\"text\"\n color=\"primary\"\n href={dashboardUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n sx={{ alignSelf: 'flex-start' }}\n >\n {'View payouts in Stripe'}\n </Button>\n ) : null}\n </>\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Only the organization owner can set up payments.'}\n </Typography>\n )}\n </Stack>\n </CardDisplay>\n )\n}\nPaymentsSettingsCard.displayName = 'PaymentsSettingsCard'\n\nexport default PaymentsSettingsCard\n"],"names":["trackEvent","Aglyn","CardDisplay","useSnackbar","Alert","Button","Chip","Stack","Typography","doc","useCallback","useState","useFirestore","useUser","useFirestoreDoc","useOrgPlan","pluginDocsHelp","authorizedFetch","PrerequisiteNotice","useCommerceEntitlement","PAYMENTS_SETTINGS_ANCHOR","PaymentsSettingsCard","props","profile","hostId","firestore","data","user","enqueueSnackbar","busy","setBusy","dashboardUrl","setDashboardUrl","org","ready","planReady","retryNonce","setRetryNonce","upgradeHref","ownerUid","undefined","status","profileStatus","isOwner","Boolean","uid","stripeState","modeVerified","stripeAccountLivemode","chargesConnected","stripeChargesEnabled","modeUnverified","chargesEnabled","physicalPct","resolveTransactionFeePct","digitalPct","commerceEnabled","checkEntitlement","handleConnect","response","method","headers","body","JSON","stringify","payload","json","variant","persist","ok","error","allowDuplicate","payoutsBlocked","payoutsEnabled","url","window","location","assign","console","id","header","help","anchor","contentGutterX","contentGutterY","spacing","direction","sx","alignItems","flex","size","label","color","severity","action","onClick","n","href","actionLabel","PLATFORM_BRAND_LEGAL_NAME","component","SALE_PROCESSING_PERCENT","SALE_PROCESSING_FIXED_CENTS","CONNECT_PAYOUT_PERCENT","CONNECT_PAYOUT_FIXED_CENTS","STRIPE_TAX_PERCENT","lastPayoutFailureAtMs","Number","lastPayoutFailureCents","toFixed","Date","toLocaleDateString","String","lastPayoutFailureReason","disabled","alignSelf","target","rel","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,UAAU,QAAQ,0CAAyC;AACpE,YAAYC,WAAW,eAAc;AACrC,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,KAAK,EAAEC,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AACtE,SAASC,GAAG,QAAQ,qBAAoB;AACxC,SAASC,WAAW,EAAEC,QAAQ,QAAQ,QAAO;AAC7C,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SAASC,eAAe,QAAQ,iCAAgC;AAChE,SAASC,UAAU,QAAQ,iCAAgC;AAC3D,SAASC,cAAc,QAAQ,eAAc;AAC7C,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,kBAAkB,QAAQ,gEAA+D;AAClG,SAASC,sBAAsB,QAAQ,kCAA8B;AAMrE,uGAAuG,GACvG,OAAO,MAAMC,2BAA2B,iBAAgB;AAExD;;;;CAIC,GACD,OAAO,SAASC,qBAAqBC,KAAgC;QAsVhDC,iCAIPA;I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oBAAMyF,UAAS;oBAAU1B,SAAQ;8BAC/B,CAAC,aAAa,EAAE,AACfwC,CAAAA,QAAOpF,kCAAAA,QAAQqF,sBAAsB,YAA9BrF,kCAAkC,KAAK,GAAE,EAChDsF,OAAO,CAAC,GAAG,4BAA4B,EAAE,IAAIC,KAC7CH,OAAOpF,QAAQmF,qBAAqB,GACpCK,kBAAkB,GAAG,GAAG,EAAEC,QAC1BzF,mCAAAA,QAAQ0F,uBAAuB,YAA/B1F,mCAAmC,0BACnC,mFAAmF,CAAC;qBAEtF;gBACH,CAACY,aAAaW,gBAAgB,WAAW,OAAOH,wBAC/C;;sCACE,KAACtC;4BACCqF,MAAK;4BACLvB,SAASf,iBAAiB,SAAS;4BACnCwC,OAAM;4BACNsB,UAAUrF;4BACVkE,SAASrC;4BACT6B,IAAI;gCAAE4B,WAAW;4BAAa;sCAE7B/D,iBACG,mBACAvB,OACE,oBACA;;wBAUPE,6BACC,KAAC1B;4BACCqF,MAAK;4BACLvB,SAAQ;4BACRyB,OAAM;4BACNK,MAAMlE;4BACNqF,QAAO;4BACPC,KAAI;4BACJ9B,IAAI;gCAAE4B,WAAW;4BAAa;sCAE7B;6BAED;;mCAGN,KAAC3G;oBAAW2D,SAAQ;oBAAUyB,OAAM;8BACjC;;;;;AAMb;AACAvE,qBAAqBiG,WAAW,GAAG;AAEnC,eAAejG,qBAAoB"}
|
|
@@ -47,7 +47,7 @@ function Fact(props) {
|
|
|
47
47
|
* under `subscriptions/{id}/invoices` by the billing webhook, and this is the
|
|
48
48
|
* first place a merchant can read them without opening Stripe.
|
|
49
49
|
*/ export function SubscriptionDetailDialog(props) {
|
|
50
|
-
var _subscription_invoicesCount, _subscription_invoicesCount1;
|
|
50
|
+
var _subscription_paidCents, _subscription_invoicesCount, _subscription_invoicesCount1;
|
|
51
51
|
var _subscription_totals;
|
|
52
52
|
const { hostId, subscription, currency, onClose } = props;
|
|
53
53
|
const firestore = useFirestore();
|
|
@@ -121,7 +121,7 @@ function Fact(props) {
|
|
|
121
121
|
}) : null,
|
|
122
122
|
/*#__PURE__*/ _jsx(Fact, {
|
|
123
123
|
label: "Paid so far",
|
|
124
|
-
value: `${money(Number(subscription.paidCents) || 0)} over ${Number((_subscription_invoicesCount = subscription.invoicesCount) != null ? _subscription_invoicesCount : 0)} ${Number((_subscription_invoicesCount1 = subscription.invoicesCount) != null ? _subscription_invoicesCount1 : 0) === 1 ? 'invoice' : 'invoices'}`
|
|
124
|
+
value: Number((_subscription_paidCents = subscription.paidCents) != null ? _subscription_paidCents : 0) > 0 ? `${money(Number(subscription.paidCents) || 0)} over ${Number((_subscription_invoicesCount = subscription.invoicesCount) != null ? _subscription_invoicesCount : 0)} ${Number((_subscription_invoicesCount1 = subscription.invoicesCount) != null ? _subscription_invoicesCount1 : 0) === 1 ? 'invoice' : 'invoices'}` : 'Nothing yet'
|
|
125
125
|
}),
|
|
126
126
|
subscription.livemode === false ? /*#__PURE__*/ _jsx(Typography, {
|
|
127
127
|
variant: "caption",
|