@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
@@ -19,7 +19,7 @@ import { firebaseAdmin, raiseOperatorAlert } from "@aglyn/tenant-data-admin";
19
19
  import * as CommerceModel from "../model/index.js";
20
20
  import { posOrderRefundRecord, POS_ORDER_REFUNDS_COLLECTION } from "../model/commerce-pos-day-report.js";
21
21
  import { POS_STRIPE_TENDERS } from "../model/commerce-pos-ops.js";
22
- import { formatPosHardwareCents, isPosHardwareSkuId, POS_HARDWARE_ORDER_ID, POS_HARDWARE_RETURN_REASON_MAX, posHardwareSaleRecord, posHardwareSaleSetOptions } from "../model/pos-hardware.js";
22
+ import { formatPosHardwareCents, isPosHardwareSellerStoreSale, isPosHardwareSkuId, POS_HARDWARE_ORDER_ID, POS_HARDWARE_RETURN_REASON_MAX, posHardwareSaleRecord, posHardwareSaleSetOptions } from "../model/pos-hardware.js";
23
23
  import { COMMERCE_POS_HARDWARE_RETURN_REQUESTED } from "../constants/operator-alerts.js";
24
24
  import { hardwareOrdersRef, posHardwareOrderNumber, posHardwareSaleRef } from "./pos-hardware.js";
25
25
  import { posStripe } from "./pos-stripe.js";
@@ -161,9 +161,13 @@ const units = (order)=>{
161
161
  }
162
162
  }
