@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-attach.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 { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n findUserByEmailAcrossPools,\n findUserByUidAcrossPools,\n} from '@aglyn/tenant-data-admin/server/auth-pools'\nimport type { OrderHardwareBuyer } from '../model/commerce-orders'\nimport {\n POS_HARDWARE_ORDER_ID,\n posHardwareBuyerAddress,\n posHardwareSaleRecord,\n posHardwareSaleSetOptions,\n type PosHardwareAddress,\n type PosHardwareInPersonConfig,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\nimport { posHardwareAttachmentOf } from '../model/pos-hardware-in-person'\nimport { hardwareOrdersRef, posHardwareInPersonOrderId, posHardwareSaleRef } from './pos-hardware'\nimport { recordInPersonPosHardwareSale } from './pos-hardware-in-person'\nimport { sendPosHardwareInvite } from './pos-hardware-notify'\n\n/*==========================================\n * ATTACHING AN IN-PERSON SALE TO ITS BUYER (AGL-4038).\n *\n * The register user who sold a card reader says whose it is: an account and\n * the workspace (and, if they chose one, the store) it is for; an account\n * with no workspace yet; or the address of someone with no account, who is\n * then invited to sign up. The order moves to the buyer's workspace the\n * moment it has one, and is pending on the selling workspace's To attach\n * list until then.\n *\n * Every attachment is checked here, never trusted from the register: the\n * account exists, it is a member of the workspace, the store is the\n * workspace's, and an address given for \"no account\" really has none.\n *\n * A sale not recorded yet (the register attaches the buyer while the sale is\n * still open, or the instant it is paid) carries the buyer on the register\n * order (`hardwareBuyer`), and the recorder builds the order already\n * attached. A sale already recorded is moved: created in the buyer's\n * workspace and deleted from where it was, with its retained sale record and\n * the register order, in one transaction.\n *\n * A NEW WORKSPACE CLAIMS ITS OWNER'S SALES. When a buyer who was invited\n * signs up and creates a workspace, every pending sale naming their verified\n * address (or their account) moves into it ({@link claimPosHardwareForNewWorkspace}).\n *=========================================*/\n\nexport class PosHardwareAttachRefusal extends Error {\n constructor(\n message: string,\n readonly status: number,\n ) {\n super(message)\n }\n}\n\n/** Who the register says the buyer is, before it is checked. */\nexport interface PosHardwareBuyerRequest {\n uid?: unknown\n orgId?: unknown\n hostId?: unknown\n email?: unknown\n /** The buyer's name, typed at the sale; an account's own name wins. */\n name?: unknown\n /** The buyer's business address, typed at the sale (optional). */\n address?: unknown\n}\n\nconst ID = /^[A-Za-z0-9_-]{1,128}$/\nconst EMAIL = /^[^@\\s]{1,64}@[^@\\s]+\\.[^@\\s]{2,}$/\n\nconst id = (value: unknown): string | null => (typeof value === 'string' && ID.test(value.trim()) ? value.trim() : null)\n\nfunction firestore() {\n return firebaseAdmin.app().firestore()\n}\n\n/** A checked buyer: who they are, where the order goes, where its emails go. */\nexport interface CheckedBuyer {\n uid: string | null\n orgId: string | null\n hostId: string | null\n email: string | null\n /**\n * The buyer's name and business address, for the platform's reseller\n * records (AGL-4038): the account's name, else the one typed; the address\n * typed at the sale, when one was.\n */\n name?: string | null\n address?: PosHardwareAddress | null\n}\n\n/** The name and address the register typed, checked: an address is all of it or refused. */\nfunction typedIdentity(request: PosHardwareBuyerRequest): { name: string | null; address: PosHardwareAddress | null } {\n const name = typeof request.name === 'string' && request.name.trim() ? request.name.trim().slice(0, 200) : null\n if (request.address === undefined || request.address === null || request.address === '') {\n return { name, address: null }\n }\n const address = posHardwareBuyerAddress(request.address)\n if (!address) {\n throw new PosHardwareAttachRefusal('Enter the buyer’s street, city, postal code and two-letter country, or leave the address empty.', 400)\n }\n return { name, address }\n}\n\n/**\n * The buyer the register named, checked. Refuses an account that does not\n * exist or is not in the workspace, a store not in the workspace, and an\n * address said to have no account that has one.\n */\nexport async function checkHardwareBuyer(request: PosHardwareBuyerRequest): Promise<CheckedBuyer> {\n const uid = id(request.uid)\n const orgId = id(request.orgId)\n const hostId = id(request.hostId)\n const typed = typedIdentity(request)\n if (uid) {\n const user = await findUserByUidAcrossPools(uid)\n if (!user) throw new PosHardwareAttachRefusal('That account no longer exists. Look the buyer up again.', 404)\n const email = String(user.record.email ?? '').trim().toLowerCase() || null\n const name = String(user.record.displayName ?? '').trim().slice(0, 200) || typed.name\n if (!orgId) return { uid, orgId: null, hostId: null, email, name, address: typed.address }\n const member = await firestore().collection('orgs').doc(orgId).collection('members').doc(uid).get()\n if (!member.exists) {\n throw new PosHardwareAttachRefusal('That person is not on that workspace. Look the buyer up again.', 409)\n }\n if (hostId) {\n const host = await firestore().collection('hosts').doc(hostId).get()\n if (!host.exists || host.get('orgId') !== orgId) {\n throw new PosHardwareAttachRefusal('That store is not in the buyer’s workspace.', 409)\n }\n }\n return { uid, orgId, hostId, email, name, address: typed.address }\n }\n const email = String(request.email ?? '').trim().toLowerCase()\n if (!EMAIL.test(email)) throw new PosHardwareAttachRefusal('Enter the buyer’s email address.', 400)\n if (await findUserByEmailAcrossPools(email)) {\n throw new PosHardwareAttachRefusal(\n 'That email already has an account. Look it up and attach the account instead.',\n 409,\n )\n }\n return { uid: null, orgId: null, hostId: null, email, ...typed }\n}\n\n/** The buyer as the register order keeps it. */\nfunction orderBuyer(buyer: CheckedBuyer, attachedBy: string | null, now: number): OrderHardwareBuyer {\n return {\n uid: buyer.uid,\n orgId: buyer.orgId,\n hostId: buyer.hostId,\n email: buyer.email,\n attachedBy: attachedBy ?? '',\n attachedAtMs: now,\n ...(buyer.name ? { name: buyer.name } : {}),\n ...(buyer.address ? { address: buyer.address } : {}),\n }\n}\n\nexport type PosHardwareAttachOutcome =\n | { outcome: 'waiting'; registerOrderId: string }\n | { outcome: 'attached' | 'pending'; orderId: string; orgId: string; order: PosHardwareOrder }\n\n/**\n * Moves (or re-stamps) a recorded order for its new buyer, in one\n * transaction with its sale record and the register order. Returns the order\n * as it now stands.\n */\nasync function moveRecordedOrder(input: {\n orderId: string\n buyer: CheckedBuyer\n attachedBy: string | null\n config: PosHardwareInPersonConfig\n now: number\n /** Only a pending order moves: an attached one must be detached first. */\n requirePending: boolean\n}): Promise<{ order: PosHardwareOrder; orgId: string }> {\n const { orderId, buyer, attachedBy, config, now } = input\n const saleRef = posHardwareSaleRef(orderId)\n return firestore().runTransaction(async (transaction: any) => {\n const sale = await transaction.get(saleRef)\n if (!sale.exists) throw new PosHardwareAttachRefusal('No such card reader sale.', 404)\n const fromOrgId = String(sale.get('orgId') ?? '')\n const fromRef = hardwareOrdersRef(fromOrgId).doc(orderId)\n const from = await transaction.get(fromRef)\n if (!from.exists) throw new PosHardwareAttachRefusal('No such card reader sale.', 404)\n const before = from.data() as PosHardwareOrder\n if (before.source !== 'in_person' || before.posSale?.hostId !== config.sellerHostId) {\n throw new PosHardwareAttachRefusal('Only a card reader sold in person here can be attached.', 409)\n }\n if (before.status === 'canceled' || before.status === 'refunded') {\n throw new PosHardwareAttachRefusal('This sale was refunded and can no longer be attached.', 409)\n }\n const fresh = posHardwareAttachmentOf(orderBuyer(buyer, attachedBy, now))\n // The same person again (a claim on sign-up, a store chosen later)\n // keeps the name and address already known of them.\n const samePerson = Boolean(\n (fresh.uid && before.attachment?.uid === fresh.uid) ||\n (fresh.email && before.attachment?.email === fresh.email),\n )\n const attachment = {\n ...fresh,\n name: fresh.name ?? (samePerson ? (before.attachment?.name ?? null) : null),\n address: fresh.address ?? (samePerson ? (before.attachment?.address ?? null) : null),\n }\n const same =\n before.attachment?.state === attachment.state &&\n (before.attachment?.uid ?? null) === attachment.uid &&\n (before.attachment?.orgId ?? null) === attachment.orgId &&\n (before.attachment?.email ?? null) === attachment.email &&\n (before.attachment?.hostId ?? null) === attachment.hostId &&\n (before.attachment?.name ?? null) === attachment.name &&\n JSON.stringify(before.attachment?.address ?? null) === JSON.stringify(attachment.address)\n if (same) return { order: before, orgId: fromOrgId }\n if (input.requirePending && before.attachment?.state === 'attached') {\n throw new PosHardwareAttachRefusal('This sale is already attached. Detach it first.', 409)\n }\n const toOrgId = attachment.state === 'attached' ? (attachment.orgId as string) : config.sellerOrgId\n const after: PosHardwareOrder = {\n ...before,\n orgId: toOrgId,\n hostId: attachment.state === 'attached' ? (attachment.hostId ?? '') : '',\n createdBy: attachment.uid,\n // The buyer's address for the order's emails; the receipt address a\n // pending sale carried was the register's, not necessarily theirs.\n contactEmail: attachment.email,\n attachment: {\n ...attachment,\n // An invitation already sent stays sent for the same address.\n ...(before.attachment?.email === attachment.email && before.attachment?.invitedAtMs\n ? { invitedAtMs: before.attachment.invitedAtMs }\n : {}),\n },\n updatedAtMs: now,\n }\n if (toOrgId === fromOrgId) {\n transaction.set(fromRef, after)\n } else {\n transaction.create(hardwareOrdersRef(toOrgId).doc(orderId), after)\n transaction.delete(fromRef)\n }\n transaction.set(saleRef, posHardwareSaleRecord(orderId, after), posHardwareSaleSetOptions(after))\n const registerOrderId = before.posSale?.orderId\n if (registerOrderId) {\n transaction.set(\n firestore().collection('hosts').doc(config.sellerHostId).collection('orders').doc(registerOrderId),\n { hardwareBuyer: orderBuyer(buyer, attachedBy, now) },\n { merge: true },\n )\n }\n return { order: after, orgId: toOrgId }\n })\n}\n\n/**\n * Says whose a sale's hardware is: by the register order (the sale the\n * register just rang, recorded or not) or by the hardware order's id (a sale\n * on the To attach list). Invites a buyer with no account, once.\n */\nexport async function attachPosHardwareSale(input: {\n config: PosHardwareInPersonConfig\n buyer: CheckedBuyer\n attachedBy: string | null\n registerOrderId?: string | null\n orderId?: string | null\n now?: number\n}): Promise<PosHardwareAttachOutcome> {\n const now = input.now ?? Date.now()\n const registerOrderId = id(input.registerOrderId)\n const orderId = registerOrderId\n ? posHardwareInPersonOrderId(input.config.sellerHostId, registerOrderId)\n : String(input.orderId ?? '')\n if (!POS_HARDWARE_ORDER_ID.test(orderId)) throw new PosHardwareAttachRefusal('Name the sale to attach.', 400)\n\n const recorded = (await posHardwareSaleRef(orderId).get()).exists\n if (!recorded) {\n if (!registerOrderId) throw new PosHardwareAttachRefusal('No such card reader sale.', 404)\n const registerRef = firestore()\n .collection('hosts')\n .doc(input.config.sellerHostId)\n .collection('orders')\n .doc(registerOrderId)\n const register = await registerRef.get()\n if (!register.exists) throw new PosHardwareAttachRefusal('No such sale on this register.', 404)\n const status = String(register.get('status') ?? '')\n if (status !== 'pending' && status !== 'paid') {\n throw new PosHardwareAttachRefusal('This sale was voided or refunded and can no longer be attached.', 409)\n }\n await registerRef.set({ hardwareBuyer: orderBuyer(input.buyer, input.attachedBy, now) }, { merge: true })\n if (status === 'pending') return { outcome: 'waiting', registerOrderId }\n // Paid and not yet recorded: record it now, already attached.\n const outcome = await recordInPersonPosHardwareSale(input.config.sellerHostId, registerOrderId, {\n config: input.config,\n now,\n })\n if (outcome.outcome !== 'recorded' && outcome.outcome !== 'already') {\n throw new PosHardwareAttachRefusal('This sale has no card reader to attach.', 409)\n }\n if (outcome.outcome === 'recorded') return await settled(outcome.orderId, input.config)\n // Recorded by the listener between the two reads: attach the recorded one.\n }\n const moved = await moveRecordedOrder({\n orderId,\n buyer: input.buyer,\n attachedBy: input.attachedBy,\n config: input.config,\n now,\n requirePending: true,\n })\n return await settled(orderId, input.config, moved)\n}\n\n/** The order as it stands, after inviting a buyer with no account if it is owed. */\nasync function settled(\n orderId: string,\n config: PosHardwareInPersonConfig,\n known?: { order: PosHardwareOrder; orgId: string },\n): Promise<PosHardwareAttachOutcome> {\n let current = known\n if (!current) {\n const sale = await posHardwareSaleRef(orderId).get()\n const orgId = String(sale.get('orgId') ?? config.sellerOrgId)\n const doc = await hardwareOrdersRef(orgId).doc(orderId).get()\n current = { order: doc.data() as PosHardwareOrder, orgId }\n }\n let order = await invitePendingBuyer(orderId, current.orgId, current.order)\n // The buyer's address for the reseller's records, from the store chosen\n // for the readers, where the register typed none (AGL-4038).\n if (order.attachment?.state === 'attached' && order.attachment.hostId && !order.attachment.address) {\n const { fillPosHardwareBuyerAddress } = await import('./pos-hardware-buyer-record')\n if (await fillPosHardwareBuyerAddress({ orgId: current.orgId, orderId })) {\n const fresh = await hardwareOrdersRef(current.orgId).doc(orderId).get()\n order = (fresh.data() as PosHardwareOrder | undefined) ?? order\n }\n }\n return {\n outcome: order.attachment?.state === 'attached' ? 'attached' : 'pending',\n orderId,\n orgId: current.orgId,\n order,\n }\n}\n\n/**\n * Sends the sign-up invitation to a pending buyer with an address and no\n * account, once per address: the stamp is claimed in a transaction before\n * the email goes, so two callers never both send it.\n */\nexport async function invitePendingBuyer(\n orderId: string,\n orgId: string,\n order: PosHardwareOrder,\n): Promise<PosHardwareOrder> {\n const attachment = order.attachment\n if (!attachment || attachment.state !== 'pending' || attachment.uid || !attachment.email || attachment.invitedAtMs) {\n return order\n }\n const ref = hardwareOrdersRef(orgId).doc(orderId)\n const claimed = await firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n const now = snapshot.exists ? (snapshot.data() as PosHardwareOrder) : null\n if (!now?.attachment || now.attachment.invitedAtMs || now.attachment.email !== attachment.email) return null\n const invitedAtMs = Date.now()\n // The whole map, read in this transaction, rather than a dotted path.\n const next = { ...now.attachment, invitedAtMs }\n transaction.update(ref, { attachment: next })\n return { ...now, attachment: next } as PosHardwareOrder\n })\n if (!claimed) return order\n await sendPosHardwareInvite(orderId, claimed)\n return claimed\n}\n\n/**\n * Puts an attached sale back on the To attach list: the wrong buyer was\n * chosen. Refused once one of its readers is set up on the buyer's store.\n */\nexport async function detachPosHardwareSale(input: {\n config: PosHardwareInPersonConfig\n orderId: string\n now?: number\n}): Promise<{ order: PosHardwareOrder }> {\n const { config, orderId } = input\n if (!POS_HARDWARE_ORDER_ID.test(orderId)) throw new PosHardwareAttachRefusal('Name the sale to detach.', 400)\n const now = input.now ?? Date.now()\n const saleRef = posHardwareSaleRef(orderId)\n return firestore().runTransaction(async (transaction: any) => {\n const sale = await transaction.get(saleRef)\n if (!sale.exists) throw new PosHardwareAttachRefusal('No such card reader sale.', 404)\n const fromOrgId = String(sale.get('orgId') ?? '')\n const fromRef = hardwareOrdersRef(fromOrgId).doc(orderId)\n const from = await transaction.get(fromRef)\n if (!from.exists) throw new PosHardwareAttachRefusal('No such card reader sale.', 404)\n const before = from.data() as PosHardwareOrder\n if (before.source !== 'in_person' || before.posSale?.hostId !== config.sellerHostId) {\n throw new PosHardwareAttachRefusal('Only a card reader sold in person here can be detached.', 409)\n }\n if (before.attachment?.state !== 'attached') return { order: before }\n if ((before.units ?? []).some((unit) => unit.readerId)) {\n throw new PosHardwareAttachRefusal('A reader from this sale is already set up on the buyer’s store.', 409)\n }\n const after: PosHardwareOrder = {\n ...before,\n orgId: config.sellerOrgId,\n hostId: '',\n createdBy: null,\n contactEmail: null,\n attachment: posHardwareAttachmentOf(null),\n updatedAtMs: now,\n }\n transaction.create(hardwareOrdersRef(config.sellerOrgId).doc(orderId), after)\n transaction.delete(fromRef)\n transaction.set(saleRef, posHardwareSaleRecord(orderId, after), posHardwareSaleSetOptions(after))\n const registerOrderId = before.posSale?.orderId\n if (registerOrderId) {\n transaction.set(\n firestore().collection('hosts').doc(config.sellerHostId).collection('orders').doc(registerOrderId),\n { hardwareBuyer: firebaseAdmin.firestore.FieldValue.delete() },\n { merge: true },\n )\n }\n return { order: after }\n })\n}\n\n/**\n * A workspace was just created: every pending sale naming its owner — their\n * account, or their address once verified — moves into it. Never throws:\n * a sale it cannot move stays on the To attach list.\n */\nexport async function claimPosHardwareForNewWorkspace(input: {\n config: PosHardwareInPersonConfig | null\n orgId: string\n ownerUid: string\n ownerEmail: string | null\n emailVerified: boolean\n}): Promise<{ claimed: number }> {\n const { config } = input\n if (!config || !id(input.orgId) || !id(input.ownerUid)) return { claimed: 0 }\n const pending = hardwareOrdersRef(config.sellerOrgId)\n const email = input.emailVerified ? String(input.ownerEmail ?? '').trim().toLowerCase() : ''\n const [byUid, byEmail] = await Promise.all([\n pending.where('attachment.uid', '==', input.ownerUid).limit(20).get(),\n email ? pending.where('attachment.email', '==', email).limit(20).get() : Promise.resolve({ docs: [] }),\n ])\n const ids = new Set<string>()\n for (const doc of [...byUid.docs, ...byEmail.docs] as Array<{ id: string; data: () => PosHardwareOrder }>) {\n if (doc.data().attachment?.state === 'pending') ids.add(String(doc.id))\n }\n let claimed = 0\n // Their account's name, for the reseller's records of the sale.\n const owner = ids.size ? await findUserByUidAcrossPools(input.ownerUid).catch(() => null) : null\n const name = String(owner?.record.displayName ?? '').trim().slice(0, 200) || null\n for (const orderId of ids) {\n try {\n await moveRecordedOrder({\n orderId,\n buyer: {\n uid: input.ownerUid,\n orgId: input.orgId,\n hostId: null,\n // Their account's address carries the order's emails from now on.\n email: String(input.ownerEmail ?? '').trim().toLowerCase() || null,\n name,\n },\n attachedBy: null,\n config,\n now: Date.now(),\n requirePending: true,\n })\n claimed += 1\n } catch (error) {\n console.error('[pos-hardware-attach] a pending sale was not claimed', orderId, error)\n }\n }\n return { claimed }\n}\n"],"names":["firebaseAdmin","findUserByEmailAcrossPools","findUserByUidAcrossPools","POS_HARDWARE_ORDER_ID","posHardwareBuyerAddress","posHardwareSaleRecord","posHardwareSaleSetOptions","posHardwareAttachmentOf","hardwareOrdersRef","posHardwareInPersonOrderId","posHardwareSaleRef","recordInPersonPosHardwareSale","sendPosHardwareInvite","PosHardwareAttachRefusal","Error","message","status","ID","EMAIL","id","value","test","trim","firestore","app","typedIdentity","request","name","slice","address","undefined","checkHardwareBuyer","uid","orgId","hostId","typed","user","email","String","record","toLowerCase","displayName","member","collection","doc","get","exists","host","orderBuyer","buyer","attachedBy","now","attachedAtMs","moveRecordedOrder","input","orderId","config","saleRef","runTransaction","transaction","sale","fresh","attachment","before","fromOrgId","fromRef","from","data","source","posSale","sellerHostId","samePerson","Boolean","same","state","JSON","stringify","order","requirePending","toOrgId","sellerOrgId","after","createdBy","contactEmail","invitedAtMs","updatedAtMs","set","create","delete","registerOrderId","hardwareBuyer","merge","attachPosHardwareSale","Date","recorded","register","registerRef","outcome","settled","moved","known","current","invitePendingBuyer","fillPosHardwareBuyerAddress","ref","claimed","snapshot","next","update","detachPosHardwareSale","units","some","unit","readerId","FieldValue","claimPosHardwareForNewWorkspace","ownerUid","pending","emailVerified","ownerEmail","byUid","byEmail","Promise","all","where","limit","resolve","docs","ids","Set","add","owner","size","catch","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SACEC,0BAA0B,EAC1BC,wBAAwB,QACnB,6CAA4C;AAEnD,SACEC,qBAAqB,EACrBC,uBAAuB,EACvBC,qBAAqB,EACrBC,yBAAyB,QAIpB,2BAAuB;AAC9B,SAASC,uBAAuB,QAAQ,qCAAiC;AACzE,SAASC,iBAAiB,EAAEC,0BAA0B,EAAEC,kBAAkB,QAAQ,oBAAgB;AAClG,SAASC,6BAA6B,QAAQ,8BAA0B;AACxE,SAASC,qBAAqB,QAAQ,2BAAuB;AAE7D;;;;;;;;;;;;;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B,MAAM8D,QAAQ;oBACnBnF,OAAOqB,MAAMrB,KAAK;oBAClBC,QAAQ;oBACR,kEAAkE;oBAClEG,OAAOC,QAAOgB,qBAAAA,MAAMiE,UAAU,YAAhBjE,qBAAoB,IAAIhC,IAAI,GAAGkB,WAAW,MAAM;oBAC9Db;gBACF;gBACAuB,YAAY;gBACZM;gBACAL,KAAK0C,KAAK1C,GAAG;gBACb2B,gBAAgB;YAClB;YACA2B,WAAW;QACb,EAAE,OAAO6B,OAAO;YACdC,QAAQD,KAAK,CAAC,wDAAwD/E,SAAS+E;QACjF;IACF;IACA,OAAO;QAAE7B;IAAQ;AACnB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-attach.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 { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n findUserByEmailAcrossPools,\n findUserByUidAcrossPools,\n} from '@aglyn/tenant-data-admin/server/auth-pools'\nimport type { OrderHardwareBuyer } from '../model/commerce-orders'\nimport {\n isPosHardwareSellerStoreSale,\n POS_HARDWARE_ORDER_ID,\n posHardwareBuyerAddress,\n posHardwareSaleRecord,\n posHardwareSaleSetOptions,\n type PosHardwareAddress,\n type PosHardwareInPersonConfig,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\nimport { posHardwareAttachmentOf } from '../model/pos-hardware-in-person'\nimport { hardwareOrdersRef, posHardwareInPersonOrderId, posHardwareSaleRef } from './pos-hardware'\nimport { recordInPersonPosHardwareSale } from './pos-hardware-in-person'\nimport { sendPosHardwareInvite } from './pos-hardware-notify'\n\n/*==========================================\n * ATTACHING AN IN-PERSON SALE TO ITS BUYER (AGL-4038).\n *\n * The register user who sold a card reader says whose it is: an account and\n * the workspace (and, if they chose one, the store) it is for; an account\n * with no workspace yet; or the address of someone with no account, who is\n * then invited to sign up. The order moves to the buyer's workspace the\n * moment it has one, and is pending on the selling workspace's To attach\n * list until then.\n *\n * Every attachment is checked here, never trusted from the register: the\n * account exists, it is a member of the workspace, the store is the\n * workspace's, and an address given for \"no account\" really has none.\n *\n * A sale not recorded yet (the register attaches the buyer while the sale is\n * still open, or the instant it is paid) carries the buyer on the register\n * order (`hardwareBuyer`), and the recorder builds the order already\n * attached. A sale already recorded is moved: created in the buyer's\n * workspace and deleted from where it was, with its retained sale record and\n * the register order, in one transaction.\n *\n * A NEW WORKSPACE CLAIMS ITS OWNER'S SALES. When a buyer who was invited\n * signs up and creates a workspace, every pending sale naming their verified\n * address (or their account) moves into it ({@link claimPosHardwareForNewWorkspace}).\n *=========================================*/\n\nexport class PosHardwareAttachRefusal extends Error {\n constructor(\n message: string,\n readonly status: number,\n ) {\n super(message)\n }\n}\n\n/** Who the register says the buyer is, before it is checked. */\nexport interface PosHardwareBuyerRequest {\n uid?: unknown\n orgId?: unknown\n hostId?: unknown\n email?: unknown\n /** The buyer's name, typed at the sale; an account's own name wins. */\n name?: unknown\n /** The buyer's business address, typed at the sale (optional). */\n address?: unknown\n}\n\nconst ID = /^[A-Za-z0-9_-]{1,128}$/\nconst EMAIL = /^[^@\\s]{1,64}@[^@\\s]+\\.[^@\\s]{2,}$/\n\nconst id = (value: unknown): string | null => (typeof value === 'string' && ID.test(value.trim()) ? value.trim() : null)\n\nfunction firestore() {\n return firebaseAdmin.app().firestore()\n}\n\n/** A checked buyer: who they are, where the order goes, where its emails go. */\nexport interface CheckedBuyer {\n uid: string | null\n orgId: string | null\n hostId: string | null\n email: string | null\n /**\n * The buyer's name and business address, for the platform's reseller\n * records (AGL-4038): the account's name, else the one typed; the address\n * typed at the sale, when one was.\n */\n name?: string | null\n address?: PosHardwareAddress | null\n}\n\n/** The name and address the register typed, checked: an address is all of it or refused. */\nfunction typedIdentity(request: PosHardwareBuyerRequest): { name: string | null; address: PosHardwareAddress | null } {\n const name = typeof request.name === 'string' && request.name.trim() ? request.name.trim().slice(0, 200) : null\n if (request.address === undefined || request.address === null || request.address === '') {\n return { name, address: null }\n }\n const address = posHardwareBuyerAddress(request.address)\n if (!address) {\n throw new PosHardwareAttachRefusal('Enter the buyer’s street, city, postal code and two-letter country, or leave the address empty.', 400)\n }\n return { name, address }\n}\n\n/**\n * The buyer the register named, checked. Refuses an account that does not\n * exist or is not in the workspace, a store not in the workspace, and an\n * address said to have no account that has one.\n */\nexport async function checkHardwareBuyer(request: PosHardwareBuyerRequest): Promise<CheckedBuyer> {\n const uid = id(request.uid)\n const orgId = id(request.orgId)\n const hostId = id(request.hostId)\n const typed = typedIdentity(request)\n if (uid) {\n const user = await findUserByUidAcrossPools(uid)\n if (!user) throw new PosHardwareAttachRefusal('That account no longer exists. Look the buyer up again.', 404)\n const email = String(user.record.email ?? '').trim().toLowerCase() || null\n const name = String(user.record.displayName ?? '').trim().slice(0, 200) || typed.name\n if (!orgId) return { uid, orgId: null, hostId: null, email, name, address: typed.address }\n const member = await firestore().collection('orgs').doc(orgId).collection('members').doc(uid).get()\n if (!member.exists) {\n throw new PosHardwareAttachRefusal('That person is not on that workspace. Look the buyer up again.', 409)\n }\n if (hostId) {\n const host = await firestore().collection('hosts').doc(hostId).get()\n if (!host.exists || host.get('orgId') !== orgId) {\n throw new PosHardwareAttachRefusal('That store is not in the buyer’s workspace.', 409)\n }\n }\n return { uid, orgId, hostId, email, name, address: typed.address }\n }\n const email = String(request.email ?? '').trim().toLowerCase()\n if (!EMAIL.test(email)) throw new PosHardwareAttachRefusal('Enter the buyer’s email address.', 400)\n if (await findUserByEmailAcrossPools(email)) {\n throw new PosHardwareAttachRefusal(\n 'That email already has an account. Look it up and attach the account instead.',\n 409,\n )\n }\n return { uid: null, orgId: null, hostId: null, email, ...typed }\n}\n\n/** The buyer as the register order keeps it. */\nfunction orderBuyer(buyer: CheckedBuyer, attachedBy: string | null, now: number): OrderHardwareBuyer {\n return {\n uid: buyer.uid,\n orgId: buyer.orgId,\n hostId: buyer.hostId,\n email: buyer.email,\n attachedBy: attachedBy ?? '',\n attachedAtMs: now,\n ...(buyer.name ? { name: buyer.name } : {}),\n ...(buyer.address ? { address: buyer.address } : {}),\n }\n}\n\nexport type PosHardwareAttachOutcome =\n | { outcome: 'waiting'; registerOrderId: string }\n | { outcome: 'attached' | 'pending'; orderId: string; orgId: string; order: PosHardwareOrder }\n\n/**\n * Moves (or re-stamps) a recorded order for its new buyer, in one\n * transaction with its sale record and the register order. Returns the order\n * as it now stands.\n */\nasync function moveRecordedOrder(input: {\n orderId: string\n buyer: CheckedBuyer\n attachedBy: string | null\n config: PosHardwareInPersonConfig\n now: number\n /** Only a pending order moves: an attached one must be detached first. */\n requirePending: boolean\n}): Promise<{ order: PosHardwareOrder; orgId: string }> {\n const { orderId, buyer, attachedBy, config, now } = input\n const saleRef = posHardwareSaleRef(orderId)\n return firestore().runTransaction(async (transaction: any) => {\n const sale = await transaction.get(saleRef)\n if (!sale.exists) throw new PosHardwareAttachRefusal('No such card reader sale.', 404)\n const fromOrgId = String(sale.get('orgId') ?? '')\n const fromRef = hardwareOrdersRef(fromOrgId).doc(orderId)\n const from = await transaction.get(fromRef)\n if (!from.exists) throw new PosHardwareAttachRefusal('No such card reader sale.', 404)\n const before = from.data() as PosHardwareOrder\n if (!isPosHardwareSellerStoreSale(before) || before.posSale?.hostId !== config.sellerHostId) {\n throw new PosHardwareAttachRefusal('Only a card reader sold by this store can be attached.', 409)\n }\n if (before.status === 'canceled' || before.status === 'refunded') {\n throw new PosHardwareAttachRefusal('This sale was refunded and can no longer be attached.', 409)\n }\n const fresh = posHardwareAttachmentOf(orderBuyer(buyer, attachedBy, now))\n // The same person again (a claim on sign-up, a store chosen later)\n // keeps the name and address already known of them.\n const samePerson = Boolean(\n (fresh.uid && before.attachment?.uid === fresh.uid) ||\n (fresh.email && before.attachment?.email === fresh.email),\n )\n const attachment = {\n ...fresh,\n name: fresh.name ?? (samePerson ? (before.attachment?.name ?? null) : null),\n address: fresh.address ?? (samePerson ? (before.attachment?.address ?? null) : null),\n }\n const same =\n before.attachment?.state === attachment.state &&\n (before.attachment?.uid ?? null) === attachment.uid &&\n (before.attachment?.orgId ?? null) === attachment.orgId &&\n (before.attachment?.email ?? null) === attachment.email &&\n (before.attachment?.hostId ?? null) === attachment.hostId &&\n (before.attachment?.name ?? null) === attachment.name &&\n JSON.stringify(before.attachment?.address ?? null) === JSON.stringify(attachment.address)\n if (same) return { order: before, orgId: fromOrgId }\n if (input.requirePending && before.attachment?.state === 'attached') {\n throw new PosHardwareAttachRefusal('This sale is already attached. Detach it first.', 409)\n }\n const toOrgId = attachment.state === 'attached' ? (attachment.orgId as string) : config.sellerOrgId\n const after: PosHardwareOrder = {\n ...before,\n orgId: toOrgId,\n hostId: attachment.state === 'attached' ? (attachment.hostId ?? '') : '',\n createdBy: attachment.uid,\n // The buyer's address for the order's emails; the receipt address a\n // pending sale carried was the register's, not necessarily theirs.\n contactEmail: attachment.email,\n attachment: {\n ...attachment,\n // An invitation already sent stays sent for the same address.\n ...(before.attachment?.email === attachment.email && before.attachment?.invitedAtMs\n ? { invitedAtMs: before.attachment.invitedAtMs }\n : {}),\n },\n updatedAtMs: now,\n }\n if (toOrgId === fromOrgId) {\n transaction.set(fromRef, after)\n } else {\n transaction.create(hardwareOrdersRef(toOrgId).doc(orderId), after)\n transaction.delete(fromRef)\n }\n transaction.set(saleRef, posHardwareSaleRecord(orderId, after), posHardwareSaleSetOptions(after))\n const registerOrderId = before.posSale?.orderId\n if (registerOrderId) {\n transaction.set(\n firestore().collection('hosts').doc(config.sellerHostId).collection('orders').doc(registerOrderId),\n { hardwareBuyer: orderBuyer(buyer, attachedBy, now) },\n { merge: true },\n )\n }\n return { order: after, orgId: toOrgId }\n })\n}\n\n/**\n * Says whose a sale's hardware is: by the register order (the sale the\n * register just rang, recorded or not) or by the hardware order's id (a sale\n * on the To attach list). Invites a buyer with no account, once.\n */\nexport async function attachPosHardwareSale(input: {\n config: PosHardwareInPersonConfig\n buyer: CheckedBuyer\n attachedBy: string | null\n registerOrderId?: string | null\n orderId?: string | null\n now?: number\n}): Promise<PosHardwareAttachOutcome> {\n const now = input.now ?? Date.now()\n const registerOrderId = id(input.registerOrderId)\n const orderId = registerOrderId\n ? posHardwareInPersonOrderId(input.config.sellerHostId, registerOrderId)\n : String(input.orderId ?? '')\n if (!POS_HARDWARE_ORDER_ID.test(orderId)) throw new PosHardwareAttachRefusal('Name the sale to attach.', 400)\n\n const recorded = (await posHardwareSaleRef(orderId).get()).exists\n if (!recorded) {\n if (!registerOrderId) throw new PosHardwareAttachRefusal('No such card reader sale.', 404)\n const registerRef = firestore()\n .collection('hosts')\n .doc(input.config.sellerHostId)\n .collection('orders')\n .doc(registerOrderId)\n const register = await registerRef.get()\n if (!register.exists) throw new PosHardwareAttachRefusal('No such sale on this register.', 404)\n const status = String(register.get('status') ?? '')\n if (status !== 'pending' && status !== 'paid') {\n throw new PosHardwareAttachRefusal('This sale was voided or refunded and can no longer be attached.', 409)\n }\n await registerRef.set({ hardwareBuyer: orderBuyer(input.buyer, input.attachedBy, now) }, { merge: true })\n if (status === 'pending') return { outcome: 'waiting', registerOrderId }\n // Paid and not yet recorded: record it now, already attached.\n const outcome = await recordInPersonPosHardwareSale(input.config.sellerHostId, registerOrderId, {\n config: input.config,\n now,\n })\n if (outcome.outcome !== 'recorded' && outcome.outcome !== 'already') {\n throw new PosHardwareAttachRefusal('This sale has no card reader to attach.', 409)\n }\n if (outcome.outcome === 'recorded') return await settled(outcome.orderId, input.config)\n // Recorded by the listener between the two reads: attach the recorded one.\n }\n const moved = await moveRecordedOrder({\n orderId,\n buyer: input.buyer,\n attachedBy: input.attachedBy,\n config: input.config,\n now,\n requirePending: true,\n })\n return await settled(orderId, input.config, moved)\n}\n\n/** The order as it stands, after inviting a buyer with no account if it is owed. */\nasync function settled(\n orderId: string,\n config: PosHardwareInPersonConfig,\n known?: { order: PosHardwareOrder; orgId: string },\n): Promise<PosHardwareAttachOutcome> {\n let current = known\n if (!current) {\n const sale = await posHardwareSaleRef(orderId).get()\n const orgId = String(sale.get('orgId') ?? config.sellerOrgId)\n const doc = await hardwareOrdersRef(orgId).doc(orderId).get()\n current = { order: doc.data() as PosHardwareOrder, orgId }\n }\n let order = await invitePendingBuyer(orderId, current.orgId, current.order)\n // The buyer's address for the reseller's records, from the store chosen\n // for the readers, where the register typed none (AGL-4038).\n if (order.attachment?.state === 'attached' && order.attachment.hostId && !order.attachment.address) {\n const { fillPosHardwareBuyerAddress } = await import('./pos-hardware-buyer-record')\n if (await fillPosHardwareBuyerAddress({ orgId: current.orgId, orderId })) {\n const fresh = await hardwareOrdersRef(current.orgId).doc(orderId).get()\n order = (fresh.data() as PosHardwareOrder | undefined) ?? order\n }\n }\n return {\n outcome: order.attachment?.state === 'attached' ? 'attached' : 'pending',\n orderId,\n orgId: current.orgId,\n order,\n }\n}\n\n/**\n * Sends the sign-up invitation to a pending buyer with an address and no\n * account, once per address: the stamp is claimed in a transaction before\n * the email goes, so two callers never both send it.\n */\nexport async function invitePendingBuyer(\n orderId: string,\n orgId: string,\n order: PosHardwareOrder,\n): Promise<PosHardwareOrder> {\n const attachment = order.attachment\n if (!attachment || attachment.state !== 'pending' || attachment.uid || !attachment.email || attachment.invitedAtMs) {\n return order\n }\n const ref = hardwareOrdersRef(orgId).doc(orderId)\n const claimed = await firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n const now = snapshot.exists ? (snapshot.data() as PosHardwareOrder) : null\n if (!now?.attachment || now.attachment.invitedAtMs || now.attachment.email !== attachment.email) return null\n const invitedAtMs = Date.now()\n // The whole map, read in this transaction, rather than a dotted path.\n const next = { ...now.attachment, invitedAtMs }\n transaction.update(ref, { attachment: next })\n return { ...now, attachment: next } as PosHardwareOrder\n })\n if (!claimed) return order\n await sendPosHardwareInvite(orderId, claimed)\n return claimed\n}\n\n/**\n * Puts an attached sale back on the To attach list: the wrong buyer was\n * chosen. Refused once one of its readers is set up on the buyer's store.\n */\nexport async function detachPosHardwareSale(input: {\n config: PosHardwareInPersonConfig\n orderId: string\n now?: number\n}): Promise<{ order: PosHardwareOrder }> {\n const { config, orderId } = input\n if (!POS_HARDWARE_ORDER_ID.test(orderId)) throw new PosHardwareAttachRefusal('Name the sale to detach.', 400)\n const now = input.now ?? Date.now()\n const saleRef = posHardwareSaleRef(orderId)\n return firestore().runTransaction(async (transaction: any) => {\n const sale = await transaction.get(saleRef)\n if (!sale.exists) throw new PosHardwareAttachRefusal('No such card reader sale.', 404)\n const fromOrgId = String(sale.get('orgId') ?? '')\n const fromRef = hardwareOrdersRef(fromOrgId).doc(orderId)\n const from = await transaction.get(fromRef)\n if (!from.exists) throw new PosHardwareAttachRefusal('No such card reader sale.', 404)\n const before = from.data() as PosHardwareOrder\n if (!isPosHardwareSellerStoreSale(before) || before.posSale?.hostId !== config.sellerHostId) {\n throw new PosHardwareAttachRefusal('Only a card reader sold by this store can be detached.', 409)\n }\n if (before.attachment?.state !== 'attached') return { order: before }\n if ((before.units ?? []).some((unit) => unit.readerId)) {\n throw new PosHardwareAttachRefusal('A reader from this sale is already set up on the buyer’s store.', 409)\n }\n const after: PosHardwareOrder = {\n ...before,\n orgId: config.sellerOrgId,\n hostId: '',\n createdBy: null,\n contactEmail: null,\n attachment: posHardwareAttachmentOf(null),\n updatedAtMs: now,\n }\n transaction.create(hardwareOrdersRef(config.sellerOrgId).doc(orderId), after)\n transaction.delete(fromRef)\n transaction.set(saleRef, posHardwareSaleRecord(orderId, after), posHardwareSaleSetOptions(after))\n const registerOrderId = before.posSale?.orderId\n if (registerOrderId) {\n transaction.set(\n firestore().collection('hosts').doc(config.sellerHostId).collection('orders').doc(registerOrderId),\n { hardwareBuyer: firebaseAdmin.firestore.FieldValue.delete() },\n { merge: true },\n )\n }\n return { order: after }\n })\n}\n\n/**\n * A workspace was just created: every pending sale naming its owner — their\n * account, or their address once verified — moves into it. Never throws:\n * a sale it cannot move stays on the To attach list.\n */\nexport async function claimPosHardwareForNewWorkspace(input: {\n config: PosHardwareInPersonConfig | null\n orgId: string\n ownerUid: string\n ownerEmail: string | null\n emailVerified: boolean\n}): Promise<{ claimed: number }> {\n const { config } = input\n if (!config || !id(input.orgId) || !id(input.ownerUid)) return { claimed: 0 }\n const pending = hardwareOrdersRef(config.sellerOrgId)\n const email = input.emailVerified ? String(input.ownerEmail ?? '').trim().toLowerCase() : ''\n const [byUid, byEmail] = await Promise.all([\n pending.where('attachment.uid', '==', input.ownerUid).limit(20).get(),\n email ? pending.where('attachment.email', '==', email).limit(20).get() : Promise.resolve({ docs: [] }),\n ])\n const ids = new Set<string>()\n for (const doc of [...byUid.docs, ...byEmail.docs] as Array<{ id: string; data: () => PosHardwareOrder }>) {\n if (doc.data().attachment?.state === 'pending') ids.add(String(doc.id))\n }\n let claimed = 0\n // Their account's name, for the reseller's records of the sale.\n const owner = ids.size ? await findUserByUidAcrossPools(input.ownerUid).catch(() => null) : null\n const name = String(owner?.record.displayName ?? '').trim().slice(0, 200) || null\n for (const orderId of ids) {\n try {\n await moveRecordedOrder({\n orderId,\n buyer: {\n uid: input.ownerUid,\n orgId: input.orgId,\n hostId: null,\n // Their account's address carries the order's emails from now on.\n email: String(input.ownerEmail ?? '').trim().toLowerCase() || null,\n name,\n },\n attachedBy: null,\n config,\n now: Date.now(),\n requirePending: true,\n })\n claimed += 1\n } catch (error) {\n console.error('[pos-hardware-attach] a pending sale was not claimed', orderId, error)\n }\n }\n return { claimed }\n}\n"],"names":["firebaseAdmin","findUserByEmailAcrossPools","findUserByUidAcrossPools","isPosHardwareSellerStoreSale","POS_HARDWARE_ORDER_ID","posHardwareBuyerAddress","posHardwareSaleRecord","posHardwareSaleSetOptions","posHardwareAttachmentOf","hardwareOrdersRef","posHardwareInPersonOrderId","posHardwareSaleRef","recordInPersonPosHardwareSale","sendPosHardwareInvite","PosHardwareAttachRefusal","Error","message","status","ID","EMAIL","id","value","test","trim","firestore","app","typedIdentity","request","name","slice","address","undefined","checkHardwareBuyer","uid","orgId","hostId","typed","user","email","String","record","toLowerCase","displayName","member","collection","doc","get","exists","host","orderBuyer","buyer","attachedBy","now","attachedAtMs","moveRecordedOrder","input","orderId","config","saleRef","runTransaction","transaction","sale","fresh","attachment","before","fromOrgId","fromRef","from","data","posSale","sellerHostId","samePerson","Boolean","same","state","JSON","stringify","order","requirePending","toOrgId","sellerOrgId","after","createdBy","contactEmail","invitedAtMs","updatedAtMs","set","create","delete","registerOrderId","hardwareBuyer","merge","attachPosHardwareSale","Date","recorded","register","registerRef","outcome","settled","moved","known","current","invitePendingBuyer","fillPosHardwareBuyerAddress","ref","claimed","snapshot","next","update","detachPosHardwareSale","units","some","unit","readerId","FieldValue","claimPosHardwareForNewWorkspace","ownerUid","pending","emailVerified","ownerEmail","byUid","byEmail","Promise","all","where","limit","resolve","docs","ids","Set","add","owner","size","catch","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SACEC,0BAA0B,EAC1BC,wBAAwB,QACnB,6CAA4C;AAEnD,SACEC,4BAA4B,EAC5BC,qBAAqB,EACrBC,uBAAuB,EACvBC,qBAAqB,EACrBC,yBAAyB,QAIpB,2BAAuB;AAC9B,SAASC,uBAAuB,QAAQ,qCAAiC;AACzE,SAASC,iBAAiB,EAAEC,0BAA0B,EAAEC,kBAAkB,QAAQ,oBAAgB;AAClG,SAASC,6BAA6B,QAAQ,8BAA0B;AACxE,SAASC,qBAAqB,QAAQ,2BAAuB;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;2CAwB2C,GAE3C,OAAO,MAAMC,iCAAiCC;IAC5C,YACEC,OAAe,EACf,AAASC,MAAc,CACvB;QACA,KAAK,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AU,YAAhBhE,qBAAoB,IAAIhC,IAAI,GAAGkB,WAAW,MAAM;oBAC9Db;gBACF;gBACAuB,YAAY;gBACZM;gBACAL,KAAKyC,KAAKzC,GAAG;gBACb0B,gBAAgB;YAClB;YACA2B,WAAW;QACb,EAAE,OAAO6B,OAAO;YACdC,QAAQD,KAAK,CAAC,wDAAwD9E,SAAS8E;QACjF;IACF;IACA,OAAO;QAAE7B;IAAQ;AACnB"}
@@ -48,6 +48,11 @@ export async function cancelAndRefundPosHardwareOrder(request) {
48
48
  const now = (_request_now = request.now) != null ? _request_now : Date.now;
49
49
  const firestore = firebaseAdmin.app().firestore();
50
50
  const ref = hardwareOrdersRef(orgId).doc(orderId);
51
+ // Bought from the platform's own online store (AGL-4038): its money is in
52
+ // that store's account, so it comes back through the store order's own
53
+ // refund, never a refund on the platform's balance.
54
+ const stored = (await ref.get()).data();
55
+ if ((stored == null ? void 0 : stored.source) === 'storefront') return cancelSellerStoreOrder(request, stored);
51
56
  const claim = await firestore.runTransaction(async (transaction)=>{
52
57
  const snapshot = await transaction.get(ref);
53
58
  if (!snapshot.exists) return {
@@ -143,5 +148,65 @@ export async function cancelAndRefundPosHardwareOrder(request) {
143
148
  order: after
144
149
  };
145
150
  }
151
+ /**
152
+ * Cancels an order the platform's own online store sold (AGL-4038): the
153
+ * same rules as {@link cancelAndRefundPosHardwareOrder} — only before it
154
+ * ships, once — with the refund made through the store order's own card
155
+ * refund (`refundInPersonPosHardwareOrder`), which reverses the transfer into
156
+ * the store's account and writes the refund onto the order once by its key.
157
+ */ async function cancelSellerStoreOrder(request, stored) {
158
+ var _request_now;
159
+ const { orgId, orderId, finalStatus, reason } = request;
160
+ const now = (_request_now = request.now) != null ? _request_now : Date.now;
161
+ if (stored.status === finalStatus) return {
162
+ outcome: 'already',
163
+ order: stored
164
+ };
165
+ if (!posHardwareRefundable(stored.status)) return {
166
+ outcome: 'not-refundable',
167
+ order: stored
168
+ };
169
+ const [{ refundInPersonPosHardwareOrder, PosHardwareReturnRefusal }, { posHardwareInPersonConfig }] = await Promise.all([
170
+ import("./pos-hardware-returns.js"),
171
+ import("./pos-hardware.js")
172
+ ]);
173
+ let refunded;
174
+ try {
175
+ refunded = (await refundInPersonPosHardwareOrder({
176
+ config: posHardwareInPersonConfig(),
177
+ orgId,
178
+ orderId,
179
+ actorUid: `system:${reason}`,
180
+ now: now()
181
+ })).order;
182
+ } catch (error) {
183
+ if (error instanceof PosHardwareReturnRefusal) {
184
+ return {
185
+ outcome: 'refused',
186
+ order: stored,
187
+ message: error.message,
188
+ code: null
189
+ };
190
+ }
191
+ throw error;
192
+ }
193
+ const at = now();
194
+ const ref = hardwareOrdersRef(orgId).doc(orderId);
195
+ const after = _extends({}, refunded, {
196
+ status: finalStatus,
197
+ [POS_HARDWARE_STATUS_STAMP[finalStatus]]: at,
198
+ updatedAtMs: at,
199
+ cancelReason: reason
200
+ });
201
+ await firebaseAdmin.app().firestore().runTransaction(async (transaction)=>{
202
+ transaction.set(ref, after);
203
+ transaction.set(posHardwareSaleRef(orderId), posHardwareSaleRecord(orderId, after), posHardwareSaleSetOptions(after));
204
+ });
205
+ return {
206
+ outcome: 'settled',
207
+ before: stored,
208
+ order: after
209
+ };
210
+ }
146
211
 
147
212
  //# sourceMappingURL=pos-hardware-cancel.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-cancel.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 { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n POS_HARDWARE_STATUS_STAMP,\n posHardwareRefundable,\n posHardwareSaleRecord,\n posHardwareSaleSetOptions,\n type PosHardwareCancelReason,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\nimport { hardwareOrdersRef, posHardwareSaleRef } from './pos-hardware'\nimport { posStripe } from './pos-stripe'\n\n/*==========================================\n * CANCELING AND REFUNDING A HARDWARE ORDER IN FULL (AGL-4038).\n *\n * One path for every caller: staff on the Hardware orders page, and the\n * closures (a workspace deleted, the buying account closed) that cancel every\n * order of theirs that has not shipped. Each refunds the whole payment on the\n * PLATFORM account, only before the order ships, and only once:\n *\n * 1. CLAIM under the lock: the order must still be paid or ordered, and\n * `refundRequestedAtMs` is set, so it cannot be marked shipped while the\n * money is on its way back.\n * 2. REFUND through Stripe under ONE idempotency key per order,\n * `pos-hw-refund-{orderId}`, with the same parameters whoever asks — a\n * key replayed with different parameters is refused by Stripe, so no\n * caller adds its own. A second ask inside Stripe's key window gets the\n * first refund back; after it, Stripe refuses the charge as already\n * refunded, and the refund it already made is read back instead of a\n * second one made.\n * 3. SETTLE: the order and its retained sale record move together, in one\n * transaction, with the refund id, the cents Stripe reported and why.\n *\n * Stripe refusing releases the claim, so the order can still ship. Telling\n * people (the buyer, staff) and the audit row are the caller's: staff and a\n * closure say different things.\n *=========================================*/\n\n/** What became of one cancel. */\nexport type PosHardwareCancelResult =\n /** Refunded now (or Stripe's earlier refund recovered) and settled. */\n | { outcome: 'settled'; before: PosHardwareOrder; order: PosHardwareOrder }\n /** It already had the final status: nothing was asked of Stripe. */\n | { outcome: 'already'; order: PosHardwareOrder }\n | { outcome: 'missing' }\n /** Shipped, delivered, registered, or canceled the other way. */\n | { outcome: 'not-refundable'; order: PosHardwareOrder }\n | { outcome: 'no-payment'; order: PosHardwareOrder }\n /** Stripe refused; the claim was released and the order is as it was. */\n | { outcome: 'refused'; order: PosHardwareOrder; message: string; code: string | null }\n\nexport interface PosHardwareCancelRequest {\n orgId: string\n orderId: string\n /** `canceled` for a cancel (staff or closure), `refunded` for a staff refund. */\n finalStatus: 'canceled' | 'refunded'\n reason: PosHardwareCancelReason\n now?: () => number\n}\n\ntype ClaimedOrder = PosHardwareOrder & { refundRequestedAtMs?: number }\n\n/** The idempotency key every caller refunds an order under. */\nexport function posHardwareRefundKey(orderId: string): string {\n return `pos-hw-refund-${orderId}`\n}\n\n/**\n * The refund Stripe already made on this payment, for a charge it refuses as\n * already refunded: the earlier ask settled at Stripe and never reached the\n * order (a crash between the two, or an ask after Stripe's key window).\n */\nasync function existingRefund(paymentIntentId: string): Promise<{ id: string; amount: number } | null> {\n const listed = await posStripe('GET', 'refunds', {\n params: { payment_intent: paymentIntentId, limit: 10 },\n }).catch(() => null)\n const refunds = Array.isArray(listed?.body?.data) ? (listed?.body?.data as Array<Record<string, unknown>>) : []\n const found = refunds.find(\n (refund) => refund?.['id'] && (refund?.['status'] === 'succeeded' || refund?.['status'] === 'pending'),\n )\n return found ? { id: String(found['id']), amount: Number(found['amount'] ?? 0) } : null\n}\n\nexport async function cancelAndRefundPosHardwareOrder(\n request: PosHardwareCancelRequest,\n): Promise<PosHardwareCancelResult> {\n const { orgId, orderId, finalStatus, reason } = request\n const now = request.now ?? Date.now\n const firestore = firebaseAdmin.app().firestore()\n const ref = hardwareOrdersRef(orgId).doc(orderId)\n\n const claim = await firestore.runTransaction(async (transaction: any): Promise<PosHardwareCancelResult | { outcome: 'claimed'; order: ClaimedOrder }> => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) return { outcome: 'missing' }\n const order = snapshot.data() as ClaimedOrder\n if (order.status === finalStatus) return { outcome: 'already', order }\n if (!posHardwareRefundable(order.status)) return { outcome: 'not-refundable', order }\n if (!order.stripePaymentIntentId) return { outcome: 'no-payment', order }\n transaction.update(ref, { refundRequestedAtMs: now() })\n return { outcome: 'claimed', order }\n })\n if (claim.outcome !== 'claimed') return claim\n const before = claim.order\n\n const asked = await posStripe('POST', 'refunds', {\n // The same parameters for every caller: see the module note.\n params: {\n payment_intent: before.stripePaymentIntentId,\n 'metadata[type]': 'pos-hardware-order',\n 'metadata[orderId]': orderId,\n 'metadata[orgId]': orgId,\n },\n idempotencyKey: posHardwareRefundKey(orderId),\n })\n let refund: { id: string; amount: number } | null =\n asked.ok && asked.body?.id ? { id: String(asked.body.id), amount: Number(asked.body.amount ?? 0) } : null\n const code = asked.ok ? null : String(asked.body?.error?.code ?? '') || null\n if (!refund && code === 'charge_already_refunded') {\n refund = await existingRefund(String(before.stripePaymentIntentId))\n }\n if (!refund) {\n await ref.update({ refundRequestedAtMs: firebaseAdmin.firestore.FieldValue.delete() }).catch(() => undefined)\n console.error('[pos-hardware] refund refused', orderId, asked.status, code)\n const settledBefore = { ...before }\n delete settledBefore.refundRequestedAtMs\n return {\n outcome: 'refused',\n order: settledBefore,\n message: String(asked.body?.error?.message ?? '') || 'Stripe refused the refund.',\n code,\n }\n }\n\n const at = now()\n const refundedCents = refund.amount > 0 ? refund.amount : Number(before.totalCents ?? 0)\n const patch = {\n status: finalStatus,\n [POS_HARDWARE_STATUS_STAMP[finalStatus]]: at,\n updatedAtMs: at,\n refundId: refund.id,\n refundedCents,\n cancelReason: reason,\n refundRequestedAtMs: firebaseAdmin.firestore.FieldValue.delete(),\n }\n const settled: ClaimedOrder = { ...before }\n delete settled.refundRequestedAtMs\n const after: PosHardwareOrder = {\n ...settled,\n status: finalStatus,\n [POS_HARDWARE_STATUS_STAMP[finalStatus]]: at,\n updatedAtMs: at,\n refundId: refund.id,\n refundedCents,\n cancelReason: reason,\n }\n // The order and its retained sale record move together: the record is\n // what the refund is accounted from once the workspace is gone.\n await firestore.runTransaction(async (transaction: any) => {\n transaction.update(ref, patch)\n transaction.set(posHardwareSaleRef(orderId), posHardwareSaleRecord(orderId, after), posHardwareSaleSetOptions(after))\n })\n return { outcome: 'settled', before: settled, order: after }\n}\n"],"names":["firebaseAdmin","POS_HARDWARE_STATUS_STAMP","posHardwareRefundable","posHardwareSaleRecord","posHardwareSaleSetOptions","hardwareOrdersRef","posHardwareSaleRef","posStripe","posHardwareRefundKey","orderId","existingRefund","paymentIntentId","found","listed","params","payment_intent","limit","catch","refunds","Array","isArray","body","data","find","refund","id","String","amount","Number","cancelAndRefundPosHardwareOrder","request","asked","before","orgId","finalStatus","reason","now","Date","firestore","app","ref","doc","claim","runTransaction","transaction","snapshot","get","exists","outcome","order","status","stripePaymentIntentId","update","refundRequestedAtMs","idempotencyKey","ok","code","error","FieldValue","delete","undefined","console","settledBefore","message","at","refundedCents","totalCents","patch","updatedAtMs","refundId","cancelReason","settled","after","set"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SACEC,yBAAyB,EACzBC,qBAAqB,EACrBC,qBAAqB,EACrBC,yBAAyB,QAGpB,2BAAuB;AAC9B,SAASC,iBAAiB,EAAEC,kBAAkB,QAAQ,oBAAgB;AACtE,SAASC,SAAS,QAAQ,kBAAc;AAoDxC,6DAA6D,GAC7D,OAAO,SAASC,qBAAqBC,OAAe;IAClD,OAAO,CAAC,cAAc,EAAEA,SAAS;AACnC;AAEA;;;;CAIC,GACD,eAAeC,eAAeC,eAAuB;QAQMC;QAJ3BC,cAAuBA;IAHrD,MAAMA,SAAS,MAAMN,UAAU,OAAO,WAAW;QAC/CO,QAAQ;YAAEC,gBAAgBJ;YAAiBK,OAAO;QAAG;IACvD,GAAGC,KAAK,CAAC,IAAM;IACf,MAAMC,UAAUC,MAAMC,OAAO,CAACP,2BAAAA,eAAAA,OAAQQ,IAAI,qBAAZR,aAAcS,IAAI,IAAKT,2BAAAA,gBAAAA,OAAQQ,IAAI,qBAAZR,cAAcS,IAAI,GAAsC,EAAE;IAC/G,MAAMV,QAAQM,QAAQK,IAAI,CACxB,CAACC,SAAWA,CAAAA,0BAAAA,MAAQ,CAAC,KAAK,KAAKA,CAAAA,CAAAA,0BAAAA,MAAQ,CAAC,SAAS,MAAK,eAAeA,CAAAA,0BAAAA,MAAQ,CAAC,SAAS,MAAK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AC,EAAE8B;QAC1CI,aAAaJ;QACbK,UAAU7C,OAAOC,EAAE;QACnBwC;QACAK,cAAcnC;QACdkB,qBAAqBrD,cAAcsC,SAAS,CAACoB,UAAU,CAACC,MAAM;IAChE;IACA,MAAMY,UAAwB,aAAKvC;IACnC,OAAOuC,QAAQlB,mBAAmB;IAClC,MAAMmB,QAA0B,aAC3BD;QACHrB,QAAQhB;QACR,CAACjC,yBAAyB,CAACiC,YAAY,CAAC,EAAE8B;QAC1CI,aAAaJ;QACbK,UAAU7C,OAAOC,EAAE;QACnBwC;QACAK,cAAcnC;;IAEhB,sEAAsE;IACtE,gEAAgE;IAChE,MAAMG,UAAUK,cAAc,CAAC,OAAOC;QACpCA,YAAYQ,MAAM,CAACZ,KAAK2B;QACxBvB,YAAY6B,GAAG,CAACnE,mBAAmBG,UAAUN,sBAAsBM,SAAS+D,QAAQpE,0BAA0BoE;IAChH;IACA,OAAO;QAAExB,SAAS;QAAWhB,QAAQuC;QAAStB,OAAOuB;IAAM;AAC7D"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-cancel.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 { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n POS_HARDWARE_STATUS_STAMP,\n posHardwareRefundable,\n posHardwareSaleRecord,\n posHardwareSaleSetOptions,\n type PosHardwareCancelReason,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\nimport { hardwareOrdersRef, posHardwareSaleRef } from './pos-hardware'\nimport { posStripe } from './pos-stripe'\n\n/*==========================================\n * CANCELING AND REFUNDING A HARDWARE ORDER IN FULL (AGL-4038).\n *\n * One path for every caller: staff on the Hardware orders page, and the\n * closures (a workspace deleted, the buying account closed) that cancel every\n * order of theirs that has not shipped. Each refunds the whole payment on the\n * PLATFORM account, only before the order ships, and only once:\n *\n * 1. CLAIM under the lock: the order must still be paid or ordered, and\n * `refundRequestedAtMs` is set, so it cannot be marked shipped while the\n * money is on its way back.\n * 2. REFUND through Stripe under ONE idempotency key per order,\n * `pos-hw-refund-{orderId}`, with the same parameters whoever asks — a\n * key replayed with different parameters is refused by Stripe, so no\n * caller adds its own. A second ask inside Stripe's key window gets the\n * first refund back; after it, Stripe refuses the charge as already\n * refunded, and the refund it already made is read back instead of a\n * second one made.\n * 3. SETTLE: the order and its retained sale record move together, in one\n * transaction, with the refund id, the cents Stripe reported and why.\n *\n * Stripe refusing releases the claim, so the order can still ship. Telling\n * people (the buyer, staff) and the audit row are the caller's: staff and a\n * closure say different things.\n *=========================================*/\n\n/** What became of one cancel. */\nexport type PosHardwareCancelResult =\n /** Refunded now (or Stripe's earlier refund recovered) and settled. */\n | { outcome: 'settled'; before: PosHardwareOrder; order: PosHardwareOrder }\n /** It already had the final status: nothing was asked of Stripe. */\n | { outcome: 'already'; order: PosHardwareOrder }\n | { outcome: 'missing' }\n /** Shipped, delivered, registered, or canceled the other way. */\n | { outcome: 'not-refundable'; order: PosHardwareOrder }\n | { outcome: 'no-payment'; order: PosHardwareOrder }\n /** Stripe refused; the claim was released and the order is as it was. */\n | { outcome: 'refused'; order: PosHardwareOrder; message: string; code: string | null }\n\nexport interface PosHardwareCancelRequest {\n orgId: string\n orderId: string\n /** `canceled` for a cancel (staff or closure), `refunded` for a staff refund. */\n finalStatus: 'canceled' | 'refunded'\n reason: PosHardwareCancelReason\n now?: () => number\n}\n\ntype ClaimedOrder = PosHardwareOrder & { refundRequestedAtMs?: number }\n\n/** The idempotency key every caller refunds an order under. */\nexport function posHardwareRefundKey(orderId: string): string {\n return `pos-hw-refund-${orderId}`\n}\n\n/**\n * The refund Stripe already made on this payment, for a charge it refuses as\n * already refunded: the earlier ask settled at Stripe and never reached the\n * order (a crash between the two, or an ask after Stripe's key window).\n */\nasync function existingRefund(paymentIntentId: string): Promise<{ id: string; amount: number } | null> {\n const listed = await posStripe('GET', 'refunds', {\n params: { payment_intent: paymentIntentId, limit: 10 },\n }).catch(() => null)\n const refunds = Array.isArray(listed?.body?.data) ? (listed?.body?.data as Array<Record<string, unknown>>) : []\n const found = refunds.find(\n (refund) => refund?.['id'] && (refund?.['status'] === 'succeeded' || refund?.['status'] === 'pending'),\n )\n return found ? { id: String(found['id']), amount: Number(found['amount'] ?? 0) } : null\n}\n\nexport async function cancelAndRefundPosHardwareOrder(\n request: PosHardwareCancelRequest,\n): Promise<PosHardwareCancelResult> {\n const { orgId, orderId, finalStatus, reason } = request\n const now = request.now ?? Date.now\n const firestore = firebaseAdmin.app().firestore()\n const ref = hardwareOrdersRef(orgId).doc(orderId)\n\n // Bought from the platform's own online store (AGL-4038): its money is in\n // that store's account, so it comes back through the store order's own\n // refund, never a refund on the platform's balance.\n const stored = (await ref.get()).data() as PosHardwareOrder | undefined\n if (stored?.source === 'storefront') return cancelSellerStoreOrder(request, stored)\n\n const claim = await firestore.runTransaction(async (transaction: any): Promise<PosHardwareCancelResult | { outcome: 'claimed'; order: ClaimedOrder }> => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) return { outcome: 'missing' }\n const order = snapshot.data() as ClaimedOrder\n if (order.status === finalStatus) return { outcome: 'already', order }\n if (!posHardwareRefundable(order.status)) return { outcome: 'not-refundable', order }\n if (!order.stripePaymentIntentId) return { outcome: 'no-payment', order }\n transaction.update(ref, { refundRequestedAtMs: now() })\n return { outcome: 'claimed', order }\n })\n if (claim.outcome !== 'claimed') return claim\n const before = claim.order\n\n const asked = await posStripe('POST', 'refunds', {\n // The same parameters for every caller: see the module note.\n params: {\n payment_intent: before.stripePaymentIntentId,\n 'metadata[type]': 'pos-hardware-order',\n 'metadata[orderId]': orderId,\n 'metadata[orgId]': orgId,\n },\n idempotencyKey: posHardwareRefundKey(orderId),\n })\n let refund: { id: string; amount: number } | null =\n asked.ok && asked.body?.id ? { id: String(asked.body.id), amount: Number(asked.body.amount ?? 0) } : null\n const code = asked.ok ? null : String(asked.body?.error?.code ?? '') || null\n if (!refund && code === 'charge_already_refunded') {\n refund = await existingRefund(String(before.stripePaymentIntentId))\n }\n if (!refund) {\n await ref.update({ refundRequestedAtMs: firebaseAdmin.firestore.FieldValue.delete() }).catch(() => undefined)\n console.error('[pos-hardware] refund refused', orderId, asked.status, code)\n const settledBefore = { ...before }\n delete settledBefore.refundRequestedAtMs\n return {\n outcome: 'refused',\n order: settledBefore,\n message: String(asked.body?.error?.message ?? '') || 'Stripe refused the refund.',\n code,\n }\n }\n\n const at = now()\n const refundedCents = refund.amount > 0 ? refund.amount : Number(before.totalCents ?? 0)\n const patch = {\n status: finalStatus,\n [POS_HARDWARE_STATUS_STAMP[finalStatus]]: at,\n updatedAtMs: at,\n refundId: refund.id,\n refundedCents,\n cancelReason: reason,\n refundRequestedAtMs: firebaseAdmin.firestore.FieldValue.delete(),\n }\n const settled: ClaimedOrder = { ...before }\n delete settled.refundRequestedAtMs\n const after: PosHardwareOrder = {\n ...settled,\n status: finalStatus,\n [POS_HARDWARE_STATUS_STAMP[finalStatus]]: at,\n updatedAtMs: at,\n refundId: refund.id,\n refundedCents,\n cancelReason: reason,\n }\n // The order and its retained sale record move together: the record is\n // what the refund is accounted from once the workspace is gone.\n await firestore.runTransaction(async (transaction: any) => {\n transaction.update(ref, patch)\n transaction.set(posHardwareSaleRef(orderId), posHardwareSaleRecord(orderId, after), posHardwareSaleSetOptions(after))\n })\n return { outcome: 'settled', before: settled, order: after }\n}\n\n/**\n * Cancels an order the platform's own online store sold (AGL-4038): the\n * same rules as {@link cancelAndRefundPosHardwareOrder} — only before it\n * ships, once — with the refund made through the store order's own card\n * refund (`refundInPersonPosHardwareOrder`), which reverses the transfer into\n * the store's account and writes the refund onto the order once by its key.\n */\nasync function cancelSellerStoreOrder(\n request: PosHardwareCancelRequest,\n stored: PosHardwareOrder,\n): Promise<PosHardwareCancelResult> {\n const { orgId, orderId, finalStatus, reason } = request\n const now = request.now ?? Date.now\n if (stored.status === finalStatus) return { outcome: 'already', order: stored }\n if (!posHardwareRefundable(stored.status)) return { outcome: 'not-refundable', order: stored }\n const [{ refundInPersonPosHardwareOrder, PosHardwareReturnRefusal }, { posHardwareInPersonConfig }] = await Promise.all([\n import('./pos-hardware-returns'),\n import('./pos-hardware'),\n ])\n let refunded: PosHardwareOrder\n try {\n refunded = (\n await refundInPersonPosHardwareOrder({\n config: posHardwareInPersonConfig(),\n orgId,\n orderId,\n actorUid: `system:${reason}`,\n now: now(),\n })\n ).order\n } catch (error) {\n if (error instanceof PosHardwareReturnRefusal) {\n return { outcome: 'refused', order: stored, message: error.message, code: null }\n }\n throw error\n }\n const at = now()\n const ref = hardwareOrdersRef(orgId).doc(orderId)\n const after: PosHardwareOrder = {\n ...refunded,\n status: finalStatus,\n [POS_HARDWARE_STATUS_STAMP[finalStatus]]: at,\n updatedAtMs: at,\n cancelReason: reason,\n }\n await firebaseAdmin\n .app()\n .firestore()\n .runTransaction(async (transaction: any) => {\n transaction.set(ref, after)\n transaction.set(posHardwareSaleRef(orderId), posHardwareSaleRecord(orderId, after), posHardwareSaleSetOptions(after))\n })\n return { outcome: 'settled', before: stored, order: after }\n}\n"],"names":["firebaseAdmin","POS_HARDWARE_STATUS_STAMP","posHardwareRefundable","posHardwareSaleRecord","posHardwareSaleSetOptions","hardwareOrdersRef","posHardwareSaleRef","posStripe","posHardwareRefundKey","orderId","existingRefund","paymentIntentId","found","listed","params","payment_intent","limit","catch","refunds","Array","isArray","body","data","find","refund","id","String","amount","Number","cancelAndRefundPosHardwareOrder","request","asked","before","orgId","finalStatus","reason","now","Date","firestore","app","ref","doc","stored","get","source","cancelSellerStoreOrder","claim","runTransaction","transaction","snapshot","exists","outcome","order","status","stripePaymentIntentId","update","refundRequestedAtMs","idempotencyKey","ok","code","error","FieldValue","delete","undefined","console","settledBefore","message","at","refundedCents","totalCents","patch","updatedAtMs","refundId","cancelReason","settled","after","set","refundInPersonPosHardwareOrder","PosHardwareReturnRefusal","posHardwareInPersonConfig","Promise","all","refunded","config","actorUid"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SACEC,yBAAyB,EACzBC,qBAAqB,EACrBC,qBAAqB,EACrBC,yBAAyB,QAGpB,2BAAuB;AAC9B,SAASC,iBAAiB,EAAEC,kBAAkB,QAAQ,oBAAgB;AACtE,SAASC,SAAS,QAAQ,kBAAc;AAoDxC,6DAA6D,GAC7D,OAAO,SAASC,qBAAqBC,OAAe;IAClD,OAAO,CAAC,cAAc,EAAEA,SAAS;AACnC;AAEA;;;;CAIC,GACD,eAAeC,eAAeC,eAAuB;QAQMC;QAJ3BC,cAAuBA;IAHrD,MAAMA,SAAS,MAAMN,UAAU,OAAO,WAAW;QAC/CO,QAAQ;YAAEC,gBAAgBJ;YAAiBK,OAAO;QAAG;IACvD,GAAGC,KAAK,CAAC,IAAM;IACf,MAAMC,UAAUC,MAAMC,OAAO,CAACP,2BAAAA,eAAAA,OAAQQ,IAAI,qBAAZR,aAAcS,IAAI,IAAKT,2BAAAA,gBAAAA,OAAQQ,IAAI,qBAAZR,cAAcS,IAAI,GAAsC,EAAE;IAC/G,MAAMV,QAAQM,QAAQK,IAAI,CACxB,CAACC,SAAWA,CAAAA,0BAAAA,MAAQ,CAAC,KAAK,KAAKA,CAAAA,CAAAA,0BAAAA,MAAQ,CAAC,SAAS,MAAK,eAAeA,CAAAA,0BAAAA,MAAQ,CAAC,SAAS,MAAK,SAAQ;IAEtG,OAAOZ,QAAQ;QAAEa,IAAIC,OAAOd,KAAK,CAAC,KAAK;QAAGe,QAAQC,QAAOhB,gBAAAA,KAAK,CAAC,SAAS,YAAfA,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AAM,CAAC;KACR;IACD,IAAIC;IACJ,IAAI;QACFA,WAAW,AACT,CAAA,MAAML,+BAA+B;YACnCM,QAAQJ;YACR9C;YACAxB;YACA2E,UAAU,CAAC,OAAO,EAAEjD,QAAQ;YAC5BC,KAAKA;QACP,EAAC,EACDgB,KAAK;IACT,EAAE,OAAOQ,OAAO;QACd,IAAIA,iBAAiBkB,0BAA0B;YAC7C,OAAO;gBAAE3B,SAAS;gBAAWC,OAAOV;gBAAQwB,SAASN,MAAMM,OAAO;gBAAEP,MAAM;YAAK;QACjF;QACA,MAAMC;IACR;IACA,MAAMO,KAAK/B;IACX,MAAMI,MAAMnC,kBAAkB4B,OAAOQ,GAAG,CAAChC;IACzC,MAAMkE,QAA0B,aAC3BO;QACH7B,QAAQnB;QACR,CAACjC,yBAAyB,CAACiC,YAAY,CAAC,EAAEiC;QAC1CI,aAAaJ;QACbM,cAActC;;IAEhB,MAAMnC,cACHuC,GAAG,GACHD,SAAS,GACTS,cAAc,CAAC,OAAOC;QACrBA,YAAY4B,GAAG,CAACpC,KAAKmC;QACrB3B,YAAY4B,GAAG,CAACtE,mBAAmBG,UAAUN,sBAAsBM,SAASkE,QAAQvE,0BAA0BuE;IAChH;IACF,OAAO;QAAExB,SAAS;QAAWnB,QAAQU;QAAQU,OAAOuB;IAAM;AAC5D"}
@@ -14,7 +14,7 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */ import { firebaseAdmin } from "@aglyn/tenant-data-admin";
17
- import { formatPosHardwareCents, POS_HARDWARE_ORDERS_COLLECTION, posHardwareRefundable } from "../model/pos-hardware.js";
17
+ import { POS_HARDWARE_UNSHIPPED_STATUSES, formatPosHardwareCents, POS_HARDWARE_ORDERS_COLLECTION, posHardwareRefundable } from "../model/pos-hardware.js";
18
18
  /*==========================================
19
19
  * BEFORE A CLOSURE: WHICH HARDWARE ORDERS IT WILL CANCEL AND REFUND (AGL-4038).
20
20
  *
@@ -61,10 +61,7 @@ import { formatPosHardwareCents, POS_HARDWARE_ORDERS_COLLECTION, posHardwareRefu
61
61
  if (subject.kind === 'workspace') {
62
62
  const orders = firestore.collection('orgs').doc(subject.orgId).collection(POS_HARDWARE_ORDERS_COLLECTION);
63
63
  // One equality query per status, as the closure reads them.
64
- const found = await Promise.all([
65
- 'paid',
66
- 'ordered'
67
- ].map((status)=>orders.where('status', '==', status).get()));
64
+ const found = await Promise.all(POS_HARDWARE_UNSHIPPED_STATUSES.map((status)=>orders.where('status', '==', status).get()));
68
65
  return found.flatMap((snapshot)=>snapshot.docs.map((doc)=>({
69
66
  orderId: doc.id,
70
67
  order: doc.data()
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-closure-notices.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 {\n ClosureNotice,\n ClosureNoticeSource,\n ClosureSubject,\n} from '@aglyn/aglyn/plugin-manager/plugin-closure-notices'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n formatPosHardwareCents,\n POS_HARDWARE_ORDERS_COLLECTION,\n posHardwareRefundable,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\n\n/*==========================================\n * BEFORE A CLOSURE: WHICH HARDWARE ORDERS IT WILL CANCEL AND REFUND (AGL-4038).\n *\n * Deleting a workspace, or closing the account that placed an order, cancels\n * every card reader order that has not shipped — paid, or already placed\n * with Stripe — and refunds it in full (`pos-hardware-closure.ts`). The\n * delete-workspace and close-account screens ask core's closure notices\n * before the confirm, and this answers for the hardware shop: one warning\n * listing each such order, its number, its items and what is refunded.\n *\n * The same orders the closure reads: a workspace's own (`paid` or `ordered`),\n * or every one the person placed in any workspace (by `createdBy`, the\n * collection-group override the account eraser uses). Nothing is held back:\n * the closure goes ahead, and this only says what it will do.\n *=========================================*/\n\n/** The notice's id. */\nexport const POS_HARDWARE_CLOSURE_NOTICE_ID = 'pos-hardware-unshipped-orders'\n\n/** The number a person reads: `HW-` and six characters of the id. */\nfunction orderNumber(orderId: string): string {\n return `HW-${orderId.replace(/^hw_/, '').slice(0, 6).toUpperCase()}`\n}\n\n/** The warning for these unshipped orders, or none when there are none. Pure. */\nexport function posHardwareClosureNotice(\n subject: ClosureSubject['kind'],\n orders: ReadonlyArray<{ orderId: string; order: Pick<PosHardwareOrder, 'status' | 'lines' | 'totalCents'> }>,\n): ClosureNotice[] {\n const unshipped = orders.filter(({ order }) => posHardwareRefundable(order?.status))\n if (!unshipped.length) return []\n const count = unshipped.length\n const one = count === 1\n return [\n {\n id: POS_HARDWARE_CLOSURE_NOTICE_ID,\n severity: 'warning',\n title: one\n ? 'A card reader order will be canceled and refunded'\n : `${count} card reader orders will be canceled and refunded`,\n body:\n subject === 'workspace'\n ? `${one ? 'This order has' : 'These orders have'} not shipped yet. When the workspace is deleted, ` +\n `${one ? 'it is' : 'each is'} canceled and refunded in full, shipping and tax included, to the card ` +\n `it was paid with, and the person who placed ${one ? 'it gets an email' : 'each gets an email'}. ` +\n `Nothing will ship. Keep the workspace if you still want ${one ? 'it' : 'them'}.`\n : `${one ? 'This order you placed has' : 'These orders you placed have'} not shipped yet. When your ` +\n `account is closed, ${one ? 'it is' : 'each is'} canceled and refunded in full, shipping and tax ` +\n `included, to the card it was paid with, and you get an email about ${one ? 'it' : 'each'}. Nothing ` +\n `will ship. Keep your account if you still want ${one ? 'it' : 'them'}.`,\n items: unshipped.map(({ orderId, order }) => ({\n id: orderId,\n primary: `Order ${orderNumber(orderId)}`,\n secondary: (order.lines ?? []).map((line) => `${line.name} × ${line.quantity}`).join(', ') || undefined,\n amount: formatPosHardwareCents(Number(order.totalCents ?? 0)),\n })),\n },\n ]\n}\n\n/** Reads the unshipped orders a closure of `subject` would cancel. */\nasync function unshippedOrders(\n subject: ClosureSubject,\n): Promise<Array<{ orderId: string; order: PosHardwareOrder }>> {\n const firestore = firebaseAdmin.app().firestore()\n if (subject.kind === 'workspace') {\n const orders = firestore.collection('orgs').doc(subject.orgId).collection(POS_HARDWARE_ORDERS_COLLECTION)\n // One equality query per status, as the closure reads them.\n const found = await Promise.all(['paid', 'ordered'].map((status) => orders.where('status', '==', status).get()))\n return found.flatMap((snapshot) =>\n snapshot.docs.map((doc: { id: string; data: () => unknown }) => ({ orderId: doc.id, order: doc.data() as PosHardwareOrder })),\n )\n }\n const placed = await firestore.collectionGroup(POS_HARDWARE_ORDERS_COLLECTION).where('createdBy', '==', subject.uid).get()\n return placed.docs.map((doc: { id: string; data: () => unknown }) => ({ orderId: doc.id, order: doc.data() as PosHardwareOrder }))\n}\n\n/** The hardware shop's closure notices, as the declarations register them. */\nexport const posHardwareClosureNoticeSource: ClosureNoticeSource = {\n async notices(subject) {\n return posHardwareClosureNotice(subject.kind, await unshippedOrders(subject))\n },\n}\n"],"names":["firebaseAdmin","formatPosHardwareCents","POS_HARDWARE_ORDERS_COLLECTION","posHardwareRefundable","POS_HARDWARE_CLOSURE_NOTICE_ID","orderNumber","orderId","replace","slice","toUpperCase","posHardwareClosureNotice","subject","orders","unshipped","filter","order","status","length","count","one","id","severity","title","body","items","map","primary","secondary","lines","line","name","quantity","join","undefined","amount","Number","totalCents","unshippedOrders","firestore","app","kind","collection","doc","orgId","found","Promise","all","where","get","flatMap","snapshot","docs","data","placed","collectionGroup","uid","posHardwareClosureNoticeSource","notices"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAOD,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SACEC,sBAAsB,EACtBC,8BAA8B,EAC9BC,qBAAqB,QAEhB,2BAAuB;AAE9B;;;;;;;;;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,gBAAgB1B;IACtE;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-closure-notices.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 {\n ClosureNotice,\n ClosureNoticeSource,\n ClosureSubject,\n} from '@aglyn/aglyn/plugin-manager/plugin-closure-notices'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n POS_HARDWARE_UNSHIPPED_STATUSES,\n formatPosHardwareCents,\n POS_HARDWARE_ORDERS_COLLECTION,\n posHardwareRefundable,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\n\n/*==========================================\n * BEFORE A CLOSURE: WHICH HARDWARE ORDERS IT WILL CANCEL AND REFUND (AGL-4038).\n *\n * Deleting a workspace, or closing the account that placed an order, cancels\n * every card reader order that has not shipped — paid, or already placed\n * with Stripe — and refunds it in full (`pos-hardware-closure.ts`). The\n * delete-workspace and close-account screens ask core's closure notices\n * before the confirm, and this answers for the hardware shop: one warning\n * listing each such order, its number, its items and what is refunded.\n *\n * The same orders the closure reads: a workspace's own (`paid` or `ordered`),\n * or every one the person placed in any workspace (by `createdBy`, the\n * collection-group override the account eraser uses). Nothing is held back:\n * the closure goes ahead, and this only says what it will do.\n *=========================================*/\n\n/** The notice's id. */\nexport const POS_HARDWARE_CLOSURE_NOTICE_ID = 'pos-hardware-unshipped-orders'\n\n/** The number a person reads: `HW-` and six characters of the id. */\nfunction orderNumber(orderId: string): string {\n return `HW-${orderId.replace(/^hw_/, '').slice(0, 6).toUpperCase()}`\n}\n\n/** The warning for these unshipped orders, or none when there are none. Pure. */\nexport function posHardwareClosureNotice(\n subject: ClosureSubject['kind'],\n orders: ReadonlyArray<{ orderId: string; order: Pick<PosHardwareOrder, 'status' | 'lines' | 'totalCents'> }>,\n): ClosureNotice[] {\n const unshipped = orders.filter(({ order }) => posHardwareRefundable(order?.status))\n if (!unshipped.length) return []\n const count = unshipped.length\n const one = count === 1\n return [\n {\n id: POS_HARDWARE_CLOSURE_NOTICE_ID,\n severity: 'warning',\n title: one\n ? 'A card reader order will be canceled and refunded'\n : `${count} card reader orders will be canceled and refunded`,\n body:\n subject === 'workspace'\n ? `${one ? 'This order has' : 'These orders have'} not shipped yet. When the workspace is deleted, ` +\n `${one ? 'it is' : 'each is'} canceled and refunded in full, shipping and tax included, to the card ` +\n `it was paid with, and the person who placed ${one ? 'it gets an email' : 'each gets an email'}. ` +\n `Nothing will ship. Keep the workspace if you still want ${one ? 'it' : 'them'}.`\n : `${one ? 'This order you placed has' : 'These orders you placed have'} not shipped yet. When your ` +\n `account is closed, ${one ? 'it is' : 'each is'} canceled and refunded in full, shipping and tax ` +\n `included, to the card it was paid with, and you get an email about ${one ? 'it' : 'each'}. Nothing ` +\n `will ship. Keep your account if you still want ${one ? 'it' : 'them'}.`,\n items: unshipped.map(({ orderId, order }) => ({\n id: orderId,\n primary: `Order ${orderNumber(orderId)}`,\n secondary: (order.lines ?? []).map((line) => `${line.name} × ${line.quantity}`).join(', ') || undefined,\n amount: formatPosHardwareCents(Number(order.totalCents ?? 0)),\n })),\n },\n ]\n}\n\n/** Reads the unshipped orders a closure of `subject` would cancel. */\nasync function unshippedOrders(\n subject: ClosureSubject,\n): Promise<Array<{ orderId: string; order: PosHardwareOrder }>> {\n const firestore = firebaseAdmin.app().firestore()\n if (subject.kind === 'workspace') {\n const orders = firestore.collection('orgs').doc(subject.orgId).collection(POS_HARDWARE_ORDERS_COLLECTION)\n // One equality query per status, as the closure reads them.\n const found = await Promise.all(POS_HARDWARE_UNSHIPPED_STATUSES.map((status) => orders.where('status', '==', status).get()))\n return found.flatMap((snapshot) =>\n snapshot.docs.map((doc: { id: string; data: () => unknown }) => ({ orderId: doc.id, order: doc.data() as PosHardwareOrder })),\n )\n }\n const placed = await firestore.collectionGroup(POS_HARDWARE_ORDERS_COLLECTION).where('createdBy', '==', subject.uid).get()\n return placed.docs.map((doc: { id: string; data: () => unknown }) => ({ orderId: doc.id, order: doc.data() as PosHardwareOrder }))\n}\n\n/** The hardware shop's closure notices, as the declarations register them. */\nexport const posHardwareClosureNoticeSource: ClosureNoticeSource = {\n async notices(subject) {\n return posHardwareClosureNotice(subject.kind, await unshippedOrders(subject))\n },\n}\n"],"names":["firebaseAdmin","POS_HARDWARE_UNSHIPPED_STATUSES","formatPosHardwareCents","POS_HARDWARE_ORDERS_COLLECTION","posHardwareRefundable","POS_HARDWARE_CLOSURE_NOTICE_ID","orderNumber","orderId","replace","slice","toUpperCase","posHardwareClosureNotice","subject","orders","unshipped","filter","order","status","length","count","one","id","severity","title","body","items","map","primary","secondary","lines","line","name","quantity","join","undefined","amount","Number","totalCents","unshippedOrders","firestore","app","kind","collection","doc","orgId","found","Promise","all","where","get","flatMap","snapshot","docs","data","placed","collectionGroup","uid","posHardwareClosureNoticeSource","notices"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAOD,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SACEC,+BAA+B,EAC/BC,sBAAsB,EACtBC,8BAA8B,EAC9BC,qBAAqB,QAEhB,2BAAuB;AAE9B;;;;;;;;;;;;;;2CAc2C,GAE3C,qBAAqB,GACrB,OAAO,MAAMC,iCAAiC,gCAA+B;AAE7E,mEAAmE,GACnE,SAASC,YAAYC,OAAe;IAClC,OAAO,CAAC,GAAG,EAAEA,QAAQC,OAAO,CAAC,QAAQ,IAAIC,KAAK,CAAC,GAAG,GAAGC,WAAW,IAAI;AACtE;AAEA,+EAA+E,GAC/E,OAAO,SAASC,yBACdC,OAA+B,EAC/BC,MAA4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E,GACpE,eAAesB,gBACb1B,OAAuB;IAEvB,MAAM2B,YAAYvC,cAAcwC,GAAG,GAAGD,SAAS;IAC/C,IAAI3B,QAAQ6B,IAAI,KAAK,aAAa;QAChC,MAAM5B,SAAS0B,UAAUG,UAAU,CAAC,QAAQC,GAAG,CAAC/B,QAAQgC,KAAK,EAAEF,UAAU,CAACvC;QAC1E,4DAA4D;QAC5D,MAAM0C,QAAQ,MAAMC,QAAQC,GAAG,CAAC9C,gCAAgCyB,GAAG,CAAC,CAACT,SAAWJ,OAAOmC,KAAK,CAAC,UAAU,MAAM/B,QAAQgC,GAAG;QACxH,OAAOJ,MAAMK,OAAO,CAAC,CAACC,WACpBA,SAASC,IAAI,CAAC1B,GAAG,CAAC,CAACiB,MAA8C,CAAA;oBAAEpC,SAASoC,IAAItB,EAAE;oBAAEL,OAAO2B,IAAIU,IAAI;gBAAuB,CAAA;IAE9H;IACA,MAAMC,SAAS,MAAMf,UAAUgB,eAAe,CAACpD,gCAAgC6C,KAAK,CAAC,aAAa,MAAMpC,QAAQ4C,GAAG,EAAEP,GAAG;IACxH,OAAOK,OAAOF,IAAI,CAAC1B,GAAG,CAAC,CAACiB,MAA8C,CAAA;YAAEpC,SAASoC,IAAItB,EAAE;YAAEL,OAAO2B,IAAIU,IAAI;QAAuB,CAAA;AACjI;AAEA,4EAA4E,GAC5E,OAAO,MAAMI,iCAAsD;IACjE,MAAMC,SAAQ9C,OAAO;QACnB,OAAOD,yBAAyBC,QAAQ6B,IAAI,EAAE,MAAMH,gBAAgB1B;IACtE;AACF,EAAC"}
@@ -16,13 +16,10 @@
16
16
  */ import { _ as _extends } from "@swc/helpers/_/_extends";
17
17
  import { firebaseAdmin } from "@aglyn/tenant-data-admin";
18
18
  import { addAdminAudit } from "@aglyn/tenant-data-admin/server/admin-audit-write";
19
- import { POS_HARDWARE_ORDERS_COLLECTION } from "../model/pos-hardware.js";
19
+ import { POS_HARDWARE_ORDERS_COLLECTION, POS_HARDWARE_UNSHIPPED_STATUSES } from "../model/pos-hardware.js";
20
20
  import { cancelAndRefundPosHardwareOrder } from "./pos-hardware-cancel.js";
21
21
  import { raisePosHardwareCanceledAfterOrderingAlert, raisePosHardwareRefundFailedAlert, sendPosHardwareEmailOnce } from "./pos-hardware-notify.js";
22
- /** The unshipped statuses a closure cancels. */ const UNSHIPPED = [
23
- 'paid',
24
- 'ordered'
25
- ];
22
+ /** The unshipped statuses a closure cancels: paid, ordered, or received and being set up. */ const UNSHIPPED = POS_HARDWARE_UNSHIPPED_STATUSES;
26
23
  /** The audit row's actor: the closure, never a person. */ const CLOSURE_ACTOR = {
27
24
  'workspace-closed': 'system:workspace-closed',
28
25
  'account-closed': 'system:account-closed'
@@ -77,7 +74,7 @@ import { raisePosHardwareCanceledAfterOrderingAlert, raisePosHardwareRefundFaile
77
74
  // Once between this and the staff page: a staff cancel that already
78
75
  // told the buyer is not told again (AGL-4038).
79
76
  await sendPosHardwareEmailOnce('canceled', orderId, result.order);
80
- if (result.before.status === 'ordered') {
77
+ if (result.before.status === 'ordered' || result.before.status === 'received') {
81
78
  await raisePosHardwareCanceledAfterOrderingAlert(orderId, result.order, reason);
82
79
  }
83
80
  return 'canceled';
@@ -108,7 +105,7 @@ import { raisePosHardwareCanceledAfterOrderingAlert, raisePosHardwareRefundFaile
108
105
  const outcome = await closeUnshippedPosHardwareOrder(order.orgId, orderId, reason, order);
109
106
  if (outcome === 'canceled') {
110
107
  counts.hardwareOrdersCanceled += 1;
111
- if (order.status === 'ordered') counts.hardwareOrdersPlacedWithStripe += 1;
108
+ if (order.status === 'ordered' || order.status === 'received') counts.hardwareOrdersPlacedWithStripe += 1;
112
109
  }
113
110
  if (outcome === 'failed') counts.hardwareRefundsFailed += 1;
114
111
  }
@@ -139,7 +136,7 @@ import { raisePosHardwareCanceledAfterOrderingAlert, raisePosHardwareRefundFaile
139
136
  if (dryRun) {
140
137
  return {
141
138
  hardwareOrdersCanceled: unshipped.length,
142
- hardwareOrdersPlacedWithStripe: unshipped.filter(({ order })=>order.status === 'ordered').length,
139
+ hardwareOrdersPlacedWithStripe: unshipped.filter(({ order })=>order.status === 'ordered' || order.status === 'received').length,
143
140
  hardwareRefundsFailed: 0
144
141
  };
145
142
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-closure.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 {\n PluginOrgEraser,\n PluginOrgErasureReport,\n} from '@aglyn/aglyn/plugin-manager/plugin-org-erasure'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { addAdminAudit } from '@aglyn/tenant-data-admin/server/admin-audit-write'\nimport {\n POS_HARDWARE_ORDERS_COLLECTION,\n type PosHardwareCancelReason,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\nimport { cancelAndRefundPosHardwareOrder } from './pos-hardware-cancel'\nimport {\n raisePosHardwareCanceledAfterOrderingAlert,\n raisePosHardwareRefundFailedAlert,\n sendPosHardwareEmailOnce,\n} from './pos-hardware-notify'\n\n/*==========================================\n * A CLOSURE CANCELS EVERY UNSHIPPED HARDWARE ORDER (AGL-4038).\n *\n * When the workspace that bought hardware is deleted, or the account that\n * placed an order is closed, every order of theirs that has not shipped —\n * `paid` or `ordered` — is canceled and refunded in full on the platform's\n * Stripe account, through the staff page's own path and its idempotency\n * (`pos-hardware-cancel.ts`). Then:\n *\n * - the buyer gets the \"canceled and refunded\" email, once: the same claim\n * the staff page sends it under (`sendPosHardwareEmailOnce`);\n * - staff get an alert when the order was already placed with Stripe\n * (`ordered`), because Stripe will still ship it unless someone cancels\n * it there, and another when Stripe refuses the refund;\n * - an `adminAudit` row records the cancel, with the closure as its actor.\n *\n * THE CLOSURE NEVER WAITS ON THIS. A refusal, or a throw, is counted and\n * alerted and the next order is tried; nothing here fails the erasure, so\n * the workspace or the account closes right away whatever Stripe says.\n * Shipped, delivered and registered orders are untouched, and the retained\n * sale record (`posHardwareSales`) records the refund and outlives both.\n *\n * Idempotent: a canceled order is no longer `paid` or `ordered`, so a second\n * closure run finds nothing to refund, sends no second email, raises no\n * second alert and makes no second Stripe call. A run that died after Stripe\n * refunded and before the order said so reads that refund back instead of\n * making another (`pos-hardware-cancel.ts`).\n *=========================================*/\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport type PosHardwareClosureOutcome = 'canceled' | 'already' | 'skipped' | 'failed'\n\n/** The unshipped statuses a closure cancels. */\nconst UNSHIPPED = ['paid', 'ordered'] as const\n\n/** The audit row's actor: the closure, never a person. */\nconst CLOSURE_ACTOR: Record<Exclude<PosHardwareCancelReason, 'staff'>, string> = {\n 'workspace-closed': 'system:workspace-closed',\n 'account-closed': 'system:account-closed',\n}\n\n/**\n * Cancels and refunds one unshipped order because of a closure, and tells\n * the buyer and staff. Never throws. `known` is the order as the closure read\n * it, for the alert should the cancel itself throw.\n */\nexport async function closeUnshippedPosHardwareOrder(\n orgId: string,\n orderId: string,\n reason: Exclude<PosHardwareCancelReason, 'staff'>,\n known?: PosHardwareOrder,\n): Promise<PosHardwareClosureOutcome> {\n try {\n const result = await cancelAndRefundPosHardwareOrder({ orgId, orderId, finalStatus: 'canceled', reason })\n switch (result.outcome) {\n case 'missing':\n case 'not-refundable':\n return 'skipped'\n case 'already':\n // Canceled between the closure's read and the lock: whoever canceled\n // it told the buyer and staff.\n return 'already'\n case 'no-payment':\n await raisePosHardwareRefundFailedAlert(orderId, result.order, reason, 'the order has no payment to refund')\n return 'failed'\n case 'refused':\n await raisePosHardwareRefundFailedAlert(orderId, result.order, reason, result.message)\n return 'failed'\n }\n const firestore = firebaseAdmin.app().firestore()\n await addAdminAudit(firestore, {\n action: 'pos-hardware-order-cancel',\n actorUid: CLOSURE_ACTOR[reason],\n actorEmail: null,\n scope: 'posHardwareOrder',\n target: `orgs/${orgId}/${POS_HARDWARE_ORDERS_COLLECTION}/${orderId}`,\n orgId,\n before: { status: result.before.status },\n after: {\n status: result.order.status,\n refundId: result.order.refundId ?? null,\n refundedCents: result.order.refundedCents ?? null,\n reason,\n },\n at: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n }).catch((error: unknown) => console.error('[pos-hardware] closure audit failed', orderId, error))\n // Once between this and the staff page: a staff cancel that already\n // told the buyer is not told again (AGL-4038).\n await sendPosHardwareEmailOnce('canceled', orderId, result.order)\n if (result.before.status === 'ordered') {\n await raisePosHardwareCanceledAfterOrderingAlert(orderId, result.order, reason)\n }\n return 'canceled'\n } catch (error) {\n console.error('[pos-hardware] closure cancel failed', orderId, error)\n await raisePosHardwareRefundFailedAlert(\n orderId,\n known ?? ({ orgId, hostId: '', status: 'paid', totalCents: 0, stripePaymentIntentId: null } as unknown as PosHardwareOrder),\n reason,\n error instanceof Error ? error.message : String(error),\n )\n return 'failed'\n }\n}\n\n/** What a closure did to one buyer's or workspace's hardware orders. */\nexport interface PosHardwareClosureCounts {\n hardwareOrdersCanceled: number\n /** Of those, the ones staff had already placed with Stripe. */\n hardwareOrdersPlacedWithStripe: number\n /** Unshipped orders whose refund Stripe refused; staff were alerted. */\n hardwareRefundsFailed: number\n}\n\n/**\n * Cancels every order given that is still unshipped. `orders` is read before\n * the call; each order is re-read under the lock by the cancel itself, so one\n * that shipped in between is left alone.\n */\nexport async function closeUnshippedPosHardwareOrders(\n orders: ReadonlyArray<{ orderId: string; order: PosHardwareOrder }>,\n reason: Exclude<PosHardwareCancelReason, 'staff'>,\n): Promise<PosHardwareClosureCounts> {\n const counts: PosHardwareClosureCounts = {\n hardwareOrdersCanceled: 0,\n hardwareOrdersPlacedWithStripe: 0,\n hardwareRefundsFailed: 0,\n }\n for (const { orderId, order } of orders) {\n if (!(UNSHIPPED as readonly string[]).includes(order?.status)) continue\n const outcome = await closeUnshippedPosHardwareOrder(order.orgId, orderId, reason, order)\n if (outcome === 'canceled') {\n counts.hardwareOrdersCanceled += 1\n if (order.status === 'ordered') counts.hardwareOrdersPlacedWithStripe += 1\n }\n if (outcome === 'failed') counts.hardwareRefundsFailed += 1\n }\n return counts\n}\n\nexport interface PosHardwareOrgEraserDeps {\n firestore(): Firestore\n}\n\n/**\n * COMMERCE'S SHARE OF A WORKSPACE ERASURE: the workspace's unshipped hardware\n * orders, canceled and refunded before the erasure deletes them with the\n * workspace. It runs first among the erasure's steps (plugin erasers run\n * while the workspace still stands), so the buyer's email can still name the\n * site and the workspace.\n *\n * A plan (`dryRun`) counts what it would cancel and touches neither Stripe\n * nor Firestore.\n */\nexport function createPosHardwareOrgEraser(deps: PosHardwareOrgEraserDeps): PluginOrgEraser {\n return async ({ orgId, dryRun }): Promise<PluginOrgErasureReport> => {\n const orders = deps.firestore().collection('orgs').doc(orgId).collection(POS_HARDWARE_ORDERS_COLLECTION)\n // One equality query per status, each served by the automatic\n // single-field index: a workspace's hardware orders are few.\n const found = await Promise.all(UNSHIPPED.map((status) => orders.where('status', '==', status).get()))\n const unshipped = found.flatMap((snapshot) =>\n snapshot.docs.map((doc) => ({\n orderId: doc.id,\n // The path names the workspace; the field is what the order says.\n order: { ...(doc.data() as PosHardwareOrder), orgId },\n })),\n )\n if (dryRun) {\n return {\n hardwareOrdersCanceled: unshipped.length,\n hardwareOrdersPlacedWithStripe: unshipped.filter(({ order }) => order.status === 'ordered').length,\n hardwareRefundsFailed: 0,\n }\n }\n return { ...(await closeUnshippedPosHardwareOrders(unshipped, 'workspace-closed')) }\n }\n}\n\n/** The eraser over the platform's own Firestore, as the declarations register it. */\nexport const posHardwareOrgEraser: PluginOrgEraser = (request) =>\n createPosHardwareOrgEraser({ firestore: () => firebaseAdmin.app().firestore() })(request)\n"],"names":["firebaseAdmin","addAdminAudit","POS_HARDWARE_ORDERS_COLLECTION","cancelAndRefundPosHardwareOrder","raisePosHardwareCanceledAfterOrderingAlert","raisePosHardwareRefundFailedAlert","sendPosHardwareEmailOnce","UNSHIPPED","CLOSURE_ACTOR","closeUnshippedPosHardwareOrder","orgId","orderId","reason","known","result","finalStatus","outcome","order","message","firestore","app","action","actorUid","actorEmail","scope","target","before","status","after","refundId","refundedCents","at","FieldValue","serverTimestamp","catch","error","console","hostId","totalCents","stripePaymentIntentId","Error","String","closeUnshippedPosHardwareOrders","orders","counts","hardwareOrdersCanceled","hardwareOrdersPlacedWithStripe","hardwareRefundsFailed","includes","createPosHardwareOrgEraser","deps","dryRun","collection","doc","found","Promise","all","map","where","get","unshipped","flatMap","snapshot","docs","id","data","length","filter","posHardwareOrgEraser","request"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAMD,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SAASC,aAAa,QAAQ,oDAAmD;AACjF,SACEC,8BAA8B,QAGzB,2BAAuB;AAC9B,SAASC,+BAA+B,QAAQ,2BAAuB;AACvE,SACEC,0CAA0C,EAC1CC,iCAAiC,EACjCC,wBAAwB,QACnB,2BAAuB;AAmC9B,8CAA8C,GAC9C,MAAMC,YAAY;IAAC;IAAQ;CAAU;AAErC,wDAAwD,GACxD,MAAMC,gBAA2E;IAC/E,oBAAoB;IACpB,kBAAkB;AACpB;AAEA;;;;CAIC,GACD,OAAO,eAAeC,+BACpBC,KAAa,EACbC,OAAe,EACfC,MAAiD,EACjDC,KAAwB;IAExB,IAAI;YA4BYC,wBACKA;QA5BnB,MAAMA,SAAS,MAAMX,gCAAgC;YAAEO;YAAOC;YAASI,aAAa;YAAYH;QAAO;QACvG,OAAQE,OAAOE,OAAO;YACpB,KAAK;YACL,KAAK;gBACH,OAAO;YACT,KAAK;gBACH,qEAAqE;gBACrE,+BAA+B;gBAC/B,OAAO;YACT,KAAK;gBACH,MAAMX,kCAAkCM,SAASG,O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CAAgCc,UAAUO,MAAM,CAAC,CAAC,EAAElD,KAAK,EAAE,GAAKA,MAAMU,MAAM,KAAK,WAAWuC,MAAM;gBAClGnB,uBAAuB;YACzB;QACF;QACA,OAAO,aAAM,MAAML,gCAAgCkB,WAAW;IAChE;AACF;AAEA,mFAAmF,GACnF,OAAO,MAAMQ,uBAAwC,CAACC,UACpDpB,2BAA2B;QAAE9B,WAAW,IAAMnB,cAAcoB,GAAG,GAAGD,SAAS;IAAG,GAAGkD,SAAQ"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-closure.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 {\n PluginOrgEraser,\n PluginOrgErasureReport,\n} from '@aglyn/aglyn/plugin-manager/plugin-org-erasure'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { addAdminAudit } from '@aglyn/tenant-data-admin/server/admin-audit-write'\nimport {\n POS_HARDWARE_ORDERS_COLLECTION,\n POS_HARDWARE_UNSHIPPED_STATUSES,\n type PosHardwareCancelReason,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\nimport { cancelAndRefundPosHardwareOrder } from './pos-hardware-cancel'\nimport {\n raisePosHardwareCanceledAfterOrderingAlert,\n raisePosHardwareRefundFailedAlert,\n sendPosHardwareEmailOnce,\n} from './pos-hardware-notify'\n\n/*==========================================\n * A CLOSURE CANCELS EVERY UNSHIPPED HARDWARE ORDER (AGL-4038).\n *\n * When the workspace that bought hardware is deleted, or the account that\n * placed an order is closed, every order of theirs that has not shipped —\n * `paid` or `ordered` — is canceled and refunded in full on the platform's\n * Stripe account, through the staff page's own path and its idempotency\n * (`pos-hardware-cancel.ts`). Then:\n *\n * - the buyer gets the \"canceled and refunded\" email, once: the same claim\n * the staff page sends it under (`sendPosHardwareEmailOnce`);\n * - staff get an alert when the order was already placed with Stripe\n * (`ordered`), because Stripe will still ship it unless someone cancels\n * it there, and another when Stripe refuses the refund;\n * - an `adminAudit` row records the cancel, with the closure as its actor.\n *\n * THE CLOSURE NEVER WAITS ON THIS. A refusal, or a throw, is counted and\n * alerted and the next order is tried; nothing here fails the erasure, so\n * the workspace or the account closes right away whatever Stripe says.\n * Shipped, delivered and registered orders are untouched, and the retained\n * sale record (`posHardwareSales`) records the refund and outlives both.\n *\n * Idempotent: a canceled order is no longer `paid` or `ordered`, so a second\n * closure run finds nothing to refund, sends no second email, raises no\n * second alert and makes no second Stripe call. A run that died after Stripe\n * refunded and before the order said so reads that refund back instead of\n * making another (`pos-hardware-cancel.ts`).\n *=========================================*/\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport type PosHardwareClosureOutcome = 'canceled' | 'already' | 'skipped' | 'failed'\n\n/** The unshipped statuses a closure cancels: paid, ordered, or received and being set up. */\nconst UNSHIPPED = POS_HARDWARE_UNSHIPPED_STATUSES\n\n/** The audit row's actor: the closure, never a person. */\nconst CLOSURE_ACTOR: Record<Exclude<PosHardwareCancelReason, 'staff'>, string> = {\n 'workspace-closed': 'system:workspace-closed',\n 'account-closed': 'system:account-closed',\n}\n\n/**\n * Cancels and refunds one unshipped order because of a closure, and tells\n * the buyer and staff. Never throws. `known` is the order as the closure read\n * it, for the alert should the cancel itself throw.\n */\nexport async function closeUnshippedPosHardwareOrder(\n orgId: string,\n orderId: string,\n reason: Exclude<PosHardwareCancelReason, 'staff'>,\n known?: PosHardwareOrder,\n): Promise<PosHardwareClosureOutcome> {\n try {\n const result = await cancelAndRefundPosHardwareOrder({ orgId, orderId, finalStatus: 'canceled', reason })\n switch (result.outcome) {\n case 'missing':\n case 'not-refundable':\n return 'skipped'\n case 'already':\n // Canceled between the closure's read and the lock: whoever canceled\n // it told the buyer and staff.\n return 'already'\n case 'no-payment':\n await raisePosHardwareRefundFailedAlert(orderId, result.order, reason, 'the order has no payment to refund')\n return 'failed'\n case 'refused':\n await raisePosHardwareRefundFailedAlert(orderId, result.order, reason, result.message)\n return 'failed'\n }\n const firestore = firebaseAdmin.app().firestore()\n await addAdminAudit(firestore, {\n action: 'pos-hardware-order-cancel',\n actorUid: CLOSURE_ACTOR[reason],\n actorEmail: null,\n scope: 'posHardwareOrder',\n target: `orgs/${orgId}/${POS_HARDWARE_ORDERS_COLLECTION}/${orderId}`,\n orgId,\n before: { status: result.before.status },\n after: {\n status: result.order.status,\n refundId: result.order.refundId ?? null,\n refundedCents: result.order.refundedCents ?? null,\n reason,\n },\n at: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n }).catch((error: unknown) => console.error('[pos-hardware] closure audit failed', orderId, error))\n // Once between this and the staff page: a staff cancel that already\n // told the buyer is not told again (AGL-4038).\n await sendPosHardwareEmailOnce('canceled', orderId, result.order)\n if (result.before.status === 'ordered' || result.before.status === 'received') {\n await raisePosHardwareCanceledAfterOrderingAlert(orderId, result.order, reason)\n }\n return 'canceled'\n } catch (error) {\n console.error('[pos-hardware] closure cancel failed', orderId, error)\n await raisePosHardwareRefundFailedAlert(\n orderId,\n known ?? ({ orgId, hostId: '', status: 'paid', totalCents: 0, stripePaymentIntentId: null } as unknown as PosHardwareOrder),\n reason,\n error instanceof Error ? error.message : String(error),\n )\n return 'failed'\n }\n}\n\n/** What a closure did to one buyer's or workspace's hardware orders. */\nexport interface PosHardwareClosureCounts {\n hardwareOrdersCanceled: number\n /** Of those, the ones staff had already placed with Stripe. */\n hardwareOrdersPlacedWithStripe: number\n /** Unshipped orders whose refund Stripe refused; staff were alerted. */\n hardwareRefundsFailed: number\n}\n\n/**\n * Cancels every order given that is still unshipped. `orders` is read before\n * the call; each order is re-read under the lock by the cancel itself, so one\n * that shipped in between is left alone.\n */\nexport async function closeUnshippedPosHardwareOrders(\n orders: ReadonlyArray<{ orderId: string; order: PosHardwareOrder }>,\n reason: Exclude<PosHardwareCancelReason, 'staff'>,\n): Promise<PosHardwareClosureCounts> {\n const counts: PosHardwareClosureCounts = {\n hardwareOrdersCanceled: 0,\n hardwareOrdersPlacedWithStripe: 0,\n hardwareRefundsFailed: 0,\n }\n for (const { orderId, order } of orders) {\n if (!(UNSHIPPED as readonly string[]).includes(order?.status)) continue\n const outcome = await closeUnshippedPosHardwareOrder(order.orgId, orderId, reason, order)\n if (outcome === 'canceled') {\n counts.hardwareOrdersCanceled += 1\n if (order.status === 'ordered' || order.status === 'received') counts.hardwareOrdersPlacedWithStripe += 1\n }\n if (outcome === 'failed') counts.hardwareRefundsFailed += 1\n }\n return counts\n}\n\nexport interface PosHardwareOrgEraserDeps {\n firestore(): Firestore\n}\n\n/**\n * COMMERCE'S SHARE OF A WORKSPACE ERASURE: the workspace's unshipped hardware\n * orders, canceled and refunded before the erasure deletes them with the\n * workspace. It runs first among the erasure's steps (plugin erasers run\n * while the workspace still stands), so the buyer's email can still name the\n * site and the workspace.\n *\n * A plan (`dryRun`) counts what it would cancel and touches neither Stripe\n * nor Firestore.\n */\nexport function createPosHardwareOrgEraser(deps: PosHardwareOrgEraserDeps): PluginOrgEraser {\n return async ({ orgId, dryRun }): Promise<PluginOrgErasureReport> => {\n const orders = deps.firestore().collection('orgs').doc(orgId).collection(POS_HARDWARE_ORDERS_COLLECTION)\n // One equality query per status, each served by the automatic\n // single-field index: a workspace's hardware orders are few.\n const found = await Promise.all(UNSHIPPED.map((status) => orders.where('status', '==', status).get()))\n const unshipped = found.flatMap((snapshot) =>\n snapshot.docs.map((doc) => ({\n orderId: doc.id,\n // The path names the workspace; the field is what the order says.\n order: { ...(doc.data() as PosHardwareOrder), orgId },\n })),\n )\n if (dryRun) {\n return {\n hardwareOrdersCanceled: unshipped.length,\n hardwareOrdersPlacedWithStripe: unshipped.filter(({ order }) => order.status === 'ordered' || order.status === 'received').length,\n hardwareRefundsFailed: 0,\n }\n }\n return { ...(await closeUnshippedPosHardwareOrders(unshipped, 'workspace-closed')) }\n }\n}\n\n/** The eraser over the platform's own Firestore, as the declarations register it. */\nexport const posHardwareOrgEraser: PluginOrgEraser = (request) =>\n createPosHardwareOrgEraser({ firestore: () => firebaseAdmin.app().firestore() })(request)\n"],"names":["firebaseAdmin","addAdminAudit","POS_HARDWARE_ORDERS_COLLECTION","POS_HARDWARE_UNSHIPPED_STATUSES","cancelAndRefundPosHardwareOrder","raisePosHardwareCanceledAfterOrderingAlert","raisePosHardwareRefundFailedAlert","sendPosHardwareEmailOnce","UNSHIPPED","CLOSURE_ACTOR","closeUnshippedPosHardwareOrder","orgId","orderId","reason","known","result","finalStatus","outcome","order","message","firestore","app","action","actorUid","actorEmail","scope","target","before","status","after","refundId","refundedCents","at","FieldValue","serverTimestamp","catch","error","console","hostId","totalCents","stripePaymentIntentId","Error","String","closeUnshippedPosHardwareOrders","orders","counts","hardwareOrdersCanceled","hardwareOrdersPlacedWithStripe","hardwareRefundsFailed","includes","createPosHardwareOrgEraser","deps","dryRun","collection","doc","found","Promise","all","map","where","get","unshipped","flatMap","snapshot","docs","id","data","length","filter","posHardwareOrgEraser","request"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAMD,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SAASC,aAAa,QAAQ,oDAAmD;AACjF,SACEC,8BAA8B,EAC9BC,+BAA+B,QAG1B,2BAAuB;AAC9B,SAASC,+BAA+B,QAAQ,2BAAuB;AACvE,SACEC,0CAA0C,EAC1CC,iCAAiC,EACjCC,wBAAwB,QACnB,2BAAuB;AAmC9B,2FAA2F,GAC3F,MAAMC,YAAYL;AAElB,wDAAwD,GACxD,MAAMM,gBAA2E;IAC/E,oBAAoB;IACpB,kBAAkB;AACpB;AAEA;;;;CAIC,GACD,OAAO,eAAeC,+BACpBC,KAAa,EACbC,OAAe,EAC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AC,CAAC9B,SAAWgB,OAAOe,KAAK,CAAC,UAAU,MAAM/B,QAAQgC,GAAG;QAClG,MAAMC,YAAYN,MAAMO,OAAO,CAAC,CAACC,WAC/BA,SAASC,IAAI,CAACN,GAAG,CAAC,CAACJ,MAAS,CAAA;oBAC1B1C,SAAS0C,IAAIW,EAAE;oBACf,kEAAkE;oBAClE/C,OAAO,aAAMoC,IAAIY,IAAI;wBAAyBvD;;gBAChD,CAAA;QAEF,IAAIyC,QAAQ;YACV,OAAO;gBACLN,wBAAwBe,UAAUM,MAAM;gBACxCpB,gCAAgCc,UAAUO,MAAM,CAAC,CAAC,EAAElD,KAAK,EAAE,GAAKA,MAAMU,MAAM,KAAK,aAAaV,MAAMU,MAAM,KAAK,YAAYuC,MAAM;gBACjInB,uBAAuB;YACzB;QACF;QACA,OAAO,aAAM,MAAML,gCAAgCkB,WAAW;IAChE;AACF;AAEA,mFAAmF,GACnF,OAAO,MAAMQ,uBAAwC,CAACC,UACpDpB,2BAA2B;QAAE9B,WAAW,IAAMpB,cAAcqB,GAAG,GAAGD,SAAS;IAAG,GAAGkD,SAAQ"}
@@ -26,7 +26,8 @@ export type InPersonRecordOutcome = {
26
26
  /** How many marked sales one sweep records at most. */
27
27
  export declare const IN_PERSON_SWEEP_LIMIT = 25;
28
28
  /**
29
- * Records the hardware order of one register sale on the seller store, once.
29
+ * Records the hardware order of one sale on the seller store, at its
30
+ * register or online (AGL-4038), once.
30
31
  * Never throws for a sale that is not one: it says why it did nothing.
31
32
  */
32
33
  export declare function recordInPersonPosHardwareSale(hostId: string, registerOrderId: string, options?: {