@aglyn/plugins-commerce 1.15.2 → 1.17.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.
Files changed (220) hide show
  1. package/README.md +1 -1
  2. package/package.json +13 -13
  3. package/src/lib/components/cart.js +2 -1
  4. package/src/lib/components/cart.js.map +1 -1
  5. package/src/lib/components/console/payments-settings-card.component.js +6 -1
  6. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  7. package/src/lib/components/console/pos/pos-api.d.ts +5 -0
  8. package/src/lib/components/console/pos/pos-api.js.map +1 -1
  9. package/src/lib/components/console/pos/pos-tender-dialogs.component.d.ts +2 -0
  10. package/src/lib/components/console/pos/pos-tender-dialogs.component.js +13 -6
  11. package/src/lib/components/console/pos/pos-tender-dialogs.component.js.map +1 -1
  12. package/src/lib/components/console/pos/pos-tender-panel.component.js +7 -4
  13. package/src/lib/components/console/pos/pos-tender-panel.component.js.map +1 -1
  14. package/src/lib/components/console/pos-cellular-control.component.d.ts +5 -0
  15. package/src/lib/components/console/pos-cellular-control.component.js +29 -15
  16. package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
  17. package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
  18. package/src/lib/components/console/product-add-ons-fields.component.js +96 -3
  19. package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
  20. package/src/lib/components/console/product-builder-fields.component.d.ts +39 -0
  21. package/src/lib/components/console/product-builder-fields.component.js +195 -0
  22. package/src/lib/components/console/product-builder-fields.component.js.map +1 -0
  23. package/src/lib/components/console/product-editor-dialog.component.js +35 -2
  24. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  25. package/src/lib/components/console/quote-editor-dialog.component.js +43 -6
  26. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
  27. package/src/lib/components/console/quote-messages.component.d.ts +21 -0
  28. package/src/lib/components/console/quote-messages.component.js +185 -0
  29. package/src/lib/components/console/quote-messages.component.js.map +1 -0
  30. package/src/lib/components/console/quote-pay-link.component.js +1 -1
  31. package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
  32. package/src/lib/components/console/quote-proofs.component.js +30 -3
  33. package/src/lib/components/console/quote-proofs.component.js.map +1 -1
  34. package/src/lib/components/console/quote-settings-card.component.d.ts +7 -3
  35. package/src/lib/components/console/quote-settings-card.component.js +154 -24
  36. package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
  37. package/src/lib/components/product-builder-context.d.ts +22 -0
  38. package/src/lib/components/product-builder-context.js +21 -0
  39. package/src/lib/components/product-builder-context.js.map +1 -0
  40. package/src/lib/components/product-builder-mockup.d.ts +42 -0
  41. package/src/lib/components/product-builder-mockup.js +120 -0
  42. package/src/lib/components/product-builder-mockup.js.map +1 -0
  43. package/src/lib/components/product-builder-sample.d.ts +63 -0
  44. package/src/lib/components/product-builder-sample.js +96 -0
  45. package/src/lib/components/product-builder-sample.js.map +1 -0
  46. package/src/lib/components/product-choice-cards.d.ts +51 -0
  47. package/src/lib/components/product-choice-cards.js +311 -0
  48. package/src/lib/components/product-choice-cards.js.map +1 -0
  49. package/src/lib/components/product-detail-panels.d.ts +42 -0
  50. package/src/lib/components/product-detail-panels.js +185 -0
  51. package/src/lib/components/product-detail-panels.js.map +1 -0
  52. package/src/lib/components/product-detail.d.ts +20 -12
  53. package/src/lib/components/product-detail.js +136 -221
  54. package/src/lib/components/product-detail.js.map +1 -1
  55. package/src/lib/components/product-grid.d.ts +7 -0
  56. package/src/lib/components/product-grid.js +13 -9
  57. package/src/lib/components/product-grid.js.map +1 -1
  58. package/src/lib/components/product-name-lines.d.ts +37 -0
  59. package/src/lib/components/product-name-lines.js +36 -0
  60. package/src/lib/components/product-name-lines.js.map +1 -0
  61. package/src/lib/components/product-options-field-body.d.ts +9 -8
  62. package/src/lib/components/product-options-field-body.js +152 -3
  63. package/src/lib/components/product-options-field-body.js.map +1 -1
  64. package/src/lib/components/product-options-field.js +1 -1
  65. package/src/lib/components/product-options-field.js.map +1 -1
  66. package/src/lib/components/product-photo-fit.d.ts +49 -0
  67. package/src/lib/components/product-photo-fit.js +58 -0
  68. package/src/lib/components/product-photo-fit.js.map +1 -0
  69. package/src/lib/components/product-restock-notify.d.ts +12 -0
  70. package/src/lib/components/product-restock-notify.js +86 -0
  71. package/src/lib/components/product-restock-notify.js.map +1 -0
  72. package/src/lib/components/quote-messages-panel.d.ts +21 -0
  73. package/src/lib/components/quote-messages-panel.js +191 -0
  74. package/src/lib/components/quote-messages-panel.js.map +1 -0
  75. package/src/lib/components/quote-page-body.js +15 -1
  76. package/src/lib/components/quote-page-body.js.map +1 -1
  77. package/src/lib/components/quote-proof-panel.d.ts +6 -3
  78. package/src/lib/components/quote-proof-panel.js +139 -14
  79. package/src/lib/components/quote-proof-panel.js.map +1 -1
  80. package/src/lib/components/related-products.d.ts +7 -0
  81. package/src/lib/components/related-products.js +10 -7
  82. package/src/lib/components/related-products.js.map +1 -1
  83. package/src/lib/constants/quote-page.d.ts +8 -0
  84. package/src/lib/constants/quote-page.js +11 -0
  85. package/src/lib/constants/quote-page.js.map +1 -1
  86. package/src/lib/model/commerce-cart.d.ts +6 -1
  87. package/src/lib/model/commerce-cart.js +5 -1
  88. package/src/lib/model/commerce-cart.js.map +1 -1
  89. package/src/lib/model/commerce-invoices.js +5 -1
  90. package/src/lib/model/commerce-invoices.js.map +1 -1
  91. package/src/lib/model/commerce-pos-ops.d.ts +3 -0
  92. package/src/lib/model/commerce-pos-ops.js +3 -0
  93. package/src/lib/model/commerce-pos-ops.js.map +1 -1
  94. package/src/lib/model/commerce-pos.d.ts +8 -0
  95. package/src/lib/model/commerce-pos.js.map +1 -1
  96. package/src/lib/model/commerce-quote-messages.d.ts +106 -0
  97. package/src/lib/model/commerce-quote-messages.js +146 -0
  98. package/src/lib/model/commerce-quote-messages.js.map +1 -0
  99. package/src/lib/model/commerce-quote-pay.d.ts +31 -2
  100. package/src/lib/model/commerce-quote-pay.js +31 -7
  101. package/src/lib/model/commerce-quote-pay.js.map +1 -1
  102. package/src/lib/model/commerce-quote-proofs.d.ts +47 -8
  103. package/src/lib/model/commerce-quote-proofs.js +73 -18
  104. package/src/lib/model/commerce-quote-proofs.js.map +1 -1
  105. package/src/lib/model/commerce-quote-request.d.ts +14 -4
  106. package/src/lib/model/commerce-quote-request.js +25 -2
  107. package/src/lib/model/commerce-quote-request.js.map +1 -1
  108. package/src/lib/model/commerce-quotes.d.ts +56 -3
  109. package/src/lib/model/commerce-quotes.js +47 -2
  110. package/src/lib/model/commerce-quotes.js.map +1 -1
  111. package/src/lib/model/commerce.d.ts +12 -1
  112. package/src/lib/model/commerce.js.map +1 -1
  113. package/src/lib/model/index.d.ts +1 -0
  114. package/src/lib/model/index.js +1 -0
  115. package/src/lib/model/index.js.map +1 -1
  116. package/src/lib/model/pos-cellular.d.ts +36 -4
  117. package/src/lib/model/pos-cellular.js +39 -4
  118. package/src/lib/model/pos-cellular.js.map +1 -1
  119. package/src/lib/model/product-card-rules.d.ts +41 -0
  120. package/src/lib/model/product-card-rules.js +90 -0
  121. package/src/lib/model/product-card-rules.js.map +1 -0
  122. package/src/lib/model/product-modifiers.d.ts +11 -0
  123. package/src/lib/model/product-modifiers.js +10 -0
  124. package/src/lib/model/product-modifiers.js.map +1 -1
  125. package/src/lib/model/product-write.d.ts +3 -0
  126. package/src/lib/server/billing-webhook.js +6 -2
  127. package/src/lib/server/billing-webhook.js.map +1 -1
  128. package/src/lib/server/cancel-order.js +15 -0
  129. package/src/lib/server/cancel-order.js.map +1 -1
  130. package/src/lib/server/channel-order-updates.js +15 -1
  131. package/src/lib/server/channel-order-updates.js.map +1 -1
  132. package/src/lib/server/channel-orders.js +20 -0
  133. package/src/lib/server/channel-orders.js.map +1 -1
  134. package/src/lib/server/checkout.js +1 -1
  135. package/src/lib/server/checkout.js.map +1 -1
  136. package/src/lib/server/local-fulfillment.js +1 -1
  137. package/src/lib/server/local-fulfillment.js.map +1 -1
  138. package/src/lib/server/pos-cellular-billing.d.ts +5 -4
  139. package/src/lib/server/pos-cellular-billing.js +24 -12
  140. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  141. package/src/lib/server/pos-cellular.d.ts +3 -1
  142. package/src/lib/server/pos-cellular.js +55 -33
  143. package/src/lib/server/pos-cellular.js.map +1 -1
  144. package/src/lib/server/pos-offline-sync.d.ts +3 -3
  145. package/src/lib/server/pos-offline-sync.js +17 -4
  146. package/src/lib/server/pos-offline-sync.js.map +1 -1
  147. package/src/lib/server/pos-order.js +17 -6
  148. package/src/lib/server/pos-order.js.map +1 -1
  149. package/src/lib/server/pos-payment.js +27 -11
  150. package/src/lib/server/pos-payment.js.map +1 -1
  151. package/src/lib/server/pos-reader-splash.js +10 -5
  152. package/src/lib/server/pos-reader-splash.js.map +1 -1
  153. package/src/lib/server/pos-readers.js +42 -12
  154. package/src/lib/server/pos-readers.js.map +1 -1
  155. package/src/lib/server/pos-return.js +19 -3
  156. package/src/lib/server/pos-return.js.map +1 -1
  157. package/src/lib/server/pos-stripe.d.ts +14 -0
  158. package/src/lib/server/pos-stripe.js +6 -2
  159. package/src/lib/server/pos-stripe.js.map +1 -1
  160. package/src/lib/server/pos-terminal-connection-token.js +23 -9
  161. package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
  162. package/src/lib/server/pos-terminal.d.ts +80 -14
  163. package/src/lib/server/pos-terminal.js +393 -123
  164. package/src/lib/server/pos-terminal.js.map +1 -1
  165. package/src/lib/server/product-drafts.d.ts +1 -1
  166. package/src/lib/server/product-drafts.js +4 -3
  167. package/src/lib/server/product-drafts.js.map +1 -1
  168. package/src/lib/server/product-writer.js +5 -4
  169. package/src/lib/server/product-writer.js.map +1 -1
  170. package/src/lib/server/product.d.ts +11 -0
  171. package/src/lib/server/product.js +18 -3
  172. package/src/lib/server/product.js.map +1 -1
  173. package/src/lib/server/products-write.js +4 -3
  174. package/src/lib/server/products-write.js.map +1 -1
  175. package/src/lib/server/quote-email.d.ts +26 -0
  176. package/src/lib/server/quote-email.js +73 -7
  177. package/src/lib/server/quote-email.js.map +1 -1
  178. package/src/lib/server/quote-messages.d.ts +72 -0
  179. package/src/lib/server/quote-messages.js +356 -0
  180. package/src/lib/server/quote-messages.js.map +1 -0
  181. package/src/lib/server/quote-pay.d.ts +42 -0
  182. package/src/lib/server/quote-pay.js +81 -4
  183. package/src/lib/server/quote-pay.js.map +1 -1
  184. package/src/lib/server/quote-proofs.d.ts +1 -1
  185. package/src/lib/server/quote-proofs.js +63 -19
  186. package/src/lib/server/quote-proofs.js.map +1 -1
  187. package/src/lib/server/quote.d.ts +12 -0
  188. package/src/lib/server/quote.js +69 -16
  189. package/src/lib/server/quote.js.map +1 -1
  190. package/src/lib/server/refund.js +3 -1
  191. package/src/lib/server/refund.js.map +1 -1
  192. package/src/lib/server/reserve-stock.js +9 -0
  193. package/src/lib/server/reserve-stock.js.map +1 -1
  194. package/src/lib/server/returns.js +15 -1
  195. package/src/lib/server/returns.js.map +1 -1
  196. package/src/lib/server/reviews.js +15 -0
  197. package/src/lib/server/reviews.js.map +1 -1
  198. package/src/lib/server/sold-out-drop.d.ts +58 -0
  199. package/src/lib/server/sold-out-drop.js +81 -0
  200. package/src/lib/server/sold-out-drop.js.map +1 -0
  201. package/src/lib/server/stock-levels.js +9 -0
  202. package/src/lib/server/stock-levels.js.map +1 -1
  203. package/src/lib/server/stripe-refund.d.ts +7 -0
  204. package/src/lib/server/stripe-refund.js +26 -7
  205. package/src/lib/server/stripe-refund.js.map +1 -1
  206. package/src/lib/server.d.ts +15 -0
  207. package/src/lib/server.js +30 -1
  208. package/src/lib/server.js.map +1 -1
  209. package/src/lib/tenant-emails.js +85 -2
  210. package/src/lib/tenant-emails.js.map +1 -1
  211. package/src/lib/testing/fake-seller-payment-account.d.ts +29 -0
  212. package/src/lib/testing/fake-seller-payment-account.js +40 -0
  213. package/src/lib/testing/fake-seller-payment-account.js.map +1 -0
  214. package/src/lib/transfer/product-transfer.js +6 -5
  215. package/src/lib/transfer/product-transfer.js.map +1 -1
  216. package/src/lib/transfer/products.server.js +4 -3
  217. package/src/lib/transfer/products.server.js.map +1 -1
  218. package/src/lib/utils/quote-email-content.d.ts +6 -0
  219. package/src/lib/utils/quote-email-content.js +6 -3
  220. package/src/lib/utils/quote-email-content.js.map +1 -1
