@aglyn/plugins-commerce 1.15.1 → 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +13 -13
- package/src/lib/components/cart.js +2 -1
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/console/payments-settings-card.component.js +6 -1
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-api.d.ts +5 -0
- package/src/lib/components/console/pos/pos-api.js.map +1 -1
- package/src/lib/components/console/pos/pos-tender-dialogs.component.d.ts +2 -0
- package/src/lib/components/console/pos/pos-tender-dialogs.component.js +13 -6
- package/src/lib/components/console/pos/pos-tender-dialogs.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-tender-panel.component.js +7 -4
- package/src/lib/components/console/pos/pos-tender-panel.component.js.map +1 -1
- package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
- package/src/lib/components/console/product-add-ons-fields.component.js +96 -3
- package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
- package/src/lib/components/console/product-builder-fields.component.d.ts +39 -0
- package/src/lib/components/console/product-builder-fields.component.js +195 -0
- package/src/lib/components/console/product-builder-fields.component.js.map +1 -0
- package/src/lib/components/console/product-editor-dialog.component.js +35 -2
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/quote-editor-dialog.component.js +43 -6
- package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/quote-messages.component.d.ts +21 -0
- package/src/lib/components/console/quote-messages.component.js +185 -0
- package/src/lib/components/console/quote-messages.component.js.map +1 -0
- package/src/lib/components/console/quote-pay-link.component.js +1 -1
- package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
- package/src/lib/components/console/quote-proofs.component.js +30 -3
- package/src/lib/components/console/quote-proofs.component.js.map +1 -1
- package/src/lib/components/console/quote-settings-card.component.d.ts +7 -3
- package/src/lib/components/console/quote-settings-card.component.js +154 -24
- package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
- package/src/lib/components/product-builder-context.d.ts +22 -0
- package/src/lib/components/product-builder-context.js +21 -0
- package/src/lib/components/product-builder-context.js.map +1 -0
- package/src/lib/components/product-builder-mockup.d.ts +42 -0
- package/src/lib/components/product-builder-mockup.js +120 -0
- package/src/lib/components/product-builder-mockup.js.map +1 -0
- package/src/lib/components/product-builder-sample.d.ts +63 -0
- package/src/lib/components/product-builder-sample.js +96 -0
- package/src/lib/components/product-builder-sample.js.map +1 -0
- package/src/lib/components/product-choice-cards.d.ts +51 -0
- package/src/lib/components/product-choice-cards.js +311 -0
- package/src/lib/components/product-choice-cards.js.map +1 -0
- package/src/lib/components/product-detail-panels.d.ts +42 -0
- package/src/lib/components/product-detail-panels.js +185 -0
- package/src/lib/components/product-detail-panels.js.map +1 -0
- package/src/lib/components/product-detail.d.ts +20 -12
- package/src/lib/components/product-detail.js +136 -221
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/product-grid.d.ts +7 -0
- package/src/lib/components/product-grid.js +11 -8
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/product-options-field-body.d.ts +9 -8
- package/src/lib/components/product-options-field-body.js +152 -3
- package/src/lib/components/product-options-field-body.js.map +1 -1
- package/src/lib/components/product-options-field.js +1 -1
- package/src/lib/components/product-options-field.js.map +1 -1
- package/src/lib/components/product-photo-fit.d.ts +49 -0
- package/src/lib/components/product-photo-fit.js +58 -0
- package/src/lib/components/product-photo-fit.js.map +1 -0
- package/src/lib/components/product-restock-notify.d.ts +12 -0
- package/src/lib/components/product-restock-notify.js +86 -0
- package/src/lib/components/product-restock-notify.js.map +1 -0
- package/src/lib/components/quote-messages-panel.d.ts +21 -0
- package/src/lib/components/quote-messages-panel.js +191 -0
- package/src/lib/components/quote-messages-panel.js.map +1 -0
- package/src/lib/components/quote-page-body.js +15 -1
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/components/quote-proof-panel.d.ts +6 -3
- package/src/lib/components/quote-proof-panel.js +139 -14
- package/src/lib/components/quote-proof-panel.js.map +1 -1
- package/src/lib/components/related-products.d.ts +7 -0
- package/src/lib/components/related-products.js +8 -6
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/constants/quote-page.d.ts +8 -0
- package/src/lib/constants/quote-page.js +11 -0
- package/src/lib/constants/quote-page.js.map +1 -1
- package/src/lib/model/commerce-cart.d.ts +6 -1
- package/src/lib/model/commerce-cart.js +5 -1
- package/src/lib/model/commerce-cart.js.map +1 -1
- package/src/lib/model/commerce-invoices.js +5 -1
- package/src/lib/model/commerce-invoices.js.map +1 -1
- package/src/lib/model/commerce-pos-ops.d.ts +3 -0
- package/src/lib/model/commerce-pos-ops.js +3 -0
- package/src/lib/model/commerce-pos-ops.js.map +1 -1
- package/src/lib/model/commerce-pos.d.ts +8 -0
- package/src/lib/model/commerce-pos.js.map +1 -1
- package/src/lib/model/commerce-quote-messages.d.ts +106 -0
- package/src/lib/model/commerce-quote-messages.js +146 -0
- package/src/lib/model/commerce-quote-messages.js.map +1 -0
- package/src/lib/model/commerce-quote-pay.d.ts +31 -2
- package/src/lib/model/commerce-quote-pay.js +31 -7
- package/src/lib/model/commerce-quote-pay.js.map +1 -1
- package/src/lib/model/commerce-quote-proofs.d.ts +47 -8
- package/src/lib/model/commerce-quote-proofs.js +73 -18
- package/src/lib/model/commerce-quote-proofs.js.map +1 -1
- package/src/lib/model/commerce-quote-request.d.ts +14 -4
- package/src/lib/model/commerce-quote-request.js +25 -2
- package/src/lib/model/commerce-quote-request.js.map +1 -1
- package/src/lib/model/commerce-quotes.d.ts +56 -3
- package/src/lib/model/commerce-quotes.js +47 -2
- package/src/lib/model/commerce-quotes.js.map +1 -1
- package/src/lib/model/commerce.d.ts +12 -1
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/index.d.ts +1 -0
- package/src/lib/model/index.js +1 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/pos-cellular.d.ts +5 -0
- package/src/lib/model/pos-cellular.js.map +1 -1
- package/src/lib/model/product-card-rules.d.ts +41 -0
- package/src/lib/model/product-card-rules.js +90 -0
- package/src/lib/model/product-card-rules.js.map +1 -0
- package/src/lib/model/product-modifiers.d.ts +11 -0
- package/src/lib/model/product-modifiers.js +10 -0
- package/src/lib/model/product-modifiers.js.map +1 -1
- package/src/lib/model/product-write.d.ts +3 -0
- package/src/lib/server/billing-webhook.js +6 -2
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cancel-order.js +15 -0
- package/src/lib/server/cancel-order.js.map +1 -1
- package/src/lib/server/channel-order-updates.js +15 -1
- package/src/lib/server/channel-order-updates.js.map +1 -1
- package/src/lib/server/channel-orders.js +20 -0
- package/src/lib/server/channel-orders.js.map +1 -1
- package/src/lib/server/checkout.js +1 -1
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/local-fulfillment.js +1 -1
- package/src/lib/server/local-fulfillment.js.map +1 -1
- package/src/lib/server/pos-cellular-billing.d.ts +1 -1
- package/src/lib/server/pos-cellular-billing.js +2 -1
- package/src/lib/server/pos-cellular-billing.js.map +1 -1
- package/src/lib/server/pos-cellular.d.ts +3 -1
- package/src/lib/server/pos-cellular.js +15 -8
- package/src/lib/server/pos-cellular.js.map +1 -1
- package/src/lib/server/pos-offline-sync.d.ts +3 -3
- package/src/lib/server/pos-offline-sync.js +17 -4
- package/src/lib/server/pos-offline-sync.js.map +1 -1
- package/src/lib/server/pos-order.js +17 -6
- package/src/lib/server/pos-order.js.map +1 -1
- package/src/lib/server/pos-payment.js +27 -11
- package/src/lib/server/pos-payment.js.map +1 -1
- package/src/lib/server/pos-reader-splash.js +10 -5
- package/src/lib/server/pos-reader-splash.js.map +1 -1
- package/src/lib/server/pos-readers.js +34 -10
- package/src/lib/server/pos-readers.js.map +1 -1
- package/src/lib/server/pos-return.js +19 -3
- package/src/lib/server/pos-return.js.map +1 -1
- package/src/lib/server/pos-stripe.d.ts +14 -0
- package/src/lib/server/pos-stripe.js +6 -2
- package/src/lib/server/pos-stripe.js.map +1 -1
- package/src/lib/server/pos-terminal-connection-token.js +23 -9
- package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
- package/src/lib/server/pos-terminal.d.ts +80 -14
- package/src/lib/server/pos-terminal.js +393 -123
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/server/product-drafts.d.ts +1 -1
- package/src/lib/server/product-drafts.js +4 -3
- package/src/lib/server/product-drafts.js.map +1 -1
- package/src/lib/server/product-writer.js +5 -4
- package/src/lib/server/product-writer.js.map +1 -1
- package/src/lib/server/product.d.ts +11 -0
- package/src/lib/server/product.js +18 -3
- package/src/lib/server/product.js.map +1 -1
- package/src/lib/server/products-write.js +4 -3
- package/src/lib/server/products-write.js.map +1 -1
- package/src/lib/server/quote-email.d.ts +26 -0
- package/src/lib/server/quote-email.js +73 -7
- package/src/lib/server/quote-email.js.map +1 -1
- package/src/lib/server/quote-messages.d.ts +72 -0
- package/src/lib/server/quote-messages.js +356 -0
- package/src/lib/server/quote-messages.js.map +1 -0
- package/src/lib/server/quote-pay.d.ts +42 -0
- package/src/lib/server/quote-pay.js +81 -4
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote-proofs.d.ts +1 -1
- package/src/lib/server/quote-proofs.js +63 -19
- package/src/lib/server/quote-proofs.js.map +1 -1
- package/src/lib/server/quote.d.ts +12 -0
- package/src/lib/server/quote.js +44 -14
- package/src/lib/server/quote.js.map +1 -1
- package/src/lib/server/refund.js +3 -1
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server/reserve-stock.js +9 -0
- package/src/lib/server/reserve-stock.js.map +1 -1
- package/src/lib/server/returns.js +15 -1
- package/src/lib/server/returns.js.map +1 -1
- package/src/lib/server/reviews.js +15 -0
- package/src/lib/server/reviews.js.map +1 -1
- package/src/lib/server/sold-out-drop.d.ts +58 -0
- package/src/lib/server/sold-out-drop.js +81 -0
- package/src/lib/server/sold-out-drop.js.map +1 -0
- package/src/lib/server/stock-levels.js +9 -0
- package/src/lib/server/stock-levels.js.map +1 -1
- package/src/lib/server/stripe-refund.d.ts +7 -0
- package/src/lib/server/stripe-refund.js +26 -7
- package/src/lib/server/stripe-refund.js.map +1 -1
- package/src/lib/server.js +2 -0
- package/src/lib/server.js.map +1 -1
- package/src/lib/tenant-emails.js +85 -2
- package/src/lib/tenant-emails.js.map +1 -1
- package/src/lib/testing/fake-seller-payment-account.d.ts +29 -0
- package/src/lib/testing/fake-seller-payment-account.js +40 -0
- package/src/lib/testing/fake-seller-payment-account.js.map +1 -0
- package/src/lib/transfer/product-transfer.js +6 -5
- package/src/lib/transfer/product-transfer.js.map +1 -1
- package/src/lib/transfer/products.server.js +4 -3
- package/src/lib/transfer/products.server.js.map +1 -1
- package/src/lib/utils/quote-email-content.d.ts +6 -0
- package/src/lib/utils/quote-email-content.js +6 -3
- package/src/lib/utils/quote-email-content.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 checkEntitlement,\n claimAttempt,\n deriveStripeObjectKey,\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 { 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 now(): number\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 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: { hostId: string; orderId: string; loaded: Pick<LoadedQuote, 'host' | 'order' | 'storeName' | 'store' | 'kind'> },\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 return kind === 'quote' ? CommerceModel.buildQuotePageView(view) : CommerceModel.buildInvoicePageView(view)\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 view = await payLinkPageView(deps, { hostId, orderId: quoteId, loaded: linked.loaded })\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":["checkEntitlement","claimAttempt","deriveStripeObjectKey","resolveTransactionFeeCents","resolveHostToken","readClientIp","siteReturnOrigin","consumeRateLimit","firebaseAdmin","getOrgForHost","connectedAccountHeader","directChargeParams","merchantAccountIsReady","saleChargeModel","checkoutSessionCardAuthenticationParams","quotePageHref","CommerceModel","expireCheckoutSession","resolveManualTaxRateId","applyNativeCheckoutParams","nativeCheckoutStripeHeaders","readCheckoutSessionPayload","resolveNativeCheckoutMode","orderStatusUrl","ensureCheckoutDomain","verifyQuoteLinkToken","SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE","sellerStripeTaxActive","QUOTE_VIEW_LOOKUPS_PER_WINDOW","QUOTE_PAY_PRESSES_PER_WINDOW","QUOTE_WINDOW_MS","defaultQuotePayDeps","firestore","app","key","options","orgForHost","hostId","found","id","orgId","org","nativeMode","taxRateId","input","createSession","params","headers","response","fetch","method","Authorization","process","env","STRIPE_SECRET_KEY","body","toString","ok","session","json","catch","expireSession","sessionId","stripeAccount","expireConnectedCheckoutSession","ensureDomain","now","Date","test","String","secretKey","trim","expired","read","status","DOC_ID","NOT_FOUND","error","NOT_FOUND_ANY","nounOf","kind","bodyOf","req","raw","parsed","JSON","parse","headerOf","name","value","toLowerCase","Array","isArray","limitedQuoteLink","deps","limit","ip","remoteAddress","socket","rate","windowMs","allowed","Math","max","ceil","resetMs","loadLinkedQuote","quoteId","token","hostSnapshot","notFound","invoices","version","outcome","hostRef","collection","doc","store","orderSnapshot","Promise","all","get","exists","order","data","orderPayLinkKind","host","storeName","current","orderPayLinkVersion","history","noun","quoteIsProofOnly","state","replaced","loaded","quoteLinkParams","source","slice","complete","Boolean","payLinkPayments","owner","ready","accountId","chargeModel","ownerUid","profile","chargesEnabled","accountLivemode","subject","orderId","payLinkPageView","currency","unpaid","receiptUrl","paymentsReady","undefined","view","payLinkStoreOf","tax","buildQuotePageView","buildInvoicePageView","handleQuoteView","query","refused","linked","buildQuoteSessionParams","charge","invoice","quote","URLSearchParams","mode","taxAtPayment","lines","forEach","line","index","at","set","amountCents","description","taxable","rates","shippingOptions","length","appendShippingAddressCollectionParams","shippingCountries","CHECKOUT_SHIPPING_COUNTRIES","appendCheckoutShippingParams","shippingCents","country","shipTo","toUpperCase","rateId","shippingFloorCents","direct","Object","entries","feeCents","destinationChargeParams","taxOwner","merchantGoodsCents","goodsCents","email","customerEmail","customer","separator","returnUrl","includes","discountId","quoteLinkVersion","Number","updatedAtMs","chargedTax","quoteTaxBasisKey","taxCents","taxPct","platformLiableTransferCents","appendStorefrontPaymentMethodParams","paymentMethods","QUOTE_UPDATED_MESSAGE","refusal","reason","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","orderRef","settled","runTransaction","transaction","snapshot","displaced","closed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AAM1E,eAAelM,uBAAuBmD,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'\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","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,SA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AAKC,MAAM;gBAAEC,OAAO;YAA6C;QAAE;IAChH;AACF,EAAC;AAED,oCAAoC,GACpC,OAAO,MAAMkQ,kBAAoC,OAAOtR,KAAKmR,MAC3DD,qBAAqBC,KAAK,MAAMzE,eAAenL,uBAAuBvB,MAAK"}
|
|
@@ -49,7 +49,7 @@ export type QuoteProofOutcome = QuoteLinkOutcome & {
|
|
|
49
49
|
export declare function handleQuoteProof(deps: QuoteProofDeps, req: PluginApiRequest): Promise<QuoteProofOutcome>;
|
|
50
50
|
/** `POST /api/commerce/quote-upload`: a ticket for one of the customer's files, or its finalize. */
|
|
51
51
|
export declare function handleQuoteUpload(deps: QuoteProofDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome>;
|
|
52
|
-
/** `POST /api/commerce/quote-respond`: the customer approves the proof or
|
|
52
|
+
/** `POST /api/commerce/quote-respond`: the customer approves the proof or rejects it with changes. */
|
|
53
53
|
export declare function handleQuoteRespond(deps: QuoteProofDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome>;
|
|
54
54
|
/** `GET /api/commerce/quote-proof`. */
|
|
55
55
|
export declare const quoteProofHandler: PluginApiHandler;
|
|
@@ -19,7 +19,7 @@ import { readClientIp } from "@aglyn/aglyn/app-utils/request-ip";
|
|
|
19
19
|
import { VISITOR_UPLOAD_HONEYPOT_FIELD, visitorUploadFileView, visitorUploadFolder } from "@aglyn/aglyn/app-utils/visitor-upload";
|
|
20
20
|
import { notifyHostManagers } from "@aglyn/tenant-data-admin";
|
|
21
21
|
import * as CommerceModel from "../model/index.js";
|
|
22
|
-
import { defaultQuotePayDeps, limitedQuoteLink, loadLinkedQuote, payLinkPageView, quoteLinkParams, sendQuoteLinkOutcome } from "./quote-pay.js";
|
|
22
|
+
import { defaultQuotePayDeps, limitedQuoteLink, loadLinkedQuote, payLinkPageView, quoteLinkParams, quoteProofAccessFor, quoteProofAccessRefusal, sendQuoteLinkOutcome } from "./quote-pay.js";
|
|
23
23
|
import { keepSentQuoteUploads, quoteUploadKeyRef, recordPendingQuoteUpload } from "./quote-upload-keys.js";
|
|
24
24
|
import { quoteUploadCalls } from "./quote-uploads.js";
|
|
25
25
|
/*==========================================
|
|
@@ -33,10 +33,18 @@ import { quoteUploadCalls } from "./quote-uploads.js";
|
|
|
33
33
|
* → { ticket, upload: { url, fields }, file }
|
|
34
34
|
* POST /api/commerce/quote-upload { hostId, q, t, action: 'finalize', ticket }
|
|
35
35
|
* → { file: { id, name, contentType, size, uploadedAtMs } }
|
|
36
|
-
* POST /api/commerce/quote-respond { hostId, q, t, v, action: 'approve', name }
|
|
37
|
-
* { hostId, q, t, v, action: 'changes', comment, fileIds? }
|
|
36
|
+
* POST /api/commerce/quote-respond { hostId, q, t, v, action: 'approve', name, confirmed }
|
|
37
|
+
* { hostId, q, t, v, action: 'changes', comment, name, fileIds? }
|
|
38
38
|
* + Idempotency-Key → 200 { view } | 409 { error, reason } | 410 { replaced } | 404 | 400 | 429
|
|
39
39
|
*
|
|
40
|
+
* An approval ticks every statement the store asks for (`confirmed`, the
|
|
41
|
+
* store's words as the page showed them, AGL-4206); one that skips any is
|
|
42
|
+
* 400, and one whose words the store has since changed is 409 `updated`.
|
|
43
|
+
* A quote that asks a customer with a site account to sign in
|
|
44
|
+
* (`requireProofSignIn`) answers all three routes 403 { reason: 'sign-in' |
|
|
45
|
+
* 'other-account' } until the browser is signed in to that account; a guest
|
|
46
|
+
* keeps the link alone.
|
|
47
|
+
*
|
|
40
48
|
* Every route spends a per-address rate limit on the site BEFORE the token is
|
|
41
49
|
* checked, answers a wrong token exactly as a missing quote, and (but for a
|
|
42
50
|
* proof, which an earlier email still draws) answers a link to an older
|
|
@@ -128,6 +136,13 @@ const PROOF_GONE = {
|
|
|
128
136
|
history: true
|
|
129
137
|
});
|
|
130
138
|
if ('outcome' in linked) return linked.outcome;
|
|
139
|
+
// A customer with a site account signs in to see it, when the quote asks (AGL-4206).
|
|
140
|
+
const access = await quoteProofAccessFor(deps, req, {
|
|
141
|
+
hostId,
|
|
142
|
+
host: linked.loaded.host,
|
|
143
|
+
order: linked.loaded.order
|
|
144
|
+
});
|
|
145
|
+
if (access !== 'open') return quoteProofAccessRefusal(access, linked.loaded.storeName);
|
|
131
146
|
const quote = linked.loaded.order.quote;
|
|
132
147
|
// The earlier revisions are read only when the current one lacks the proof.
|
|
133
148
|
let proof = CommerceModel.quoteProofInHistory(quote, [], fileId);
|
|
@@ -182,6 +197,12 @@ const PROOF_GONE = {
|
|
|
182
197
|
const linked = await loadLinkedQuote(deps, hostId, quoteId, token);
|
|
183
198
|
if ('outcome' in linked) return linked.outcome;
|
|
184
199
|
const { order, storeName } = linked.loaded;
|
|
200
|
+
const access = await quoteProofAccessFor(deps, req, {
|
|
201
|
+
hostId,
|
|
202
|
+
host: linked.loaded.host,
|
|
203
|
+
order
|
|
204
|
+
});
|
|
205
|
+
if (access !== 'open') return quoteProofAccessRefusal(access, storeName);
|
|
185
206
|
// Artwork rides an answer; a quote that cannot be answered takes none.
|
|
186
207
|
const refused = CommerceModel.quoteRespondRefusal(order);
|
|
187
208
|
if (refused) return reasonRefusal(409, refused, CommerceModel.quoteRespondRefusalMessage(refused, storeName));
|
|
@@ -271,12 +292,12 @@ const UPDATED_MESSAGE = 'This quote was updated since you opened it. Look it ove
|
|
|
271
292
|
* It rides `content.order`, so whoever is told about orders (in the feed, by
|
|
272
293
|
* email, by push) is told about the quotes that become them, and it names
|
|
273
294
|
* itself as what it is rather than as that type: "Proof approved" or
|
|
274
|
-
* "
|
|
295
|
+
* "Rejected with changes" where the feed and the email's eyebrow would say "New
|
|
275
296
|
* order", the customer and the quote as its heading, and "View quote" on the
|
|
276
297
|
* email's button, which opens the quote's dialog on the Orders page.
|
|
277
298
|
*/ function noticeOf(input) {
|
|
278
299
|
var _response_files, _ref, _response_name, _response_comment, _ref1;
|
|
279
|
-
var _quote_customer, _quote_customer1, _quote_customer2, _order_totals, _quote_customer3, _quote_customer4, _quote_customer5, _quote_customer6;
|
|
300
|
+
var _quote_customer, _quote_customer1, _quote_customer2, _order_totals, _quote_customer3, _quote_customer4, _quote_customer5, _response_confirmed, _quote_customer6;
|
|
280
301
|
const { hostId, quoteId, order, response } = input;
|
|
281
302
|
const quote = order.quote;
|
|
282
303
|
const number = CommerceModel.formatQuoteNumber(order, quoteId);
|
|
@@ -318,8 +339,20 @@ const UPDATED_MESSAGE = 'This quote was updated since you opened it. Look it ove
|
|
|
318
339
|
{
|
|
319
340
|
label: 'Approved as',
|
|
320
341
|
value: (_response_name = response.name) != null ? _response_name : ''
|
|
321
|
-
}
|
|
342
|
+
},
|
|
343
|
+
...((_response_confirmed = response.confirmed) == null ? void 0 : _response_confirmed.length) ? [
|
|
344
|
+
{
|
|
345
|
+
label: 'They confirmed',
|
|
346
|
+
value: response.confirmed.join(' ')
|
|
347
|
+
}
|
|
348
|
+
] : []
|
|
322
349
|
] : [
|
|
350
|
+
...response.name ? [
|
|
351
|
+
{
|
|
352
|
+
label: 'Rejected as',
|
|
353
|
+
value: response.name
|
|
354
|
+
}
|
|
355
|
+
] : [],
|
|
323
356
|
{
|
|
324
357
|
label: 'What to change',
|
|
325
358
|
value: (_response_comment = response.comment) != null ? _response_comment : ''
|
|
@@ -338,10 +371,10 @@ const UPDATED_MESSAGE = 'This quote was updated since you opened it. Look it ove
|
|
|
338
371
|
type: 'content.order',
|
|
339
372
|
// Good news for an approval; a change request is work to read.
|
|
340
373
|
level: approving ? 'success' : 'info',
|
|
341
|
-
label: approving ? 'Proof approved' : '
|
|
374
|
+
label: approving ? 'Proof approved' : 'Rejected with changes',
|
|
342
375
|
actionLabel: 'View quote',
|
|
343
|
-
title: approving ? `${customer} approved the proof for ${number} on {site}` : `${customer}
|
|
344
|
-
body: approving ? (proofOnly ? `Revision ${revision} is approved. It has no price yet: add items to the quote when you’re ready, and send it.` : quote.requireProofApproval === true ? `Revision ${revision} is approved, so they can pay the quote now. It becomes an order when they do.` : `Revision ${revision} is approved. The quote becomes an order when they pay.`) + ' The approval, with the name, time and address it was given from, is on the quote.' : files.length ? `
|
|
376
|
+
title: approving ? `${customer} approved the proof for ${number} on {site}` : `${customer} rejected the proof for ${number} with changes on {site}`,
|
|
377
|
+
body: approving ? (proofOnly ? `Revision ${revision} is approved. It has no price yet: add items to the quote when you’re ready, and send it.` : quote.requireProofApproval === true ? `Revision ${revision} is approved, so they can pay the quote now. It becomes an order when they do.` : `Revision ${revision} is approved. The quote becomes an order when they pay.`) + ' The approval, with the name, what they confirmed, and the time and address it was given from, is on the quote.' : files.length ? `They rejected revision ${revision}. What they want changed, and the ${filesSent} they sent, are on the quote. ` + `Read them, then start revision ${revision + 1} with new proofs and send it.` : `They rejected revision ${revision}. What they want changed is on the quote. ` + `Read it, then start revision ${revision + 1} with new proofs and send it.`,
|
|
345
378
|
link: `/${hostId}/products/orders?quote=${encodeURIComponent(quoteId)}`
|
|
346
379
|
},
|
|
347
380
|
options: _extends({
|
|
@@ -351,7 +384,7 @@ const UPDATED_MESSAGE = 'This quote was updated since you opened it. Look it ove
|
|
|
351
384
|
} : {})
|
|
352
385
|
};
|
|
353
386
|
}
|
|
354
|
-
/** `POST /api/commerce/quote-respond`: the customer approves the proof or
|
|
387
|
+
/** `POST /api/commerce/quote-respond`: the customer approves the proof or rejects it with changes. */ export async function handleQuoteRespond(deps, req) {
|
|
355
388
|
var _order_quote;
|
|
356
389
|
if (req.method !== 'POST') return {
|
|
357
390
|
status: 405,
|
|
@@ -387,17 +420,27 @@ const UPDATED_MESSAGE = 'This quote was updated since you opened it. Look it ove
|
|
|
387
420
|
if ('outcome' in linked) return linked.outcome;
|
|
388
421
|
const { hostRef, host, order, storeName, store } = linked.loaded;
|
|
389
422
|
// Everything the customer can be refused is decided before the claim, so
|
|
390
|
-
// none of it spends the attempt.
|
|
423
|
+
// none of it spends the attempt. A customer with a site account answers
|
|
424
|
+
// signed in to it, when the quote asks (AGL-4206).
|
|
425
|
+
const access = await quoteProofAccessFor(deps, req, {
|
|
426
|
+
hostId,
|
|
427
|
+
host,
|
|
428
|
+
order
|
|
429
|
+
});
|
|
430
|
+
if (access !== 'open') return quoteProofAccessRefusal(access, storeName);
|
|
391
431
|
const seen = Number(body['v']);
|
|
392
432
|
const version = Number((_order_quote = order.quote) == null ? void 0 : _order_quote.updatedAtMs) || 0;
|
|
393
433
|
if (!Number.isFinite(seen) || seen !== version) return reasonRefusal(409, 'updated', UPDATED_MESSAGE);
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
434
|
+
// An approval ticks every statement the store asks for now, word for word (AGL-4206).
|
|
435
|
+
const parsed = CommerceModel.parseQuoteResponseInput(body, CommerceModel.quoteApprovalStatements(store.get('quotes')));
|
|
436
|
+
if ('error' in parsed) {
|
|
437
|
+
return parsed.reason === 'statements-changed' ? reasonRefusal(409, 'updated', parsed.error) : {
|
|
438
|
+
status: 400,
|
|
439
|
+
body: {
|
|
440
|
+
error: parsed.error
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
}
|
|
401
444
|
const refused = CommerceModel.quoteRespondRefusal(order);
|
|
402
445
|
if (refused) return reasonRefusal(409, refused, CommerceModel.quoteRespondRefusalMessage(refused, storeName));
|
|
403
446
|
// The files are read back from this quote's artwork, by id: nothing the
|
|
@@ -515,7 +558,8 @@ const UPDATED_MESSAGE = 'This quote was updated since you opened it. Look it ove
|
|
|
515
558
|
storeName,
|
|
516
559
|
store,
|
|
517
560
|
kind: 'quote'
|
|
518
|
-
}
|
|
561
|
+
},
|
|
562
|
+
proofAccess: access
|
|
519
563
|
});
|
|
520
564
|
const outcome = {
|
|
521
565
|
status: 200,
|