@aglyn/plugins-commerce 1.14.0 → 1.15.1

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 (214) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/account-subscriptions.d.ts +51 -0
  3. package/src/lib/components/account-subscriptions.js +168 -0
  4. package/src/lib/components/account-subscriptions.js.map +1 -0
  5. package/src/lib/components/account.js +12 -48
  6. package/src/lib/components/account.js.map +1 -1
  7. package/src/lib/components/cart.js +38 -9
  8. package/src/lib/components/cart.js.map +1 -1
  9. package/src/lib/components/commerce-console-page.js +6 -0
  10. package/src/lib/components/commerce-console-page.js.map +1 -1
  11. package/src/lib/components/commerce-console-sections.d.ts +1 -1
  12. package/src/lib/components/commerce-console-sections.js +5 -0
  13. package/src/lib/components/commerce-console-sections.js.map +1 -1
  14. package/src/lib/components/console/paid-media.d.ts +1 -0
  15. package/src/lib/components/console/paid-media.js +15 -4
  16. package/src/lib/components/console/paid-media.js.map +1 -1
  17. package/src/lib/components/console/payments-settings-card.component.js +1 -1
  18. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  19. package/src/lib/components/console/pos/pos-hardware-api.d.ts +10 -1
  20. package/src/lib/components/console/pos/pos-hardware-api.js.map +1 -1
  21. package/src/lib/components/console/pos/pos-hardware-buyer.component.js +2 -2
  22. package/src/lib/components/console/pos/pos-hardware-buyer.component.js.map +1 -1
  23. package/src/lib/components/console/pos/pos-hardware-sale-api.d.ts +2 -0
  24. package/src/lib/components/console/pos/pos-hardware-sale-api.js.map +1 -1
  25. package/src/lib/components/console/pos-cellular-control.component.d.ts +1 -1
  26. package/src/lib/components/console/pos-cellular-control.component.js +5 -5
  27. package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
  28. package/src/lib/components/console/pos-devices-card.component.js +2 -2
  29. package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
  30. package/src/lib/components/console/pos-hardware-card.component.d.ts +5 -0
  31. package/src/lib/components/console/pos-hardware-card.component.js +77 -8
  32. package/src/lib/components/console/pos-hardware-card.component.js.map +1 -1
  33. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js +137 -19
  34. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js.map +1 -1
  35. package/src/lib/components/console/pos-page.component.js +19 -2
  36. package/src/lib/components/console/pos-page.component.js.map +1 -1
  37. package/src/lib/components/console/product-editor-dialog.component.js +21 -2
  38. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  39. package/src/lib/components/console/subscription-detail-dialog.component.d.ts +58 -0
  40. package/src/lib/components/console/subscription-detail-dialog.component.js +201 -0
  41. package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -0
  42. package/src/lib/components/console/subscriptions-card.component.d.ts +60 -0
  43. package/src/lib/components/console/subscriptions-card.component.js +282 -0
  44. package/src/lib/components/console/subscriptions-card.component.js.map +1 -0
  45. package/src/lib/components/hardware-terms-consent.d.ts +22 -0
  46. package/src/lib/components/hardware-terms-consent.js +85 -0
  47. package/src/lib/components/hardware-terms-consent.js.map +1 -0
  48. package/src/lib/components/product-detail.js +32 -8
  49. package/src/lib/components/product-detail.js.map +1 -1
  50. package/src/lib/components/quote-page-body.js +7 -3
  51. package/src/lib/components/quote-page-body.js.map +1 -1
  52. package/src/lib/components/related-products.js +6 -3
  53. package/src/lib/components/related-products.js.map +1 -1
  54. package/src/lib/components/storefront-payment-element.d.ts +7 -1
  55. package/src/lib/components/storefront-payment-element.js +11 -7
  56. package/src/lib/components/storefront-payment-element.js.map +1 -1
  57. package/src/lib/constants/operator-alerts.d.ts +1 -1
  58. package/src/lib/constants/operator-alerts.js +4 -4
  59. package/src/lib/constants/operator-alerts.js.map +1 -1
  60. package/src/lib/model/commerce-orders.d.ts +6 -2
  61. package/src/lib/model/commerce-orders.js.map +1 -1
  62. package/src/lib/model/commerce-payment-methods.d.ts +27 -16
  63. package/src/lib/model/commerce-payment-methods.js +11 -83
  64. package/src/lib/model/commerce-payment-methods.js.map +1 -1
  65. package/src/lib/model/commerce.d.ts +6 -0
  66. package/src/lib/model/commerce.js.map +1 -1
  67. package/src/lib/model/index.d.ts +1 -0
  68. package/src/lib/model/index.js +1 -0
  69. package/src/lib/model/index.js.map +1 -1
  70. package/src/lib/model/paid-media.d.ts +8 -0
  71. package/src/lib/model/paid-media.js +13 -0
  72. package/src/lib/model/paid-media.js.map +1 -1
  73. package/src/lib/model/pos-hardware-in-person.d.ts +23 -2
  74. package/src/lib/model/pos-hardware-in-person.js +52 -20
  75. package/src/lib/model/pos-hardware-in-person.js.map +1 -1
  76. package/src/lib/model/pos-hardware-tax-summary.d.ts +5 -1
  77. package/src/lib/model/pos-hardware-tax-summary.js +2 -1
  78. package/src/lib/model/pos-hardware-tax-summary.js.map +1 -1
  79. package/src/lib/model/pos-hardware-terms.d.ts +37 -2
  80. package/src/lib/model/pos-hardware-terms.js +68 -3
  81. package/src/lib/model/pos-hardware-terms.js.map +1 -1
  82. package/src/lib/model/pos-hardware.d.ts +101 -15
  83. package/src/lib/model/pos-hardware.js +128 -18
  84. package/src/lib/model/pos-hardware.js.map +1 -1
  85. package/src/lib/model/pos-reader-splash.js +2 -2
  86. package/src/lib/model/pos-reader-splash.js.map +1 -1
  87. package/src/lib/model/product-write.d.ts +3 -0
  88. package/src/lib/model/subscription-view.d.ts +90 -0
  89. package/src/lib/model/subscription-view.js +176 -0
  90. package/src/lib/model/subscription-view.js.map +1 -0
  91. package/src/lib/server/billing-webhook.d.ts +27 -6
  92. package/src/lib/server/billing-webhook.js +271 -81
  93. package/src/lib/server/billing-webhook.js.map +1 -1
  94. package/src/lib/server/cancel-order.js +4 -3
  95. package/src/lib/server/cancel-order.js.map +1 -1
  96. package/src/lib/server/cart-checkout.js +105 -23
  97. package/src/lib/server/cart-checkout.js.map +1 -1
  98. package/src/lib/server/cart.js +15 -3
  99. package/src/lib/server/cart.js.map +1 -1
  100. package/src/lib/server/catalog.js +58 -22
  101. package/src/lib/server/catalog.js.map +1 -1
  102. package/src/lib/server/checkout-session-expiry.d.ts +1 -1
  103. package/src/lib/server/checkout-session-expiry.js +19 -5
  104. package/src/lib/server/checkout-session-expiry.js.map +1 -1
  105. package/src/lib/server/checkout-status.js +4 -3
  106. package/src/lib/server/checkout-status.js.map +1 -1
  107. package/src/lib/server/checkout.js +98 -26
  108. package/src/lib/server/checkout.js.map +1 -1
  109. package/src/lib/server/connect.js +42 -11
  110. package/src/lib/server/connect.js.map +1 -1
  111. package/src/lib/server/draft-order.js +36 -7
  112. package/src/lib/server/draft-order.js.map +1 -1
  113. package/src/lib/server/manual-tax-rate.d.ts +11 -3
  114. package/src/lib/server/manual-tax-rate.js +10 -6
  115. package/src/lib/server/manual-tax-rate.js.map +1 -1
  116. package/src/lib/server/membership-account.d.ts +22 -0
  117. package/src/lib/server/membership-account.js +52 -8
  118. package/src/lib/server/membership-account.js.map +1 -1
  119. package/src/lib/server/native-checkout.d.ts +10 -3
  120. package/src/lib/server/native-checkout.js +8 -3
  121. package/src/lib/server/native-checkout.js.map +1 -1
  122. package/src/lib/server/payment-method-domains.d.ts +50 -9
  123. package/src/lib/server/payment-method-domains.js +150 -51
  124. package/src/lib/server/payment-method-domains.js.map +1 -1
  125. package/src/lib/server/payment-methods.js +3 -2
  126. package/src/lib/server/payment-methods.js.map +1 -1
  127. package/src/lib/server/pos-auth.d.ts +3 -3
  128. package/src/lib/server/pos-auth.js +3 -3
  129. package/src/lib/server/pos-auth.js.map +1 -1
  130. package/src/lib/server/pos-cellular-billing.js +1 -1
  131. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  132. package/src/lib/server/pos-cellular-notify.js +1 -1
  133. package/src/lib/server/pos-cellular-notify.js.map +1 -1
  134. package/src/lib/server/pos-cellular.js +1 -1
  135. package/src/lib/server/pos-cellular.js.map +1 -1
  136. package/src/lib/server/pos-hardware-admin.js +86 -13
  137. package/src/lib/server/pos-hardware-admin.js.map +1 -1
  138. package/src/lib/server/pos-hardware-attach.js +5 -5
  139. package/src/lib/server/pos-hardware-attach.js.map +1 -1
  140. package/src/lib/server/pos-hardware-cancel.js +65 -0
  141. package/src/lib/server/pos-hardware-cancel.js.map +1 -1
  142. package/src/lib/server/pos-hardware-closure-notices.js +2 -5
  143. package/src/lib/server/pos-hardware-closure-notices.js.map +1 -1
  144. package/src/lib/server/pos-hardware-closure.js +5 -8
  145. package/src/lib/server/pos-hardware-closure.js.map +1 -1
  146. package/src/lib/server/pos-hardware-in-person.d.ts +2 -1
  147. package/src/lib/server/pos-hardware-in-person.js +72 -17
  148. package/src/lib/server/pos-hardware-in-person.js.map +1 -1
  149. package/src/lib/server/pos-hardware-notify.d.ts +2 -0
  150. package/src/lib/server/pos-hardware-notify.js +30 -5
  151. package/src/lib/server/pos-hardware-notify.js.map +1 -1
  152. package/src/lib/server/pos-hardware-readers.d.ts +25 -0
  153. package/src/lib/server/pos-hardware-readers.js +206 -85
  154. package/src/lib/server/pos-hardware-readers.js.map +1 -1
  155. package/src/lib/server/pos-hardware-returns.d.ts +8 -3
  156. package/src/lib/server/pos-hardware-returns.js +39 -7
  157. package/src/lib/server/pos-hardware-returns.js.map +1 -1
  158. package/src/lib/server/pos-hardware-sale-fields.d.ts +76 -0
  159. package/src/lib/server/pos-hardware-sale-fields.js +114 -1
  160. package/src/lib/server/pos-hardware-sale-fields.js.map +1 -1
  161. package/src/lib/server/pos-hardware-sale.d.ts +2 -0
  162. package/src/lib/server/pos-hardware-sale.js +1 -0
  163. package/src/lib/server/pos-hardware-sale.js.map +1 -1
  164. package/src/lib/server/pos-hardware-tax-return-source.js +7 -4
  165. package/src/lib/server/pos-hardware-tax-return-source.js.map +1 -1
  166. package/src/lib/server/pos-hardware-webhook.js +16 -3
  167. package/src/lib/server/pos-hardware-webhook.js.map +1 -1
  168. package/src/lib/server/pos-hardware.d.ts +14 -3
  169. package/src/lib/server/pos-hardware.js +83 -18
  170. package/src/lib/server/pos-hardware.js.map +1 -1
  171. package/src/lib/server/pos-ops-routes.js +2 -10
  172. package/src/lib/server/pos-ops-routes.js.map +1 -1
  173. package/src/lib/server/pos-order.js +5 -1
  174. package/src/lib/server/pos-order.js.map +1 -1
  175. package/src/lib/server/pos-stripe.d.ts +7 -7
  176. package/src/lib/server/pos-stripe.js +15 -13
  177. package/src/lib/server/pos-stripe.js.map +1 -1
  178. package/src/lib/server/pos-terminal.js +11 -3
  179. package/src/lib/server/pos-terminal.js.map +1 -1
  180. package/src/lib/server/quote-pay.d.ts +23 -1
  181. package/src/lib/server/quote-pay.js +111 -27
  182. package/src/lib/server/quote-pay.js.map +1 -1
  183. package/src/lib/server/quote.d.ts +2 -1
  184. package/src/lib/server/quote.js +12 -11
  185. package/src/lib/server/quote.js.map +1 -1
  186. package/src/lib/server/refund.js +13 -6
  187. package/src/lib/server/refund.js.map +1 -1
  188. package/src/lib/server/related.js +10 -3
  189. package/src/lib/server/related.js.map +1 -1
  190. package/src/lib/server/reserve.js +19 -6
  191. package/src/lib/server/reserve.js.map +1 -1
  192. package/src/lib/server/revenue-source.d.ts +6 -0
  193. package/src/lib/server/revenue-source.js +25 -9
  194. package/src/lib/server/revenue-source.js.map +1 -1
  195. package/src/lib/server/seller-stripe-account.d.ts +45 -0
  196. package/src/lib/server/seller-stripe-account.js +99 -0
  197. package/src/lib/server/seller-stripe-account.js.map +1 -0
  198. package/src/lib/server/storefront-tax-record.js +6 -1
  199. package/src/lib/server/storefront-tax-record.js.map +1 -1
  200. package/src/lib/server/storefront-tax.d.ts +33 -2
  201. package/src/lib/server/storefront-tax.js +39 -3
  202. package/src/lib/server/storefront-tax.js.map +1 -1
  203. package/src/lib/server/stream.d.ts +2 -0
  204. package/src/lib/server/stream.js +22 -2
  205. package/src/lib/server/stream.js.map +1 -1
  206. package/src/lib/server/stripe-refund.d.ts +15 -0
  207. package/src/lib/server/stripe-refund.js +54 -26
  208. package/src/lib/server/stripe-refund.js.map +1 -1
  209. package/src/lib/server/subscription-portal.js +8 -3
  210. package/src/lib/server/subscription-portal.js.map +1 -1
  211. package/src/lib/server/tax-return-source.js +5 -1
  212. package/src/lib/server/tax-return-source.js.map +1 -1
  213. package/src/lib/server.js +2 -2
  214. package/src/lib/server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-webhook.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 type { BillingWebhookHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n decodePosHardwareLines,\n isPosHardwareShippingMethod,\n POS_HARDWARE_CURRENCY,\n POS_HARDWARE_METADATA_TYPE,\n POS_HARDWARE_ORDER_ID,\n POS_HARDWARE_SHIPPING_LABELS,\n posHardwareSaleRecord,\n posHardwareSaleSetOptions,\n type PosHardwareAddress,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\nimport { hardwareOrdersRef, posHardwareSaleRef } from './pos-hardware'\nimport { raisePosHardwareOrderAlert, sendPosHardwareEmail } from './pos-hardware-notify'\nimport { posStripe } from './pos-stripe'\nimport { stripeTaxBreakdownLines } from './storefront-tax'\n\n/*==========================================\n * A PAID HARDWARE CHECKOUT BECOMES AN ORDER (AGL-4038).\n *\n * The platform's Stripe webhook fans every event out to the plugins' handlers\n * (`registerBillingWebhookHandler`); this one self-selects on a\n * `checkout.session.completed` whose metadata says it is a POS hardware\n * order, and writes `orgs/{orgId}/hardwareOrders/{orderId}` and, in the same\n * transaction, the retained sale record `posHardwareSales/{orderId}` that\n * outlives the workspace (see `PosHardwareSaleRecord`).\n *\n * IDEMPOTENT BY THE ORDER ID. The id was fixed when the session was made\n * (from the merchant's attempt key), and the write is a transactional\n * create: a redelivered event finds the document and does nothing, so a\n * replay never makes a second order, a second email or a second alert.\n *\n * NOTHING ON THE WIRE IS TRUSTED FOR WHAT IT NAMES. The lines are re-read\n * against the catalog; the amounts are Stripe's own totals for the session;\n * an unreadable session is logged and ignored rather than half-recorded.\n *\n * THE TAX BASE IS KEPT, NEVER INFERRED. Where Stripe Tax computed the tax,\n * the session's breakdown — the base each rate was applied to — is read back\n * (the delivered event does not carry it) and kept on the order and its sale\n * record, because the platform's sales tax return reports that base as its\n * taxable sales. A read that fails records no lines, and the return counts\n * the order as taxed with no stated base rather than as a zero base.\n *=========================================*/\n\nfunction addressFrom(raw: any): PosHardwareAddress | null {\n if (!raw || typeof raw !== 'object') return null\n const line1 = String(raw.line1 ?? '').trim()\n const city = String(raw.city ?? '').trim()\n const postalCode = String(raw.postal_code ?? '').trim()\n const country = String(raw.country ?? '').trim().toUpperCase()\n if (!line1 || !city || !postalCode || !country) return null\n const line2 = String(raw.line2 ?? '').trim()\n const state = String(raw.state ?? '').trim()\n return {\n line1: line1.slice(0, 200),\n ...(line2 ? { line2: line2.slice(0, 200) } : {}),\n city: city.slice(0, 100),\n ...(state ? { state: state.slice(0, 100) } : {}),\n postalCode: postalCode.slice(0, 20),\n country: country.slice(0, 2),\n }\n}\n\nconst cents = (value: unknown): number => {\n const number = Number(value)\n return Number.isSafeInteger(number) && number >= 0 ? number : 0\n}\n\n/** The order a paid session describes, or `null` when it is not readable. */\nexport function posHardwareOrderFromSession(\n session: any,\n now = Date.now(),\n): { orderId: string; order: PosHardwareOrder } | null {\n const metadata = session?.metadata ?? {}\n if (metadata.type !== POS_HARDWARE_METADATA_TYPE) return null\n const orderId = String(metadata.orderId ?? '')\n const orgId = String(metadata.orgId ?? '')\n const hostId = String(metadata.hostId ?? '')\n if (!POS_HARDWARE_ORDER_ID.test(orderId) || !orgId || !hostId) return null\n const lines = decodePosHardwareLines(metadata.lines)\n if (!lines) return null\n const method = isPosHardwareShippingMethod(metadata.shippingMethod) ? metadata.shippingMethod : 'standard'\n // Where the newer API versions keep the shipping details, then the older.\n const shippingDetails =\n session?.collected_information?.shipping_details ?? session?.shipping_details ?? null\n const customer = session?.customer_details ?? {}\n const subtotalCents = lines.reduce((sum, line) => sum + line.lineCents, 0)\n const shippingCents =\n session?.shipping_cost?.amount_total != null\n ? cents(session.shipping_cost.amount_total)\n : cents(metadata.shippingCents)\n const taxCents = cents(session?.total_details?.amount_tax)\n const totalCents =\n session?.amount_total != null ? cents(session.amount_total) : subtotalCents + shippingCents + taxCents\n const paymentIntent = session?.payment_intent\n return {\n orderId,\n order: {\n orgId,\n hostId,\n createdBy: String(metadata.uid ?? ''),\n contactEmail: String(customer?.email ?? '').trim() || null,\n lines,\n subtotalCents,\n shipping: {\n method,\n label: POS_HARDWARE_SHIPPING_LABELS[method],\n cents: shippingCents,\n name: String(shippingDetails?.name ?? customer?.name ?? '').trim() || null,\n phone: String(customer?.phone ?? '').trim() || null,\n address: addressFrom(shippingDetails?.address),\n },\n taxCents,\n totalCents,\n currency: String(session?.currency ?? POS_HARDWARE_CURRENCY),\n automaticTax: session?.automatic_tax?.enabled === true,\n // From whatever breakdown the delivered session carries; the handler\n // reads the expanded one where Stripe Tax ran.\n taxLines: stripeTaxBreakdownLines(session),\n stripeCheckoutSessionId: String(session?.id ?? ''),\n stripePaymentIntentId:\n (typeof paymentIntent === 'string' ? paymentIntent : String(paymentIntent?.id ?? '')) || null,\n stripeHardwareOrderId: null,\n tracking: null,\n status: 'paid',\n livemode: session?.livemode === true,\n createdAtMs: now,\n updatedAtMs: now,\n paidAtMs: now,\n },\n }\n}\n\n/**\n * The session with its tax breakdown, which the delivered event does not\n * carry, or the delivered session when the read fails. Never throws: the\n * order is recorded either way.\n */\nasync function withTaxBreakdown(session: any): Promise<any> {\n if (session?.automatic_tax?.enabled !== true) return session\n if (Array.isArray(session?.total_details?.breakdown?.taxes)) return session\n const id = String(session?.id ?? '')\n if (!id) return session\n try {\n const read = await posStripe('GET', `checkout/sessions/${encodeURIComponent(id)}`, {\n params: { 'expand[]': 'total_details.breakdown' },\n })\n return read.ok && read.body?.id === id ? read.body : session\n } catch (error) {\n console.error('[pos-hardware] the tax breakdown could not be read', id, error)\n return session\n }\n}\n\n/**\n * Writes the order once, with its retained sale record. `created` is false\n * when a delivery already did, so the caller tells people only the first time.\n *\n * Once means once by the ID, wherever the order now is: the sale record is\n * top-level and keyed by the order id, and is written with every order, so\n * an in-person order that has since moved to the buyer's workspace\n * (AGL-4038) is found by it and never recorded a second time where it began.\n */\nexport async function recordPosHardwareOrder(\n orderId: string,\n order: PosHardwareOrder,\n): Promise<{ created: boolean }> {\n const ref = hardwareOrdersRef(order.orgId).doc(orderId)\n const saleRef = posHardwareSaleRef(orderId)\n return firebaseAdmin\n .app()\n .firestore()\n .runTransaction(async (transaction: any) => {\n const [existing, sale] = await Promise.all([transaction.get(ref), transaction.get(saleRef)])\n if (existing.exists || sale.exists) return { created: false }\n transaction.create(ref, order)\n transaction.set(saleRef, posHardwareSaleRecord(orderId, order), posHardwareSaleSetOptions(order))\n return { created: true }\n })\n}\n\nexport const posHardwareBillingWebhookHandler: BillingWebhookHandler = async ({ type, object }) => {\n if (type !== 'checkout.session.completed') return\n if (object?.metadata?.type !== POS_HARDWARE_METADATA_TYPE) return\n const hostId = String(object?.metadata?.hostId ?? '')\n // A session that is not paid holds nothing to fulfil. Card is the only\n // method offered, so payment is settled when the session completes.\n if (object?.mode !== 'payment' || object?.payment_status !== 'paid') {\n return { claimed: true, ...(hostId ? { hostId } : {}) }\n }\n const parsed = posHardwareOrderFromSession(await withTaxBreakdown(object))\n if (!parsed) {\n console.error('[pos-hardware] a paid hardware session could not be read', String(object?.id ?? ''))\n return { claimed: true, ...(hostId ? { hostId } : {}) }\n }\n // Errors here propagate on purpose: the route answers 500 and Stripe\n // redelivers, and the create above makes the retry safe.\n const { created } = await recordPosHardwareOrder(parsed.orderId, parsed.order)\n if (created) {\n await Promise.all([\n sendPosHardwareEmail('received', parsed.orderId, parsed.order),\n raisePosHardwareOrderAlert(parsed.orderId, parsed.order),\n ])\n }\n return { claimed: true, hostId: parsed.order.hostId }\n}\n"],"names":["firebaseAdmin","decodePosHardwareLines","isPosHardwareShippingMethod","POS_HARDWARE_CURRENCY","POS_HARDWARE_METADATA_TYPE","POS_HARDWARE_ORDER_ID","POS_HARDWARE_SHIPPING_LABELS","posHardwareSaleRecord","posHardwareSaleSetOptions","hardwareOrdersRef","posHardwareSaleRef","raisePosHardwareOrderAlert","sendPosHardwareEmail","posStripe","stripeTaxBreakdownLines","addressFrom","raw","line1","String","trim","city","postalCode","postal_code","country","toUpperCase","line2","state","slice","cents","value","number","Number","isSafeInteger","posHardwareOrderFromSession","session","now","Date","metadata","shippingDetails","type","orderId","orgId","hostId","test","lines","method","shippingMethod","collected_information","shipping_details","customer","customer_details","subtotalCents","reduce","sum","line","lineCents","shippingCents","shipping_cost","amount_total","taxCents","total_details","amount_tax","totalCents","paymentIntent","payment_intent","order","createdBy","uid","contactEmail","email","shipping","label","name","phone","address","currency","automaticTax","automatic_tax","enabled","taxLines","stripeCheckoutSessionId","id","stripePaymentIntentId","stripeHardwareOrderId","tracking","status","livemode","createdAtMs","updatedAtMs","paidAtMs","withTaxBreakdown","Array","isArray","breakdown","taxes","read","encodeURIComponent","params","ok","body","error","console","recordPosHardwareOrder","ref","doc","saleRef","app","firestore","runTransaction","transaction","existing","sale","Promise","all","get","exists","created","create","set","posHardwareBillingWebhookHandler","object","mode","payment_status","claimed","parsed"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SACEC,sBAAsB,EACtBC,2BAA2B,EAC3BC,qBAAqB,EACrBC,0BAA0B,EAC1BC,qBAAqB,EACrBC,4BAA4B,EAC5BC,qBAAqB,EACrBC,yBAAyB,QAGpB,2BAAuB;AAC9B,SAASC,iBAAiB,EAAEC,kBAAkB,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AO3D,KAAK;SACxD;IACH;IACA,OAAO;QAAE0D,SAAS;QAAMjF,QAAQkF,OAAO3D,KAAK,CAACvB,MAAM;IAAC;AACtD,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-webhook.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 type { BillingWebhookHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n decodePosHardwareLines,\n isPosHardwareShippingMethod,\n POS_HARDWARE_CURRENCY,\n POS_HARDWARE_METADATA_TYPE,\n POS_HARDWARE_ORDER_ID,\n POS_HARDWARE_SHIPPING_LABELS,\n posHardwareOrderUnits,\n posHardwareSaleRecord,\n posHardwareSaleSetOptions,\n type PosHardwareAddress,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\nimport { posHardwareTermsFromMetadata } from '../model/pos-hardware-terms'\nimport { hardwareOrdersRef, posHardwareSaleRef } from './pos-hardware'\nimport { raisePosHardwareOrderAlert, sendPosHardwareEmail } from './pos-hardware-notify'\nimport { posStripe } from './pos-stripe'\nimport { stripeTaxBreakdownLines } from './storefront-tax'\n\n/*==========================================\n * A PAID HARDWARE CHECKOUT BECOMES AN ORDER (AGL-4038).\n *\n * The platform's Stripe webhook fans every event out to the plugins' handlers\n * (`registerBillingWebhookHandler`); this one self-selects on a\n * `checkout.session.completed` whose metadata says it is a POS hardware\n * order, and writes `orgs/{orgId}/hardwareOrders/{orderId}` and, in the same\n * transaction, the retained sale record `posHardwareSales/{orderId}` that\n * outlives the workspace (see `PosHardwareSaleRecord`).\n *\n * IDEMPOTENT BY THE ORDER ID. The id was fixed when the session was made\n * (from the merchant's attempt key), and the write is a transactional\n * create: a redelivered event finds the document and does nothing, so a\n * replay never makes a second order, a second email or a second alert.\n *\n * NOTHING ON THE WIRE IS TRUSTED FOR WHAT IT NAMES. The lines are re-read\n * against the catalog; the amounts are Stripe's own totals for the session;\n * an unreadable session is logged and ignored rather than half-recorded.\n *\n * THE TAX BASE IS KEPT, NEVER INFERRED. Where Stripe Tax computed the tax,\n * the session's breakdown — the base each rate was applied to — is read back\n * (the delivered event does not carry it) and kept on the order and its sale\n * record, because the platform's sales tax return reports that base as its\n * taxable sales. A read that fails records no lines, and the return counts\n * the order as taxed with no stated base rather than as a zero base.\n *=========================================*/\n\nfunction addressFrom(raw: any): PosHardwareAddress | null {\n if (!raw || typeof raw !== 'object') return null\n const line1 = String(raw.line1 ?? '').trim()\n const city = String(raw.city ?? '').trim()\n const postalCode = String(raw.postal_code ?? '').trim()\n const country = String(raw.country ?? '').trim().toUpperCase()\n if (!line1 || !city || !postalCode || !country) return null\n const line2 = String(raw.line2 ?? '').trim()\n const state = String(raw.state ?? '').trim()\n return {\n line1: line1.slice(0, 200),\n ...(line2 ? { line2: line2.slice(0, 200) } : {}),\n city: city.slice(0, 100),\n ...(state ? { state: state.slice(0, 100) } : {}),\n postalCode: postalCode.slice(0, 20),\n country: country.slice(0, 2),\n }\n}\n\nconst cents = (value: unknown): number => {\n const number = Number(value)\n return Number.isSafeInteger(number) && number >= 0 ? number : 0\n}\n\n/** The order a paid session describes, or `null` when it is not readable. */\nexport function posHardwareOrderFromSession(\n session: any,\n now = Date.now(),\n): { orderId: string; order: PosHardwareOrder } | null {\n const metadata = session?.metadata ?? {}\n if (metadata.type !== POS_HARDWARE_METADATA_TYPE) return null\n const orderId = String(metadata.orderId ?? '')\n const orgId = String(metadata.orgId ?? '')\n const hostId = String(metadata.hostId ?? '')\n if (!POS_HARDWARE_ORDER_ID.test(orderId) || !orgId || !hostId) return null\n const lines = decodePosHardwareLines(metadata.lines)\n if (!lines) return null\n const method = isPosHardwareShippingMethod(metadata.shippingMethod) ? metadata.shippingMethod : 'standard'\n // Where the newer API versions keep the shipping details, then the older.\n const shippingDetails =\n session?.collected_information?.shipping_details ?? session?.shipping_details ?? null\n const customer = session?.customer_details ?? {}\n const subtotalCents = lines.reduce((sum, line) => sum + line.lineCents, 0)\n const shippingCents =\n session?.shipping_cost?.amount_total != null\n ? cents(session.shipping_cost.amount_total)\n : cents(metadata.shippingCents)\n const taxCents = cents(session?.total_details?.amount_tax)\n const totalCents =\n session?.amount_total != null ? cents(session.amount_total) : subtotalCents + shippingCents + taxCents\n const paymentIntent = session?.payment_intent\n // The terms of sale and business use the buyer ticked on the Hardware card\n // (AGL-4038), accepted when the session was made.\n const createdMs = Number(session?.created) > 0 ? Number(session.created) * 1000 : now\n const termsAcceptance = posHardwareTermsFromMetadata(metadata, createdMs)\n return {\n orderId,\n order: {\n orgId,\n hostId,\n createdBy: String(metadata.uid ?? ''),\n contactEmail: String(customer?.email ?? '').trim() || null,\n lines,\n subtotalCents,\n shipping: {\n method,\n label: POS_HARDWARE_SHIPPING_LABELS[method],\n cents: shippingCents,\n name: String(shippingDetails?.name ?? customer?.name ?? '').trim() || null,\n phone: String(customer?.phone ?? '').trim() || null,\n address: addressFrom(shippingDetails?.address),\n },\n taxCents,\n totalCents,\n currency: String(session?.currency ?? POS_HARDWARE_CURRENCY),\n automaticTax: session?.automatic_tax?.enabled === true,\n // From whatever breakdown the delivered session carries; the handler\n // reads the expanded one where Stripe Tax ran.\n taxLines: stripeTaxBreakdownLines(session),\n stripeCheckoutSessionId: String(session?.id ?? ''),\n stripePaymentIntentId:\n (typeof paymentIntent === 'string' ? paymentIntent : String(paymentIntent?.id ?? '')) || null,\n stripeHardwareOrderId: null,\n tracking: null,\n status: 'paid',\n livemode: session?.livemode === true,\n createdAtMs: now,\n updatedAtMs: now,\n paidAtMs: now,\n ...(termsAcceptance ? { termsAcceptance } : {}),\n // One per reader, for its serial when staff set it up before it ships.\n units: posHardwareOrderUnits({ lines }),\n serialNumbers: [],\n },\n }\n}\n\n/**\n * The session with its tax breakdown, which the delivered event does not\n * carry, or the delivered session when the read fails. Never throws: the\n * order is recorded either way.\n */\nasync function withTaxBreakdown(session: any): Promise<any> {\n if (session?.automatic_tax?.enabled !== true) return session\n if (Array.isArray(session?.total_details?.breakdown?.taxes)) return session\n const id = String(session?.id ?? '')\n if (!id) return session\n try {\n const read = await posStripe('GET', `checkout/sessions/${encodeURIComponent(id)}`, {\n params: { 'expand[]': 'total_details.breakdown' },\n })\n return read.ok && read.body?.id === id ? read.body : session\n } catch (error) {\n console.error('[pos-hardware] the tax breakdown could not be read', id, error)\n return session\n }\n}\n\n/**\n * Writes the order once, with its retained sale record. `created` is false\n * when a delivery already did, so the caller tells people only the first time.\n *\n * Once means once by the ID, wherever the order now is: the sale record is\n * top-level and keyed by the order id, and is written with every order, so\n * an in-person order that has since moved to the buyer's workspace\n * (AGL-4038) is found by it and never recorded a second time where it began.\n */\nexport async function recordPosHardwareOrder(\n orderId: string,\n order: PosHardwareOrder,\n): Promise<{ created: boolean }> {\n const ref = hardwareOrdersRef(order.orgId).doc(orderId)\n const saleRef = posHardwareSaleRef(orderId)\n return firebaseAdmin\n .app()\n .firestore()\n .runTransaction(async (transaction: any) => {\n const [existing, sale] = await Promise.all([transaction.get(ref), transaction.get(saleRef)])\n if (existing.exists || sale.exists) return { created: false }\n transaction.create(ref, order)\n transaction.set(saleRef, posHardwareSaleRecord(orderId, order), posHardwareSaleSetOptions(order))\n return { created: true }\n })\n}\n\nexport const posHardwareBillingWebhookHandler: BillingWebhookHandler = async ({ type, object }) => {\n if (type !== 'checkout.session.completed') return\n if (object?.metadata?.type !== POS_HARDWARE_METADATA_TYPE) return\n const hostId = String(object?.metadata?.hostId ?? '')\n // A session that is not paid holds nothing to fulfil. Card is the only\n // method offered, so payment is settled when the session completes.\n if (object?.mode !== 'payment' || object?.payment_status !== 'paid') {\n return { claimed: true, ...(hostId ? { hostId } : {}) }\n }\n const parsed = posHardwareOrderFromSession(await withTaxBreakdown(object))\n if (!parsed) {\n console.error('[pos-hardware] a paid hardware session could not be read', String(object?.id ?? ''))\n return { claimed: true, ...(hostId ? { hostId } : {}) }\n }\n // Errors here propagate on purpose: the route answers 500 and Stripe\n // redelivers, and the create above makes the retry safe.\n const { created } = await recordPosHardwareOrder(parsed.orderId, parsed.order)\n if (created) {\n await Promise.all([\n sendPosHardwareEmail('received', parsed.orderId, parsed.order),\n raisePosHardwareOrderAlert(parsed.orderId, parsed.order),\n ])\n }\n return { claimed: true, hostId: parsed.order.hostId }\n}\n"],"names":["firebaseAdmin","decodePosHardwareLines","isPosHardwareShippingMethod","POS_HARDWARE_CURRENCY","POS_HARDWARE_METADATA_TYPE","POS_HARDWARE_ORDER_ID","POS_HARDWARE_SHIPPING_LABELS","posHardwareOrderUnits","posHardwareSaleRecord","posHardwareSaleSetOptions","posHardwareTermsFromMetadata","hardwareOrdersRef","posHardwareSaleRef","raisePosHardwareOrderAlert","sendPosHardwareEmail","posStripe","stripeTaxBreakdownLines","addressFrom","raw","line1","String","trim","city","postalCode","postal_code","country","toUpperCase","line2","state","slice","cents","value","number","Number","isSafeInteger","posHardwareOrderFromSession","session","now","Date","metadata","shippingDetails","type","orderId","orgId","hostId","test","lines","method","shippingMethod","collected_information","shipping_details","customer","customer_details","subtotalCents","reduce","sum","line","lineCents","shippingCents","shipping_cost","amount_total","taxCents","total_details","amount_tax","totalCents","paymentIntent","payment_intent","createdMs","created","termsAcceptance","order","createdBy","uid","contactEmail","email","shipping","label","name","phone","address","currency","automaticTax","automatic_tax","enabled","taxLines","stripeCheckoutSessionId","id","stripePaymentIntentId","stripeHardwareOrderId","tracking","status","livemode","createdAtMs","updatedAtMs","paidAtMs","units","serialNumbers","withTaxBreakdown","Array","isArray","breakdown","taxes","read","encodeURIComponent","params","ok","body","error","console","recordPosHardwareOrder","ref","doc","saleRef","app","firestore","runTransaction","transaction","existing","sale","Promise","all","get","exists","create","set","posHardwareBillingWebhookHandler","object","mode","payment_status","claimed","parsed"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SACEC,sBAAsB,EACtBC,2BAA2B,EAC3BC,qBAAqB,EACrBC,0BAA0B,EAC1BC,qBAAqB,EACrBC,4BAA4B,EAC5BC,qBAAqB,EACrBC,qBAAqB,EACrBC,yBAAyB,QAGpB,2BAAuB;AAC9B,SAASC,4BAA4B,QAAQ,iCAA6B;AAC1E,SAASC,iBAAiB,EAAEC,kBAAkB,QAAQ,oBAAgB;AACtE,SAASC,0BAA0B,EAAEC,oBAAoB,QAAQ,2BAAuB;AACxF,SAASC,SAAS,QAAQ,kBAAc;AACxC,SAASC,uBAAuB,QAAQ,sBAAkB;AAE1D;;;;;;;;;;;;;;;;;;;;;;;;;2CAyB2C,GAE3C,SAASC,YAAYC,GAAQ;QAENA,YACDA,WACMA,kBACHA,cAEFA,YACAA;IAPrB,IAAI,CAACA,OAAO,OAAOA,QAAQ,UAAU,OAAO;IAC5C,MAAMC,QAAQC,QAAOF,aAAAA,IAAIC,KAAK,YAATD,aAAa,IAAIG,IAAI;IAC1C,MAAMC,OAAOF,QAAOF,YAAAA,IAAII,IAAI,YAARJ,YAAY,IAAIG,IAAI;IACxC,MAAME,aAAaH,QAAOF,mBAAAA,IAAIM,WAAW,YAAfN,mBAAmB,IAAIG,IAAI;IACrD,MAAMI,UAAUL,QAAOF,eAAAA,IAAIO,OAAO,YAAXP,eAAe,IAAIG,IAAI,GAAGK,WAAW;IAC5D,IAAI,CAACP,SAAS,CAACG,QAAQ,CAACC,cAAc,CAACE,SAAS,OAAO;IACvD,MAAME,QAAQP,QAAOF,aAAAA,IAAIS,KAAK,YAATT,aAAa,IAAIG,IAAI;IAC1C,MAAMO,QAAQR,QAAOF,aAAAA,IAAIU,KAAK,YAATV,aAAa,IAAI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mBAAI;IAClD,uEAAuE;IACvE,oEAAoE;IACpE,IAAIkF,CAAAA,0BAAAA,OAAQC,IAAI,MAAK,aAAaD,CAAAA,0BAAAA,OAAQE,cAAc,MAAK,QAAQ;QACnE,OAAO;YAAEC,SAAS;WAAUrF,SAAS;YAAEA;QAAO,IAAI,CAAC;IACrD;IACA,MAAMsF,SAAS/F,4BAA4B,MAAM8D,iBAAiB6B;IAClE,IAAI,CAACI,QAAQ;;QACXtB,QAAQD,KAAK,CAAC,4DAA4DvF,gBAAO0G,0BAAAA,OAAQxC,EAAE,oBAAI;QAC/F,OAAO;YAAE2C,SAAS;WAAUrF,SAAS;YAAEA;QAAO,IAAI,CAAC;IACrD;IACA,qEAAqE;IACrE,yDAAyD;IACzD,MAAM,EAAEwB,OAAO,EAAE,GAAG,MAAMyC,uBAAuBqB,OAAOxF,OAAO,EAAEwF,OAAO5D,KAAK;IAC7E,IAAIF,SAAS;QACX,MAAMmD,QAAQC,GAAG,CAAC;YAChB1G,qBAAqB,YAAYoH,OAAOxF,OAAO,EAAEwF,OAAO5D,KAAK;YAC7DzD,2BAA2BqH,OAAOxF,OAAO,EAAEwF,OAAO5D,KAAK;SACxD;IACH;IACA,OAAO;QAAE2D,SAAS;QAAMrF,QAAQsF,OAAO5D,KAAK,CAAC1B,MAAM;IAAC;AACtD,EAAC"}
@@ -15,7 +15,7 @@
15
15
  * limitations under the License.
16
16
  */
17
17
  import type { PluginApiHandler } from '@aglyn/aglyn/server';
18
- import { type PosHardwareConfig, type PosHardwareInPersonConfig, type PosHardwareOrder } from '../model/pos-hardware';
18
+ import { type PosHardwareConfig, type PosHardwareInPersonConfig, type PosHardwareOrder, type PosHardwareSkuId } from '../model/pos-hardware';
19
19
  /** The shop's config from this deployment, or `null` while it is hidden. */
20
20
  export declare function posHardwareConfig(env?: Record<string, string | undefined>): PosHardwareConfig | null;
21
21
  /**
@@ -25,6 +25,17 @@ export declare function posHardwareConfig(env?: Record<string, string | undefine
25
25
  * to another workspace stops selling hardware rather than selling it for them.
26
26
  */
27
27
  export declare function posHardwareInPersonConfig(env?: Record<string, string | undefined>): PosHardwareInPersonConfig | null;
28
+ /**
29
+ * The price each hardware item is listed at in the platform's own store
30
+ * (AGL-4038), in cents: an active product there whose `hardwareSku` names
31
+ * the item, at its first variant's price. Where two products name one item,
32
+ * the lower price, so no page the store shows quotes less than the shop
33
+ * charges. Empty while no seller store is configured. A failed read throws:
34
+ * the shop does not quote a price it cannot check against the store's.
35
+ */
36
+ export declare function posHardwareListedCents(inPerson?: PosHardwareInPersonConfig | null): Promise<Partial<Record<PosHardwareSkuId, number>>>;
37
+ /** The shop's config with the platform's own store's listed prices, or `null` while it is hidden. */
38
+ export declare function posHardwarePricedConfig(): Promise<PosHardwareConfig | null>;
28
39
  /** Whether a store, owned by `orgId`, is the platform's own hardware seller. */
29
40
  export declare function isPosHardwareSellerStore(config: PosHardwareInPersonConfig | null, hostId: string, orgId: string): config is PosHardwareInPersonConfig;
30
41
  /**
@@ -49,7 +60,7 @@ export declare function merchantHardwareOrderView(id: string, order: PosHardware
49
60
  number: string;
50
61
  status: import("../model/pos-hardware").PosHardwareOrderStatus;
51
62
  lines: {
52
- sku: import("../model/pos-hardware").PosHardwareSkuId;
63
+ sku: PosHardwareSkuId;
53
64
  name: string;
54
65
  quantity: number;
55
66
  unitCents: number;
@@ -101,7 +112,7 @@ export declare function waitingInPersonReaders(orgId: string, hostId: string): P
101
112
  number: string;
102
113
  status: import("../model/pos-hardware").PosHardwareOrderStatus;
103
114
  lines: {
104
- sku: import("../model/pos-hardware").PosHardwareSkuId;
115
+ sku: PosHardwareSkuId;
105
116
  name: string;
106
117
  quantity: number;
107
118
  unitCents: number;
@@ -15,10 +15,12 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
17
  */ import { createHash } from "crypto";
18
+ import { readClientIp } from "@aglyn/aglyn/app-utils/request-ip";
18
19
  import * as Aglyn from "@aglyn/aglyn/server";
19
20
  import { firebaseAdmin, readOrgBilling } from "@aglyn/tenant-data-admin";
20
21
  import { hostConsoleUrl } from "@aglyn/tenant-data-admin/server/host-console-link";
21
- import { encodePosHardwareLines, isPosHardwareShippingMethod, POS_HARDWARE_ANCHOR, parsePosHardwareConfig, parsePosHardwareInPersonConfig, POS_HARDWARE_CURRENCY, POS_HARDWARE_METADATA_TYPE, POS_HARDWARE_ORDERS_COLLECTION, POS_HARDWARE_SALES_COLLECTION, POS_HARDWARE_SHIP_COUNTRIES, POS_HARDWARE_SHIPPING_LABELS, posHardwareOffers, posHardwareOrderSource, posHardwareSku, pricePosHardwareCart } from "../model/pos-hardware.js";
22
+ import { isPosHardwareSellerStoreSale, encodePosHardwareLines, isPosHardwareShippingMethod, POS_HARDWARE_ANCHOR, parsePosHardwareConfig, parsePosHardwareInPersonConfig, POS_HARDWARE_CURRENCY, POS_HARDWARE_METADATA_TYPE, POS_HARDWARE_ORDERS_COLLECTION, POS_HARDWARE_SALES_COLLECTION, POS_HARDWARE_SHIP_COUNTRIES, POS_HARDWARE_SHIPPING_LABELS, POS_HARDWARE_SKUS, POS_HARDWARE_TAX_CODE, posHardwareOffers, posHardwareOrderSource, posHardwareSku, pricePosHardwareCart } from "../model/pos-hardware.js";
23
+ import { POS_HARDWARE_TERMS_REQUIRED, posHardwareTermsConfirmed, posHardwareTermsMetadata } from "../model/pos-hardware-terms.js";
22
24
  import { mayVisitPosHardwareShop } from "../model/plugin-permissions.js";
23
25
  import { authorizePosStaff, posIdempotencyKey, posRequestBody } from "./pos-auth.js";
24
26
  import { posStripe, posTerminalAvailable } from "./pos-stripe.js";
@@ -30,8 +32,9 @@ import { posStripe, posTerminalAvailable } from "./pos-stripe.js";
30
32
  * checkout a Stripe Checkout Session for the basket, on the PLATFORM
31
33
  * orders this site's hardware orders, newest first
32
34
  *
33
- * Gated like the register (`authorizePosStaff`, on a plan with POS), because
34
- * the readers it sells are the register's, with one difference (AGL-4047):
35
+ * Gated like the register (`authorizePosStaff`) but on ANY plan (AGL-4038):
36
+ * a workspace buys its readers first and adds the point of sale when it sets
37
+ * them up. The readers it sells are the register's, with one difference (AGL-4047):
35
38
  * the shop admits whoever works the register (`managePos`) AND whoever may
36
39
  * buy hardware (`posBuyHardware`), which stands on its own — a bookkeeper
37
40
  * with no register orders the store's readers. A checkout needs
@@ -56,6 +59,38 @@ import { posStripe, posTerminalAvailable } from "./pos-stripe.js";
56
59
  */ export function posHardwareInPersonConfig(env = process.env) {
57
60
  return parsePosHardwareInPersonConfig(env);
58
61
  }
62
+ /**
63
+ * The price each hardware item is listed at in the platform's own store
64
+ * (AGL-4038), in cents: an active product there whose `hardwareSku` names
65
+ * the item, at its first variant's price. Where two products name one item,
66
+ * the lower price, so no page the store shows quotes less than the shop
67
+ * charges. Empty while no seller store is configured. A failed read throws:
68
+ * the shop does not quote a price it cannot check against the store's.
69
+ */ export async function posHardwareListedCents(inPerson = posHardwareInPersonConfig()) {
70
+ if (!inPerson) return {};
71
+ const snapshot = await firebaseAdmin.app().firestore().collection('hosts').doc(inPerson.sellerHostId).collection('products').where('hardwareSku', 'in', POS_HARDWARE_SKUS.map((sku)=>sku.id)).get();
72
+ const listed = {};
73
+ for (const doc of snapshot.docs){
74
+ var _product_hardwareSku, _product_status, _listed_sku_id;
75
+ var _variants_;
76
+ const product = doc.data();
77
+ const sku = posHardwareSku(String((_product_hardwareSku = product['hardwareSku']) != null ? _product_hardwareSku : ''));
78
+ if (!sku || ((_product_status = product['status']) != null ? _product_status : 'active') !== 'active') continue;
79
+ const variants = Array.isArray(product['variants']) ? product['variants'] : [];
80
+ const priceUsd = Number(variants.length ? (_variants_ = variants[0]) == null ? void 0 : _variants_.priceUsd : product['priceUsd']);
81
+ if (!Number.isFinite(priceUsd) || priceUsd <= 0) continue;
82
+ const cents = Math.round(priceUsd * 100);
83
+ listed[sku.id] = Math.min((_listed_sku_id = listed[sku.id]) != null ? _listed_sku_id : cents, cents);
84
+ }
85
+ return listed;
86
+ }
87
+ /** The shop's config with the platform's own store's listed prices, or `null` while it is hidden. */ export async function posHardwarePricedConfig() {
88
+ const config = posHardwareConfig();
89
+ if (!config) return null;
90
+ return _extends({}, config, {
91
+ listedCents: await posHardwareListedCents()
92
+ });
93
+ }
59
94
  /** Whether a store, owned by `orgId`, is the platform's own hardware seller. */ export function isPosHardwareSellerStore(config, hostId, orgId) {
60
95
  return Boolean(config) && (config == null ? void 0 : config.sellerHostId) === hostId && (config == null ? void 0 : config.sellerOrgId) === orgId;
61
96
  }
@@ -167,7 +202,8 @@ export function hardwareOrdersRef(orgId) {
167
202
  orders: orders.docs.map((doc)=>({
168
203
  id: String(doc.id),
169
204
  order: doc.data()
170
- })).filter(({ order })=>order.source === 'in_person').sort((a, b)=>Number(b.order.hostId === hostId) - Number(a.order.hostId === hostId)).map(({ id, order })=>{
205
+ }))// Bought from the platform's own store, at an event or online (AGL-4038).
206
+ .filter(({ order })=>isPosHardwareSellerStoreSale(order)).sort((a, b)=>Number(b.order.hostId === hostId) - Number(a.order.hostId === hostId)).map(({ id, order })=>{
171
207
  var _order_units;
172
208
  return _extends({}, merchantHardwareOrderView(id, order), {
173
209
  hostId: order.hostId,
@@ -176,6 +212,11 @@ export function hardwareOrdersRef(orgId) {
176
212
  })
177
213
  };
178
214
  }
215
+ const LISTED_READ_FAILED = Symbol('listed-read-failed');
216
+ function listedReadFailed(error) {
217
+ console.error('[pos-hardware] the store\'s listed prices could not be read', error);
218
+ return LISTED_READ_FAILED;
219
+ }
179
220
  export const posHardwareHandler = async (req, res)=>{
180
221
  var _body_hostId, _body_action;
181
222
  if (req.method !== 'POST') return res.status(405).json({
@@ -190,21 +231,28 @@ export const posHardwareHandler = async (req, res)=>{
190
231
  // `managePos` until a role or the member sets it, and may be granted
191
232
  // without it — starts a checkout that the workspace pays for.
192
233
  //
193
- // A READER BOUGHT IN PERSON (AGL-4038): `waiting` is read without the
194
- // point of sale plan, because a workspace without it is exactly the one
195
- // that must be told to add it first; choosing its store and marking it set
196
- // up are setting up devices (`posDevices`) on the store named.
234
+ // ANYONE CAN BUY (AGL-4038): browsing, checking out, the orders, a return
235
+ // request and the readers waiting to be set up are open whatever the
236
+ // workspace's plan. A reader takes payments at the register, which comes
237
+ // with the point of sale, so the card, a delivered order and the register
238
+ // prompt to add it; the key above still decides who may buy. Setting a
239
+ // reader up — choosing its store, marking it set up — is setting up
240
+ // devices (`posDevices`) on the store named, and asks the plan.
197
241
  const settingUp = action === 'choose-store' || action === 'mark-set-up';
198
- const gate = await authorizePosStaff(req, hostId, action === 'checkout' ? 'posBuyHardware' : settingUp ? 'posDevices' : undefined, mayVisitPosHardwareShop, // A workspace whose plan lost the point of sale still sees what it bought
199
- // and may ask to return a reader bought in person.
200
- action === 'waiting' || action === 'orders' || action === 'request-return' ? {
201
- planRequired: false
202
- } : {});
242
+ const gate = await authorizePosStaff(req, hostId, action === 'checkout' ? 'posBuyHardware' : settingUp ? 'posDevices' : undefined, mayVisitPosHardwareShop, {
243
+ planRequired: settingUp
244
+ });
203
245
  if ('error' in gate) return res.status(gate.status).json({
204
246
  error: gate.error
205
247
  });
206
248
  const staff = gate.staff;
207
- const config = posHardwareConfig();
249
+ // Priced by the store's listed prices only where a price is quoted or charged.
250
+ const config = action === 'catalog' || action === 'checkout' ? await posHardwarePricedConfig().catch(listedReadFailed) : posHardwareConfig();
251
+ if (config === LISTED_READ_FAILED) {
252
+ return res.status(503).json({
253
+ error: 'The hardware shop could not check its prices. Try again in a moment.'
254
+ });
255
+ }
208
256
  try {
209
257
  switch(action){
210
258
  case 'waiting':
@@ -296,8 +344,8 @@ export const posHardwareHandler = async (req, res)=>{
296
344
  }
297
345
  case 'checkout':
298
346
  {
299
- var _billing_stripeCustomerId, _ref;
300
- var _created_body;
347
+ var _readClientIp, _ref, _billing_stripeCustomerId, _ref1;
348
+ var _req_headers, _created_body;
301
349
  if (!config) return res.status(404).json({
302
350
  error: 'The hardware shop is not available.'
303
351
  });
@@ -317,6 +365,17 @@ export const posHardwareHandler = async (req, res)=>{
317
365
  if (!shipping) return res.status(400).json({
318
366
  error: 'Choose a shipping speed.'
319
367
  });
368
+ // The terms of sale and business use, both ticked (AGL-4038).
369
+ if (!posHardwareTermsConfirmed(body['hardwareTerms'])) {
370
+ return res.status(400).json({
371
+ error: POS_HARDWARE_TERMS_REQUIRED,
372
+ needsHardwareTerms: true
373
+ });
374
+ }
375
+ const terms = posHardwareTermsMetadata({
376
+ ip: (_readClientIp = readClientIp(req.headers)) != null ? _readClientIp : null,
377
+ userAgent: String((_ref = (_req_headers = req.headers) == null ? void 0 : _req_headers['user-agent']) != null ? _ref : '') || null
378
+ });
320
379
  const orderId = posHardwareOrderId(staff.orgId, staff.hostId, attemptKey);
321
380
  const billing = await readOrgBilling(staff.orgId).catch(()=>({}));
322
381
  const customer = String((_billing_stripeCustomerId = billing.stripeCustomerId) != null ? _billing_stripeCustomerId : '').trim();
@@ -341,7 +400,11 @@ export const posHardwareHandler = async (req, res)=>{
341
400
  'metadata[lines]': encodePosHardwareLines(priced.lines),
342
401
  'metadata[shippingMethod]': shipping.method,
343
402
  'metadata[shippingCents]': shipping.cents,
344
- 'metadata[subtotalCents]': priced.subtotalCents,
403
+ 'metadata[subtotalCents]': priced.subtotalCents
404
+ }, Object.fromEntries(Object.entries(terms).map(([key, value])=>[
405
+ `metadata[${key}]`,
406
+ value
407
+ ])), {
345
408
  'payment_intent_data[description]': `Card reader order ${posHardwareOrderNumber(orderId)}`,
346
409
  'payment_intent_data[metadata][type]': POS_HARDWARE_METADATA_TYPE,
347
410
  'payment_intent_data[metadata][orderId]': orderId,
@@ -364,13 +427,15 @@ export const posHardwareHandler = async (req, res)=>{
364
427
  params[`line_items[${index}][price_data][product_data][name]`] = line.name;
365
428
  if (sku) params[`line_items[${index}][price_data][product_data][description]`] = sku.use;
366
429
  params[`line_items[${index}][price_data][product_data][metadata][sku]`] = line.sku;
430
+ // Taxed as the physical good it is, never as the account's default (software).
431
+ params[`line_items[${index}][price_data][product_data][tax_code]`] = POS_HARDWARE_TAX_CODE;
367
432
  if (config.automaticTax) params[`line_items[${index}][price_data][tax_behavior]`] = 'exclusive';
368
433
  });
369
434
  const created = await posStripe('POST', 'checkout/sessions', {
370
435
  params,
371
436
  idempotencyKey: `pos-hw-checkout-${orderId}`
372
437
  });
373
- const url = String((_ref = (_created_body = created.body) == null ? void 0 : _created_body.url) != null ? _ref : '');
438
+ const url = String((_ref1 = (_created_body = created.body) == null ? void 0 : _created_body.url) != null ? _ref1 : '');
374
439
  if (!created.ok || !url) {
375
440
  var _created_body_error, _created_body1;
376
441
  console.error('[pos-hardware] checkout refused', created.status, (_created_body1 = created.body) == null ? void 0 : (_created_body_error = _created_body1.error) == null ? void 0 : _created_body_error.code);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware.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 { createHash } from 'crypto'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, readOrgBilling } from '@aglyn/tenant-data-admin'\nimport { hostConsoleUrl } from '@aglyn/tenant-data-admin/server/host-console-link'\nimport {\n encodePosHardwareLines,\n isPosHardwareShippingMethod,\n POS_HARDWARE_ANCHOR,\n parsePosHardwareConfig,\n parsePosHardwareInPersonConfig,\n POS_HARDWARE_CURRENCY,\n POS_HARDWARE_METADATA_TYPE,\n POS_HARDWARE_ORDERS_COLLECTION,\n POS_HARDWARE_SALES_COLLECTION,\n POS_HARDWARE_SHIP_COUNTRIES,\n POS_HARDWARE_SHIPPING_LABELS,\n posHardwareOffers,\n posHardwareOrderSource,\n posHardwareSku,\n pricePosHardwareCart,\n type PosHardwareConfig,\n type PosHardwareInPersonConfig,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\nimport { mayVisitPosHardwareShop } from '../model/plugin-permissions'\nimport { authorizePosStaff, posIdempotencyKey, posRequestBody } from './pos-auth'\nimport { posStripe, posTerminalAvailable } from './pos-stripe'\n\n/*==========================================\n * `POST /api/commerce/pos-hardware` (AGL-4038): the merchant's half of the\n * POS hardware shop, behind the Hardware card on Products → Point of sale.\n *\n * catalog what is on offer and at what price, or `available: false`\n * checkout a Stripe Checkout Session for the basket, on the PLATFORM\n * orders this site's hardware orders, newest first\n *\n * Gated like the register (`authorizePosStaff`, on a plan with POS), because\n * the readers it sells are the register's, with one difference (AGL-4047):\n * the shop admits whoever works the register (`managePos`) AND whoever may\n * buy hardware (`posBuyHardware`), which stands on its own — a bookkeeper\n * with no register orders the store's readers. A checkout needs\n * `posBuyHardware`; seeing the catalog and the site's orders needs either.\n *\n * THE SALE IS THE PLATFORM'S. The session is created with the platform key\n * and NO connected account, `transfer_data` or application fee: the merchant\n * is the buyer here, and the platform is the seller of record that places\n * the order with Stripe. The order document is written by the webhook once\n * Stripe says the session is paid (`pos-hardware-webhook.ts`), never here.\n *=========================================*/\n\n/** The shop's config from this deployment, or `null` while it is hidden. */\nexport function posHardwareConfig(\n env: Record<string, string | undefined> = process.env,\n): PosHardwareConfig | null {\n // A reader the platform cannot yet take payments on is not for sale: the\n // shop opens only where the register offers card readers at all.\n if (!posTerminalAvailable()) return null\n return parsePosHardwareConfig(env)\n}\n\n/**\n * The platform's own store that sells hardware in person (AGL-4038), or\n * `null` while that is off. Read like the shop's other figures; a store is\n * the seller only when BOTH its id and its workspace's match, so a site moved\n * to another workspace stops selling hardware rather than selling it for them.\n */\nexport function posHardwareInPersonConfig(\n env: Record<string, string | undefined> = process.env,\n): PosHardwareInPersonConfig | null {\n return parsePosHardwareInPersonConfig(env)\n}\n\n/** Whether a store, owned by `orgId`, is the platform's own hardware seller. */\nexport function isPosHardwareSellerStore(\n config: PosHardwareInPersonConfig | null,\n hostId: string,\n orgId: string,\n): config is PosHardwareInPersonConfig {\n return Boolean(config) && config?.sellerHostId === hostId && config?.sellerOrgId === orgId\n}\n\n/**\n * An in-person order's id, from the register sale it came from: one register\n * sale is one hardware order however often its completion is told.\n */\nexport function posHardwareInPersonOrderId(hostId: string, registerOrderId: string): string {\n return `hw_${createHash('sha256').update(`pos:${hostId}:${registerOrderId}`).digest('hex').slice(0, 20)}`\n}\n\n/** The order's id, derived from the attempt so a repeated press is one order. */\nexport function posHardwareOrderId(orgId: string, hostId: string, attemptKey: string): string {\n return `hw_${createHash('sha256').update(`${orgId}:${hostId}:${attemptKey}`).digest('hex').slice(0, 20)}`\n}\n\n/** The number a person reads: `HW-` and six characters of the id. */\nexport function posHardwareOrderNumber(orderId: string): string {\n return `HW-${orderId.replace(/^hw_/, '').slice(0, 6).toUpperCase()}`\n}\n\nexport function hardwareOrdersRef(orgId: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(orgId)\n .collection(POS_HARDWARE_ORDERS_COLLECTION)\n}\n\n/**\n * `posHardwareSales/{orderId}`, the retained sale record beside each order\n * (see `PosHardwareSaleRecord`). Top-level on purpose: the workspace erasure\n * cannot reach it.\n */\nexport function posHardwareSaleRef(orderId: string) {\n return firebaseAdmin.app().firestore().collection(POS_HARDWARE_SALES_COLLECTION).doc(orderId)\n}\n\n/** An order as the merchant's card shows it: no Stripe ids, no staff notes. */\nexport function merchantHardwareOrderView(id: string, order: PosHardwareOrder) {\n return {\n id,\n number: posHardwareOrderNumber(id),\n status: order.status,\n lines: (order.lines ?? []).map((line) => ({\n sku: line.sku,\n name: line.name,\n quantity: line.quantity,\n unitCents: line.unitCents,\n lineCents: line.lineCents,\n })),\n subtotalCents: order.subtotalCents ?? 0,\n shippingCents: order.shipping?.cents ?? 0,\n shippingLabel: order.shipping?.label ?? '',\n taxCents: order.taxCents ?? 0,\n totalCents: order.totalCents ?? 0,\n tracking: order.tracking ?? null,\n createdAtMs: order.createdAtMs ?? 0,\n updatedAtMs: order.updatedAtMs ?? order.createdAtMs ?? 0,\n // Bought in person (AGL-4038): handed over at the sale, no parcel.\n source: posHardwareOrderSource(order),\n discountCents: order.discountCents ?? 0,\n /** Readers still to set up, for an in-person order that took serials. */\n readersToSetUp: (order.units ?? []).filter((unit) => !unit.readerId).length,\n refundedCents: order.refundedCents ?? 0,\n /** The buyer's return request and what was decided, without who asked. */\n returnRequest: order.returnRequest\n ? { state: order.returnRequest.state, requestedAtMs: order.returnRequest.requestedAtMs, note: order.returnRequest.note }\n : null,\n }\n}\n\nexport type MerchantHardwareOrderView = ReturnType<typeof merchantHardwareOrderView>\n\n/** The POS settings page of a site, as an absolute console URL. */\nexport async function posSettingsUrl(hostId: string): Promise<string> {\n return hostConsoleUrl(hostId, `/${hostId}/products/pos`)\n}\n\n/** `base` with `query` added before any `#fragment`, then `#hash`. */\nexport function withQueryAndHash(base: string, query: string, hash: string): string {\n const [path] = base.split('#')\n const joiner = path.includes('?') ? '&' : '?'\n return `${path}${joiner}${query}#${hash}`\n}\n\n\n/**\n * The readers this workspace bought in person that are not set up yet\n * (AGL-4038): whether its plan includes the point of sale, its stores and\n * whether each can take a reader, and each order with what it waits for.\n * Nothing at all while the in-person sale is off.\n */\nexport async function waitingInPersonReaders(orgId: string, hostId: string) {\n if (!posHardwareInPersonConfig() || !orgId) return { posPlan: false, stores: [], orders: [] }\n const firestore = firebaseAdmin.app().firestore()\n const [orders, org, hosts] = await Promise.all([\n hardwareOrdersRef(orgId)\n .where('attachment.state', '==', 'attached')\n .where('status', '==', 'delivered')\n .limit(20)\n .get(),\n firestore.collection('orgs').doc(orgId).get(),\n firestore.collection('hosts').where('orgId', '==', orgId).limit(20).get(),\n ])\n if (!orders.docs.length) return { posPlan: false, stores: [], orders: [] }\n const stores = await Promise.all(\n hosts.docs.map(async (doc: any) => {\n const id = String(doc.id)\n const [terminal, setupUrl] = await Promise.all([\n firestore.collection('hosts').doc(id).collection('terminal').doc('config').get(),\n posSettingsUrl(id),\n ])\n return {\n hostId: id,\n name: String(doc.get('name') ?? doc.get('title') ?? id),\n hasLocation: Boolean(terminal.exists && terminal.get('stripeLocationId')),\n setupUrl: `${setupUrl.split('#')[0]}#pos-devices`,\n }\n }),\n )\n return {\n posPlan: Aglyn.checkEntitlement(org.data() as never, 'pos'),\n stores,\n // Every store's, this store's first: a reader waits wherever the\n // workspace's people look.\n orders: orders.docs\n .map((doc: any) => ({ id: String(doc.id), order: doc.data() as PosHardwareOrder }))\n .filter(({ order }) => order.source === 'in_person')\n .sort((a, b) => Number(b.order.hostId === hostId) - Number(a.order.hostId === hostId))\n .map(({ id, order }) => ({\n ...merchantHardwareOrderView(id, order),\n hostId: order.hostId,\n serialsTaken: (order.units ?? []).filter((unit) => unit.serialNumber && !unit.readerId).length,\n })),\n }\n}\n\nexport const posHardwareHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = posRequestBody(req)\n const hostId = String(body['hostId'] ?? '')\n const action = String(body['action'] ?? '')\n // BUYING IS ITS OWN KEY (AGL-4047): anyone who works the register or may\n // buy hardware sees what the shop offers and what this site ordered, and\n // only a member holding \"Buy point of sale hardware\" — which follows\n // `managePos` until a role or the member sets it, and may be granted\n // without it — starts a checkout that the workspace pays for.\n //\n // A READER BOUGHT IN PERSON (AGL-4038): `waiting` is read without the\n // point of sale plan, because a workspace without it is exactly the one\n // that must be told to add it first; choosing its store and marking it set\n // up are setting up devices (`posDevices`) on the store named.\n const settingUp = action === 'choose-store' || action === 'mark-set-up'\n const gate = await authorizePosStaff(\n req,\n hostId,\n action === 'checkout' ? 'posBuyHardware' : settingUp ? 'posDevices' : undefined,\n mayVisitPosHardwareShop,\n // A workspace whose plan lost the point of sale still sees what it bought\n // and may ask to return a reader bought in person.\n action === 'waiting' || action === 'orders' || action === 'request-return' ? { planRequired: false } : {},\n )\n if ('error' in gate) return res.status(gate.status).json({ error: gate.error })\n const staff = gate.staff\n const config = posHardwareConfig()\n try {\n switch (action) {\n case 'waiting':\n return res.status(200).json(await waitingInPersonReaders(staff.orgId, staff.hostId))\n case 'request-return': {\n const returns = await import('./pos-hardware-returns')\n const orderId = String(body['orderId'] ?? '')\n try {\n const order = await returns.requestPosHardwareReturn({\n orgId: staff.orgId,\n orderId,\n uid: staff.uid,\n reason: body['reason'],\n })\n return res.status(200).json({ ok: true, order: merchantHardwareOrderView(orderId, order) })\n } catch (error) {\n if (error instanceof returns.PosHardwareReturnRefusal) {\n return res.status(error.status).json({ error: error.message })\n }\n throw error\n }\n }\n case 'choose-store':\n case 'mark-set-up': {\n const readers = await import('./pos-hardware-readers')\n const orderId = String(body['orderId'] ?? '')\n try {\n const order =\n action === 'choose-store'\n ? await readers.choosePosHardwareStore({ orgId: staff.orgId, orderId, hostId: staff.hostId })\n : await readers.markPosHardwareSetUp({ orgId: staff.orgId, orderId })\n return res.status(200).json({ ok: true, order: merchantHardwareOrderView(orderId, order) })\n } catch (error) {\n if (error instanceof readers.PosHardwareReaderRefusal) {\n return res.status(error.status).json({ error: error.message })\n }\n throw error\n }\n }\n case 'catalog':\n if (!config) return res.status(200).json({ available: false })\n return res.status(200).json({\n available: true,\n offers: posHardwareOffers(config),\n shipping: config.shipping.map((option) => ({\n method: option.method,\n label: POS_HARDWARE_SHIPPING_LABELS[option.method],\n cents: option.cents,\n })),\n automaticTax: config.automaticTax,\n shipCountries: POS_HARDWARE_SHIP_COUNTRIES,\n })\n case 'orders': {\n // This site's orders, and the readers bought in person for the\n // workspace that wait for a store to be chosen at setup (AGL-4038).\n // A sale on the selling workspace's own To attach list is never one.\n const [site, workspace] = await Promise.all([\n hardwareOrdersRef(staff.orgId).where('hostId', '==', staff.hostId).orderBy('createdAtMs', 'desc').limit(50).get(),\n hardwareOrdersRef(staff.orgId)\n .where('hostId', '==', '')\n .where('attachment.state', '==', 'attached')\n .orderBy('createdAtMs', 'desc')\n .limit(50)\n .get(),\n ])\n const orders = [...site.docs, ...workspace.docs]\n .map((doc: any) => merchantHardwareOrderView(String(doc.id), doc.data() as PosHardwareOrder))\n .sort((a, b) => b.createdAtMs - a.createdAtMs)\n .slice(0, 50)\n return res.status(200).json({ orders })\n }\n case 'checkout': {\n if (!config) return res.status(404).json({ error: 'The hardware shop is not available.' })\n const attemptKey = posIdempotencyKey(req)\n if (!attemptKey) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n if (!staff.orgId) return res.status(409).json({ error: 'This site has no workspace.' })\n const priced = pricePosHardwareCart(config, body['lines'])\n if ('error' in priced) return res.status(400).json({ error: priced.error })\n const method = body['shippingMethod']\n const shipping = isPosHardwareShippingMethod(method)\n ? config.shipping.find((option) => option.method === method)\n : undefined\n if (!shipping) return res.status(400).json({ error: 'Choose a shipping speed.' })\n\n const orderId = posHardwareOrderId(staff.orgId, staff.hostId, attemptKey)\n const billing = await readOrgBilling(staff.orgId).catch(() => ({}))\n const customer = String((billing as { stripeCustomerId?: unknown }).stripeCustomerId ?? '').trim()\n const base = await posSettingsUrl(staff.hostId)\n const params: Record<string, string | number | boolean> = {\n mode: 'payment',\n client_reference_id: orderId,\n success_url: withQueryAndHash(base, 'hardwareOrder=placed', POS_HARDWARE_ANCHOR),\n cancel_url: withQueryAndHash(base, 'hardwareOrder=canceled', POS_HARDWARE_ANCHOR),\n 'payment_method_types[0]': 'card',\n 'shipping_address_collection[allowed_countries][0]': POS_HARDWARE_SHIP_COUNTRIES[0],\n 'phone_number_collection[enabled]': true,\n 'shipping_options[0][shipping_rate_data][type]': 'fixed_amount',\n 'shipping_options[0][shipping_rate_data][display_name]': POS_HARDWARE_SHIPPING_LABELS[shipping.method],\n 'shipping_options[0][shipping_rate_data][fixed_amount][amount]': shipping.cents,\n 'shipping_options[0][shipping_rate_data][fixed_amount][currency]': POS_HARDWARE_CURRENCY,\n 'metadata[type]': POS_HARDWARE_METADATA_TYPE,\n 'metadata[orderId]': orderId,\n 'metadata[orgId]': staff.orgId,\n 'metadata[hostId]': staff.hostId,\n 'metadata[uid]': staff.uid,\n 'metadata[lines]': encodePosHardwareLines(priced.lines),\n 'metadata[shippingMethod]': shipping.method,\n 'metadata[shippingCents]': shipping.cents,\n 'metadata[subtotalCents]': priced.subtotalCents,\n 'payment_intent_data[description]': `Card reader order ${posHardwareOrderNumber(orderId)}`,\n 'payment_intent_data[metadata][type]': POS_HARDWARE_METADATA_TYPE,\n 'payment_intent_data[metadata][orderId]': orderId,\n 'payment_intent_data[metadata][orgId]': staff.orgId,\n ...(customer ? { customer } : {}),\n ...(config.automaticTax\n ? {\n 'automatic_tax[enabled]': true,\n 'shipping_options[0][shipping_rate_data][tax_behavior]': 'exclusive',\n // A returning workspace's saved address is kept up to date\n // from what Checkout collects, which automatic tax requires.\n ...(customer ? { 'customer_update[shipping]': 'auto' } : {}),\n }\n : {}),\n }\n priced.lines.forEach((line, index) => {\n const sku = posHardwareSku(line.sku)\n params[`line_items[${index}][quantity]`] = line.quantity\n // A literal, not POS_HARDWARE_CURRENCY: check:facilitator-charge-shape\n // reads Stripe Tax beside a usd line item only when it says so (AGL-1956).\n params[`line_items[${index}][price_data][currency]`] = 'usd'\n params[`line_items[${index}][price_data][unit_amount]`] = line.unitCents\n params[`line_items[${index}][price_data][product_data][name]`] = line.name\n if (sku) params[`line_items[${index}][price_data][product_data][description]`] = sku.use\n params[`line_items[${index}][price_data][product_data][metadata][sku]`] = line.sku\n if (config.automaticTax) params[`line_items[${index}][price_data][tax_behavior]`] = 'exclusive'\n })\n const created = await posStripe('POST', 'checkout/sessions', {\n params,\n idempotencyKey: `pos-hw-checkout-${orderId}`,\n })\n const url = String(created.body?.url ?? '')\n if (!created.ok || !url) {\n console.error('[pos-hardware] checkout refused', created.status, created.body?.error?.code)\n return res.status(502).json({ error: 'Checkout could not be started. Try again in a moment.' })\n }\n return res.status(200).json({ url, orderId })\n }\n default:\n return res.status(400).json({ error: 'Unknown action' })\n }\n } catch (error) {\n console.error('[pos-hardware]', action, error)\n return res.status(500).json({ error: 'The hardware shop could not answer' })\n }\n}\n"],"names":["createHash","Aglyn","firebaseAdmin","readOrgBilling","hostConsoleUrl","encodePosHardwareLines","isPosHardwareShippingMethod","POS_HARDWARE_ANCHOR","parsePosHardwareConfig","parsePosHardwareInPersonConfig","POS_HARDWARE_CURRENCY","POS_HARDWARE_METADATA_TYPE","POS_HARDWARE_ORDERS_COLLECTION","POS_HARDWARE_SALES_COLLECTION","POS_HARDWARE_SHIP_COUNTRIES","POS_HARDWARE_SHIPPING_LABELS","posHardwareOffers","posHardwareOrderSource","posHardwareSku","pricePosHardwareCart","mayVisitPosHardwareShop","authorizePosStaff","posIdempotencyKey","posRequestBody","posStripe","posTerminalAvailable","posHardwareConfig","env","process","posHardwareInPersonConfig","isPosHardwareSellerStore","config","hostId","orgId","Boolean","sellerHostId","sellerOrgId","posHardwareInPersonOrderId","registerOrderId","update","digest","slice","posHardwareOrderId","attemptKey","posHardwareOrderNumber","orderId","replace","toUpperCase","hardwareOrdersRef","app","firestore","collection","doc","posHardwareSaleRef","merchantHardwareOrderView","id","order","number","status","lines","map","line","sku","name","quantity","unitCents","lineCents","subtotalCents","shippingCents","shipping","cents","shippingLabel","label","taxCents","totalCents","tracking","createdAtMs","updatedAtMs","source","discountCents","readersToSetUp","units","filter","unit","readerId","length","refundedCents","returnRequest","state","requestedAtMs","note","posSettingsUrl","withQueryAndHash","base","query","hash","path","split","joiner","includes","waitingInPersonReaders","posPlan","stores","orders","org","hosts","Promise","all","where","limit","get","docs","String","terminal","setupUrl","hasLocation","exists","checkEntitlement","data","sort","a","b","Number","serialsTaken","serialNumber","posHardwareHandler","req","res","body","method","json","error","action","settingUp","gate","undefined","planRequired","staff","returns","requestPosHardwareReturn","uid","reason","ok","PosHardwareReturnRefusal","message","readers","choosePosHardwareStore","markPosHardwareSetUp","PosHardwareReaderRefusal","available","offers","option","automaticTax","shipCountries","site","workspace","orderBy","created","priced","find","billing","catch","customer","stripeCustomerId","trim","params","mode","client_reference_id","success_url","cancel_url","forEach","index","use","idempotencyKey","url","console","code"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,SAAQ;AACnC,YAAYC,WAAW,sBAAqB;AAE5C,SAASC,aAAa,EAAEC,cAAc,QAAQ,2BAA0B;AACxE,SAASC,cAAc,QAAQ,oDAAmD;AAClF,SACEC,sBAAsB,EACtBC,2BAA2B,EAC3BC,mBAAmB,EACnBC,sBAAsB,EACtBC,8BAA8B,EAC9BC,qBAAqB,EACrBC,0BAA0B,EAC1BC,8BAA8B,EAC9BC,6BAA6B,EAC7BC,2BAA2B,EAC3BC,4BAA4B,EAC5BC,iBAAiB,EACjBC,sBAAsB,EACtBC,cAAc,EACdC,oBAAoB,QAIf,2BAAuB;AAC9B,SAASC,uBAAuB,QAAQ,iCAA6B;AACrE,SAASC,iBAAiB,EAAEC,iBAAiB,EAAEC,cAAc,QAAQ,gBAAY;AACjF,SAASC,SAAS,EAAEC,oBAAoB,QAAQ,kBAAc;AAE9D;;;;;;;;;;;;;;;;;;;;2CAoB2C,GAE3C,0EAA0E,GAC1E,OAAO,SAASC,kBACdC,MAA0CC,QAAQD,GAAG;IAErD,yEAAyE;IACzE,iEAAiE;IACjE,IAAI,CAACF,wBAAwB,OAAO;IACpC,OAAOjB,uBAAuBmB;AAChC;AAEA;;;;;CAKC,GACD,OAAO,SAASE,0BACdF,MAA0CC,QAAQD,GAAG;IAErD,OAAOlB,+BAA+BkB;AACxC;AAEA,8EAA8E,GAC9E,OAAO,SAASG,yBACdC,MAAwC,EACxCC,MAAc,EACdC,KAAa;IAEb,OAAOC,QAAQH,WAAWA,CAAAA,0BAAAA,OAAQI,YAAY,MAAKH,UAAUD,CAAAA,0BAAAA,OAAQK,WAAW,MAAKH;AACvF;AAEA;;;CAGC,GACD,OAAO,SAASI,2BAA2BL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cesContent":["/**\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 { createHash } from 'crypto'\nimport { readClientIp } from '@aglyn/aglyn/app-utils/request-ip'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, readOrgBilling } from '@aglyn/tenant-data-admin'\nimport { hostConsoleUrl } from '@aglyn/tenant-data-admin/server/host-console-link'\nimport {\n isPosHardwareSellerStoreSale,\n encodePosHardwareLines,\n isPosHardwareShippingMethod,\n POS_HARDWARE_ANCHOR,\n parsePosHardwareConfig,\n parsePosHardwareInPersonConfig,\n POS_HARDWARE_CURRENCY,\n POS_HARDWARE_METADATA_TYPE,\n POS_HARDWARE_ORDERS_COLLECTION,\n POS_HARDWARE_SALES_COLLECTION,\n POS_HARDWARE_SHIP_COUNTRIES,\n POS_HARDWARE_SHIPPING_LABELS,\n POS_HARDWARE_SKUS,\n POS_HARDWARE_TAX_CODE,\n posHardwareOffers,\n posHardwareOrderSource,\n posHardwareSku,\n pricePosHardwareCart,\n type PosHardwareConfig,\n type PosHardwareInPersonConfig,\n type PosHardwareOrder,\n type PosHardwareSkuId,\n} from '../model/pos-hardware'\nimport {\n POS_HARDWARE_TERMS_REQUIRED,\n posHardwareTermsConfirmed,\n posHardwareTermsMetadata,\n} from '../model/pos-hardware-terms'\nimport { mayVisitPosHardwareShop } from '../model/plugin-permissions'\nimport { authorizePosStaff, posIdempotencyKey, posRequestBody } from './pos-auth'\nimport { posStripe, posTerminalAvailable } from './pos-stripe'\n\n/*==========================================\n * `POST /api/commerce/pos-hardware` (AGL-4038): the merchant's half of the\n * POS hardware shop, behind the Hardware card on Products → Point of sale.\n *\n * catalog what is on offer and at what price, or `available: false`\n * checkout a Stripe Checkout Session for the basket, on the PLATFORM\n * orders this site's hardware orders, newest first\n *\n * Gated like the register (`authorizePosStaff`) but on ANY plan (AGL-4038):\n * a workspace buys its readers first and adds the point of sale when it sets\n * them up. The readers it sells are the register's, with one difference (AGL-4047):\n * the shop admits whoever works the register (`managePos`) AND whoever may\n * buy hardware (`posBuyHardware`), which stands on its own — a bookkeeper\n * with no register orders the store's readers. A checkout needs\n * `posBuyHardware`; seeing the catalog and the site's orders needs either.\n *\n * THE SALE IS THE PLATFORM'S. The session is created with the platform key\n * and NO connected account, `transfer_data` or application fee: the merchant\n * is the buyer here, and the platform is the seller of record that places\n * the order with Stripe. The order document is written by the webhook once\n * Stripe says the session is paid (`pos-hardware-webhook.ts`), never here.\n *=========================================*/\n\n/** The shop's config from this deployment, or `null` while it is hidden. */\nexport function posHardwareConfig(\n env: Record<string, string | undefined> = process.env,\n): PosHardwareConfig | null {\n // A reader the platform cannot yet take payments on is not for sale: the\n // shop opens only where the register offers card readers at all.\n if (!posTerminalAvailable()) return null\n return parsePosHardwareConfig(env)\n}\n\n/**\n * The platform's own store that sells hardware in person (AGL-4038), or\n * `null` while that is off. Read like the shop's other figures; a store is\n * the seller only when BOTH its id and its workspace's match, so a site moved\n * to another workspace stops selling hardware rather than selling it for them.\n */\nexport function posHardwareInPersonConfig(\n env: Record<string, string | undefined> = process.env,\n): PosHardwareInPersonConfig | null {\n return parsePosHardwareInPersonConfig(env)\n}\n\n/**\n * The price each hardware item is listed at in the platform's own store\n * (AGL-4038), in cents: an active product there whose `hardwareSku` names\n * the item, at its first variant's price. Where two products name one item,\n * the lower price, so no page the store shows quotes less than the shop\n * charges. Empty while no seller store is configured. A failed read throws:\n * the shop does not quote a price it cannot check against the store's.\n */\nexport async function posHardwareListedCents(\n inPerson: PosHardwareInPersonConfig | null = posHardwareInPersonConfig(),\n): Promise<Partial<Record<PosHardwareSkuId, number>>> {\n if (!inPerson) return {}\n const snapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(inPerson.sellerHostId)\n .collection('products')\n .where(\n 'hardwareSku',\n 'in',\n POS_HARDWARE_SKUS.map((sku) => sku.id),\n )\n .get()\n const listed: Partial<Record<PosHardwareSkuId, number>> = {}\n for (const doc of snapshot.docs as Array<{ data: () => Record<string, unknown> }>) {\n const product = doc.data()\n const sku = posHardwareSku(String(product['hardwareSku'] ?? ''))\n if (!sku || (product['status'] ?? 'active') !== 'active') continue\n const variants = Array.isArray(product['variants']) ? (product['variants'] as Array<{ priceUsd?: unknown }>) : []\n const priceUsd = Number(variants.length ? variants[0]?.priceUsd : product['priceUsd'])\n if (!Number.isFinite(priceUsd) || priceUsd <= 0) continue\n const cents = Math.round(priceUsd * 100)\n listed[sku.id] = Math.min(listed[sku.id] ?? cents, cents)\n }\n return listed\n}\n\n/** The shop's config with the platform's own store's listed prices, or `null` while it is hidden. */\nexport async function posHardwarePricedConfig(): Promise<PosHardwareConfig | null> {\n const config = posHardwareConfig()\n if (!config) return null\n return { ...config, listedCents: await posHardwareListedCents() }\n}\n\n/** Whether a store, owned by `orgId`, is the platform's own hardware seller. */\nexport function isPosHardwareSellerStore(\n config: PosHardwareInPersonConfig | null,\n hostId: string,\n orgId: string,\n): config is PosHardwareInPersonConfig {\n return Boolean(config) && config?.sellerHostId === hostId && config?.sellerOrgId === orgId\n}\n\n/**\n * An in-person order's id, from the register sale it came from: one register\n * sale is one hardware order however often its completion is told.\n */\nexport function posHardwareInPersonOrderId(hostId: string, registerOrderId: string): string {\n return `hw_${createHash('sha256').update(`pos:${hostId}:${registerOrderId}`).digest('hex').slice(0, 20)}`\n}\n\n/** The order's id, derived from the attempt so a repeated press is one order. */\nexport function posHardwareOrderId(orgId: string, hostId: string, attemptKey: string): string {\n return `hw_${createHash('sha256').update(`${orgId}:${hostId}:${attemptKey}`).digest('hex').slice(0, 20)}`\n}\n\n/** The number a person reads: `HW-` and six characters of the id. */\nexport function posHardwareOrderNumber(orderId: string): string {\n return `HW-${orderId.replace(/^hw_/, '').slice(0, 6).toUpperCase()}`\n}\n\nexport function hardwareOrdersRef(orgId: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(orgId)\n .collection(POS_HARDWARE_ORDERS_COLLECTION)\n}\n\n/**\n * `posHardwareSales/{orderId}`, the retained sale record beside each order\n * (see `PosHardwareSaleRecord`). Top-level on purpose: the workspace erasure\n * cannot reach it.\n */\nexport function posHardwareSaleRef(orderId: string) {\n return firebaseAdmin.app().firestore().collection(POS_HARDWARE_SALES_COLLECTION).doc(orderId)\n}\n\n/** An order as the merchant's card shows it: no Stripe ids, no staff notes. */\nexport function merchantHardwareOrderView(id: string, order: PosHardwareOrder) {\n return {\n id,\n number: posHardwareOrderNumber(id),\n status: order.status,\n lines: (order.lines ?? []).map((line) => ({\n sku: line.sku,\n name: line.name,\n quantity: line.quantity,\n unitCents: line.unitCents,\n lineCents: line.lineCents,\n })),\n subtotalCents: order.subtotalCents ?? 0,\n shippingCents: order.shipping?.cents ?? 0,\n shippingLabel: order.shipping?.label ?? '',\n taxCents: order.taxCents ?? 0,\n totalCents: order.totalCents ?? 0,\n tracking: order.tracking ?? null,\n createdAtMs: order.createdAtMs ?? 0,\n updatedAtMs: order.updatedAtMs ?? order.createdAtMs ?? 0,\n // Bought in person (AGL-4038): handed over at the sale, no parcel.\n source: posHardwareOrderSource(order),\n discountCents: order.discountCents ?? 0,\n /** Readers still to set up, for an in-person order that took serials. */\n readersToSetUp: (order.units ?? []).filter((unit) => !unit.readerId).length,\n refundedCents: order.refundedCents ?? 0,\n /** The buyer's return request and what was decided, without who asked. */\n returnRequest: order.returnRequest\n ? { state: order.returnRequest.state, requestedAtMs: order.returnRequest.requestedAtMs, note: order.returnRequest.note }\n : null,\n }\n}\n\nexport type MerchantHardwareOrderView = ReturnType<typeof merchantHardwareOrderView>\n\n/** The POS settings page of a site, as an absolute console URL. */\nexport async function posSettingsUrl(hostId: string): Promise<string> {\n return hostConsoleUrl(hostId, `/${hostId}/products/pos`)\n}\n\n/** `base` with `query` added before any `#fragment`, then `#hash`. */\nexport function withQueryAndHash(base: string, query: string, hash: string): string {\n const [path] = base.split('#')\n const joiner = path.includes('?') ? '&' : '?'\n return `${path}${joiner}${query}#${hash}`\n}\n\n\n/**\n * The readers this workspace bought in person that are not set up yet\n * (AGL-4038): whether its plan includes the point of sale, its stores and\n * whether each can take a reader, and each order with what it waits for.\n * Nothing at all while the in-person sale is off.\n */\nexport async function waitingInPersonReaders(orgId: string, hostId: string) {\n if (!posHardwareInPersonConfig() || !orgId) return { posPlan: false, stores: [], orders: [] }\n const firestore = firebaseAdmin.app().firestore()\n const [orders, org, hosts] = await Promise.all([\n hardwareOrdersRef(orgId)\n .where('attachment.state', '==', 'attached')\n .where('status', '==', 'delivered')\n .limit(20)\n .get(),\n firestore.collection('orgs').doc(orgId).get(),\n firestore.collection('hosts').where('orgId', '==', orgId).limit(20).get(),\n ])\n if (!orders.docs.length) return { posPlan: false, stores: [], orders: [] }\n const stores = await Promise.all(\n hosts.docs.map(async (doc: any) => {\n const id = String(doc.id)\n const [terminal, setupUrl] = await Promise.all([\n firestore.collection('hosts').doc(id).collection('terminal').doc('config').get(),\n posSettingsUrl(id),\n ])\n return {\n hostId: id,\n name: String(doc.get('name') ?? doc.get('title') ?? id),\n hasLocation: Boolean(terminal.exists && terminal.get('stripeLocationId')),\n setupUrl: `${setupUrl.split('#')[0]}#pos-devices`,\n }\n }),\n )\n return {\n posPlan: Aglyn.checkEntitlement(org.data() as never, 'pos'),\n stores,\n // Every store's, this store's first: a reader waits wherever the\n // workspace's people look.\n orders: orders.docs\n .map((doc: any) => ({ id: String(doc.id), order: doc.data() as PosHardwareOrder }))\n // Bought from the platform's own store, at an event or online (AGL-4038).\n .filter(({ order }) => isPosHardwareSellerStoreSale(order))\n .sort((a, b) => Number(b.order.hostId === hostId) - Number(a.order.hostId === hostId))\n .map(({ id, order }) => ({\n ...merchantHardwareOrderView(id, order),\n hostId: order.hostId,\n serialsTaken: (order.units ?? []).filter((unit) => unit.serialNumber && !unit.readerId).length,\n })),\n }\n}\n\nconst LISTED_READ_FAILED = Symbol('listed-read-failed')\n\nfunction listedReadFailed(error: unknown): typeof LISTED_READ_FAILED {\n console.error('[pos-hardware] the store\\'s listed prices could not be read', error)\n return LISTED_READ_FAILED\n}\n\nexport const posHardwareHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = posRequestBody(req)\n const hostId = String(body['hostId'] ?? '')\n const action = String(body['action'] ?? '')\n // BUYING IS ITS OWN KEY (AGL-4047): anyone who works the register or may\n // buy hardware sees what the shop offers and what this site ordered, and\n // only a member holding \"Buy point of sale hardware\" — which follows\n // `managePos` until a role or the member sets it, and may be granted\n // without it — starts a checkout that the workspace pays for.\n //\n // ANYONE CAN BUY (AGL-4038): browsing, checking out, the orders, a return\n // request and the readers waiting to be set up are open whatever the\n // workspace's plan. A reader takes payments at the register, which comes\n // with the point of sale, so the card, a delivered order and the register\n // prompt to add it; the key above still decides who may buy. Setting a\n // reader up — choosing its store, marking it set up — is setting up\n // devices (`posDevices`) on the store named, and asks the plan.\n const settingUp = action === 'choose-store' || action === 'mark-set-up'\n const gate = await authorizePosStaff(\n req,\n hostId,\n action === 'checkout' ? 'posBuyHardware' : settingUp ? 'posDevices' : undefined,\n mayVisitPosHardwareShop,\n { planRequired: settingUp },\n )\n if ('error' in gate) return res.status(gate.status).json({ error: gate.error })\n const staff = gate.staff\n // Priced by the store's listed prices only where a price is quoted or charged.\n const config = action === 'catalog' || action === 'checkout' ? await posHardwarePricedConfig().catch(listedReadFailed) : posHardwareConfig()\n if (config === LISTED_READ_FAILED) {\n return res.status(503).json({ error: 'The hardware shop could not check its prices. Try again in a moment.' })\n }\n try {\n switch (action) {\n case 'waiting':\n return res.status(200).json(await waitingInPersonReaders(staff.orgId, staff.hostId))\n case 'request-return': {\n const returns = await import('./pos-hardware-returns')\n const orderId = String(body['orderId'] ?? '')\n try {\n const order = await returns.requestPosHardwareReturn({\n orgId: staff.orgId,\n orderId,\n uid: staff.uid,\n reason: body['reason'],\n })\n return res.status(200).json({ ok: true, order: merchantHardwareOrderView(orderId, order) })\n } catch (error) {\n if (error instanceof returns.PosHardwareReturnRefusal) {\n return res.status(error.status).json({ error: error.message })\n }\n throw error\n }\n }\n case 'choose-store':\n case 'mark-set-up': {\n const readers = await import('./pos-hardware-readers')\n const orderId = String(body['orderId'] ?? '')\n try {\n const order =\n action === 'choose-store'\n ? await readers.choosePosHardwareStore({ orgId: staff.orgId, orderId, hostId: staff.hostId })\n : await readers.markPosHardwareSetUp({ orgId: staff.orgId, orderId })\n return res.status(200).json({ ok: true, order: merchantHardwareOrderView(orderId, order) })\n } catch (error) {\n if (error instanceof readers.PosHardwareReaderRefusal) {\n return res.status(error.status).json({ error: error.message })\n }\n throw error\n }\n }\n case 'catalog':\n if (!config) return res.status(200).json({ available: false })\n return res.status(200).json({\n available: true,\n offers: posHardwareOffers(config),\n shipping: config.shipping.map((option) => ({\n method: option.method,\n label: POS_HARDWARE_SHIPPING_LABELS[option.method],\n cents: option.cents,\n })),\n automaticTax: config.automaticTax,\n shipCountries: POS_HARDWARE_SHIP_COUNTRIES,\n })\n case 'orders': {\n // This site's orders, and the readers bought in person for the\n // workspace that wait for a store to be chosen at setup (AGL-4038).\n // A sale on the selling workspace's own To attach list is never one.\n const [site, workspace] = await Promise.all([\n hardwareOrdersRef(staff.orgId).where('hostId', '==', staff.hostId).orderBy('createdAtMs', 'desc').limit(50).get(),\n hardwareOrdersRef(staff.orgId)\n .where('hostId', '==', '')\n .where('attachment.state', '==', 'attached')\n .orderBy('createdAtMs', 'desc')\n .limit(50)\n .get(),\n ])\n const orders = [...site.docs, ...workspace.docs]\n .map((doc: any) => merchantHardwareOrderView(String(doc.id), doc.data() as PosHardwareOrder))\n .sort((a, b) => b.createdAtMs - a.createdAtMs)\n .slice(0, 50)\n return res.status(200).json({ orders })\n }\n case 'checkout': {\n if (!config) return res.status(404).json({ error: 'The hardware shop is not available.' })\n const attemptKey = posIdempotencyKey(req)\n if (!attemptKey) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n if (!staff.orgId) return res.status(409).json({ error: 'This site has no workspace.' })\n const priced = pricePosHardwareCart(config, body['lines'])\n if ('error' in priced) return res.status(400).json({ error: priced.error })\n const method = body['shippingMethod']\n const shipping = isPosHardwareShippingMethod(method)\n ? config.shipping.find((option) => option.method === method)\n : undefined\n if (!shipping) return res.status(400).json({ error: 'Choose a shipping speed.' })\n // The terms of sale and business use, both ticked (AGL-4038).\n if (!posHardwareTermsConfirmed(body['hardwareTerms'])) {\n return res.status(400).json({ error: POS_HARDWARE_TERMS_REQUIRED, needsHardwareTerms: true })\n }\n const terms = posHardwareTermsMetadata({\n ip: readClientIp(req.headers as never) ?? null,\n userAgent: String(req.headers?.['user-agent'] ?? '') || null,\n })\n\n const orderId = posHardwareOrderId(staff.orgId, staff.hostId, attemptKey)\n const billing = await readOrgBilling(staff.orgId).catch(() => ({}))\n const customer = String((billing as { stripeCustomerId?: unknown }).stripeCustomerId ?? '').trim()\n const base = await posSettingsUrl(staff.hostId)\n const params: Record<string, string | number | boolean> = {\n mode: 'payment',\n client_reference_id: orderId,\n success_url: withQueryAndHash(base, 'hardwareOrder=placed', POS_HARDWARE_ANCHOR),\n cancel_url: withQueryAndHash(base, 'hardwareOrder=canceled', POS_HARDWARE_ANCHOR),\n 'payment_method_types[0]': 'card',\n 'shipping_address_collection[allowed_countries][0]': POS_HARDWARE_SHIP_COUNTRIES[0],\n 'phone_number_collection[enabled]': true,\n 'shipping_options[0][shipping_rate_data][type]': 'fixed_amount',\n 'shipping_options[0][shipping_rate_data][display_name]': POS_HARDWARE_SHIPPING_LABELS[shipping.method],\n 'shipping_options[0][shipping_rate_data][fixed_amount][amount]': shipping.cents,\n 'shipping_options[0][shipping_rate_data][fixed_amount][currency]': POS_HARDWARE_CURRENCY,\n 'metadata[type]': POS_HARDWARE_METADATA_TYPE,\n 'metadata[orderId]': orderId,\n 'metadata[orgId]': staff.orgId,\n 'metadata[hostId]': staff.hostId,\n 'metadata[uid]': staff.uid,\n 'metadata[lines]': encodePosHardwareLines(priced.lines),\n 'metadata[shippingMethod]': shipping.method,\n 'metadata[shippingCents]': shipping.cents,\n 'metadata[subtotalCents]': priced.subtotalCents,\n ...Object.fromEntries(Object.entries(terms).map(([key, value]) => [`metadata[${key}]`, value])),\n 'payment_intent_data[description]': `Card reader order ${posHardwareOrderNumber(orderId)}`,\n 'payment_intent_data[metadata][type]': POS_HARDWARE_METADATA_TYPE,\n 'payment_intent_data[metadata][orderId]': orderId,\n 'payment_intent_data[metadata][orgId]': staff.orgId,\n ...(customer ? { customer } : {}),\n ...(config.automaticTax\n ? {\n 'automatic_tax[enabled]': true,\n 'shipping_options[0][shipping_rate_data][tax_behavior]': 'exclusive',\n // A returning workspace's saved address is kept up to date\n // from what Checkout collects, which automatic tax requires.\n ...(customer ? { 'customer_update[shipping]': 'auto' } : {}),\n }\n : {}),\n }\n priced.lines.forEach((line, index) => {\n const sku = posHardwareSku(line.sku)\n params[`line_items[${index}][quantity]`] = line.quantity\n // A literal, not POS_HARDWARE_CURRENCY: check:facilitator-charge-shape\n // reads Stripe Tax beside a usd line item only when it says so (AGL-1956).\n params[`line_items[${index}][price_data][currency]`] = 'usd'\n params[`line_items[${index}][price_data][unit_amount]`] = line.unitCents\n params[`line_items[${index}][price_data][product_data][name]`] = line.name\n if (sku) params[`line_items[${index}][price_data][product_data][description]`] = sku.use\n params[`line_items[${index}][price_data][product_data][metadata][sku]`] = line.sku\n // Taxed as the physical good it is, never as the account's default (software).\n params[`line_items[${index}][price_data][product_data][tax_code]`] = POS_HARDWARE_TAX_CODE\n if (config.automaticTax) params[`line_items[${index}][price_data][tax_behavior]`] = 'exclusive'\n })\n const created = await posStripe('POST', 'checkout/sessions', {\n params,\n idempotencyKey: `pos-hw-checkout-${orderId}`,\n })\n const url = String(created.body?.url ?? '')\n if (!created.ok || !url) {\n console.error('[pos-hardware] checkout refused', created.status, created.body?.error?.code)\n return res.status(502).json({ error: 'Checkout could not be started. Try again in a moment.' })\n }\n return res.status(200).json({ url, orderId })\n }\n default:\n return res.status(400).json({ error: 'Unknown action' })\n }\n } catch (error) {\n console.error('[pos-hardware]', action, error)\n return res.status(500).json({ error: 'The hardware shop could not answer' })\n }\n}\n"],"names":["createHash","readClientIp","Aglyn","firebaseAdmin","readOrgBilling","hostConsoleUrl","isPosHardwareSellerStoreSale","encodePosHardwareLines","isPosHardwareShippingMethod","POS_HARDWARE_ANCHOR","parsePosHardwareConfig","parsePosHardwareInPersonConfig","POS_HARDWARE_CURRENCY","POS_HARDWARE_METADATA_TYPE","POS_HARDWARE_ORDERS_COLLECTION","POS_HARDWARE_SALES_COLLECTION","POS_HARDWARE_SHIP_COUNTRIES","POS_HARDWARE_SHIPPING_LABELS","POS_HARDWARE_SKUS","POS_HARDWARE_TAX_CODE","posHardwareOffers","posHardwareOrderSource","posHardwareSku","pricePosHardwareCart","POS_HARDWARE_TERMS_REQUIRED","posHardwareTermsConfirmed","posHardwareTermsMetadata","mayVisitPosHardwareShop","authorizePosStaff","posIdempotencyKey","posRequestBody","posStripe","posTerminalAvailable","posHardwareConfig","env","process","posHardwareInPersonConfig","posHardwareListedCents","inPerson","snapshot","app","firestore","collection","doc","sellerHostId","where","map","sku","id","get","listed","docs","product","variants","data","String","Array","isArray","priceUsd","Number","length","isFinite","cents","Math","round","min","posHardwarePricedConfig","config","listedCents","isPosHardwareSellerStore","hostId","orgId","Boolean","sellerOrgId","posHardwareInPersonOrderId","registerOrderId","update","digest","slice","posHardwareOrderId","attemptKey","posHardwareOrderNumber","orderId","replace","toUpperCase","hardwareOrdersRef","posHardwareSaleRef","merchantHardwareOrderView","order","number","status","lines","line","name","quantity","unitCents","lineCents","subtotalCents","shippingCents","shipping","shippingLabel","label","taxCents","totalCents","tracking","createdAtMs","updatedAtMs","source","discountCents","readersToSetUp","units","filter","unit","readerId","refundedCents","returnRequest","state","requestedAtMs","note","posSettingsUrl","withQueryAndHash","base","query","hash","path","split","joiner","includes","waitingInPersonReaders","posPlan","stores","orders","org","hosts","Promise","all","limit","terminal","setupUrl","hasLocation","exists","checkEntitlement","sort","a","b","serialsTaken","serialNumber","LISTED_READ_FAILED","Symbol","listedReadFailed","error","console","posHardwareHandler","req","res","body","method","json","action","settingUp","gate","undefined","planRequired","staff","catch","returns","requestPosHardwareReturn","uid","reason","ok","PosHardwareReturnRefusal","message","readers","choosePosHardwareStore","markPosHardwareSetUp","PosHardwareReaderRefusal","available","offers","option","automaticTax","shipCountries","site","workspace","orderBy","created","priced","find","needsHardwareTerms","terms","ip","headers","userAgent","billing","customer","stripeCustomerId","trim","params","mode","client_reference_id","success_url","cancel_url","Object","fromEntries","entries","key","value","forEach","index","use","idempotencyKey","url","code"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,YAAY,QAAQ,oCAAmC;AAChE,YAAYC,WAAW,sBAAqB;AAE5C,SAASC,aAAa,EAAEC,cAAc,QAAQ,2BAA0B;AACxE,SAASC,cAAc,QAAQ,oDAAmD;AAClF,SACEC,4BAA4B,EAC5BC,sBAAsB,EACtBC,2BAA2B,EAC3BC,mBAAmB,EACnBC,sBAAsB,EACtBC,8BAA8B,EAC9BC,qBAAqB,EACrBC,0BAA0B,EAC1BC,8BAA8B,EAC9BC,6BAA6B,EAC7BC,2BAA2B,EAC3BC,4BAA4B,EAC5BC,iBAAiB,EACjBC,qBAAqB,EACrBC,iBAAiB,EACjBC,sBAAsB,EACtBC,cAAc,EACdC,oBAAoB,QAKf,2BAAuB;AAC9B,SACEC,2BAA2B,EAC3BC,yBAAyB,EACzBC,wBAAwB,QACnB,iCAA6B;AACpC,SAASC,uBAAuB,QAAQ,iCAA6B;A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,KAAKmE,IAAI,CAAC;wBAAEqD;wBAAKhI;oBAAQ;gBAC7C;YACA;gBACE,OAAOwE,IAAIhE,MAAM,CAAC,KAAKmE,IAAI,CAAC;oBAAEP,OAAO;gBAAiB;QAC1D;IACF,EAAE,OAAOA,OAAO;QACdC,QAAQD,KAAK,CAAC,kBAAkBQ,QAAQR;QACxC,OAAOI,IAAIhE,MAAM,CAAC,KAAKmE,IAAI,CAAC;YAAEP,OAAO;QAAqC;IAC5E;AACF,EAAC"}
@@ -19,7 +19,7 @@ import { posCustomerHandler } from "./pos-customer.js";
19
19
  import { posDayReportHandler } from "./pos-day-report.js";
20
20
  import { registerPosSalePrinting } from "./pos-print.js";
21
21
  import { onPosSaleCompleted } from "./pos-sale.js";
22
- import { parsePosHardwareInPersonConfig } from "../model/pos-hardware.js";
22
+ import { recordSellerStoreSaleHardware } from "./pos-hardware-sale-fields.js";
23
23
  import { posReturnHandler } from "./pos-return.js";
24
24
  import { posShiftHandler } from "./pos-shift.js";
25
25
  import { posStaffPinHandler } from "./pos-staff-pin.js";
@@ -58,15 +58,7 @@ let hardwareSubscribed = false;
58
58
  */ function registerPosSaleHardware() {
59
59
  if (hardwareSubscribed) return;
60
60
  hardwareSubscribed = true;
61
- onPosSaleCompleted(async (event)=>{
62
- var _parsePosHardwareInPersonConfig;
63
- if (((_parsePosHardwareInPersonConfig = parsePosHardwareInPersonConfig(process.env)) == null ? void 0 : _parsePosHardwareInPersonConfig.sellerHostId) !== event.hostId) return;
64
- try {
65
- await (await import("./pos-hardware-in-person.js")).recordCompletedSaleHardware(event);
66
- } catch (error) {
67
- console.error('[pos-hardware-in-person] recorder not loaded', event.orderId, error);
68
- }
69
- });
61
+ onPosSaleCompleted((event)=>recordSellerStoreSaleHardware(event));
70
62
  }
71
63
 
72
64
  //# sourceMappingURL=pos-ops-routes.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-ops-routes.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 { registerPluginApiRoute } from '@aglyn/aglyn/server'\nimport { posCheckInHandler, registerPosSaleCheckIns } from './pos-check-in'\nimport { posCustomerHandler } from './pos-customer'\nimport { posDayReportHandler } from './pos-day-report'\nimport { registerPosSalePrinting } from './pos-print'\nimport { onPosSaleCompleted } from './pos-sale'\nimport { parsePosHardwareInPersonConfig } from '../model/pos-hardware'\nimport { posReturnHandler } from './pos-return'\nimport { posShiftHandler } from './pos-shift'\nimport { posStaffPinHandler } from './pos-staff-pin'\n\n/**\n * The register's operations routes (AGL-3609): shifts and the drawer, staff\n * PINs, the customer lookup and returns, the day totals (AGL-4037), the\n * check-in (AGL-4043), plus the\n * sale printing. Console-auth, so they register on the console surface with\n * the sale route itself.\n */\nexport function registerPosOpsRoutes(): void {\n registerPluginApiRoute('commerce/pos-shift', posShiftHandler)\n registerPluginApiRoute('commerce/pos-staff-pin', posStaffPinHandler)\n registerPluginApiRoute('commerce/pos-customer', posCustomerHandler)\n registerPluginApiRoute('commerce/pos-return', posReturnHandler)\n // One day's or one event's totals across every register, shift and cashier\n // (AGL-4037): a GET, read with the same gate as the shift reports.\n registerPluginApiRoute('commerce/pos-day-report', posDayReportHandler)\n // Check-in at the window (AGL-4043): who is due today, checking them in\n // with a wristband, and the day's list; a register sale's check-ins are\n // written the moment it completes, through the same seam as its printing.\n registerPluginApiRoute('commerce/pos-check-in', posCheckInHandler)\n registerPosSaleCheckIns()\n // A completed sale's receipt and drawer kick on the register's cloud\n // printers (AGL-3619), through the sale-completed seam every path fires.\n registerPosSalePrinting()\n // A card reader sold at the platform's own store's register becomes a\n // hardware order for the buyer's workspace (AGL-4038).\n registerPosSaleHardware()\n}\n\nlet hardwareSubscribed = false\n\n/**\n * Records the hardware order of a completed sale on the platform's own\n * store. Every other store's sale is answered from the environment alone,\n * without loading the recorder. Never throws into a sale; a sale this misses\n * stays marked and the To attach list's sweep records it.\n */\nfunction registerPosSaleHardware(): void {\n if (hardwareSubscribed) return\n hardwareSubscribed = true\n onPosSaleCompleted(async (event) => {\n if (parsePosHardwareInPersonConfig(process.env)?.sellerHostId !== event.hostId) return\n try {\n await (await import('./pos-hardware-in-person')).recordCompletedSaleHardware(event)\n } catch (error) {\n console.error('[pos-hardware-in-person] recorder not loaded', event.orderId, error)\n }\n })\n}\n"],"names":["registerPluginApiRoute","posCheckInHandler","registerPosSaleCheckIns","posCustomerHandler","posDayReportHandler","registerPosSalePrinting","onPosSaleCompleted","parsePosHardwareInPersonConfig","posReturnHandler","posShiftHandler","posStaffPinHandler","registerPosOpsRoutes","registerPosSaleHardware","hardwareSubscribed","event","process","env","sellerHostId","hostId","recordCompletedSaleHardware","error","console","orderId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,sBAAqB;AAC5D,SAASC,iBAAiB,EAAEC,uBAAuB,QAAQ,oBAAgB;AAC3E,SAASC,kBAAkB,QAAQ,oBAAgB;AACnD,SAASC,mBAAmB,QAAQ,sBAAkB;AACtD,SAASC,uBAAuB,QAAQ,iBAAa;AACrD,SAASC,kBAAkB,QAAQ,gBAAY;AAC/C,SAASC,8BAA8B,QAAQ,2BAAuB;AACtE,SAASC,gBAAgB,QAAQ,kBAAc;AAC/C,SAASC,eAAe,QAAQ,iBAAa;AAC7C,SAASC,kBAAkB,QAAQ,qBAAiB;AAEpD;;;;;;CAMC,GACD,OAAO,SAASC;IACdX,uBAAuB,sBAAsBS;IAC7CT,uBAAuB,0BAA0BU;IACjDV,uBAAuB,yBAAyBG;IAChDH,uBAAuB,uBAAuBQ;IAC9C,2EAA2E;IAC3E,mEAAmE;IACnER,uBAAuB,2BAA2BI;IAClD,wEAAwE;IACxE,wEAAwE;IACxE,0EAA0E;IAC1EJ,uBAAuB,yBAAyBC;IAChDC;IACA,qEAAqE;IACrE,yEAAyE;IACzEG;IACA,sEAAsE;IACtE,uDAAuD;IACvDO;AACF;AAEA,IAAIC,qBAAqB;AAEzB;;;;;CAKC,GACD,SAASD;IACP,IAAIC,oBAAoB;IACxBA,qBAAqB;IACrBP,mBAAmB,OAAOQ;YACpBP;QAAJ,IAAIA,EAAAA,kCAAAA,+BAA+BQ,QAAQC,GAAG,sBAA1CT,gCAA6CU,YAAY,MAAKH,MAAMI,MAAM,EAAE;QAChF,IAAI;YACF,MAAM,AAAC,CAAA,MAAM,MAAM,CAAC,8BAA0B,EAAGC,2BAA2B,CAACL;QAC/E,EAAE,OAAOM,OAAO;YACdC,QAAQD,KAAK,CAAC,gDAAgDN,MAAMQ,OAAO,EAAEF;QAC/E;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-ops-routes.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 { registerPluginApiRoute } from '@aglyn/aglyn/server'\nimport { posCheckInHandler, registerPosSaleCheckIns } from './pos-check-in'\nimport { posCustomerHandler } from './pos-customer'\nimport { posDayReportHandler } from './pos-day-report'\nimport { registerPosSalePrinting } from './pos-print'\nimport { onPosSaleCompleted } from './pos-sale'\nimport { recordSellerStoreSaleHardware } from './pos-hardware-sale-fields'\nimport { posReturnHandler } from './pos-return'\nimport { posShiftHandler } from './pos-shift'\nimport { posStaffPinHandler } from './pos-staff-pin'\n\n/**\n * The register's operations routes (AGL-3609): shifts and the drawer, staff\n * PINs, the customer lookup and returns, the day totals (AGL-4037), the\n * check-in (AGL-4043), plus the\n * sale printing. Console-auth, so they register on the console surface with\n * the sale route itself.\n */\nexport function registerPosOpsRoutes(): void {\n registerPluginApiRoute('commerce/pos-shift', posShiftHandler)\n registerPluginApiRoute('commerce/pos-staff-pin', posStaffPinHandler)\n registerPluginApiRoute('commerce/pos-customer', posCustomerHandler)\n registerPluginApiRoute('commerce/pos-return', posReturnHandler)\n // One day's or one event's totals across every register, shift and cashier\n // (AGL-4037): a GET, read with the same gate as the shift reports.\n registerPluginApiRoute('commerce/pos-day-report', posDayReportHandler)\n // Check-in at the window (AGL-4043): who is due today, checking them in\n // with a wristband, and the day's list; a register sale's check-ins are\n // written the moment it completes, through the same seam as its printing.\n registerPluginApiRoute('commerce/pos-check-in', posCheckInHandler)\n registerPosSaleCheckIns()\n // A completed sale's receipt and drawer kick on the register's cloud\n // printers (AGL-3619), through the sale-completed seam every path fires.\n registerPosSalePrinting()\n // A card reader sold at the platform's own store's register becomes a\n // hardware order for the buyer's workspace (AGL-4038).\n registerPosSaleHardware()\n}\n\nlet hardwareSubscribed = false\n\n/**\n * Records the hardware order of a completed sale on the platform's own\n * store. Every other store's sale is answered from the environment alone,\n * without loading the recorder. Never throws into a sale; a sale this misses\n * stays marked and the To attach list's sweep records it.\n */\nfunction registerPosSaleHardware(): void {\n if (hardwareSubscribed) return\n hardwareSubscribed = true\n onPosSaleCompleted((event) => recordSellerStoreSaleHardware(event))\n}\n"],"names":["registerPluginApiRoute","posCheckInHandler","registerPosSaleCheckIns","posCustomerHandler","posDayReportHandler","registerPosSalePrinting","onPosSaleCompleted","recordSellerStoreSaleHardware","posReturnHandler","posShiftHandler","posStaffPinHandler","registerPosOpsRoutes","registerPosSaleHardware","hardwareSubscribed","event"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,sBAAqB;AAC5D,SAASC,iBAAiB,EAAEC,uBAAuB,QAAQ,oBAAgB;AAC3E,SAASC,kBAAkB,QAAQ,oBAAgB;AACnD,SAASC,mBAAmB,QAAQ,sBAAkB;AACtD,SAASC,uBAAuB,QAAQ,iBAAa;AACrD,SAASC,kBAAkB,QAAQ,gBAAY;AAC/C,SAASC,6BAA6B,QAAQ,gCAA4B;AAC1E,SAASC,gBAAgB,QAAQ,kBAAc;AAC/C,SAASC,eAAe,QAAQ,iBAAa;AAC7C,SAASC,kBAAkB,QAAQ,qBAAiB;AAEpD;;;;;;CAMC,GACD,OAAO,SAASC;IACdX,uBAAuB,sBAAsBS;IAC7CT,uBAAuB,0BAA0BU;IACjDV,uBAAuB,yBAAyBG;IAChDH,uBAAuB,uBAAuBQ;IAC9C,2EAA2E;IAC3E,mEAAmE;IACnER,uBAAuB,2BAA2BI;IAClD,wEAAwE;IACxE,wEAAwE;IACxE,0EAA0E;IAC1EJ,uBAAuB,yBAAyBC;IAChDC;IACA,qEAAqE;IACrE,yEAAyE;IACzEG;IACA,sEAAsE;IACtE,uDAAuD;IACvDO;AACF;AAEA,IAAIC,qBAAqB;AAEzB;;;;;CAKC,GACD,SAASD;IACP,IAAIC,oBAAoB;IACxBA,qBAAqB;IACrBP,mBAAmB,CAACQ,QAAUP,8BAA8BO;AAC9D"}
@@ -15,6 +15,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
17
  */ import * as Aglyn from "@aglyn/aglyn/server";
18
+ import { excludeBuyNowPayLater } from "@aglyn/aglyn/app-utils/buy-now-pay-later";
18
19
  import * as CommerceModel from "../model/index.js";
19
20
  import { firebaseAdmin, getOrgForHost, getPluginConfig } from "@aglyn/tenant-data-admin";
20
21
  import recordCapturedContact from "@aglyn/aglyn/plugin-manager/record-captured-contact";
@@ -604,7 +605,7 @@ import { posKioskPrincipal } from "./pos-kiosk-principal.js";
604
605
  // cashier's discount, plus the origin tax. A till knows both — there is no
605
606
  // shopper-chosen shipping and no Stripe Tax to wait on — so unlike the
606
607
  // online doors this one recovers the cost exactly.
607
- const feeCents = payment === 'link' ? tenderTakeFeeCents + Aglyn.saleProcessingCostCents(chargedItemsCents + taxCents) : tenderTakeFeeCents;
608
+ const feeCents = payment === 'link' ? Aglyn.saleApplicationFeeCents(tenderTakeFeeCents, chargedItemsCents + taxCents) : tenderTakeFeeCents;
608
609
  const totals = CommerceModel.computeOrderTotals(lineItems, {
609
610
  discountCents,
610
611
  taxCents,
@@ -938,6 +939,9 @@ import { posKioskPrincipal } from "./pos-kiosk-principal.js";
938
939
  } : {}, discountHoldKey ? {
939
940
  'metadata[discountHoldKey]': discountHoldKey
940
941
  } : {}));
942
+ // The register's card link offers no buy-now-pay-later (AGL-4198), so
943
+ // its fee, at the card rate, covers whatever the customer pays with.
944
+ excludeBuyNowPayLater(params);
941
945
  const response = await fetch('https://api.stripe.com/v1/checkout/sessions', {
942
946
  method: 'POST',
943
947
  headers: _extends({