@@ -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,OA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yC,aAAa,YAAnBzC,uBAAuB,KAAK,IAAI,UAAU,EAACA,wBAAAA,MAAMyC,aAAa,YAAnBzC,wBAAuB,KAAK,IAAI,SAAS;wBAC5F1E,OAAOmF,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,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,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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
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-pos.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * THE POS TENDER LEDGER (AGL-3607).\n *\n * A register sale used to be settled by exactly one tender and recorded none:\n * whether a POS order was paid in cash, by the QR link or to a room was\n * inferred afterwards from which other fields happened to be set. A sale now\n * carries `payments[]`, one entry per tender, and takes payments until the\n * balance due is zero. Only then is it `paid`.\n *\n * Every figure here is integer cents. `amountCents` is what a payment put\n * toward the SALE; a tip rides beside it in `tipCents` and never counts toward\n * the balance, the platform's take or the store's revenue. Tips belong to the\n * merchant and their staff.\n *\n * Pure and framework-free, so the register, the customer display and the\n * server read one answer.\n *=========================================*/\n\n/** How one payment toward a register sale was taken. */\nexport type OrderPaymentMethod =\n | 'cash'\n /** A Stripe Terminal smart reader (tap, insert or swipe). */\n | 'card_present'\n /** A card typed into the console by staff (card not present). */\n | 'card_keyed'\n /** The Stripe payment page the customer opens from a QR code. */\n | 'card_link'\n | 'gift_card'\n /** Charged to a checked-in reservation's folio. */\n | 'folio'\n /**\n * Store credit another plugin keeps — rewards, referral credit — taken\n * through core's checkout-credits seam (AGL-3640). Which plugin and which\n * account ride on the payment as `creditProviderId` and `creditReference`.\n */\n | 'credit'\n\nexport type OrderPaymentStatus =\n /** Started and not finished: reserves its amount against the balance. */\n | 'pending'\n | 'succeeded'\n /** Declined or errored; may be retried, reserves nothing. */\n | 'failed'\n | 'canceled'\n /** Taken and then handed back when the open sale was voided. */\n | 'reversed'\n\nexport const ORDER_PAYMENT_METHODS: readonly OrderPaymentMethod[] = [\n 'cash',\n 'card_present',\n 'card_keyed',\n 'card_link',\n 'gift_card',\n 'folio',\n 'credit',\n]\n\n/** One payment toward a register sale, on `HostOrder.payments`. */\nexport interface OrderPayment {\n /** Stable id, derived from the register's attempt key so a retry finds it. */\n id: string\n method: OrderPaymentMethod\n /** Cents put toward the sale. Never includes the tip. */\n amountCents: number\n /** Gratuity on top of `amountCents`, the merchant's and not revenue. */\n tipCents?: number\n status: OrderPaymentStatus\n /** When the payment was started. */\n atMs: number\n /** When it reached `succeeded`. */\n settledAtMs?: number\n /** Stripe PaymentIntent for `card_present` / `card_keyed` / a paid link. */\n paymentIntentId?: string\n /** Stripe Checkout Session for `card_link`. */\n checkoutSessionId?: string\n /** The payment page a `card_link` payment shows as a QR. */\n checkoutUrl?: string\n /** The Terminal reader a `card_present` payment runs on. */\n readerId?: string\n /** The gift card's code (its document id) for `gift_card`. */\n giftCardId?: string\n /** For `credit`: the provider that paid it (`{pluginId}.{key}`, AGL-3640). */\n creditProviderId?: string\n /** For `credit`: the provider's own handle on the account it came from. */\n creditReference?: string\n /** For `credit`: what the provider calls it, for the register and receipt. */\n creditLabel?: string\n cardBrand?: string\n last4?: string\n /** Cash handed over for a `cash` payment, and the change given back. */\n cashTenderedCents?: number\n changeCents?: number\n /** The stay a `folio` payment was charged to. */\n reservationId?: string\n /** The folio entry's `atMs`, so a void can remove exactly that entry. */\n folioAtMs?: number\n /**\n * The platform's take attributed to this payment (excludes the tip). For a\n * card payment it is netted from the payout with Stripe's processing cost\n * added, and recorded in `feeCents`; otherwise it accrues to the invoice.\n */\n takeFeeCents?: number\n /** The `application_fee_amount` a card payment carried, or 0. */\n feeCents?: number\n /** Why a `failed` payment failed, in words the cashier can read out. */\n failureMessage?: string\n /** Whether Stripe moved real money; absent for tenders Stripe never saw. */\n livemode?: boolean\n /** The console user who took the payment. */\n cashierId?: string\n}\n\n/** The tenders whose money moves through Stripe. */\nexport const POS_CARD_METHODS: ReadonlySet<OrderPaymentMethod> = new Set([\n 'card_present',\n 'card_keyed',\n 'card_link',\n])\n\nexport function isCardPaymentMethod(method: OrderPaymentMethod): boolean {\n return POS_CARD_METHODS.has(method)\n}\n\n/*==========================================\n * WHICH TENDERS CARRY THE PLATFORM FEE (AGL-4036).\n *\n * The take used to follow the sale whatever paid it (AGL-2111): a cash sale\n * owed the same percentage as a card sale and had it added to the monthly\n * invoice. In-person rivals charge nothing on cash, and an event register that\n * bills its operator for the cash in their own apron is not one they will\n * choose, so three tenders now carry none:\n *\n * - cash: no payment service touches it, and the merchant keeps all of it;\n * - gift card: the fee was taken when the card was SOLD, so charging it again\n * when the card is spent would charge the same money twice;\n * - store credit (`credit`): rewards or referral value the merchant gave\n * away, so no money changes hands and an invoiced fee on it would only\n * penalize running a rewards program.\n *\n * Everything else still carries it. Card payments net it from their payout,\n * as always. A room charge (`folio`) is new revenue booked to a stay, so its\n * share goes on the invoice.\n *\n * One predicate, so the register, the completion, the offline sync and the\n * docs cannot disagree about which tender is which.\n *=========================================*/\n\n/** The tenders that carry no platform fee (AGL-4036). */\nexport const POS_FEE_FREE_METHODS: ReadonlySet<OrderPaymentMethod> = new Set([\n 'cash',\n 'gift_card',\n 'credit',\n])\n\n/** Whether a payment by `method` carries its share of the platform's take. */\nexport function paymentCarriesPlatformFee(method: OrderPaymentMethod): boolean {\n return !POS_FEE_FREE_METHODS.has(method)\n}\n\n/**\n * The take a sale owes when ONE tender pays all of it: the whole take, or\n * nothing for a fee-free tender.\n */\nexport function posTenderTakeCents(\n method: OrderPaymentMethod,\n takeFeeCents: number,\n): number {\n return paymentCarriesPlatformFee(method) ? wholeCents(takeFeeCents) : 0\n}\n\n/** Whole non-negative cents from an untrusted value. */\nfunction wholeCents(value: unknown): number {\n const number = Math.round(Number(value))\n return Number.isFinite(number) && number > 0 ? number : 0\n}\n\n/**\n * The order's payments, read through one door.\n *\n * Orders written before the ledger existed carry no `payments`, so one is\n * INFERRED from the fields the single-tender register wrote: a folio sale has\n * `reservationId`, a QR sale has `checkoutSessionId`, and anything else on the\n * POS channel was cash. A pending legacy sale is the QR link still waiting.\n * Online orders paid through Stripe Checkout read as one `card_link` payment.\n * Nothing is written back: this is a reader, never a migration.\n */\nexport function orderPayments(order: {\n payments?: OrderPayment[] | null\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 createdAtMs?: number\n}): OrderPayment[] {\n if (Array.isArray(order?.payments)) {\n return order.payments.filter(\n (payment): payment is OrderPayment =>\n Boolean(payment) && typeof payment === 'object' && Boolean(payment.id),\n )\n }\n const totalCents = wholeCents(order?.totals?.totalCents ?? order?.amountCents)\n if (!(totalCents > 0)) return []\n const settled = order?.status !== 'pending' && order?.status !== 'cancelled'\n const atMs = Number(order?.createdAtMs) || 0\n const method: OrderPaymentMethod = order?.reservationId\n ? 'folio'\n : order?.checkoutSessionId || order?.paymentIntentId || order?.channel !== 'pos'\n ? 'card_link'\n : 'cash'\n return [\n {\n id: 'legacy',\n method,\n amountCents: totalCents,\n status: settled ? 'succeeded' : order?.status === 'cancelled' ? 'canceled' : 'pending',\n atMs,\n ...(order?.paymentIntentId ? { paymentIntentId: order.paymentIntentId } : {}),\n ...(order?.checkoutSessionId ? { checkoutSessionId: order.checkoutSessionId } : {}),\n ...(order?.reservationId ? { reservationId: order.reservationId } : {}),\n },\n ]\n}\n\n/** Cents put toward the sale by payments that succeeded. */\nexport function posSettledCents(payments: readonly OrderPayment[]): number {\n return payments\n .filter((payment) => payment.status === 'succeeded')\n .reduce((sum, payment) => sum + wholeCents(payment.amountCents), 0)\n}\n\n/**\n * Cents spoken for: succeeded payments plus the ones still in flight. A\n * reader waiting for a tap has claimed its share of the balance, so a second\n * tender cannot be started for the same money.\n */\nexport function posReservedCents(payments: readonly OrderPayment[]): number {\n return payments\n .filter((payment) => payment.status === 'succeeded' || payment.status === 'pending')\n .reduce((sum, payment) => sum + wholeCents(payment.amountCents), 0)\n}\n\n/** What the customer still owes, by settled payments. */\nexport function posBalanceDueCents(\n totalCents: number,\n payments: readonly OrderPayment[],\n): number {\n return Math.max(0, wholeCents(totalCents) - posSettledCents(payments))\n}\n\n/** What a NEW payment may still take: the balance less what is in flight. */\nexport function posTenderableCents(\n totalCents: number,\n payments: readonly OrderPayment[],\n): number {\n return Math.max(0, wholeCents(totalCents) - posReservedCents(payments))\n}\n\n/** Tips taken across the sale's settled payments. */\nexport function posTipCents(payments: readonly OrderPayment[]): number {\n return payments\n .filter((payment) => payment.status === 'succeeded')\n .reduce((sum, payment) => sum + wholeCents(payment.tipCents), 0)\n}\n\n/**\n * The share of the sale's take a payment of `amountCents` carries.\n *\n * Proportional to the part of the SALE it pays, never to the tip. Card\n * payments carry their share in `application_fee_amount`; whatever the card\n * shares leave is accrued to the invoice at completion\n * ({@link posInvoiceTakeCents}), so the take is exact however the sale was\n * split and however each share rounded.\n */\nexport function posTakeShareCents(input: {\n takeFeeCents: number\n totalCents: number\n amountCents: number\n}): number {\n const take = wholeCents(input.takeFeeCents)\n const total = wholeCents(input.totalCents)\n const amount = Math.min(wholeCents(input.amountCents), total)\n if (!(take > 0) || !(total > 0) || !(amount > 0)) return 0\n return Math.min(take, Math.round((take * amount) / total))\n}\n\n/**\n * {@link posTakeShareCents} for a payment by `method`: its share of the take,\n * or 0 for a tender that carries no platform fee (AGL-4036).\n */\nexport function posPaymentTakeShareCents(input: {\n method: OrderPaymentMethod\n takeFeeCents: number\n totalCents: number\n amountCents: number\n}): number {\n if (!paymentCarriesPlatformFee(input.method)) return 0\n return posTakeShareCents(input)\n}\n\n/**\n * The part of the sale's take its tenders owe (AGL-4036): the whole take when\n * every settled payment carries the fee, and otherwise the share for the part\n * of the sale the fee-carrying payments paid. Cash and gift-card parts owe\n * nothing, so a sale paid all in cash owes 0.\n *\n * Worked from the payments' METHODS, not from the `takeFeeCents` each one\n * recorded, so a sale that was opened before this rule and finished after it\n * is charged by the rule it finished under.\n */\nexport function posOwedTakeCents(input: {\n takeFeeCents: number\n totalCents: number\n payments: readonly OrderPayment[]\n}): number {\n const take = wholeCents(input.takeFeeCents)\n const settled = input.payments.filter((payment) => payment.status === 'succeeded')\n if (settled.every((payment) => paymentCarriesPlatformFee(payment.method))) return take\n const carryingCents = settled\n .filter((payment) => paymentCarriesPlatformFee(payment.method))\n .reduce((sum, payment) => sum + wholeCents(payment.amountCents), 0)\n return posTakeShareCents({\n takeFeeCents: take,\n totalCents: input.totalCents,\n amountCents: carryingCents,\n })\n}\n\n/**\n * What of the sale's take was NOT netted from a card payout, and therefore\n * goes on the merchant's invoice: the take the tenders owe\n * ({@link posOwedTakeCents}) less every succeeded card payment's share. Never\n * negative, and 0 for a sale paid only by card, cash, gift card and store credit.\n */\nexport function posInvoiceTakeCents(input: {\n takeFeeCents: number\n totalCents: number\n payments: readonly OrderPayment[]\n}): number {\n const netted = input.payments\n .filter(\n (payment) =>\n payment.status === 'succeeded' && isCardPaymentMethod(payment.method),\n )\n .reduce((sum, payment) => sum + wholeCents(payment.takeFeeCents), 0)\n return Math.max(0, posOwedTakeCents(input) - netted)\n}\n\n/**\n * How the sale's fee reaches the platform, from the payments that carried it.\n * A cash, gift-card or store-credit part carries none (AGL-4036), so a card + cash sale is\n * `payout`, not `split`.\n */\nexport function posFeeCollection(\n payments: readonly OrderPayment[],\n): 'payout' | 'invoice' | 'split' {\n const settled = payments.filter(\n (payment) =>\n payment.status === 'succeeded' && paymentCarriesPlatformFee(payment.method),\n )\n const card = settled.some((payment) => isCardPaymentMethod(payment.method))\n const other = settled.some((payment) => !isCardPaymentMethod(payment.method))\n if (card && other) return 'split'\n return card ? 'payout' : 'invoice'\n}\n\n/** A one-line description of a payment for the register, receipt and timeline. */\nexport function describeOrderPayment(payment: OrderPayment): string {\n const dollars = (cents: number) => `$${(cents / 100).toFixed(2)}`\n const label =\n (payment.method === 'credit' && payment.creditLabel) || ORDER_PAYMENT_METHOD_LABELS[payment.method] || 'Payment'\n const card =\n payment.cardBrand || payment.last4\n ? ` (${[payment.cardBrand, payment.last4 ? `•••• ${payment.last4}` : '']\n .filter(Boolean)\n .join(' ')})`\n : ''\n const tip = wholeCents(payment.tipCents)\n ? ` + ${dollars(wholeCents(payment.tipCents))} tip`\n : ''\n return `${label}${card} ${dollars(wholeCents(payment.amountCents))}${tip}`\n}\n\nexport const ORDER_PAYMENT_METHOD_LABELS: Record<OrderPaymentMethod, string> = {\n cash: 'Cash',\n card_present: 'Card reader',\n card_keyed: 'Typed card',\n card_link: 'Card (QR)',\n gift_card: 'Gift card',\n folio: 'Charged to room',\n credit: 'Store credit',\n}\n\n/*==========================================\n * TIPS (AGL-3607).\n *=========================================*/\n\n/** The presets a merchant starts with. */\nexport const POS_TIP_PERCENTAGES_DEFAULT: readonly number[] = [15, 18, 20, 25]\n\n/**\n * The merchant's tip presets from the plugin setting, a comma list such as\n * `15, 18, 20, 25`. Whole percentages from 1 to 100, at most four, in the order\n * given; anything unreadable falls back to the defaults rather than showing\n * the customer an empty choice.\n */\nexport function posTipPercentages(raw: unknown): number[] {\n const parsed = String(raw ?? '')\n .split(/[,\\s]+/)\n .map((part) => Math.round(Number(part)))\n .filter((value) => Number.isFinite(value) && value >= 1 && value <= 100)\n const unique = [...new Set(parsed)].slice(0, 4)\n return unique.length ? unique : [...POS_TIP_PERCENTAGES_DEFAULT]\n}\n\n/** A percentage tip on `baseCents`, rounded to the cent. */\nexport function posTipFromPercent(baseCents: number, percent: number): number {\n const base = wholeCents(baseCents)\n const pct = Number(percent)\n if (!(base > 0) || !Number.isFinite(pct) || pct <= 0) return 0\n return Math.round((base * pct) / 100)\n}\n\n/** The largest tip the register accepts on one payment: the payment itself. */\nexport function posTipProblem(tipCents: number, amountCents: number): string | null {\n if (!Number.isInteger(tipCents) || tipCents < 0) return 'Enter a tip of $0 or more.'\n if (tipCents > wholeCents(amountCents)) {\n return 'A tip can be at most the amount being paid. Check the amount and try again.'\n }\n return null\n}\n\n/*==========================================\n * THE CUSTOMER DISPLAY (AGL-3608).\n *\n * A paired screen facing the customer reads one document per register,\n * `hosts/{hostId}/registers/{registerId}/display/state`, through the\n * `commerce/pos-display` route and its display token. The register writes\n * the prompt; the customer's answer comes back in `response`.\n *=========================================*/\n\nexport type PosDisplayMode =\n | 'idle'\n /** The live basket, mirrored as the cashier builds it. */\n | 'cart'\n /** The customer picks a tip. */\n | 'tip'\n /** The customer picks how they want their receipt. */\n | 'receipt'\n /** A card payment is waiting on the reader. */\n | 'processing'\n | 'thanks'\n /**\n * Another plugin's screen (AGL-4042), asked for through core's customer\n * display seam (`plugin-customer-display`): the display opens that\n * plugin's public page, which sends it back here when the customer is done.\n */\n | 'screen'\n\nexport type PosReceiptChannel = 'email' | 'sms' | 'print' | 'none'\n\nexport interface PosDisplayLine {\n name: string\n variantLabel?: string\n quantity: number\n amountCents: number\n}\n\nexport interface PosDisplayCart {\n lines: PosDisplayLine[]\n itemsCents: number\n discountCents: number\n taxCents: number\n totalCents: number\n /** Taken so far, and what is still due, once payments start. */\n paidCents?: number\n dueCents?: number\n tipCents?: number\n}\n\n/** The customer's answer to the current prompt. */\nexport interface PosDisplayResponse {\n /** The prompt this answers; a stale answer is refused. */\n promptId: string\n tipCents?: number\n tipPercent?: number\n /** `none` when the customer chose no tip. */\n tipChoice?: 'percent' | 'custom' | 'none'\n receiptChannel?: PosReceiptChannel\n email?: string\n phone?: string\n marketingOptIn?: boolean\n atMs: number\n}\n\nexport interface PosDisplayState {\n mode: PosDisplayMode\n updatedAtMs: number\n /**\n * The ISO currency every amount on the screen is in (`usd`). Stamped by\n * the server from the store's own currency, never taken from the register.\n */\n currency?: string\n /** Changes every time the register asks something new. */\n promptId?: string\n cart?: PosDisplayCart\n tip?: {\n /** What a percentage is taken of: the amount being paid now. */\n baseCents: number\n percentages: number[]\n allowCustom: boolean\n }\n receipt?: {\n channels: PosReceiptChannel[]\n /** Whether to offer the store's marketing opt-in under the email field. */\n offerMarketing: boolean\n }\n processing?: { message: string }\n /** The plugin page a `screen` state opens, as core's seam shapes it. */\n screen?: PosDisplayScreen\n /**\n * The staff member (uid) who put {@link screen} on the display (AGL-4042),\n * stamped by the server from the session that pushed it, never taken from\n * the register's body. Core's display verifier names them to the screen's\n * plugin, whose record of what the customer did there names who showed it.\n * Never sent to the display.\n */\n screenShownBy?: string\n response?: PosDisplayResponse\n}\n\n/**\n * A plugin's screen on the display (AGL-4042): the shape of core's\n * `CustomerDisplayScreen`, restated so this module imports nothing. The\n * server checks it with core's own sanitizer before it is stored.\n */\nexport interface PosDisplayScreen {\n pluginId: string\n path: string\n params: Record<string, string>\n}\n\n/** Most lines a display state carries; a longer basket shows its newest. */\nexport const POS_DISPLAY_MAX_LINES = 60\n\n/** A pairing code lives this long before the register must show a new one. */\nexport const POS_DISPLAY_PAIRING_TTL_MS = 10 * 60 * 1000\n\n/** A thank-you screen returns to idle on the display after this long. */\nexport const POS_DISPLAY_THANKS_MS = 8_000\n\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/** An email address as the display may store it, or '' when it is not one. */\nexport function posDisplayEmail(value: unknown): string {\n const email = String(value ?? '').trim().toLowerCase().slice(0, 254)\n return EMAIL_PATTERN.test(email) ? email : ''\n}\n\n/** A phone number as digits with an optional leading +, or '' when too short. */\nexport function posDisplayPhone(value: unknown): string {\n const raw = String(value ?? '').trim()\n const digits = raw.replace(/[^0-9]/g, '')\n if (digits.length < 7 || digits.length > 15) return ''\n return `${raw.startsWith('+') ? '+' : ''}${digits}`\n}\n\n/**\n * The display state as the REGISTER may send it: clamped, typed and stripped\n * of anything the customer screen has no business holding. The register is\n * staff and trusted for intent, not for shape.\n */\nexport function sanitizePosDisplayState(\n raw: unknown,\n nowMs: number,\n options: {\n /**\n * Checks a `screen` state's plugin page (core's\n * `sanitizeCustomerDisplayScreen`). Without it, or when it refuses, a\n * `screen` state is idle: nothing opens on the display unchecked.\n */\n screen?: (raw: unknown) => PosDisplayScreen | null\n } = {},\n): PosDisplayState {\n const input = (raw && typeof raw === 'object' ? raw : {}) as Record<string, any>\n const modes: PosDisplayMode[] = ['idle', 'cart', 'tip', 'receipt', 'processing', 'thanks', 'screen']\n const asked = modes.includes(input['mode']) ? (input['mode'] as PosDisplayMode) : 'idle'\n const promptId = String(input['promptId'] ?? '').slice(0, 64)\n // A screen opens once per prompt, so one without a prompt, or one the\n // checker refuses, opens nothing.\n const screen = asked === 'screen' && promptId && options.screen ? options.screen(input['screen']) : null\n const mode: PosDisplayMode = asked === 'screen' && !screen ? 'idle' : asked\n const state: PosDisplayState = { mode, updatedAtMs: nowMs }\n if (promptId) state.promptId = promptId\n if (mode === 'screen' && screen) state.screen = screen\n const cart = input['cart']\n if (cart && typeof cart === 'object' && mode !== 'idle') {\n const lines = (Array.isArray(cart.lines) ? cart.lines : [])\n .slice(-POS_DISPLAY_MAX_LINES)\n .map((line: any) => ({\n name: String(line?.name ?? '').slice(0, 120),\n ...(line?.variantLabel\n ? { variantLabel: String(line.variantLabel).slice(0, 80) }\n : {}),\n quantity: Math.max(1, Math.min(999, Math.round(Number(line?.quantity) || 1))),\n amountCents: wholeCents(line?.amountCents),\n }))\n state.cart = {\n lines,\n itemsCents: wholeCents(cart.itemsCents),\n discountCents: wholeCents(cart.discountCents),\n taxCents: wholeCents(cart.taxCents),\n totalCents: wholeCents(cart.totalCents),\n ...(cart.paidCents != null ? { paidCents: wholeCents(cart.paidCents) } : {}),\n ...(cart.dueCents != null ? { dueCents: wholeCents(cart.dueCents) } : {}),\n ...(cart.tipCents != null ? { tipCents: wholeCents(cart.tipCents) } : {}),\n }\n }\n if (mode === 'tip') {\n const tip = input['tip'] ?? {}\n state.tip = {\n baseCents: wholeCents(tip.baseCents),\n percentages: posTipPercentages(\n Array.isArray(tip.percentages) ? tip.percentages.join(',') : tip.percentages,\n ),\n allowCustom: tip.allowCustom !== false,\n }\n }\n if (mode === 'receipt') {\n const receipt = input['receipt'] ?? {}\n const allowed: PosReceiptChannel[] = ['email', 'sms', 'print', 'none']\n const channels = (Array.isArray(receipt.channels) ? receipt.channels : [])\n .filter((channel: unknown): channel is PosReceiptChannel =>\n allowed.includes(channel as PosReceiptChannel),\n )\n state.receipt = {\n channels: channels.length ? [...new Set<PosReceiptChannel>(channels)] : ['print', 'none'],\n offerMarketing: receipt.offerMarketing === true,\n }\n }\n if (mode === 'processing') {\n state.processing = {\n message:\n String(input['processing']?.message ?? '').slice(0, 160) ||\n 'Tap, insert or swipe your card on the reader.',\n }\n }\n return state\n}\n\n/**\n * The customer's answer as the DISPLAY may send it, checked against the\n * prompt it claims to answer. Returns null when it answers nothing the\n * register asked: a stale screen, a replay, or a mode that takes no answer.\n */\nexport function sanitizePosDisplayResponse(\n state: PosDisplayState | null | undefined,\n raw: unknown,\n nowMs: number,\n): PosDisplayResponse | null {\n if (!state || !state.promptId) return null\n const input = (raw && typeof raw === 'object' ? raw : {}) as Record<string, any>\n if (String(input['promptId'] ?? '') !== state.promptId) return null\n const response: PosDisplayResponse = { promptId: state.promptId, atMs: nowMs }\n if (state.mode === 'tip' && state.tip) {\n const choice = input['tipChoice']\n if (choice === 'none') {\n response.tipChoice = 'none'\n response.tipCents = 0\n } else if (choice === 'percent') {\n const percent = Math.round(Number(input['tipPercent']))\n if (!state.tip.percentages.includes(percent)) return null\n response.tipChoice = 'percent'\n response.tipPercent = percent\n response.tipCents = posTipFromPercent(state.tip.baseCents, percent)\n } else if (choice === 'custom' && state.tip.allowCustom) {\n const tipCents = Math.round(Number(input['tipCents']))\n if (posTipProblem(tipCents, state.tip.baseCents)) return null\n response.tipChoice = 'custom'\n response.tipCents = tipCents\n } else {\n return null\n }\n return response\n }\n if (state.mode === 'receipt' && state.receipt) {\n const channel = input['receiptChannel'] as PosReceiptChannel\n if (!state.receipt.channels.includes(channel)) return null\n response.receiptChannel = channel\n if (channel === 'email') {\n const email = posDisplayEmail(input['email'])\n if (!email) return null\n response.email = email\n if (state.receipt.offerMarketing && input['marketingOptIn'] === true) {\n response.marketingOptIn = true\n }\n }\n if (channel === 'sms') {\n const phone = posDisplayPhone(input['phone'])\n if (!phone) return null\n response.phone = phone\n }\n return response\n }\n return null\n}\n\n/**\n * The state as the DISPLAY reads it. The customer's own typed address is\n * never echoed back to the screen: once answered, the prompt is done and the\n * screen shows what comes next, so nothing a later customer could read off\n * an unattended tablet is ever sent to it.\n */\nexport function posDisplayPublicState(\n state: PosDisplayState | null | undefined,\n nowMs: number,\n): Omit<PosDisplayState, 'response' | 'screenShownBy'> & { answered: boolean } {\n if (!state) return { mode: 'idle', updatedAtMs: nowMs, answered: false }\n // Who showed a plugin's screen is the server's to know, not the display's.\n const { response, screenShownBy: _shownBy, ...rest } = state\n if (rest.mode === 'thanks' && nowMs - rest.updatedAtMs > POS_DISPLAY_THANKS_MS) {\n return { mode: 'idle', updatedAtMs: rest.updatedAtMs, answered: false }\n }\n return {\n ...rest,\n answered: Boolean(response && response.promptId === rest.promptId),\n }\n}\n"],"names":["ORDER_PAYMENT_METHODS","POS_CARD_METHODS","Set","isCardPaymentMethod","method","has","POS_FEE_FREE_METHODS","paymentCarriesPlatformFee","posTenderTakeCents","takeFeeCents","wholeCents","value","number","Math","round","Number","isFinite","orderPayments","order","Array","isArray","payments","filter","payment","Boolean","id","totalCents","totals","amountCents","settled","status","atMs","createdAtMs","reservationId","checkoutSessionId","paymentIntentId","channel","posSettledCents","reduce","sum","posReservedCents","posBalanceDueCents","max","posTenderableCents","posTipCents","tipCents","posTakeShareCents","input","take","total","amount","min","posPaymentTakeShareCents","posOwedTakeCents","every","carryingCents","posInvoiceTakeCents","netted","posFeeCollection","card","some","other","describeOrderPayment","dollars","cents","toFixed","label","creditLabel","ORDER_PAYMENT_METHOD_LABELS","cardBrand","last4","join","tip","cash","card_present","card_keyed","card_link","gift_card","folio","credit","POS_TIP_PERCENTAGES_DEFAULT","posTipPercentages","raw","parsed","String","split","map","part","unique","slice","length","posTipFromPercent","baseCents","percent","base","pct","posTipProblem","isInteger","POS_DISPLAY_MAX_LINES","POS_DISPLAY_PAIRING_TTL_MS","POS_DISPLAY_THANKS_MS","EMAIL_PATTERN","posDisplayEmail","email","trim","toLowerCase","test","posDisplayPhone","digits","replace","startsWith","sanitizePosDisplayState","nowMs","options","modes","asked","includes","promptId","screen","mode","state","updatedAtMs","cart","lines","line","name","variantLabel","quantity","itemsCents","discountCents","taxCents","paidCents","dueCents","percentages","allowCustom","receipt","allowed","channels","offerMarketing","processing","message","sanitizePosDisplayResponse","response","choice","tipChoice","tipPercent","receiptChannel","marketingOptIn","phone","posDisplayPublicState","answered","screenShownBy","_shownBy","rest"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;2CAgB2C,GAE3C,sDAAsD;;AA6BtD,OAAO,MAAMA,wBAAuD;IAClE;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAyDD,kDAAkD,GAClD,OAAO,MAAMC,mBAAoD,IAAIC,IAAI;IACvE;IACA;IACA;CACD,EAAC;AAEF,OAAO,SAASC,oBAAoBC,MAA0B;IAC5D,OAAOH,iBAAiBI,GAAG,CAACD;AAC9B;AAEA;;;;;;;;;;;;;;;;;;;;;;2CAsB2C,GAE3C,uDAAuD,GACvD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Me,OAAO,CAACE,QAAQ,CAACrB,QAAQ,CAAChF,UAAU,OAAO;QACtD0G,SAASI,cAAc,GAAG9G;QAC1B,IAAIA,YAAY,SAAS;YACvB,MAAMmE,QAAQD,gBAAgBvD,KAAK,CAAC,QAAQ;YAC5C,IAAI,CAACwD,OAAO,OAAO;YACnBuC,SAASvC,KAAK,GAAGA;YACjB,IAAIiB,MAAMe,OAAO,CAACG,cAAc,IAAI3F,KAAK,CAAC,iBAAiB,KAAK,MAAM;gBACpE+F,SAASK,cAAc,GAAG;YAC5B;QACF;QACA,IAAI/G,YAAY,OAAO;YACrB,MAAMgH,QAAQzC,gBAAgB5D,KAAK,CAAC,QAAQ;YAC5C,IAAI,CAACqG,OAAO,OAAO;YACnBN,SAASM,KAAK,GAAGA;QACnB;QACA,OAAON;IACT;IACA,OAAO;AACT;AAEA;;;;;CAKC,GACD,OAAO,SAASO,sBACd7B,KAAyC,EACzCR,KAAa;IAEb,IAAI,CAACQ,OAAO,OAAO;QAAED,MAAM;QAAQE,aAAaT;QAAOsC,UAAU;IAAM;IACvE,2EAA2E;IAC3E,MAAM,EAAER,QAAQ,EAAES,eAAeC,QAAQ,EAAW,GAAGhC,OAATiC,wCAASjC;;;;IACvD,IAAIiC,KAAKlC,IAAI,KAAK,YAAYP,QAAQyC,KAAKhC,WAAW,GAAGrB,uBAAuB;QAC9E,OAAO;YAAEmB,MAAM;YAAQE,aAAagC,KAAKhC,WAAW;YAAE6B,UAAU;QAAM;IACxE;IACA,OAAO,aACFG;QACHH,UAAU9H,QAAQsH,YAAYA,SAASzB,QAAQ,KAAKoC,KAAKpC,QAAQ;;AAErE"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-pos.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * THE POS TENDER LEDGER (AGL-3607).\n *\n * A register sale used to be settled by exactly one tender and recorded none:\n * whether a POS order was paid in cash, by the QR link or to a room was\n * inferred afterwards from which other fields happened to be set. A sale now\n * carries `payments[]`, one entry per tender, and takes payments until the\n * balance due is zero. Only then is it `paid`.\n *\n * Every figure here is integer cents. `amountCents` is what a payment put\n * toward the SALE; a tip rides beside it in `tipCents` and never counts toward\n * the balance, the platform's take or the store's revenue. Tips belong to the\n * merchant and their staff.\n *\n * Pure and framework-free, so the register, the customer display and the\n * server read one answer.\n *=========================================*/\n\n/** How one payment toward a register sale was taken. */\nexport type OrderPaymentMethod =\n | 'cash'\n /** A Stripe Terminal smart reader (tap, insert or swipe). */\n | 'card_present'\n /** A card typed into the console by staff (card not present). */\n | 'card_keyed'\n /** The Stripe payment page the customer opens from a QR code. */\n | 'card_link'\n | 'gift_card'\n /** Charged to a checked-in reservation's folio. */\n | 'folio'\n /**\n * Store credit another plugin keeps — rewards, referral credit — taken\n * through core's checkout-credits seam (AGL-3640). Which plugin and which\n * account ride on the payment as `creditProviderId` and `creditReference`.\n */\n | 'credit'\n\nexport type OrderPaymentStatus =\n /** Started and not finished: reserves its amount against the balance. */\n | 'pending'\n | 'succeeded'\n /** Declined or errored; may be retried, reserves nothing. */\n | 'failed'\n | 'canceled'\n /** Taken and then handed back when the open sale was voided. */\n | 'reversed'\n\nexport const ORDER_PAYMENT_METHODS: readonly OrderPaymentMethod[] = [\n 'cash',\n 'card_present',\n 'card_keyed',\n 'card_link',\n 'gift_card',\n 'folio',\n 'credit',\n]\n\n/** One payment toward a register sale, on `HostOrder.payments`. */\nexport interface OrderPayment {\n /** Stable id, derived from the register's attempt key so a retry finds it. */\n id: string\n method: OrderPaymentMethod\n /** Cents put toward the sale. Never includes the tip. */\n amountCents: number\n /** Gratuity on top of `amountCents`, the merchant's and not revenue. */\n tipCents?: number\n status: OrderPaymentStatus\n /** When the payment was started. */\n atMs: number\n /** When it reached `succeeded`. */\n settledAtMs?: number\n /** Stripe PaymentIntent for `card_present` / `card_keyed` / a paid link. */\n paymentIntentId?: string\n /** Stripe Checkout Session for `card_link`. */\n checkoutSessionId?: string\n /** The payment page a `card_link` payment shows as a QR. */\n checkoutUrl?: string\n /** The Terminal reader a `card_present` payment runs on. */\n readerId?: string\n /** The gift card's code (its document id) for `gift_card`. */\n giftCardId?: string\n /** For `credit`: the provider that paid it (`{pluginId}.{key}`, AGL-3640). */\n creditProviderId?: string\n /** For `credit`: the provider's own handle on the account it came from. */\n creditReference?: string\n /** For `credit`: what the provider calls it, for the register and receipt. */\n creditLabel?: string\n cardBrand?: string\n last4?: string\n /** Cash handed over for a `cash` payment, and the change given back. */\n cashTenderedCents?: number\n changeCents?: number\n /** The stay a `folio` payment was charged to. */\n reservationId?: string\n /** The folio entry's `atMs`, so a void can remove exactly that entry. */\n folioAtMs?: number\n /**\n * The platform's take attributed to this payment (excludes the tip). For a\n * card payment it is netted from the payout with Stripe's processing cost\n * added, and recorded in `feeCents`; otherwise it accrues to the invoice.\n */\n takeFeeCents?: number\n /** The `application_fee_amount` a card payment carried, or 0. */\n feeCents?: number\n /** Why a `failed` payment failed, in words the cashier can read out. */\n failureMessage?: string\n /** Whether Stripe moved real money; absent for tenders Stripe never saw. */\n livemode?: boolean\n /**\n * `direct` when the card was charged ON the store's own Stripe account\n * (ToS v24 section 10.2(a)), with that account in `stripeAccountId`: its\n * capture, cancel and refund are made there. Absent for a destination\n * charge on the platform, every register payment before the switch.\n */\n chargeModel?: 'direct'\n stripeAccountId?: string\n /** The console user who took the payment. */\n cashierId?: string\n}\n\n/** The tenders whose money moves through Stripe. */\nexport const POS_CARD_METHODS: ReadonlySet<OrderPaymentMethod> = new Set([\n 'card_present',\n 'card_keyed',\n 'card_link',\n])\n\nexport function isCardPaymentMethod(method: OrderPaymentMethod): boolean {\n return POS_CARD_METHODS.has(method)\n}\n\n/*==========================================\n * WHICH TENDERS CARRY THE PLATFORM FEE (AGL-4036).\n *\n * The take used to follow the sale whatever paid it (AGL-2111): a cash sale\n * owed the same percentage as a card sale and had it added to the monthly\n * invoice. In-person rivals charge nothing on cash, and an event register that\n * bills its operator for the cash in their own apron is not one they will\n * choose, so three tenders now carry none:\n *\n * - cash: no payment service touches it, and the merchant keeps all of it;\n * - gift card: the fee was taken when the card was SOLD, so charging it again\n * when the card is spent would charge the same money twice;\n * - store credit (`credit`): rewards or referral value the merchant gave\n * away, so no money changes hands and an invoiced fee on it would only\n * penalize running a rewards program.\n *\n * Everything else still carries it. Card payments net it from their payout,\n * as always. A room charge (`folio`) is new revenue booked to a stay, so its\n * share goes on the invoice.\n *\n * One predicate, so the register, the completion, the offline sync and the\n * docs cannot disagree about which tender is which.\n *=========================================*/\n\n/** The tenders that carry no platform fee (AGL-4036). */\nexport const POS_FEE_FREE_METHODS: ReadonlySet<OrderPaymentMethod> = new Set([\n 'cash',\n 'gift_card',\n 'credit',\n])\n\n/** Whether a payment by `method` carries its share of the platform's take. */\nexport function paymentCarriesPlatformFee(method: OrderPaymentMethod): boolean {\n return !POS_FEE_FREE_METHODS.has(method)\n}\n\n/**\n * The take a sale owes when ONE tender pays all of it: the whole take, or\n * nothing for a fee-free tender.\n */\nexport function posTenderTakeCents(\n method: OrderPaymentMethod,\n takeFeeCents: number,\n): number {\n return paymentCarriesPlatformFee(method) ? wholeCents(takeFeeCents) : 0\n}\n\n/** Whole non-negative cents from an untrusted value. */\nfunction wholeCents(value: unknown): number {\n const number = Math.round(Number(value))\n return Number.isFinite(number) && number > 0 ? number : 0\n}\n\n/**\n * The order's payments, read through one door.\n *\n * Orders written before the ledger existed carry no `payments`, so one is\n * INFERRED from the fields the single-tender register wrote: a folio sale has\n * `reservationId`, a QR sale has `checkoutSessionId`, and anything else on the\n * POS channel was cash. A pending legacy sale is the QR link still waiting.\n * Online orders paid through Stripe Checkout read as one `card_link` payment.\n * Nothing is written back: this is a reader, never a migration.\n */\nexport function orderPayments(order: {\n payments?: OrderPayment[] | null\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 createdAtMs?: number\n}): OrderPayment[] {\n if (Array.isArray(order?.payments)) {\n return order.payments.filter(\n (payment): payment is OrderPayment =>\n Boolean(payment) && typeof payment === 'object' && Boolean(payment.id),\n )\n }\n const totalCents = wholeCents(order?.totals?.totalCents ?? order?.amountCents)\n if (!(totalCents > 0)) return []\n const settled = order?.status !== 'pending' && order?.status !== 'cancelled'\n const atMs = Number(order?.createdAtMs) || 0\n const method: OrderPaymentMethod = order?.reservationId\n ? 'folio'\n : order?.checkoutSessionId || order?.paymentIntentId || order?.channel !== 'pos'\n ? 'card_link'\n : 'cash'\n return [\n {\n id: 'legacy',\n method,\n amountCents: totalCents,\n status: settled ? 'succeeded' : order?.status === 'cancelled' ? 'canceled' : 'pending',\n atMs,\n ...(order?.paymentIntentId ? { paymentIntentId: order.paymentIntentId } : {}),\n ...(order?.checkoutSessionId ? { checkoutSessionId: order.checkoutSessionId } : {}),\n ...(order?.reservationId ? { reservationId: order.reservationId } : {}),\n },\n ]\n}\n\n/** Cents put toward the sale by payments that succeeded. */\nexport function posSettledCents(payments: readonly OrderPayment[]): number {\n return payments\n .filter((payment) => payment.status === 'succeeded')\n .reduce((sum, payment) => sum + wholeCents(payment.amountCents), 0)\n}\n\n/**\n * Cents spoken for: succeeded payments plus the ones still in flight. A\n * reader waiting for a tap has claimed its share of the balance, so a second\n * tender cannot be started for the same money.\n */\nexport function posReservedCents(payments: readonly OrderPayment[]): number {\n return payments\n .filter((payment) => payment.status === 'succeeded' || payment.status === 'pending')\n .reduce((sum, payment) => sum + wholeCents(payment.amountCents), 0)\n}\n\n/** What the customer still owes, by settled payments. */\nexport function posBalanceDueCents(\n totalCents: number,\n payments: readonly OrderPayment[],\n): number {\n return Math.max(0, wholeCents(totalCents) - posSettledCents(payments))\n}\n\n/** What a NEW payment may still take: the balance less what is in flight. */\nexport function posTenderableCents(\n totalCents: number,\n payments: readonly OrderPayment[],\n): number {\n return Math.max(0, wholeCents(totalCents) - posReservedCents(payments))\n}\n\n/** Tips taken across the sale's settled payments. */\nexport function posTipCents(payments: readonly OrderPayment[]): number {\n return payments\n .filter((payment) => payment.status === 'succeeded')\n .reduce((sum, payment) => sum + wholeCents(payment.tipCents), 0)\n}\n\n/**\n * The share of the sale's take a payment of `amountCents` carries.\n *\n * Proportional to the part of the SALE it pays, never to the tip. Card\n * payments carry their share in `application_fee_amount`; whatever the card\n * shares leave is accrued to the invoice at completion\n * ({@link posInvoiceTakeCents}), so the take is exact however the sale was\n * split and however each share rounded.\n */\nexport function posTakeShareCents(input: {\n takeFeeCents: number\n totalCents: number\n amountCents: number\n}): number {\n const take = wholeCents(input.takeFeeCents)\n const total = wholeCents(input.totalCents)\n const amount = Math.min(wholeCents(input.amountCents), total)\n if (!(take > 0) || !(total > 0) || !(amount > 0)) return 0\n return Math.min(take, Math.round((take * amount) / total))\n}\n\n/**\n * {@link posTakeShareCents} for a payment by `method`: its share of the take,\n * or 0 for a tender that carries no platform fee (AGL-4036).\n */\nexport function posPaymentTakeShareCents(input: {\n method: OrderPaymentMethod\n takeFeeCents: number\n totalCents: number\n amountCents: number\n}): number {\n if (!paymentCarriesPlatformFee(input.method)) return 0\n return posTakeShareCents(input)\n}\n\n/**\n * The part of the sale's take its tenders owe (AGL-4036): the whole take when\n * every settled payment carries the fee, and otherwise the share for the part\n * of the sale the fee-carrying payments paid. Cash and gift-card parts owe\n * nothing, so a sale paid all in cash owes 0.\n *\n * Worked from the payments' METHODS, not from the `takeFeeCents` each one\n * recorded, so a sale that was opened before this rule and finished after it\n * is charged by the rule it finished under.\n */\nexport function posOwedTakeCents(input: {\n takeFeeCents: number\n totalCents: number\n payments: readonly OrderPayment[]\n}): number {\n const take = wholeCents(input.takeFeeCents)\n const settled = input.payments.filter((payment) => payment.status === 'succeeded')\n if (settled.every((payment) => paymentCarriesPlatformFee(payment.method))) return take\n const carryingCents = settled\n .filter((payment) => paymentCarriesPlatformFee(payment.method))\n .reduce((sum, payment) => sum + wholeCents(payment.amountCents), 0)\n return posTakeShareCents({\n takeFeeCents: take,\n totalCents: input.totalCents,\n amountCents: carryingCents,\n })\n}\n\n/**\n * What of the sale's take was NOT netted from a card payout, and therefore\n * goes on the merchant's invoice: the take the tenders owe\n * ({@link posOwedTakeCents}) less every succeeded card payment's share. Never\n * negative, and 0 for a sale paid only by card, cash, gift card and store credit.\n */\nexport function posInvoiceTakeCents(input: {\n takeFeeCents: number\n totalCents: number\n payments: readonly OrderPayment[]\n}): number {\n const netted = input.payments\n .filter(\n (payment) =>\n payment.status === 'succeeded' && isCardPaymentMethod(payment.method),\n )\n .reduce((sum, payment) => sum + wholeCents(payment.takeFeeCents), 0)\n return Math.max(0, posOwedTakeCents(input) - netted)\n}\n\n/**\n * How the sale's fee reaches the platform, from the payments that carried it.\n * A cash, gift-card or store-credit part carries none (AGL-4036), so a card + cash sale is\n * `payout`, not `split`.\n */\nexport function posFeeCollection(\n payments: readonly OrderPayment[],\n): 'payout' | 'invoice' | 'split' {\n const settled = payments.filter(\n (payment) =>\n payment.status === 'succeeded' && paymentCarriesPlatformFee(payment.method),\n )\n const card = settled.some((payment) => isCardPaymentMethod(payment.method))\n const other = settled.some((payment) => !isCardPaymentMethod(payment.method))\n if (card && other) return 'split'\n return card ? 'payout' : 'invoice'\n}\n\n/** A one-line description of a payment for the register, receipt and timeline. */\nexport function describeOrderPayment(payment: OrderPayment): string {\n const dollars = (cents: number) => `$${(cents / 100).toFixed(2)}`\n const label =\n (payment.method === 'credit' && payment.creditLabel) || ORDER_PAYMENT_METHOD_LABELS[payment.method] || 'Payment'\n const card =\n payment.cardBrand || payment.last4\n ? ` (${[payment.cardBrand, payment.last4 ? `•••• ${payment.last4}` : '']\n .filter(Boolean)\n .join(' ')})`\n : ''\n const tip = wholeCents(payment.tipCents)\n ? ` + ${dollars(wholeCents(payment.tipCents))} tip`\n : ''\n return `${label}${card} ${dollars(wholeCents(payment.amountCents))}${tip}`\n}\n\nexport const ORDER_PAYMENT_METHOD_LABELS: Record<OrderPaymentMethod, string> = {\n cash: 'Cash',\n card_present: 'Card reader',\n card_keyed: 'Typed card',\n card_link: 'Card (QR)',\n gift_card: 'Gift card',\n folio: 'Charged to room',\n credit: 'Store credit',\n}\n\n/*==========================================\n * TIPS (AGL-3607).\n *=========================================*/\n\n/** The presets a merchant starts with. */\nexport const POS_TIP_PERCENTAGES_DEFAULT: readonly number[] = [15, 18, 20, 25]\n\n/**\n * The merchant's tip presets from the plugin setting, a comma list such as\n * `15, 18, 20, 25`. Whole percentages from 1 to 100, at most four, in the order\n * given; anything unreadable falls back to the defaults rather than showing\n * the customer an empty choice.\n */\nexport function posTipPercentages(raw: unknown): number[] {\n const parsed = String(raw ?? '')\n .split(/[,\\s]+/)\n .map((part) => Math.round(Number(part)))\n .filter((value) => Number.isFinite(value) && value >= 1 && value <= 100)\n const unique = [...new Set(parsed)].slice(0, 4)\n return unique.length ? unique : [...POS_TIP_PERCENTAGES_DEFAULT]\n}\n\n/** A percentage tip on `baseCents`, rounded to the cent. */\nexport function posTipFromPercent(baseCents: number, percent: number): number {\n const base = wholeCents(baseCents)\n const pct = Number(percent)\n if (!(base > 0) || !Number.isFinite(pct) || pct <= 0) return 0\n return Math.round((base * pct) / 100)\n}\n\n/** The largest tip the register accepts on one payment: the payment itself. */\nexport function posTipProblem(tipCents: number, amountCents: number): string | null {\n if (!Number.isInteger(tipCents) || tipCents < 0) return 'Enter a tip of $0 or more.'\n if (tipCents > wholeCents(amountCents)) {\n return 'A tip can be at most the amount being paid. Check the amount and try again.'\n }\n return null\n}\n\n/*==========================================\n * THE CUSTOMER DISPLAY (AGL-3608).\n *\n * A paired screen facing the customer reads one document per register,\n * `hosts/{hostId}/registers/{registerId}/display/state`, through the\n * `commerce/pos-display` route and its display token. The register writes\n * the prompt; the customer's answer comes back in `response`.\n *=========================================*/\n\nexport type PosDisplayMode =\n | 'idle'\n /** The live basket, mirrored as the cashier builds it. */\n | 'cart'\n /** The customer picks a tip. */\n | 'tip'\n /** The customer picks how they want their receipt. */\n | 'receipt'\n /** A card payment is waiting on the reader. */\n | 'processing'\n | 'thanks'\n /**\n * Another plugin's screen (AGL-4042), asked for through core's customer\n * display seam (`plugin-customer-display`): the display opens that\n * plugin's public page, which sends it back here when the customer is done.\n */\n | 'screen'\n\nexport type PosReceiptChannel = 'email' | 'sms' | 'print' | 'none'\n\nexport interface PosDisplayLine {\n name: string\n variantLabel?: string\n quantity: number\n amountCents: number\n}\n\nexport interface PosDisplayCart {\n lines: PosDisplayLine[]\n itemsCents: number\n discountCents: number\n taxCents: number\n totalCents: number\n /** Taken so far, and what is still due, once payments start. */\n paidCents?: number\n dueCents?: number\n tipCents?: number\n}\n\n/** The customer's answer to the current prompt. */\nexport interface PosDisplayResponse {\n /** The prompt this answers; a stale answer is refused. */\n promptId: string\n tipCents?: number\n tipPercent?: number\n /** `none` when the customer chose no tip. */\n tipChoice?: 'percent' | 'custom' | 'none'\n receiptChannel?: PosReceiptChannel\n email?: string\n phone?: string\n marketingOptIn?: boolean\n atMs: number\n}\n\nexport interface PosDisplayState {\n mode: PosDisplayMode\n updatedAtMs: number\n /**\n * The ISO currency every amount on the screen is in (`usd`). Stamped by\n * the server from the store's own currency, never taken from the register.\n */\n currency?: string\n /** Changes every time the register asks something new. */\n promptId?: string\n cart?: PosDisplayCart\n tip?: {\n /** What a percentage is taken of: the amount being paid now. */\n baseCents: number\n percentages: number[]\n allowCustom: boolean\n }\n receipt?: {\n channels: PosReceiptChannel[]\n /** Whether to offer the store's marketing opt-in under the email field. */\n offerMarketing: boolean\n }\n processing?: { message: string }\n /** The plugin page a `screen` state opens, as core's seam shapes it. */\n screen?: PosDisplayScreen\n /**\n * The staff member (uid) who put {@link screen} on the display (AGL-4042),\n * stamped by the server from the session that pushed it, never taken from\n * the register's body. Core's display verifier names them to the screen's\n * plugin, whose record of what the customer did there names who showed it.\n * Never sent to the display.\n */\n screenShownBy?: string\n response?: PosDisplayResponse\n}\n\n/**\n * A plugin's screen on the display (AGL-4042): the shape of core's\n * `CustomerDisplayScreen`, restated so this module imports nothing. The\n * server checks it with core's own sanitizer before it is stored.\n */\nexport interface PosDisplayScreen {\n pluginId: string\n path: string\n params: Record<string, string>\n}\n\n/** Most lines a display state carries; a longer basket shows its newest. */\nexport const POS_DISPLAY_MAX_LINES = 60\n\n/** A pairing code lives this long before the register must show a new one. */\nexport const POS_DISPLAY_PAIRING_TTL_MS = 10 * 60 * 1000\n\n/** A thank-you screen returns to idle on the display after this long. */\nexport const POS_DISPLAY_THANKS_MS = 8_000\n\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/** An email address as the display may store it, or '' when it is not one. */\nexport function posDisplayEmail(value: unknown): string {\n const email = String(value ?? '').trim().toLowerCase().slice(0, 254)\n return EMAIL_PATTERN.test(email) ? email : ''\n}\n\n/** A phone number as digits with an optional leading +, or '' when too short. */\nexport function posDisplayPhone(value: unknown): string {\n const raw = String(value ?? '').trim()\n const digits = raw.replace(/[^0-9]/g, '')\n if (digits.length < 7 || digits.length > 15) return ''\n return `${raw.startsWith('+') ? '+' : ''}${digits}`\n}\n\n/**\n * The display state as the REGISTER may send it: clamped, typed and stripped\n * of anything the customer screen has no business holding. The register is\n * staff and trusted for intent, not for shape.\n */\nexport function sanitizePosDisplayState(\n raw: unknown,\n nowMs: number,\n options: {\n /**\n * Checks a `screen` state's plugin page (core's\n * `sanitizeCustomerDisplayScreen`). Without it, or when it refuses, a\n * `screen` state is idle: nothing opens on the display unchecked.\n */\n screen?: (raw: unknown) => PosDisplayScreen | null\n } = {},\n): PosDisplayState {\n const input = (raw && typeof raw === 'object' ? raw : {}) as Record<string, any>\n const modes: PosDisplayMode[] = ['idle', 'cart', 'tip', 'receipt', 'processing', 'thanks', 'screen']\n const asked = modes.includes(input['mode']) ? (input['mode'] as PosDisplayMode) : 'idle'\n const promptId = String(input['promptId'] ?? '').slice(0, 64)\n // A screen opens once per prompt, so one without a prompt, or one the\n // checker refuses, opens nothing.\n const screen = asked === 'screen' && promptId && options.screen ? options.screen(input['screen']) : null\n const mode: PosDisplayMode = asked === 'screen' && !screen ? 'idle' : asked\n const state: PosDisplayState = { mode, updatedAtMs: nowMs }\n if (promptId) state.promptId = promptId\n if (mode === 'screen' && screen) state.screen = screen\n const cart = input['cart']\n if (cart && typeof cart === 'object' && mode !== 'idle') {\n const lines = (Array.isArray(cart.lines) ? cart.lines : [])\n .slice(-POS_DISPLAY_MAX_LINES)\n .map((line: any) => ({\n name: String(line?.name ?? '').slice(0, 120),\n ...(line?.variantLabel\n ? { variantLabel: String(line.variantLabel).slice(0, 80) }\n : {}),\n quantity: Math.max(1, Math.min(999, Math.round(Number(line?.quantity) || 1))),\n amountCents: wholeCents(line?.amountCents),\n }))\n state.cart = {\n lines,\n itemsCents: wholeCents(cart.itemsCents),\n discountCents: wholeCents(cart.discountCents),\n taxCents: wholeCents(cart.taxCents),\n totalCents: wholeCents(cart.totalCents),\n ...(cart.paidCents != null ? { paidCents: wholeCents(cart.paidCents) } : {}),\n ...(cart.dueCents != null ? { dueCents: wholeCents(cart.dueCents) } : {}),\n ...(cart.tipCents != null ? { tipCents: wholeCents(cart.tipCents) } : {}),\n }\n }\n if (mode === 'tip') {\n const tip = input['tip'] ?? {}\n state.tip = {\n baseCents: wholeCents(tip.baseCents),\n percentages: posTipPercentages(\n Array.isArray(tip.percentages) ? tip.percentages.join(',') : tip.percentages,\n ),\n allowCustom: tip.allowCustom !== false,\n }\n }\n if (mode === 'receipt') {\n const receipt = input['receipt'] ?? {}\n const allowed: PosReceiptChannel[] = ['email', 'sms', 'print', 'none']\n const channels = (Array.isArray(receipt.channels) ? receipt.channels : [])\n .filter((channel: unknown): channel is PosReceiptChannel =>\n allowed.includes(channel as PosReceiptChannel),\n )\n state.receipt = {\n channels: channels.length ? [...new Set<PosReceiptChannel>(channels)] : ['print', 'none'],\n offerMarketing: receipt.offerMarketing === true,\n }\n }\n if (mode === 'processing') {\n state.processing = {\n message:\n String(input['processing']?.message ?? '').slice(0, 160) ||\n 'Tap, insert or swipe your card on the reader.',\n }\n }\n return state\n}\n\n/**\n * The customer's answer as the DISPLAY may send it, checked against the\n * prompt it claims to answer. Returns null when it answers nothing the\n * register asked: a stale screen, a replay, or a mode that takes no answer.\n */\nexport function sanitizePosDisplayResponse(\n state: PosDisplayState | null | undefined,\n raw: unknown,\n nowMs: number,\n): PosDisplayResponse | null {\n if (!state || !state.promptId) return null\n const input = (raw && typeof raw === 'object' ? raw : {}) as Record<string, any>\n if (String(input['promptId'] ?? '') !== state.promptId) return null\n const response: PosDisplayResponse = { promptId: state.promptId, atMs: nowMs }\n if (state.mode === 'tip' && state.tip) {\n const choice = input['tipChoice']\n if (choice === 'none') {\n response.tipChoice = 'none'\n response.tipCents = 0\n } else if (choice === 'percent') {\n const percent = Math.round(Number(input['tipPercent']))\n if (!state.tip.percentages.includes(percent)) return null\n response.tipChoice = 'percent'\n response.tipPercent = percent\n response.tipCents = posTipFromPercent(state.tip.baseCents, percent)\n } else if (choice === 'custom' && state.tip.allowCustom) {\n const tipCents = Math.round(Number(input['tipCents']))\n if (posTipProblem(tipCents, state.tip.baseCents)) return null\n response.tipChoice = 'custom'\n response.tipCents = tipCents\n } else {\n return null\n }\n return response\n }\n if (state.mode === 'receipt' && state.receipt) {\n const channel = input['receiptChannel'] as PosReceiptChannel\n if (!state.receipt.channels.includes(channel)) return null\n response.receiptChannel = channel\n if (channel === 'email') {\n const email = posDisplayEmail(input['email'])\n if (!email) return null\n response.email = email\n if (state.receipt.offerMarketing && input['marketingOptIn'] === true) {\n response.marketingOptIn = true\n }\n }\n if (channel === 'sms') {\n const phone = posDisplayPhone(input['phone'])\n if (!phone) return null\n response.phone = phone\n }\n return response\n }\n return null\n}\n\n/**\n * The state as the DISPLAY reads it. The customer's own typed address is\n * never echoed back to the screen: once answered, the prompt is done and the\n * screen shows what comes next, so nothing a later customer could read off\n * an unattended tablet is ever sent to it.\n */\nexport function posDisplayPublicState(\n state: PosDisplayState | null | undefined,\n nowMs: number,\n): Omit<PosDisplayState, 'response' | 'screenShownBy'> & { answered: boolean } {\n if (!state) return { mode: 'idle', updatedAtMs: nowMs, answered: false }\n // Who showed a plugin's screen is the server's to know, not the display's.\n const { response, screenShownBy: _shownBy, ...rest } = state\n if (rest.mode === 'thanks' && nowMs - rest.updatedAtMs > POS_DISPLAY_THANKS_MS) {\n return { mode: 'idle', updatedAtMs: rest.updatedAtMs, answered: false }\n }\n return {\n ...rest,\n answered: Boolean(response && response.promptId === rest.promptId),\n }\n}\n"],"names":["ORDER_PAYMENT_METHODS","POS_CARD_METHODS","Set","isCardPaymentMethod","method","has","POS_FEE_FREE_METHODS","paymentCarriesPlatformFee","posTenderTakeCents","takeFeeCents","wholeCents","value","number","Math","round","Number","isFinite","orderPayments","order","Array","isArray","payments","filter","payment","Boolean","id","totalCents","totals","amountCents","settled","status","atMs","createdAtMs","reservationId","checkoutSessionId","paymentIntentId","channel","posSettledCents","reduce","sum","posReservedCents","posBalanceDueCents","max","posTenderableCents","posTipCents","tipCents","posTakeShareCents","input","take","total","amount","min","posPaymentTakeShareCents","posOwedTakeCents","every","carryingCents","posInvoiceTakeCents","netted","posFeeCollection","card","some","other","describeOrderPayment","dollars","cents","toFixed","label","creditLabel","ORDER_PAYMENT_METHOD_LABELS","cardBrand","last4","join","tip","cash","card_present","card_keyed","card_link","gift_card","folio","credit","POS_TIP_PERCENTAGES_DEFAULT","posTipPercentages","raw","parsed","String","split","map","part","unique","slice","length","posTipFromPercent","baseCents","percent","base","pct","posTipProblem","isInteger","POS_DISPLAY_MAX_LINES","POS_DISPLAY_PAIRING_TTL_MS","POS_DISPLAY_THANKS_MS","EMAIL_PATTERN","posDisplayEmail","email","trim","toLowerCase","test","posDisplayPhone","digits","replace","startsWith","sanitizePosDisplayState","nowMs","options","modes","asked","includes","promptId","screen","mode","state","updatedAtMs","cart","lines","line","name","variantLabel","quantity","itemsCents","discountCents","taxCents","paidCents","dueCents","percentages","allowCustom","receipt","allowed","channels","offerMarketing","processing","message","sanitizePosDisplayResponse","response","choice","tipChoice","tipPercent","receiptChannel","marketingOptIn","phone","posDisplayPublicState","answered","screenShownBy","_shownBy","rest"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;2CAgB2C,GAE3C,sDAAsD;;AA6BtD,OAAO,MAAMA,wBAAuD;IAClE;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAiED,kDAAkD,GAClD,OAAO,MAAMC,mBAAoD,IAAIC,IAAI;IACvE;IACA;IACA;CACD,EAAC;AAEF,OAAO,SAASC,oBAAoBC,MAA0B;IAC5D,OAAOH,iBAAiBI,GAAG,CAACD;AAC9B;AAEA;;;;;;;;;;;;;;;;;;;;;;2CAsB2C,GAE3C,uDAAuD,GACvD,OAAO,MAAME,uBAAwD,IAAIJ,IAAI;IAC3E;IACA;IACA;CACD,EAAC;AAEF,4EAA4E,GAC5E,OAAO,SAASK,0BAA0BH,MAA0B;IAClE,OAAO,CAACE,qBAAqBD,GAAG,CAACD;AACnC;AAEA;;;CAGC,GACD,OAAO,SAASI,mBACdJ,MAA0B,EAC1BK,YAAoB;IAEpB,OAAOF,0BAA0BH,UAAUM,WAAWD,gBAAgB;AACxE;AAEA,sDAAsD,GACtD,SAASC,WAAWC,KAAc;IAChC,MAAMC,SAASC,KAAKC,KAAK,CAACC,OAAOJ;IACjC,OAAOI,OAAOC,QAAQ,CAACJ,WAAWA,SAAS,IAAIA,SAAS;AAC1D;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASK,cAAcC,KAU7B;;QAO+BA;IAN9B,IAAIC,MAAMC,OAAO,CAACF,yBAAAA,MAAOG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