@aglyn/plugins-commerce 1.29.1 → 1.29.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/checkout-tax-blocked-notice.component.d.ts +18 -0
- package/src/lib/components/console/checkout-tax-blocked-notice.component.js +67 -0
- package/src/lib/components/console/checkout-tax-blocked-notice.component.js.map +1 -0
- package/src/lib/components/console/payments-settings-card.component.d.ts +2 -2
- package/src/lib/components/console/payments-settings-card.component.js +99 -5
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +14 -3
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/stripe-tax-readiness.component.d.ts +45 -0
- package/src/lib/components/console/stripe-tax-readiness.component.js +276 -0
- package/src/lib/components/console/stripe-tax-readiness.component.js.map +1 -0
- package/src/lib/components/console/tax-settings-card.component.js +22 -8
- package/src/lib/components/console/tax-settings-card.component.js.map +1 -1
- package/src/lib/constants/operator-alerts.d.ts +9 -0
- package/src/lib/constants/operator-alerts.js +22 -1
- package/src/lib/constants/operator-alerts.js.map +1 -1
- package/src/lib/declarations.server.js +11 -0
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/model/commerce-tax-readiness.d.ts +79 -0
- package/src/lib/model/commerce-tax-readiness.js +99 -0
- package/src/lib/model/commerce-tax-readiness.js.map +1 -0
- package/src/lib/model/commerce.d.ts +7 -0
- package/src/lib/model/commerce.js +17 -4
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/payments-setup-status.d.ts +68 -0
- package/src/lib/model/payments-setup-status.js +103 -0
- package/src/lib/model/payments-setup-status.js.map +1 -0
- package/src/lib/plan-entitlements.d.ts +2 -1
- package/src/lib/plan-entitlements.js +2 -1
- package/src/lib/plan-entitlements.js.map +1 -1
- package/src/lib/server/cart-checkout.js +3 -0
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/checkout-tax-refusal.d.ts +51 -0
- package/src/lib/server/checkout-tax-refusal.js +133 -0
- package/src/lib/server/checkout-tax-refusal.js.map +1 -0
- package/src/lib/server/checkout.d.ts +2 -1
- package/src/lib/server/checkout.js +7 -2
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/connect-prefill.d.ts +65 -0
- package/src/lib/server/connect-prefill.js +85 -0
- package/src/lib/server/connect-prefill.js.map +1 -0
- package/src/lib/server/connect.d.ts +4 -2
- package/src/lib/server/connect.js +117 -37
- package/src/lib/server/connect.js.map +1 -1
- package/src/lib/server/draft-order.js +4 -2
- package/src/lib/server/draft-order.js.map +1 -1
- package/src/lib/server/pos-order.js +1 -1
- package/src/lib/server/pos-order.js.map +1 -1
- package/src/lib/server/product-writer.d.ts +27 -0
- package/src/lib/server/product-writer.js +174 -4
- package/src/lib/server/product-writer.js.map +1 -1
- package/src/lib/server/quote-pay.d.ts +6 -0
- package/src/lib/server/quote-pay.js +8 -2
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/seller-stripe-account.d.ts +19 -0
- package/src/lib/server/seller-stripe-account.js +40 -4
- package/src/lib/server/seller-stripe-account.js.map +1 -1
- package/src/lib/server/site-page-resolver.d.ts +1 -6
- package/src/lib/server/site-page-resolver.js +4 -12
- package/src/lib/server/site-page-resolver.js.map +1 -1
- package/src/lib/server/site-search.d.ts +43 -0
- package/src/lib/server/site-search.js +124 -0
- package/src/lib/server/site-search.js.map +1 -0
- package/src/lib/server/tax-readiness.d.ts +56 -0
- package/src/lib/server/tax-readiness.js +169 -0
- package/src/lib/server/tax-readiness.js.map +1 -0
- package/src/lib/server.js +6 -0
- package/src/lib/server.js.map +1 -1
- package/src/lib/transfer/product-image-copy.server.d.ts +77 -0
- package/src/lib/transfer/product-image-copy.server.js +307 -0
- package/src/lib/transfer/product-image-copy.server.js.map +1 -0
- package/src/lib/transfer/product-images.d.ts +62 -0
- package/src/lib/transfer/product-images.js +143 -0
- package/src/lib/transfer/product-images.js.map +1 -0
- package/src/lib/transfer/product-sources.d.ts +92 -0
- package/src/lib/transfer/product-sources.js +519 -0
- package/src/lib/transfer/product-sources.js.map +1 -0
- package/src/lib/transfer/product-transfer.d.ts +26 -1
- package/src/lib/transfer/product-transfer.js +283 -11
- package/src/lib/transfer/product-transfer.js.map +1 -1
- package/src/lib/transfer/products.server.d.ts +29 -3
- package/src/lib/transfer/products.server.js +289 -13
- package/src/lib/transfer/products.server.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/quote-pay.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 ACCOUNTS_PLUGIN_ID,\n checkEntitlement,\n claimAttempt,\n deriveStripeObjectKey,\n resolveHostEnabledPlugins,\n resolveTransactionFeeCents,\n type PluginApiHandler,\n type PluginApiRequest,\n} from '@aglyn/aglyn/server'\nimport { resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport { readClientIp } from '@aglyn/aglyn/app-utils/request-ip'\nimport { type SiteReturnHost, siteReturnOrigin } from '@aglyn/aglyn/app-utils/site-return-url'\nimport { consumeRateLimit, firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport {\n connectedAccountHeader,\n directChargeParams,\n merchantAccountIsReady,\n saleChargeModel,\n type SaleChargeModel,\n} from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { checkoutSessionCardAuthenticationParams } from '@aglyn/tenant-data-admin/server/stripe-card-authentication'\nimport { quotePageHref } from '../constants/quote-page'\nimport * as CommerceModel from '../model'\nimport { expireCheckoutSession, type CheckoutSessionExpiry } from './checkout-session-expiry'\nimport { resolveManualTaxRateId } from './manual-tax-rate'\nimport {\n applyNativeCheckoutParams,\n nativeCheckoutStripeHeaders,\n readCheckoutSessionPayload,\n resolveNativeCheckoutMode,\n type NativeCheckoutMode,\n} from './native-checkout'\nimport { orderStatusUrl } from './order-status-token'\nimport { MEMBER_SESSIONS_VALID_FROM_FIELD, memberCookieName, parseMemberSession } from './membership'\nimport { ensureCheckoutDomain } from './payment-method-domains'\nimport { verifyQuoteLinkToken } from './quote-link-token'\nimport { SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE, sellerStripeTaxActive } from './seller-stripe-account'\n\n/*==========================================\n * THE CUSTOMER'S QUOTE PAGE AND ITS PAY BUTTON (AGL-4094), AND AN\n * INVOICE'S (AGL-4099).\n *\n * GET /api/commerce/quote-view?hostId=&q=<quoteId>&t=<token>\n * → 200 QuotePageView | 200 { state: 'replaced', storeName } | 404\n * POST /api/commerce/quote-pay { hostId, q, t, v } + Idempotency-Key\n * → 200 { url } (Stripe's page) | 200 { clientSecret, publishableKey, sessionId, wallets? }\n * (the in-page form) | 409 { error, reason } | 410 { error, replaced: true } | 404\n *\n * The signed link (`quote-link-token.ts`) is the whole credential. A wrong\n * token answers exactly as a missing quote does, so neither route tells\n * anyone which quote ids exist; both are rate-limited per address per site\n * BEFORE the token check, so guessing costs what looking does. A link signed\n * for an older version of the quote opens the replaced page and nothing else.\n *\n * Pay opens a FRESH Checkout Session from the stored quote on every press:\n * the prices are the stored lines', never anything the page sends, and the\n * session the previous press opened is expired first, so two sessions for one\n * quote can never both be open. The quote keeps the open one in\n * `checkoutSessionId`. A Stripe session lapses after a day; the quote and its\n * link do not, because the next press opens another.\n *\n * The payment completes in `billing-webhook.ts`, which turns this same\n * document into the order (`paidQuoteOrder`); nothing here marks it paid.\n *\n * THE PAGE OFFERS ONLY A PAY THAT WORKS (AGL-4162). The view asks the same\n * payments check Pay refuses on ({@link payLinkPayments}) and prices the tax\n * the same way (`quotePayTax`): a quote saved before the store chose its\n * sales tax is shown and charged under the store's choice now, and Pay\n * refuses when that choice is not the one the page showed (`tax`). The\n * session carries that basis (`quoteTax`) so the paid order records it.\n *\n * AN INVOICE'S LINK IS THIS ONE (AGL-4099). A draft order the business sent\n * an invoice for opens on the same page from the same kind of link (its\n * version on `payLink.version`, `commerce-invoices.ts`), as \"Invoice #N\" with\n * no proofs or approval, and Pay opens the same kind of fresh session from\n * its stored lines, discount, tax and the shipping rates it was made with.\n * Its webhook is the draft branch it always completed through, which flips\n * the draft to paid without restamping its list fields. The proof and answer\n * routes stay a quote's alone: `loadLinkedQuote` opens an invoice only for\n * the routes that ask (`{ invoices: true }`).\n *=========================================*/\n\n/** Lookups and presses one address may make per site, per ten minutes. */\nexport const QUOTE_VIEW_LOOKUPS_PER_WINDOW = 60\nexport const QUOTE_PAY_PRESSES_PER_WINDOW = 20\nexport const QUOTE_WINDOW_MS = 10 * 60_000\n\nexport interface QuotePayDeps {\n firestore(): FirebaseFirestore.Firestore\n consumeRateLimit(key: string, options: { limit: number; windowMs: number }): Promise<{ allowed: boolean; resetMs: number }>\n orgForHost(hostId: string): Promise<{ id?: string; org?: any } | null>\n nativeMode(orgId: string): Promise<NativeCheckoutMode>\n /** The store's manual tax rate as a Stripe tax rate, or null when one cannot be had. */\n taxRateId(input: Parameters<typeof resolveManualTaxRateId>[0]): Promise<string | null>\n createSession(\n params: URLSearchParams,\n headers: Record<string, string>,\n ): Promise<{ ok: boolean; session: { id?: string; url?: string; client_secret?: string; error?: unknown } }>\n /**\n * Closes a session so it can no longer be paid. `stripeAccount` names the\n * seller's account for a session opened there (a direct charge); absent, the\n * session is the platform's.\n */\n expireSession(sessionId: string, stripeAccount?: string): Promise<CheckoutSessionExpiry>\n /**\n * Whether the seller's own Stripe Tax is set up, for a direct charge that\n * asks Stripe Tax. Absent, `sellerStripeTaxActive` answers.\n */\n sellerTaxActive?(accountId: string): Promise<boolean>\n /** Registers the page's domain for Apple Pay; never throws. */\n ensureDomain(input: Parameters<typeof ensureCheckoutDomain>[0]): Promise<unknown>\n /**\n * The site account a quote's customer signs in to (AGL-4206): the member\n * under that address, on a site that serves accounts; null for a guest.\n * Absent, every customer reads as a guest.\n */\n customerAccount?(input: { hostId: string; host: Record<string, unknown>; email: string }): Promise<QuoteCustomerAccount | null>\n now(): number\n}\n\n/** A quote customer's account on the site, as the sign-in check needs it. */\nexport interface QuoteCustomerAccount {\n id: string\n /** Sessions minted before this were revoked in bulk (AGL-914). */\n validFromMs: number\n suspended: boolean\n}\n\n/**\n * The member under `email` on a site that serves accounts, or null. A site\n * with User Accounts switched off has no sign-in page to send anyone to, so\n * every customer of it is a guest.\n */\nexport async function readQuoteCustomerAccount(input: {\n hostId: string\n host: Record<string, unknown>\n email: string\n}): Promise<QuoteCustomerAccount | null> {\n const owner = await getOrgForHost(input.hostId)\n if (!owner || !resolveHostEnabledPlugins(owner.org as never, input.host as never).includes(ACCOUNTS_PLUGIN_ID)) return null\n const found = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(input.hostId)\n .collection('siteMembers')\n .where('email', '==', input.email)\n .limit(1)\n .get()\n const member = found.docs[0]\n if (!member) return null\n return {\n id: member.id,\n validFromMs: Number(member.get(MEMBER_SESSIONS_VALID_FROM_FIELD) ?? 0) || 0,\n suspended: member.get('suspended') === true,\n }\n}\n\n/**\n * Whether this request may see the quote's proof and answer it (AGL-4206):\n * `open` unless the quote asks a customer with a site account to sign in and\n * this browser is not signed in to that account. Reads nothing for a quote\n * that does not ask, or a customer with no address.\n */\nexport async function quoteProofAccessFor(\n deps: QuotePayDeps,\n req: PluginApiRequest,\n input: { hostId: string; host: Record<string, unknown>; order: CommerceModel.HostOrder },\n): Promise<CommerceModel.QuoteProofAccess> {\n const quote = input.order.quote\n if (quote?.requireProofSignIn !== true) return 'open'\n const email = CommerceModel.quoteCustomerAccountEmail(quote)\n if (!email) return 'open'\n const account = deps.customerAccount ? await deps.customerAccount({ hostId: input.hostId, host: input.host, email }) : null\n const cookies = (req.cookies ?? {}) as Record<string, string | undefined>\n const session = parseMemberSession(input.hostId, cookies[memberCookieName(input.hostId)])\n // A session for the customer's account counts only while the account stands and the session was not revoked.\n const signedIn =\n session && account && session.memberId === account.id && (account.suspended || session.issuedAtMs < account.validFromMs)\n ? null\n : (session?.memberId ?? null)\n return CommerceModel.quoteProofAccess({ quote, accountId: account?.id ?? null, signedInAccountId: signedIn })\n}\n\n/** A proof route's answer while the proof waits on a sign-in. */\nexport function quoteProofAccessRefusal(access: Exclude<CommerceModel.QuoteProofAccess, 'open'>, storeName: string): QuoteLinkOutcome {\n return {\n status: 403,\n body: { error: CommerceModel.quoteProofAccessMessage(access, storeName), reason: access },\n }\n}\n\nexport function defaultQuotePayDeps(): QuotePayDeps {\n return {\n firestore: () => firebaseAdmin.app().firestore(),\n consumeRateLimit: (key, options) => consumeRateLimit(key, options),\n orgForHost: async (hostId) => {\n const found = await getOrgForHost(hostId)\n return found ? { id: found.orgId, org: found.org } : null\n },\n nativeMode: (orgId) => resolveNativeCheckoutMode(orgId),\n taxRateId: (input) => resolveManualTaxRateId(input),\n createSession: async (params, headers) => {\n const response = await fetch('https://api.stripe.com/v1/checkout/sessions', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...headers,\n },\n body: params.toString(),\n })\n return { ok: response.ok, session: (await response.json().catch(() => ({}))) as never }\n },\n expireSession: (sessionId, stripeAccount) =>\n stripeAccount ? expireConnectedCheckoutSession(sessionId, stripeAccount) : expireCheckoutSession(sessionId),\n ensureDomain: (input) => ensureCheckoutDomain(input).catch(() => null),\n customerAccount: (input) => readQuoteCustomerAccount(input),\n now: () => Date.now(),\n }\n}\n\n/**\n * `expireCheckoutSession` for a session on the seller's own account (a direct\n * charge), where the platform's call answers 404. Same answers, same rule: a\n * refused expiry reads the session back, so a paid one is never read as closed.\n */\nasync function expireConnectedCheckoutSession(\n sessionId: string,\n stripeAccount: string,\n): Promise<CheckoutSessionExpiry> {\n if (!/^cs_(test|live)_[A-Za-z0-9]{8,255}$/.test(String(sessionId ?? ''))) return 'missing'\n const secretKey = String(process.env.STRIPE_SECRET_KEY ?? '').trim()\n if (!secretKey) return 'open'\n const headers = {\n Authorization: `Bearer ${secretKey}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Stripe-Account': stripeAccount,\n }\n try {\n const expired = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}/expire`, {\n method: 'POST',\n headers,\n })\n if (expired.ok) return 'expired'\n const read = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}`, { headers })\n if (read.status === 404) return 'missing'\n if (!read.ok) return 'open'\n const session = (await read.json().catch(() => ({}))) as { status?: string }\n if (session.status === 'complete') return 'complete'\n if (session.status === 'expired') return 'expired'\n return 'open'\n } catch {\n return 'open'\n }\n}\n\n/** A link route's answer: a status, a JSON body and any extra headers. */\nexport type QuoteLinkOutcome = { status: number; body: Record<string, unknown>; headers?: Record<string, string> }\n\nconst DOC_ID = /^(?!__.*__$)[^/]{1,200}$/\n\nconst NOT_FOUND: QuoteLinkOutcome = {\n status: 404,\n body: { error: 'We could not find that quote. Check the link you were sent.' },\n}\n\n/** The not-found answer of a route an invoice's link reaches too: it names neither. */\nconst NOT_FOUND_ANY: QuoteLinkOutcome = {\n status: 404,\n body: { error: 'We could not find that quote or invoice. Check the link you were sent.' },\n}\n\n/** `quote` or `invoice`, as the customer reads it. */\nconst nounOf = (kind: CommerceModel.OrderPayLinkKind) => (kind === 'invoice' ? 'invoice' : 'quote')\n\nfunction bodyOf(req: PluginApiRequest): Record<string, unknown> {\n const raw = req.body\n if (typeof raw === 'string') {\n try {\n const parsed = JSON.parse(raw)\n return parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n return {}\n }\n }\n return raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {}\n}\n\nfunction headerOf(req: PluginApiRequest, name: string): string {\n const headers = (req.headers ?? {}) as Record<string, unknown>\n const value = headers[name.toLowerCase()] ?? headers[name]\n return String(Array.isArray(value) ? (value[0] ?? '') : (value ?? '')).trim()\n}\n\n/** The rate limit a link route spends per address per site, BEFORE the token is checked. */\nexport async function limitedQuoteLink(\n deps: QuotePayDeps,\n req: PluginApiRequest,\n key: string,\n limit: number,\n): Promise<QuoteLinkOutcome | null> {\n const ip = readClientIp(req.headers as never, { remoteAddress: req.socket?.remoteAddress }) ?? 'no-address'\n const rate = await deps.consumeRateLimit(`${key}:${ip}`, { limit, windowMs: QUOTE_WINDOW_MS })\n if (rate.allowed) return null\n return {\n status: 429,\n body: { error: 'Too many tries. Try again in a few minutes.' },\n headers: { 'Retry-After': String(Math.max(1, Math.ceil((rate.resetMs - deps.now()) / 1000))) },\n }\n}\n\nexport interface LoadedQuote {\n hostRef: FirebaseFirestore.DocumentReference\n host: Record<string, unknown>\n order: CommerceModel.HostOrder\n storeName: string\n store: FirebaseFirestore.DocumentSnapshot\n /** A quote, or an order's invoice (only for a route that opens invoices). */\n kind: CommerceModel.OrderPayLinkKind\n}\n\n/**\n * The quote a link names, after its token: the quote, the replaced answer for\n * a link to an older version, or the one not-found answer for everything else.\n * With `invoices`, a draft order's invoice too (AGL-4099). With `history`, a\n * link to an older version opens the quote as well: only for a route that\n * serves the quote's record and acts on nothing (its proofs, which an earlier\n * email draws, AGL-4097); pay, answers and uploads keep the current version.\n */\nexport async function loadLinkedQuote(\n deps: QuotePayDeps,\n hostId: string,\n quoteId: string,\n token: string,\n options: { invoices?: boolean; history?: boolean } = {},\n): Promise<{ loaded: LoadedQuote } | { outcome: QuoteLinkOutcome }> {\n const notFound = options.invoices ? NOT_FOUND_ANY : NOT_FOUND\n const version = verifyQuoteLinkToken(hostId, quoteId, token)\n if (version === null) return { outcome: notFound }\n const hostRef = deps.firestore().collection('hosts').doc(hostId)\n const [hostSnapshot, store, orderSnapshot] = await Promise.all([\n hostRef.get(),\n hostRef.collection('settings').doc('store').get(),\n hostRef.collection('orders').doc(quoteId).get(),\n ])\n if (!hostSnapshot.exists || !orderSnapshot.exists) return { outcome: notFound }\n const order = orderSnapshot.data() as CommerceModel.HostOrder\n const kind = CommerceModel.orderPayLinkKind(order)\n if (kind === null || (kind === 'invoice' && !options.invoices)) return { outcome: notFound }\n const host = (hostSnapshot.data() ?? {}) as Record<string, unknown>\n const storeName = String(resolveHostToken('businessName', host as HostTokenSource) ?? '')\n const current = CommerceModel.orderPayLinkVersion(order)\n if (version > current) return { outcome: notFound }\n if (version < current && !options.history) {\n // What the customer was sent, in their words: a proof with no price says proof (AGL-4184).\n const noun = kind === 'quote' && CommerceModel.quoteIsProofOnly(order) ? 'proof' : nounOf(kind)\n return {\n outcome: {\n status: 410,\n body: {\n state: 'replaced',\n kind,\n noun,\n storeName,\n replaced: true,\n error: `This ${noun} was updated, and ${storeName || 'the business'} sent you a newer link.`,\n },\n },\n }\n }\n return { loaded: { hostRef, host, order, storeName, store, kind } }\n}\n\n/** The link's site, quote and token from a query or a body, and whether all three are there. */\nexport function quoteLinkParams(source: Record<string, unknown>) {\n const hostId = String(source['hostId'] ?? '')\n const quoteId = String(source['q'] ?? '').slice(0, 200)\n const token = String(source['t'] ?? '').slice(0, 200)\n const complete = DOC_ID.test(hostId) && DOC_ID.test(quoteId) && Boolean(token)\n return { hostId, quoteId, token, complete }\n}\n\n/** Whether the business behind a pay link can take a card payment now, and with what. */\nexport interface PayLinkPayments {\n ready: boolean\n /** The site's workspace, for the platform fee and the attempt's record. */\n owner: { id?: string; org?: any } | null\n /** The owner's payment account; empty unless `ready`. */\n accountId: string\n /**\n * Whether a sale is a direct charge on that account or a destination charge\n * from the platform's, as the connect route recorded it on the profile.\n */\n chargeModel: SaleChargeModel\n}\n\n/**\n * The one payments check a pay link answers on: the workspace's plan\n * includes commerce, and the workspace OWNER's payment account can take\n * charges (`merchantAccountIsReady`, the check every money route makes). The\n * page asks it before offering Pay and Pay asks it before charging, so the\n * two never disagree.\n */\nexport async function payLinkPayments(\n deps: QuotePayDeps,\n input: { hostId: string; orderId: string; kind: CommerceModel.OrderPayLinkKind },\n): Promise<PayLinkPayments> {\n const owner = await deps.orgForHost(input.hostId)\n if (!checkEntitlement(owner?.org as never, 'commerce')) {\n return { ready: false, owner, accountId: '', chargeModel: 'destination' }\n }\n const ownerUid = owner?.org?.ownerUid\n const profile = ownerUid ? await deps.firestore().collection('profiles').doc(String(ownerUid)).get() : null\n const accountId = profile?.get('stripeAccountId')\n const ready = merchantAccountIsReady(\n {\n accountId,\n chargesEnabled: profile?.get('stripeChargesEnabled'),\n accountLivemode: profile?.get('stripeAccountLivemode'),\n },\n { subject: `${nounOf(input.kind)} ${input.orderId} on host ${input.hostId}` },\n )\n return {\n ready,\n owner,\n accountId: ready ? String(accountId) : '',\n chargeModel: saleChargeModel(profile?.get('stripeChargeModel')),\n }\n}\n\n/**\n * The page's view of a linked quote or invoice: the allow-listed projection,\n * priced under the store's tax choice and with Pay only where the business\n * can take it. A paid one asks nothing about payments.\n */\nexport async function payLinkPageView(\n deps: QuotePayDeps,\n input: {\n hostId: string\n orderId: string\n loaded: Pick<LoadedQuote, 'host' | 'order' | 'storeName' | 'store' | 'kind'>\n /** Whether this browser may see the proof (AGL-4206); absent reads as `open`. */\n proofAccess?: CommerceModel.QuoteProofAccess\n },\n): Promise<CommerceModel.QuotePageView> {\n const { hostId, orderId } = input\n const { host, order, storeName, store, kind } = input.loaded\n const currency = String(store.get('currency') ?? 'USD')\n const unpaid = order.status === 'pending'\n const receiptUrl = unpaid ? null : orderStatusUrl(host, hostId, orderId)\n const paymentsReady = unpaid ? (await payLinkPayments(deps, { hostId, orderId, kind })).ready : undefined\n const view = {\n order,\n orderId,\n storeName,\n currency,\n receiptUrl,\n store: CommerceModel.payLinkStoreOf({ tax: store.get('tax') }),\n paymentsReady,\n }\n if (kind !== 'quote') return CommerceModel.buildInvoicePageView(view)\n const proofAccess = input.proofAccess ?? 'open'\n // The quote's conversation rides its page (AGL-4207), an answer's view too; it waits on\n // the same sign-in as the proof, so it is not read for a page that will not show it.\n let messages: CommerceModel.QuotePageMessage[] = []\n if (proofAccess === 'open' || CommerceModel.currentQuoteProofs(order.quote).length === 0) {\n const orderRef = deps.firestore().collection('hosts').doc(hostId).collection('orders').doc(orderId)\n const listed = await orderRef.collection('messages').orderBy('atMs', 'desc').limit(CommerceModel.QUOTE_MESSAGES_SHOWN).get()\n messages = CommerceModel.quotePageMessages(\n listed.docs.map((entry) => ({ id: entry.id, data: entry.data() as Partial<CommerceModel.QuoteMessage> })),\n )\n }\n return CommerceModel.buildQuotePageView({\n ...view,\n messages,\n approvalStatements: CommerceModel.quoteApprovalStatements(store.get('quotes')),\n proofAccess,\n })\n}\n\n/** `GET /api/commerce/quote-view`: the quote page's data. */\nexport async function handleQuoteView(deps: QuotePayDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome> {\n if (req.method !== 'GET') return { status: 405, body: { error: 'Method not allowed' } }\n const { hostId, quoteId, token, complete } = quoteLinkParams((req.query ?? {}) as Record<string, unknown>)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const refused = await limitedQuoteLink(deps, req, `commerce-quote-view:${hostId}`, QUOTE_VIEW_LOOKUPS_PER_WINDOW)\n if (refused) return refused\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { invoices: true })\n if ('outcome' in linked) {\n // The replaced page is a page, not a failure: answered as data.\n if (linked.outcome.status === 410) {\n const { storeName, kind, noun } = linked.outcome.body as {\n storeName: string\n kind: CommerceModel.OrderPayLinkKind\n noun: string\n }\n return { status: 200, body: { state: 'replaced', kind, noun, storeName } }\n }\n return linked.outcome\n }\n const proofAccess =\n linked.loaded.kind === 'quote'\n ? await quoteProofAccessFor(deps, req, { hostId, host: linked.loaded.host, order: linked.loaded.order })\n : 'open'\n const view = await payLinkPageView(deps, { hostId, orderId: quoteId, loaded: linked.loaded, proofAccess })\n return { status: 200, body: view as unknown as Record<string, unknown> }\n}\n\n/** The Checkout Session a quote's (or an invoice's) Pay opens, as form params. Pure over its inputs. */\nexport function buildQuoteSessionParams(input: {\n hostId: string\n quoteId: string\n order: CommerceModel.HostOrder\n charge: CommerceModel.QuoteCheckoutCharge & Partial<Pick<CommerceModel.InvoiceCheckoutCharge, 'shippingOptions' | 'shippingCountries'>>\n accountId: string\n /**\n * `direct` opens the session ON the seller's account (the caller sends the\n * `Stripe-Account` header): Aglyn's take is the application fee, the seller\n * owns any Stripe Tax, and nothing is transferred. Absent is `destination`.\n */\n chargeModel?: SaleChargeModel\n feeCents: number\n taxRateId: string\n returnUrl: string\n paymentMethods: CommerceModel.StorefrontPaymentMethodControls\n /**\n * The tax basis charged when it is not the quote's stored one: a quote\n * saved before the store chose its sales tax, priced under the choice now\n * (`quotePayTax`, AGL-4162). The webhook records it on the paid order.\n */\n chargedTax?: CommerceModel.QuoteTaxBasis | null\n}): URLSearchParams {\n const { charge, order } = input\n const invoice = CommerceModel.orderPayLinkKind(order) === 'invoice'\n const quote = (order.quote ?? {}) as CommerceModel.OrderQuote\n const params = new URLSearchParams({\n mode: 'payment',\n ...checkoutSessionCardAuthenticationParams('payment'),\n ...(charge.taxAtPayment ? { 'automatic_tax[enabled]': 'true' } : {}),\n })\n charge.lines.forEach((line, index) => {\n const at = `line_items[${index}]`\n params.set(`${at}[quantity]`, '1')\n params.set(`${at}[price_data][currency]`, 'usd')\n params.set(`${at}[price_data][unit_amount]`, String(line.amountCents))\n params.set(`${at}[price_data][product_data][name]`, line.name.slice(0, 120))\n if (line.description) params.set(`${at}[price_data][product_data][description]`, line.description)\n // Stripe Tax's nontaxable code, for tax-exempt products and a tax charged as its own line.\n if (!line.taxable) params.set(`${at}[price_data][product_data][tax_code]`, 'txcd_00000000')\n if (line.taxable && input.taxRateId) params.set(`${at}[tax_rates][0]`, input.taxRateId)\n })\n // Shipping the business priced for the quote's ship-to, charged as the one\n // option, with the address asked for where it ships (and where Stripe Tax\n // reads the tax from). The quote's own address stands when it asks nothing.\n // An invoiced draft offers the rates it was made with, and the buyer picks\n // one, as on the draft's first link (AGL-4099).\n const rates = charge.shippingOptions ?? []\n if (rates.length > 0) {\n CommerceModel.appendShippingAddressCollectionParams(\n params,\n charge.shippingCountries?.length ? charge.shippingCountries : CommerceModel.CHECKOUT_SHIPPING_COUNTRIES,\n )\n CommerceModel.appendCheckoutShippingParams(params, rates)\n } else if (charge.shippingCents > 0) {\n const country = String(quote.shipTo?.country ?? '').toUpperCase()\n CommerceModel.appendShippingAddressCollectionParams(\n params,\n /^[A-Z]{2}$/.test(country) ? [country] : CommerceModel.CHECKOUT_SHIPPING_COUNTRIES,\n )\n CommerceModel.appendCheckoutShippingParams(params, [\n { rateId: 'quote', name: 'Shipping', amountCents: charge.shippingCents },\n ])\n }\n const shippingFloorCents = rates.length > 0 ? CommerceModel.shippingFloorCents(rates) : charge.shippingCents\n const direct = input.chargeModel === 'direct'\n for (const [key, value] of Object.entries(\n // A direct charge is already the seller's money, Stripe Tax included\n // (computed on THEIR registrations), so the take is the whole split.\n direct\n ? directChargeParams(input.feeCents)\n : CommerceModel.destinationChargeParams({\n accountId: input.accountId,\n feeCents: input.feeCents,\n taxOwner: charge.taxAtPayment ? 'platform' : 'merchant',\n merchantGoodsCents: charge.goodsCents,\n shippingFloorCents,\n }),\n )) {\n params.set(key, value)\n }\n const email = String((invoice ? order.customerEmail : quote.customer?.email) ?? '').trim()\n if (email) params.set('customer_email', email)\n const separator = input.returnUrl.includes('?') ? '&' : '?'\n params.set('success_url', `${input.returnUrl}${separator}session_id={CHECKOUT_SESSION_ID}`)\n params.set('cancel_url', input.returnUrl)\n // What the `commerce-draft` webhook branch reads to turn this quote into\n // its order, and to tell a payment for the quote as it stands from one for\n // a replaced link or an earlier edit.\n params.set('metadata[type]', 'commerce-draft')\n params.set('metadata[hostId]', input.hostId)\n params.set('metadata[orderId]', input.quoteId)\n if (invoice) {\n // An invoice's link version, which the draft branch compares as a\n // quote's (AGL-4099), and the promotion the draft was priced with, which\n // it counts once the draft is paid (no hold: the draft's lapsed with its\n // first session).\n params.set('metadata[payLinkVersion]', String(CommerceModel.orderPayLinkVersion(order)))\n if (order.discountId) params.set('metadata[discountId]', String(order.discountId))\n } else {\n params.set('metadata[quoteId]', input.quoteId)\n params.set('metadata[quoteLinkVersion]', String(CommerceModel.quoteLinkVersion(quote)))\n params.set('metadata[quoteUpdatedAtMs]', String(Number(quote.updatedAtMs) || 0))\n if (input.chargedTax) params.set('metadata[quoteTax]', CommerceModel.quoteTaxBasisKey(input.chargedTax))\n }\n params.set('metadata[feeCents]', String(input.feeCents))\n // What the webhook, refunds and reports read to find the payment on the\n // seller's account rather than the platform's.\n if (direct) params.set('metadata[chargeModel]', 'direct')\n // A tax charged as its own line is invisible to Stripe's tax total; this\n // witness is what records it as the business's tax.\n if (charge.taxCents > 0 && charge.taxPct === null) {\n params.set('metadata[taxCents]', String(charge.taxCents))\n }\n // The fixed transfer Aglyn keeps its Stripe Tax back from; a direct charge\n // transfers nothing and its tax is the seller's.\n if (charge.taxAtPayment && !direct) {\n params.set(\n 'metadata[transferCents]',\n String(\n CommerceModel.platformLiableTransferCents({\n feeCents: input.feeCents,\n merchantGoodsCents: charge.goodsCents,\n shippingFloorCents,\n }),\n ),\n )\n params.set('metadata[transferShippingCents]', String(shippingFloorCents))\n }\n // The store's choices, and never buy-now-pay-later (AGL-4198), so the fee\n // above is priced at the card rate.\n CommerceModel.appendStorefrontPaymentMethodParams(params, input.paymentMethods)\n return params\n}\n\nconst QUOTE_UPDATED_MESSAGE = 'This quote was updated since you opened it. Reload the page to see it before you pay.'\n\nconst refusal = (status: number, reason: string, error: string, extra: Record<string, unknown> = {}): QuoteLinkOutcome => ({\n status,\n body: { error, reason, ...extra },\n})\n\n/** `POST /api/commerce/quote-pay`: a fresh Checkout Session for the quote. */\nexport async function handleQuotePay(deps: QuotePayDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome> {\n if (req.method !== 'POST') return { status: 405, body: { error: 'Method not allowed' } }\n if (!process.env.STRIPE_SECRET_KEY) return { status: 501, body: { error: 'Payments are not configured.' } }\n const { hostId, quoteId, token, complete } = quoteLinkParams(bodyOf(req))\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const idempotencyKey = headerOf(req, 'idempotency-key').slice(0, 200)\n if (!idempotencyKey) return { status: 400, body: { error: 'Paying needs an Idempotency-Key header.' } }\n const refused = await limitedQuoteLink(deps, req, `commerce-quote-pay:${hostId}`, QUOTE_PAY_PRESSES_PER_WINDOW)\n if (refused) return refused\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { invoices: true })\n if ('outcome' in linked) return linked.outcome\n const { hostRef, host, order, storeName, store, kind } = linked.loaded\n const noun = nounOf(kind)\n\n // Every refusal the customer can be given is above the claim, so none of\n // them spends the press. `v` is the edit of the quote the page showed: a\n // quote changed since is shown again before it is paid, never charged unseen.\n // An invoice is not edited, so it sends none. `tax` is the tax the page\n // priced it under: a quote saved before the store chose its sales tax is\n // priced under the choice as it stands, so one the store changed since, or\n // a page that did not say, is shown again too.\n const body = bodyOf(req)\n const seen = Number(body['v'])\n if (kind === 'quote' && Number.isFinite(seen) && seen > 0 && seen !== (Number(order.quote?.updatedAtMs) || 0)) {\n return refusal(409, 'updated', QUOTE_UPDATED_MESSAGE)\n }\n const payStore = CommerceModel.payLinkStoreOf({ tax: store.get('tax') })\n const payTax = CommerceModel.quotePayTax(order.quote, payStore)\n if (kind === 'quote') {\n const shownTax = typeof body['tax'] === 'string' ? body['tax'] : null\n const taxKey = CommerceModel.quoteTaxBasisKey(payTax.basis)\n if (shownTax !== null ? shownTax !== taxKey : payTax.source === 'current') {\n return refusal(409, 'updated', QUOTE_UPDATED_MESSAGE)\n }\n }\n const payments = await payLinkPayments(deps, { hostId, orderId: quoteId, kind })\n const blocked = CommerceModel.payLinkRefusalWithPayments(\n CommerceModel.invoicePayRefusal(order, quoteId, payStore),\n payments.ready,\n )\n if (blocked === 'payments-unavailable') {\n return refusal(409, blocked, CommerceModel.payLinkPaymentsUnavailableMessage(storeName, kind))\n }\n if (blocked) return refusal(409, blocked, CommerceModel.invoicePayRefusalMessage(blocked, storeName, kind))\n const { owner, accountId, chargeModel } = payments\n const direct = chargeModel === 'direct'\n // Every Stripe object for a direct sale lives on the seller's account.\n const onAccount = connectedAccountHeader(chargeModel, accountId)\n const sessionAccount = onAccount['Stripe-Account'] ?? ''\n\n const charge = CommerceModel.invoiceCheckoutCharge(order, quoteId, payStore)\n // The fee is sized on the most the buyer can pay, as a draft's first link\n // sized it on its dearest rate, and its processing half at the card rate:\n // the session below excludes every buy-now-pay-later method. A direct\n // charge's fee is the take alone: Stripe bills the seller its card fee.\n const dearestRateCents = charge.shippingOptions.reduce((most, rate) => Math.max(most, rate.amountCents), 0)\n const feeCents = resolveTransactionFeeCents(\n owner?.org as never,\n charge.feeProductType,\n charge.goodsCents,\n charge.totalCents + dearestRateCents,\n direct ? { direct: true } : { stripeTax: charge.taxAtPayment },\n )\n // Stripe refuses `automatic_tax` on a seller's account whose Stripe Tax is\n // not set up, and a store that chose it must not sell untaxed. Above the\n // claim, so the refusal spends no press.\n if (direct && charge.taxAtPayment) {\n const taxActive = await (deps.sellerTaxActive ?? sellerStripeTaxActive)(String(accountId))\n if (!taxActive) return refusal(409, 'seller-tax', SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE)\n }\n const nativeMode = await deps.nativeMode(String(owner?.id ?? ''))\n const site = host as SiteReturnHost\n const origin = siteReturnOrigin({\n candidates: [headerOf(req, 'referer'), `https://${headerOf(req, 'host')}`],\n site,\n requestHost: headerOf(req, 'host'),\n })\n const returnUrl = `${origin}${quotePageHref(quoteId, token)}`\n // A draft's first session (the one its paymentLinkUrl opens) is closed\n // here too, so the draft has one way to pay from the first press on.\n const openedFor = order.checkoutSessionId ?? ''\n const openedAtEdit = Number(order.quote?.updatedAtMs) || 0\n const openedAtVersion = CommerceModel.orderPayLinkVersion(order)\n // Closes a session this quote opened, on the account it was opened on. A\n // seller's earlier session may be the platform's (opened before the seller\n // moved to direct charges), so one the seller's account does not know is\n // closed there too: leaving it open would be a second way to pay.\n const expire = async (sessionId: string): Promise<CheckoutSessionExpiry> => {\n if (!sessionAccount) return deps.expireSession(sessionId)\n const result = await deps.expireSession(sessionId, sessionAccount)\n return result === 'missing' ? deps.expireSession(sessionId) : result\n }\n\n const claimed = await claimAttempt(deps.firestore(), {\n kind: 'commerce-quote-pay',\n scopeId: `${hostId}:${quoteId}`,\n orgId: String(owner?.id ?? ''),\n key: idempotencyKey,\n busyMessage: 'Your payment is already being set up',\n })\n if ('replay' in claimed) {\n return { status: claimed.replay.status, body: claimed.replay.body as Record<string, unknown> }\n }\n const claim = claimed.claim\n const stripeKey = (object: string): Record<string, string> => {\n const derived = deriveStripeObjectKey(claim.stripeKey, object)\n return derived ? { 'Idempotency-Key': derived } : {}\n }\n let minted = ''\n try {\n // The session the last press opened is closed before another opens. One\n // that was paid a moment ago means the quote is paid; one that cannot be\n // closed means a second session would be a second way to pay.\n if (openedFor) {\n const previous = await expire(openedFor)\n if (previous === 'complete') {\n await claim.release()\n return refusal(409, 'paid', `This ${noun} has just been paid. Your receipt is on its way.`, { confirming: true })\n }\n if (previous === 'open') {\n await claim.release()\n return { status: 502, body: { error: 'Your payment could not be set up. Try again.' } }\n }\n }\n\n let taxRateId = ''\n if (charge.taxPct !== null && charge.taxableCents > 0) {\n const basis = kind === 'quote' ? payTax.basis : null\n taxRateId =\n (await deps.taxRateId({\n hostRef,\n taxPct: charge.taxPct,\n taxLabel:\n basis?.kind === 'rate'\n ? basis.label || `Tax (${charge.taxPct}%)`\n : 'Sales tax',\n headers: stripeKey(`tax-rate-${Math.round(charge.taxPct * 10_000)}`),\n // A platform rate id does not resolve on the seller's account.\n ...(sessionAccount ? { stripeAccount: sessionAccount } : {}),\n })) ?? ''\n if (!taxRateId) {\n // Never an untaxed session for a taxed quote.\n await claim.release()\n return { status: 502, body: { error: 'Your payment could not be set up. Try again.' } }\n }\n }\n\n const paymentMethods = CommerceModel.resolveStorefrontPaymentMethodControls(\n CommerceModel.normalizeStorefrontPaymentMethodSettings(store.get('paymentMethods')),\n )\n const params = buildQuoteSessionParams({\n hostId,\n quoteId,\n order,\n charge,\n accountId: String(accountId),\n ...(direct ? { chargeModel } : {}),\n feeCents,\n taxRateId,\n returnUrl,\n paymentMethods,\n chargedTax: kind === 'quote' && payTax.source === 'current' ? payTax.basis : null,\n })\n if (nativeMode.native) {\n applyNativeCheckoutParams(params, params.get('success_url') ?? returnUrl)\n }\n // Apple Pay's domain is registered on the account the session lives on.\n const domainInput = {\n pageUrl: returnUrl,\n site,\n hostId,\n ...(sessionAccount ? { stripeAccount: sessionAccount } : {}),\n }\n const domain = nativeMode.native ? deps.ensureDomain(domainInput) : Promise.resolve(null)\n const created = await deps.createSession(params, {\n ...stripeKey('session'),\n ...nativeCheckoutStripeHeaders(nativeMode),\n ...onAccount,\n })\n await domain\n const payload = created.ok\n ? // A direct sale's in-page form opens Stripe.js on the seller's account, where the session is.\n readCheckoutSessionPayload(created.session, nativeMode, paymentMethods.wallets, sessionAccount)\n : null\n if (!payload || !created.session.id) {\n console.error('Stripe quote checkout error', created.session?.error)\n await claim.release()\n return { status: 502, body: { error: 'Your payment could not be set up. Try again.' } }\n }\n minted = String(created.session.id)\n\n // The quote keeps the session it now has open. Whatever another press\n // stored meanwhile is closed after, so the last press is the one open\n // session; a quote that was paid, replaced or edited meanwhile closes\n // this one instead.\n const orderRef = hostRef.collection('orders').doc(quoteId)\n const settled = await deps.firestore().runTransaction(async (transaction) => {\n const snapshot = await transaction.get(orderRef)\n const current = snapshot.exists ? (snapshot.data() as CommerceModel.HostOrder) : null\n if (!current || CommerceModel.orderPayLinkKind(current) !== kind) return { outcome: NOT_FOUND_ANY, displaced: '' }\n if (current.status !== 'pending') {\n const closed = current.status === 'cancelled' || current.status === 'refunded'\n return {\n outcome: refusal(\n 409,\n closed ? 'closed' : 'paid',\n CommerceModel.invoicePayRefusalMessage(closed ? 'closed' : 'paid', storeName, kind),\n ),\n displaced: '',\n }\n }\n if (CommerceModel.orderPayLinkVersion(current) !== openedAtVersion) {\n return {\n outcome: {\n status: 410,\n body: { replaced: true, error: `This ${noun} was updated, and ${storeName || 'the business'} sent you a newer link.` },\n },\n displaced: '',\n }\n }\n if (kind === 'quote' && (Number(current.quote?.updatedAtMs) || 0) !== openedAtEdit) {\n return { outcome: refusal(409, 'updated', QUOTE_UPDATED_MESSAGE), displaced: '' }\n }\n transaction.set(orderRef, { checkoutSessionId: minted }, { merge: true })\n const displaced = current.checkoutSessionId && current.checkoutSessionId !== openedFor ? current.checkoutSessionId : ''\n return { outcome: null, displaced }\n })\n if (settled.outcome) {\n await expire(minted)\n await claim.release()\n return settled.outcome\n }\n if (settled.displaced && settled.displaced !== minted) await expire(settled.displaced)\n await claim.record(200, payload)\n return { status: 200, body: payload as unknown as Record<string, unknown> }\n } catch (error) {\n console.error('quote pay failed', error)\n if (minted) await expire(minted).catch(() => 'open')\n await claim.release()\n return { status: 500, body: { error: 'Your payment could not be set up. Try again.' } }\n }\n}\n\n/** Sends a link route's answer, never cached or indexed. */\nexport function sendQuoteLinkOutcome(res: Parameters<PluginApiHandler>[1], outcome: QuoteLinkOutcome) {\n res.setHeader('Cache-Control', 'private, no-store')\n res.setHeader('X-Robots-Tag', 'noindex, nofollow')\n for (const [name, value] of Object.entries(outcome.headers ?? {})) res.setHeader(name, value)\n return res.status(outcome.status).json(outcome.body)\n}\n\n/** `GET /api/commerce/quote-view`. */\nexport const quoteViewHandler: PluginApiHandler = async (req, res) => {\n try {\n return sendQuoteLinkOutcome(res, await handleQuoteView(defaultQuotePayDeps(), req))\n } catch (error) {\n console.error('quote view failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'This quote could not be loaded. Try again.' } })\n }\n}\n\n/** `POST /api/commerce/quote-pay`. */\nexport const quotePayHandler: PluginApiHandler = async (req, res) =>\n sendQuoteLinkOutcome(res, await handleQuotePay(defaultQuotePayDeps(), req))\n"],"names":["ACCOUNTS_PLUGIN_ID","checkEntitlement","claimAttempt","deriveStripeObjectKey","resolveHostEnabledPlugins","resolveTransactionFeeCents","resolveHostToken","readClientIp","siteReturnOrigin","consumeRateLimit","firebaseAdmin","getOrgForHost","connectedAccountHeader","directChargeParams","merchantAccountIsReady","saleChargeModel","checkoutSessionCardAuthenticationParams","quotePageHref","CommerceModel","expireCheckoutSession","resolveManualTaxRateId","applyNativeCheckoutParams","nativeCheckoutStripeHeaders","readCheckoutSessionPayload","resolveNativeCheckoutMode","orderStatusUrl","MEMBER_SESSIONS_VALID_FROM_FIELD","memberCookieName","parseMemberSession","ensureCheckoutDomain","verifyQuoteLinkToken","SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE","sellerStripeTaxActive","QUOTE_VIEW_LOOKUPS_PER_WINDOW","QUOTE_PAY_PRESSES_PER_WINDOW","QUOTE_WINDOW_MS","readQuoteCustomerAccount","input","member","owner","hostId","org","host","includes","found","app","firestore","collection","doc","where","email","limit","get","docs","id","validFromMs","Number","suspended","quoteProofAccessFor","deps","req","quote","order","requireProofSignIn","quoteCustomerAccountEmail","account","customerAccount","cookies","session","signedIn","memberId","issuedAtMs","quoteProofAccess","accountId","signedInAccountId","quoteProofAccessRefusal","access","storeName","status","body","error","quoteProofAccessMessage","reason","defaultQuotePayDeps","key","options","orgForHost","orgId","nativeMode","taxRateId","createSession","params","headers","response","fetch","method","Authorization","process","env","STRIPE_SECRET_KEY","toString","ok","json","catch","expireSession","sessionId","stripeAccount","expireConnectedCheckoutSession","ensureDomain","now","Date","test","String","secretKey","trim","expired","read","DOC_ID","NOT_FOUND","NOT_FOUND_ANY","nounOf","kind","bodyOf","raw","parsed","JSON","parse","headerOf","name","value","toLowerCase","Array","isArray","limitedQuoteLink","ip","remoteAddress","socket","rate","windowMs","allowed","Math","max","ceil","resetMs","loadLinkedQuote","quoteId","token","hostSnapshot","notFound","invoices","version","outcome","hostRef","store","orderSnapshot","Promise","all","exists","data","orderPayLinkKind","current","orderPayLinkVersion","history","noun","quoteIsProofOnly","state","replaced","loaded","quoteLinkParams","source","slice","complete","Boolean","payLinkPayments","ready","chargeModel","ownerUid","profile","chargesEnabled","accountLivemode","subject","orderId","payLinkPageView","currency","unpaid","receiptUrl","paymentsReady","undefined","view","payLinkStoreOf","tax","buildInvoicePageView","proofAccess","messages","currentQuoteProofs","length","orderRef","listed","orderBy","QUOTE_MESSAGES_SHOWN","quotePageMessages","map","entry","buildQuotePageView","approvalStatements","quoteApprovalStatements","handleQuoteView","query","refused","linked","buildQuoteSessionParams","charge","invoice","URLSearchParams","mode","taxAtPayment","lines","forEach","line","index","at","set","amountCents","description","taxable","rates","shippingOptions","appendShippingAddressCollectionParams","shippingCountries","CHECKOUT_SHIPPING_COUNTRIES","appendCheckoutShippingParams","shippingCents","country","shipTo","toUpperCase","rateId","shippingFloorCents","direct","Object","entries","feeCents","destinationChargeParams","taxOwner","merchantGoodsCents","goodsCents","customerEmail","customer","separator","returnUrl","discountId","quoteLinkVersion","updatedAtMs","chargedTax","quoteTaxBasisKey","taxCents","taxPct","platformLiableTransferCents","appendStorefrontPaymentMethodParams","paymentMethods","QUOTE_UPDATED_MESSAGE","refusal","extra","handleQuotePay","onAccount","idempotencyKey","seen","isFinite","payStore","payTax","quotePayTax","shownTax","taxKey","basis","payments","blocked","payLinkRefusalWithPayments","invoicePayRefusal","payLinkPaymentsUnavailableMessage","invoicePayRefusalMessage","sessionAccount","invoiceCheckoutCharge","dearestRateCents","reduce","most","feeProductType","totalCents","stripeTax","taxActive","sellerTaxActive","site","origin","candidates","requestHost","openedFor","checkoutSessionId","openedAtEdit","openedAtVersion","expire","result","claimed","scopeId","busyMessage","replay","claim","stripeKey","object","derived","minted","previous","release","confirming","taxableCents","taxLabel","label","round","resolveStorefrontPaymentMethodControls","normalizeStorefrontPaymentMethodSettings","native","domainInput","pageUrl","domain","resolve","created","payload","wallets","console","settled","runTransaction","transaction","snapshot","displaced","closed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B,IAAI,CAACiD,QAAQxE,IAAI;AACrD;AAEA,oCAAoC,GACpC,OAAO,MAAMkQ,mBAAqC,OAAOrR,KAAKmR;IAC5D,IAAI;QACF,OAAOD,qBAAqBC,KAAK,MAAMjI,gBAAgB3H,uBAAuBvB;IAChF,EAAE,OAAOoB,OAAO;QACdqP,QAAQrP,KAAK,CAAC,qBAAqBA;QACnC,OAAO8P,qBAAqBC,KAAK;YAAEjQ,QAAQ;YAAKC,MAAM;gBAAEC,OAAO;YAA6C;QAAE;IAChH;AACF,EAAC;AAED,oCAAoC,GACpC,OAAO,MAAMkQ,kBAAoC,OAAOtR,KAAKmR,MAC3DD,qBAAqBC,KAAK,MAAMzE,eAAenL,uBAAuBvB,MAAK"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/quote-pay.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 ACCOUNTS_PLUGIN_ID,\n checkEntitlement,\n claimAttempt,\n deriveStripeObjectKey,\n resolveHostEnabledPlugins,\n resolveTransactionFeeCents,\n type PluginApiHandler,\n type PluginApiRequest,\n} from '@aglyn/aglyn/server'\nimport { resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport { readClientIp } from '@aglyn/aglyn/app-utils/request-ip'\nimport { type SiteReturnHost, siteReturnOrigin } from '@aglyn/aglyn/app-utils/site-return-url'\nimport { consumeRateLimit, firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport {\n connectedAccountHeader,\n directChargeParams,\n merchantAccountIsReady,\n saleChargeModel,\n type SaleChargeModel,\n} from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { checkoutSessionCardAuthenticationParams } from '@aglyn/tenant-data-admin/server/stripe-card-authentication'\nimport { quotePageHref } from '../constants/quote-page'\nimport * as CommerceModel from '../model'\nimport { expireCheckoutSession, type CheckoutSessionExpiry } from './checkout-session-expiry'\nimport { resolveManualTaxRateId } from './manual-tax-rate'\nimport {\n applyNativeCheckoutParams,\n nativeCheckoutStripeHeaders,\n readCheckoutSessionPayload,\n resolveNativeCheckoutMode,\n type NativeCheckoutMode,\n} from './native-checkout'\nimport { orderStatusUrl } from './order-status-token'\nimport { MEMBER_SESSIONS_VALID_FROM_FIELD, memberCookieName, parseMemberSession } from './membership'\nimport { ensureCheckoutDomain } from './payment-method-domains'\nimport { verifyQuoteLinkToken } from './quote-link-token'\nimport { SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE, sellerStripeTaxActive } from './seller-stripe-account'\nimport { tellCheckoutTaxRefusal } from './checkout-tax-refusal'\n\n/*==========================================\n * THE CUSTOMER'S QUOTE PAGE AND ITS PAY BUTTON (AGL-4094), AND AN\n * INVOICE'S (AGL-4099).\n *\n * GET /api/commerce/quote-view?hostId=&q=<quoteId>&t=<token>\n * → 200 QuotePageView | 200 { state: 'replaced', storeName } | 404\n * POST /api/commerce/quote-pay { hostId, q, t, v } + Idempotency-Key\n * → 200 { url } (Stripe's page) | 200 { clientSecret, publishableKey, sessionId, wallets? }\n * (the in-page form) | 409 { error, reason } | 410 { error, replaced: true } | 404\n *\n * The signed link (`quote-link-token.ts`) is the whole credential. A wrong\n * token answers exactly as a missing quote does, so neither route tells\n * anyone which quote ids exist; both are rate-limited per address per site\n * BEFORE the token check, so guessing costs what looking does. A link signed\n * for an older version of the quote opens the replaced page and nothing else.\n *\n * Pay opens a FRESH Checkout Session from the stored quote on every press:\n * the prices are the stored lines', never anything the page sends, and the\n * session the previous press opened is expired first, so two sessions for one\n * quote can never both be open. The quote keeps the open one in\n * `checkoutSessionId`. A Stripe session lapses after a day; the quote and its\n * link do not, because the next press opens another.\n *\n * The payment completes in `billing-webhook.ts`, which turns this same\n * document into the order (`paidQuoteOrder`); nothing here marks it paid.\n *\n * THE PAGE OFFERS ONLY A PAY THAT WORKS (AGL-4162). The view asks the same\n * payments check Pay refuses on ({@link payLinkPayments}) and prices the tax\n * the same way (`quotePayTax`): a quote saved before the store chose its\n * sales tax is shown and charged under the store's choice now, and Pay\n * refuses when that choice is not the one the page showed (`tax`). The\n * session carries that basis (`quoteTax`) so the paid order records it.\n *\n * AN INVOICE'S LINK IS THIS ONE (AGL-4099). A draft order the business sent\n * an invoice for opens on the same page from the same kind of link (its\n * version on `payLink.version`, `commerce-invoices.ts`), as \"Invoice #N\" with\n * no proofs or approval, and Pay opens the same kind of fresh session from\n * its stored lines, discount, tax and the shipping rates it was made with.\n * Its webhook is the draft branch it always completed through, which flips\n * the draft to paid without restamping its list fields. The proof and answer\n * routes stay a quote's alone: `loadLinkedQuote` opens an invoice only for\n * the routes that ask (`{ invoices: true }`).\n *=========================================*/\n\n/** Lookups and presses one address may make per site, per ten minutes. */\nexport const QUOTE_VIEW_LOOKUPS_PER_WINDOW = 60\nexport const QUOTE_PAY_PRESSES_PER_WINDOW = 20\nexport const QUOTE_WINDOW_MS = 10 * 60_000\n\nexport interface QuotePayDeps {\n firestore(): FirebaseFirestore.Firestore\n consumeRateLimit(key: string, options: { limit: number; windowMs: number }): Promise<{ allowed: boolean; resetMs: number }>\n orgForHost(hostId: string): Promise<{ id?: string; org?: any } | null>\n nativeMode(orgId: string): Promise<NativeCheckoutMode>\n /** The store's manual tax rate as a Stripe tax rate, or null when one cannot be had. */\n taxRateId(input: Parameters<typeof resolveManualTaxRateId>[0]): Promise<string | null>\n createSession(\n params: URLSearchParams,\n headers: Record<string, string>,\n ): Promise<{ ok: boolean; session: { id?: string; url?: string; client_secret?: string; error?: unknown } }>\n /**\n * Closes a session so it can no longer be paid. `stripeAccount` names the\n * seller's account for a session opened there (a direct charge); absent, the\n * session is the platform's.\n */\n expireSession(sessionId: string, stripeAccount?: string): Promise<CheckoutSessionExpiry>\n /**\n * Whether the seller's own Stripe Tax is set up, for a direct charge that\n * asks Stripe Tax. Absent, `sellerStripeTaxActive` answers.\n */\n sellerTaxActive?(accountId: string): Promise<boolean>\n /**\n * Tells the store's managers, once, that a customer was refused because the\n * store's sales tax is not set up (AGL-4245). Absent,\n * `tellCheckoutTaxRefusal` does.\n */\n tellTaxRefusal?(hostId: string, reason: 'tax-undecided' | 'stripe-tax-not-active'): void\n /** Registers the page's domain for Apple Pay; never throws. */\n ensureDomain(input: Parameters<typeof ensureCheckoutDomain>[0]): Promise<unknown>\n /**\n * The site account a quote's customer signs in to (AGL-4206): the member\n * under that address, on a site that serves accounts; null for a guest.\n * Absent, every customer reads as a guest.\n */\n customerAccount?(input: { hostId: string; host: Record<string, unknown>; email: string }): Promise<QuoteCustomerAccount | null>\n now(): number\n}\n\n/** A quote customer's account on the site, as the sign-in check needs it. */\nexport interface QuoteCustomerAccount {\n id: string\n /** Sessions minted before this were revoked in bulk (AGL-914). */\n validFromMs: number\n suspended: boolean\n}\n\n/**\n * The member under `email` on a site that serves accounts, or null. A site\n * with User Accounts switched off has no sign-in page to send anyone to, so\n * every customer of it is a guest.\n */\nexport async function readQuoteCustomerAccount(input: {\n hostId: string\n host: Record<string, unknown>\n email: string\n}): Promise<QuoteCustomerAccount | null> {\n const owner = await getOrgForHost(input.hostId)\n if (!owner || !resolveHostEnabledPlugins(owner.org as never, input.host as never).includes(ACCOUNTS_PLUGIN_ID)) return null\n const found = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(input.hostId)\n .collection('siteMembers')\n .where('email', '==', input.email)\n .limit(1)\n .get()\n const member = found.docs[0]\n if (!member) return null\n return {\n id: member.id,\n validFromMs: Number(member.get(MEMBER_SESSIONS_VALID_FROM_FIELD) ?? 0) || 0,\n suspended: member.get('suspended') === true,\n }\n}\n\n/**\n * Whether this request may see the quote's proof and answer it (AGL-4206):\n * `open` unless the quote asks a customer with a site account to sign in and\n * this browser is not signed in to that account. Reads nothing for a quote\n * that does not ask, or a customer with no address.\n */\nexport async function quoteProofAccessFor(\n deps: QuotePayDeps,\n req: PluginApiRequest,\n input: { hostId: string; host: Record<string, unknown>; order: CommerceModel.HostOrder },\n): Promise<CommerceModel.QuoteProofAccess> {\n const quote = input.order.quote\n if (quote?.requireProofSignIn !== true) return 'open'\n const email = CommerceModel.quoteCustomerAccountEmail(quote)\n if (!email) return 'open'\n const account = deps.customerAccount ? await deps.customerAccount({ hostId: input.hostId, host: input.host, email }) : null\n const cookies = (req.cookies ?? {}) as Record<string, string | undefined>\n const session = parseMemberSession(input.hostId, cookies[memberCookieName(input.hostId)])\n // A session for the customer's account counts only while the account stands and the session was not revoked.\n const signedIn =\n session && account && session.memberId === account.id && (account.suspended || session.issuedAtMs < account.validFromMs)\n ? null\n : (session?.memberId ?? null)\n return CommerceModel.quoteProofAccess({ quote, accountId: account?.id ?? null, signedInAccountId: signedIn })\n}\n\n/** A proof route's answer while the proof waits on a sign-in. */\nexport function quoteProofAccessRefusal(access: Exclude<CommerceModel.QuoteProofAccess, 'open'>, storeName: string): QuoteLinkOutcome {\n return {\n status: 403,\n body: { error: CommerceModel.quoteProofAccessMessage(access, storeName), reason: access },\n }\n}\n\nexport function defaultQuotePayDeps(): QuotePayDeps {\n return {\n firestore: () => firebaseAdmin.app().firestore(),\n consumeRateLimit: (key, options) => consumeRateLimit(key, options),\n orgForHost: async (hostId) => {\n const found = await getOrgForHost(hostId)\n return found ? { id: found.orgId, org: found.org } : null\n },\n nativeMode: (orgId) => resolveNativeCheckoutMode(orgId),\n taxRateId: (input) => resolveManualTaxRateId(input),\n createSession: async (params, headers) => {\n const response = await fetch('https://api.stripe.com/v1/checkout/sessions', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...headers,\n },\n body: params.toString(),\n })\n return { ok: response.ok, session: (await response.json().catch(() => ({}))) as never }\n },\n expireSession: (sessionId, stripeAccount) =>\n stripeAccount ? expireConnectedCheckoutSession(sessionId, stripeAccount) : expireCheckoutSession(sessionId),\n ensureDomain: (input) => ensureCheckoutDomain(input).catch(() => null),\n customerAccount: (input) => readQuoteCustomerAccount(input),\n now: () => Date.now(),\n }\n}\n\n/**\n * `expireCheckoutSession` for a session on the seller's own account (a direct\n * charge), where the platform's call answers 404. Same answers, same rule: a\n * refused expiry reads the session back, so a paid one is never read as closed.\n */\nasync function expireConnectedCheckoutSession(\n sessionId: string,\n stripeAccount: string,\n): Promise<CheckoutSessionExpiry> {\n if (!/^cs_(test|live)_[A-Za-z0-9]{8,255}$/.test(String(sessionId ?? ''))) return 'missing'\n const secretKey = String(process.env.STRIPE_SECRET_KEY ?? '').trim()\n if (!secretKey) return 'open'\n const headers = {\n Authorization: `Bearer ${secretKey}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Stripe-Account': stripeAccount,\n }\n try {\n const expired = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}/expire`, {\n method: 'POST',\n headers,\n })\n if (expired.ok) return 'expired'\n const read = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}`, { headers })\n if (read.status === 404) return 'missing'\n if (!read.ok) return 'open'\n const session = (await read.json().catch(() => ({}))) as { status?: string }\n if (session.status === 'complete') return 'complete'\n if (session.status === 'expired') return 'expired'\n return 'open'\n } catch {\n return 'open'\n }\n}\n\n/** A link route's answer: a status, a JSON body and any extra headers. */\nexport type QuoteLinkOutcome = { status: number; body: Record<string, unknown>; headers?: Record<string, string> }\n\nconst DOC_ID = /^(?!__.*__$)[^/]{1,200}$/\n\nconst NOT_FOUND: QuoteLinkOutcome = {\n status: 404,\n body: { error: 'We could not find that quote. Check the link you were sent.' },\n}\n\n/** The not-found answer of a route an invoice's link reaches too: it names neither. */\nconst NOT_FOUND_ANY: QuoteLinkOutcome = {\n status: 404,\n body: { error: 'We could not find that quote or invoice. Check the link you were sent.' },\n}\n\n/** `quote` or `invoice`, as the customer reads it. */\nconst nounOf = (kind: CommerceModel.OrderPayLinkKind) => (kind === 'invoice' ? 'invoice' : 'quote')\n\nfunction bodyOf(req: PluginApiRequest): Record<string, unknown> {\n const raw = req.body\n if (typeof raw === 'string') {\n try {\n const parsed = JSON.parse(raw)\n return parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n return {}\n }\n }\n return raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {}\n}\n\nfunction headerOf(req: PluginApiRequest, name: string): string {\n const headers = (req.headers ?? {}) as Record<string, unknown>\n const value = headers[name.toLowerCase()] ?? headers[name]\n return String(Array.isArray(value) ? (value[0] ?? '') : (value ?? '')).trim()\n}\n\n/** The rate limit a link route spends per address per site, BEFORE the token is checked. */\nexport async function limitedQuoteLink(\n deps: QuotePayDeps,\n req: PluginApiRequest,\n key: string,\n limit: number,\n): Promise<QuoteLinkOutcome | null> {\n const ip = readClientIp(req.headers as never, { remoteAddress: req.socket?.remoteAddress }) ?? 'no-address'\n const rate = await deps.consumeRateLimit(`${key}:${ip}`, { limit, windowMs: QUOTE_WINDOW_MS })\n if (rate.allowed) return null\n return {\n status: 429,\n body: { error: 'Too many tries. Try again in a few minutes.' },\n headers: { 'Retry-After': String(Math.max(1, Math.ceil((rate.resetMs - deps.now()) / 1000))) },\n }\n}\n\nexport interface LoadedQuote {\n hostRef: FirebaseFirestore.DocumentReference\n host: Record<string, unknown>\n order: CommerceModel.HostOrder\n storeName: string\n store: FirebaseFirestore.DocumentSnapshot\n /** A quote, or an order's invoice (only for a route that opens invoices). */\n kind: CommerceModel.OrderPayLinkKind\n}\n\n/**\n * The quote a link names, after its token: the quote, the replaced answer for\n * a link to an older version, or the one not-found answer for everything else.\n * With `invoices`, a draft order's invoice too (AGL-4099). With `history`, a\n * link to an older version opens the quote as well: only for a route that\n * serves the quote's record and acts on nothing (its proofs, which an earlier\n * email draws, AGL-4097); pay, answers and uploads keep the current version.\n */\nexport async function loadLinkedQuote(\n deps: QuotePayDeps,\n hostId: string,\n quoteId: string,\n token: string,\n options: { invoices?: boolean; history?: boolean } = {},\n): Promise<{ loaded: LoadedQuote } | { outcome: QuoteLinkOutcome }> {\n const notFound = options.invoices ? NOT_FOUND_ANY : NOT_FOUND\n const version = verifyQuoteLinkToken(hostId, quoteId, token)\n if (version === null) return { outcome: notFound }\n const hostRef = deps.firestore().collection('hosts').doc(hostId)\n const [hostSnapshot, store, orderSnapshot] = await Promise.all([\n hostRef.get(),\n hostRef.collection('settings').doc('store').get(),\n hostRef.collection('orders').doc(quoteId).get(),\n ])\n if (!hostSnapshot.exists || !orderSnapshot.exists) return { outcome: notFound }\n const order = orderSnapshot.data() as CommerceModel.HostOrder\n const kind = CommerceModel.orderPayLinkKind(order)\n if (kind === null || (kind === 'invoice' && !options.invoices)) return { outcome: notFound }\n const host = (hostSnapshot.data() ?? {}) as Record<string, unknown>\n const storeName = String(resolveHostToken('businessName', host as HostTokenSource) ?? '')\n const current = CommerceModel.orderPayLinkVersion(order)\n if (version > current) return { outcome: notFound }\n if (version < current && !options.history) {\n // What the customer was sent, in their words: a proof with no price says proof (AGL-4184).\n const noun = kind === 'quote' && CommerceModel.quoteIsProofOnly(order) ? 'proof' : nounOf(kind)\n return {\n outcome: {\n status: 410,\n body: {\n state: 'replaced',\n kind,\n noun,\n storeName,\n replaced: true,\n error: `This ${noun} was updated, and ${storeName || 'the business'} sent you a newer link.`,\n },\n },\n }\n }\n return { loaded: { hostRef, host, order, storeName, store, kind } }\n}\n\n/** The link's site, quote and token from a query or a body, and whether all three are there. */\nexport function quoteLinkParams(source: Record<string, unknown>) {\n const hostId = String(source['hostId'] ?? '')\n const quoteId = String(source['q'] ?? '').slice(0, 200)\n const token = String(source['t'] ?? '').slice(0, 200)\n const complete = DOC_ID.test(hostId) && DOC_ID.test(quoteId) && Boolean(token)\n return { hostId, quoteId, token, complete }\n}\n\n/** Whether the business behind a pay link can take a card payment now, and with what. */\nexport interface PayLinkPayments {\n ready: boolean\n /** The site's workspace, for the platform fee and the attempt's record. */\n owner: { id?: string; org?: any } | null\n /** The owner's payment account; empty unless `ready`. */\n accountId: string\n /**\n * Whether a sale is a direct charge on that account or a destination charge\n * from the platform's, as the connect route recorded it on the profile.\n */\n chargeModel: SaleChargeModel\n}\n\n/**\n * The one payments check a pay link answers on: the workspace's plan\n * includes commerce, and the workspace OWNER's payment account can take\n * charges (`merchantAccountIsReady`, the check every money route makes). The\n * page asks it before offering Pay and Pay asks it before charging, so the\n * two never disagree.\n */\nexport async function payLinkPayments(\n deps: QuotePayDeps,\n input: { hostId: string; orderId: string; kind: CommerceModel.OrderPayLinkKind },\n): Promise<PayLinkPayments> {\n const owner = await deps.orgForHost(input.hostId)\n if (!checkEntitlement(owner?.org as never, 'commerce')) {\n return { ready: false, owner, accountId: '', chargeModel: 'destination' }\n }\n const ownerUid = owner?.org?.ownerUid\n const profile = ownerUid ? await deps.firestore().collection('profiles').doc(String(ownerUid)).get() : null\n const accountId = profile?.get('stripeAccountId')\n const ready = merchantAccountIsReady(\n {\n accountId,\n chargesEnabled: profile?.get('stripeChargesEnabled'),\n accountLivemode: profile?.get('stripeAccountLivemode'),\n },\n { subject: `${nounOf(input.kind)} ${input.orderId} on host ${input.hostId}` },\n )\n return {\n ready,\n owner,\n accountId: ready ? String(accountId) : '',\n chargeModel: saleChargeModel(profile?.get('stripeChargeModel')),\n }\n}\n\n/**\n * The page's view of a linked quote or invoice: the allow-listed projection,\n * priced under the store's tax choice and with Pay only where the business\n * can take it. A paid one asks nothing about payments.\n */\nexport async function payLinkPageView(\n deps: QuotePayDeps,\n input: {\n hostId: string\n orderId: string\n loaded: Pick<LoadedQuote, 'host' | 'order' | 'storeName' | 'store' | 'kind'>\n /** Whether this browser may see the proof (AGL-4206); absent reads as `open`. */\n proofAccess?: CommerceModel.QuoteProofAccess\n },\n): Promise<CommerceModel.QuotePageView> {\n const { hostId, orderId } = input\n const { host, order, storeName, store, kind } = input.loaded\n const currency = String(store.get('currency') ?? 'USD')\n const unpaid = order.status === 'pending'\n const receiptUrl = unpaid ? null : orderStatusUrl(host, hostId, orderId)\n const paymentsReady = unpaid ? (await payLinkPayments(deps, { hostId, orderId, kind })).ready : undefined\n const view = {\n order,\n orderId,\n storeName,\n currency,\n receiptUrl,\n store: CommerceModel.payLinkStoreOf({ tax: store.get('tax') }),\n paymentsReady,\n }\n if (kind !== 'quote') return CommerceModel.buildInvoicePageView(view)\n const proofAccess = input.proofAccess ?? 'open'\n // The quote's conversation rides its page (AGL-4207), an answer's view too; it waits on\n // the same sign-in as the proof, so it is not read for a page that will not show it.\n let messages: CommerceModel.QuotePageMessage[] = []\n if (proofAccess === 'open' || CommerceModel.currentQuoteProofs(order.quote).length === 0) {\n const orderRef = deps.firestore().collection('hosts').doc(hostId).collection('orders').doc(orderId)\n const listed = await orderRef.collection('messages').orderBy('atMs', 'desc').limit(CommerceModel.QUOTE_MESSAGES_SHOWN).get()\n messages = CommerceModel.quotePageMessages(\n listed.docs.map((entry) => ({ id: entry.id, data: entry.data() as Partial<CommerceModel.QuoteMessage> })),\n )\n }\n return CommerceModel.buildQuotePageView({\n ...view,\n messages,\n approvalStatements: CommerceModel.quoteApprovalStatements(store.get('quotes')),\n proofAccess,\n })\n}\n\n/** `GET /api/commerce/quote-view`: the quote page's data. */\nexport async function handleQuoteView(deps: QuotePayDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome> {\n if (req.method !== 'GET') return { status: 405, body: { error: 'Method not allowed' } }\n const { hostId, quoteId, token, complete } = quoteLinkParams((req.query ?? {}) as Record<string, unknown>)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const refused = await limitedQuoteLink(deps, req, `commerce-quote-view:${hostId}`, QUOTE_VIEW_LOOKUPS_PER_WINDOW)\n if (refused) return refused\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { invoices: true })\n if ('outcome' in linked) {\n // The replaced page is a page, not a failure: answered as data.\n if (linked.outcome.status === 410) {\n const { storeName, kind, noun } = linked.outcome.body as {\n storeName: string\n kind: CommerceModel.OrderPayLinkKind\n noun: string\n }\n return { status: 200, body: { state: 'replaced', kind, noun, storeName } }\n }\n return linked.outcome\n }\n const proofAccess =\n linked.loaded.kind === 'quote'\n ? await quoteProofAccessFor(deps, req, { hostId, host: linked.loaded.host, order: linked.loaded.order })\n : 'open'\n const view = await payLinkPageView(deps, { hostId, orderId: quoteId, loaded: linked.loaded, proofAccess })\n return { status: 200, body: view as unknown as Record<string, unknown> }\n}\n\n/** The Checkout Session a quote's (or an invoice's) Pay opens, as form params. Pure over its inputs. */\nexport function buildQuoteSessionParams(input: {\n hostId: string\n quoteId: string\n order: CommerceModel.HostOrder\n charge: CommerceModel.QuoteCheckoutCharge & Partial<Pick<CommerceModel.InvoiceCheckoutCharge, 'shippingOptions' | 'shippingCountries'>>\n accountId: string\n /**\n * `direct` opens the session ON the seller's account (the caller sends the\n * `Stripe-Account` header): Aglyn's take is the application fee, the seller\n * owns any Stripe Tax, and nothing is transferred. Absent is `destination`.\n */\n chargeModel?: SaleChargeModel\n feeCents: number\n taxRateId: string\n returnUrl: string\n paymentMethods: CommerceModel.StorefrontPaymentMethodControls\n /**\n * The tax basis charged when it is not the quote's stored one: a quote\n * saved before the store chose its sales tax, priced under the choice now\n * (`quotePayTax`, AGL-4162). The webhook records it on the paid order.\n */\n chargedTax?: CommerceModel.QuoteTaxBasis | null\n}): URLSearchParams {\n const { charge, order } = input\n const invoice = CommerceModel.orderPayLinkKind(order) === 'invoice'\n const quote = (order.quote ?? {}) as CommerceModel.OrderQuote\n const params = new URLSearchParams({\n mode: 'payment',\n ...checkoutSessionCardAuthenticationParams('payment'),\n ...(charge.taxAtPayment ? { 'automatic_tax[enabled]': 'true' } : {}),\n })\n charge.lines.forEach((line, index) => {\n const at = `line_items[${index}]`\n params.set(`${at}[quantity]`, '1')\n params.set(`${at}[price_data][currency]`, 'usd')\n params.set(`${at}[price_data][unit_amount]`, String(line.amountCents))\n params.set(`${at}[price_data][product_data][name]`, line.name.slice(0, 120))\n if (line.description) params.set(`${at}[price_data][product_data][description]`, line.description)\n // Stripe Tax's nontaxable code, for tax-exempt products and a tax charged as its own line.\n if (!line.taxable) params.set(`${at}[price_data][product_data][tax_code]`, 'txcd_00000000')\n if (line.taxable && input.taxRateId) params.set(`${at}[tax_rates][0]`, input.taxRateId)\n })\n // Shipping the business priced for the quote's ship-to, charged as the one\n // option, with the address asked for where it ships (and where Stripe Tax\n // reads the tax from). The quote's own address stands when it asks nothing.\n // An invoiced draft offers the rates it was made with, and the buyer picks\n // one, as on the draft's first link (AGL-4099).\n const rates = charge.shippingOptions ?? []\n if (rates.length > 0) {\n CommerceModel.appendShippingAddressCollectionParams(\n params,\n charge.shippingCountries?.length ? charge.shippingCountries : CommerceModel.CHECKOUT_SHIPPING_COUNTRIES,\n )\n CommerceModel.appendCheckoutShippingParams(params, rates)\n } else if (charge.shippingCents > 0) {\n const country = String(quote.shipTo?.country ?? '').toUpperCase()\n CommerceModel.appendShippingAddressCollectionParams(\n params,\n /^[A-Z]{2}$/.test(country) ? [country] : CommerceModel.CHECKOUT_SHIPPING_COUNTRIES,\n )\n CommerceModel.appendCheckoutShippingParams(params, [\n { rateId: 'quote', name: 'Shipping', amountCents: charge.shippingCents },\n ])\n }\n const shippingFloorCents = rates.length > 0 ? CommerceModel.shippingFloorCents(rates) : charge.shippingCents\n const direct = input.chargeModel === 'direct'\n for (const [key, value] of Object.entries(\n // A direct charge is already the seller's money, Stripe Tax included\n // (computed on THEIR registrations), so the take is the whole split.\n direct\n ? directChargeParams(input.feeCents)\n : CommerceModel.destinationChargeParams({\n accountId: input.accountId,\n feeCents: input.feeCents,\n taxOwner: charge.taxAtPayment ? 'platform' : 'merchant',\n merchantGoodsCents: charge.goodsCents,\n shippingFloorCents,\n }),\n )) {\n params.set(key, value)\n }\n const email = String((invoice ? order.customerEmail : quote.customer?.email) ?? '').trim()\n if (email) params.set('customer_email', email)\n const separator = input.returnUrl.includes('?') ? '&' : '?'\n params.set('success_url', `${input.returnUrl}${separator}session_id={CHECKOUT_SESSION_ID}`)\n params.set('cancel_url', input.returnUrl)\n // What the `commerce-draft` webhook branch reads to turn this quote into\n // its order, and to tell a payment for the quote as it stands from one for\n // a replaced link or an earlier edit.\n params.set('metadata[type]', 'commerce-draft')\n params.set('metadata[hostId]', input.hostId)\n params.set('metadata[orderId]', input.quoteId)\n if (invoice) {\n // An invoice's link version, which the draft branch compares as a\n // quote's (AGL-4099), and the promotion the draft was priced with, which\n // it counts once the draft is paid (no hold: the draft's lapsed with its\n // first session).\n params.set('metadata[payLinkVersion]', String(CommerceModel.orderPayLinkVersion(order)))\n if (order.discountId) params.set('metadata[discountId]', String(order.discountId))\n } else {\n params.set('metadata[quoteId]', input.quoteId)\n params.set('metadata[quoteLinkVersion]', String(CommerceModel.quoteLinkVersion(quote)))\n params.set('metadata[quoteUpdatedAtMs]', String(Number(quote.updatedAtMs) || 0))\n if (input.chargedTax) params.set('metadata[quoteTax]', CommerceModel.quoteTaxBasisKey(input.chargedTax))\n }\n params.set('metadata[feeCents]', String(input.feeCents))\n // What the webhook, refunds and reports read to find the payment on the\n // seller's account rather than the platform's.\n if (direct) params.set('metadata[chargeModel]', 'direct')\n // A tax charged as its own line is invisible to Stripe's tax total; this\n // witness is what records it as the business's tax.\n if (charge.taxCents > 0 && charge.taxPct === null) {\n params.set('metadata[taxCents]', String(charge.taxCents))\n }\n // The fixed transfer Aglyn keeps its Stripe Tax back from; a direct charge\n // transfers nothing and its tax is the seller's.\n if (charge.taxAtPayment && !direct) {\n params.set(\n 'metadata[transferCents]',\n String(\n CommerceModel.platformLiableTransferCents({\n feeCents: input.feeCents,\n merchantGoodsCents: charge.goodsCents,\n shippingFloorCents,\n }),\n ),\n )\n params.set('metadata[transferShippingCents]', String(shippingFloorCents))\n }\n // The store's choices, and never buy-now-pay-later (AGL-4198), so the fee\n // above is priced at the card rate.\n CommerceModel.appendStorefrontPaymentMethodParams(params, input.paymentMethods)\n return params\n}\n\nconst QUOTE_UPDATED_MESSAGE = 'This quote was updated since you opened it. Reload the page to see it before you pay.'\n\nconst refusal = (status: number, reason: string, error: string, extra: Record<string, unknown> = {}): QuoteLinkOutcome => ({\n status,\n body: { error, reason, ...extra },\n})\n\n/** `POST /api/commerce/quote-pay`: a fresh Checkout Session for the quote. */\nexport async function handleQuotePay(deps: QuotePayDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome> {\n if (req.method !== 'POST') return { status: 405, body: { error: 'Method not allowed' } }\n if (!process.env.STRIPE_SECRET_KEY) return { status: 501, body: { error: 'Payments are not configured.' } }\n const { hostId, quoteId, token, complete } = quoteLinkParams(bodyOf(req))\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const idempotencyKey = headerOf(req, 'idempotency-key').slice(0, 200)\n if (!idempotencyKey) return { status: 400, body: { error: 'Paying needs an Idempotency-Key header.' } }\n const refused = await limitedQuoteLink(deps, req, `commerce-quote-pay:${hostId}`, QUOTE_PAY_PRESSES_PER_WINDOW)\n if (refused) return refused\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { invoices: true })\n if ('outcome' in linked) return linked.outcome\n const { hostRef, host, order, storeName, store, kind } = linked.loaded\n const noun = nounOf(kind)\n\n // Every refusal the customer can be given is above the claim, so none of\n // them spends the press. `v` is the edit of the quote the page showed: a\n // quote changed since is shown again before it is paid, never charged unseen.\n // An invoice is not edited, so it sends none. `tax` is the tax the page\n // priced it under: a quote saved before the store chose its sales tax is\n // priced under the choice as it stands, so one the store changed since, or\n // a page that did not say, is shown again too.\n const body = bodyOf(req)\n const seen = Number(body['v'])\n if (kind === 'quote' && Number.isFinite(seen) && seen > 0 && seen !== (Number(order.quote?.updatedAtMs) || 0)) {\n return refusal(409, 'updated', QUOTE_UPDATED_MESSAGE)\n }\n const payStore = CommerceModel.payLinkStoreOf({ tax: store.get('tax') })\n const payTax = CommerceModel.quotePayTax(order.quote, payStore)\n if (kind === 'quote') {\n const shownTax = typeof body['tax'] === 'string' ? body['tax'] : null\n const taxKey = CommerceModel.quoteTaxBasisKey(payTax.basis)\n if (shownTax !== null ? shownTax !== taxKey : payTax.source === 'current') {\n return refusal(409, 'updated', QUOTE_UPDATED_MESSAGE)\n }\n }\n const payments = await payLinkPayments(deps, { hostId, orderId: quoteId, kind })\n const blocked = CommerceModel.payLinkRefusalWithPayments(\n CommerceModel.invoicePayRefusal(order, quoteId, payStore),\n payments.ready,\n )\n if (blocked === 'payments-unavailable') {\n return refusal(409, blocked, CommerceModel.payLinkPaymentsUnavailableMessage(storeName, kind))\n }\n const tellTaxRefusal = deps.tellTaxRefusal ?? tellCheckoutTaxRefusal\n if (blocked === 'tax-undecided') tellTaxRefusal(hostId, 'tax-undecided')\n if (blocked) return refusal(409, blocked, CommerceModel.invoicePayRefusalMessage(blocked, storeName, kind))\n const { owner, accountId, chargeModel } = payments\n const direct = chargeModel === 'direct'\n // Every Stripe object for a direct sale lives on the seller's account.\n const onAccount = connectedAccountHeader(chargeModel, accountId)\n const sessionAccount = onAccount['Stripe-Account'] ?? ''\n\n const charge = CommerceModel.invoiceCheckoutCharge(order, quoteId, payStore)\n // The fee is sized on the most the buyer can pay, as a draft's first link\n // sized it on its dearest rate, and its processing half at the card rate:\n // the session below excludes every buy-now-pay-later method. A direct\n // charge's fee is the take alone: Stripe bills the seller its card fee.\n const dearestRateCents = charge.shippingOptions.reduce((most, rate) => Math.max(most, rate.amountCents), 0)\n const feeCents = resolveTransactionFeeCents(\n owner?.org as never,\n charge.feeProductType,\n charge.goodsCents,\n charge.totalCents + dearestRateCents,\n direct ? { direct: true } : { stripeTax: charge.taxAtPayment },\n )\n // Stripe refuses `automatic_tax` on a seller's account whose Stripe Tax is\n // not set up, and a store that chose it must not sell untaxed. Above the\n // claim, so the refusal spends no press.\n if (direct && charge.taxAtPayment) {\n const taxActive = await (deps.sellerTaxActive ?? sellerStripeTaxActive)(String(accountId))\n if (!taxActive) {\n tellTaxRefusal(hostId, 'stripe-tax-not-active')\n return refusal(409, 'seller-tax', SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE)\n }\n }\n const nativeMode = await deps.nativeMode(String(owner?.id ?? ''))\n const site = host as SiteReturnHost\n const origin = siteReturnOrigin({\n candidates: [headerOf(req, 'referer'), `https://${headerOf(req, 'host')}`],\n site,\n requestHost: headerOf(req, 'host'),\n })\n const returnUrl = `${origin}${quotePageHref(quoteId, token)}`\n // A draft's first session (the one its paymentLinkUrl opens) is closed\n // here too, so the draft has one way to pay from the first press on.\n const openedFor = order.checkoutSessionId ?? ''\n const openedAtEdit = Number(order.quote?.updatedAtMs) || 0\n const openedAtVersion = CommerceModel.orderPayLinkVersion(order)\n // Closes a session this quote opened, on the account it was opened on. A\n // seller's earlier session may be the platform's (opened before the seller\n // moved to direct charges), so one the seller's account does not know is\n // closed there too: leaving it open would be a second way to pay.\n const expire = async (sessionId: string): Promise<CheckoutSessionExpiry> => {\n if (!sessionAccount) return deps.expireSession(sessionId)\n const result = await deps.expireSession(sessionId, sessionAccount)\n return result === 'missing' ? deps.expireSession(sessionId) : result\n }\n\n const claimed = await claimAttempt(deps.firestore(), {\n kind: 'commerce-quote-pay',\n scopeId: `${hostId}:${quoteId}`,\n orgId: String(owner?.id ?? ''),\n key: idempotencyKey,\n busyMessage: 'Your payment is already being set up',\n })\n if ('replay' in claimed) {\n return { status: claimed.replay.status, body: claimed.replay.body as Record<string, unknown> }\n }\n const claim = claimed.claim\n const stripeKey = (object: string): Record<string, string> => {\n const derived = deriveStripeObjectKey(claim.stripeKey, object)\n return derived ? { 'Idempotency-Key': derived } : {}\n }\n let minted = ''\n try {\n // The session the last press opened is closed before another opens. One\n // that was paid a moment ago means the quote is paid; one that cannot be\n // closed means a second session would be a second way to pay.\n if (openedFor) {\n const previous = await expire(openedFor)\n if (previous === 'complete') {\n await claim.release()\n return refusal(409, 'paid', `This ${noun} has just been paid. Your receipt is on its way.`, { confirming: true })\n }\n if (previous === 'open') {\n await claim.release()\n return { status: 502, body: { error: 'Your payment could not be set up. Try again.' } }\n }\n }\n\n let taxRateId = ''\n if (charge.taxPct !== null && charge.taxableCents > 0) {\n const basis = kind === 'quote' ? payTax.basis : null\n taxRateId =\n (await deps.taxRateId({\n hostRef,\n taxPct: charge.taxPct,\n taxLabel:\n basis?.kind === 'rate'\n ? basis.label || `Tax (${charge.taxPct}%)`\n : 'Sales tax',\n headers: stripeKey(`tax-rate-${Math.round(charge.taxPct * 10_000)}`),\n // A platform rate id does not resolve on the seller's account.\n ...(sessionAccount ? { stripeAccount: sessionAccount } : {}),\n })) ?? ''\n if (!taxRateId) {\n // Never an untaxed session for a taxed quote.\n await claim.release()\n return { status: 502, body: { error: 'Your payment could not be set up. Try again.' } }\n }\n }\n\n const paymentMethods = CommerceModel.resolveStorefrontPaymentMethodControls(\n CommerceModel.normalizeStorefrontPaymentMethodSettings(store.get('paymentMethods')),\n )\n const params = buildQuoteSessionParams({\n hostId,\n quoteId,\n order,\n charge,\n accountId: String(accountId),\n ...(direct ? { chargeModel } : {}),\n feeCents,\n taxRateId,\n returnUrl,\n paymentMethods,\n chargedTax: kind === 'quote' && payTax.source === 'current' ? payTax.basis : null,\n })\n if (nativeMode.native) {\n applyNativeCheckoutParams(params, params.get('success_url') ?? returnUrl)\n }\n // Apple Pay's domain is registered on the account the session lives on.\n const domainInput = {\n pageUrl: returnUrl,\n site,\n hostId,\n ...(sessionAccount ? { stripeAccount: sessionAccount } : {}),\n }\n const domain = nativeMode.native ? deps.ensureDomain(domainInput) : Promise.resolve(null)\n const created = await deps.createSession(params, {\n ...stripeKey('session'),\n ...nativeCheckoutStripeHeaders(nativeMode),\n ...onAccount,\n })\n await domain\n const payload = created.ok\n ? // A direct sale's in-page form opens Stripe.js on the seller's account, where the session is.\n readCheckoutSessionPayload(created.session, nativeMode, paymentMethods.wallets, sessionAccount)\n : null\n if (!payload || !created.session.id) {\n console.error('Stripe quote checkout error', created.session?.error)\n await claim.release()\n return { status: 502, body: { error: 'Your payment could not be set up. Try again.' } }\n }\n minted = String(created.session.id)\n\n // The quote keeps the session it now has open. Whatever another press\n // stored meanwhile is closed after, so the last press is the one open\n // session; a quote that was paid, replaced or edited meanwhile closes\n // this one instead.\n const orderRef = hostRef.collection('orders').doc(quoteId)\n const settled = await deps.firestore().runTransaction(async (transaction) => {\n const snapshot = await transaction.get(orderRef)\n const current = snapshot.exists ? (snapshot.data() as CommerceModel.HostOrder) : null\n if (!current || CommerceModel.orderPayLinkKind(current) !== kind) return { outcome: NOT_FOUND_ANY, displaced: '' }\n if (current.status !== 'pending') {\n const closed = current.status === 'cancelled' || current.status === 'refunded'\n return {\n outcome: refusal(\n 409,\n closed ? 'closed' : 'paid',\n CommerceModel.invoicePayRefusalMessage(closed ? 'closed' : 'paid', storeName, kind),\n ),\n displaced: '',\n }\n }\n if (CommerceModel.orderPayLinkVersion(current) !== openedAtVersion) {\n return {\n outcome: {\n status: 410,\n body: { replaced: true, error: `This ${noun} was updated, and ${storeName || 'the business'} sent you a newer link.` },\n },\n displaced: '',\n }\n }\n if (kind === 'quote' && (Number(current.quote?.updatedAtMs) || 0) !== openedAtEdit) {\n return { outcome: refusal(409, 'updated', QUOTE_UPDATED_MESSAGE), displaced: '' }\n }\n transaction.set(orderRef, { checkoutSessionId: minted }, { merge: true })\n const displaced = current.checkoutSessionId && current.checkoutSessionId !== openedFor ? current.checkoutSessionId : ''\n return { outcome: null, displaced }\n })\n if (settled.outcome) {\n await expire(minted)\n await claim.release()\n return settled.outcome\n }\n if (settled.displaced && settled.displaced !== minted) await expire(settled.displaced)\n await claim.record(200, payload)\n return { status: 200, body: payload as unknown as Record<string, unknown> }\n } catch (error) {\n console.error('quote pay failed', error)\n if (minted) await expire(minted).catch(() => 'open')\n await claim.release()\n return { status: 500, body: { error: 'Your payment could not be set up. Try again.' } }\n }\n}\n\n/** Sends a link route's answer, never cached or indexed. */\nexport function sendQuoteLinkOutcome(res: Parameters<PluginApiHandler>[1], outcome: QuoteLinkOutcome) {\n res.setHeader('Cache-Control', 'private, no-store')\n res.setHeader('X-Robots-Tag', 'noindex, nofollow')\n for (const [name, value] of Object.entries(outcome.headers ?? {})) res.setHeader(name, value)\n return res.status(outcome.status).json(outcome.body)\n}\n\n/** `GET /api/commerce/quote-view`. */\nexport const quoteViewHandler: PluginApiHandler = async (req, res) => {\n try {\n return sendQuoteLinkOutcome(res, await handleQuoteView(defaultQuotePayDeps(), req))\n } catch (error) {\n console.error('quote view failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'This quote could not be loaded. Try again.' } })\n }\n}\n\n/** `POST /api/commerce/quote-pay`. */\nexport const quotePayHandler: PluginApiHandler = async (req, res) =>\n sendQuoteLinkOutcome(res, await handleQuotePay(defaultQuotePayDeps(), req))\n"],"names":["ACCOUNTS_PLUGIN_ID","checkEntitlement","claimAttempt","deriveStripeObjectKey","resolveHostEnabledPlugins","resolveTransactionFeeCents","resolveHostToken","readClientIp","siteReturnOrigin","consumeRateLimit","firebaseAdmin","getOrgForHost","connectedAccountHeader","directChargeParams","merchantAccountIsReady","saleChargeModel","checkoutSessionCardAuthenticationParams","quotePageHref","CommerceModel","expireCheckoutSession","resolveManualTaxRateId","applyNativeCheckoutParams","nativeCheckoutStripeHeaders","readCheckoutSessionPayload","resolveNativeCheckoutMode","orderStatusUrl","MEMBER_SESSIONS_VALID_FROM_FIELD","memberCookieName","parseMemberSession","ensureCheckoutDomain","verifyQuoteLinkToken","SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE","sellerStripeTaxActive","tellCheckoutTaxRefusal","QUOTE_VIEW_LOOKUPS_PER_WINDOW","QUOTE_PAY_PRESSES_PER_WINDOW","QUOTE_WINDOW_MS","readQuoteCustomerAccount","input","member","owner","hostId","org","host","includes","found","app","firestore","collection","doc","where","email","limit","get","docs","id","validFromMs","Number","suspended","quoteProofAccessFor","deps","req","quote","order","requireProofSignIn","quoteCustomerAccountEmail","account","customerAccount","cookies","session","signedIn","memberId","issuedAtMs","quoteProofAccess","accountId","signedInAccountId","quoteProofAccessRefusal","access","storeName","status","body","error","quoteProofAccessMessage","reason","defaultQuotePayDeps","key","options","orgForHost","orgId","nativeMode","taxRateId","createSession","params","headers","response","fetch","method","Authorization","process","env","STRIPE_SECRET_KEY","toString","ok","json","catch","expireSession","sessionId","stripeAccount","expireConnectedCheckoutSession","ensureDomain","now","Date","test","String","secretKey","trim","expired","read","DOC_ID","NOT_FOUND","NOT_FOUND_ANY","nounOf","kind","bodyOf","raw","parsed","JSON","parse","headerOf","name","value","toLowerCase","Array","isArray","limitedQuoteLink","ip","remoteAddress","socket","rate","windowMs","allowed","Math","max","ceil","resetMs","loadLinkedQuote","quoteId","token","hostSnapshot","notFound","invoices","version","outcome","hostRef","store","orderSnapshot","Promise","all","exists","data","orderPayLinkKind","current","orderPayLinkVersion","history","noun","quoteIsProofOnly","state","replaced","loaded","quoteLinkParams","source","slice","complete","Boolean","payLinkPayments","ready","chargeModel","ownerUid","profile","chargesEnabled","accountLivemode","subject","orderId","payLinkPageView","currency","unpaid","receiptUrl","paymentsReady","undefined","view","payLinkStoreOf","tax","buildInvoicePageView","proofAccess","messages","currentQuoteProofs","length","orderRef","listed","orderBy","QUOTE_MESSAGES_SHOWN","quotePageMessages","map","entry","buildQuotePageView","approvalStatements","quoteApprovalStatements","handleQuoteView","query","refused","linked","buildQuoteSessionParams","charge","invoice","URLSearchParams","mode","taxAtPayment","lines","forEach","line","index","at","set","amountCents","description","taxable","rates","shippingOptions","appendShippingAddressCollectionParams","shippingCountries","CHECKOUT_SHIPPING_COUNTRIES","appendCheckoutShippingParams","shippingCents","country","shipTo","toUpperCase","rateId","shippingFloorCents","direct","Object","entries","feeCents","destinationChargeParams","taxOwner","merchantGoodsCents","goodsCents","customerEmail","customer","separator","returnUrl","discountId","quoteLinkVersion","updatedAtMs","chargedTax","quoteTaxBasisKey","taxCents","taxPct","platformLiableTransferCents","appendStorefrontPaymentMethodParams","paymentMethods","QUOTE_UPDATED_MESSAGE","refusal","extra","handleQuotePay","onAccount","idempotencyKey","seen","isFinite","payStore","payTax","quotePayTax","shownTax","taxKey","basis","payments","blocked","payLinkRefusalWithPayments","invoicePayRefusal","payLinkPaymentsUnavailableMessage","tellTaxRefusal","invoicePayRefusalMessage","sessionAccount","invoiceCheckoutCharge","dearestRateCents","reduce","most","feeProductType","totalCents","stripeTax","taxActive","sellerTaxActive","site","origin","candidates","requestHost","openedFor","checkoutSessionId","openedAtEdit","openedAtVersion","expire","result","claimed","scopeId","busyMessage","replay","claim","stripeKey","object","derived","minted","previous","release","confirming","taxableCents","taxLabel","label","round","resolveStorefrontPaymentMethodControls","normalizeStorefrontPaymentMethodSettings","native","domainInput","pageUrl","domain","resolve","created","payload","wallets","console","settled","runTransaction","transaction","snapshot","displaced","closed","merge","record","sendQuoteLinkOutcome","res","setHeader","quoteViewHandler","quotePayHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,kBAAkB,EAClBC,gBAAgB,EAChBC,YAAY,EACZC,qBAAqB,EACrBC,yBAAyB,EACzBC,0BAA0B,QAGrB,sBAAqB;AAC5B,SAASC,gBAAgB,QAA8B,qCAAoC;AAC3F,SAASC,YAAY,QAAQ,oCAAmC;AAChE,SAA8BC,gBAAgB,QAAQ,yCAAwC;AAC9F,SAASC,gBAAgB,EAAEC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACzF,SACEC,sBAAsB,EACtBC,kBAAkB,EAClBC,sBAAsB,EACtBC,eAAe,QAEV,mDAAkD;AACzD,SAASC,uCAAuC,QAAQ,6DAA4D;AACpH,SAASC,aAAa,QAAQ,6BAAyB;AACvD,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,qBAAqB,QAAoC,+BAA2B;AAC7F,SAASC,sBAAsB,QAAQ,uBAAmB;AAC1D,SACEC,yBAAyB,EACzBC,2BAA2B,EAC3BC,0BAA0B,EAC1BC,yBAAyB,QAEpB,uBAAmB;AAC1B,SAASC,cAAc,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ero-tax sale would be wrong.
|
|
34
34
|
*/
|
|
35
35
|
export declare const SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE = "This store is finishing its sales tax setup. Please try again later.";
|
|
36
|
+
/**
|
|
37
|
+
* The same refusal for the store's own manager, who makes a draft order's
|
|
38
|
+
* payment link in the console and reads the answer there (AGL-4245).
|
|
39
|
+
*/
|
|
40
|
+
export declare const SELLER_STRIPE_TAX_NOT_SET_UP_MANAGER_MESSAGE: string;
|
|
36
41
|
/**
|
|
37
42
|
* Whether the seller's own Stripe Tax is set up (head office, preset tax
|
|
38
43
|
* code, at least one registration): Stripe's `tax/settings` status on their
|
|
@@ -43,3 +48,17 @@ export declare const SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE = "This store is finis
|
|
|
43
48
|
* read reads as not set up, the answer that never blocks a sale.
|
|
44
49
|
*/
|
|
45
50
|
export declare function sellerStripeTaxActive(sellerAccount: string): Promise<boolean>;
|
|
51
|
+
/**
|
|
52
|
+
* The seller's own `GET /v1/tax/settings` answer, or null when it could not be
|
|
53
|
+
* read: the one read `sellerStripeTaxActive` makes, shared with the console's
|
|
54
|
+
* readiness route (AGL-4245) so the two can never disagree.
|
|
55
|
+
*/
|
|
56
|
+
export declare function fetchSellerStripeTaxSettings(sellerAccount: string): Promise<Record<string, unknown> | null>;
|
|
57
|
+
/**
|
|
58
|
+
* Whether the seller's account has at least one active tax registration
|
|
59
|
+
* (`GET /v1/tax/registrations`), for the console's readiness route
|
|
60
|
+
* (AGL-4245). Stripe Tax turns on without one and then adds no tax anywhere,
|
|
61
|
+
* so the Taxes card says so. Null when the list could not be read. Checkout
|
|
62
|
+
* never asks this: it changes nothing about whether a sale may go through.
|
|
63
|
+
*/
|
|
64
|
+
export declare function sellerHasActiveTaxRegistration(sellerAccount: string): Promise<boolean | null>;
|
|
@@ -69,6 +69,10 @@ import { saleChargeModel } from "@aglyn/tenant-data-admin/server/payment-provide
|
|
|
69
69
|
* sold untaxed, the same doctrine as an unfinished tax settings card
|
|
70
70
|
* (AGL-2145): the store decided to collect, so a zero-tax sale would be wrong.
|
|
71
71
|
*/ export const SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE = 'This store is finishing its sales tax setup. Please try again later.';
|
|
72
|
+
/**
|
|
73
|
+
* The same refusal for the store's own manager, who makes a draft order's
|
|
74
|
+
* payment link in the console and reads the answer there (AGL-4245).
|
|
75
|
+
*/ export const SELLER_STRIPE_TAX_NOT_SET_UP_MANAGER_MESSAGE = 'Stripe Tax isn’t on in your Stripe account yet, so this link can’t collect sales tax. ' + 'Finish it in Products → Taxes, or choose another sales tax option there.';
|
|
72
76
|
/**
|
|
73
77
|
* Whether the seller's own Stripe Tax is set up (head office, preset tax
|
|
74
78
|
* code, at least one registration): Stripe's `tax/settings` status on their
|
|
@@ -78,9 +82,17 @@ import { saleChargeModel } from "@aglyn/tenant-data-admin/server/payment-provide
|
|
|
78
82
|
* to collect through Stripe Tax yet: their tax, their call. Any failure to
|
|
79
83
|
* read reads as not set up, the answer that never blocks a sale.
|
|
80
84
|
*/ export async function sellerStripeTaxActive(sellerAccount) {
|
|
85
|
+
const settings = await fetchSellerStripeTaxSettings(sellerAccount);
|
|
86
|
+
return (settings == null ? void 0 : settings.status) === 'active';
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The seller's own `GET /v1/tax/settings` answer, or null when it could not be
|
|
90
|
+
* read: the one read `sellerStripeTaxActive` makes, shared with the console's
|
|
91
|
+
* readiness route (AGL-4245) so the two can never disagree.
|
|
92
|
+
*/ export async function fetchSellerStripeTaxSettings(sellerAccount) {
|
|
81
93
|
var _process_env_STRIPE_SECRET_KEY;
|
|
82
94
|
const key = String((_process_env_STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY) != null ? _process_env_STRIPE_SECRET_KEY : '').trim();
|
|
83
|
-
if (!key || !sellerAccount) return
|
|
95
|
+
if (!key || !sellerAccount) return null;
|
|
84
96
|
try {
|
|
85
97
|
const response = await fetch('https://api.stripe.com/v1/tax/settings', {
|
|
86
98
|
headers: {
|
|
@@ -88,11 +100,35 @@ import { saleChargeModel } from "@aglyn/tenant-data-admin/server/payment-provide
|
|
|
88
100
|
'Stripe-Account': sellerAccount
|
|
89
101
|
}
|
|
90
102
|
});
|
|
91
|
-
if (!response.ok) return
|
|
103
|
+
if (!response.ok) return null;
|
|
92
104
|
const settings = await response.json().catch(()=>null);
|
|
93
|
-
return
|
|
105
|
+
return settings && typeof settings === 'object' ? settings : null;
|
|
94
106
|
} catch (unused) {
|
|
95
|
-
return
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Whether the seller's account has at least one active tax registration
|
|
112
|
+
* (`GET /v1/tax/registrations`), for the console's readiness route
|
|
113
|
+
* (AGL-4245). Stripe Tax turns on without one and then adds no tax anywhere,
|
|
114
|
+
* so the Taxes card says so. Null when the list could not be read. Checkout
|
|
115
|
+
* never asks this: it changes nothing about whether a sale may go through.
|
|
116
|
+
*/ export async function sellerHasActiveTaxRegistration(sellerAccount) {
|
|
117
|
+
var _process_env_STRIPE_SECRET_KEY;
|
|
118
|
+
const key = String((_process_env_STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY) != null ? _process_env_STRIPE_SECRET_KEY : '').trim();
|
|
119
|
+
if (!key || !sellerAccount) return null;
|
|
120
|
+
try {
|
|
121
|
+
const response = await fetch('https://api.stripe.com/v1/tax/registrations?status=active&limit=1', {
|
|
122
|
+
headers: {
|
|
123
|
+
Authorization: `Bearer ${key}`,
|
|
124
|
+
'Stripe-Account': sellerAccount
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
if (!response.ok) return null;
|
|
128
|
+
const list = await response.json().catch(()=>null);
|
|
129
|
+
return Array.isArray(list == null ? void 0 : list.data) ? list.data.length > 0 : null;
|
|
130
|
+
} catch (unused) {
|
|
131
|
+
return null;
|
|
96
132
|
}
|
|
97
133
|
}
|
|
98
134
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/seller-stripe-account.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 { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { saleChargeModel } from '@aglyn/tenant-data-admin/server/payment-provider'\n\n/*==========================================\n * WHERE A SITE SALE'S STRIPE OBJECTS LIVE\n *\n * A direct-charge sale's session, payment intent, customer and subscription\n * live on the SELLER's connected account, and Stripe answers 404 for them on\n * the platform. The routes that come back to a sale later (the return page's\n * status read, a cancel, a refund lookup, the subscriber portal) only hold an\n * id, so they ask the site which account sells for it, try that account\n * first, and fall back to the platform on a 404. The fallback is what keeps\n * the sales that stay on the platform readable from the same route: Aglyn's\n * own card-reader hardware, and anything sold before the seller switched.\n *=========================================*/\n\n/** The seller's account when the site sells by direct charges, else null. */\nexport async function directSellerAccountForHost(\n hostId: string,\n): Promise<string | null> {\n if (!hostId) return null\n try {\n const ownerOrg = await getOrgForHost(hostId)\n const ownerUid = String(ownerOrg?.org?.ownerUid ?? '')\n if (!ownerUid) return null\n const profile = await firebaseAdmin\n .app()\n .firestore()\n .collection('profiles')\n .doc(ownerUid)\n .get()\n const accountId = String(profile.get('stripeAccountId') ?? '').trim()\n if (!accountId) return null\n return saleChargeModel(profile.get('stripeChargeModel')) === 'direct'\n ? accountId\n : null\n } catch {\n return null\n }\n}\n\n/**\n * `fetch` against the Stripe API on the seller's account first, then on the\n * platform when the seller's account does not know the object. With no\n * seller account it is a plain platform call.\n */\nexport async function fetchOnSellerThenPlatform(\n url: string,\n init: RequestInit & { headers?: Record<string, string> },\n sellerAccount: string | null | undefined,\n): Promise<Response> {\n if (!sellerAccount) return fetch(url, init)\n const onSeller = await fetch(url, {\n ...init,\n headers: { ...(init.headers ?? {}), 'Stripe-Account': sellerAccount },\n })\n if (onSeller.status !== 404) return onSeller\n return fetch(url, init)\n}\n\n/** Whether a Stripe object says it was sold by direct charge. */\nexport function isDirectChargeObject(object: any): boolean {\n return (\n String(\n object?.metadata?.chargeModel ??\n object?.subscription_details?.metadata?.chargeModel ??\n object?.parent?.subscription_details?.metadata?.chargeModel ??\n '',\n ) === 'direct'\n )\n}\n\n/**\n * What a shopper is told when a direct-charge store chose Stripe Tax but has\n * not finished setting it up on its own Stripe account. Refused rather than\n * sold untaxed, the same doctrine as an unfinished tax settings card\n * (AGL-2145): the store decided to collect, so a zero-tax sale would be wrong.\n */\nexport const SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE =\n 'This store is finishing its sales tax setup. Please try again later.'\n\n/**\n * Whether the seller's own Stripe Tax is set up (head office, preset tax\n * code, at least one registration): Stripe's `tax/settings` status on their\n * account. A direct-charge session asks for `automatic_tax` only when it is,\n * because on an account without it Stripe refuses the session and the\n * shopper is told checkout failed. Not set up means the seller has chosen not\n * to collect through Stripe Tax yet: their tax, their call. Any failure to\n * read reads as not set up, the answer that never blocks a sale.\n */\nexport async function sellerStripeTaxActive(\n sellerAccount: string,\n): Promise<boolean> {\n const key = String(process.env.STRIPE_SECRET_KEY ?? '').trim()\n if (!key || !sellerAccount) return false\n try {\n const response = await fetch('https://api.stripe.com/v1/tax/settings', {\n headers: { Authorization: `Bearer ${key}`, 'Stripe-Account': sellerAccount },\n })\n if (!response.ok) return false\n const settings = (await response.json().catch(() => null)) as {\n status?: string\n } | null\n return settings?.status === 'active'\n } catch {\n return false\n }\n}\n"],"names":["firebaseAdmin","getOrgForHost","saleChargeModel","directSellerAccountForHost","hostId","profile","ownerOrg","ownerUid","String","org","app","firestore","collection","doc","get","accountId","trim","fetchOnSellerThenPlatform","url","init","sellerAccount","fetch","onSeller","headers","status","isDirectChargeObject","object","metadata","chargeModel","subscription_details","parent","SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE","sellerStripeTaxActive","process","key","env","STRIPE_SECRET_KEY","response","Authorization","ok","settings","json","catch"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,eAAe,QAAQ,mDAAkD;AAElF;;;;;;;;;;;2CAW2C,GAE3C,2EAA2E,GAC3E,OAAO,eAAeC,2BACpBC,MAAc;IAEd,IAAI,CAACA,QAAQ,OAAO;IACpB,IAAI;kBAUuBC;YARDC;QADxB,MAAMA,WAAW,MAAML,cAAcG;QACrC,MAAMG,WAAWC,eAAOF,6BAAAA,gBAAAA,SAAUG,GAAG,qBAAbH,cAAeC,QAAQ,mBAAI;QACnD,IAAI,CAACA,UAAU,OAAO;QACtB,MAAMF,UAAU,MAAML,cACnBU,GAAG,GACHC,SAAS,GACTC,UAAU,CAAC,YACXC,GAAG,CAACN,UACJO,GAAG;QACN,MAAMC,YAAYP,QAAOH,eAAAA,QAAQS,GAAG,CAAC,8BAAZT,eAAkC,IAAIW,IAAI;QACnE,IAAI,CAACD,WAAW,OAAO;QACvB,OAAOb,gBAAgBG,QAAQS,GAAG,CAAC,0BAA0B,WACzDC,YACA;IACN,EAAE,eAAM;QACN,OAAO;IACT;AACF;AAEA;;;;CAIC,GACD,OAAO,eAAeE,0BACpBC,GAAW,EACXC,IAAwD,EACxDC,aAAwC;QAKvBD;IAHjB,IAAI,CAACC,eAAe,OAAOC,MAAMH,KAAKC;IACtC,MAAMG,WAAW,MAAMD,MAAMH,KAAK,aAC7BC;QACHI,SAAS,cAAMJ,gBAAAA,KAAKI,OAAO,YAAZJ,gBAAgB,CAAC;YAAI,kBAAkBC;;;IAExD,IAAIE,SAASE,MAAM,KAAK,KAAK,OAAOF;IACpC,OAAOD,MAAMH,KAAKC;AACpB;AAEA,+DAA+D,GAC/D,OAAO,SAASM,qBAAqBC,MAAW;QAG1CA,MAAAA;QAAAA,kBACEA,uCAAAA,8BACAA,8CAAAA,qCAAAA;IAJN,OACElB,QACEkB,QAAAA,iBAAAA,2BAAAA,mBAAAA,OAAQC,QAAQ,qBAAhBD,iBAAkBE,WAAW,oBAC3BF,2BAAAA,+BAAAA,OAAQG,oBAAoB,sBAA5BH,wCAAAA,6BAA8BC,QAAQ,qBAAtCD,sCAAwCE,WAAW,YADrDF,QAEEA,2BAAAA,iBAAAA,OAAQI,MAAM,sBAAdJ,sCAAAA,eAAgBG,oBAAoB,sBAApCH,+CAAAA,oCAAsCC,QAAQ,qBAA9CD,6CAAgDE,WAAW,YAF7DF,OAGE,QACE;AAEV;AAEA;;;;;CAKC,GACD,OAAO,MAAMK,uCACX,uEAAsE;AAExE;;;;;;;;CAQC,GACD,OAAO,eAAeC,sBACpBZ,aAAqB;QAEFa;IAAnB,MAAMC,MAAM1B,QAAOyB,iCAAAA,QAAQE,GAAG,CAACC,iBAAiB,YAA7BH,iCAAiC,IAAIjB,IAAI;IAC5D,IAAI,CAACkB,OAAO,CAACd,eAAe,OAAO;IACnC,IAAI;QACF,MAAMiB,WAAW,MAAMhB,MAAM,0CAA0C;YACrEE,SAAS;gBAAEe,eAAe,CAAC,OAAO,EAAEJ,KAAK;gBAAE,kBAAkBd;YAAc;QAC7E;QACA,IAAI,CAACiB,SAASE,EAAE,EAAE,OAAO;QACzB,MAAMC,WAAY,MAAMH,SAASI,IAAI,GAAGC,KAAK,CAAC,IAAM;QAGpD,OAAOF,CAAAA,4BAAAA,SAAUhB,MAAM,MAAK;IAC9B,EAAE,eAAM;QACN,OAAO;IACT;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/seller-stripe-account.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 { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { saleChargeModel } from '@aglyn/tenant-data-admin/server/payment-provider'\n\n/*==========================================\n * WHERE A SITE SALE'S STRIPE OBJECTS LIVE\n *\n * A direct-charge sale's session, payment intent, customer and subscription\n * live on the SELLER's connected account, and Stripe answers 404 for them on\n * the platform. The routes that come back to a sale later (the return page's\n * status read, a cancel, a refund lookup, the subscriber portal) only hold an\n * id, so they ask the site which account sells for it, try that account\n * first, and fall back to the platform on a 404. The fallback is what keeps\n * the sales that stay on the platform readable from the same route: Aglyn's\n * own card-reader hardware, and anything sold before the seller switched.\n *=========================================*/\n\n/** The seller's account when the site sells by direct charges, else null. */\nexport async function directSellerAccountForHost(\n hostId: string,\n): Promise<string | null> {\n if (!hostId) return null\n try {\n const ownerOrg = await getOrgForHost(hostId)\n const ownerUid = String(ownerOrg?.org?.ownerUid ?? '')\n if (!ownerUid) return null\n const profile = await firebaseAdmin\n .app()\n .firestore()\n .collection('profiles')\n .doc(ownerUid)\n .get()\n const accountId = String(profile.get('stripeAccountId') ?? '').trim()\n if (!accountId) return null\n return saleChargeModel(profile.get('stripeChargeModel')) === 'direct'\n ? accountId\n : null\n } catch {\n return null\n }\n}\n\n/**\n * `fetch` against the Stripe API on the seller's account first, then on the\n * platform when the seller's account does not know the object. With no\n * seller account it is a plain platform call.\n */\nexport async function fetchOnSellerThenPlatform(\n url: string,\n init: RequestInit & { headers?: Record<string, string> },\n sellerAccount: string | null | undefined,\n): Promise<Response> {\n if (!sellerAccount) return fetch(url, init)\n const onSeller = await fetch(url, {\n ...init,\n headers: { ...(init.headers ?? {}), 'Stripe-Account': sellerAccount },\n })\n if (onSeller.status !== 404) return onSeller\n return fetch(url, init)\n}\n\n/** Whether a Stripe object says it was sold by direct charge. */\nexport function isDirectChargeObject(object: any): boolean {\n return (\n String(\n object?.metadata?.chargeModel ??\n object?.subscription_details?.metadata?.chargeModel ??\n object?.parent?.subscription_details?.metadata?.chargeModel ??\n '',\n ) === 'direct'\n )\n}\n\n/**\n * What a shopper is told when a direct-charge store chose Stripe Tax but has\n * not finished setting it up on its own Stripe account. Refused rather than\n * sold untaxed, the same doctrine as an unfinished tax settings card\n * (AGL-2145): the store decided to collect, so a zero-tax sale would be wrong.\n */\nexport const SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE =\n 'This store is finishing its sales tax setup. Please try again later.'\n\n/**\n * The same refusal for the store's own manager, who makes a draft order's\n * payment link in the console and reads the answer there (AGL-4245).\n */\nexport const SELLER_STRIPE_TAX_NOT_SET_UP_MANAGER_MESSAGE =\n 'Stripe Tax isn’t on in your Stripe account yet, so this link can’t collect sales tax. ' +\n 'Finish it in Products → Taxes, or choose another sales tax option there.'\n\n/**\n * Whether the seller's own Stripe Tax is set up (head office, preset tax\n * code, at least one registration): Stripe's `tax/settings` status on their\n * account. A direct-charge session asks for `automatic_tax` only when it is,\n * because on an account without it Stripe refuses the session and the\n * shopper is told checkout failed. Not set up means the seller has chosen not\n * to collect through Stripe Tax yet: their tax, their call. Any failure to\n * read reads as not set up, the answer that never blocks a sale.\n */\nexport async function sellerStripeTaxActive(\n sellerAccount: string,\n): Promise<boolean> {\n const settings = await fetchSellerStripeTaxSettings(sellerAccount)\n return (settings as { status?: string } | null)?.status === 'active'\n}\n\n/**\n * The seller's own `GET /v1/tax/settings` answer, or null when it could not be\n * read: the one read `sellerStripeTaxActive` makes, shared with the console's\n * readiness route (AGL-4245) so the two can never disagree.\n */\nexport async function fetchSellerStripeTaxSettings(\n sellerAccount: string,\n): Promise<Record<string, unknown> | null> {\n const key = String(process.env.STRIPE_SECRET_KEY ?? '').trim()\n if (!key || !sellerAccount) return null\n try {\n const response = await fetch('https://api.stripe.com/v1/tax/settings', {\n headers: { Authorization: `Bearer ${key}`, 'Stripe-Account': sellerAccount },\n })\n if (!response.ok) return null\n const settings = (await response.json().catch(() => null)) as Record<string, unknown> | null\n return settings && typeof settings === 'object' ? settings : null\n } catch {\n return null\n }\n}\n\n/**\n * Whether the seller's account has at least one active tax registration\n * (`GET /v1/tax/registrations`), for the console's readiness route\n * (AGL-4245). Stripe Tax turns on without one and then adds no tax anywhere,\n * so the Taxes card says so. Null when the list could not be read. Checkout\n * never asks this: it changes nothing about whether a sale may go through.\n */\nexport async function sellerHasActiveTaxRegistration(\n sellerAccount: string,\n): Promise<boolean | null> {\n const key = String(process.env.STRIPE_SECRET_KEY ?? '').trim()\n if (!key || !sellerAccount) return null\n try {\n const response = await fetch('https://api.stripe.com/v1/tax/registrations?status=active&limit=1', {\n headers: { Authorization: `Bearer ${key}`, 'Stripe-Account': sellerAccount },\n })\n if (!response.ok) return null\n const list = (await response.json().catch(() => null)) as { data?: unknown } | null\n return Array.isArray(list?.data) ? list.data.length > 0 : null\n } catch {\n return null\n }\n}\n"],"names":["firebaseAdmin","getOrgForHost","saleChargeModel","directSellerAccountForHost","hostId","profile","ownerOrg","ownerUid","String","org","app","firestore","collection","doc","get","accountId","trim","fetchOnSellerThenPlatform","url","init","sellerAccount","fetch","onSeller","headers","status","isDirectChargeObject","object","metadata","chargeModel","subscription_details","parent","SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE","SELLER_STRIPE_TAX_NOT_SET_UP_MANAGER_MESSAGE","sellerStripeTaxActive","settings","fetchSellerStripeTaxSettings","process","key","env","STRIPE_SECRET_KEY","response","Authorization","ok","json","catch","sellerHasActiveTaxRegistration","list","Array","isArray","data","length"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,eAAe,QAAQ,mDAAkD;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AS;gBAAEkB,eAAe,CAAC,OAAO,EAAEJ,KAAK;gBAAE,kBAAkBjB;YAAc;QAC7E;QACA,IAAI,CAACoB,SAASE,EAAE,EAAE,OAAO;QACzB,MAAMI,OAAQ,MAAMN,SAASG,IAAI,GAAGC,KAAK,CAAC,IAAM;QAChD,OAAOG,MAAMC,OAAO,CAACF,wBAAAA,KAAMG,IAAI,IAAIH,KAAKG,IAAI,CAACC,MAAM,GAAG,IAAI;IAC5D,EAAE,eAAM;QACN,OAAO;IACT;AACF"}
|
|
@@ -26,12 +26,7 @@ import * as CommerceModel from '../model';
|
|
|
26
26
|
* undefined for everything else so the loader falls through.
|
|
27
27
|
*/
|
|
28
28
|
export declare const commerceSitePageResolver: SitePageResolver;
|
|
29
|
-
|
|
30
|
-
* What `{{product.price}}` says: the price, "From" the lowest where variants
|
|
31
|
-
* differ, or "Price coming soon" for a product listed before any variant has
|
|
32
|
-
* one (AGL-3676) — never "$0".
|
|
33
|
-
*/
|
|
34
|
-
export declare function productPriceText(product: Pick<CommerceModel.HostProduct, 'variants'>, minPrice: number, maxPrice: number): string;
|
|
29
|
+
export { productPriceText } from '../model';
|
|
35
30
|
/**
|
|
36
31
|
* The store's built-in product page (AGL-3676), root first, for the layout's
|
|
37
32
|
* slot: the product block for the routed slug — with its Details and
|
|
@@ -122,7 +122,7 @@ import { readProductReviews } from "./reviews.js";
|
|
|
122
122
|
tokens: {
|
|
123
123
|
'product.name': product.name,
|
|
124
124
|
'product.description': (_product_description = product.description) != null ? _product_description : '',
|
|
125
|
-
'product.price': productPriceText(product, minPrice, maxPrice),
|
|
125
|
+
'product.price': CommerceModel.productPriceText(product, minPrice, maxPrice),
|
|
126
126
|
'product.image': (_ref = (_ref1 = (_product_mediaUrls = product.mediaUrls) == null ? void 0 : _product_mediaUrls[0]) != null ? _ref1 : product.imageUrl) != null ? _ref : '',
|
|
127
127
|
'product.slug': product.slug
|
|
128
128
|
},
|
|
@@ -281,17 +281,9 @@ import { readProductReviews } from "./reviews.js";
|
|
|
281
281
|
}
|
|
282
282
|
return undefined;
|
|
283
283
|
};
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
* one (AGL-3676) — never "$0".
|
|
288
|
-
*/ export function productPriceText(product, minPrice, maxPrice) {
|
|
289
|
-
var _product_variants;
|
|
290
|
-
if (!((_product_variants = product.variants) != null ? _product_variants : []).some((variant)=>CommerceModel.variantHasPrice(variant))) {
|
|
291
|
-
return 'Price coming soon';
|
|
292
|
-
}
|
|
293
|
-
return minPrice === maxPrice ? `$${minPrice}` : `From $${minPrice}`;
|
|
294
|
-
}
|
|
284
|
+
// What `{{product.price}}` says (AGL-3676) lives with the model now, so the
|
|
285
|
+
// site's search can caption a product the same way without loading this page.
|
|
286
|
+
export { productPriceText } from "../model/index.js";
|
|
295
287
|
const PRODUCT_PAGE_NODE = 'pdp__detail';
|
|
296
288
|
const PRODUCT_PAGE_REVIEWS_NODE = 'pdp__reviews';
|
|
297
289
|
const PRODUCT_PAGE_RELATED_NODE = 'pdp__related';
|