@aglyn/plugins-commerce 1.15.2 → 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +13 -13
- package/src/lib/components/cart.js +2 -1
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/console/payments-settings-card.component.js +6 -1
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-api.d.ts +5 -0
- package/src/lib/components/console/pos/pos-api.js.map +1 -1
- package/src/lib/components/console/pos/pos-tender-dialogs.component.d.ts +2 -0
- package/src/lib/components/console/pos/pos-tender-dialogs.component.js +13 -6
- package/src/lib/components/console/pos/pos-tender-dialogs.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-tender-panel.component.js +7 -4
- package/src/lib/components/console/pos/pos-tender-panel.component.js.map +1 -1
- package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
- package/src/lib/components/console/product-add-ons-fields.component.js +96 -3
- package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
- package/src/lib/components/console/product-builder-fields.component.d.ts +39 -0
- package/src/lib/components/console/product-builder-fields.component.js +195 -0
- package/src/lib/components/console/product-builder-fields.component.js.map +1 -0
- package/src/lib/components/console/product-editor-dialog.component.js +35 -2
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/quote-editor-dialog.component.js +43 -6
- package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/quote-messages.component.d.ts +21 -0
- package/src/lib/components/console/quote-messages.component.js +185 -0
- package/src/lib/components/console/quote-messages.component.js.map +1 -0
- package/src/lib/components/console/quote-pay-link.component.js +1 -1
- package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
- package/src/lib/components/console/quote-proofs.component.js +30 -3
- package/src/lib/components/console/quote-proofs.component.js.map +1 -1
- package/src/lib/components/console/quote-settings-card.component.d.ts +7 -3
- package/src/lib/components/console/quote-settings-card.component.js +154 -24
- package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
- package/src/lib/components/product-builder-context.d.ts +22 -0
- package/src/lib/components/product-builder-context.js +21 -0
- package/src/lib/components/product-builder-context.js.map +1 -0
- package/src/lib/components/product-builder-mockup.d.ts +42 -0
- package/src/lib/components/product-builder-mockup.js +120 -0
- package/src/lib/components/product-builder-mockup.js.map +1 -0
- package/src/lib/components/product-builder-sample.d.ts +63 -0
- package/src/lib/components/product-builder-sample.js +96 -0
- package/src/lib/components/product-builder-sample.js.map +1 -0
- package/src/lib/components/product-choice-cards.d.ts +51 -0
- package/src/lib/components/product-choice-cards.js +311 -0
- package/src/lib/components/product-choice-cards.js.map +1 -0
- package/src/lib/components/product-detail-panels.d.ts +42 -0
- package/src/lib/components/product-detail-panels.js +185 -0
- package/src/lib/components/product-detail-panels.js.map +1 -0
- package/src/lib/components/product-detail.d.ts +20 -12
- package/src/lib/components/product-detail.js +136 -221
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/product-grid.d.ts +7 -0
- package/src/lib/components/product-grid.js +11 -8
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/product-options-field-body.d.ts +9 -8
- package/src/lib/components/product-options-field-body.js +152 -3
- package/src/lib/components/product-options-field-body.js.map +1 -1
- package/src/lib/components/product-options-field.js +1 -1
- package/src/lib/components/product-options-field.js.map +1 -1
- package/src/lib/components/product-photo-fit.d.ts +49 -0
- package/src/lib/components/product-photo-fit.js +58 -0
- package/src/lib/components/product-photo-fit.js.map +1 -0
- package/src/lib/components/product-restock-notify.d.ts +12 -0
- package/src/lib/components/product-restock-notify.js +86 -0
- package/src/lib/components/product-restock-notify.js.map +1 -0
- package/src/lib/components/quote-messages-panel.d.ts +21 -0
- package/src/lib/components/quote-messages-panel.js +191 -0
- package/src/lib/components/quote-messages-panel.js.map +1 -0
- package/src/lib/components/quote-page-body.js +15 -1
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/components/quote-proof-panel.d.ts +6 -3
- package/src/lib/components/quote-proof-panel.js +139 -14
- package/src/lib/components/quote-proof-panel.js.map +1 -1
- package/src/lib/components/related-products.d.ts +7 -0
- package/src/lib/components/related-products.js +8 -6
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/constants/quote-page.d.ts +8 -0
- package/src/lib/constants/quote-page.js +11 -0
- package/src/lib/constants/quote-page.js.map +1 -1
- package/src/lib/model/commerce-cart.d.ts +6 -1
- package/src/lib/model/commerce-cart.js +5 -1
- package/src/lib/model/commerce-cart.js.map +1 -1
- package/src/lib/model/commerce-invoices.js +5 -1
- package/src/lib/model/commerce-invoices.js.map +1 -1
- package/src/lib/model/commerce-pos-ops.d.ts +3 -0
- package/src/lib/model/commerce-pos-ops.js +3 -0
- package/src/lib/model/commerce-pos-ops.js.map +1 -1
- package/src/lib/model/commerce-pos.d.ts +8 -0
- package/src/lib/model/commerce-pos.js.map +1 -1
- package/src/lib/model/commerce-quote-messages.d.ts +106 -0
- package/src/lib/model/commerce-quote-messages.js +146 -0
- package/src/lib/model/commerce-quote-messages.js.map +1 -0
- package/src/lib/model/commerce-quote-pay.d.ts +31 -2
- package/src/lib/model/commerce-quote-pay.js +31 -7
- package/src/lib/model/commerce-quote-pay.js.map +1 -1
- package/src/lib/model/commerce-quote-proofs.d.ts +47 -8
- package/src/lib/model/commerce-quote-proofs.js +73 -18
- package/src/lib/model/commerce-quote-proofs.js.map +1 -1
- package/src/lib/model/commerce-quote-request.d.ts +14 -4
- package/src/lib/model/commerce-quote-request.js +25 -2
- package/src/lib/model/commerce-quote-request.js.map +1 -1
- package/src/lib/model/commerce-quotes.d.ts +56 -3
- package/src/lib/model/commerce-quotes.js +47 -2
- package/src/lib/model/commerce-quotes.js.map +1 -1
- package/src/lib/model/commerce.d.ts +12 -1
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/index.d.ts +1 -0
- package/src/lib/model/index.js +1 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/pos-cellular.d.ts +5 -0
- package/src/lib/model/pos-cellular.js.map +1 -1
- package/src/lib/model/product-card-rules.d.ts +41 -0
- package/src/lib/model/product-card-rules.js +90 -0
- package/src/lib/model/product-card-rules.js.map +1 -0
- package/src/lib/model/product-modifiers.d.ts +11 -0
- package/src/lib/model/product-modifiers.js +10 -0
- package/src/lib/model/product-modifiers.js.map +1 -1
- package/src/lib/model/product-write.d.ts +3 -0
- package/src/lib/server/billing-webhook.js +6 -2
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cancel-order.js +15 -0
- package/src/lib/server/cancel-order.js.map +1 -1
- package/src/lib/server/channel-order-updates.js +15 -1
- package/src/lib/server/channel-order-updates.js.map +1 -1
- package/src/lib/server/channel-orders.js +20 -0
- package/src/lib/server/channel-orders.js.map +1 -1
- package/src/lib/server/checkout.js +1 -1
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/local-fulfillment.js +1 -1
- package/src/lib/server/local-fulfillment.js.map +1 -1
- package/src/lib/server/pos-cellular-billing.d.ts +1 -1
- package/src/lib/server/pos-cellular-billing.js +2 -1
- package/src/lib/server/pos-cellular-billing.js.map +1 -1
- package/src/lib/server/pos-cellular.d.ts +3 -1
- package/src/lib/server/pos-cellular.js +15 -8
- package/src/lib/server/pos-cellular.js.map +1 -1
- package/src/lib/server/pos-offline-sync.d.ts +3 -3
- package/src/lib/server/pos-offline-sync.js +17 -4
- package/src/lib/server/pos-offline-sync.js.map +1 -1
- package/src/lib/server/pos-order.js +17 -6
- package/src/lib/server/pos-order.js.map +1 -1
- package/src/lib/server/pos-payment.js +27 -11
- package/src/lib/server/pos-payment.js.map +1 -1
- package/src/lib/server/pos-reader-splash.js +10 -5
- package/src/lib/server/pos-reader-splash.js.map +1 -1
- package/src/lib/server/pos-readers.js +34 -10
- package/src/lib/server/pos-readers.js.map +1 -1
- package/src/lib/server/pos-return.js +19 -3
- package/src/lib/server/pos-return.js.map +1 -1
- package/src/lib/server/pos-stripe.d.ts +14 -0
- package/src/lib/server/pos-stripe.js +6 -2
- package/src/lib/server/pos-stripe.js.map +1 -1
- package/src/lib/server/pos-terminal-connection-token.js +23 -9
- package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
- package/src/lib/server/pos-terminal.d.ts +80 -14
- package/src/lib/server/pos-terminal.js +393 -123
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/server/product-drafts.d.ts +1 -1
- package/src/lib/server/product-drafts.js +4 -3
- package/src/lib/server/product-drafts.js.map +1 -1
- package/src/lib/server/product-writer.js +5 -4
- package/src/lib/server/product-writer.js.map +1 -1
- package/src/lib/server/product.d.ts +11 -0
- package/src/lib/server/product.js +18 -3
- package/src/lib/server/product.js.map +1 -1
- package/src/lib/server/products-write.js +4 -3
- package/src/lib/server/products-write.js.map +1 -1
- package/src/lib/server/quote-email.d.ts +26 -0
- package/src/lib/server/quote-email.js +73 -7
- package/src/lib/server/quote-email.js.map +1 -1
- package/src/lib/server/quote-messages.d.ts +72 -0
- package/src/lib/server/quote-messages.js +356 -0
- package/src/lib/server/quote-messages.js.map +1 -0
- package/src/lib/server/quote-pay.d.ts +42 -0
- package/src/lib/server/quote-pay.js +81 -4
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote-proofs.d.ts +1 -1
- package/src/lib/server/quote-proofs.js +63 -19
- package/src/lib/server/quote-proofs.js.map +1 -1
- package/src/lib/server/quote.d.ts +12 -0
- package/src/lib/server/quote.js +44 -14
- package/src/lib/server/quote.js.map +1 -1
- package/src/lib/server/refund.js +3 -1
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server/reserve-stock.js +9 -0
- package/src/lib/server/reserve-stock.js.map +1 -1
- package/src/lib/server/returns.js +15 -1
- package/src/lib/server/returns.js.map +1 -1
- package/src/lib/server/reviews.js +15 -0
- package/src/lib/server/reviews.js.map +1 -1
- package/src/lib/server/sold-out-drop.d.ts +58 -0
- package/src/lib/server/sold-out-drop.js +81 -0
- package/src/lib/server/sold-out-drop.js.map +1 -0
- package/src/lib/server/stock-levels.js +9 -0
- package/src/lib/server/stock-levels.js.map +1 -1
- package/src/lib/server/stripe-refund.d.ts +7 -0
- package/src/lib/server/stripe-refund.js +26 -7
- package/src/lib/server/stripe-refund.js.map +1 -1
- package/src/lib/server.js +2 -0
- package/src/lib/server.js.map +1 -1
- package/src/lib/tenant-emails.js +85 -2
- package/src/lib/tenant-emails.js.map +1 -1
- package/src/lib/testing/fake-seller-payment-account.d.ts +29 -0
- package/src/lib/testing/fake-seller-payment-account.js +40 -0
- package/src/lib/testing/fake-seller-payment-account.js.map +1 -0
- package/src/lib/transfer/product-transfer.js +6 -5
- package/src/lib/transfer/product-transfer.js.map +1 -1
- package/src/lib/transfer/products.server.js +4 -3
- package/src/lib/transfer/products.server.js.map +1 -1
- package/src/lib/utils/quote-email-content.d.ts +6 -0
- package/src/lib/utils/quote-email-content.js +6 -3
- package/src/lib/utils/quote-email-content.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/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","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,EACPC,gBAAgB,QAIX,uBAAmB;AAE1B,SAASC,qBAAqB,QAAQ,6BAAyB;AAC/D,SAASC,oBAAoB,QAAQ,yBAAqB;AAmC1D,0EAA0E,GAC1E,OAAO,MAAMC,oBAAoB,GAAE;AAEnC,MAAMC,QAAQ;AAEd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,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"}
|
|
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 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 approvalStatements: [],\n proofAccess: 'open',\n proofAccessMessage: null,\n messages: [],\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","approvalStatements","proofAccess","proofAccessMessage","messages","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,EACPC,gBAAgB,QAIX,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;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A,WAAW,eAAe,OAAO;IAChE,OAAO;AACT;AAEA;;;;CAIC,GACD,OAAO,SAASyG,iBACdnI,KAA6D,EAC7D+G,IAA4B,EAC5Bc,MAAwB;IAOxB,OAAO;QACL9G,UAAU/C,iBACRgC,OACA,gBACA,oFAAoF;QACpF,GAAG+G,KAAKqB,IAAI,GAAG,iBAAiB,UAAU,4BAA4B,EAAErB,KAAKsB,EAAE,EAAE,EACjFtB,KAAK7F,IAAI;QAEX0F,cAAc;eAAIA,aAAa5G;YAAQ+G;SAAK,CAAC9D,KAAK,CAAC,CAAC9D;OAChDa,MAAMC,KAAK,GAAG;QAAEA,OAAO;YAAEyH,aAAaG;QAAO;IAAE,IAAI;QAAEH,aAAaG;IAAO;AAEjF"}
|
|
@@ -46,6 +46,9 @@ export interface PosOrderTender {
|
|
|
46
46
|
last4?: string;
|
|
47
47
|
cashTenderedCents?: number;
|
|
48
48
|
changeCents?: number;
|
|
49
|
+
/** Where a card tender's charge lives: on the store's own account when `direct`. */
|
|
50
|
+
chargeModel?: 'direct';
|
|
51
|
+
stripeAccountId?: string;
|
|
49
52
|
}
|
|
50
53
|
/** The order fields the tender reader looks at. */
|
|
51
54
|
export interface PosTenderSource {
|
|
@@ -88,6 +88,9 @@ const isTenderMethod = (value)=>typeof value === 'string' && POS_TENDER_METHODS.
|
|
|
88
88
|
cashTenderedCents: wholeCents(payment.cashTenderedCents)
|
|
89
89
|
} : {}, payment.changeCents != null ? {
|
|
90
90
|
changeCents: wholeCents(payment.changeCents)
|
|
91
|
+
} : {}, payment.chargeModel === 'direct' && payment.stripeAccountId ? {
|
|
92
|
+
chargeModel: 'direct',
|
|
93
|
+
stripeAccountId: payment.stripeAccountId
|
|
91
94
|
} : {});
|
|
92
95
|
});
|
|
93
96
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-pos-ops.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 { apportionCents, type HostOrder } from './commerce-orders'\nimport { withPosHardwareReceiptNotice } from './pos-hardware-terms'\nimport { orderPayments } from './commerce-pos'\nimport type { PrintReport } from './commerce-printers'\nimport { receiptDataFromOrder } from './commerce-receipt'\n\n/*==========================================\n * RUNNING THE REGISTER (AGL-3609): shifts and the cash drawer, register\n * returns and the receipt. Pure and client-safe: the routes, the register\n * and the reports all compute from these, so a drawer's expected cash is one\n * formula wherever it is shown.\n *\n * Where each thing lives:\n *\n * hosts/{hostId}/registers/{registerId}\n * `openShiftId` — the one open shift, claimed in a transaction\n * hosts/{hostId}/registers/{registerId}/shifts/{shiftId} {@link PosShift}\n * hosts/{hostId}/registers/{registerId}/returns/{returnId} {@link PosRegisterReturn}\n * hosts/{hostId}/posStaffPins/{uid} server-only\n *\n * Everything under `registers` is written by the Admin SDK only (the\n * register pool is billed), and every member of the site may read it.\n *=========================================*/\n\n/** How one payment toward a sale was taken, in the register's tender words. */\nexport type PosTenderMethod =\n | 'cash'\n | 'card_present'\n | 'card_keyed'\n | 'card_link'\n | 'gift_card'\n | 'folio'\n /** Store credit another plugin keeps (AGL-3640). */\n | 'credit'\n\nexport const POS_TENDER_METHODS: readonly PosTenderMethod[] = [\n 'cash',\n 'card_present',\n 'card_keyed',\n 'card_link',\n 'gift_card',\n 'folio',\n 'credit',\n]\n\n/** What each tender is called on a report, a receipt and a refund. */\nexport const POS_TENDER_LABELS: Readonly<Record<PosTenderMethod, string>> = {\n cash: 'Cash',\n card_present: 'Card',\n card_keyed: 'Card (keyed)',\n card_link: 'Card (payment link)',\n gift_card: 'Gift card',\n folio: 'Room charge',\n credit: 'Store credit',\n}\n\n/** The tenders whose money moved through Stripe and goes back through it. */\nexport const POS_STRIPE_TENDERS: ReadonlySet<PosTenderMethod> = new Set([\n 'card_present',\n 'card_keyed',\n 'card_link',\n])\n\n/**\n * One settled payment toward a sale, as the shift report and a register\n * return read it.\n */\nexport interface PosOrderTender {\n /** The payment's id on the order, or `legacy` for an order before the tender ledger. */\n id: string\n method: PosTenderMethod\n /** Cents put toward the sale; never the tip, never the change. */\n amountCents: number\n tipCents: number\n paymentIntentId?: string\n giftCardId?: string\n reservationId?: string\n /** For `credit` (AGL-3640): the provider, its account handle, and its name. */\n creditProviderId?: string\n creditReference?: string\n creditLabel?: string\n cardBrand?: string\n last4?: string\n cashTenderedCents?: number\n changeCents?: number\n}\n\nconst wholeCents = (value: unknown): number => {\n const number = Math.round(Number(value))\n return Number.isFinite(number) && number > 0 ? number : 0\n}\n\n\nconst isTenderMethod = (value: unknown): value is PosTenderMethod =>\n typeof value === 'string' && (POS_TENDER_METHODS as readonly string[]).includes(value)\n\n/** The order fields the tender reader looks at. */\nexport interface PosTenderSource {\n payments?: unknown\n channel?: string\n status?: string\n totals?: { totalCents?: number; tipCents?: number } | null\n amountCents?: number\n reservationId?: string\n checkoutSessionId?: string\n paymentIntentId?: string\n}\n\n/**\n * THE ONE PLACE THE TENDER LEDGER IS READ (AGL-3609).\n *\n * A register sale may carry `payments[]` — one entry per tender, the ledger\n * the split-tender register writes (AGL-3607) — and only the payments that\n * SUCCEEDED count: a declined card or a voided gift card took nothing. An\n * order written before that ledger is one payment, inferred the way the\n * ledger's own reader infers it: a folio when it names a reservation, a card\n * link when Stripe saw it (or it came through the storefront), cash otherwise.\n *\n * The ledger's own reader (`orderPayments`) does both; this narrows it to the\n * settled payments and the fields a report or a refund reads.\n */\nexport function posOrderTenders(order: PosTenderSource | null | undefined): PosOrderTender[] {\n if (!order) return []\n return orderPayments(order as Parameters<typeof orderPayments>[0])\n .filter((payment) => payment.status === 'succeeded' && isTenderMethod(payment.method))\n .map((payment) => ({\n id: payment.id,\n method: payment.method as PosTenderMethod,\n amountCents: wholeCents(payment.amountCents),\n tipCents: wholeCents(payment.tipCents ?? (payment.id === 'legacy' ? order.totals?.tipCents : 0)),\n ...(payment.paymentIntentId ? { paymentIntentId: payment.paymentIntentId } : {}),\n ...(payment.giftCardId ? { giftCardId: payment.giftCardId } : {}),\n ...(payment.reservationId ? { reservationId: payment.reservationId } : {}),\n ...(payment.creditProviderId ? { creditProviderId: payment.creditProviderId } : {}),\n ...(payment.creditReference ? { creditReference: payment.creditReference } : {}),\n ...(payment.creditLabel ? { creditLabel: payment.creditLabel } : {}),\n ...(payment.cardBrand ? { cardBrand: payment.cardBrand } : {}),\n ...(payment.last4 ? { last4: payment.last4 } : {}),\n ...(payment.cashTenderedCents != null ? { cashTenderedCents: wholeCents(payment.cashTenderedCents) } : {}),\n ...(payment.changeCents != null ? { changeCents: wholeCents(payment.changeCents) } : {}),\n }))\n}\n\n/** A tender as one line of a receipt: `Card •• 4242`. */\nexport function posTenderLabel(\n tender: Pick<PosOrderTender, 'method' | 'cardBrand' | 'last4'> & { creditLabel?: string },\n): string {\n const base = (tender.method === 'credit' && tender.creditLabel) || POS_TENDER_LABELS[tender.method] || tender.method\n if (tender.last4) {\n return `${tender.cardBrand ? capitalize(tender.cardBrand) : base} •• ${tender.last4}`\n }\n return base\n}\n\nfunction capitalize(value: string): string {\n return value ? value.charAt(0).toUpperCase() + value.slice(1) : value\n}\n\n/*==========================================\n * SHIFTS AND THE CASH DRAWER\n *=========================================*/\n\n/**\n * Cash that moved through the drawer without a sale: money put in, money\n * paid out for a reason (a delivery, petty cash), a drop to the safe, and\n * a register return paid out in cash.\n */\nexport type PosCashEventType = 'paid_in' | 'paid_out' | 'drop' | 'refund'\n\nexport const POS_CASH_EVENT_LABELS: Readonly<Record<PosCashEventType, string>> = {\n paid_in: 'Paid in',\n paid_out: 'Paid out',\n drop: 'Safe drop',\n refund: 'Cash refund',\n}\n\nexport interface PosCashEvent {\n /** The register's attempt id, so a retried tap records one event. */\n id: string\n type: PosCashEventType\n amountCents: number\n reason: string\n /** The member who moved the cash. */\n by: string\n atMs: number\n /** The order a `refund` paid out against. */\n orderId?: string\n}\n\n/** Sales, refunds and cash movements over one shift. */\nexport interface PosShiftReport {\n orderCount: number\n /** What customers paid for the goods: order totals, tax in, tips out. */\n grossSalesCents: number\n discountsCents: number\n taxCents: number\n tipsCents: number\n salesByTender: Partial<Record<PosTenderMethod, number>>\n refundCount: number\n refundsCents: number\n refundsByTender: Partial<Record<PosTenderMethod, number>>\n /** Gross sales less refunds. */\n netSalesCents: number\n openingFloatCents: number\n cashSalesCents: number\n paidInCents: number\n paidOutCents: number\n dropsCents: number\n cashRefundsCents: number\n /** float + cash sales + paid in − paid out − drops − cash refunds. */\n expectedCashCents: number\n /** More sales were stamped with the shift than the report could read. */\n truncated?: boolean\n}\n\n/** `hosts/{hostId}/registers/{registerId}/shifts/{shiftId}`. */\nexport interface PosShift {\n hostId: string\n registerId: string\n status: 'open' | 'closed'\n openedBy: string\n /** The member's name when the shift opened, for the history and the export. */\n openedByName?: string\n openedAtMs: number\n openingFloatCents: number\n cashEvents: PosCashEvent[]\n closedBy?: string\n closedByName?: string\n /*\n * The history sorts by each of the five below (AGL-3680), and an `orderBy`\n * drops a shift that lacks the field, so the shift is opened with each one\n * `null` and the close fills them — see `POS_SHIFT_LIST_QUERY`.\n */\n closedAtMs?: number | null\n /** What the closing cashier counted in the drawer. */\n countedCashCents?: number | null\n expectedCashCents?: number | null\n /** counted − expected: positive is over, negative is short. */\n varianceCents?: number | null\n /** The Z report's `netSalesCents`, flattened so the history can order by it. */\n netSalesCents?: number | null\n closingNote?: string\n /** The Z report, frozen when the shift closed. */\n report?: PosShiftReport\n}\n\n/** The cash-event sums one formula reads. */\nexport function posCashEventTotals(events: readonly PosCashEvent[] | null | undefined): {\n paidInCents: number\n paidOutCents: number\n dropsCents: number\n cashRefundsCents: number\n} {\n const sum = (type: PosCashEventType) =>\n (events ?? [])\n .filter((event) => event?.type === type)\n .reduce((total, event) => total + wholeCents(event.amountCents), 0)\n return {\n paidInCents: sum('paid_in'),\n paidOutCents: sum('paid_out'),\n dropsCents: sum('drop'),\n cashRefundsCents: sum('refund'),\n }\n}\n\n/**\n * THE DRAWER'S EXPECTED CASH: what should be in it when it is counted.\n *\n * opening float + cash sales + paid in − paid out − safe drops − cash refunds\n *\n * Cash SALES are the cash tender's `amountCents`, which is what the sale took\n * and never what the customer handed over: the change went straight back out\n * of the same drawer. A tip left in cash is in the drawer too, so it counts.\n */\nexport function posExpectedCashCents(input: {\n openingFloatCents: number\n cashSalesCents: number\n paidInCents: number\n paidOutCents: number\n dropsCents: number\n cashRefundsCents: number\n}): number {\n return (\n wholeCents(input.openingFloatCents) +\n wholeCents(input.cashSalesCents) +\n wholeCents(input.paidInCents) -\n wholeCents(input.paidOutCents) -\n wholeCents(input.dropsCents) -\n wholeCents(input.cashRefundsCents)\n )\n}\n\n/** A sale as the shift report reads it. */\nexport interface PosShiftSale extends PosTenderSource {\n totals?: {\n totalCents?: number\n discountCents?: number\n taxCents?: number\n tipCents?: number\n } | null\n}\n\n/** A register return as the shift report reads it. */\nexport interface PosShiftRefund {\n refundedCents: number\n tenders: Array<{ method: PosTenderMethod; amountCents: number }>\n}\n\n/**\n * The X report (mid-shift) and the Z report (at close) are this one function\n * over the sales stamped with the shift, the returns rung at the register\n * during it and the shift's own cash events. A pending sale took no money and\n * a cancelled one gave it back, so neither counts; a sale refunded LATER\n * still counts as a sale, and its refund is counted where it was paid out.\n */\nexport function computePosShiftReport(input: {\n shift: Pick<PosShift, 'openingFloatCents' | 'cashEvents'>\n sales: readonly PosShiftSale[]\n refunds: readonly PosShiftRefund[]\n truncated?: boolean\n}): PosShiftReport {\n const salesByTender: Partial<Record<PosTenderMethod, number>> = {}\n const refundsByTender: Partial<Record<PosTenderMethod, number>> = {}\n let orderCount = 0\n let grossSalesCents = 0\n let discountsCents = 0\n let taxCents = 0\n let tipsCents = 0\n let cashSalesCents = 0\n for (const sale of input.sales) {\n if (sale.status === 'pending' || sale.status === 'cancelled') continue\n const tenders = posOrderTenders(sale)\n orderCount += 1\n grossSalesCents += wholeCents(sale.totals?.totalCents ?? sale.amountCents)\n discountsCents += wholeCents(sale.totals?.discountCents)\n taxCents += wholeCents(sale.totals?.taxCents)\n const tenderTips = tenders.reduce((sum, tender) => sum + tender.tipCents, 0)\n tipsCents += Math.max(wholeCents(sale.totals?.tipCents), tenderTips)\n for (const tender of tenders) {\n salesByTender[tender.method] = (salesByTender[tender.method] ?? 0) + tender.amountCents\n if (tender.method === 'cash') cashSalesCents += tender.amountCents + tender.tipCents\n }\n }\n let refundsCents = 0\n for (const refund of input.refunds) {\n refundsCents += wholeCents(refund.refundedCents)\n for (const tender of refund.tenders ?? []) {\n if (!isTenderMethod(tender.method)) continue\n refundsByTender[tender.method] =\n (refundsByTender[tender.method] ?? 0) + wholeCents(tender.amountCents)\n }\n }\n const cash = posCashEventTotals(input.shift.cashEvents)\n const openingFloatCents = wholeCents(input.shift.openingFloatCents)\n return {\n orderCount,\n grossSalesCents,\n discountsCents,\n taxCents,\n tipsCents,\n salesByTender,\n refundCount: input.refunds.length,\n refundsCents,\n refundsByTender,\n netSalesCents: grossSalesCents - refundsCents,\n openingFloatCents,\n cashSalesCents,\n ...cash,\n expectedCashCents: posExpectedCashCents({ openingFloatCents, cashSalesCents, ...cash }),\n ...(input.truncated ? { truncated: true } : {}),\n }\n}\n\n/** counted − expected; positive is over, negative is short. */\nexport function posCashVarianceCents(countedCashCents: number, expectedCashCents: number): number {\n return Math.round(Number(countedCashCents) || 0) - Math.round(Number(expectedCashCents) || 0)\n}\n\n/** `$12.34`, `-$0.50` — the register's money format, store currency USD. */\nexport function posMoney(cents: number): string {\n const value = Math.round(Number(cents) || 0)\n return `${value < 0 ? '-' : ''}$${(Math.abs(value) / 100).toFixed(2)}`\n}\n\n/** One CSV cell, quoted when it needs to be and never read as a formula. */\nfunction csvCell(value: unknown): string {\n let cell = value == null ? '' : String(value)\n if (/^[=+\\-@\\t\\r]/.test(cell) && !/^-?\\d+(\\.\\d+)?$/.test(cell)) cell = `'${cell}`\n return /[\",\\r\\n]/.test(cell) ? `\"${cell.replace(/\"/g, '\"\"')}\"` : cell\n}\n\nexport { csvCell as posCsvCell }\n\nconst dollars = (cents: number | null | undefined): string =>\n cents == null ? '' : (Math.round(cents) / 100).toFixed(2)\n\n/** The shift history as a spreadsheet: one row per shift, money in dollars. */\nexport function posShiftsCsv(\n shifts: ReadonlyArray<PosShift & { id: string; registerName?: string }>,\n memberName: (uid: string) => string = (uid) => uid,\n): string {\n const header = [\n 'Shift',\n 'Register',\n 'Opened',\n 'Opened by',\n 'Closed',\n 'Closed by',\n 'Orders',\n 'Gross sales',\n 'Refunds',\n 'Net sales',\n 'Discounts',\n 'Tax',\n 'Tips',\n 'Cash sales',\n 'Card sales',\n 'Gift card sales',\n 'Room charges',\n 'Opening float',\n 'Paid in',\n 'Paid out',\n 'Safe drops',\n 'Cash refunds',\n 'Expected cash',\n 'Counted cash',\n 'Variance',\n ]\n const iso = (ms: number | null | undefined) => (ms ? new Date(ms).toISOString() : '')\n const rows = shifts.map((shift) => {\n const report = shift.report\n const card = report\n ? (report.salesByTender.card_present ?? 0) +\n (report.salesByTender.card_keyed ?? 0) +\n (report.salesByTender.card_link ?? 0)\n : undefined\n return [\n shift.id,\n shift.registerName ?? shift.registerId,\n iso(shift.openedAtMs),\n shift.openedByName ?? memberName(shift.openedBy),\n iso(shift.closedAtMs),\n shift.closedBy ? (shift.closedByName ?? memberName(shift.closedBy)) : '',\n report?.orderCount ?? '',\n dollars(report?.grossSalesCents),\n dollars(report?.refundsCents),\n dollars(report?.netSalesCents),\n dollars(report?.discountsCents),\n dollars(report?.taxCents),\n dollars(report?.tipsCents),\n dollars(report?.cashSalesCents),\n dollars(card),\n dollars(report ? (report.salesByTender.gift_card ?? 0) : undefined),\n dollars(report ? (report.salesByTender.folio ?? 0) : undefined),\n dollars(shift.openingFloatCents),\n dollars(report?.paidInCents),\n dollars(report?.paidOutCents),\n dollars(report?.dropsCents),\n dollars(report?.cashRefundsCents),\n dollars(shift.expectedCashCents ?? report?.expectedCashCents),\n dollars(shift.countedCashCents),\n dollars(shift.varianceCents),\n ]\n })\n return [header, ...rows].map((row) => row.map(csvCell).join(',')).join('\\r\\n')\n}\n\n/*==========================================\n * RETURNS AT THE REGISTER\n *=========================================*/\n\n/** One line picked for return: its index on the order and how many units. */\nexport interface PosReturnPick {\n index: number\n quantity: number\n}\n\n/** The order fields a return reads. */\nexport interface PosReturnSource extends PosTenderSource {\n lineItems?: Array<{ unitAmountCents?: number; quantity?: number; name?: string }> | null\n totals?: {\n totalCents?: number\n discountCents?: number\n taxCents?: number\n shippingCents?: number\n tipCents?: number\n } | null\n refundedCents?: number\n refundedLineItemIds?: number[]\n /** Units of each line already returned at a register, by line index. */\n returnedQuantities?: Record<string, number>\n /** Cents already refunded to each payment by a register return. */\n posPaymentRefunds?: Record<string, number>\n}\n\n/**\n * What each line is worth back, whole: its price less its share of the\n * order's discount, plus its share of the order's tax — the same\n * apportionment `orderLineRefundCents` uses for the discount, extended to the\n * tax a register sale charged on top. Shipping and tips are not a line's.\n */\nexport function posReturnLineValues(order: PosReturnSource): number[] {\n const lines = order.lineItems ?? []\n const gross = lines.map(\n (line) =>\n Math.max(0, Math.round(Number(line?.unitAmountCents ?? 0))) *\n Math.max(1, Math.round(Number(line?.quantity ?? 1))),\n )\n const discountShares = apportionCents(gross, wholeCents(order.totals?.discountCents))\n const net = gross.map((cents, index) => Math.max(0, cents - (discountShares[index] ?? 0)))\n const taxShares = apportionCents(net, wholeCents(order.totals?.taxCents))\n return net.map((cents, index) => cents + (taxShares[index] ?? 0))\n}\n\n/** Units of each line already returned, a line refunded whole counting as all of it. */\nexport function posReturnedQuantities(order: PosReturnSource): number[] {\n const lines = order.lineItems ?? []\n const wholeLines = new Set(order.refundedLineItemIds ?? [])\n return lines.map((line, index) => {\n const quantity = Math.max(1, Math.round(Number(line?.quantity ?? 1)))\n if (wholeLines.has(index)) return quantity\n const returned = Math.round(Number(order.returnedQuantities?.[String(index)] ?? 0))\n return Math.min(quantity, Math.max(0, Number.isFinite(returned) ? returned : 0))\n })\n}\n\nexport type PosReturnPlan =\n | {\n ok: true\n refundCents: number\n /** Cents per picked line, in the order picked. */\n lineCents: number[]\n /** The order's per-line returned quantities after this return. */\n returnedQuantities: Record<string, number>\n /** Lines this return finishes, for `refundedLineItemIds`. */\n completedLines: number[]\n }\n | { ok: false; error: string }\n\n/**\n * What a return of these picks refunds, to the cent.\n *\n * Each line's value is split across its units CUMULATIVELY: returning `k` of\n * `n` units already returned `r` refunds `round(V·(r+k)/n) − round(V·r/n)`,\n * so returning a line one unit at a time refunds exactly what returning it\n * whole would have, and the rounding never strands or invents a cent. The\n * sum is capped at what is left to refund on the order — a refund given\n * from the order dialog already took its share.\n *\n * `heldElsewhere` is, per line, the units an online return (the returns\n * flow) already holds or took back. They cap what the register may take, but\n * they are not written into `returnedQuantities`, which counts only what the\n * register itself took.\n */\nexport function planPosReturn(\n order: PosReturnSource,\n picks: readonly PosReturnPick[],\n heldElsewhere: readonly number[] = [],\n): PosReturnPlan {\n const lines = order.lineItems ?? []\n if (!picks.length) return { ok: false, error: 'Pick at least one item to return.' }\n const values = posReturnLineValues(order)\n const returned = posReturnedQuantities(order)\n const seen = new Set<number>()\n const lineCents: number[] = []\n const nextReturned: Record<string, number> = {}\n for (const [index, count] of returned.entries()) if (count > 0) nextReturned[String(index)] = count\n const completedLines: number[] = []\n for (const pick of picks) {\n const index = Number(pick.index)\n const quantity = Number(pick.quantity)\n if (!Number.isInteger(index) || index < 0 || index >= lines.length) {\n return { ok: false, error: `Line ${pick.index} is not on this order.` }\n }\n if (seen.has(index)) return { ok: false, error: 'Each line can be picked once.' }\n seen.add(index)\n if (!Number.isInteger(quantity) || quantity < 1) {\n return { ok: false, error: 'Return at least one of each line you pick.' }\n }\n const total = Math.max(1, Math.round(Number(lines[index]?.quantity ?? 1)))\n const already = returned[index] ?? 0\n const held = Math.max(0, Math.round(Number(heldElsewhere[index] ?? 0)))\n if (already + held + quantity > total) {\n const left = Math.max(0, total - already - held)\n return {\n ok: false,\n error:\n left > 0\n ? `Only ${left} of \"${lines[index]?.name ?? 'that item'}\" can still be returned.`\n : held > 0\n ? `\"${lines[index]?.name ?? 'That item'}\" is already in a return. Finish it under Returns.`\n : `\"${lines[index]?.name ?? 'That item'}\" has already been returned.`,\n }\n }\n const value = values[index] ?? 0\n lineCents.push(\n Math.round((value * (already + quantity)) / total) - Math.round((value * already) / total),\n )\n nextReturned[String(index)] = already + quantity\n if (already + quantity === total) completedLines.push(index)\n }\n const remaining = Math.max(\n 0,\n wholeCents(order.totals?.totalCents) - wholeCents(order.refundedCents),\n )\n const asked = lineCents.reduce((sum, cents) => sum + cents, 0)\n const refundCents = Math.min(asked, remaining)\n if (!(refundCents > 0)) return { ok: false, error: 'Nothing is left to refund on this order.' }\n return { ok: true, refundCents, lineCents, returnedQuantities: nextReturned, completedLines }\n}\n\n/** One slice of a refund, sent back to one of the sale's payments. */\nexport interface PosRefundAllocation {\n paymentId: string\n method: PosTenderMethod\n amountCents: number\n}\n\n/**\n * What each payment can still take back: what it put toward the sale, less\n * what register returns already sent to it. A refund given from the order\n * dialog refunds through Stripe without naming a payment, so whatever it\n * took that no payment accounts for comes off the Stripe payments first.\n */\nexport function posRefundableByTender(order: PosReturnSource): Array<PosOrderTender & { refundableCents: number }> {\n const tenders = posOrderTenders(order)\n const attributed = Object.values(order.posPaymentRefunds ?? {}).reduce(\n (sum, cents) => sum + wholeCents(cents),\n 0,\n )\n let unattributed = Math.max(0, wholeCents(order.refundedCents) - attributed)\n const ordered = [...tenders].sort(\n (a, b) => Number(POS_STRIPE_TENDERS.has(b.method)) - Number(POS_STRIPE_TENDERS.has(a.method)),\n )\n const refundable = new Map<string, number>()\n for (const tender of ordered) {\n let left = Math.max(0, tender.amountCents - wholeCents(order.posPaymentRefunds?.[tender.id]))\n if (POS_STRIPE_TENDERS.has(tender.method) && unattributed > 0) {\n const taken = Math.min(left, unattributed)\n left -= taken\n unattributed -= taken\n }\n refundable.set(tender.id, left)\n }\n return tenders.map((tender) => ({ ...tender, refundableCents: refundable.get(tender.id) ?? 0 }))\n}\n\n/**\n * The order a refund goes back in, when the cashier does not split it by\n * hand: the cards first, then store credit, then the room, and the drawer\n * LAST — so cash leaves the till only for what the customer paid in cash.\n */\nconst REFUND_ORDER: readonly PosTenderMethod[] = [\n 'card_present',\n 'card_keyed',\n 'card_link',\n 'gift_card',\n 'credit',\n 'folio',\n 'cash',\n]\n\nexport type PosRefundSplit =\n | { ok: true; allocations: PosRefundAllocation[] }\n | { ok: false; error: string }\n\n/**\n * Sends `amountCents` back to the sale's own payments.\n *\n * With no `requested` split, each payment takes what it can in\n * {@link REFUND_ORDER}. With one, every slice must name a payment of this\n * sale and fit what that payment can still take, and the slices must add up\n * to the refund exactly — a refund is never sent to a tender the sale was\n * not paid with.\n */\nexport function splitPosRefund(\n order: PosReturnSource,\n amountCents: number,\n requested?: ReadonlyArray<{ paymentId: string; amountCents: number }> | null,\n): PosRefundSplit {\n const amount = wholeCents(amountCents)\n const tenders = posRefundableByTender(order)\n if (!tenders.length) return { ok: false, error: 'This order has no payment to refund to.' }\n if (requested && requested.length) {\n const allocations: PosRefundAllocation[] = []\n const used = new Set<string>()\n for (const slice of requested) {\n const tender = tenders.find((candidate) => candidate.id === slice.paymentId)\n if (!tender) return { ok: false, error: 'That payment is not on this order.' }\n if (used.has(tender.id)) return { ok: false, error: 'Each payment can be named once.' }\n used.add(tender.id)\n const cents = Math.round(Number(slice.amountCents))\n if (!Number.isFinite(cents) || cents < 0) return { ok: false, error: 'Refund amounts must be positive.' }\n if (cents === 0) continue\n if (cents > tender.refundableCents) {\n return {\n ok: false,\n error: `${posTenderLabel(tender)} can take back at most ${posMoney(tender.refundableCents)}.`,\n }\n }\n allocations.push({ paymentId: tender.id, method: tender.method, amountCents: cents })\n }\n const total = allocations.reduce((sum, slice) => sum + slice.amountCents, 0)\n if (total !== amount) {\n return {\n ok: false,\n error: `The refund is ${posMoney(amount)}; the split adds up to ${posMoney(total)}.`,\n }\n }\n return { ok: true, allocations }\n }\n const ordered = [...tenders].sort(\n (a, b) => REFUND_ORDER.indexOf(a.method) - REFUND_ORDER.indexOf(b.method),\n )\n const allocations: PosRefundAllocation[] = []\n let left = amount\n for (const tender of ordered) {\n if (!(left > 0)) break\n const cents = Math.min(left, tender.refundableCents)\n if (!(cents > 0)) continue\n allocations.push({ paymentId: tender.id, method: tender.method, amountCents: cents })\n left -= cents\n }\n if (left > 0) {\n return {\n ok: false,\n error: `Only ${posMoney(amount - left)} can go back to this sale's payments.`,\n }\n }\n return { ok: true, allocations }\n}\n\n/** `hosts/{hostId}/registers/{registerId}/returns/{returnId}`. */\nexport interface PosRegisterReturn {\n hostId: string\n registerId: string\n orderId: string\n orderNumber?: number\n /** The shift the drawer was in when the return was rung, if one was open. */\n shiftId?: string\n lines: Array<{ index: number; quantity: number; name: string; refundCents: number }>\n refundedCents: number\n tenders: Array<PosRefundAllocation & { status: 'refunded' | 'failed'; refundId?: string; error?: string }>\n restocked: boolean\n locationId?: string\n /** The member at the register (by PIN or by sign-in). */\n cashierId: string\n /** The manager whose PIN allowed a refund above the cashier's limit. */\n approvedBy?: string\n reason?: string\n status: 'refunded' | 'partial'\n atMs: number\n}\n\n/*==========================================\n * STAFF PINS\n *=========================================*/\n\n/** How long a cashier PIN switch lasts before the register asks again. */\nexport const POS_CASHIER_ASSERTION_TTL_MS = 15 * 60 * 1000\n/** A manager's approval is for the one refund in front of them. */\nexport const POS_MANAGER_ASSERTION_TTL_MS = 2 * 60 * 1000\n/** Wrong PINs in a row before the member is locked out. */\nexport const POS_PIN_MAX_ATTEMPTS = 5\n/** How long a lockout lasts. */\nexport const POS_PIN_LOCKOUT_MS = 15 * 60 * 1000\n\n/**\n * Why a PIN cannot be used, or `null` when it can: 4 to 6 digits, and not\n * one a stranger tries first — every digit the same, or a straight run.\n */\nexport function posPinProblem(pin: unknown): string | null {\n const value = typeof pin === 'string' ? pin : ''\n if (!/^\\d{4,6}$/.test(value)) return 'A PIN is 4 to 6 digits.'\n if (/^(\\d)\\1+$/.test(value)) return 'Pick a PIN that is not one digit repeated.'\n const digits = [...value].map(Number)\n const step = (digits[1] ?? 0) - (digits[0] ?? 0)\n if (\n (step === 1 || step === -1) &&\n digits.every((digit, index) => index === 0 || digit - (digits[index - 1] ?? 0) === step)\n ) {\n return 'Pick a PIN that is not a straight run like 1234.'\n }\n return null\n}\n\n/*==========================================\n * THE THERMAL RECEIPT\n *=========================================*/\n\nexport interface PosReceiptLine {\n name: string\n variantLabel?: string\n quantity: number\n unitAmountCents: number\n lineCents: number\n}\n\nexport interface PosReceipt {\n storeName: string\n logoUrl?: string\n addressLines: string[]\n orderNumber: string\n /** The digits the barcode encodes and the register's return lookup reads. */\n barcodeValue: string\n dateLabel: string\n cashierName?: string\n registerName?: string\n customerName?: string\n lines: PosReceiptLine[]\n subtotalCents: number\n discountCents: number\n taxCents: number\n totalCents: number\n tipCents: number\n tenders: Array<{ label: string; amountCents: number }>\n changeCents: number\n refundedCents: number\n footer?: string\n returnPolicy?: string\n /** A gift receipt: the items and nothing about what they cost. */\n gift: boolean\n}\n\n/** The order fields a receipt prints. */\nexport interface PosReceiptOrder extends PosReturnSource {\n number?: number\n createdAtMs?: number\n customerName?: string | null\n lineItems?: Array<{\n name?: string\n variantLabel?: string\n unitAmountCents?: number\n quantity?: number\n }> | null\n}\n\n/**\n * The receipt for one sale, from the order alone plus what the store prints\n * on every receipt. The sale's lines, totals, tenders and change are the\n * receipt model's (`receiptDataFromOrder`, the one the cloud printers print\n * from), so a browser print and a cloud print never disagree; this adds the\n * logo, the address, the return policy and the gift receipt. A gift receipt\n * keeps the lines and the barcode — the recipient's way to return — and\n * drops every price, total and tender.\n */\nexport function buildPosReceipt(input: {\n orderId: string\n order: PosReceiptOrder\n store: {\n name: string\n logoUrl?: string\n address?: string\n footer?: string\n returnPolicy?: string\n }\n cashierName?: string\n registerName?: string\n gift?: boolean\n /** How the date prints; the register's own locale by default. */\n formatDate?: (ms: number) => string\n}): PosReceipt {\n const { order } = input\n const gift = input.gift === true\n const data = receiptDataFromOrder(input.orderId, order as unknown as HostOrder & Record<string, any>, {\n storeName: input.store.name,\n })\n const lines: PosReceiptLine[] = data.lines.map((line) => ({\n name: line.name,\n ...(line.detail ? { variantLabel: line.detail } : {}),\n quantity: line.quantity,\n unitAmountCents: gift ? 0 : line.unitCents,\n lineCents: gift ? 0 : line.totalCents,\n }))\n const number = Number(order.number)\n const digits = Number.isInteger(number) && number > 0 ? String(number) : ''\n const createdAtMs = Number(order.createdAtMs) || 0\n const formatDate =\n input.formatDate ?? ((ms: number) => (ms ? new Date(ms).toLocaleString() : ''))\n const money = (cents: number | undefined) => (gift ? 0 : wholeCents(cents))\n return {\n storeName: input.store.name,\n ...(input.store.logoUrl ? { logoUrl: input.store.logoUrl } : {}),\n addressLines: String(input.store.address ?? '')\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean),\n orderNumber: digits ? `#${digits}` : `#${input.orderId.slice(0, 8)}`,\n barcodeValue: digits || input.orderId,\n dateLabel: formatDate(createdAtMs),\n ...(input.cashierName ? { cashierName: input.cashierName } : {}),\n ...(input.registerName ? { registerName: input.registerName } : {}),\n ...(order.customerName ? { customerName: String(order.customerName) } : {}),\n lines,\n subtotalCents: money(data.subtotalCents),\n discountCents: money(data.discountCents),\n taxCents: money(data.taxCents),\n totalCents: money(data.totalCents),\n tipCents: money(data.tipCents),\n tenders: gift ? [] : (data.tenders ?? []),\n changeCents: money(data.changeCents),\n refundedCents: money(data.refundedCents),\n // A sale of card reader hardware prints the terms it is sold under\n // (AGL-4038, Terms 4.28), after the store's own footer.\n ...(withPosHardwareReceiptNotice(input.store.footer, order as Record<string, unknown>)\n ? { footer: withPosHardwareReceiptNotice(input.store.footer, order as Record<string, unknown>) }\n : {}),\n ...(input.store.returnPolicy ? { returnPolicy: input.store.returnPolicy } : {}),\n gift,\n }\n}\n\n/** One titled block of an X or Z report: what the screen, the browser print and a cloud printer all show. */\nexport interface PosShiftReportSection {\n section: string\n rows: Array<{ label: string; value: string; strong?: boolean }>\n}\n\n/** The rows of an X or Z report, in the order a manager reads them. */\nexport function posShiftReportRows(\n report: PosShiftReport,\n shift?: Pick<PosShift, 'countedCashCents' | 'varianceCents'>,\n): PosShiftReportSection[] {\n const tenders = POS_TENDER_METHODS.filter(\n (method) => (report.salesByTender[method] ?? 0) > 0 || (report.refundsByTender[method] ?? 0) > 0,\n )\n return [\n {\n section: 'Sales',\n rows: [\n { label: 'Orders', value: String(report.orderCount) },\n { label: 'Gross sales', value: posMoney(report.grossSalesCents) },\n { label: 'Discounts', value: posMoney(report.discountsCents) },\n { label: 'Tax', value: posMoney(report.taxCents) },\n { label: 'Tips', value: posMoney(report.tipsCents) },\n { label: `Refunds (${report.refundCount})`, value: `-${posMoney(report.refundsCents)}` },\n { label: 'Net sales', value: posMoney(report.netSalesCents), strong: true },\n ],\n },\n {\n section: 'By tender',\n rows: tenders.length\n ? tenders.map((method) => ({\n label: POS_TENDER_LABELS[method],\n value:\n posMoney(report.salesByTender[method] ?? 0) +\n ((report.refundsByTender[method] ?? 0) > 0\n ? ` (−${posMoney(report.refundsByTender[method] ?? 0)})`\n : ''),\n }))\n : [{ label: 'No sales yet', value: '' }],\n },\n {\n section: 'Cash drawer',\n rows: [\n { label: 'Starting cash', value: posMoney(report.openingFloatCents) },\n { label: 'Cash sales', value: posMoney(report.cashSalesCents) },\n { label: 'Paid in', value: posMoney(report.paidInCents) },\n { label: 'Paid out', value: `-${posMoney(report.paidOutCents)}` },\n { label: 'Safe drops', value: `-${posMoney(report.dropsCents)}` },\n { label: 'Cash refunds', value: `-${posMoney(report.cashRefundsCents)}` },\n { label: 'Expected in drawer', value: posMoney(report.expectedCashCents), strong: true },\n ...(shift?.countedCashCents != null\n ? [\n { label: 'Counted', value: posMoney(shift.countedCashCents) },\n {\n label: (shift.varianceCents ?? 0) < 0 ? 'Short' : (shift.varianceCents ?? 0) > 0 ? 'Over' : 'Balanced',\n value: posMoney(shift.varianceCents ?? 0),\n strong: true,\n },\n ]\n : []),\n ],\n },\n ]\n}\n\n/** A shift's X or Z report as the receipt printer prints it. */\nexport function posShiftPrintReport(input: {\n title: 'X REPORT' | 'Z REPORT'\n storeName: string\n registerName?: string\n report: PosShiftReport\n shift?: Pick<PosShift, 'countedCashCents' | 'varianceCents'>\n subtitle?: string\n}): PrintReport {\n return {\n title: input.title,\n storeName: input.storeName,\n ...(input.subtitle || input.registerName\n ? { subtitle: [input.registerName, input.subtitle].filter(Boolean).join(' - ') }\n : {}),\n sections: posShiftReportRows(input.report, input.shift),\n }\n}\n"],"names":["apportionCents","withPosHardwareReceiptNotice","orderPayments","receiptDataFromOrder","POS_TENDER_METHODS","POS_TENDER_LABELS","cash","card_present","card_keyed","card_link","gift_card","folio","credit","POS_STRIPE_TENDERS","Set","wholeCents","value","number","Math","round","Number","isFinite","isTenderMethod","includes","posOrderTenders","order","filter","payment","status","method","map","id","amountCents","tipCents","totals","paymentIntentId","giftCardId","reservationId","creditProviderId","creditReference","creditLabel","cardBrand","last4","cashTenderedCents","changeCents","posTenderLabel","tender","base","capitalize","charAt","toUpperCase","slice","POS_CASH_EVENT_LABELS","paid_in","paid_out","drop","refund","posCashEventTotals","events","sum","type","event","reduce","total","paidInCents","paidOutCents","dropsCents","cashRefundsCents","posExpectedCashCents","input","openingFloatCents","cashSalesCents","computePosShiftReport","salesByTender","refundsByTender","orderCount","grossSalesCents","discountsCents","taxCents","tipsCents","sale","sales","tenders","totalCents","discountCents","tenderTips","max","refundsCents","refunds","refundedCents","shift","cashEvents","refundCount","length","netSalesCents","expectedCashCents","truncated","posCashVarianceCents","countedCashCents","posMoney","cents","abs","toFixed","csvCell","cell","String","test","replace","posCsvCell","dollars","posShiftsCsv","shifts","memberName","uid","header","iso","ms","Date","toISOString","rows","report","card","undefined","registerName","registerId","openedAtMs","openedByName","openedBy","closedAtMs","closedBy","closedByName","varianceCents","row","join","posReturnLineValues","lines","lineItems","gross","line","unitAmountCents","quantity","discountShares","net","index","taxShares","posReturnedQuantities","wholeLines","refundedLineItemIds","has","returned","returnedQuantities","min","planPosReturn","picks","heldElsewhere","ok","error","values","seen","lineCents","nextReturned","count","entries","completedLines","pick","isInteger","add","already","held","left","name","push","remaining","asked","refundCents","posRefundableByTender","attributed","Object","posPaymentRefunds","unattributed","ordered","sort","a","b","refundable","Map","taken","set","refundableCents","get","REFUND_ORDER","splitPosRefund","requested","amount","allocations","used","find","candidate","paymentId","indexOf","POS_CASHIER_ASSERTION_TTL_MS","POS_MANAGER_ASSERTION_TTL_MS","POS_PIN_MAX_ATTEMPTS","POS_PIN_LOCKOUT_MS","posPinProblem","pin","digits","step","every","digit","buildPosReceipt","data","gift","orderId","storeName","store","detail","variantLabel","unitCents","createdAtMs","formatDate","toLocaleString","money","logoUrl","addressLines","address","split","trim","Boolean","orderNumber","barcodeValue","dateLabel","cashierName","customerName","subtotalCents","footer","returnPolicy","posShiftReportRows","section","label","strong","posShiftPrintReport","title","subtitle","sections"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,cAAc,QAAwB,uBAAmB;AAClE,SAASC,4BAA4B,QAAQ,0BAAsB;AACnE,SAASC,aAAa,QAAQ,oBAAgB;AAE9C,SAASC,oBAAoB,QAAQ,wBAAoB;AA+BzD,OAAO,MAAMC,qBAAiD;IAC5D;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAED,oEAAoE,GACpE,OAAO,MAAMC,oBAA+D;IAC1EC,MAAM;IACNC,cAAc;IACdC,YAAY;IACZC,WAAW;IACXC,WAAW;IACXC,OAAO;IACPC,QAAQ;AACV,EAAC;AAED,2EAA2E,GAC3E,OAAO,MAAMC,qBAAmD,IAAIC,IAAI;IACtE;IACA;IACA;CACD,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KAOnC;IACC,OAAO;QACL6K,OAAO7K,MAAM6K,KAAK;QAClB5B,WAAWjJ,MAAMiJ,SAAS;OACtBjJ,MAAM8K,QAAQ,IAAI9K,MAAMsD,YAAY,GACpC;QAAEwH,UAAU;YAAC9K,MAAMsD,YAAY;YAAEtD,MAAM8K,QAAQ;SAAC,CAACzN,MAAM,CAAC0M,SAAS/F,IAAI,CAAC;IAAO,IAC7E,CAAC;QACL+G,UAAUP,mBAAmBxK,MAAMmD,MAAM,EAAEnD,MAAMqB,KAAK;;AAE1D"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-pos-ops.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 { apportionCents, type HostOrder } from './commerce-orders'\nimport { withPosHardwareReceiptNotice } from './pos-hardware-terms'\nimport { orderPayments } from './commerce-pos'\nimport type { PrintReport } from './commerce-printers'\nimport { receiptDataFromOrder } from './commerce-receipt'\n\n/*==========================================\n * RUNNING THE REGISTER (AGL-3609): shifts and the cash drawer, register\n * returns and the receipt. Pure and client-safe: the routes, the register\n * and the reports all compute from these, so a drawer's expected cash is one\n * formula wherever it is shown.\n *\n * Where each thing lives:\n *\n * hosts/{hostId}/registers/{registerId}\n * `openShiftId` — the one open shift, claimed in a transaction\n * hosts/{hostId}/registers/{registerId}/shifts/{shiftId} {@link PosShift}\n * hosts/{hostId}/registers/{registerId}/returns/{returnId} {@link PosRegisterReturn}\n * hosts/{hostId}/posStaffPins/{uid} server-only\n *\n * Everything under `registers` is written by the Admin SDK only (the\n * register pool is billed), and every member of the site may read it.\n *=========================================*/\n\n/** How one payment toward a sale was taken, in the register's tender words. */\nexport type PosTenderMethod =\n | 'cash'\n | 'card_present'\n | 'card_keyed'\n | 'card_link'\n | 'gift_card'\n | 'folio'\n /** Store credit another plugin keeps (AGL-3640). */\n | 'credit'\n\nexport const POS_TENDER_METHODS: readonly PosTenderMethod[] = [\n 'cash',\n 'card_present',\n 'card_keyed',\n 'card_link',\n 'gift_card',\n 'folio',\n 'credit',\n]\n\n/** What each tender is called on a report, a receipt and a refund. */\nexport const POS_TENDER_LABELS: Readonly<Record<PosTenderMethod, string>> = {\n cash: 'Cash',\n card_present: 'Card',\n card_keyed: 'Card (keyed)',\n card_link: 'Card (payment link)',\n gift_card: 'Gift card',\n folio: 'Room charge',\n credit: 'Store credit',\n}\n\n/** The tenders whose money moved through Stripe and goes back through it. */\nexport const POS_STRIPE_TENDERS: ReadonlySet<PosTenderMethod> = new Set([\n 'card_present',\n 'card_keyed',\n 'card_link',\n])\n\n/**\n * One settled payment toward a sale, as the shift report and a register\n * return read it.\n */\nexport interface PosOrderTender {\n /** The payment's id on the order, or `legacy` for an order before the tender ledger. */\n id: string\n method: PosTenderMethod\n /** Cents put toward the sale; never the tip, never the change. */\n amountCents: number\n tipCents: number\n paymentIntentId?: string\n giftCardId?: string\n reservationId?: string\n /** For `credit` (AGL-3640): the provider, its account handle, and its name. */\n creditProviderId?: string\n creditReference?: string\n creditLabel?: string\n cardBrand?: string\n last4?: string\n cashTenderedCents?: number\n changeCents?: number\n /** Where a card tender's charge lives: on the store's own account when `direct`. */\n chargeModel?: 'direct'\n stripeAccountId?: string\n}\n\nconst wholeCents = (value: unknown): number => {\n const number = Math.round(Number(value))\n return Number.isFinite(number) && number > 0 ? number : 0\n}\n\n\nconst isTenderMethod = (value: unknown): value is PosTenderMethod =>\n typeof value === 'string' && (POS_TENDER_METHODS as readonly string[]).includes(value)\n\n/** The order fields the tender reader looks at. */\nexport interface PosTenderSource {\n payments?: unknown\n channel?: string\n status?: string\n totals?: { totalCents?: number; tipCents?: number } | null\n amountCents?: number\n reservationId?: string\n checkoutSessionId?: string\n paymentIntentId?: string\n}\n\n/**\n * THE ONE PLACE THE TENDER LEDGER IS READ (AGL-3609).\n *\n * A register sale may carry `payments[]` — one entry per tender, the ledger\n * the split-tender register writes (AGL-3607) — and only the payments that\n * SUCCEEDED count: a declined card or a voided gift card took nothing. An\n * order written before that ledger is one payment, inferred the way the\n * ledger's own reader infers it: a folio when it names a reservation, a card\n * link when Stripe saw it (or it came through the storefront), cash otherwise.\n *\n * The ledger's own reader (`orderPayments`) does both; this narrows it to the\n * settled payments and the fields a report or a refund reads.\n */\nexport function posOrderTenders(order: PosTenderSource | null | undefined): PosOrderTender[] {\n if (!order) return []\n return orderPayments(order as Parameters<typeof orderPayments>[0])\n .filter((payment) => payment.status === 'succeeded' && isTenderMethod(payment.method))\n .map((payment) => ({\n id: payment.id,\n method: payment.method as PosTenderMethod,\n amountCents: wholeCents(payment.amountCents),\n tipCents: wholeCents(payment.tipCents ?? (payment.id === 'legacy' ? order.totals?.tipCents : 0)),\n ...(payment.paymentIntentId ? { paymentIntentId: payment.paymentIntentId } : {}),\n ...(payment.giftCardId ? { giftCardId: payment.giftCardId } : {}),\n ...(payment.reservationId ? { reservationId: payment.reservationId } : {}),\n ...(payment.creditProviderId ? { creditProviderId: payment.creditProviderId } : {}),\n ...(payment.creditReference ? { creditReference: payment.creditReference } : {}),\n ...(payment.creditLabel ? { creditLabel: payment.creditLabel } : {}),\n ...(payment.cardBrand ? { cardBrand: payment.cardBrand } : {}),\n ...(payment.last4 ? { last4: payment.last4 } : {}),\n ...(payment.cashTenderedCents != null ? { cashTenderedCents: wholeCents(payment.cashTenderedCents) } : {}),\n ...(payment.changeCents != null ? { changeCents: wholeCents(payment.changeCents) } : {}),\n ...(payment.chargeModel === 'direct' && payment.stripeAccountId\n ? { chargeModel: 'direct' as const, stripeAccountId: payment.stripeAccountId }\n : {}),\n }))\n}\n\n/** A tender as one line of a receipt: `Card •• 4242`. */\nexport function posTenderLabel(\n tender: Pick<PosOrderTender, 'method' | 'cardBrand' | 'last4'> & { creditLabel?: string },\n): string {\n const base = (tender.method === 'credit' && tender.creditLabel) || POS_TENDER_LABELS[tender.method] || tender.method\n if (tender.last4) {\n return `${tender.cardBrand ? capitalize(tender.cardBrand) : base} •• ${tender.last4}`\n }\n return base\n}\n\nfunction capitalize(value: string): string {\n return value ? value.charAt(0).toUpperCase() + value.slice(1) : value\n}\n\n/*==========================================\n * SHIFTS AND THE CASH DRAWER\n *=========================================*/\n\n/**\n * Cash that moved through the drawer without a sale: money put in, money\n * paid out for a reason (a delivery, petty cash), a drop to the safe, and\n * a register return paid out in cash.\n */\nexport type PosCashEventType = 'paid_in' | 'paid_out' | 'drop' | 'refund'\n\nexport const POS_CASH_EVENT_LABELS: Readonly<Record<PosCashEventType, string>> = {\n paid_in: 'Paid in',\n paid_out: 'Paid out',\n drop: 'Safe drop',\n refund: 'Cash refund',\n}\n\nexport interface PosCashEvent {\n /** The register's attempt id, so a retried tap records one event. */\n id: string\n type: PosCashEventType\n amountCents: number\n reason: string\n /** The member who moved the cash. */\n by: string\n atMs: number\n /** The order a `refund` paid out against. */\n orderId?: string\n}\n\n/** Sales, refunds and cash movements over one shift. */\nexport interface PosShiftReport {\n orderCount: number\n /** What customers paid for the goods: order totals, tax in, tips out. */\n grossSalesCents: number\n discountsCents: number\n taxCents: number\n tipsCents: number\n salesByTender: Partial<Record<PosTenderMethod, number>>\n refundCount: number\n refundsCents: number\n refundsByTender: Partial<Record<PosTenderMethod, number>>\n /** Gross sales less refunds. */\n netSalesCents: number\n openingFloatCents: number\n cashSalesCents: number\n paidInCents: number\n paidOutCents: number\n dropsCents: number\n cashRefundsCents: number\n /** float + cash sales + paid in − paid out − drops − cash refunds. */\n expectedCashCents: number\n /** More sales were stamped with the shift than the report could read. */\n truncated?: boolean\n}\n\n/** `hosts/{hostId}/registers/{registerId}/shifts/{shiftId}`. */\nexport interface PosShift {\n hostId: string\n registerId: string\n status: 'open' | 'closed'\n openedBy: string\n /** The member's name when the shift opened, for the history and the export. */\n openedByName?: string\n openedAtMs: number\n openingFloatCents: number\n cashEvents: PosCashEvent[]\n closedBy?: string\n closedByName?: string\n /*\n * The history sorts by each of the five below (AGL-3680), and an `orderBy`\n * drops a shift that lacks the field, so the shift is opened with each one\n * `null` and the close fills them — see `POS_SHIFT_LIST_QUERY`.\n */\n closedAtMs?: number | null\n /** What the closing cashier counted in the drawer. */\n countedCashCents?: number | null\n expectedCashCents?: number | null\n /** counted − expected: positive is over, negative is short. */\n varianceCents?: number | null\n /** The Z report's `netSalesCents`, flattened so the history can order by it. */\n netSalesCents?: number | null\n closingNote?: string\n /** The Z report, frozen when the shift closed. */\n report?: PosShiftReport\n}\n\n/** The cash-event sums one formula reads. */\nexport function posCashEventTotals(events: readonly PosCashEvent[] | null | undefined): {\n paidInCents: number\n paidOutCents: number\n dropsCents: number\n cashRefundsCents: number\n} {\n const sum = (type: PosCashEventType) =>\n (events ?? [])\n .filter((event) => event?.type === type)\n .reduce((total, event) => total + wholeCents(event.amountCents), 0)\n return {\n paidInCents: sum('paid_in'),\n paidOutCents: sum('paid_out'),\n dropsCents: sum('drop'),\n cashRefundsCents: sum('refund'),\n }\n}\n\n/**\n * THE DRAWER'S EXPECTED CASH: what should be in it when it is counted.\n *\n * opening float + cash sales + paid in − paid out − safe drops − cash refunds\n *\n * Cash SALES are the cash tender's `amountCents`, which is what the sale took\n * and never what the customer handed over: the change went straight back out\n * of the same drawer. A tip left in cash is in the drawer too, so it counts.\n */\nexport function posExpectedCashCents(input: {\n openingFloatCents: number\n cashSalesCents: number\n paidInCents: number\n paidOutCents: number\n dropsCents: number\n cashRefundsCents: number\n}): number {\n return (\n wholeCents(input.openingFloatCents) +\n wholeCents(input.cashSalesCents) +\n wholeCents(input.paidInCents) -\n wholeCents(input.paidOutCents) -\n wholeCents(input.dropsCents) -\n wholeCents(input.cashRefundsCents)\n )\n}\n\n/** A sale as the shift report reads it. */\nexport interface PosShiftSale extends PosTenderSource {\n totals?: {\n totalCents?: number\n discountCents?: number\n taxCents?: number\n tipCents?: number\n } | null\n}\n\n/** A register return as the shift report reads it. */\nexport interface PosShiftRefund {\n refundedCents: number\n tenders: Array<{ method: PosTenderMethod; amountCents: number }>\n}\n\n/**\n * The X report (mid-shift) and the Z report (at close) are this one function\n * over the sales stamped with the shift, the returns rung at the register\n * during it and the shift's own cash events. A pending sale took no money and\n * a cancelled one gave it back, so neither counts; a sale refunded LATER\n * still counts as a sale, and its refund is counted where it was paid out.\n */\nexport function computePosShiftReport(input: {\n shift: Pick<PosShift, 'openingFloatCents' | 'cashEvents'>\n sales: readonly PosShiftSale[]\n refunds: readonly PosShiftRefund[]\n truncated?: boolean\n}): PosShiftReport {\n const salesByTender: Partial<Record<PosTenderMethod, number>> = {}\n const refundsByTender: Partial<Record<PosTenderMethod, number>> = {}\n let orderCount = 0\n let grossSalesCents = 0\n let discountsCents = 0\n let taxCents = 0\n let tipsCents = 0\n let cashSalesCents = 0\n for (const sale of input.sales) {\n if (sale.status === 'pending' || sale.status === 'cancelled') continue\n const tenders = posOrderTenders(sale)\n orderCount += 1\n grossSalesCents += wholeCents(sale.totals?.totalCents ?? sale.amountCents)\n discountsCents += wholeCents(sale.totals?.discountCents)\n taxCents += wholeCents(sale.totals?.taxCents)\n const tenderTips = tenders.reduce((sum, tender) => sum + tender.tipCents, 0)\n tipsCents += Math.max(wholeCents(sale.totals?.tipCents), tenderTips)\n for (const tender of tenders) {\n salesByTender[tender.method] = (salesByTender[tender.method] ?? 0) + tender.amountCents\n if (tender.method === 'cash') cashSalesCents += tender.amountCents + tender.tipCents\n }\n }\n let refundsCents = 0\n for (const refund of input.refunds) {\n refundsCents += wholeCents(refund.refundedCents)\n for (const tender of refund.tenders ?? []) {\n if (!isTenderMethod(tender.method)) continue\n refundsByTender[tender.method] =\n (refundsByTender[tender.method] ?? 0) + wholeCents(tender.amountCents)\n }\n }\n const cash = posCashEventTotals(input.shift.cashEvents)\n const openingFloatCents = wholeCents(input.shift.openingFloatCents)\n return {\n orderCount,\n grossSalesCents,\n discountsCents,\n taxCents,\n tipsCents,\n salesByTender,\n refundCount: input.refunds.length,\n refundsCents,\n refundsByTender,\n netSalesCents: grossSalesCents - refundsCents,\n openingFloatCents,\n cashSalesCents,\n ...cash,\n expectedCashCents: posExpectedCashCents({ openingFloatCents, cashSalesCents, ...cash }),\n ...(input.truncated ? { truncated: true } : {}),\n }\n}\n\n/** counted − expected; positive is over, negative is short. */\nexport function posCashVarianceCents(countedCashCents: number, expectedCashCents: number): number {\n return Math.round(Number(countedCashCents) || 0) - Math.round(Number(expectedCashCents) || 0)\n}\n\n/** `$12.34`, `-$0.50` — the register's money format, store currency USD. */\nexport function posMoney(cents: number): string {\n const value = Math.round(Number(cents) || 0)\n return `${value < 0 ? '-' : ''}$${(Math.abs(value) / 100).toFixed(2)}`\n}\n\n/** One CSV cell, quoted when it needs to be and never read as a formula. */\nfunction csvCell(value: unknown): string {\n let cell = value == null ? '' : String(value)\n if (/^[=+\\-@\\t\\r]/.test(cell) && !/^-?\\d+(\\.\\d+)?$/.test(cell)) cell = `'${cell}`\n return /[\",\\r\\n]/.test(cell) ? `\"${cell.replace(/\"/g, '\"\"')}\"` : cell\n}\n\nexport { csvCell as posCsvCell }\n\nconst dollars = (cents: number | null | undefined): string =>\n cents == null ? '' : (Math.round(cents) / 100).toFixed(2)\n\n/** The shift history as a spreadsheet: one row per shift, money in dollars. */\nexport function posShiftsCsv(\n shifts: ReadonlyArray<PosShift & { id: string; registerName?: string }>,\n memberName: (uid: string) => string = (uid) => uid,\n): string {\n const header = [\n 'Shift',\n 'Register',\n 'Opened',\n 'Opened by',\n 'Closed',\n 'Closed by',\n 'Orders',\n 'Gross sales',\n 'Refunds',\n 'Net sales',\n 'Discounts',\n 'Tax',\n 'Tips',\n 'Cash sales',\n 'Card sales',\n 'Gift card sales',\n 'Room charges',\n 'Opening float',\n 'Paid in',\n 'Paid out',\n 'Safe drops',\n 'Cash refunds',\n 'Expected cash',\n 'Counted cash',\n 'Variance',\n ]\n const iso = (ms: number | null | undefined) => (ms ? new Date(ms).toISOString() : '')\n const rows = shifts.map((shift) => {\n const report = shift.report\n const card = report\n ? (report.salesByTender.card_present ?? 0) +\n (report.salesByTender.card_keyed ?? 0) +\n (report.salesByTender.card_link ?? 0)\n : undefined\n return [\n shift.id,\n shift.registerName ?? shift.registerId,\n iso(shift.openedAtMs),\n shift.openedByName ?? memberName(shift.openedBy),\n iso(shift.closedAtMs),\n shift.closedBy ? (shift.closedByName ?? memberName(shift.closedBy)) : '',\n report?.orderCount ?? '',\n dollars(report?.grossSalesCents),\n dollars(report?.refundsCents),\n dollars(report?.netSalesCents),\n dollars(report?.discountsCents),\n dollars(report?.taxCents),\n dollars(report?.tipsCents),\n dollars(report?.cashSalesCents),\n dollars(card),\n dollars(report ? (report.salesByTender.gift_card ?? 0) : undefined),\n dollars(report ? (report.salesByTender.folio ?? 0) : undefined),\n dollars(shift.openingFloatCents),\n dollars(report?.paidInCents),\n dollars(report?.paidOutCents),\n dollars(report?.dropsCents),\n dollars(report?.cashRefundsCents),\n dollars(shift.expectedCashCents ?? report?.expectedCashCents),\n dollars(shift.countedCashCents),\n dollars(shift.varianceCents),\n ]\n })\n return [header, ...rows].map((row) => row.map(csvCell).join(',')).join('\\r\\n')\n}\n\n/*==========================================\n * RETURNS AT THE REGISTER\n *=========================================*/\n\n/** One line picked for return: its index on the order and how many units. */\nexport interface PosReturnPick {\n index: number\n quantity: number\n}\n\n/** The order fields a return reads. */\nexport interface PosReturnSource extends PosTenderSource {\n lineItems?: Array<{ unitAmountCents?: number; quantity?: number; name?: string }> | null\n totals?: {\n totalCents?: number\n discountCents?: number\n taxCents?: number\n shippingCents?: number\n tipCents?: number\n } | null\n refundedCents?: number\n refundedLineItemIds?: number[]\n /** Units of each line already returned at a register, by line index. */\n returnedQuantities?: Record<string, number>\n /** Cents already refunded to each payment by a register return. */\n posPaymentRefunds?: Record<string, number>\n}\n\n/**\n * What each line is worth back, whole: its price less its share of the\n * order's discount, plus its share of the order's tax — the same\n * apportionment `orderLineRefundCents` uses for the discount, extended to the\n * tax a register sale charged on top. Shipping and tips are not a line's.\n */\nexport function posReturnLineValues(order: PosReturnSource): number[] {\n const lines = order.lineItems ?? []\n const gross = lines.map(\n (line) =>\n Math.max(0, Math.round(Number(line?.unitAmountCents ?? 0))) *\n Math.max(1, Math.round(Number(line?.quantity ?? 1))),\n )\n const discountShares = apportionCents(gross, wholeCents(order.totals?.discountCents))\n const net = gross.map((cents, index) => Math.max(0, cents - (discountShares[index] ?? 0)))\n const taxShares = apportionCents(net, wholeCents(order.totals?.taxCents))\n return net.map((cents, index) => cents + (taxShares[index] ?? 0))\n}\n\n/** Units of each line already returned, a line refunded whole counting as all of it. */\nexport function posReturnedQuantities(order: PosReturnSource): number[] {\n const lines = order.lineItems ?? []\n const wholeLines = new Set(order.refundedLineItemIds ?? [])\n return lines.map((line, index) => {\n const quantity = Math.max(1, Math.round(Number(line?.quantity ?? 1)))\n if (wholeLines.has(index)) return quantity\n const returned = Math.round(Number(order.returnedQuantities?.[String(index)] ?? 0))\n return Math.min(quantity, Math.max(0, Number.isFinite(returned) ? returned : 0))\n })\n}\n\nexport type PosReturnPlan =\n | {\n ok: true\n refundCents: number\n /** Cents per picked line, in the order picked. */\n lineCents: number[]\n /** The order's per-line returned quantities after this return. */\n returnedQuantities: Record<string, number>\n /** Lines this return finishes, for `refundedLineItemIds`. */\n completedLines: number[]\n }\n | { ok: false; error: string }\n\n/**\n * What a return of these picks refunds, to the cent.\n *\n * Each line's value is split across its units CUMULATIVELY: returning `k` of\n * `n` units already returned `r` refunds `round(V·(r+k)/n) − round(V·r/n)`,\n * so returning a line one unit at a time refunds exactly what returning it\n * whole would have, and the rounding never strands or invents a cent. The\n * sum is capped at what is left to refund on the order — a refund given\n * from the order dialog already took its share.\n *\n * `heldElsewhere` is, per line, the units an online return (the returns\n * flow) already holds or took back. They cap what the register may take, but\n * they are not written into `returnedQuantities`, which counts only what the\n * register itself took.\n */\nexport function planPosReturn(\n order: PosReturnSource,\n picks: readonly PosReturnPick[],\n heldElsewhere: readonly number[] = [],\n): PosReturnPlan {\n const lines = order.lineItems ?? []\n if (!picks.length) return { ok: false, error: 'Pick at least one item to return.' }\n const values = posReturnLineValues(order)\n const returned = posReturnedQuantities(order)\n const seen = new Set<number>()\n const lineCents: number[] = []\n const nextReturned: Record<string, number> = {}\n for (const [index, count] of returned.entries()) if (count > 0) nextReturned[String(index)] = count\n const completedLines: number[] = []\n for (const pick of picks) {\n const index = Number(pick.index)\n const quantity = Number(pick.quantity)\n if (!Number.isInteger(index) || index < 0 || index >= lines.length) {\n return { ok: false, error: `Line ${pick.index} is not on this order.` }\n }\n if (seen.has(index)) return { ok: false, error: 'Each line can be picked once.' }\n seen.add(index)\n if (!Number.isInteger(quantity) || quantity < 1) {\n return { ok: false, error: 'Return at least one of each line you pick.' }\n }\n const total = Math.max(1, Math.round(Number(lines[index]?.quantity ?? 1)))\n const already = returned[index] ?? 0\n const held = Math.max(0, Math.round(Number(heldElsewhere[index] ?? 0)))\n if (already + held + quantity > total) {\n const left = Math.max(0, total - already - held)\n return {\n ok: false,\n error:\n left > 0\n ? `Only ${left} of \"${lines[index]?.name ?? 'that item'}\" can still be returned.`\n : held > 0\n ? `\"${lines[index]?.name ?? 'That item'}\" is already in a return. Finish it under Returns.`\n : `\"${lines[index]?.name ?? 'That item'}\" has already been returned.`,\n }\n }\n const value = values[index] ?? 0\n lineCents.push(\n Math.round((value * (already + quantity)) / total) - Math.round((value * already) / total),\n )\n nextReturned[String(index)] = already + quantity\n if (already + quantity === total) completedLines.push(index)\n }\n const remaining = Math.max(\n 0,\n wholeCents(order.totals?.totalCents) - wholeCents(order.refundedCents),\n )\n const asked = lineCents.reduce((sum, cents) => sum + cents, 0)\n const refundCents = Math.min(asked, remaining)\n if (!(refundCents > 0)) return { ok: false, error: 'Nothing is left to refund on this order.' }\n return { ok: true, refundCents, lineCents, returnedQuantities: nextReturned, completedLines }\n}\n\n/** One slice of a refund, sent back to one of the sale's payments. */\nexport interface PosRefundAllocation {\n paymentId: string\n method: PosTenderMethod\n amountCents: number\n}\n\n/**\n * What each payment can still take back: what it put toward the sale, less\n * what register returns already sent to it. A refund given from the order\n * dialog refunds through Stripe without naming a payment, so whatever it\n * took that no payment accounts for comes off the Stripe payments first.\n */\nexport function posRefundableByTender(order: PosReturnSource): Array<PosOrderTender & { refundableCents: number }> {\n const tenders = posOrderTenders(order)\n const attributed = Object.values(order.posPaymentRefunds ?? {}).reduce(\n (sum, cents) => sum + wholeCents(cents),\n 0,\n )\n let unattributed = Math.max(0, wholeCents(order.refundedCents) - attributed)\n const ordered = [...tenders].sort(\n (a, b) => Number(POS_STRIPE_TENDERS.has(b.method)) - Number(POS_STRIPE_TENDERS.has(a.method)),\n )\n const refundable = new Map<string, number>()\n for (const tender of ordered) {\n let left = Math.max(0, tender.amountCents - wholeCents(order.posPaymentRefunds?.[tender.id]))\n if (POS_STRIPE_TENDERS.has(tender.method) && unattributed > 0) {\n const taken = Math.min(left, unattributed)\n left -= taken\n unattributed -= taken\n }\n refundable.set(tender.id, left)\n }\n return tenders.map((tender) => ({ ...tender, refundableCents: refundable.get(tender.id) ?? 0 }))\n}\n\n/**\n * The order a refund goes back in, when the cashier does not split it by\n * hand: the cards first, then store credit, then the room, and the drawer\n * LAST — so cash leaves the till only for what the customer paid in cash.\n */\nconst REFUND_ORDER: readonly PosTenderMethod[] = [\n 'card_present',\n 'card_keyed',\n 'card_link',\n 'gift_card',\n 'credit',\n 'folio',\n 'cash',\n]\n\nexport type PosRefundSplit =\n | { ok: true; allocations: PosRefundAllocation[] }\n | { ok: false; error: string }\n\n/**\n * Sends `amountCents` back to the sale's own payments.\n *\n * With no `requested` split, each payment takes what it can in\n * {@link REFUND_ORDER}. With one, every slice must name a payment of this\n * sale and fit what that payment can still take, and the slices must add up\n * to the refund exactly — a refund is never sent to a tender the sale was\n * not paid with.\n */\nexport function splitPosRefund(\n order: PosReturnSource,\n amountCents: number,\n requested?: ReadonlyArray<{ paymentId: string; amountCents: number }> | null,\n): PosRefundSplit {\n const amount = wholeCents(amountCents)\n const tenders = posRefundableByTender(order)\n if (!tenders.length) return { ok: false, error: 'This order has no payment to refund to.' }\n if (requested && requested.length) {\n const allocations: PosRefundAllocation[] = []\n const used = new Set<string>()\n for (const slice of requested) {\n const tender = tenders.find((candidate) => candidate.id === slice.paymentId)\n if (!tender) return { ok: false, error: 'That payment is not on this order.' }\n if (used.has(tender.id)) return { ok: false, error: 'Each payment can be named once.' }\n used.add(tender.id)\n const cents = Math.round(Number(slice.amountCents))\n if (!Number.isFinite(cents) || cents < 0) return { ok: false, error: 'Refund amounts must be positive.' }\n if (cents === 0) continue\n if (cents > tender.refundableCents) {\n return {\n ok: false,\n error: `${posTenderLabel(tender)} can take back at most ${posMoney(tender.refundableCents)}.`,\n }\n }\n allocations.push({ paymentId: tender.id, method: tender.method, amountCents: cents })\n }\n const total = allocations.reduce((sum, slice) => sum + slice.amountCents, 0)\n if (total !== amount) {\n return {\n ok: false,\n error: `The refund is ${posMoney(amount)}; the split adds up to ${posMoney(total)}.`,\n }\n }\n return { ok: true, allocations }\n }\n const ordered = [...tenders].sort(\n (a, b) => REFUND_ORDER.indexOf(a.method) - REFUND_ORDER.indexOf(b.method),\n )\n const allocations: PosRefundAllocation[] = []\n let left = amount\n for (const tender of ordered) {\n if (!(left > 0)) break\n const cents = Math.min(left, tender.refundableCents)\n if (!(cents > 0)) continue\n allocations.push({ paymentId: tender.id, method: tender.method, amountCents: cents })\n left -= cents\n }\n if (left > 0) {\n return {\n ok: false,\n error: `Only ${posMoney(amount - left)} can go back to this sale's payments.`,\n }\n }\n return { ok: true, allocations }\n}\n\n/** `hosts/{hostId}/registers/{registerId}/returns/{returnId}`. */\nexport interface PosRegisterReturn {\n hostId: string\n registerId: string\n orderId: string\n orderNumber?: number\n /** The shift the drawer was in when the return was rung, if one was open. */\n shiftId?: string\n lines: Array<{ index: number; quantity: number; name: string; refundCents: number }>\n refundedCents: number\n tenders: Array<PosRefundAllocation & { status: 'refunded' | 'failed'; refundId?: string; error?: string }>\n restocked: boolean\n locationId?: string\n /** The member at the register (by PIN or by sign-in). */\n cashierId: string\n /** The manager whose PIN allowed a refund above the cashier's limit. */\n approvedBy?: string\n reason?: string\n status: 'refunded' | 'partial'\n atMs: number\n}\n\n/*==========================================\n * STAFF PINS\n *=========================================*/\n\n/** How long a cashier PIN switch lasts before the register asks again. */\nexport const POS_CASHIER_ASSERTION_TTL_MS = 15 * 60 * 1000\n/** A manager's approval is for the one refund in front of them. */\nexport const POS_MANAGER_ASSERTION_TTL_MS = 2 * 60 * 1000\n/** Wrong PINs in a row before the member is locked out. */\nexport const POS_PIN_MAX_ATTEMPTS = 5\n/** How long a lockout lasts. */\nexport const POS_PIN_LOCKOUT_MS = 15 * 60 * 1000\n\n/**\n * Why a PIN cannot be used, or `null` when it can: 4 to 6 digits, and not\n * one a stranger tries first — every digit the same, or a straight run.\n */\nexport function posPinProblem(pin: unknown): string | null {\n const value = typeof pin === 'string' ? pin : ''\n if (!/^\\d{4,6}$/.test(value)) return 'A PIN is 4 to 6 digits.'\n if (/^(\\d)\\1+$/.test(value)) return 'Pick a PIN that is not one digit repeated.'\n const digits = [...value].map(Number)\n const step = (digits[1] ?? 0) - (digits[0] ?? 0)\n if (\n (step === 1 || step === -1) &&\n digits.every((digit, index) => index === 0 || digit - (digits[index - 1] ?? 0) === step)\n ) {\n return 'Pick a PIN that is not a straight run like 1234.'\n }\n return null\n}\n\n/*==========================================\n * THE THERMAL RECEIPT\n *=========================================*/\n\nexport interface PosReceiptLine {\n name: string\n variantLabel?: string\n quantity: number\n unitAmountCents: number\n lineCents: number\n}\n\nexport interface PosReceipt {\n storeName: string\n logoUrl?: string\n addressLines: string[]\n orderNumber: string\n /** The digits the barcode encodes and the register's return lookup reads. */\n barcodeValue: string\n dateLabel: string\n cashierName?: string\n registerName?: string\n customerName?: string\n lines: PosReceiptLine[]\n subtotalCents: number\n discountCents: number\n taxCents: number\n totalCents: number\n tipCents: number\n tenders: Array<{ label: string; amountCents: number }>\n changeCents: number\n refundedCents: number\n footer?: string\n returnPolicy?: string\n /** A gift receipt: the items and nothing about what they cost. */\n gift: boolean\n}\n\n/** The order fields a receipt prints. */\nexport interface PosReceiptOrder extends PosReturnSource {\n number?: number\n createdAtMs?: number\n customerName?: string | null\n lineItems?: Array<{\n name?: string\n variantLabel?: string\n unitAmountCents?: number\n quantity?: number\n }> | null\n}\n\n/**\n * The receipt for one sale, from the order alone plus what the store prints\n * on every receipt. The sale's lines, totals, tenders and change are the\n * receipt model's (`receiptDataFromOrder`, the one the cloud printers print\n * from), so a browser print and a cloud print never disagree; this adds the\n * logo, the address, the return policy and the gift receipt. A gift receipt\n * keeps the lines and the barcode — the recipient's way to return — and\n * drops every price, total and tender.\n */\nexport function buildPosReceipt(input: {\n orderId: string\n order: PosReceiptOrder\n store: {\n name: string\n logoUrl?: string\n address?: string\n footer?: string\n returnPolicy?: string\n }\n cashierName?: string\n registerName?: string\n gift?: boolean\n /** How the date prints; the register's own locale by default. */\n formatDate?: (ms: number) => string\n}): PosReceipt {\n const { order } = input\n const gift = input.gift === true\n const data = receiptDataFromOrder(input.orderId, order as unknown as HostOrder & Record<string, any>, {\n storeName: input.store.name,\n })\n const lines: PosReceiptLine[] = data.lines.map((line) => ({\n name: line.name,\n ...(line.detail ? { variantLabel: line.detail } : {}),\n quantity: line.quantity,\n unitAmountCents: gift ? 0 : line.unitCents,\n lineCents: gift ? 0 : line.totalCents,\n }))\n const number = Number(order.number)\n const digits = Number.isInteger(number) && number > 0 ? String(number) : ''\n const createdAtMs = Number(order.createdAtMs) || 0\n const formatDate =\n input.formatDate ?? ((ms: number) => (ms ? new Date(ms).toLocaleString() : ''))\n const money = (cents: number | undefined) => (gift ? 0 : wholeCents(cents))\n return {\n storeName: input.store.name,\n ...(input.store.logoUrl ? { logoUrl: input.store.logoUrl } : {}),\n addressLines: String(input.store.address ?? '')\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean),\n orderNumber: digits ? `#${digits}` : `#${input.orderId.slice(0, 8)}`,\n barcodeValue: digits || input.orderId,\n dateLabel: formatDate(createdAtMs),\n ...(input.cashierName ? { cashierName: input.cashierName } : {}),\n ...(input.registerName ? { registerName: input.registerName } : {}),\n ...(order.customerName ? { customerName: String(order.customerName) } : {}),\n lines,\n subtotalCents: money(data.subtotalCents),\n discountCents: money(data.discountCents),\n taxCents: money(data.taxCents),\n totalCents: money(data.totalCents),\n tipCents: money(data.tipCents),\n tenders: gift ? [] : (data.tenders ?? []),\n changeCents: money(data.changeCents),\n refundedCents: money(data.refundedCents),\n // A sale of card reader hardware prints the terms it is sold under\n // (AGL-4038, Terms 4.28), after the store's own footer.\n ...(withPosHardwareReceiptNotice(input.store.footer, order as Record<string, unknown>)\n ? { footer: withPosHardwareReceiptNotice(input.store.footer, order as Record<string, unknown>) }\n : {}),\n ...(input.store.returnPolicy ? { returnPolicy: input.store.returnPolicy } : {}),\n gift,\n }\n}\n\n/** One titled block of an X or Z report: what the screen, the browser print and a cloud printer all show. */\nexport interface PosShiftReportSection {\n section: string\n rows: Array<{ label: string; value: string; strong?: boolean }>\n}\n\n/** The rows of an X or Z report, in the order a manager reads them. */\nexport function posShiftReportRows(\n report: PosShiftReport,\n shift?: Pick<PosShift, 'countedCashCents' | 'varianceCents'>,\n): PosShiftReportSection[] {\n const tenders = POS_TENDER_METHODS.filter(\n (method) => (report.salesByTender[method] ?? 0) > 0 || (report.refundsByTender[method] ?? 0) > 0,\n )\n return [\n {\n section: 'Sales',\n rows: [\n { label: 'Orders', value: String(report.orderCount) },\n { label: 'Gross sales', value: posMoney(report.grossSalesCents) },\n { label: 'Discounts', value: posMoney(report.discountsCents) },\n { label: 'Tax', value: posMoney(report.taxCents) },\n { label: 'Tips', value: posMoney(report.tipsCents) },\n { label: `Refunds (${report.refundCount})`, value: `-${posMoney(report.refundsCents)}` },\n { label: 'Net sales', value: posMoney(report.netSalesCents), strong: true },\n ],\n },\n {\n section: 'By tender',\n rows: tenders.length\n ? tenders.map((method) => ({\n label: POS_TENDER_LABELS[method],\n value:\n posMoney(report.salesByTender[method] ?? 0) +\n ((report.refundsByTender[method] ?? 0) > 0\n ? ` (−${posMoney(report.refundsByTender[method] ?? 0)})`\n : ''),\n }))\n : [{ label: 'No sales yet', value: '' }],\n },\n {\n section: 'Cash drawer',\n rows: [\n { label: 'Starting cash', value: posMoney(report.openingFloatCents) },\n { label: 'Cash sales', value: posMoney(report.cashSalesCents) },\n { label: 'Paid in', value: posMoney(report.paidInCents) },\n { label: 'Paid out', value: `-${posMoney(report.paidOutCents)}` },\n { label: 'Safe drops', value: `-${posMoney(report.dropsCents)}` },\n { label: 'Cash refunds', value: `-${posMoney(report.cashRefundsCents)}` },\n { label: 'Expected in drawer', value: posMoney(report.expectedCashCents), strong: true },\n ...(shift?.countedCashCents != null\n ? [\n { label: 'Counted', value: posMoney(shift.countedCashCents) },\n {\n label: (shift.varianceCents ?? 0) < 0 ? 'Short' : (shift.varianceCents ?? 0) > 0 ? 'Over' : 'Balanced',\n value: posMoney(shift.varianceCents ?? 0),\n strong: true,\n },\n ]\n : []),\n ],\n },\n ]\n}\n\n/** A shift's X or Z report as the receipt printer prints it. */\nexport function posShiftPrintReport(input: {\n title: 'X REPORT' | 'Z REPORT'\n storeName: string\n registerName?: string\n report: PosShiftReport\n shift?: Pick<PosShift, 'countedCashCents' | 'varianceCents'>\n subtitle?: string\n}): PrintReport {\n return {\n title: input.title,\n storeName: input.storeName,\n ...(input.subtitle || input.registerName\n ? { subtitle: [input.registerName, input.subtitle].filter(Boolean).join(' - ') }\n : {}),\n sections: posShiftReportRows(input.report, input.shift),\n }\n}\n"],"names":["apportionCents","withPosHardwareReceiptNotice","orderPayments","receiptDataFromOrder","POS_TENDER_METHODS","POS_TENDER_LABELS","cash","card_present","card_keyed","card_link","gift_card","folio","credit","POS_STRIPE_TENDERS","Set","wholeCents","value","number","Math","round","Number","isFinite","isTenderMethod","includes","posOrderTenders","order","filter","payment","status","method","map","id","amountCents","tipCents","totals","paymentIntentId","giftCardId","reservationId","creditProviderId","creditReference","creditLabel","cardBrand","last4","cashTenderedCents","changeCents","chargeModel","stripeAccountId","posTenderLabel","tender","base","capitalize","charAt","toUpperCase","slice","POS_CASH_EVENT_LABELS","paid_in","paid_out","drop","refund","posCashEventTotals","events","sum","type","event","reduce","total","paidInCents","paidOutCents","dropsCents","cashRefundsCents","posExpectedCashCents","input","openingFloatCents","cashSalesCents","computePosShiftReport","salesByTender","refundsByTender","orderCount","grossSalesCents","discountsCents","taxCents","tipsCents","sale","sales","tenders","totalCents","discountCents","tenderTips","max","refundsCents","refunds","refundedCents","shift","cashEvents","refundCount","length","netSalesCents","expectedCashCents","truncated","posCashVarianceCents","countedCashCents","posMoney","cents","abs","toFixed","csvCell","cell","String","test","replace","posCsvCell","dollars","posShiftsCsv","shifts","memberName","uid","header","iso","ms","Date","toISOString","rows","report","card","undefined","registerName","registerId","openedAtMs","openedByName","openedBy","closedAtMs","closedBy","closedByName","varianceCents","row","join","posReturnLineValues","lines","lineItems","gross","line","unitAmountCents","quantity","discountShares","net","index","taxShares","posReturnedQuantities","wholeLines","refundedLineItemIds","has","returned","returnedQuantities","min","planPosReturn","picks","heldElsewhere","ok","error","values","seen","lineCents","nextReturned","count","entries","completedLines","pick","isInteger","add","already","held","left","name","push","remaining","asked","refundCents","posRefundableByTender","attributed","Object","posPaymentRefunds","unattributed","ordered","sort","a","b","refundable","Map","taken","set","refundableCents","get","REFUND_ORDER","splitPosRefund","requested","amount","allocations","used","find","candidate","paymentId","indexOf","POS_CASHIER_ASSERTION_TTL_MS","POS_MANAGER_ASSERTION_TTL_MS","POS_PIN_MAX_ATTEMPTS","POS_PIN_LOCKOUT_MS","posPinProblem","pin","digits","step","every","digit","buildPosReceipt","data","gift","orderId","storeName","store","detail","variantLabel","unitCents","createdAtMs","formatDate","toLocaleString","money","logoUrl","addressLines","address","split","trim","Boolean","orderNumber","barcodeValue","dateLabel","cashierName","customerName","subtotalCents","footer","returnPolicy","posShiftReportRows","section","label","strong","posShiftPrintReport","title","subtitle","sections"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,cAAc,QAAwB,uBAAmB;AAClE,SAASC,4BAA4B,QAAQ,0BAAsB;AACnE,SAASC,aAAa,QAAQ,oBAAgB;AAE9C,SAASC,oBAAoB,QAAQ,wBAAoB;AA+BzD,OAAO,MAAMC,qBAAiD;IAC5D;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAED,oEAAoE,GACpE,OAAO,MAAMC,oBAA+D;IAC1EC,MAAM;IACNC,cAAc;IACdC,YAAY;IACZC,WAAW;IACXC,WAAW;IACXC,OAAO;IACPC,QAAQ;AACV,EAAC;AAED,2EAA2E,GAC3E,OAAO,MAAMC,qBAAmD,IAAIC,IAAI;IACtE;IACA;IACA;CACD,EAAC;AA6BF,MAAMC,aAAa,CAACC;IAClB,MAAMC,SAASC,KAAKC,KAAK,CAACC,OAAOJ;IACjC,OAAOI,OAAOC,QAAQ,CAACJ,WAAWA,SAAS,IAAIA,SAAS;AAC1D;AAGA,MAAMK,iBAAiB,CAACN,QACtB,OAAOA,UAAU,YAAY,AAACZ,mBAAyCmB,QAAQ,CAACP;AAclF;;;;;;;;;;;;CAYC,GACD,OAAO,SAASQ,gBAAgBC,KAAyC;IACvE,IAAI,CAACA,OAAO,OAAO,EAAE;IACrB,OAAOvB,cAAcuB,OAClBC,MAAM,CAAC,CAACC,UAAYA,QAAQC,MAAM,KAAK,eAAeN,eAAeK,QAAQE,MAAM,GACnFC,GAAG,CAAC,CAACH;YAIiBA;YAA+CF;eAJnD;YACjBM,IAAIJ,QAAQI,EAAE;YACdF,QAAQF,QAAQE,MAAM;YACtBG,aAAajB,WAAWY,QAAQK,WAAW;YAC3CC,UAAUlB,YAAWY,oBAAAA,QAAQM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AAC;gBAChE;oBAAE8K,OAAO;oBAAcjO,OAAO,CAAC,CAAC,EAAEqF,SAASqB,OAAOtD,UAAU,GAAG;gBAAC;gBAChE;oBAAE6K,OAAO;oBAAgBjO,OAAO,CAAC,CAAC,EAAEqF,SAASqB,OAAOrD,gBAAgB,GAAG;gBAAC;gBACxE;oBAAE4K,OAAO;oBAAsBjO,OAAOqF,SAASqB,OAAOzB,iBAAiB;oBAAGiJ,QAAQ;gBAAK;mBACnFtJ,CAAAA,yBAAAA,MAAOQ,gBAAgB,KAAI,OAC3B;oBACE;wBAAE6I,OAAO;wBAAWjO,OAAOqF,SAAST,MAAMQ,gBAAgB;oBAAE;oBAC5D;wBACE6I,OAAO,EAACrJ,uBAAAA,MAAMyC,aAAa,YAAnBzC,uBAAuB,KAAK,IAAI,UAAU,EAACA,wBAAAA,MAAMyC,aAAa,YAAnBzC,wBAAuB,KAAK,IAAI,SAAS;wBAC5F5E,OAAOqF,UAAST,wBAAAA,MAAMyC,aAAa,YAAnBzC,wBAAuB;wBACvCsJ,QAAQ;oBACV;iBACD,GACD,EAAE;aACP;QACH;KACD;AACH;AAEA,8DAA8D,GAC9D,OAAO,SAASC,oBAAoB5K,KAOnC;IACC,OAAO;QACL6K,OAAO7K,MAAM6K,KAAK;QAClB5B,WAAWjJ,MAAMiJ,SAAS;OACtBjJ,MAAM8K,QAAQ,IAAI9K,MAAMsD,YAAY,GACpC;QAAEwH,UAAU;YAAC9K,MAAMsD,YAAY;YAAEtD,MAAM8K,QAAQ;SAAC,CAAC3N,MAAM,CAAC4M,SAAS/F,IAAI,CAAC;IAAO,IAC7E,CAAC;QACL+G,UAAUP,mBAAmBxK,MAAMmD,MAAM,EAAEnD,MAAMqB,KAAK;;AAE1D"}
|
|
@@ -89,6 +89,14 @@ export interface OrderPayment {
|
|
|
89
89
|
failureMessage?: string;
|
|
90
90
|
/** Whether Stripe moved real money; absent for tenders Stripe never saw. */
|
|
91
91
|
livemode?: boolean;
|
|
92
|
+
/**
|
|
93
|
+
* `direct` when the card was charged ON the store's own Stripe account
|
|
94
|
+
* (ToS v24 section 10.2(a)), with that account in `stripeAccountId`: its
|
|
95
|
+
* capture, cancel and refund are made there. Absent for a destination
|
|
96
|
+
* charge on the platform, every register payment before the switch.
|
|
97
|
+
*/
|
|
98
|
+
chargeModel?: 'direct';
|
|
99
|
+
stripeAccountId?: string;
|
|
92
100
|
/** The console user who took the payment. */
|
|
93
101
|
cashierId?: string;
|
|
94
102
|
}
|