@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-notify.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 { formatOperatorAlertAmount } from '@aglyn/aglyn/app-utils/operator-alerts'\nimport {\n isAccountBanLockdownReason,\n normalizeOrgLockdown,\n} from '@aglyn/aglyn/app-utils/lockdown'\nimport { POS_HARDWARE_EMAIL_KEYS, sendEmail } from '@aglyn/shared-util-email'\nimport { platformConsoleOrigin } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n firebaseAdmin,\n hostDisplayName,\n meterPlatformEmail,\n raiseOperatorAlert,\n} from '@aglyn/tenant-data-admin'\nimport { filterSuppressedEmails } from '@aglyn/tenant-data-admin/server/email-suppression'\nimport {\n orgSystemEmailBrand,\n renderSystemEmailContent,\n} from '@aglyn/tenant-data-admin/server/render-system-email'\nimport {\n COMMERCE_POS_HARDWARE_CANCELED_AFTER_ORDERING,\n COMMERCE_POS_HARDWARE_ORDER,\n COMMERCE_POS_HARDWARE_REFUND_FAILED,\n} from '../constants/operator-alerts'\nimport { carrierLabelFor } from '../model/tracking-url'\nimport {\n formatPosHardwareCents,\n POS_HARDWARE_ANCHOR,\n type PosHardwareCancelReason,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\nimport { hardwareOrdersRef, posHardwareOrderNumber, posSettingsUrl } from './pos-hardware'\n\n/*==========================================\n * TELLING PEOPLE ABOUT A HARDWARE ORDER (AGL-4038).\n *\n * The buyer gets a system email at each step they wait on: received, shipped\n * (with the carrier and tracking link) and delivered (with the way to set the\n * reader up), and canceled and refunded when staff cancel it before it ships\n * and choose to tell them, or the workspace is deleted or their account is\n * closed first; a reader bought in person gets \"refunded\" when staff refund\n * it and choose to tell them. The canceled and refunded emails are sent\n * ONCE, by a claim on the order ({@link sendPosHardwareEmailOnce}), so the\n * staff page and a closure never both send one. Staff get the \"New hardware order\" operator alert,\n * because in phase 1 a person places every order with Stripe, and an alert\n * when a closure cancels an order already placed with Stripe or Stripe\n * refuses a closure's refund.\n *\n * Never throws. The order is already recorded when any of these run, and a\n * lost email must not undo it or turn a webhook into a redelivery.\n *=========================================*/\n\nexport type PosHardwareEmailKind = keyof typeof POS_HARDWARE_EMAIL_KEYS\n\n/** The lines as the emails list them, one per item. */\nfunction itemsText(order: PosHardwareOrder): string {\n return (order.lines ?? []).map((line) => `${line.name} × ${line.quantity}`).join('\\n')\n}\n\nfunction shipToText(order: PosHardwareOrder): string {\n const address = order.shipping?.address\n const cityLine = address\n ? [address.city, [address.state, address.postalCode].filter(Boolean).join(' ')].filter(Boolean).join(', ')\n : ''\n return [order.shipping?.name, address?.line1, address?.line2, cityLine].filter(Boolean).join('\\n')\n}\n\nasync function siteAndOrgNames(order: PosHardwareOrder): Promise<{ site: string; org: string; ban: boolean }> {\n const firestore = firebaseAdmin.app().firestore()\n const [host, org] = await Promise.all([\n firestore.collection('hosts').doc(order.hostId).get().catch(() => null),\n firestore.collection('orgs').doc(order.orgId).get().catch(() => null),\n ])\n const lock = normalizeOrgLockdown(org?.data() as never)\n return {\n site: host?.exists ? hostDisplayName(host.data() as Record<string, unknown>, order.hostId) : 'your site',\n org: String(org?.get('name') ?? '').trim() || UNNAMED_WORKSPACE,\n ban: Boolean(lock && isAccountBanLockdownReason(lock.reason)),\n }\n}\n\n/** The fallback subject and first line, when no design renders. */\nconst FALLBACK: Record<PosHardwareEmailKind, (number: string) => string> = {\n received: (number) => `We have your card reader order ${number}`,\n shipped: (number) => `Your card reader order ${number} has shipped`,\n delivered: (number) => `Your card reader order ${number} was delivered`,\n canceled: (number) => `Your card reader order ${number} was canceled and refunded`,\n refunded: (number) => `Your refund for card reader order ${number}`,\n invited: (number) => `Your card reader order ${number} is waiting for your account`,\n returnRefunded: (number) => `We refunded your returned card reader order ${number}`,\n}\n\n/** The fallback a workspace with no name gets in a sentence. */\nconst UNNAMED_WORKSPACE = 'your workspace'\n\n/**\n * Who canceled the order and why, as the email's first sentence; the\n * template goes on \"It had not shipped yet, so we refunded …\".\n */\nfunction cancelReasonText(reason: PosHardwareCancelReason | undefined, org: string): string {\n if (reason === 'workspace-closed') {\n return org && org !== UNNAMED_WORKSPACE\n ? `We canceled your order because the ${org} workspace was deleted.`\n : 'We canceled your order because your workspace was deleted.'\n }\n if (reason === 'account-closed') return 'We canceled your order because the account that placed it was closed.'\n return 'Our team canceled your order.'\n}\n\n/** Why, for staff: the closure that canceled it, never who the buyer was. */\nfunction staffReasonText(reason: PosHardwareCancelReason, orgId: string): string {\n if (reason === 'workspace-closed') return `its workspace ${orgId} was deleted`\n if (reason === 'account-closed') return 'the account that placed it was closed'\n return 'staff canceled it'\n}\n\n/** The merge values for one order's emails. Exported for the render spec. */\nexport async function posHardwareEmailMerge(\n orderId: string,\n order: PosHardwareOrder,\n names: { site: string; org: string },\n): Promise<Record<string, string>> {\n const base = await posSettingsUrl(order.hostId)\n const [path] = base.split('#')\n const ordersUrl = `${path}#${POS_HARDWARE_ANCHOR}`\n return {\n 'org.name': names.org,\n 'site.name': names.site,\n 'order.number': posHardwareOrderNumber(orderId),\n 'order.items': itemsText(order),\n 'order.total': formatPosHardwareCents(order.totalCents ?? 0),\n 'order.shipTo': shipToText(order),\n 'order.shippingMethod': order.shipping?.label ?? '',\n 'order.carrier': carrierLabelFor(order.tracking?.carrier) || 'the carrier',\n 'order.trackingNumber': order.tracking?.number ?? '',\n // An unknown carrier has no tracker to link; the card shows the number.\n 'order.trackingUrl': order.tracking?.url ?? ordersUrl,\n 'order.ordersUrl': ordersUrl,\n 'order.setupUrl': `${path}#pos-devices`,\n // What Stripe reported refunding, or the whole charge where it has not.\n 'order.refunded': formatPosHardwareCents(order.refundedCents ?? order.totalCents ?? 0),\n // This refund alone, for an order refunded in parts; the whole of it otherwise.\n 'order.refundedNow': formatPosHardwareCents(\n (order.refunds ?? []).slice(-1)[0]?.cents ?? order.refundedCents ?? order.totalCents ?? 0,\n ),\n 'order.cancelReason': cancelReasonText(order.cancelReason, names.org),\n // What a return kept back: the original shipping and any restocking fee.\n 'order.kept': formatPosHardwareCents(Math.max(0, (order.totalCents ?? 0) - (order.refundedCents ?? 0))),\n }\n}\n\n/** What became of one email. */\nexport type PosHardwareEmailOutcome =\n /** Sent. */\n | 'sent'\n /** Nobody to send it to: no address, suppressed, or the account is banned. */\n | 'skipped'\n /** The send failed, and may be tried again. */\n | 'failed'\n\nexport async function sendPosHardwareEmail(\n kind: PosHardwareEmailKind,\n orderId: string,\n order: PosHardwareOrder,\n): Promise<PosHardwareEmailOutcome> {\n try {\n const to = String(order.contactEmail ?? '').trim()\n if (!to) return 'skipped'\n const names = await siteAndOrgNames(order)\n // A ban is a ban (AGL-3420): after its notice the account is sent nothing.\n if (names.ban) return 'skipped'\n const [recipient] = await filterSuppressedEmails([to])\n if (!recipient) return 'skipped'\n const merge = await posHardwareEmailMerge(orderId, order, names)\n const subject = FALLBACK[kind](merge['order.number'])\n // A refund in person is in the selling workspace's brand, as its\n // invitation is; the rest in the buyer's.\n const brand = await orgSystemEmailBrand(kind === 'refunded' ? (order.posSale?.orgId ?? order.orgId) : order.orgId)\n // A canceled order's workspace may be gone, so its fallback names the\n // refund rather than linking a card that no longer opens.\n const last =\n kind === 'canceled'\n ? `Refunded: ${merge['order.refunded']}`\n : kind === 'refunded'\n ? `Refunded now: ${merge['order.refundedNow']}`\n : merge['order.ordersUrl']\n const content = await renderSystemEmailContent(POS_HARDWARE_EMAIL_KEYS[kind], merge, brand, {\n subject,\n text: `${subject}\\n\\n${merge['order.items']}\\n\\n${last}`,\n })\n const result = await sendEmail({\n to: recipient,\n ...content,\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: POS_HARDWARE_EMAIL_KEYS[kind],\n })\n if (!result.sent) return 'failed'\n await meterPlatformEmail(1)\n return 'sent'\n } catch (error) {\n console.error('[pos-hardware] email failed', kind, orderId, error)\n return 'failed'\n }\n}\n\n/** How long a claimed send that never finished holds the next one back. */\nconst EMAIL_CLAIM_STALE_MS = 10 * 60 * 1000\n\n/**\n * Sends one email for an order ONCE, under `key` (the kind by default; one\n * per refund for a refund in parts). The claim is a field on the order,\n * `buyerEmails.{key}`, taken in a transaction before the send, so the staff\n * page and a closure, a retried press or two staff at once, send it once\n * between them. A send that failed can be claimed again; one that found\n * nobody to send to is not tried again. Never throws.\n */\nexport async function sendPosHardwareEmailOnce(\n kind: PosHardwareEmailKind,\n orderId: string,\n order: PosHardwareOrder,\n key: string = kind,\n): Promise<PosHardwareEmailOutcome | 'already'> {\n try {\n const firestore = firebaseAdmin.app().firestore()\n const ref = hardwareOrdersRef(order.orgId).doc(orderId)\n const claimed = await firestore.runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) return false\n const held = (snapshot.data()?.buyerEmails ?? {})[key] as { state?: string; atMs?: number } | undefined\n const now = Date.now()\n if (held?.state === 'sent' || held?.state === 'skipped') return false\n if (held?.state === 'sending' && now - Number(held.atMs ?? 0) < EMAIL_CLAIM_STALE_MS) return false\n transaction.set(ref, { buyerEmails: { [key]: { state: 'sending', atMs: now } } }, { merge: true })\n return true\n })\n if (!claimed) return 'already'\n const outcome = await sendPosHardwareEmail(kind, orderId, order)\n await ref\n .set({ buyerEmails: { [key]: { state: outcome === 'sent' ? 'sent' : outcome, atMs: Date.now() } } }, { merge: true })\n .catch((error: unknown) => console.error('[pos-hardware] email claim not settled', kind, orderId, error))\n return outcome\n } catch (error) {\n console.error('[pos-hardware] email claim failed', kind, orderId, error)\n return 'failed'\n }\n}\n\n/**\n * The invitation to sign up (AGL-4038), for someone who bought a card reader\n * in person at the platform's own store with no account yet: create the\n * account with this address and the order joins their workspace on its own.\n * Sent in the selling workspace's brand, which is the platform's. Never\n * throws; the caller has already claimed the send.\n */\n/** The invitation's merge values. Exported for the render spec. */\nexport function posHardwareInviteMerge(orderId: string, order: PosHardwareOrder): Record<string, string> {\n return {\n 'order.number': posHardwareOrderNumber(orderId),\n 'order.items': itemsText(order),\n 'order.total': formatPosHardwareCents(order.totalCents ?? 0),\n 'order.signUpUrl': `${platformConsoleOrigin()}/signup`,\n }\n}\n\nexport async function sendPosHardwareInvite(orderId: string, order: PosHardwareOrder): Promise<void> {\n try {\n const to = String(order.attachment?.email ?? '').trim()\n if (!to) return\n const [recipient] = await filterSuppressedEmails([to])\n if (!recipient) return\n const merge = posHardwareInviteMerge(orderId, order)\n const signUpUrl = merge['order.signUpUrl']\n const subject = FALLBACK.invited(merge['order.number'])\n const brand = await orgSystemEmailBrand(order.posSale?.orgId ?? order.orgId)\n const content = await renderSystemEmailContent(POS_HARDWARE_EMAIL_KEYS.invited, merge, brand, {\n subject,\n text: `${subject}\\n\\n${merge['order.items']}\\n\\nCreate your account with this email address: ${signUpUrl}`,\n })\n const result = await sendEmail({\n to: recipient,\n ...content,\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: POS_HARDWARE_EMAIL_KEYS.invited,\n })\n if (result.sent) await meterPlatformEmail(1)\n } catch (error) {\n console.error('[pos-hardware] invitation failed', orderId, error)\n }\n}\n\n/**\n * A closure canceled an order staff had already placed with Stripe: the\n * merchant is refunded, and Stripe will still ship it unless someone cancels\n * it there. Once per order.\n */\nexport async function raisePosHardwareCanceledAfterOrderingAlert(\n orderId: string,\n order: PosHardwareOrder,\n reason: PosHardwareCancelReason,\n): Promise<void> {\n try {\n const stripeOrderId = String(order.stripeHardwareOrderId ?? '').trim()\n await raiseOperatorAlert(COMMERCE_POS_HARDWARE_CANCELED_AFTER_ORDERING, {\n dedupeKey: orderId,\n orgId: order.orgId,\n hostId: order.hostId,\n context: {\n orderNumber: posHardwareOrderNumber(orderId),\n amount: formatOperatorAlertAmount(order.totalCents ?? 0),\n items: (order.lines ?? []).map((line) => `${line.quantity} × ${line.name}`).join(', '),\n reason: staffReasonText(reason, order.orgId),\n stripeOrder: stripeOrderId ? ` (Stripe order ${stripeOrderId})` : '',\n },\n })\n } catch (error) {\n console.error('[pos-hardware] canceled-after-ordering alert failed', orderId, error)\n }\n}\n\n/**\n * Stripe refused a closure's refund, and the closure went ahead without it.\n * Carries the payment to refund by hand, never the buyer.\n */\nexport async function raisePosHardwareRefundFailedAlert(\n orderId: string,\n order: PosHardwareOrder,\n reason: PosHardwareCancelReason,\n error: string,\n): Promise<void> {\n try {\n const stripeOrderId = String(order.stripeHardwareOrderId ?? '').trim()\n await raiseOperatorAlert(COMMERCE_POS_HARDWARE_REFUND_FAILED, {\n dedupeKey: orderId,\n orgId: order.orgId,\n hostId: order.hostId,\n context: {\n orderNumber: posHardwareOrderNumber(orderId),\n amount: formatOperatorAlertAmount(order.totalCents ?? 0),\n reason: staffReasonText(reason, order.orgId),\n error: error || 'no reason given',\n paymentIntentId: order.stripePaymentIntentId ?? 'for this order (no payment id is recorded on it)',\n orderedNote:\n order.status === 'ordered'\n ? `. It had already been placed with Stripe${stripeOrderId ? ` as ${stripeOrderId}` : ''}, so cancel it there too before it ships`\n : '',\n },\n })\n } catch (failure) {\n console.error('[pos-hardware] refund-failed alert failed', orderId, failure)\n }\n}\n\n/** \"New hardware order\", once per order. */\nexport async function raisePosHardwareOrderAlert(orderId: string, order: PosHardwareOrder): Promise<void> {\n try {\n const names = await siteAndOrgNames(order)\n await raiseOperatorAlert(COMMERCE_POS_HARDWARE_ORDER, {\n dedupeKey: orderId,\n orgId: order.orgId,\n hostId: order.hostId,\n context: {\n orderNumber: posHardwareOrderNumber(orderId),\n amount: formatOperatorAlertAmount(order.totalCents ?? 0),\n site: `${names.site} (${order.hostId})`,\n items: (order.lines ?? []).map((line) => `${line.quantity} × ${line.name}`).join(', '),\n shipping: order.shipping?.label ?? 'shipping',\n },\n })\n } catch (error) {\n console.error('[pos-hardware] operator alert failed', orderId, error)\n }\n}\n"],"names":["formatOperatorAlertAmount","isAccountBanLockdownReason","normalizeOrgLockdown","POS_HARDWARE_EMAIL_KEYS","sendEmail","platformConsoleOrigin","firebaseAdmin","hostDisplayName","meterPlatformEmail","raiseOperatorAlert","filterSuppressedEmails","orgSystemEmailBrand","renderSystemEmailContent","COMMERCE_POS_HARDWARE_CANCELED_AFTER_ORDERING","COMMERCE_POS_HARDWARE_ORDER","COMMERCE_POS_HARDWARE_REFUND_FAILED","carrierLabelFor","formatPosHardwareCents","POS_HARDWARE_ANCHOR","hardwareOrdersRef","posHardwareOrderNumber","posSettingsUrl","itemsText","order","lines","map","line","name","quantity","join","shipToText","address","shipping","cityLine","city","state","postalCode","filter","Boolean","line1","line2","siteAndOrgNames","firestore","app","host","org","Promise","all","collection","doc","hostId","get","catch","orgId","lock","data","site","exists","String","trim","UNNAMED_WORKSPACE","ban","reason","FALLBACK","received","number","shipped","delivered","canceled","refunded","invited","returnRefunded","cancelReasonText","staffReasonText","posHardwareEmailMerge","orderId","names","base","path","split","ordersUrl","totalCents","label","tracking","carrier","url","refundedCents","refunds","slice","cents","cancelReason","Math","max","sendPosHardwareEmail","kind","to","contactEmail","recipient","merge","subject","brand","posSale","last","content","text","result","fromName","context","sent","error","console","EMAIL_CLAIM_STALE_MS","sendPosHardwareEmailOnce","key","ref","claimed","runTransaction","transaction","held","snapshot","buyerEmails","now","Date","Number","atMs","set","outcome","posHardwareInviteMerge","sendPosHardwareInvite","attachment","email","signUpUrl","raisePosHardwareCanceledAfterOrderingAlert","stripeOrderId","stripeHardwareOrderId","dedupeKey","orderNumber","amount","items","stripeOrder","raisePosHardwareRefundFailedAlert","paymentIntentId","stripePaymentIntentId","orderedNote","status","fail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/server/pos-hardware-notify.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 { formatOperatorAlertAmount } from '@aglyn/aglyn/app-utils/operator-alerts'\nimport {\n isAccountBanLockdownReason,\n normalizeOrgLockdown,\n} from '@aglyn/aglyn/app-utils/lockdown'\nimport { POS_HARDWARE_EMAIL_KEYS, sendEmail } from '@aglyn/shared-util-email'\nimport { platformConsoleOrigin } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n firebaseAdmin,\n hostDisplayName,\n meterPlatformEmail,\n raiseOperatorAlert,\n} from '@aglyn/tenant-data-admin'\nimport { filterSuppressedEmails } from '@aglyn/tenant-data-admin/server/email-suppression'\nimport {\n orgSystemEmailBrand,\n renderSystemEmailContent,\n} from '@aglyn/tenant-data-admin/server/render-system-email'\nimport {\n COMMERCE_POS_HARDWARE_CANCELED_AFTER_ORDERING,\n COMMERCE_POS_HARDWARE_ORDER,\n COMMERCE_POS_HARDWARE_REFUND_FAILED,\n} from '../constants/operator-alerts'\nimport { carrierLabelFor } from '../model/tracking-url'\nimport {\n formatPosHardwareCents,\n POS_HARDWARE_ANCHOR,\n posHardwareOrderUnits,\n type PosHardwareCancelReason,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\nimport { hardwareOrdersRef, posHardwareOrderNumber, posSettingsUrl } from './pos-hardware'\n\n/*==========================================\n * TELLING PEOPLE ABOUT A HARDWARE ORDER (AGL-4038).\n *\n * The buyer gets a system email at each step they wait on: received, shipped\n * (with the carrier and tracking link) and delivered (with the way to set the\n * reader up), and canceled and refunded when staff cancel it before it ships\n * and choose to tell them, or the workspace is deleted or their account is\n * closed first; a reader bought in person gets \"refunded\" when staff refund\n * it and choose to tell them. The canceled and refunded emails are sent\n * ONCE, by a claim on the order ({@link sendPosHardwareEmailOnce}), so the\n * staff page and a closure never both send one. Staff get the \"New hardware order\" operator alert,\n * because in phase 1 a person places every order with Stripe, and an alert\n * when a closure cancels an order already placed with Stripe or Stripe\n * refuses a closure's refund.\n *\n * Never throws. The order is already recorded when any of these run, and a\n * lost email must not undo it or turn a webhook into a redelivery.\n *=========================================*/\n\nexport type PosHardwareEmailKind = keyof typeof POS_HARDWARE_EMAIL_KEYS\n\n/** The lines as the emails list them, one per item. */\nfunction itemsText(order: PosHardwareOrder): string {\n return (order.lines ?? []).map((line) => `${line.name} × ${line.quantity}`).join('\\n')\n}\n\nfunction shipToText(order: PosHardwareOrder): string {\n const address = order.shipping?.address\n const cityLine = address\n ? [address.city, [address.state, address.postalCode].filter(Boolean).join(' ')].filter(Boolean).join(', ')\n : ''\n return [order.shipping?.name, address?.line1, address?.line2, cityLine].filter(Boolean).join('\\n')\n}\n\nasync function siteAndOrgNames(order: PosHardwareOrder): Promise<{ site: string; org: string; ban: boolean }> {\n const firestore = firebaseAdmin.app().firestore()\n // Bought from the platform's own store and not yet in the buyer's\n // workspace (AGL-4038): it is for their business, which has no workspace\n // here yet, and the selling store's name says where it came from.\n if (order.attachment?.state === 'pending' && order.posSale?.hostId) {\n const seller = await firestore.collection('hosts').doc(order.posSale.hostId).get().catch(() => null)\n return {\n site: seller?.exists ? hostDisplayName(seller.data() as Record<string, unknown>, order.posSale.hostId) : 'our store',\n org: PENDING_BUYER,\n ban: false,\n }\n }\n const [host, org] = await Promise.all([\n firestore.collection('hosts').doc(order.hostId).get().catch(() => null),\n firestore.collection('orgs').doc(order.orgId).get().catch(() => null),\n ])\n const lock = normalizeOrgLockdown(org?.data() as never)\n return {\n site: host?.exists ? hostDisplayName(host.data() as Record<string, unknown>, order.hostId) : 'your site',\n org: String(org?.get('name') ?? '').trim() || UNNAMED_WORKSPACE,\n ban: Boolean(lock && isAccountBanLockdownReason(lock.reason)),\n }\n}\n\n/** The fallback subject and first line, when no design renders. */\nconst FALLBACK: Record<PosHardwareEmailKind, (number: string) => string> = {\n received: (number) => `We have your card reader order ${number}`,\n shipped: (number) => `Your card reader order ${number} has shipped`,\n delivered: (number) => `Your card reader order ${number} was delivered`,\n canceled: (number) => `Your card reader order ${number} was canceled and refunded`,\n refunded: (number) => `Your refund for card reader order ${number}`,\n invited: (number) => `Your card reader order ${number} is waiting for your account`,\n returnRefunded: (number) => `We refunded your returned card reader order ${number}`,\n}\n\n/** The fallback a workspace with no name gets in a sentence. */\nconst UNNAMED_WORKSPACE = 'your workspace'\n\n/** Who a sale not yet in anyone's workspace is for, in a sentence. */\nconst PENDING_BUYER = 'your business'\n\n/**\n * Who canceled the order and why, as the email's first sentence; the\n * template goes on \"It had not shipped yet, so we refunded …\".\n */\nfunction cancelReasonText(reason: PosHardwareCancelReason | undefined, org: string): string {\n if (reason === 'workspace-closed') {\n return org && org !== UNNAMED_WORKSPACE\n ? `We canceled your order because the ${org} workspace was deleted.`\n : 'We canceled your order because your workspace was deleted.'\n }\n if (reason === 'account-closed') return 'We canceled your order because the account that placed it was closed.'\n return 'Our team canceled your order.'\n}\n\n/** Why, for staff: the closure that canceled it, never who the buyer was. */\nfunction staffReasonText(reason: PosHardwareCancelReason, orgId: string): string {\n if (reason === 'workspace-closed') return `its workspace ${orgId} was deleted`\n if (reason === 'account-closed') return 'the account that placed it was closed'\n return 'staff canceled it'\n}\n\n/** The steps the delivered email gives: pair the reader, or it is already set up. */\nexport function posHardwareSetupSteps(order: Pick<PosHardwareOrder, 'units' | 'lines'>): string {\n const units = posHardwareOrderUnits(order)\n if (units.length && units.every((unit) => unit.readerId)) {\n return (\n 'We set your reader up on your store before it shipped.\\n' +\n '1. Charge it and switch it on.\\n' +\n '2. Connect it to Wi-Fi from the reader’s Settings.\\n' +\n '3. It shows on the POS devices card, ready for a register.'\n )\n }\n return (\n '1. Charge it and switch it on.\\n' +\n '2. Connect it to Wi-Fi from the reader’s Settings.\\n' +\n '3. On the reader, generate a pairing code.\\n' +\n '4. On the POS devices card, choose Add card reader and enter the code.'\n )\n}\n\n/** The merge values for one order's emails. Exported for the render spec. */\nexport async function posHardwareEmailMerge(\n orderId: string,\n order: PosHardwareOrder,\n names: { site: string; org: string },\n): Promise<Record<string, string>> {\n // An order with no store yet (AGL-4038) has no settings page to link: the\n // console's front door, where signing in or up leads to it.\n const base = order.hostId ? await posSettingsUrl(order.hostId) : platformConsoleOrigin()\n const [path] = base.split('#')\n const ordersUrl = order.hostId ? `${path}#${POS_HARDWARE_ANCHOR}` : path\n return {\n 'org.name': names.org,\n 'site.name': names.site,\n 'order.number': posHardwareOrderNumber(orderId),\n 'order.items': itemsText(order),\n 'order.total': formatPosHardwareCents(order.totalCents ?? 0),\n 'order.shipTo': shipToText(order),\n 'order.shippingMethod': order.shipping?.label ?? '',\n 'order.carrier': carrierLabelFor(order.tracking?.carrier) || 'the carrier',\n 'order.trackingNumber': order.tracking?.number ?? '',\n // An unknown carrier has no tracker to link; the card shows the number.\n 'order.trackingUrl': order.tracking?.url ?? ordersUrl,\n 'order.ordersUrl': ordersUrl,\n 'order.setupUrl': order.hostId ? `${path}#pos-devices` : path,\n // What arrived: readers registered to the store before they shipped\n // (AGL-4038) only need power and Wi-Fi; any other is paired by its code.\n 'order.setupSteps': posHardwareSetupSteps(order),\n // What Stripe reported refunding, or the whole charge where it has not.\n 'order.refunded': formatPosHardwareCents(order.refundedCents ?? order.totalCents ?? 0),\n // This refund alone, for an order refunded in parts; the whole of it otherwise.\n 'order.refundedNow': formatPosHardwareCents(\n (order.refunds ?? []).slice(-1)[0]?.cents ?? order.refundedCents ?? order.totalCents ?? 0,\n ),\n 'order.cancelReason': cancelReasonText(order.cancelReason, names.org),\n // What a return kept back: the original shipping and any restocking fee.\n 'order.kept': formatPosHardwareCents(Math.max(0, (order.totalCents ?? 0) - (order.refundedCents ?? 0))),\n }\n}\n\n/** What became of one email. */\nexport type PosHardwareEmailOutcome =\n /** Sent. */\n | 'sent'\n /** Nobody to send it to: no address, suppressed, or the account is banned. */\n | 'skipped'\n /** The send failed, and may be tried again. */\n | 'failed'\n\nexport async function sendPosHardwareEmail(\n kind: PosHardwareEmailKind,\n orderId: string,\n order: PosHardwareOrder,\n): Promise<PosHardwareEmailOutcome> {\n try {\n const to = String(order.contactEmail ?? '').trim()\n if (!to) return 'skipped'\n const names = await siteAndOrgNames(order)\n // A ban is a ban (AGL-3420): after its notice the account is sent nothing.\n if (names.ban) return 'skipped'\n const [recipient] = await filterSuppressedEmails([to])\n if (!recipient) return 'skipped'\n const merge = await posHardwareEmailMerge(orderId, order, names)\n const subject = FALLBACK[kind](merge['order.number'])\n // A refund in person is in the selling workspace's brand, as its\n // invitation is; the rest in the buyer's.\n const brand = await orgSystemEmailBrand(kind === 'refunded' ? (order.posSale?.orgId ?? order.orgId) : order.orgId)\n // A canceled order's workspace may be gone, so its fallback names the\n // refund rather than linking a card that no longer opens.\n const last =\n kind === 'canceled'\n ? `Refunded: ${merge['order.refunded']}`\n : kind === 'refunded'\n ? `Refunded now: ${merge['order.refundedNow']}`\n : merge['order.ordersUrl']\n const content = await renderSystemEmailContent(POS_HARDWARE_EMAIL_KEYS[kind], merge, brand, {\n subject,\n text: `${subject}\\n\\n${merge['order.items']}\\n\\n${last}`,\n })\n const result = await sendEmail({\n to: recipient,\n ...content,\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: POS_HARDWARE_EMAIL_KEYS[kind],\n })\n if (!result.sent) return 'failed'\n await meterPlatformEmail(1)\n return 'sent'\n } catch (error) {\n console.error('[pos-hardware] email failed', kind, orderId, error)\n return 'failed'\n }\n}\n\n/** How long a claimed send that never finished holds the next one back. */\nconst EMAIL_CLAIM_STALE_MS = 10 * 60 * 1000\n\n/**\n * Sends one email for an order ONCE, under `key` (the kind by default; one\n * per refund for a refund in parts). The claim is a field on the order,\n * `buyerEmails.{key}`, taken in a transaction before the send, so the staff\n * page and a closure, a retried press or two staff at once, send it once\n * between them. A send that failed can be claimed again; one that found\n * nobody to send to is not tried again. Never throws.\n */\nexport async function sendPosHardwareEmailOnce(\n kind: PosHardwareEmailKind,\n orderId: string,\n order: PosHardwareOrder,\n key: string = kind,\n): Promise<PosHardwareEmailOutcome | 'already'> {\n try {\n const firestore = firebaseAdmin.app().firestore()\n const ref = hardwareOrdersRef(order.orgId).doc(orderId)\n const claimed = await firestore.runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) return false\n const held = (snapshot.data()?.buyerEmails ?? {})[key] as { state?: string; atMs?: number } | undefined\n const now = Date.now()\n if (held?.state === 'sent' || held?.state === 'skipped') return false\n if (held?.state === 'sending' && now - Number(held.atMs ?? 0) < EMAIL_CLAIM_STALE_MS) return false\n transaction.set(ref, { buyerEmails: { [key]: { state: 'sending', atMs: now } } }, { merge: true })\n return true\n })\n if (!claimed) return 'already'\n const outcome = await sendPosHardwareEmail(kind, orderId, order)\n await ref\n .set({ buyerEmails: { [key]: { state: outcome === 'sent' ? 'sent' : outcome, atMs: Date.now() } } }, { merge: true })\n .catch((error: unknown) => console.error('[pos-hardware] email claim not settled', kind, orderId, error))\n return outcome\n } catch (error) {\n console.error('[pos-hardware] email claim failed', kind, orderId, error)\n return 'failed'\n }\n}\n\n/**\n * The invitation to sign up (AGL-4038), for someone who bought a card reader\n * in person at the platform's own store with no account yet: create the\n * account with this address and the order joins their workspace on its own.\n * Sent in the selling workspace's brand, which is the platform's. Never\n * throws; the caller has already claimed the send.\n */\n/** The invitation's merge values. Exported for the render spec. */\nexport function posHardwareInviteMerge(orderId: string, order: PosHardwareOrder): Record<string, string> {\n return {\n 'order.number': posHardwareOrderNumber(orderId),\n 'order.items': itemsText(order),\n 'order.total': formatPosHardwareCents(order.totalCents ?? 0),\n 'order.signUpUrl': `${platformConsoleOrigin()}/signup`,\n }\n}\n\nexport async function sendPosHardwareInvite(orderId: string, order: PosHardwareOrder): Promise<void> {\n try {\n const to = String(order.attachment?.email ?? '').trim()\n if (!to) return\n const [recipient] = await filterSuppressedEmails([to])\n if (!recipient) return\n const merge = posHardwareInviteMerge(orderId, order)\n const signUpUrl = merge['order.signUpUrl']\n const subject = FALLBACK.invited(merge['order.number'])\n const brand = await orgSystemEmailBrand(order.posSale?.orgId ?? order.orgId)\n const content = await renderSystemEmailContent(POS_HARDWARE_EMAIL_KEYS.invited, merge, brand, {\n subject,\n text: `${subject}\\n\\n${merge['order.items']}\\n\\nCreate your account with this email address: ${signUpUrl}`,\n })\n const result = await sendEmail({\n to: recipient,\n ...content,\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: POS_HARDWARE_EMAIL_KEYS.invited,\n })\n if (result.sent) await meterPlatformEmail(1)\n } catch (error) {\n console.error('[pos-hardware] invitation failed', orderId, error)\n }\n}\n\n/**\n * A closure canceled an order staff had already placed with Stripe: the\n * merchant is refunded, and Stripe will still ship it unless someone cancels\n * it there. Once per order.\n */\nexport async function raisePosHardwareCanceledAfterOrderingAlert(\n orderId: string,\n order: PosHardwareOrder,\n reason: PosHardwareCancelReason,\n): Promise<void> {\n try {\n const stripeOrderId = String(order.stripeHardwareOrderId ?? '').trim()\n await raiseOperatorAlert(COMMERCE_POS_HARDWARE_CANCELED_AFTER_ORDERING, {\n dedupeKey: orderId,\n orgId: order.orgId,\n hostId: order.hostId,\n context: {\n orderNumber: posHardwareOrderNumber(orderId),\n amount: formatOperatorAlertAmount(order.totalCents ?? 0),\n items: (order.lines ?? []).map((line) => `${line.quantity} × ${line.name}`).join(', '),\n reason: staffReasonText(reason, order.orgId),\n stripeOrder: stripeOrderId ? ` (Stripe order ${stripeOrderId})` : '',\n },\n })\n } catch (error) {\n console.error('[pos-hardware] canceled-after-ordering alert failed', orderId, error)\n }\n}\n\n/**\n * Stripe refused a closure's refund, and the closure went ahead without it.\n * Carries the payment to refund by hand, never the buyer.\n */\nexport async function raisePosHardwareRefundFailedAlert(\n orderId: string,\n order: PosHardwareOrder,\n reason: PosHardwareCancelReason,\n error: string,\n): Promise<void> {\n try {\n const stripeOrderId = String(order.stripeHardwareOrderId ?? '').trim()\n await raiseOperatorAlert(COMMERCE_POS_HARDWARE_REFUND_FAILED, {\n dedupeKey: orderId,\n orgId: order.orgId,\n hostId: order.hostId,\n context: {\n orderNumber: posHardwareOrderNumber(orderId),\n amount: formatOperatorAlertAmount(order.totalCents ?? 0),\n reason: staffReasonText(reason, order.orgId),\n error: error || 'no reason given',\n paymentIntentId: order.stripePaymentIntentId ?? 'for this order (no payment id is recorded on it)',\n orderedNote:\n order.status === 'ordered' || order.status === 'received'\n ? `. It had already been placed with Stripe${stripeOrderId ? ` as ${stripeOrderId}` : ''}, so cancel it there too before it ships`\n : '',\n },\n })\n } catch (failure) {\n console.error('[pos-hardware] refund-failed alert failed', orderId, failure)\n }\n}\n\n/** \"New hardware order\", once per order. */\nexport async function raisePosHardwareOrderAlert(orderId: string, order: PosHardwareOrder): Promise<void> {\n try {\n const names = await siteAndOrgNames(order)\n await raiseOperatorAlert(COMMERCE_POS_HARDWARE_ORDER, {\n dedupeKey: orderId,\n orgId: order.orgId,\n hostId: order.hostId,\n context: {\n orderNumber: posHardwareOrderNumber(orderId),\n amount: formatOperatorAlertAmount(order.totalCents ?? 0),\n site: `${names.site} (${order.hostId})`,\n items: (order.lines ?? []).map((line) => `${line.quantity} × ${line.name}`).join(', '),\n shipping: order.shipping?.label ?? 'shipping',\n },\n })\n } catch (error) {\n console.error('[pos-hardware] operator alert failed', orderId, error)\n }\n}\n"],"names":["formatOperatorAlertAmount","isAccountBanLockdownReason","normalizeOrgLockdown","POS_HARDWARE_EMAIL_KEYS","sendEmail","platformConsoleOrigin","firebaseAdmin","hostDisplayName","meterPlatformEmail","raiseOperatorAlert","filterSuppressedEmails","orgSystemEmailBrand","renderSystemEmailContent","COMMERCE_POS_HARDWARE_CANCELED_AFTER_ORDERING","COMMERCE_POS_HARDWARE_ORDER","COMMERCE_POS_HARDWARE_REFUND_FAILED","carrierLabelFor","formatPosHardwareCents","POS_HARDWARE_ANCHOR","posHardwareOrderUnits","hardwareOrdersRef","posHardwareOrderNumber","posSettingsUrl","itemsText","order","lines","map","line","name","quantity","join","shipToText","address","shipping","cityLine","city","state","postalCode","filter","Boolean","line1","line2","siteAndOrgNames","firestore","app","attachment","posSale","hostId","seller","collection","doc","get","catch","site","exists","data","org","PENDING_BUYER","ban","host","Promise","all","orgId","lock","String","trim","UNNAMED_WORKSPACE","reason","FALLBACK","received","number","shipped","delivered","canceled","refunded","invited","returnRefunded","cancelReasonText","staffReasonText","posHardwareSetupSteps","units","length","every","unit","readerId","posHardwareEmailMerge","orderId","names","base","path","split","ordersUrl","totalCents","label","tracking","carrier","url","refundedCents","refunds","slice","cents","cancelReason","Math","max","sendPosHardwareEmail","kind","to","contactEmail","recipient","merge","subject","brand","last","content","text","result","fromName","context","sent","error","console","EMAIL_CLAIM_STALE_MS","sendPosHardwareEmailOnce","key","ref","claimed","runTransaction","transaction","held","snapshot","buyerEmails","now","Date","Number","atMs","set","outcome","posHardwareInviteMerge","sendPosHardwareInvite","email","signUpUrl","raisePosHardwareCanceledAfterOrderingAlert","stripeOrderId","stripeHardwareOrderId","dedupeKey","orderNumber","amount","items","stripeOrder","raisePosHardwareRefundFailedAlert","paymentIntentId","stripePaymentIntentId","orderedNote","status","failure","raisePosHardwareOrderAlert"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,yBAAyB,QAAQ,yCAAwC;AAClF,SACEC,0BAA0B,EAC1BC,oBAAoB,QACf,kCAAiC;AACxC,SAASC,uBAAuB,EAAEC,SAAS,QAAQ,2BAA0B;AAC7E,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,aAAa,EACbC,eAAe,EACfC,kBAAkB,EAClBC,kBAAkB,QACb,2BAA0B;AACjC,SAASC,sBAAsB,QAAQ,oDAAmD;AAC1F,SACEC,mBAAmB,EAC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xB,OAAOtC,MAAMsC,KAAK;YAClBf,QAAQvB,MAAMuB,MAAM;YACpBsE,SAAS;gBACP4B,aAAa5H,uBAAuBiE;gBACpC4D,QAAQlJ,2BAA0BwB,oBAAAA,MAAMoE,UAAU,YAAhBpE,oBAAoB;gBACtD6B,MAAM,GAAGkC,MAAMlC,IAAI,CAAC,EAAE,EAAE7B,MAAMuB,MAAM,CAAC,CAAC,CAAC;gBACvCoG,OAAO,EAAC3H,eAAAA,MAAMC,KAAK,YAAXD,eAAe,EAAE,EAAEE,GAAG,CAAC,CAACC,OAAS,GAAGA,KAAKE,QAAQ,CAAC,GAAG,EAAEF,KAAKC,IAAI,EAAE,EAAEE,IAAI,CAAC;gBACjFG,QAAQ,WAAET,kBAAAA,MAAMS,QAAQ,qBAAdT,gBAAgBqE,KAAK,mBAAI;YACrC;QACF;IACF,EAAE,OAAO0B,OAAO;QACdC,QAAQD,KAAK,CAAC,wCAAwCjC,SAASiC;IACjE;AACF"}
@@ -63,6 +63,31 @@ export declare function recordPosHardwareSerials(input: {
63
63
  serials: string[];
64
64
  recorded: boolean;
65
65
  }>;
66
+ /** Records the serial numbers of an order's readers, from the staff page. */
67
+ export declare function recordPosHardwareOrderSerials(input: {
68
+ orgId: string;
69
+ orderId: string;
70
+ serials: unknown;
71
+ }): Promise<PosHardwareOrder>;
72
+ /**
73
+ * Registers one of an order's readers to the buyer's store by the code it
74
+ * shows, from the staff page, before it ships. The order must name the
75
+ * buyer's store (an order from our own store is attached first, from the
76
+ * register's To attach list), and the store's plan must include the point of
77
+ * sale; a store with no reader Location yet is refused with
78
+ * `needs-address`, since only the buyer can say where it is, and the reader
79
+ * is then set up when they pair it.
80
+ */
81
+ export declare function registerPosHardwareOrderReader(input: {
82
+ orgId: string;
83
+ orderId: string;
84
+ registrationCode: unknown;
85
+ label?: unknown;
86
+ uid: string;
87
+ }): Promise<{
88
+ order: PosHardwareOrder;
89
+ readerId: string;
90
+ }>;
66
91
  /**
67
92
  * The store a reader bought in person is for, chosen at setup by someone
68
93
  * who may set up devices there. The store must be the workspace's.
@@ -16,7 +16,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
16
16
  * limitations under the License.
17
17
  */ import * as Aglyn from "@aglyn/aglyn/server";
18
18
  import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
19
- import { normalizePosHardwareSerial, POS_HARDWARE_ORDER_ID, POS_HARDWARE_ORDERS_COLLECTION, posHardwareSaleRecord, posHardwareSaleSetOptions, posHardwareSku } from "../model/pos-hardware.js";
19
+ import { isPosHardwareSellerStoreSale, normalizePosHardwareSerial, POS_HARDWARE_ORDER_ID, POS_HARDWARE_ORDERS_COLLECTION, posHardwareSaleRecord, posHardwareSaleSetOptions, posHardwareOrderUnits, posHardwareSku } from "../model/pos-hardware.js";
20
20
  import { posHardwareAttachmentOf } from "../model/pos-hardware-in-person.js";
21
21
  import { fillPosHardwareBuyerAddress } from "./pos-hardware-buyer-record.js";
22
22
  import { hardwareOrdersRef, posHardwareInPersonOrderId, posHardwareSaleRef } from "./pos-hardware.js";
@@ -114,8 +114,10 @@ function firestore() {
114
114
  const from = await transaction.get(fromRef);
115
115
  if (!from.exists) return false;
116
116
  const before = from.data();
117
- if (before.source !== 'in_person' || before.status === 'canceled' || before.status === 'refunded') return false;
118
- const pending = ((_before_attachment = before.attachment) == null ? void 0 : _before_attachment.state) !== 'attached';
117
+ if (before.status === 'canceled' || before.status === 'refunded') return false;
118
+ // Only a sale of the platform's own store can be nobody's yet; any
119
+ // other order is its workspace's (AGL-4038), set up before it shipped.
120
+ const pending = isPosHardwareSellerStoreSale(before) && ((_before_attachment = before.attachment) == null ? void 0 : _before_attachment.state) !== 'attached';
119
121
  if (!pending && fromOrgId !== input.orgId) return false;
120
122
  const units = withRegisteredUnit((_before_units = before.units) != null ? _before_units : [], serial, input.readerId, input.hostId, now);
121
123
  if (!units) return false;
@@ -215,27 +217,10 @@ function firestore() {
215
217
  const snapshot = await transaction.get(ref);
216
218
  if (!snapshot.exists) throw new PosHardwareReaderRefusal('No such card reader sale.', 404);
217
219
  const before = snapshot.data();
218
- if (before.source !== 'in_person' || ((_before_posSale = before.posSale) == null ? void 0 : _before_posSale.hostId) !== input.config.sellerHostId) {
219
- throw new PosHardwareReaderRefusal('Only a card reader sold in person here takes serial numbers.', 409);
220
+ if (!isPosHardwareSellerStoreSale(before) || ((_before_posSale = before.posSale) == null ? void 0 : _before_posSale.hostId) !== input.config.sellerHostId) {
221
+ throw new PosHardwareReaderRefusal('Only a card reader sold by this store takes serial numbers here.', 409);
220
222
  }
221
- const units = (_before_units = before.units) != null ? _before_units : [];
222
- if (serials.length > units.length) {
223
- throw new PosHardwareReaderRefusal(`This sale has ${units.length} reader${units.length === 1 ? '' : 's'}.`, 400);
224
- }
225
- // Serials fill the readers not yet set up, in order; a registered one keeps its own.
226
- const open = units.map((unit, index)=>({
227
- unit,
228
- index
229
- })).filter(({ unit })=>!unit.readerId);
230
- const next = [
231
- ...units
232
- ];
233
- open.forEach(({ index }, position)=>{
234
- var _serials_position;
235
- next[index] = _extends({}, units[index], {
236
- serialNumber: (_serials_position = serials[position]) != null ? _serials_position : null
237
- });
238
- });
223
+ const next = withPosHardwareSerials((_before_units = before.units) != null ? _before_units : [], serials);
239
224
  transaction.update(ref, {
240
225
  units: next,
241
226
  serialNumbers: next.flatMap((unit)=>unit.serialNumber ? [
@@ -250,6 +235,193 @@ function firestore() {
250
235
  };
251
236
  });
252
237
  }
238
+ /**
239
+ * The units with `serials` filling the readers not yet set up, in order; a
240
+ * registered reader keeps its own. Refuses more serials than readers.
241
+ */ function withPosHardwareSerials(units, serials) {
242
+ if (serials.length > units.length) {
243
+ throw new PosHardwareReaderRefusal(`This order has ${units.length} reader${units.length === 1 ? '' : 's'}.`, 400);
244
+ }
245
+ const open = units.map((unit, index)=>({
246
+ unit,
247
+ index
248
+ })).filter(({ unit })=>!unit.readerId);
249
+ const next = [
250
+ ...units
251
+ ];
252
+ open.forEach(({ index }, position)=>{
253
+ var _serials_position;
254
+ next[index] = _extends({}, units[index], {
255
+ serialNumber: (_serials_position = serials[position]) != null ? _serials_position : null
256
+ });
257
+ });
258
+ return next;
259
+ }
260
+ /** Serial numbers as given: normalized, each once, none already on another order. */ async function checkedSerials(raw, orderId) {
261
+ const serials = (Array.isArray(raw) ? raw : []).map(normalizePosHardwareSerial).filter(Boolean);
262
+ if (new Set(serials).size !== serials.length) {
263
+ throw new PosHardwareReaderRefusal('A serial number is listed twice.', 400);
264
+ }
265
+ for (const serial of serials){
266
+ const elsewhere = await firestore().collectionGroup(POS_HARDWARE_ORDERS_COLLECTION).where('serialNumbers', 'array-contains', serial).limit(2).get();
267
+ if (elsewhere.docs.some((doc)=>String(doc.id) !== orderId)) {
268
+ throw new PosHardwareReaderRefusal(`Serial number ${serial} is already on another order.`, 409);
269
+ }
270
+ }
271
+ return serials;
272
+ }
273
+ /*==========================================
274
+ * SETTING AN ORDER UP BEFORE IT SHIPS (AGL-4038).
275
+ *
276
+ * The platform buys the readers in, receives them, sets them up and ships
277
+ * them to the buyer. Setting one up, on the staff Hardware orders page, is:
278
+ *
279
+ * - its serial number recorded on the order
280
+ * ({@link recordPosHardwareOrderSerials}), so the reader is matched to
281
+ * the order the moment the buyer pairs it on their store, and an order
282
+ * nobody is attached to yet joins the workspace that pairs it;
283
+ * - and, where the buyer's store can already take a reader (its plan
284
+ * includes the point of sale), the reader registered to that store by
285
+ * the code it shows ({@link registerPosHardwareOrderReader}), the same
286
+ * registration the booth and the POS devices card make.
287
+ *
288
+ * Both only while the order is still with the platform (paid, ordered or
289
+ * received), and shipping waits until every reader has its serial
290
+ * (`posHardwareReadyToShip`).
291
+ *=========================================*/ /** The statuses an order is still with the platform in, and can be set up. */ const BEFORE_SHIPPING = new Set([
292
+ 'paid',
293
+ 'ordered',
294
+ 'received'
295
+ ]);
296
+ /** Records the serial numbers of an order's readers, from the staff page. */ export async function recordPosHardwareOrderSerials(input) {
297
+ if (!POS_HARDWARE_ORDER_ID.test(input.orderId)) throw new PosHardwareReaderRefusal('No such order.', 404);
298
+ const serials = await checkedSerials(input.serials, input.orderId);
299
+ const ref = hardwareOrdersRef(input.orgId).doc(input.orderId);
300
+ return firestore().runTransaction(async (transaction)=>{
301
+ const snapshot = await transaction.get(ref);
302
+ if (!snapshot.exists) throw new PosHardwareReaderRefusal('No such order.', 404);
303
+ const before = snapshot.data();
304
+ if (!BEFORE_SHIPPING.has(before.status)) {
305
+ throw new PosHardwareReaderRefusal('Serial numbers are recorded before the order ships.', 409);
306
+ }
307
+ const units = withPosHardwareSerials(posHardwareOrderUnits(before), serials);
308
+ const after = _extends({}, before, {
309
+ units,
310
+ serialNumbers: units.flatMap((unit)=>unit.serialNumber ? [
311
+ unit.serialNumber
312
+ ] : []),
313
+ updatedAtMs: Date.now()
314
+ });
315
+ transaction.set(ref, after);
316
+ transaction.set(posHardwareSaleRef(input.orderId), posHardwareSaleRecord(input.orderId, after), posHardwareSaleSetOptions(after));
317
+ return after;
318
+ });
319
+ }
320
+ /**
321
+ * Registers one of an order's readers to the buyer's store by the code it
322
+ * shows, from the staff page, before it ships. The order must name the
323
+ * buyer's store (an order from our own store is attached first, from the
324
+ * register's To attach list), and the store's plan must include the point of
325
+ * sale; a store with no reader Location yet is refused with
326
+ * `needs-address`, since only the buyer can say where it is, and the reader
327
+ * is then set up when they pair it.
328
+ */ export async function registerPosHardwareOrderReader(input) {
329
+ var _order_attachment;
330
+ if (!POS_HARDWARE_ORDER_ID.test(input.orderId)) throw new PosHardwareReaderRefusal('No such order.', 404);
331
+ const snapshot = await hardwareOrdersRef(input.orgId).doc(input.orderId).get();
332
+ const order = snapshot.data();
333
+ if (!order) throw new PosHardwareReaderRefusal('No such order.', 404);
334
+ if (!BEFORE_SHIPPING.has(order.status)) {
335
+ throw new PosHardwareReaderRefusal('A reader is registered here before the order ships.', 409);
336
+ }
337
+ if (isPosHardwareSellerStoreSale(order) && ((_order_attachment = order.attachment) == null ? void 0 : _order_attachment.state) !== 'attached') {
338
+ throw new PosHardwareReaderRefusal('Attach the order to the buyer’s workspace first, from To attach on our store’s register, or ship it and the reader joins their store when they pair it.', 409);
339
+ }
340
+ if (!order.hostId) throw new PosHardwareReaderRefusal('The buyer has not chosen a store for it yet.', 409);
341
+ if (!posHardwareOrderUnits(order).some((unit)=>!unit.readerId)) {
342
+ throw new PosHardwareReaderRefusal('Every reader on this order is registered.', 409);
343
+ }
344
+ return registerReaderOnOrder({
345
+ orgId: input.orgId,
346
+ orderId: input.orderId,
347
+ hostId: order.hostId,
348
+ registrationCode: input.registrationCode,
349
+ label: input.label,
350
+ uid: input.uid,
351
+ storeAddress: null
352
+ });
353
+ }
354
+ /**
355
+ * The registration itself, for the booth and the staff page: the store's
356
+ * plan and Location checked, the reader registered, and the order's first
357
+ * reader not yet set up (or the one with its serial) marked registered.
358
+ */ async function registerReaderOnOrder(input) {
359
+ const { orgId, hostId } = input;
360
+ const readiness = await posHardwareStoreReadiness(hostId);
361
+ if (!readiness.posPlan) {
362
+ throw new PosHardwareReaderRefusal('Their workspace needs a plan with the point of sale before a reader can be added. They can add it, then set the reader up themselves.', 409);
363
+ }
364
+ if (!readiness.hasLocation && !input.storeAddress) {
365
+ throw new PosHardwareReaderRefusal('Their store has no address for card readers yet. Enter the store’s address to register the reader now, or they add it when they set the reader up on the POS devices card.', 409, 'needs-address');
366
+ }
367
+ const { registerPosTerminalReader } = await import("./pos-readers.js");
368
+ const registered = await registerPosTerminalReader(_extends({
369
+ hostId,
370
+ orgId,
371
+ uid: input.uid,
372
+ registrationCode: input.registrationCode,
373
+ label: input.label
374
+ }, input.storeAddress ? {
375
+ address: input.storeAddress
376
+ } : {}));
377
+ if ('error' in registered) throw new PosHardwareReaderRefusal(registered.error, registered.status);
378
+ // A reader with a serial matched its unit as it registered. One without
379
+ // (or not on the order) takes the first reader of the order not set up yet.
380
+ const ref = hardwareOrdersRef(orgId).doc(input.orderId);
381
+ const after = await firestore().runTransaction(async (transaction)=>{
382
+ const now = (await transaction.get(ref)).data();
383
+ const units = posHardwareOrderUnits(now);
384
+ if (units.some((unit)=>unit.readerId === registered.id)) return now;
385
+ const at = units.findIndex((unit)=>{
386
+ var _posHardwareSku;
387
+ return !unit.readerId && ((_posHardwareSku = posHardwareSku(unit.sku)) == null ? void 0 : _posHardwareSku.kind) === 'reader';
388
+ });
389
+ if (at < 0) return now;
390
+ const stamp = Date.now();
391
+ const next = units.map((unit, index)=>{
392
+ var _unit_serialNumber;
393
+ return index === at ? _extends({}, unit, {
394
+ serialNumber: (_unit_serialNumber = unit.serialNumber) != null ? _unit_serialNumber : registered.reader.serialNumber ? normalizePosHardwareSerial(registered.reader.serialNumber) : null,
395
+ readerId: registered.id,
396
+ hostId,
397
+ registeredAtMs: stamp
398
+ }) : unit;
399
+ });
400
+ const done = everyReaderRegistered(next);
401
+ const updated = _extends({}, now, {
402
+ units: next,
403
+ serialNumbers: next.flatMap((unit)=>unit.serialNumber ? [
404
+ unit.serialNumber
405
+ ] : [])
406
+ }, done && now.status === 'delivered' ? {
407
+ status: 'registered',
408
+ registeredAtMs: stamp
409
+ } : {}, {
410
+ updatedAtMs: stamp
411
+ });
412
+ transaction.set(ref, updated);
413
+ transaction.set(posHardwareSaleRef(input.orderId), posHardwareSaleRecord(input.orderId, updated), posHardwareSaleSetOptions(updated));
414
+ return updated;
415
+ });
416
+ await fillPosHardwareBuyerAddress({
417
+ orgId,
418
+ orderId: input.orderId
419
+ });
420
+ return {
421
+ order: after,
422
+ readerId: registered.id
423
+ };
424
+ }
253
425
  /** An in-person order of this workspace, for a change by its own people. */ function workspaceOrder(orgId, orderId) {
254
426
  if (!POS_HARDWARE_ORDER_ID.test(orderId)) throw new PosHardwareReaderRefusal('No such order.', 404);
255
427
  return {
@@ -265,7 +437,7 @@ function firestore() {
265
437
  const snapshot = await transaction.get(ref);
266
438
  if (!snapshot.exists) throw new PosHardwareReaderRefusal('No such order.', 404);
267
439
  const before = snapshot.data();
268
- if (before.source !== 'in_person') throw new PosHardwareReaderRefusal('Only a reader bought in person waits for a store.', 409);
440
+ if (!isPosHardwareSellerStoreSale(before)) throw new PosHardwareReaderRefusal('Only a reader bought from our store waits for a store.', 409);
269
441
  const after = _extends({}, before, {
270
442
  hostId: input.hostId
271
443
  }, before.attachment ? {
@@ -295,7 +467,7 @@ function firestore() {
295
467
  const snapshot = await transaction.get(ref);
296
468
  if (!snapshot.exists) throw new PosHardwareReaderRefusal('No such order.', 404);
297
469
  const before = snapshot.data();
298
- if (before.source !== 'in_person') throw new PosHardwareReaderRefusal('Only a reader bought in person is marked set up here.', 409);
470
+ if (!isPosHardwareSellerStoreSale(before)) throw new PosHardwareReaderRefusal('Only a reader bought from our store is marked set up here.', 409);
299
471
  if (before.status === 'registered') return before;
300
472
  if (before.status !== 'delivered') throw new PosHardwareReaderRefusal('This order can no longer be set up.', 409);
301
473
  const now = Date.now();
@@ -344,7 +516,7 @@ function firestore() {
344
516
  const orgId = String((_sale_get = sale.get('orgId')) != null ? _sale_get : '');
345
517
  const snapshot = await hardwareOrdersRef(orgId).doc(input.orderId).get();
346
518
  const order = snapshot.data();
347
- if (!order || order.source !== 'in_person' || ((_order_posSale = order.posSale) == null ? void 0 : _order_posSale.hostId) !== input.config.sellerHostId) {
519
+ if (!order || !isPosHardwareSellerStoreSale(order) || ((_order_posSale = order.posSale) == null ? void 0 : _order_posSale.hostId) !== input.config.sellerHostId) {
348
520
  throw new PosHardwareReaderRefusal('No such card reader sale.', 404);
349
521
  }
350
522
  if (((_order_attachment = order.attachment) == null ? void 0 : _order_attachment.state) !== 'attached' || !order.attachment.orgId) {
@@ -353,76 +525,25 @@ function firestore() {
353
525
  const hostId = order.hostId;
354
526
  if (!hostId) throw new PosHardwareReaderRefusal('Choose the buyer’s store first.', 409);
355
527
  const readiness = await posHardwareStoreReadiness(hostId);
356
- if (!readiness.posPlan) {
357
- throw new PosHardwareReaderRefusal('Their workspace needs a plan with the point of sale before a reader can be added. They can add it, then set the reader up themselves.', 409);
358
- }
359
528
  // The store's address, only for a store with no Location: one that has
360
529
  // its Location keeps it, whatever was sent.
361
530
  const storeAddress = readiness.hasLocation ? null : boothStoreAddress(input.address);
362
- if (!readiness.hasLocation) {
363
- if (!storeAddress) {
364
- throw new PosHardwareReaderRefusal('Their store has no address for card readers yet. Enter the store’s address to register the reader now, or they add it when they set the reader up on the POS devices card.', 409, 'needs-address');
365
- }
531
+ if (storeAddress) {
366
532
  const problem = (await import("./pos-terminal.js")).posTerminalAddressProblem(storeAddress);
367
533
  if (problem) throw new PosHardwareReaderRefusal(problem, 400, 'needs-address');
368
534
  }
369
- const { registerPosTerminalReader } = await import("./pos-readers.js");
370
- const registered = await registerPosTerminalReader(_extends({
371
- hostId,
535
+ const { order: after, readerId } = await registerReaderOnOrder({
372
536
  orgId,
373
- uid: input.uid,
537
+ orderId: input.orderId,
538
+ hostId,
374
539
  registrationCode: input.registrationCode,
375
- label: input.label
376
- }, storeAddress ? {
377
- address: storeAddress
378
- } : {}));
379
- if ('error' in registered) throw new PosHardwareReaderRefusal(registered.error, registered.status);
380
- // A reader with a serial matched its unit as it registered. One without
381
- // (or not on the sale) takes the first reader of the sale not set up yet.
382
- const ref = hardwareOrdersRef(orgId).doc(input.orderId);
383
- const after = await firestore().runTransaction(async (transaction)=>{
384
- var _now_units;
385
- const now = (await transaction.get(ref)).data();
386
- const units = (_now_units = now.units) != null ? _now_units : [];
387
- if (units.some((unit)=>unit.readerId === registered.id)) return now;
388
- const at = units.findIndex((unit)=>{
389
- var _posHardwareSku;
390
- return !unit.readerId && ((_posHardwareSku = posHardwareSku(unit.sku)) == null ? void 0 : _posHardwareSku.kind) === 'reader';
391
- });
392
- if (at < 0) return now;
393
- const stamp = Date.now();
394
- const next = units.map((unit, index)=>{
395
- var _unit_serialNumber;
396
- return index === at ? _extends({}, unit, {
397
- serialNumber: (_unit_serialNumber = unit.serialNumber) != null ? _unit_serialNumber : registered.reader.serialNumber ? normalizePosHardwareSerial(registered.reader.serialNumber) : null,
398
- readerId: registered.id,
399
- hostId,
400
- registeredAtMs: stamp
401
- }) : unit;
402
- });
403
- const done = everyReaderRegistered(next);
404
- const updated = _extends({}, now, {
405
- units: next,
406
- serialNumbers: next.flatMap((unit)=>unit.serialNumber ? [
407
- unit.serialNumber
408
- ] : [])
409
- }, done && now.status === 'delivered' ? {
410
- status: 'registered',
411
- registeredAtMs: stamp
412
- } : {}, {
413
- updatedAtMs: stamp
414
- });
415
- transaction.set(ref, updated);
416
- transaction.set(posHardwareSaleRef(input.orderId), posHardwareSaleRecord(input.orderId, updated), posHardwareSaleSetOptions(updated));
417
- return updated;
418
- });
419
- await fillPosHardwareBuyerAddress({
420
- orgId,
421
- orderId: input.orderId
540
+ label: input.label,
541
+ uid: input.uid,
542
+ storeAddress
422
543
  });
423
544
  return {
424
545
  order: after,
425
- readerId: registered.id,
546
+ readerId,
426
547
  storeAddress
427
548
  };
428
549
  }