@aglyn/plugins-commerce 1.10.0 → 1.12.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/host-quotes-card.component.js +20 -11
- package/src/lib/components/console/host-quotes-card.component.js.map +1 -1
- 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/pos-kiosk/kiosk-menu.d.ts +10 -3
- package/src/lib/components/console/pos-kiosk/kiosk-menu.js +29 -8
- package/src/lib/components/console/pos-kiosk/kiosk-menu.js.map +1 -1
- package/src/lib/components/console/pos-kiosk/pos-kiosk-api.d.ts +2 -0
- package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js +7 -0
- package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js.map +1 -1
- package/src/lib/components/console/pos-kiosk-page.component.d.ts +2 -0
- package/src/lib/components/console/pos-kiosk-page.component.js +54 -3
- package/src/lib/components/console/pos-kiosk-page.component.js.map +1 -1
- package/src/lib/components/console/product-add-ons-fields.component.d.ts +0 -2
- package/src/lib/components/console/product-add-ons-fields.component.js +1 -6
- package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
- package/src/lib/components/console/quote-editor-dialog.component.d.ts +2 -0
- package/src/lib/components/console/quote-editor-dialog.component.js +35 -27
- 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/product-detail.js +1 -1
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/product-grid.js +5 -3
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/product-reviews.js +17 -12
- package/src/lib/components/product-reviews.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/components/related-products.js +2 -1
- package/src/lib/components/related-products.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-kiosk-search.d.ts +22 -0
- package/src/lib/model/commerce-kiosk-search.js +32 -0
- package/src/lib/model/commerce-kiosk-search.js.map +1 -0
- package/src/lib/model/commerce-pos-kiosk.d.ts +7 -1
- package/src/lib/model/commerce-pos-kiosk.js +1 -1
- package/src/lib/model/commerce-pos-kiosk.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/model/product-modifiers.d.ts +4 -0
- package/src/lib/model/product-modifiers.js +5 -0
- package/src/lib/model/product-modifiers.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/pos-kiosk.js +70 -15
- package/src/lib/server/pos-kiosk.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 +20 -11
- package/src/lib/server/quote-proofs.js.map +1 -1
- package/src/lib/server/site-page-enricher.js +5 -1
- package/src/lib/server/site-page-enricher.js.map +1 -1
- package/src/lib/testing/fake-firestore.js +34 -5
- package/src/lib/testing/fake-firestore.js.map +1 -1
- package/src/lib/transfer/product-register-cells.d.ts +75 -0
- package/src/lib/transfer/product-register-cells.js +487 -0
- package/src/lib/transfer/product-register-cells.js.map +1 -0
- package/src/lib/transfer/product-transfer.d.ts +12 -0
- package/src/lib/transfer/product-transfer.js +174 -10
- package/src/lib/transfer/product-transfer.js.map +1 -1
- package/src/lib/transfer/products.server.js +24 -9
- package/src/lib/transfer/products.server.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/model/commerce-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 { visitorUploadIsInline } from '@aglyn/aglyn/app-utils/visitor-upload'\nimport type { ProductType } from './commerce'\nimport {\n appendOrderEvent,\n formatOrderNumber,\n type HostOrder,\n type OrderAddress,\n type OrderLineItem,\n type OrderStatus,\n} from './commerce-orders'\nimport {\n computeQuoteTotals,\n describeQuoteTax,\n formatQuoteNumber,\n quoteLineAmounts,\n quotePaymentBlockedByApproval,\n type OrderQuote,\n type QuoteDiscount,\n type QuoteTaxBasis,\n type QuoteUnmatchedPayment,\n} from './commerce-quotes'\nimport { currentQuoteProofs, latestQuoteResponse, quoteRespondRefusal } from './commerce-quote-proofs'\nimport type { StorefrontTaxMode } from './commerce-tax-decision'\nimport { engineLineTaxPercentages } from './commerce-tax-engine'\nimport { withOrderListFields, type OrderListFields } from './order-list-fields'\n\n/*==========================================\n * PAYING A QUOTE (AGL-4094).\n *\n * The customer opens the quote on the business's own site from a signed pay\n * link, sees it, and pays it. Everything here is pure, so the page's view,\n * the pay route's charge and the webhook's paid order all come from one\n * reading of the stored quote, and none of them from anything the browser\n * sends:\n *\n * - {@link buildQuotePageView}: the ONE projection of a quote that leaves the\n * server for a visitor holding the link, allow-listed field by field.\n * - {@link quoteCheckoutCharge}: what a Checkout Session charges, priced from\n * the stored lines, discount, shipping and tax basis.\n * - {@link quotePayRefusal}: why a quote cannot be paid now, if it cannot.\n * - {@link quotePaymentDisposition} and {@link paidQuoteOrder}: what a\n * completed payment does to the quote, and the order it becomes.\n *\n * The customer side has no expiry and no open or closed states: a quote and\n * its link stay until the quote is paid or the business replaces the link.\n *=========================================*/\n\n/** Stripe's smallest card charge; a quote that totals less cannot be paid by card. */\nexport const QUOTE_MIN_CHARGE_CENTS = 50\n\n/** The pay link version a quote is on; absent reads as the first. */\nexport function quoteLinkVersion(quote: Pick<OrderQuote, 'linkVersion'> | null | undefined): number {\n const version = Math.floor(Number(quote?.linkVersion))\n return Number.isFinite(version) && version >= 1 ? version : 1\n}\n\n/**\n * The pay link version any order is on (AGL-4099). A quote keeps its version\n * where slice 2 put it, `quote.linkVersion`, so every link already sent keeps\n * verifying; any other order keeps it as `payLink.version`. Absent reads as\n * the first either way.\n */\nexport function orderPayLinkVersion(order: Partial<Pick<HostOrder, 'quote' | 'payLink'>> | null | undefined): number {\n if (order?.quote) return quoteLinkVersion(order.quote)\n const version = Math.floor(Number(order?.payLink?.version))\n return Number.isFinite(version) && version >= 1 ? version : 1\n}\n\n/** Payments the order's pay link could not take: a quote's on the quote, any other order's on `payLink`. */\nexport function orderPayLinkUnmatched(\n order: Partial<Pick<HostOrder, 'quote' | 'payLink'>> | null | undefined,\n): QuoteUnmatchedPayment[] {\n const list = order?.quote ? order.quote.unmatchedPayments : order?.payLink?.unmatchedPayments\n return Array.isArray(list) ? list.filter((entry) => entry && typeof entry === 'object') : []\n}\n\n/*==========================================\n * THE CUSTOMER'S PAGE\n *=========================================*/\n\n/** An address as the quote page prints it: no phone. */\nexport interface QuotePageAddress {\n name: string | null\n line1: string | null\n line2: string | null\n city: string | null\n state: string | null\n postalCode: string | null\n country: string | null\n}\n\nexport interface QuotePageLine {\n name: string\n /** The option and add-ons chosen, as order lines print them. */\n variantLabel: string | null\n description: string | null\n sku: string | null\n quantity: number\n unitAmountCents: number\n /** What the line charges: 0 for an included line. */\n amountCents: number\n /** Included at no charge. */\n included: boolean\n}\n\n/** Where the quote stands, as its customer sees it. */\nexport type QuotePageStatus = 'unpaid' | 'paid' | 'canceled' | 'refunded'\n\n/** A proof as the quote page lists it: no storage path, nothing about who attached it. */\nexport interface QuotePageProof {\n id: string\n name: string\n contentType: string\n size: number\n /** Shown in the page as a picture; everything else is a download. */\n inline: boolean\n}\n\n/** The customer's latest answer to the revision the page shows. */\nexport interface QuotePageResponse {\n action: 'approve' | 'changes'\n atMs: number\n /** With an approval: the name it was given under. */\n name: string | null\n comment: string | null\n /** How many files came with it. */\n files: number\n}\n\n/**\n * What the quote page shows. Allow-listed, never spread: the order document\n * carries the customer's email and phone, Stripe ids, the business's own\n * timeline and who wrote the quote, none of which a forwarded link may show.\n * New fields are added here deliberately, or not at all.\n */\nexport interface QuotePageView {\n state: 'quote'\n /**\n * What the page shows (AGL-4099): a quote, or an invoice for an order the\n * business sent one for. An invoice has no proofs and no approval, and the\n * page says \"invoice\" where a quote's says \"quote\".\n */\n kind: 'quote' | 'invoice'\n storeName: string\n /** `Quote #1042`, or `Invoice #1042`. */\n number: string\n /** When the quote was last written, which is the date it carries. */\n dateMs: number | null\n /**\n * The edit of the quote this view shows. Pay sends it back, and a quote\n * changed since is refused, so nobody pays for a version they have not seen.\n */\n version: number\n currency: string\n customerName: string | null\n company: string | null\n billTo: QuotePageAddress | null\n shipTo: QuotePageAddress | null\n lines: QuotePageLine[]\n totals: {\n itemsCents: number\n discountCents: number\n shippingCents: number\n taxCents: number\n totalCents: number\n }\n /** `10% off`, or null for an amount or no discount. */\n discountLabel: string | null\n /** The tax line's label, or `Tax is added at payment`. */\n taxLabel: string\n /** Stripe Tax works the tax out when the customer pays; `taxCents` is 0 until then. */\n taxAtPayment: boolean\n /**\n * The customer picks a shipping rate when they pay (an invoiced draft\n * order, AGL-4099); `shippingCents` is 0 until then. A quote's shipping is\n * priced on it, so this is false for every quote.\n */\n shippingAtPayment: boolean\n notes: string | null\n terms: string | null\n status: QuotePageStatus\n statusLabel: string\n paidAtMs: number | null\n /** The order's status page, once paid. */\n receiptUrl: string | null\n /** The business asks the customer to approve the proof before paying. */\n approvalRequired: boolean\n /** A Pay button belongs on the page. */\n payable: boolean\n /** The revision the page shows (AGL-4096). */\n revision: number\n /** That revision's proofs. */\n proofs: QuotePageProof[]\n /** The customer's latest answer to it, if any. */\n response: QuotePageResponse | null\n /** Approve and Request changes belong on the page. */\n respondable: boolean\n}\n\n/** What a signed link for an older version of the quote opens: nothing of the quote. */\nexport interface QuotePageReplacedView {\n state: 'replaced'\n storeName: string\n}\n\nconst text = (value: unknown): string | null => {\n const trimmed = typeof value === 'string' ? value.trim() : ''\n return trimmed ? trimmed : null\n}\n\nconst cents = (value: unknown): number => {\n const number = Math.round(Number(value))\n return Number.isFinite(number) ? number : 0\n}\n\n/** An address as the pay link's page prints it, or null when it says nothing. */\nexport function quotePageAddress(address: OrderAddress | null | undefined): QuotePageAddress | null {\n if (!address) return null\n const view: QuotePageAddress = {\n name: text(address.name),\n line1: text(address.line1),\n line2: text(address.line2),\n city: text(address.city),\n state: text(address.state),\n postalCode: text(address.postalCode),\n country: text(address.country),\n }\n return Object.values(view).some(Boolean) ? view : null\n}\n\n/** Where an order stands as the pay link's page says it. */\nexport function quotePageStatus(status: OrderStatus | string | undefined): { status: QuotePageStatus; label: string } {\n if (status === 'pending') return { status: 'unpaid', label: 'Unpaid' }\n if (status === 'cancelled') return { status: 'canceled', label: 'Canceled' }\n if (status === 'refunded') return { status: 'refunded', label: 'Refunded' }\n return { status: 'paid', label: 'Paid' }\n}\n\nfunction discountLabel(discount: QuoteDiscount | null | undefined): string | null {\n if (discount?.kind !== 'percent' || !(Number(discount.pct) > 0)) return null\n return `${Number(discount.pct)}% off`\n}\n\n/** When the quote was paid: its stamp, else the timeline's `paid` event. */\nfunction paidAt(order: Pick<HostOrder, 'status' | 'quote' | 'timeline'>): number | null {\n if (order.status === 'pending') return null\n const stamped = Number(order.quote?.paidAtMs)\n if (Number.isFinite(stamped) && stamped > 0) return stamped\n const event = (order.timeline ?? []).find((entry) => entry?.event === 'paid')\n return event ? Number(event.atMs) || null : null\n}\n\n/**\n * The quote page's view of an order document on the `quote` channel. Totals\n * are the stored lines' through {@link computeQuoteTotals} until the quote is\n * paid, and the paid order's own totals (what Stripe charged) after.\n */\nexport function buildQuotePageView(input: {\n order: Pick<HostOrder, 'number' | 'status' | 'lineItems' | 'totals' | 'quote' | 'timeline'>\n orderId: string\n storeName: string\n currency: string\n /** The order's status page, for a paid quote. */\n receiptUrl?: string | null\n}): QuotePageView {\n const { order } = input\n const quote = order.quote\n const lines = order.lineItems ?? []\n const status = quotePageStatus(order.status)\n const unpaid = status.status === 'unpaid'\n const charge = quoteCheckoutCharge(order, input.orderId)\n const stored = order.totals\n const totals = unpaid || !stored\n ? {\n itemsCents: charge.itemsCents,\n discountCents: charge.discountCents,\n shippingCents: charge.shippingCents,\n taxCents: charge.taxCents,\n totalCents: charge.totalCents,\n }\n : {\n itemsCents: cents(stored.itemsCents),\n discountCents: cents(stored.discountCents),\n shippingCents: cents(stored.shippingCents),\n taxCents: cents(stored.taxCents),\n totalCents: cents(stored.totalCents),\n }\n const approvalRequired = unpaid && quotePaymentBlockedByApproval(quote)\n const taxAtPayment = unpaid && quote?.tax?.kind === 'at-payment'\n return {\n state: 'quote',\n kind: 'quote',\n storeName: input.storeName,\n number: formatQuoteNumber(order, input.orderId),\n dateMs: Number(quote?.updatedAtMs ?? quote?.createdAtMs) || null,\n version: Number(quote?.updatedAtMs) || 0,\n currency: input.currency || 'USD',\n customerName: text(quote?.customer?.name) ?? text(quote?.customer?.company),\n company: text(quote?.customer?.name) ? text(quote?.customer?.company) : null,\n billTo: quotePageAddress(quote?.billTo),\n shipTo: quotePageAddress(quote?.shipTo),\n lines: quotePageLines(lines),\n totals,\n discountLabel: discountLabel(quote?.discount),\n // Once paid, the tax is what was charged: Stripe's figure under Stripe Tax.\n taxLabel: unpaid || quote?.tax?.kind !== 'at-payment' ? describeQuoteTax(quote?.tax) : 'Tax',\n taxAtPayment,\n shippingAtPayment: false,\n notes: text(quote?.notes),\n terms: text(quote?.terms),\n status: status.status,\n statusLabel: status.label,\n paidAtMs: paidAt(order),\n receiptUrl: unpaid ? null : (input.receiptUrl ?? null),\n approvalRequired,\n payable: unpaid && !approvalRequired && quotePayRefusal(order, input.orderId) === null,\n revision: Math.max(1, Number(quote?.revision ?? 1) || 1),\n proofs: currentQuoteProofs(quote).map((proof) => ({\n id: String(proof.id),\n name: String(proof.name ?? 'Proof'),\n contentType: String(proof.contentType ?? ''),\n size: Math.max(0, cents(proof.size)),\n inline: visitorUploadIsInline(String(proof.contentType ?? '')),\n })),\n response: pageResponse(quote),\n // The page is only ever a quote's, whatever the caller picked off the order.\n respondable: quoteRespondRefusal({ channel: 'quote', status: order.status, quote }) === null,\n }\n}\n\n/** Order lines as the pay link's page lists them: what each charges, nothing about stock or cost. */\nexport function quotePageLines(lines: readonly OrderLineItem[]): QuotePageLine[] {\n return lines.map((line) => {\n const included = line.included === true\n const quantity = Math.max(0, cents(line.quantity))\n const unitAmountCents = included ? 0 : Math.max(0, cents(line.unitAmountCents))\n return {\n name: String(line.name ?? ''),\n variantLabel: text(line.variantLabel),\n description: text(line.description),\n sku: text(line.sku),\n quantity,\n unitAmountCents,\n amountCents: unitAmountCents * quantity,\n included,\n }\n })\n}\n\n/** The latest answer, as the page may show it back to the link's holder: never the address or browser. */\nfunction pageResponse(quote: OrderQuote | null | undefined): QuotePageResponse | null {\n const latest = latestQuoteResponse(quote)\n if (!latest) return null\n return {\n action: latest.action === 'approve' ? 'approve' : 'changes',\n atMs: Number(latest.atMs) || 0,\n name: latest.action === 'approve' ? text(latest.name) : null,\n comment: latest.action === 'changes' ? text(latest.comment) : null,\n files: latest.files?.length ?? 0,\n }\n}\n\n/*==========================================\n * WHAT A PAYMENT CHARGES\n *=========================================*/\n\n/** One line of a quote's Checkout Session. */\nexport interface QuoteCheckoutLine {\n name: string\n /** The quote's lines this one charges for, as the hosted page lists them. */\n description: string\n amountCents: number\n /** False for tax-exempt products: no rate is applied and Stripe Tax is told it is nontaxable. */\n taxable: boolean\n}\n\n/** What a quote's Checkout Session charges, priced from the stored quote alone. */\nexport interface QuoteCheckoutCharge {\n /** The goods grouped by whether they are taxed, so one rate taxes exactly the quote's taxable amount. */\n lines: QuoteCheckoutLine[]\n itemsCents: number\n discountCents: number\n /** The goods after the discount: what the business is paid for them. */\n goodsCents: number\n taxableCents: number\n shippingCents: number\n /** The quote's tax; 0 when Stripe Tax works it out at payment. */\n taxCents: number\n /**\n * The percentage applied to the taxed line as a Stripe tax rate, or null\n * when no rate is applied (no tax, Stripe Tax, or tax charged as its own line).\n */\n taxPct: number | null\n taxAtPayment: boolean\n /** Goods, shipping and the quote's tax. Stripe Tax adds to it at payment. */\n totalCents: number\n /** What the platform fee prices the goods as. */\n feeProductType: ProductType\n}\n\nconst LINE_DESCRIPTION_MAX = 500\n\nfunction lineSummary(lines: readonly OrderLineItem[]): string {\n const parts = lines.map((line) => {\n const label = line.variantLabel ? `${line.name} (${line.variantLabel})` : line.name\n return `${Math.max(1, cents(line.quantity))} × ${label}`\n })\n const summary = parts.join(', ')\n return summary.length > LINE_DESCRIPTION_MAX ? `${summary.slice(0, LINE_DESCRIPTION_MAX - 1)}…` : summary\n}\n\n/** What the fee ladder prices the quote's charged goods as: physical when any line ships. */\nfunction feeProductTypeOf(lines: readonly OrderLineItem[]): ProductType {\n const charged = lines.filter((line) => !line.included)\n const types = new Set(charged.map((line) => line.productType ?? 'physical'))\n if (types.has('physical') || types.size === 0) return 'physical'\n return types.has('service') ? 'service' : 'digital'\n}\n\n/**\n * The charge for a quote, from its stored lines, discount, shipping and tax\n * basis through {@link computeQuoteTotals} — the same function that priced it\n * when it was saved, so the page, the session and the stored quote agree.\n *\n * The goods are charged as at most two lines, the taxed and the tax-exempt,\n * each after its share of the discount. A store rate is applied to the taxed\n * line as one Stripe tax rate, so Stripe's tax is the rate on exactly the\n * amount the quote taxed, and the quote's figure is what is collected. A tax\n * service's figure is carried the same way, as the percentage of the taxed\n * line it amounts to. Included lines charge nothing and are not sent.\n */\nexport function quoteCheckoutCharge(\n order: Pick<HostOrder, 'number' | 'lineItems' | 'quote'>,\n orderId: string,\n): QuoteCheckoutCharge {\n return payLinkCheckoutCharge({\n lineItems: order.lineItems ?? [],\n tax: order.quote?.tax ?? { kind: 'none', reason: 'not-collected' },\n discount: order.quote?.discount ?? null,\n shippingCents: Math.max(0, cents(order.quote?.shipping?.amountCents)),\n label: formatQuoteNumber(order, orderId),\n })\n}\n\n/**\n * What a pay link's Checkout Session charges for stored lines, a discount,\n * fixed shipping and a tax basis, under a label (`Quote #1042`,\n * `Invoice #1042`): {@link quoteCheckoutCharge}'s pricing, shared with an\n * invoiced order's (AGL-4099), so both are charged the same way.\n */\nexport function payLinkCheckoutCharge(input: {\n lineItems: readonly OrderLineItem[]\n tax: QuoteTaxBasis\n discount: QuoteDiscount | null\n shippingCents: number\n label: string\n}): QuoteCheckoutCharge {\n const { lineItems, tax, discount, shippingCents, label } = input\n const totals = computeQuoteTotals({ lines: lineItems, discount, shippingCents, tax })\n const amounts = quoteLineAmounts(lineItems, discount)\n const groups = [true, false].map((taxable) => {\n const members = lineItems\n .map((line, index) => ({ line, net: amounts.netCents[index] }))\n .filter(({ line, net }) => net > 0 && (line.taxExempt !== true) === taxable)\n return {\n taxable,\n amountCents: members.reduce((sum, { net }) => sum + net, 0),\n description: lineSummary(members.map(({ line }) => line)),\n }\n })\n const charged = groups.filter((group) => group.amountCents > 0)\n const lines: QuoteCheckoutLine[] = charged.map((group) => ({\n name: charged.length > 1 && !group.taxable ? `${label} (tax-exempt items)` : label,\n description: group.description,\n amountCents: group.amountCents,\n taxable: group.taxable,\n }))\n const taxableCents = groups[0].amountCents\n const taxPct =\n totals.taxCents > 0 && taxableCents > 0\n ? tax.kind === 'rate'\n ? Number(tax.pct)\n : engineLineTaxPercentages([{ amountCents: taxableCents, taxCents: totals.taxCents }], 0)[0]\n : null\n // A tax service can tax a quote whose goods are all exempt (on its\n // shipping, say): with no taxed line to carry a rate, its figure is\n // charged as a line of its own, so the customer still pays what the quote says.\n if (totals.taxCents > 0 && taxPct === null) {\n lines.push({\n name: tax.providerLabel ? `Sales tax (${tax.providerLabel})` : 'Sales tax',\n description: label,\n amountCents: totals.taxCents,\n taxable: false,\n })\n }\n return {\n lines,\n itemsCents: totals.itemsCents,\n discountCents: totals.discountCents,\n goodsCents: totals.itemsCents - totals.discountCents,\n taxableCents,\n shippingCents,\n taxCents: totals.taxCents,\n taxPct,\n taxAtPayment: totals.taxAtPayment,\n totalCents: totals.totalCents,\n feeProductType: feeProductTypeOf(lineItems),\n }\n}\n\n/*==========================================\n * WHETHER IT CAN BE PAID NOW\n *=========================================*/\n\nexport type QuotePayRefusal =\n | 'paid'\n | 'closed'\n | 'approval-required'\n | 'tax-undecided'\n | 'nothing-to-pay'\n\n/** Why a quote cannot be paid now, or null when it can. */\nexport function quotePayRefusal(\n order: Pick<HostOrder, 'number' | 'status' | 'lineItems' | 'quote'>,\n orderId: string,\n): QuotePayRefusal | null {\n if (order.status === 'cancelled' || order.status === 'refunded') return 'closed'\n if (order.status !== 'pending') return 'paid'\n if (quotePaymentBlockedByApproval(order.quote)) return 'approval-required'\n if (order.quote?.tax?.kind === 'none' && order.quote.tax.reason === 'undecided') return 'tax-undecided'\n if (quoteCheckoutCharge(order, orderId).totalCents < QUOTE_MIN_CHARGE_CENTS) return 'nothing-to-pay'\n return null\n}\n\n/** What the customer is told for a {@link QuotePayRefusal}, naming the business. */\nexport function quotePayRefusalMessage(reason: QuotePayRefusal, storeName: string): string {\n const business = storeName.trim() || 'the business'\n switch (reason) {\n case 'paid':\n return 'This quote has been paid.'\n case 'closed':\n return `This quote is closed. Contact ${business} with any questions.`\n case 'approval-required':\n return `${business} asks you to approve the proof before you pay.`\n case 'tax-undecided':\n return `${business} has not finished setting up payments. Contact them to pay this quote.`\n case 'nothing-to-pay':\n return `This quote has nothing to pay by card. Contact ${business} with any questions.`\n }\n}\n\n/*==========================================\n * WHEN A PAYMENT COMPLETES\n *=========================================*/\n\n/** What a completed Checkout Session says about the quote it paid. */\nexport interface QuotePaymentFacts {\n sessionId: string\n paymentIntentId: string | null\n /** The link version and quote edit the session was minted for, from its metadata. */\n linkVersion?: string | number | null\n quoteUpdatedAtMs?: string | number | null\n paidAtMs: number\n /** The payer, as Stripe collected them. */\n email: string | null\n name: string | null\n /** What Stripe charged in all, and its shipping and tax parts. */\n amountTotalCents: number | null\n shippingCents: number\n taxCents: number\n /** The platform fee the session was minted with. */\n feeCents: number\n taxMode: StorefrontTaxMode\n /** The address Stripe collected, when the session asked for one. */\n shippingAddress: OrderAddress | null\n}\n\n/**\n * What a completed payment does to a quote:\n *\n * - `pay`: the quote is unpaid and the payment is for it as it stands, so it\n * becomes the order.\n * - `superseded`: the quote is unpaid, but the payment was made through a pay\n * link the business replaced, or for a version of the quote it has since\n * changed. Taking it would record a sale at a price or for a link the\n * business withdrew.\n * - `already-paid`: another payment paid the quote first.\n * - `redelivery`: Stripe sending this same payment again; nothing to do.\n *\n * The two refusals keep the money visible: they are recorded on the quote and\n * the business is told, so a payment is never fulfilled twice and never lost.\n */\nexport type QuotePaymentDisposition = 'pay' | 'superseded' | 'already-paid' | 'redelivery'\n\nexport function quotePaymentDisposition(\n order: Pick<HostOrder, 'status' | 'quote' | 'checkoutSessionId' | 'paymentIntentId'> &\n Partial<Pick<HostOrder, 'payLink'>>,\n payment: Pick<QuotePaymentFacts, 'sessionId' | 'paymentIntentId' | 'linkVersion' | 'quoteUpdatedAtMs'>,\n): QuotePaymentDisposition {\n // Any order's pay link answers the same way (AGL-4099): an invoiced order\n // reads its version and its recorded payments off `payLink`, and its\n // session carries no quote edit to compare.\n const recorded = orderPayLinkUnmatched(order).some((entry) => entry?.sessionId === payment.sessionId)\n if (recorded) return 'redelivery'\n if (order.status !== 'pending') {\n const same =\n (order.checkoutSessionId && order.checkoutSessionId === payment.sessionId) ||\n (payment.paymentIntentId && order.paymentIntentId === payment.paymentIntentId)\n return same ? 'redelivery' : 'already-paid'\n }\n const sentVersion = payment.linkVersion\n if (sentVersion != null && sentVersion !== '' && Number(sentVersion) !== orderPayLinkVersion(order)) {\n return 'superseded'\n }\n const sentEdit = payment.quoteUpdatedAtMs\n if (sentEdit != null && sentEdit !== '' && Number(sentEdit) !== Number(order.quote?.updatedAtMs)) {\n return 'superseded'\n }\n return 'pay'\n}\n\n/** A payment the quote could not take, as {@link QuoteUnmatchedPayment} records it. */\nexport function quoteUnmatchedPayment(\n facts: Pick<QuotePaymentFacts, 'sessionId' | 'paymentIntentId' | 'amountTotalCents' | 'paidAtMs'>,\n reason: QuoteUnmatchedPayment['reason'],\n): QuoteUnmatchedPayment {\n return {\n sessionId: facts.sessionId,\n paymentIntentId: facts.paymentIntentId,\n amountCents: Math.max(0, cents(facts.amountTotalCents)),\n atMs: facts.paidAtMs,\n reason,\n }\n}\n\n/** The timeline line for a payment the quote (or an order's invoice, AGL-4099) could not take. */\nexport function quoteUnmatchedPaymentDetail(\n entry: QuoteUnmatchedPayment,\n noun: 'quote' | 'invoice' = 'quote',\n): string {\n const amount = `$${(entry.amountCents / 100).toFixed(2)}`\n return entry.reason === 'superseded'\n ? `A payment of ${amount} came through a pay link that was replaced, or for an earlier ` +\n `version of this ${noun}. The money is in Stripe and this ${noun} records no sale for it; ` +\n 'refund it in Stripe, or reconcile it by hand.'\n : `A second payment of ${amount} came in after this ${noun} was paid. The money is in Stripe ` +\n 'and no second sale was recorded; refund it in Stripe, or reconcile it by hand.'\n}\n\n/**\n * The order a paid quote becomes, the whole document as it will stand. A\n * quote carries none of the fields order lists read (`commerce-quotes.ts`);\n * paying it writes them:\n *\n * - `createdAtMs` is the time it was paid, the moment it became an order, so\n * it lists and counts on the day the money came in.\n * - The customer moves to the top-level fields every order reader asks\n * (`customerEmail`, `customerName`, `customerPhone`, `customerRecord`), the\n * payer's own email first, as a paid draft takes it.\n * - The address Stripe collected ships it, else the quote's ship-to; the\n * quote's bill-to bills it.\n * - The totals are what Stripe charged: its shipping and tax where it charged\n * any, the platform fee the session was minted with, and its total.\n * - The list fields (`withOrderListFields`) are stamped from all of that.\n */\nexport function paidQuoteOrder(\n order: HostOrder,\n orderId: string,\n facts: QuotePaymentFacts,\n): HostOrder & OrderListFields & { updatedAtMs: number; requiresShipping: boolean } {\n const quote = order.quote as OrderQuote\n const customer = quote?.customer ?? {}\n const stored = order.totals ?? { itemsCents: 0, discountCents: 0, shippingCents: 0, taxCents: 0, feeCents: 0, totalCents: 0 }\n const shippingCents = facts.shippingCents > 0 ? facts.shippingCents : cents(stored.shippingCents)\n const taxCents = facts.taxCents > 0 ? facts.taxCents : cents(stored.taxCents)\n const totalCents =\n facts.amountTotalCents != null && Number.isFinite(facts.amountTotalCents)\n ? facts.amountTotalCents\n : cents(stored.itemsCents) - cents(stored.discountCents) + shippingCents + taxCents\n const shippingAddress = facts.shippingAddress ?? quote?.shipTo ?? null\n const label = formatOrderNumber(order, orderId)\n const paid: HostOrder & { updatedAtMs: number } = {\n ...order,\n status: 'paid',\n createdAtMs: facts.paidAtMs,\n customerEmail: text(facts.email) ?? text(customer.email),\n customerName: text(customer.name) ?? text(facts.name) ?? text(customer.company),\n ...(text(customer.phone) ? { customerPhone: text(customer.phone) } : {}),\n ...(customer.record?.kind && customer.record?.id ? { customerRecord: { ...customer.record } } : {}),\n ...(shippingAddress ? { shippingAddress: { ...shippingAddress } } : {}),\n ...(quote?.billTo ? { billingAddress: { ...quote.billTo } } : {}),\n totals: {\n itemsCents: cents(stored.itemsCents),\n discountCents: cents(stored.discountCents),\n shippingCents,\n taxCents,\n feeCents: Math.max(0, cents(facts.feeCents)),\n totalCents,\n },\n taxMode: facts.taxMode,\n paymentIntentId: facts.paymentIntentId ?? undefined,\n checkoutSessionId: facts.sessionId,\n timeline: appendOrderEvent(order, 'paid', `${label} paid through its pay link`, facts.paidAtMs),\n quote: { ...quote, paidAtMs: facts.paidAtMs },\n // New to a shipping tool's feed from the moment it is paid.\n updatedAtMs: facts.paidAtMs,\n }\n if (!paid.paymentIntentId) delete paid.paymentIntentId\n return withOrderListFields(orderId, paid)\n}\n"],"names":["visitorUploadIsInline","appendOrderEvent","formatOrderNumber","computeQuoteTotals","describeQuoteTax","formatQuoteNumber","quoteLineAmounts","quotePaymentBlockedByApproval","currentQuoteProofs","latestQuoteResponse","quoteRespondRefusal","engineLineTaxPercentages","withOrderListFields","QUOTE_MIN_CHARGE_CENTS","quoteLinkVersion","quote","version","Math","floor","Number","linkVersion","isFinite","orderPayLinkVersion","order","payLink","orderPayLinkUnmatched","list","unmatchedPayments","Array","isArray","filter","entry","text","value","trimmed","trim","cents","number","round","quotePageAddress","address","view","name","line1","line2","city","state","postalCode","country","Object","values","some","Boolean","quotePageStatus","status","label","discountLabel","discount","kind","pct","paidAt","stamped","paidAtMs","event","timeline","find","atMs","buildQuotePageView","input","lines","lineItems","unpaid","charge","quoteCheckoutCharge","orderId","stored","totals","itemsCents","discountCents","shippingCents","taxCents","totalCents","approvalRequired","taxAtPayment","tax","storeName","dateMs","updatedAtMs","createdAtMs","currency","customerName","customer","company","billTo","shipTo","quotePageLines","taxLabel","shippingAtPayment","notes","terms","statusLabel","receiptUrl","payable","quotePayRefusal","revision","max","proofs","map","proof","id","String","contentType","size","inline","response","pageResponse","respondable","channel","line","included","quantity","unitAmountCents","variantLabel","description","sku","amountCents","latest","action","comment","files","length","LINE_DESCRIPTION_MAX","lineSummary","parts","summary","join","slice","feeProductTypeOf","charged","types","Set","productType","has","payLinkCheckoutCharge","reason","shipping","amounts","groups","taxable","members","index","net","netCents","taxExempt","reduce","sum","group","taxableCents","taxPct","push","providerLabel","goodsCents","feeProductType","quotePayRefusalMessage","business","quotePaymentDisposition","payment","recorded","sessionId","same","checkoutSessionId","paymentIntentId","sentVersion","sentEdit","quoteUpdatedAtMs","quoteUnmatchedPayment","facts","amountTotalCents","quoteUnmatchedPaymentDetail","noun","amount","toFixed","paidQuoteOrder","feeCents","shippingAddress","paid","customerEmail","email","phone","customerPhone","record","customerRecord","billingAddress","taxMode","undefined"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,wCAAuC;AAE7E,SACEC,gBAAgB,EAChBC,iBAAiB,QAKZ,uBAAmB;AAC1B,SACEC,kBAAkB,EAClBC,gBAAgB,EAChBC,iBAAiB,EACjBC,gBAAgB,EAChBC,6BAA6B,QAKxB,uBAAmB;AAC1B,SAASC,kBAAkB,EAAEC,mBAAmB,EAAEC,mBAAmB,QAAQ,6BAAyB;AAEtG,SAASC,wBAAwB,QAAQ,2BAAuB;AAChE,SAASC,mBAAmB,QAA8B,yBAAqB;AAE/E;;;;;;;;;;;;;;;;;;;2CAmB2C,GAE3C,oFAAoF,GACpF,OAAO,MAAMC,yBAAyB,GAAE;AA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AAAA,SAASmG,MAAM,qBAAfnG,iBAAiBjC,IAAI,OAAIiC,oBAAAA,SAASmG,MAAM,qBAAfnG,kBAAiBkB,EAAE,IAAG;QAAEkF,gBAAgB,aAAKpG,SAASmG,MAAM;IAAG,IAAI,CAAC,GAC7FN,kBAAkB;QAAEA,iBAAiB,aAAKA;IAAkB,IAAI,CAAC,GACjEzK,CAAAA,yBAAAA,MAAO8E,MAAM,IAAG;QAAEmG,gBAAgB,aAAKjL,MAAM8E,MAAM;IAAG,IAAI,CAAC;QAC/DjB,QAAQ;YACNC,YAAYzC,MAAMuC,OAAOE,UAAU;YACnCC,eAAe1C,MAAMuC,OAAOG,aAAa;YACzCC;YACAC;YACAuG,UAAUtK,KAAKwF,GAAG,CAAC,GAAGrE,MAAM4I,MAAMO,QAAQ;YAC1CtG;QACF;QACAgH,SAASjB,MAAMiB,OAAO;QACtBtB,eAAe,GAAEK,yBAAAA,MAAML,eAAe,YAArBK,yBAAyBkB;QAC1CxB,mBAAmBM,MAAMR,SAAS;QAClCxG,UAAU/D,iBAAiBsB,OAAO,QAAQ,GAAGgC,MAAM,0BAA0B,CAAC,EAAEyH,MAAMlH,QAAQ;QAC9F/C,OAAO,aAAKA;YAAO+C,UAAUkH,MAAMlH,QAAQ;;QAC3C,4DAA4D;QAC5DyB,aAAayF,MAAMlH,QAAQ;;IAE7B,IAAI,CAAC2H,KAAKd,eAAe,EAAE,OAAOc,KAAKd,eAAe;IACtD,OAAO/J,oBAAoB8D,SAAS+G;AACtC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-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 { visitorUploadIsInline } from '@aglyn/aglyn/app-utils/visitor-upload'\nimport type { ProductType } from './commerce'\nimport {\n appendOrderEvent,\n formatOrderNumber,\n type HostOrder,\n type OrderAddress,\n type OrderLineItem,\n type OrderStatus,\n} from './commerce-orders'\nimport {\n computeQuoteTotals,\n describeQuoteTax,\n formatQuoteNumber,\n quoteLineAmounts,\n quotePaymentBlockedByApproval,\n quoteTaxBasisFromSettings,\n type OrderQuote,\n type QuoteDiscount,\n type QuoteNoTaxReason,\n type QuoteTaxBasis,\n type QuoteTaxKind,\n type QuoteUnmatchedPayment,\n} from './commerce-quotes'\nimport { currentQuoteProofs, latestQuoteResponse, quoteRespondRefusal } from './commerce-quote-proofs'\nimport type { TaxSettings } from './commerce-tax'\nimport { storefrontTaxDecision, type StorefrontTaxMode } from './commerce-tax-decision'\nimport { engineLineTaxPercentages, storeTaxAllowsEngine } from './commerce-tax-engine'\nimport { withOrderListFields, type OrderListFields } from './order-list-fields'\n\n/*==========================================\n * PAYING A QUOTE (AGL-4094).\n *\n * The customer opens the quote on the business's own site from a signed pay\n * link, sees it, and pays it. Everything here is pure, so the page's view,\n * the pay route's charge and the webhook's paid order all come from one\n * reading of the stored quote, and none of them from anything the browser\n * sends:\n *\n * - {@link buildQuotePageView}: the ONE projection of a quote that leaves the\n * server for a visitor holding the link, allow-listed field by field.\n * - {@link quoteCheckoutCharge}: what a Checkout Session charges, priced from\n * the stored lines, discount, shipping and tax basis.\n * - {@link quotePayRefusal}: why a quote cannot be paid now, if it cannot.\n * - {@link quotePaymentDisposition} and {@link paidQuoteOrder}: what a\n * completed payment does to the quote, and the order it becomes.\n * - {@link quotePayTax}: the tax every one of them reads, which for a quote\n * saved before the store chose its sales tax is the store's choice now.\n *\n * The customer side has no expiry and no open or closed states: a quote and\n * its link stay until the quote is paid or the business replaces the link.\n *=========================================*/\n\n/** Stripe's smallest card charge; a quote that totals less cannot be paid by card. */\nexport const QUOTE_MIN_CHARGE_CENTS = 50\n\n/** The pay link version a quote is on; absent reads as the first. */\nexport function quoteLinkVersion(quote: Pick<OrderQuote, 'linkVersion'> | null | undefined): number {\n const version = Math.floor(Number(quote?.linkVersion))\n return Number.isFinite(version) && version >= 1 ? version : 1\n}\n\n/**\n * The pay link version any order is on (AGL-4099). A quote keeps its version\n * where slice 2 put it, `quote.linkVersion`, so every link already sent keeps\n * verifying; any other order keeps it as `payLink.version`. Absent reads as\n * the first either way.\n */\nexport function orderPayLinkVersion(order: Partial<Pick<HostOrder, 'quote' | 'payLink'>> | null | undefined): number {\n if (order?.quote) return quoteLinkVersion(order.quote)\n const version = Math.floor(Number(order?.payLink?.version))\n return Number.isFinite(version) && version >= 1 ? version : 1\n}\n\n/** Payments the order's pay link could not take: a quote's on the quote, any other order's on `payLink`. */\nexport function orderPayLinkUnmatched(\n order: Partial<Pick<HostOrder, 'quote' | 'payLink'>> | null | undefined,\n): QuoteUnmatchedPayment[] {\n const list = order?.quote ? order.quote.unmatchedPayments : order?.payLink?.unmatchedPayments\n return Array.isArray(list) ? list.filter((entry) => entry && typeof entry === 'object') : []\n}\n\n/*==========================================\n * THE TAX A QUOTE IS SHOWN AND PAID UNDER\n *=========================================*/\n\n/**\n * The store a pay link is read against: its sales tax choice, as\n * `hosts/{hostId}/settings/store` keeps it under `tax`. Absent or null, the\n * store has not chosen.\n */\nexport interface PayLinkStore {\n tax?: TaxSettings | null\n}\n\n/** The store a pay link reads, from the store settings document's data (nothing, for no document). */\nexport function payLinkStoreOf(settings: { tax?: unknown } | null | undefined): PayLinkStore {\n const tax = settings?.tax\n return { tax: tax && typeof tax === 'object' ? (tax as TaxSettings) : null }\n}\n\n/** Whether a basis records that nobody had chosen the store's sales tax, which is no choice at all. */\nexport function quoteTaxIsUndecided(basis: Pick<QuoteTaxBasis, 'kind' | 'reason'> | null | undefined): boolean {\n return basis?.kind === 'none' && basis.reason === 'undecided'\n}\n\n/**\n * Where a quote's tax comes from when it is shown and paid:\n *\n * - `stored`: the basis it was saved with.\n * - `current`: it was saved before the store chose, and takes the store's\n * choice as it stands now.\n * - `save`: it was saved before the store chose, and the store's choice now\n * prices it only when it is saved again.\n */\nexport type QuotePayTaxSource = 'stored' | 'current' | 'save'\n\nexport interface QuotePayTax {\n basis: QuoteTaxBasis\n source: QuotePayTaxSource\n}\n\n/**\n * The tax a quote is shown, charged and paid under (AGL-4162): the one answer\n * the quote page, Pay, the payment's record (carried on its session) and the\n * console's notice all read.\n *\n * A quote keeps the basis it was saved with, except one saved before the\n * store chose how it handles sales tax. That basis records no choice, so the\n * quote takes the store's choice as it stands now, through the same\n * `quoteTaxBasisFromSettings` the editor prices a save with: no sales tax,\n * prices that include tax, or Stripe Tax at payment. Nothing is written for\n * it; the next save stores the same basis.\n *\n * The store's own rates on prices that exclude tax are the one choice not\n * taken this way. On those settings a save asks the site's tax service where\n * one is connected (`priceQuote` in `server/quote.ts`), and only that save\n * knows the figure: which service is connected is the tax service's own to\n * say. Such a quote keeps its basis, and so stays unpaid, until it is saved.\n *\n * Without a store, the stored basis stands.\n */\nexport function quotePayTax(\n quote: Pick<OrderQuote, 'tax' | 'shipTo'> | null | undefined,\n store?: PayLinkStore | null,\n): QuotePayTax {\n const stored: QuoteTaxBasis = quote?.tax ?? { kind: 'none', reason: 'not-collected' }\n if (!store || !quoteTaxIsUndecided(stored)) return { basis: stored, source: 'stored' }\n if (storefrontTaxDecision({ settings: store.tax }).kind === 'undecided') return { basis: stored, source: 'stored' }\n if (storeTaxAllowsEngine(store.tax)) return { basis: stored, source: 'save' }\n return { basis: quoteTaxBasisFromSettings(store.tax, quote?.shipTo), source: 'current' }\n}\n\nconst TAX_KINDS: ReadonlySet<string> = new Set<QuoteTaxKind>(['rate', 'service', 'at-payment', 'none'])\nconst NO_TAX_REASONS: ReadonlySet<string> = new Set<QuoteNoTaxReason>([\n 'not-collected',\n 'prices-include-tax',\n 'no-rate',\n 'undecided',\n])\nconst BASIS_LABEL_MAX = 120\n\n/** A basis holding only what its kind carries, in one order, or null for anything that is not one. */\nfunction tidyTaxBasis(raw: unknown): QuoteTaxBasis | null {\n if (!raw || typeof raw !== 'object') return null\n const source = raw as Record<string, unknown>\n const kind = String(source['kind'] ?? '')\n if (!TAX_KINDS.has(kind)) return null\n const label = (value: unknown) => (typeof value === 'string' && value.trim() ? value.trim().slice(0, BASIS_LABEL_MAX) : '')\n if (kind === 'rate') {\n const pct = Number(source['pct'])\n if (!Number.isFinite(pct)) return null\n const named = label(source['label'])\n return { kind, pct, ...(named ? { label: named } : {}) }\n }\n if (kind === 'service') {\n const taxCents = Math.round(Number(source['taxCents']))\n if (!Number.isFinite(taxCents) || taxCents < 0) return null\n const named = label(source['providerLabel'])\n return { kind, taxCents, ...(named ? { providerLabel: named } : {}) }\n }\n if (kind === 'at-payment') return { kind }\n const reason = String(source['reason'] ?? '')\n return { kind: 'none', reason: (NO_TAX_REASONS.has(reason) ? reason : 'not-collected') as QuoteNoTaxReason }\n}\n\n/**\n * A basis as one short string: what the quote page sends back with Pay, so a\n * payment is refused when the tax it would charge is not the tax the page\n * showed, and what a session records as the basis it charged. Equal bases\n * have one key.\n */\nexport function quoteTaxBasisKey(basis: QuoteTaxBasis): string {\n return JSON.stringify(tidyTaxBasis(basis) ?? { kind: 'none', reason: 'not-collected' })\n}\n\n/** A basis back from {@link quoteTaxBasisKey}, or null for anything else. */\nexport function quoteTaxBasisFromKey(key: unknown): QuoteTaxBasis | null {\n if (typeof key !== 'string' || !key || key.length > 500) return null\n try {\n return tidyTaxBasis(JSON.parse(key))\n } catch {\n return null\n }\n}\n\n/*==========================================\n * THE CUSTOMER'S PAGE\n *=========================================*/\n\n/** An address as the quote page prints it: no phone. */\nexport interface QuotePageAddress {\n name: string | null\n line1: string | null\n line2: string | null\n city: string | null\n state: string | null\n postalCode: string | null\n country: string | null\n}\n\nexport interface QuotePageLine {\n name: string\n /** The option and add-ons chosen, as order lines print them. */\n variantLabel: string | null\n description: string | null\n sku: string | null\n quantity: number\n unitAmountCents: number\n /** What the line charges: 0 for an included line. */\n amountCents: number\n /** Included at no charge. */\n included: boolean\n}\n\n/** Where the quote stands, as its customer sees it. */\nexport type QuotePageStatus = 'unpaid' | 'paid' | 'canceled' | 'refunded'\n\n/** A proof as the quote page lists it: no storage path, nothing about who attached it. */\nexport interface QuotePageProof {\n id: string\n name: string\n contentType: string\n size: number\n /** Shown in the page as a picture; everything else is a download. */\n inline: boolean\n}\n\n/** The customer's latest answer to the revision the page shows. */\nexport interface QuotePageResponse {\n action: 'approve' | 'changes'\n atMs: number\n /** With an approval: the name it was given under. */\n name: string | null\n comment: string | null\n /** How many files came with it. */\n files: number\n}\n\n/**\n * What the quote page shows. Allow-listed, never spread: the order document\n * carries the customer's email and phone, Stripe ids, the business's own\n * timeline and who wrote the quote, none of which a forwarded link may show.\n * New fields are added here deliberately, or not at all.\n */\nexport interface QuotePageView {\n state: 'quote'\n /**\n * What the page shows (AGL-4099): a quote, or an invoice for an order the\n * business sent one for. An invoice has no proofs and no approval, and the\n * page says \"invoice\" where a quote's says \"quote\".\n */\n kind: 'quote' | 'invoice'\n storeName: string\n /** `Quote #1042`, or `Invoice #1042`. */\n number: string\n /** When the quote was last written, which is the date it carries. */\n dateMs: number | null\n /**\n * The edit of the quote this view shows. Pay sends it back, and a quote\n * changed since is refused, so nobody pays for a version they have not seen.\n */\n version: number\n currency: string\n customerName: string | null\n company: string | null\n billTo: QuotePageAddress | null\n shipTo: QuotePageAddress | null\n lines: QuotePageLine[]\n totals: {\n itemsCents: number\n discountCents: number\n shippingCents: number\n taxCents: number\n totalCents: number\n }\n /** `10% off`, or null for an amount or no discount. */\n discountLabel: string | null\n /** The tax line's label, or `Tax is added at payment`. */\n taxLabel: string\n /** Stripe Tax works the tax out when the customer pays; `taxCents` is 0 until then. */\n taxAtPayment: boolean\n /**\n * The customer picks a shipping rate when they pay (an invoiced draft\n * order, AGL-4099); `shippingCents` is 0 until then. A quote's shipping is\n * priced on it, so this is false for every quote.\n */\n shippingAtPayment: boolean\n notes: string | null\n terms: string | null\n status: QuotePageStatus\n statusLabel: string\n paidAtMs: number | null\n /** The order's status page, once paid. */\n receiptUrl: string | null\n /** The business asks the customer to approve the proof before paying. */\n approvalRequired: boolean\n /** A Pay button belongs on the page. */\n payable: boolean\n /**\n * What the page says in place of Pay when the business can't take payments\n * online right now (AGL-4162): the Pay route's own refusal, word for word.\n * Null otherwise, and the page asks the customer to contact the business.\n */\n notPayableMessage: string | null\n /**\n * The tax the quote's totals are priced under ({@link quoteTaxBasisKey}),\n * which Pay sends back as `tax`: a quote whose tax would charge differently\n * from the page is shown again before it is paid (AGL-4162). Null for an\n * invoice, whose tax is fixed when it is made, and once paid.\n */\n taxKey: string | null\n /** The revision the page shows (AGL-4096). */\n revision: number\n /** That revision's proofs. */\n proofs: QuotePageProof[]\n /** The customer's latest answer to it, if any. */\n response: QuotePageResponse | null\n /** Approve and Request changes belong on the page. */\n respondable: boolean\n}\n\n/** What a signed link for an older version of the quote opens: nothing of the quote. */\nexport interface QuotePageReplacedView {\n state: 'replaced'\n storeName: string\n}\n\nconst text = (value: unknown): string | null => {\n const trimmed = typeof value === 'string' ? value.trim() : ''\n return trimmed ? trimmed : null\n}\n\nconst cents = (value: unknown): number => {\n const number = Math.round(Number(value))\n return Number.isFinite(number) ? number : 0\n}\n\n/** An address as the pay link's page prints it, or null when it says nothing. */\nexport function quotePageAddress(address: OrderAddress | null | undefined): QuotePageAddress | null {\n if (!address) return null\n const view: QuotePageAddress = {\n name: text(address.name),\n line1: text(address.line1),\n line2: text(address.line2),\n city: text(address.city),\n state: text(address.state),\n postalCode: text(address.postalCode),\n country: text(address.country),\n }\n return Object.values(view).some(Boolean) ? view : null\n}\n\n/** Where an order stands as the pay link's page says it. */\nexport function quotePageStatus(status: OrderStatus | string | undefined): { status: QuotePageStatus; label: string } {\n if (status === 'pending') return { status: 'unpaid', label: 'Unpaid' }\n if (status === 'cancelled') return { status: 'canceled', label: 'Canceled' }\n if (status === 'refunded') return { status: 'refunded', label: 'Refunded' }\n return { status: 'paid', label: 'Paid' }\n}\n\nfunction discountLabel(discount: QuoteDiscount | null | undefined): string | null {\n if (discount?.kind !== 'percent' || !(Number(discount.pct) > 0)) return null\n return `${Number(discount.pct)}% off`\n}\n\n/** When the quote was paid: its stamp, else the timeline's `paid` event. */\nfunction paidAt(order: Pick<HostOrder, 'status' | 'quote' | 'timeline'>): number | null {\n if (order.status === 'pending') return null\n const stamped = Number(order.quote?.paidAtMs)\n if (Number.isFinite(stamped) && stamped > 0) return stamped\n const event = (order.timeline ?? []).find((entry) => entry?.event === 'paid')\n return event ? Number(event.atMs) || null : null\n}\n\n/**\n * The quote page's view of an order document on the `quote` channel. Totals\n * are the stored lines' through {@link computeQuoteTotals} until the quote is\n * paid, and the paid order's own totals (what Stripe charged) after. The tax\n * is {@link quotePayTax}'s for the store given, and Pay belongs on the page\n * only when nothing would refuse it: the store's payments included, when the\n * caller says whether it can take them.\n */\nexport function buildQuotePageView(input: {\n order: Pick<HostOrder, 'number' | 'status' | 'lineItems' | 'totals' | 'quote' | 'timeline'>\n orderId: string\n storeName: string\n currency: string\n /** The order's status page, for a paid quote. */\n receiptUrl?: string | null\n /** The store's sales tax choice, which a quote saved before it was made takes. */\n store?: PayLinkStore | null\n /** Whether the business can take a card payment now; absent, it is not judged here. */\n paymentsReady?: boolean\n}): QuotePageView {\n const { order } = input\n const quote = order.quote\n const lines = order.lineItems ?? []\n const status = quotePageStatus(order.status)\n const unpaid = status.status === 'unpaid'\n const payTax = quotePayTax(quote, input.store)\n const charge = quoteCheckoutCharge(order, input.orderId, input.store)\n const stored = order.totals\n const totals = unpaid || !stored\n ? {\n itemsCents: charge.itemsCents,\n discountCents: charge.discountCents,\n shippingCents: charge.shippingCents,\n taxCents: charge.taxCents,\n totalCents: charge.totalCents,\n }\n : {\n itemsCents: cents(stored.itemsCents),\n discountCents: cents(stored.discountCents),\n shippingCents: cents(stored.shippingCents),\n taxCents: cents(stored.taxCents),\n totalCents: cents(stored.totalCents),\n }\n const approvalRequired = unpaid && quotePaymentBlockedByApproval(quote)\n const taxAtPayment = unpaid && payTax.basis.kind === 'at-payment'\n const refused = unpaid\n ? payLinkRefusalWithPayments(quotePayRefusal(order, input.orderId, input.store), input.paymentsReady)\n : null\n return {\n state: 'quote',\n kind: 'quote',\n storeName: input.storeName,\n number: formatQuoteNumber(order, input.orderId),\n dateMs: Number(quote?.updatedAtMs ?? quote?.createdAtMs) || null,\n version: Number(quote?.updatedAtMs) || 0,\n currency: input.currency || 'USD',\n customerName: text(quote?.customer?.name) ?? text(quote?.customer?.company),\n company: text(quote?.customer?.name) ? text(quote?.customer?.company) : null,\n billTo: quotePageAddress(quote?.billTo),\n shipTo: quotePageAddress(quote?.shipTo),\n lines: quotePageLines(lines),\n totals,\n discountLabel: discountLabel(quote?.discount),\n // Once paid, the tax is what was charged: Stripe's figure under Stripe Tax.\n taxLabel: unpaid || payTax.basis.kind !== 'at-payment' ? describeQuoteTax(payTax.basis) : 'Tax',\n taxAtPayment,\n shippingAtPayment: false,\n notes: text(quote?.notes),\n terms: text(quote?.terms),\n status: status.status,\n statusLabel: status.label,\n paidAtMs: paidAt(order),\n receiptUrl: unpaid ? null : (input.receiptUrl ?? null),\n approvalRequired,\n payable: unpaid && refused === null,\n notPayableMessage: refused === 'payments-unavailable' ? payLinkPaymentsUnavailableMessage(input.storeName, 'quote') : null,\n taxKey: unpaid ? quoteTaxBasisKey(payTax.basis) : null,\n revision: Math.max(1, Number(quote?.revision ?? 1) || 1),\n proofs: currentQuoteProofs(quote).map((proof) => ({\n id: String(proof.id),\n name: String(proof.name ?? 'Proof'),\n contentType: String(proof.contentType ?? ''),\n size: Math.max(0, cents(proof.size)),\n inline: visitorUploadIsInline(String(proof.contentType ?? '')),\n })),\n response: pageResponse(quote),\n // The page is only ever a quote's, whatever the caller picked off the order.\n respondable: quoteRespondRefusal({ channel: 'quote', status: order.status, quote }) === null,\n }\n}\n\n/** Order lines as the pay link's page lists them: what each charges, nothing about stock or cost. */\nexport function quotePageLines(lines: readonly OrderLineItem[]): QuotePageLine[] {\n return lines.map((line) => {\n const included = line.included === true\n const quantity = Math.max(0, cents(line.quantity))\n const unitAmountCents = included ? 0 : Math.max(0, cents(line.unitAmountCents))\n return {\n name: String(line.name ?? ''),\n variantLabel: text(line.variantLabel),\n description: text(line.description),\n sku: text(line.sku),\n quantity,\n unitAmountCents,\n amountCents: unitAmountCents * quantity,\n included,\n }\n })\n}\n\n/** The latest answer, as the page may show it back to the link's holder: never the address or browser. */\nfunction pageResponse(quote: OrderQuote | null | undefined): QuotePageResponse | null {\n const latest = latestQuoteResponse(quote)\n if (!latest) return null\n return {\n action: latest.action === 'approve' ? 'approve' : 'changes',\n atMs: Number(latest.atMs) || 0,\n name: latest.action === 'approve' ? text(latest.name) : null,\n comment: latest.action === 'changes' ? text(latest.comment) : null,\n files: latest.files?.length ?? 0,\n }\n}\n\n/*==========================================\n * WHAT A PAYMENT CHARGES\n *=========================================*/\n\n/** One line of a quote's Checkout Session. */\nexport interface QuoteCheckoutLine {\n name: string\n /** The quote's lines this one charges for, as the hosted page lists them. */\n description: string\n amountCents: number\n /** False for tax-exempt products: no rate is applied and Stripe Tax is told it is nontaxable. */\n taxable: boolean\n}\n\n/** What a quote's Checkout Session charges, priced from the stored quote alone. */\nexport interface QuoteCheckoutCharge {\n /** The goods grouped by whether they are taxed, so one rate taxes exactly the quote's taxable amount. */\n lines: QuoteCheckoutLine[]\n itemsCents: number\n discountCents: number\n /** The goods after the discount: what the business is paid for them. */\n goodsCents: number\n taxableCents: number\n shippingCents: number\n /** The quote's tax; 0 when Stripe Tax works it out at payment. */\n taxCents: number\n /**\n * The percentage applied to the taxed line as a Stripe tax rate, or null\n * when no rate is applied (no tax, Stripe Tax, or tax charged as its own line).\n */\n taxPct: number | null\n taxAtPayment: boolean\n /** Goods, shipping and the quote's tax. Stripe Tax adds to it at payment. */\n totalCents: number\n /** What the platform fee prices the goods as. */\n feeProductType: ProductType\n}\n\nconst LINE_DESCRIPTION_MAX = 500\n\nfunction lineSummary(lines: readonly OrderLineItem[]): string {\n const parts = lines.map((line) => {\n const label = line.variantLabel ? `${line.name} (${line.variantLabel})` : line.name\n return `${Math.max(1, cents(line.quantity))} × ${label}`\n })\n const summary = parts.join(', ')\n return summary.length > LINE_DESCRIPTION_MAX ? `${summary.slice(0, LINE_DESCRIPTION_MAX - 1)}…` : summary\n}\n\n/** What the fee ladder prices the quote's charged goods as: physical when any line ships. */\nfunction feeProductTypeOf(lines: readonly OrderLineItem[]): ProductType {\n const charged = lines.filter((line) => !line.included)\n const types = new Set(charged.map((line) => line.productType ?? 'physical'))\n if (types.has('physical') || types.size === 0) return 'physical'\n return types.has('service') ? 'service' : 'digital'\n}\n\n/**\n * The charge for a quote, from its stored lines, discount, shipping and tax\n * basis through {@link computeQuoteTotals} — the same function that priced it\n * when it was saved, so the page, the session and the stored quote agree. The\n * basis is {@link quotePayTax}'s: a quote saved before the store chose its\n * sales tax is charged under the store's choice now.\n *\n * The goods are charged as at most two lines, the taxed and the tax-exempt,\n * each after its share of the discount. A store rate is applied to the taxed\n * line as one Stripe tax rate, so Stripe's tax is the rate on exactly the\n * amount the quote taxed, and the quote's figure is what is collected. A tax\n * service's figure is carried the same way, as the percentage of the taxed\n * line it amounts to. Included lines charge nothing and are not sent.\n */\nexport function quoteCheckoutCharge(\n order: Pick<HostOrder, 'number' | 'lineItems' | 'quote'>,\n orderId: string,\n store?: PayLinkStore | null,\n): QuoteCheckoutCharge {\n return payLinkCheckoutCharge({\n lineItems: order.lineItems ?? [],\n tax: quotePayTax(order.quote, store).basis,\n discount: order.quote?.discount ?? null,\n shippingCents: Math.max(0, cents(order.quote?.shipping?.amountCents)),\n label: formatQuoteNumber(order, orderId),\n })\n}\n\n/**\n * What a pay link's Checkout Session charges for stored lines, a discount,\n * fixed shipping and a tax basis, under a label (`Quote #1042`,\n * `Invoice #1042`): {@link quoteCheckoutCharge}'s pricing, shared with an\n * invoiced order's (AGL-4099), so both are charged the same way.\n */\nexport function payLinkCheckoutCharge(input: {\n lineItems: readonly OrderLineItem[]\n tax: QuoteTaxBasis\n discount: QuoteDiscount | null\n shippingCents: number\n label: string\n}): QuoteCheckoutCharge {\n const { lineItems, tax, discount, shippingCents, label } = input\n const totals = computeQuoteTotals({ lines: lineItems, discount, shippingCents, tax })\n const amounts = quoteLineAmounts(lineItems, discount)\n const groups = [true, false].map((taxable) => {\n const members = lineItems\n .map((line, index) => ({ line, net: amounts.netCents[index] }))\n .filter(({ line, net }) => net > 0 && (line.taxExempt !== true) === taxable)\n return {\n taxable,\n amountCents: members.reduce((sum, { net }) => sum + net, 0),\n description: lineSummary(members.map(({ line }) => line)),\n }\n })\n const charged = groups.filter((group) => group.amountCents > 0)\n const lines: QuoteCheckoutLine[] = charged.map((group) => ({\n name: charged.length > 1 && !group.taxable ? `${label} (tax-exempt items)` : label,\n description: group.description,\n amountCents: group.amountCents,\n taxable: group.taxable,\n }))\n const taxableCents = groups[0].amountCents\n const taxPct =\n totals.taxCents > 0 && taxableCents > 0\n ? tax.kind === 'rate'\n ? Number(tax.pct)\n : engineLineTaxPercentages([{ amountCents: taxableCents, taxCents: totals.taxCents }], 0)[0]\n : null\n // A tax service can tax a quote whose goods are all exempt (on its\n // shipping, say): with no taxed line to carry a rate, its figure is\n // charged as a line of its own, so the customer still pays what the quote says.\n if (totals.taxCents > 0 && taxPct === null) {\n lines.push({\n name: tax.providerLabel ? `Sales tax (${tax.providerLabel})` : 'Sales tax',\n description: label,\n amountCents: totals.taxCents,\n taxable: false,\n })\n }\n return {\n lines,\n itemsCents: totals.itemsCents,\n discountCents: totals.discountCents,\n goodsCents: totals.itemsCents - totals.discountCents,\n taxableCents,\n shippingCents,\n taxCents: totals.taxCents,\n taxPct,\n taxAtPayment: totals.taxAtPayment,\n totalCents: totals.totalCents,\n feeProductType: feeProductTypeOf(lineItems),\n }\n}\n\n/*==========================================\n * WHETHER IT CAN BE PAID NOW\n *=========================================*/\n\nexport type QuotePayRefusal =\n | 'paid'\n | 'closed'\n | 'approval-required'\n | 'tax-undecided'\n | 'nothing-to-pay'\n\n/**\n * Why a quote cannot be paid now, or null when it can. With the store, its\n * tax is {@link quotePayTax}'s, and a store that has not chosen its sales tax\n * refuses every sale (AGL-1999), whatever basis the quote was saved with.\n */\nexport function quotePayRefusal(\n order: Pick<HostOrder, 'number' | 'status' | 'lineItems' | 'quote'>,\n orderId: string,\n store?: PayLinkStore | null,\n): QuotePayRefusal | null {\n if (order.status === 'cancelled' || order.status === 'refunded') return 'closed'\n if (order.status !== 'pending') return 'paid'\n if (quotePaymentBlockedByApproval(order.quote)) return 'approval-required'\n if (store && storefrontTaxDecision({ settings: store.tax }).kind === 'undecided') return 'tax-undecided'\n if (quoteTaxIsUndecided(quotePayTax(order.quote, store).basis)) return 'tax-undecided'\n if (quoteCheckoutCharge(order, orderId, store).totalCents < QUOTE_MIN_CHARGE_CENTS) return 'nothing-to-pay'\n return null\n}\n\n/**\n * A pay link's refusal once the store's payments are judged too: a business\n * that can't take a card payment now outranks every refusal but the ones a\n * payment never gets past (paid, closed, not linked, waiting on the\n * customer's approval). `paymentsReady` absent leaves the refusal as it is.\n */\nexport function payLinkRefusalWithPayments<Reason extends string>(\n reason: Reason | null,\n paymentsReady: boolean | undefined,\n): Reason | 'payments-unavailable' | null {\n if (paymentsReady !== false) return reason\n if (reason === 'paid' || reason === 'closed' || reason === 'not-payable' || reason === 'approval-required') {\n return reason\n }\n return 'payments-unavailable'\n}\n\n/** What the customer is told when the business can't take a card payment now: the page's words and Pay's. */\nexport function payLinkPaymentsUnavailableMessage(storeName: string, kind: 'quote' | 'invoice'): string {\n return `${storeName || 'This business'} can’t take payments online right now. Contact them to pay this ${kind === 'invoice' ? 'invoice' : 'quote'}.`\n}\n\n/** What the customer is told for a {@link QuotePayRefusal}, naming the business. */\nexport function quotePayRefusalMessage(reason: QuotePayRefusal, storeName: string): string {\n const business = storeName.trim() || 'the business'\n switch (reason) {\n case 'paid':\n return 'This quote has been paid.'\n case 'closed':\n return `This quote is closed. Contact ${business} with any questions.`\n case 'approval-required':\n return `${business} asks you to approve the proof before you pay.`\n case 'tax-undecided':\n return `${business} has not finished setting up payments. Contact them to pay this quote.`\n case 'nothing-to-pay':\n return `This quote has nothing to pay by card. Contact ${business} with any questions.`\n }\n}\n\n/*==========================================\n * WHEN A PAYMENT COMPLETES\n *=========================================*/\n\n/** What a completed Checkout Session says about the quote it paid. */\nexport interface QuotePaymentFacts {\n sessionId: string\n paymentIntentId: string | null\n /** The link version and quote edit the session was minted for, from its metadata. */\n linkVersion?: string | number | null\n quoteUpdatedAtMs?: string | number | null\n paidAtMs: number\n /** The payer, as Stripe collected them. */\n email: string | null\n name: string | null\n /** What Stripe charged in all, and its shipping and tax parts. */\n amountTotalCents: number | null\n shippingCents: number\n taxCents: number\n /** The platform fee the session was minted with. */\n feeCents: number\n taxMode: StorefrontTaxMode\n /** The address Stripe collected, when the session asked for one. */\n shippingAddress: OrderAddress | null\n /**\n * The tax the session charged under when it was not the quote's stored\n * basis: {@link quotePayTax}'s answer for a quote saved before the store\n * chose its sales tax, carried on the session (`quoteTax`,\n * {@link quoteTaxBasisKey}) by the press that opened it (AGL-4162).\n */\n taxBasis?: QuoteTaxBasis | null\n}\n\n/**\n * What a completed payment does to a quote:\n *\n * - `pay`: the quote is unpaid and the payment is for it as it stands, so it\n * becomes the order.\n * - `superseded`: the quote is unpaid, but the payment was made through a pay\n * link the business replaced, or for a version of the quote it has since\n * changed. Taking it would record a sale at a price or for a link the\n * business withdrew.\n * - `already-paid`: another payment paid the quote first.\n * - `redelivery`: Stripe sending this same payment again; nothing to do.\n *\n * The two refusals keep the money visible: they are recorded on the quote and\n * the business is told, so a payment is never fulfilled twice and never lost.\n */\nexport type QuotePaymentDisposition = 'pay' | 'superseded' | 'already-paid' | 'redelivery'\n\nexport function quotePaymentDisposition(\n order: Pick<HostOrder, 'status' | 'quote' | 'checkoutSessionId' | 'paymentIntentId'> &\n Partial<Pick<HostOrder, 'payLink'>>,\n payment: Pick<QuotePaymentFacts, 'sessionId' | 'paymentIntentId' | 'linkVersion' | 'quoteUpdatedAtMs'>,\n): QuotePaymentDisposition {\n // Any order's pay link answers the same way (AGL-4099): an invoiced order\n // reads its version and its recorded payments off `payLink`, and its\n // session carries no quote edit to compare.\n const recorded = orderPayLinkUnmatched(order).some((entry) => entry?.sessionId === payment.sessionId)\n if (recorded) return 'redelivery'\n if (order.status !== 'pending') {\n const same =\n (order.checkoutSessionId && order.checkoutSessionId === payment.sessionId) ||\n (payment.paymentIntentId && order.paymentIntentId === payment.paymentIntentId)\n return same ? 'redelivery' : 'already-paid'\n }\n const sentVersion = payment.linkVersion\n if (sentVersion != null && sentVersion !== '' && Number(sentVersion) !== orderPayLinkVersion(order)) {\n return 'superseded'\n }\n const sentEdit = payment.quoteUpdatedAtMs\n if (sentEdit != null && sentEdit !== '' && Number(sentEdit) !== Number(order.quote?.updatedAtMs)) {\n return 'superseded'\n }\n return 'pay'\n}\n\n/** A payment the quote could not take, as {@link QuoteUnmatchedPayment} records it. */\nexport function quoteUnmatchedPayment(\n facts: Pick<QuotePaymentFacts, 'sessionId' | 'paymentIntentId' | 'amountTotalCents' | 'paidAtMs'>,\n reason: QuoteUnmatchedPayment['reason'],\n): QuoteUnmatchedPayment {\n return {\n sessionId: facts.sessionId,\n paymentIntentId: facts.paymentIntentId,\n amountCents: Math.max(0, cents(facts.amountTotalCents)),\n atMs: facts.paidAtMs,\n reason,\n }\n}\n\n/** The timeline line for a payment the quote (or an order's invoice, AGL-4099) could not take. */\nexport function quoteUnmatchedPaymentDetail(\n entry: QuoteUnmatchedPayment,\n noun: 'quote' | 'invoice' = 'quote',\n): string {\n const amount = `$${(entry.amountCents / 100).toFixed(2)}`\n return entry.reason === 'superseded'\n ? `A payment of ${amount} came through a pay link that was replaced, or for an earlier ` +\n `version of this ${noun}. The money is in Stripe and this ${noun} records no sale for it; ` +\n 'refund it in Stripe, or reconcile it by hand.'\n : `A second payment of ${amount} came in after this ${noun} was paid. The money is in Stripe ` +\n 'and no second sale was recorded; refund it in Stripe, or reconcile it by hand.'\n}\n\n/**\n * The order a paid quote becomes, the whole document as it will stand. A\n * quote carries none of the fields order lists read (`commerce-quotes.ts`);\n * paying it writes them:\n *\n * - `createdAtMs` is the time it was paid, the moment it became an order, so\n * it lists and counts on the day the money came in.\n * - The customer moves to the top-level fields every order reader asks\n * (`customerEmail`, `customerName`, `customerPhone`, `customerRecord`), the\n * payer's own email first, as a paid draft takes it.\n * - The address Stripe collected ships it, else the quote's ship-to; the\n * quote's bill-to bills it.\n * - The totals are what Stripe charged: its shipping and tax where it charged\n * any, the platform fee the session was minted with, and its total.\n * - The quote keeps the tax basis it was paid under: the session's\n * ({@link QuotePaymentFacts.taxBasis}) where the press took the store's\n * choice for it, so the order says how its tax was worked out.\n * - The list fields (`withOrderListFields`) are stamped from all of that.\n */\nexport function paidQuoteOrder(\n order: HostOrder,\n orderId: string,\n facts: QuotePaymentFacts,\n): HostOrder & OrderListFields & { updatedAtMs: number; requiresShipping: boolean } {\n const quote = order.quote as OrderQuote\n const customer = quote?.customer ?? {}\n const stored = order.totals ?? { itemsCents: 0, discountCents: 0, shippingCents: 0, taxCents: 0, feeCents: 0, totalCents: 0 }\n const shippingCents = facts.shippingCents > 0 ? facts.shippingCents : cents(stored.shippingCents)\n const taxCents = facts.taxCents > 0 ? facts.taxCents : cents(stored.taxCents)\n const totalCents =\n facts.amountTotalCents != null && Number.isFinite(facts.amountTotalCents)\n ? facts.amountTotalCents\n : cents(stored.itemsCents) - cents(stored.discountCents) + shippingCents + taxCents\n const shippingAddress = facts.shippingAddress ?? quote?.shipTo ?? null\n const label = formatOrderNumber(order, orderId)\n const paid: HostOrder & { updatedAtMs: number } = {\n ...order,\n status: 'paid',\n createdAtMs: facts.paidAtMs,\n customerEmail: text(facts.email) ?? text(customer.email),\n customerName: text(customer.name) ?? text(facts.name) ?? text(customer.company),\n ...(text(customer.phone) ? { customerPhone: text(customer.phone) } : {}),\n ...(customer.record?.kind && customer.record?.id ? { customerRecord: { ...customer.record } } : {}),\n ...(shippingAddress ? { shippingAddress: { ...shippingAddress } } : {}),\n ...(quote?.billTo ? { billingAddress: { ...quote.billTo } } : {}),\n totals: {\n itemsCents: cents(stored.itemsCents),\n discountCents: cents(stored.discountCents),\n shippingCents,\n taxCents,\n feeCents: Math.max(0, cents(facts.feeCents)),\n totalCents,\n },\n taxMode: facts.taxMode,\n paymentIntentId: facts.paymentIntentId ?? undefined,\n checkoutSessionId: facts.sessionId,\n timeline: appendOrderEvent(order, 'paid', `${label} paid through its pay link`, facts.paidAtMs),\n quote: { ...quote, ...(facts.taxBasis ? { tax: facts.taxBasis } : {}), paidAtMs: facts.paidAtMs },\n // New to a shipping tool's feed from the moment it is paid.\n updatedAtMs: facts.paidAtMs,\n }\n if (!paid.paymentIntentId) delete paid.paymentIntentId\n return withOrderListFields(orderId, paid)\n}\n"],"names":["visitorUploadIsInline","appendOrderEvent","formatOrderNumber","computeQuoteTotals","describeQuoteTax","formatQuoteNumber","quoteLineAmounts","quotePaymentBlockedByApproval","quoteTaxBasisFromSettings","currentQuoteProofs","latestQuoteResponse","quoteRespondRefusal","storefrontTaxDecision","engineLineTaxPercentages","storeTaxAllowsEngine","withOrderListFields","QUOTE_MIN_CHARGE_CENTS","quoteLinkVersion","quote","version","Math","floor","Number","linkVersion","isFinite","orderPayLinkVersion","order","payLink","orderPayLinkUnmatched","list","unmatchedPayments","Array","isArray","filter","entry","payLinkStoreOf","settings","tax","quoteTaxIsUndecided","basis","kind","reason","quotePayTax","store","stored","source","shipTo","TAX_KINDS","Set","NO_TAX_REASONS","BASIS_LABEL_MAX","tidyTaxBasis","raw","String","has","label","value","trim","slice","pct","named","taxCents","round","providerLabel","quoteTaxBasisKey","JSON","stringify","quoteTaxBasisFromKey","key","length","parse","text","trimmed","cents","number","quotePageAddress","address","view","name","line1","line2","city","state","postalCode","country","Object","values","some","Boolean","quotePageStatus","status","discountLabel","discount","paidAt","stamped","paidAtMs","event","timeline","find","atMs","buildQuotePageView","input","lines","lineItems","unpaid","payTax","charge","quoteCheckoutCharge","orderId","totals","itemsCents","discountCents","shippingCents","totalCents","approvalRequired","taxAtPayment","refused","payLinkRefusalWithPayments","quotePayRefusal","paymentsReady","storeName","dateMs","updatedAtMs","createdAtMs","currency","customerName","customer","company","billTo","quotePageLines","taxLabel","shippingAtPayment","notes","terms","statusLabel","receiptUrl","payable","notPayableMessage","payLinkPaymentsUnavailableMessage","taxKey","revision","max","proofs","map","proof","id","contentType","size","inline","response","pageResponse","respondable","channel","line","included","quantity","unitAmountCents","variantLabel","description","sku","amountCents","latest","action","comment","files","LINE_DESCRIPTION_MAX","lineSummary","parts","summary","join","feeProductTypeOf","charged","types","productType","payLinkCheckoutCharge","shipping","amounts","groups","taxable","members","index","net","netCents","taxExempt","reduce","sum","group","taxableCents","taxPct","push","goodsCents","feeProductType","quotePayRefusalMessage","business","quotePaymentDisposition","payment","recorded","sessionId","same","checkoutSessionId","paymentIntentId","sentVersion","sentEdit","quoteUpdatedAtMs","quoteUnmatchedPayment","facts","amountTotalCents","quoteUnmatchedPaymentDetail","noun","amount","toFixed","paidQuoteOrder","feeCents","shippingAddress","paid","customerEmail","email","phone","customerPhone","record","customerRecord","billingAddress","taxMode","undefined","taxBasis"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,wCAAuC;AAE7E,SACEC,gBAAgB,EAChBC,iBAAiB,QAKZ,uBAAmB;AAC1B,SACEC,kBAAkB,EAClBC,gBAAgB,EAChBC,iBAAiB,EACjBC,gBAAgB,EAChBC,6BAA6B,EAC7BC,yBAAyB,QAOpB,uBAAmB;AAC1B,SAASC,kBAAkB,EAAEC,mBAAmB,EAAEC,mBAAmB,QAAQ,6BAAyB;AAEtG,SAASC,qBAAqB,QAAgC,6BAAyB;AACvF,SAASC,wBAAwB,EAAEC,oBAAo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;YACAnD;YACAuJ,UAAUhM,KAAKyH,GAAG,CAAC,GAAGpE,MAAMoI,MAAMO,QAAQ;YAC1CnG;QACF;QACA6G,SAASjB,MAAMiB,OAAO;QACtBtB,eAAe,GAAEK,yBAAAA,MAAML,eAAe,YAArBK,yBAAyBkB;QAC1CxB,mBAAmBM,MAAMR,SAAS;QAClCpG,UAAUhG,iBAAiByB,OAAO,QAAQ,GAAG6B,MAAM,0BAA0B,CAAC,EAAEsJ,MAAM9G,QAAQ;QAC9F7E,OAAO,aAAKA,OAAW2L,MAAMmB,QAAQ,GAAG;YAAE3L,KAAKwK,MAAMmB,QAAQ;QAAC,IAAI,CAAC;YAAIjI,UAAU8G,MAAM9G,QAAQ;;QAC/F,4DAA4D;QAC5D2B,aAAamF,MAAM9G,QAAQ;;IAE7B,IAAI,CAACuH,KAAKd,eAAe,EAAE,OAAOc,KAAKd,eAAe;IACtD,OAAOzL,oBAAoB6F,SAAS0G;AACtC"}
|
|
@@ -63,6 +63,10 @@ export declare const POS_MAX_MODIFIER_OPTIONS = 20;
|
|
|
63
63
|
export declare const POS_MAX_MODIFIER_PRICE_CENTS = 100000;
|
|
64
64
|
/** Why a product's modifier groups cannot be saved, or null when they can. */
|
|
65
65
|
export declare function modifierGroupsProblem(groups: unknown): string | null;
|
|
66
|
+
/** How a variant is named in a choice's price list, in the editor and in an import file. */
|
|
67
|
+
export declare function variantPriceLabel(variant: {
|
|
68
|
+
options?: Record<string, string>;
|
|
69
|
+
}): string;
|
|
66
70
|
/** The product's groups, or none when they are missing or malformed. */
|
|
67
71
|
export declare function productModifierGroups(product: {
|
|
68
72
|
modifierGroups?: unknown;
|
|
@@ -88,6 +88,11 @@ function modifierPriceIsValid(price) {
|
|
|
88
88
|
}
|
|
89
89
|
return null;
|
|
90
90
|
}
|
|
91
|
+
/** How a variant is named in a choice's price list, in the editor and in an import file. */ export function variantPriceLabel(variant) {
|
|
92
|
+
var _variant_options;
|
|
93
|
+
const values = Object.values((_variant_options = variant.options) != null ? _variant_options : {}).filter(Boolean);
|
|
94
|
+
return values.length ? values.join(' / ') : 'Default';
|
|
95
|
+
}
|
|
91
96
|
/** The product's groups, or none when they are missing or malformed. */ export function productModifierGroups(product) {
|
|
92
97
|
const groups = product == null ? void 0 : product.modifierGroups;
|
|
93
98
|
if (!Array.isArray(groups) || modifierGroupsProblem(groups)) return [];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/product-modifiers.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\n/*==========================================\n * REGISTER MODIFIERS AND QUICK KEYS (AGL-3607).\n *\n * A modifier is a choice added to an item as it is rung up — \"Oat milk\",\n * \"Extra shot +$0.75\", \"No onions\" — that is not a stocked variant. Groups\n * live on the product (`modifierGroups`); the register sends the chosen\n * option ids with each line and the SERVER prices them from the product\n * document, so a register never names what a modifier costs.\n *\n * A chosen modifier is folded into the line's `variantLabel` as well as kept\n * structured in `modifiers`: every receipt, email, order view and export\n * already prints the label, so the choice reaches all of them without each\n * learning a new field.\n *\n * ADD-ONS ON THE WEBSITE (AGL-4100). A group switched to \"Show on the\n * website\" (`online`) is offered on the product's page too, and a cart line,\n * Buy now and the order carry its picks the same way: ids from the shopper,\n * prices from the product. A choice may cost more on one variant than\n * another (`priceCentsByVariant`), which is how one page sells a canopy whose\n * walls cost more at a larger size without a variant for every combination.\n *=========================================*/\n\n/** One choice in a modifier group. `priceCents` is added to the item, 0 for free. */\nexport interface ProductModifierOption {\n id: string\n name: string\n priceCents: number\n /**\n * What the choice adds on one variant, keyed by variant id (AGL-4100):\n * walls cost more on a larger canopy. A variant not listed pays\n * `priceCents`. Read through {@link modifierOptionPriceCents}.\n */\n priceCentsByVariant?: Record<string, number>\n}\n\n/**\n * A set of choices offered together (\"Milk\", \"Add-ons\"). `min` of 1 or more\n * makes it required; `max` caps how many can be picked (1 = pick one).\n */\nexport interface ProductModifierGroup {\n id: string\n name: string\n min: number\n max: number\n options: ProductModifierOption[]\n /**\n * Offered on the product's page on the website as well as at the register\n * (AGL-4100), \"Show on the website\". Absent reads as register only, so a\n * group made before the switch changes nothing on a live store; the\n * console makes new groups with it on.\n */\n online?: boolean\n}\n\n/** A modifier as the order line keeps it: names and price as sold. */\nexport interface OrderLineModifier {\n groupId: string\n optionId: string\n group: string\n name: string\n priceCents: number\n}\n\n/** What the register sends for a line: the option ids it picked, nothing priced. */\nexport interface ModifierSelection {\n groupId: string\n optionId: string\n}\n\nexport const POS_MAX_MODIFIER_GROUPS = 10\nexport const POS_MAX_MODIFIER_OPTIONS = 20\n/** $1,000 on one modifier: anything larger is a product, not an add-on. */\nexport const POS_MAX_MODIFIER_PRICE_CENTS = 100_000\n\nfunction modifierPriceIsValid(price: unknown): boolean {\n return (\n typeof price === 'number' &&\n Number.isInteger(price) &&\n price >= 0 &&\n price <= POS_MAX_MODIFIER_PRICE_CENTS\n )\n}\n\n/** Why a product's modifier groups cannot be saved, or null when they can. */\nexport function modifierGroupsProblem(groups: unknown): string | null {\n if (groups == null) return null\n if (!Array.isArray(groups)) return 'Modifiers must be a list'\n if (groups.length > POS_MAX_MODIFIER_GROUPS) {\n return `At most ${POS_MAX_MODIFIER_GROUPS} modifier groups per product`\n }\n const groupIds = new Set<string>()\n for (const group of groups as ProductModifierGroup[]) {\n if (!group?.id || groupIds.has(group.id)) return 'Modifier groups need unique ids'\n groupIds.add(group.id)\n if (!String(group.name ?? '').trim()) return 'Name every modifier group'\n const options = Array.isArray(group.options) ? group.options : []\n if (options.length === 0) return `Add a choice to “${group.name}”`\n if (options.length > POS_MAX_MODIFIER_OPTIONS) {\n return `“${group.name}” has more than ${POS_MAX_MODIFIER_OPTIONS} choices`\n }\n const optionIds = new Set<string>()\n for (const option of options) {\n if (!option?.id || optionIds.has(option.id)) return 'Modifier choices need unique ids'\n optionIds.add(option.id)\n if (!String(option.name ?? '').trim()) return `Name every choice in “${group.name}”`\n const price = option.priceCents\n if (!modifierPriceIsValid(price)) {\n return `“${option.name}” needs a price of $0 to $1,000`\n }\n const byVariant = option.priceCentsByVariant\n if (byVariant != null) {\n if (typeof byVariant !== 'object' || Array.isArray(byVariant)) {\n return `“${option.name}” has prices that are not a list by option`\n }\n if (Object.values(byVariant).some((cents) => !modifierPriceIsValid(cents))) {\n return `“${option.name}” needs a price of $0 to $1,000 for each option it is priced by`\n }\n }\n }\n if (group.online != null && typeof group.online !== 'boolean') {\n return `“${group.name}” is shown on the website or not`\n }\n const { min, max } = group\n if (!Number.isInteger(min) || min < 0) return `“${group.name}” needs a minimum of 0 or more`\n if (!Number.isInteger(max) || max < 1 || max > options.length) {\n return `“${group.name}” allows 1 to ${options.length} choices`\n }\n if (min > max) return `“${group.name}” requires more choices than it allows`\n }\n return null\n}\n\n/** The product's groups, or none when they are missing or malformed. */\nexport function productModifierGroups(product: {\n modifierGroups?: unknown\n}): ProductModifierGroup[] {\n const groups = product?.modifierGroups\n if (!Array.isArray(groups) || modifierGroupsProblem(groups)) return []\n return groups as ProductModifierGroup[]\n}\n\n/** Whether a group must be answered before the item can be added. */\nexport function modifierGroupRequired(group: ProductModifierGroup): boolean {\n return group.min > 0\n}\n\n/**\n * The groups the product's page on the website offers (AGL-4100): those\n * switched to \"Show on the website\". A register-only group is never sent to\n * a shopper, never asked of one and never priced on an online order.\n */\nexport function websiteModifierGroups(product: { modifierGroups?: unknown }): ProductModifierGroup[] {\n return productModifierGroups(product).filter((group) => group.online === true)\n}\n\n/** Whether the website must ask a shopper a choice before the item goes in a cart. */\nexport function websiteModifiersRequired(product: { modifierGroups?: unknown }): boolean {\n return websiteModifierGroups(product).some(modifierGroupRequired)\n}\n\n/**\n * What one choice adds to one unit of the picked variant (AGL-4100): its\n * price on that variant where it has one, else its own price.\n */\nexport function modifierOptionPriceCents(\n option: Pick<ProductModifierOption, 'priceCents' | 'priceCentsByVariant'>,\n variantId?: string | null,\n): number {\n const byVariant = variantId ? option.priceCentsByVariant?.[variantId] : undefined\n return typeof byVariant === 'number' && Number.isFinite(byVariant) ? byVariant : option.priceCents\n}\n\n/** A line's chosen modifiers, priced. */\nexport interface ResolvedLineModifiers {\n ok: boolean\n /** The chosen modifiers, in group order; empty when not `ok`. */\n modifiers: OrderLineModifier[]\n /** What they add to one unit, in cents. */\n extraCents: number\n /** What to fix, when not `ok`. */\n error?: string\n}\n\n/** The picks a request names, as ids only, bounded; nothing for a value that is not a list. */\nexport function modifierSelectionFrom(raw: unknown): ModifierSelection[] {\n return (Array.isArray(raw) ? raw : [])\n .slice(0, POS_MAX_MODIFIER_GROUPS * POS_MAX_MODIFIER_OPTIONS)\n .map((entry: any) => ({\n groupId: String(entry?.groupId ?? ''),\n optionId: String(entry?.optionId ?? ''),\n }))\n}\n\n/**\n * Prices a line's chosen modifiers from the PRODUCT, in group order, and\n * checks every group's minimum and maximum. Unknown ids, a repeated choice\n * and a group answered past its maximum are refused with what to fix.\n *\n * `variantId` is the variant the line sells (AGL-4100): a choice priced by\n * variant adds its price on that one. Without it every choice adds its own\n * `priceCents`, as it always did.\n */\nexport function resolveLineModifiers(\n product: { name?: string; modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): ResolvedLineModifiers {\n const refuse = (error: string): ResolvedLineModifiers => ({\n ok: false,\n modifiers: [],\n extraCents: 0,\n error,\n })\n const groups = productModifierGroups(product)\n const picks = modifierSelectionFrom(raw)\n const seen = new Set<string>()\n for (const pick of picks) {\n const key = `${pick.groupId}:${pick.optionId}`\n if (seen.has(key)) return refuse(`A choice on ${product.name} was picked twice.`)\n seen.add(key)\n const group = groups.find((entry) => entry.id === pick.groupId)\n if (!group || !group.options.some((option) => option.id === pick.optionId)) {\n return refuse(`A choice on ${product.name} is no longer offered. Remove it and add it again.`)\n }\n }\n const modifiers: OrderLineModifier[] = []\n for (const group of groups) {\n const chosen = group.options.filter((option) =>\n picks.some((pick) => pick.groupId === group.id && pick.optionId === option.id),\n )\n if (chosen.length < group.min) {\n return refuse(`Choose ${group.name.toLowerCase()} for ${product.name}.`)\n }\n if (chosen.length > group.max) {\n return refuse(`Choose at most ${group.max} for ${group.name.toLowerCase()} on ${product.name}.`)\n }\n for (const option of chosen) {\n modifiers.push({\n groupId: group.id,\n optionId: option.id,\n group: group.name,\n name: option.name,\n priceCents: modifierOptionPriceCents(option, variantId),\n })\n }\n }\n return {\n ok: true,\n modifiers,\n extraCents: modifiers.reduce((sum, modifier) => sum + modifier.priceCents, 0),\n }\n}\n\n/**\n * {@link resolveLineModifiers} for a sale made online (AGL-4100): only the\n * groups shown on the website are offered, asked or priced. A register-only\n * group, required or not, is not the shopper's to answer.\n */\nexport function resolveWebsiteLineModifiers(\n product: { name?: string; modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): ResolvedLineModifiers {\n return resolveLineModifiers(\n { name: product.name, modifierGroups: websiteModifierGroups(product) },\n raw,\n variantId,\n )\n}\n\n/**\n * The modifiers a PAID line names, for its order record (AGL-4100): every\n * pick the product still offers, in group order, priced as it is now, with no\n * minimum or maximum asked. The money was taken when the sale was priced;\n * a choice the merchant removed since is left off the record, never a reason\n * to lose the order.\n */\nexport function soldLineModifiers(\n product: { modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): OrderLineModifier[] {\n const picks = modifierSelectionFrom(raw)\n const modifiers: OrderLineModifier[] = []\n for (const group of productModifierGroups(product)) {\n for (const option of group.options) {\n if (picks.some((pick) => pick.groupId === group.id && pick.optionId === option.id)) {\n modifiers.push({\n groupId: group.id,\n optionId: option.id,\n group: group.name,\n name: option.name,\n priceCents: modifierOptionPriceCents(option, variantId),\n })\n }\n }\n }\n return modifiers\n}\n\n/**\n * What a shopper is told about a cart line whose add-ons no longer answer\n * the product (AGL-4100): the resolver's reason, and how to put it right.\n */\nexport function cartLineModifierProblem(error: string | undefined): string {\n const reason = String(error ?? '').trim() || 'The choices on this item have changed.'\n return /Remove it and add it again/.test(reason)\n ? reason\n : `${reason} Remove it and add it again from its page.`\n}\n\n/** The picks a priced line keeps: ids only, in the product's group order. */\nexport function modifierSelectionOf(\n modifiers: readonly Pick<OrderLineModifier, 'groupId' | 'optionId'>[],\n): ModifierSelection[] {\n return modifiers.map((modifier) => ({ groupId: modifier.groupId, optionId: modifier.optionId }))\n}\n\n/**\n * The picks as one metadata value (AGL-4100), for a payment processor that\n * holds strings only: `[[\"group\",\"option\"],…]`. Empty for no picks.\n */\nexport function encodeModifierSelection(selection: readonly ModifierSelection[] | undefined): string {\n if (!selection?.length) return ''\n return JSON.stringify(selection.map((pick) => [pick.groupId, pick.optionId]))\n}\n\n/** {@link encodeModifierSelection} read back; nothing for a value it did not write. */\nexport function decodeModifierSelection(value: unknown): ModifierSelection[] {\n if (typeof value !== 'string' || !value) return []\n try {\n const parsed: unknown = JSON.parse(value)\n if (!Array.isArray(parsed)) return []\n return parsed\n .filter(\n (pair): pair is [string, string] =>\n Array.isArray(pair) && typeof pair[0] === 'string' && typeof pair[1] === 'string',\n )\n .slice(0, POS_MAX_MODIFIER_GROUPS * POS_MAX_MODIFIER_OPTIONS)\n .map(([groupId, optionId]) => ({ groupId, optionId }))\n } catch {\n return []\n }\n}\n\n/** The label a line prints: the variant, then each modifier (`Large / Oat milk, Extra shot`). */\nexport function lineLabelWithModifiers(\n variantLabel: string | undefined,\n modifiers: readonly Pick<OrderLineModifier, 'name'>[],\n): string {\n const added = modifiers.map((modifier) => modifier.name).join(', ')\n return [variantLabel, added].filter(Boolean).join(' / ')\n}\n\n/** Two lines merge only when they are the same item with the same choices. */\nexport function modifierSelectionKey(selection: readonly ModifierSelection[] | undefined): string {\n return [...(selection ?? [])]\n .map((pick) => `${pick.groupId}:${pick.optionId}`)\n .sort()\n .join('|')\n}\n"],"names":["POS_MAX_MODIFIER_GROUPS","POS_MAX_MODIFIER_OPTIONS","POS_MAX_MODIFIER_PRICE_CENTS","modifierPriceIsValid","price","Number","isInteger","modifierGroupsProblem","groups","Array","isArray","length","groupIds","Set","group","id","has","add","String","name","trim","options","optionIds","option","priceCents","byVariant","priceCentsByVariant","Object","values","some","cents","online","min","max","productModifierGroups","product","modifierGroups","modifierGroupRequired","websiteModifierGroups","filter","websiteModifiersRequired","modifierOptionPriceCents","variantId","undefined","isFinite","modifierSelectionFrom","raw","slice","map","entry","groupId","optionId","resolveLineModifiers","refuse","error","ok","modifiers","extraCents","picks","seen","pick","key","find","chosen","toLowerCase","push","reduce","sum","modifier","resolveWebsiteLineModifiers","soldLineModifiers","cartLineModifierProblem","reason","test","modifierSelectionOf","encodeModifierSelection","selection","JSON","stringify","decodeModifierSelection","value","parsed","parse","pair","lineLabelWithModifiers","variantLabel","added","join","Boolean","modifierSelectionKey","sort"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;2CAoB2C,GAE3C,mFAAmF,GA+CnF,OAAO,MAAMA,0BAA0B,GAAE;AACzC,OAAO,MAAMC,2BAA2B,GAAE;AAC1C,yEAAyE,GACzE,OAAO,MAAMC,+BAA+B,OAAO;AAEnD,SAASC,qBAAqBC,KAAc;IAC1C,OACE,OAAOA,UAAU,YACjBC,OAAOC,SAAS,CAACF,UACjBA,SAAS,KACTA,SAASF;AAEb;AAEA,4EAA4E,GAC5E,OAAO,SAASK,sBAAsBC,MAAe;IACnD,IAAIA,UAAU,MAAM,OAAO;IAC3B,IAAI,CAACC,MAAMC,OAAO,CAACF,SAAS,OAAO;IACnC,IAAIA,OAAOG,MAAM,GAAGX,yBAAyB;QAC3C,OAAO,CAAC,QAAQ,EAAEA,wBAAwB,4BAA4B,CAAC;IACzE;IACA,MAAMY,WAAW,IAAIC;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iers.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\n/*==========================================\n * REGISTER MODIFIERS AND QUICK KEYS (AGL-3607).\n *\n * A modifier is a choice added to an item as it is rung up — \"Oat milk\",\n * \"Extra shot +$0.75\", \"No onions\" — that is not a stocked variant. Groups\n * live on the product (`modifierGroups`); the register sends the chosen\n * option ids with each line and the SERVER prices them from the product\n * document, so a register never names what a modifier costs.\n *\n * A chosen modifier is folded into the line's `variantLabel` as well as kept\n * structured in `modifiers`: every receipt, email, order view and export\n * already prints the label, so the choice reaches all of them without each\n * learning a new field.\n *\n * ADD-ONS ON THE WEBSITE (AGL-4100). A group switched to \"Show on the\n * website\" (`online`) is offered on the product's page too, and a cart line,\n * Buy now and the order carry its picks the same way: ids from the shopper,\n * prices from the product. A choice may cost more on one variant than\n * another (`priceCentsByVariant`), which is how one page sells a canopy whose\n * walls cost more at a larger size without a variant for every combination.\n *=========================================*/\n\n/** One choice in a modifier group. `priceCents` is added to the item, 0 for free. */\nexport interface ProductModifierOption {\n id: string\n name: string\n priceCents: number\n /**\n * What the choice adds on one variant, keyed by variant id (AGL-4100):\n * walls cost more on a larger canopy. A variant not listed pays\n * `priceCents`. Read through {@link modifierOptionPriceCents}.\n */\n priceCentsByVariant?: Record<string, number>\n}\n\n/**\n * A set of choices offered together (\"Milk\", \"Add-ons\"). `min` of 1 or more\n * makes it required; `max` caps how many can be picked (1 = pick one).\n */\nexport interface ProductModifierGroup {\n id: string\n name: string\n min: number\n max: number\n options: ProductModifierOption[]\n /**\n * Offered on the product's page on the website as well as at the register\n * (AGL-4100), \"Show on the website\". Absent reads as register only, so a\n * group made before the switch changes nothing on a live store; the\n * console makes new groups with it on.\n */\n online?: boolean\n}\n\n/** A modifier as the order line keeps it: names and price as sold. */\nexport interface OrderLineModifier {\n groupId: string\n optionId: string\n group: string\n name: string\n priceCents: number\n}\n\n/** What the register sends for a line: the option ids it picked, nothing priced. */\nexport interface ModifierSelection {\n groupId: string\n optionId: string\n}\n\nexport const POS_MAX_MODIFIER_GROUPS = 10\nexport const POS_MAX_MODIFIER_OPTIONS = 20\n/** $1,000 on one modifier: anything larger is a product, not an add-on. */\nexport const POS_MAX_MODIFIER_PRICE_CENTS = 100_000\n\nfunction modifierPriceIsValid(price: unknown): boolean {\n return (\n typeof price === 'number' &&\n Number.isInteger(price) &&\n price >= 0 &&\n price <= POS_MAX_MODIFIER_PRICE_CENTS\n )\n}\n\n/** Why a product's modifier groups cannot be saved, or null when they can. */\nexport function modifierGroupsProblem(groups: unknown): string | null {\n if (groups == null) return null\n if (!Array.isArray(groups)) return 'Modifiers must be a list'\n if (groups.length > POS_MAX_MODIFIER_GROUPS) {\n return `At most ${POS_MAX_MODIFIER_GROUPS} modifier groups per product`\n }\n const groupIds = new Set<string>()\n for (const group of groups as ProductModifierGroup[]) {\n if (!group?.id || groupIds.has(group.id)) return 'Modifier groups need unique ids'\n groupIds.add(group.id)\n if (!String(group.name ?? '').trim()) return 'Name every modifier group'\n const options = Array.isArray(group.options) ? group.options : []\n if (options.length === 0) return `Add a choice to “${group.name}”`\n if (options.length > POS_MAX_MODIFIER_OPTIONS) {\n return `“${group.name}” has more than ${POS_MAX_MODIFIER_OPTIONS} choices`\n }\n const optionIds = new Set<string>()\n for (const option of options) {\n if (!option?.id || optionIds.has(option.id)) return 'Modifier choices need unique ids'\n optionIds.add(option.id)\n if (!String(option.name ?? '').trim()) return `Name every choice in “${group.name}”`\n const price = option.priceCents\n if (!modifierPriceIsValid(price)) {\n return `“${option.name}” needs a price of $0 to $1,000`\n }\n const byVariant = option.priceCentsByVariant\n if (byVariant != null) {\n if (typeof byVariant !== 'object' || Array.isArray(byVariant)) {\n return `“${option.name}” has prices that are not a list by option`\n }\n if (Object.values(byVariant).some((cents) => !modifierPriceIsValid(cents))) {\n return `“${option.name}” needs a price of $0 to $1,000 for each option it is priced by`\n }\n }\n }\n if (group.online != null && typeof group.online !== 'boolean') {\n return `“${group.name}” is shown on the website or not`\n }\n const { min, max } = group\n if (!Number.isInteger(min) || min < 0) return `“${group.name}” needs a minimum of 0 or more`\n if (!Number.isInteger(max) || max < 1 || max > options.length) {\n return `“${group.name}” allows 1 to ${options.length} choices`\n }\n if (min > max) return `“${group.name}” requires more choices than it allows`\n }\n return null\n}\n\n/** How a variant is named in a choice's price list, in the editor and in an import file. */\nexport function variantPriceLabel(variant: { options?: Record<string, string> }): string {\n const values = Object.values(variant.options ?? {}).filter(Boolean)\n return values.length ? values.join(' / ') : 'Default'\n}\n\n/** The product's groups, or none when they are missing or malformed. */\nexport function productModifierGroups(product: {\n modifierGroups?: unknown\n}): ProductModifierGroup[] {\n const groups = product?.modifierGroups\n if (!Array.isArray(groups) || modifierGroupsProblem(groups)) return []\n return groups as ProductModifierGroup[]\n}\n\n/** Whether a group must be answered before the item can be added. */\nexport function modifierGroupRequired(group: ProductModifierGroup): boolean {\n return group.min > 0\n}\n\n/**\n * The groups the product's page on the website offers (AGL-4100): those\n * switched to \"Show on the website\". A register-only group is never sent to\n * a shopper, never asked of one and never priced on an online order.\n */\nexport function websiteModifierGroups(product: { modifierGroups?: unknown }): ProductModifierGroup[] {\n return productModifierGroups(product).filter((group) => group.online === true)\n}\n\n/** Whether the website must ask a shopper a choice before the item goes in a cart. */\nexport function websiteModifiersRequired(product: { modifierGroups?: unknown }): boolean {\n return websiteModifierGroups(product).some(modifierGroupRequired)\n}\n\n/**\n * What one choice adds to one unit of the picked variant (AGL-4100): its\n * price on that variant where it has one, else its own price.\n */\nexport function modifierOptionPriceCents(\n option: Pick<ProductModifierOption, 'priceCents' | 'priceCentsByVariant'>,\n variantId?: string | null,\n): number {\n const byVariant = variantId ? option.priceCentsByVariant?.[variantId] : undefined\n return typeof byVariant === 'number' && Number.isFinite(byVariant) ? byVariant : option.priceCents\n}\n\n/** A line's chosen modifiers, priced. */\nexport interface ResolvedLineModifiers {\n ok: boolean\n /** The chosen modifiers, in group order; empty when not `ok`. */\n modifiers: OrderLineModifier[]\n /** What they add to one unit, in cents. */\n extraCents: number\n /** What to fix, when not `ok`. */\n error?: string\n}\n\n/** The picks a request names, as ids only, bounded; nothing for a value that is not a list. */\nexport function modifierSelectionFrom(raw: unknown): ModifierSelection[] {\n return (Array.isArray(raw) ? raw : [])\n .slice(0, POS_MAX_MODIFIER_GROUPS * POS_MAX_MODIFIER_OPTIONS)\n .map((entry: any) => ({\n groupId: String(entry?.groupId ?? ''),\n optionId: String(entry?.optionId ?? ''),\n }))\n}\n\n/**\n * Prices a line's chosen modifiers from the PRODUCT, in group order, and\n * checks every group's minimum and maximum. Unknown ids, a repeated choice\n * and a group answered past its maximum are refused with what to fix.\n *\n * `variantId` is the variant the line sells (AGL-4100): a choice priced by\n * variant adds its price on that one. Without it every choice adds its own\n * `priceCents`, as it always did.\n */\nexport function resolveLineModifiers(\n product: { name?: string; modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): ResolvedLineModifiers {\n const refuse = (error: string): ResolvedLineModifiers => ({\n ok: false,\n modifiers: [],\n extraCents: 0,\n error,\n })\n const groups = productModifierGroups(product)\n const picks = modifierSelectionFrom(raw)\n const seen = new Set<string>()\n for (const pick of picks) {\n const key = `${pick.groupId}:${pick.optionId}`\n if (seen.has(key)) return refuse(`A choice on ${product.name} was picked twice.`)\n seen.add(key)\n const group = groups.find((entry) => entry.id === pick.groupId)\n if (!group || !group.options.some((option) => option.id === pick.optionId)) {\n return refuse(`A choice on ${product.name} is no longer offered. Remove it and add it again.`)\n }\n }\n const modifiers: OrderLineModifier[] = []\n for (const group of groups) {\n const chosen = group.options.filter((option) =>\n picks.some((pick) => pick.groupId === group.id && pick.optionId === option.id),\n )\n if (chosen.length < group.min) {\n return refuse(`Choose ${group.name.toLowerCase()} for ${product.name}.`)\n }\n if (chosen.length > group.max) {\n return refuse(`Choose at most ${group.max} for ${group.name.toLowerCase()} on ${product.name}.`)\n }\n for (const option of chosen) {\n modifiers.push({\n groupId: group.id,\n optionId: option.id,\n group: group.name,\n name: option.name,\n priceCents: modifierOptionPriceCents(option, variantId),\n })\n }\n }\n return {\n ok: true,\n modifiers,\n extraCents: modifiers.reduce((sum, modifier) => sum + modifier.priceCents, 0),\n }\n}\n\n/**\n * {@link resolveLineModifiers} for a sale made online (AGL-4100): only the\n * groups shown on the website are offered, asked or priced. A register-only\n * group, required or not, is not the shopper's to answer.\n */\nexport function resolveWebsiteLineModifiers(\n product: { name?: string; modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): ResolvedLineModifiers {\n return resolveLineModifiers(\n { name: product.name, modifierGroups: websiteModifierGroups(product) },\n raw,\n variantId,\n )\n}\n\n/**\n * The modifiers a PAID line names, for its order record (AGL-4100): every\n * pick the product still offers, in group order, priced as it is now, with no\n * minimum or maximum asked. The money was taken when the sale was priced;\n * a choice the merchant removed since is left off the record, never a reason\n * to lose the order.\n */\nexport function soldLineModifiers(\n product: { modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): OrderLineModifier[] {\n const picks = modifierSelectionFrom(raw)\n const modifiers: OrderLineModifier[] = []\n for (const group of productModifierGroups(product)) {\n for (const option of group.options) {\n if (picks.some((pick) => pick.groupId === group.id && pick.optionId === option.id)) {\n modifiers.push({\n groupId: group.id,\n optionId: option.id,\n group: group.name,\n name: option.name,\n priceCents: modifierOptionPriceCents(option, variantId),\n })\n }\n }\n }\n return modifiers\n}\n\n/**\n * What a shopper is told about a cart line whose add-ons no longer answer\n * the product (AGL-4100): the resolver's reason, and how to put it right.\n */\nexport function cartLineModifierProblem(error: string | undefined): string {\n const reason = String(error ?? '').trim() || 'The choices on this item have changed.'\n return /Remove it and add it again/.test(reason)\n ? reason\n : `${reason} Remove it and add it again from its page.`\n}\n\n/** The picks a priced line keeps: ids only, in the product's group order. */\nexport function modifierSelectionOf(\n modifiers: readonly Pick<OrderLineModifier, 'groupId' | 'optionId'>[],\n): ModifierSelection[] {\n return modifiers.map((modifier) => ({ groupId: modifier.groupId, optionId: modifier.optionId }))\n}\n\n/**\n * The picks as one metadata value (AGL-4100), for a payment processor that\n * holds strings only: `[[\"group\",\"option\"],…]`. Empty for no picks.\n */\nexport function encodeModifierSelection(selection: readonly ModifierSelection[] | undefined): string {\n if (!selection?.length) return ''\n return JSON.stringify(selection.map((pick) => [pick.groupId, pick.optionId]))\n}\n\n/** {@link encodeModifierSelection} read back; nothing for a value it did not write. */\nexport function decodeModifierSelection(value: unknown): ModifierSelection[] {\n if (typeof value !== 'string' || !value) return []\n try {\n const parsed: unknown = JSON.parse(value)\n if (!Array.isArray(parsed)) return []\n return parsed\n .filter(\n (pair): pair is [string, string] =>\n Array.isArray(pair) && typeof pair[0] === 'string' && typeof pair[1] === 'string',\n )\n .slice(0, POS_MAX_MODIFIER_GROUPS * POS_MAX_MODIFIER_OPTIONS)\n .map(([groupId, optionId]) => ({ groupId, optionId }))\n } catch {\n return []\n }\n}\n\n/** The label a line prints: the variant, then each modifier (`Large / Oat milk, Extra shot`). */\nexport function lineLabelWithModifiers(\n variantLabel: string | undefined,\n modifiers: readonly Pick<OrderLineModifier, 'name'>[],\n): string {\n const added = modifiers.map((modifier) => modifier.name).join(', ')\n return [variantLabel, added].filter(Boolean).join(' / ')\n}\n\n/** Two lines merge only when they are the same item with the same choices. */\nexport function modifierSelectionKey(selection: readonly ModifierSelection[] | undefined): string {\n return [...(selection ?? [])]\n .map((pick) => `${pick.groupId}:${pick.optionId}`)\n .sort()\n .join('|')\n}\n"],"names":["POS_MAX_MODIFIER_GROUPS","POS_MAX_MODIFIER_OPTIONS","POS_MAX_MODIFIER_PRICE_CENTS","modifierPriceIsValid","price","Number","isInteger","modifierGroupsProblem","groups","Array","isArray","length","groupIds","Set","group","id","has","add","String","name","trim","options","optionIds","option","priceCents","byVariant","priceCentsByVariant","Object","values","some","cents","online","min","max","variantPriceLabel","variant","filter","Boolean","join","productModifierGroups","product","modifierGroups","modifierGroupRequired","websiteModifierGroups","websiteModifiersRequired","modifierOptionPriceCents","variantId","undefined","isFinite","modifierSelectionFrom","raw","slice","map","entry","groupId","optionId","resolveLineModifiers","refuse","error","ok","modifiers","extraCents","picks","seen","pick","key","find","chosen","toLowerCase","push","reduce","sum","modifier","resolveWebsiteLineModifiers","soldLineModifiers","cartLineModifierProblem","reason","test","modifierSelectionOf","encodeModifierSelection","selection","JSON","stringify","decodeModifierSelection","value","parsed","parse","pair","lineLabelWithModifiers","variantLabel","added","modifierSelectionKey","sort"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;2CAoB2C,GAE3C,mFAAmF,GA+CnF,OAAO,MAAMA,0BAA0B,GAAE;AACzC,OAAO,MAAMC,2BAA2B,GAAE;AAC1C,yEAAyE,GACzE,OAAO,MAAMC,+BAA+B,OAAO;AAEnD,SAASC,qBAAqBC,KAAc;IAC1C,OACE,OAAOA,UAAU,YACjBC,OAAOC,SAAS,CAACF,UACjBA,SAAS,KACTA,SAASF;AAEb;AAEA,4EAA4E,GAC5E,OAAO,SAASK,sBAAsBC,MAAe;IACnD,IAAIA,UAAU,MAAM,OAAO;IAC3B,IAAI,CAACC,MAAMC,OAAO,CAACF,SAAS,OAAO;IACnC,IAAIA,OAAOG,MAAM,GAAGX,yBAAyB;QAC3C,OAAO,CAAC,QAAQ,EAAEA,wBAAwB,4BAA4B,CAAC;IACzE;IACA,MAAMY,WAAW,IAAIC;IACrB,KAAK,MAAMC,SAASN,OAAkC;YAGxCM;QAFZ,IAAI,EAACA,yBAAAA,MAAOC,EAAE,KAAIH,SAASI,GAAG,CAACF,MAAMC,EAAE,GAAG,OAAO;QACjDH,SAASK,GAAG,CA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V"}
|
|
@@ -3660,7 +3660,7 @@ async function findOrderForDispute(paymentIntentId) {
|
|
|
3660
3660
|
// and the business is told, as a paid-after-cancel payment is.
|
|
3661
3661
|
if (raw && CommerceModel.isQuote(raw) && raw.quote) {
|
|
3662
3662
|
var _ref7, _ref8, _ref9, _ref10, _ref11, _ref12, _ref13, _ref14;
|
|
3663
|
-
var _object_metadata2, _object_metadata3, _object_customer_details2, _object_customer_details3, _object_metadata4, _object_metadata5;
|
|
3663
|
+
var _object_metadata2, _object_metadata3, _object_customer_details2, _object_customer_details3, _object_metadata4, _object_metadata5, _object_metadata6;
|
|
3664
3664
|
const facts = {
|
|
3665
3665
|
sessionId: String((_ref7 = object == null ? void 0 : object.id) != null ? _ref7 : ''),
|
|
3666
3666
|
paymentIntentId: String((_ref8 = object == null ? void 0 : object.payment_intent) != null ? _ref8 : '') || null,
|
|
@@ -3674,6 +3674,9 @@ async function findOrderForDispute(paymentIntentId) {
|
|
|
3674
3674
|
taxCents: stripeTaxCents,
|
|
3675
3675
|
feeCents: Number((_ref13 = object == null ? void 0 : (_object_metadata4 = object.metadata) == null ? void 0 : _object_metadata4.feeCents) != null ? _ref13 : 0) || 0,
|
|
3676
3676
|
taxMode: storefrontTaxModeOf(object, Number((_ref14 = object == null ? void 0 : (_object_metadata5 = object.metadata) == null ? void 0 : _object_metadata5.taxCents) != null ? _ref14 : 0)),
|
|
3677
|
+
// The basis Pay charged a quote saved before the store chose its
|
|
3678
|
+
// sales tax under (AGL-4162); absent, the quote's own stands.
|
|
3679
|
+
taxBasis: CommerceModel.quoteTaxBasisFromKey(object == null ? void 0 : (_object_metadata6 = object.metadata) == null ? void 0 : _object_metadata6.quoteTax),
|
|
3677
3680
|
shippingAddress: (shipTo == null ? void 0 : shipTo.address) ? Object.fromEntries(Object.entries({
|
|
3678
3681
|
name: shipTo.name,
|
|
3679
3682
|
line1: shipTo.address.line1,
|