@aglyn/plugins-commerce 1.12.0 → 1.13.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/catalog-organization-card.component.js +1 -1
- package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
- package/src/lib/components/console/host-quotes-card.component.js +3 -2
- package/src/lib/components/console/host-quotes-card.component.js.map +1 -1
- package/src/lib/components/console/order-detail-dialog.component.js +1 -1
- package/src/lib/components/console/order-detail-dialog.component.js.map +1 -1
- package/src/lib/components/console/pay-link-readiness-notice.component.d.ts +1 -1
- package/src/lib/components/console/pay-link-readiness-notice.component.js.map +1 -1
- package/src/lib/components/console/pos-devices-card.component.js +2 -2
- package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
- package/src/lib/components/console/pos-ops/pos-check-ins-card.component.js +1 -1
- package/src/lib/components/console/pos-ops/pos-check-ins-card.component.js.map +1 -1
- package/src/lib/components/console/pos-ops/pos-day-totals-card.component.js +1 -1
- package/src/lib/components/console/pos-ops/pos-day-totals-card.component.js.map +1 -1
- package/src/lib/components/console/pos-reader-splash-setting.component.js +1 -1
- package/src/lib/components/console/pos-reader-splash-setting.component.js.map +1 -1
- package/src/lib/components/console/quote-editor-dialog.component.d.ts +5 -0
- package/src/lib/components/console/quote-editor-dialog.component.js +104 -16
- package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/quote-pay-link.component.d.ts +4 -1
- package/src/lib/components/console/quote-pay-link.component.js +23 -12
- package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
- package/src/lib/components/console/quote-proofs.component.d.ts +3 -2
- package/src/lib/components/console/quote-proofs.component.js +73 -5
- package/src/lib/components/console/quote-proofs.component.js.map +1 -1
- package/src/lib/components/console/quote-send.component.js +9 -6
- package/src/lib/components/console/quote-send.component.js.map +1 -1
- package/src/lib/components/console/site-member-purchases.component.js +1 -1
- package/src/lib/components/console/site-member-purchases.component.js.map +1 -1
- package/src/lib/components/quote-page-body.js +14 -8
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/model/commerce-invoices.d.ts +1 -1
- package/src/lib/model/commerce-invoices.js +4 -1
- package/src/lib/model/commerce-invoices.js.map +1 -1
- package/src/lib/model/commerce-quote-email.d.ts +7 -6
- package/src/lib/model/commerce-quote-email.js +11 -6
- package/src/lib/model/commerce-quote-email.js.map +1 -1
- package/src/lib/model/commerce-quote-pay.d.ts +6 -1
- package/src/lib/model/commerce-quote-pay.js +18 -8
- package/src/lib/model/commerce-quote-pay.js.map +1 -1
- package/src/lib/model/commerce-quote-proofs.d.ts +28 -1
- package/src/lib/model/commerce-quote-proofs.js +58 -2
- package/src/lib/model/commerce-quote-proofs.js.map +1 -1
- package/src/lib/model/commerce-quotes.d.ts +22 -1
- package/src/lib/model/commerce-quotes.js +25 -5
- package/src/lib/model/commerce-quotes.js.map +1 -1
- package/src/lib/model/plugin-permissions.d.ts +1 -1
- package/src/lib/model/plugin-permissions.js +10 -0
- package/src/lib/model/plugin-permissions.js.map +1 -1
- package/src/lib/server/commerce-pdf.d.ts +1 -1
- package/src/lib/server/commerce-pdf.js +1 -1
- package/src/lib/server/commerce-pdf.js.map +1 -1
- package/src/lib/server/paid-media-delivery.js +1 -1
- package/src/lib/server/paid-media-delivery.js.map +1 -1
- package/src/lib/server/quote-email.js +29 -25
- package/src/lib/server/quote-email.js.map +1 -1
- package/src/lib/server/quote-pay.js +6 -2
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote-proof-media.d.ts +63 -0
- package/src/lib/server/quote-proof-media.js +96 -0
- package/src/lib/server/quote-proof-media.js.map +1 -0
- package/src/lib/server/quote-proofs.js +9 -5
- package/src/lib/server/quote-proofs.js.map +1 -1
- package/src/lib/server/quote-uploads.d.ts +3 -1
- package/src/lib/server/quote-uploads.js +2 -1
- package/src/lib/server/quote-uploads.js.map +1 -1
- package/src/lib/server/quote.d.ts +3 -0
- package/src/lib/server/quote.js +127 -20
- package/src/lib/server/quote.js.map +1 -1
- package/src/lib/tenant-emails.js +16 -9
- package/src/lib/tenant-emails.js.map +1 -1
- package/src/lib/transfer/gift-cards.server.js +9 -11
- package/src/lib/transfer/gift-cards.server.js.map +1 -1
- package/src/lib/utils/commerce-document-pdf.js +12 -9
- package/src/lib/utils/commerce-document-pdf.js.map +1 -1
- package/src/lib/utils/quote-email-content.d.ts +2 -0
- package/src/lib/utils/quote-email-content.js +20 -10
- package/src/lib/utils/quote-email-content.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-invoices.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n appendOrderEvent,\n formatOrderNumber,\n orderCreatedAtMs,\n type HostOrder,\n type OrderStatus,\n type OrderTimelineEvent,\n} from './commerce-orders'\nimport {\n QUOTE_MIN_CHARGE_CENTS,\n payLinkCheckoutCharge,\n payLinkPaymentsUnavailableMessage,\n payLinkRefusalWithPayments,\n quoteCheckoutCharge,\n quotePageAddress,\n quotePageLines,\n quotePageStatus,\n quotePayRefusal,\n quotePayRefusalMessage,\n quotePayTax,\n type PayLinkStore,\n type QuoteCheckoutCharge,\n type QuotePageView,\n type QuotePayRefusal,\n} from './commerce-quote-pay'\nimport { lastQuoteSend } from './commerce-quote-email'\nimport {\n isQuote,\n type OrderInvoiceSendRecord,\n type QuoteEmailThread,\n type QuoteTaxBasis,\n} from './commerce-quotes'\nimport type { ResolvedShippingRate } from './commerce-shipping'\nimport { storefrontTaxDecision } from './commerce-tax-decision'\nimport { lineRequiresShipping } from './order-fulfillment'\n\n/*==========================================\n * INVOICES FOR ORDERS AND QUOTES (AGL-4099).\n *\n * The business emails an invoice for an order or a quote: unpaid, it asks\n * for payment through ONE lasting pay link; paid, it is the record. The link\n * is slice 2's (`/pay-quote?q=&t=`, AGL-4094), generalized rather than made\n * twice:\n *\n * - THE TOKEN is unchanged: `<version>.<HMAC(quote-link:hostId:orderId:version)>`,\n * no expiry. An order id names one document under `hosts/{hostId}/orders`\n * whatever its channel, so the same signature serves any order.\n * - THE VERSION is the quote's `quote.linkVersion` for a quote, as before,\n * so every link already sent keeps verifying; any other order keeps its own\n * as `payLink.version` (`orderPayLinkVersion`). Absent reads as 1.\n * - WHICH ORDERS the link opens ({@link orderPayLinkKind}): a quote, and a\n * draft order (`channel: 'draft'`), the two a business composes for a\n * customer to pay online. A register sale still open takes its payment at\n * the register, an online order was paid at checkout, and a marketplace\n * order on its channel, so none of them is linked; their invoices go out\n * paid, as the record.\n * - THE PAGE shows a non-quote order as \"Invoice #N\", with no proofs and no\n * approval ({@link buildInvoicePageView}).\n * - THE CHARGE is priced from the stored lines and totals on every press\n * ({@link invoiceCheckoutCharge}): the draft's discount, its frozen tax (or\n * Stripe Tax at payment where the draft used it), and the shipping rates\n * the draft offered when it was made (`draftShipping`).\n *\n * Pure: the console, the routes and the webhook read the same answers.\n *=========================================*/\n\n/** Which page a pay link opens for an order: a quote, an invoice, or none. */\nexport type OrderPayLinkKind = 'quote' | 'invoice'\n\n/** The most invoice sends an order keeps on record; the oldest go first. */\nexport const INVOICE_MAX_SENDS = 50\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\nconst cents = (value: unknown): number => {\n const number = Math.round(Number(value))\n return Number.isFinite(number) ? number : 0\n}\n\nconst text = (value: unknown): string | null => {\n const trimmed = typeof value === 'string' ? value.trim() : ''\n return trimmed ? trimmed : null\n}\n\n/**\n * Which page the lasting pay link opens for an order, or null when it opens\n * none: a quote (with its quote section), or a draft order as an invoice.\n */\nexport function orderPayLinkKind(\n order: Pick<HostOrder, 'channel'> & Partial<Pick<HostOrder, 'quote'>> | null | undefined,\n): OrderPayLinkKind | null {\n if (!order) return null\n if (isQuote(order)) return order.quote ? 'quote' : null\n return order.channel === 'draft' ? 'invoice' : null\n}\n\n/** `Invoice #1042`: the order's own number, which a paid quote keeps too. */\nexport function formatInvoiceNumber(order: Pick<HostOrder, 'number'>, orderId?: string): string {\n return `Invoice ${formatOrderNumber(order, orderId)}`\n}\n\nconst PAID_STATUSES: ReadonlySet<OrderStatus | string> = new Set([\n 'paid',\n 'partially_fulfilled',\n 'fulfilled',\n 'delivered',\n])\n\n/** The order is paid (and not refunded or canceled): its invoice is the record. */\nexport function invoiceIsPaid(order: Pick<HostOrder, 'status'> | null | undefined): boolean {\n return PAID_STATUSES.has(String(order?.status ?? ''))\n}\n\n/**\n * When the order was paid: a quote's stamp, else the timeline's `paid`\n * event, else (an order created paid, as checkout's are) when it was made.\n * Null for an order not paid.\n */\nexport function orderPaidAtMs(\n order: Pick<HostOrder, 'status' | 'quote' | 'timeline'> & { createdAtMs?: number } | null | undefined,\n): number | null {\n if (!order || 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 if (event && Number(event.atMs) > 0) return Number(event.atMs)\n const created = orderCreatedAtMs(order as never)\n return created > 0 ? created : null\n}\n\n/*==========================================\n * WHAT AN INVOICE'S PAY LINK CHARGES\n *=========================================*/\n\n/** What an invoice's Checkout Session charges, with the rates a draft lets the buyer pick from. */\nexport interface InvoiceCheckoutCharge extends QuoteCheckoutCharge {\n /** The draft's shipping rates, picked at payment; empty when shipping is fixed or there is none. */\n shippingOptions: ResolvedShippingRate[]\n /** Where those rates ship; empty with none. */\n shippingCountries: string[]\n}\n\n/**\n * The tax basis an order's stored figures give its invoice: Stripe Tax at\n * payment where the order was composed under it, its frozen tax as a fixed\n * figure (charged as the rate that yields it on the taxed line, the way a tax\n * service's quote is), else none.\n */\nexport function invoiceTaxBasis(order: Pick<HostOrder, 'taxMode' | 'totals'>): QuoteTaxBasis {\n if (order.taxMode === 'stripe-automatic') return { kind: 'at-payment' }\n const taxCents = Math.max(0, cents(order.totals?.taxCents))\n if (taxCents > 0) return { kind: 'service', taxCents }\n return { kind: 'none', reason: 'not-collected' }\n}\n\n/** A stored draft rate, as Stripe is given it, or null for one that is not a rate. */\nfunction draftRate(option: unknown): ResolvedShippingRate | null {\n if (!option || typeof option !== 'object') return null\n const source = option as Record<string, unknown>\n const name = text(source['name'])\n const amountCents = cents(source['amountCents'])\n if (!name || amountCents < 0) return null\n return { rateId: String(source['rateId'] ?? '') || name, name, amountCents }\n}\n\n/**\n * What an invoice's pay link charges, from the stored order alone. A quote is\n * charged as slice 2 charges it; any other order from its lines, its\n * discount, its tax ({@link invoiceTaxBasis}) and, for a draft, the shipping\n * rates it offered when it was made (Stripe asks for the address and the\n * buyer picks one, as on the draft's first link).\n */\nexport function invoiceCheckoutCharge(\n order: Pick<HostOrder, 'number' | 'lineItems' | 'quote' | 'totals' | 'taxMode'> &\n Partial<Pick<HostOrder, 'draftShipping'>>,\n orderId: string,\n /** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */\n store?: PayLinkStore | null,\n): InvoiceCheckoutCharge {\n if (order.quote) return { ...quoteCheckoutCharge(order, orderId, store), shippingOptions: [], shippingCountries: [] }\n const discountCents = Math.max(0, cents(order.totals?.discountCents))\n const charge = payLinkCheckoutCharge({\n lineItems: order.lineItems ?? [],\n tax: invoiceTaxBasis(order),\n discount: discountCents > 0 ? { kind: 'amount', amountCents: discountCents } : null,\n shippingCents: 0,\n label: formatInvoiceNumber(order, orderId),\n })\n const options = (order.draftShipping?.options ?? [])\n .map(draftRate)\n .filter((rate): rate is ResolvedShippingRate => rate !== null)\n .slice(0, 5)\n const countries = (order.draftShipping?.countries ?? [])\n .map((country) => String(country ?? '').trim().toUpperCase())\n .filter((country) => /^[A-Z]{2}$/.test(country))\n return { ...charge, shippingOptions: options, shippingCountries: options.length ? countries : [] }\n}\n\n/*==========================================\n * WHETHER AN INVOICE CAN BE PAID NOW\n *=========================================*/\n\n/**\n * Why an order cannot be paid through its pay link now: a quote's reasons,\n * and two of an invoice's own. `not-payable` is an order the link does not\n * open (a register sale still open, say); `shipping-unknown` is a draft made\n * before drafts kept their shipping rates, whose shipping cannot be charged.\n */\nexport type InvoicePayRefusal = QuotePayRefusal | 'not-payable' | 'shipping-unknown'\n\nexport function invoicePayRefusal(\n order: Pick<HostOrder, 'number' | 'status' | 'lineItems' | 'quote' | 'totals' | 'taxMode' | 'channel'> &\n Partial<Pick<HostOrder, 'draftShipping'>>,\n orderId: string,\n /** The store's sales tax choice; with it, a store that has not chosen refuses (AGL-1999). */\n store?: PayLinkStore | null,\n): InvoicePayRefusal | null {\n const kind = orderPayLinkKind(order)\n if (kind === 'quote') return quotePayRefusal(order, orderId, store)\n if (order.status === 'cancelled' || order.status === 'refunded') return 'closed'\n if (order.status !== 'pending') return 'paid'\n if (kind !== 'invoice') return 'not-payable'\n if (store && storefrontTaxDecision({ settings: store.tax }).kind === 'undecided') return 'tax-undecided'\n const ships = (order.lineItems ?? []).some((line) => line && !line.included && lineRequiresShipping(line))\n if (ships && !order.draftShipping) return 'shipping-unknown'\n if (invoiceCheckoutCharge(order, orderId).totalCents < QUOTE_MIN_CHARGE_CENTS) return 'nothing-to-pay'\n return null\n}\n\n/** What the customer is told for a refusal, in the page's words: \"quote\" or \"invoice\". */\nexport function invoicePayRefusalMessage(\n reason: InvoicePayRefusal,\n storeName: string,\n kind: OrderPayLinkKind,\n): string {\n const business = storeName.trim() || 'the business'\n if (kind === 'quote' && reason !== 'not-payable' && reason !== 'shipping-unknown') {\n return quotePayRefusalMessage(reason, storeName)\n }\n switch (reason) {\n case 'paid':\n return 'This invoice has been paid.'\n case 'closed':\n return `This invoice 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 invoice.`\n case 'nothing-to-pay':\n return `This invoice has nothing to pay by card. Contact ${business} with any questions.`\n case 'not-payable':\n case 'shipping-unknown':\n return `This invoice can’t be paid online. Contact ${business} to pay it.`\n }\n}\n\n/*==========================================\n * WHAT THE CONSOLE TELLS THE BUSINESS\n *=========================================*/\n\n/**\n * What stands between a pay link and a payment that the business fixes in\n * the console (AGL-4162):\n *\n * - `payments`: the workspace can't take card payments yet.\n * - `tax-undecided`: the store has not chosen how it handles sales tax.\n * - `tax-save`: the quote was saved before the store chose, and the store's\n * choice now prices it only on a save (`quotePayTax`'s `save`).\n */\nexport type PayLinkGap = 'payments' | 'tax-undecided' | 'tax-save'\n\n/**\n * What the console's \"Customers can't pay this … online yet\" notice names,\n * for an unpaid quote or a draft order's invoice, or a quote not saved yet\n * (`order: null`), which will be saved under the store's choice as it stands.\n * The same answers Pay refuses on: `invoicePayRefusal` with the store, and\n * the payment account check the page and Pay share.\n *\n * Null while either answer is unknown, so the notice waits rather than tell a\n * store that is set up to set up. Empty for anything the pay link does not\n * charge (a paid, closed or unlinked order) or that nothing stands in front of.\n * A refusal that is not the business's setup (approval, an amount too small)\n * is said where it is decided, not here.\n */\nexport function payLinkGaps(input: {\n order: (Pick<HostOrder, 'status' | 'channel'> & Partial<Pick<HostOrder, 'quote'>>) | null\n /** The workspace can take card payments; null while that is unknown. */\n paymentsReady: boolean | null\n /** The store's sales tax choice; undefined while it is being read. */\n store: PayLinkStore | undefined\n}): PayLinkGap[] | null {\n const { order, store } = input\n if (input.paymentsReady === null || store === undefined) return null\n if (order && (order.status !== 'pending' || orderPayLinkKind(order) === null)) return []\n const gaps: PayLinkGap[] = []\n if (!input.paymentsReady) gaps.push('payments')\n if (storefrontTaxDecision({ settings: store.tax }).kind === 'undecided') gaps.push('tax-undecided')\n else if (order?.quote && quotePayTax(order.quote, store).source === 'save') gaps.push('tax-save')\n return gaps\n}\n\n/*==========================================\n * THE CUSTOMER'S PAGE FOR AN INVOICE\n *=========================================*/\n\n/**\n * The pay link's page for an order that is not a quote: \"Invoice #N\", its\n * lines and totals, the customer's addresses, and Pay while it is unpaid. No\n * proofs, no approval, no notes or terms (an order carries none). Allow-listed\n * as the quote's view is: the order's email, phone, Stripe ids and timeline\n * never leave the server.\n */\nexport function buildInvoicePageView(input: {\n order: Pick<\n HostOrder,\n | 'number'\n | 'status'\n | 'channel'\n | 'lineItems'\n | 'totals'\n | 'quote'\n | 'timeline'\n | 'taxMode'\n | 'customerName'\n | 'billingAddress'\n | 'shippingAddress'\n > &\n Partial<Pick<HostOrder, 'draftShipping'>> & { createdAtMs?: number }\n orderId: string\n storeName: string\n currency: string\n /** The order's status page, once paid. */\n receiptUrl?: string | null\n /** The store's sales tax choice; with it, a store that has not chosen refuses Pay (AGL-1999). */\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 status = quotePageStatus(order.status)\n const unpaid = status.status === 'unpaid'\n const charge = invoiceCheckoutCharge(order, input.orderId, input.store)\n const refused = unpaid\n ? payLinkRefusalWithPayments(invoicePayRefusal(order, input.orderId, input.store), input.paymentsReady)\n : null\n const stored = order.totals\n const totals =\n 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 taxAtPayment = unpaid && charge.taxAtPayment\n const created = orderCreatedAtMs(order as never)\n return {\n state: 'quote',\n kind: 'invoice',\n storeName: input.storeName,\n number: formatInvoiceNumber(order, input.orderId),\n dateMs: created > 0 ? created : null,\n // An invoice is not edited; the page has no version to send back.\n version: 0,\n currency: input.currency || 'USD',\n customerName: text(order.customerName),\n company: null,\n billTo: quotePageAddress(order.billingAddress),\n shipTo: quotePageAddress(order.shippingAddress),\n lines: quotePageLines(order.lineItems ?? []),\n totals,\n discountLabel: null,\n taxLabel: taxAtPayment ? 'Tax is added at payment' : 'Tax',\n taxAtPayment,\n shippingAtPayment: unpaid && charge.shippingOptions.length > 0,\n notes: null,\n terms: null,\n status: status.status,\n statusLabel: status.label,\n paidAtMs: orderPaidAtMs(order),\n receiptUrl: unpaid ? null : (input.receiptUrl ?? null),\n approvalRequired: false,\n payable: unpaid && refused === null,\n notPayableMessage: refused === 'payments-unavailable' ? payLinkPaymentsUnavailableMessage(input.storeName, 'invoice') : null,\n taxKey: null,\n revision: 1,\n proofs: [],\n response: null,\n respondable: false,\n }\n}\n\n/*==========================================\n * EMAILING AN INVOICE\n *=========================================*/\n\n/** The order's invoice sends on record, oldest first. */\nexport function invoiceSends(order: Pick<HostOrder, 'invoiceSends'> | null | undefined): OrderInvoiceSendRecord[] {\n return Array.isArray(order?.invoiceSends)\n ? order.invoiceSends.filter((send) => send && typeof send === 'object')\n : []\n}\n\n/** The last time the order's invoice was emailed, or null. */\nexport function lastInvoiceSend(order: Pick<HostOrder, 'invoiceSends'> | null | undefined): OrderInvoiceSendRecord | null {\n const sends = invoiceSends(order)\n return sends.length ? sends[sends.length - 1] : null\n}\n\n/** Where the invoice goes: what was typed, else the order's customer, else a quote's. */\nexport function invoiceSendRecipient(\n order: Pick<HostOrder, 'customerEmail' | 'quote'> | null | undefined,\n typed: string | null | undefined,\n): string {\n return (\n String(typed ?? '').trim() ||\n String(order?.customerEmail ?? '').trim() ||\n String(order?.quote?.customer?.email ?? '').trim()\n )\n}\n\n/**\n * Who the console's Send invoice form starts addressed to: the customer's\n * email, else where the last invoice went, else (for a quote) where the quote\n * was last emailed, so an order or quote that names no email still opens\n * addressed to the customer it was already sent to.\n */\nexport function invoiceSendPrefill(order: Pick<HostOrder, 'customerEmail' | 'quote' | 'invoiceSends'> | null | undefined): string {\n return (\n invoiceSendRecipient(order, null) ||\n String(lastInvoiceSend(order)?.to ?? '').trim() ||\n String(lastQuoteSend(order?.quote)?.to ?? '').trim()\n )\n}\n\n/**\n * The conversation an invoice replies into: a quote's own (its emails, and a\n * request's confirmation before them), else the order's, which the first\n * invoice starts.\n */\nexport function invoiceEmailThread(\n order: Pick<HostOrder, 'quote' | 'emailThread'> | null | undefined,\n): QuoteEmailThread | null {\n if (order?.quote) return order.quote.emailThread ?? null\n return order?.emailThread ?? null\n}\n\n/**\n * The subject an invoice defaults to: the conversation's, so it stays one\n * conversation in the customer's mailbox, else `Invoice #1042 from Acme Signs`.\n */\nexport function invoiceEmailDefaultSubject(\n order: Pick<HostOrder, 'number' | 'quote' | 'emailThread'>,\n businessName: string,\n orderId?: string,\n): string {\n const thread = String(invoiceEmailThread(order)?.subject ?? '').trim()\n if (thread) return thread\n const name = String(businessName ?? '').trim()\n const number = formatInvoiceNumber(order, orderId)\n return name ? `${number} from ${name}` : number\n}\n\n/** Why an invoice cannot be emailed now, and what the console says. */\nexport type InvoiceSendRefusal =\n | 'unknown'\n | 'closed'\n | 'empty'\n | 'not-payable'\n | 'approval-required'\n | 'tax-undecided'\n | 'tax-save'\n | 'nothing-to-pay'\n | 'shipping-unknown'\n | 'no-address'\n | 'bad-address'\n\n/**\n * Why the order's invoice cannot be emailed to `to` now, if it cannot:\n * a canceled or refunded order, one with nothing on it, an unpaid order its\n * pay link cannot take payment for (and why), and the address.\n */\nexport function invoiceSendRefusal(\n order:\n | (Pick<HostOrder, 'number' | 'status' | 'channel' | 'lineItems' | 'totals' | 'quote' | 'taxMode'> &\n Partial<Pick<HostOrder, 'draftShipping'>>)\n | null\n | undefined,\n orderId: string,\n to: string,\n /** The store's sales tax choice, as the pay link reads it (`invoicePayRefusal`). */\n store?: PayLinkStore | null,\n): InvoiceSendRefusal | null {\n if (!order) return 'unknown'\n if (order.status === 'cancelled' || order.status === 'refunded') return 'closed'\n const lines = (order.lineItems ?? []).filter(Boolean)\n if (!lines.length && cents(order.totals?.totalCents) <= 0) return 'empty'\n if (!invoiceIsPaid(order)) {\n const refused = invoicePayRefusal(order, orderId, store)\n if (refused === 'closed') return 'closed'\n // A quote saved before the store chose: the store has chosen, and a save prices it.\n if (refused === 'tax-undecided' && order.quote && quotePayTax(order.quote, store).source === 'save') {\n return 'tax-save'\n }\n if (refused && refused !== 'paid') return refused\n }\n if (!to) return 'no-address'\n if (to.length > 320 || !EMAIL.test(to)) return 'bad-address'\n return null\n}\n\n/** What the console says for a refused invoice send. */\nexport function invoiceSendRefusalMessage(reason: InvoiceSendRefusal): string {\n switch (reason) {\n case 'unknown':\n return 'Unknown order'\n case 'closed':\n return 'This order was canceled or refunded, so it has no invoice to send.'\n case 'empty':\n return 'This order has no items and no total, so there is nothing to put on an invoice.'\n case 'not-payable':\n return 'This order isn’t paid yet, and it can’t be paid online from an invoice. Take its payment where the sale was made, then send the invoice.'\n case 'approval-required':\n return 'This quote asks your customer to approve the proof before they pay, and they haven’t yet. Send the quote so they can approve it, then send the invoice.'\n case 'tax-undecided':\n return 'Sales tax isn’t set up for this store yet, so the invoice can’t be paid online. Finish the tax settings, then send it.'\n case 'tax-save':\n return 'This quote was saved before your store chose how it handles sales tax. Save the quote again, then send the invoice.'\n case 'nothing-to-pay':\n return 'This invoice totals less than $0.50, so it can’t be paid by card.'\n case 'shipping-unknown':\n return 'This draft order was made before invoices could charge its shipping, so its invoice can’t be paid online. Make a new draft order and send its invoice.'\n case 'no-address':\n return 'This order has no email for the customer. Type where to send the invoice.'\n case 'bad-address':\n return 'Enter a valid email address to send the invoice to.'\n }\n}\n\n/** The HTTP status a refused send answers with. */\nexport function invoiceSendRefusalStatus(reason: InvoiceSendRefusal): number {\n if (reason === 'unknown') return 404\n if (reason === 'no-address' || reason === 'bad-address') return 400\n return 409\n}\n\n/**\n * What an invoice email changes on the order, as a merge: the send on\n * record, a line on the timeline, and the conversation moved on, on the\n * quote for a quote and on the order otherwise.\n */\nexport function invoiceSendPatch(\n order: Pick<HostOrder, 'timeline' | 'invoiceSends' | 'quote'>,\n send: OrderInvoiceSendRecord,\n thread: QuoteEmailThread,\n): {\n timeline: OrderTimelineEvent[]\n invoiceSends: OrderInvoiceSendRecord[]\n emailThread?: QuoteEmailThread\n quote?: { emailThread: QuoteEmailThread }\n} {\n return {\n timeline: appendOrderEvent(\n order,\n 'invoice-sent',\n // The address is on the send record, which erasure clears; the timeline keeps none.\n `${send.paid ? 'Paid invoice' : 'Invoice'} emailed to the customer by ${send.by}`,\n send.atMs,\n ),\n invoiceSends: [...invoiceSends(order), send].slice(-INVOICE_MAX_SENDS),\n ...(order.quote ? { quote: { emailThread: thread } } : { emailThread: thread }),\n }\n}\n"],"names":["appendOrderEvent","formatOrderNumber","orderCreatedAtMs","QUOTE_MIN_CHARGE_CENTS","payLinkCheckoutCharge","payLinkPaymentsUnavailableMessage","payLinkRefusalWithPayments","quoteCheckoutCharge","quotePageAddress","quotePageLines","quotePageStatus","quotePayRefusal","quotePayRefusalMessage","quotePayTax","lastQuoteSend","isQuote","storefrontTaxDecision","lineRequiresShipping","INVOICE_MAX_SENDS","EMAIL","cents","value","number","Math","round","Number","isFinite","text","trimmed","trim","orderPayLinkKind","order","quote","channel","formatInvoiceNumber","orderId","PAID_STATUSES","Set","invoiceIsPaid","has","String","status","orderPaidAtMs","stamped","paidAtMs","event","timeline","find","entry","atMs","created","invoiceTaxBasis","taxMode","kind","taxCents","max","totals","reason","draftRate","option","source","name","amountCents","rateId","invoiceCheckoutCharge","store","shippingOptions","shippingCountries","discountCents","charge","lineItems","tax","discount","shippingCents","label","options","draftShipping","map","filter","rate","slice","countries","country","toUpperCase","test","length","invoicePayRefusal","settings","ships","some","line","included","totalCents","invoicePayRefusalMessage","storeName","business","payLinkGaps","input","paymentsReady","undefined","gaps","push","buildInvoicePageView","unpaid","refused","stored","itemsCents","taxAtPayment","state","dateMs","version","currency","customerName","company","billTo","billingAddress","shipTo","shippingAddress","lines","discountLabel","taxLabel","shippingAtPayment","notes","terms","statusLabel","receiptUrl","approvalRequired","payable","notPayableMessage","taxKey","revision","proofs","response","respondable","invoiceSends","Array","isArray","send","lastInvoiceSend","sends","invoiceSendRecipient","typed","customerEmail","customer","email","invoiceSendPrefill","to","invoiceEmailThread","emailThread","invoiceEmailDefaultSubject","businessName","thread","subject","invoiceSendRefusal","Boolean","invoiceSendRefusalMessage","invoiceSendRefusalStatus","invoiceSendPatch","paid","by"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,iBAAiB,EACjBC,gBAAgB,QAIX,uBAAmB;AAC1B,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,iCAAiC,EACjCC,0BAA0B,EAC1BC,mBAAmB,EACnBC,gBAAgB,EAChBC,cAAc,EACdC,eAAe,EACfC,eAAe,EACfC,sBAAsB,EACtBC,WAAW,QAKN,0BAAsB;AAC7B,SAASC,aAAa,QAAQ,4BAAwB;AACtD,SACEC,OAAO,QAIF,uBAAmB;AAE1B,SAASC,qBAAqB,QAAQ,6BAAyB;AAC/D,SAASC,oBAAoB,QAAQ,yBAAqB;AAmC1D,0EAA0E,GAC1E,OAAO,MAAMC,oBAAoB,GAAE;AAEnC,MAAMC,QAAQ;AAEd,MAAMC,QAAQ,CAACC;IACb,MAAMC,SAASC,KAAKC,KAAK,CAACC,OAAOJ;IACjC,OAAOI,OAAOC,QAAQ,CAACJ,UAAUA,SAAS;AAC5C;AAEA,MAAMK,OAAO,CAACN;IACZ,MAAMO,UAAU,OAAOP,UAAU,WAAWA,MAAMQ,IAAI,KAAK;IAC3D,OAAOD,UAAUA,UAAU;AAC7B;AAEA;;;CAGC,GACD,OAAO,SAASE,iBACdC,KAAwF;IAExF,IAAI,CAACA,OAAO,OAAO;IACnB,IAAIhB,QAAQgB,QAAQ,OAAOA,MAAMC,KAAK,GAAG,UAAU;IACnD,OAAOD,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commerce/src/lib/model/commerce-invoices.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n appendOrderEvent,\n formatOrderNumber,\n orderCreatedAtMs,\n type HostOrder,\n type OrderStatus,\n type OrderTimelineEvent,\n} from './commerce-orders'\nimport {\n QUOTE_MIN_CHARGE_CENTS,\n payLinkCheckoutCharge,\n payLinkPaymentsUnavailableMessage,\n payLinkRefusalWithPayments,\n quoteCheckoutCharge,\n quotePageAddress,\n quotePageLines,\n quotePageStatus,\n quotePayRefusal,\n quotePayRefusalMessage,\n quotePayTax,\n type PayLinkStore,\n type QuoteCheckoutCharge,\n type QuotePageView,\n type QuotePayRefusal,\n} from './commerce-quote-pay'\nimport { lastQuoteSend } from './commerce-quote-email'\nimport {\n isQuote,\n quoteIsProofOnly,\n type OrderInvoiceSendRecord,\n type QuoteEmailThread,\n type QuoteTaxBasis,\n} from './commerce-quotes'\nimport type { ResolvedShippingRate } from './commerce-shipping'\nimport { storefrontTaxDecision } from './commerce-tax-decision'\nimport { lineRequiresShipping } from './order-fulfillment'\n\n/*==========================================\n * INVOICES FOR ORDERS AND QUOTES (AGL-4099).\n *\n * The business emails an invoice for an order or a quote: unpaid, it asks\n * for payment through ONE lasting pay link; paid, it is the record. The link\n * is slice 2's (`/pay-quote?q=&t=`, AGL-4094), generalized rather than made\n * twice:\n *\n * - THE TOKEN is unchanged: `<version>.<HMAC(quote-link:hostId:orderId:version)>`,\n * no expiry. An order id names one document under `hosts/{hostId}/orders`\n * whatever its channel, so the same signature serves any order.\n * - THE VERSION is the quote's `quote.linkVersion` for a quote, as before,\n * so every link already sent keeps verifying; any other order keeps its own\n * as `payLink.version` (`orderPayLinkVersion`). Absent reads as 1.\n * - WHICH ORDERS the link opens ({@link orderPayLinkKind}): a quote, and a\n * draft order (`channel: 'draft'`), the two a business composes for a\n * customer to pay online. A register sale still open takes its payment at\n * the register, an online order was paid at checkout, and a marketplace\n * order on its channel, so none of them is linked; their invoices go out\n * paid, as the record.\n * - THE PAGE shows a non-quote order as \"Invoice #N\", with no proofs and no\n * approval ({@link buildInvoicePageView}).\n * - THE CHARGE is priced from the stored lines and totals on every press\n * ({@link invoiceCheckoutCharge}): the draft's discount, its frozen tax (or\n * Stripe Tax at payment where the draft used it), and the shipping rates\n * the draft offered when it was made (`draftShipping`).\n *\n * Pure: the console, the routes and the webhook read the same answers.\n *=========================================*/\n\n/** Which page a pay link opens for an order: a quote, an invoice, or none. */\nexport type OrderPayLinkKind = 'quote' | 'invoice'\n\n/** The most invoice sends an order keeps on record; the oldest go first. */\nexport const INVOICE_MAX_SENDS = 50\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\nconst cents = (value: unknown): number => {\n const number = Math.round(Number(value))\n return Number.isFinite(number) ? number : 0\n}\n\nconst text = (value: unknown): string | null => {\n const trimmed = typeof value === 'string' ? value.trim() : ''\n return trimmed ? trimmed : null\n}\n\n/**\n * Which page the lasting pay link opens for an order, or null when it opens\n * none: a quote (with its quote section), or a draft order as an invoice.\n */\nexport function orderPayLinkKind(\n order: Pick<HostOrder, 'channel'> & Partial<Pick<HostOrder, 'quote'>> | null | undefined,\n): OrderPayLinkKind | null {\n if (!order) return null\n if (isQuote(order)) return order.quote ? 'quote' : null\n return order.channel === 'draft' ? 'invoice' : null\n}\n\n/** `Invoice #1042`: the order's own number, which a paid quote keeps too. */\nexport function formatInvoiceNumber(order: Pick<HostOrder, 'number'>, orderId?: string): string {\n return `Invoice ${formatOrderNumber(order, orderId)}`\n}\n\nconst PAID_STATUSES: ReadonlySet<OrderStatus | string> = new Set([\n 'paid',\n 'partially_fulfilled',\n 'fulfilled',\n 'delivered',\n])\n\n/** The order is paid (and not refunded or canceled): its invoice is the record. */\nexport function invoiceIsPaid(order: Pick<HostOrder, 'status'> | null | undefined): boolean {\n return PAID_STATUSES.has(String(order?.status ?? ''))\n}\n\n/**\n * When the order was paid: a quote's stamp, else the timeline's `paid`\n * event, else (an order created paid, as checkout's are) when it was made.\n * Null for an order not paid.\n */\nexport function orderPaidAtMs(\n order: Pick<HostOrder, 'status' | 'quote' | 'timeline'> & { createdAtMs?: number } | null | undefined,\n): number | null {\n if (!order || 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 if (event && Number(event.atMs) > 0) return Number(event.atMs)\n const created = orderCreatedAtMs(order as never)\n return created > 0 ? created : null\n}\n\n/*==========================================\n * WHAT AN INVOICE'S PAY LINK CHARGES\n *=========================================*/\n\n/** What an invoice's Checkout Session charges, with the rates a draft lets the buyer pick from. */\nexport interface InvoiceCheckoutCharge extends QuoteCheckoutCharge {\n /** The draft's shipping rates, picked at payment; empty when shipping is fixed or there is none. */\n shippingOptions: ResolvedShippingRate[]\n /** Where those rates ship; empty with none. */\n shippingCountries: string[]\n}\n\n/**\n * The tax basis an order's stored figures give its invoice: Stripe Tax at\n * payment where the order was composed under it, its frozen tax as a fixed\n * figure (charged as the rate that yields it on the taxed line, the way a tax\n * service's quote is), else none.\n */\nexport function invoiceTaxBasis(order: Pick<HostOrder, 'taxMode' | 'totals'>): QuoteTaxBasis {\n if (order.taxMode === 'stripe-automatic') return { kind: 'at-payment' }\n const taxCents = Math.max(0, cents(order.totals?.taxCents))\n if (taxCents > 0) return { kind: 'service', taxCents }\n return { kind: 'none', reason: 'not-collected' }\n}\n\n/** A stored draft rate, as Stripe is given it, or null for one that is not a rate. */\nfunction draftRate(option: unknown): ResolvedShippingRate | null {\n if (!option || typeof option !== 'object') return null\n const source = option as Record<string, unknown>\n const name = text(source['name'])\n const amountCents = cents(source['amountCents'])\n if (!name || amountCents < 0) return null\n return { rateId: String(source['rateId'] ?? '') || name, name, amountCents }\n}\n\n/**\n * What an invoice's pay link charges, from the stored order alone. A quote is\n * charged as slice 2 charges it; any other order from its lines, its\n * discount, its tax ({@link invoiceTaxBasis}) and, for a draft, the shipping\n * rates it offered when it was made (Stripe asks for the address and the\n * buyer picks one, as on the draft's first link).\n */\nexport function invoiceCheckoutCharge(\n order: Pick<HostOrder, 'number' | 'lineItems' | 'quote' | 'totals' | 'taxMode'> &\n Partial<Pick<HostOrder, 'draftShipping'>>,\n orderId: string,\n /** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */\n store?: PayLinkStore | null,\n): InvoiceCheckoutCharge {\n if (order.quote) return { ...quoteCheckoutCharge(order, orderId, store), shippingOptions: [], shippingCountries: [] }\n const discountCents = Math.max(0, cents(order.totals?.discountCents))\n const charge = payLinkCheckoutCharge({\n lineItems: order.lineItems ?? [],\n tax: invoiceTaxBasis(order),\n discount: discountCents > 0 ? { kind: 'amount', amountCents: discountCents } : null,\n shippingCents: 0,\n label: formatInvoiceNumber(order, orderId),\n })\n const options = (order.draftShipping?.options ?? [])\n .map(draftRate)\n .filter((rate): rate is ResolvedShippingRate => rate !== null)\n .slice(0, 5)\n const countries = (order.draftShipping?.countries ?? [])\n .map((country) => String(country ?? '').trim().toUpperCase())\n .filter((country) => /^[A-Z]{2}$/.test(country))\n return { ...charge, shippingOptions: options, shippingCountries: options.length ? countries : [] }\n}\n\n/*==========================================\n * WHETHER AN INVOICE CAN BE PAID NOW\n *=========================================*/\n\n/**\n * Why an order cannot be paid through its pay link now: a quote's reasons,\n * and two of an invoice's own. `not-payable` is an order the link does not\n * open (a register sale still open, say); `shipping-unknown` is a draft made\n * before drafts kept their shipping rates, whose shipping cannot be charged.\n */\nexport type InvoicePayRefusal = QuotePayRefusal | 'not-payable' | 'shipping-unknown'\n\nexport function invoicePayRefusal(\n order: Pick<HostOrder, 'number' | 'status' | 'lineItems' | 'quote' | 'totals' | 'taxMode' | 'channel'> &\n Partial<Pick<HostOrder, 'draftShipping'>>,\n orderId: string,\n /** The store's sales tax choice; with it, a store that has not chosen refuses (AGL-1999). */\n store?: PayLinkStore | null,\n): InvoicePayRefusal | null {\n const kind = orderPayLinkKind(order)\n if (kind === 'quote') return quotePayRefusal(order, orderId, store)\n if (order.status === 'cancelled' || order.status === 'refunded') return 'closed'\n if (order.status !== 'pending') return 'paid'\n if (kind !== 'invoice') return 'not-payable'\n if (store && storefrontTaxDecision({ settings: store.tax }).kind === 'undecided') return 'tax-undecided'\n const ships = (order.lineItems ?? []).some((line) => line && !line.included && lineRequiresShipping(line))\n if (ships && !order.draftShipping) return 'shipping-unknown'\n if (invoiceCheckoutCharge(order, orderId).totalCents < QUOTE_MIN_CHARGE_CENTS) return 'nothing-to-pay'\n return null\n}\n\n/** What the customer is told for a refusal, in the page's words: \"quote\" or \"invoice\". */\nexport function invoicePayRefusalMessage(\n reason: InvoicePayRefusal,\n storeName: string,\n kind: OrderPayLinkKind,\n): string {\n const business = storeName.trim() || 'the business'\n if (kind === 'quote' && reason !== 'not-payable' && reason !== 'shipping-unknown') {\n return quotePayRefusalMessage(reason, storeName)\n }\n switch (reason) {\n case 'paid':\n return 'This invoice has been paid.'\n case 'closed':\n return `This invoice 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 invoice.`\n case 'nothing-to-pay':\n return `This invoice has nothing to pay by card. Contact ${business} with any questions.`\n case 'not-payable':\n case 'shipping-unknown':\n return `This invoice can’t be paid online. Contact ${business} to pay it.`\n }\n}\n\n/*==========================================\n * WHAT THE CONSOLE TELLS THE BUSINESS\n *=========================================*/\n\n/**\n * What stands between a pay link and a payment that the business fixes in\n * the console (AGL-4162):\n *\n * - `payments`: the workspace can't take card payments yet.\n * - `tax-undecided`: the store has not chosen how it handles sales tax.\n * - `tax-save`: the quote was saved before the store chose, and the store's\n * choice now prices it only on a save (`quotePayTax`'s `save`).\n */\nexport type PayLinkGap = 'payments' | 'tax-undecided' | 'tax-save'\n\n/**\n * What the console's \"Customers can't pay this … online yet\" notice names,\n * for an unpaid quote or a draft order's invoice, or a quote not saved yet\n * (`order: null`), which will be saved under the store's choice as it stands.\n * The same answers Pay refuses on: `invoicePayRefusal` with the store, and\n * the payment account check the page and Pay share.\n *\n * Null while either answer is unknown, so the notice waits rather than tell a\n * store that is set up to set up. Empty for anything the pay link does not\n * charge (a paid, closed or unlinked order) or that nothing stands in front of.\n * A refusal that is not the business's setup (approval, an amount too small)\n * is said where it is decided, not here.\n */\nexport function payLinkGaps(input: {\n order: (Pick<HostOrder, 'status' | 'channel'> & Partial<Pick<HostOrder, 'quote' | 'lineItems'>>) | null\n /** The workspace can take card payments; null while that is unknown. */\n paymentsReady: boolean | null\n /** The store's sales tax choice; undefined while it is being read. */\n store: PayLinkStore | undefined\n}): PayLinkGap[] | null {\n const { order, store } = input\n if (input.paymentsReady === null || store === undefined) return null\n if (order && (order.status !== 'pending' || orderPayLinkKind(order) === null)) return []\n // A proof only quote charges nothing until it has lines (AGL-4184).\n if (order?.quote && quoteIsProofOnly(order)) return []\n const gaps: PayLinkGap[] = []\n if (!input.paymentsReady) gaps.push('payments')\n if (storefrontTaxDecision({ settings: store.tax }).kind === 'undecided') gaps.push('tax-undecided')\n else if (order?.quote && quotePayTax(order.quote, store).source === 'save') gaps.push('tax-save')\n return gaps\n}\n\n/*==========================================\n * THE CUSTOMER'S PAGE FOR AN INVOICE\n *=========================================*/\n\n/**\n * The pay link's page for an order that is not a quote: \"Invoice #N\", its\n * lines and totals, the customer's addresses, and Pay while it is unpaid. No\n * proofs, no approval, no notes or terms (an order carries none). Allow-listed\n * as the quote's view is: the order's email, phone, Stripe ids and timeline\n * never leave the server.\n */\nexport function buildInvoicePageView(input: {\n order: Pick<\n HostOrder,\n | 'number'\n | 'status'\n | 'channel'\n | 'lineItems'\n | 'totals'\n | 'quote'\n | 'timeline'\n | 'taxMode'\n | 'customerName'\n | 'billingAddress'\n | 'shippingAddress'\n > &\n Partial<Pick<HostOrder, 'draftShipping'>> & { createdAtMs?: number }\n orderId: string\n storeName: string\n currency: string\n /** The order's status page, once paid. */\n receiptUrl?: string | null\n /** The store's sales tax choice; with it, a store that has not chosen refuses Pay (AGL-1999). */\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 status = quotePageStatus(order.status)\n const unpaid = status.status === 'unpaid'\n const charge = invoiceCheckoutCharge(order, input.orderId, input.store)\n const refused = unpaid\n ? payLinkRefusalWithPayments(invoicePayRefusal(order, input.orderId, input.store), input.paymentsReady)\n : null\n const stored = order.totals\n const totals =\n 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 taxAtPayment = unpaid && charge.taxAtPayment\n const created = orderCreatedAtMs(order as never)\n return {\n state: 'quote',\n kind: 'invoice',\n proofOnly: false,\n storeName: input.storeName,\n number: formatInvoiceNumber(order, input.orderId),\n dateMs: created > 0 ? created : null,\n // An invoice is not edited; the page has no version to send back.\n version: 0,\n currency: input.currency || 'USD',\n customerName: text(order.customerName),\n company: null,\n billTo: quotePageAddress(order.billingAddress),\n shipTo: quotePageAddress(order.shippingAddress),\n lines: quotePageLines(order.lineItems ?? []),\n totals,\n discountLabel: null,\n taxLabel: taxAtPayment ? 'Tax is added at payment' : 'Tax',\n taxAtPayment,\n shippingAtPayment: unpaid && charge.shippingOptions.length > 0,\n notes: null,\n terms: null,\n status: status.status,\n statusLabel: status.label,\n paidAtMs: orderPaidAtMs(order),\n receiptUrl: unpaid ? null : (input.receiptUrl ?? null),\n approvalRequired: false,\n payable: unpaid && refused === null,\n notPayableMessage: refused === 'payments-unavailable' ? payLinkPaymentsUnavailableMessage(input.storeName, 'invoice') : null,\n taxKey: null,\n revision: 1,\n proofs: [],\n response: null,\n respondable: false,\n }\n}\n\n/*==========================================\n * EMAILING AN INVOICE\n *=========================================*/\n\n/** The order's invoice sends on record, oldest first. */\nexport function invoiceSends(order: Pick<HostOrder, 'invoiceSends'> | null | undefined): OrderInvoiceSendRecord[] {\n return Array.isArray(order?.invoiceSends)\n ? order.invoiceSends.filter((send) => send && typeof send === 'object')\n : []\n}\n\n/** The last time the order's invoice was emailed, or null. */\nexport function lastInvoiceSend(order: Pick<HostOrder, 'invoiceSends'> | null | undefined): OrderInvoiceSendRecord | null {\n const sends = invoiceSends(order)\n return sends.length ? sends[sends.length - 1] : null\n}\n\n/** Where the invoice goes: what was typed, else the order's customer, else a quote's. */\nexport function invoiceSendRecipient(\n order: Pick<HostOrder, 'customerEmail' | 'quote'> | null | undefined,\n typed: string | null | undefined,\n): string {\n return (\n String(typed ?? '').trim() ||\n String(order?.customerEmail ?? '').trim() ||\n String(order?.quote?.customer?.email ?? '').trim()\n )\n}\n\n/**\n * Who the console's Send invoice form starts addressed to: the customer's\n * email, else where the last invoice went, else (for a quote) where the quote\n * was last emailed, so an order or quote that names no email still opens\n * addressed to the customer it was already sent to.\n */\nexport function invoiceSendPrefill(order: Pick<HostOrder, 'customerEmail' | 'quote' | 'invoiceSends'> | null | undefined): string {\n return (\n invoiceSendRecipient(order, null) ||\n String(lastInvoiceSend(order)?.to ?? '').trim() ||\n String(lastQuoteSend(order?.quote)?.to ?? '').trim()\n )\n}\n\n/**\n * The conversation an invoice replies into: a quote's own (its emails, and a\n * request's confirmation before them), else the order's, which the first\n * invoice starts.\n */\nexport function invoiceEmailThread(\n order: Pick<HostOrder, 'quote' | 'emailThread'> | null | undefined,\n): QuoteEmailThread | null {\n if (order?.quote) return order.quote.emailThread ?? null\n return order?.emailThread ?? null\n}\n\n/**\n * The subject an invoice defaults to: the conversation's, so it stays one\n * conversation in the customer's mailbox, else `Invoice #1042 from Acme Signs`.\n */\nexport function invoiceEmailDefaultSubject(\n order: Pick<HostOrder, 'number' | 'quote' | 'emailThread'>,\n businessName: string,\n orderId?: string,\n): string {\n const thread = String(invoiceEmailThread(order)?.subject ?? '').trim()\n if (thread) return thread\n const name = String(businessName ?? '').trim()\n const number = formatInvoiceNumber(order, orderId)\n return name ? `${number} from ${name}` : number\n}\n\n/** Why an invoice cannot be emailed now, and what the console says. */\nexport type InvoiceSendRefusal =\n | 'unknown'\n | 'closed'\n | 'empty'\n | 'not-payable'\n | 'approval-required'\n | 'tax-undecided'\n | 'tax-save'\n | 'nothing-to-pay'\n | 'shipping-unknown'\n | 'no-address'\n | 'bad-address'\n\n/**\n * Why the order's invoice cannot be emailed to `to` now, if it cannot:\n * a canceled or refunded order, one with nothing on it, an unpaid order its\n * pay link cannot take payment for (and why), and the address.\n */\nexport function invoiceSendRefusal(\n order:\n | (Pick<HostOrder, 'number' | 'status' | 'channel' | 'lineItems' | 'totals' | 'quote' | 'taxMode'> &\n Partial<Pick<HostOrder, 'draftShipping'>>)\n | null\n | undefined,\n orderId: string,\n to: string,\n /** The store's sales tax choice, as the pay link reads it (`invoicePayRefusal`). */\n store?: PayLinkStore | null,\n): InvoiceSendRefusal | null {\n if (!order) return 'unknown'\n if (order.status === 'cancelled' || order.status === 'refunded') return 'closed'\n const lines = (order.lineItems ?? []).filter(Boolean)\n if (!lines.length && cents(order.totals?.totalCents) <= 0) return 'empty'\n if (!invoiceIsPaid(order)) {\n const refused = invoicePayRefusal(order, orderId, store)\n if (refused === 'closed') return 'closed'\n // A quote saved before the store chose: the store has chosen, and a save prices it.\n if (refused === 'tax-undecided' && order.quote && quotePayTax(order.quote, store).source === 'save') {\n return 'tax-save'\n }\n if (refused && refused !== 'paid') return refused\n }\n if (!to) return 'no-address'\n if (to.length > 320 || !EMAIL.test(to)) return 'bad-address'\n return null\n}\n\n/** What the console says for a refused invoice send. */\nexport function invoiceSendRefusalMessage(reason: InvoiceSendRefusal): string {\n switch (reason) {\n case 'unknown':\n return 'Unknown order'\n case 'closed':\n return 'This order was canceled or refunded, so it has no invoice to send.'\n case 'empty':\n return 'This order has no items and no total, so there is nothing to put on an invoice.'\n case 'not-payable':\n return 'This order isn’t paid yet, and it can’t be paid online from an invoice. Take its payment where the sale was made, then send the invoice.'\n case 'approval-required':\n return 'This quote asks your customer to approve the proof before they pay, and they haven’t yet. Send the quote so they can approve it, then send the invoice.'\n case 'tax-undecided':\n return 'Sales tax isn’t set up for this store yet, so the invoice can’t be paid online. Finish the tax settings, then send it.'\n case 'tax-save':\n return 'This quote was saved before your store chose how it handles sales tax. Save the quote again, then send the invoice.'\n case 'nothing-to-pay':\n return 'This invoice totals less than $0.50, so it can’t be paid by card.'\n case 'shipping-unknown':\n return 'This draft order was made before invoices could charge its shipping, so its invoice can’t be paid online. Make a new draft order and send its invoice.'\n case 'no-address':\n return 'This order has no email for the customer. Type where to send the invoice.'\n case 'bad-address':\n return 'Enter a valid email address to send the invoice to.'\n }\n}\n\n/** The HTTP status a refused send answers with. */\nexport function invoiceSendRefusalStatus(reason: InvoiceSendRefusal): number {\n if (reason === 'unknown') return 404\n if (reason === 'no-address' || reason === 'bad-address') return 400\n return 409\n}\n\n/**\n * What an invoice email changes on the order, as a merge: the send on\n * record, a line on the timeline, and the conversation moved on, on the\n * quote for a quote and on the order otherwise.\n */\nexport function invoiceSendPatch(\n order: Pick<HostOrder, 'timeline' | 'invoiceSends' | 'quote'>,\n send: OrderInvoiceSendRecord,\n thread: QuoteEmailThread,\n): {\n timeline: OrderTimelineEvent[]\n invoiceSends: OrderInvoiceSendRecord[]\n emailThread?: QuoteEmailThread\n quote?: { emailThread: QuoteEmailThread }\n} {\n return {\n timeline: appendOrderEvent(\n order,\n 'invoice-sent',\n // The address is on the send record, which erasure clears; the timeline keeps none.\n `${send.paid ? 'Paid invoice' : 'Invoice'} emailed to the customer by ${send.by}`,\n send.atMs,\n ),\n invoiceSends: [...invoiceSends(order), send].slice(-INVOICE_MAX_SENDS),\n ...(order.quote ? { quote: { emailThread: thread } } : { emailThread: thread }),\n }\n}\n"],"names":["appendOrderEvent","formatOrderNumber","orderCreatedAtMs","QUOTE_MIN_CHARGE_CENTS","payLinkCheckoutCharge","payLinkPaymentsUnavailableMessage","payLinkRefusalWithPayments","quoteCheckoutCharge","quotePageAddress","quotePageLines","quotePageStatus","quotePayRefusal","quotePayRefusalMessage","quotePayTax","lastQuoteSend","isQuote","quoteIsProofOnly","storefrontTaxDecision","lineRequiresShipping","INVOICE_MAX_SENDS","EMAIL","cents","value","number","Math","round","Number","isFinite","text","trimmed","trim","orderPayLinkKind","order","quote","channel","formatInvoiceNumber","orderId","PAID_STATUSES","Set","invoiceIsPaid","has","String","status","orderPaidAtMs","stamped","paidAtMs","event","timeline","find","entry","atMs","created","invoiceTaxBasis","taxMode","kind","taxCents","max","totals","reason","draftRate","option","source","name","amountCents","rateId","invoiceCheckoutCharge","store","shippingOptions","shippingCountries","discountCents","charge","lineItems","tax","discount","shippingCents","label","options","draftShipping","map","filter","rate","slice","countries","country","toUpperCase","test","length","invoicePayRefusal","settings","ships","some","line","included","totalCents","invoicePayRefusalMessage","storeName","business","payLinkGaps","input","paymentsReady","undefined","gaps","push","buildInvoicePageView","unpaid","refused","stored","itemsCents","taxAtPayment","state","proofOnly","dateMs","version","currency","customerName","company","billTo","billingAddress","shipTo","shippingAddress","lines","discountLabel","taxLabel","shippingAtPayment","notes","terms","statusLabel","receiptUrl","approvalRequired","payable","notPayableMessage","taxKey","revision","proofs","response","respondable","invoiceSends","Array","isArray","send","lastInvoiceSend","sends","invoiceSendRecipient","typed","customerEmail","customer","email","invoiceSendPrefill","to","invoiceEmailThread","emailThread","invoiceEmailDefaultSubject","businessName","thread","subject","invoiceSendRef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AY,QAAQ,OAAOA;IAC5C;IACA,IAAI,CAAC2C,IAAI,OAAO;IAChB,IAAIA,GAAG9D,MAAM,GAAG,OAAO,CAAClE,MAAMiE,IAAI,CAAC+D,KAAK,OAAO;IAC/C,OAAO;AACT;AAEA,sDAAsD,GACtD,OAAO,SAASS,0BAA0BnG,MAA0B;IAClE,OAAQA;QACN,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;IACX;AACF;AAEA,iDAAiD,GACjD,OAAO,SAASoG,yBAAyBpG,MAA0B;IACjE,IAAIA,WAAW,WAAW,OAAO;IACjC,IAAIA,WAAW,gBAAgBA,WAAW,eAAe,OAAO;IAChE,OAAO;AACT;AAEA;;;;CAIC,GACD,OAAO,SAASqG,iBACd/H,KAA6D,EAC7D2G,IAA4B,EAC5Bc,MAAwB;IAOxB,OAAO;QACL1G,UAAU/C,iBACRgC,OACA,gBACA,oFAAoF;QACpF,GAAG2G,KAAKqB,IAAI,GAAG,iBAAiB,UAAU,4BAA4B,EAAErB,KAAKsB,EAAE,EAAE,EACjFtB,KAAKzF,IAAI;QAEXsF,cAAc;eAAIA,aAAaxG;YAAQ2G;SAAK,CAAC1D,KAAK,CAAC,CAAC9D;OAChDa,MAAMC,KAAK,GAAG;QAAEA,OAAO;YAAEqH,aAAaG;QAAO;IAAE,IAAI;QAAEH,aAAaG;IAAO;AAEjF"}
|
|
@@ -39,8 +39,8 @@ export declare function quoteSendIsNewRevision(quote: Pick<OrderQuote, 'sends' |
|
|
|
39
39
|
* emailed an earlier revision, and the link has not been replaced since.
|
|
40
40
|
*/
|
|
41
41
|
export declare function quoteSendReplacesLink(quote: Pick<OrderQuote, 'sends' | 'revision' | 'linkVersion'> | null | undefined): boolean;
|
|
42
|
-
/** What the console's Send button says: `Send quote
|
|
43
|
-
export declare function quoteSendLabel(quote: Pick<OrderQuote, 'sends' | 'revision'> | null | undefined): string;
|
|
42
|
+
/** What the console's Send button says: `Send quote` (`Send proof` for one with no price yet), `Send again`, or `Send revision 2`. */
|
|
43
|
+
export declare function quoteSendLabel(quote: Pick<OrderQuote, 'sends' | 'revision'> | null | undefined, proofOnly?: boolean): string;
|
|
44
44
|
/** Where the quote goes: what was typed in the dialog, else the customer's email. */
|
|
45
45
|
export declare function quoteSendRecipient(order: Pick<HostOrder, 'quote'> | null | undefined, typed: string | null | undefined): string;
|
|
46
46
|
/**
|
|
@@ -49,15 +49,16 @@ export declare function quoteSendRecipient(order: Pick<HostOrder, 'quote'> | nul
|
|
|
49
49
|
* where the last one went when the quote names no email.
|
|
50
50
|
*/
|
|
51
51
|
export declare function quoteSendPrefill(order: Pick<HostOrder, 'quote'> | null | undefined): string;
|
|
52
|
-
export type QuoteSendRefusal = 'not-a-quote' | 'paid' | 'no-address' | 'bad-address';
|
|
52
|
+
export type QuoteSendRefusal = 'not-a-quote' | 'paid' | 'nothing-to-send' | 'no-address' | 'bad-address';
|
|
53
53
|
/** Why the quote cannot be emailed to `to` now, if it cannot. */
|
|
54
|
-
export declare function quoteSendRefusal(order: Pick<HostOrder, 'channel' | 'status' | 'quote'> | null | undefined, to: string): QuoteSendRefusal | null;
|
|
54
|
+
export declare function quoteSendRefusal(order: (Pick<HostOrder, 'channel' | 'status' | 'quote'> & Partial<Pick<HostOrder, 'lineItems'>>) | null | undefined, to: string): QuoteSendRefusal | null;
|
|
55
55
|
export declare function quoteSendRefusalMessage(reason: QuoteSendRefusal): string;
|
|
56
56
|
/**
|
|
57
57
|
* The subject a send defaults to: the conversation's, so it stays one
|
|
58
|
-
* conversation, else `Quote #1042 from Acme Signs
|
|
58
|
+
* conversation, else `Quote #1042 from Acme Signs` (`Proof #1042` for one with
|
|
59
|
+
* no price yet).
|
|
59
60
|
*/
|
|
60
|
-
export declare function quoteEmailDefaultSubject(order: Pick<HostOrder, 'number' | 'quote'
|
|
61
|
+
export declare function quoteEmailDefaultSubject(order: Pick<HostOrder, 'number' | 'quote'> & Partial<Pick<HostOrder, 'lineItems'>>, businessName: string, quoteId?: string): string;
|
|
61
62
|
/** What the console sends: where, under what subject, and the business's message. */
|
|
62
63
|
export interface QuoteSendInput {
|
|
63
64
|
to: string;
|
|
@@ -16,8 +16,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import { appendOrderEvent } from "./commerce-orders.js";
|
|
18
18
|
import { quoteLinkVersion } from "./commerce-quote-pay.js";
|
|
19
|
-
import { latestQuoteResponse } from "./commerce-quote-proofs.js";
|
|
20
|
-
import { formatQuoteNumber, isQuote, isUnpaidQuote } from "./commerce-quotes.js";
|
|
19
|
+
import { currentQuoteProofs, latestQuoteResponse } from "./commerce-quote-proofs.js";
|
|
20
|
+
import { formatProofNumber, formatQuoteNumber, isQuote, isUnpaidQuote, quoteIsProofOnly } from "./commerce-quotes.js";
|
|
21
21
|
/*==========================================
|
|
22
22
|
* EMAILING A QUOTE TO THE CUSTOMER (AGL-4097).
|
|
23
23
|
*
|
|
@@ -68,9 +68,9 @@ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
|
68
68
|
if (!quoteSendIsNewRevision(quote)) return false;
|
|
69
69
|
return Number((_lastQuoteSend = lastQuoteSend(quote)) == null ? void 0 : _lastQuoteSend.linkVersion) === quoteLinkVersion(quote);
|
|
70
70
|
}
|
|
71
|
-
/** What the console's Send button says: `Send quote
|
|
71
|
+
/** What the console's Send button says: `Send quote` (`Send proof` for one with no price yet), `Send again`, or `Send revision 2`. */ export function quoteSendLabel(quote, proofOnly = false) {
|
|
72
72
|
var _ref;
|
|
73
|
-
if (!lastQuoteSend(quote)) return 'Send quote';
|
|
73
|
+
if (!lastQuoteSend(quote)) return proofOnly ? 'Send proof' : 'Send quote';
|
|
74
74
|
return quoteSendIsNewRevision(quote) ? `Send revision ${Number((_ref = quote == null ? void 0 : quote.revision) != null ? _ref : 1)}` : 'Send again';
|
|
75
75
|
}
|
|
76
76
|
/** Where the quote goes: what was typed in the dialog, else the customer's email. */ export function quoteSendRecipient(order, typed) {
|
|
@@ -90,6 +90,8 @@ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
|
90
90
|
/** Why the quote cannot be emailed to `to` now, if it cannot. */ export function quoteSendRefusal(order, to) {
|
|
91
91
|
if (!order || !isQuote(order) || !order.quote) return 'not-a-quote';
|
|
92
92
|
if (!isUnpaidQuote(order)) return 'paid';
|
|
93
|
+
// A new revision of a proof only quote starts with no proof, and so with nothing to show (AGL-4184).
|
|
94
|
+
if (quoteIsProofOnly(order) && currentQuoteProofs(order.quote).length === 0) return 'nothing-to-send';
|
|
93
95
|
if (!to) return 'no-address';
|
|
94
96
|
if (to.length > 320 || !EMAIL.test(to)) return 'bad-address';
|
|
95
97
|
return null;
|
|
@@ -100,6 +102,8 @@ export function quoteSendRefusalMessage(reason) {
|
|
|
100
102
|
return 'Unknown quote';
|
|
101
103
|
case 'paid':
|
|
102
104
|
return 'This quote has been paid, so it is an order now and is not sent again.';
|
|
105
|
+
case 'nothing-to-send':
|
|
106
|
+
return 'This quote has no items and no proof on this revision yet. Add one, then send it.';
|
|
103
107
|
case 'no-address':
|
|
104
108
|
return 'This quote has no email for the customer. Add one to the quote, or type where to send it.';
|
|
105
109
|
case 'bad-address':
|
|
@@ -108,14 +112,15 @@ export function quoteSendRefusalMessage(reason) {
|
|
|
108
112
|
}
|
|
109
113
|
/**
|
|
110
114
|
* The subject a send defaults to: the conversation's, so it stays one
|
|
111
|
-
* conversation, else `Quote #1042 from Acme Signs
|
|
115
|
+
* conversation, else `Quote #1042 from Acme Signs` (`Proof #1042` for one with
|
|
116
|
+
* no price yet).
|
|
112
117
|
*/ export function quoteEmailDefaultSubject(order, businessName, quoteId) {
|
|
113
118
|
var _ref;
|
|
114
119
|
var _order_quote_emailThread, _order_quote;
|
|
115
120
|
const thread = String((_ref = (_order_quote = order.quote) == null ? void 0 : (_order_quote_emailThread = _order_quote.emailThread) == null ? void 0 : _order_quote_emailThread.subject) != null ? _ref : '').trim();
|
|
116
121
|
if (thread) return thread;
|
|
117
122
|
const name = String(businessName != null ? businessName : '').trim();
|
|
118
|
-
const number = formatQuoteNumber(order, quoteId);
|
|
123
|
+
const number = quoteIsProofOnly(order) ? formatProofNumber(order, quoteId) : formatQuoteNumber(order, quoteId);
|
|
119
124
|
return name ? `${number} from ${name}` : number;
|
|
120
125
|
}
|
|
121
126
|
/** A send as the route received it, trimmed, or what to fix. `to` and `subject` may be empty: the defaults fill them. */ export function parseQuoteSendInput(raw) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-quote-email.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 { appendOrderEvent, type HostOrder } from './commerce-orders'\nimport { quoteLinkVersion } from './commerce-quote-pay'\nimport { latestQuoteResponse } from './commerce-quote-proofs'\nimport {\n formatQuoteNumber,\n isQuote,\n isUnpaidQuote,\n type OrderQuote,\n type QuoteEmailThread,\n type QuoteSendRecord,\n} from './commerce-quotes'\n\n/*==========================================\n * EMAILING A QUOTE TO THE CUSTOMER (AGL-4097).\n *\n * The business sends the quote from the console: one email in the site's\n * look with its message, the proof, the PDF and the pay button, in the\n * customer's existing conversation when there is one. Each send is recorded\n * on the quote (`quote.sends`) with the revision it carried and the pay link\n * version it carried, and the conversation is kept as `quote.emailThread`.\n *\n * THE PAY LINK ON A NEW REVISION. When the customer was emailed an earlier\n * revision, the first email of a new revision gives them a new pay link and\n * retires the old one (slice 2's Replace link), so the link in the earlier\n * email opens a page saying the quote was updated. A resend of the same\n * revision keeps the link. \"Was the link already replaced since that email\"\n * is read off the record (the link version it carried), which is also what\n * keeps a send that failed after replacing the link from replacing it again\n * when it is retried.\n *\n * Pure: the console's Send button and the server's send action read the\n * same answers.\n *=========================================*/\n\n/** The most sends a quote keeps on record; the oldest go first. */\nexport const QUOTE_MAX_SENDS = 50\n\n/** The longest message a send carries. */\nexport const QUOTE_MAX_SEND_MESSAGE = 5_000\n\n/** The longest subject a send carries. */\nexport const QUOTE_MAX_SEND_SUBJECT = 200\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/** The quote's sends on record, oldest first. */\nexport function quoteSends(quote: Pick<OrderQuote, 'sends'> | null | undefined): QuoteSendRecord[] {\n return Array.isArray(quote?.sends) ? quote.sends.filter((send) => send && typeof send === 'object') : []\n}\n\n/** The last time the quote was emailed, or null. */\nexport function lastQuoteSend(quote: Pick<OrderQuote, 'sends'> | null | undefined): QuoteSendRecord | null {\n const sends = quoteSends(quote)\n return sends.length ? sends[sends.length - 1] : null\n}\n\n/**\n * Whether emailing the quote now hands the customer a new revision of a quote\n * they were already emailed: an earlier revision went out, and this one has\n * not yet. The quote's first email (whatever revision it is at, since\n * revisions nobody was sent replace nothing) and a resend of the revision\n * already sent are neither, so their email does not call itself an update.\n */\nexport function quoteSendIsNewRevision(quote: Pick<OrderQuote, 'sends' | 'revision'> | null | undefined): boolean {\n const last = lastQuoteSend(quote)\n return Boolean(last) && Number(last.revision) < Number(quote?.revision ?? 1)\n}\n\n/**\n * Whether emailing the quote now gives the customer a new pay link: they were\n * emailed an earlier revision, and the link has not been replaced since.\n */\nexport function quoteSendReplacesLink(\n quote: Pick<OrderQuote, 'sends' | 'revision' | 'linkVersion'> | null | undefined,\n): boolean {\n if (!quoteSendIsNewRevision(quote)) return false\n return Number(lastQuoteSend(quote)?.linkVersion) === quoteLinkVersion(quote)\n}\n\n/** What the console's Send button says: `Send quote`, `Send again`, or `Send revision 2`. */\nexport function quoteSendLabel(quote: Pick<OrderQuote, 'sends' | 'revision'> | null | undefined): string {\n if (!lastQuoteSend(quote)) return 'Send quote'\n return quoteSendIsNewRevision(quote) ? `Send revision ${Number(quote?.revision ?? 1)}` : 'Send again'\n}\n\n/** Where the quote goes: what was typed in the dialog, else the customer's email. */\nexport function quoteSendRecipient(\n order: Pick<HostOrder, 'quote'> | null | undefined,\n typed: string | null | undefined,\n): string {\n return String(typed ?? '').trim() || String(order?.quote?.customer?.email ?? '').trim()\n}\n\n/**\n * Who the console's send form starts addressed to: the customer's email, else\n * where the quote was last emailed, so Send again and Send revision N go\n * where the last one went when the quote names no email.\n */\nexport function quoteSendPrefill(order: Pick<HostOrder, 'quote'> | null | undefined): string {\n return quoteSendRecipient(order, null) || String(lastQuoteSend(order?.quote)?.to ?? '').trim()\n}\n\nexport type QuoteSendRefusal = 'not-a-quote' | 'paid' | 'no-address' | 'bad-address'\n\n/** Why the quote cannot be emailed to `to` now, if it cannot. */\nexport function quoteSendRefusal(\n order: Pick<HostOrder, 'channel' | 'status' | 'quote'> | null | undefined,\n to: string,\n): QuoteSendRefusal | null {\n if (!order || !isQuote(order) || !order.quote) return 'not-a-quote'\n if (!isUnpaidQuote(order)) return 'paid'\n if (!to) return 'no-address'\n if (to.length > 320 || !EMAIL.test(to)) return 'bad-address'\n return null\n}\n\nexport function quoteSendRefusalMessage(reason: QuoteSendRefusal): string {\n switch (reason) {\n case 'not-a-quote':\n return 'Unknown quote'\n case 'paid':\n return 'This quote has been paid, so it is an order now and is not sent again.'\n case 'no-address':\n return 'This quote has no email for the customer. Add one to the quote, or type where to send it.'\n case 'bad-address':\n return 'Enter a valid email address to send the quote to.'\n }\n}\n\n/**\n * The subject a send defaults to: the conversation's, so it stays one\n * conversation, else `Quote #1042 from Acme Signs`.\n */\nexport function quoteEmailDefaultSubject(\n order: Pick<HostOrder, 'number' | 'quote'>,\n businessName: string,\n quoteId?: string,\n): string {\n const thread = String(order.quote?.emailThread?.subject ?? '').trim()\n if (thread) return thread\n const name = String(businessName ?? '').trim()\n const number = formatQuoteNumber(order, quoteId)\n return name ? `${number} from ${name}` : number\n}\n\n/** What the console sends: where, under what subject, and the business's message. */\nexport interface QuoteSendInput {\n to: string\n subject: string\n message: string\n}\n\n/** A send as the route received it, trimmed, or what to fix. `to` and `subject` may be empty: the defaults fill them. */\nexport function parseQuoteSendInput(raw: unknown): { ok: true; input: QuoteSendInput } | { ok: false; error: string } {\n const source = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>\n const text = (value: unknown) => (typeof value === 'string' ? value : '')\n const to = text(source['to']).trim()\n // A subject is one header line.\n const subject = text(source['subject']).replace(/[\\r\\n]+/g, ' ').trim()\n const message = text(source['message']).replace(/\\r\\n?/g, '\\n').trim()\n if (subject.length > QUOTE_MAX_SEND_SUBJECT) {\n return { ok: false, error: `Keep the subject under ${QUOTE_MAX_SEND_SUBJECT} characters.` }\n }\n if (message.length > QUOTE_MAX_SEND_MESSAGE) {\n return { ok: false, error: `Keep the message under ${QUOTE_MAX_SEND_MESSAGE.toLocaleString('en-US')} characters.` }\n }\n return { ok: true, input: { to, subject, message } }\n}\n\n/**\n * The quote once an email went out: the send on record, the conversation\n * moved on, a line on the timeline, and the quote at Sent, unless the\n * customer has already answered this revision (approved it, or asked for\n * changes), which stays what it says.\n */\nexport function quoteAfterSend(\n order: HostOrder,\n send: QuoteSendRecord,\n thread: QuoteEmailThread,\n): HostOrder {\n const quote = order.quote as OrderQuote\n const answered = latestQuoteResponse(quote) !== null\n return {\n ...order,\n timeline: appendOrderEvent(\n order,\n 'quote-sent',\n `Revision ${send.revision} emailed to ${send.to} by ${send.by}`,\n send.atMs,\n ),\n quote: {\n ...quote,\n stage: answered ? quote.stage : 'sent',\n sends: [...quoteSends(quote), send].slice(-QUOTE_MAX_SENDS),\n emailThread: thread,\n },\n }\n}\n"],"names":["appendOrderEvent","quoteLinkVersion","latestQuoteResponse","formatQuoteNumber","isQuote","isUnpaidQuote","QUOTE_MAX_SENDS","QUOTE_MAX_SEND_MESSAGE","QUOTE_MAX_SEND_SUBJECT","EMAIL","quoteSends","quote","Array","isArray","sends","filter","send","lastQuoteSend","length","quoteSendIsNewRevision","last","Boolean","Number","revision","quoteSendReplacesLink","linkVersion","quoteSendLabel","quoteSendRecipient","order","typed","String","trim","customer","email","quoteSendPrefill","to","quoteSendRefusal","test","quoteSendRefusalMessage","reason","quoteEmailDefaultSubject","businessName","quoteId","thread","emailThread","subject","name","number","parseQuoteSendInput","raw","source","text","value","replace","message","ok","error","toLocaleString","input","quoteAfterSend","answered","timeline","by","atMs","stage","slice"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAwB,uBAAmB;AACpE,SAASC,gBAAgB,QAAQ,0BAAsB;AACvD,SAASC,mBAAmB,QAAQ,6BAAyB;AAC7D,SACEC,iBAAiB,EACjBC,OAAO,EACPC,aAAa,QAIR,uBAAmB;AAE1B;;;;;;;;;;;;;;;;;;;;2CAoB2C,GAE3C,iEAAiE,GACjE,OAAO,MAAMC,kBAAkB,GAAE;AAEjC,wCAAwC,GACxC,OAAO,MAAMC,yBAAyB,KAAK;AAE3C,wCAAwC,GACxC,OAAO,MAAMC,yBAAyB,IAAG;AAEzC,MAAMC,QAAQ;AAEd,+CAA+C,GAC/C,OAAO,SAASC,WAAWC,KAAmD;IAC5E,OAAOC,MAAMC,OAAO,CAACF,yBAAAA,MAAOG,KAAK,IAAIH,MAAMG,KAAK,CAACC,MAAM,CAAC,CAACC,OAASA,QAAQ,OAAOA,SAAS,YAAY,EAAE;AAC1G;AAEA,kDAAkD,GAClD,OAAO,SAASC,cAAcN,KAAmD;IAC/E,MAAMG,QAAQJ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O,CAAC,uBAAuB,EAAEhD,uBAAuB,YAAY,CAAC;QAAC;IAC5F;IACA,IAAI8C,QAAQpC,MAAM,GAAGX,wBAAwB;QAC3C,OAAO;YAAEgD,IAAI;YAAOC,OAAO,CAAC,uBAAuB,EAAEjD,uBAAuBkD,cAAc,CAAC,SAAS,YAAY,CAAC;QAAC;IACpH;IACA,OAAO;QAAEF,IAAI;QAAMG,OAAO;YAAEvB;YAAIU;YAASS;QAAQ;IAAE;AACrD;AAEA;;;;;CAKC,GACD,OAAO,SAASK,eACd/B,KAAgB,EAChBZ,IAAqB,EACrB2B,MAAwB;IAExB,MAAMhC,QAAQiB,MAAMjB,KAAK;IACzB,MAAMiD,WAAW1D,oBAAoBS,WAAW;IAChD,OAAO,aACFiB;QACHiC,UAAU7D,iBACR4B,OACA,cACA,CAAC,SAAS,EAAEZ,KAAKO,QAAQ,CAAC,YAAY,EAAEP,KAAKmB,EAAE,CAAC,IAAI,EAAEnB,KAAK8C,EAAE,EAAE,EAC/D9C,KAAK+C,IAAI;QAEXpD,OAAO,aACFA;YACHqD,OAAOJ,WAAWjD,MAAMqD,KAAK,GAAG;YAChClD,OAAO;mBAAIJ,WAAWC;gBAAQK;aAAK,CAACiD,KAAK,CAAC,CAAC3D;YAC3CsC,aAAaD;;;AAGnB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-quote-email.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 { appendOrderEvent, type HostOrder } from './commerce-orders'\nimport { quoteLinkVersion } from './commerce-quote-pay'\nimport { currentQuoteProofs, latestQuoteResponse } from './commerce-quote-proofs'\nimport {\n formatProofNumber,\n formatQuoteNumber,\n isQuote,\n isUnpaidQuote,\n quoteIsProofOnly,\n type OrderQuote,\n type QuoteEmailThread,\n type QuoteSendRecord,\n} from './commerce-quotes'\n\n/*==========================================\n * EMAILING A QUOTE TO THE CUSTOMER (AGL-4097).\n *\n * The business sends the quote from the console: one email in the site's\n * look with its message, the proof, the PDF and the pay button, in the\n * customer's existing conversation when there is one. Each send is recorded\n * on the quote (`quote.sends`) with the revision it carried and the pay link\n * version it carried, and the conversation is kept as `quote.emailThread`.\n *\n * THE PAY LINK ON A NEW REVISION. When the customer was emailed an earlier\n * revision, the first email of a new revision gives them a new pay link and\n * retires the old one (slice 2's Replace link), so the link in the earlier\n * email opens a page saying the quote was updated. A resend of the same\n * revision keeps the link. \"Was the link already replaced since that email\"\n * is read off the record (the link version it carried), which is also what\n * keeps a send that failed after replacing the link from replacing it again\n * when it is retried.\n *\n * Pure: the console's Send button and the server's send action read the\n * same answers.\n *=========================================*/\n\n/** The most sends a quote keeps on record; the oldest go first. */\nexport const QUOTE_MAX_SENDS = 50\n\n/** The longest message a send carries. */\nexport const QUOTE_MAX_SEND_MESSAGE = 5_000\n\n/** The longest subject a send carries. */\nexport const QUOTE_MAX_SEND_SUBJECT = 200\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/** The quote's sends on record, oldest first. */\nexport function quoteSends(quote: Pick<OrderQuote, 'sends'> | null | undefined): QuoteSendRecord[] {\n return Array.isArray(quote?.sends) ? quote.sends.filter((send) => send && typeof send === 'object') : []\n}\n\n/** The last time the quote was emailed, or null. */\nexport function lastQuoteSend(quote: Pick<OrderQuote, 'sends'> | null | undefined): QuoteSendRecord | null {\n const sends = quoteSends(quote)\n return sends.length ? sends[sends.length - 1] : null\n}\n\n/**\n * Whether emailing the quote now hands the customer a new revision of a quote\n * they were already emailed: an earlier revision went out, and this one has\n * not yet. The quote's first email (whatever revision it is at, since\n * revisions nobody was sent replace nothing) and a resend of the revision\n * already sent are neither, so their email does not call itself an update.\n */\nexport function quoteSendIsNewRevision(quote: Pick<OrderQuote, 'sends' | 'revision'> | null | undefined): boolean {\n const last = lastQuoteSend(quote)\n return Boolean(last) && Number(last.revision) < Number(quote?.revision ?? 1)\n}\n\n/**\n * Whether emailing the quote now gives the customer a new pay link: they were\n * emailed an earlier revision, and the link has not been replaced since.\n */\nexport function quoteSendReplacesLink(\n quote: Pick<OrderQuote, 'sends' | 'revision' | 'linkVersion'> | null | undefined,\n): boolean {\n if (!quoteSendIsNewRevision(quote)) return false\n return Number(lastQuoteSend(quote)?.linkVersion) === quoteLinkVersion(quote)\n}\n\n/** What the console's Send button says: `Send quote` (`Send proof` for one with no price yet), `Send again`, or `Send revision 2`. */\nexport function quoteSendLabel(quote: Pick<OrderQuote, 'sends' | 'revision'> | null | undefined, proofOnly = false): string {\n if (!lastQuoteSend(quote)) return proofOnly ? 'Send proof' : 'Send quote'\n return quoteSendIsNewRevision(quote) ? `Send revision ${Number(quote?.revision ?? 1)}` : 'Send again'\n}\n\n/** Where the quote goes: what was typed in the dialog, else the customer's email. */\nexport function quoteSendRecipient(\n order: Pick<HostOrder, 'quote'> | null | undefined,\n typed: string | null | undefined,\n): string {\n return String(typed ?? '').trim() || String(order?.quote?.customer?.email ?? '').trim()\n}\n\n/**\n * Who the console's send form starts addressed to: the customer's email, else\n * where the quote was last emailed, so Send again and Send revision N go\n * where the last one went when the quote names no email.\n */\nexport function quoteSendPrefill(order: Pick<HostOrder, 'quote'> | null | undefined): string {\n return quoteSendRecipient(order, null) || String(lastQuoteSend(order?.quote)?.to ?? '').trim()\n}\n\nexport type QuoteSendRefusal = 'not-a-quote' | 'paid' | 'nothing-to-send' | 'no-address' | 'bad-address'\n\n/** Why the quote cannot be emailed to `to` now, if it cannot. */\nexport function quoteSendRefusal(\n order: (Pick<HostOrder, 'channel' | 'status' | 'quote'> & Partial<Pick<HostOrder, 'lineItems'>>) | null | undefined,\n to: string,\n): QuoteSendRefusal | null {\n if (!order || !isQuote(order) || !order.quote) return 'not-a-quote'\n if (!isUnpaidQuote(order)) return 'paid'\n // A new revision of a proof only quote starts with no proof, and so with nothing to show (AGL-4184).\n if (quoteIsProofOnly(order) && currentQuoteProofs(order.quote).length === 0) return 'nothing-to-send'\n if (!to) return 'no-address'\n if (to.length > 320 || !EMAIL.test(to)) return 'bad-address'\n return null\n}\n\nexport function quoteSendRefusalMessage(reason: QuoteSendRefusal): string {\n switch (reason) {\n case 'not-a-quote':\n return 'Unknown quote'\n case 'paid':\n return 'This quote has been paid, so it is an order now and is not sent again.'\n case 'nothing-to-send':\n return 'This quote has no items and no proof on this revision yet. Add one, then send it.'\n case 'no-address':\n return 'This quote has no email for the customer. Add one to the quote, or type where to send it.'\n case 'bad-address':\n return 'Enter a valid email address to send the quote to.'\n }\n}\n\n/**\n * The subject a send defaults to: the conversation's, so it stays one\n * conversation, else `Quote #1042 from Acme Signs` (`Proof #1042` for one with\n * no price yet).\n */\nexport function quoteEmailDefaultSubject(\n order: Pick<HostOrder, 'number' | 'quote'> & Partial<Pick<HostOrder, 'lineItems'>>,\n businessName: string,\n quoteId?: string,\n): string {\n const thread = String(order.quote?.emailThread?.subject ?? '').trim()\n if (thread) return thread\n const name = String(businessName ?? '').trim()\n const number = quoteIsProofOnly(order) ? formatProofNumber(order, quoteId) : formatQuoteNumber(order, quoteId)\n return name ? `${number} from ${name}` : number\n}\n\n/** What the console sends: where, under what subject, and the business's message. */\nexport interface QuoteSendInput {\n to: string\n subject: string\n message: string\n}\n\n/** A send as the route received it, trimmed, or what to fix. `to` and `subject` may be empty: the defaults fill them. */\nexport function parseQuoteSendInput(raw: unknown): { ok: true; input: QuoteSendInput } | { ok: false; error: string } {\n const source = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>\n const text = (value: unknown) => (typeof value === 'string' ? value : '')\n const to = text(source['to']).trim()\n // A subject is one header line.\n const subject = text(source['subject']).replace(/[\\r\\n]+/g, ' ').trim()\n const message = text(source['message']).replace(/\\r\\n?/g, '\\n').trim()\n if (subject.length > QUOTE_MAX_SEND_SUBJECT) {\n return { ok: false, error: `Keep the subject under ${QUOTE_MAX_SEND_SUBJECT} characters.` }\n }\n if (message.length > QUOTE_MAX_SEND_MESSAGE) {\n return { ok: false, error: `Keep the message under ${QUOTE_MAX_SEND_MESSAGE.toLocaleString('en-US')} characters.` }\n }\n return { ok: true, input: { to, subject, message } }\n}\n\n/**\n * The quote once an email went out: the send on record, the conversation\n * moved on, a line on the timeline, and the quote at Sent, unless the\n * customer has already answered this revision (approved it, or asked for\n * changes), which stays what it says.\n */\nexport function quoteAfterSend(\n order: HostOrder,\n send: QuoteSendRecord,\n thread: QuoteEmailThread,\n): HostOrder {\n const quote = order.quote as OrderQuote\n const answered = latestQuoteResponse(quote) !== null\n return {\n ...order,\n timeline: appendOrderEvent(\n order,\n 'quote-sent',\n `Revision ${send.revision} emailed to ${send.to} by ${send.by}`,\n send.atMs,\n ),\n quote: {\n ...quote,\n stage: answered ? quote.stage : 'sent',\n sends: [...quoteSends(quote), send].slice(-QUOTE_MAX_SENDS),\n emailThread: thread,\n },\n }\n}\n"],"names":["appendOrderEvent","quoteLinkVersion","currentQuoteProofs","latestQuoteResponse","formatProofNumber","formatQuoteNumber","isQuote","isUnpaidQuote","quoteIsProofOnly","QUOTE_MAX_SENDS","QUOTE_MAX_SEND_MESSAGE","QUOTE_MAX_SEND_SUBJECT","EMAIL","quoteSends","quote","Array","isArray","sends","filter","send","lastQuoteSend","length","quoteSendIsNewRevision","last","Boolean","Number","revision","quoteSendReplacesLink","linkVersion","quoteSendLabel","proofOnly","quoteSendRecipient","order","typed","String","trim","customer","email","quoteSendPrefill","to","quoteSendRefusal","test","quoteSendRefusalMessage","reason","quoteEmailDefaultSubject","businessName","quoteId","thread","emailThread","subject","name","number","parseQuoteSendInput","raw","source","text","value","replace","message","ok","error","toLocaleString","input","quoteAf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ASS;QAAQ;IAAE;AACrD;AAEA;;;;;CAKC,GACD,OAAO,SAASK,eACd/B,KAAgB,EAChBb,IAAqB,EACrB4B,MAAwB;IAExB,MAAMjC,QAAQkB,MAAMlB,KAAK;IACzB,MAAMkD,WAAW7D,oBAAoBW,WAAW;IAChD,OAAO,aACFkB;QACHiC,UAAUjE,iBACRgC,OACA,cACA,CAAC,SAAS,EAAEb,KAAKO,QAAQ,CAAC,YAAY,EAAEP,KAAKoB,EAAE,CAAC,IAAI,EAAEpB,KAAK+C,EAAE,EAAE,EAC/D/C,KAAKgD,IAAI;QAEXrD,OAAO,aACFA;YACHsD,OAAOJ,WAAWlD,MAAMsD,KAAK,GAAG;YAChCnD,OAAO;mBAAIJ,WAAWC;gBAAQK;aAAK,CAACkD,KAAK,CAAC,CAAC5D;YAC3CuC,aAAaD;;;AAGnB"}
|
|
@@ -149,8 +149,13 @@ export interface QuotePageView {
|
|
|
149
149
|
* page says "invoice" where a quote's says "quote".
|
|
150
150
|
*/
|
|
151
151
|
kind: 'quote' | 'invoice';
|
|
152
|
+
/**
|
|
153
|
+
* A proof for the customer to answer, with no price yet (AGL-4184): the page
|
|
154
|
+
* shows no lines, totals or Pay, and the view carries none of them.
|
|
155
|
+
*/
|
|
156
|
+
proofOnly: boolean;
|
|
152
157
|
storeName: string;
|
|
153
|
-
/** `Quote #1042`, or `Invoice #1042`. */
|
|
158
|
+
/** `Quote #1042`, `Proof #1042` for a proof only quote, or `Invoice #1042`. */
|
|
154
159
|
number: string;
|
|
155
160
|
/** When the quote was last written, which is the date it carries. */
|
|
156
161
|
dateMs: number | null;
|
|
@@ -16,7 +16,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import { visitorUploadIsInline } from "@aglyn/aglyn/app-utils/visitor-upload";
|
|
18
18
|
import { appendOrderEvent, formatOrderNumber } from "./commerce-orders.js";
|
|
19
|
-
import { computeQuoteTotals, describeQuoteTax, formatQuoteNumber, quoteLineAmounts, quotePaymentBlockedByApproval, quoteTaxBasisFromSettings } from "./commerce-quotes.js";
|
|
19
|
+
import { computeQuoteTotals, describeQuoteTax, formatProofNumber, formatQuoteNumber, quoteIsProofOnly, quoteLineAmounts, quotePaymentBlockedByApproval, quoteTaxBasisFromSettings } from "./commerce-quotes.js";
|
|
20
20
|
import { currentQuoteProofs, latestQuoteResponse, quoteRespondRefusal } from "./commerce-quote-proofs.js";
|
|
21
21
|
import { storefrontTaxDecision } from "./commerce-tax-decision.js";
|
|
22
22
|
import { engineLineTaxPercentages, storeTaxAllowsEngine } from "./commerce-tax-engine.js";
|
|
@@ -254,10 +254,17 @@ function discountLabel(discount) {
|
|
|
254
254
|
const lines = (_order_lineItems = order.lineItems) != null ? _order_lineItems : [];
|
|
255
255
|
const status = quotePageStatus(order.status);
|
|
256
256
|
const unpaid = status.status === 'unpaid';
|
|
257
|
+
const proofOnly = quoteIsProofOnly(order);
|
|
257
258
|
const payTax = quotePayTax(quote, input.store);
|
|
258
259
|
const charge = quoteCheckoutCharge(order, input.orderId, input.store);
|
|
259
260
|
const stored = order.totals;
|
|
260
|
-
const totals =
|
|
261
|
+
const totals = proofOnly ? {
|
|
262
|
+
itemsCents: 0,
|
|
263
|
+
discountCents: 0,
|
|
264
|
+
shippingCents: 0,
|
|
265
|
+
taxCents: 0,
|
|
266
|
+
totalCents: 0
|
|
267
|
+
} : unpaid || !stored ? {
|
|
261
268
|
itemsCents: charge.itemsCents,
|
|
262
269
|
discountCents: charge.discountCents,
|
|
263
270
|
shippingCents: charge.shippingCents,
|
|
@@ -270,14 +277,15 @@ function discountLabel(discount) {
|
|
|
270
277
|
taxCents: cents(stored.taxCents),
|
|
271
278
|
totalCents: cents(stored.totalCents)
|
|
272
279
|
};
|
|
273
|
-
const approvalRequired = unpaid && quotePaymentBlockedByApproval(quote);
|
|
274
|
-
const taxAtPayment = unpaid && payTax.basis.kind === 'at-payment';
|
|
280
|
+
const approvalRequired = unpaid && !proofOnly && quotePaymentBlockedByApproval(quote);
|
|
281
|
+
const taxAtPayment = unpaid && !proofOnly && payTax.basis.kind === 'at-payment';
|
|
275
282
|
const refused = unpaid ? payLinkRefusalWithPayments(quotePayRefusal(order, input.orderId, input.store), input.paymentsReady) : null;
|
|
276
283
|
return {
|
|
277
284
|
state: 'quote',
|
|
278
285
|
kind: 'quote',
|
|
286
|
+
proofOnly,
|
|
279
287
|
storeName: input.storeName,
|
|
280
|
-
number: formatQuoteNumber(order, input.orderId),
|
|
288
|
+
number: proofOnly ? formatProofNumber(order, input.orderId) : formatQuoteNumber(order, input.orderId),
|
|
281
289
|
dateMs: Number((_ref = quote == null ? void 0 : quote.updatedAtMs) != null ? _ref : quote == null ? void 0 : quote.createdAtMs) || null,
|
|
282
290
|
version: Number(quote == null ? void 0 : quote.updatedAtMs) || 0,
|
|
283
291
|
currency: input.currency || 'USD',
|
|
@@ -289,7 +297,7 @@ function discountLabel(discount) {
|
|
|
289
297
|
totals,
|
|
290
298
|
discountLabel: discountLabel(quote == null ? void 0 : quote.discount),
|
|
291
299
|
// Once paid, the tax is what was charged: Stripe's figure under Stripe Tax.
|
|
292
|
-
taxLabel: unpaid || payTax.basis.kind !== 'at-payment' ? describeQuoteTax(payTax.basis) : 'Tax',
|
|
300
|
+
taxLabel: proofOnly ? '' : unpaid || payTax.basis.kind !== 'at-payment' ? describeQuoteTax(payTax.basis) : 'Tax',
|
|
293
301
|
taxAtPayment,
|
|
294
302
|
shippingAtPayment: false,
|
|
295
303
|
notes: text(quote == null ? void 0 : quote.notes),
|
|
@@ -300,8 +308,8 @@ function discountLabel(discount) {
|
|
|
300
308
|
receiptUrl: unpaid ? null : (_input_receiptUrl = input.receiptUrl) != null ? _input_receiptUrl : null,
|
|
301
309
|
approvalRequired,
|
|
302
310
|
payable: unpaid && refused === null,
|
|
303
|
-
notPayableMessage: refused === 'payments-unavailable' ? payLinkPaymentsUnavailableMessage(input.storeName, 'quote') : null,
|
|
304
|
-
taxKey: unpaid ? quoteTaxBasisKey(payTax.basis) : null,
|
|
311
|
+
notPayableMessage: !proofOnly && refused === 'payments-unavailable' ? payLinkPaymentsUnavailableMessage(input.storeName, 'quote') : null,
|
|
312
|
+
taxKey: unpaid && !proofOnly ? quoteTaxBasisKey(payTax.basis) : null,
|
|
305
313
|
revision: Math.max(1, Number((_ref1 = quote == null ? void 0 : quote.revision) != null ? _ref1 : 1) || 1),
|
|
306
314
|
proofs: currentQuoteProofs(quote).map((proof)=>{
|
|
307
315
|
var _proof_name, _proof_contentType, _proof_contentType1;
|
|
@@ -469,6 +477,8 @@ function lineSummary(lines) {
|
|
|
469
477
|
*/ export function quotePayRefusal(order, orderId, store) {
|
|
470
478
|
if (order.status === 'cancelled' || order.status === 'refunded') return 'closed';
|
|
471
479
|
if (order.status !== 'pending') return 'paid';
|
|
480
|
+
// No lines, no price: nothing to pay, whatever the proof or the store's setup says (AGL-4184).
|
|
481
|
+
if (quoteIsProofOnly(order)) return 'nothing-to-pay';
|
|
472
482
|
if (quotePaymentBlockedByApproval(order.quote)) return 'approval-required';
|
|
473
483
|
if (store && storefrontTaxDecision({
|
|
474
484
|
settings: store.tax
|