@aglyn/plugins-commerce 1.14.0 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) 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 +30 -6
  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 +280 -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 +25 -5
  49. package/src/lib/components/product-detail.js.map +1 -1
  50. package/src/lib/constants/operator-alerts.d.ts +1 -1
  51. package/src/lib/constants/operator-alerts.js +4 -4
  52. package/src/lib/constants/operator-alerts.js.map +1 -1
  53. package/src/lib/model/commerce-orders.d.ts +6 -2
  54. package/src/lib/model/commerce-orders.js.map +1 -1
  55. package/src/lib/model/commerce-payment-methods.d.ts +24 -0
  56. package/src/lib/model/commerce-payment-methods.js +35 -0
  57. package/src/lib/model/commerce-payment-methods.js.map +1 -1
  58. package/src/lib/model/commerce.d.ts +6 -0
  59. package/src/lib/model/commerce.js.map +1 -1
  60. package/src/lib/model/index.d.ts +1 -0
  61. package/src/lib/model/index.js +1 -0
  62. package/src/lib/model/index.js.map +1 -1
  63. package/src/lib/model/paid-media.d.ts +8 -0
  64. package/src/lib/model/paid-media.js +13 -0
  65. package/src/lib/model/paid-media.js.map +1 -1
  66. package/src/lib/model/pos-hardware-in-person.d.ts +23 -2
  67. package/src/lib/model/pos-hardware-in-person.js +52 -20
  68. package/src/lib/model/pos-hardware-in-person.js.map +1 -1
  69. package/src/lib/model/pos-hardware-tax-summary.d.ts +5 -1
  70. package/src/lib/model/pos-hardware-tax-summary.js +2 -1
  71. package/src/lib/model/pos-hardware-tax-summary.js.map +1 -1
  72. package/src/lib/model/pos-hardware-terms.d.ts +37 -2
  73. package/src/lib/model/pos-hardware-terms.js +68 -3
  74. package/src/lib/model/pos-hardware-terms.js.map +1 -1
  75. package/src/lib/model/pos-hardware.d.ts +101 -15
  76. package/src/lib/model/pos-hardware.js +128 -18
  77. package/src/lib/model/pos-hardware.js.map +1 -1
  78. package/src/lib/model/pos-reader-splash.js +2 -2
  79. package/src/lib/model/pos-reader-splash.js.map +1 -1
  80. package/src/lib/model/product-write.d.ts +3 -0
  81. package/src/lib/model/subscription-view.d.ts +90 -0
  82. package/src/lib/model/subscription-view.js +176 -0
  83. package/src/lib/model/subscription-view.js.map +1 -0
  84. package/src/lib/server/billing-webhook.d.ts +4 -6
  85. package/src/lib/server/billing-webhook.js +109 -51
  86. package/src/lib/server/billing-webhook.js.map +1 -1
  87. package/src/lib/server/cart-checkout.js +45 -10
  88. package/src/lib/server/cart-checkout.js.map +1 -1
  89. package/src/lib/server/cart.js +15 -3
  90. package/src/lib/server/cart.js.map +1 -1
  91. package/src/lib/server/checkout.js +58 -16
  92. package/src/lib/server/checkout.js.map +1 -1
  93. package/src/lib/server/draft-order.js +7 -3
  94. package/src/lib/server/draft-order.js.map +1 -1
  95. package/src/lib/server/membership-account.d.ts +22 -0
  96. package/src/lib/server/membership-account.js +52 -8
  97. package/src/lib/server/membership-account.js.map +1 -1
  98. package/src/lib/server/pos-auth.d.ts +3 -3
  99. package/src/lib/server/pos-auth.js +3 -3
  100. package/src/lib/server/pos-auth.js.map +1 -1
  101. package/src/lib/server/pos-cellular-billing.js +1 -1
  102. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  103. package/src/lib/server/pos-cellular-notify.js +1 -1
  104. package/src/lib/server/pos-cellular-notify.js.map +1 -1
  105. package/src/lib/server/pos-cellular.js +1 -1
  106. package/src/lib/server/pos-cellular.js.map +1 -1
  107. package/src/lib/server/pos-hardware-admin.js +86 -13
  108. package/src/lib/server/pos-hardware-admin.js.map +1 -1
  109. package/src/lib/server/pos-hardware-attach.js +5 -5
  110. package/src/lib/server/pos-hardware-attach.js.map +1 -1
  111. package/src/lib/server/pos-hardware-cancel.js +65 -0
  112. package/src/lib/server/pos-hardware-cancel.js.map +1 -1
  113. package/src/lib/server/pos-hardware-closure-notices.js +2 -5
  114. package/src/lib/server/pos-hardware-closure-notices.js.map +1 -1
  115. package/src/lib/server/pos-hardware-closure.js +5 -8
  116. package/src/lib/server/pos-hardware-closure.js.map +1 -1
  117. package/src/lib/server/pos-hardware-in-person.d.ts +2 -1
  118. package/src/lib/server/pos-hardware-in-person.js +72 -17
  119. package/src/lib/server/pos-hardware-in-person.js.map +1 -1
  120. package/src/lib/server/pos-hardware-notify.d.ts +2 -0
  121. package/src/lib/server/pos-hardware-notify.js +30 -5
  122. package/src/lib/server/pos-hardware-notify.js.map +1 -1
  123. package/src/lib/server/pos-hardware-readers.d.ts +25 -0
  124. package/src/lib/server/pos-hardware-readers.js +206 -85
  125. package/src/lib/server/pos-hardware-readers.js.map +1 -1
  126. package/src/lib/server/pos-hardware-returns.d.ts +8 -3
  127. package/src/lib/server/pos-hardware-returns.js +39 -7
  128. package/src/lib/server/pos-hardware-returns.js.map +1 -1
  129. package/src/lib/server/pos-hardware-sale-fields.d.ts +76 -0
  130. package/src/lib/server/pos-hardware-sale-fields.js +114 -1
  131. package/src/lib/server/pos-hardware-sale-fields.js.map +1 -1
  132. package/src/lib/server/pos-hardware-sale.d.ts +2 -0
  133. package/src/lib/server/pos-hardware-sale.js +1 -0
  134. package/src/lib/server/pos-hardware-sale.js.map +1 -1
  135. package/src/lib/server/pos-hardware-tax-return-source.js +7 -4
  136. package/src/lib/server/pos-hardware-tax-return-source.js.map +1 -1
  137. package/src/lib/server/pos-hardware-webhook.js +16 -3
  138. package/src/lib/server/pos-hardware-webhook.js.map +1 -1
  139. package/src/lib/server/pos-hardware.d.ts +14 -3
  140. package/src/lib/server/pos-hardware.js +83 -18
  141. package/src/lib/server/pos-hardware.js.map +1 -1
  142. package/src/lib/server/pos-ops-routes.js +2 -10
  143. package/src/lib/server/pos-ops-routes.js.map +1 -1
  144. package/src/lib/server/quote-pay.js +8 -4
  145. package/src/lib/server/quote-pay.js.map +1 -1
  146. package/src/lib/server/stream.d.ts +2 -0
  147. package/src/lib/server/stream.js +22 -2
  148. package/src/lib/server/stream.js.map +1 -1
  149. package/src/lib/server/tax-return-source.js +5 -1
  150. package/src/lib/server/tax-return-source.js.map +1 -1
  151. package/src/lib/server.js +2 -2
  152. package/src/lib/server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-sale.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 { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { consumeRateLimit, firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { addAdminAudit } from '@aglyn/tenant-data-admin/server/admin-audit-write'\nimport { maskEmailAddress } from '@aglyn/tenant-data-admin/server/admin-audit'\nimport { POS_HARDWARE_SKUS, type PosHardwareOrder } from '../model/pos-hardware'\nimport type { PosPermission } from '../model/plugin-permissions'\nimport { authorizePosStaff, posIdempotencyKey, posRequestBody, type PosStaff } from './pos-auth'\nimport { isPosHardwareSellerStore, posHardwareInPersonConfig, posHardwareOrderNumber } from './pos-hardware'\n\n/** How many lookups one register user makes in ten minutes. */\nexport const BUYER_LOOKUPS_PER_WINDOW = 30\nconst LOOKUP_WINDOW_MS = 10 * 60 * 1000\n\n/*==========================================\n * `POST /api/commerce/pos-hardware-sale` (AGL-4038): selling a card reader in\n * person, at the platform's own store's register, to someone who is not a\n * member of it.\n *\n * status whether this store is the platform's hardware seller, and the\n * hardware items a product of it may be — the product editor's\n * \"Point of sale hardware\" choice is shown only where it is.\n * pending the \"To attach\" list: sales of hardware nobody has said whose\n * they are yet (a kiosk or offline sale, a buyer with no account\n * or no workspace yet), newest first. Records any paid sale still\n * waiting to be recorded first (`sweepInPersonPosHardwareSales`).\n * find look the buyer up across the platform by exact email, a\n * person's name or a workspace's name (`pos-hardware-buyer-lookup.ts`):\n * the least that picks the right person, their address in full.\n * Rate-limited per register user and written to the platform's\n * audit log (the address masked there), every time.\n * attach say whose a sale is — by the register sale or the To attach\n * entry — as an account and workspace (and store), an account\n * with no workspace yet, or the address of someone with no\n * account, who is invited to sign up (`pos-hardware-attach.ts`).\n * Idempotency-Key required; audited.\n * detach put an attached sale back on the To attach list. Audited.\n * serials the serial numbers of the sale's readers, scanned or typed at\n * the sale, so the order sets itself up when the buyer registers\n * them (`pos-hardware-readers.ts`).\n * terms the terms of sale the buyer accepts before paying (Terms\n * 4.26–4.32 in short, with the link), and `terms-status` whether\n * they have, for the register waiting on its display.\n * accept-terms the buyer accepted on the register tablet handed to them;\n * `terms-on-display` notes who is putting them on the customer\n * display, before the register shows them there (`pos-hardware-terms.ts`).\n * register-at-booth register a reader to the buyer's chosen store by the\n * code it shows, while they are there, with the store's address\n * when it has no reader Location yet (`address`; refused with\n * `reason: 'needs-address'` without one). Idempotency-Key\n * required; audited.\n *\n * `status` is asked of whoever works the register; everything else needs\n * \"Sell at the register\" (`posSell`) on the seller store, since it is part\n * of ringing a sale there, and answers 404 on any other store.\n *\n * Gated like the register (`authorizePosStaff`, on a plan with POS). Every\n * answer is about THIS store: on any store but the configured seller it says\n * `seller: false` and nothing else, so no other workspace learns the\n * platform's configuration or is shown a control it cannot use.\n *=========================================*/\n\nexport const posHardwareSaleHandler: 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 const permission: PosPermission | undefined = action === 'status' ? undefined : 'posSell'\n const gate = await authorizePosStaff(req, hostId, permission)\n if ('error' in gate) return res.status(gate.status).json({ error: gate.error })\n const staff = gate.staff\n const config = posHardwareInPersonConfig()\n const seller = isPosHardwareSellerStore(config, staff.hostId, staff.orgId)\n try {\n if (action === 'status') {\n if (!seller) return res.status(200).json({ seller: false })\n return res.status(200).json({\n seller: true,\n items: POS_HARDWARE_SKUS.map((sku) => ({ sku: sku.id, name: sku.displayName, kind: sku.kind })),\n })\n }\n if (!seller) return res.status(404).json({ error: 'Card reader sales are not available on this store.' })\n const inPerson = await import('./pos-hardware-in-person')\n switch (action) {\n case 'pending': {\n await inPerson.sweepInPersonPosHardwareSales(config)\n const pending = await inPerson.pendingInPersonPosHardwareOrders(config)\n return res.status(200).json({ orders: pending.map(({ id, order }) => toAttachView(id, order)) })\n }\n case 'find': {\n const query = String(body['query'] ?? '').trim().slice(0, 120)\n if (query.length < 2) return res.status(400).json({ error: 'Type at least two letters, or an email address.' })\n const rate = await consumeRateLimit(`pos-hardware-lookup:${staff.uid}`, {\n limit: BUYER_LOOKUPS_PER_WINDOW,\n windowMs: LOOKUP_WINDOW_MS,\n })\n if (!rate.allowed) return res.status(429).json({ error: 'Too many lookups. Try again in a few minutes.' })\n const found = await (await import('./pos-hardware-buyer-lookup')).findHardwareBuyers(query)\n await audit(staff, 'pos-hardware-buyer-lookup', {\n // The audit log keeps an address masked; a name as typed. The\n // register itself is answered in full.\n query: found.kind === 'email' ? maskEmailAddress(query) : query,\n kind: found.kind,\n matched: [\n ...found.people.map((person) => person.uid),\n ...found.workspaces.map((workspace) => `org:${workspace.orgId}`),\n ],\n })\n return res.status(200).json(found)\n }\n case 'terms':\n case 'terms-status':\n case 'terms-on-display':\n case 'accept-terms': {\n const terms = await import('./pos-hardware-terms')\n const registerOrderId = String(body['registerOrderId'] ?? '')\n try {\n if (action === 'terms') return res.status(200).json(terms.posHardwareTermsView())\n if (action === 'terms-status') {\n return res.status(200).json(await terms.posHardwareTermsStatus(config, registerOrderId))\n }\n if (action === 'terms-on-display') {\n await terms.requestPosHardwareTermsOnDisplay({ config, registerOrderId, uid: staff.uid })\n return res.status(200).json({ ok: true })\n }\n const device = terms.posHardwareTermsDevice(req.headers as Record<string, unknown>)\n const acceptance = await terms.recordPosHardwareTermsAcceptance({\n config,\n registerOrderId,\n method: 'tablet',\n staffUid: staff.uid,\n ...device,\n })\n await audit(staff, 'pos-hardware-terms-accepted', { method: acceptance.method, version: acceptance.version, registerOrderId }, null)\n return res.status(200).json({ ok: true, acceptance })\n } catch (error) {\n if (error instanceof terms.PosHardwareTermsRefusal) {\n return res.status(error.status).json({ error: error.message })\n }\n throw error\n }\n }\n case 'serials':\n case 'register-at-booth': {\n const readers = await import('./pos-hardware-readers')\n try {\n if (action === 'serials') {\n const saved = await readers.recordPosHardwareSerials({\n config,\n registerOrderId: typeof body['registerOrderId'] === 'string' ? body['registerOrderId'] : null,\n orderId: typeof body['orderId'] === 'string' ? body['orderId'] : null,\n serials: body['serials'],\n })\n return res.status(200).json({ ok: true, serials: saved.serials, recorded: saved.recorded })\n }\n if (!posIdempotencyKey(req)) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n const registerOrderId = typeof body['registerOrderId'] === 'string' ? body['registerOrderId'] : ''\n const orderId = registerOrderId\n ? (await import('./pos-hardware')).posHardwareInPersonOrderId(config.sellerHostId, registerOrderId)\n : String(body['orderId'] ?? '')\n const { order, readerId, storeAddress } = await readers.registerPosHardwareAtBooth({\n config,\n orderId,\n registrationCode: body['registrationCode'],\n label: body['label'],\n address: body['address'],\n uid: staff.uid,\n })\n await audit(\n staff,\n 'pos-hardware-register-at-booth',\n {\n readerId,\n hostId: order.hostId,\n orgId: order.orgId,\n // That the buyer's store address was typed here, and where:\n // the store's reader Location was made from it. The street\n // stays with the store, never in the audit log.\n ...(storeAddress\n ? {\n storeAddressEntered: {\n city: storeAddress.city,\n state: storeAddress.state ?? null,\n country: storeAddress.country,\n },\n }\n : {}),\n },\n orderId,\n )\n return res.status(200).json({\n ok: true,\n readerId,\n storeAddressSaved: Boolean(storeAddress),\n order: toAttachView(orderId, order),\n })\n } catch (error) {\n if (error instanceof readers.PosHardwareReaderRefusal) {\n return res\n .status(error.status)\n .json({ error: error.message, ...(error.reason ? { reason: error.reason } : {}) })\n }\n throw error\n }\n }\n case 'attach':\n case 'detach': {\n if (!posIdempotencyKey(req)) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n const attach = await import('./pos-hardware-attach')\n try {\n if (action === 'detach') {\n const orderId = String(body['orderId'] ?? '')\n const { order } = await attach.detachPosHardwareSale({ config, orderId })\n await audit(staff, 'pos-hardware-sale-detach', { orderId }, orderId)\n return res.status(200).json({ ok: true, order: toAttachView(orderId, order) })\n }\n const buyer = await attach.checkHardwareBuyer((body['buyer'] ?? {}) as Record<string, unknown>)\n const outcome = await attach.attachPosHardwareSale({\n config,\n buyer,\n attachedBy: staff.uid,\n registerOrderId: typeof body['registerOrderId'] === 'string' ? body['registerOrderId'] : null,\n orderId: typeof body['orderId'] === 'string' ? body['orderId'] : null,\n })\n const target = outcome.outcome === 'waiting' ? null : outcome.orderId\n await audit(\n staff,\n 'pos-hardware-sale-attach',\n {\n outcome: outcome.outcome,\n uid: buyer.uid,\n orgId: buyer.orgId,\n hostId: buyer.hostId,\n email: buyer.uid ? null : maskEmailAddress(buyer.email),\n ...(outcome.outcome === 'waiting' ? { registerOrderId: outcome.registerOrderId } : {}),\n },\n target,\n )\n return res.status(200).json(\n outcome.outcome === 'waiting'\n ? { outcome: 'waiting' }\n : { outcome: outcome.outcome, order: toAttachView(outcome.orderId, outcome.order) },\n )\n } catch (error) {\n if (error instanceof attach.PosHardwareAttachRefusal) {\n return res.status(error.status).json({ error: error.message })\n }\n throw error\n }\n }\n default:\n return res.status(400).json({ error: 'Unknown action' })\n }\n } catch (error) {\n console.error('[pos-hardware-sale]', action, error)\n return res.status(500).json({ error: 'The card reader sale could not answer' })\n }\n}\n\n/**\n * A sale on the To attach list, as the register shows it: what was sold and\n * when, the register order it came from, and what is known of the buyer —\n * the receipt address, or the address or account a register user gave.\n */\nexport function toAttachView(id: string, order: PosHardwareOrder) {\n return {\n id,\n number: posHardwareOrderNumber(id),\n registerOrderId: order.posSale?.orderId ?? null,\n registerNumber: order.posSale?.number ?? null,\n kiosk: order.posSale?.kiosk === true,\n offline: order.posSale?.offline === true,\n lines: (order.lines ?? []).map((line) => ({ sku: line.sku, name: line.name, quantity: line.quantity })),\n totalCents: order.totalCents ?? 0,\n createdAtMs: order.createdAtMs ?? 0,\n // The buyer's address in full, as the lookup shows it (AGL-4038): the\n // account's, a receipt's, or one typed for a buyer with no account.\n contactEmail: order.contactEmail ?? null,\n attached: order.attachment?.state === 'attached',\n /** Attached with the buyer's store chosen: a reader can be registered to it here. */\n storeChosen: order.attachment?.state === 'attached' && Boolean(order.hostId),\n /** Readers on the sale, and how many have a serial or are set up. */\n readers: (order.units ?? []).length,\n serialsTaken: (order.units ?? []).filter((unit) => unit.serialNumber).length,\n readersSetUp: (order.units ?? []).filter((unit) => unit.readerId).length,\n /** A buyer with an account and no workspace yet. */\n awaitingWorkspace: Boolean(order.attachment?.uid),\n /** A buyer with no account yet, invited to sign up. */\n invited: Boolean(order.attachment?.email && !order.attachment?.uid),\n }\n}\n\nexport type ToAttachView = ReturnType<typeof toAttachView>\n\n/**\n * One row of the platform's audit log for a lookup or an attachment: who on\n * the selling store did it, and what — never the buyer's full address.\n */\nasync function audit(\n staff: PosStaff,\n action: string,\n after: Record<string, unknown>,\n orderId: string | null = null,\n): Promise<void> {\n const firestore = firebaseAdmin.app().firestore()\n await addAdminAudit(firestore, {\n action,\n actorUid: staff.uid,\n actorEmail: null,\n scope: 'posHardwareSale',\n target: orderId ? `posHardwareSales/${orderId}` : `hosts/${staff.hostId}`,\n orgId: staff.orgId,\n before: null,\n after,\n at: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n })\n}\n"],"names":["consumeRateLimit","firebaseAdmin","addAdminAudit","maskEmailAddress","POS_HARDWARE_SKUS","authorizePosStaff","posIdempotencyKey","posRequestBody","isPosHardwareSellerStore","posHardwareInPersonConfig","posHardwareOrderNumber","BUYER_LOOKUPS_PER_WINDOW","LOOKUP_WINDOW_MS","posHardwareSaleHandler","req","res","body","method","status","json","error","hostId","String","action","permission","undefined","gate","staff","config","seller","orgId","items","map","sku","id","name","displayName","kind","inPerson","sweepInPersonPosHardwareSales","pending","pendingInPersonPosHardwareOrders","orders","order","toAttachView","query","trim","slice","length","rate","uid","limit","windowMs","allowed","found","findHardwareBuyers","audit","matched","people","person","workspaces","workspace","terms","registerOrderId","posHardwareTermsView","posHardwareTermsStatus","requestPosHardwareTermsOnDisplay","ok","device","posHardwareTermsDevice","headers","acceptance","recordPosHardwareTermsAcceptance","staffUid","version","PosHardwareTermsRefusal","message","readers","storeAddress","saved","recordPosHardwareSerials","orderId","serials","recorded","posHardwareInPersonOrderId","sellerHostId","readerId","registerPosHardwareAtBooth","registrationCode","label","address","storeAddressEntered","city","state","country","storeAddressSaved","Boolean","PosHardwareReaderRefusal","reason","attach","detachPosHardwareSale","buyer","checkHardwareBuyer","outcome","attachPosHardwareSale","attachedBy","target","email","PosHardwareAttachRefusal","console","number","posSale","registerNumber","kiosk","offline","lines","line","quantity","totalCents","createdAtMs","contactEmail","attached","attachment","storeChosen","units","serialsTaken","filter","unit","serialNumber","readersSetUp","awaitingWorkspace","invited","after","firestore","app","actorUid","actorEmail","scope","before","at","FieldValue","serverTimestamp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AGC,GACD,eAAeM,MACb7B,KAAe,EACfJ,MAAc,EACd6G,KAA8B,EAC9BnD,UAAyB,IAAI;IAE7B,MAAMoD,YAAYpI,cAAcqI,GAAG,GAAGD,SAAS;IAC/C,MAAMnI,cAAcmI,WAAW;QAC7B9G;QACAgH,UAAU5G,MAAMuB,GAAG;QACnBsF,YAAY;QACZC,OAAO;QACP/B,QAAQzB,UAAU,CAAC,iBAAiB,EAAEA,SAAS,GAAG,CAAC,MAAM,EAAEtD,MAAMN,MAAM,EAAE;QACzES,OAAOH,MAAMG,KAAK;QAClB4G,QAAQ;QACRN;QACAO,IAAI1I,cAAcoI,SAAS,CAACO,UAAU,CAACC,eAAe;IACxD;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-sale.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 { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { consumeRateLimit, firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { addAdminAudit } from '@aglyn/tenant-data-admin/server/admin-audit-write'\nimport { maskEmailAddress } from '@aglyn/tenant-data-admin/server/admin-audit'\nimport { POS_HARDWARE_SKUS, type PosHardwareOrder } from '../model/pos-hardware'\nimport type { PosPermission } from '../model/plugin-permissions'\nimport { authorizePosStaff, posIdempotencyKey, posRequestBody, type PosStaff } from './pos-auth'\nimport { isPosHardwareSellerStore, posHardwareInPersonConfig, posHardwareOrderNumber } from './pos-hardware'\n\n/** How many lookups one register user makes in ten minutes. */\nexport const BUYER_LOOKUPS_PER_WINDOW = 30\nconst LOOKUP_WINDOW_MS = 10 * 60 * 1000\n\n/*==========================================\n * `POST /api/commerce/pos-hardware-sale` (AGL-4038): selling a card reader in\n * person, at the platform's own store's register, to someone who is not a\n * member of it.\n *\n * status whether this store is the platform's hardware seller, and the\n * hardware items a product of it may be — the product editor's\n * \"Point of sale hardware\" choice is shown only where it is.\n * pending the \"To attach\" list: sales of hardware nobody has said whose\n * they are yet (a kiosk or offline sale, a buyer with no account\n * or no workspace yet), newest first. Records any paid sale still\n * waiting to be recorded first (`sweepInPersonPosHardwareSales`).\n * find look the buyer up across the platform by exact email, a\n * person's name or a workspace's name (`pos-hardware-buyer-lookup.ts`):\n * the least that picks the right person, their address in full.\n * Rate-limited per register user and written to the platform's\n * audit log (the address masked there), every time.\n * attach say whose a sale is — by the register sale or the To attach\n * entry — as an account and workspace (and store), an account\n * with no workspace yet, or the address of someone with no\n * account, who is invited to sign up (`pos-hardware-attach.ts`).\n * Idempotency-Key required; audited.\n * detach put an attached sale back on the To attach list. Audited.\n * serials the serial numbers of the sale's readers, scanned or typed at\n * the sale, so the order sets itself up when the buyer registers\n * them (`pos-hardware-readers.ts`).\n * terms the terms of sale the buyer accepts before paying (Terms\n * 4.26–4.32 in short, with the link), and `terms-status` whether\n * they have, for the register waiting on its display.\n * accept-terms the buyer accepted on the register tablet handed to them;\n * `terms-on-display` notes who is putting them on the customer\n * display, before the register shows them there (`pos-hardware-terms.ts`).\n * register-at-booth register a reader to the buyer's chosen store by the\n * code it shows, while they are there, with the store's address\n * when it has no reader Location yet (`address`; refused with\n * `reason: 'needs-address'` without one). Idempotency-Key\n * required; audited.\n *\n * `status` is asked of whoever works the register; everything else needs\n * \"Sell at the register\" (`posSell`) on the seller store, since it is part\n * of ringing a sale there, and answers 404 on any other store.\n *\n * Gated like the register (`authorizePosStaff`, on a plan with POS). Every\n * answer is about THIS store: on any store but the configured seller it says\n * `seller: false` and nothing else, so no other workspace learns the\n * platform's configuration or is shown a control it cannot use.\n *=========================================*/\n\nexport const posHardwareSaleHandler: 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 const permission: PosPermission | undefined = action === 'status' ? undefined : 'posSell'\n const gate = await authorizePosStaff(req, hostId, permission)\n if ('error' in gate) return res.status(gate.status).json({ error: gate.error })\n const staff = gate.staff\n const config = posHardwareInPersonConfig()\n const seller = isPosHardwareSellerStore(config, staff.hostId, staff.orgId)\n try {\n if (action === 'status') {\n if (!seller) return res.status(200).json({ seller: false })\n return res.status(200).json({\n seller: true,\n items: POS_HARDWARE_SKUS.map((sku) => ({ sku: sku.id, name: sku.displayName, kind: sku.kind })),\n })\n }\n if (!seller) return res.status(404).json({ error: 'Card reader sales are not available on this store.' })\n const inPerson = await import('./pos-hardware-in-person')\n switch (action) {\n case 'pending': {\n await inPerson.sweepInPersonPosHardwareSales(config)\n const pending = await inPerson.pendingInPersonPosHardwareOrders(config)\n return res.status(200).json({ orders: pending.map(({ id, order }) => toAttachView(id, order)) })\n }\n case 'find': {\n const query = String(body['query'] ?? '').trim().slice(0, 120)\n if (query.length < 2) return res.status(400).json({ error: 'Type at least two letters, or an email address.' })\n const rate = await consumeRateLimit(`pos-hardware-lookup:${staff.uid}`, {\n limit: BUYER_LOOKUPS_PER_WINDOW,\n windowMs: LOOKUP_WINDOW_MS,\n })\n if (!rate.allowed) return res.status(429).json({ error: 'Too many lookups. Try again in a few minutes.' })\n const found = await (await import('./pos-hardware-buyer-lookup')).findHardwareBuyers(query)\n await audit(staff, 'pos-hardware-buyer-lookup', {\n // The audit log keeps an address masked; a name as typed. The\n // register itself is answered in full.\n query: found.kind === 'email' ? maskEmailAddress(query) : query,\n kind: found.kind,\n matched: [\n ...found.people.map((person) => person.uid),\n ...found.workspaces.map((workspace) => `org:${workspace.orgId}`),\n ],\n })\n return res.status(200).json(found)\n }\n case 'terms':\n case 'terms-status':\n case 'terms-on-display':\n case 'accept-terms': {\n const terms = await import('./pos-hardware-terms')\n const registerOrderId = String(body['registerOrderId'] ?? '')\n try {\n if (action === 'terms') return res.status(200).json(terms.posHardwareTermsView())\n if (action === 'terms-status') {\n return res.status(200).json(await terms.posHardwareTermsStatus(config, registerOrderId))\n }\n if (action === 'terms-on-display') {\n await terms.requestPosHardwareTermsOnDisplay({ config, registerOrderId, uid: staff.uid })\n return res.status(200).json({ ok: true })\n }\n const device = terms.posHardwareTermsDevice(req.headers as Record<string, unknown>)\n const acceptance = await terms.recordPosHardwareTermsAcceptance({\n config,\n registerOrderId,\n method: 'tablet',\n staffUid: staff.uid,\n ...device,\n })\n await audit(staff, 'pos-hardware-terms-accepted', { method: acceptance.method, version: acceptance.version, registerOrderId }, null)\n return res.status(200).json({ ok: true, acceptance })\n } catch (error) {\n if (error instanceof terms.PosHardwareTermsRefusal) {\n return res.status(error.status).json({ error: error.message })\n }\n throw error\n }\n }\n case 'serials':\n case 'register-at-booth': {\n const readers = await import('./pos-hardware-readers')\n try {\n if (action === 'serials') {\n const saved = await readers.recordPosHardwareSerials({\n config,\n registerOrderId: typeof body['registerOrderId'] === 'string' ? body['registerOrderId'] : null,\n orderId: typeof body['orderId'] === 'string' ? body['orderId'] : null,\n serials: body['serials'],\n })\n return res.status(200).json({ ok: true, serials: saved.serials, recorded: saved.recorded })\n }\n if (!posIdempotencyKey(req)) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n const registerOrderId = typeof body['registerOrderId'] === 'string' ? body['registerOrderId'] : ''\n const orderId = registerOrderId\n ? (await import('./pos-hardware')).posHardwareInPersonOrderId(config.sellerHostId, registerOrderId)\n : String(body['orderId'] ?? '')\n const { order, readerId, storeAddress } = await readers.registerPosHardwareAtBooth({\n config,\n orderId,\n registrationCode: body['registrationCode'],\n label: body['label'],\n address: body['address'],\n uid: staff.uid,\n })\n await audit(\n staff,\n 'pos-hardware-register-at-booth',\n {\n readerId,\n hostId: order.hostId,\n orgId: order.orgId,\n // That the buyer's store address was typed here, and where:\n // the store's reader Location was made from it. The street\n // stays with the store, never in the audit log.\n ...(storeAddress\n ? {\n storeAddressEntered: {\n city: storeAddress.city,\n state: storeAddress.state ?? null,\n country: storeAddress.country,\n },\n }\n : {}),\n },\n orderId,\n )\n return res.status(200).json({\n ok: true,\n readerId,\n storeAddressSaved: Boolean(storeAddress),\n order: toAttachView(orderId, order),\n })\n } catch (error) {\n if (error instanceof readers.PosHardwareReaderRefusal) {\n return res\n .status(error.status)\n .json({ error: error.message, ...(error.reason ? { reason: error.reason } : {}) })\n }\n throw error\n }\n }\n case 'attach':\n case 'detach': {\n if (!posIdempotencyKey(req)) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n const attach = await import('./pos-hardware-attach')\n try {\n if (action === 'detach') {\n const orderId = String(body['orderId'] ?? '')\n const { order } = await attach.detachPosHardwareSale({ config, orderId })\n await audit(staff, 'pos-hardware-sale-detach', { orderId }, orderId)\n return res.status(200).json({ ok: true, order: toAttachView(orderId, order) })\n }\n const buyer = await attach.checkHardwareBuyer((body['buyer'] ?? {}) as Record<string, unknown>)\n const outcome = await attach.attachPosHardwareSale({\n config,\n buyer,\n attachedBy: staff.uid,\n registerOrderId: typeof body['registerOrderId'] === 'string' ? body['registerOrderId'] : null,\n orderId: typeof body['orderId'] === 'string' ? body['orderId'] : null,\n })\n const target = outcome.outcome === 'waiting' ? null : outcome.orderId\n await audit(\n staff,\n 'pos-hardware-sale-attach',\n {\n outcome: outcome.outcome,\n uid: buyer.uid,\n orgId: buyer.orgId,\n hostId: buyer.hostId,\n email: buyer.uid ? null : maskEmailAddress(buyer.email),\n ...(outcome.outcome === 'waiting' ? { registerOrderId: outcome.registerOrderId } : {}),\n },\n target,\n )\n return res.status(200).json(\n outcome.outcome === 'waiting'\n ? { outcome: 'waiting' }\n : { outcome: outcome.outcome, order: toAttachView(outcome.orderId, outcome.order) },\n )\n } catch (error) {\n if (error instanceof attach.PosHardwareAttachRefusal) {\n return res.status(error.status).json({ error: error.message })\n }\n throw error\n }\n }\n default:\n return res.status(400).json({ error: 'Unknown action' })\n }\n } catch (error) {\n console.error('[pos-hardware-sale]', action, error)\n return res.status(500).json({ error: 'The card reader sale could not answer' })\n }\n}\n\n/**\n * A sale on the To attach list, as the register shows it: what was sold and\n * when, the register order it came from, and what is known of the buyer —\n * the receipt address, or the address or account a register user gave.\n */\nexport function toAttachView(id: string, order: PosHardwareOrder) {\n return {\n id,\n number: posHardwareOrderNumber(id),\n registerOrderId: order.posSale?.orderId ?? null,\n registerNumber: order.posSale?.number ?? null,\n kiosk: order.posSale?.kiosk === true,\n /** Bought from the store's own product pages or cart (AGL-4038), not at the register. */\n online: order.source === 'storefront',\n offline: order.posSale?.offline === true,\n lines: (order.lines ?? []).map((line) => ({ sku: line.sku, name: line.name, quantity: line.quantity })),\n totalCents: order.totalCents ?? 0,\n createdAtMs: order.createdAtMs ?? 0,\n // The buyer's address in full, as the lookup shows it (AGL-4038): the\n // account's, a receipt's, or one typed for a buyer with no account.\n contactEmail: order.contactEmail ?? null,\n attached: order.attachment?.state === 'attached',\n /** Attached with the buyer's store chosen: a reader can be registered to it here. */\n storeChosen: order.attachment?.state === 'attached' && Boolean(order.hostId),\n /** Readers on the sale, and how many have a serial or are set up. */\n readers: (order.units ?? []).length,\n serialsTaken: (order.units ?? []).filter((unit) => unit.serialNumber).length,\n readersSetUp: (order.units ?? []).filter((unit) => unit.readerId).length,\n /** A buyer with an account and no workspace yet. */\n awaitingWorkspace: Boolean(order.attachment?.uid),\n /** A buyer with no account yet, invited to sign up. */\n invited: Boolean(order.attachment?.email && !order.attachment?.uid),\n }\n}\n\nexport type ToAttachView = ReturnType<typeof toAttachView>\n\n/**\n * One row of the platform's audit log for a lookup or an attachment: who on\n * the selling store did it, and what — never the buyer's full address.\n */\nasync function audit(\n staff: PosStaff,\n action: string,\n after: Record<string, unknown>,\n orderId: string | null = null,\n): Promise<void> {\n const firestore = firebaseAdmin.app().firestore()\n await addAdminAudit(firestore, {\n action,\n actorUid: staff.uid,\n actorEmail: null,\n scope: 'posHardwareSale',\n target: orderId ? `posHardwareSales/${orderId}` : `hosts/${staff.hostId}`,\n orgId: staff.orgId,\n before: null,\n after,\n at: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n })\n}\n"],"names":["consumeRateLimit","firebaseAdmin","addAdminAudit","maskEmailAddress","POS_HARDWARE_SKUS","authorizePosStaff","posIdempotencyKey","posRequestBody","isPosHardwareSellerStore","posHardwareInPersonConfig","posHardwareOrderNumber","BUYER_LOOKUPS_PER_WINDOW","LOOKUP_WINDOW_MS","posHardwareSaleHandler","req","res","body","method","status","json","error","hostId","String","action","permission","undefined","gate","staff","config","seller","orgId","items","map","sku","id","name","displayName","kind","inPerson","sweepInPersonPosHardwareSales","pending","pendingInPersonPosHardwareOrders","orders","order","toAttachView","query","trim","slice","length","rate","uid","limit","windowMs","allowed","found","findHardwareBuyers","audit","matched","people","person","workspaces","workspace","terms","registerOrderId","posHardwareTermsView","posHardwareTermsStatus","requestPosHardwareTermsOnDisplay","ok","device","posHardwareTermsDevice","headers","acceptance","recordPosHardwareTermsAcceptance","staffUid","version","PosHardwareTermsRefusal","message","readers","storeAddress","saved","recordPosHardwareSerials","orderId","serials","recorded","posHardwareInPersonOrderId","sellerHostId","readerId","registerPosHardwareAtBooth","registrationCode","label","address","storeAddressEntered","city","state","country","storeAddressSaved","Boolean","PosHardwareReaderRefusal","reason","attach","detachPosHardwareSale","buyer","checkHardwareBuyer","outcome","attachPosHardwareSale","attachedBy","target","email","PosHardwareAttachRefusal","console","number","posSale","registerNumber","kiosk","online","source","offline","lines","line","quantity","totalCents","createdAtMs","contactEmail","attached","attachment","storeChosen","units","serialsTaken","filter","unit","serialNumber","readersSetUp","awaitingWorkspace","invited","after","firestore","app","actorUid","actorEmail","scope","before","at","FieldValue","serverTimestamp"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,gBAAgB,EAAEC,aAAa,QAAQ,2B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ACfJ,MAAc,EACd+G,KAA8B,EAC9BrD,UAAyB,IAAI;IAE7B,MAAMsD,YAAYtI,cAAcuI,GAAG,GAAGD,SAAS;IAC/C,MAAMrI,cAAcqI,WAAW;QAC7BhH;QACAkH,UAAU9G,MAAMuB,GAAG;QACnBwF,YAAY;QACZC,OAAO;QACPjC,QAAQzB,UAAU,CAAC,iBAAiB,EAAEA,SAAS,GAAG,CAAC,MAAM,EAAEtD,MAAMN,MAAM,EAAE;QACzES,OAAOH,MAAMG,KAAK;QAClB8G,QAAQ;QACRN;QACAO,IAAI5I,cAAcsI,SAAS,CAACO,UAAU,CAACC,eAAe;IACxD;AACF"}
@@ -24,9 +24,10 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
24
24
  *
25
25
  * - **sold online from the shop** — on the platform's own account — under
26
26
  * "Card reader shop (online)";
27
- * - **sold in person** at the operator's own store's register: already in
28
- * that store's register sale, which the own-stores section folds in
29
- * (`own-store-tax-return-source.ts`), so NOT again here. Only a sale whose
27
+ * - **sold by the operator's own store**, in person at its register or
28
+ * online from its product pages and cart: already in that store's sale,
29
+ * which the own-stores section folds in (`own-store-tax-return-source.ts`),
30
+ * so NOT again here. Only a sale whose
30
31
  * store is not one of the operator's own (the store was moved, or no
31
32
  * workspace is named as the operator's own) is folded in from its record
32
33
  * here, and a review finding says so.
@@ -51,7 +52,9 @@ import { posHardwareRefundStamp, posHardwareRowInPeriod, posHardwareTaxableBase,
51
52
  /** The part an in-person sale at a store that is not the operator's own folds in under. */ export const POS_HARDWARE_IN_PERSON_PART_ID = 'posHardwareInPerson';
52
53
  /** Where one retained sale record folds into the filing figures. See the module note. */ export function posHardwareFoldedAs(row, options = {}) {
53
54
  var _options_ownHostIds;
54
- if (row.source !== 'in_person') return 'shop';
55
+ // Sold by the operator's own store, at its register or online (AGL-4038):
56
+ // in that store's sale, as every other sale it makes.
57
+ if (row.source !== 'in_person' && row.source !== 'storefront') return 'shop';
55
58
  const host = typeof row.posHostId === 'string' ? row.posHostId : '';
56
59
  return host && ((_options_ownHostIds = options.ownHostIds) == null ? void 0 : _options_ownHostIds.has(host)) ? 'store register sale' : 'in-person record';
57
60
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-tax-return-source.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The POS hardware shop's sales on the operator's sales tax return (AGL-4038).\n *\n * The operator is the seller of record for every card reader order, so these\n * are its OWN sales, unlike the storefront's facilitated ones beside them.\n * They FOLD INTO the filing figures (Items 1–2 for Texas) as the operator's\n * own sales outside its invoices, through the contract's `operatorSales`:\n *\n * - **sold online from the shop** — on the platform's own account — under\n * \"Card reader shop (online)\";\n * - **sold in person** at the operator's own store's register: already in\n * that store's register sale, which the own-stores section folds in\n * (`own-store-tax-return-source.ts`), so NOT again here. Only a sale whose\n * store is not one of the operator's own (the store was moved, or no\n * workspace is named as the operator's own) is folded in from its record\n * here, and a review finding says so.\n *\n * This card states, worded for the filing jurisdiction:\n *\n * - **every card reader sale by ship-to state** (in person: where the store\n * is), with the refunds of the period beside them — the figure an\n * economic-nexus threshold elsewhere is measured against;\n * - **every order in the period** in the working papers, each with where it\n * is folded in.\n *\n * Truncation and rows no period can reach are reported, and the platform\n * raises each as a blocking finding of its own.\n */\n\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { centsToDollars } from '@aglyn/aglyn/app-utils/tax-jurisdiction-figures'\nimport type {\n TaxReturnExportBlock,\n TaxReturnFiling,\n TaxReturnFinding,\n TaxReturnOperatorSalesPart,\n TaxReturnSectionFigure,\n TaxReturnSectionTable,\n TaxReturnSourceAnswer,\n TaxReturnSourceRequest,\n} from '@aglyn/aglyn/plugin-manager/plugin-tax-return-sources'\nimport { POS_HARDWARE_SALES_COLLECTION } from '../model/pos-hardware'\nimport {\n posHardwareRefundStamp,\n posHardwareRowInPeriod,\n posHardwareTaxableBase,\n posHardwareTaxSummary,\n type PosHardwareTaxJurisdiction,\n type PosHardwareTaxRowInput,\n type PosHardwareTaxSummary,\n} from '../model/pos-hardware-tax-summary'\n\n/** The section's id, unique on the return. */\nexport const POS_HARDWARE_TAX_SECTION_ID = 'posHardware'\n\n/** The part the shop's online sales fold into the filing figures under. */\nexport const POS_HARDWARE_SHOP_PART_ID = 'posHardwareShop'\n/** The part an in-person sale at a store that is not the operator's own folds in under. */\nexport const POS_HARDWARE_IN_PERSON_PART_ID = 'posHardwareInPerson'\n\n/** Where an order is folded into the filing figures. */\nexport type PosHardwareFoldedAs = 'shop' | 'store register sale' | 'in-person record'\n\n/** Who decides where a record folds in: the operator's own stores, by site id. */\nexport interface PosHardwareFoldOptions {\n /** The sites of the operator's own stores, whose register sales the own-stores section folds in. */\n ownHostIds?: ReadonlySet<string>\n}\n\n/** Where one retained sale record folds into the filing figures. See the module note. */\nexport function posHardwareFoldedAs(\n row: Pick<PosHardwareTaxRowInput, 'source' | 'posHostId'>,\n options: PosHardwareFoldOptions = {},\n): PosHardwareFoldedAs {\n if (row.source !== 'in_person') return 'shop'\n const host = typeof row.posHostId === 'string' ? row.posHostId : ''\n return host && options.ownHostIds?.has(host) ? 'store register sale' : 'in-person record'\n}\n\n/**\n * The operator's own hardware sales the filing figures fold in from this\n * section: the shop's online sales, and any in-person sale whose store is not\n * the operator's own. Every figure is the summary's own math over that part's\n * records, so the card and the figures cannot disagree.\n */\nexport function posHardwareOperatorSales(\n rows: readonly PosHardwareTaxRowInput[],\n period: { start: Date; end: Date },\n options: PosHardwareFoldOptions = {},\n): TaxReturnOperatorSalesPart[] {\n const parts: Array<{ id: string; label: string; foldedAs: PosHardwareFoldedAs }> = [\n { id: POS_HARDWARE_SHOP_PART_ID, label: 'Card reader shop (online)', foldedAs: 'shop' },\n {\n id: POS_HARDWARE_IN_PERSON_PART_ID,\n label: 'Card readers sold in person (store not read)',\n foldedAs: 'in-person record',\n },\n ]\n return parts.flatMap(({ id, label, foldedAs }) => {\n const summary = posHardwareTaxSummary(\n rows.filter((row) => posHardwareFoldedAs(row, options) === foldedAs),\n period,\n )\n const byJurisdiction = Object.fromEntries(\n Object.entries(summary.byJurisdiction).map(([jurisdiction, figures]) => [\n jurisdiction,\n {\n transactionCount: figures.transactionCount,\n totalSalesCents: figures.totalSalesCents,\n taxableSalesCents: figures.taxableSalesCents,\n taxCollectedCents: figures.taxCollectedCents,\n refundCount: figures.refundedOrders,\n refundedSalesCents: figures.refundedSalesCents,\n refundedTaxCents: figures.refundedTaxCents,\n },\n ]),\n )\n // The shop's part is always stated, so its zero is a figure; an empty\n // in-person part is simply not there.\n return foldedAs === 'shop' || Object.keys(byJurisdiction).length ? [{ id, label, byJurisdiction }] : []\n })\n}\n\n/** One order as the working papers carry it: amounts and the region, no buyer. */\nexport interface PosHardwareTaxRow {\n orderId: string\n paidAt: string | null\n status: string | null\n state: string | null\n country: string | null\n totalSalesCents: number\n taxableSalesCents: number | null\n taxCents: number\n refundedCents: number\n refundedAt: string | null\n /** How the order counts in this period. */\n inPeriodAs: 'sale' | 'refund' | 'sale and refund'\n /** Where it is folded into the filing figures. */\n foldedAs: PosHardwareFoldedAs\n}\n\nconst isoOrNull = (value: number | null): string | null =>\n value === null ? null : new Date(value).toISOString()\n\nconst numberOrNull = (value: unknown): number | null =>\n typeof value === 'number' && Number.isFinite(value) ? value : null\n\nconst textOrNull = (value: unknown): string | null =>\n typeof value === 'string' && value ? value : null\n\nconst emptyFigures = (): PosHardwareTaxJurisdiction => ({\n transactionCount: 0,\n totalSalesCents: 0,\n taxableSalesCents: 0,\n taxCollectedCents: 0,\n taxabilityReasons: {},\n rates: [],\n untaxedOrders: 0,\n refundedOrders: 0,\n refundedSalesCents: 0,\n refundedTaxCents: 0,\n})\n\n/** The filing jurisdiction's hardware figures, or zeros when none sold there. */\nexport function posHardwareFilingFigures(\n summary: PosHardwareTaxSummary,\n filing: TaxReturnFiling,\n): PosHardwareTaxJurisdiction {\n return summary.byJurisdiction[filing.code] ?? emptyFigures()\n}\n\n/** The section's findings. The platform raises the non-zero ones. */\nexport function posHardwareTaxFindings(\n summary: PosHardwareTaxSummary,\n filing: TaxReturnFiling,\n operatorSales: readonly TaxReturnOperatorSalesPart[] = [],\n): TaxReturnFinding[] {\n const brand = PLATFORM_BRAND_NAME\n const figures = posHardwareFilingFigures(summary, filing)\n const unread = operatorSales.find((part) => part.id === POS_HARDWARE_IN_PERSON_PART_ID)\n return [\n {\n // REVIEW: the sales ARE in the figures, from their hardware records;\n // the rest of that store's sales are not, because it is not one of the\n // operator's own stores.\n id: 'posHardwareInPersonStoreNotRead',\n severity: 'review',\n count: Object.values(unread?.byJurisdiction ?? {}).reduce((sum, part) => sum + part.transactionCount, 0),\n label: `Card readers sold in person at a store that is not one of ${brand}’s own`,\n detail:\n `Folded into ${filing.figuresName} from their hardware records. The store that sold them is not a ` +\n `site of the workspace named as ${brand}’s own (POS_HARDWARE_SELLER_ORG_ID), so its other sales are ` +\n 'not in the figures. Name the workspace, or check the store was moved on purpose.',\n },\n {\n id: 'posHardwareUntaxed',\n severity: 'review',\n count: figures.untaxedOrders,\n label: `Card reader hardware sold into ${filing.label} without tax`,\n detail:\n 'Sold while Stripe Tax was off for the hardware shop, so no tax was ' +\n `collected. If the sale was taxable in ${filing.label}, the tax is ` +\n `still owed, out of ${brand}’s receipt.`,\n },\n {\n id: 'posHardwareMissingTaxableBase',\n severity: 'review',\n count: summary.attention.ordersMissingTaxableBase,\n label: 'Card reader hardware orders with tax but no stated base',\n detail:\n 'Tax was collected but Stripe’s taxable_amount was not recorded on the ' +\n 'order, so the hardware taxable-sales line understates the base. Read ' +\n 'the Checkout Session in Stripe with the tax breakdown expanded.',\n },\n {\n id: 'posHardwareMissingShipTo',\n severity: 'review',\n count: summary.attention.ordersMissingShipTo,\n label: 'Card reader hardware orders with no ship-to region',\n detail:\n 'Listed as Not stated, and in no state’s figures. If the order shipped ' +\n `to ${filing.label}, the hardware lines understate its sales.`,\n },\n {\n id: 'posHardwareCanceledWithoutRefund',\n severity: 'review',\n count: summary.attention.canceledWithoutRefund,\n label: 'Canceled card reader hardware orders with no refund recorded',\n detail:\n 'Counted as sales: the order is marked canceled or refunded, but no ' +\n 'refund was recorded on it. Check the payment in Stripe.',\n },\n ]\n}\n\n/** One ship-to state's row, ready to print. */\nexport interface PosHardwareJurisdictionRow {\n jurisdiction: string\n isFilingJurisdiction: boolean\n orders: number\n totalSalesCents: number\n taxableSalesCents: number\n taxCollectedCents: number\n refundedOrders: number\n refundedSalesCents: number\n refundedTaxCents: number\n}\n\n/** Every ship-to state, the filing jurisdiction first, then by sales. */\nexport function posHardwareJurisdictionRows(\n summary: PosHardwareTaxSummary,\n filing: TaxReturnFiling,\n): PosHardwareJurisdictionRow[] {\n return Object.entries(summary.byJurisdiction)\n .map(([jurisdiction, figures]) => ({\n jurisdiction,\n isFilingJurisdiction: jurisdiction === filing.code,\n orders: figures.transactionCount,\n totalSalesCents: figures.totalSalesCents,\n taxableSalesCents: figures.taxableSalesCents,\n taxCollectedCents: figures.taxCollectedCents,\n refundedOrders: figures.refundedOrders,\n refundedSalesCents: figures.refundedSalesCents,\n refundedTaxCents: figures.refundedTaxCents,\n }))\n .sort(\n (a, b) =>\n Number(b.isFilingJurisdiction) - Number(a.isFilingJurisdiction) ||\n b.totalSalesCents - a.totalSalesCents ||\n a.jurisdiction.localeCompare(b.jurisdiction),\n )\n}\n\nconst dollars = (centsValue: number) => `$${centsToDollars(centsValue)}`\n\nfunction posHardwareTables(summary: PosHardwareTaxSummary, filing: TaxReturnFiling): TaxReturnSectionTable[] {\n return [\n {\n description:\n 'Sales by where each order shipped, which is where its sales tax is ' +\n 'sourced, and the refunds made in this period beside them. A state ' +\n 'other than the one filed here is the figure an economic-nexus ' +\n 'threshold there is measured against.',\n columns: [\n { label: 'Ship-to state' },\n { label: 'Orders', numeric: true },\n { label: 'Total sales', numeric: true, money: true },\n { label: 'Taxable sales', numeric: true, money: true },\n { label: 'Tax collected', numeric: true, money: true },\n { label: 'Refunded in period', numeric: true, money: true },\n { label: 'Tax refunded', numeric: true, money: true },\n ],\n rows: posHardwareJurisdictionRows(summary, filing).map((row) => ({\n key: row.jurisdiction,\n cells: [\n {\n text: row.jurisdiction === 'unknown' ? 'Not stated' : row.jurisdiction,\n ...(row.isFilingJurisdiction ? { tag: { label: 'Registered', tone: 'attention' as const } } : {}),\n ...(row.refundedOrders\n ? { caption: `${row.refundedOrders} refund${row.refundedOrders === 1 ? '' : 's'} in this period` }\n : {}),\n },\n { text: String(row.orders) },\n { text: dollars(row.totalSalesCents), strong: row.isFilingJurisdiction },\n { text: dollars(row.taxableSalesCents) },\n { text: dollars(row.taxCollectedCents) },\n { text: dollars(row.refundedSalesCents) },\n { text: dollars(row.refundedTaxCents) },\n ],\n })),\n empty: 'No card reader hardware was sold or refunded in this period.',\n footnote:\n 'Every card reader sale, online and in person. The online ones are folded into the filing figures ' +\n 'as “Card reader shop (online)”; one sold in person is in its store’s register sale there. ' +\n 'Test-mode orders are in no figure. A refund is counted in the period it was made, whenever the ' +\n 'order was paid.',\n },\n ]\n}\n\nfunction posHardwareFigures(summary: PosHardwareTaxSummary): TaxReturnSectionFigure[] {\n const figures: TaxReturnSectionFigure[] = [\n {\n label: 'Orders paid in this period',\n value: String(summary.orders),\n note: 'Every ship-to state. Live orders only.',\n },\n ]\n if (summary.excluded.testModeOrders) {\n figures.push({\n label: 'Test-mode orders left out',\n value: String(summary.excluded.testModeOrders),\n note: 'Made with Stripe’s test keys, so not sales: in no figure above.',\n })\n }\n return figures\n}\n\n/** One record as the working papers carry it, for an order the period counts. */\nfunction projectRow(\n row: PosHardwareTaxRowInput,\n period: { start: Date; end: Date },\n options: PosHardwareFoldOptions,\n): PosHardwareTaxRow {\n const placed = posHardwareRowInPeriod(row, period)\n const total = Number(row.totalCents ?? 0) || 0\n const tax = Number(row.taxCents ?? 0) || 0\n return {\n orderId: row.orderId,\n paidAt: isoOrNull(numberOrNull(row.paidAtMs)),\n status: textOrNull(row.status),\n state: textOrNull(row.shipTo?.state),\n country: textOrNull(row.shipTo?.country),\n totalSalesCents: total - tax,\n taxableSalesCents: posHardwareTaxableBase(Array.isArray(row.taxLines) ? row.taxLines : []),\n taxCents: tax,\n refundedCents: Number(row.refundedCents ?? 0) || 0,\n refundedAt: isoOrNull(posHardwareRefundStamp(row)),\n inPeriodAs: placed.sale && placed.refund ? 'sale and refund' : placed.sale ? 'sale' : 'refund',\n foldedAs: posHardwareFoldedAs(row, options),\n }\n}\n\nfunction posHardwareExports(\n summary: PosHardwareTaxSummary,\n filing: TaxReturnFiling,\n rows: readonly PosHardwareTaxRow[],\n): TaxReturnExportBlock[] {\n const brand = PLATFORM_BRAND_NAME\n const states = posHardwareJurisdictionRows(summary, filing)\n return [\n {\n placement: 'jurisdictions',\n rows: [\n [`Card reader hardware — ${brand}’s OWN sales by ship-to state (folded into the filing figures above, by source)`],\n [\n 'Ship-to state',\n 'Orders',\n 'Total sales (USD)',\n 'Taxable sales (USD)',\n 'Tax collected (USD)',\n 'Refunded in period (USD)',\n 'Tax refunded (USD)',\n ],\n ...(states.length\n ? states.map((row) => [\n row.jurisdiction,\n String(row.orders),\n centsToDollars(row.totalSalesCents),\n centsToDollars(row.taxableSalesCents),\n centsToDollars(row.taxCollectedCents),\n centsToDollars(row.refundedSalesCents),\n centsToDollars(row.refundedTaxCents),\n ])\n : [['—', '0', '0.00', '0.00', '0.00', '0.00', '0.00']]),\n ],\n },\n {\n placement: 'sections',\n rows: [\n ['Card reader hardware orders in this period (posHardwareSales) — folded into the filing figures as each says'],\n [\n 'Order',\n 'Paid (UTC)',\n 'Status',\n 'Ship-to state',\n 'Country',\n 'Total sales (USD)',\n 'Taxable sales (USD)',\n 'Tax collected (USD)',\n 'Refunded (USD)',\n 'Refunded at (UTC)',\n 'In this period as',\n 'Folded in as',\n ],\n ...rows.map((row) => [\n row.orderId,\n row.paidAt ?? '',\n row.status ?? '',\n row.state ?? '',\n row.country ?? '',\n centsToDollars(row.totalSalesCents),\n row.taxableSalesCents === null ? 'not stated' : centsToDollars(row.taxableSalesCents),\n centsToDollars(row.taxCents),\n centsToDollars(row.refundedCents),\n row.refundedAt ?? '',\n row.inPeriodAs,\n row.foldedAs === 'shop'\n ? 'Card reader shop (online)'\n : row.foldedAs === 'store register sale'\n ? 'its store’s register sale'\n : 'Card readers sold in person (store not read)',\n ]),\n ],\n },\n ]\n}\n\n/**\n * The hardware section for one period, from records already read. Pure, so\n * the section a preparer reads can be proved from fixtures.\n */\nexport function posHardwareTaxReturnAnswer(\n read: { rows: readonly PosHardwareTaxRowInput[]; truncated: boolean; undatedRows: number },\n request: TaxReturnSourceRequest,\n options: PosHardwareFoldOptions = {},\n): TaxReturnSourceAnswer {\n const brand = PLATFORM_BRAND_NAME\n const { filing } = request\n const period = { start: request.start, end: request.end }\n const summary = posHardwareTaxSummary(read.rows, period)\n const operatorSales = posHardwareOperatorSales(read.rows, period, options)\n const seen = new Set<string>()\n const rows = read.rows\n .filter((row) => {\n if (!row?.orderId || seen.has(row.orderId) || row.livemode !== true) return false\n seen.add(row.orderId)\n const placed = posHardwareRowInPeriod(row, period)\n return placed.sale || placed.refund\n })\n .map((row) => projectRow(row, period, options))\n return {\n id: POS_HARDWARE_TAX_SECTION_ID,\n name: 'Card reader hardware',\n title: `Card reader hardware — ${brand}’s own sales`,\n help:\n `Card readers and accessories ${brand} sold to workspaces, online from the POS hardware shop and ` +\n `in person at its own store. ${brand} is the seller, so these are its own sales, folded into the ` +\n 'filing figures above.',\n intro:\n `${brand} is the seller of record for every card reader order, so these are ` +\n `${brand}’s OWN sales, not facilitated ones, and they are folded into ${filing.figuresName}: ` +\n 'the online ones as “Card reader shop (online)”, one sold in person in its store’s register sale. ' +\n 'Refunds are counted in the period they were made and never netted.',\n truncated: read.truncated,\n undatedRows: read.undatedRows,\n findings: posHardwareTaxFindings(summary, filing, operatorSales),\n filingLines: [],\n operatorSales,\n tables: posHardwareTables(summary, filing),\n figures: posHardwareFigures(summary),\n exports: posHardwareExports(summary, filing, rows),\n summary,\n rows,\n }\n}\n\n/**\n * Reads the period's hardware records and answers for them.\n *\n * Three range queries, because a record counts in a period two ways — paid\n * in it, or refunded in it (by the stamp of the status that refunded it) —\n * and a fourth, the honesty check: a range query cannot match a record whose\n * `paidAtMs` is null, so those are counted over all of them and the platform\n * blocks the return on any. Each is a single-field range, served by\n * Firestore's automatic index. A query that reaches the row cap marks the\n * section truncated, and the platform blocks on that too.\n */\nexport async function readPosHardwareTaxReturn(\n request: TaxReturnSourceRequest,\n options: PosHardwareFoldOptions = {},\n): Promise<TaxReturnSourceAnswer> {\n const collection = firebaseAdmin.app().firestore().collection(POS_HARDWARE_SALES_COLLECTION)\n const startMs = request.start.getTime()\n const endMs = request.end.getTime()\n const inRange = (field: string) =>\n collection.where(field, '>=', startMs).where(field, '<', endMs).limit(request.rowCap + 1).get()\n const [paid, refunded, canceled, undated] = await Promise.all([\n inRange('paidAtMs'),\n inRange('refundedAtMs'),\n inRange('canceledAtMs'),\n collection.where('paidAtMs', '==', null).count().get(),\n ])\n const byId = new Map<string, PosHardwareTaxRowInput>()\n for (const snapshot of [paid, refunded, canceled]) {\n for (const doc of snapshot.docs.slice(0, request.rowCap)) {\n if (!byId.has(doc.id)) {\n byId.set(doc.id, { ...(doc.data() as Omit<PosHardwareTaxRowInput, 'orderId'>), orderId: doc.id })\n }\n }\n }\n return posHardwareTaxReturnAnswer(\n {\n rows: [...byId.values()],\n truncated: [paid, refunded, canceled].some((snapshot) => snapshot.size > request.rowCap),\n undatedRows: Number(undated.data().count ?? 0),\n },\n request,\n options,\n )\n}\n"],"names":["firebaseAdmin","PLATFORM_BRAND_NAME","centsToDollars","POS_HARDWARE_SALES_COLLECTION","posHardwareRefundStamp","posHardwareRowInPeriod","posHardwareTaxableBase","posHardwareTaxSummary","POS_HARDWARE_TAX_SECTION_ID","POS_HARDWARE_SHOP_PART_ID","POS_HARDWARE_IN_PERSON_PART_ID","posHardwareFoldedAs","row","options","source","host","posHostId","ownHostIds","has","posHardwareOperatorSales","rows","period","parts","id","label","foldedAs","flatMap","summary","filter","byJurisdiction","Object","fromEntries","entries","map","jurisdiction","figures","transactionCount","totalSalesCents","taxableSalesCents","taxCollectedCents","refundCount","refundedOrders","refundedSalesCents","refundedTaxCents","keys","length","isoOrNull","value","Date","toISOString","numberOrNull","Number","isFinite","textOrNull","emptyFigures","taxabilityReasons","rates","untaxedOrders","posHardwareFilingFigures","filing","code","posHardwareTaxFindings","operatorSales","brand","unread","find","part","severity","count","values","reduce","sum","detail","figuresName","attention","ordersMissingTaxableBase","ordersMissingShipTo","canceledWithoutRefund","posHardwareJurisdictionRows","isFilingJurisdiction","orders","sort","a","b","localeCompare","dollars","centsValue","posHardwareTables","description","columns","numeric","money","key","cells","text","tag","tone","caption","String","strong","empty","footnote","posHardwareFigures","note","excluded","testModeOrders","push","projectRow","placed","total","totalCents","tax","taxCents","orderId","paidAt","paidAtMs","status","state","shipTo","country","Array","isArray","taxLines","refundedCents","refundedAt","inPeriodAs","sale","refund","posHardwareExports","states","placement","posHardwareTaxReturnAnswer","read","request","start","end","seen","Set","livemode","add","name","title","help","intro","truncated","undatedRows","findings","filingLines","tables","exports","readPosHardwareTaxReturn","undated","collection","app","firestore","startMs","getTime","endMs","inRange","field","where","limit","rowCap","get","paid","refunded","canceled","Promise","all","byId","Map","snapshot","doc","docs","slice","set","data","some","size"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GAED,SAASA,a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C,SAAS,GAAGF,UAAU,CAACrJ;IAC9D,MAAMwJ,UAAUtB,QAAQC,KAAK,CAACsB,OAAO;IACrC,MAAMC,QAAQxB,QAAQE,GAAG,CAACqB,OAAO;IACjC,MAAME,UAAU,CAACC,QACfP,WAAWQ,KAAK,CAACD,OAAO,MAAMJ,SAASK,KAAK,CAACD,OAAO,KAAKF,OAAOI,KAAK,CAAC5B,QAAQ6B,MAAM,GAAG,GAAGC,GAAG;IAC/F,MAAM,CAACC,MAAMC,UAAUC,UAAUf,QAAQ,GAAG,MAAMgB,QAAQC,GAAG,CAAC;QAC5DV,QAAQ;QACRA,QAAQ;QACRA,QAAQ;QACRN,WAAWQ,KAAK,CAAC,YAAY,MAAM,MAAM5F,KAAK,GAAG+F,GAAG;KACrD;IACD,MAAMM,OAAO,IAAIC;IACjB,KAAK,MAAMC,YAAY;QAACP;QAAMC;QAAUC;KAAS,CAAE;QACjD,KAAK,MAAMM,OAAOD,SAASE,IAAI,CAACC,KAAK,CAAC,GAAGzC,QAAQ6B,MAAM,EAAG;YACxD,IAAI,CAACO,KAAKvJ,GAAG,CAAC0J,IAAIrJ,EAAE,GAAG;gBACrBkJ,KAAKM,GAAG,CAACH,IAAIrJ,EAAE,EAAE,aAAMqJ,IAAII,IAAI;oBAAgD/D,SAAS2D,IAAIrJ,EAAE;;YAChG;QACF;IACF;IACA,OAAO4G,2BACL;QACE/G,MAAM;eAAIqJ,KAAKpG,MAAM;SAAG;QACxB2E,WAAW;YAACoB;YAAMC;YAAUC;SAAS,CAACW,IAAI,CAAC,CAACN,WAAaA,SAASO,IAAI,GAAG7C,QAAQ6B,MAAM;QACvFjB,aAAa9F,QAAOoG,sBAAAA,QAAQyB,IAAI,GAAG5G,KAAK,YAApBmF,sBAAwB;IAC9C,GACAlB,SACAxH;AAEJ"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-tax-return-source.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The POS hardware shop's sales on the operator's sales tax return (AGL-4038).\n *\n * The operator is the seller of record for every card reader order, so these\n * are its OWN sales, unlike the storefront's facilitated ones beside them.\n * They FOLD INTO the filing figures (Items 1–2 for Texas) as the operator's\n * own sales outside its invoices, through the contract's `operatorSales`:\n *\n * - **sold online from the shop** — on the platform's own account — under\n * \"Card reader shop (online)\";\n * - **sold by the operator's own store**, in person at its register or\n * online from its product pages and cart: already in that store's sale,\n * which the own-stores section folds in (`own-store-tax-return-source.ts`),\n * so NOT again here. Only a sale whose\n * store is not one of the operator's own (the store was moved, or no\n * workspace is named as the operator's own) is folded in from its record\n * here, and a review finding says so.\n *\n * This card states, worded for the filing jurisdiction:\n *\n * - **every card reader sale by ship-to state** (in person: where the store\n * is), with the refunds of the period beside them — the figure an\n * economic-nexus threshold elsewhere is measured against;\n * - **every order in the period** in the working papers, each with where it\n * is folded in.\n *\n * Truncation and rows no period can reach are reported, and the platform\n * raises each as a blocking finding of its own.\n */\n\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { centsToDollars } from '@aglyn/aglyn/app-utils/tax-jurisdiction-figures'\nimport type {\n TaxReturnExportBlock,\n TaxReturnFiling,\n TaxReturnFinding,\n TaxReturnOperatorSalesPart,\n TaxReturnSectionFigure,\n TaxReturnSectionTable,\n TaxReturnSourceAnswer,\n TaxReturnSourceRequest,\n} from '@aglyn/aglyn/plugin-manager/plugin-tax-return-sources'\nimport { POS_HARDWARE_SALES_COLLECTION } from '../model/pos-hardware'\nimport {\n posHardwareRefundStamp,\n posHardwareRowInPeriod,\n posHardwareTaxableBase,\n posHardwareTaxSummary,\n type PosHardwareTaxJurisdiction,\n type PosHardwareTaxRowInput,\n type PosHardwareTaxSummary,\n} from '../model/pos-hardware-tax-summary'\n\n/** The section's id, unique on the return. */\nexport const POS_HARDWARE_TAX_SECTION_ID = 'posHardware'\n\n/** The part the shop's online sales fold into the filing figures under. */\nexport const POS_HARDWARE_SHOP_PART_ID = 'posHardwareShop'\n/** The part an in-person sale at a store that is not the operator's own folds in under. */\nexport const POS_HARDWARE_IN_PERSON_PART_ID = 'posHardwareInPerson'\n\n/** Where an order is folded into the filing figures. */\nexport type PosHardwareFoldedAs = 'shop' | 'store register sale' | 'in-person record'\n\n/** Who decides where a record folds in: the operator's own stores, by site id. */\nexport interface PosHardwareFoldOptions {\n /** The sites of the operator's own stores, whose register sales the own-stores section folds in. */\n ownHostIds?: ReadonlySet<string>\n}\n\n/** Where one retained sale record folds into the filing figures. See the module note. */\nexport function posHardwareFoldedAs(\n row: Pick<PosHardwareTaxRowInput, 'source' | 'posHostId'>,\n options: PosHardwareFoldOptions = {},\n): PosHardwareFoldedAs {\n // Sold by the operator's own store, at its register or online (AGL-4038):\n // in that store's sale, as every other sale it makes.\n if (row.source !== 'in_person' && row.source !== 'storefront') return 'shop'\n const host = typeof row.posHostId === 'string' ? row.posHostId : ''\n return host && options.ownHostIds?.has(host) ? 'store register sale' : 'in-person record'\n}\n\n/**\n * The operator's own hardware sales the filing figures fold in from this\n * section: the shop's online sales, and any in-person sale whose store is not\n * the operator's own. Every figure is the summary's own math over that part's\n * records, so the card and the figures cannot disagree.\n */\nexport function posHardwareOperatorSales(\n rows: readonly PosHardwareTaxRowInput[],\n period: { start: Date; end: Date },\n options: PosHardwareFoldOptions = {},\n): TaxReturnOperatorSalesPart[] {\n const parts: Array<{ id: string; label: string; foldedAs: PosHardwareFoldedAs }> = [\n { id: POS_HARDWARE_SHOP_PART_ID, label: 'Card reader shop (online)', foldedAs: 'shop' },\n {\n id: POS_HARDWARE_IN_PERSON_PART_ID,\n label: 'Card readers sold in person (store not read)',\n foldedAs: 'in-person record',\n },\n ]\n return parts.flatMap(({ id, label, foldedAs }) => {\n const summary = posHardwareTaxSummary(\n rows.filter((row) => posHardwareFoldedAs(row, options) === foldedAs),\n period,\n )\n const byJurisdiction = Object.fromEntries(\n Object.entries(summary.byJurisdiction).map(([jurisdiction, figures]) => [\n jurisdiction,\n {\n transactionCount: figures.transactionCount,\n totalSalesCents: figures.totalSalesCents,\n taxableSalesCents: figures.taxableSalesCents,\n taxCollectedCents: figures.taxCollectedCents,\n refundCount: figures.refundedOrders,\n refundedSalesCents: figures.refundedSalesCents,\n refundedTaxCents: figures.refundedTaxCents,\n },\n ]),\n )\n // The shop's part is always stated, so its zero is a figure; an empty\n // in-person part is simply not there.\n return foldedAs === 'shop' || Object.keys(byJurisdiction).length ? [{ id, label, byJurisdiction }] : []\n })\n}\n\n/** One order as the working papers carry it: amounts and the region, no buyer. */\nexport interface PosHardwareTaxRow {\n orderId: string\n paidAt: string | null\n status: string | null\n state: string | null\n country: string | null\n totalSalesCents: number\n taxableSalesCents: number | null\n taxCents: number\n refundedCents: number\n refundedAt: string | null\n /** How the order counts in this period. */\n inPeriodAs: 'sale' | 'refund' | 'sale and refund'\n /** Where it is folded into the filing figures. */\n foldedAs: PosHardwareFoldedAs\n}\n\nconst isoOrNull = (value: number | null): string | null =>\n value === null ? null : new Date(value).toISOString()\n\nconst numberOrNull = (value: unknown): number | null =>\n typeof value === 'number' && Number.isFinite(value) ? value : null\n\nconst textOrNull = (value: unknown): string | null =>\n typeof value === 'string' && value ? value : null\n\nconst emptyFigures = (): PosHardwareTaxJurisdiction => ({\n transactionCount: 0,\n totalSalesCents: 0,\n taxableSalesCents: 0,\n taxCollectedCents: 0,\n taxabilityReasons: {},\n rates: [],\n untaxedOrders: 0,\n refundedOrders: 0,\n refundedSalesCents: 0,\n refundedTaxCents: 0,\n})\n\n/** The filing jurisdiction's hardware figures, or zeros when none sold there. */\nexport function posHardwareFilingFigures(\n summary: PosHardwareTaxSummary,\n filing: TaxReturnFiling,\n): PosHardwareTaxJurisdiction {\n return summary.byJurisdiction[filing.code] ?? emptyFigures()\n}\n\n/** The section's findings. The platform raises the non-zero ones. */\nexport function posHardwareTaxFindings(\n summary: PosHardwareTaxSummary,\n filing: TaxReturnFiling,\n operatorSales: readonly TaxReturnOperatorSalesPart[] = [],\n): TaxReturnFinding[] {\n const brand = PLATFORM_BRAND_NAME\n const figures = posHardwareFilingFigures(summary, filing)\n const unread = operatorSales.find((part) => part.id === POS_HARDWARE_IN_PERSON_PART_ID)\n return [\n {\n // REVIEW: the sales ARE in the figures, from their hardware records;\n // the rest of that store's sales are not, because it is not one of the\n // operator's own stores.\n id: 'posHardwareInPersonStoreNotRead',\n severity: 'review',\n count: Object.values(unread?.byJurisdiction ?? {}).reduce((sum, part) => sum + part.transactionCount, 0),\n label: `Card readers sold in person at a store that is not one of ${brand}’s own`,\n detail:\n `Folded into ${filing.figuresName} from their hardware records. The store that sold them is not a ` +\n `site of the workspace named as ${brand}’s own (POS_HARDWARE_SELLER_ORG_ID), so its other sales are ` +\n 'not in the figures. Name the workspace, or check the store was moved on purpose.',\n },\n {\n id: 'posHardwareUntaxed',\n severity: 'review',\n count: figures.untaxedOrders,\n label: `Card reader hardware sold into ${filing.label} without tax`,\n detail:\n 'Sold while Stripe Tax was off for the hardware shop, so no tax was ' +\n `collected. If the sale was taxable in ${filing.label}, the tax is ` +\n `still owed, out of ${brand}’s receipt.`,\n },\n {\n id: 'posHardwareMissingTaxableBase',\n severity: 'review',\n count: summary.attention.ordersMissingTaxableBase,\n label: 'Card reader hardware orders with tax but no stated base',\n detail:\n 'Tax was collected but Stripe’s taxable_amount was not recorded on the ' +\n 'order, so the hardware taxable-sales line understates the base. Read ' +\n 'the Checkout Session in Stripe with the tax breakdown expanded.',\n },\n {\n id: 'posHardwareMissingShipTo',\n severity: 'review',\n count: summary.attention.ordersMissingShipTo,\n label: 'Card reader hardware orders with no ship-to region',\n detail:\n 'Listed as Not stated, and in no state’s figures. If the order shipped ' +\n `to ${filing.label}, the hardware lines understate its sales.`,\n },\n {\n id: 'posHardwareCanceledWithoutRefund',\n severity: 'review',\n count: summary.attention.canceledWithoutRefund,\n label: 'Canceled card reader hardware orders with no refund recorded',\n detail:\n 'Counted as sales: the order is marked canceled or refunded, but no ' +\n 'refund was recorded on it. Check the payment in Stripe.',\n },\n ]\n}\n\n/** One ship-to state's row, ready to print. */\nexport interface PosHardwareJurisdictionRow {\n jurisdiction: string\n isFilingJurisdiction: boolean\n orders: number\n totalSalesCents: number\n taxableSalesCents: number\n taxCollectedCents: number\n refundedOrders: number\n refundedSalesCents: number\n refundedTaxCents: number\n}\n\n/** Every ship-to state, the filing jurisdiction first, then by sales. */\nexport function posHardwareJurisdictionRows(\n summary: PosHardwareTaxSummary,\n filing: TaxReturnFiling,\n): PosHardwareJurisdictionRow[] {\n return Object.entries(summary.byJurisdiction)\n .map(([jurisdiction, figures]) => ({\n jurisdiction,\n isFilingJurisdiction: jurisdiction === filing.code,\n orders: figures.transactionCount,\n totalSalesCents: figures.totalSalesCents,\n taxableSalesCents: figures.taxableSalesCents,\n taxCollectedCents: figures.taxCollectedCents,\n refundedOrders: figures.refundedOrders,\n refundedSalesCents: figures.refundedSalesCents,\n refundedTaxCents: figures.refundedTaxCents,\n }))\n .sort(\n (a, b) =>\n Number(b.isFilingJurisdiction) - Number(a.isFilingJurisdiction) ||\n b.totalSalesCents - a.totalSalesCents ||\n a.jurisdiction.localeCompare(b.jurisdiction),\n )\n}\n\nconst dollars = (centsValue: number) => `$${centsToDollars(centsValue)}`\n\nfunction posHardwareTables(summary: PosHardwareTaxSummary, filing: TaxReturnFiling): TaxReturnSectionTable[] {\n return [\n {\n description:\n 'Sales by where each order shipped, which is where its sales tax is ' +\n 'sourced, and the refunds made in this period beside them. A state ' +\n 'other than the one filed here is the figure an economic-nexus ' +\n 'threshold there is measured against.',\n columns: [\n { label: 'Ship-to state' },\n { label: 'Orders', numeric: true },\n { label: 'Total sales', numeric: true, money: true },\n { label: 'Taxable sales', numeric: true, money: true },\n { label: 'Tax collected', numeric: true, money: true },\n { label: 'Refunded in period', numeric: true, money: true },\n { label: 'Tax refunded', numeric: true, money: true },\n ],\n rows: posHardwareJurisdictionRows(summary, filing).map((row) => ({\n key: row.jurisdiction,\n cells: [\n {\n text: row.jurisdiction === 'unknown' ? 'Not stated' : row.jurisdiction,\n ...(row.isFilingJurisdiction ? { tag: { label: 'Registered', tone: 'attention' as const } } : {}),\n ...(row.refundedOrders\n ? { caption: `${row.refundedOrders} refund${row.refundedOrders === 1 ? '' : 's'} in this period` }\n : {}),\n },\n { text: String(row.orders) },\n { text: dollars(row.totalSalesCents), strong: row.isFilingJurisdiction },\n { text: dollars(row.taxableSalesCents) },\n { text: dollars(row.taxCollectedCents) },\n { text: dollars(row.refundedSalesCents) },\n { text: dollars(row.refundedTaxCents) },\n ],\n })),\n empty: 'No card reader hardware was sold or refunded in this period.',\n footnote:\n 'Every card reader sale, online and in person. The online ones are folded into the filing figures ' +\n 'as “Card reader shop (online)”; one sold in person is in its store’s register sale there. ' +\n 'Test-mode orders are in no figure. A refund is counted in the period it was made, whenever the ' +\n 'order was paid.',\n },\n ]\n}\n\nfunction posHardwareFigures(summary: PosHardwareTaxSummary): TaxReturnSectionFigure[] {\n const figures: TaxReturnSectionFigure[] = [\n {\n label: 'Orders paid in this period',\n value: String(summary.orders),\n note: 'Every ship-to state. Live orders only.',\n },\n ]\n if (summary.excluded.testModeOrders) {\n figures.push({\n label: 'Test-mode orders left out',\n value: String(summary.excluded.testModeOrders),\n note: 'Made with Stripe’s test keys, so not sales: in no figure above.',\n })\n }\n return figures\n}\n\n/** One record as the working papers carry it, for an order the period counts. */\nfunction projectRow(\n row: PosHardwareTaxRowInput,\n period: { start: Date; end: Date },\n options: PosHardwareFoldOptions,\n): PosHardwareTaxRow {\n const placed = posHardwareRowInPeriod(row, period)\n const total = Number(row.totalCents ?? 0) || 0\n const tax = Number(row.taxCents ?? 0) || 0\n return {\n orderId: row.orderId,\n paidAt: isoOrNull(numberOrNull(row.paidAtMs)),\n status: textOrNull(row.status),\n state: textOrNull(row.shipTo?.state),\n country: textOrNull(row.shipTo?.country),\n totalSalesCents: total - tax,\n taxableSalesCents: posHardwareTaxableBase(Array.isArray(row.taxLines) ? row.taxLines : []),\n taxCents: tax,\n refundedCents: Number(row.refundedCents ?? 0) || 0,\n refundedAt: isoOrNull(posHardwareRefundStamp(row)),\n inPeriodAs: placed.sale && placed.refund ? 'sale and refund' : placed.sale ? 'sale' : 'refund',\n foldedAs: posHardwareFoldedAs(row, options),\n }\n}\n\nfunction posHardwareExports(\n summary: PosHardwareTaxSummary,\n filing: TaxReturnFiling,\n rows: readonly PosHardwareTaxRow[],\n): TaxReturnExportBlock[] {\n const brand = PLATFORM_BRAND_NAME\n const states = posHardwareJurisdictionRows(summary, filing)\n return [\n {\n placement: 'jurisdictions',\n rows: [\n [`Card reader hardware — ${brand}’s OWN sales by ship-to state (folded into the filing figures above, by source)`],\n [\n 'Ship-to state',\n 'Orders',\n 'Total sales (USD)',\n 'Taxable sales (USD)',\n 'Tax collected (USD)',\n 'Refunded in period (USD)',\n 'Tax refunded (USD)',\n ],\n ...(states.length\n ? states.map((row) => [\n row.jurisdiction,\n String(row.orders),\n centsToDollars(row.totalSalesCents),\n centsToDollars(row.taxableSalesCents),\n centsToDollars(row.taxCollectedCents),\n centsToDollars(row.refundedSalesCents),\n centsToDollars(row.refundedTaxCents),\n ])\n : [['—', '0', '0.00', '0.00', '0.00', '0.00', '0.00']]),\n ],\n },\n {\n placement: 'sections',\n rows: [\n ['Card reader hardware orders in this period (posHardwareSales) — folded into the filing figures as each says'],\n [\n 'Order',\n 'Paid (UTC)',\n 'Status',\n 'Ship-to state',\n 'Country',\n 'Total sales (USD)',\n 'Taxable sales (USD)',\n 'Tax collected (USD)',\n 'Refunded (USD)',\n 'Refunded at (UTC)',\n 'In this period as',\n 'Folded in as',\n ],\n ...rows.map((row) => [\n row.orderId,\n row.paidAt ?? '',\n row.status ?? '',\n row.state ?? '',\n row.country ?? '',\n centsToDollars(row.totalSalesCents),\n row.taxableSalesCents === null ? 'not stated' : centsToDollars(row.taxableSalesCents),\n centsToDollars(row.taxCents),\n centsToDollars(row.refundedCents),\n row.refundedAt ?? '',\n row.inPeriodAs,\n row.foldedAs === 'shop'\n ? 'Card reader shop (online)'\n : row.foldedAs === 'store register sale'\n ? 'its store’s register sale'\n : 'Card readers sold in person (store not read)',\n ]),\n ],\n },\n ]\n}\n\n/**\n * The hardware section for one period, from records already read. Pure, so\n * the section a preparer reads can be proved from fixtures.\n */\nexport function posHardwareTaxReturnAnswer(\n read: { rows: readonly PosHardwareTaxRowInput[]; truncated: boolean; undatedRows: number },\n request: TaxReturnSourceRequest,\n options: PosHardwareFoldOptions = {},\n): TaxReturnSourceAnswer {\n const brand = PLATFORM_BRAND_NAME\n const { filing } = request\n const period = { start: request.start, end: request.end }\n const summary = posHardwareTaxSummary(read.rows, period)\n const operatorSales = posHardwareOperatorSales(read.rows, period, options)\n const seen = new Set<string>()\n const rows = read.rows\n .filter((row) => {\n if (!row?.orderId || seen.has(row.orderId) || row.livemode !== true) return false\n seen.add(row.orderId)\n const placed = posHardwareRowInPeriod(row, period)\n return placed.sale || placed.refund\n })\n .map((row) => projectRow(row, period, options))\n return {\n id: POS_HARDWARE_TAX_SECTION_ID,\n name: 'Card reader hardware',\n title: `Card reader hardware — ${brand}’s own sales`,\n help:\n `Card readers and accessories ${brand} sold to workspaces, online from the POS hardware shop and ` +\n `in person at its own store. ${brand} is the seller, so these are its own sales, folded into the ` +\n 'filing figures above.',\n intro:\n `${brand} is the seller of record for every card reader order, so these are ` +\n `${brand}’s OWN sales, not facilitated ones, and they are folded into ${filing.figuresName}: ` +\n 'the online ones as “Card reader shop (online)”, one sold in person in its store’s register sale. ' +\n 'Refunds are counted in the period they were made and never netted.',\n truncated: read.truncated,\n undatedRows: read.undatedRows,\n findings: posHardwareTaxFindings(summary, filing, operatorSales),\n filingLines: [],\n operatorSales,\n tables: posHardwareTables(summary, filing),\n figures: posHardwareFigures(summary),\n exports: posHardwareExports(summary, filing, rows),\n summary,\n rows,\n }\n}\n\n/**\n * Reads the period's hardware records and answers for them.\n *\n * Three range queries, because a record counts in a period two ways — paid\n * in it, or refunded in it (by the stamp of the status that refunded it) —\n * and a fourth, the honesty check: a range query cannot match a record whose\n * `paidAtMs` is null, so those are counted over all of them and the platform\n * blocks the return on any. Each is a single-field range, served by\n * Firestore's automatic index. A query that reaches the row cap marks the\n * section truncated, and the platform blocks on that too.\n */\nexport async function readPosHardwareTaxReturn(\n request: TaxReturnSourceRequest,\n options: PosHardwareFoldOptions = {},\n): Promise<TaxReturnSourceAnswer> {\n const collection = firebaseAdmin.app().firestore().collection(POS_HARDWARE_SALES_COLLECTION)\n const startMs = request.start.getTime()\n const endMs = request.end.getTime()\n const inRange = (field: string) =>\n collection.where(field, '>=', startMs).where(field, '<', endMs).limit(request.rowCap + 1).get()\n const [paid, refunded, canceled, undated] = await Promise.all([\n inRange('paidAtMs'),\n inRange('refundedAtMs'),\n inRange('canceledAtMs'),\n collection.where('paidAtMs', '==', null).count().get(),\n ])\n const byId = new Map<string, PosHardwareTaxRowInput>()\n for (const snapshot of [paid, refunded, canceled]) {\n for (const doc of snapshot.docs.slice(0, request.rowCap)) {\n if (!byId.has(doc.id)) {\n byId.set(doc.id, { ...(doc.data() as Omit<PosHardwareTaxRowInput, 'orderId'>), orderId: doc.id })\n }\n }\n }\n return posHardwareTaxReturnAnswer(\n {\n rows: [...byId.values()],\n truncated: [paid, refunded, canceled].some((snapshot) => snapshot.size > request.rowCap),\n undatedRows: Number(undated.data().count ?? 0),\n },\n request,\n options,\n )\n}\n"],"names":["firebaseAdmin","PLATFORM_BRAND_NAME","centsToDollars","POS_HARDWARE_SALES_COLLECTION","posHardwareRefundStamp","posHardwareRowInPeriod","posHardwareTaxableBase","posHardwareTaxSummary","POS_HARDWARE_TAX_SECTION_ID","POS_HARDWARE_SHOP_PART_ID","POS_HARDWARE_IN_PERSON_PART_ID","posHardwareFoldedAs","row","options","source","host","posHostId","ownHostIds","has","posHardwareOperatorSales","rows","period","parts","id","label","foldedAs","flatMap","summary","filter","byJurisdiction","Object","fromEntries","entries","map","jurisdiction","figures","transactionCount","totalSalesCents","taxableSalesCents","taxCollectedCents","refundCount","refundedOrders","refundedSalesCents","refundedTaxCents","keys","length","isoOrNull","value","Date","toISOString","numberOrNull","Number","isFinite","textOrNull","emptyFigures","taxabilityReasons","rates","untaxedOrders","posHardwareFilingFigures","filing","code","posHardwareTaxFindings","operatorSales","brand","unread","find","part","severity","count","values","reduce","sum","detail","figuresName","attention","ordersMissingTaxableBase","ordersMissingShipTo","canceledWithoutRefund","posHardwareJurisdictionRows","isFilingJurisdiction","orders","sort","a","b","localeCompare","dollars","centsValue","posHardwareTables","description","columns","numeric","money","key","cells","text","tag","tone","caption","String","strong","empty","footnote","posHardwareFigures","note","excluded","testModeOrders","push","projectRow","placed","total","totalCents","tax","taxCents","orderId","paidAt","paidAtMs","status","state","shipTo","country","Array","isArray","taxLines","refundedCents","refundedAt","inPeriodAs","sale","refund","posHardwareExports","states","placement","posHardwareTaxReturnAnswer","read","request","start","end","seen","Set","livemode","add","name","title","help","intro","truncated","undatedRows","findings","filingLines","tables","exports","readPosHardwareTaxReturn","undated","collection","app","firestore","startMs","getTime","endMs","inRange","field","where","limit","rowCap","get","paid","refunded","canceled","Promise","all","byId","Map","snapshot","doc","docs","slice","set","data","some","size"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,cAAc,QAAQ,kDAAiD;AAWhF,SAASC,6BAA6B,QAAQ,2BAAuB;AACrE,S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O;IACrC,MAAMC,QAAQxB,QAAQE,GAAG,CAACqB,OAAO;IACjC,MAAME,UAAU,CAACC,QACfP,WAAWQ,KAAK,CAACD,OAAO,MAAMJ,SAASK,KAAK,CAACD,OAAO,KAAKF,OAAOI,KAAK,CAAC5B,QAAQ6B,MAAM,GAAG,GAAGC,GAAG;IAC/F,MAAM,CAACC,MAAMC,UAAUC,UAAUf,QAAQ,GAAG,MAAMgB,QAAQC,GAAG,CAAC;QAC5DV,QAAQ;QACRA,QAAQ;QACRA,QAAQ;QACRN,WAAWQ,KAAK,CAAC,YAAY,MAAM,MAAM5F,KAAK,GAAG+F,GAAG;KACrD;IACD,MAAMM,OAAO,IAAIC;IACjB,KAAK,MAAMC,YAAY;QAACP;QAAMC;QAAUC;KAAS,CAAE;QACjD,KAAK,MAAMM,OAAOD,SAASE,IAAI,CAACC,KAAK,CAAC,GAAGzC,QAAQ6B,MAAM,EAAG;YACxD,IAAI,CAACO,KAAKvJ,GAAG,CAAC0J,IAAIrJ,EAAE,GAAG;gBACrBkJ,KAAKM,GAAG,CAACH,IAAIrJ,EAAE,EAAE,aAAMqJ,IAAII,IAAI;oBAAgD/D,SAAS2D,IAAIrJ,EAAE;;YAChG;QACF;IACF;IACA,OAAO4G,2BACL;QACE/G,MAAM;eAAIqJ,KAAKpG,MAAM;SAAG;QACxB2E,WAAW;YAACoB;YAAMC;YAAUC;SAAS,CAACW,IAAI,CAAC,CAACN,WAAaA,SAASO,IAAI,GAAG7C,QAAQ6B,MAAM;QACvFjB,aAAa9F,QAAOoG,sBAAAA,QAAQyB,IAAI,GAAG5G,KAAK,YAApBmF,sBAAwB;IAC9C,GACAlB,SACAxH;AAEJ"}
@@ -15,7 +15,8 @@
15
15
  * limitations under the License.
16
16
  */ import { _ as _extends } from "@swc/helpers/_/_extends";
17
17
  import { firebaseAdmin } from "@aglyn/tenant-data-admin";
18
- import { decodePosHardwareLines, isPosHardwareShippingMethod, POS_HARDWARE_CURRENCY, POS_HARDWARE_METADATA_TYPE, POS_HARDWARE_ORDER_ID, POS_HARDWARE_SHIPPING_LABELS, posHardwareSaleRecord, posHardwareSaleSetOptions } from "../model/pos-hardware.js";
18
+ import { decodePosHardwareLines, isPosHardwareShippingMethod, POS_HARDWARE_CURRENCY, POS_HARDWARE_METADATA_TYPE, POS_HARDWARE_ORDER_ID, POS_HARDWARE_SHIPPING_LABELS, posHardwareOrderUnits, posHardwareSaleRecord, posHardwareSaleSetOptions } from "../model/pos-hardware.js";
19
+ import { posHardwareTermsFromMetadata } from "../model/pos-hardware-terms.js";
19
20
  import { hardwareOrdersRef, posHardwareSaleRef } from "./pos-hardware.js";
20
21
  import { raisePosHardwareOrderAlert, sendPosHardwareEmail } from "./pos-hardware-notify.js";
21
22
  import { posStripe } from "./pos-stripe.js";
@@ -92,9 +93,13 @@ const cents = (value)=>{
92
93
  const taxCents = cents(session == null ? void 0 : (_session_total_details = session.total_details) == null ? void 0 : _session_total_details.amount_tax);
93
94
  const totalCents = (session == null ? void 0 : session.amount_total) != null ? cents(session.amount_total) : subtotalCents + shippingCents + taxCents;
94
95
  const paymentIntent = session == null ? void 0 : session.payment_intent;
96
+ // The terms of sale and business use the buyer ticked on the Hardware card
97
+ // (AGL-4038), accepted when the session was made.
98
+ const createdMs = Number(session == null ? void 0 : session.created) > 0 ? Number(session.created) * 1000 : now;
99
+ const termsAcceptance = posHardwareTermsFromMetadata(metadata, createdMs);
95
100
  return {
96
101
  orderId,
97
- order: {
102
+ order: _extends({
98
103
  orgId,
99
104
  hostId,
100
105
  createdBy: String((_metadata_uid = metadata.uid) != null ? _metadata_uid : ''),
@@ -125,7 +130,15 @@ const cents = (value)=>{
125
130
  createdAtMs: now,
126
131
  updatedAtMs: now,
127
132
  paidAtMs: now
128
- }
133
+ }, termsAcceptance ? {
134
+ termsAcceptance
135
+ } : {}, {
136
+ // One per reader, for its serial when staff set it up before it ships.
137
+ units: posHardwareOrderUnits({
138
+ lines
139
+ }),
140
+ serialNumbers: []
141
+ })
129
142
  };
130
143
  }
131
144
  /**
@@ -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,QAAQ,oBAAgB;AACtE,SAASC,0BAA0B,EAAEC,oBAAoB,QAAQ,2BAAuB;AACxF,SAAS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K,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","posHardwareBillingWebhookHand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I,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;