@aglyn/plugins-commerce 1.10.0 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +13 -13
- package/src/lib/components/console/invoice-send.component.d.ts +9 -2
- package/src/lib/components/console/invoice-send.component.js +58 -30
- package/src/lib/components/console/invoice-send.component.js.map +1 -1
- package/src/lib/components/console/pay-link-readiness-notice.component.d.ts +84 -0
- package/src/lib/components/console/pay-link-readiness-notice.component.js +164 -0
- package/src/lib/components/console/pay-link-readiness-notice.component.js.map +1 -0
- package/src/lib/components/console/quote-editor-dialog.component.js +7 -8
- package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/quote-pay-link.component.d.ts +3 -0
- package/src/lib/components/console/quote-pay-link.component.js +9 -0
- package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
- package/src/lib/components/console/quote-send.component.d.ts +3 -0
- package/src/lib/components/console/quote-send.component.js +9 -0
- package/src/lib/components/console/quote-send.component.js.map +1 -1
- package/src/lib/components/quote-page-body.js +5 -3
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/model/commerce-invoices.d.ts +45 -5
- package/src/lib/model/commerce-invoices.js +46 -9
- package/src/lib/model/commerce-invoices.js.map +1 -1
- package/src/lib/model/commerce-quote-pay.d.ts +110 -6
- package/src/lib/model/commerce-quote-pay.js +182 -23
- package/src/lib/model/commerce-quote-pay.js.map +1 -1
- package/src/lib/server/billing-webhook.js +4 -1
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/commerce-pdf.js +2 -1
- package/src/lib/server/commerce-pdf.js.map +1 -1
- package/src/lib/server/invoice-email.js +2 -1
- package/src/lib/server/invoice-email.js.map +1 -1
- package/src/lib/server/order-invoice-send.js +1 -1
- package/src/lib/server/order-invoice-send.js.map +1 -1
- package/src/lib/server/order-status.d.ts +5 -1
- package/src/lib/server/order-status.js +19 -5
- package/src/lib/server/order-status.js.map +1 -1
- package/src/lib/server/quote-email.js +2 -1
- package/src/lib/server/quote-email.js.map +1 -1
- package/src/lib/server/quote-pay.d.ts +39 -0
- package/src/lib/server/quote-pay.js +103 -43
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote-proofs.js +13 -9
- package/src/lib/server/quote-proofs.js.map +1 -1
- package/src/lib/utils/invoice-email-content.d.ts +3 -1
- package/src/lib/utils/invoice-email-content.js +1 -1
- package/src/lib/utils/invoice-email-content.js.map +1 -1
- package/src/lib/utils/quote-email-content.d.ts +3 -1
- package/src/lib/utils/quote-email-content.js +3 -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 { merchantAccountIsReady } 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'\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 * 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 expireSession(sessionId: string): Promise<CheckoutSessionExpiry>\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) => expireCheckoutSession(sessionId),\n ensureDomain: (input) => ensureCheckoutDomain(input).catch(() => null),\n now: () => Date.now(),\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 return {\n outcome: {\n status: 410,\n body: {\n state: 'replaced',\n kind,\n storeName,\n replaced: true,\n error: `This ${nounOf(kind)} 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/** `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 } = linked.outcome.body as { storeName: string; kind: CommerceModel.OrderPayLinkKind }\n return { status: 200, body: { state: 'replaced', kind, storeName } }\n }\n return linked.outcome\n }\n const { host, order, storeName, store, kind } = linked.loaded\n const currency = String(store.get('currency') ?? 'USD')\n const receiptUrl = order.status === 'pending' ? null : orderStatusUrl(host, hostId, quoteId)\n const view =\n kind === 'quote'\n ? CommerceModel.buildQuotePageView({ order, orderId: quoteId, storeName, currency, receiptUrl })\n : CommerceModel.buildInvoicePageView({ order, orderId: quoteId, storeName, currency, receiptUrl })\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 feeCents: number\n taxRateId: string\n returnUrl: string\n paymentMethods: CommerceModel.StorefrontPaymentMethodControls\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 for (const [key, value] of Object.entries(\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 }\n params.set('metadata[feeCents]', String(input.feeCents))\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 if (charge.taxAtPayment) {\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 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.\n const seen = Number(bodyOf(req)['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 blocked = CommerceModel.invoicePayRefusal(order, quoteId)\n if (blocked) return refusal(409, blocked, CommerceModel.invoicePayRefusalMessage(blocked, storeName, kind))\n const owner = await deps.orgForHost(hostId)\n const unavailable = refusal(\n 409,\n 'payments-unavailable',\n `${storeName || 'This business'} can’t take payments online right now. Contact them to pay this ${noun}.`,\n )\n if (!checkEntitlement(owner?.org as never, 'commerce')) return unavailable\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: `${noun} ${quoteId} on host ${hostId}` },\n )\n if (!ready) return unavailable\n const taxSettings = (store.get('tax') ?? {}) as CommerceModel.TaxSettings\n if (CommerceModel.storefrontTaxDecision({ settings: taxSettings }).kind === 'undecided') {\n return refusal(409, 'tax-undecided', CommerceModel.invoicePayRefusalMessage('tax-undecided', storeName, kind))\n }\n\n const charge = CommerceModel.invoiceCheckoutCharge(order, quoteId)\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.\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 )\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\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 deps.expireSession(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 = order.quote?.tax\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 })) ?? ''\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 feeCents,\n taxRateId,\n returnUrl,\n paymentMethods,\n })\n if (nativeMode.native) {\n applyNativeCheckoutParams(params, params.get('success_url') ?? returnUrl)\n }\n const domain = nativeMode.native\n ? deps.ensureDomain({ pageUrl: returnUrl, site, hostId })\n : Promise.resolve(null)\n const created = await deps.createSession(params, {\n ...stripeKey('session'),\n ...nativeCheckoutStripeHeaders(nativeMode),\n })\n await domain\n const payload = created.ok\n ? readCheckoutSessionPayload(created.session, nativeMode, paymentMethods.wallets)\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 deps.expireSession(minted)\n await claim.release()\n return settled.outcome\n }\n if (settled.displaced && settled.displaced !== minted) await deps.expireSession(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 deps.expireSession(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","merchantAccountIsReady","checkoutSessionCardAuthenticationParams","quotePageHref","CommerceModel","expireCheckoutSession","resolveManualTaxRateId","applyNativeCheckoutParams","nativeCheckoutStripeHeaders","readCheckoutSessionPayload","resolveNativeCheckoutMode","orderStatusUrl","ensureCheckoutDomain","verifyQuoteLinkToken","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","ensureDomain","now","Date","DOC_ID","NOT_FOUND","status","error","NOT_FOUND_ANY","nounOf","kind","bodyOf","req","raw","parsed","JSON","parse","headerOf","name","value","toLowerCase","String","Array","isArray","trim","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","state","replaced","loaded","quoteLinkParams","source","slice","complete","test","Boolean","handleQuoteView","query","refused","linked","currency","receiptUrl","view","buildQuotePageView","orderId","buildInvoicePageView","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","Object","entries","destinationChargeParams","accountId","feeCents","taxOwner","merchantGoodsCents","goodsCents","email","customerEmail","customer","separator","returnUrl","includes","discountId","quoteLinkVersion","Number","updatedAtMs","taxCents","taxPct","platformLiableTransferCents","appendStorefrontPaymentMethodParams","paymentMethods","QUOTE_UPDATED_MESSAGE","refusal","reason","extra","handleQuotePay","owner","idempotencyKey","noun","seen","isFinite","blocked","invoicePayRefusal","invoicePayRefusalMessage","unavailable","ownerUid","profile","ready","chargesEnabled","accountLivemode","subject","taxSettings","storefrontTaxDecision","settings","invoiceCheckoutCharge","dearestRateCents","reduce","most","feeProductType","totalCents","site","origin","candidates","requestHost","openedFor","checkoutSessionId","openedAtEdit","openedAtVersion","claimed","scopeId","busyMessage","replay","claim","stripeKey","object","derived","minted","previous","release","confirming","taxableCents","basis","tax","taxLabel","label","round","resolveStorefrontPaymentMethodControls","normalizeStorefrontPaymentMethodSettings","native","domain","pageUrl","resolve","created","payload","wallets","console","orderRef","settled","runTransaction","transaction","snapshot","displaced","closed","merge","record","sendQuoteLinkOutcome","res","setHeader","quoteViewHandler","quotePayHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,YAAY,EACZC,qBAAqB,EACrBC,0BAA0B,QAGrB,sBAAqB;AAC5B,SAASC,gBAAgB,QAA8B,qCAAoC;AAC3F,SAASC,YAAY,QAAQ,oCAAmC;AAChE,SAA8BC,gBAAgB,QAAQ,yCAAwC;AAC9F,SAASC,gBAAgB,EAAEC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACzF,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SAASC,uCAAuC,QAAQ,6DAA4D;AACpH,SAASC,aAAa,QAAQ,6BAAyB;AACvD,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,qBAAqB,QAAoC,+BAA2B;AAC7F,SAASC,sBAAsB,QAAQ,uBAAmB;AAC1D,SACEC,yBAAyB,EACzBC,2BAA2B,EAC3BC,0BAA0B,EAC1BC,yBAAyB,QAEpB,uBAAmB;AAC1B,SAASC,cAAc,QAAQ,0BAAsB;AACrD,SAASC,oBAAoB,QAAQ,8BAA0B;AAC/D,SAASC,oBAAoB,QAAQ,wBAAoB;AAEzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAmC2C,GAE3C,wEAAwE,GACxE,OAAO,MAAMC,gCAAgC,GAAE;AAC/C,OAAO,MAAMC,+BAA+B,GAAE;AAC9C,OAAO,MAAMC,kBAAkB,KAAK,MAAM;AAmB1C,OAAO,SAASC;IACd,OAAO;QACLC,WAAW,IAAMnB,cAAcoB,GAAG,GAAGD,SAAS;QAC9CpB,kBAAkB,CAACsB,KAAKC,UAAYvB,iBAAiBsB,KAAKC;QAC1DC,YAAY,OAAOC;YACjB,MAAMC,QAAQ,MAAMxB,cAAcuB;YAClC,OAAOC,QAAQ;gBAAEC,IAAID,MAAME,KAAK;gBAAEC,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
|
+
{"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 { merchantAccountIsReady } 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'\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 expireSession(sessionId: string): Promise<CheckoutSessionExpiry>\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) => expireCheckoutSession(sessionId),\n ensureDomain: (input) => ensureCheckoutDomain(input).catch(() => null),\n now: () => Date.now(),\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 return {\n outcome: {\n status: 410,\n body: {\n state: 'replaced',\n kind,\n storeName,\n replaced: true,\n error: `This ${nounOf(kind)} 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\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')) return { ready: false, owner, accountId: '' }\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 { ready, owner, accountId: ready ? String(accountId) : '' }\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 } = linked.outcome.body as { storeName: string; kind: CommerceModel.OrderPayLinkKind }\n return { status: 200, body: { state: 'replaced', kind, 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 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 for (const [key, value] of Object.entries(\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 // 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 if (charge.taxAtPayment) {\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 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 } = payments\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.\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 )\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\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 deps.expireSession(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 })) ?? ''\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 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 const domain = nativeMode.native\n ? deps.ensureDomain({ pageUrl: returnUrl, site, hostId })\n : Promise.resolve(null)\n const created = await deps.createSession(params, {\n ...stripeKey('session'),\n ...nativeCheckoutStripeHeaders(nativeMode),\n })\n await domain\n const payload = created.ok\n ? readCheckoutSessionPayload(created.session, nativeMode, paymentMethods.wallets)\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 deps.expireSession(minted)\n await claim.release()\n return settled.outcome\n }\n if (settled.displaced && settled.displaced !== minted) await deps.expireSession(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 deps.expireSession(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","merchantAccountIsReady","checkoutSessionCardAuthenticationParams","quotePageHref","CommerceModel","expireCheckoutSession","resolveManualTaxRateId","applyNativeCheckoutParams","nativeCheckoutStripeHeaders","readCheckoutSessionPayload","resolveNativeCheckoutMode","orderStatusUrl","ensureCheckoutDomain","verifyQuoteLinkToken","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","ensureDomain","now","Date","DOC_ID","NOT_FOUND","status","error","NOT_FOUND_ANY","nounOf","kind","bodyOf","req","raw","parsed","JSON","parse","headerOf","name","value","toLowerCase","String","Array","isArray","trim","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","state","replaced","loaded","quoteLinkParams","source","slice","complete","test","Boolean","payLinkPayments","owner","ready","accountId","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","Object","entries","destinationChargeParams","feeCents","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","idempotencyKey","noun","seen","isFinite","payStore","payTax","quotePayTax","shownTax","taxKey","basis","payments","blocked","payLinkRefusalWithPayments","invoicePayRefusal","payLinkPaymentsUnavailableMessage","invoicePayRefusalMessage","invoiceCheckoutCharge","dearestRateCents","reduce","most","feeProductType","totalCents","site","origin","candidates","requestHost","openedFor","checkoutSessionId","openedAtEdit","openedAtVersion","claimed","scopeId","busyMessage","replay","claim","stripeKey","object","derived","minted","previous","release","confirming","taxableCents","taxLabel","label","round","resolveStorefrontPaymentMethodControls","normalizeStorefrontPaymentMethodSettings","native","domain","pageUrl","resolve","created","payload","wallets","console","orderRef","settled","runTransaction","transaction","snapshot","displaced","closed","merge","record","sendQuoteLinkOutcome","res","setHeader","quoteViewHandler","quotePayHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,YAAY,EACZC,qBAAqB,EACrBC,0BAA0B,QAGrB,sBAAqB;AAC5B,SAASC,gBAAgB,QAA8B,qCAAoC;AAC3F,SAASC,YAAY,QAAQ,oCAAmC;AAChE,SAA8BC,gBAAgB,QAAQ,yCAAwC;AAC9F,SAASC,gBAAgB,EAAEC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACzF,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SAASC,uCAAuC,QAAQ,6DAA4D;AACpH,SAASC,aAAa,QAAQ,6BAAyB;AACvD,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,qBAAqB,QAAoC,+BAA2B;AAC7F,SAASC,sBAAsB,QAAQ,uBAAmB;AAC1D,SACEC,yBAAyB,EACzBC,2BAA2B,EAC3BC,0BAA0B,EAC1BC,yBAAyB,QAEpB,uBAAmB;AAC1B,SAASC,cAAc,QAAQ,0BAAsB;AACrD,SAASC,oBAAoB,QAAQ,8BAA0B;AAC/D,SAASC,oBAAoB,QAAQ,wBAAoB;AAEzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA0C2C,GAE3C,wEAAwE,GACxE,OAAO,MAAMC,gCAAgC,GAAE;AAC/C,OAAO,MAAMC,+BAA+B,GAAE;AAC9C,OAAO,MAAMC,kBAAkB,KAAK,MAAM;AAmB1C,OAAO,SAASC;IACd,OAAO;QACLC,WAAW,IAAMnB,cAAcoB,GAAG,GAAGD,SAAS;QAC9CpB,kBAAkB,CAACsB,KAAKC,UAAYvB,iBAAiBsB,KAAKC;QAC1DC,YAAY,OAAOC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,EAAC;AAED,oCAAoC,GACpC,OAAO,MAAMyN,kBAAoC,OAAOpN,KAAKiN,MAC3DD,qBAAqBC,KAAK,MAAMnE,eAAezL,uBAAuB2C,MAAK"}
|
|
@@ -19,8 +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 {
|
|
23
|
-
import { defaultQuotePayDeps, limitedQuoteLink, loadLinkedQuote, quoteLinkParams, sendQuoteLinkOutcome } from "./quote-pay.js";
|
|
22
|
+
import { defaultQuotePayDeps, limitedQuoteLink, loadLinkedQuote, payLinkPageView, quoteLinkParams, sendQuoteLinkOutcome } from "./quote-pay.js";
|
|
24
23
|
import { keepSentQuoteUploads, quoteUploadKeyRef, recordPendingQuoteUpload } from "./quote-upload-keys.js";
|
|
25
24
|
import { quoteUploadCalls } from "./quote-uploads.js";
|
|
26
25
|
/*==========================================
|
|
@@ -439,7 +438,7 @@ const UPDATED_MESSAGE = 'This quote was updated since you opened it. Look it ove
|
|
|
439
438
|
const claim = claimed.claim;
|
|
440
439
|
const now = deps.now();
|
|
441
440
|
try {
|
|
442
|
-
var _store_get
|
|
441
|
+
var _store_get;
|
|
443
442
|
const ref = hostRef.collection('orders').doc(quoteId);
|
|
444
443
|
const pendingRef = quoteUploadKeyRef(deps.firestore(), hostId, quoteId);
|
|
445
444
|
const settled = await deps.firestore().runTransaction(async (transaction)=>{
|
|
@@ -500,12 +499,17 @@ const UPDATED_MESSAGE = 'This quote was updated since you opened it. Look it ove
|
|
|
500
499
|
await claim.release();
|
|
501
500
|
return settled.outcome;
|
|
502
501
|
}
|
|
503
|
-
|
|
504
|
-
|
|
502
|
+
// The page's own view, so an approval brings Pay back only where Pay would work.
|
|
503
|
+
const view = await payLinkPageView(deps, {
|
|
504
|
+
hostId,
|
|
505
505
|
orderId: quoteId,
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
506
|
+
loaded: {
|
|
507
|
+
host,
|
|
508
|
+
order: settled.order,
|
|
509
|
+
storeName,
|
|
510
|
+
store,
|
|
511
|
+
kind: 'quote'
|
|
512
|
+
}
|
|
509
513
|
});
|
|
510
514
|
const outcome = {
|
|
511
515
|
status: 200,
|
|
@@ -519,7 +523,7 @@ const UPDATED_MESSAGE = 'This quote was updated since you opened it. Look it ove
|
|
|
519
523
|
quoteId,
|
|
520
524
|
order: settled.order,
|
|
521
525
|
response: settled.response,
|
|
522
|
-
currency: String((
|
|
526
|
+
currency: String((_store_get = store.get('currency')) != null ? _store_get : 'USD')
|
|
523
527
|
});
|
|
524
528
|
void deps.notify(hostId, notice.payload, notice.options);
|
|
525
529
|
return outcome;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/quote-proofs.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 { claimAttempt, type PluginApiHandler, type PluginApiRequest } from '@aglyn/aglyn/server'\nimport { readClientIp } from '@aglyn/aglyn/app-utils/request-ip'\nimport { VISITOR_UPLOAD_HONEYPOT_FIELD, visitorUploadFileView, visitorUploadFolder } from '@aglyn/aglyn/app-utils/visitor-upload'\nimport { notifyHostManagers } from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport { orderStatusUrl } from './order-status-token'\nimport {\n defaultQuotePayDeps,\n limitedQuoteLink,\n loadLinkedQuote,\n quoteLinkParams,\n sendQuoteLinkOutcome,\n type QuoteLinkOutcome,\n type QuotePayDeps,\n} from './quote-pay'\nimport { keepSentQuoteUploads, quoteUploadKeyRef, recordPendingQuoteUpload } from './quote-upload-keys'\nimport { quoteUploadCalls, type QuoteUploadCalls } from './quote-uploads'\n\n/*==========================================\n * THE CUSTOMER'S SIDE OF A PROOF (AGL-4096), on the business's site, behind\n * the quote's signed pay link like the page itself:\n *\n * GET /api/commerce/quote-proof?hostId=&q=&t=&file=<proofId>\n * → a proof from any revision, for a link to any version of this quote\n * (a picture inline, anything else as a download) | 404 | 429\n * POST /api/commerce/quote-upload { hostId, q, t, action: 'ticket', file: { name, contentType, size } }\n * → { ticket, upload: { url, fields }, file }\n * POST /api/commerce/quote-upload { hostId, q, t, action: 'finalize', ticket }\n * → { file: { id, name, contentType, size, uploadedAtMs } }\n * POST /api/commerce/quote-respond { hostId, q, t, v, action: 'approve', name }\n * { hostId, q, t, v, action: 'changes', comment, fileIds? }\n * + Idempotency-Key → 200 { view } | 409 { error, reason } | 410 { replaced } | 404 | 400 | 429\n *\n * Every route spends a per-address rate limit on the site BEFORE the token is\n * checked, answers a wrong token exactly as a missing quote, and (but for a\n * proof, which an earlier email still draws) answers a link to an older\n * version as replaced. The uploads are the shared visitor\n * upload (`@aglyn/tenant-data-admin/server/visitor-upload`), scoped to this\n * quote's artwork; the answer names the files by id and the server reads\n * them back from that scope, so nothing else can be attached.\n *\n * `v` is the edit of the quote the page showed, as Pay sends it: an answer to\n * proofs the customer has not seen is refused and the page is shown again.\n *\n * A file goes up before the answer does, so each one is recorded as pending\n * under its quote from its ticket on, and the answer that sends it takes it\n * off; one never sent is deleted a day later (`quote-upload-keys.ts`).\n *=========================================*/\n\n/** Proofs one address may load per site, per ten minutes: every thumbnail of a few visits. */\nexport const QUOTE_PROOF_LOADS_PER_WINDOW = 120\n/** Upload calls (tickets and finalizes) one address may make per site, per ten minutes, before the upload's own limits. */\nexport const QUOTE_UPLOAD_CALLS_PER_WINDOW = 80\n/** Answers one address may send per site, per ten minutes. */\nexport const QUOTE_RESPONSES_PER_WINDOW = 20\n\nexport interface QuoteProofDeps extends QuotePayDeps {\n uploads(): Promise<QuoteUploadCalls>\n notify(...args: Parameters<typeof notifyHostManagers>): Promise<void>\n}\n\nexport function defaultQuoteProofDeps(): QuoteProofDeps {\n return {\n ...defaultQuotePayDeps(),\n uploads: async () => quoteUploadCalls(),\n notify: (...args) => notifyHostManagers(...args),\n }\n}\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\nconst clientIp = (req: PluginApiRequest): string | null =>\n readClientIp(req.headers as never, { remoteAddress: req.socket?.remoteAddress })\n\nconst reasonRefusal = (status: number, reason: string, error: string): QuoteLinkOutcome => ({\n status,\n body: { error, reason },\n})\n\n/** What a proof route answers: a JSON outcome, or a file to stream. */\nexport type QuoteProofOutcome = QuoteLinkOutcome & { file?: { path: string; name: string; contentType: string } }\n\nconst PROOF_GONE: QuoteProofOutcome = { status: 404, body: { error: 'That proof is no longer on this quote.' } }\n\n/**\n * `GET /api/commerce/quote-proof`: one of the proofs in the quote's history\n * (AGL-4097). An email is a record the customer keeps, so the proof it draws\n * keeps showing after the business starts the next revision or replaces the\n * link: any link signed for this quote, an older version's too, is served the\n * current revision's proofs and every earlier revision's as its snapshot kept\n * them. A proof taken off its revision, another quote's file and a wrong token\n * are not found.\n */\nexport async function handleQuoteProof(deps: QuoteProofDeps, req: PluginApiRequest): Promise<QuoteProofOutcome> {\n if (req.method !== 'GET') return { status: 405, body: { error: 'Method not allowed' } }\n const query = (req.query ?? {}) as Record<string, unknown>\n const { hostId, quoteId, token, complete } = quoteLinkParams(query)\n const fileId = String(query['file'] ?? '').slice(0, 200)\n if (!complete || !fileId) return { status: 400, body: { error: 'This link is incomplete.' } }\n const limited = await limitedQuoteLink(deps, req, `commerce-quote-proof:${hostId}`, QUOTE_PROOF_LOADS_PER_WINDOW)\n if (limited) return limited\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { history: true })\n if ('outcome' in linked) return linked.outcome\n const quote = linked.loaded.order.quote\n // The earlier revisions are read only when the current one lacks the proof.\n let proof = CommerceModel.quoteProofInHistory(quote, [], fileId)\n if (!proof) {\n const listed = await linked.loaded.hostRef.collection('orders').doc(quoteId).collection('revisions').get()\n const snapshots = listed.docs.map((entry) => entry.data() as Partial<CommerceModel.QuoteRevisionSnapshot>)\n proof = CommerceModel.quoteProofInHistory(quote, snapshots, fileId)\n }\n // A proof is kept under this quote's own folder; a path anywhere else is never served.\n const folder = visitorUploadFolder({ hostId, purpose: CommerceModel.QUOTE_PROOF_PURPOSE, purposeId: quoteId })\n if (!proof?.path || !proof.path.startsWith(folder)) return PROOF_GONE\n return { status: 200, body: {}, file: { path: proof.path, name: proof.name, contentType: proof.contentType } }\n}\n\n/** `POST /api/commerce/quote-upload`: a ticket for one of the customer's files, or its finalize. */\nexport async function handleQuoteUpload(deps: QuoteProofDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome> {\n if (req.method !== 'POST') return { status: 405, body: { error: 'Method not allowed' } }\n const body = bodyOf(req)\n const { hostId, quoteId, token, complete } = quoteLinkParams(body)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n // A form a person fills never fills this; a bot that did learns nothing.\n const honeypot = body[VISITOR_UPLOAD_HONEYPOT_FIELD]\n if (typeof honeypot === 'string' && honeypot.trim()) return { status: 200, body: { received: true } }\n const limited = await limitedQuoteLink(deps, req, `commerce-quote-upload:${hostId}`, QUOTE_UPLOAD_CALLS_PER_WINDOW)\n if (limited) return limited\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token)\n if ('outcome' in linked) return linked.outcome\n const { order, storeName } = linked.loaded\n // Artwork rides an answer; a quote that cannot be answered takes none.\n const refused = CommerceModel.quoteRespondRefusal(order)\n if (refused) return reasonRefusal(409, refused, CommerceModel.quoteRespondRefusalMessage(refused, storeName))\n\n const scope = { hostId, purpose: CommerceModel.QUOTE_ARTWORK_PURPOSE, purposeId: quoteId }\n const caller = { ip: clientIp(req) ?? 'no-address' }\n const uploads = await deps.uploads()\n if (body['action'] === 'ticket') {\n const minted = await uploads.mint({ scope, request: body['file'], caller })\n if ('error' in minted) {\n return {\n status: minted.status,\n body: { error: minted.error, code: minted.code },\n ...(minted.retryAfterSeconds ? { headers: { 'Retry-After': String(minted.retryAfterSeconds) } } : {}),\n }\n }\n // Pending before a byte can arrive, so a file kept and never sent is always swept.\n await recordPendingQuoteUpload(deps.firestore(), { hostId, quoteId, fileId: minted.file.id, nowMs: deps.now() })\n return { status: 200, body: { ticket: minted.ticket, upload: minted.upload, file: minted.file } }\n }\n if (body['action'] === 'finalize') {\n const kept = await uploads.finalize({ scope, ticket: body['ticket'], caller })\n if ('error' in kept) return { status: kept.status, body: { error: kept.error, code: kept.code } }\n // Its day starts again from the latest file.\n await recordPendingQuoteUpload(deps.firestore(), { hostId, quoteId, fileId: kept.file.id, nowMs: deps.now() })\n return { status: 200, body: { file: visitorUploadFileView(kept.file) } }\n }\n return { status: 400, body: { error: 'Unknown action' } }\n}\n\nconst UPDATED_MESSAGE = 'This quote was updated since you opened it. Look it over again before you answer.'\n\n/**\n * The managers' notice of an answer (AGL-4096): who, which quote and\n * revision, what they said, and what to do next.\n *\n * It rides `content.order`, so whoever is told about orders (in the feed, by\n * email, by push) is told about the quotes that become them, and it names\n * itself as what it is rather than as that type: \"Proof approved\" or\n * \"Changes requested\" where the feed and the email's eyebrow would say \"New\n * order\", the customer and the quote as its heading, and \"View quote\" on the\n * email's button, which opens the quote's dialog on the Orders page.\n */\nfunction noticeOf(input: {\n hostId: string\n quoteId: string\n order: CommerceModel.HostOrder\n response: CommerceModel.QuoteCustomerResponse\n currency: string\n}) {\n const { hostId, quoteId, order, response } = input\n const quote = order.quote as CommerceModel.OrderQuote\n const number = CommerceModel.formatQuoteNumber(order, quoteId)\n const customer = quote.customer?.name || quote.customer?.company || quote.customer?.email || 'The customer'\n const revision = response.revision\n const files = response.files ?? []\n const approving = response.action === 'approve'\n const money = CommerceModel.formatOrderMoney(Number(order.totals?.totalCents ?? 0), input.currency)\n const total = quote.tax?.kind === 'at-payment' ? `${money} before tax` : money\n const filesSent = `${files.length} file${files.length === 1 ? '' : 's'}`\n const details = [\n { label: 'Quote', value: number },\n { label: 'Customer', value: [quote.customer?.name, quote.customer?.company, quote.customer?.email].filter(Boolean).join(', ') },\n { label: 'Revision', value: String(revision) },\n { label: 'Total', value: total },\n ...(approving\n ? [{ label: 'Approved as', value: response.name ?? '' }]\n : [\n { label: 'What to change', value: response.comment ?? '' },\n ...(files.length ? [{ label: 'Files sent', value: files.map((file) => file.name).join(', ') }] : []),\n ]),\n ]\n const email = String(quote.customer?.email ?? '').trim()\n return {\n payload: {\n type: 'content.order' as const,\n // Good news for an approval; a change request is work to read.\n level: approving ? ('success' as const) : ('info' as const),\n label: approving ? 'Proof approved' : 'Changes requested',\n actionLabel: 'View quote',\n title: approving\n ? `${customer} approved the proof for ${number} on {site}`\n : `${customer} asked for changes to ${number} on {site}`,\n body: approving\n ? (quote.requireProofApproval === true\n ? `Revision ${revision} is approved, so they can pay the quote now. It becomes an order when they do.`\n : `Revision ${revision} is approved. The quote becomes an order when they pay.`) +\n ' The approval, with the name, time and address it was given from, is on the quote.'\n : files.length\n ? `What they want changed on revision ${revision}, and the ${filesSent} they sent, are on the quote. ` +\n `Read them, then start revision ${revision + 1} with new proofs and send it.`\n : `What they want changed on revision ${revision} is on the quote. ` +\n `Read it, then start revision ${revision + 1} with new proofs and send it.`,\n link: `/${hostId}/products/orders?quote=${encodeURIComponent(quoteId)}`,\n },\n options: {\n emailDetails: details,\n ...(/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) ? { replyTo: email } : {}),\n },\n }\n}\n\n/** `POST /api/commerce/quote-respond`: the customer approves the proof or asks for changes. */\nexport async function handleQuoteRespond(deps: QuoteProofDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome> {\n if (req.method !== 'POST') return { status: 405, body: { error: 'Method not allowed' } }\n const body = bodyOf(req)\n const { hostId, quoteId, token, complete } = quoteLinkParams(body)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const honeypot = body[VISITOR_UPLOAD_HONEYPOT_FIELD]\n if (typeof honeypot === 'string' && honeypot.trim()) return { status: 200, body: { received: true } }\n const idempotencyKey = headerOf(req, 'idempotency-key').slice(0, 200)\n if (!idempotencyKey) return { status: 400, body: { error: 'An answer needs an Idempotency-Key header.' } }\n const limited = await limitedQuoteLink(deps, req, `commerce-quote-respond:${hostId}`, QUOTE_RESPONSES_PER_WINDOW)\n if (limited) return limited\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token)\n if ('outcome' in linked) return linked.outcome\n const { hostRef, host, order, storeName, store } = linked.loaded\n\n // Everything the customer can be refused is decided before the claim, so\n // none of it spends the attempt.\n const seen = Number(body['v'])\n const version = Number(order.quote?.updatedAtMs) || 0\n if (!Number.isFinite(seen) || seen !== version) return reasonRefusal(409, 'updated', UPDATED_MESSAGE)\n const parsed = CommerceModel.parseQuoteResponseInput(body)\n if ('error' in parsed) return { status: 400, body: { error: parsed.error } }\n const refused = CommerceModel.quoteRespondRefusal(order)\n if (refused) return reasonRefusal(409, refused, CommerceModel.quoteRespondRefusalMessage(refused, storeName))\n\n // The files are read back from this quote's artwork, by id: nothing the\n // browser says about a file is believed, and no other record's file can\n // be named.\n let files: CommerceModel.QuoteResponseFile[] = []\n if (parsed.input.action === 'changes' && parsed.input.fileIds.length) {\n const uploads = await deps.uploads()\n const scope = { hostId, purpose: CommerceModel.QUOTE_ARTWORK_PURPOSE, purposeId: quoteId }\n const read = await Promise.all(parsed.input.fileIds.map((id) => uploads.read(scope, id)))\n if (read.some((file) => !file)) {\n return { status: 400, body: { error: 'One of your files did not finish sending. Send it again.' } }\n }\n files = read.map((file) => ({\n id: file!.id,\n name: file!.name,\n contentType: file!.contentType,\n size: file!.size,\n path: file!.path,\n }))\n }\n\n const claimed = await claimAttempt(deps.firestore(), {\n kind: 'commerce-quote-respond',\n scopeId: `${hostId}:${quoteId}`,\n orgId: '',\n key: idempotencyKey,\n busyMessage: 'Your answer is already being sent',\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 now = deps.now()\n try {\n const ref = hostRef.collection('orders').doc(quoteId)\n const pendingRef = quoteUploadKeyRef(deps.firestore(), hostId, quoteId)\n const settled = await deps.firestore().runTransaction(\n async (transaction): Promise<{ outcome: QuoteLinkOutcome; order?: CommerceModel.HostOrder; response?: CommerceModel.QuoteCustomerResponse }> => {\n const snapshot = await transaction.get(ref)\n // The files this answer sends leave the pending record with it.\n const pending = files.length ? await transaction.get(pendingRef) : null\n const current = snapshot.exists ? (snapshot.data() as CommerceModel.HostOrder) : null\n if (!current || !CommerceModel.isQuote(current) || !current.quote) {\n return { outcome: { status: 404, body: { error: 'We could not find that quote. Check the link you were sent.' } } }\n }\n if (CommerceModel.quoteLinkVersion(current.quote) !== CommerceModel.quoteLinkVersion(order.quote)) {\n return {\n outcome: {\n status: 410,\n body: { replaced: true, error: `This quote was updated, and ${storeName || 'the business'} sent you a newer link.` },\n },\n }\n }\n if ((Number(current.quote.updatedAtMs) || 0) !== version) {\n return { outcome: reasonRefusal(409, 'updated', UPDATED_MESSAGE) }\n }\n const answered = CommerceModel.applyQuoteResponse(\n current,\n { ...parsed.input, ...(files.length ? { files } : {}) },\n { atMs: now, ip: clientIp(req), userAgent: headerOf(req, 'user-agent') || null },\n )\n if ('reason' in answered) {\n return {\n outcome: reasonRefusal(409, answered.reason, CommerceModel.quoteRespondRefusalMessage(answered.reason, storeName)),\n }\n }\n transaction.set(ref, answered.order)\n if (pending) keepSentQuoteUploads(transaction, pending, pendingRef, files.map((file) => file.id))\n return { outcome: { status: 200, body: {} }, order: answered.order, response: answered.response }\n },\n )\n if (!settled.order || !settled.response) {\n await claim.release()\n return settled.outcome\n }\n const view = CommerceModel.buildQuotePageView({\n order: settled.order,\n orderId: quoteId,\n storeName,\n currency: String(store.get('currency') ?? 'USD'),\n receiptUrl: CommerceModel.isUnpaidQuote(settled.order) ? null : orderStatusUrl(host, hostId, quoteId),\n })\n const outcome = { status: 200, body: { view } as Record<string, unknown> }\n await claim.record(200, outcome.body)\n const notice = noticeOf({\n hostId,\n quoteId,\n order: settled.order,\n response: settled.response,\n currency: String(store.get('currency') ?? 'USD'),\n })\n void deps.notify(hostId, notice.payload, notice.options)\n return outcome\n } catch (error) {\n console.error('quote respond failed', error)\n await claim.release()\n return { status: 500, body: { error: 'Your answer could not be sent. Try again.' } }\n }\n}\n\n/** `GET /api/commerce/quote-proof`. */\nexport const quoteProofHandler: PluginApiHandler = async (req, res) => {\n const deps = defaultQuoteProofDeps()\n try {\n const outcome = await handleQuoteProof(deps, req)\n if (!outcome.file) return sendQuoteLinkOutcome(res, outcome)\n const uploads = await deps.uploads()\n return await uploads.send(res as never, outcome.file)\n } catch (error) {\n console.error('quote proof failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'This proof could not be loaded. Try again.' } })\n }\n}\n\n/** `POST /api/commerce/quote-upload`. */\nexport const quoteUploadHandler: PluginApiHandler = async (req, res) => {\n try {\n return sendQuoteLinkOutcome(res, await handleQuoteUpload(defaultQuoteProofDeps(), req))\n } catch (error) {\n console.error('quote upload failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'The file could not be sent. Try again.' } })\n }\n}\n\n/** `POST /api/commerce/quote-respond`. */\nexport const quoteRespondHandler: PluginApiHandler = async (req, res) =>\n sendQuoteLinkOutcome(res, await handleQuoteRespond(defaultQuoteProofDeps(), req))\n"],"names":["claimAttempt","readClientIp","VISITOR_UPLOAD_HONEYPOT_FIELD","visitorUploadFileView","visitorUploadFolder","notifyHostManagers","CommerceModel","orderStatusUrl","defaultQuotePayDeps","limitedQuoteLink","loadLinkedQuote","quoteLinkParams","sendQuoteLinkOutcome","keepSentQuoteUploads","quoteUploadKeyRef","recordPendingQuoteUpload","quoteUploadCalls","QUOTE_PROOF_LOADS_PER_WINDOW","QUOTE_UPLOAD_CALLS_PER_WINDOW","QUOTE_RESPONSES_PER_WINDOW","defaultQuoteProofDeps","uploads","notify","args","bodyOf","req","raw","body","parsed","JSON","parse","headerOf","name","headers","value","toLowerCase","String","Array","isArray","trim","clientIp","remoteAddress","socket","reasonRefusal","status","reason","error","PROOF_GONE","handleQuoteProof","deps","query","method","hostId","quoteId","token","complete","fileId","slice","limited","linked","history","outcome","quote","loaded","order","proof","quoteProofInHistory","listed","hostRef","collection","doc","get","snapshots","docs","map","entry","data","folder","purpose","QUOTE_PROOF_PURPOSE","purposeId","path","startsWith","file","contentType","handleQuoteUpload","honeypot","received","storeName","refused","quoteRespondRefusal","quoteRespondRefusalMessage","scope","QUOTE_ARTWORK_PURPOSE","caller","ip","minted","mint","request","code","retryAfterSeconds","firestore","id","nowMs","now","ticket","upload","kept","finalize","UPDATED_MESSAGE","noticeOf","input","response","number","formatQuoteNumber","customer","company","email","revision","files","approving","action","money","formatOrderMoney","Number","totals","totalCents","currency","total","tax","kind","filesSent","length","details","label","filter","Boolean","join","comment","payload","type","level","actionLabel","title","requireProofApproval","link","encodeURIComponent","options","emailDetails","test","replyTo","handleQuoteRespond","idempotencyKey","host","store","seen","version","updatedAtMs","isFinite","parseQuoteResponseInput","fileIds","read","Promise","all","some","size","claimed","scopeId","orgId","key","busyMessage","replay","claim","ref","pendingRef","settled","runTransaction","transaction","snapshot","pending","current","exists","isQuote","quoteLinkVersion","replaced","answered","applyQuoteResponse","atMs","userAgent","set","release","view","buildQuotePageView","orderId","receiptUrl","isUnpaidQuote","record","notice","console","quoteProofHandler","res","send","quoteUploadHandler","quoteRespondHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,YAAY,QAAsD,sBAAqB;AAChG,SAASC,YAAY,QAAQ,oCAAmC;AAChE,SAASC,6BAA6B,EAAEC,qBAAqB,EAAEC,mBAAmB,QAAQ,wCAAuC;AACjI,SAASC,kBAAkB,QAAQ,2BAA0B;AAC7D,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,cAAc,QAAQ,0BAAsB;AACrD,SACEC,mBAAmB,EACnBC,gBAAgB,EAChBC,eAAe,EACfC,eAAe,EACfC,oBAAoB,QAGf,iBAAa;AACpB,SAASC,oBAAoB,EAAEC,iBAAiB,EAAEC,wBAAwB,QAAQ,yBAAqB;AACvG,SAASC,gBAAgB,QAA+B,qBAAiB;AAEzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA6B2C,GAE3C,4FAA4F,GAC5F,OAAO,MAAMC,+BAA+B,IAAG;AAC/C,yHAAyH,GACzH,OAAO,MAAMC,gCAAgC,GAAE;AAC/C,4DAA4D,GAC5D,OAAO,MAAMC,6BAA6B,GAAE;AAO5C,OAAO,SAASC;IACd,OAAO,aACFZ;QACHa,SAAS,UAAYL;QACrBM,QAAQ,CAAC,GAAGC,OAASlB,sBAAsBkB;;AAE/C;AAEA,SAASC,OAAOC,GAAqB;IACnC,MAAMC,MAAMD,IAAIE,IAAI;IACpB,IAAI,OAAOD,QAAQ,UAAU;QAC3B,IAAI;YACF,MAAME,SAASC,KAAKC,KAAK,CAACJ;YAC1B,OAAOE,UAAU,OAAOA,WAAW,WAAWA,SAAS,CAAC;QAC1D,EAAE,eAAM;YACN,OAAO,CAAC;QACV;IACF;IACA,OAAOF,OAAO,OAAOA,QAAQ,WAAYA,MAAkC,C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5J,QAAQ;YAAKjB,MAAM;gBAAEmB,OAAO;YAA6C;QAAE;IAChH;AACF,EAAC;AAED,uCAAuC,GACvC,OAAO,MAAM4J,qBAAuC,OAAOjL,KAAK+K;IAC9D,IAAI;QACF,OAAO5L,qBAAqB4L,KAAK,MAAMnH,kBAAkBjE,yBAAyBK;IACpF,EAAE,OAAOqB,OAAO;QACdwJ,QAAQxJ,KAAK,CAAC,uBAAuBA;QACrC,OAAOlC,qBAAqB4L,KAAK;YAAE5J,QAAQ;YAAKjB,MAAM;gBAAEmB,OAAO;YAAyC;QAAE;IAC5G;AACF,EAAC;AAED,wCAAwC,GACxC,OAAO,MAAM6J,sBAAwC,OAAOlL,KAAK+K,MAC/D5L,qBAAqB4L,KAAK,MAAMjD,mBAAmBnI,yBAAyBK,MAAK"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/quote-proofs.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 { claimAttempt, type PluginApiHandler, type PluginApiRequest } from '@aglyn/aglyn/server'\nimport { readClientIp } from '@aglyn/aglyn/app-utils/request-ip'\nimport { VISITOR_UPLOAD_HONEYPOT_FIELD, visitorUploadFileView, visitorUploadFolder } from '@aglyn/aglyn/app-utils/visitor-upload'\nimport { notifyHostManagers } from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport {\n defaultQuotePayDeps,\n limitedQuoteLink,\n loadLinkedQuote,\n payLinkPageView,\n quoteLinkParams,\n sendQuoteLinkOutcome,\n type QuoteLinkOutcome,\n type QuotePayDeps,\n} from './quote-pay'\nimport { keepSentQuoteUploads, quoteUploadKeyRef, recordPendingQuoteUpload } from './quote-upload-keys'\nimport { quoteUploadCalls, type QuoteUploadCalls } from './quote-uploads'\n\n/*==========================================\n * THE CUSTOMER'S SIDE OF A PROOF (AGL-4096), on the business's site, behind\n * the quote's signed pay link like the page itself:\n *\n * GET /api/commerce/quote-proof?hostId=&q=&t=&file=<proofId>\n * → a proof from any revision, for a link to any version of this quote\n * (a picture inline, anything else as a download) | 404 | 429\n * POST /api/commerce/quote-upload { hostId, q, t, action: 'ticket', file: { name, contentType, size } }\n * → { ticket, upload: { url, fields }, file }\n * POST /api/commerce/quote-upload { hostId, q, t, action: 'finalize', ticket }\n * → { file: { id, name, contentType, size, uploadedAtMs } }\n * POST /api/commerce/quote-respond { hostId, q, t, v, action: 'approve', name }\n * { hostId, q, t, v, action: 'changes', comment, fileIds? }\n * + Idempotency-Key → 200 { view } | 409 { error, reason } | 410 { replaced } | 404 | 400 | 429\n *\n * Every route spends a per-address rate limit on the site BEFORE the token is\n * checked, answers a wrong token exactly as a missing quote, and (but for a\n * proof, which an earlier email still draws) answers a link to an older\n * version as replaced. The uploads are the shared visitor\n * upload (`@aglyn/tenant-data-admin/server/visitor-upload`), scoped to this\n * quote's artwork; the answer names the files by id and the server reads\n * them back from that scope, so nothing else can be attached.\n *\n * `v` is the edit of the quote the page showed, as Pay sends it: an answer to\n * proofs the customer has not seen is refused and the page is shown again.\n *\n * A file goes up before the answer does, so each one is recorded as pending\n * under its quote from its ticket on, and the answer that sends it takes it\n * off; one never sent is deleted a day later (`quote-upload-keys.ts`).\n *=========================================*/\n\n/** Proofs one address may load per site, per ten minutes: every thumbnail of a few visits. */\nexport const QUOTE_PROOF_LOADS_PER_WINDOW = 120\n/** Upload calls (tickets and finalizes) one address may make per site, per ten minutes, before the upload's own limits. */\nexport const QUOTE_UPLOAD_CALLS_PER_WINDOW = 80\n/** Answers one address may send per site, per ten minutes. */\nexport const QUOTE_RESPONSES_PER_WINDOW = 20\n\nexport interface QuoteProofDeps extends QuotePayDeps {\n uploads(): Promise<QuoteUploadCalls>\n notify(...args: Parameters<typeof notifyHostManagers>): Promise<void>\n}\n\nexport function defaultQuoteProofDeps(): QuoteProofDeps {\n return {\n ...defaultQuotePayDeps(),\n uploads: async () => quoteUploadCalls(),\n notify: (...args) => notifyHostManagers(...args),\n }\n}\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\nconst clientIp = (req: PluginApiRequest): string | null =>\n readClientIp(req.headers as never, { remoteAddress: req.socket?.remoteAddress })\n\nconst reasonRefusal = (status: number, reason: string, error: string): QuoteLinkOutcome => ({\n status,\n body: { error, reason },\n})\n\n/** What a proof route answers: a JSON outcome, or a file to stream. */\nexport type QuoteProofOutcome = QuoteLinkOutcome & { file?: { path: string; name: string; contentType: string } }\n\nconst PROOF_GONE: QuoteProofOutcome = { status: 404, body: { error: 'That proof is no longer on this quote.' } }\n\n/**\n * `GET /api/commerce/quote-proof`: one of the proofs in the quote's history\n * (AGL-4097). An email is a record the customer keeps, so the proof it draws\n * keeps showing after the business starts the next revision or replaces the\n * link: any link signed for this quote, an older version's too, is served the\n * current revision's proofs and every earlier revision's as its snapshot kept\n * them. A proof taken off its revision, another quote's file and a wrong token\n * are not found.\n */\nexport async function handleQuoteProof(deps: QuoteProofDeps, req: PluginApiRequest): Promise<QuoteProofOutcome> {\n if (req.method !== 'GET') return { status: 405, body: { error: 'Method not allowed' } }\n const query = (req.query ?? {}) as Record<string, unknown>\n const { hostId, quoteId, token, complete } = quoteLinkParams(query)\n const fileId = String(query['file'] ?? '').slice(0, 200)\n if (!complete || !fileId) return { status: 400, body: { error: 'This link is incomplete.' } }\n const limited = await limitedQuoteLink(deps, req, `commerce-quote-proof:${hostId}`, QUOTE_PROOF_LOADS_PER_WINDOW)\n if (limited) return limited\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { history: true })\n if ('outcome' in linked) return linked.outcome\n const quote = linked.loaded.order.quote\n // The earlier revisions are read only when the current one lacks the proof.\n let proof = CommerceModel.quoteProofInHistory(quote, [], fileId)\n if (!proof) {\n const listed = await linked.loaded.hostRef.collection('orders').doc(quoteId).collection('revisions').get()\n const snapshots = listed.docs.map((entry) => entry.data() as Partial<CommerceModel.QuoteRevisionSnapshot>)\n proof = CommerceModel.quoteProofInHistory(quote, snapshots, fileId)\n }\n // A proof is kept under this quote's own folder; a path anywhere else is never served.\n const folder = visitorUploadFolder({ hostId, purpose: CommerceModel.QUOTE_PROOF_PURPOSE, purposeId: quoteId })\n if (!proof?.path || !proof.path.startsWith(folder)) return PROOF_GONE\n return { status: 200, body: {}, file: { path: proof.path, name: proof.name, contentType: proof.contentType } }\n}\n\n/** `POST /api/commerce/quote-upload`: a ticket for one of the customer's files, or its finalize. */\nexport async function handleQuoteUpload(deps: QuoteProofDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome> {\n if (req.method !== 'POST') return { status: 405, body: { error: 'Method not allowed' } }\n const body = bodyOf(req)\n const { hostId, quoteId, token, complete } = quoteLinkParams(body)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n // A form a person fills never fills this; a bot that did learns nothing.\n const honeypot = body[VISITOR_UPLOAD_HONEYPOT_FIELD]\n if (typeof honeypot === 'string' && honeypot.trim()) return { status: 200, body: { received: true } }\n const limited = await limitedQuoteLink(deps, req, `commerce-quote-upload:${hostId}`, QUOTE_UPLOAD_CALLS_PER_WINDOW)\n if (limited) return limited\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token)\n if ('outcome' in linked) return linked.outcome\n const { order, storeName } = linked.loaded\n // Artwork rides an answer; a quote that cannot be answered takes none.\n const refused = CommerceModel.quoteRespondRefusal(order)\n if (refused) return reasonRefusal(409, refused, CommerceModel.quoteRespondRefusalMessage(refused, storeName))\n\n const scope = { hostId, purpose: CommerceModel.QUOTE_ARTWORK_PURPOSE, purposeId: quoteId }\n const caller = { ip: clientIp(req) ?? 'no-address' }\n const uploads = await deps.uploads()\n if (body['action'] === 'ticket') {\n const minted = await uploads.mint({ scope, request: body['file'], caller })\n if ('error' in minted) {\n return {\n status: minted.status,\n body: { error: minted.error, code: minted.code },\n ...(minted.retryAfterSeconds ? { headers: { 'Retry-After': String(minted.retryAfterSeconds) } } : {}),\n }\n }\n // Pending before a byte can arrive, so a file kept and never sent is always swept.\n await recordPendingQuoteUpload(deps.firestore(), { hostId, quoteId, fileId: minted.file.id, nowMs: deps.now() })\n return { status: 200, body: { ticket: minted.ticket, upload: minted.upload, file: minted.file } }\n }\n if (body['action'] === 'finalize') {\n const kept = await uploads.finalize({ scope, ticket: body['ticket'], caller })\n if ('error' in kept) return { status: kept.status, body: { error: kept.error, code: kept.code } }\n // Its day starts again from the latest file.\n await recordPendingQuoteUpload(deps.firestore(), { hostId, quoteId, fileId: kept.file.id, nowMs: deps.now() })\n return { status: 200, body: { file: visitorUploadFileView(kept.file) } }\n }\n return { status: 400, body: { error: 'Unknown action' } }\n}\n\nconst UPDATED_MESSAGE = 'This quote was updated since you opened it. Look it over again before you answer.'\n\n/**\n * The managers' notice of an answer (AGL-4096): who, which quote and\n * revision, what they said, and what to do next.\n *\n * It rides `content.order`, so whoever is told about orders (in the feed, by\n * email, by push) is told about the quotes that become them, and it names\n * itself as what it is rather than as that type: \"Proof approved\" or\n * \"Changes requested\" where the feed and the email's eyebrow would say \"New\n * order\", the customer and the quote as its heading, and \"View quote\" on the\n * email's button, which opens the quote's dialog on the Orders page.\n */\nfunction noticeOf(input: {\n hostId: string\n quoteId: string\n order: CommerceModel.HostOrder\n response: CommerceModel.QuoteCustomerResponse\n currency: string\n}) {\n const { hostId, quoteId, order, response } = input\n const quote = order.quote as CommerceModel.OrderQuote\n const number = CommerceModel.formatQuoteNumber(order, quoteId)\n const customer = quote.customer?.name || quote.customer?.company || quote.customer?.email || 'The customer'\n const revision = response.revision\n const files = response.files ?? []\n const approving = response.action === 'approve'\n const money = CommerceModel.formatOrderMoney(Number(order.totals?.totalCents ?? 0), input.currency)\n const total = quote.tax?.kind === 'at-payment' ? `${money} before tax` : money\n const filesSent = `${files.length} file${files.length === 1 ? '' : 's'}`\n const details = [\n { label: 'Quote', value: number },\n { label: 'Customer', value: [quote.customer?.name, quote.customer?.company, quote.customer?.email].filter(Boolean).join(', ') },\n { label: 'Revision', value: String(revision) },\n { label: 'Total', value: total },\n ...(approving\n ? [{ label: 'Approved as', value: response.name ?? '' }]\n : [\n { label: 'What to change', value: response.comment ?? '' },\n ...(files.length ? [{ label: 'Files sent', value: files.map((file) => file.name).join(', ') }] : []),\n ]),\n ]\n const email = String(quote.customer?.email ?? '').trim()\n return {\n payload: {\n type: 'content.order' as const,\n // Good news for an approval; a change request is work to read.\n level: approving ? ('success' as const) : ('info' as const),\n label: approving ? 'Proof approved' : 'Changes requested',\n actionLabel: 'View quote',\n title: approving\n ? `${customer} approved the proof for ${number} on {site}`\n : `${customer} asked for changes to ${number} on {site}`,\n body: approving\n ? (quote.requireProofApproval === true\n ? `Revision ${revision} is approved, so they can pay the quote now. It becomes an order when they do.`\n : `Revision ${revision} is approved. The quote becomes an order when they pay.`) +\n ' The approval, with the name, time and address it was given from, is on the quote.'\n : files.length\n ? `What they want changed on revision ${revision}, and the ${filesSent} they sent, are on the quote. ` +\n `Read them, then start revision ${revision + 1} with new proofs and send it.`\n : `What they want changed on revision ${revision} is on the quote. ` +\n `Read it, then start revision ${revision + 1} with new proofs and send it.`,\n link: `/${hostId}/products/orders?quote=${encodeURIComponent(quoteId)}`,\n },\n options: {\n emailDetails: details,\n ...(/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) ? { replyTo: email } : {}),\n },\n }\n}\n\n/** `POST /api/commerce/quote-respond`: the customer approves the proof or asks for changes. */\nexport async function handleQuoteRespond(deps: QuoteProofDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome> {\n if (req.method !== 'POST') return { status: 405, body: { error: 'Method not allowed' } }\n const body = bodyOf(req)\n const { hostId, quoteId, token, complete } = quoteLinkParams(body)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const honeypot = body[VISITOR_UPLOAD_HONEYPOT_FIELD]\n if (typeof honeypot === 'string' && honeypot.trim()) return { status: 200, body: { received: true } }\n const idempotencyKey = headerOf(req, 'idempotency-key').slice(0, 200)\n if (!idempotencyKey) return { status: 400, body: { error: 'An answer needs an Idempotency-Key header.' } }\n const limited = await limitedQuoteLink(deps, req, `commerce-quote-respond:${hostId}`, QUOTE_RESPONSES_PER_WINDOW)\n if (limited) return limited\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token)\n if ('outcome' in linked) return linked.outcome\n const { hostRef, host, order, storeName, store } = linked.loaded\n\n // Everything the customer can be refused is decided before the claim, so\n // none of it spends the attempt.\n const seen = Number(body['v'])\n const version = Number(order.quote?.updatedAtMs) || 0\n if (!Number.isFinite(seen) || seen !== version) return reasonRefusal(409, 'updated', UPDATED_MESSAGE)\n const parsed = CommerceModel.parseQuoteResponseInput(body)\n if ('error' in parsed) return { status: 400, body: { error: parsed.error } }\n const refused = CommerceModel.quoteRespondRefusal(order)\n if (refused) return reasonRefusal(409, refused, CommerceModel.quoteRespondRefusalMessage(refused, storeName))\n\n // The files are read back from this quote's artwork, by id: nothing the\n // browser says about a file is believed, and no other record's file can\n // be named.\n let files: CommerceModel.QuoteResponseFile[] = []\n if (parsed.input.action === 'changes' && parsed.input.fileIds.length) {\n const uploads = await deps.uploads()\n const scope = { hostId, purpose: CommerceModel.QUOTE_ARTWORK_PURPOSE, purposeId: quoteId }\n const read = await Promise.all(parsed.input.fileIds.map((id) => uploads.read(scope, id)))\n if (read.some((file) => !file)) {\n return { status: 400, body: { error: 'One of your files did not finish sending. Send it again.' } }\n }\n files = read.map((file) => ({\n id: file!.id,\n name: file!.name,\n contentType: file!.contentType,\n size: file!.size,\n path: file!.path,\n }))\n }\n\n const claimed = await claimAttempt(deps.firestore(), {\n kind: 'commerce-quote-respond',\n scopeId: `${hostId}:${quoteId}`,\n orgId: '',\n key: idempotencyKey,\n busyMessage: 'Your answer is already being sent',\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 now = deps.now()\n try {\n const ref = hostRef.collection('orders').doc(quoteId)\n const pendingRef = quoteUploadKeyRef(deps.firestore(), hostId, quoteId)\n const settled = await deps.firestore().runTransaction(\n async (transaction): Promise<{ outcome: QuoteLinkOutcome; order?: CommerceModel.HostOrder; response?: CommerceModel.QuoteCustomerResponse }> => {\n const snapshot = await transaction.get(ref)\n // The files this answer sends leave the pending record with it.\n const pending = files.length ? await transaction.get(pendingRef) : null\n const current = snapshot.exists ? (snapshot.data() as CommerceModel.HostOrder) : null\n if (!current || !CommerceModel.isQuote(current) || !current.quote) {\n return { outcome: { status: 404, body: { error: 'We could not find that quote. Check the link you were sent.' } } }\n }\n if (CommerceModel.quoteLinkVersion(current.quote) !== CommerceModel.quoteLinkVersion(order.quote)) {\n return {\n outcome: {\n status: 410,\n body: { replaced: true, error: `This quote was updated, and ${storeName || 'the business'} sent you a newer link.` },\n },\n }\n }\n if ((Number(current.quote.updatedAtMs) || 0) !== version) {\n return { outcome: reasonRefusal(409, 'updated', UPDATED_MESSAGE) }\n }\n const answered = CommerceModel.applyQuoteResponse(\n current,\n { ...parsed.input, ...(files.length ? { files } : {}) },\n { atMs: now, ip: clientIp(req), userAgent: headerOf(req, 'user-agent') || null },\n )\n if ('reason' in answered) {\n return {\n outcome: reasonRefusal(409, answered.reason, CommerceModel.quoteRespondRefusalMessage(answered.reason, storeName)),\n }\n }\n transaction.set(ref, answered.order)\n if (pending) keepSentQuoteUploads(transaction, pending, pendingRef, files.map((file) => file.id))\n return { outcome: { status: 200, body: {} }, order: answered.order, response: answered.response }\n },\n )\n if (!settled.order || !settled.response) {\n await claim.release()\n return settled.outcome\n }\n // The page's own view, so an approval brings Pay back only where Pay would work.\n const view = await payLinkPageView(deps, {\n hostId,\n orderId: quoteId,\n loaded: { host, order: settled.order, storeName, store, kind: 'quote' },\n })\n const outcome = { status: 200, body: { view } as Record<string, unknown> }\n await claim.record(200, outcome.body)\n const notice = noticeOf({\n hostId,\n quoteId,\n order: settled.order,\n response: settled.response,\n currency: String(store.get('currency') ?? 'USD'),\n })\n void deps.notify(hostId, notice.payload, notice.options)\n return outcome\n } catch (error) {\n console.error('quote respond failed', error)\n await claim.release()\n return { status: 500, body: { error: 'Your answer could not be sent. Try again.' } }\n }\n}\n\n/** `GET /api/commerce/quote-proof`. */\nexport const quoteProofHandler: PluginApiHandler = async (req, res) => {\n const deps = defaultQuoteProofDeps()\n try {\n const outcome = await handleQuoteProof(deps, req)\n if (!outcome.file) return sendQuoteLinkOutcome(res, outcome)\n const uploads = await deps.uploads()\n return await uploads.send(res as never, outcome.file)\n } catch (error) {\n console.error('quote proof failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'This proof could not be loaded. Try again.' } })\n }\n}\n\n/** `POST /api/commerce/quote-upload`. */\nexport const quoteUploadHandler: PluginApiHandler = async (req, res) => {\n try {\n return sendQuoteLinkOutcome(res, await handleQuoteUpload(defaultQuoteProofDeps(), req))\n } catch (error) {\n console.error('quote upload failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'The file could not be sent. Try again.' } })\n }\n}\n\n/** `POST /api/commerce/quote-respond`. */\nexport const quoteRespondHandler: PluginApiHandler = async (req, res) =>\n sendQuoteLinkOutcome(res, await handleQuoteRespond(defaultQuoteProofDeps(), req))\n"],"names":["claimAttempt","readClientIp","VISITOR_UPLOAD_HONEYPOT_FIELD","visitorUploadFileView","visitorUploadFolder","notifyHostManagers","CommerceModel","defaultQuotePayDeps","limitedQuoteLink","loadLinkedQuote","payLinkPageView","quoteLinkParams","sendQuoteLinkOutcome","keepSentQuoteUploads","quoteUploadKeyRef","recordPendingQuoteUpload","quoteUploadCalls","QUOTE_PROOF_LOADS_PER_WINDOW","QUOTE_UPLOAD_CALLS_PER_WINDOW","QUOTE_RESPONSES_PER_WINDOW","defaultQuoteProofDeps","uploads","notify","args","bodyOf","req","raw","body","parsed","JSON","parse","headerOf","name","headers","value","toLowerCase","String","Array","isArray","trim","clientIp","remoteAddress","socket","reasonRefusal","status","reason","error","PROOF_GONE","handleQuoteProof","deps","query","method","hostId","quoteId","token","complete","fileId","slice","limited","linked","history","outcome","quote","loaded","order","proof","quoteProofInHistory","listed","hostRef","collection","doc","get","snapshots","docs","map","entry","data","folder","purpose","QUOTE_PROOF_PURPOSE","purposeId","path","startsWith","file","contentType","handleQuoteUpload","honeypot","received","storeName","refused","quoteRespondRefusal","quoteRespondRefusalMessage","scope","QUOTE_ARTWORK_PURPOSE","caller","ip","minted","mint","request","code","retryAfterSeconds","firestore","id","nowMs","now","ticket","upload","kept","finalize","UPDATED_MESSAGE","noticeOf","input","response","number","formatQuoteNumber","customer","company","email","revision","files","approving","action","money","formatOrderMoney","Number","totals","totalCents","currency","total","tax","kind","filesSent","length","details","label","filter","Boolean","join","comment","payload","type","level","actionLabel","title","requireProofApproval","link","encodeURIComponent","options","emailDetails","test","replyTo","handleQuoteRespond","idempotencyKey","host","store","seen","version","updatedAtMs","isFinite","parseQuoteResponseInput","fileIds","read","Promise","all","some","size","claimed","scopeId","orgId","key","busyMessage","replay","claim","ref","pendingRef","settled","runTransaction","transaction","snapshot","pending","current","exists","isQuote","quoteLinkVersion","replaced","answered","applyQuoteResponse","atMs","userAgent","set","release","view","orderId","record","notice","console","quoteProofHandler","res","send","quoteUploadHandler","quoteRespondHandler"],"mappings":";AA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YAAEzJ,QAAQ;YAAKjB,MAAM;gBAAEmB,OAAO;YAAyC;QAAE;IAC5G;AACF,EAAC;AAED,wCAAwC,GACxC,OAAO,MAAM0J,sBAAwC,OAAO/K,KAAK4K,MAC/DzL,qBAAqByL,KAAK,MAAM9C,mBAAmBnI,yBAAyBK,MAAK"}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
-
import { type HostOrder } from '../model';
|
|
17
|
+
import { type HostOrder, type PayLinkStore } from '../model';
|
|
18
18
|
/** The catalog key the invoice email is sent and designed under. */
|
|
19
19
|
export declare const INVOICE_EMAIL_KEY = "order-invoice";
|
|
20
20
|
export interface InvoiceEmailContentInput {
|
|
@@ -30,6 +30,8 @@ export interface InvoiceEmailContentInput {
|
|
|
30
30
|
payUrl: string | null;
|
|
31
31
|
/** The site's time zone, for the dates. */
|
|
32
32
|
timeZone?: string | null;
|
|
33
|
+
/** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */
|
|
34
|
+
store?: PayLinkStore | null;
|
|
33
35
|
}
|
|
34
36
|
export interface InvoiceEmailContent {
|
|
35
37
|
/** The catalog email's merge tokens. */
|
|
@@ -74,7 +74,7 @@ function capitalize(value) {
|
|
|
74
74
|
const dateMs = orderCreatedAtMs(order) || Number((_ref = quoteSection == null ? void 0 : quoteSection.updatedAtMs) != null ? _ref : quoteSection == null ? void 0 : quoteSection.createdAtMs) || 0;
|
|
75
75
|
const date = longDate(dateMs, timeZone);
|
|
76
76
|
// What it shows: what the link charges while it is unpaid, the order's own figures once paid.
|
|
77
|
-
const charge = paid ? null : invoiceCheckoutCharge(order, orderId);
|
|
77
|
+
const charge = paid ? null : invoiceCheckoutCharge(order, orderId, input.store);
|
|
78
78
|
const totalCents = charge ? charge.totalCents : Math.max(0, Math.round(Number((_ref1 = (_order_totals = order.totals) == null ? void 0 : _order_totals.totalCents) != null ? _ref1 : 0)));
|
|
79
79
|
const money = formatOrderMoney(totalCents, input.currency);
|
|
80
80
|
const later = charge ? laterParts(charge.shippingOptions.length > 0, charge.taxAtPayment) : '';
|