@aglyn/plugins-commerce 1.20.0 → 1.20.2
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/console/payments-settings-card.component.js +21 -9
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/server/connect.js +63 -14
- package/src/lib/server/connect.js.map +1 -1
- package/src/lib/server/payment-methods.js +8 -2
- package/src/lib/server/payment-methods.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/plugins-commerce",
|
|
3
|
-
"version": "1.20.
|
|
3
|
+
"version": "1.20.2",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,18 +25,18 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.20.
|
|
29
|
-
"@aglyn/shared-data-mdi": "1.20.
|
|
30
|
-
"@aglyn/shared-ui-jsx": "1.20.
|
|
31
|
-
"@aglyn/shared-ui-next": "1.20.
|
|
32
|
-
"@aglyn/shared-ui-snackstack": "1.20.
|
|
33
|
-
"@aglyn/shared-util-email": "1.20.
|
|
34
|
-
"@aglyn/shared-util-http": "1.20.
|
|
35
|
-
"@aglyn/shared-util-timestamp": "1.20.
|
|
36
|
-
"@aglyn/shared-util-tools": "1.20.
|
|
37
|
-
"@aglyn/tenant-data-admin": "1.20.
|
|
38
|
-
"@aglyn/tenant-feature-instance": "1.20.
|
|
39
|
-
"@aglyn/tenant-runtime": "1.20.
|
|
28
|
+
"@aglyn/aglyn": "1.20.2",
|
|
29
|
+
"@aglyn/shared-data-mdi": "1.20.2",
|
|
30
|
+
"@aglyn/shared-ui-jsx": "1.20.2",
|
|
31
|
+
"@aglyn/shared-ui-next": "1.20.2",
|
|
32
|
+
"@aglyn/shared-ui-snackstack": "1.20.2",
|
|
33
|
+
"@aglyn/shared-util-email": "1.20.2",
|
|
34
|
+
"@aglyn/shared-util-http": "1.20.2",
|
|
35
|
+
"@aglyn/shared-util-timestamp": "1.20.2",
|
|
36
|
+
"@aglyn/shared-util-tools": "1.20.2",
|
|
37
|
+
"@aglyn/tenant-data-admin": "1.20.2",
|
|
38
|
+
"@aglyn/tenant-feature-instance": "1.20.2",
|
|
39
|
+
"@aglyn/tenant-runtime": "1.20.2",
|
|
40
40
|
"@stripe/react-stripe-js": "^6.12.0",
|
|
41
41
|
"@stripe/stripe-js": "^9.17.0",
|
|
42
42
|
"@swc/helpers": "0.5.23",
|
|
@@ -25,6 +25,7 @@ import { useCallback, useState } from "react";
|
|
|
25
25
|
import { useFirestore, useUser } from "@aglyn/tenant-feature-instance";
|
|
26
26
|
import { useFirestoreDoc } from "@aglyn/tenant-feature-instance";
|
|
27
27
|
import { useOrgPlan } from "@aglyn/tenant-feature-instance";
|
|
28
|
+
import { merchantPaymentsPlatformMode, merchantPaymentsStateFromProfile } from "@aglyn/tenant-feature-instance/hooks/merchant-payments-state";
|
|
28
29
|
import { pluginDocsHelp } from "@aglyn/aglyn";
|
|
29
30
|
import { authorizedFetch } from "@aglyn/shared-util-http/authorized-token";
|
|
30
31
|
import { PrerequisiteNotice } from "@aglyn/shared-ui-jsx/components/prerequisite-notice.component";
|
|
@@ -79,13 +80,20 @@ import { useCommerceEntitlement } from "./entitlement-gate.component.js";
|
|
|
79
80
|
* `stripeChargesEnabled: true` was the whole readiness claim, and a
|
|
80
81
|
* production profile carrying it named a TEST-mode account: this card said
|
|
81
82
|
* "Charges enabled" about three storefronts that could not take a single
|
|
82
|
-
* payment.
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
83
|
+
* payment.
|
|
84
|
+
*
|
|
85
|
+
* The verdict is `merchantPaymentsStateFromProfile`, the console's copy of
|
|
86
|
+
* the server's `merchantAccountReadiness`, against this deployment's mode,
|
|
87
|
+
* so the chip and the checkout cannot disagree. This card used to count
|
|
88
|
+
* ANY recorded mode as verified, so a test account recorded as test on a
|
|
89
|
+
* live deployment read "Charges enabled" and offered only "Refresh status",
|
|
90
|
+
* while every sale was refused.
|
|
91
|
+
*/ const platformMode = merchantPaymentsPlatformMode();
|
|
92
|
+
const liveDeployment = platformMode === 'live';
|
|
93
|
+
const paymentsState = stripeState === 'loaded' ? merchantPaymentsStateFromProfile(profile, platformMode) : null;
|
|
94
|
+
/** The account is in the other Stripe mode from this deployment. */ const modeMismatch = paymentsState === 'mode-mismatch';
|
|
95
|
+
/** Charges on, mode never recorded, on a live deployment. */ const modeUnverified = paymentsState === 'mode-unverified';
|
|
96
|
+
const chargesEnabled = paymentsState === 'ready';
|
|
89
97
|
/** The store's own Stripe account (direct charges), or none yet: every new setup is one. */ const ownStripeAccount = stripeState === 'loaded' && ((profile == null ? void 0 : profile.stripeChargeModel) === 'direct' || !(profile == null ? void 0 : profile.stripeAccountId));
|
|
90
98
|
const physicalPct = Aglyn.resolveTransactionFeePct(org, 'physical');
|
|
91
99
|
const digitalPct = Aglyn.resolveTransactionFeePct(org, 'digital');
|
|
@@ -201,8 +209,8 @@ import { useCommerceEntitlement } from "./entitlement-gate.component.js";
|
|
|
201
209
|
}),
|
|
202
210
|
stripeState === 'error' ? null : /*#__PURE__*/ _jsx(Chip, {
|
|
203
211
|
size: "small",
|
|
204
|
-
label: stripeState === 'pending' ? 'Checking…' : chargesEnabled ? 'Charges enabled' : modeUnverified ? 'Not verified' : 'Not set up',
|
|
205
|
-
color: stripeState === 'pending' ? 'default' : chargesEnabled ? 'success' : modeUnverified ? 'error' : 'warning',
|
|
212
|
+
label: stripeState === 'pending' ? 'Checking…' : chargesEnabled ? 'Charges enabled' : modeMismatch ? liveDeployment ? 'Test account' : 'Live account' : modeUnverified ? 'Not verified' : 'Not set up',
|
|
213
|
+
color: stripeState === 'pending' ? 'default' : chargesEnabled ? 'success' : modeMismatch || modeUnverified ? 'error' : 'warning',
|
|
206
214
|
variant: "outlined"
|
|
207
215
|
})
|
|
208
216
|
]
|
|
@@ -265,6 +273,10 @@ import { useCommerceEntitlement } from "./entitlement-gate.component.js";
|
|
|
265
273
|
severity: "error",
|
|
266
274
|
children: 'Your Stripe account has not been verified for payments on ' + 'this site, so sales will be refused. Set up payments again ' + 'to verify it — if it was connected against Stripe test mode, ' + 'you will need to connect a live account.'
|
|
267
275
|
}) : null,
|
|
276
|
+
modeMismatch ? /*#__PURE__*/ _jsx(Alert, {
|
|
277
|
+
severity: "error",
|
|
278
|
+
children: liveDeployment ? 'The connected Stripe account is a test account, so this ' + 'store can’t take real payments and every sale is refused. ' + 'Live payments need a live Stripe account: set up payments ' + 'to connect one.' : 'The connected Stripe account is a live account, and this ' + 'site takes test payments only, so every sale is refused. ' + 'Set up payments to connect a test account.'
|
|
279
|
+
}) : null,
|
|
268
280
|
stripeState === 'loaded' && (profile == null ? void 0 : profile.lastPayoutFailureAtMs) ? /*#__PURE__*/ _jsx(Alert, {
|
|
269
281
|
severity: "warning",
|
|
270
282
|
variant: "outlined",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/payments-settings-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { trackEvent } from '@aglyn/aglyn/app-utils/analytics-events'\nimport * as Aglyn from '@aglyn/aglyn'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Alert, Button, Chip, Stack, Typography } from '@mui/material'\nimport { doc } from 'firebase/firestore'\nimport { useCallback, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { useFirestoreDoc } from '@aglyn/tenant-feature-instance'\nimport { useOrgPlan } from '@aglyn/tenant-feature-instance'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { PrerequisiteNotice } from '@aglyn/shared-ui-jsx/components/prerequisite-notice.component'\nimport { useCommerceEntitlement } from './entitlement-gate.component'\n\nexport interface PaymentsSettingsCardProps {\n hostId: string\n}\n\n/** The element id the Payments card carries, for a link on the same page that lands on it (AGL-3982). */\nexport const PAYMENTS_SETTINGS_ANCHOR = 'store-payments'\n\n/**\n * Merchant payments card (AGL-284): Stripe Connect Express onboarding\n * status for the org owner + the plan's transaction-fee ladder so the\n * \"upgrade to kill fees\" motion (AGL-278) is visible where it matters.\n */\nexport function PaymentsSettingsCard(props: PaymentsSettingsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const [busy, setBusy] = useState(false)\n /**\n * A one-time Stripe Express dashboard link, minted by the connect route on\n * request. Not persisted: login links are single-use and short-lived, so a\n * stored one would be a button that fails the second time it is pressed.\n */\n const [dashboardUrl, setDashboardUrl] = useState<string | null>(null)\n const { org, ready: planReady } = useOrgPlan(hostId)\n /** Bumped by Retry to re-subscribe the profile listen (AGL-1380). */\n const [retryNonce, setRetryNonce] = useState(0)\n const { upgradeHref } = useCommerceEntitlement(hostId, 'commerce')\n /**\n * The OWNER's profile: the Stripe account every money route charges\n * against is the one on the workspace owner's profile. Reading the\n * signed-in member's instead told an admin who is not the owner that a\n * connected store was not set up.\n */\n const ownerUid =\n typeof org?.ownerUid === 'string' && org.ownerUid ? org.ownerUid : undefined\n const { data: profile, status: profileStatus } = useFirestoreDoc<any>(\n // Held at null rather than addressed as `profiles/-pending-` — that\n // sentinel issued a guaranteed-denied read on every pre-auth mount, and\n // a denial lands in `status: 'error'`, which now means something.\n () => (ownerUid ? doc(firestore, 'profiles', ownerUid) : null),\n [firestore, ownerUid, retryNonce],\n )\n const isOwner = Boolean(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. Only a literal boolean counts as recorded — the same\n * three-valued reading `merchantAccountIsReady` uses on the server, so the\n * chip and the checkout cannot disagree.\n */\n const modeVerified = typeof profile?.stripeAccountLivemode === 'boolean'\n const chargesConnected =\n stripeState === 'loaded' && Boolean(profile?.stripeChargesEnabled)\n const modeUnverified = chargesConnected && !modeVerified\n const chargesEnabled = chargesConnected && modeVerified\n /** 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 const handleConnect = useCallback(async () => {\n setBusy(true)\n try {\n const response = await authorizedFetch(user, '/api/commerce/connect', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId }),\n })\n const payload = await response.json()\n if (response.status === 501) {\n return void enqueueSnackbar(\n 'Payments are not configured on this deployment',\n { variant: 'info', persist: false },\n )\n }\n if (!response.ok) {\n return void enqueueSnackbar(payload?.error ?? 'Payment setup failed', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n if (payload.chargesEnabled) {\n // \"% who connect Stripe\" — a GTM plan §6 activation metric\n // (AGL-1561). Gated on the TRANSITION, not the state: this handler\n // is a re-entrant create-or-resume, so it answers `chargesEnabled:\n // true` on every subsequent visit to a connected account, and a bare\n // event here would count one merchant once per click forever.\n // `chargesEnabled` is the state read from the profile BEFORE this\n // request, so the event fires only when onboarding actually completed.\n if (!chargesEnabled) trackEvent('stripe_connected', {})\n // CHARGES AND PAYOUTS ARE TWO FLAGS, AND ONLY ONE OF THEM IS THIS\n // SENTENCE (AGL-1997). `chargesEnabled` says Stripe will let the\n // account take money; whether the money can LEAVE is `payoutsEnabled`,\n // which the route answers alongside it. Charges-yes/payouts-no is an\n // ordinary Stripe state — verification pending or lapsed, no payout\n // method — and announcing \"Payments are enabled\" in it is false in the\n // direction that costs the merchant: they sell believing they are\n // paid, and the funds sit in a Connect account that cannot release\n // them. Read three-valued, so only a literal `false` from Stripe\n // downgrades the claim; an absent flag means unasked, not off.\n const payoutsBlocked = payload.payoutsEnabled === false\n // A WARNING THAT NAMES A PROBLEM MUST OFFER THE FIX.\n //\n // Stripe is the only place payouts can be released — an Express\n // account has no password and no direct login — so telling the\n // merchant their funds are stranded and then keeping them here is half\n // an answer. The route now mints the remediation link for exactly this\n // state; going there is the whole point of pressing the button.\n if (payoutsBlocked && payload.url) {\n return void window.location.assign(payload.url)\n }\n // Payouts are flowing, so the link is the Express dashboard: balance,\n // payout schedule, and the reason a payout failed. Held in state\n // rather than followed, because this click was a status check and\n // navigating away from one nobody asked to leave is its own defect.\n if (!payoutsBlocked && typeof payload.dashboardUrl === 'string') {\n setDashboardUrl(payload.dashboardUrl)\n }\n return void enqueueSnackbar(\n payoutsBlocked\n ? 'Connected — payouts are not released yet'\n : 'Payments are enabled',\n {\n variant: payoutsBlocked ? 'warning' : 'success',\n persist: false,\n },\n )\n }\n if (payload.url) window.location.assign(payload.url)\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }, [user, hostId, chargesEnabled, enqueueSnackbar])\n\n return (\n <CardDisplay\n id={PAYMENTS_SETTINGS_ANCHOR}\n header={'Payments'}\n help={pluginDocsHelp('commerceEndToEnd', {\n anchor: '#1-connect-payments',\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"body2\" sx={{ flex: 1 }}>\n {'Stripe account'}\n </Typography>\n {/*\n No chip at all on error: both labels it could carry — \"Charges\n enabled\" and \"Not set up\" — assert something we failed to find\n out. Whatever Stripe is doing right now it carries on doing.\n */}\n {stripeState === 'error' ? null : (\n <Chip\n size=\"small\"\n label={\n stripeState === 'pending'\n ? 'Checking…'\n : chargesEnabled\n ? 'Charges enabled'\n : modeUnverified\n ? 'Not verified'\n : 'Not set up'\n }\n color={\n stripeState === 'pending'\n ? 'default'\n : chargesEnabled\n ? 'success'\n : modeUnverified\n ? 'error'\n : 'warning'\n }\n variant=\"outlined\"\n />\n )}\n </Stack>\n {stripeState === 'error' ? (\n <Alert\n severity=\"error\"\n action={\n <Button\n color=\"inherit\"\n size=\"small\"\n onClick={() => setRetryNonce((n) => n + 1)}\n >\n {'Retry'}\n </Button>\n }\n >\n {'We couldn’t load your payment setup. This says nothing about ' +\n 'whether payments are on — we could not reach the setting to ' +\n 'find out. Nothing has changed.'}\n </Alert>\n ) : null}\n {/*\n Every line below reads the plan, and an org doc still in flight\n resolves to the FREE tier (AGL-1064) — which would flash \"Selling\n requires a paid plan\" and the wrong fee percentages at a paying\n seller, then correct itself. Say nothing until it is known.\n */}\n {!planReady ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Checking your plan…'}\n </Typography>\n ) : (\n <>\n {!commerceEnabled ? (\n <PrerequisiteNotice href={upgradeHref} actionLabel=\"See plans\">\n {\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 button's own label is a claim — \"Set up payments\" tells the\n owner they have none. Withheld until the answer is in, for the same\n reason as the chip (AGL-1380); on error the Retry above is the only\n action offered, because acting on a setup we could not read is how\n a connected merchant gets sent back through onboarding.\n */}\n {/*\n WHERE THE MONEY STOPPED. Mirrored onto this profile by the\n `payout.failed` handler and retired by the next successful payout, so\n it names a live problem rather than a scar. Without it a merchant sold\n into an account that could not release the funds and the card said\n \"Payments are enabled\" the whole time — the storefront looked healthy\n from every angle available to them.\n */}\n {stripeState === 'loaded' && profile?.lastPayoutFailureAtMs ? (\n <Alert severity=\"warning\" variant=\"outlined\">\n {`A payout of $${(\n Number(profile.lastPayoutFailureCents ?? 0) / 100\n ).toFixed(2)} did not reach your bank on ${new Date(\n Number(profile.lastPayoutFailureAtMs),\n ).toLocaleDateString()} — ${String(\n profile.lastPayoutFailureReason ?? 'Stripe did not say why',\n )} The money is still in your Stripe account. Open Stripe to fix your payout details.`}\n </Alert>\n ) : null}\n {!planReady || stripeState !== 'loaded' ? null : isOwner ? (\n <>\n <Button\n size=\"small\"\n variant={chargesEnabled ? 'text' : 'contained'}\n color=\"primary\"\n disabled={busy}\n onClick={handleConnect}\n sx={{ alignSelf: 'flex-start' }}\n >\n {chargesEnabled\n ? 'Refresh status'\n : busy\n ? 'Opening Stripe…'\n : 'Set up payments'}\n </Button>\n {/*\n Where the money actually is. Aglyn records none of it —\n no balance, no payout schedule, and no `payout.failed` handling\n anywhere — so a merchant whose payout bounced has no way to learn\n that from this console. An Express account has no direct login\n either, which leaves a link minted by the platform as the only\n route in. `target=\"_blank\"` because it leaves the app entirely.\n */}\n {dashboardUrl ? (\n <Button\n size=\"small\"\n variant=\"text\"\n color=\"primary\"\n href={dashboardUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n sx={{ alignSelf: 'flex-start' }}\n >\n {'View payouts in Stripe'}\n </Button>\n ) : null}\n </>\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Only the organization owner can set up payments.'}\n </Typography>\n )}\n </Stack>\n </CardDisplay>\n )\n}\nPaymentsSettingsCard.displayName = 'PaymentsSettingsCard'\n\nexport default PaymentsSettingsCard\n"],"names":["trackEvent","Aglyn","CardDisplay","useSnackbar","Alert","Button","Chip","Stack","Typography","doc","useCallback","useState","useFirestore","useUser","useFirestoreDoc","useOrgPlan","pluginDocsHelp","authorizedFetch","PrerequisiteNotice","useCommerceEntitlement","PAYMENTS_SETTINGS_ANCHOR","PaymentsSettingsCard","props","profile","hostId","firestore","data","user","enqueueSnackbar","busy","setBusy","dashboardUrl","setDashboardUrl","org","ready","planReady","retryNonce","setRetryNonce","upgradeHref","ownerUid","undefined","status","profileStatus","isOwner","Boolean","uid","stripeState","modeVerified","stripeAccountLivemode","chargesConnected","stripeChargesEnabled","modeUnverified","chargesEnabled","ownStripeAccount","stripeChargeModel","stripeAccountId","physicalPct","resolveTransactionFeePct","digitalPct","commerceEnabled","checkEntitlement","handleConnect","response","method","headers","body","JSON","stringify","payload","json","variant","persist","ok","error","allowDuplicate","payoutsBlocked","payoutsEnabled","url","window","location","assign","console","id","header","help","anchor","contentGutterX","contentGutterY","spacing","direction","sx","alignItems","flex","size","label","color","severity","action","onClick","n","href","actionLabel","PLATFORM_BRAND_LEGAL_NAME","component","SALE_PROCESSING_PERCENT","SALE_PROCESSING_FIXED_CENTS","CONNECT_PAYOUT_PERCENT","CONNECT_PAYOUT_FIXED_CENTS","STRIPE_TAX_PERCENT","lastPayoutFailureAtMs","Number","lastPayoutFailureCents","toFixed","Date","toLocaleDateString","String","lastPayoutFailureReason","disabled","alignSelf","target","rel","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,UAAU,QAAQ,0CAAyC;AACpE,YAAYC,WAAW,eAAc;AACrC,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,KAAK,EAAEC,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AACtE,SAASC,GAAG,QAAQ,qBAAoB;AACxC,SAASC,WAAW,EAAEC,QAAQ,QAAQ,QAAO;AAC7C,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SAASC,eAAe,QAAQ,iCAAgC;AAChE,SAASC,UAAU,QAAQ,iCAAgC;AAC3D,SAASC,cAAc,QAAQ,eAAc;AAC7C,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,kBAAkB,QAAQ,gEAA+D;AAClG,SAASC,sBAAsB,QAAQ,kCAA8B;AAMrE,uGAAuG,GACvG,OAAO,MAAMC,2BAA2B,iBAAgB;AAExD;;;;CAIC,GACD,OAAO,SAASC,qBAAqBC,KAAgC;QA4WhDC,iCAIPA;IA/WZ,MAAM,EAAEC,MAAM,EAAE,GAAGF;IACnB,MAAMG,YAAYb;IAClB,MAAM,EAAEc,MAAMC,IAAI,EAAE,GAAGd;IACvB,MAAM,EAAEe,eAAe,EAAE,GAAGzB;IAC5B,MAAM,CAAC0B,MAAMC,QAAQ,GA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;oBAAM4F,UAAS;8BACb,+DACC,gEACA,kEACA;qBAEF;gBAgBHlD,gBAAgB,aAAYvB,2BAAAA,QAASsF,qBAAqB,kBACzD,KAACzG;oBAAM4F,UAAS;oBAAU1B,SAAQ;8BAC/B,CAAC,aAAa,EAAE,AACfwC,CAAAA,QAAOvF,kCAAAA,QAAQwF,sBAAsB,YAA9BxF,kCAAkC,KAAK,GAAE,EAChDyF,OAAO,CAAC,GAAG,4BAA4B,EAAE,IAAIC,KAC7CH,OAAOvF,QAAQsF,qBAAqB,GACpCK,kBAAkB,GAAG,GAAG,EAAEC,QAC1B5F,mCAAAA,QAAQ6F,uBAAuB,YAA/B7F,mCAAmC,0BACnC,mFAAmF,CAAC;qBAEtF;gBACH,CAACY,aAAaW,gBAAgB,WAAW,OAAOH,wBAC/C;;sCACE,KAACtC;4BACCwF,MAAK;4BACLvB,SAASlB,iBAAiB,SAAS;4BACnC2C,OAAM;4BACNsB,UAAUxF;4BACVqE,SAASrC;4BACT6B,IAAI;gCAAE4B,WAAW;4BAAa;sCAE7BlE,iBACG,mBACAvB,OACE,oBACA;;wBAUPE,6BACC,KAAC1B;4BACCwF,MAAK;4BACLvB,SAAQ;4BACRyB,OAAM;4BACNK,MAAMrE;4BACNwF,QAAO;4BACPC,KAAI;4BACJ9B,IAAI;gCAAE4B,WAAW;4BAAa;sCAE7B;6BAED;;mCAGN,KAAC9G;oBAAW8D,SAAQ;oBAAUyB,OAAM;8BACjC;;;;;AAMb;AACA1E,qBAAqBoG,WAAW,GAAG;AAEnC,eAAepG,qBAAoB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/payments-settings-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { trackEvent } from '@aglyn/aglyn/app-utils/analytics-events'\nimport * as Aglyn from '@aglyn/aglyn'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Alert, Button, Chip, Stack, Typography } from '@mui/material'\nimport { doc } from 'firebase/firestore'\nimport { useCallback, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { useFirestoreDoc } from '@aglyn/tenant-feature-instance'\nimport { useOrgPlan } from '@aglyn/tenant-feature-instance'\nimport {\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'\n\nexport interface PaymentsSettingsCardProps {\n hostId: string\n}\n\n/** The element id the Payments card carries, for a link on the same page that lands on it (AGL-3982). */\nexport const PAYMENTS_SETTINGS_ANCHOR = 'store-payments'\n\n/**\n * Merchant payments card (AGL-284): Stripe Connect Express onboarding\n * status for the org owner + the plan's transaction-fee ladder so the\n * \"upgrade to kill fees\" motion (AGL-278) is visible where it matters.\n */\nexport function PaymentsSettingsCard(props: PaymentsSettingsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const [busy, setBusy] = useState(false)\n /**\n * A one-time Stripe Express dashboard link, minted by the connect route on\n * request. Not persisted: login links are single-use and short-lived, so a\n * stored one would be a button that fails the second time it is pressed.\n */\n const [dashboardUrl, setDashboardUrl] = useState<string | null>(null)\n const { org, ready: planReady } = useOrgPlan(hostId)\n /** Bumped by Retry to re-subscribe the profile listen (AGL-1380). */\n const [retryNonce, setRetryNonce] = useState(0)\n const { upgradeHref } = useCommerceEntitlement(hostId, 'commerce')\n /**\n * The OWNER's profile: the Stripe account every money route charges\n * against is the one on the workspace owner's profile. Reading the\n * signed-in member's instead told an admin who is not the owner that a\n * connected store was not set up.\n */\n const ownerUid =\n typeof org?.ownerUid === 'string' && org.ownerUid ? org.ownerUid : undefined\n const { data: profile, status: profileStatus } = useFirestoreDoc<any>(\n // Held at null rather than addressed as `profiles/-pending-` — that\n // sentinel issued a guaranteed-denied read on every pre-auth mount, and\n // a denial lands in `status: 'error'`, which now means something.\n () => (ownerUid ? doc(firestore, 'profiles', ownerUid) : null),\n [firestore, ownerUid, retryNonce],\n )\n const isOwner = Boolean(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 const handleConnect = useCallback(async () => {\n setBusy(true)\n try {\n const response = await authorizedFetch(user, '/api/commerce/connect', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId }),\n })\n const payload = await response.json()\n if (response.status === 501) {\n return void enqueueSnackbar(\n 'Payments are not configured on this deployment',\n { variant: 'info', persist: false },\n )\n }\n if (!response.ok) {\n return void enqueueSnackbar(payload?.error ?? 'Payment setup failed', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n if (payload.chargesEnabled) {\n // \"% who connect Stripe\" — a GTM plan §6 activation metric\n // (AGL-1561). Gated on the TRANSITION, not the state: this handler\n // is a re-entrant create-or-resume, so it answers `chargesEnabled:\n // true` on every subsequent visit to a connected account, and a bare\n // event here would count one merchant once per click forever.\n // `chargesEnabled` is the state read from the profile BEFORE this\n // request, so the event fires only when onboarding actually completed.\n if (!chargesEnabled) trackEvent('stripe_connected', {})\n // CHARGES AND PAYOUTS ARE TWO FLAGS, AND ONLY ONE OF THEM IS THIS\n // SENTENCE (AGL-1997). `chargesEnabled` says Stripe will let the\n // account take money; whether the money can LEAVE is `payoutsEnabled`,\n // which the route answers alongside it. Charges-yes/payouts-no is an\n // ordinary Stripe state — verification pending or lapsed, no payout\n // method — and announcing \"Payments are enabled\" in it is false in the\n // direction that costs the merchant: they sell believing they are\n // paid, and the funds sit in a Connect account that cannot release\n // them. Read three-valued, so only a literal `false` from Stripe\n // downgrades the claim; an absent flag means unasked, not off.\n const payoutsBlocked = payload.payoutsEnabled === false\n // A WARNING THAT NAMES A PROBLEM MUST OFFER THE FIX.\n //\n // Stripe is the only place payouts can be released — an Express\n // account has no password and no direct login — so telling the\n // merchant their funds are stranded and then keeping them here is half\n // an answer. The route now mints the remediation link for exactly this\n // state; going there is the whole point of pressing the button.\n if (payoutsBlocked && payload.url) {\n return void window.location.assign(payload.url)\n }\n // Payouts are flowing, so the link is the Express dashboard: balance,\n // payout schedule, and the reason a payout failed. Held in state\n // rather than followed, because this click was a status check and\n // navigating away from one nobody asked to leave is its own defect.\n if (!payoutsBlocked && typeof payload.dashboardUrl === 'string') {\n setDashboardUrl(payload.dashboardUrl)\n }\n return void enqueueSnackbar(\n payoutsBlocked\n ? 'Connected — payouts are not released yet'\n : 'Payments are enabled',\n {\n variant: payoutsBlocked ? 'warning' : 'success',\n persist: false,\n },\n )\n }\n if (payload.url) window.location.assign(payload.url)\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }, [user, hostId, chargesEnabled, enqueueSnackbar])\n\n return (\n <CardDisplay\n id={PAYMENTS_SETTINGS_ANCHOR}\n header={'Payments'}\n help={pluginDocsHelp('commerceEndToEnd', {\n anchor: '#1-connect-payments',\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"body2\" sx={{ flex: 1 }}>\n {'Stripe account'}\n </Typography>\n {/*\n No chip at all on error: both labels it could carry — \"Charges\n enabled\" and \"Not set up\" — assert something we failed to find\n out. Whatever Stripe is doing right now it carries on doing.\n */}\n {stripeState === 'error' ? null : (\n <Chip\n size=\"small\"\n label={\n stripeState === 'pending'\n ? 'Checking…'\n : chargesEnabled\n ? 'Charges enabled'\n : 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 {stripeState === 'loaded' && profile?.lastPayoutFailureAtMs ? (\n <Alert severity=\"warning\" variant=\"outlined\">\n {`A payout of $${(\n Number(profile.lastPayoutFailureCents ?? 0) / 100\n ).toFixed(2)} did not reach your bank on ${new Date(\n Number(profile.lastPayoutFailureAtMs),\n ).toLocaleDateString()} — ${String(\n profile.lastPayoutFailureReason ?? 'Stripe did not say why',\n )} The money is still in your Stripe account. Open Stripe to fix your payout details.`}\n </Alert>\n ) : null}\n {!planReady || stripeState !== 'loaded' ? null : isOwner ? (\n <>\n <Button\n size=\"small\"\n variant={chargesEnabled ? 'text' : 'contained'}\n color=\"primary\"\n disabled={busy}\n onClick={handleConnect}\n sx={{ alignSelf: 'flex-start' }}\n >\n {chargesEnabled\n ? 'Refresh status'\n : busy\n ? 'Opening Stripe…'\n : 'Set up payments'}\n </Button>\n {/*\n Where the money actually is. Aglyn records none of it —\n no balance, no payout schedule, and no `payout.failed` handling\n anywhere — so a merchant whose payout bounced has no way to learn\n that from this console. An Express account has no direct login\n either, which leaves a link minted by the platform as the only\n route in. `target=\"_blank\"` because it leaves the app entirely.\n */}\n {dashboardUrl ? (\n <Button\n size=\"small\"\n variant=\"text\"\n color=\"primary\"\n href={dashboardUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n sx={{ alignSelf: 'flex-start' }}\n >\n {'View payouts in Stripe'}\n </Button>\n ) : null}\n </>\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Only the organization owner can set up payments.'}\n </Typography>\n )}\n </Stack>\n </CardDisplay>\n )\n}\nPaymentsSettingsCard.displayName = 'PaymentsSettingsCard'\n\nexport default PaymentsSettingsCard\n"],"names":["trackEvent","Aglyn","CardDisplay","useSnackbar","Alert","Button","Chip","Stack","Typography","doc","useCallback","useState","useFirestore","useUser","useFirestoreDoc","useOrgPlan","merchantPaymentsPlatformMode","merchantPaymentsStateFromProfile","pluginDocsHelp","authorizedFetch","PrerequisiteNotice","useCommerceEntitlement","PAYMENTS_SETTINGS_ANCHOR","PaymentsSettingsCard","props","profile","hostId","firestore","data","user","enqueueSnackbar","busy","setBusy","dashboardUrl","setDashboardUrl","org","ready","planReady","retryNonce","setRetryNonce","upgradeHref","ownerUid","undefined","status","profileStatus","isOwner","Boolean","uid","stripeState","platformMode","liveDeployment","paymentsState","modeMismatch","modeUnverified","chargesEnabled","ownStripeAccount","stripeChargeModel","stripeAccountId","physicalPct","resolveTransactionFeePct","digitalPct","commerceEnabled","checkEntitlement","handleConnect","response","method","headers","body","JSON","stringify","payload","json","variant","persist","ok","error","allowDuplicate","payoutsBlocked","payoutsEnabled","url","window","location","assign","console","id","header","help","anchor","contentGutterX","contentGutterY","spacing","direction","sx","alignItems","flex","size","label","color","severity","action","onClick","n","href","actionLabel","PLATFORM_BRAND_LEGAL_NAME","component","SALE_PROCESSING_PERCENT","SALE_PROCESSING_FIXED_CENTS","CONNECT_PAYOUT_PERCENT","CONNECT_PAYOUT_FIXED_CENTS","STRIPE_TAX_PERCENT","lastPayoutFailureAtMs","Number","lastPayoutFailureCents","toFixed","Date","toLocaleDateString","String","lastPayoutFailureReason","disabled","alignSelf","target","rel","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,UAAU,QAAQ,0CAAyC;AACpE,YAAYC,WAAW,eAAc;AACrC,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,KAAK,EAAEC,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AACtE,SAASC,GAAG,QAAQ,qBAAoB;AACxC,SAASC,WAAW,EAAEC,QAAQ,QAAQ,QAAO;AAC7C,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SAASC,eAAe,QAAQ,iCAAgC;AAChE,SAASC,UAAU,QAAQ,iCAAgC;AAC3D,SACEC,4BAA4B,EAC5BC,gCAAgC,QAC3B,+DAA8D;AACrE,SAASC,cAAc,QAAQ,eAAc;AAC7C,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,kBAAkB,QAAQ,gEAA+D;AAClG,SAASC,sBAAsB,QAAQ,kCAA8B;AAMrE,uGAAuG,GACvG,OAAO,MAAMC,2BAA2B,iBAAgB;AAExD;;;;CAIC,GACD,OAAO,SAASC,qBAAqBC,KAAgC;QA8YhDC,iCAIPA;IAjZZ,MAAM,EAAEC,MAAM,EAAE,GAAGF;IACnB,MAAMG,YAAYf;IAClB,MAAM,EAAEgB,MAAMC,IAAI,EAAE,GAAGhB;IACvB,MAAM,EAAEiB,eAAe,EAAE,GAAG3B;IAC5B,MAAM,CAAC4B,MAAMC,QAAQ,GAAGrB,SAAS;IACjC;;;;GAIC,GACD,MAAM,CAACsB,cAAcC,gBAAgB,GAAGvB,SAAwB;IAChE,MAAM,EAAEwB,GAAG,EAAEC,OAAOC,SAAS,EAAE,GAAGtB,WAAWW;IAC7C,mEAAmE,GACnE,MAAM,CAACY,YAAYC,c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,+DACA,oBACA,8DACA,8DACA;qBAEJ;gBAgBHF,gBAAgB,aAAYvB,2BAAAA,QAASsF,qBAAqB,kBACzD,KAAC3G;oBAAM8F,UAAS;oBAAU1B,SAAQ;8BAC/B,CAAC,aAAa,EAAE,AACfwC,CAAAA,QAAOvF,kCAAAA,QAAQwF,sBAAsB,YAA9BxF,kCAAkC,KAAK,GAAE,EAChDyF,OAAO,CAAC,GAAG,4BAA4B,EAAE,IAAIC,KAC7CH,OAAOvF,QAAQsF,qBAAqB,GACpCK,kBAAkB,GAAG,GAAG,EAAEC,QAC1B5F,mCAAAA,QAAQ6F,uBAAuB,YAA/B7F,mCAAmC,0BACnC,mFAAmF,CAAC;qBAEtF;gBACH,CAACY,aAAaW,gBAAgB,WAAW,OAAOH,wBAC/C;;sCACE,KAACxC;4BACC0F,MAAK;4BACLvB,SAASlB,iBAAiB,SAAS;4BACnC2C,OAAM;4BACNsB,UAAUxF;4BACVqE,SAASrC;4BACT6B,IAAI;gCAAE4B,WAAW;4BAAa;sCAE7BlE,iBACG,mBACAvB,OACE,oBACA;;wBAUPE,6BACC,KAAC5B;4BACC0F,MAAK;4BACLvB,SAAQ;4BACRyB,OAAM;4BACNK,MAAMrE;4BACNwF,QAAO;4BACPC,KAAI;4BACJ9B,IAAI;gCAAE4B,WAAW;4BAAa;sCAE7B;6BAED;;mCAGN,KAAChH;oBAAWgE,SAAQ;oBAAUyB,OAAM;8BACjC;;;;;AAMb;AACA1E,qBAAqBoG,WAAW,GAAG;AAEnC,eAAepG,qBAAoB"}
|
|
@@ -15,7 +15,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import { firebaseAdmin, getOrgForHost, isServerReleaseFlagOnForOrg } from "@aglyn/tenant-data-admin";
|
|
18
|
-
import { accountChargeModel, DIRECT_CHARGE_ACCOUNT_PARAMS, paymentProvider } from "@aglyn/tenant-data-admin/server/payment-provider";
|
|
18
|
+
import { accountChargeModel, DIRECT_CHARGE_ACCOUNT_PARAMS, merchantAccountInOtherMode, merchantAccountReplacement, paymentProvider, PREVIOUS_MERCHANT_ACCOUNTS_FIELD } from "@aglyn/tenant-data-admin/server/payment-provider";
|
|
19
19
|
import { buildRoute, Route } from "@aglyn/aglyn/server";
|
|
20
20
|
async function stripe(path, params) {
|
|
21
21
|
const response = await fetch(`https://api.stripe.com/v1/${path}`, _extends({
|
|
@@ -84,8 +84,45 @@ async function stripe(path, params) {
|
|
|
84
84
|
const firestore = firebaseAdmin.app().firestore();
|
|
85
85
|
const profileRef = firestore.collection('profiles').doc(decoded.uid);
|
|
86
86
|
const profileSnapshot = await profileRef.get();
|
|
87
|
+
// This deployment's Stripe mode, asked first: whether the stored account
|
|
88
|
+
// can be used here at all depends on it (AGL-2471).
|
|
89
|
+
const platformMode = await paymentProvider().resolvePlatformMode();
|
|
87
90
|
let accountId = profileSnapshot.get('stripeAccountId');
|
|
88
|
-
|
|
91
|
+
// AN ACCOUNT FROM THE OTHER STRIPE MODE IS REPLACED, NEVER RESUMED.
|
|
92
|
+
//
|
|
93
|
+
// A test account on a live deployment (a localhost session onboarded with
|
|
94
|
+
// the test key while writing production Firestore, see
|
|
95
|
+
// `payment-provider-stripe-connect.ts`) can never take a live payment, and
|
|
96
|
+
// a live key cannot even read it: Stripe refuses the retrieve. This route
|
|
97
|
+
// used to retrieve it anyway, so the owner pressing "Set up payments" got
|
|
98
|
+
// "Payment setup failed" every time and the store could not sell. Two
|
|
99
|
+
// ways in:
|
|
100
|
+
//
|
|
101
|
+
// - `mode-mismatch`: the profile RECORDS the other mode. Not read at all,
|
|
102
|
+
// since the read cannot succeed.
|
|
103
|
+
// - `mode-unverified` (and any recorded mode Stripe contradicts): the
|
|
104
|
+
// account is read, and a read that succeeds is the proof it is in this
|
|
105
|
+
// mode, recorded below exactly as before. Only Stripe's own cross-mode
|
|
106
|
+
// refusal retires it; any other failure is the 502 it always was.
|
|
107
|
+
//
|
|
108
|
+
// A new account is then created in this mode, of the shape every new
|
|
109
|
+
// setup takes (direct charges, below), and the replaced id is kept on the
|
|
110
|
+
// profile (`merchantAccountReplacement`).
|
|
111
|
+
let account;
|
|
112
|
+
let replacedAccountId;
|
|
113
|
+
if (accountId && merchantAccountInOtherMode(profileSnapshot.get('stripeAccountLivemode'), platformMode)) {
|
|
114
|
+
replacedAccountId = accountId;
|
|
115
|
+
} else if (accountId) {
|
|
116
|
+
try {
|
|
117
|
+
account = await stripe(`accounts/${accountId}`);
|
|
118
|
+
} catch (error) {
|
|
119
|
+
if (!paymentProvider().refusedAsOtherMode(error == null ? void 0 : error.message)) {
|
|
120
|
+
throw error;
|
|
121
|
+
}
|
|
122
|
+
replacedAccountId = accountId;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (!accountId || replacedAccountId) {
|
|
89
126
|
// The seller's OWN Stripe account (direct charges): Stripe bills it,
|
|
90
127
|
// underwrites it and gives it the full Stripe Dashboard, so the seller
|
|
91
128
|
// is the merchant of record on every site sale and can refund, answer
|
|
@@ -104,7 +141,7 @@ async function stripe(path, params) {
|
|
|
104
141
|
} catch (unused) {
|
|
105
142
|
ownsAccount = false;
|
|
106
143
|
}
|
|
107
|
-
const
|
|
144
|
+
const created = await stripe('accounts', new URLSearchParams(_extends({}, ownsAccount ? DIRECT_CHARGE_ACCOUNT_PARAMS : {
|
|
108
145
|
type: 'express'
|
|
109
146
|
}, {
|
|
110
147
|
// Explicit capabilities (AGL-1994): `card_payments` for the
|
|
@@ -115,18 +152,31 @@ async function stripe(path, params) {
|
|
|
115
152
|
'capabilities[transfers][requested]': 'true',
|
|
116
153
|
'metadata[profileId]': decoded.uid,
|
|
117
154
|
'metadata[purpose]': 'commerce'
|
|
118
|
-
},
|
|
155
|
+
}, replacedAccountId ? {
|
|
156
|
+
'metadata[replacesAccount]': replacedAccountId
|
|
157
|
+
} : {}, decoded.email ? {
|
|
119
158
|
email: decoded.email
|
|
120
159
|
} : {})));
|
|
121
|
-
accountId =
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
160
|
+
accountId = String(created.id);
|
|
161
|
+
if (replacedAccountId) {
|
|
162
|
+
console.warn(`[AGL-2471] Replacing Stripe account ${replacedAccountId} on ` + `profiles/${decoded.uid}: it belongs to the other Stripe mode ` + `from this ${platformMode != null ? platformMode : 'unknown'}-mode deployment. New ` + `account ${accountId}.`);
|
|
163
|
+
await profileRef.set(merchantAccountReplacement({
|
|
164
|
+
previousAccountIds: profileSnapshot.get(PREVIOUS_MERCHANT_ACCOUNTS_FIELD),
|
|
165
|
+
replacedAccountId,
|
|
166
|
+
newAccountId: accountId
|
|
167
|
+
}), {
|
|
168
|
+
merge: true
|
|
169
|
+
});
|
|
170
|
+
} else {
|
|
171
|
+
await profileRef.set({
|
|
172
|
+
stripeAccountId: accountId,
|
|
173
|
+
stripeChargesEnabled: false
|
|
174
|
+
}, {
|
|
175
|
+
merge: true
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
account = await stripe(`accounts/${accountId}`);
|
|
128
179
|
}
|
|
129
|
-
const account = await stripe(`accounts/${accountId}`);
|
|
130
180
|
const chargesEnabled = Boolean(account == null ? void 0 : account.charges_enabled);
|
|
131
181
|
// WHICH STRIPE WORLD THIS ACCOUNT LIVES IN (AGL-2471).
|
|
132
182
|
//
|
|
@@ -140,8 +190,7 @@ async function stripe(path, params) {
|
|
|
140
190
|
// access outright — "was a test account created with a testmode key" —
|
|
141
191
|
// so an account this key just fetched is in this key's mode, and the
|
|
142
192
|
// payment provider asks Stripe (`/v1/balance.livemode`) what that mode is
|
|
143
|
-
// rather than reading the key string.
|
|
144
|
-
const platformMode = await paymentProvider().resolvePlatformMode();
|
|
193
|
+
// rather than reading the key string (`platformMode`, asked first).
|
|
145
194
|
// Payout readiness rides along (AGL-1994): the sale gate stays on
|
|
146
195
|
// charges_enabled — that is what Stripe checks at charge time — but
|
|
147
196
|
// charges-yes/payouts-no was invisible to the storefront, because
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/connect.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 {\n firebaseAdmin,\n getOrgForHost,\n isServerReleaseFlagOnForOrg,\n} from '@aglyn/tenant-data-admin'\nimport {\n accountChargeModel,\n DIRECT_CHARGE_ACCOUNT_PARAMS,\n paymentProvider,\n} from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { buildRoute, Route, type PluginApiHandler } from '@aglyn/aglyn/server'\n\nasync function stripe(path: string, params?: URLSearchParams) {\n const response = await fetch(`https://api.stripe.com/v1/${path}`, {\n method: params ? 'POST' : 'GET',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n ...(params && {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }),\n },\n ...(params && { body: params.toString() }),\n })\n const payload = await response.json()\n if (!response.ok) {\n throw new Error(payload?.error?.message ?? `Stripe ${path} failed`)\n }\n return payload\n}\n\n/**\n * Merchant payments onboarding (AGL-284): Stripe Connect Express for\n * storefront selling. Same account storage the checkout reads\n * (`profiles/{ownerUid}.stripeAccountId`, AGL-46) but without the\n * marketplace-profile prerequisite — commerce merchants aren't necessarily\n * publishers. Only the owning org's owner may onboard (payouts land on\n * their account). 501 without Stripe env.\n */\nexport const connectHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res\n .status(501)\n .json({ error: 'Payments are not configured (STRIPE_SECRET_KEY).' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const ownerOrg = await getOrgForHost(hostId)\n const ownerUid = ownerOrg?.org?.ownerUid\n if (!ownerUid) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n if (String(ownerUid) !== decoded.uid) {\n return res\n .status(403)\n .json({ error: 'Only the organization owner can set up payments' })\n }\n const firestore = firebaseAdmin.app().firestore()\n const profileRef = firestore.collection('profiles').doc(decoded.uid)\n const profileSnapshot = await profileRef.get()\n\n let accountId = profileSnapshot.get('stripeAccountId') as\n | string\n | undefined\n if (!accountId) {\n // The seller's OWN Stripe account (direct charges): Stripe bills it,\n // underwrites it and gives it the full Stripe Dashboard, so the seller\n // is the merchant of record on every site sale and can refund, answer\n // a dispute and manage tax registrations there. See\n // `DIRECT_CHARGE_ACCOUNT_PARAMS`. Behind `release_direct_charges` until\n // the Terms say so; off, the platform-managed Express account and its\n // destination charges, exactly as before. The shape cannot be changed\n // once the account exists, so this is the one place it is decided.\n // Any failure to read the flag is OFF: the account it would create is\n // the one every store had before, never a shape nobody chose.\n let ownsAccount = false\n try {\n ownsAccount = await isServerReleaseFlagOnForOrg(\n 'release_direct_charges',\n String(ownerOrg?.org?.id ?? ownerOrg?.orgId ?? '') || null,\n )\n } catch {\n ownsAccount = false\n }\n const account = await stripe(\n 'accounts',\n new URLSearchParams({\n ...(ownsAccount\n ? DIRECT_CHARGE_ACCOUNT_PARAMS\n : { type: 'express' }),\n // Explicit capabilities (AGL-1994): `card_payments` for the\n // charges, and `transfers` because a destination charge (every\n // sale on an Express account, and the register and Tap to Pay on\n // either kind) requires the destination to hold it.\n 'capabilities[card_payments][requested]': 'true',\n 'capabilities[transfers][requested]': 'true',\n 'metadata[profileId]': decoded.uid,\n 'metadata[purpose]': 'commerce',\n ...(decoded.email ? { email: decoded.email } : {}),\n }),\n )\n accountId = account.id\n await profileRef.set(\n { stripeAccountId: accountId, stripeChargesEnabled: false },\n { merge: true },\n )\n }\n\n const account = await stripe(`accounts/${accountId}`)\n const chargesEnabled = Boolean(account?.charges_enabled)\n // WHICH STRIPE WORLD THIS ACCOUNT LIVES IN (AGL-2471).\n //\n // Three production linkages named TEST-mode accounts, one of them with\n // `stripeChargesEnabled: true`, so its storefronts read as payments-ready\n // and could not take a payment. Nothing recorded the mode, and nothing\n // could recover it later: the Account object carries no `livemode` field\n // and an `acct_…` id is the same shape in both worlds.\n //\n // The retrieve above IS the proof. Stripe refuses cross-mode account\n // access outright — \"was a test account created with a testmode key\" —\n // so an account this key just fetched is in this key's mode, and the\n // payment provider asks Stripe (`/v1/balance.livemode`) what that mode is\n // rather than reading the key string.\n const platformMode = await paymentProvider().resolvePlatformMode()\n // Payout readiness rides along (AGL-1994): the sale gate stays on\n // charges_enabled — that is what Stripe checks at charge time — but\n // charges-yes/payouts-no was invisible to the storefront, because\n // commerce wrote only `stripeChargesEnabled`. Recording\n // `payouts_enabled` is what lets a console surface warn a merchant\n // BEFORE the first sale strands funds in a Connect account that\n // cannot pay them out.\n const payoutsEnabled = Boolean(account?.payouts_enabled)\n // Which charge shape this account takes, read off the account itself\n // every time, so a re-onboarded seller can never inherit the last\n // account's answer.\n const chargeModel = accountChargeModel(account)\n await profileRef.set(\n {\n stripeChargesEnabled: chargesEnabled,\n stripeChargeModel: chargeModel,\n stripePayoutsEnabled: payoutsEnabled,\n // ALWAYS written, and `null` when Stripe would not say (AGL-2471).\n // Writing unconditionally is what makes re-onboarding safe: a fresh\n // `stripeAccountId` on a document that still carried the PREVIOUS\n // account's verdict would otherwise inherit it. `null` is not a\n // boolean, so the gate reads it as `mode-unverified` and refuses —\n // never a fabricated `true`.\n stripeAccountLivemode: platformMode ? platformMode === 'live' : null,\n },\n { merge: true },\n )\n const origin = req.headers.origin ?? `https://${req.headers.host}`\n // Stripe bakes these into the onboarding link, so they have to be real\n // console paths. They were `/{hostDocId}/products` — the pre-AGL-621/622\n // shape — so finishing Connect onboarding dropped the seller on a 404\n // (AGL-685). Console products is the plugin route under the org slug and\n // the host SUBDOMAIN, both of which have to be resolved here; the client\n // hook (useConsoleHostRoute) is not available to server code.\n const index = await firebaseAdmin\n .app()\n .firestore()\n .collection('hostIndex')\n .doc(hostId)\n .get()\n const subdomain = index.get('subdomain') as string | undefined\n const orgSlug = ownerOrg?.org?.slug as string | undefined\n // No slug/subdomain means no route to send them to; Stripe requires\n // both URLs, so fall back to the origin root rather than a fabricated\n // path that 404s.\n const productsUrl =\n orgSlug && subdomain\n ? `${origin}${buildRoute(Route.HOST_PLUGIN, {\n orgSlug,\n host: subdomain,\n pluginSlug: 'products',\n })}`\n : origin\n // A CONNECTED MERCHANT STILL NEEDS A DOOR INTO STRIPE.\n //\n // This route used to return here the moment `charges_enabled` was true,\n // with a status and no link of any kind, and both console cards read the\n // `chargesEnabled` flag before they ever looked for a url. So the one\n // state that most needs Stripe — charges on, payouts NOT released, funds\n // accumulating in a Connect account that cannot pay them out — offered a\n // button labelled \"Finish payout setup in Stripe\" that raised a toast and\n // went nowhere. An Express account has no password and no direct login, so\n // a link minted here is the merchant's ONLY way in; without one the money\n // is unreachable and no surface says why.\n if (chargesEnabled) {\n if (!payoutsEnabled) {\n // The remediation flow, which is what Stripe points an account with\n // outstanding requirements at. Failures are NOT swallowed: answering\n // 200 with no link is precisely the dead end being closed here, so a\n // mint that fails surfaces as the handler's 502 and the merchant is\n // told to try again rather than left pressing a dead button.\n const fix = await stripe(\n 'account_links',\n new URLSearchParams({\n account: accountId as string,\n type: 'account_onboarding',\n refresh_url: `${productsUrl}?connect=refresh`,\n return_url: `${productsUrl}?connect=done`,\n }),\n )\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n url: fix.url,\n })\n }\n // Payouts are flowing, so this is the VIEW: balance, payout schedule,\n // and the reason a payout failed — none of which Aglyn records and none\n // of which the merchant could otherwise reach. Best-effort on purpose:\n // a login link is a convenience, and failing to mint one must never turn\n // a working status check into an error.\n let dashboardUrl: string | undefined\n if (chargeModel === 'direct') {\n // A full Stripe account signs in to Stripe itself; login links exist\n // only for Express accounts.\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n dashboardUrl: 'https://dashboard.stripe.com/',\n })\n }\n try {\n const login = await stripe(\n `accounts/${accountId}/login_links`,\n new URLSearchParams(),\n )\n dashboardUrl = typeof login?.url === 'string' ? login.url : undefined\n } catch (error) {\n console.error('Stripe Express dashboard link failed', error)\n }\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n ...(dashboardUrl ? { dashboardUrl } : {}),\n })\n }\n\n const link = await stripe(\n 'account_links',\n new URLSearchParams({\n account: accountId as string,\n type: 'account_onboarding',\n refresh_url: `${productsUrl}?connect=refresh`,\n return_url: `${productsUrl}?connect=done`,\n }),\n )\n return res\n .status(200)\n .json({ accountId, chargesEnabled: false, url: link.url })\n } catch (error) {\n console.error(error)\n return res.status(502).json({ error: 'Payment setup failed' })\n }\n}\n"],"names":["firebaseAdmin","getOrgForHost","isServerReleaseFlagOnForOrg","accountChargeModel","DIRECT_CHARGE_ACCOUNT_PARAMS","paymentProvider","buildRoute","Route","stripe","path","params","response","fetch","method","headers","Authorization","process","env","STRIPE_SECRET_KEY","body","toString","payload","json","ok","Error","error","message","connectHandler","req","res","status","authorization","String","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","ownerOrg","decoded","app","auth","verifyIdToken","ownerUid","org","uid","firestore","profileRef","collection","doc","profileSnapshot","get","accountId","ownsAccount","id","orgId","account","URLSearchParams","type","email","set","stripeAccountId","stripeChargesEnabled","merge","chargesEnabled","Boolean","charges_enabled","platformMode","resolvePlatformMode","payoutsEnabled","payouts_enabled","chargeModel","stripeChargeModel","stripePayoutsEnabled","stripeAccountLivemode","origin","host","index","subdomain","orgSlug","slug","productsUrl","HOST_PLUGIN","pluginSlug","fix","refresh_url","return_url","url","dashboardUrl","login","console","link"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,aAAa,EACbC,aAAa,EACbC,2BAA2B,QACtB,2BAA0B;AACjC,SACEC,kBAAkB,EAClBC,4BAA4B,EAC5BC,eAAe,QACV,mDAAkD;AACzD,SAASC,UAAU,EAAEC,KAAK,QAA+B,sBAAqB;AAE9E,eAAeC,OAAOC,IAAY,EAAEC,MAAwB;IAC1D,MAAMC,WAAW,MAAMC,MAAM,CAAC,0BAA0B,EAAEH,MAAM,EAAE;QAChEI,QAAQH,SAAS,SAAS;QAC1BI,SAAS;YACPC,eAAe,CAAC,OAAO,EAAEC,QAAQC,GAAG,CAACC,iBAAiB,EAAE;WACpDR,UAAU;YACZ,gBAAgB;QAClB;OAEEA,UAAU;QAAES,MAAMT,OAAOU,QAAQ;IAAG;IAE1C,MAAMC,UAAU,MAAMV,SAASW,IAAI;IACnC,IAAI,CAACX,SAASY,EAAE,EAAE;;YACAF;QAAhB,MAAM,IAAIG,cAAMH,4BAAAA,iBAAAA,QAASI,KAAK,qBAAdJ,eAAgBK,OAAO,mBAAI,CAAC,OAAO,EAAEjB,KAAK,OAAO,CAAC;IACpE;IACA,OAAOY;AACT;AAEA;;;;;;;CAOC,GACD,OAAO,MAAMM,iBAAmC,OAAOC,KAAKC;QAS7BD,4BAM4BA,WACnCT;IAftB,IAAIS,IAAIf,MAAM,KAAK,QAAQ;QACzB,OAAOgB,IAAIC,MAAM,CAAC,KAAKR,IAAI,CAAC;YAAEG,OAAO;QAAqB;IAC5D;IACA,IAAI,CAACT,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAOW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AAY,GAAGL,YAAY,aAAa,CAAC;QAC3C;QAEF,OAAOvD,IACJC,MAAM,CAAC,KACPR,IAAI,CAAC;YAAEiC;YAAWY,gBAAgB;YAAOuB,KAAKI,KAAKJ,GAAG;QAAC;IAC5D,EAAE,OAAOjE,OAAO;QACdoE,QAAQpE,KAAK,CAACA;QACd,OAAOI,IAAIC,MAAM,CAAC,KAAKR,IAAI,CAAC;YAAEG,OAAO;QAAuB;IAC9D;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/connect.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 {\n firebaseAdmin,\n getOrgForHost,\n isServerReleaseFlagOnForOrg,\n} from '@aglyn/tenant-data-admin'\nimport {\n accountChargeModel,\n DIRECT_CHARGE_ACCOUNT_PARAMS,\n merchantAccountInOtherMode,\n merchantAccountReplacement,\n paymentProvider,\n PREVIOUS_MERCHANT_ACCOUNTS_FIELD,\n} from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { buildRoute, Route, type PluginApiHandler } from '@aglyn/aglyn/server'\n\nasync function stripe(path: string, params?: URLSearchParams) {\n const response = await fetch(`https://api.stripe.com/v1/${path}`, {\n method: params ? 'POST' : 'GET',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n ...(params && {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }),\n },\n ...(params && { body: params.toString() }),\n })\n const payload = await response.json()\n if (!response.ok) {\n throw new Error(payload?.error?.message ?? `Stripe ${path} failed`)\n }\n return payload\n}\n\n/**\n * Merchant payments onboarding (AGL-284): Stripe Connect Express for\n * storefront selling. Same account storage the checkout reads\n * (`profiles/{ownerUid}.stripeAccountId`, AGL-46) but without the\n * marketplace-profile prerequisite — commerce merchants aren't necessarily\n * publishers. Only the owning org's owner may onboard (payouts land on\n * their account). 501 without Stripe env.\n */\nexport const connectHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res\n .status(501)\n .json({ error: 'Payments are not configured (STRIPE_SECRET_KEY).' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const ownerOrg = await getOrgForHost(hostId)\n const ownerUid = ownerOrg?.org?.ownerUid\n if (!ownerUid) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n if (String(ownerUid) !== decoded.uid) {\n return res\n .status(403)\n .json({ error: 'Only the organization owner can set up payments' })\n }\n const firestore = firebaseAdmin.app().firestore()\n const profileRef = firestore.collection('profiles').doc(decoded.uid)\n const profileSnapshot = await profileRef.get()\n\n // This deployment's Stripe mode, asked first: whether the stored account\n // can be used here at all depends on it (AGL-2471).\n const platformMode = await paymentProvider().resolvePlatformMode()\n let accountId = profileSnapshot.get('stripeAccountId') as\n | string\n | undefined\n // AN ACCOUNT FROM THE OTHER STRIPE MODE IS REPLACED, NEVER RESUMED.\n //\n // A test account on a live deployment (a localhost session onboarded with\n // the test key while writing production Firestore, see\n // `payment-provider-stripe-connect.ts`) can never take a live payment, and\n // a live key cannot even read it: Stripe refuses the retrieve. This route\n // used to retrieve it anyway, so the owner pressing \"Set up payments\" got\n // \"Payment setup failed\" every time and the store could not sell. Two\n // ways in:\n //\n // - `mode-mismatch`: the profile RECORDS the other mode. Not read at all,\n // since the read cannot succeed.\n // - `mode-unverified` (and any recorded mode Stripe contradicts): the\n // account is read, and a read that succeeds is the proof it is in this\n // mode, recorded below exactly as before. Only Stripe's own cross-mode\n // refusal retires it; any other failure is the 502 it always was.\n //\n // A new account is then created in this mode, of the shape every new\n // setup takes (direct charges, below), and the replaced id is kept on the\n // profile (`merchantAccountReplacement`).\n let account: any\n let replacedAccountId: string | undefined\n if (\n accountId &&\n merchantAccountInOtherMode(\n profileSnapshot.get('stripeAccountLivemode'),\n platformMode,\n )\n ) {\n replacedAccountId = accountId\n } else if (accountId) {\n try {\n account = await stripe(`accounts/${accountId}`)\n } catch (error) {\n if (!paymentProvider().refusedAsOtherMode((error as Error)?.message)) {\n throw error\n }\n replacedAccountId = accountId\n }\n }\n if (!accountId || replacedAccountId) {\n // The seller's OWN Stripe account (direct charges): Stripe bills it,\n // underwrites it and gives it the full Stripe Dashboard, so the seller\n // is the merchant of record on every site sale and can refund, answer\n // a dispute and manage tax registrations there. See\n // `DIRECT_CHARGE_ACCOUNT_PARAMS`. Behind `release_direct_charges` until\n // the Terms say so; off, the platform-managed Express account and its\n // destination charges, exactly as before. The shape cannot be changed\n // once the account exists, so this is the one place it is decided.\n // Any failure to read the flag is OFF: the account it would create is\n // the one every store had before, never a shape nobody chose.\n let ownsAccount = false\n try {\n ownsAccount = await isServerReleaseFlagOnForOrg(\n 'release_direct_charges',\n String(ownerOrg?.org?.id ?? ownerOrg?.orgId ?? '') || null,\n )\n } catch {\n ownsAccount = false\n }\n const created = await stripe(\n 'accounts',\n new URLSearchParams({\n ...(ownsAccount\n ? DIRECT_CHARGE_ACCOUNT_PARAMS\n : { type: 'express' }),\n // Explicit capabilities (AGL-1994): `card_payments` for the\n // charges, and `transfers` because a destination charge (every\n // sale on an Express account, and the register and Tap to Pay on\n // either kind) requires the destination to hold it.\n 'capabilities[card_payments][requested]': 'true',\n 'capabilities[transfers][requested]': 'true',\n 'metadata[profileId]': decoded.uid,\n 'metadata[purpose]': 'commerce',\n ...(replacedAccountId\n ? { 'metadata[replacesAccount]': replacedAccountId }\n : {}),\n ...(decoded.email ? { email: decoded.email } : {}),\n }),\n )\n accountId = String(created.id)\n if (replacedAccountId) {\n console.warn(\n `[AGL-2471] Replacing Stripe account ${replacedAccountId} on ` +\n `profiles/${decoded.uid}: it belongs to the other Stripe mode ` +\n `from this ${platformMode ?? 'unknown'}-mode deployment. New ` +\n `account ${accountId}.`,\n )\n await profileRef.set(\n merchantAccountReplacement({\n previousAccountIds: profileSnapshot.get(\n PREVIOUS_MERCHANT_ACCOUNTS_FIELD,\n ),\n replacedAccountId,\n newAccountId: accountId,\n }),\n { merge: true },\n )\n } else {\n await profileRef.set(\n { stripeAccountId: accountId, stripeChargesEnabled: false },\n { merge: true },\n )\n }\n account = await stripe(`accounts/${accountId}`)\n }\n\n const chargesEnabled = Boolean(account?.charges_enabled)\n // WHICH STRIPE WORLD THIS ACCOUNT LIVES IN (AGL-2471).\n //\n // Three production linkages named TEST-mode accounts, one of them with\n // `stripeChargesEnabled: true`, so its storefronts read as payments-ready\n // and could not take a payment. Nothing recorded the mode, and nothing\n // could recover it later: the Account object carries no `livemode` field\n // and an `acct_…` id is the same shape in both worlds.\n //\n // The retrieve above IS the proof. Stripe refuses cross-mode account\n // access outright — \"was a test account created with a testmode key\" —\n // so an account this key just fetched is in this key's mode, and the\n // payment provider asks Stripe (`/v1/balance.livemode`) what that mode is\n // rather than reading the key string (`platformMode`, asked first).\n // Payout readiness rides along (AGL-1994): the sale gate stays on\n // charges_enabled — that is what Stripe checks at charge time — but\n // charges-yes/payouts-no was invisible to the storefront, because\n // commerce wrote only `stripeChargesEnabled`. Recording\n // `payouts_enabled` is what lets a console surface warn a merchant\n // BEFORE the first sale strands funds in a Connect account that\n // cannot pay them out.\n const payoutsEnabled = Boolean(account?.payouts_enabled)\n // Which charge shape this account takes, read off the account itself\n // every time, so a re-onboarded seller can never inherit the last\n // account's answer.\n const chargeModel = accountChargeModel(account)\n await profileRef.set(\n {\n stripeChargesEnabled: chargesEnabled,\n stripeChargeModel: chargeModel,\n stripePayoutsEnabled: payoutsEnabled,\n // ALWAYS written, and `null` when Stripe would not say (AGL-2471).\n // Writing unconditionally is what makes re-onboarding safe: a fresh\n // `stripeAccountId` on a document that still carried the PREVIOUS\n // account's verdict would otherwise inherit it. `null` is not a\n // boolean, so the gate reads it as `mode-unverified` and refuses —\n // never a fabricated `true`.\n stripeAccountLivemode: platformMode ? platformMode === 'live' : null,\n },\n { merge: true },\n )\n const origin = req.headers.origin ?? `https://${req.headers.host}`\n // Stripe bakes these into the onboarding link, so they have to be real\n // console paths. They were `/{hostDocId}/products` — the pre-AGL-621/622\n // shape — so finishing Connect onboarding dropped the seller on a 404\n // (AGL-685). Console products is the plugin route under the org slug and\n // the host SUBDOMAIN, both of which have to be resolved here; the client\n // hook (useConsoleHostRoute) is not available to server code.\n const index = await firebaseAdmin\n .app()\n .firestore()\n .collection('hostIndex')\n .doc(hostId)\n .get()\n const subdomain = index.get('subdomain') as string | undefined\n const orgSlug = ownerOrg?.org?.slug as string | undefined\n // No slug/subdomain means no route to send them to; Stripe requires\n // both URLs, so fall back to the origin root rather than a fabricated\n // path that 404s.\n const productsUrl =\n orgSlug && subdomain\n ? `${origin}${buildRoute(Route.HOST_PLUGIN, {\n orgSlug,\n host: subdomain,\n pluginSlug: 'products',\n })}`\n : origin\n // A CONNECTED MERCHANT STILL NEEDS A DOOR INTO STRIPE.\n //\n // This route used to return here the moment `charges_enabled` was true,\n // with a status and no link of any kind, and both console cards read the\n // `chargesEnabled` flag before they ever looked for a url. So the one\n // state that most needs Stripe — charges on, payouts NOT released, funds\n // accumulating in a Connect account that cannot pay them out — offered a\n // button labelled \"Finish payout setup in Stripe\" that raised a toast and\n // went nowhere. An Express account has no password and no direct login, so\n // a link minted here is the merchant's ONLY way in; without one the money\n // is unreachable and no surface says why.\n if (chargesEnabled) {\n if (!payoutsEnabled) {\n // The remediation flow, which is what Stripe points an account with\n // outstanding requirements at. Failures are NOT swallowed: answering\n // 200 with no link is precisely the dead end being closed here, so a\n // mint that fails surfaces as the handler's 502 and the merchant is\n // told to try again rather than left pressing a dead button.\n const fix = await stripe(\n 'account_links',\n new URLSearchParams({\n account: accountId as string,\n type: 'account_onboarding',\n refresh_url: `${productsUrl}?connect=refresh`,\n return_url: `${productsUrl}?connect=done`,\n }),\n )\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n url: fix.url,\n })\n }\n // Payouts are flowing, so this is the VIEW: balance, payout schedule,\n // and the reason a payout failed — none of which Aglyn records and none\n // of which the merchant could otherwise reach. Best-effort on purpose:\n // a login link is a convenience, and failing to mint one must never turn\n // a working status check into an error.\n let dashboardUrl: string | undefined\n if (chargeModel === 'direct') {\n // A full Stripe account signs in to Stripe itself; login links exist\n // only for Express accounts.\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n dashboardUrl: 'https://dashboard.stripe.com/',\n })\n }\n try {\n const login = await stripe(\n `accounts/${accountId}/login_links`,\n new URLSearchParams(),\n )\n dashboardUrl = typeof login?.url === 'string' ? login.url : undefined\n } catch (error) {\n console.error('Stripe Express dashboard link failed', error)\n }\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n ...(dashboardUrl ? { dashboardUrl } : {}),\n })\n }\n\n const link = await stripe(\n 'account_links',\n new URLSearchParams({\n account: accountId as string,\n type: 'account_onboarding',\n refresh_url: `${productsUrl}?connect=refresh`,\n return_url: `${productsUrl}?connect=done`,\n }),\n )\n return res\n .status(200)\n .json({ accountId, chargesEnabled: false, url: link.url })\n } catch (error) {\n console.error(error)\n return res.status(502).json({ error: 'Payment setup failed' })\n }\n}\n"],"names":["firebaseAdmin","getOrgForHost","isServerReleaseFlagOnForOrg","accountChargeModel","DIRECT_CHARGE_ACCOUNT_PARAMS","merchantAccountInOtherMode","merchantAccountReplacement","paymentProvider","PREVIOUS_MERCHANT_ACCOUNTS_FIELD","buildRoute","Route","stripe","path","params","response","fetch","method","headers","Authorization","process","env","STRIPE_SECRET_KEY","body","toString","payload","json","ok","Error","error","message","connectHandler","req","res","status","authorization","String","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","ownerOrg","decoded","app","auth","verifyIdToken","ownerUid","org","uid","firestore","profileRef","collection","doc","profileSnapshot","get","platformMode","resolvePlatformMode","accountId","account","replacedAccountId","refusedAsOtherMode","ownsAccount","id","orgId","created","URLSearchParams","type","email","console","warn","set","previousAccountIds","newAccountId","merge","stripeAccountId","stripeChargesEnabled","chargesEnabled","Boolean","charges_enabled","payoutsEnabled","payouts_enabled","chargeModel","stripeChargeModel","stripePayoutsEnabled","stripeAccountLivemode","origin","host","index","subdomain","orgSlug","slug","productsUrl","HOST_PLUGIN","pluginSlug","fix","refresh_url","return_url","url","dashboardUrl","login","link"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,aAAa,EACbC,aAAa,EACbC,2BAA2B,QACtB,2BAA0B;AACjC,SACEC,kBAAkB,EAClBC,4BAA4B,EAC5BC,0BAA0B,EAC1BC,0BAA0B,EAC1BC,eAAe,EACfC,gCAAgC,QAC3B,mDAAkD;AACzD,SAASC,UAAU,EAAEC,KAAK,QAA+B,sBAAqB;AAE9E,eAAeC,OAAOC,IAAY,EAAEC,MAAwB;IAC1D,MAAMC,WAAW,MAAMC,MAAM,CAAC,0BAA0B,EAAEH,MAAM,EAAE;QAChEI,QAAQH,SAAS,SAAS;QAC1BI,SAAS;YACPC,eAAe,CAAC,OAAO,EAAEC,QAAQC,GAAG,CAACC,iBAAiB,EAAE;WACpDR,UAAU;YACZ,gBAAgB;QAClB;OAEEA,UAAU;QAAES,MAAMT,OAAOU,QAAQ;IAAG;IAE1C,MAAMC,UAAU,MAAMV,SAASW,IAAI;IACnC,IAAI,CAAC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AAAA,MAAOF,GAAG,MAAK,WAAWE,MAAMF,GAAG,GAAG5D;YAC9D,EAAE,OAAOZ,OAAO;gBACd2C,QAAQ3C,KAAK,CAAC,wCAAwCA;YACxD;YACA,OAAOI,IAAIC,MAAM,CAAC,KAAKR,IAAI,CAAC;gBAC1BmC;gBACAmB,gBAAgB;gBAChBG;eACImB,eAAe;gBAAEA;YAAa,IAAI,CAAC;QAE3C;QAEA,MAAME,OAAO,MAAM5F,OACjB,iBACA,IAAIyD,gBAAgB;YAClBP,SAASD;YACTS,MAAM;YACN6B,aAAa,GAAGJ,YAAY,gBAAgB,CAAC;YAC7CK,YAAY,GAAGL,YAAY,aAAa,CAAC;QAC3C;QAEF,OAAO9D,IACJC,MAAM,CAAC,KACPR,IAAI,CAAC;YAAEmC;YAAWmB,gBAAgB;YAAOqB,KAAKG,KAAKH,GAAG;QAAC;IAC5D,EAAE,OAAOxE,OAAO;QACd2C,QAAQ3C,KAAK,CAACA;QACd,OAAOI,IAAIC,MAAM,CAAC,KAAKR,IAAI,CAAC;YAAEG,OAAO;QAAuB;IAC9D;AACF,EAAC"}
|
|
@@ -18,6 +18,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
18
18
|
import { checkEntitlement, pluginRequestFromWeb } from "@aglyn/aglyn/server";
|
|
19
19
|
import { emailUnverifiedResponse, firebaseAdmin, getOrgForHost, isImpersonationSession, lockdownRefusal } from "@aglyn/tenant-data-admin";
|
|
20
20
|
import { invalidIdTokenResponse } from "@aglyn/tenant-data-admin/server/id-token-refusal";
|
|
21
|
+
import { merchantAccountInOtherMode, paymentProvider } from "@aglyn/tenant-data-admin/server/payment-provider";
|
|
21
22
|
import { isStorefrontPaymentMethodOn, normalizeStorefrontPaymentMethodSettings, STOREFRONT_PAYMENT_METHODS } from "../model/commerce-payment-methods.js";
|
|
22
23
|
import { commerceSitePermissionRefusal } from "../model/plugin-permissions.js";
|
|
23
24
|
import { holdsCommerceSiteKey } from "./commerce-site-keys.js";
|
|
@@ -162,7 +163,7 @@ export async function paymentMethodsHandler(request) {
|
|
|
162
163
|
error: 'Missing hostId'
|
|
163
164
|
}, 400);
|
|
164
165
|
try {
|
|
165
|
-
var _ref1, _ref2,
|
|
166
|
+
var _ref1, _ref2, _ownerProfile_get;
|
|
166
167
|
var _owner_org;
|
|
167
168
|
const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
|
|
168
169
|
if (!decoded.email_verified && !isImpersonationSession(decoded)) {
|
|
@@ -204,7 +205,12 @@ export async function paymentMethodsHandler(request) {
|
|
|
204
205
|
}, 402);
|
|
205
206
|
}
|
|
206
207
|
const ownerUid = String((_ref2 = owner == null ? void 0 : (_owner_org = owner.org) == null ? void 0 : _owner_org.ownerUid) != null ? _ref2 : '');
|
|
207
|
-
const
|
|
208
|
+
const ownerProfile = ownerUid ? await firestore.collection('profiles').doc(ownerUid).get() : null;
|
|
209
|
+
// An account RECORDED in the other Stripe mode (AGL-2471) is no payout
|
|
210
|
+
// account here: this key cannot read it, every sale against it is
|
|
211
|
+
// refused, and "Set up payments" replaces it. So nothing is asked of it,
|
|
212
|
+
// and the methods read as waiting on Stripe, not as ready.
|
|
213
|
+
const accountId = ownerProfile && !merchantAccountInOtherMode(ownerProfile.get('stripeAccountLivemode'), paymentProvider().platformMode()) ? (_ownerProfile_get = ownerProfile.get('stripeAccountId')) != null ? _ownerProfile_get : null : null;
|
|
208
214
|
const storeRef = hostRef.collection('settings').doc('store');
|
|
209
215
|
let settings = normalizeStorefrontPaymentMethodSettings((await storeRef.get()).get('paymentMethods'));
|
|
210
216
|
const platform = await platformPaymentMethodAvailability();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/payment-methods.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 { directSellerAccountForHost } from './seller-stripe-account'\nimport { checkEntitlement, pluginRequestFromWeb } from '@aglyn/aglyn/server'\nimport type { SiteReturnHost } from '@aglyn/aglyn/app-utils/site-return-url'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n getOrgForHost,\n isImpersonationSession,\n lockdownRefusal,\n} from '@aglyn/tenant-data-admin'\nimport { invalidIdTokenResponse } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport {\n isStorefrontPaymentMethodOn,\n normalizeStorefrontPaymentMethodSettings,\n STOREFRONT_PAYMENT_METHODS,\n type StorefrontPaymentMethodId,\n type StorefrontPaymentMethodSettings,\n} from '../model/commerce-payment-methods'\nimport { commerceSitePermissionRefusal } from '../model/plugin-permissions'\nimport { holdsCommerceSiteKey } from './commerce-site-keys'\nimport {\n type PaymentMethodDomainRecord,\n readSiteDomainRecords,\n} from './payment-method-domains'\n\n/**\n * The merchant's payment methods card (AGL-3629):\n * `GET|POST /api/commerce/payment-methods?hostId=…`, served by the console.\n *\n * GET answers, per method, three facts the card needs and no client can read:\n *\n * - whether the PLATFORM offers it (its default payment method configuration\n * — storefront charges are destination charges with the platform as\n * merchant of record, so that configuration is the ceiling). A method the\n * platform has not turned on, or that Stripe has not made available to it,\n * is reported `unavailable` and the card does not show it at all;\n * - the connected account's capability for it, which Stripe asks platforms to\n * request before an account accepts BNPL, Cash App, Amazon Pay or crypto;\n * - the site's domain registrations, which Apple Pay depends on.\n *\n * POST saves the toggles to `hosts/{hostId}/settings/store.paymentMethods` and\n * requests the capability of each method turned on, in one account update with\n * an idempotency key. Server-side, because the toggle and the capability are\n * one decision: a toggle saved by the browser with no capability behind it\n * would read as on and never appear.\n */\n\nexport type PlatformAvailability = 'on' | 'unavailable' | null\n\nexport type CapabilityStatus = 'active' | 'pending' | 'inactive' | 'unrequested' | null\n\nexport interface PaymentMethodRow {\n id: StorefrontPaymentMethodId\n on: boolean\n platform: PlatformAvailability\n capability: CapabilityStatus\n}\n\nexport interface PaymentMethodsAnswer {\n methods: PaymentMethodRow[]\n domains: PaymentMethodDomainRecord[]\n accountConnected: boolean\n /** The caller may save toggles: a site admin. */\n canEdit: boolean\n /** The caller may open Stripe to finish a method: the organization owner. */\n canFinish: boolean\n warnings: string[]\n}\n\n/** How long the platform's configuration is trusted in memory. */\nconst PLATFORM_CONFIGURATION_TTL_MS = 10 * 60 * 1000\n\nlet platformCache: { at: number; value: Record<string, PlatformAvailability> } | null = null\n\n/** Test seam: forget the cached platform configuration. */\nexport function resetPlatformPaymentMethodCacheForTests(): void {\n platformCache = null\n}\n\nasync function stripe<T>(\n method: 'GET' | 'POST',\n path: string,\n params?: URLSearchParams,\n idempotencyKey?: string,\n): Promise<T> {\n const query = method === 'GET' && params ? `?${params}` : ''\n const response = await fetch(`https://api.stripe.com/v1/${path}${query}`, {\n method,\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n ...(method === 'POST' && { 'Content-Type': 'application/x-www-form-urlencoded' }),\n ...(idempotencyKey && { 'Idempotency-Key': idempotencyKey }),\n },\n ...(method === 'POST' && params && { body: params.toString() }),\n })\n const payload = (await response.json().catch(() => ({}))) as T & {\n error?: { message?: string }\n }\n if (!response.ok) {\n throw new Error(payload?.error?.message ?? `Stripe ${path} failed (${response.status})`)\n }\n return payload\n}\n\ninterface StripeConfiguration {\n is_default?: boolean\n application?: string | null\n active?: boolean\n [key: string]: unknown\n}\n\n/**\n * Which methods the platform's own default configuration offers. The list\n * also returns configurations OTHER Connect applications made for this\n * account (`application` set); those do not govern our sessions and are\n * skipped. `null` per method when Stripe could not be asked — the card then\n * shows the toggle without a verdict rather than hiding a method that may work.\n */\nexport async function platformPaymentMethodAvailability(): Promise<\n Record<string, PlatformAvailability>\n> {\n if (platformCache && Date.now() - platformCache.at < PLATFORM_CONFIGURATION_TTL_MS) {\n return platformCache.value\n }\n const value: Record<string, PlatformAvailability> = {}\n try {\n const list = await stripe<{ data?: StripeConfiguration[] }>(\n 'GET',\n 'payment_method_configurations',\n new URLSearchParams({ limit: '20' }),\n )\n const own =\n list.data?.find((entry) => entry.is_default && !entry.application) ??\n list.data?.find((entry) => !entry.application) ??\n null\n for (const method of STOREFRONT_PAYMENT_METHODS) {\n if (!own) {\n value[method.id] = null\n continue\n }\n const entry = own[method.configurationKey] as\n | { available?: boolean; display_preference?: { value?: string } }\n | undefined\n value[method.id] =\n entry?.available === true && entry?.display_preference?.value === 'on'\n ? 'on'\n : 'unavailable'\n }\n platformCache = { at: Date.now(), value }\n } catch (error) {\n console.warn('[commerce] payment method configuration unreadable', error)\n for (const method of STOREFRONT_PAYMENT_METHODS) value[method.id] = null\n }\n return value\n}\n\nfunction capabilityStatus(\n capabilities: Record<string, string> | undefined,\n key: string | undefined,\n): CapabilityStatus {\n if (!key) return null\n const status = capabilities?.[key]\n if (status === 'active' || status === 'pending' || status === 'inactive') return status\n return 'unrequested'\n}\n\nasync function readAccountCapabilities(\n accountId: string | null,\n): Promise<Record<string, string> | undefined> {\n if (!accountId) return undefined\n try {\n const account = await stripe<{ capabilities?: Record<string, string> }>(\n 'GET',\n `accounts/${encodeURIComponent(accountId)}`,\n )\n return account.capabilities ?? {}\n } catch (error) {\n console.warn('[commerce] connected account unreadable', error)\n return undefined\n }\n}\n\n/** The capabilities a save asks Stripe for: on, offered, not yet requested. */\nexport function capabilitiesToRequest(\n settings: StorefrontPaymentMethodSettings,\n platform: Record<string, PlatformAvailability>,\n capabilities: Record<string, string> | undefined,\n): string[] {\n return STOREFRONT_PAYMENT_METHODS.filter(\n (method) =>\n method.capability &&\n isStorefrontPaymentMethodOn(settings, method.id) &&\n platform[method.id] !== 'unavailable' &&\n capabilityStatus(capabilities, method.capability) === 'unrequested',\n ).map((method) => method.capability as string)\n}\n\nexport function buildPaymentMethodRows(\n settings: StorefrontPaymentMethodSettings,\n platform: Record<string, PlatformAvailability>,\n capabilities: Record<string, string> | undefined,\n): PaymentMethodRow[] {\n return STOREFRONT_PAYMENT_METHODS.map((method) => ({\n id: method.id,\n on: isStorefrontPaymentMethodOn(settings, method.id),\n platform: platform[method.id] ?? null,\n capability: capabilities ? capabilityStatus(capabilities, method.capability) : null,\n }))\n}\n\nconst json = (body: unknown, status = 200) => Response.json(body, { status })\n\n/**\n * Where Stripe sends the owner back: the console page they pressed the button\n * on, judged against the request's own origin so a forged `Referer` cannot\n * turn the link into a redirect to somewhere else.\n */\nexport function consoleReturnUrl(headers: Partial<Record<string, string>>): string {\n const origin = headers.origin || (headers.host ? `https://${headers.host}` : '')\n const referer = headers.referer ?? ''\n try {\n if (origin && referer && new URL(referer).origin === new URL(origin).origin) {\n return referer\n }\n } catch {\n // Unparseable: fall through to the origin.\n }\n return origin || 'https://localhost/'\n}\n\nexport async function paymentMethodsHandler(request: Request): Promise<Response> {\n const { method, headers: rawHeaders, query, body } = await pluginRequestFromWeb(request)\n const headers = rawHeaders as Partial<Record<string, string>>\n if (method !== 'GET' && method !== 'POST') {\n return json({ error: 'Method not allowed' }, 405)\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return json({ error: 'Payments are not configured (STRIPE_SECRET_KEY).' }, 501)\n }\n const authorization = headers.authorization ?? ''\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return json({ error: 'Unauthenticated' }, 401)\n\n const parsed =\n typeof body === 'string' ? (JSON.parse(body || '{}') as Record<string, unknown>) : (body ?? {})\n const hostId = String(\n (method === 'GET' ? query?.['hostId'] : (parsed as Record<string, unknown>)['hostId']) ?? '',\n )\n if (!hostId) return json({ error: 'Missing hostId' }, 400)\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return emailUnverifiedResponse()\n }\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) return json({ error: 'Not found' }, 404)\n\n // An allowlist. Reading the card is for whoever works the store's orders\n // or changes its methods; a change asks Stripe for capabilities on the\n // owner's payout account, so it is \"Manage payment methods\" (AGL-4047),\n // whose preset is the site Admin who alone made it before, as the\n // reader's is the Admin and Editor.\n const mayEdit = holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.paymentMethods')\n const mayRead = mayEdit || holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.orders')\n if (!mayRead) return json({ error: 'Not found' }, 404)\n if (method === 'POST' && !mayEdit) {\n return json({ error: commerceSitePermissionRefusal('commerce.paymentMethods') }, 403)\n }\n\n const owner = await getOrgForHost(hostId)\n const locked = await lockdownRefusal({\n request,\n staff: decoded['staff'] === true,\n uid: decoded.uid,\n org: owner?.org,\n host: hostSnapshot.data(),\n })\n if (locked) return locked\n if (!checkEntitlement((owner?.org ?? {}) as never, 'commerce')) {\n return json({ error: 'Selling is not included on this plan' }, 402)\n }\n\n const ownerUid = String(owner?.org?.ownerUid ?? '')\n const accountId = ownerUid\n ? (((await firestore.collection('profiles').doc(ownerUid).get()).get(\n 'stripeAccountId',\n ) as string | undefined) ?? null)\n : null\n\n const storeRef = hostRef.collection('settings').doc('store')\n let settings = normalizeStorefrontPaymentMethodSettings(\n (await storeRef.get()).get('paymentMethods'),\n )\n const platform = await platformPaymentMethodAvailability()\n let capabilities = await readAccountCapabilities(accountId)\n const warnings: string[] = []\n\n // FINISH IN STRIPE: a capability Stripe holds `inactive` needs details\n // only the account holder can give, and an Express account has no login of\n // its own, so a link minted here is the only way in. The owner's alone,\n // as connecting the account is (`connect.ts`): the link opens the owner's\n // identity and bank details.\n if (method === 'POST' && (parsed as Record<string, unknown>)['action'] === 'finish') {\n if (!accountId || decoded.uid !== ownerUid) {\n return json({ error: 'Only the organization owner can finish this in Stripe' }, 403)\n }\n const back = consoleReturnUrl(headers)\n const link = await stripe<{ url?: string }>(\n 'POST',\n 'account_links',\n new URLSearchParams({\n account: accountId,\n type: 'account_onboarding',\n 'collection_options[fields]': 'currently_due',\n refresh_url: back,\n return_url: back,\n }),\n )\n return json({ url: link.url ?? null })\n }\n\n if (method === 'POST') {\n const requested = normalizeStorefrontPaymentMethodSettings(\n (parsed as Record<string, unknown>)['methods'],\n )\n if (!Object.keys(requested).length) {\n return json({ error: 'Nothing to save' }, 400)\n }\n settings = { ...settings, ...requested }\n await storeRef.set(\n { paymentMethods: settings, paymentMethodsUpdatedAtMs: Date.now(), paymentMethodsUpdatedBy: decoded.uid },\n { merge: true },\n )\n const wanted = accountId ? capabilitiesToRequest(settings, platform, capabilities) : []\n if (accountId && wanted.length) {\n const params = new URLSearchParams()\n for (const capability of wanted) {\n params.set(`capabilities[${capability}][requested]`, 'true')\n }\n try {\n const account = await stripe<{ capabilities?: Record<string, string> }>(\n 'POST',\n `accounts/${encodeURIComponent(accountId)}`,\n params,\n `aglyn-pm-capabilities:${accountId}:${[...wanted].sort().join(',')}`,\n )\n capabilities = account.capabilities ?? capabilities\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n warnings.push(\n `Stripe did not accept the request to enable ${wanted.join(', ')} on your payout account: ${message}`,\n )\n }\n }\n }\n\n const answer: PaymentMethodsAnswer = {\n methods: buildPaymentMethodRows(settings, platform, capabilities),\n domains: await readSiteDomainRecords(\n hostSnapshot.data() as SiteReturnHost | undefined,\n await directSellerAccountForHost(hostId),\n ),\n accountConnected: Boolean(accountId),\n canEdit: mayEdit,\n canFinish: Boolean(accountId) && decoded.uid === ownerUid,\n warnings,\n }\n return json(answer)\n } catch (error) {\n const unauthenticated = invalidIdTokenResponse(error)\n if (unauthenticated) return unauthenticated\n console.error(error)\n return json({ error: 'Payment methods could not be loaded' }, 500)\n }\n}\n"],"names":["directSellerAccountForHost","checkEntitlement","pluginRequestFromWeb","emailUnverifiedResponse","firebaseAdmin","getOrgForHost","isImpersonationSession","lockdownRefusal","invalidIdTokenResponse","isStorefrontPaymentMethodOn","normalizeStorefrontPaymentMethodSettings","STOREFRONT_PAYMENT_METHODS","commerceSitePermissionRefusal","holdsCommerceSiteKey","readSiteDomainRecords","PLATFORM_CONFIGURATION_TTL_MS","platformCache","resetPlatformPaymentMethodCacheForTests","stripe","method","path","params","idempotencyKey","query","response","fetch","headers","Authorization","process","env","STRIPE_SECRET_KEY","body","toString","payload","json","catch","ok","Error","error","message","status","platformPaymentMethodAvailability","Date","now","at","value","list","URLSearchParams","limit","own","data","find","entry","is_default","application","id","configurationKey","available","display_preference","console","warn","capabilityStatus","capabilities","key","readAccountCapabilities","accountId","undefined","account","encodeURIComponent","capabilitiesToRequest","settings","platform","filter","capability","map","buildPaymentMethodRows","on","Response","consoleReturnUrl","origin","host","referer","URL","paymentMethodsHandler","request","rawHeaders","authorization","idToken","startsWith","slice","length","parsed","JSON","parse","hostId","String","owner","decoded","app","auth","verifyIdToken","email_verified","firestore","hostRef","collection","doc","hostSnapshot","get","exists","mayEdit","uid","mayRead","locked","staff","org","ownerUid","storeRef","warnings","link","back","type","refresh_url","return_url","url","requested","Object","keys","set","paymentMethods","paymentMethodsUpdatedAtMs","paymentMethodsUpdatedBy","merge","wanted","sort","join","push","answer","methods","domains","accountConnected","Boolean","canEdit","canFinish","unauthenticated"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC,gBAAgB,EAAEC,oBAAoB,QAAQ,sBAAqB;AAE5E,SACEC,uBAAuB,EACvBC,aAAa,EACbC,aAAa,EACbC,sBAAsB,EACtBC,eAAe,QACV,2BAA0B;AACjC,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SACEC,2BAA2B,EAC3BC,wCAAwC,EACxCC,0BAA0B,QAGrB,uCAAmC;AAC1C,SAASC,6BAA6B,QAAQ,iCAA6B;AAC3E,SAASC,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AK,MAAM0B,cAAc2D,OAAQ;oBAC/B/G,OAAO0G,GAAG,CAAC,CAAC,aAAa,EAAEtD,WAAW,YAAY,CAAC,EAAE;gBACvD;gBACA,IAAI;wBAOaN;oBANf,MAAMA,UAAU,MAAMjD,OACpB,QACA,CAAC,SAAS,EAAEkD,mBAAmBH,YAAY,EAC3C5C,QACA,CAAC,sBAAsB,EAAE4C,UAAU,CAAC,EAAE;2BAAImE;qBAAO,CAACC,IAAI,GAAGC,IAAI,CAAC,MAAM;oBAEtExE,gBAAeK,wBAAAA,QAAQL,YAAY,YAApBK,wBAAwBL;gBACzC,EAAE,OAAOxB,OAAO;oBACd,MAAMC,UAAUD,iBAAiBD,QAAQC,MAAMC,OAAO,GAAGwD,OAAOzD;oBAChE+E,SAASkB,IAAI,CACX,CAAC,4CAA4C,EAAEH,OAAOE,IAAI,CAAC,MAAM,yBAAyB,EAAE/F,SAAS;gBAEzG;YACF;QACF;QAEA,MAAMiG,SAA+B;YACnCC,SAAS9D,uBAAuBL,UAAUC,UAAUT;YACpD4E,SAAS,MAAM5H,sBACb4F,aAAaxD,IAAI,IACjB,MAAMlD,2BAA2B8F;YAEnC6C,kBAAkBC,QAAQ3E;YAC1B4E,SAAShC;YACTiC,WAAWF,QAAQ3E,cAAcgC,QAAQa,GAAG,KAAKK;YACjDE;QACF;QACA,OAAOnF,KAAKsG;IACd,EAAE,OAAOlG,OAAO;QACd,MAAMyG,kBAAkBvI,uBAAuB8B;QAC/C,IAAIyG,iBAAiB,OAAOA;QAC5BpF,QAAQrB,KAAK,CAACA;QACd,OAAOJ,KAAK;YAAEI,OAAO;QAAsC,GAAG;IAChE;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/payment-methods.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 { directSellerAccountForHost } from './seller-stripe-account'\nimport { checkEntitlement, pluginRequestFromWeb } from '@aglyn/aglyn/server'\nimport type { SiteReturnHost } from '@aglyn/aglyn/app-utils/site-return-url'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n getOrgForHost,\n isImpersonationSession,\n lockdownRefusal,\n} from '@aglyn/tenant-data-admin'\nimport { invalidIdTokenResponse } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport {\n merchantAccountInOtherMode,\n paymentProvider,\n} from '@aglyn/tenant-data-admin/server/payment-provider'\nimport {\n isStorefrontPaymentMethodOn,\n normalizeStorefrontPaymentMethodSettings,\n STOREFRONT_PAYMENT_METHODS,\n type StorefrontPaymentMethodId,\n type StorefrontPaymentMethodSettings,\n} from '../model/commerce-payment-methods'\nimport { commerceSitePermissionRefusal } from '../model/plugin-permissions'\nimport { holdsCommerceSiteKey } from './commerce-site-keys'\nimport {\n type PaymentMethodDomainRecord,\n readSiteDomainRecords,\n} from './payment-method-domains'\n\n/**\n * The merchant's payment methods card (AGL-3629):\n * `GET|POST /api/commerce/payment-methods?hostId=…`, served by the console.\n *\n * GET answers, per method, three facts the card needs and no client can read:\n *\n * - whether the PLATFORM offers it (its default payment method configuration\n * — storefront charges are destination charges with the platform as\n * merchant of record, so that configuration is the ceiling). A method the\n * platform has not turned on, or that Stripe has not made available to it,\n * is reported `unavailable` and the card does not show it at all;\n * - the connected account's capability for it, which Stripe asks platforms to\n * request before an account accepts BNPL, Cash App, Amazon Pay or crypto;\n * - the site's domain registrations, which Apple Pay depends on.\n *\n * POST saves the toggles to `hosts/{hostId}/settings/store.paymentMethods` and\n * requests the capability of each method turned on, in one account update with\n * an idempotency key. Server-side, because the toggle and the capability are\n * one decision: a toggle saved by the browser with no capability behind it\n * would read as on and never appear.\n */\n\nexport type PlatformAvailability = 'on' | 'unavailable' | null\n\nexport type CapabilityStatus = 'active' | 'pending' | 'inactive' | 'unrequested' | null\n\nexport interface PaymentMethodRow {\n id: StorefrontPaymentMethodId\n on: boolean\n platform: PlatformAvailability\n capability: CapabilityStatus\n}\n\nexport interface PaymentMethodsAnswer {\n methods: PaymentMethodRow[]\n domains: PaymentMethodDomainRecord[]\n accountConnected: boolean\n /** The caller may save toggles: a site admin. */\n canEdit: boolean\n /** The caller may open Stripe to finish a method: the organization owner. */\n canFinish: boolean\n warnings: string[]\n}\n\n/** How long the platform's configuration is trusted in memory. */\nconst PLATFORM_CONFIGURATION_TTL_MS = 10 * 60 * 1000\n\nlet platformCache: { at: number; value: Record<string, PlatformAvailability> } | null = null\n\n/** Test seam: forget the cached platform configuration. */\nexport function resetPlatformPaymentMethodCacheForTests(): void {\n platformCache = null\n}\n\nasync function stripe<T>(\n method: 'GET' | 'POST',\n path: string,\n params?: URLSearchParams,\n idempotencyKey?: string,\n): Promise<T> {\n const query = method === 'GET' && params ? `?${params}` : ''\n const response = await fetch(`https://api.stripe.com/v1/${path}${query}`, {\n method,\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n ...(method === 'POST' && { 'Content-Type': 'application/x-www-form-urlencoded' }),\n ...(idempotencyKey && { 'Idempotency-Key': idempotencyKey }),\n },\n ...(method === 'POST' && params && { body: params.toString() }),\n })\n const payload = (await response.json().catch(() => ({}))) as T & {\n error?: { message?: string }\n }\n if (!response.ok) {\n throw new Error(payload?.error?.message ?? `Stripe ${path} failed (${response.status})`)\n }\n return payload\n}\n\ninterface StripeConfiguration {\n is_default?: boolean\n application?: string | null\n active?: boolean\n [key: string]: unknown\n}\n\n/**\n * Which methods the platform's own default configuration offers. The list\n * also returns configurations OTHER Connect applications made for this\n * account (`application` set); those do not govern our sessions and are\n * skipped. `null` per method when Stripe could not be asked — the card then\n * shows the toggle without a verdict rather than hiding a method that may work.\n */\nexport async function platformPaymentMethodAvailability(): Promise<\n Record<string, PlatformAvailability>\n> {\n if (platformCache && Date.now() - platformCache.at < PLATFORM_CONFIGURATION_TTL_MS) {\n return platformCache.value\n }\n const value: Record<string, PlatformAvailability> = {}\n try {\n const list = await stripe<{ data?: StripeConfiguration[] }>(\n 'GET',\n 'payment_method_configurations',\n new URLSearchParams({ limit: '20' }),\n )\n const own =\n list.data?.find((entry) => entry.is_default && !entry.application) ??\n list.data?.find((entry) => !entry.application) ??\n null\n for (const method of STOREFRONT_PAYMENT_METHODS) {\n if (!own) {\n value[method.id] = null\n continue\n }\n const entry = own[method.configurationKey] as\n | { available?: boolean; display_preference?: { value?: string } }\n | undefined\n value[method.id] =\n entry?.available === true && entry?.display_preference?.value === 'on'\n ? 'on'\n : 'unavailable'\n }\n platformCache = { at: Date.now(), value }\n } catch (error) {\n console.warn('[commerce] payment method configuration unreadable', error)\n for (const method of STOREFRONT_PAYMENT_METHODS) value[method.id] = null\n }\n return value\n}\n\nfunction capabilityStatus(\n capabilities: Record<string, string> | undefined,\n key: string | undefined,\n): CapabilityStatus {\n if (!key) return null\n const status = capabilities?.[key]\n if (status === 'active' || status === 'pending' || status === 'inactive') return status\n return 'unrequested'\n}\n\nasync function readAccountCapabilities(\n accountId: string | null,\n): Promise<Record<string, string> | undefined> {\n if (!accountId) return undefined\n try {\n const account = await stripe<{ capabilities?: Record<string, string> }>(\n 'GET',\n `accounts/${encodeURIComponent(accountId)}`,\n )\n return account.capabilities ?? {}\n } catch (error) {\n console.warn('[commerce] connected account unreadable', error)\n return undefined\n }\n}\n\n/** The capabilities a save asks Stripe for: on, offered, not yet requested. */\nexport function capabilitiesToRequest(\n settings: StorefrontPaymentMethodSettings,\n platform: Record<string, PlatformAvailability>,\n capabilities: Record<string, string> | undefined,\n): string[] {\n return STOREFRONT_PAYMENT_METHODS.filter(\n (method) =>\n method.capability &&\n isStorefrontPaymentMethodOn(settings, method.id) &&\n platform[method.id] !== 'unavailable' &&\n capabilityStatus(capabilities, method.capability) === 'unrequested',\n ).map((method) => method.capability as string)\n}\n\nexport function buildPaymentMethodRows(\n settings: StorefrontPaymentMethodSettings,\n platform: Record<string, PlatformAvailability>,\n capabilities: Record<string, string> | undefined,\n): PaymentMethodRow[] {\n return STOREFRONT_PAYMENT_METHODS.map((method) => ({\n id: method.id,\n on: isStorefrontPaymentMethodOn(settings, method.id),\n platform: platform[method.id] ?? null,\n capability: capabilities ? capabilityStatus(capabilities, method.capability) : null,\n }))\n}\n\nconst json = (body: unknown, status = 200) => Response.json(body, { status })\n\n/**\n * Where Stripe sends the owner back: the console page they pressed the button\n * on, judged against the request's own origin so a forged `Referer` cannot\n * turn the link into a redirect to somewhere else.\n */\nexport function consoleReturnUrl(headers: Partial<Record<string, string>>): string {\n const origin = headers.origin || (headers.host ? `https://${headers.host}` : '')\n const referer = headers.referer ?? ''\n try {\n if (origin && referer && new URL(referer).origin === new URL(origin).origin) {\n return referer\n }\n } catch {\n // Unparseable: fall through to the origin.\n }\n return origin || 'https://localhost/'\n}\n\nexport async function paymentMethodsHandler(request: Request): Promise<Response> {\n const { method, headers: rawHeaders, query, body } = await pluginRequestFromWeb(request)\n const headers = rawHeaders as Partial<Record<string, string>>\n if (method !== 'GET' && method !== 'POST') {\n return json({ error: 'Method not allowed' }, 405)\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return json({ error: 'Payments are not configured (STRIPE_SECRET_KEY).' }, 501)\n }\n const authorization = headers.authorization ?? ''\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return json({ error: 'Unauthenticated' }, 401)\n\n const parsed =\n typeof body === 'string' ? (JSON.parse(body || '{}') as Record<string, unknown>) : (body ?? {})\n const hostId = String(\n (method === 'GET' ? query?.['hostId'] : (parsed as Record<string, unknown>)['hostId']) ?? '',\n )\n if (!hostId) return json({ error: 'Missing hostId' }, 400)\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return emailUnverifiedResponse()\n }\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) return json({ error: 'Not found' }, 404)\n\n // An allowlist. Reading the card is for whoever works the store's orders\n // or changes its methods; a change asks Stripe for capabilities on the\n // owner's payout account, so it is \"Manage payment methods\" (AGL-4047),\n // whose preset is the site Admin who alone made it before, as the\n // reader's is the Admin and Editor.\n const mayEdit = holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.paymentMethods')\n const mayRead = mayEdit || holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.orders')\n if (!mayRead) return json({ error: 'Not found' }, 404)\n if (method === 'POST' && !mayEdit) {\n return json({ error: commerceSitePermissionRefusal('commerce.paymentMethods') }, 403)\n }\n\n const owner = await getOrgForHost(hostId)\n const locked = await lockdownRefusal({\n request,\n staff: decoded['staff'] === true,\n uid: decoded.uid,\n org: owner?.org,\n host: hostSnapshot.data(),\n })\n if (locked) return locked\n if (!checkEntitlement((owner?.org ?? {}) as never, 'commerce')) {\n return json({ error: 'Selling is not included on this plan' }, 402)\n }\n\n const ownerUid = String(owner?.org?.ownerUid ?? '')\n const ownerProfile = ownerUid\n ? await firestore.collection('profiles').doc(ownerUid).get()\n : null\n // An account RECORDED in the other Stripe mode (AGL-2471) is no payout\n // account here: this key cannot read it, every sale against it is\n // refused, and \"Set up payments\" replaces it. So nothing is asked of it,\n // and the methods read as waiting on Stripe, not as ready.\n const accountId =\n ownerProfile &&\n !merchantAccountInOtherMode(\n ownerProfile.get('stripeAccountLivemode'),\n paymentProvider().platformMode(),\n )\n ? ((ownerProfile.get('stripeAccountId') as string | undefined) ?? null)\n : null\n\n const storeRef = hostRef.collection('settings').doc('store')\n let settings = normalizeStorefrontPaymentMethodSettings(\n (await storeRef.get()).get('paymentMethods'),\n )\n const platform = await platformPaymentMethodAvailability()\n let capabilities = await readAccountCapabilities(accountId)\n const warnings: string[] = []\n\n // FINISH IN STRIPE: a capability Stripe holds `inactive` needs details\n // only the account holder can give, and an Express account has no login of\n // its own, so a link minted here is the only way in. The owner's alone,\n // as connecting the account is (`connect.ts`): the link opens the owner's\n // identity and bank details.\n if (method === 'POST' && (parsed as Record<string, unknown>)['action'] === 'finish') {\n if (!accountId || decoded.uid !== ownerUid) {\n return json({ error: 'Only the organization owner can finish this in Stripe' }, 403)\n }\n const back = consoleReturnUrl(headers)\n const link = await stripe<{ url?: string }>(\n 'POST',\n 'account_links',\n new URLSearchParams({\n account: accountId,\n type: 'account_onboarding',\n 'collection_options[fields]': 'currently_due',\n refresh_url: back,\n return_url: back,\n }),\n )\n return json({ url: link.url ?? null })\n }\n\n if (method === 'POST') {\n const requested = normalizeStorefrontPaymentMethodSettings(\n (parsed as Record<string, unknown>)['methods'],\n )\n if (!Object.keys(requested).length) {\n return json({ error: 'Nothing to save' }, 400)\n }\n settings = { ...settings, ...requested }\n await storeRef.set(\n { paymentMethods: settings, paymentMethodsUpdatedAtMs: Date.now(), paymentMethodsUpdatedBy: decoded.uid },\n { merge: true },\n )\n const wanted = accountId ? capabilitiesToRequest(settings, platform, capabilities) : []\n if (accountId && wanted.length) {\n const params = new URLSearchParams()\n for (const capability of wanted) {\n params.set(`capabilities[${capability}][requested]`, 'true')\n }\n try {\n const account = await stripe<{ capabilities?: Record<string, string> }>(\n 'POST',\n `accounts/${encodeURIComponent(accountId)}`,\n params,\n `aglyn-pm-capabilities:${accountId}:${[...wanted].sort().join(',')}`,\n )\n capabilities = account.capabilities ?? capabilities\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n warnings.push(\n `Stripe did not accept the request to enable ${wanted.join(', ')} on your payout account: ${message}`,\n )\n }\n }\n }\n\n const answer: PaymentMethodsAnswer = {\n methods: buildPaymentMethodRows(settings, platform, capabilities),\n domains: await readSiteDomainRecords(\n hostSnapshot.data() as SiteReturnHost | undefined,\n await directSellerAccountForHost(hostId),\n ),\n accountConnected: Boolean(accountId),\n canEdit: mayEdit,\n canFinish: Boolean(accountId) && decoded.uid === ownerUid,\n warnings,\n }\n return json(answer)\n } catch (error) {\n const unauthenticated = invalidIdTokenResponse(error)\n if (unauthenticated) return unauthenticated\n console.error(error)\n return json({ error: 'Payment methods could not be loaded' }, 500)\n }\n}\n"],"names":["directSellerAccountForHost","checkEntitlement","pluginRequestFromWeb","emailUnverifiedResponse","firebaseAdmin","getOrgForHost","isImpersonationSession","lockdownRefusal","invalidIdTokenResponse","merchantAccountInOtherMode","paymentProvider","isStorefrontPaymentMethodOn","normalizeStorefrontPaymentMethodSettings","STOREFRONT_PAYMENT_METHODS","commerceSitePermissionRefusal","holdsCommerceSiteKey","readSiteDomainRecords","PLATFORM_CONFIGURATION_TTL_MS","platformCache","resetPlatformPaymentMethodCacheForTests","stripe","method","path","params","idempotencyKey","query","response","fetch","headers","Authorization","process","env","STRIPE_SECRET_KEY","body","toString","payload","json","catch","ok","Error","error","message","status","platformPaymentMethodAvailability","Date","now","at","value","list","URLSearchParams","limit","own","data","find","entry","is_default","application","id","configurationKey","available","display_preference","console","warn","capabilityStatus","capabilities","key","readAccountCapabilities","accountId","undefined","account","encodeURIComponent","capabilitiesToRequest","settings","platform","filter","capability","map","buildPaymentMethodRows","on","Response","consoleReturnUrl","origin","host","referer","URL","paymentMethodsHandler","request","rawHeaders","authorization","idToken","startsWith","slice","length","parsed","JSON","parse","hostId","String","ownerProfile","owner","decoded","app","auth","verifyIdToken","email_verified","firestore","hostRef","collection","doc","hostSnapshot","get","exists","mayEdit","uid","mayRead","locked","staff","org","ownerUid","platformMode","storeRef","warnings","link","back","type","refresh_url","return_url","url","requested","Object","keys","set","paymentMethods","paymentMethodsUpdatedAtMs","paymentMethodsUpdatedBy","merge","wanted","sort","join","push","answer","methods","domains","accountConnected","Boolean","canEdit","canFinish","unauthenticated"],"mappings":";AAAA;;;;;;;;;;;;;;;C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