@aglyn/plugins-commerce 1.33.2 → 1.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +13 -13
- package/src/lib/components/cart.js +3 -1
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/console/catalog-organization-card.component.js +82 -69
- package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
- package/src/lib/components/console/discounts-card.component.js +46 -25
- package/src/lib/components/console/discounts-card.component.js.map +1 -1
- package/src/lib/components/console/gift-cards-card.component.js +81 -55
- package/src/lib/components/console/gift-cards-card.component.js.map +1 -1
- package/src/lib/components/console/host-coupons-card.component.js +36 -25
- package/src/lib/components/console/host-coupons-card.component.js.map +1 -1
- package/src/lib/components/console/locations-card.component.js +53 -32
- package/src/lib/components/console/locations-card.component.js.map +1 -1
- package/src/lib/components/console/member-posts-card.component.js +35 -32
- package/src/lib/components/console/member-posts-card.component.js.map +1 -1
- package/src/lib/components/console/new-store-tax-question.component.d.ts +17 -0
- package/src/lib/components/console/new-store-tax-question.component.js +197 -0
- package/src/lib/components/console/new-store-tax-question.component.js.map +1 -0
- package/src/lib/components/console/payments-settings-card.component.js +132 -5
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-api.d.ts +6 -0
- package/src/lib/components/console/pos/pos-api.js.map +1 -1
- package/src/lib/components/console/pos/pos-tax-notice.component.d.ts +21 -0
- package/src/lib/components/console/pos/pos-tax-notice.component.js +59 -0
- package/src/lib/components/console/pos/pos-tax-notice.component.js.map +1 -0
- package/src/lib/components/console/pos-page.component.js +65 -17
- package/src/lib/components/console/pos-page.component.js.map +1 -1
- package/src/lib/components/console/registers-card.component.js +21 -13
- package/src/lib/components/console/registers-card.component.js.map +1 -1
- package/src/lib/components/console/reviews-moderation-card.component.js +108 -68
- package/src/lib/components/console/reviews-moderation-card.component.js.map +1 -1
- package/src/lib/components/console/site-member-purchases.component.js +5 -3
- package/src/lib/components/console/site-member-purchases.component.js.map +1 -1
- package/src/lib/components/console/subscription-detail-dialog.component.d.ts +2 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js +1 -1
- package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -1
- package/src/lib/components/console/subscriptions-card.component.js +13 -5
- package/src/lib/components/console/subscriptions-card.component.js.map +1 -1
- package/src/lib/components/console/suppliers-card.component.js +47 -40
- package/src/lib/components/console/suppliers-card.component.js.map +1 -1
- package/src/lib/components/product-choice-cards.js +2 -1
- package/src/lib/components/product-choice-cards.js.map +1 -1
- package/src/lib/components/product-detail.js +9 -4
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/product-grid.js +3 -1
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/related-products.js +2 -1
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/components/store-image-sizing.d.ts +46 -0
- package/src/lib/components/store-image-sizing.js +53 -0
- package/src/lib/components/store-image-sizing.js.map +1 -0
- package/src/lib/components/wishlist.js +2 -1
- package/src/lib/components/wishlist.js.map +1 -1
- package/src/lib/declarations.console-server.js +10 -0
- package/src/lib/declarations.console-server.js.map +1 -1
- package/src/lib/model/commerce-tax-step.d.ts +123 -0
- package/src/lib/model/commerce-tax-step.js +185 -0
- package/src/lib/model/commerce-tax-step.js.map +1 -0
- package/src/lib/model/index.d.ts +1 -0
- package/src/lib/model/index.js +1 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/payments-setup-status.d.ts +40 -0
- package/src/lib/model/payments-setup-status.js +63 -0
- package/src/lib/model/payments-setup-status.js.map +1 -1
- package/src/lib/model/subscription-view.d.ts +19 -0
- package/src/lib/model/subscription-view.js +16 -0
- package/src/lib/model/subscription-view.js.map +1 -1
- package/src/lib/model/tap-to-pay-launch.d.ts +103 -0
- package/src/lib/model/tap-to-pay-launch.js +148 -0
- package/src/lib/model/tap-to-pay-launch.js.map +1 -0
- package/src/lib/plugin.js +12 -0
- package/src/lib/plugin.js.map +1 -1
- package/src/lib/server/billing-webhook.js +140 -116
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/checkout.js +15 -4
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/connect-return.d.ts +83 -0
- package/src/lib/server/connect-return.js +105 -0
- package/src/lib/server/connect-return.js.map +1 -0
- package/src/lib/server/connect.d.ts +18 -0
- package/src/lib/server/connect.js +60 -6
- package/src/lib/server/connect.js.map +1 -1
- package/src/lib/server/new-store-tax.d.ts +10 -0
- package/src/lib/server/new-store-tax.js +43 -0
- package/src/lib/server/new-store-tax.js.map +1 -0
- package/src/lib/server/pos-payment.js +3 -2
- package/src/lib/server/pos-payment.js.map +1 -1
- package/src/lib/server/pos-tax-step.d.ts +43 -0
- package/src/lib/server/pos-tax-step.js +55 -0
- package/src/lib/server/pos-tax-step.js.map +1 -0
- package/src/lib/server/pos-terminal-connection-token.d.ts +10 -1
- package/src/lib/server/pos-terminal-connection-token.js +18 -7
- package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
- package/src/lib/server/pos-terminal.d.ts +9 -0
- package/src/lib/server/pos-terminal.js +17 -1
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/server/tap-to-pay-launch-admin.d.ts +18 -0
- package/src/lib/server/tap-to-pay-launch-admin.js +204 -0
- package/src/lib/server/tap-to-pay-launch-admin.js.map +1 -0
- package/src/lib/server/tap-to-pay-launch.d.ts +114 -0
- package/src/lib/server/tap-to-pay-launch.js +408 -0
- package/src/lib/server/tap-to-pay-launch.js.map +1 -0
- package/src/lib/server.js +15 -0
- package/src/lib/server.js.map +1 -1
|
@@ -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, useEffect, useRef, useState } from 'react'\nimport { useSearchParams } from 'next/navigation'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { useFirestoreDoc } from '@aglyn/tenant-feature-instance'\nimport { useOrgPlan } from '@aglyn/tenant-feature-instance'\nimport {\n merchantPaymentsPlatformMode,\n merchantPaymentsStateFromProfile,\n} from '@aglyn/tenant-feature-instance/hooks/merchant-payments-state'\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'\nimport CheckoutTaxBlockedNotice from './checkout-tax-blocked-notice.component'\nimport {\n CONNECT_REFRESH_GUARD_MS,\n CONNECT_RETURN_PARAM,\n paymentsRequirementsNotice,\n paymentsReturnResult,\n} from '../../model/payments-setup-status'\n\n/** Where the card remembers it already continued an expired Stripe link, so it never loops. */\nconst REFRESH_GUARD_KEY = 'aglyn.commerce.connectRefreshAt'\n\n/** The connect return this page was opened with, read once and taken off the address. */\nfunction useConnectReturn(): 'done' | 'refresh' | null {\n const searchParams = useSearchParams()\n const [value] = useState<'done' | 'refresh' | null>(() => {\n const raw = searchParams?.get(CONNECT_RETURN_PARAM)\n return raw === 'done' || raw === 'refresh' ? raw : null\n })\n useEffect(() => {\n // Off the address once read, so a reload or a copied link does not show\n // the result again or mint another link.\n if (!value || typeof window === 'undefined') return\n try {\n const url = new URL(window.location.href)\n url.searchParams.delete(CONNECT_RETURN_PARAM)\n window.history.replaceState(window.history.state, '', url.toString())\n } catch {\n // The result still shows; only the address keeps the parameter.\n }\n }, [value])\n return value\n}\n\n/** Whether an expired link was already continued a moment ago (then the owner presses the button). */\nfunction refreshAlreadyContinued(now: number): boolean {\n try {\n const at = Number(window.sessionStorage.getItem(REFRESH_GUARD_KEY))\n if (Number.isFinite(at) && at > 0 && now - at < CONNECT_REFRESH_GUARD_MS) return true\n window.sessionStorage.setItem(REFRESH_GUARD_KEY, String(now))\n return false\n } catch {\n // No storage: the in-page guard still stops a repeat in this page.\n return false\n }\n}\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 setup status for the org\n * owner (the store's own Stripe account for every new setup) + 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 /** Back from Stripe (AGL-4245): `done` shows the result, `refresh` continues once. */\n const connectReturn = useConnectReturn()\n const [returnDismissed, setReturnDismissed] = useState(false)\n const refreshHandled = useRef(false)\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(org?.ownerUid && (user as any)?.uid === org.ownerUid)\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.\n *\n * The verdict is `merchantPaymentsStateFromProfile`, the console's copy of\n * the server's `merchantAccountReadiness`, against this deployment's mode,\n * so the chip and the checkout cannot disagree. This card used to count\n * ANY recorded mode as verified, so a test account recorded as test on a\n * live deployment read \"Charges enabled\" and offered only \"Refresh status\",\n * while every sale was refused.\n */\n const platformMode = merchantPaymentsPlatformMode()\n const liveDeployment = platformMode === 'live'\n const paymentsState =\n stripeState === 'loaded'\n ? merchantPaymentsStateFromProfile(profile, platformMode)\n : null\n /** The account is in the other Stripe mode from this deployment. */\n const modeMismatch = paymentsState === 'mode-mismatch'\n /** Charges on, mode never recorded, on a live deployment. */\n const modeUnverified = paymentsState === 'mode-unverified'\n const chargesEnabled = paymentsState === 'ready'\n /** The store's own Stripe account (direct charges), or none yet: every new setup is one. */\n const ownStripeAccount =\n stripeState === 'loaded' &&\n (profile?.stripeChargeModel === 'direct' || !profile?.stripeAccountId)\n const physicalPct = Aglyn.resolveTransactionFeePct(org, 'physical')\n const digitalPct = Aglyn.resolveTransactionFeePct(org, 'digital')\n const commerceEnabled = Aglyn.checkEntitlement(org, 'commerce')\n\n /**\n * `continue`: the owner asked to go on with Stripe setup, so a link the\n * route answers with is followed even for an account that can already\n * take payments (Stripe asking for more before a deadline, AGL-4245).\n * Without it this is the status check the button has always been.\n */\n const handleConnect = useCallback(async (intent?: 'continue') => {\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 if (intent === 'continue' && typeof payload.url === 'string' && payload.url) {\n return void window.location.assign(payload.url)\n }\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 /**\n * AN EXPIRED STRIPE LINK CONTINUES BY ITSELF, ONCE (AGL-4245). Stripe sends\n * the owner to `?connect=refresh` when the onboarding link had expired or\n * was already opened; the fix is a new link. Once per page and once per\n * two minutes in this tab, so a link that keeps failing leaves the owner\n * here with the button rather than bouncing between the two forever.\n */\n const ready = planReady && stripeState === 'loaded'\n useEffect(() => {\n if (connectReturn !== 'refresh' || !ready || !isOwner || refreshHandled.current) return\n refreshHandled.current = true\n if (refreshAlreadyContinued(Date.now())) return\n void handleConnect('continue')\n }, [connectReturn, ready, isOwner, handleConnect])\n\n /** What Stripe still needs, as a standing notice (AGL-4245). */\n const requirementsNotice =\n stripeState === 'loaded' && !modeMismatch && !modeUnverified\n ? paymentsRequirementsNotice(profile)\n : null\n /** The result of coming back from Stripe, from the live profile. */\n const returnResult =\n !returnDismissed &&\n stripeState === 'loaded' &&\n !modeMismatch &&\n !modeUnverified &&\n !requirementsNotice\n ? connectReturn === 'done'\n ? paymentsReturnResult(profile, chargesEnabled)\n : connectReturn === 'refresh' && !chargesEnabled\n ? {\n severity: 'info' as const,\n text: 'The Stripe page had expired. Continue setup to pick up where you left off.',\n continueSetup: true,\n }\n : null\n : null\n const continueButton = isOwner ? (\n <Button\n color=\"inherit\"\n size=\"small\"\n disabled={busy}\n onClick={() => void handleConnect('continue')}\n >\n {busy ? 'Opening Stripe…' : 'Continue setup'}\n </Button>\n ) : undefined\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 : modeMismatch\n ? liveDeployment\n ? 'Test account'\n : 'Live account'\n : modeUnverified\n ? 'Not verified'\n : 'Not set up'\n }\n color={\n stripeState === 'pending'\n ? 'default'\n : chargesEnabled\n ? 'success'\n : modeMismatch || 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 {\n 'Selling needs a paid plan. Choose one on Billing, then connect Stripe here.'\n }\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 {/* DIRECT CHARGES: the store's own Stripe account. Stripe bills\n its processing (and Stripe Tax) to that account itself, so\n nothing is passed through and the platform fee above is the\n whole of what the platform takes. Also the wording before\n payments are set up, because every new setup is that kind of\n account; an account that already exists keeps its own shape,\n so a platform-managed one keeps the pass-through paragraph. */}\n {ownStripeAccount ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Card processing is billed by Stripe straight to your Stripe ' +\n 'account at Stripe’s standard rates, online and on a card ' +\n 'reader, along with Stripe Tax if you use it. It is separate ' +\n `from the platform fee and is not a ${Aglyn.PLATFORM_BRAND_LEGAL_NAME} ` +\n 'charge. Refunds, disputes and payouts are handled on your ' +\n 'Stripe account.'}\n </Typography>\n ) : (\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 )}\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 account is PROVEN to be in the other Stripe mode: on a live\n deployment, a test account, which can never take a real payment and\n which the live key cannot even read. Set up payments creates a new\n account in this deployment's mode (the connect route keeps the old\n id on the profile), so the alert names that as the fix.\n */}\n {modeMismatch ? (\n <Alert severity=\"error\">\n {liveDeployment\n ? 'The connected Stripe account is a test account, so this ' +\n 'store can’t take real payments and every sale is refused. ' +\n 'Live payments need a live Stripe account: set up payments ' +\n 'to connect one.'\n : 'The connected Stripe account is a live account, and this ' +\n 'site takes test payments only, so every sale is refused. ' +\n 'Set up payments to connect a test 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 {/*\n BACK FROM STRIPE, AND WHAT IT STILL NEEDS (AGL-4245). The return\n used to land on Catalog with nothing reading it, so finishing (or\n leaving) Stripe's form showed nothing. Both read the live profile,\n so the words change by themselves when Stripe's update lands. The\n standing notice wins over the return result: one message, one\n button.\n */}\n {requirementsNotice ? (\n <Alert\n severity={requirementsNotice.severity}\n variant=\"outlined\"\n action={requirementsNotice.continueSetup ? continueButton : undefined}\n >\n {requirementsNotice.text}\n </Alert>\n ) : null}\n {returnResult ? (\n <Alert\n severity={returnResult.severity}\n onClose={returnResult.continueSetup ? undefined : () => setReturnDismissed(true)}\n action={returnResult.continueSetup ? continueButton : undefined}\n >\n {returnResult.text}\n </Alert>\n ) : null}\n <CheckoutTaxBlockedNotice hostId={hostId} />\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={() => void 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","useEffect","useRef","useState","useSearchParams","useFirestore","useUser","useFirestoreDoc","useOrgPlan","merchantPaymentsPlatformMode","merchantPaymentsStateFromProfile","pluginDocsHelp","authorizedFetch","PrerequisiteNotice","useCommerceEntitlement","CheckoutTaxBlockedNotice","CONNECT_REFRESH_GUARD_MS","CONNECT_RETURN_PARAM","paymentsRequirementsNotice","paymentsReturnResult","REFRESH_GUARD_KEY","useConnectReturn","searchParams","value","raw","get","window","url","URL","location","href","delete","history","replaceState","state","toString","refreshAlreadyContinued","now","at","Number","sessionStorage","getItem","isFinite","setItem","String","PAYMENTS_SETTINGS_ANCHOR","PaymentsSettingsCard","props","profile","hostId","firestore","data","user","enqueueSnackbar","busy","setBusy","dashboardUrl","setDashboardUrl","connectReturn","returnDismissed","setReturnDismissed","refreshHandled","org","ready","planReady","retryNonce","setRetryNonce","upgradeHref","ownerUid","undefined","status","profileStatus","isOwner","Boolean","uid","stripeState","platformMode","liveDeployment","paymentsState","modeMismatch","modeUnverified","chargesEnabled","ownStripeAccount","stripeChargeModel","stripeAccountId","physicalPct","resolveTransactionFeePct","digitalPct","commerceEnabled","checkEntitlement","handleConnect","intent","response","method","headers","body","JSON","stringify","payload","json","variant","persist","ok","error","allowDuplicate","payoutsBlocked","payoutsEnabled","assign","console","current","Date","requirementsNotice","returnResult","severity","text","continueSetup","continueButton","color","size","disabled","onClick","id","header","help","anchor","contentGutterX","contentGutterY","spacing","direction","sx","alignItems","flex","label","action","n","actionLabel","PLATFORM_BRAND_LEGAL_NAME","component","SALE_PROCESSING_PERCENT","SALE_PROCESSING_FIXED_CENTS","CONNECT_PAYOUT_PERCENT","CONNECT_PAYOUT_FIXED_CENTS","STRIPE_TAX_PERCENT","onClose","lastPayoutFailureAtMs","lastPayoutFailureCents","toFixed","toLocaleDateString","lastPayoutFailureReason","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,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAChE,SAASC,eAAe,QAAQ,kBAAiB;AACjD,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SAASC,eAAe,QAAQ,iCAAgC;AAChE,SAASC,UAAU,QAAQ,iCAAgC;AAC3D,SACEC,4BAA4B,EAC5BC,gCAAgC,QAC3B,+DAA8D;AACrE,SAASC,cAAc,QAAQ,eAAc;AAC7C,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,kB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AI;gCAAEoB,WAAW;4BAAa;sCAE7BpE,iBACG,mBACA3B,OACE,oBACA;;wBAUPE,6BACC,KAAC7D;4BACC2H,MAAK;4BACLlB,SAAQ;4BACRiB,OAAM;4BACNvF,MAAM0B;4BACN8F,QAAO;4BACPC,KAAI;4BACJtB,IAAI;gCAAEoB,WAAW;4BAAa;sCAE7B;6BAED;;mCAGN,KAACvJ;oBAAWsG,SAAQ;oBAAUiB,OAAM;8BACjC;;;;;AAMb;AACAvE,qBAAqB0G,WAAW,GAAG;AAEnC,eAAe1G,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, useEffect, useRef, useState } from 'react'\nimport { useSearchParams } from 'next/navigation'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { useFirestoreDoc } from '@aglyn/tenant-feature-instance'\nimport { useOrgPlan } from '@aglyn/tenant-feature-instance'\nimport {\n merchantPaymentsPlatformMode,\n merchantPaymentsStateFromProfile,\n} from '@aglyn/tenant-feature-instance/hooks/merchant-payments-state'\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'\nimport CheckoutTaxBlockedNotice from './checkout-tax-blocked-notice.component'\nimport {\n CONNECT_REFRESH_GUARD_MS,\n CONNECT_RETURN_PARAM,\n paymentsRequirementsNotice,\n paymentsReturnResult,\n recheckPayments,\n stripeStillChecking,\n type PaymentsSyncAnswer,\n} from '../../model/payments-setup-status'\n\n/** Where the card remembers it already continued an expired Stripe link, so it never loops. */\nconst REFRESH_GUARD_KEY = 'aglyn.commerce.connectRefreshAt'\n\n/** The connect return this page was opened with, read once and taken off the address. */\nfunction useConnectReturn(): 'done' | 'refresh' | null {\n const searchParams = useSearchParams()\n const [value] = useState<'done' | 'refresh' | null>(() => {\n const raw = searchParams?.get(CONNECT_RETURN_PARAM)\n return raw === 'done' || raw === 'refresh' ? raw : null\n })\n useEffect(() => {\n // Off the address once read, so a reload or a copied link does not show\n // the result again or mint another link.\n if (!value || typeof window === 'undefined') return\n try {\n const url = new URL(window.location.href)\n url.searchParams.delete(CONNECT_RETURN_PARAM)\n window.history.replaceState(window.history.state, '', url.toString())\n } catch {\n // The result still shows; only the address keeps the parameter.\n }\n }, [value])\n return value\n}\n\n/** Whether the page is in view: a hidden tab asks Stripe nothing, and asks again when it comes back. */\nfunction usePageVisible(): boolean {\n const [visible, setVisible] = useState(\n () => typeof document === 'undefined' || document.visibilityState !== 'hidden',\n )\n useEffect(() => {\n if (typeof document === 'undefined') return\n const update = () => setVisible(document.visibilityState !== 'hidden')\n document.addEventListener('visibilitychange', update)\n return () => document.removeEventListener('visibilitychange', update)\n }, [])\n return visible\n}\n\n/** Whether an expired link was already continued a moment ago (then the owner presses the button). */\nfunction refreshAlreadyContinued(now: number): boolean {\n try {\n const at = Number(window.sessionStorage.getItem(REFRESH_GUARD_KEY))\n if (Number.isFinite(at) && at > 0 && now - at < CONNECT_REFRESH_GUARD_MS) return true\n window.sessionStorage.setItem(REFRESH_GUARD_KEY, String(now))\n return false\n } catch {\n // No storage: the in-page guard still stops a repeat in this page.\n return false\n }\n}\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 setup status for the org\n * owner (the store's own Stripe account for every new setup) + 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 /** Back from Stripe (AGL-4245): `done` shows the result, `refresh` continues once. */\n const connectReturn = useConnectReturn()\n const [returnDismissed, setReturnDismissed] = useState(false)\n const refreshHandled = useRef(false)\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(org?.ownerUid && (user as any)?.uid === org.ownerUid)\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.\n *\n * The verdict is `merchantPaymentsStateFromProfile`, the console's copy of\n * the server's `merchantAccountReadiness`, against this deployment's mode,\n * so the chip and the checkout cannot disagree. This card used to count\n * ANY recorded mode as verified, so a test account recorded as test on a\n * live deployment read \"Charges enabled\" and offered only \"Refresh status\",\n * while every sale was refused.\n */\n const platformMode = merchantPaymentsPlatformMode()\n const liveDeployment = platformMode === 'live'\n const paymentsState =\n stripeState === 'loaded'\n ? merchantPaymentsStateFromProfile(profile, platformMode)\n : null\n /** The account is in the other Stripe mode from this deployment. */\n const modeMismatch = paymentsState === 'mode-mismatch'\n /** Charges on, mode never recorded, on a live deployment. */\n const modeUnverified = paymentsState === 'mode-unverified'\n const chargesEnabled = paymentsState === 'ready'\n /** The store's own Stripe account (direct charges), or none yet: every new setup is one. */\n const ownStripeAccount =\n stripeState === 'loaded' &&\n (profile?.stripeChargeModel === 'direct' || !profile?.stripeAccountId)\n const physicalPct = Aglyn.resolveTransactionFeePct(org, 'physical')\n const digitalPct = Aglyn.resolveTransactionFeePct(org, 'digital')\n const commerceEnabled = Aglyn.checkEntitlement(org, 'commerce')\n\n /**\n * `continue`: the owner asked to go on with Stripe setup, so a link the\n * route answers with is followed even for an account that can already\n * take payments (Stripe asking for more before a deadline, AGL-4245).\n * Without it this is the status check the button has always been.\n */\n const handleConnect = useCallback(async (intent?: 'continue') => {\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 if (intent === 'continue' && typeof payload.url === 'string' && payload.url) {\n return void window.location.assign(payload.url)\n }\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 /**\n * AN EXPIRED STRIPE LINK CONTINUES BY ITSELF, ONCE (AGL-4245). Stripe sends\n * the owner to `?connect=refresh` when the onboarding link had expired or\n * was already opened; the fix is a new link. Once per page and once per\n * two minutes in this tab, so a link that keeps failing leaves the owner\n * here with the button rather than bouncing between the two forever.\n */\n const ready = planReady && stripeState === 'loaded'\n useEffect(() => {\n if (connectReturn !== 'refresh' || !ready || !isOwner || refreshHandled.current) return\n refreshHandled.current = true\n if (refreshAlreadyContinued(Date.now())) return\n void handleConnect('continue')\n }, [connectReturn, ready, isOwner, handleConnect])\n\n /**\n * THE RESULT IS READ FROM STRIPE, AND READ AGAIN WHILE STRIPE CHECKS\n * (AGL-4061). The card follows the live profile, which the\n * `account.updated` webhook keeps; a webhook that is late, or missing on a\n * local stack, left it saying Stripe still needed details the owner had\n * just given, or \"Not set up\" for an account Stripe had enabled. So the\n * owner's card asks Stripe (`sync`, which records what Stripe says now and\n * mints nothing) back from Stripe's form (`?connect=done`) and on opening\n * for a store with an account that is not ready; while Stripe is still\n * checking it asks again (quick at first, then every 30 seconds, for up to\n * 15 minutes) while the page is in view, and after that says Stripe is\n * still checking, with Check again. The profile listen redraws the rest.\n */\n const pageVisible = usePageVisible()\n const [recheckRun, setRecheckRun] = useState(0)\n const [syncing, setSyncing] = useState(false)\n const [syncAnswer, setSyncAnswer] = useState<PaymentsSyncAnswer | null>(null)\n const [recheckWaitedOut, setRecheckWaitedOut] = useState(false)\n const [rechecking, setRechecking] = useState(false)\n /** The store has a Stripe account that is not ready: worth asking Stripe about. */\n const accountNotReady = paymentsState === 'charges-disabled'\n const openSynced = useRef(false)\n useEffect(() => {\n if (!ready || !isOwner || openSynced.current || connectReturn === 'refresh') return\n if (connectReturn !== 'done' && !accountNotReady) return\n openSynced.current = true\n setRecheckRun((run) => run + 1)\n }, [connectReturn, ready, isOwner, accountNotReady])\n // Back in view with the account still not ready: Stripe may have answered meanwhile.\n const wasVisible = useRef(pageVisible)\n useEffect(() => {\n const cameBack = pageVisible && !wasVisible.current\n wasVisible.current = pageVisible\n if (cameBack && ready && isOwner && accountNotReady && openSynced.current) {\n setRecheckRun((run) => run + 1)\n }\n }, [pageVisible, ready, isOwner, accountNotReady])\n // The signed-in person, read when a check is sent: a fresh user object must not restart a run.\n const userRef = useRef(user)\n userRef.current = user\n useEffect(() => {\n if (recheckRun === 0 || !pageVisible) return\n let cancelled = false\n const timers = new Set<ReturnType<typeof setTimeout>>()\n const wakers = new Set<() => void>()\n setRechecking(true)\n setRecheckWaitedOut(false)\n void recheckPayments({\n sync: async () => {\n const response = await authorizedFetch(userRef.current, '/api/commerce/connect', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, sync: true }),\n })\n if (!response.ok) throw new Error(`Payments status check answered ${response.status}`)\n return (await response.json()) as PaymentsSyncAnswer\n },\n onChecking: (checking) => {\n if (!cancelled) setSyncing(checking)\n },\n onStatus: (answer) => {\n if (!cancelled) setSyncAnswer(answer)\n },\n cancelled: () => cancelled,\n // Leaving ends the wait at once rather than after it.\n sleep: (ms) =>\n new Promise<void>((done) => {\n const timer = setTimeout(() => {\n timers.delete(timer)\n wakers.delete(done)\n done()\n }, ms)\n timers.add(timer)\n wakers.add(done)\n }),\n })\n .then((end) => {\n if (!cancelled && end === 'waited-out') setRecheckWaitedOut(true)\n })\n .catch((error) => console.warn('Payments status check with Stripe failed', error))\n .finally(() => {\n if (!cancelled) setRechecking(false)\n })\n return () => {\n cancelled = true\n timers.forEach(clearTimeout)\n wakers.forEach((wake) => wake())\n setSyncing(false)\n setRechecking(false)\n }\n }, [recheckRun, pageVisible, hostId])\n /** What Stripe last said, while the profile still says not ready: it is checking the owner's details. */\n const stripeVerifying =\n stripeState === 'loaded' &&\n !chargesEnabled &&\n !modeMismatch &&\n !modeUnverified &&\n stripeStillChecking(syncAnswer)\n /** The re-checks ran out while Stripe was still checking, and nothing is asking now. */\n const stripePending = stripeVerifying && recheckWaitedOut && !rechecking\n /** Asking Stripe now, or Stripe still checking within the run: never a stale \"Not set up\". */\n const checkingStripe =\n stripeState === 'loaded' &&\n !chargesEnabled &&\n !modeMismatch &&\n !modeUnverified &&\n ((syncing && !syncAnswer) || (stripeVerifying && !stripePending))\n\n /** What Stripe still needs, as a standing notice (AGL-4245). */\n const requirementsNotice =\n stripeState === 'loaded' && !modeMismatch && !modeUnverified\n ? paymentsRequirementsNotice(profile)\n : null\n /** The result of coming back from Stripe, from the live profile; Stripe's own word on checking wins over it. */\n const returnResult =\n !returnDismissed &&\n !stripeVerifying &&\n stripeState === 'loaded' &&\n !modeMismatch &&\n !modeUnverified &&\n !requirementsNotice\n ? connectReturn === 'done'\n ? paymentsReturnResult(profile, chargesEnabled)\n : connectReturn === 'refresh' && !chargesEnabled\n ? {\n severity: 'info' as const,\n text: 'The Stripe page had expired. Continue setup to pick up where you left off.',\n continueSetup: true,\n }\n : null\n : null\n const continueButton = isOwner ? (\n <Button\n color=\"inherit\"\n size=\"small\"\n disabled={busy}\n onClick={() => void handleConnect('continue')}\n >\n {busy ? 'Opening Stripe…' : 'Continue setup'}\n </Button>\n ) : undefined\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' || checkingStripe\n ? 'Checking…'\n : chargesEnabled\n ? 'Charges enabled'\n : modeMismatch\n ? liveDeployment\n ? 'Test account'\n : 'Live account'\n : modeUnverified\n ? 'Not verified'\n : stripePending\n ? 'Pending'\n : 'Not set up'\n }\n color={\n stripeState === 'pending'\n ? 'default'\n : checkingStripe || stripePending\n ? 'info'\n : chargesEnabled\n ? 'success'\n : modeMismatch || 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 {\n 'Selling needs a paid plan. Choose one on Billing, then connect Stripe here.'\n }\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 {/* DIRECT CHARGES: the store's own Stripe account. Stripe bills\n its processing (and Stripe Tax) to that account itself, so\n nothing is passed through and the platform fee above is the\n whole of what the platform takes. Also the wording before\n payments are set up, because every new setup is that kind of\n account; an account that already exists keeps its own shape,\n so a platform-managed one keeps the pass-through paragraph. */}\n {ownStripeAccount ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Card processing is billed by Stripe straight to your Stripe ' +\n 'account at Stripe’s standard rates, online and on a card ' +\n 'reader, along with Stripe Tax if you use it. It is separate ' +\n `from the platform fee and is not a ${Aglyn.PLATFORM_BRAND_LEGAL_NAME} ` +\n 'charge. Refunds, disputes and payouts are handled on your ' +\n 'Stripe account.'}\n </Typography>\n ) : (\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 )}\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 account is PROVEN to be in the other Stripe mode: on a live\n deployment, a test account, which can never take a real payment and\n which the live key cannot even read. Set up payments creates a new\n account in this deployment's mode (the connect route keeps the old\n id on the profile), so the alert names that as the fix.\n */}\n {modeMismatch ? (\n <Alert severity=\"error\">\n {liveDeployment\n ? 'The connected Stripe account is a test account, so this ' +\n 'store can’t take real payments and every sale is refused. ' +\n 'Live payments need a live Stripe account: set up payments ' +\n 'to connect one.'\n : 'The connected Stripe account is a live account, and this ' +\n 'site takes test payments only, so every sale is refused. ' +\n 'Set up payments to connect a test 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 {/*\n BACK FROM STRIPE, AND WHAT IT STILL NEEDS (AGL-4245). The return\n used to land on Catalog with nothing reading it, so finishing (or\n leaving) Stripe's form showed nothing. Both read the live profile,\n so the words change by themselves when Stripe's update lands. The\n standing notice wins over the return result: one message, one\n button.\n */}\n {requirementsNotice ? (\n <Alert\n severity={requirementsNotice.severity}\n variant=\"outlined\"\n action={requirementsNotice.continueSetup ? continueButton : undefined}\n >\n {requirementsNotice.text}\n </Alert>\n ) : null}\n {stripeVerifying && !requirementsNotice ? (\n <Alert\n severity=\"info\"\n action={\n stripePending ? (\n <Button color=\"inherit\" size=\"small\" onClick={() => setRecheckRun((run) => run + 1)}>\n {'Check again'}\n </Button>\n ) : undefined\n }\n >\n {stripePending\n ? 'Stripe is still checking your details. Check again in a few minutes.'\n : 'Stripe is checking your details. This usually takes a minute.'}\n </Alert>\n ) : null}\n {returnResult ? (\n <Alert\n severity={returnResult.severity}\n onClose={returnResult.continueSetup ? undefined : () => setReturnDismissed(true)}\n action={returnResult.continueSetup ? continueButton : undefined}\n >\n {returnResult.text}\n </Alert>\n ) : null}\n <CheckoutTaxBlockedNotice hostId={hostId} />\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 {/* While Stripe checks what the owner already sent there is nothing to set up: Check again is the action. */}\n {stripeVerifying ? null : (\n <Button\n size=\"small\"\n variant={chargesEnabled ? 'text' : 'contained'}\n color=\"primary\"\n disabled={busy}\n onClick={() => void 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 {/*\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","useEffect","useRef","useState","useSearchParams","useFirestore","useUser","useFirestoreDoc","useOrgPlan","merchantPaymentsPlatformMode","merchantPaymentsStateFromProfile","pluginDocsHelp","authorizedFetch","PrerequisiteNotice","useCommerceEntitlement","CheckoutTaxBlockedNotice","CONNECT_REFRESH_GUARD_MS","CONNECT_RETURN_PARAM","paymentsRequirementsNotice","paymentsReturnResult","recheckPayments","stripeStillChecking","REFRESH_GUARD_KEY","useConnectReturn","searchParams","value","raw","get","window","url","URL","location","href","delete","history","replaceState","state","toString","usePageVisible","visible","setVisible","document","visibilityState","update","addEventListener","removeEventListener","refreshAlreadyContinued","now","at","Number","sessionStorage","getItem","isFinite","setItem","String","PAYMENTS_SETTINGS_ANCHOR","PaymentsSettingsCard","props","profile","hostId","firestore","data","user","enqueueSnackbar","busy","setBusy","dashboardUrl","setDashboardUrl","connectReturn","returnDismissed","setReturnDismissed","refreshHandled","org","ready","planReady","retryNonce","setRetryNonce","upgradeHref","ownerUid","undefined","status","profileStatus","isOwner","Boolean","uid","stripeState","platformMode","liveDeployment","paymentsState","modeMismatch","modeUnverified","chargesEnabled","ownStripeAccount","stripeChargeModel","stripeAccountId","physicalPct","resolveTransactionFeePct","digitalPct","commerceEnabled","checkEntitlement","handleConnect","intent","response","method","headers","body","JSON","stringify","payload","json","variant","persist","ok","error","allowDuplicate","payoutsBlocked","payoutsEnabled","assign","console","current","Date","pageVisible","recheckRun","setRecheckRun","syncing","setSyncing","syncAnswer","setSyncAnswer","recheckWaitedOut","setRecheckWaitedOut","rechecking","setRechecking","accountNotReady","openSynced","run","wasVisible","cameBack","userRef","cancelled","timers","Set","wakers","sync","Error","onChecking","checking","onStatus","answer","sleep","ms","Promise","done","timer","setTimeout","add","then","end","catch","warn","finally","forEach","clearTimeout","wake","stripeVerifying","stripePending","checkingStripe","requirementsNotice","returnResult","severity","text","continueSetup","continueButton","color","size","disabled","onClick","id","header","help","anchor","contentGutterX","contentGutterY","spacing","direction","sx","alignItems","flex","label","action","n","actionLabel","PLATFORM_BRAND_LEGAL_NAME","component","SALE_PROCESSING_PERCENT","SALE_PROCESSING_FIXED_CENTS","CONNECT_PAYOUT_PERCENT","CONNECT_PAYOUT_FIXED_CENTS","STRIPE_TAX_PERCENT","onClose","lastPayoutFailureAtMs","lastPayoutFailureCents","toFixed","toLocaleDateString","lastPayoutFailureReason","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,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAChE,SAASC,eAAe,QAAQ,kBAAiB;AACjD,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SAASC,eAAe,QAAQ,iCAAgC;AAChE,SAASC,UAAU,QAAQ,iCAAgC;A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AoB"}
|
|
@@ -82,6 +82,12 @@ export interface PosRegisterContext {
|
|
|
82
82
|
label: string;
|
|
83
83
|
lookup: boolean;
|
|
84
84
|
}>;
|
|
85
|
+
/** Whether the store has decided how it handles sales tax (AGL-4061); absent from an older server. */
|
|
86
|
+
taxDecided?: boolean;
|
|
87
|
+
/** Whether this person may decide it ("Edit the site"). */
|
|
88
|
+
canDecideTax?: boolean;
|
|
89
|
+
/** Decided, but the register refuses every sale anyway (AGL-2145), in the refusal's words. */
|
|
90
|
+
taxRefusal?: string | null;
|
|
85
91
|
}
|
|
86
92
|
/** A store-credit account a staff lookup found (AGL-3640). */
|
|
87
93
|
export interface PosCreditAccount {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../../libs/plugins/commerce/src/lib/components/console/pos/pos-api.ts"],"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 { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport type * as CommerceModel from '../../../model'\nimport type { PosRegisterSettings } from '../../../plugin-config'\n\n/**\n * The register's client half (AGL-3607): one place that knows the routes, so\n * the components ask \"take cash\" rather than building requests. Every call\n * that starts a payment carries the attempt key it is given; the server\n * derives the payment from it, so a retried press finds the same payment.\n */\n\n/** The open sale as the server reports it after every change. */\nexport interface PosSaleSummary {\n orderId: string\n status: string\n totalCents: number\n paidCents: number\n dueCents: number\n tenderableCents: number\n tipCents: number\n payments: Array<{\n id: string\n method: CommerceModel.OrderPaymentMethod\n amountCents: number\n tipCents?: number\n status: CommerceModel.OrderPaymentStatus\n cardBrand?: string\n last4?: string\n changeCents?: number\n checkoutUrl?: string\n readerId?: string\n /** What a store-credit payment's provider calls it (AGL-3640). */\n creditLabel?: string\n failureMessage?: string\n livemode?: boolean\n }>\n}\n\nexport interface PosTenderResult {\n sale: PosSaleSummary\n paymentId?: string\n completed: boolean\n clientSecret?: string\n paymentIntentId?: string\n /**\n * For a typed card on a store that sells on its own Stripe account: the\n * account the intent lives on, which the Payment Element loads Stripe for.\n */\n stripeAccount?: string\n}\n\nexport interface PosRegisterContext {\n settings: PosRegisterSettings\n terminal: { available: boolean; testMode: boolean }\n readers: Array<{\n id: string\n label: string\n registerId: string | null\n status: string\n livemode: boolean\n }>\n publishableKey: string\n smsReceipts: boolean\n /** Store credit other plugins keep, taken as a tender (AGL-3640). */\n credits?: Array<{ providerId: string; label: string; lookup: boolean }>\n}\n\n/** A store-credit account a staff lookup found (AGL-3640). */\nexport interface PosCreditAccount {\n reference: string\n label: string\n last4: string\n availableCents: number\n detail?: string\n}\n\ntype User = Parameters<typeof authorizedFetch>[0]\n\nexport class PosRequestError extends Error {\n constructor(\n message: string,\n readonly status: number,\n ) {\n super(message)\n }\n}\n\nasync function call<T>(\n user: User,\n route: string,\n body: Record<string, unknown>,\n options: { attemptKey?: string; method?: 'GET' | 'POST' } = {},\n): Promise<T> {\n const method = options.method ?? 'POST'\n const url =\n method === 'GET'\n ? `${route}?${new URLSearchParams(\n Object.entries(body).map(([key, value]) => [key, String(value)]),\n ).toString()}`\n : route\n const response = await authorizedFetch(user, url, {\n method,\n headers: {\n ...(method === 'POST' ? { 'Content-Type': 'application/json' } : {}),\n ...(options.attemptKey ? { 'Idempotency-Key': options.attemptKey } : {}),\n },\n ...(method === 'POST' ? { body: JSON.stringify(body) } : {}),\n })\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n throw new PosRequestError(String(payload?.error ?? 'Something went wrong'), response.status)\n }\n return payload as T\n}\n\n/** A fresh attempt key, for one press of one tender. */\nexport function newAttemptKey(): string {\n return (\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now()}-${Math.random().toString(36).slice(2)}`\n )\n}\n\nexport function posRegisterContext(user: User, hostId: string) {\n return call<PosRegisterContext>(user, '/api/commerce/pos-payment', { action: 'context', hostId }, { method: 'GET' })\n}\n\n/** Prices the basket on the server and opens a sale with an empty ledger. */\nexport function openPosSale(\n user: User,\n attemptKey: string,\n body: {\n hostId: string\n registerId: string\n lines: unknown[]\n discountPct: number\n customerEmail?: string\n /** The person the register's customer lookup attached (AGL-3609). */\n customer?: unknown\n /** A PIN-switched cashier's signed assertion (AGL-3609). */\n cashierAssertion?: string\n locationId?: string\n },\n) {\n return call<{ orderId: string; totals: CommerceModel.OrderTotals; dueCents: number; stockWarnings?: unknown[] }>(\n user,\n '/api/commerce/pos-order',\n { ...body, payment: 'open' },\n { attemptKey },\n )\n}\n\nexport type PosTenderAction =\n | 'cash'\n | 'gift-card'\n | 'credit'\n | 'folio'\n | 'card-present'\n | 'card-present-sdk'\n | 'card-keyed'\n | 'card-link'\n | 'status'\n | 'cancel'\n | 'retry'\n | 'simulate'\n | 'void'\n | 'receipt'\n\nexport function posTender(\n user: User,\n hostId: string,\n orderId: string,\n action: PosTenderAction,\n body: Record<string, unknown> = {},\n attemptKey?: string,\n) {\n return call<PosTenderResult>(\n user,\n '/api/commerce/pos-payment',\n { ...body, action, hostId, orderId },\n attemptKey ? { attemptKey } : {},\n )\n}\n\nexport function posGiftCardBalance(user: User, hostId: string, code: string) {\n return call<{ availableCents: number; frozen: boolean; voided: boolean; last4: string }>(\n user,\n '/api/commerce/pos-payment',\n { action: 'gift-card-balance', hostId, code },\n )\n}\n\n/** Finds store-credit accounts by a customer's email or code (AGL-3640). */\nexport function posCreditLookup(user: User, hostId: string, providerId: string, query: string) {\n return call<{ providerId: string; accounts: PosCreditAccount[] }>(user, '/api/commerce/pos-payment', {\n action: 'credit-lookup',\n hostId,\n providerId,\n query,\n })\n}\n\nexport function posDisplayCall<T = any>(\n user: User,\n body: Record<string, unknown>,\n method: 'GET' | 'POST' = 'POST',\n) {\n return call<T>(user, '/api/commerce/pos-display', body, { method })\n}\n\n/** The register's side of the self-service kiosk (AGL-3623): its queue of \"pay at counter\" orders. */\nexport function posKioskCall<T = any>(\n user: User,\n body: Record<string, unknown>,\n method: 'GET' | 'POST' = 'POST',\n) {\n return call<T>(user, '/api/commerce/pos-kiosk', body, { method })\n}\n\nexport function posReadersCall<T = any>(user: User, body: Record<string, unknown>) {\n return call<T>(user, '/api/commerce/pos-readers', body)\n}\n\n/** Cents as the register shows them. */\nexport const usd = (cents: number) => `$${(Math.max(0, cents) / 100).toFixed(2)}`\n\n/** A dollar string the cashier typed, as whole cents (NaN-safe, never negative). */\nexport function centsFromInput(value: string): number {\n const number = Math.round(Number(String(value).replace(/[^0-9.]/g, '')) * 100)\n return Number.isFinite(number) && number > 0 ? number : 0\n}\n\n/*==========================================\n * THE NATIVE BRIDGE (AGL-3618).\n *\n * The POS companion app loads this register in a WebView and injects\n * `window.AglynPosBridge`. When it is there, the register offers a third\n * card option — Tap to Pay or a Bluetooth reader — and hands the app a\n * PaymentIntent the SERVER created (`card-present-sdk`); the app collects\n * the card with the Stripe Terminal SDK and the register settles it exactly\n * like a smart-reader payment, by asking the server.\n *=========================================*/\n\nexport interface AglynPosBridge {\n collectCardPayment(input: {\n paymentIntentId: string\n clientSecret: string\n amountCents: number\n }): Promise<{ status: 'collected' | 'canceled' | 'failed'; message?: string }>\n}\n\nexport function posNativeBridge(): AglynPosBridge | null {\n const bridge = (globalThis as { AglynPosBridge?: AglynPosBridge }).AglynPosBridge\n return bridge && typeof bridge.collectCardPayment === 'function' ? bridge : null\n}\n"],"names":["authorizedFetch","PosRequestError","Error","message","status","call","user","route","body","options","method","url","URLSearchParams","Object","entries","map","key","value","String","toString","response","headers","attemptKey","JSON","stringify","payload","json","catch","ok","error","newAttemptKey","globalThis","crypto","randomUUID","Date","now","Math","random","slice","posRegisterContext","hostId","action","openPosSale","payment","posTender","orderId","posGiftCardBalance","code","posCreditLookup","providerId","query","posDisplayCall","posKioskCall","posReadersCall","usd","cents","max","toFixed","centsFromInput","number","round","Number","replace","isFinite","posNativeBridge","bridge","AglynPosBridge","collectCardPayment"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,eAAe,QAAQ,2CAA0C;AA8E1E,OAAO,MAAMC,wBAAwBC;IACnC,YACEC,OAAe,EACf,AAASC,MAAc,CACvB;QACA,KAAK,CAACD,eAFGC,SAAAA;IAGX;AACF;AAEA,eAAeC,KACbC,IAAU,EACVC,KAAa,EACbC,IAA6B,EAC7BC,UAA4D,CAAC,CAAC;QAE/CA;IAAf,MAAMC,UAASD,kBAAAA,QAAQC,MAAM,YAAdD,kBAAkB;IACjC,MAAME,MACJD,WAAW,QACP,GAAGH,MAAM,CAAC,EAAE,IAAIK,gBACdC,OAAOC,OAAO,CAACN,MAAMO,GAAG,CAAC,CAAC,CAACC,KAAKC,MAAM,GAAK;YAACD;YAAKE,OAAOD;SAAO,GAC/DE,QAAQ,IAAI,GACdZ;IACN,MAAMa,WAAW,MAAMpB,gBAAgBM,MAAMK,KAAK;QAChDD;QACAW,SAAS,aACHX,WAAW,SAAS;YAAE,gBAAgB;QAAmB,IAAI,CAAC,GAC9DD,QAAQa,UAAU,GAAG;YAAE,mBAAmBb,QAAQa,UAAU;QAAC,IAAI,CAAC;OAEpEZ,WAAW,SAAS;QAAEF,MAAMe,KAAKC,SAAS,CAAChB;IAAM,IAAI,CAAC;IAE5D,MAAMiB,UAAU,MAAML,SAASM,IAAI,GAAGC,KAAK,CAAC,IAAO,CAAA,CAAC,CAAA;IACpD,IAAI,CAACP,SAASQ,EAAE,EAAE;;QAChB,MAAM,IAAI3B,gBAAgBiB,eAAOO,2BAAAA,QAASI,KAAK,mBAAI,yBAAyBT,SAAShB,MAAM;IAC7F;IACA,OAAOqB;AACT;AAEA,sDAAsD,GACtD,OAAO,SAASK;;QAEZC,+BAAAA;IADF,gBACEA,qBAAAA,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IAE/B,OAAOL,KAAQC,MAAM,2BAA2BE,MAAM;QAAEE;IAAO;AACjE;AAEA,OAAO,SAAS2C,eAAwB/C,IAAU,EAAEE,IAA6B;IAC/E,OAAOH,KAAQC,MAAM,6BAA6BE;AACpD;AAEA,sCAAsC,GACtC,OAAO,MAAM8C,MAAM,CAACC,QAAkB,CAAC,CAAC,EAAE,AAACnB,CAAAA,KAAKoB,GAAG,CAAC,GAAGD,SAAS,GAAE,EAAGE,OAAO,CAAC,IAAI,CAAA;AAEjF,kFAAkF,GAClF,OAAO,SAASC,eAAezC,KAAa;IAC1C,MAAM0C,SAASvB,KAAKwB,KAAK,CAACC,OAAO3C,OAAOD,OAAO6C,OAAO,CAAC,YAAY,OAAO;IAC1E,OAAOD,OAAOE,QAAQ,CAACJ,WAAWA,SAAS,IAAIA,SAAS;AAC1D;AAqBA,OAAO,SAASK;IACd,MAAMC,SAAS,AAAClC,WAAmDmC,cAAc;IACjF,OAAOD,UAAU,OAAOA,OAAOE,kBAAkB,KAAK,aAAaF,SAAS;AAC9E"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../../libs/plugins/commerce/src/lib/components/console/pos/pos-api.ts"],"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 { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport type * as CommerceModel from '../../../model'\nimport type { PosRegisterSettings } from '../../../plugin-config'\n\n/**\n * The register's client half (AGL-3607): one place that knows the routes, so\n * the components ask \"take cash\" rather than building requests. Every call\n * that starts a payment carries the attempt key it is given; the server\n * derives the payment from it, so a retried press finds the same payment.\n */\n\n/** The open sale as the server reports it after every change. */\nexport interface PosSaleSummary {\n orderId: string\n status: string\n totalCents: number\n paidCents: number\n dueCents: number\n tenderableCents: number\n tipCents: number\n payments: Array<{\n id: string\n method: CommerceModel.OrderPaymentMethod\n amountCents: number\n tipCents?: number\n status: CommerceModel.OrderPaymentStatus\n cardBrand?: string\n last4?: string\n changeCents?: number\n checkoutUrl?: string\n readerId?: string\n /** What a store-credit payment's provider calls it (AGL-3640). */\n creditLabel?: string\n failureMessage?: string\n livemode?: boolean\n }>\n}\n\nexport interface PosTenderResult {\n sale: PosSaleSummary\n paymentId?: string\n completed: boolean\n clientSecret?: string\n paymentIntentId?: string\n /**\n * For a typed card on a store that sells on its own Stripe account: the\n * account the intent lives on, which the Payment Element loads Stripe for.\n */\n stripeAccount?: string\n}\n\nexport interface PosRegisterContext {\n settings: PosRegisterSettings\n terminal: { available: boolean; testMode: boolean }\n readers: Array<{\n id: string\n label: string\n registerId: string | null\n status: string\n livemode: boolean\n }>\n publishableKey: string\n smsReceipts: boolean\n /** Store credit other plugins keep, taken as a tender (AGL-3640). */\n credits?: Array<{ providerId: string; label: string; lookup: boolean }>\n /** Whether the store has decided how it handles sales tax (AGL-4061); absent from an older server. */\n taxDecided?: boolean\n /** Whether this person may decide it (\"Edit the site\"). */\n canDecideTax?: boolean\n /** Decided, but the register refuses every sale anyway (AGL-2145), in the refusal's words. */\n taxRefusal?: string | null\n}\n\n/** A store-credit account a staff lookup found (AGL-3640). */\nexport interface PosCreditAccount {\n reference: string\n label: string\n last4: string\n availableCents: number\n detail?: string\n}\n\ntype User = Parameters<typeof authorizedFetch>[0]\n\nexport class PosRequestError extends Error {\n constructor(\n message: string,\n readonly status: number,\n ) {\n super(message)\n }\n}\n\nasync function call<T>(\n user: User,\n route: string,\n body: Record<string, unknown>,\n options: { attemptKey?: string; method?: 'GET' | 'POST' } = {},\n): Promise<T> {\n const method = options.method ?? 'POST'\n const url =\n method === 'GET'\n ? `${route}?${new URLSearchParams(\n Object.entries(body).map(([key, value]) => [key, String(value)]),\n ).toString()}`\n : route\n const response = await authorizedFetch(user, url, {\n method,\n headers: {\n ...(method === 'POST' ? { 'Content-Type': 'application/json' } : {}),\n ...(options.attemptKey ? { 'Idempotency-Key': options.attemptKey } : {}),\n },\n ...(method === 'POST' ? { body: JSON.stringify(body) } : {}),\n })\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n throw new PosRequestError(String(payload?.error ?? 'Something went wrong'), response.status)\n }\n return payload as T\n}\n\n/** A fresh attempt key, for one press of one tender. */\nexport function newAttemptKey(): string {\n return (\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now()}-${Math.random().toString(36).slice(2)}`\n )\n}\n\nexport function posRegisterContext(user: User, hostId: string) {\n return call<PosRegisterContext>(user, '/api/commerce/pos-payment', { action: 'context', hostId }, { method: 'GET' })\n}\n\n/** Prices the basket on the server and opens a sale with an empty ledger. */\nexport function openPosSale(\n user: User,\n attemptKey: string,\n body: {\n hostId: string\n registerId: string\n lines: unknown[]\n discountPct: number\n customerEmail?: string\n /** The person the register's customer lookup attached (AGL-3609). */\n customer?: unknown\n /** A PIN-switched cashier's signed assertion (AGL-3609). */\n cashierAssertion?: string\n locationId?: string\n },\n) {\n return call<{ orderId: string; totals: CommerceModel.OrderTotals; dueCents: number; stockWarnings?: unknown[] }>(\n user,\n '/api/commerce/pos-order',\n { ...body, payment: 'open' },\n { attemptKey },\n )\n}\n\nexport type PosTenderAction =\n | 'cash'\n | 'gift-card'\n | 'credit'\n | 'folio'\n | 'card-present'\n | 'card-present-sdk'\n | 'card-keyed'\n | 'card-link'\n | 'status'\n | 'cancel'\n | 'retry'\n | 'simulate'\n | 'void'\n | 'receipt'\n\nexport function posTender(\n user: User,\n hostId: string,\n orderId: string,\n action: PosTenderAction,\n body: Record<string, unknown> = {},\n attemptKey?: string,\n) {\n return call<PosTenderResult>(\n user,\n '/api/commerce/pos-payment',\n { ...body, action, hostId, orderId },\n attemptKey ? { attemptKey } : {},\n )\n}\n\nexport function posGiftCardBalance(user: User, hostId: string, code: string) {\n return call<{ availableCents: number; frozen: boolean; voided: boolean; last4: string }>(\n user,\n '/api/commerce/pos-payment',\n { action: 'gift-card-balance', hostId, code },\n )\n}\n\n/** Finds store-credit accounts by a customer's email or code (AGL-3640). */\nexport function posCreditLookup(user: User, hostId: string, providerId: string, query: string) {\n return call<{ providerId: string; accounts: PosCreditAccount[] }>(user, '/api/commerce/pos-payment', {\n action: 'credit-lookup',\n hostId,\n providerId,\n query,\n })\n}\n\nexport function posDisplayCall<T = any>(\n user: User,\n body: Record<string, unknown>,\n method: 'GET' | 'POST' = 'POST',\n) {\n return call<T>(user, '/api/commerce/pos-display', body, { method })\n}\n\n/** The register's side of the self-service kiosk (AGL-3623): its queue of \"pay at counter\" orders. */\nexport function posKioskCall<T = any>(\n user: User,\n body: Record<string, unknown>,\n method: 'GET' | 'POST' = 'POST',\n) {\n return call<T>(user, '/api/commerce/pos-kiosk', body, { method })\n}\n\nexport function posReadersCall<T = any>(user: User, body: Record<string, unknown>) {\n return call<T>(user, '/api/commerce/pos-readers', body)\n}\n\n/** Cents as the register shows them. */\nexport const usd = (cents: number) => `$${(Math.max(0, cents) / 100).toFixed(2)}`\n\n/** A dollar string the cashier typed, as whole cents (NaN-safe, never negative). */\nexport function centsFromInput(value: string): number {\n const number = Math.round(Number(String(value).replace(/[^0-9.]/g, '')) * 100)\n return Number.isFinite(number) && number > 0 ? number : 0\n}\n\n/*==========================================\n * THE NATIVE BRIDGE (AGL-3618).\n *\n * The POS companion app loads this register in a WebView and injects\n * `window.AglynPosBridge`. When it is there, the register offers a third\n * card option — Tap to Pay or a Bluetooth reader — and hands the app a\n * PaymentIntent the SERVER created (`card-present-sdk`); the app collects\n * the card with the Stripe Terminal SDK and the register settles it exactly\n * like a smart-reader payment, by asking the server.\n *=========================================*/\n\nexport interface AglynPosBridge {\n collectCardPayment(input: {\n paymentIntentId: string\n clientSecret: string\n amountCents: number\n }): Promise<{ status: 'collected' | 'canceled' | 'failed'; message?: string }>\n}\n\nexport function posNativeBridge(): AglynPosBridge | null {\n const bridge = (globalThis as { AglynPosBridge?: AglynPosBridge }).AglynPosBridge\n return bridge && typeof bridge.collectCardPayment === 'function' ? bridge : null\n}\n"],"names":["authorizedFetch","PosRequestError","Error","message","status","call","user","route","body","options","method","url","URLSearchParams","Object","entries","map","key","value","String","toString","response","headers","attemptKey","JSON","stringify","payload","json","catch","ok","error","newAttemptKey","globalThis","crypto","randomUUID","Date","now","Math","random","slice","posRegisterContext","hostId","action","openPosSale","payment","posTender","orderId","posGiftCardBalance","code","posCreditLookup","providerId","query","posDisplayCall","posKioskCall","posReadersCall","usd","cents","max","toFixed","centsFromInput","number","round","Number","replace","isFinite","posNativeBridge","bridge","AglynPosBridge","collectCardPayment"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,eAAe,QAAQ,2CAA0C;AAoF1E,OAAO,MAAMC,wBAAwBC;IACnC,YACEC,OAAe,EACf,AAASC,MAAc,CACvB;QACA,KAAK,CAACD,eAFGC,SAAAA;IAGX;AACF;AAEA,eAAeC,KACbC,IAAU,EACVC,KAAa,EACbC,IAA6B,EAC7BC,UAA4D,CAAC,CAAC;QAE/CA;IAAf,MAAMC,UAASD,kBAAAA,QAAQC,MAAM,YAAdD,kBAAkB;IACjC,MAAME,MACJD,WAAW,QACP,GAAGH,MAAM,CAAC,EAAE,IAAIK,gBACdC,OAAOC,OAAO,CAACN,MAAMO,GAAG,CAAC,CAAC,CAACC,KAAKC,MAAM,GAAK;YAACD;YAAKE,OAAOD;SAAO,GAC/DE,QAAQ,IAAI,GACdZ;IACN,MAAMa,WAAW,MAAMpB,gBAAgBM,MAAMK,KAAK;QAChDD;QACAW,SAAS,aACHX,WAAW,SAAS;YAAE,gBAAgB;QAAmB,IAAI,CAAC,GAC9DD,QAAQa,UAAU,GAAG;YAAE,mBAAmBb,QAAQa,UAAU;QAAC,IAAI,CAAC;OAEpE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0E,GAC1E,OAAO,SAASC,gBAAgB1C,IAAU,EAAEkC,MAAc,EAAES,UAAkB,EAAEC,KAAa;IAC3F,OAAO7C,KAA2DC,MAAM,6BAA6B;QACnGmC,QAAQ;QACRD;QACAS;QACAC;IACF;AACF;AAEA,OAAO,SAASC,eACd7C,IAAU,EACVE,IAA6B,EAC7BE,SAAyB,MAAM;IAE/B,OAAOL,KAAQC,MAAM,6BAA6BE,MAAM;QAAEE;IAAO;AACnE;AAEA,oGAAoG,GACpG,OAAO,SAAS0C,aACd9C,IAAU,EACVE,IAA6B,EAC7BE,SAAyB,MAAM;IAE/B,OAAOL,KAAQC,MAAM,2BAA2BE,MAAM;QAAEE;IAAO;AACjE;AAEA,OAAO,SAAS2C,eAAwB/C,IAAU,EAAEE,IAA6B;IAC/E,OAAOH,KAAQC,MAAM,6BAA6BE;AACpD;AAEA,sCAAsC,GACtC,OAAO,MAAM8C,MAAM,CAACC,QAAkB,CAAC,CAAC,EAAE,AAACnB,CAAAA,KAAKoB,GAAG,CAAC,GAAGD,SAAS,GAAE,EAAGE,OAAO,CAAC,IAAI,CAAA;AAEjF,kFAAkF,GAClF,OAAO,SAASC,eAAezC,KAAa;IAC1C,MAAM0C,SAASvB,KAAKwB,KAAK,CAACC,OAAO3C,OAAOD,OAAO6C,OAAO,CAAC,YAAY,OAAO;IAC1E,OAAOD,OAAOE,QAAQ,CAACJ,WAAWA,SAAS,IAAIA,SAAS;AAC1D;AAqBA,OAAO,SAASK;IACd,MAAMC,SAAS,AAAClC,WAAmDmC,cAAc;IACjF,OAAOD,UAAU,OAAOA,OAAOE,kBAAkB,KAAK,aAAaF,SAAS;AAC9E"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export interface PosTaxNoticeProps {
|
|
2
|
+
hostId: string;
|
|
3
|
+
/** The register context's answer; absent from an older server, which draws nothing. */
|
|
4
|
+
taxDecided: boolean | undefined;
|
|
5
|
+
canDecideTax: boolean | undefined;
|
|
6
|
+
/** Decided, but the register refuses every sale anyway (AGL-2145), in the refusal's words. */
|
|
7
|
+
taxRefusal?: string | null;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* The register's notice while the store has not decided sales tax (AGL-4061),
|
|
11
|
+
* or has decided on something the register refuses in person (AGL-2145),
|
|
12
|
+
* drawn over the products, above "Add a register", before any sale is rung
|
|
13
|
+
* up. It is the payments notice's shape: who may decide gets "Decide
|
|
14
|
+
* sales tax", the link to Products → Taxes; everyone else is asked to fetch
|
|
15
|
+
* the store owner. Charge is unchanged: the server still refuses the sale.
|
|
16
|
+
*/
|
|
17
|
+
export declare function PosTaxNotice(props: PosTaxNoticeProps): import("react").JSX.Element;
|
|
18
|
+
export declare namespace PosTaxNotice {
|
|
19
|
+
var displayName: string;
|
|
20
|
+
}
|
|
21
|
+
export default PosTaxNotice;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ 'use client';
|
|
17
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
18
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
19
|
+
import { PrerequisiteNotice } from "@aglyn/shared-ui-jsx/components/prerequisite-notice.component";
|
|
20
|
+
import { useStoreSettingsHref } from "@aglyn/tenant-feature-instance";
|
|
21
|
+
import { DECIDE_SALES_TAX_LABEL, registerTaxNotice } from "../../../model/commerce-tax-step.js";
|
|
22
|
+
/**
|
|
23
|
+
* The register's notice while the store has not decided sales tax (AGL-4061),
|
|
24
|
+
* or has decided on something the register refuses in person (AGL-2145),
|
|
25
|
+
* drawn over the products, above "Add a register", before any sale is rung
|
|
26
|
+
* up. It is the payments notice's shape: who may decide gets "Decide
|
|
27
|
+
* sales tax", the link to Products → Taxes; everyone else is asked to fetch
|
|
28
|
+
* the store owner. Charge is unchanged: the server still refuses the sale.
|
|
29
|
+
*/ export function PosTaxNotice(props) {
|
|
30
|
+
var _props_taxRefusal;
|
|
31
|
+
const notice = registerTaxNotice({
|
|
32
|
+
taxDecided: props.taxDecided,
|
|
33
|
+
canDecide: props.canDecideTax === true,
|
|
34
|
+
refusal: (_props_taxRefusal = props.taxRefusal) != null ? _props_taxRefusal : null
|
|
35
|
+
});
|
|
36
|
+
if (!notice) return null;
|
|
37
|
+
return notice.decides ? /*#__PURE__*/ _jsx(DecideNotice, {
|
|
38
|
+
hostId: props.hostId,
|
|
39
|
+
text: notice.text
|
|
40
|
+
}) : /*#__PURE__*/ _jsx(PrerequisiteNotice, {
|
|
41
|
+
severity: "warning",
|
|
42
|
+
children: notice.text
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
PosTaxNotice.displayName = 'PosTaxNotice';
|
|
46
|
+
/** Mounted only for someone who may decide, so the Taxes page's address is looked up only then. */ function DecideNotice(props) {
|
|
47
|
+
const taxesHref = useStoreSettingsHref(props.hostId, 'taxes');
|
|
48
|
+
return /*#__PURE__*/ _jsx(PrerequisiteNotice, _extends({
|
|
49
|
+
severity: "warning"
|
|
50
|
+
}, taxesHref ? {
|
|
51
|
+
href: taxesHref
|
|
52
|
+
} : {}, {
|
|
53
|
+
actionLabel: DECIDE_SALES_TAX_LABEL,
|
|
54
|
+
children: props.text
|
|
55
|
+
}));
|
|
56
|
+
}
|
|
57
|
+
export default PosTaxNotice;
|
|
58
|
+
|
|
59
|
+
//# sourceMappingURL=pos-tax-notice.component.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../../libs/plugins/commerce/src/lib/components/console/pos/pos-tax-notice.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 { PrerequisiteNotice } from '@aglyn/shared-ui-jsx/components/prerequisite-notice.component'\nimport { useStoreSettingsHref } from '@aglyn/tenant-feature-instance'\nimport { DECIDE_SALES_TAX_LABEL, registerTaxNotice } from '../../../model/commerce-tax-step'\n\nexport interface PosTaxNoticeProps {\n hostId: string\n /** The register context's answer; absent from an older server, which draws nothing. */\n taxDecided: boolean | undefined\n canDecideTax: boolean | undefined\n /** Decided, but the register refuses every sale anyway (AGL-2145), in the refusal's words. */\n taxRefusal?: string | null\n}\n\n/**\n * The register's notice while the store has not decided sales tax (AGL-4061),\n * or has decided on something the register refuses in person (AGL-2145),\n * drawn over the products, above \"Add a register\", before any sale is rung\n * up. It is the payments notice's shape: who may decide gets \"Decide\n * sales tax\", the link to Products → Taxes; everyone else is asked to fetch\n * the store owner. Charge is unchanged: the server still refuses the sale.\n */\nexport function PosTaxNotice(props: PosTaxNoticeProps) {\n const notice = registerTaxNotice({\n taxDecided: props.taxDecided,\n canDecide: props.canDecideTax === true,\n refusal: props.taxRefusal ?? null,\n })\n if (!notice) return null\n return notice.decides ? (\n <DecideNotice hostId={props.hostId} text={notice.text} />\n ) : (\n <PrerequisiteNotice severity=\"warning\">{notice.text}</PrerequisiteNotice>\n )\n}\nPosTaxNotice.displayName = 'PosTaxNotice'\n\n/** Mounted only for someone who may decide, so the Taxes page's address is looked up only then. */\nfunction DecideNotice(props: { hostId: string; text: string }) {\n const taxesHref = useStoreSettingsHref(props.hostId, 'taxes')\n return (\n <PrerequisiteNotice\n severity=\"warning\"\n {...(taxesHref ? { href: taxesHref } : {})}\n actionLabel={DECIDE_SALES_TAX_LABEL}\n >\n {props.text}\n </PrerequisiteNotice>\n )\n}\n\nexport default PosTaxNotice\n"],"names":["PrerequisiteNotice","useStoreSettingsHref","DECIDE_SALES_TAX_LABEL","registerTaxNotice","PosTaxNotice","props","notice","taxDecided","canDecide","canDecideTax","refusal","taxRefusal","decides","DecideNotice","hostId","text","severity","displayName","taxesHref","href","actionLabel"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,kBAAkB,QAAQ,gEAA+D;AAClG,SAASC,oBAAoB,QAAQ,iCAAgC;AACrE,SAASC,sBAAsB,EAAEC,iBAAiB,QAAQ,sCAAkC;AAW5F;;;;;;;CAOC,GACD,OAAO,SAASC,aAAaC,KAAwB;QAIxCA;IAHX,MAAMC,SAASH,kBAAkB;QAC/BI,YAAYF,MAAME,UAAU;QAC5BC,WAAWH,MAAMI,YAAY,KAAK;QAClCC,OAAO,GAAEL,oBAAAA,MAAMM,UAAU,YAAhBN,oBAAoB;IAC/B;IACA,IAAI,CAACC,QAAQ,OAAO;IACpB,OAAOA,OAAOM,OAAO,iBACnB,KAACC;QAAaC,QAAQT,MAAMS,MAAM;QAAEC,MAAMT,OAAOS,IAAI;uBAErD,KAACf;QAAmBgB,UAAS;kBAAWV,OAAOS,IAAI;;AAEvD;AACAX,aAAaa,WAAW,GAAG;AAE3B,iGAAiG,GACjG,SAASJ,aAAaR,KAAuC;IAC3D,MAAMa,YAAYjB,qBAAqBI,MAAMS,MAAM,EAAE;IACrD,qBACE,KAACd;QACCgB,UAAS;OACJE,YAAY;QAAEC,MAAMD;IAAU,IAAI,CAAC;QACxCE,aAAalB;kBAEZG,MAAMU,IAAI;;AAGjB;AAEA,eAAeX,aAAY"}
|
|
@@ -48,6 +48,7 @@ import { posDisplayTipCents, usePosDisplay } from "./pos/use-pos-display.js";
|
|
|
48
48
|
import { posRegistersSettingsHref, usePosPairing } from "./pos/pos-pairing.component.js";
|
|
49
49
|
import { useConsoleWidgetSlot } from "@aglyn/aglyn/app-utils/console-widget-slot-context";
|
|
50
50
|
import { POS_ORDERS_ZONE } from "./pos-zones.js";
|
|
51
|
+
import { PosTaxNotice } from "./pos/pos-tax-notice.component.js";
|
|
51
52
|
import { isPosHardwareSkuId, posPlanPrompt } from "../../model/pos-hardware.js";
|
|
52
53
|
/**
|
|
53
54
|
* Card reader sales at the platform's own store (AGL-4038): attaching the
|
|
@@ -196,7 +197,7 @@ import { PosOfflineBanner, PosOfflineCheckout, usePosOffline } from "./pos-offli
|
|
|
196
197
|
});
|
|
197
198
|
});
|
|
198
199
|
export function PosConsolePage({ hostId, basePath, permissions }) {
|
|
199
|
-
var _ref, _ref1, _ref2, _liveRegister_openShiftId, _ref3, _ref4, _ref5;
|
|
200
|
+
var _ref, _ref1, _ref2, _liveRegister_openShiftId, _ref3, _ref4, _ref5, _ref6;
|
|
200
201
|
var _exec, _usableRegisters_find, _usableRegisters_, _offline_totalsFor;
|
|
201
202
|
/*
|
|
202
203
|
* The register's FINER keys (AGL-4047) — discounts, returns, the drawer —
|
|
@@ -338,6 +339,26 @@ export function PosConsolePage({ hostId, basePath, permissions }) {
|
|
|
338
339
|
const userRef = useRef(user);
|
|
339
340
|
userRef.current = user;
|
|
340
341
|
const uid = (_ref2 = user == null ? void 0 : user.uid) != null ? _ref2 : '';
|
|
342
|
+
// Asked again when the page comes back into view while the store has not
|
|
343
|
+
// decided sales tax (AGL-4061): the owner decides in Products → Taxes, and
|
|
344
|
+
// the notice goes away by itself on the way back.
|
|
345
|
+
const [contextRead, setContextRead] = useState(0);
|
|
346
|
+
// Undecided, or decided on something the register refuses (AGL-2145).
|
|
347
|
+
const taxNeedsDeciding = (context == null ? void 0 : context.taxDecided) === false || Boolean(context == null ? void 0 : context.taxRefusal);
|
|
348
|
+
useEffect(()=>{
|
|
349
|
+
if (!taxNeedsDeciding || typeof document === 'undefined') return undefined;
|
|
350
|
+
const reread = ()=>{
|
|
351
|
+
if (document.visibilityState === 'visible') setContextRead((count)=>count + 1);
|
|
352
|
+
};
|
|
353
|
+
document.addEventListener('visibilitychange', reread);
|
|
354
|
+
window.addEventListener('focus', reread);
|
|
355
|
+
return ()=>{
|
|
356
|
+
document.removeEventListener('visibilitychange', reread);
|
|
357
|
+
window.removeEventListener('focus', reread);
|
|
358
|
+
};
|
|
359
|
+
}, [
|
|
360
|
+
taxNeedsDeciding
|
|
361
|
+
]);
|
|
341
362
|
useEffect(()=>{
|
|
342
363
|
const signedIn = userRef.current;
|
|
343
364
|
if (!signedIn) return;
|
|
@@ -352,7 +373,8 @@ export function PosConsolePage({ hostId, basePath, permissions }) {
|
|
|
352
373
|
};
|
|
353
374
|
}, [
|
|
354
375
|
uid,
|
|
355
|
-
hostId
|
|
376
|
+
hostId,
|
|
377
|
+
contextRead
|
|
356
378
|
]);
|
|
357
379
|
/** The open sale, once the basket has been priced and payment started. */ const [sale, setSale] = useState(null);
|
|
358
380
|
const [saleLines, setSaleLines] = useState([]);
|
|
@@ -742,17 +764,12 @@ export function PosConsolePage({ hostId, basePath, permissions }) {
|
|
|
742
764
|
pendingTipCents
|
|
743
765
|
]);
|
|
744
766
|
const registersHref = posRegistersSettingsHref(basePath);
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
upgradeHref: posPlan.upgradeHref,
|
|
752
|
-
children: posPlanPrompt({
|
|
753
|
-
atRegister: true
|
|
754
|
-
})
|
|
755
|
-
}) : usableRegisters.length === 0 ? registers.length > 0 ? /*#__PURE__*/ _jsx(Typography, {
|
|
767
|
+
/**
|
|
768
|
+
* Why this page cannot take a payment yet: no register on the plan. It is
|
|
769
|
+
* the register panel's own notice, and on a narrow screen that panel only
|
|
770
|
+
* opens from Cart, so a new store saw a page with no way forward until it
|
|
771
|
+
* opened Cart (AGL-4061). There it is also shown above the products.
|
|
772
|
+
*/ const noRegisterNotice = planReady && !posPlan.locked && usableRegisters.length === 0 ? registers.length > 0 ? /*#__PURE__*/ _jsx(Typography, {
|
|
756
773
|
variant: "body2",
|
|
757
774
|
color: "warning.main",
|
|
758
775
|
children: 'Your registers exceed your plan — remove extras or upgrade in Billing to take payments.'
|
|
@@ -775,7 +792,18 @@ export function PosConsolePage({ hostId, basePath, permissions }) {
|
|
|
775
792
|
children: 'Add a register'
|
|
776
793
|
}) : null
|
|
777
794
|
]
|
|
778
|
-
}) :
|
|
795
|
+
}) : null;
|
|
796
|
+
const registerPicker = !planReady ? /*#__PURE__*/ _jsx(Typography, {
|
|
797
|
+
variant: "body2",
|
|
798
|
+
color: "text.secondary",
|
|
799
|
+
children: 'Checking your plan…'
|
|
800
|
+
}) : posPlan.locked ? /*#__PURE__*/ _jsx(EntitlementUpsell, {
|
|
801
|
+
planLabel: posPlan.planLabel,
|
|
802
|
+
upgradeHref: posPlan.upgradeHref,
|
|
803
|
+
children: posPlanPrompt({
|
|
804
|
+
atRegister: true
|
|
805
|
+
})
|
|
806
|
+
}) : usableRegisters.length === 0 ? noRegisterNotice : usableRegisters.length > 1 ? /*#__PURE__*/ _jsx(TextField, {
|
|
779
807
|
label: "Register",
|
|
780
808
|
value: registerId,
|
|
781
809
|
onChange: (event)=>setRegisterId(event.target.value),
|
|
@@ -815,6 +843,12 @@ export function PosConsolePage({ hostId, basePath, permissions }) {
|
|
|
815
843
|
}, [
|
|
816
844
|
wide
|
|
817
845
|
]);
|
|
846
|
+
/** Before any sale is rung up, while the store has not decided sales tax (AGL-4061), over the products. */ const taxNotice = /*#__PURE__*/ _jsx(PosTaxNotice, {
|
|
847
|
+
hostId: hostId,
|
|
848
|
+
taxDecided: context == null ? void 0 : context.taxDecided,
|
|
849
|
+
canDecideTax: context == null ? void 0 : context.canDecideTax,
|
|
850
|
+
taxRefusal: (_ref3 = context == null ? void 0 : context.taxRefusal) != null ? _ref3 : null
|
|
851
|
+
});
|
|
818
852
|
const registerPanel = /*#__PURE__*/ _jsxs(Stack, {
|
|
819
853
|
spacing: 1.5,
|
|
820
854
|
sx: {
|
|
@@ -844,7 +878,7 @@ export function PosConsolePage({ hostId, basePath, permissions }) {
|
|
|
844
878
|
]
|
|
845
879
|
}),
|
|
846
880
|
registerPicker,
|
|
847
|
-
((
|
|
881
|
+
((_ref4 = locationDocs == null ? void 0 : locationDocs.length) != null ? _ref4 : 0) > 1 ? /*#__PURE__*/ _jsx(TextField, {
|
|
848
882
|
label: "Location",
|
|
849
883
|
value: locationId,
|
|
850
884
|
onChange: (event)=>setLocationId(event.target.value),
|
|
@@ -999,7 +1033,7 @@ export function PosConsolePage({ hostId, basePath, permissions }) {
|
|
|
999
1033
|
sx: {
|
|
1000
1034
|
minHeight: 56
|
|
1001
1035
|
},
|
|
1002
|
-
children: opening ? 'Pricing…' : offline.offline ? `Cash ${usd((
|
|
1036
|
+
children: opening ? 'Pricing…' : offline.offline ? `Cash ${usd((_ref5 = (_offline_totalsFor = offline.totalsFor(lines, discountPct)) == null ? void 0 : _offline_totalsFor.totalCents) != null ? _ref5 : estimateCents)} (offline)` : `Charge ${usd(estimateCents)}`
|
|
1003
1037
|
}),
|
|
1004
1038
|
lastReceipt ? /*#__PURE__*/ _jsx(PosLastReceipt, _extends({
|
|
1005
1039
|
hostId: hostId,
|
|
@@ -1048,6 +1082,20 @@ export function PosConsolePage({ hostId, basePath, permissions }) {
|
|
|
1048
1082
|
offline: offline
|
|
1049
1083
|
})
|
|
1050
1084
|
}),
|
|
1085
|
+
taxNeedsDeciding ? /*#__PURE__*/ _jsx(Box, {
|
|
1086
|
+
sx: {
|
|
1087
|
+
mb: 2
|
|
1088
|
+
},
|
|
1089
|
+
"data-testid": "pos-tax-undecided",
|
|
1090
|
+
children: taxNotice
|
|
1091
|
+
}) : null,
|
|
1092
|
+
!wide && noRegisterNotice ? /*#__PURE__*/ _jsx(Box, {
|
|
1093
|
+
sx: {
|
|
1094
|
+
mb: 2
|
|
1095
|
+
},
|
|
1096
|
+
"data-testid": "pos-no-register",
|
|
1097
|
+
children: noRegisterNotice
|
|
1098
|
+
}) : null,
|
|
1051
1099
|
registerId ? /*#__PURE__*/ _jsx(PosKioskQueue, {
|
|
1052
1100
|
user: user,
|
|
1053
1101
|
hostId: hostId,
|
|
@@ -1176,7 +1224,7 @@ export function PosConsolePage({ hostId, basePath, permissions }) {
|
|
|
1176
1224
|
]
|
|
1177
1225
|
}) : null,
|
|
1178
1226
|
/*#__PURE__*/ _jsx(PosItemDialog, _extends({
|
|
1179
|
-
product: (
|
|
1227
|
+
product: (_ref6 = itemSheet == null ? void 0 : itemSheet.product) != null ? _ref6 : null,
|
|
1180
1228
|
initial: itemSheet == null ? void 0 : itemSheet.initial,
|
|
1181
1229
|
onClose: ()=>setItemSheet(null),
|
|
1182
1230
|
onConfirm: (choice)=>{
|