163
163
  /**
164
- * Refunds what is left of an in-person order from the staff page (way 2),
165
- * through the register sale's own card refund. Refused for a sale paid by
166
- * anything Stripe cannot refund, which goes back at the register instead.
164
+ * Refunds what is left of an order sold by the platform's own store from the
165
+ * staff page (way 2), through the store order's own card refund: an
166
+ * in-person sale's register sale, or an online order's Checkout payment
167
+ * (AGL-4038), both destination charges into the store's account. Refused
168
+ * for a sale paid by anything Stripe cannot refund, which goes back at the
169
+ * register instead. `amountCents` refunds less than what is left: a return
170
+ * of an online order keeps the original shipping and any restocking fee.
167
171
  */ export async function refundInPersonPosHardwareOrder(input) {
168
172
  var _before_totalCents, _before_refundedCents, _ref, _ref1, _before_refunds, _input_now, _before_refunds1;
169
173
  var _before_posSale, _before_posSale1, _sale_totals;
@@ -173,14 +177,15 @@ const units = (order)=>{
173
177
  const snapshot = await ref.get();
174
178
  if (!snapshot.exists) throw new PosHardwareReturnRefusal('No such order', 404);
175
179
  const before = snapshot.data();
176
- if (before.source !== 'in_person' || ((_before_posSale = before.posSale) == null ? void 0 : _before_posSale.hostId) !== config.sellerHostId) {
177
- throw new PosHardwareReturnRefusal('Only a card reader sold in person here is refunded this way.', 409);
180
+ if (!isPosHardwareSellerStoreSale(before) || ((_before_posSale = before.posSale) == null ? void 0 : _before_posSale.hostId) !== config.sellerHostId) {
181
+ throw new PosHardwareReturnRefusal('Only a card reader sold by our own store is refunded this way.', 409);
178
182
  }
179
183
  if (before.status === 'refunded' || before.status === 'canceled') return {
180
184
  before,
181
185
  order: before
182
186
  };
183
- const cents = Math.max(0, ((_before_totalCents = before.totalCents) != null ? _before_totalCents : 0) - ((_before_refundedCents = before.refundedCents) != null ? _before_refundedCents : 0));
187
+ const left = Math.max(0, ((_before_totalCents = before.totalCents) != null ? _before_totalCents : 0) - ((_before_refundedCents = before.refundedCents) != null ? _before_refundedCents : 0));
188
+ const cents = input.amountCents === undefined ? left : Math.min(left, Math.max(0, Math.round(Number(input.amountCents) || 0)));
184
189
  if (!cents) throw new PosHardwareReturnRefusal('Nothing is left to refund on this order.', 409);
185
190
  const registerOrderId = String((_ref = (_before_posSale1 = before.posSale) == null ? void 0 : _before_posSale1.orderId) != null ? _ref : '');
186
191
  const registerRef = firestore().collection('hosts').doc(config.sellerHostId).collection('orders').doc(registerOrderId);
@@ -415,6 +420,33 @@ const units = (order)=>{
415
420
  if (!POS_HARDWARE_ORDER_ID.test(input.orderId)) throw new PosHardwareReturnRefusal('No such order', 404);
416
421
  const now = (_input_now = input.now) != null ? _input_now : Date.now;
417
422
  const ref = hardwareOrdersRef(input.orgId).doc(input.orderId);
423
+ // Bought from the platform's own online store (AGL-4038): the money is in
424
+ // that store's account, so it goes back through the store order's own
425
+ // refund, under the same return rule — the items and their tax, less the fee.
426
+ const current = (await ref.get()).data();
427
+ if (current && current.source === 'storefront') {
428
+ var _current_returnRequest;
429
+ if (((_current_returnRequest = current.returnRequest) == null ? void 0 : _current_returnRequest.state) !== 'requested') {
430
+ throw new PosHardwareReturnRefusal('There is no open return request on this order.', 409);
431
+ }
432
+ if (!POS_HARDWARE_ONLINE_RETURNABLE.includes(current.status)) {
433
+ throw new PosHardwareReturnRefusal('Only an order that has shipped is refunded as a return.', 409);
434
+ }
435
+ const cents = posHardwareReturnRefundableCents(current) - fee;
436
+ if (cents <= 0) throw new PosHardwareReturnRefusal('The restocking fee leaves nothing to refund.', 400);
437
+ const { posHardwareInPersonConfig } = await import("./pos-hardware.js");
438
+ const refunded = await refundInPersonPosHardwareOrder({
439
+ config: posHardwareInPersonConfig(),
440
+ orgId: input.orgId,
441
+ orderId: input.orderId,
442
+ actorUid: input.actorUid,
443
+ amountCents: cents,
444
+ now: now()
445
+ });
446
+ return _extends({}, refunded, {
447
+ cents
448
+ });
449
+ }
418
450
  const claimed = await firestore().runTransaction(async (transaction)=>{
419
451
  var _before_returnRequest;
420
452
  const snapshot = await transaction.get(ref);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-returns.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { formatOperatorAlertAmount } from '@aglyn/aglyn/app-utils/operator-alerts'\nimport { firebaseAdmin, raiseOperatorAlert } from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport { posOrderRefundRecord, POS_ORDER_REFUNDS_COLLECTION } from '../model/commerce-pos-day-report'\nimport { POS_STRIPE_TENDERS, type PosTenderSource } from '../model/commerce-pos-ops'\nimport {\n formatPosHardwareCents,\n isPosHardwareSkuId,\n POS_HARDWARE_ORDER_ID,\n POS_HARDWARE_RETURN_REASON_MAX,\n posHardwareSaleRecord,\n posHardwareSaleSetOptions,\n type PosHardwareInPersonConfig,\n type PosHardwareOrder,\n type PosHardwareRefund,\n} from '../model/pos-hardware'\nimport { COMMERCE_POS_HARDWARE_RETURN_REQUESTED } from '../constants/operator-alerts'\nimport { hardwareOrdersRef, posHardwareOrderNumber, posHardwareSaleRef } from './pos-hardware'\nimport { posStripe } from './pos-stripe'\nimport { createStripeRefund } from './stripe-refund'\nimport { posOrderRefundHardwareId } from './pos-order-refund-ids'\n\n/*==========================================\n * RETURNING A CARD READER SOLD IN PERSON (AGL-4038).\n *\n * Three ways, and all of them pay back from the SELLING store's takings,\n * the way the sale was paid — never from the platform's Checkout, which an\n * in-person sale never used:\n *\n * 1. At the selling store's register, at a later event: the register's own\n * return (`pos-return.ts`) refunds the sale's tenders as for anything\n * else, and the hardware's share of it is written here onto the\n * hardware order and its retained sale record.\n * 2. From the staff Hardware orders page: the card the sale was paid with\n * is refunded through the register sale's own Stripe refund (a\n * destination charge, so the money comes back out of the store's\n * connected account), recorded on the register sale as any refund is,\n * and on the hardware order. A sale paid in cash can only be refunded\n * at the register.\n * 3. Requested by the buyer from their own purchase history: staff are\n * alerted, and refund it (2) or decline it.\n *\n * Each refund is written once by its key, and the order says Refunded once\n * every hardware item on it has come back. Returns follow the hardware terms\n * of sale; nothing here decides them.\n *\n * AN ORDER SHIPPED TO THE BUYER (AGL-4038) is asked back the same way (3)\n * once it has shipped, and declined the same way. Staff refund it as a\n * return ({@link refundReturnedOnlinePosHardwareOrder}): the items and their\n * tax, less any restocking fee Stripe charged, on the platform's own\n * account, since the platform's Checkout took the payment.\n *=========================================*/\n\nexport class PosHardwareReturnRefusal extends Error {\n constructor(\n message: string,\n readonly status: number,\n ) {\n super(message)\n }\n}\n\nfunction firestore() {\n return firebaseAdmin.app().firestore()\n}\n\nconst units = (order: Pick<PosHardwareOrder, 'lines'>) =>\n (order.lines ?? []).reduce((sum, line) => sum + (Number(line.quantity) || 0), 0)\n\n/** The order with one more refund on it, or as it was when the key was already used. */\nexport function withPosHardwareRefund(order: PosHardwareOrder, refund: PosHardwareRefund): PosHardwareOrder {\n const refunds = order.refunds ?? []\n if (refunds.some((held) => held.key === refund.key)) return order\n const next = [...refunds, refund]\n const refundedCents = next.reduce((sum, held) => sum + held.cents, 0)\n const returned = next.reduce((sum, held) => sum + held.quantity, 0)\n const whole = refundedCents >= (order.totalCents ?? 0) || (returned > 0 && returned >= units(order))\n return {\n ...order,\n refunds: next,\n refundedCents,\n refundedAtMs: refund.atMs,\n refundId: refund.stripeRefundId ?? order.refundId ?? null,\n ...(whole ? { status: 'refunded' as const } : {}),\n ...(order.returnRequest && order.returnRequest.state === 'requested'\n ? { returnRequest: { ...order.returnRequest, state: 'refunded' as const, decidedAtMs: refund.atMs } }\n : {}),\n updatedAtMs: refund.atMs,\n }\n}\n\n/** Writes one refund onto a hardware order and its sale record, once. */\nasync function applyRefund(orderId: string, refund: PosHardwareRefund): Promise<PosHardwareOrder | null> {\n const saleRef = posHardwareSaleRef(orderId)\n return firestore().runTransaction(async (transaction: any) => {\n const sale = await transaction.get(saleRef)\n if (!sale.exists) return null\n const ref = hardwareOrdersRef(String(sale.get('orgId') ?? '')).doc(orderId)\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) return null\n const before = snapshot.data() as PosHardwareOrder\n const after = withPosHardwareRefund(before, refund)\n if (after === before) return before\n transaction.set(ref, after)\n transaction.set(saleRef, posHardwareSaleRecord(orderId, after), posHardwareSaleSetOptions(after))\n return after\n })\n}\n\n/**\n * A return at the selling store's register (way 1): the hardware's share of\n * what the return refunded, by the lines it took back. Never throws into the\n * return; the money has already gone back.\n */\nexport async function recordRegisterHardwareReturn(input: {\n config: PosHardwareInPersonConfig | null\n hostId: string\n registerOrderId: string\n returnId: string\n refundCents: number\n lines: ReadonlyArray<{ index: number; quantity: number; refundCents: number }>\n now?: number\n}): Promise<PosHardwareOrder | null> {\n const { config } = input\n if (!config || input.hostId !== config.sellerHostId || !input.lines.length) return null\n try {\n const hostRef = firestore().collection('hosts').doc(input.hostId)\n const register = await hostRef.collection('orders').doc(input.registerOrderId).get()\n const orderId = String(register.get('hardwareOrderId') ?? '')\n if (!POS_HARDWARE_ORDER_ID.test(orderId)) return null\n const lineItems = (register.get('lineItems') ?? []) as CommerceModel.OrderLineItem[]\n const productIds = [...new Set(input.lines.map((line) => String(lineItems[line.index]?.productId ?? '')))].filter(Boolean)\n const products = new Map(\n (await Promise.all(productIds.map((id) => hostRef.collection('products').doc(id).get()))).map((doc: any) => [\n String(doc.id),\n doc.get('hardwareSku'),\n ]),\n )\n const hardware = input.lines.filter((line) =>\n isPosHardwareSkuId(products.get(String(lineItems[line.index]?.productId ?? ''))),\n )\n if (!hardware.length) return null\n const linesCents = input.lines.reduce((sum, line) => sum + Math.max(0, Math.round(line.refundCents)), 0)\n const hardwareCents = hardware.reduce((sum, line) => sum + Math.max(0, Math.round(line.refundCents)), 0)\n // What actually went back, in the lines' own proportion: a card that\n // refused after another tender paid back leaves a part-return.\n const refunded = Math.max(0, Math.round(input.refundCents))\n const cents =\n linesCents > 0 && refunded < linesCents\n ? Math.floor((refunded * hardwareCents * 2 + linesCents) / (linesCents * 2))\n : hardwareCents\n return await applyRefund(orderId, {\n key: `register:${input.returnId}`,\n via: 'register',\n cents,\n quantity: hardware.reduce((sum, line) => sum + Math.max(0, Math.round(line.quantity)), 0),\n atMs: input.now ?? Date.now(),\n stripeRefundId: null,\n })\n } catch (error) {\n console.error('[pos-hardware-returns] a register return was not written to its hardware order', input.registerOrderId, error)\n return null\n }\n}\n\n/**\n * Refunds what is left of an in-person order from the staff page (way 2),\n * through the register sale's own card refund. Refused for a sale paid by\n * anything Stripe cannot refund, which goes back at the register instead.\n */\nexport async function refundInPersonPosHardwareOrder(input: {\n config: PosHardwareInPersonConfig | null\n orgId: string\n orderId: string\n actorUid: string\n now?: number\n}): Promise<{ before: PosHardwareOrder; order: PosHardwareOrder }> {\n const { config } = input\n if (!config) throw new PosHardwareReturnRefusal('Card reader sales in person are off.', 409)\n const ref = hardwareOrdersRef(input.orgId).doc(input.orderId)\n const snapshot = await ref.get()\n if (!snapshot.exists) throw new PosHardwareReturnRefusal('No such order', 404)\n const before = snapshot.data() as PosHardwareOrder\n if (before.source !== 'in_person' || before.posSale?.hostId !== config.sellerHostId) {\n throw new PosHardwareReturnRefusal('Only a card reader sold in person here is refunded this way.', 409)\n }\n if (before.status === 'refunded' || before.status === 'canceled') return { before, order: before }\n const cents = Math.max(0, (before.totalCents ?? 0) - (before.refundedCents ?? 0))\n if (!cents) throw new PosHardwareReturnRefusal('Nothing is left to refund on this order.', 409)\n const registerOrderId = String(before.posSale?.orderId ?? '')\n const registerRef = firestore().collection('hosts').doc(config.sellerHostId).collection('orders').doc(registerOrderId)\n const register = await registerRef.get()\n if (!register.exists) throw new PosHardwareReturnRefusal('The register sale is missing.', 404)\n const sale = register.data() as PosTenderSource & CommerceModel.HostOrder & { refundedCents?: number }\n const card = CommerceModel.orderPayments(sale as never)\n .filter((payment) => payment.status === 'succeeded' && POS_STRIPE_TENDERS.has(payment.method) && payment.paymentIntentId)\n .find((payment) => payment.amountCents >= cents)\n if (!card?.paymentIntentId) {\n throw new PosHardwareReturnRefusal(\n 'This card reader was not paid by one card that can take this refund. Refund it as a return at the selling store’s register instead.',\n 409,\n )\n }\n const totalCents = Number(sale.totals?.totalCents ?? 0)\n // Reserve on the register sale first, as its own refunds do, so a refund\n // there and one here cannot both take the same money.\n const reserved = await firestore().runTransaction(async (transaction: any) => {\n const fresh = (await transaction.get(registerRef)).data() ?? {}\n const already = Number(fresh['refundedCents'] ?? 0)\n if (already + cents > totalCents) return false\n transaction.set(registerRef, { refundedCents: already + cents }, { merge: true })\n return true\n })\n if (!reserved) {\n throw new PosHardwareReturnRefusal('The register sale was already refunded. Check it on the store’s orders.', 409)\n }\n const attempt = (before.refunds ?? []).filter((held) => held.via === 'staff').length + 1\n const refund = await createStripeRefund({\n paymentIntentId: card.paymentIntentId,\n amountCents: cents,\n idempotencyKey: `pos-hw-refund-${input.orderId}-${attempt}`,\n metadata: {\n hostId: config.sellerHostId,\n orderId: registerOrderId,\n hardwareOrderId: input.orderId,\n kind: 'pos-hardware-refund',\n },\n })\n if ('error' in refund) {\n // Stripe said no, so no money moved: the reservation goes back.\n await firestore()\n .runTransaction(async (transaction: any) => {\n const current = Number((await transaction.get(registerRef)).get('refundedCents') ?? 0)\n transaction.set(registerRef, { refundedCents: Math.max(0, current - cents) }, { merge: true })\n })\n .catch(() => undefined)\n throw new PosHardwareReturnRefusal(refund.error, refund.status === 409 ? 409 : 502)\n }\n const now = input.now ?? Date.now()\n const registerRefund = posOrderRefundRecord({\n orderId: registerOrderId,\n order: sale as PosTenderSource & { registerId?: unknown },\n refundedCents: cents,\n paymentIntentId: card.paymentIntentId,\n cashierId: null,\n source: 'staff',\n stripeRefundId: refund.refundId || null,\n atMs: now,\n })\n await firestore().runTransaction(async (transaction: any) => {\n const fresh = (await transaction.get(registerRef)).data() ?? {}\n const refundedCents = Number(fresh['refundedCents'] ?? 0)\n transaction.set(\n registerRef,\n {\n ...(refundedCents >= totalCents ? { status: 'refunded' } : {}),\n updatedAtMs: now,\n timeline: firebaseAdmin.firestore.FieldValue.arrayUnion({\n atMs: now,\n event: 'refund',\n detail: `Card reader refunded from the staff hardware page: ${formatPosHardwareCents(cents)}`,\n }),\n },\n { merge: true },\n )\n if (registerRefund) {\n transaction.set(\n firestore()\n .collection('hosts')\n .doc(config.sellerHostId)\n .collection('registers')\n .doc(registerRefund.registerId)\n .collection(POS_ORDER_REFUNDS_COLLECTION)\n .doc(refund.refundId || posOrderRefundHardwareId(registerOrderId, attempt)),\n registerRefund,\n )\n }\n })\n const order = await applyRefund(input.orderId, {\n key: `staff:${attempt}`,\n via: 'staff',\n cents,\n quantity: Math.max(0, units(before) - (before.refunds ?? []).reduce((sum, held) => sum + held.quantity, 0)),\n atMs: now,\n stripeRefundId: refund.refundId || null,\n })\n return { before, order: order ?? before }\n}\n\n/**\n * The statuses an online order may be asked back in (AGL-4038): once it has\n * shipped. Before that, changing or canceling it is for support, who cancel\n * and refund it in full from the staff page.\n */\nexport const POS_HARDWARE_ONLINE_RETURNABLE: readonly PosHardwareOrder['status'][] = ['shipped', 'delivered', 'registered']\n\n/**\n * The buyer asks to return an order (way 3), from their own purchase\n * history: once while a request is open, with a reason. Staff are alerted.\n * An in-person order any time before it is refunded; an online one once it\n * has shipped (AGL-4038), which staff refund as a return\n * ({@link refundReturnedOnlinePosHardwareOrder}) or decline. Never for an\n * order already refunded.\n */\nexport async function requestPosHardwareReturn(input: {\n orgId: string\n orderId: string\n uid: string\n reason: unknown\n now?: number\n}): Promise<PosHardwareOrder> {\n const reason = String(input.reason ?? '').trim().slice(0, POS_HARDWARE_RETURN_REASON_MAX)\n if (reason.length < 3) throw new PosHardwareReturnRefusal('Say why you are returning it.', 400)\n if (!POS_HARDWARE_ORDER_ID.test(input.orderId)) throw new PosHardwareReturnRefusal('No such order.', 404)\n const ref = hardwareOrdersRef(input.orgId).doc(input.orderId)\n const now = input.now ?? Date.now()\n const outcome = await firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new PosHardwareReturnRefusal('No such order.', 404)\n const before = snapshot.data() as PosHardwareOrder\n if (before.status === 'refunded' || before.status === 'canceled') {\n throw new PosHardwareReturnRefusal('This order was already refunded.', 409)\n }\n if (before.source !== 'in_person' && !POS_HARDWARE_ONLINE_RETURNABLE.includes(before.status)) {\n throw new PosHardwareReturnRefusal(\n 'This order has not shipped yet. To change or cancel it, contact support.',\n 409,\n )\n }\n if (before.returnRequest?.state === 'requested') return { order: before, created: false }\n const after: PosHardwareOrder = {\n ...before,\n returnRequest: {\n state: 'requested',\n reason,\n requestedBy: input.uid,\n requestedAtMs: now,\n decidedBy: null,\n decidedAtMs: null,\n note: null,\n },\n updatedAtMs: now,\n }\n transaction.set(ref, after)\n return { order: after, created: true }\n })\n if (outcome.created) {\n try {\n await raiseOperatorAlert(COMMERCE_POS_HARDWARE_RETURN_REQUESTED, {\n dedupeKey: `${input.orderId}:${now}`,\n orgId: input.orgId,\n hostId: outcome.order.hostId || outcome.order.posSale?.hostId || '',\n context: {\n orderNumber: posHardwareOrderNumber(input.orderId),\n amount: formatOperatorAlertAmount(outcome.order.totalCents ?? 0),\n orgId: input.orgId,\n items: (outcome.order.lines ?? []).map((line) => `${line.quantity} × ${line.name}`).join(', '),\n reason,\n },\n })\n } catch (error) {\n console.error('[pos-hardware-returns] return request alert failed', input.orderId, error)\n }\n }\n return outcome.order\n}\n\n/** Staff decline an open return request, with a note for the buyer. */\nexport async function declinePosHardwareReturn(input: {\n orgId: string\n orderId: string\n actorUid: string\n note: unknown\n now?: number\n}): Promise<{ before: PosHardwareOrder; order: PosHardwareOrder }> {\n const note = String(input.note ?? '').trim().slice(0, POS_HARDWARE_RETURN_REASON_MAX) || null\n const ref = hardwareOrdersRef(input.orgId).doc(input.orderId)\n const now = input.now ?? Date.now()\n return firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new PosHardwareReturnRefusal('No such order', 404)\n const before = snapshot.data() as PosHardwareOrder\n if (before.returnRequest?.state !== 'requested') {\n throw new PosHardwareReturnRefusal('There is no open return request on this order.', 409)\n }\n const order: PosHardwareOrder = {\n ...before,\n returnRequest: { ...before.returnRequest, state: 'declined', decidedBy: input.actorUid, decidedAtMs: now, note },\n updatedAtMs: now,\n }\n transaction.set(ref, order)\n return { before, order }\n })\n}\n\n/** The idempotency key of an online return's refund: the order and the amount. */\nexport function posHardwareReturnRefundKey(orderId: string, cents: number): string {\n return `pos-hw-return-${orderId}-${cents}`\n}\n\n/** What an online return gives back: the items and their tax, never the original shipping. */\nexport function posHardwareReturnRefundableCents(order: Pick<PosHardwareOrder, 'totalCents' | 'shipping'>): number {\n return Math.max(0, (order.totalCents ?? 0) - (order.shipping?.cents ?? 0))\n}\n\n/**\n * Staff refund an ONLINE order the buyer sent back (AGL-4038), from the\n * staff Hardware orders page, once its return was requested: the price of\n * the items and the tax on them, less any restocking fee Stripe charged for\n * the return, to the card it was paid with on the platform's own account.\n * The original shipping is not refunded, under the hardware terms of sale.\n *\n * Claimed first, as a cancel is (`refundRequestedAtMs`), so two presses make\n * one refund; the Stripe key names the order and the amount, so a retry of\n * the same refund is the same refund. The order says Refunded, its return\n * request Refunded, and the refund is written once by its key, with the\n * sale record in the same transaction.\n */\nexport async function refundReturnedOnlinePosHardwareOrder(input: {\n orgId: string\n orderId: string\n actorUid: string\n restockingFeeCents: unknown\n now?: () => number\n}): Promise<{ before: PosHardwareOrder; order: PosHardwareOrder; cents: number }> {\n const fee = input.restockingFeeCents === undefined || input.restockingFeeCents === null || input.restockingFeeCents === '' ? 0 : Number(input.restockingFeeCents)\n if (!Number.isSafeInteger(fee) || fee < 0) {\n throw new PosHardwareReturnRefusal('Enter the restocking fee in whole cents, or 0.', 400)\n }\n if (!POS_HARDWARE_ORDER_ID.test(input.orderId)) throw new PosHardwareReturnRefusal('No such order', 404)\n const now = input.now ?? Date.now\n const ref = hardwareOrdersRef(input.orgId).doc(input.orderId)\n const claimed = await firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new PosHardwareReturnRefusal('No such order', 404)\n const before = snapshot.data() as PosHardwareOrder & { refundRequestedAtMs?: number }\n if (before.source === 'in_person') {\n throw new PosHardwareReturnRefusal('A reader sold in person is refunded with Refund.', 409)\n }\n if (before.returnRequest?.state !== 'requested') {\n throw new PosHardwareReturnRefusal('There is no open return request on this order.', 409)\n }\n if (!POS_HARDWARE_ONLINE_RETURNABLE.includes(before.status)) {\n throw new PosHardwareReturnRefusal('Only an order that has shipped is refunded as a return.', 409)\n }\n if (!before.stripePaymentIntentId) throw new PosHardwareReturnRefusal('This order has no payment to refund.', 409)\n if (before.refundRequestedAtMs && now() - before.refundRequestedAtMs < 2 * 60 * 1000) {\n throw new PosHardwareReturnRefusal('A refund of this order is already in progress.', 409)\n }\n const cents = posHardwareReturnRefundableCents(before) - fee\n if (cents <= 0) throw new PosHardwareReturnRefusal('The restocking fee leaves nothing to refund.', 400)\n transaction.update(ref, { refundRequestedAtMs: now() })\n return { before: before as PosHardwareOrder, cents }\n })\n const { before, cents } = claimed\n const asked = await posStripe('POST', 'refunds', {\n params: {\n payment_intent: before.stripePaymentIntentId,\n amount: cents,\n 'metadata[type]': 'pos-hardware-return',\n 'metadata[orderId]': input.orderId,\n 'metadata[orgId]': input.orgId,\n },\n idempotencyKey: posHardwareReturnRefundKey(input.orderId, cents),\n })\n if (!asked.ok || !asked.body?.id) {\n await ref.update({ refundRequestedAtMs: firebaseAdmin.firestore.FieldValue.delete() }).catch(() => undefined)\n throw new PosHardwareReturnRefusal(\n String(asked.body?.error?.message ?? '') || 'Stripe refused the refund.',\n asked.status === 400 ? 409 : 502,\n )\n }\n const at = now()\n const stripeRefundId = String(asked.body.id)\n const saleRef = posHardwareSaleRef(input.orderId)\n const order = await firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n const current = snapshot.data() as PosHardwareOrder & { refundRequestedAtMs?: number }\n const settled: PosHardwareOrder = { ...current }\n delete (settled as { refundRequestedAtMs?: number }).refundRequestedAtMs\n const refunded = withPosHardwareRefund(settled, {\n key: `return:${stripeRefundId}`,\n via: 'staff',\n cents,\n quantity: units(settled),\n atMs: at,\n stripeRefundId,\n })\n const after: PosHardwareOrder = {\n ...refunded,\n // Every item came back: the order is Refunded, whatever was kept.\n status: 'refunded',\n refundedAtMs: at,\n returnRequest: refunded.returnRequest\n ? { ...refunded.returnRequest, state: 'refunded', decidedBy: input.actorUid, decidedAtMs: at }\n : refunded.returnRequest,\n }\n transaction.set(ref, after)\n transaction.set(saleRef, posHardwareSaleRecord(input.orderId, after), posHardwareSaleSetOptions(after))\n return after\n })\n return { before, order, cents }\n}\n\n"],"names":["formatOperatorAlertAmount","firebaseAdmin","raiseOperatorAlert","CommerceModel","posOrderRefundRecord","POS_ORDER_REFUNDS_COLLECTION","POS_STRIPE_TENDERS","formatPosHardwareCents","isPosHardwareSkuId","POS_HARDWARE_ORDER_ID","POS_HARDWARE_RETURN_REASON_MAX","posHardwareSaleRecord","posHardwareSaleSetOptions","COMMERCE_POS_HARDWARE_RETURN_REQUESTED","hardwareOrdersRef","posHardwareOrderNumber","posHardwareSaleRef","posStripe","createStripeRefund","posOrderRefundHardwareId","PosHardwareReturnRefusal","Error","message","status","firestore","app","units","order","lines","reduce","sum","line","Number","quantity","withPosHardwareRefund","refund","refunds","some","held","key","next","refundedCents","cents","returned","whole","totalCents","refundedAtMs","atMs","refundId","stripeRefundId","returnRequest","state","decidedAtMs","updatedAtMs","applyRefund","orderId","saleRef","runTransaction","transaction","sale","get","exists","ref","String","doc","snapshot","before","data","after","set","recordRegisterHardwareReturn","input","config","hostId","sellerHostId","length","register","hostRef","collection","registerOrderId","test","lineItems","productIds","Set","map","index","productId","filter","Boolean","products","Map","Promise","all","id","hardware","linesCents","Math","max","round","refundCents","hardwareCents","refunded","floor","returnId","via","now","Date","error","console","refundInPersonPosHardwareOrder","orgId","source","posSale","registerRef","card","orderPayments","payment","has","method","paymentIntentId","find","amountCents","totals","reserved","fresh","already","merge","attempt","idempotencyKey","metadata","hardwareOrderId","kind","current","catch","undefined","registerRefund","cashierId","timeline","FieldValue","arrayUnion","event","detail","registerId","POS_HARDWARE_ONLINE_RETURNABLE","requestPosHardwareReturn","reason","trim","slice","outcome","includes","created","requestedBy","uid","requestedAtMs","decidedBy","note","dedupeKey","context","orderNumber","amount","items","name","join","declinePosHardwareReturn","actorUid","posHardwareReturnRefundKey","posHardwareReturnRefundableCents","shipping","refundReturnedOnlinePosHardwareOrder","asked","fee","restockingFeeCents","isSafeInteger","claimed","stripePaymentIntentId","refundRequestedAtMs","update","params","payment_intent","ok","body","delete","at","settled"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,yBAAyB,QAAQ,yCAAwC;AAClF,SAASC,aAAa,EAAEC,kBAAkB,QAAQ,2BAA0B;AAC5E,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,oBAAoB,EAAEC,4BAA4B,QAAQ,sCAAkC;AACrG,SAASC,kBAAkB,QAA8B,+BAA2B;AACpF,SACEC,sBAAsB,EACtBC,kBAAkB,EAClBC,qBAAqB,EACrBC,8BAA8B,EAC9BC,qBAAqB,EACrBC,yBAAyB,QAIpB,2BAAuB;AAC9B,SAASC,sCAAsC,QAAQ,kCAA8B;AACrF,SAASC,iBAAiB,EAAEC,sBAAsB,EAAEC,kBAAkB,QAAQ,oBAAgB;AAC9F,SAASC,SAAS,QAAQ,kBAAc;AACxC,SAASC,kBAAkB,QAAQ,qBAAiB;AACpD,SAASC,wBAAwB,QAAQ,4BAAwB;AAEjE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA6B2C,GAE3C,OAAO,MAAMC,iCAAiCC;IAC5C,Y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iC,cAAc,CAAC,OAAOC;QACpD,MAAMO,WAAW,MAAMP,YAAYE,GAAG,CAACE;QACvC,MAAMsE,UAAUnE,SAASE,IAAI;QAC7B,MAAMoH,UAA4B,aAAKnD;QACvC,OAAO,AAACmD,QAA6CR,mBAAmB;QACxE,MAAM1E,WAAWnE,sBAAsBqJ,SAAS;YAC9ChJ,KAAK,CAAC,OAAO,EAAEU,gBAAgB;YAC/BuD,KAAK;YACL9D;YACAT,UAAUP,MAAM6J;YAChBxI,MAAMuI;YACNrI;QACF;QACA,MAAMmB,QAA0B,aAC3BiC;YACH,kEAAkE;YAClE9E,QAAQ;YACRuB,cAAcwI;YACdpI,eAAemD,SAASnD,aAAa,GACjC,aAAKmD,SAASnD,aAAa;gBAAEC,OAAO;gBAAYuG,WAAWnF,MAAM6F,QAAQ;gBAAEhH,aAAakI;iBACxFjF,SAASnD,aAAa;;QAE5BQ,YAAYW,GAAG,CAACP,KAAKM;QACrBV,YAAYW,GAAG,CAACb,SAAS7C,sBAAsB4D,MAAMhB,OAAO,EAAEa,QAAQxD,0BAA0BwD;QAChG,OAAOA;IACT;IACA,OAAO;QAAEF;QAAQvC;QAAOe;IAAM;AAChC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-returns.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { formatOperatorAlertAmount } from '@aglyn/aglyn/app-utils/operator-alerts'\nimport { firebaseAdmin, raiseOperatorAlert } from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport { posOrderRefundRecord, POS_ORDER_REFUNDS_COLLECTION } from '../model/commerce-pos-day-report'\nimport { POS_STRIPE_TENDERS, type PosTenderSource } from '../model/commerce-pos-ops'\nimport {\n formatPosHardwareCents,\n isPosHardwareSellerStoreSale,\n isPosHardwareSkuId,\n POS_HARDWARE_ORDER_ID,\n POS_HARDWARE_RETURN_REASON_MAX,\n posHardwareSaleRecord,\n posHardwareSaleSetOptions,\n type PosHardwareInPersonConfig,\n type PosHardwareOrder,\n type PosHardwareRefund,\n} from '../model/pos-hardware'\nimport { COMMERCE_POS_HARDWARE_RETURN_REQUESTED } from '../constants/operator-alerts'\nimport { hardwareOrdersRef, posHardwareOrderNumber, posHardwareSaleRef } from './pos-hardware'\nimport { posStripe } from './pos-stripe'\nimport { createStripeRefund } from './stripe-refund'\nimport { posOrderRefundHardwareId } from './pos-order-refund-ids'\n\n/*==========================================\n * RETURNING A CARD READER SOLD IN PERSON (AGL-4038).\n *\n * Three ways, and all of them pay back from the SELLING store's takings,\n * the way the sale was paid — never from the platform's Checkout, which an\n * in-person sale never used:\n *\n * 1. At the selling store's register, at a later event: the register's own\n * return (`pos-return.ts`) refunds the sale's tenders as for anything\n * else, and the hardware's share of it is written here onto the\n * hardware order and its retained sale record.\n * 2. From the staff Hardware orders page: the card the sale was paid with\n * is refunded through the register sale's own Stripe refund (a\n * destination charge, so the money comes back out of the store's\n * connected account), recorded on the register sale as any refund is,\n * and on the hardware order. A sale paid in cash can only be refunded\n * at the register.\n * 3. Requested by the buyer from their own purchase history: staff are\n * alerted, and refund it (2) or decline it.\n *\n * Each refund is written once by its key, and the order says Refunded once\n * every hardware item on it has come back. Returns follow the hardware terms\n * of sale; nothing here decides them.\n *\n * AN ORDER SHIPPED TO THE BUYER (AGL-4038) is asked back the same way (3)\n * once it has shipped, and declined the same way. Staff refund it as a\n * return ({@link refundReturnedOnlinePosHardwareOrder}): the items and their\n * tax, less any restocking fee Stripe charged, on the platform's own\n * account, since the platform's Checkout took the payment.\n *=========================================*/\n\nexport class PosHardwareReturnRefusal extends Error {\n constructor(\n message: string,\n readonly status: number,\n ) {\n super(message)\n }\n}\n\nfunction firestore() {\n return firebaseAdmin.app().firestore()\n}\n\nconst units = (order: Pick<PosHardwareOrder, 'lines'>) =>\n (order.lines ?? []).reduce((sum, line) => sum + (Number(line.quantity) || 0), 0)\n\n/** The order with one more refund on it, or as it was when the key was already used. */\nexport function withPosHardwareRefund(order: PosHardwareOrder, refund: PosHardwareRefund): PosHardwareOrder {\n const refunds = order.refunds ?? []\n if (refunds.some((held) => held.key === refund.key)) return order\n const next = [...refunds, refund]\n const refundedCents = next.reduce((sum, held) => sum + held.cents, 0)\n const returned = next.reduce((sum, held) => sum + held.quantity, 0)\n const whole = refundedCents >= (order.totalCents ?? 0) || (returned > 0 && returned >= units(order))\n return {\n ...order,\n refunds: next,\n refundedCents,\n refundedAtMs: refund.atMs,\n refundId: refund.stripeRefundId ?? order.refundId ?? null,\n ...(whole ? { status: 'refunded' as const } : {}),\n ...(order.returnRequest && order.returnRequest.state === 'requested'\n ? { returnRequest: { ...order.returnRequest, state: 'refunded' as const, decidedAtMs: refund.atMs } }\n : {}),\n updatedAtMs: refund.atMs,\n }\n}\n\n/** Writes one refund onto a hardware order and its sale record, once. */\nasync function applyRefund(orderId: string, refund: PosHardwareRefund): Promise<PosHardwareOrder | null> {\n const saleRef = posHardwareSaleRef(orderId)\n return firestore().runTransaction(async (transaction: any) => {\n const sale = await transaction.get(saleRef)\n if (!sale.exists) return null\n const ref = hardwareOrdersRef(String(sale.get('orgId') ?? '')).doc(orderId)\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) return null\n const before = snapshot.data() as PosHardwareOrder\n const after = withPosHardwareRefund(before, refund)\n if (after === before) return before\n transaction.set(ref, after)\n transaction.set(saleRef, posHardwareSaleRecord(orderId, after), posHardwareSaleSetOptions(after))\n return after\n })\n}\n\n/**\n * A return at the selling store's register (way 1): the hardware's share of\n * what the return refunded, by the lines it took back. Never throws into the\n * return; the money has already gone back.\n */\nexport async function recordRegisterHardwareReturn(input: {\n config: PosHardwareInPersonConfig | null\n hostId: string\n registerOrderId: string\n returnId: string\n refundCents: number\n lines: ReadonlyArray<{ index: number; quantity: number; refundCents: number }>\n now?: number\n}): Promise<PosHardwareOrder | null> {\n const { config } = input\n if (!config || input.hostId !== config.sellerHostId || !input.lines.length) return null\n try {\n const hostRef = firestore().collection('hosts').doc(input.hostId)\n const register = await hostRef.collection('orders').doc(input.registerOrderId).get()\n const orderId = String(register.get('hardwareOrderId') ?? '')\n if (!POS_HARDWARE_ORDER_ID.test(orderId)) return null\n const lineItems = (register.get('lineItems') ?? []) as CommerceModel.OrderLineItem[]\n const productIds = [...new Set(input.lines.map((line) => String(lineItems[line.index]?.productId ?? '')))].filter(Boolean)\n const products = new Map(\n (await Promise.all(productIds.map((id) => hostRef.collection('products').doc(id).get()))).map((doc: any) => [\n String(doc.id),\n doc.get('hardwareSku'),\n ]),\n )\n const hardware = input.lines.filter((line) =>\n isPosHardwareSkuId(products.get(String(lineItems[line.index]?.productId ?? ''))),\n )\n if (!hardware.length) return null\n const linesCents = input.lines.reduce((sum, line) => sum + Math.max(0, Math.round(line.refundCents)), 0)\n const hardwareCents = hardware.reduce((sum, line) => sum + Math.max(0, Math.round(line.refundCents)), 0)\n // What actually went back, in the lines' own proportion: a card that\n // refused after another tender paid back leaves a part-return.\n const refunded = Math.max(0, Math.round(input.refundCents))\n const cents =\n linesCents > 0 && refunded < linesCents\n ? Math.floor((refunded * hardwareCents * 2 + linesCents) / (linesCents * 2))\n : hardwareCents\n return await applyRefund(orderId, {\n key: `register:${input.returnId}`,\n via: 'register',\n cents,\n quantity: hardware.reduce((sum, line) => sum + Math.max(0, Math.round(line.quantity)), 0),\n atMs: input.now ?? Date.now(),\n stripeRefundId: null,\n })\n } catch (error) {\n console.error('[pos-hardware-returns] a register return was not written to its hardware order', input.registerOrderId, error)\n return null\n }\n}\n\n/**\n * Refunds what is left of an order sold by the platform's own store from the\n * staff page (way 2), through the store order's own card refund: an\n * in-person sale's register sale, or an online order's Checkout payment\n * (AGL-4038), both destination charges into the store's account. Refused\n * for a sale paid by anything Stripe cannot refund, which goes back at the\n * register instead. `amountCents` refunds less than what is left: a return\n * of an online order keeps the original shipping and any restocking fee.\n */\nexport async function refundInPersonPosHardwareOrder(input: {\n config: PosHardwareInPersonConfig | null\n orgId: string\n orderId: string\n actorUid: string\n amountCents?: number\n now?: number\n}): Promise<{ before: PosHardwareOrder; order: PosHardwareOrder }> {\n const { config } = input\n if (!config) throw new PosHardwareReturnRefusal('Card reader sales in person are off.', 409)\n const ref = hardwareOrdersRef(input.orgId).doc(input.orderId)\n const snapshot = await ref.get()\n if (!snapshot.exists) throw new PosHardwareReturnRefusal('No such order', 404)\n const before = snapshot.data() as PosHardwareOrder\n if (!isPosHardwareSellerStoreSale(before) || before.posSale?.hostId !== config.sellerHostId) {\n throw new PosHardwareReturnRefusal('Only a card reader sold by our own store is refunded this way.', 409)\n }\n if (before.status === 'refunded' || before.status === 'canceled') return { before, order: before }\n const left = Math.max(0, (before.totalCents ?? 0) - (before.refundedCents ?? 0))\n const cents =\n input.amountCents === undefined ? left : Math.min(left, Math.max(0, Math.round(Number(input.amountCents) || 0)))\n if (!cents) throw new PosHardwareReturnRefusal('Nothing is left to refund on this order.', 409)\n const registerOrderId = String(before.posSale?.orderId ?? '')\n const registerRef = firestore().collection('hosts').doc(config.sellerHostId).collection('orders').doc(registerOrderId)\n const register = await registerRef.get()\n if (!register.exists) throw new PosHardwareReturnRefusal('The register sale is missing.', 404)\n const sale = register.data() as PosTenderSource & CommerceModel.HostOrder & { refundedCents?: number }\n const card = CommerceModel.orderPayments(sale as never)\n .filter((payment) => payment.status === 'succeeded' && POS_STRIPE_TENDERS.has(payment.method) && payment.paymentIntentId)\n .find((payment) => payment.amountCents >= cents)\n if (!card?.paymentIntentId) {\n throw new PosHardwareReturnRefusal(\n 'This card reader was not paid by one card that can take this refund. Refund it as a return at the selling store’s register instead.',\n 409,\n )\n }\n const totalCents = Number(sale.totals?.totalCents ?? 0)\n // Reserve on the register sale first, as its own refunds do, so a refund\n // there and one here cannot both take the same money.\n const reserved = await firestore().runTransaction(async (transaction: any) => {\n const fresh = (await transaction.get(registerRef)).data() ?? {}\n const already = Number(fresh['refundedCents'] ?? 0)\n if (already + cents > totalCents) return false\n transaction.set(registerRef, { refundedCents: already + cents }, { merge: true })\n return true\n })\n if (!reserved) {\n throw new PosHardwareReturnRefusal('The register sale was already refunded. Check it on the store’s orders.', 409)\n }\n const attempt = (before.refunds ?? []).filter((held) => held.via === 'staff').length + 1\n const refund = await createStripeRefund({\n paymentIntentId: card.paymentIntentId,\n amountCents: cents,\n idempotencyKey: `pos-hw-refund-${input.orderId}-${attempt}`,\n metadata: {\n hostId: config.sellerHostId,\n orderId: registerOrderId,\n hardwareOrderId: input.orderId,\n kind: 'pos-hardware-refund',\n },\n })\n if ('error' in refund) {\n // Stripe said no, so no money moved: the reservation goes back.\n await firestore()\n .runTransaction(async (transaction: any) => {\n const current = Number((await transaction.get(registerRef)).get('refundedCents') ?? 0)\n transaction.set(registerRef, { refundedCents: Math.max(0, current - cents) }, { merge: true })\n })\n .catch(() => undefined)\n throw new PosHardwareReturnRefusal(refund.error, refund.status === 409 ? 409 : 502)\n }\n const now = input.now ?? Date.now()\n const registerRefund = posOrderRefundRecord({\n orderId: registerOrderId,\n order: sale as PosTenderSource & { registerId?: unknown },\n refundedCents: cents,\n paymentIntentId: card.paymentIntentId,\n cashierId: null,\n source: 'staff',\n stripeRefundId: refund.refundId || null,\n atMs: now,\n })\n await firestore().runTransaction(async (transaction: any) => {\n const fresh = (await transaction.get(registerRef)).data() ?? {}\n const refundedCents = Number(fresh['refundedCents'] ?? 0)\n transaction.set(\n registerRef,\n {\n ...(refundedCents >= totalCents ? { status: 'refunded' } : {}),\n updatedAtMs: now,\n timeline: firebaseAdmin.firestore.FieldValue.arrayUnion({\n atMs: now,\n event: 'refund',\n detail: `Card reader refunded from the staff hardware page: ${formatPosHardwareCents(cents)}`,\n }),\n },\n { merge: true },\n )\n if (registerRefund) {\n transaction.set(\n firestore()\n .collection('hosts')\n .doc(config.sellerHostId)\n .collection('registers')\n .doc(registerRefund.registerId)\n .collection(POS_ORDER_REFUNDS_COLLECTION)\n .doc(refund.refundId || posOrderRefundHardwareId(registerOrderId, attempt)),\n registerRefund,\n )\n }\n })\n const order = await applyRefund(input.orderId, {\n key: `staff:${attempt}`,\n via: 'staff',\n cents,\n quantity: Math.max(0, units(before) - (before.refunds ?? []).reduce((sum, held) => sum + held.quantity, 0)),\n atMs: now,\n stripeRefundId: refund.refundId || null,\n })\n return { before, order: order ?? before }\n}\n\n/**\n * The statuses an online order may be asked back in (AGL-4038): once it has\n * shipped. Before that, changing or canceling it is for support, who cancel\n * and refund it in full from the staff page.\n */\nexport const POS_HARDWARE_ONLINE_RETURNABLE: readonly PosHardwareOrder['status'][] = ['shipped', 'delivered', 'registered']\n\n/**\n * The buyer asks to return an order (way 3), from their own purchase\n * history: once while a request is open, with a reason. Staff are alerted.\n * An in-person order any time before it is refunded; an online one once it\n * has shipped (AGL-4038), which staff refund as a return\n * ({@link refundReturnedOnlinePosHardwareOrder}) or decline. Never for an\n * order already refunded.\n */\nexport async function requestPosHardwareReturn(input: {\n orgId: string\n orderId: string\n uid: string\n reason: unknown\n now?: number\n}): Promise<PosHardwareOrder> {\n const reason = String(input.reason ?? '').trim().slice(0, POS_HARDWARE_RETURN_REASON_MAX)\n if (reason.length < 3) throw new PosHardwareReturnRefusal('Say why you are returning it.', 400)\n if (!POS_HARDWARE_ORDER_ID.test(input.orderId)) throw new PosHardwareReturnRefusal('No such order.', 404)\n const ref = hardwareOrdersRef(input.orgId).doc(input.orderId)\n const now = input.now ?? Date.now()\n const outcome = await firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new PosHardwareReturnRefusal('No such order.', 404)\n const before = snapshot.data() as PosHardwareOrder\n if (before.status === 'refunded' || before.status === 'canceled') {\n throw new PosHardwareReturnRefusal('This order was already refunded.', 409)\n }\n if (before.source !== 'in_person' && !POS_HARDWARE_ONLINE_RETURNABLE.includes(before.status)) {\n throw new PosHardwareReturnRefusal(\n 'This order has not shipped yet. To change or cancel it, contact support.',\n 409,\n )\n }\n if (before.returnRequest?.state === 'requested') return { order: before, created: false }\n const after: PosHardwareOrder = {\n ...before,\n returnRequest: {\n state: 'requested',\n reason,\n requestedBy: input.uid,\n requestedAtMs: now,\n decidedBy: null,\n decidedAtMs: null,\n note: null,\n },\n updatedAtMs: now,\n }\n transaction.set(ref, after)\n return { order: after, created: true }\n })\n if (outcome.created) {\n try {\n await raiseOperatorAlert(COMMERCE_POS_HARDWARE_RETURN_REQUESTED, {\n dedupeKey: `${input.orderId}:${now}`,\n orgId: input.orgId,\n hostId: outcome.order.hostId || outcome.order.posSale?.hostId || '',\n context: {\n orderNumber: posHardwareOrderNumber(input.orderId),\n amount: formatOperatorAlertAmount(outcome.order.totalCents ?? 0),\n orgId: input.orgId,\n items: (outcome.order.lines ?? []).map((line) => `${line.quantity} × ${line.name}`).join(', '),\n reason,\n },\n })\n } catch (error) {\n console.error('[pos-hardware-returns] return request alert failed', input.orderId, error)\n }\n }\n return outcome.order\n}\n\n/** Staff decline an open return request, with a note for the buyer. */\nexport async function declinePosHardwareReturn(input: {\n orgId: string\n orderId: string\n actorUid: string\n note: unknown\n now?: number\n}): Promise<{ before: PosHardwareOrder; order: PosHardwareOrder }> {\n const note = String(input.note ?? '').trim().slice(0, POS_HARDWARE_RETURN_REASON_MAX) || null\n const ref = hardwareOrdersRef(input.orgId).doc(input.orderId)\n const now = input.now ?? Date.now()\n return firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new PosHardwareReturnRefusal('No such order', 404)\n const before = snapshot.data() as PosHardwareOrder\n if (before.returnRequest?.state !== 'requested') {\n throw new PosHardwareReturnRefusal('There is no open return request on this order.', 409)\n }\n const order: PosHardwareOrder = {\n ...before,\n returnRequest: { ...before.returnRequest, state: 'declined', decidedBy: input.actorUid, decidedAtMs: now, note },\n updatedAtMs: now,\n }\n transaction.set(ref, order)\n return { before, order }\n })\n}\n\n/** The idempotency key of an online return's refund: the order and the amount. */\nexport function posHardwareReturnRefundKey(orderId: string, cents: number): string {\n return `pos-hw-return-${orderId}-${cents}`\n}\n\n/** What an online return gives back: the items and their tax, never the original shipping. */\nexport function posHardwareReturnRefundableCents(order: Pick<PosHardwareOrder, 'totalCents' | 'shipping'>): number {\n return Math.max(0, (order.totalCents ?? 0) - (order.shipping?.cents ?? 0))\n}\n\n/**\n * Staff refund an ONLINE order the buyer sent back (AGL-4038), from the\n * staff Hardware orders page, once its return was requested: the price of\n * the items and the tax on them, less any restocking fee Stripe charged for\n * the return, to the card it was paid with on the platform's own account.\n * The original shipping is not refunded, under the hardware terms of sale.\n *\n * Claimed first, as a cancel is (`refundRequestedAtMs`), so two presses make\n * one refund; the Stripe key names the order and the amount, so a retry of\n * the same refund is the same refund. The order says Refunded, its return\n * request Refunded, and the refund is written once by its key, with the\n * sale record in the same transaction.\n */\nexport async function refundReturnedOnlinePosHardwareOrder(input: {\n orgId: string\n orderId: string\n actorUid: string\n restockingFeeCents: unknown\n now?: () => number\n}): Promise<{ before: PosHardwareOrder; order: PosHardwareOrder; cents: number }> {\n const fee = input.restockingFeeCents === undefined || input.restockingFeeCents === null || input.restockingFeeCents === '' ? 0 : Number(input.restockingFeeCents)\n if (!Number.isSafeInteger(fee) || fee < 0) {\n throw new PosHardwareReturnRefusal('Enter the restocking fee in whole cents, or 0.', 400)\n }\n if (!POS_HARDWARE_ORDER_ID.test(input.orderId)) throw new PosHardwareReturnRefusal('No such order', 404)\n const now = input.now ?? Date.now\n const ref = hardwareOrdersRef(input.orgId).doc(input.orderId)\n // Bought from the platform's own online store (AGL-4038): the money is in\n // that store's account, so it goes back through the store order's own\n // refund, under the same return rule — the items and their tax, less the fee.\n const current = (await ref.get()).data() as PosHardwareOrder | undefined\n if (current && current.source === 'storefront') {\n if (current.returnRequest?.state !== 'requested') {\n throw new PosHardwareReturnRefusal('There is no open return request on this order.', 409)\n }\n if (!POS_HARDWARE_ONLINE_RETURNABLE.includes(current.status)) {\n throw new PosHardwareReturnRefusal('Only an order that has shipped is refunded as a return.', 409)\n }\n const cents = posHardwareReturnRefundableCents(current) - fee\n if (cents <= 0) throw new PosHardwareReturnRefusal('The restocking fee leaves nothing to refund.', 400)\n const { posHardwareInPersonConfig } = await import('./pos-hardware')\n const refunded = await refundInPersonPosHardwareOrder({\n config: posHardwareInPersonConfig(),\n orgId: input.orgId,\n orderId: input.orderId,\n actorUid: input.actorUid,\n amountCents: cents,\n now: now(),\n })\n return { ...refunded, cents }\n }\n const claimed = await firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new PosHardwareReturnRefusal('No such order', 404)\n const before = snapshot.data() as PosHardwareOrder & { refundRequestedAtMs?: number }\n if (before.source === 'in_person') {\n throw new PosHardwareReturnRefusal('A reader sold in person is refunded with Refund.', 409)\n }\n if (before.returnRequest?.state !== 'requested') {\n throw new PosHardwareReturnRefusal('There is no open return request on this order.', 409)\n }\n if (!POS_HARDWARE_ONLINE_RETURNABLE.includes(before.status)) {\n throw new PosHardwareReturnRefusal('Only an order that has shipped is refunded as a return.', 409)\n }\n if (!before.stripePaymentIntentId) throw new PosHardwareReturnRefusal('This order has no payment to refund.', 409)\n if (before.refundRequestedAtMs && now() - before.refundRequestedAtMs < 2 * 60 * 1000) {\n throw new PosHardwareReturnRefusal('A refund of this order is already in progress.', 409)\n }\n const cents = posHardwareReturnRefundableCents(before) - fee\n if (cents <= 0) throw new PosHardwareReturnRefusal('The restocking fee leaves nothing to refund.', 400)\n transaction.update(ref, { refundRequestedAtMs: now() })\n return { before: before as PosHardwareOrder, cents }\n })\n const { before, cents } = claimed\n const asked = await posStripe('POST', 'refunds', {\n params: {\n payment_intent: before.stripePaymentIntentId,\n amount: cents,\n 'metadata[type]': 'pos-hardware-return',\n 'metadata[orderId]': input.orderId,\n 'metadata[orgId]': input.orgId,\n },\n idempotencyKey: posHardwareReturnRefundKey(input.orderId, cents),\n })\n if (!asked.ok || !asked.body?.id) {\n await ref.update({ refundRequestedAtMs: firebaseAdmin.firestore.FieldValue.delete() }).catch(() => undefined)\n throw new PosHardwareReturnRefusal(\n String(asked.body?.error?.message ?? '') || 'Stripe refused the refund.',\n asked.status === 400 ? 409 : 502,\n )\n }\n const at = now()\n const stripeRefundId = String(asked.body.id)\n const saleRef = posHardwareSaleRef(input.orderId)\n const order = await firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n const current = snapshot.data() as PosHardwareOrder & { refundRequestedAtMs?: number }\n const settled: PosHardwareOrder = { ...current }\n delete (settled as { refundRequestedAtMs?: number }).refundRequestedAtMs\n const refunded = withPosHardwareRefund(settled, {\n key: `return:${stripeRefundId}`,\n via: 'staff',\n cents,\n quantity: units(settled),\n atMs: at,\n stripeRefundId,\n })\n const after: PosHardwareOrder = {\n ...refunded,\n // Every item came back: the order is Refunded, whatever was kept.\n status: 'refunded',\n refundedAtMs: at,\n returnRequest: refunded.returnRequest\n ? { ...refunded.returnRequest, state: 'refunded', decidedBy: input.actorUid, decidedAtMs: at }\n : refunded.returnRequest,\n }\n transaction.set(ref, after)\n transaction.set(saleRef, posHardwareSaleRecord(input.orderId, after), posHardwareSaleSetOptions(after))\n return after\n })\n return { before, order, cents }\n}\n\n"],"names":["formatOperatorAlertAmount","firebaseAdmin","raiseOperatorAlert","CommerceModel","posOrderRefundRecord","POS_ORDER_REFUNDS_COLLECTION","POS_STRIPE_TENDERS","formatPosHardwareCents","isPosHardwareSellerStoreSale","isPosHardwareSkuId","POS_HARDWARE_ORDER_ID","POS_HARDWARE_RETURN_REASON_MAX","posHardwareSaleRecord","posHardwareSaleSetOptions","COMMERCE_POS_HARDWARE_RETURN_REQUESTED","hardwareOrdersRef","posHardwareOrderNumber","posHardwareSaleRef","posStripe","createStripeRefund","posOrderRefundHardwareId","PosHardwareReturnRefusal","Error","message","status","firestore","app","units","order","lines","reduce","sum","line","Number","quantity","withPosHardwareRefund","refund","refunds","some","held","key","next","refundedCents","cents","returned","whole","totalCents","refundedAtMs","atMs","refundId","stripeRefundId","returnRequest","state","decidedAtMs","updatedAtMs","applyRefund","orderId","saleRef","runTransaction","transaction","sale","get","exists","ref","String","doc","snapshot","before","data","after","set","recordRegisterHardwareReturn","input","config","hostId","sellerHostId","length","register","hostRef","collection","registerOrderId","test","lineItems","productIds","Set","map","index","productId","filter","Boolean","products","Map","Promise","all","id","hardware","linesCents","Math","max","round","refundCents","hardwareCents","refunded","floor","returnId","via","now","Date","error","console","refundInPersonPosHardwareOrder","orgId","posSale","left","amountCents","undefined","min","registerRef","card","orderPayments","payment","has","method","paymentIntentId","find","totals","reserved","fresh","already","merge","attempt","idempotencyKey","metadata","hardwareOrderId","kind","current","catch","registerRefund","cashierId","source","timeline","FieldValue","arrayUnion","event","detail","registerId","POS_HARDWARE_ONLINE_RETURNABLE","requestPosHardwareReturn","reason","trim","slice","outcome","includes","created","requestedBy","uid","requestedAtMs","decidedBy","note","dedupeKey","context","orderNumber","amount","items","name","join","declinePosHardwareReturn","actorUid","posHardwareReturnRefundKey","posHardwareReturnRefundableCents","shipping","refundReturnedOnlinePosHardwareOrder","asked","fee","restockingFeeCents","isSafeInteger","posHardwareInPersonConfig","claimed","stripePaymentIntentId","refundRequestedAtMs","update","params","payment_intent","ok","body","delete","at","settled"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,yBAAyB,QAAQ,yCAAwC;AAClF,SAASC,aAAa,EAAEC,kBAAkB,QAAQ,2BAA0B;AAC5E,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,oBAAoB,EAAEC,4BAA4B,QAAQ,sCAAkC;AACrG,SAASC,kBAAkB,QAA8B,+BAA2B;AACpF,SACEC,sBAAsB,EACtBC,4BAA4B,EAC5BC,kBAAkB,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IAAI,CAAC1F,EAAE;IAC3C,MAAMrC,UAAUxC,mBAAmBuD,MAAMhB,OAAO;IAChD,MAAM5B,QAAQ,MAAMH,YAAYiC,cAAc,CAAC,OAAOC;QACpD,MAAMO,WAAW,MAAMP,YAAYE,GAAG,CAACE;QACvC,MAAMwE,UAAUrE,SAASE,IAAI;QAC7B,MAAMuH,UAA4B,aAAKpD;QACvC,OAAO,AAACoD,QAA6CR,mBAAmB;QACxE,MAAM7E,WAAWnE,sBAAsBwJ,SAAS;YAC9CnJ,KAAK,CAAC,OAAO,EAAEU,gBAAgB;YAC/BuD,KAAK;YACL9D;YACAT,UAAUP,MAAMgK;YAChB3I,MAAM0I;YACNxI;QACF;QACA,MAAMmB,QAA0B,aAC3BiC;YACH,kEAAkE;YAClE9E,QAAQ;YACRuB,cAAc2I;YACdvI,eAAemD,SAASnD,aAAa,GACjC,aAAKmD,SAASnD,aAAa;gBAAEC,OAAO;gBAAYyG,WAAWrF,MAAM+F,QAAQ;gBAAElH,aAAaqI;iBACxFpF,SAASnD,aAAa;;QAE5BQ,YAAYW,GAAG,CAACP,KAAKM;QACrBV,YAAYW,GAAG,CAACb,SAAS7C,sBAAsB4D,MAAMhB,OAAO,EAAEa,QAAQxD,0BAA0BwD;QAChG,OAAOA;IACT;IACA,OAAO;QAAEF;QAAQvC;QAAOe;IAAM;AAChC"}
@@ -14,6 +14,8 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
+ import { type PosHardwareSkuId } from '../model/pos-hardware';
18
+ import { type PosHardwareTermsAcceptance } from '../model/pos-hardware-terms';
17
19
  export declare function posHardwareSaleFields(input: {
18
20
  hostId: string;
19
21
  orgId: string | null | undefined;
@@ -26,3 +28,77 @@ export declare function posHardwareSaleFields(input: {
26
28
  }, env?: Record<string, string | undefined>): {
27
29
  hardwareSalePending?: true;
28
30
  };
31
+ /** What a checkout on any store is told about the hardware in it. */
32
+ export interface SellerStoreHardwareCheckout {
33
+ /** Whether any line is hardware on the platform's own store. */
34
+ hardware: boolean;
35
+ /** The hardware item of each line, by its index in the lines given; null for any other line. */
36
+ skus: Array<PosHardwareSkuId | null>;
37
+ /** Why the checkout is refused, before anything is held or charged; null when it is not. */
38
+ refusal: {
39
+ status: number;
40
+ error: string;
41
+ needsHardwareTerms?: true;
42
+ } | null;
43
+ }
44
+ /**
45
+ * Reads a checkout's lines for hardware on the platform's own store. Answers
46
+ * `hardware: false` for every other store, from the environment alone.
47
+ */
48
+ export declare function sellerStoreHardwareCheckout(input: {
49
+ hostId: string;
50
+ orgId: string | null | undefined;
51
+ lines: ReadonlyArray<{
52
+ productId: string;
53
+ quantity: number;
54
+ }>;
55
+ products: ReadonlyMap<string, {
56
+ hardwareSku?: unknown;
57
+ } | null | undefined>;
58
+ /** The request's `hardwareTerms`: both boxes ticked, or not. */
59
+ hardwareTerms: unknown;
60
+ /** A recurring checkout: hardware is bought once. */
61
+ subscription?: boolean;
62
+ }, env?: Record<string, string | undefined>): SellerStoreHardwareCheckout;
63
+ /**
64
+ * The hardware fields a paid online order on the seller store is written
65
+ * with: the mark, and the terms of sale the buyer ticked at checkout, dated
66
+ * when the session was made. Nothing for any other order.
67
+ */
68
+ export declare function storefrontHardwareSaleFields(input: {
69
+ hostId: string;
70
+ orgId: string | null | undefined;
71
+ lineItems: ReadonlyArray<{
72
+ productId: string;
73
+ }>;
74
+ products: ReadonlyMap<string, {
75
+ hardwareSku?: unknown;
76
+ } | null | undefined>;
77
+ /** The paid Checkout Session's metadata and creation time (Stripe's seconds). */
78
+ metadata: unknown;
79
+ createdSeconds: unknown;
80
+ }, env?: Record<string, string | undefined>): {
81
+ hardwareSalePending?: true;
82
+ hardwareTermsAcceptance?: PosHardwareTermsAcceptance;
83
+ };
84
+ /**
85
+ * {@link storefrontHardwareSaleFields} for the webhook that writes a paid
86
+ * online order: the store's workspace is asked for (`orgIdOf`) only when
87
+ * the store is the configured seller, so every other store's order costs
88
+ * nothing more. Never throws: an unreadable workspace leaves the order
89
+ * unmarked, as any other store's.
90
+ */
91
+ export declare function sellerStoreOrderHardwareFields(input: Omit<Parameters<typeof storefrontHardwareSaleFields>[0], 'orgId'> & {
92
+ orgIdOf: () => Promise<string | null | undefined>;
93
+ }, env?: Record<string, string | undefined>): Promise<ReturnType<typeof storefrontHardwareSaleFields>>;
94
+ /**
95
+ * Records the hardware order of a paid sale on the platform's own store —
96
+ * a register sale or an online order — once, through the one recorder. Every
97
+ * other store's sale is answered from the environment alone, without loading
98
+ * it. Never throws: a sale this misses stays marked, and the sweep records it.
99
+ */
100
+ export declare function recordSellerStoreSaleHardware(event: {
101
+ hostId: string;
102
+ orderId: string;
103
+ offline?: boolean;
104
+ }, env?: Record<string, string | undefined>): Promise<void>;
@@ -1,3 +1,4 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
1
2
  /**
2
3
  * @license
3
4
  * Copyright 2026 Aglyn LLC
@@ -13,7 +14,8 @@
13
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
15
  * See the License for the specific language governing permissions and
15
16
  * limitations under the License.
16
- */ import { isPosHardwareSkuId, parsePosHardwareInPersonConfig } from "../model/pos-hardware.js";
17
+ */ import { isPosHardwareSkuId, parsePosHardwareInPersonConfig, POS_HARDWARE_MAX_PER_LINE, POS_HARDWARE_MAX_UNITS } from "../model/pos-hardware.js";
18
+ import { POS_HARDWARE_TERMS_REQUIRED, posHardwareTermsConfirmed, posHardwareTermsFromMetadata } from "../model/pos-hardware-terms.js";
17
19
  /*==========================================
18
20
  * THE MARK A REGISTER SALE OF HARDWARE CARRIES (AGL-4038).
19
21
  *
@@ -40,5 +42,116 @@
40
42
  hardwareSalePending: true
41
43
  } : {};
42
44
  }
45
+ /**
46
+ * Reads a checkout's lines for hardware on the platform's own store. Answers
47
+ * `hardware: false` for every other store, from the environment alone.
48
+ */ export function sellerStoreHardwareCheckout(input, env = process.env) {
49
+ const config = parsePosHardwareInPersonConfig(env);
50
+ const none = {
51
+ hardware: false,
52
+ skus: input.lines.map(()=>null),
53
+ refusal: null
54
+ };
55
+ if (!config || config.sellerHostId !== input.hostId || config.sellerOrgId !== input.orgId) return none;
56
+ const skus = input.lines.map((line)=>{
57
+ var _input_products_get;
58
+ const sku = (_input_products_get = input.products.get(line.productId)) == null ? void 0 : _input_products_get.hardwareSku;
59
+ return isPosHardwareSkuId(sku) ? sku : null;
60
+ });
61
+ if (!skus.some(Boolean)) return none;
62
+ if (input.subscription) {
63
+ return {
64
+ hardware: true,
65
+ skus,
66
+ refusal: {
67
+ status: 400,
68
+ error: 'Card reader hardware is bought once, not by subscription.'
69
+ }
70
+ };
71
+ }
72
+ const perItem = new Map();
73
+ input.lines.forEach((line, index)=>{
74
+ var _perItem_get;
75
+ const sku = skus[index];
76
+ if (sku) perItem.set(sku, ((_perItem_get = perItem.get(sku)) != null ? _perItem_get : 0) + Math.max(0, Math.round(Number(line.quantity) || 0)));
77
+ });
78
+ const units = [
79
+ ...perItem.values()
80
+ ].reduce((sum, quantity)=>sum + quantity, 0);
81
+ if ([
82
+ ...perItem.values()
83
+ ].some((quantity)=>quantity > POS_HARDWARE_MAX_PER_LINE) || units > POS_HARDWARE_MAX_UNITS) {
84
+ return {
85
+ hardware: true,
86
+ skus,
87
+ refusal: {
88
+ status: 400,
89
+ error: `One order holds at most ${POS_HARDWARE_MAX_PER_LINE} of each card reader or accessory, and ${POS_HARDWARE_MAX_UNITS} in all.`
90
+ }
91
+ };
92
+ }
93
+ if (!posHardwareTermsConfirmed(input.hardwareTerms)) {
94
+ return {
95
+ hardware: true,
96
+ skus,
97
+ refusal: {
98
+ status: 400,
99
+ error: POS_HARDWARE_TERMS_REQUIRED,
100
+ needsHardwareTerms: true
101
+ }
102
+ };
103
+ }
104
+ return {
105
+ hardware: true,
106
+ skus,
107
+ refusal: null
108
+ };
109
+ }
110
+ /**
111
+ * The hardware fields a paid online order on the seller store is written
112
+ * with: the mark, and the terms of sale the buyer ticked at checkout, dated
113
+ * when the session was made. Nothing for any other order.
114
+ */ export function storefrontHardwareSaleFields(input, env = process.env) {
115
+ const mark = posHardwareSaleFields(input, env);
116
+ if (!mark.hardwareSalePending) return {};
117
+ const createdMs = Number(input.createdSeconds) > 0 ? Number(input.createdSeconds) * 1000 : Date.now();
118
+ const acceptance = posHardwareTermsFromMetadata(input.metadata, createdMs);
119
+ return _extends({}, mark, acceptance ? {
120
+ hardwareTermsAcceptance: acceptance
121
+ } : {});
122
+ }
123
+ /**
124
+ * {@link storefrontHardwareSaleFields} for the webhook that writes a paid
125
+ * online order: the store's workspace is asked for (`orgIdOf`) only when
126
+ * the store is the configured seller, so every other store's order costs
127
+ * nothing more. Never throws: an unreadable workspace leaves the order
128
+ * unmarked, as any other store's.
129
+ */ export async function sellerStoreOrderHardwareFields(input, env = process.env) {
130
+ var _parsePosHardwareInPersonConfig;
131
+ if (((_parsePosHardwareInPersonConfig = parsePosHardwareInPersonConfig(env)) == null ? void 0 : _parsePosHardwareInPersonConfig.sellerHostId) !== input.hostId) return {};
132
+ const orgId = await input.orgIdOf().catch(()=>null);
133
+ return storefrontHardwareSaleFields({
134
+ hostId: input.hostId,
135
+ orgId,
136
+ lineItems: input.lineItems,
137
+ products: input.products,
138
+ metadata: input.metadata,
139
+ createdSeconds: input.createdSeconds
140
+ }, env);
141
+ }
142
+ /**
143
+ * Records the hardware order of a paid sale on the platform's own store —
144
+ * a register sale or an online order — once, through the one recorder. Every
145
+ * other store's sale is answered from the environment alone, without loading
146
+ * it. Never throws: a sale this misses stays marked, and the sweep records it.
147
+ */ export async function recordSellerStoreSaleHardware(event, env = process.env) {
148
+ var _parsePosHardwareInPersonConfig;
149
+ if (((_parsePosHardwareInPersonConfig = parsePosHardwareInPersonConfig(env)) == null ? void 0 : _parsePosHardwareInPersonConfig.sellerHostId) !== event.hostId) return;
150
+ try {
151
+ await (await import("./pos-hardware-in-person.js")).recordCompletedSaleHardware(event);
152
+ } catch (error) {
153
+ console.error('[pos-hardware-in-person] recorder not loaded', event.orderId, error);
154
+ }
155
+ }
43
156
 
44
157
  //# sourceMappingURL=pos-hardware-sale-fields.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-sale-fields.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 { isPosHardwareSkuId, parsePosHardwareInPersonConfig } from '../model/pos-hardware'\n\n/*==========================================\n * THE MARK A REGISTER SALE OF HARDWARE CARRIES (AGL-4038).\n *\n * Every path that writes a register sale — an open sale, a payment link, a\n * cash or room sale, the kiosk's cart, an offline sale synced later — spreads\n * these fields into the order it writes. On the platform's own store, a sale\n * with a line whose product is a hardware item says `hardwareSalePending`\n * from the moment it exists, and the hardware order is recorded when it is\n * paid. The completion listener clears the mark; one it missed is found by\n * the mark and recorded on the next sweep, so a sale is never lost because a\n * listener failed after the money was taken.\n *\n * Read on every sale of every store, so it costs nothing anywhere but the\n * seller: the environment is read first, and the products are the ones the\n * sale already loaded.\n *=========================================*/\n\nexport function posHardwareSaleFields(\n input: {\n hostId: string\n orgId: string | null | undefined\n lineItems: ReadonlyArray<{ productId: string }>\n products: ReadonlyMap<string, { hardwareSku?: unknown } | null | undefined>\n },\n env: Record<string, string | undefined> = process.env,\n): { hardwareSalePending?: true } {\n const config = parsePosHardwareInPersonConfig(env)\n if (!config || config.sellerHostId !== input.hostId || config.sellerOrgId !== input.orgId) return {}\n const sellsHardware = input.lineItems.some((line) =>\n isPosHardwareSkuId(input.products.get(line.productId)?.hardwareSku),\n )\n return sellsHardware ? { hardwareSalePending: true } : {}\n}\n"],"names":["isPosHardwareSkuId","parsePosHardwareInPersonConfig","posHardwareSaleFields","input","env","process","config","sellerHostId","hostId","sellerOrgId","orgId","sellsHardware","lineItems","some","line","products","get","productId","hardwareSku","hardwareSalePending"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,EAAEC,8BAA8B,QAAQ,2BAAuB;AAE1F;;;;;;;;;;;;;;;2CAe2C,GAE3C,OAAO,SAASC,sBACdC,KAKC,EACDC,MAA0CC,QAAQD,GAAG;IAErD,MAAME,SAASL,+BAA+BG;IAC9C,IAAI,CAACE,UAAUA,OAAOC,YAAY,KAAKJ,MAAMK,MAAM,IAAIF,OAAOG,WAAW,KAAKN,MAAMO,KAAK,EAAE,OAAO,CAAC;IACnG,MAAMC,gBAAgBR,MAAMS,SAAS,CAACC,IAAI,CAAC,CAACC;YACvBX;eAAnBH,oBAAmBG,sBAAAA,MAAMY,QAAQ,CAACC,GAAG,CAACF,KAAKG,SAAS,sBAAjCd,oBAAoCe,WAAW;;IAEpE,OAAOP,gBAAgB;QAAEQ,qBAAqB;IAAK,IAAI,CAAC;AAC1D"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-sale-fields.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 {\n isPosHardwareSkuId,\n parsePosHardwareInPersonConfig,\n POS_HARDWARE_MAX_PER_LINE,\n POS_HARDWARE_MAX_UNITS,\n type PosHardwareSkuId,\n} from '../model/pos-hardware'\nimport {\n POS_HARDWARE_TERMS_REQUIRED,\n posHardwareTermsConfirmed,\n posHardwareTermsFromMetadata,\n type PosHardwareTermsAcceptance,\n} from '../model/pos-hardware-terms'\n\n/*==========================================\n * THE MARK A REGISTER SALE OF HARDWARE CARRIES (AGL-4038).\n *\n * Every path that writes a register sale — an open sale, a payment link, a\n * cash or room sale, the kiosk's cart, an offline sale synced later — spreads\n * these fields into the order it writes. On the platform's own store, a sale\n * with a line whose product is a hardware item says `hardwareSalePending`\n * from the moment it exists, and the hardware order is recorded when it is\n * paid. The completion listener clears the mark; one it missed is found by\n * the mark and recorded on the next sweep, so a sale is never lost because a\n * listener failed after the money was taken.\n *\n * Read on every sale of every store, so it costs nothing anywhere but the\n * seller: the environment is read first, and the products are the ones the\n * sale already loaded.\n *=========================================*/\n\nexport function posHardwareSaleFields(\n input: {\n hostId: string\n orgId: string | null | undefined\n lineItems: ReadonlyArray<{ productId: string }>\n products: ReadonlyMap<string, { hardwareSku?: unknown } | null | undefined>\n },\n env: Record<string, string | undefined> = process.env,\n): { hardwareSalePending?: true } {\n const config = parsePosHardwareInPersonConfig(env)\n if (!config || config.sellerHostId !== input.hostId || config.sellerOrgId !== input.orgId) return {}\n const sellsHardware = input.lineItems.some((line) =>\n isPosHardwareSkuId(input.products.get(line.productId)?.hardwareSku),\n )\n return sellsHardware ? { hardwareSalePending: true } : {}\n}\n\n/*==========================================\n * THE PLATFORM'S OWN ONLINE STORE SELLS HARDWARE TOO (AGL-4038).\n *\n * A product on the seller store that names a hardware item sells online\n * through the store's ordinary product page, cart and checkout, and the order\n * becomes a hardware order exactly as a register sale does: marked when it is\n * written ({@link posHardwareSaleFields}, `hardwareSalePending`), recorded\n * by the same recorder the register's completion listener runs\n * ({@link recordSellerStoreSaleHardware}), and found again by the same sweep.\n *\n * At checkout, before anything is held or charged\n * ({@link sellerStoreHardwareCheckout}):\n * - each hardware line carries the tangible goods tax code;\n * - the buyer must have ticked the terms of sale and business use, or the\n * checkout is refused with one plain sentence and `needsHardwareTerms`;\n * - the online order limits of the terms of sale hold: at most\n * {@link POS_HARDWARE_MAX_PER_LINE} of an item and\n * {@link POS_HARDWARE_MAX_UNITS} items of hardware in one order.\n * Every other store, and every other line, is untouched.\n *=========================================*/\n\n/** What a checkout on any store is told about the hardware in it. */\nexport interface SellerStoreHardwareCheckout {\n /** Whether any line is hardware on the platform's own store. */\n hardware: boolean\n /** The hardware item of each line, by its index in the lines given; null for any other line. */\n skus: Array<PosHardwareSkuId | null>\n /** Why the checkout is refused, before anything is held or charged; null when it is not. */\n refusal: { status: number; error: string; needsHardwareTerms?: true } | null\n}\n\n/**\n * Reads a checkout's lines for hardware on the platform's own store. Answers\n * `hardware: false` for every other store, from the environment alone.\n */\nexport function sellerStoreHardwareCheckout(\n input: {\n hostId: string\n orgId: string | null | undefined\n lines: ReadonlyArray<{ productId: string; quantity: number }>\n products: ReadonlyMap<string, { hardwareSku?: unknown } | null | undefined>\n /** The request's `hardwareTerms`: both boxes ticked, or not. */\n hardwareTerms: unknown\n /** A recurring checkout: hardware is bought once. */\n subscription?: boolean\n },\n env: Record<string, string | undefined> = process.env,\n): SellerStoreHardwareCheckout {\n const config = parsePosHardwareInPersonConfig(env)\n const none: SellerStoreHardwareCheckout = { hardware: false, skus: input.lines.map(() => null), refusal: null }\n if (!config || config.sellerHostId !== input.hostId || config.sellerOrgId !== input.orgId) return none\n const skus = input.lines.map((line) => {\n const sku = input.products.get(line.productId)?.hardwareSku\n return isPosHardwareSkuId(sku) ? sku : null\n })\n if (!skus.some(Boolean)) return none\n if (input.subscription) {\n return { hardware: true, skus, refusal: { status: 400, error: 'Card reader hardware is bought once, not by subscription.' } }\n }\n const perItem = new Map<string, number>()\n input.lines.forEach((line, index) => {\n const sku = skus[index]\n if (sku) perItem.set(sku, (perItem.get(sku) ?? 0) + Math.max(0, Math.round(Number(line.quantity) || 0)))\n })\n const units = [...perItem.values()].reduce((sum, quantity) => sum + quantity, 0)\n if ([...perItem.values()].some((quantity) => quantity > POS_HARDWARE_MAX_PER_LINE) || units > POS_HARDWARE_MAX_UNITS) {\n return {\n hardware: true,\n skus,\n refusal: {\n status: 400,\n error: `One order holds at most ${POS_HARDWARE_MAX_PER_LINE} of each card reader or accessory, and ${POS_HARDWARE_MAX_UNITS} in all.`,\n },\n }\n }\n if (!posHardwareTermsConfirmed(input.hardwareTerms)) {\n return { hardware: true, skus, refusal: { status: 400, error: POS_HARDWARE_TERMS_REQUIRED, needsHardwareTerms: true } }\n }\n return { hardware: true, skus, refusal: null }\n}\n\n/**\n * The hardware fields a paid online order on the seller store is written\n * with: the mark, and the terms of sale the buyer ticked at checkout, dated\n * when the session was made. Nothing for any other order.\n */\nexport function storefrontHardwareSaleFields(\n input: {\n hostId: string\n orgId: string | null | undefined\n lineItems: ReadonlyArray<{ productId: string }>\n products: ReadonlyMap<string, { hardwareSku?: unknown } | null | undefined>\n /** The paid Checkout Session's metadata and creation time (Stripe's seconds). */\n metadata: unknown\n createdSeconds: unknown\n },\n env: Record<string, string | undefined> = process.env,\n): { hardwareSalePending?: true; hardwareTermsAcceptance?: PosHardwareTermsAcceptance } {\n const mark = posHardwareSaleFields(input, env)\n if (!mark.hardwareSalePending) return {}\n const createdMs = Number(input.createdSeconds) > 0 ? Number(input.createdSeconds) * 1000 : Date.now()\n const acceptance = posHardwareTermsFromMetadata(input.metadata, createdMs)\n return { ...mark, ...(acceptance ? { hardwareTermsAcceptance: acceptance } : {}) }\n}\n\n/**\n * {@link storefrontHardwareSaleFields} for the webhook that writes a paid\n * online order: the store's workspace is asked for (`orgIdOf`) only when\n * the store is the configured seller, so every other store's order costs\n * nothing more. Never throws: an unreadable workspace leaves the order\n * unmarked, as any other store's.\n */\nexport async function sellerStoreOrderHardwareFields(\n input: Omit<Parameters<typeof storefrontHardwareSaleFields>[0], 'orgId'> & {\n orgIdOf: () => Promise<string | null | undefined>\n },\n env: Record<string, string | undefined> = process.env,\n): Promise<ReturnType<typeof storefrontHardwareSaleFields>> {\n if (parsePosHardwareInPersonConfig(env)?.sellerHostId !== input.hostId) return {}\n const orgId = await input.orgIdOf().catch(() => null)\n return storefrontHardwareSaleFields(\n {\n hostId: input.hostId,\n orgId,\n lineItems: input.lineItems,\n products: input.products,\n metadata: input.metadata,\n createdSeconds: input.createdSeconds,\n },\n env,\n )\n}\n\n/**\n * Records the hardware order of a paid sale on the platform's own store —\n * a register sale or an online order — once, through the one recorder. Every\n * other store's sale is answered from the environment alone, without loading\n * it. Never throws: a sale this misses stays marked, and the sweep records it.\n */\nexport async function recordSellerStoreSaleHardware(\n event: { hostId: string; orderId: string; offline?: boolean },\n env: Record<string, string | undefined> = process.env,\n): Promise<void> {\n if (parsePosHardwareInPersonConfig(env)?.sellerHostId !== event.hostId) return\n try {\n await (await import('./pos-hardware-in-person')).recordCompletedSaleHardware(event)\n } catch (error) {\n console.error('[pos-hardware-in-person] recorder not loaded', event.orderId, error)\n }\n}\n"],"names":["isPosHardwareSkuId","parsePosHardwareInPersonConfig","POS_HARDWARE_MAX_PER_LINE","POS_HARDWARE_MAX_UNITS","POS_HARDWARE_TERMS_REQUIRED","posHardwareTermsConfirmed","posHardwareTermsFromMetadata","posHardwareSaleFields","input","env","process","config","sellerHostId","hostId","sellerOrgId","orgId","sellsHardware","lineItems","some","line","products","get","productId","hardwareSku","hardwareSalePending","sellerStoreHardwareCheckout","none","hardware","skus","lines","map","refusal","sku","Boolean","subscription","status","error","perItem","Map","forEach","index","set","Math","max","round","Number","quantity","units","values","reduce","sum","hardwareTerms","needsHardwareTerms","storefrontHardwareSaleFields","mark","createdMs","createdSeconds","Date","now","acceptance","metadata","hardwareTermsAcceptance","sellerStoreOrderHardwareFields","orgIdOf","catch","recordSellerStoreSaleHardware","event","recordCompletedSaleHardware","console","orderId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,kBAAkB,EAClBC,8BAA8B,EAC9BC,yBAAyB,EACzBC,sBAAsB,QAEjB,2BAAuB;AAC9B,SACEC,2BAA2B,EAC3BC,yBAAyB,EACzBC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OAAO,aAAKD,MAAUK,aAAa;QAAEE,yBAAyBF;IAAW,IAAI,CAAC;AAChF;AAEA;;;;;;CAMC,GACD,OAAO,eAAeG,+BACpBtD,KAEC,EACDC,MAA0CC,QAAQD,GAAG;QAEjDR;IAAJ,IAAIA,EAAAA,kCAAAA,+BAA+BQ,yBAA/BR,gCAAqCW,YAAY,MAAKJ,MAAMK,MAAM,EAAE,OAAO,CAAC;IAChF,MAAME,QAAQ,MAAMP,MAAMuD,OAAO,GAAGC,KAAK,CAAC,IAAM;IAChD,OAAOX,6BACL;QACExC,QAAQL,MAAMK,MAAM;QACpBE;QACAE,WAAWT,MAAMS,SAAS;QAC1BG,UAAUZ,MAAMY,QAAQ;QACxBwC,UAAUpD,MAAMoD,QAAQ;QACxBJ,gBAAgBhD,MAAMgD,cAAc;IACtC,GACA/C;AAEJ;AAEA;;;;;CAKC,GACD,OAAO,eAAewD,8BACpBC,KAA6D,EAC7DzD,MAA0CC,QAAQD,GAAG;QAEjDR;IAAJ,IAAIA,EAAAA,kCAAAA,+BAA+BQ,yBAA/BR,gCAAqCW,YAAY,MAAKsD,MAAMrD,MAAM,EAAE;IACxE,IAAI;QACF,MAAM,AAAC,CAAA,MAAM,MAAM,CAAC,8BAA0B,EAAGsD,2BAA2B,CAACD;IAC/E,EAAE,OAAO9B,OAAO;QACdgC,QAAQhC,KAAK,CAAC,gDAAgD8B,MAAMG,OAAO,EAAEjC;IAC/E;AACF"}
@@ -30,6 +30,8 @@ export declare function toAttachView(id: string, order: PosHardwareOrder): {
30
30
  registerOrderId: string;
31
31
  registerNumber: number;
32
32
  kiosk: boolean;
33
+ /** Bought from the store's own product pages or cart (AGL-4038), not at the register. */
34
+ online: boolean;
33
35
  offline: boolean;
34
36
  lines: {
35
37
  sku: import("../model/pos-hardware").PosHardwareSkuId;
@@ -328,6 +328,7 @@ const LOOKUP_WINDOW_MS = 10 * 60 * 1000;
328
328
  registerOrderId: (_ref = (_order_posSale = order.posSale) == null ? void 0 : _order_posSale.orderId) != null ? _ref : null,
329
329
  registerNumber: (_ref1 = (_order_posSale1 = order.posSale) == null ? void 0 : _order_posSale1.number) != null ? _ref1 : null,
330
330
  kiosk: ((_order_posSale2 = order.posSale) == null ? void 0 : _order_posSale2.kiosk) === true,
331
+ /** Bought from the store's own product pages or cart (AGL-4038), not at the register. */ online: order.source === 'storefront',
331
332
  offline: ((_order_posSale3 = order.posSale) == null ? void 0 : _order_posSale3.offline) === true,
332
333
  lines: ((_order_lines = order.lines) != null ? _order_lines : []).map((line)=>({
333
334
  sku: line.sku,