@aglyn/plugins-commerce 1.15.1 → 1.16.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 (212) hide show
  1. package/README.md +1 -1
  2. package/package.json +13 -13
  3. package/src/lib/components/cart.js +2 -1
  4. package/src/lib/components/cart.js.map +1 -1
  5. package/src/lib/components/console/payments-settings-card.component.js +6 -1
  6. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  7. package/src/lib/components/console/pos/pos-api.d.ts +5 -0
  8. package/src/lib/components/console/pos/pos-api.js.map +1 -1
  9. package/src/lib/components/console/pos/pos-tender-dialogs.component.d.ts +2 -0
  10. package/src/lib/components/console/pos/pos-tender-dialogs.component.js +13 -6
  11. package/src/lib/components/console/pos/pos-tender-dialogs.component.js.map +1 -1
  12. package/src/lib/components/console/pos/pos-tender-panel.component.js +7 -4
  13. package/src/lib/components/console/pos/pos-tender-panel.component.js.map +1 -1
  14. package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
  15. package/src/lib/components/console/product-add-ons-fields.component.js +96 -3
  16. package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
  17. package/src/lib/components/console/product-builder-fields.component.d.ts +39 -0
  18. package/src/lib/components/console/product-builder-fields.component.js +195 -0
  19. package/src/lib/components/console/product-builder-fields.component.js.map +1 -0
  20. package/src/lib/components/console/product-editor-dialog.component.js +35 -2
  21. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  22. package/src/lib/components/console/quote-editor-dialog.component.js +43 -6
  23. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
  24. package/src/lib/components/console/quote-messages.component.d.ts +21 -0
  25. package/src/lib/components/console/quote-messages.component.js +185 -0
  26. package/src/lib/components/console/quote-messages.component.js.map +1 -0
  27. package/src/lib/components/console/quote-pay-link.component.js +1 -1
  28. package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
  29. package/src/lib/components/console/quote-proofs.component.js +30 -3
  30. package/src/lib/components/console/quote-proofs.component.js.map +1 -1
  31. package/src/lib/components/console/quote-settings-card.component.d.ts +7 -3
  32. package/src/lib/components/console/quote-settings-card.component.js +154 -24
  33. package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
  34. package/src/lib/components/product-builder-context.d.ts +22 -0
  35. package/src/lib/components/product-builder-context.js +21 -0
  36. package/src/lib/components/product-builder-context.js.map +1 -0
  37. package/src/lib/components/product-builder-mockup.d.ts +42 -0
  38. package/src/lib/components/product-builder-mockup.js +120 -0
  39. package/src/lib/components/product-builder-mockup.js.map +1 -0
  40. package/src/lib/components/product-builder-sample.d.ts +63 -0
  41. package/src/lib/components/product-builder-sample.js +96 -0
  42. package/src/lib/components/product-builder-sample.js.map +1 -0
  43. package/src/lib/components/product-choice-cards.d.ts +51 -0
  44. package/src/lib/components/product-choice-cards.js +311 -0
  45. package/src/lib/components/product-choice-cards.js.map +1 -0
  46. package/src/lib/components/product-detail-panels.d.ts +42 -0
  47. package/src/lib/components/product-detail-panels.js +185 -0
  48. package/src/lib/components/product-detail-panels.js.map +1 -0
  49. package/src/lib/components/product-detail.d.ts +20 -12
  50. package/src/lib/components/product-detail.js +136 -221
  51. package/src/lib/components/product-detail.js.map +1 -1
  52. package/src/lib/components/product-grid.d.ts +7 -0
  53. package/src/lib/components/product-grid.js +11 -8
  54. package/src/lib/components/product-grid.js.map +1 -1
  55. package/src/lib/components/product-options-field-body.d.ts +9 -8
  56. package/src/lib/components/product-options-field-body.js +152 -3
  57. package/src/lib/components/product-options-field-body.js.map +1 -1
  58. package/src/lib/components/product-options-field.js +1 -1
  59. package/src/lib/components/product-options-field.js.map +1 -1
  60. package/src/lib/components/product-photo-fit.d.ts +49 -0
  61. package/src/lib/components/product-photo-fit.js +58 -0
  62. package/src/lib/components/product-photo-fit.js.map +1 -0
  63. package/src/lib/components/product-restock-notify.d.ts +12 -0
  64. package/src/lib/components/product-restock-notify.js +86 -0
  65. package/src/lib/components/product-restock-notify.js.map +1 -0
  66. package/src/lib/components/quote-messages-panel.d.ts +21 -0
  67. package/src/lib/components/quote-messages-panel.js +191 -0
  68. package/src/lib/components/quote-messages-panel.js.map +1 -0
  69. package/src/lib/components/quote-page-body.js +15 -1
  70. package/src/lib/components/quote-page-body.js.map +1 -1
  71. package/src/lib/components/quote-proof-panel.d.ts +6 -3
  72. package/src/lib/components/quote-proof-panel.js +139 -14
  73. package/src/lib/components/quote-proof-panel.js.map +1 -1
  74. package/src/lib/components/related-products.d.ts +7 -0
  75. package/src/lib/components/related-products.js +8 -6
  76. package/src/lib/components/related-products.js.map +1 -1
  77. package/src/lib/constants/quote-page.d.ts +8 -0
  78. package/src/lib/constants/quote-page.js +11 -0
  79. package/src/lib/constants/quote-page.js.map +1 -1
  80. package/src/lib/model/commerce-cart.d.ts +6 -1
  81. package/src/lib/model/commerce-cart.js +5 -1
  82. package/src/lib/model/commerce-cart.js.map +1 -1
  83. package/src/lib/model/commerce-invoices.js +5 -1
  84. package/src/lib/model/commerce-invoices.js.map +1 -1
  85. package/src/lib/model/commerce-pos-ops.d.ts +3 -0
  86. package/src/lib/model/commerce-pos-ops.js +3 -0
  87. package/src/lib/model/commerce-pos-ops.js.map +1 -1
  88. package/src/lib/model/commerce-pos.d.ts +8 -0
  89. package/src/lib/model/commerce-pos.js.map +1 -1
  90. package/src/lib/model/commerce-quote-messages.d.ts +106 -0
  91. package/src/lib/model/commerce-quote-messages.js +146 -0
  92. package/src/lib/model/commerce-quote-messages.js.map +1 -0
  93. package/src/lib/model/commerce-quote-pay.d.ts +31 -2
  94. package/src/lib/model/commerce-quote-pay.js +31 -7
  95. package/src/lib/model/commerce-quote-pay.js.map +1 -1
  96. package/src/lib/model/commerce-quote-proofs.d.ts +47 -8
  97. package/src/lib/model/commerce-quote-proofs.js +73 -18
  98. package/src/lib/model/commerce-quote-proofs.js.map +1 -1
  99. package/src/lib/model/commerce-quote-request.d.ts +14 -4
  100. package/src/lib/model/commerce-quote-request.js +25 -2
  101. package/src/lib/model/commerce-quote-request.js.map +1 -1
  102. package/src/lib/model/commerce-quotes.d.ts +56 -3
  103. package/src/lib/model/commerce-quotes.js +47 -2
  104. package/src/lib/model/commerce-quotes.js.map +1 -1
  105. package/src/lib/model/commerce.d.ts +12 -1
  106. package/src/lib/model/commerce.js.map +1 -1
  107. package/src/lib/model/index.d.ts +1 -0
  108. package/src/lib/model/index.js +1 -0
  109. package/src/lib/model/index.js.map +1 -1
  110. package/src/lib/model/pos-cellular.d.ts +5 -0
  111. package/src/lib/model/pos-cellular.js.map +1 -1
  112. package/src/lib/model/product-card-rules.d.ts +41 -0
  113. package/src/lib/model/product-card-rules.js +90 -0
  114. package/src/lib/model/product-card-rules.js.map +1 -0
  115. package/src/lib/model/product-modifiers.d.ts +11 -0
  116. package/src/lib/model/product-modifiers.js +10 -0
  117. package/src/lib/model/product-modifiers.js.map +1 -1
  118. package/src/lib/model/product-write.d.ts +3 -0
  119. package/src/lib/server/billing-webhook.js +6 -2
  120. package/src/lib/server/billing-webhook.js.map +1 -1
  121. package/src/lib/server/cancel-order.js +15 -0
  122. package/src/lib/server/cancel-order.js.map +1 -1
  123. package/src/lib/server/channel-order-updates.js +15 -1
  124. package/src/lib/server/channel-order-updates.js.map +1 -1
  125. package/src/lib/server/channel-orders.js +20 -0
  126. package/src/lib/server/channel-orders.js.map +1 -1
  127. package/src/lib/server/checkout.js +1 -1
  128. package/src/lib/server/checkout.js.map +1 -1
  129. package/src/lib/server/local-fulfillment.js +1 -1
  130. package/src/lib/server/local-fulfillment.js.map +1 -1
  131. package/src/lib/server/pos-cellular-billing.d.ts +1 -1
  132. package/src/lib/server/pos-cellular-billing.js +2 -1
  133. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  134. package/src/lib/server/pos-cellular.d.ts +3 -1
  135. package/src/lib/server/pos-cellular.js +15 -8
  136. package/src/lib/server/pos-cellular.js.map +1 -1
  137. package/src/lib/server/pos-offline-sync.d.ts +3 -3
  138. package/src/lib/server/pos-offline-sync.js +17 -4
  139. package/src/lib/server/pos-offline-sync.js.map +1 -1
  140. package/src/lib/server/pos-order.js +17 -6
  141. package/src/lib/server/pos-order.js.map +1 -1
  142. package/src/lib/server/pos-payment.js +27 -11
  143. package/src/lib/server/pos-payment.js.map +1 -1
  144. package/src/lib/server/pos-reader-splash.js +10 -5
  145. package/src/lib/server/pos-reader-splash.js.map +1 -1
  146. package/src/lib/server/pos-readers.js +34 -10
  147. package/src/lib/server/pos-readers.js.map +1 -1
  148. package/src/lib/server/pos-return.js +19 -3
  149. package/src/lib/server/pos-return.js.map +1 -1
  150. package/src/lib/server/pos-stripe.d.ts +14 -0
  151. package/src/lib/server/pos-stripe.js +6 -2
  152. package/src/lib/server/pos-stripe.js.map +1 -1
  153. package/src/lib/server/pos-terminal-connection-token.js +23 -9
  154. package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
  155. package/src/lib/server/pos-terminal.d.ts +80 -14
  156. package/src/lib/server/pos-terminal.js +393 -123
  157. package/src/lib/server/pos-terminal.js.map +1 -1
  158. package/src/lib/server/product-drafts.d.ts +1 -1
  159. package/src/lib/server/product-drafts.js +4 -3
  160. package/src/lib/server/product-drafts.js.map +1 -1
  161. package/src/lib/server/product-writer.js +5 -4
  162. package/src/lib/server/product-writer.js.map +1 -1
  163. package/src/lib/server/product.d.ts +11 -0
  164. package/src/lib/server/product.js +18 -3
  165. package/src/lib/server/product.js.map +1 -1
  166. package/src/lib/server/products-write.js +4 -3
  167. package/src/lib/server/products-write.js.map +1 -1
  168. package/src/lib/server/quote-email.d.ts +26 -0
  169. package/src/lib/server/quote-email.js +73 -7
  170. package/src/lib/server/quote-email.js.map +1 -1
  171. package/src/lib/server/quote-messages.d.ts +72 -0
  172. package/src/lib/server/quote-messages.js +356 -0
  173. package/src/lib/server/quote-messages.js.map +1 -0
  174. package/src/lib/server/quote-pay.d.ts +42 -0
  175. package/src/lib/server/quote-pay.js +81 -4
  176. package/src/lib/server/quote-pay.js.map +1 -1
  177. package/src/lib/server/quote-proofs.d.ts +1 -1
  178. package/src/lib/server/quote-proofs.js +63 -19
  179. package/src/lib/server/quote-proofs.js.map +1 -1
  180. package/src/lib/server/quote.d.ts +12 -0
  181. package/src/lib/server/quote.js +44 -14
  182. package/src/lib/server/quote.js.map +1 -1
  183. package/src/lib/server/refund.js +3 -1
  184. package/src/lib/server/refund.js.map +1 -1
  185. package/src/lib/server/reserve-stock.js +9 -0
  186. package/src/lib/server/reserve-stock.js.map +1 -1
  187. package/src/lib/server/returns.js +15 -1
  188. package/src/lib/server/returns.js.map +1 -1
  189. package/src/lib/server/reviews.js +15 -0
  190. package/src/lib/server/reviews.js.map +1 -1
  191. package/src/lib/server/sold-out-drop.d.ts +58 -0
  192. package/src/lib/server/sold-out-drop.js +81 -0
  193. package/src/lib/server/sold-out-drop.js.map +1 -0
  194. package/src/lib/server/stock-levels.js +9 -0
  195. package/src/lib/server/stock-levels.js.map +1 -1
  196. package/src/lib/server/stripe-refund.d.ts +7 -0
  197. package/src/lib/server/stripe-refund.js +26 -7
  198. package/src/lib/server/stripe-refund.js.map +1 -1
  199. package/src/lib/server.js +2 -0
  200. package/src/lib/server.js.map +1 -1
  201. package/src/lib/tenant-emails.js +85 -2
  202. package/src/lib/tenant-emails.js.map +1 -1
  203. package/src/lib/testing/fake-seller-payment-account.d.ts +29 -0
  204. package/src/lib/testing/fake-seller-payment-account.js +40 -0
  205. package/src/lib/testing/fake-seller-payment-account.js.map +1 -0
  206. package/src/lib/transfer/product-transfer.js +6 -5
  207. package/src/lib/transfer/product-transfer.js.map +1 -1
  208. package/src/lib/transfer/products.server.js +4 -3
  209. package/src/lib/transfer/products.server.js.map +1 -1
  210. package/src/lib/utils/quote-email-content.d.ts +6 -0
  211. package/src/lib/utils/quote-email-content.js +6 -3
  212. package/src/lib/utils/quote-email-content.js.map +1 -1
@@ -23,6 +23,7 @@ import { notifyOrderBuyer } from "./order-notifications.js";
23
23
  import { ORDER_CANCELLED_EVENT } from "../model/order-events.js";
24
24
  import { raiseOrderEvent } from "./order-events.js";
25
25
  import { capRestockLines, resolveTrackedRestockLines, saleReleaseCaps } from "./restock-flag.js";
26
+ import { dropStorefrontPages, soldOutMoved } from "./sold-out-drop.js";
26
27
  /**
27
28
  * Cancelling an order RELEASES its stock (AGL-1808) — the opposite of what the
28
29
  * reversal doors do, and for a structural reason rather than a preference.
@@ -141,6 +142,10 @@ import { capRestockLines, resolveTrackedRestockLines, saleReleaseCaps } from "./
141
142
  });
142
143
  }
143
144
  const orderRef = hostRef.collection('orders').doc(orderId);
145
+ // Whether the restock below flipped a sold-out verdict the storefront
146
+ // shows (AGL-4121). Set inside the transaction; a retried attempt can only
147
+ // make it a spurious drop, never a missed one.
148
+ let soldOutFlipped = false;
144
149
  const outcome = await firestore.runTransaction(async (transaction)=>{
145
150
  var _snapshot_data, _order_checkoutSessionId;
146
151
  const snapshot = await transaction.get(orderRef);
@@ -284,6 +289,9 @@ import { capRestockLines, resolveTrackedRestockLines, saleReleaseCaps } from "./
284
289
  })), {
285
290
  updatedAtMs: atMs
286
291
  }));
292
+ soldOutFlipped || (soldOutFlipped = soldOutMoved(product, _extends({}, product, {
293
+ variants
294
+ })));
287
295
  for (const line of productLines){
288
296
  transaction.create(hostRef.collection('inventoryAdjustments').doc(), _extends({
289
297
  productId,
@@ -371,6 +379,13 @@ import { capRestockLines, resolveTrackedRestockLines, saleReleaseCaps } from "./
371
379
  });
372
380
  }
373
381
  }
382
+ // Back in stock on the storefront, if the release flipped it (AGL-4121).
383
+ if (soldOutFlipped && outcome.status === 200) {
384
+ await dropStorefrontPages({
385
+ hostId,
386
+ reason: 'a cancelled order restocked a product'
387
+ });
388
+ }
374
389
  // The buyer is told (AGL-3610) — only by the request that cancelled it.
375
390
  if (outcome.status === 200 && !outcome.body.alreadyCancelled) {
376
391
  await notifyOrderBuyer({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/cancel-order.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 { directSellerAccountForHost, fetchOnSellerThenPlatform } from './seller-stripe-account'\nimport { holdsCommerceSiteKey } from './commerce-site-keys'\nimport { commerceSitePermissionRefusal } from '../model/plugin-permissions'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { notifyOrderBuyer } from './order-notifications'\nimport { ORDER_CANCELLED_EVENT } from '../model/order-events'\nimport { raiseOrderEvent } from './order-events'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport {\n capRestockLines,\n resolveTrackedRestockLines,\n saleReleaseCaps,\n} from './restock-flag'\n\n/**\n * Cancelling an order RELEASES its stock (AGL-1808) — the opposite of what the\n * reversal doors do, and for a structural reason rather than a preference.\n *\n * AGL-1797 refused to increment on a refund or a chargeback because the goods\n * may well be gone: a refund with no return, or a shopper who kept the item and\n * took the money, leaves stock that incrementing would INVENT. It flags and\n * lets the merchant answer. Cancellation carries no such question, and the\n * guarantee is `ORDER_TRANSITIONS`:\n *\n * pending: ['paid', 'cancelled'],\n * paid: ['partially_fulfilled', 'fulfilled', 'cancelled', 'refunded'],\n * partially_fulfilled | fulfilled | delivered: no 'cancelled'\n *\n * so a cancelled order was never fulfilled and nothing ever shipped. The units\n * are still on the shelf; the only wrong number is ours.\n *\n * THE GUARANTEE HAD TO BE ENFORCED BEFORE IT COULD BE RELIED ON, and that is\n * why this is a handler rather than a few lines in the console. The transition\n * table said the right thing but nothing consulted it on the way IN: the order\n * dialog cancelled with a client `updateDoc`, and `canTransitionOrder` only\n * decided whether to render the button. The Firestore rules impose no status\n * machine — an order update is allowed to any admin or editor — so a dialog\n * held open while the order shipped in another tab (or any other client) could\n * write `cancelled` straight onto a `fulfilled` order, and an automatic\n * increment behind that would restock goods already in the post. Re-asking the\n * transition INSIDE the transaction that writes the status is what turns the\n * comment into a guarantee, and it is what makes the release safe.\n *\n * `pending` RELEASES NOTHING, which is the other half the issue's premise\n * missed. Stock is decremented when the money lands, not when the order is\n * written: `draft-order.ts` and the POS card path both open a `pending` order\n * and decrement only in the webhook that pays it. Incrementing on a cancelled\n * `pending` order would invent inventory exactly the way AGL-1797 refused to —\n * so only a `paid` order, the one status reachable here whose sale provably\n * decremented, releases anything.\n *\n * ONE LEDGER, NOT A SECOND STOCK WRITER. The increment goes through\n * `adjustVariantInventory` and logs an `InventoryAdjustment` per line, the same\n * pair the sale paths and the products hub's \"Adjust stock\" write, with the new\n * `cancellation` reason and the `orderId`. An increment with no ledger row\n * would leave the hub's stock history unable to explain a count that moved on\n * its own — the mirror of AGL-1797's argument against writing a row for stock\n * that had NOT moved.\n *\n * ONLY WHAT THE SALE DECREMENTED comes back: `resolveTrackedRestockLines`, the\n * helper AGL-1797 already built, applies the sale path's own\n * `variant.inventory != null` test to the products as they stand now. A store\n * that tracks no stock gets a plain cancellation and no adjustment rows.\n *\n * IT FAILS THE CANCEL RATHER THAN LOSING THE RELEASE. `flagOrderRestock`\n * swallows its errors because the money had already moved and the flag was a\n * postscript; here the status flip and the stock write are one act, so they\n * share a transaction and a failure leaves the order uncancelled for the\n * merchant to retry. A cancelled order whose stock never came back is the\n * original bug.\n *\n * ONCE. The transaction's own read is the guard: a second cancel — a retried\n * request, two admins clicking together — finds `cancelled`, which\n * `canTransitionOrder` cannot leave, and returns without touching stock. Two\n * increments of the same units is the failure mode this shape exists to\n * prevent, and it is measured rather than asserted (`cancel-order.spec.ts`).\n *\n * REACHED FROM THE CONSOLE since AGL-1818: `order-detail-dialog`'s\n * `handleCancel` POSTs here with the console id token, and the client\n * `updateDoc` cancel it replaced is gone. (The wiring landed separately from\n * the route because the dialog belonged to a concurrent agent, AGL-1806,\n * when the route was written.)\n */\nexport const cancelOrderHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const orderId = String(body.orderId ?? '')\n if (!hostId || !orderId) {\n return res.status(400).json({ error: 'Missing hostId or orderId' })\n }\n // Firestore reserves `__…__` ids and `.doc()` throws SYNCHRONOUSLY on one,\n // which would surface as a 500 on a caller's typo rather than the 400 it is.\n if (/^__.*__$/.test(hostId) || /^__.*__$/.test(orderId)) {\n return res.status(400).json({ error: 'Missing hostId or orderId' })\n }\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // The role the CLIENT write already had, not a stricter one. Order updates\n // fall through the rules' host catch-all, which admits `admin` and\n // `editor` — narrowing to admin here would take the cancel button away\n // from editors who have always had it, and widening it past what the rules\n // allow would make this endpoint the way around them.\n // \"Manage orders\" (`commerce.orders`, AGL-4047), whose preset is the site's Admin\n // and Editor this asked for, read as the rules would read it.\n if (!holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.orders')) {\n return res.status(403).json({ error: commerceSitePermissionRefusal('commerce.orders') })\n }\n const orderRef = hostRef.collection('orders').doc(orderId)\n\n const outcome = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(orderRef)\n if (!snapshot.exists) {\n return { status: 404, body: { error: 'Unknown order' } }\n }\n const order = CommerceModel.liftLegacyOrder(\n (snapshot.data() ?? {}) as never,\n )\n // A redelivered click, or the second of two admins. Answered as success\n // because it IS the state the caller asked for — reporting 409 here\n // teaches an admin that the cancel failed and invites a third attempt —\n // but nothing is written, so the units are released exactly once.\n if (order.status === 'cancelled') {\n return {\n status: 200,\n body: { ok: true, alreadyCancelled: true, released: 0, units: 0 },\n }\n }\n if (!CommerceModel.canTransitionOrder(order.status, 'cancelled')) {\n return {\n status: 409,\n body: { error: `Orders in \"${order.status}\" cannot cancel` },\n }\n }\n // An OPEN register sale that has taken money (AGL-3607) is voided at\n // the register, which hands each payment back first. Cancelling it here\n // would mark it cancelled with a card charge, a gift card debit or a\n // room charge still standing.\n if (\n order.status === 'pending' &&\n CommerceModel.orderPayments(order).some(\n (payment) => payment.status === 'succeeded' || payment.status === 'pending',\n ) &&\n Array.isArray(order.payments)\n ) {\n return {\n status: 409,\n body: {\n error:\n 'This register sale has payments on it. Void it at the register, ' +\n 'which hands each payment back first.',\n },\n }\n }\n\n // A POS CARD order's decrement happens in the webhook that pays it —\n // and before AGL-1825 it did not happen AT ALL: the paying branch's\n // decrement was gated on `productId` metadata the register's session\n // never carried. Releasing such an order restocks units that were never\n // taken, turning the silent under-count into a silent over-count. The\n // sale's own ledger is the discriminator: every decrement pairs with a\n // `reason: 'sale'` row (AGL-1807 closed the last hole, and the AGL-1825\n // decrement writes them from day one), so a paid card order with no\n // sale row is one whose sale took nothing — and nothing is released.\n //\n // Scoped to card orders (the `pos-card-pending` timeline event) rather\n // than applied to every order, because one historical path decremented\n // WITHOUT rows — draft links paid before AGL-1807 — and asking the\n // ledger to vouch for those would wrongly strand their stock. The\n // residual is stated plainly: the sibling-shaped decrement/ledger pair\n // is two swallowed sequential writes, so a card order whose ledger add\n // alone failed will not release — a bounded under-count on that one\n // order, visible as a sale missing from the hub's history, against the\n // alternative of inflating stock on every pre-fix cancel.\n //\n // One equality filter, so the automatic single-field index answers it;\n // the reason test runs here, over the handful of rows one order has.\n //\n // THE SAME READ NOW ALSO BOUNDS HOW MUCH COMES BACK (AGL-2149), so it is\n // no longer scoped to card orders. `adjustVariantInventory` floors at\n // zero, and that floor silently absorbs the overshoot on a BACKORDER\n // product: stock 0, `canPurchase` admits the sale because the policy says\n // to, three units sell, `Math.max(0, 0 + -3)` leaves the count at 0 —\n // and a `+3` here would hand the merchant three units nobody has and a\n // stock badge offering them. The sale rows carry `appliedDelta` for\n // exactly this: `delta` stays the units sold (the merchant's history),\n // `appliedDelta` says how many the count could actually give up.\n //\n // Only lines the ledger DESCRIBES are capped. A pair the ledger says\n // nothing about restores as before, which is what keeps the pre-AGL-1807\n // draft links — decremented with no row at all — from having their stock\n // stranded, and what keeps a single swallowed ledger write from turning\n // into a lost restock on an unrelated line of the same order.\n let saleDecremented = true\n // The cap rule itself lives beside the restock flag, which now bounds\n // the question it ASKS by the same ledger this bounds the stock it\n // RETURNS (AGL-2325). One implementation, so a prompt naming more units\n // than a cancellation would put back is not expressible.\n let releaseCap: ReadonlyMap<string, number> = new Map<string, number>()\n if (order.status === 'paid') {\n const orderAdjustments = await transaction.get(\n hostRef\n .collection('inventoryAdjustments')\n .where('orderId', '==', orderId),\n )\n const saleRows = orderAdjustments.docs.filter(\n (row) => row.get('reason') === 'sale',\n )\n if (\n order.channel === 'pos' &&\n (order.timeline ?? []).some(\n (event) => event.event === 'pos-card-pending',\n )\n ) {\n saleDecremented = saleRows.length > 0\n }\n releaseCap = saleReleaseCaps(saleRows)\n }\n\n // `paid` is the only status reachable here whose sale decremented; see\n // the header. Reads happen before any write, as a transaction requires.\n const { lines, products } =\n order.status === 'paid' && saleDecremented\n ? await resolveTrackedRestockLines(hostRef, order, (ref) =>\n transaction.get(ref),\n )\n : {\n lines: [],\n products: new Map<string, CommerceModel.HostProduct>(),\n }\n\n const atMs = Date.now()\n // Grouped by product, because two lines of one product (two variants, or\n // the same variant twice) are two deltas against ONE document: writing\n // them separately would compute both from the same read and land only\n // the last, silently dropping units.\n const byProduct = new Map<string, CommerceModel.OrderRestockLine[]>()\n // Never more than the sale actually took off the shelf (AGL-2149).\n for (const line of capRestockLines(lines, releaseCap)) {\n byProduct.set(line.productId, [\n ...(byProduct.get(line.productId) ?? []),\n line,\n ])\n }\n for (const [productId, productLines] of byProduct) {\n const product = products.get(productId)\n if (!product) continue\n let variants = product.variants\n for (const line of productLines) {\n variants = CommerceModel.adjustVariantInventory(\n { variants },\n line.variantId,\n line.quantity,\n // The bucket the sale came out of, for a location-tracked store\n // (AGL-286). Absent on every path that decremented the flat count,\n // where `adjustVariantInventory` puts it back the same way.\n order.locationId || undefined,\n )\n }\n // `update()`, not `set(…, { merge: true })` as the sale paths use: the\n // transaction has just read this product, so it exists, and a product\n // deleted under us must not be conjured back as a stub holding nothing\n // but a variants array.\n transaction.update(hostRef.collection('products').doc(productId), {\n variants,\n // The total and the storefront's In stock verdict (AGL-3321).\n ...CommerceModel.productStockFields({ ...product, variants }),\n updatedAtMs: atMs,\n })\n for (const line of productLines) {\n transaction.create(hostRef.collection('inventoryAdjustments').doc(), {\n productId,\n variantId: line.variantId,\n delta: line.quantity,\n reason: 'cancellation',\n orderId,\n ...(order.locationId ? { locationId: order.locationId } : {}),\n atMs,\n } satisfies CommerceModel.InventoryAdjustment)\n }\n }\n\n // From the CAPPED lines, not the order's, so the timeline reports what\n // was actually put back (AGL-2149).\n const releasedLines = [...byProduct.values()].flat()\n const units = releasedLines.reduce((sum, line) => sum + line.quantity, 0)\n const patch: Record<string, unknown> = {\n status: 'cancelled',\n // What a shipping tool's feed asks to learn of the cancel (AGL-3613).\n updatedAtMs: atMs,\n timeline: CommerceModel.appendOrderEvent(\n order,\n 'cancelled',\n units > 0\n ? `${units} ${units === 1 ? 'unit' : 'units'} returned to stock`\n : undefined,\n atMs,\n ),\n }\n // An open restock question about THIS order's stock, raised by a partial\n // refund before the cancellation (AGL-1797). The units it asked about are\n // the ones just put back, so leaving it open would invite the merchant to\n // restock them a second time from the order dialog — the double-count\n // that flag exists to avoid. Answered with what actually happened.\n if (units > 0 && order.restockCheck && !order.restockCheck.resolution) {\n patch.restockCheck = {\n ...order.restockCheck,\n resolution: 'restocked',\n resolvedAtMs: atMs,\n resolvedBy: decoded.uid,\n } satisfies CommerceModel.OrderRestockCheck\n }\n transaction.update(orderRef, patch)\n return {\n status: 200,\n body: { ok: true, released: releasedLines.length, units },\n // The live Stripe page this cancellation orphans, if any (AGL-2244).\n // Read inside the transaction that flips the status so the expiry\n // below cannot act on an order some other writer paid meanwhile.\n expireSessionId:\n order.status === 'pending' ? (order.checkoutSessionId ?? '') : '',\n }\n })\n // EXPIRE THE PAYMENT LINK (AGL-2244). Cancelling a `pending` draft order or\n // POS card sale left its Checkout Session live: the URL is on the\n // customer's phone or in the email the merchant sent, and Stripe keeps it\n // payable for 24 hours. Paying it captured real money on the merchant's\n // account and the completing webhook then discarded the event — its\n // `status !== 'pending'` guard cannot tell a redelivery from a cancelled\n // order — so the sale existed in Stripe and nowhere in the product: no\n // order, no stock move, no contact, no notification, not even a timeline\n // line. The webhook now says so when it happens; this is the half that\n // stops it happening.\n //\n // OUTSIDE the transaction, because it is a network call, and best-effort\n // by design: the cancellation itself already landed and is what the\n // merchant asked for. A failure here leaves the pre-existing behaviour\n // (a payable link) plus the webhook's new record of it, which is strictly\n // better than failing a cancel that has already released stock. Stripe\n // answers 400 for a session that is already expired or already paid, and\n // both are states this has nothing to add to.\n const expireSessionId = (outcome as { expireSessionId?: string })\n .expireSessionId\n if (expireSessionId && process.env.STRIPE_SECRET_KEY) {\n const expiry = await fetchOnSellerThenPlatform(\n `https://api.stripe.com/v1/checkout/sessions/${expireSessionId}/expire`,\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n },\n await directSellerAccountForHost(hostId),\n ).catch(() => null)\n if (!expiry?.ok) {\n console.error(\n 'Cancelled order: Stripe session not expired, the payment link may still be payable',\n { hostId, orderId, sessionId: expireSessionId },\n )\n }\n }\n // The buyer is told (AGL-3610) — only by the request that cancelled it.\n if (outcome.status === 200 && !(outcome.body as { alreadyCancelled?: boolean }).alreadyCancelled) {\n await notifyOrderBuyer({ hostId, orderId }, 'cancelled')\n await raiseOrderEvent(ORDER_CANCELLED_EVENT, { hostId, orderId, key: 'cancelled' })\n }\n return res.status(outcome.status).json(outcome.body)\n } catch (error) {\n // Nothing landed — the transaction is all-or-nothing — so the order is\n // still open and the merchant can try again. Deliberately NOT the swallow\n // `flagOrderRestock` uses: there the money had already moved and only a\n // postscript was at risk; here a swallowed failure is a cancelled order\n // whose stock never came back, which is the bug this closes.\n console.error('cancelOrder failed', error)\n return res.status(500).json({ error: 'Cancel failed' })\n }\n}\n"],"names":["directSellerAccountForHost","fetchOnSellerThenPlatform","holdsCommerceSiteKey","commerceSitePermissionRefusal","CommerceModel","firebaseAdmin","notifyOrderBuyer","ORDER_CANCELLED_EVENT","raiseOrderEvent","capRestockLines","resolveTrackedRestockLines","saleReleaseCaps","cancelOrderHandler","req","res","body","method","status","json","error","authorization","String","headers","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","orderId","test","decoded","app","auth","verifyIdToken","firestore","hostRef","collection","doc","hostSnapshot","get","exists","uid","orderRef","outcome","runTransaction","transaction","snapshot","order","liftLegacyOrder","data","ok","alreadyCancelled","released","units","canTransitionOrder","orderPayments","some","payment","Array","isArray","payments","saleDecremented","releaseCap","Map","orderAdjustments","where","saleRows","docs","filter","row","channel","timeline","event","lines","products","ref","atMs","Date","now","byProduct","line","set","productId","productLines","product","variants","adjustVariantInventory","variantId","quantity","locationId","update","productStockFields","updatedAtMs","create","delta","reason","releasedLines","values","flat","reduce","sum","patch","appendOrderEvent","restockCheck","resolution","resolvedAtMs","resolvedBy","expireSessionId","checkoutSessionId","process","env","STRIPE_SECRET_KEY","expiry","Authorization","catch","console","sessionId","key"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,0BAA0B,EAAEC,yBAAyB,QAAQ,6BAAyB;AAC/F,SA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AAE;gBACfiE,QAAQnG,KAAK,CACX,sFACA;oBAAEW;oBAAQC;oBAASwF,WAAWT;gBAAgB;YAElD;QACF;QACA,wEAAwE;QACxE,IAAIhE,QAAQ7B,MAAM,KAAK,OAAO,CAAC,AAAC6B,QAAQ/B,IAAI,CAAoCuC,gBAAgB,EAAE;YAChG,MAAMhD,iBAAiB;gBAAEwB;gBAAQC;YAAQ,GAAG;YAC5C,MAAMvB,gBAAgBD,uBAAuB;gBAAEuB;gBAAQC;gBAASyF,KAAK;YAAY;QACnF;QACA,OAAO1G,IAAIG,MAAM,CAAC6B,QAAQ7B,MAAM,EAAEC,IAAI,CAAC4B,QAAQ/B,IAAI;IACrD,EAAE,OAAOI,OAAO;QACd,uEAAuE;QACvE,0EAA0E;QAC1E,wEAAwE;QACxE,wEAAwE;QACxE,6DAA6D;QAC7DmG,QAAQnG,KAAK,CAAC,sBAAsBA;QACpC,OAAOL,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAgB;IACvD;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/cancel-order.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 { directSellerAccountForHost, fetchOnSellerThenPlatform } from './seller-stripe-account'\nimport { holdsCommerceSiteKey } from './commerce-site-keys'\nimport { commerceSitePermissionRefusal } from '../model/plugin-permissions'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { notifyOrderBuyer } from './order-notifications'\nimport { ORDER_CANCELLED_EVENT } from '../model/order-events'\nimport { raiseOrderEvent } from './order-events'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport {\n capRestockLines,\n resolveTrackedRestockLines,\n saleReleaseCaps,\n} from './restock-flag'\nimport { dropStorefrontPages, soldOutMoved } from './sold-out-drop'\n\n/**\n * Cancelling an order RELEASES its stock (AGL-1808) — the opposite of what the\n * reversal doors do, and for a structural reason rather than a preference.\n *\n * AGL-1797 refused to increment on a refund or a chargeback because the goods\n * may well be gone: a refund with no return, or a shopper who kept the item and\n * took the money, leaves stock that incrementing would INVENT. It flags and\n * lets the merchant answer. Cancellation carries no such question, and the\n * guarantee is `ORDER_TRANSITIONS`:\n *\n * pending: ['paid', 'cancelled'],\n * paid: ['partially_fulfilled', 'fulfilled', 'cancelled', 'refunded'],\n * partially_fulfilled | fulfilled | delivered: no 'cancelled'\n *\n * so a cancelled order was never fulfilled and nothing ever shipped. The units\n * are still on the shelf; the only wrong number is ours.\n *\n * THE GUARANTEE HAD TO BE ENFORCED BEFORE IT COULD BE RELIED ON, and that is\n * why this is a handler rather than a few lines in the console. The transition\n * table said the right thing but nothing consulted it on the way IN: the order\n * dialog cancelled with a client `updateDoc`, and `canTransitionOrder` only\n * decided whether to render the button. The Firestore rules impose no status\n * machine — an order update is allowed to any admin or editor — so a dialog\n * held open while the order shipped in another tab (or any other client) could\n * write `cancelled` straight onto a `fulfilled` order, and an automatic\n * increment behind that would restock goods already in the post. Re-asking the\n * transition INSIDE the transaction that writes the status is what turns the\n * comment into a guarantee, and it is what makes the release safe.\n *\n * `pending` RELEASES NOTHING, which is the other half the issue's premise\n * missed. Stock is decremented when the money lands, not when the order is\n * written: `draft-order.ts` and the POS card path both open a `pending` order\n * and decrement only in the webhook that pays it. Incrementing on a cancelled\n * `pending` order would invent inventory exactly the way AGL-1797 refused to —\n * so only a `paid` order, the one status reachable here whose sale provably\n * decremented, releases anything.\n *\n * ONE LEDGER, NOT A SECOND STOCK WRITER. The increment goes through\n * `adjustVariantInventory` and logs an `InventoryAdjustment` per line, the same\n * pair the sale paths and the products hub's \"Adjust stock\" write, with the new\n * `cancellation` reason and the `orderId`. An increment with no ledger row\n * would leave the hub's stock history unable to explain a count that moved on\n * its own — the mirror of AGL-1797's argument against writing a row for stock\n * that had NOT moved.\n *\n * ONLY WHAT THE SALE DECREMENTED comes back: `resolveTrackedRestockLines`, the\n * helper AGL-1797 already built, applies the sale path's own\n * `variant.inventory != null` test to the products as they stand now. A store\n * that tracks no stock gets a plain cancellation and no adjustment rows.\n *\n * IT FAILS THE CANCEL RATHER THAN LOSING THE RELEASE. `flagOrderRestock`\n * swallows its errors because the money had already moved and the flag was a\n * postscript; here the status flip and the stock write are one act, so they\n * share a transaction and a failure leaves the order uncancelled for the\n * merchant to retry. A cancelled order whose stock never came back is the\n * original bug.\n *\n * ONCE. The transaction's own read is the guard: a second cancel — a retried\n * request, two admins clicking together — finds `cancelled`, which\n * `canTransitionOrder` cannot leave, and returns without touching stock. Two\n * increments of the same units is the failure mode this shape exists to\n * prevent, and it is measured rather than asserted (`cancel-order.spec.ts`).\n *\n * REACHED FROM THE CONSOLE since AGL-1818: `order-detail-dialog`'s\n * `handleCancel` POSTs here with the console id token, and the client\n * `updateDoc` cancel it replaced is gone. (The wiring landed separately from\n * the route because the dialog belonged to a concurrent agent, AGL-1806,\n * when the route was written.)\n */\nexport const cancelOrderHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const orderId = String(body.orderId ?? '')\n if (!hostId || !orderId) {\n return res.status(400).json({ error: 'Missing hostId or orderId' })\n }\n // Firestore reserves `__…__` ids and `.doc()` throws SYNCHRONOUSLY on one,\n // which would surface as a 500 on a caller's typo rather than the 400 it is.\n if (/^__.*__$/.test(hostId) || /^__.*__$/.test(orderId)) {\n return res.status(400).json({ error: 'Missing hostId or orderId' })\n }\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // The role the CLIENT write already had, not a stricter one. Order updates\n // fall through the rules' host catch-all, which admits `admin` and\n // `editor` — narrowing to admin here would take the cancel button away\n // from editors who have always had it, and widening it past what the rules\n // allow would make this endpoint the way around them.\n // \"Manage orders\" (`commerce.orders`, AGL-4047), whose preset is the site's Admin\n // and Editor this asked for, read as the rules would read it.\n if (!holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.orders')) {\n return res.status(403).json({ error: commerceSitePermissionRefusal('commerce.orders') })\n }\n const orderRef = hostRef.collection('orders').doc(orderId)\n\n // Whether the restock below flipped a sold-out verdict the storefront\n // shows (AGL-4121). Set inside the transaction; a retried attempt can only\n // make it a spurious drop, never a missed one.\n let soldOutFlipped = false\n const outcome = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(orderRef)\n if (!snapshot.exists) {\n return { status: 404, body: { error: 'Unknown order' } }\n }\n const order = CommerceModel.liftLegacyOrder(\n (snapshot.data() ?? {}) as never,\n )\n // A redelivered click, or the second of two admins. Answered as success\n // because it IS the state the caller asked for — reporting 409 here\n // teaches an admin that the cancel failed and invites a third attempt —\n // but nothing is written, so the units are released exactly once.\n if (order.status === 'cancelled') {\n return {\n status: 200,\n body: { ok: true, alreadyCancelled: true, released: 0, units: 0 },\n }\n }\n if (!CommerceModel.canTransitionOrder(order.status, 'cancelled')) {\n return {\n status: 409,\n body: { error: `Orders in \"${order.status}\" cannot cancel` },\n }\n }\n // An OPEN register sale that has taken money (AGL-3607) is voided at\n // the register, which hands each payment back first. Cancelling it here\n // would mark it cancelled with a card charge, a gift card debit or a\n // room charge still standing.\n if (\n order.status === 'pending' &&\n CommerceModel.orderPayments(order).some(\n (payment) => payment.status === 'succeeded' || payment.status === 'pending',\n ) &&\n Array.isArray(order.payments)\n ) {\n return {\n status: 409,\n body: {\n error:\n 'This register sale has payments on it. Void it at the register, ' +\n 'which hands each payment back first.',\n },\n }\n }\n\n // A POS CARD order's decrement happens in the webhook that pays it —\n // and before AGL-1825 it did not happen AT ALL: the paying branch's\n // decrement was gated on `productId` metadata the register's session\n // never carried. Releasing such an order restocks units that were never\n // taken, turning the silent under-count into a silent over-count. The\n // sale's own ledger is the discriminator: every decrement pairs with a\n // `reason: 'sale'` row (AGL-1807 closed the last hole, and the AGL-1825\n // decrement writes them from day one), so a paid card order with no\n // sale row is one whose sale took nothing — and nothing is released.\n //\n // Scoped to card orders (the `pos-card-pending` timeline event) rather\n // than applied to every order, because one historical path decremented\n // WITHOUT rows — draft links paid before AGL-1807 — and asking the\n // ledger to vouch for those would wrongly strand their stock. The\n // residual is stated plainly: the sibling-shaped decrement/ledger pair\n // is two swallowed sequential writes, so a card order whose ledger add\n // alone failed will not release — a bounded under-count on that one\n // order, visible as a sale missing from the hub's history, against the\n // alternative of inflating stock on every pre-fix cancel.\n //\n // One equality filter, so the automatic single-field index answers it;\n // the reason test runs here, over the handful of rows one order has.\n //\n // THE SAME READ NOW ALSO BOUNDS HOW MUCH COMES BACK (AGL-2149), so it is\n // no longer scoped to card orders. `adjustVariantInventory` floors at\n // zero, and that floor silently absorbs the overshoot on a BACKORDER\n // product: stock 0, `canPurchase` admits the sale because the policy says\n // to, three units sell, `Math.max(0, 0 + -3)` leaves the count at 0 —\n // and a `+3` here would hand the merchant three units nobody has and a\n // stock badge offering them. The sale rows carry `appliedDelta` for\n // exactly this: `delta` stays the units sold (the merchant's history),\n // `appliedDelta` says how many the count could actually give up.\n //\n // Only lines the ledger DESCRIBES are capped. A pair the ledger says\n // nothing about restores as before, which is what keeps the pre-AGL-1807\n // draft links — decremented with no row at all — from having their stock\n // stranded, and what keeps a single swallowed ledger write from turning\n // into a lost restock on an unrelated line of the same order.\n let saleDecremented = true\n // The cap rule itself lives beside the restock flag, which now bounds\n // the question it ASKS by the same ledger this bounds the stock it\n // RETURNS (AGL-2325). One implementation, so a prompt naming more units\n // than a cancellation would put back is not expressible.\n let releaseCap: ReadonlyMap<string, number> = new Map<string, number>()\n if (order.status === 'paid') {\n const orderAdjustments = await transaction.get(\n hostRef\n .collection('inventoryAdjustments')\n .where('orderId', '==', orderId),\n )\n const saleRows = orderAdjustments.docs.filter(\n (row) => row.get('reason') === 'sale',\n )\n if (\n order.channel === 'pos' &&\n (order.timeline ?? []).some(\n (event) => event.event === 'pos-card-pending',\n )\n ) {\n saleDecremented = saleRows.length > 0\n }\n releaseCap = saleReleaseCaps(saleRows)\n }\n\n // `paid` is the only status reachable here whose sale decremented; see\n // the header. Reads happen before any write, as a transaction requires.\n const { lines, products } =\n order.status === 'paid' && saleDecremented\n ? await resolveTrackedRestockLines(hostRef, order, (ref) =>\n transaction.get(ref),\n )\n : {\n lines: [],\n products: new Map<string, CommerceModel.HostProduct>(),\n }\n\n const atMs = Date.now()\n // Grouped by product, because two lines of one product (two variants, or\n // the same variant twice) are two deltas against ONE document: writing\n // them separately would compute both from the same read and land only\n // the last, silently dropping units.\n const byProduct = new Map<string, CommerceModel.OrderRestockLine[]>()\n // Never more than the sale actually took off the shelf (AGL-2149).\n for (const line of capRestockLines(lines, releaseCap)) {\n byProduct.set(line.productId, [\n ...(byProduct.get(line.productId) ?? []),\n line,\n ])\n }\n for (const [productId, productLines] of byProduct) {\n const product = products.get(productId)\n if (!product) continue\n let variants = product.variants\n for (const line of productLines) {\n variants = CommerceModel.adjustVariantInventory(\n { variants },\n line.variantId,\n line.quantity,\n // The bucket the sale came out of, for a location-tracked store\n // (AGL-286). Absent on every path that decremented the flat count,\n // where `adjustVariantInventory` puts it back the same way.\n order.locationId || undefined,\n )\n }\n // `update()`, not `set(…, { merge: true })` as the sale paths use: the\n // transaction has just read this product, so it exists, and a product\n // deleted under us must not be conjured back as a stub holding nothing\n // but a variants array.\n transaction.update(hostRef.collection('products').doc(productId), {\n variants,\n // The total and the storefront's In stock verdict (AGL-3321).\n ...CommerceModel.productStockFields({ ...product, variants }),\n updatedAtMs: atMs,\n })\n soldOutFlipped ||= soldOutMoved(product, { ...product, variants })\n for (const line of productLines) {\n transaction.create(hostRef.collection('inventoryAdjustments').doc(), {\n productId,\n variantId: line.variantId,\n delta: line.quantity,\n reason: 'cancellation',\n orderId,\n ...(order.locationId ? { locationId: order.locationId } : {}),\n atMs,\n } satisfies CommerceModel.InventoryAdjustment)\n }\n }\n\n // From the CAPPED lines, not the order's, so the timeline reports what\n // was actually put back (AGL-2149).\n const releasedLines = [...byProduct.values()].flat()\n const units = releasedLines.reduce((sum, line) => sum + line.quantity, 0)\n const patch: Record<string, unknown> = {\n status: 'cancelled',\n // What a shipping tool's feed asks to learn of the cancel (AGL-3613).\n updatedAtMs: atMs,\n timeline: CommerceModel.appendOrderEvent(\n order,\n 'cancelled',\n units > 0\n ? `${units} ${units === 1 ? 'unit' : 'units'} returned to stock`\n : undefined,\n atMs,\n ),\n }\n // An open restock question about THIS order's stock, raised by a partial\n // refund before the cancellation (AGL-1797). The units it asked about are\n // the ones just put back, so leaving it open would invite the merchant to\n // restock them a second time from the order dialog — the double-count\n // that flag exists to avoid. Answered with what actually happened.\n if (units > 0 && order.restockCheck && !order.restockCheck.resolution) {\n patch.restockCheck = {\n ...order.restockCheck,\n resolution: 'restocked',\n resolvedAtMs: atMs,\n resolvedBy: decoded.uid,\n } satisfies CommerceModel.OrderRestockCheck\n }\n transaction.update(orderRef, patch)\n return {\n status: 200,\n body: { ok: true, released: releasedLines.length, units },\n // The live Stripe page this cancellation orphans, if any (AGL-2244).\n // Read inside the transaction that flips the status so the expiry\n // below cannot act on an order some other writer paid meanwhile.\n expireSessionId:\n order.status === 'pending' ? (order.checkoutSessionId ?? '') : '',\n }\n })\n // EXPIRE THE PAYMENT LINK (AGL-2244). Cancelling a `pending` draft order or\n // POS card sale left its Checkout Session live: the URL is on the\n // customer's phone or in the email the merchant sent, and Stripe keeps it\n // payable for 24 hours. Paying it captured real money on the merchant's\n // account and the completing webhook then discarded the event — its\n // `status !== 'pending'` guard cannot tell a redelivery from a cancelled\n // order — so the sale existed in Stripe and nowhere in the product: no\n // order, no stock move, no contact, no notification, not even a timeline\n // line. The webhook now says so when it happens; this is the half that\n // stops it happening.\n //\n // OUTSIDE the transaction, because it is a network call, and best-effort\n // by design: the cancellation itself already landed and is what the\n // merchant asked for. A failure here leaves the pre-existing behaviour\n // (a payable link) plus the webhook's new record of it, which is strictly\n // better than failing a cancel that has already released stock. Stripe\n // answers 400 for a session that is already expired or already paid, and\n // both are states this has nothing to add to.\n const expireSessionId = (outcome as { expireSessionId?: string })\n .expireSessionId\n if (expireSessionId && process.env.STRIPE_SECRET_KEY) {\n const expiry = await fetchOnSellerThenPlatform(\n `https://api.stripe.com/v1/checkout/sessions/${expireSessionId}/expire`,\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n },\n await directSellerAccountForHost(hostId),\n ).catch(() => null)\n if (!expiry?.ok) {\n console.error(\n 'Cancelled order: Stripe session not expired, the payment link may still be payable',\n { hostId, orderId, sessionId: expireSessionId },\n )\n }\n }\n // Back in stock on the storefront, if the release flipped it (AGL-4121).\n if (soldOutFlipped && outcome.status === 200) {\n await dropStorefrontPages({ hostId, reason: 'a cancelled order restocked a product' })\n }\n // The buyer is told (AGL-3610) — only by the request that cancelled it.\n if (outcome.status === 200 && !(outcome.body as { alreadyCancelled?: boolean }).alreadyCancelled) {\n await notifyOrderBuyer({ hostId, orderId }, 'cancelled')\n await raiseOrderEvent(ORDER_CANCELLED_EVENT, { hostId, orderId, key: 'cancelled' })\n }\n return res.status(outcome.status).json(outcome.body)\n } catch (error) {\n // Nothing landed — the transaction is all-or-nothing — so the order is\n // still open and the merchant can try again. Deliberately NOT the swallow\n // `flagOrderRestock` uses: there the money had already moved and only a\n // postscript was at risk; here a swallowed failure is a cancelled order\n // whose stock never came back, which is the bug this closes.\n console.error('cancelOrder failed', error)\n return res.status(500).json({ error: 'Cancel failed' })\n }\n}\n"],"names":["directSellerAccountForHost","fetchOnSellerThenPlatform","holdsCommerceSiteKey","commerceSitePermissionRefusal","CommerceModel","firebaseAdmin","notifyOrderBuyer","ORDER_CANCELLED_EVENT","raiseOrderEvent","capRestockLines","resolveTrackedRestockLines","saleReleaseCaps","dropStorefrontPages","soldOutMoved","cancelOrderHandler","req","res","body","method","status","json","error","authorization","String","headers","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","orderId","test","decoded","app","auth","verifyIdToken","firestore","hostRef","collection","doc","hostSnapshot","get","exists","uid","orderRef","soldOutFlipped","outcome","runTransaction","transaction","snapshot","order","liftLegacyOrder","data","ok","alreadyCancelled","released","units","canTransitionOrder","orderPayments","some","payment","Array","isArray","payments","saleDecremented","releaseCap","Map","orderAdjustments","where","saleRows","docs","filter","row","channel","timeline","event","lines","products","ref","atMs","Date","now","byProduct","line","set","productId","productLines","product","variants","adjustVariantInventory","variantId","quantity","locationId","update","productStockFields","updatedAtMs","create","delta","reason","releasedLines","values","flat","reduce","sum","patch","appendOrderEvent","restockCheck","resolution","resolvedAtMs","resolvedBy","expireSessionId","checkoutSessionId","process","env","STRIPE_SECRET_KEY","expiry","Authorization","catch","console","sessionId","key"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,0BAA0B,EAAEC,yBAAyB,QAAQ,6BAAyB;AAC/F,SAASC,oBAAoB,QAAQ,0BAAsB;AAC3D,SAASC,6BAA6B,QAAQ,iCAA6B;AAC3E,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,gBAAgB,QAAQ,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Q9D,EAAE,GAAE;gBACfiE,QAAQpG,KAAK,CACX,sFACA;oBAAEW;oBAAQC;oBAASyF,WAAWT;gBAAgB;YAElD;QACF;QACA,yEAAyE;QACzE,IAAIjE,kBAAkBC,QAAQ9B,MAAM,KAAK,KAAK;YAC5C,MAAMP,oBAAoB;gBAAEoB;gBAAQqE,QAAQ;YAAwC;QACtF;QACA,wEAAwE;QACxE,IAAIpD,QAAQ9B,MAAM,KAAK,OAAO,CAAC,AAAC8B,QAAQhC,IAAI,CAAoCwC,gBAAgB,EAAE;YAChG,MAAMnD,iBAAiB;gBAAE0B;gBAAQC;YAAQ,GAAG;YAC5C,MAAMzB,gBAAgBD,uBAAuB;gBAAEyB;gBAAQC;gBAAS0F,KAAK;YAAY;QACnF;QACA,OAAO3G,IAAIG,MAAM,CAAC8B,QAAQ9B,MAAM,EAAEC,IAAI,CAAC6B,QAAQhC,IAAI;IACrD,EAAE,OAAOI,OAAO;QACd,uEAAuE;QACvE,0EAA0E;QAC1E,wEAAwE;QACxE,wEAAwE;QACxE,6DAA6D;QAC7DoG,QAAQpG,KAAK,CAAC,sBAAsBA;QACpC,OAAOL,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAgB;IACvD;AACF,EAAC"}
@@ -21,6 +21,7 @@ import { ORDER_FULFILLED_EVENT, ORDER_REFUNDED_EVENT } from "../model/order-even
21
21
  import { createHash } from "node:crypto";
22
22
  import { fulfillmentEventView, stageOrderEvent } from "./order-events.js";
23
23
  import { restockCapKey, saleReleaseCaps } from "./restock-flag.js";
24
+ import { dropStorefrontPages, soldOutMoved } from "./sold-out-drop.js";
24
25
  const DOC_ID = /^[A-Za-z0-9_-]{1,200}$/;
25
26
  const MAX_CENTS = 10000000000;
26
27
  const HANDOFF_KEY = 'channel-handoff';
@@ -151,7 +152,10 @@ const validIds = (hostId, recordId)=>DOC_ID.test(String(hostId != null ? hostId
151
152
  const hostRef = firestore.collection('hosts').doc(request.hostId);
152
153
  const orderRef = hostRef.collection('orders').doc(request.recordId);
153
154
  const nowMs = deps.now();
154
- return firestore.runTransaction(async (transaction)=>{
155
+ // Whether the restock flipped a sold-out verdict the storefront shows
156
+ // (AGL-4121); a retried attempt can only make the drop spurious.
157
+ let soldOutFlipped = false;
158
+ const outcome = await firestore.runTransaction(async (transaction)=>{
155
159
  var _snapshot_data, _source_refundIds, _order_lineItems, _ref, _ref1, _order_refundedCents, _source_refundIds1;
156
160
  var _order_totals;
157
161
  const snapshot = await transaction.get(orderRef);
@@ -189,6 +193,8 @@ const validIds = (hostId, recordId)=>DOC_ID.test(String(hostId != null ? hostId
189
193
  products.set(productIds[index], CommerceModel.liftLegacyProduct(product.data()));
190
194
  }
191
195
  });
196
+ // As read, before the restock below replaces each entry.
197
+ const originals = new Map(products);
192
198
  let restockedUnits = 0;
193
199
  const restockedLines = [];
194
200
  const ledger = [];
@@ -236,6 +242,7 @@ const validIds = (hostId, recordId)=>DOC_ID.test(String(hostId != null ? hostId
236
242
  }, CommerceModel.productStockFields(product), {
237
243
  updatedAtMs: nowMs
238
244
  }));
245
+ soldOutFlipped || (soldOutFlipped = soldOutMoved(originals.get(productId), product));
239
246
  }
240
247
  for (const row of ledger)transaction.set(hostRef.collection('inventoryAdjustments').doc(createResourceUid()), row);
241
248
  const money = (cents)=>`${(cents / 100).toFixed(2)} ${source.currency}`;
@@ -285,6 +292,13 @@ const validIds = (hostId, recordId)=>DOC_ID.test(String(hostId != null ? hostId
285
292
  restockedUnits
286
293
  };
287
294
  });
295
+ if (soldOutFlipped && outcome.outcome === 'recorded') {
296
+ await dropStorefrontPages({
297
+ hostId: request.hostId,
298
+ reason: 'a channel refund restocked a product'
299
+ });
300
+ }
301
+ return outcome;
288
302
  }
289
303
 
290
304
  //# sourceMappingURL=channel-order-updates.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/channel-order-updates.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 { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport type {\n PluginChannelOrderHandoff,\n PluginChannelOrderHandoffOutcome,\n PluginChannelOrderRefund,\n PluginChannelOrderRefundOutcome,\n} from '@aglyn/aglyn/plugin-manager/plugin-channel-orders'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport * as CommerceModel from '../model'\nimport { ORDER_FULFILLED_EVENT, ORDER_REFUNDED_EVENT } from '../model/order-events'\nimport { createHash } from 'node:crypto'\nimport { fulfillmentEventView, stageOrderEvent } from './order-events'\nimport { restockCapKey, saleReleaseCaps } from './restock-flag'\n\n/**\n * WHAT A CHANNEL SAYS AFTER ITS ORDER CAME IN (AGL-3644): commerce's half of\n * `completeOrder` and `recordRefund` on core's `core.channel-orders`.\n *\n * A delivery app's order is handed to its own courier over the counter, and\n * the app — not the store — refunds its buyer or takes an item off the order.\n * So, for an order the channel sent (`channel: 'marketplace'`):\n *\n * - **A hand-off** closes the order as fulfilled with one fulfillment for\n * every unit still open, carrying the channel as its carrier and no\n * tracking: nothing was shipped from here. Keyed, so a second report of the\n * same pickup writes nothing.\n * - **A refund or adjustment** is RECORDED: `refundedCents` grows by the\n * amount (never past the order's total), the order is `refunded` once the\n * whole of it is, and the channel's id for it is kept so the same report\n * twice records once. No money moves: the channel refunded its own buyer.\n * Units the channel names as never having left go back on the shelf, at\n * most what the order's own sale took less what was already put back —\n * the ledger bound the console's cancel uses.\n *\n * Each is ONE transaction that reads the order (and, for a restock, each\n * product) before it writes, and stages its order event in the same write.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nconst DOC_ID = /^[A-Za-z0-9_-]{1,200}$/\nconst MAX_CENTS = 100_000_000_00\nconst HANDOFF_KEY = 'channel-handoff'\n/** Refund ids kept on an order: far more than any channel sends for one. */\nconst MAX_REFUND_IDS = 100\n\nconst restockKey = restockCapKey\n\n/** The hand-off's fulfillment id: one per order, so a second report finds the first. */\nconst handoffFulfillmentId = (orderId: string) =>\n `f-${createHash('sha256').update(`${orderId}:${HANDOFF_KEY}`).digest('hex').slice(0, 20)}`\n\nexport interface ChannelOrderUpdateDeps {\n firestore: () => Firestore\n now: () => number\n}\n\nconst defaultDeps = (): ChannelOrderUpdateDeps => ({ firestore: () => firebaseAdmin.app().firestore(), now: Date.now })\n\nconst clip = (value: unknown, max: number): string => String(value ?? '').trim().slice(0, max)\n\nconst validIds = (hostId: unknown, recordId: unknown): boolean =>\n DOC_ID.test(String(hostId ?? '')) &&\n DOC_ID.test(String(recordId ?? '')) &&\n !/^__.*__$/.test(String(hostId)) &&\n !/^__.*__$/.test(String(recordId))\n\n/** The channel's courier took the order: every open unit is fulfilled, with nothing shipped from here. */\nexport async function completeChannelOrder(\n request: PluginChannelOrderHandoff,\n deps: ChannelOrderUpdateDeps = defaultDeps(),\n): Promise<PluginChannelOrderHandoffOutcome> {\n if (!validIds(request?.hostId, request?.recordId)) return { outcome: 'no_such_record' }\n const firestore = deps.firestore()\n const orderRef = firestore.collection('hosts').doc(request.hostId).collection('orders').doc(request.recordId)\n const nowMs = deps.now()\n const fulfillmentId = handoffFulfillmentId(request.recordId)\n return firestore.runTransaction(async (transaction): Promise<PluginChannelOrderHandoffOutcome> => {\n const snapshot = await transaction.get(orderRef)\n if (!snapshot.exists) return { outcome: 'no_such_record' }\n const order = CommerceModel.liftLegacyOrder((snapshot.data() ?? {}) as never)\n if (order.channel !== 'marketplace' || !order.channelSource) return { outcome: 'not_completable', status: order.status }\n if ((order.fulfillments ?? []).some((entry) => entry.id === fulfillmentId)) return { outcome: 'already' }\n if (order.status === 'fulfilled' || order.status === 'delivered') return { outcome: 'already' }\n if (!CommerceModel.canTransitionOrder(order.status, 'fulfilled')) {\n return { outcome: 'not_completable', status: order.status }\n }\n let lines = CommerceModel.remainingFulfillmentLines(order)\n if (!lines.length) {\n lines = CommerceModel.orderLineFulfillmentStates(order)\n .filter((state) => state.remainingQuantity > 0)\n .map((state) => ({ lineItemId: state.lineItemId, quantity: state.remainingQuantity }))\n }\n const carrier = clip(order.channelSource.channelLabel, 40) || 'Courier'\n const fulfillment: CommerceModel.OrderFulfillment = {\n id: fulfillmentId,\n lineItemIds: lines.map((entry) => entry.lineItemId),\n lines,\n carrier,\n status: 'active',\n // The channel tells its own buyer; nobody is emailed from here.\n notify: false,\n atMs: nowMs,\n }\n const patch = {\n status: 'fulfilled' as const,\n fulfillments: [...(order.fulfillments ?? []), fulfillment],\n updatedAtMs: nowMs,\n timeline: CommerceModel.appendOrderEvent(\n order,\n 'fulfilled',\n clip(request.note, 200) || `Picked up by the ${carrier} courier`,\n nowMs,\n ),\n }\n transaction.update(orderRef, patch)\n stageOrderEvent(transaction, ORDER_FULFILLED_EVENT, {\n hostId: request.hostId,\n orderId: request.recordId,\n key: fulfillment.id,\n order: { ...(snapshot.data() ?? {}), ...patch },\n extra: { fulfillment: fulfillmentEventView(order, fulfillment) },\n })\n return { outcome: 'completed' }\n })\n}\n\n/**\n * What the order's sale took off each shelf, less what has gone back since\n * (a cancel's or an earlier adjustment's rows): the most a restock may still\n * return, by product and variant.\n */\nfunction remainingReleaseCaps(rows: readonly { get: (field: string) => unknown }[]): Map<string, number> {\n const caps = saleReleaseCaps(rows.filter((row) => row.get('reason') === 'sale'))\n for (const row of rows) {\n const reason = row.get('reason')\n if (reason !== 'refund' && reason !== 'cancellation') continue\n const delta = Number(row.get('appliedDelta') ?? row.get('delta') ?? 0)\n if (!(delta > 0)) continue\n const key = restockKey(String(row.get('productId') ?? ''), String(row.get('variantId') ?? ''))\n if (caps.has(key)) caps.set(key, Math.max(0, (caps.get(key) ?? 0) - delta))\n }\n return caps\n}\n\n/** The channel refunded its buyer or took items off the order: recorded once, with the named units back on the shelf. */\nexport async function recordChannelOrderRefund(\n request: PluginChannelOrderRefund,\n deps: ChannelOrderUpdateDeps = defaultDeps(),\n): Promise<PluginChannelOrderRefundOutcome> {\n if (!validIds(request?.hostId, request?.recordId)) return { outcome: 'no_such_record' }\n const refundId = clip(request.refundId, 200)\n if (!refundId) return { outcome: 'refused', reason: 'The refund has no id on its channel.' }\n const amount = Number(request.amountCents)\n if (!Number.isInteger(amount) || amount < 0 || amount > MAX_CENTS) {\n return { outcome: 'refused', reason: 'The refund is not a whole amount.' }\n }\n const asked = (Array.isArray(request.restock) ? request.restock : [])\n .map((entry) => ({ lineIndex: Number(entry?.lineIndex), quantity: Number(entry?.quantity) }))\n .filter((entry) => Number.isInteger(entry.lineIndex) && entry.lineIndex >= 0 && Number.isInteger(entry.quantity) && entry.quantity > 0)\n if (amount === 0 && !asked.length) return { outcome: 'refused', reason: 'The refund moves no money and no stock.' }\n\n const firestore = deps.firestore()\n const hostRef = firestore.collection('hosts').doc(request.hostId)\n const orderRef = hostRef.collection('orders').doc(request.recordId)\n const nowMs = deps.now()\n return firestore.runTransaction(async (transaction): Promise<PluginChannelOrderRefundOutcome> => {\n const snapshot = await transaction.get(orderRef)\n if (!snapshot.exists) return { outcome: 'no_such_record' }\n const order = CommerceModel.liftLegacyOrder((snapshot.data() ?? {}) as never)\n const source = order.channelSource\n if (order.channel !== 'marketplace' || !source) return { outcome: 'no_such_record' }\n if ((source.refundIds ?? []).includes(refundId)) return { outcome: 'already' }\n\n // Every read before any write: the ledger, then each product a restock touches.\n const lineItems = order.lineItems ?? []\n const wanted = new Map<number, number>()\n for (const entry of asked) {\n const line = lineItems[entry.lineIndex]\n if (!line?.productId || !line.variantId || /^__.*__$/.test(line.productId)) continue\n wanted.set(entry.lineIndex, Math.min(Number(line.quantity) || 0, (wanted.get(entry.lineIndex) ?? 0) + entry.quantity))\n }\n const rows = wanted.size\n ? (await transaction.get(hostRef.collection('inventoryAdjustments').where('orderId', '==', request.recordId))).docs\n : []\n const caps = remainingReleaseCaps(rows)\n const productIds = [...new Set([...wanted.keys()].map((index) => lineItems[index].productId))]\n const productSnaps = await Promise.all(productIds.map((id) => transaction.get(hostRef.collection('products').doc(id))))\n const products = new Map<string, CommerceModel.HostProduct>()\n productSnaps.forEach((product, index) => {\n if (product.exists && !product.get('deletedAt')) {\n products.set(productIds[index], CommerceModel.liftLegacyProduct(product.data() as never))\n }\n })\n\n let restockedUnits = 0\n const restockedLines: number[] = []\n const ledger: CommerceModel.InventoryAdjustment[] = []\n const changed = new Set<string>()\n for (const [lineIndex, quantity] of wanted) {\n const line = lineItems[lineIndex]\n const product = products.get(line.productId)\n const variantId = String(line.variantId)\n const variant = product?.variants.find((entry) => entry.id === variantId)\n if (!product || !variant || variant.inventory == null) continue\n const key = restockKey(line.productId, variantId)\n // A pair the ledger never recorded a sale for gave up nothing to return.\n const budget = caps.get(key) ?? 0\n const back = Math.min(quantity, budget)\n if (back <= 0) continue\n caps.set(key, budget - back)\n products.set(line.productId, {\n ...product,\n variants: CommerceModel.adjustVariantInventory(product, variantId, back),\n })\n changed.add(line.productId)\n restockedUnits += back\n restockedLines.push(lineIndex)\n ledger.push({\n productId: line.productId,\n variantId,\n delta: back,\n reason: 'refund',\n orderId: request.recordId,\n source: source.channelLabel,\n atMs: nowMs,\n })\n }\n\n const total = Number(order.totals?.totalCents ?? order.amountCents ?? 0)\n const before = Number(order.refundedCents ?? 0)\n const recorded = Math.max(0, Math.min(amount, total - before))\n const refundedCents = before + recorded\n const full = total > 0 && refundedCents >= total\n let status = order.status\n if (full && status !== 'refunded' && CommerceModel.canTransitionOrder(status, 'refunded')) status = 'refunded'\n\n for (const productId of changed) {\n const product = products.get(productId) as CommerceModel.HostProduct\n transaction.update(hostRef.collection('products').doc(productId), {\n variants: product.variants,\n ...CommerceModel.productStockFields(product),\n updatedAtMs: nowMs,\n })\n }\n for (const row of ledger) transaction.set(hostRef.collection('inventoryAdjustments').doc(createResourceUid()), row)\n\n const money = (cents: number) => `${(cents / 100).toFixed(2)} ${source.currency}`\n const reason = clip(request.reason, 200) || `Refunded on ${source.channelLabel}`\n const parts = [\n recorded > 0 ? `${reason}: ${money(recorded)} refunded by ${source.channelLabel}` : reason,\n ...(recorded < amount ? [`${money(amount - recorded)} more than the order had left was not recorded`] : []),\n ...(restockedUnits > 0 ? [`${restockedUnits} ${restockedUnits === 1 ? 'unit' : 'units'} returned to stock`] : []),\n ]\n const patch = {\n status,\n refundedCents,\n channelSource: { ...source, refundIds: [...(source.refundIds ?? []), refundId].slice(-MAX_REFUND_IDS) },\n updatedAtMs: nowMs,\n timeline: CommerceModel.appendOrderEvent(order, 'refund', `${parts.join('. ')}.`, nowMs),\n }\n transaction.update(orderRef, patch)\n if (recorded > 0) {\n stageOrderEvent(transaction, ORDER_REFUNDED_EVENT, {\n hostId: request.hostId,\n orderId: request.recordId,\n key: `refund:channel:${refundId}`,\n order: { ...(snapshot.data() ?? {}), ...patch },\n extra: { refund: { id: null, amountCents: recorded, lineItemIds: restockedLines, full } },\n })\n }\n return { outcome: 'recorded', refundedCents, restockedUnits }\n })\n}\n"],"names":["createResourceUid","firebaseAdmin","CommerceModel","ORDER_FULFILLED_EVENT","ORDER_REFUNDED_EVENT","createHash","fulfillmentEventView","stageOrderEvent","restockCapKey","saleReleaseCaps","DOC_ID","MAX_CENTS","HANDOFF_KEY","MAX_REFUND_IDS","restockKey","handoffFulfillmentId","orderId","update","digest","slice","defaultDeps","firestore","app","now","Date","clip","value","max","String","trim","validIds","hostId","recordId","test","completeChannelOrder","request","deps","outcome","orderRef","collection","doc","nowMs","fulfillmentId","runTransaction","transaction","snapshot","order","get","exists","liftLegacyOrder","data","channel","channelSource","status","fulfillments","some","entry","id","canTransitionOrder","lines","remainingFulfillmentLines","length","orderLineFulfillmentStates","filter","state","remainingQuantity","map","lineItemId","quantity","carrier","channelLabel","fulfillment","lineItemIds","notify","atMs","patch","updatedAtMs","timeline","appendOrderEvent","note","key","extra","remainingReleaseCaps","rows","caps","row","reason","delta","Number","has","set","Math","recordChannelOrderRefund","refundId","amount","amountCents","isInteger","asked","Array","isArray","restock","lineIndex","hostRef","source","refundIds","includes","lineItems","wanted","Map","line","productId","variantId","min","size","where","docs","productIds","Set","keys","index","productSnaps","Promise","all","products","forEach","product","liftLegacyProduct","restockedUnits","restockedLines","ledger","changed","variant","variants","find","inventory","budget","back","adjustVariantInventory","add","push","total","totals","totalCents","before","refundedCents","recorded","full","productStockFields","money","cents","toFixed","currency","parts","join","refund"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAO9E,SAASC,aAAa,QAAQ,iDAAgD;AAC9E,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,qBAAqB,EAAEC,oBAAoB,QAAQ,2BAAuB;AACnF,SAASC,UAAU,QAAQ,cAAa;AACxC,SAASC,oBAAoB,EAAEC,eAAe,QAAQ,oBAAgB;AACtE,SAASC,aAAa,EAAEC,eAAe,QAAQ,oBAAgB;AA4B/D,MAAMC,SAAS;AACf,MAAMC,YAAY;AAClB,MAAMC,cAAc;AACpB,0EAA0E,GAC1E,MAAMC,iBAAiB;AAEvB,MAAMC,aAAaN;AAEnB,sFAAsF,GACtF,MAAMO,uBAAuB,CAACC,UAC5B,CAAC,EAAE,EAAEX,WAAW,UAAUY,MAAM,CAAC,GAAGD,QAAQ,CAAC,EAAEJ,aAAa,EAAEM,MAAM,CAAC,OAAOC,KAAK,CAAC,GAAG,KAAK;AAO5F,MAAMC,cAAc,IAA+B,CAAA;QAAEC,WAAW,IAAMpB,cAAcqB,GAAG,GAAGD,SAAS;QAAIE,KAAKC,KAAKD,GAAG;IAAC,CAAA;AAErH,MAAME,OAAO,CAACC,OAAgBC,MAAwBC,OAAOF,gBAAAA,QAAS,IAAIG,IAAI,GAAGV,KAAK,CAAC,GAAGQ;AA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AAE1C,OAAOjC,YAAY,EAAE,GAAGgB;eAChF2D,WAAWnD,SAAS;gBAAC,GAAGsD,MAAMtD,SAASmD,UAAU,8CAA8C,CAAC;aAAC,GAAG,EAAE;eACtGlB,iBAAiB,IAAI;gBAAC,GAAGA,eAAe,CAAC,EAAEA,mBAAmB,IAAI,SAAS,QAAQ,kBAAkB,CAAC;aAAC,GAAG,EAAE;SACjH;QACD,MAAMpD,QAAQ;YACZtB;YACA2F;YACA5F,eAAe,aAAKmD;gBAAQC,WAAW;wBAAKD,qBAAAA,OAAOC,SAAS,YAAhBD,qBAAoB,EAAE;oBAAGV;iBAAS,CAAC1E,KAAK,CAAC,CAACN;;YACtF+D,aAAanC;YACboC,UAAU3E,cAAc4E,gBAAgB,CAAChC,OAAO,UAAU,GAAG0G,MAAMC,IAAI,CAAC,MAAM,CAAC,CAAC,EAAEhH;QACpF;QACAG,YAAY3B,MAAM,CAACqB,UAAUqC;QAC7B,IAAIsE,WAAW,GAAG;gBAKDpG;YAJftC,gBAAgBqC,aAAaxC,sBAAsB;gBACjD2B,QAAQI,QAAQJ,MAAM;gBACtBf,SAASmB,QAAQH,QAAQ;gBACzBgD,KAAK,CAAC,eAAe,EAAEa,UAAU;gBACjC/C,OAAO,cAAMD,kBAAAA,SAASK,IAAI,cAAbL,kBAAmB,CAAC,GAAO8B;gBACxCM,OAAO;oBAAEyE,QAAQ;wBAAEjG,IAAI;wBAAMsC,aAAakD;wBAAUzE,aAAawD;wBAAgBkB;oBAAK;gBAAE;YAC1F;QACF;QACA,OAAO;YAAE7G,SAAS;YAAY2G;YAAejB;QAAe;IAC9D;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/channel-order-updates.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 { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport type {\n PluginChannelOrderHandoff,\n PluginChannelOrderHandoffOutcome,\n PluginChannelOrderRefund,\n PluginChannelOrderRefundOutcome,\n} from '@aglyn/aglyn/plugin-manager/plugin-channel-orders'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport * as CommerceModel from '../model'\nimport { ORDER_FULFILLED_EVENT, ORDER_REFUNDED_EVENT } from '../model/order-events'\nimport { createHash } from 'node:crypto'\nimport { fulfillmentEventView, stageOrderEvent } from './order-events'\nimport { restockCapKey, saleReleaseCaps } from './restock-flag'\nimport { dropStorefrontPages, soldOutMoved } from './sold-out-drop'\n\n/**\n * WHAT A CHANNEL SAYS AFTER ITS ORDER CAME IN (AGL-3644): commerce's half of\n * `completeOrder` and `recordRefund` on core's `core.channel-orders`.\n *\n * A delivery app's order is handed to its own courier over the counter, and\n * the app — not the store — refunds its buyer or takes an item off the order.\n * So, for an order the channel sent (`channel: 'marketplace'`):\n *\n * - **A hand-off** closes the order as fulfilled with one fulfillment for\n * every unit still open, carrying the channel as its carrier and no\n * tracking: nothing was shipped from here. Keyed, so a second report of the\n * same pickup writes nothing.\n * - **A refund or adjustment** is RECORDED: `refundedCents` grows by the\n * amount (never past the order's total), the order is `refunded` once the\n * whole of it is, and the channel's id for it is kept so the same report\n * twice records once. No money moves: the channel refunded its own buyer.\n * Units the channel names as never having left go back on the shelf, at\n * most what the order's own sale took less what was already put back —\n * the ledger bound the console's cancel uses.\n *\n * Each is ONE transaction that reads the order (and, for a restock, each\n * product) before it writes, and stages its order event in the same write.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nconst DOC_ID = /^[A-Za-z0-9_-]{1,200}$/\nconst MAX_CENTS = 100_000_000_00\nconst HANDOFF_KEY = 'channel-handoff'\n/** Refund ids kept on an order: far more than any channel sends for one. */\nconst MAX_REFUND_IDS = 100\n\nconst restockKey = restockCapKey\n\n/** The hand-off's fulfillment id: one per order, so a second report finds the first. */\nconst handoffFulfillmentId = (orderId: string) =>\n `f-${createHash('sha256').update(`${orderId}:${HANDOFF_KEY}`).digest('hex').slice(0, 20)}`\n\nexport interface ChannelOrderUpdateDeps {\n firestore: () => Firestore\n now: () => number\n}\n\nconst defaultDeps = (): ChannelOrderUpdateDeps => ({ firestore: () => firebaseAdmin.app().firestore(), now: Date.now })\n\nconst clip = (value: unknown, max: number): string => String(value ?? '').trim().slice(0, max)\n\nconst validIds = (hostId: unknown, recordId: unknown): boolean =>\n DOC_ID.test(String(hostId ?? '')) &&\n DOC_ID.test(String(recordId ?? '')) &&\n !/^__.*__$/.test(String(hostId)) &&\n !/^__.*__$/.test(String(recordId))\n\n/** The channel's courier took the order: every open unit is fulfilled, with nothing shipped from here. */\nexport async function completeChannelOrder(\n request: PluginChannelOrderHandoff,\n deps: ChannelOrderUpdateDeps = defaultDeps(),\n): Promise<PluginChannelOrderHandoffOutcome> {\n if (!validIds(request?.hostId, request?.recordId)) return { outcome: 'no_such_record' }\n const firestore = deps.firestore()\n const orderRef = firestore.collection('hosts').doc(request.hostId).collection('orders').doc(request.recordId)\n const nowMs = deps.now()\n const fulfillmentId = handoffFulfillmentId(request.recordId)\n return firestore.runTransaction(async (transaction): Promise<PluginChannelOrderHandoffOutcome> => {\n const snapshot = await transaction.get(orderRef)\n if (!snapshot.exists) return { outcome: 'no_such_record' }\n const order = CommerceModel.liftLegacyOrder((snapshot.data() ?? {}) as never)\n if (order.channel !== 'marketplace' || !order.channelSource) return { outcome: 'not_completable', status: order.status }\n if ((order.fulfillments ?? []).some((entry) => entry.id === fulfillmentId)) return { outcome: 'already' }\n if (order.status === 'fulfilled' || order.status === 'delivered') return { outcome: 'already' }\n if (!CommerceModel.canTransitionOrder(order.status, 'fulfilled')) {\n return { outcome: 'not_completable', status: order.status }\n }\n let lines = CommerceModel.remainingFulfillmentLines(order)\n if (!lines.length) {\n lines = CommerceModel.orderLineFulfillmentStates(order)\n .filter((state) => state.remainingQuantity > 0)\n .map((state) => ({ lineItemId: state.lineItemId, quantity: state.remainingQuantity }))\n }\n const carrier = clip(order.channelSource.channelLabel, 40) || 'Courier'\n const fulfillment: CommerceModel.OrderFulfillment = {\n id: fulfillmentId,\n lineItemIds: lines.map((entry) => entry.lineItemId),\n lines,\n carrier,\n status: 'active',\n // The channel tells its own buyer; nobody is emailed from here.\n notify: false,\n atMs: nowMs,\n }\n const patch = {\n status: 'fulfilled' as const,\n fulfillments: [...(order.fulfillments ?? []), fulfillment],\n updatedAtMs: nowMs,\n timeline: CommerceModel.appendOrderEvent(\n order,\n 'fulfilled',\n clip(request.note, 200) || `Picked up by the ${carrier} courier`,\n nowMs,\n ),\n }\n transaction.update(orderRef, patch)\n stageOrderEvent(transaction, ORDER_FULFILLED_EVENT, {\n hostId: request.hostId,\n orderId: request.recordId,\n key: fulfillment.id,\n order: { ...(snapshot.data() ?? {}), ...patch },\n extra: { fulfillment: fulfillmentEventView(order, fulfillment) },\n })\n return { outcome: 'completed' }\n })\n}\n\n/**\n * What the order's sale took off each shelf, less what has gone back since\n * (a cancel's or an earlier adjustment's rows): the most a restock may still\n * return, by product and variant.\n */\nfunction remainingReleaseCaps(rows: readonly { get: (field: string) => unknown }[]): Map<string, number> {\n const caps = saleReleaseCaps(rows.filter((row) => row.get('reason') === 'sale'))\n for (const row of rows) {\n const reason = row.get('reason')\n if (reason !== 'refund' && reason !== 'cancellation') continue\n const delta = Number(row.get('appliedDelta') ?? row.get('delta') ?? 0)\n if (!(delta > 0)) continue\n const key = restockKey(String(row.get('productId') ?? ''), String(row.get('variantId') ?? ''))\n if (caps.has(key)) caps.set(key, Math.max(0, (caps.get(key) ?? 0) - delta))\n }\n return caps\n}\n\n/** The channel refunded its buyer or took items off the order: recorded once, with the named units back on the shelf. */\nexport async function recordChannelOrderRefund(\n request: PluginChannelOrderRefund,\n deps: ChannelOrderUpdateDeps = defaultDeps(),\n): Promise<PluginChannelOrderRefundOutcome> {\n if (!validIds(request?.hostId, request?.recordId)) return { outcome: 'no_such_record' }\n const refundId = clip(request.refundId, 200)\n if (!refundId) return { outcome: 'refused', reason: 'The refund has no id on its channel.' }\n const amount = Number(request.amountCents)\n if (!Number.isInteger(amount) || amount < 0 || amount > MAX_CENTS) {\n return { outcome: 'refused', reason: 'The refund is not a whole amount.' }\n }\n const asked = (Array.isArray(request.restock) ? request.restock : [])\n .map((entry) => ({ lineIndex: Number(entry?.lineIndex), quantity: Number(entry?.quantity) }))\n .filter((entry) => Number.isInteger(entry.lineIndex) && entry.lineIndex >= 0 && Number.isInteger(entry.quantity) && entry.quantity > 0)\n if (amount === 0 && !asked.length) return { outcome: 'refused', reason: 'The refund moves no money and no stock.' }\n\n const firestore = deps.firestore()\n const hostRef = firestore.collection('hosts').doc(request.hostId)\n const orderRef = hostRef.collection('orders').doc(request.recordId)\n const nowMs = deps.now()\n // Whether the restock flipped a sold-out verdict the storefront shows\n // (AGL-4121); a retried attempt can only make the drop spurious.\n let soldOutFlipped = false\n const outcome = await firestore.runTransaction(async (transaction): Promise<PluginChannelOrderRefundOutcome> => {\n const snapshot = await transaction.get(orderRef)\n if (!snapshot.exists) return { outcome: 'no_such_record' }\n const order = CommerceModel.liftLegacyOrder((snapshot.data() ?? {}) as never)\n const source = order.channelSource\n if (order.channel !== 'marketplace' || !source) return { outcome: 'no_such_record' }\n if ((source.refundIds ?? []).includes(refundId)) return { outcome: 'already' }\n\n // Every read before any write: the ledger, then each product a restock touches.\n const lineItems = order.lineItems ?? []\n const wanted = new Map<number, number>()\n for (const entry of asked) {\n const line = lineItems[entry.lineIndex]\n if (!line?.productId || !line.variantId || /^__.*__$/.test(line.productId)) continue\n wanted.set(entry.lineIndex, Math.min(Number(line.quantity) || 0, (wanted.get(entry.lineIndex) ?? 0) + entry.quantity))\n }\n const rows = wanted.size\n ? (await transaction.get(hostRef.collection('inventoryAdjustments').where('orderId', '==', request.recordId))).docs\n : []\n const caps = remainingReleaseCaps(rows)\n const productIds = [...new Set([...wanted.keys()].map((index) => lineItems[index].productId))]\n const productSnaps = await Promise.all(productIds.map((id) => transaction.get(hostRef.collection('products').doc(id))))\n const products = new Map<string, CommerceModel.HostProduct>()\n productSnaps.forEach((product, index) => {\n if (product.exists && !product.get('deletedAt')) {\n products.set(productIds[index], CommerceModel.liftLegacyProduct(product.data() as never))\n }\n })\n\n // As read, before the restock below replaces each entry.\n const originals = new Map(products)\n let restockedUnits = 0\n const restockedLines: number[] = []\n const ledger: CommerceModel.InventoryAdjustment[] = []\n const changed = new Set<string>()\n for (const [lineIndex, quantity] of wanted) {\n const line = lineItems[lineIndex]\n const product = products.get(line.productId)\n const variantId = String(line.variantId)\n const variant = product?.variants.find((entry) => entry.id === variantId)\n if (!product || !variant || variant.inventory == null) continue\n const key = restockKey(line.productId, variantId)\n // A pair the ledger never recorded a sale for gave up nothing to return.\n const budget = caps.get(key) ?? 0\n const back = Math.min(quantity, budget)\n if (back <= 0) continue\n caps.set(key, budget - back)\n products.set(line.productId, {\n ...product,\n variants: CommerceModel.adjustVariantInventory(product, variantId, back),\n })\n changed.add(line.productId)\n restockedUnits += back\n restockedLines.push(lineIndex)\n ledger.push({\n productId: line.productId,\n variantId,\n delta: back,\n reason: 'refund',\n orderId: request.recordId,\n source: source.channelLabel,\n atMs: nowMs,\n })\n }\n\n const total = Number(order.totals?.totalCents ?? order.amountCents ?? 0)\n const before = Number(order.refundedCents ?? 0)\n const recorded = Math.max(0, Math.min(amount, total - before))\n const refundedCents = before + recorded\n const full = total > 0 && refundedCents >= total\n let status = order.status\n if (full && status !== 'refunded' && CommerceModel.canTransitionOrder(status, 'refunded')) status = 'refunded'\n\n for (const productId of changed) {\n const product = products.get(productId) as CommerceModel.HostProduct\n transaction.update(hostRef.collection('products').doc(productId), {\n variants: product.variants,\n ...CommerceModel.productStockFields(product),\n updatedAtMs: nowMs,\n })\n soldOutFlipped ||= soldOutMoved(originals.get(productId), product)\n }\n for (const row of ledger) transaction.set(hostRef.collection('inventoryAdjustments').doc(createResourceUid()), row)\n\n const money = (cents: number) => `${(cents / 100).toFixed(2)} ${source.currency}`\n const reason = clip(request.reason, 200) || `Refunded on ${source.channelLabel}`\n const parts = [\n recorded > 0 ? `${reason}: ${money(recorded)} refunded by ${source.channelLabel}` : reason,\n ...(recorded < amount ? [`${money(amount - recorded)} more than the order had left was not recorded`] : []),\n ...(restockedUnits > 0 ? [`${restockedUnits} ${restockedUnits === 1 ? 'unit' : 'units'} returned to stock`] : []),\n ]\n const patch = {\n status,\n refundedCents,\n channelSource: { ...source, refundIds: [...(source.refundIds ?? []), refundId].slice(-MAX_REFUND_IDS) },\n updatedAtMs: nowMs,\n timeline: CommerceModel.appendOrderEvent(order, 'refund', `${parts.join('. ')}.`, nowMs),\n }\n transaction.update(orderRef, patch)\n if (recorded > 0) {\n stageOrderEvent(transaction, ORDER_REFUNDED_EVENT, {\n hostId: request.hostId,\n orderId: request.recordId,\n key: `refund:channel:${refundId}`,\n order: { ...(snapshot.data() ?? {}), ...patch },\n extra: { refund: { id: null, amountCents: recorded, lineItemIds: restockedLines, full } },\n })\n }\n return { outcome: 'recorded', refundedCents, restockedUnits }\n })\n if (soldOutFlipped && outcome.outcome === 'recorded') {\n await dropStorefrontPages({ hostId: request.hostId, reason: 'a channel refund restocked a product' })\n }\n return outcome\n}\n"],"names":["createResourceUid","firebaseAdmin","CommerceModel","ORDER_FULFILLED_EVENT","ORDER_REFUNDED_EVENT","createHash","fulfillmentEventView","stageOrderEvent","restockCapKey","saleReleaseCaps","dropStorefrontPages","soldOutMoved","DOC_ID","MAX_CENTS","HANDOFF_KEY","MAX_REFUND_IDS","restockKey","handoffFulfillmentId","orderId","update","digest","slice","defaultDeps","firestore","app","now","Date","clip","value","max","String","trim","validIds","hostId","recordId","test","completeChannelOrder","request","deps","outcome","orderRef","collection","doc","nowMs","fulfillmentId","runTransaction","transaction","snapshot","order","get","exists","liftLegacyOrder","data","channel","channelSource","status","fulfillments","some","entry","id","canTransitionOrder","lines","remainingFulfillmentLines","length","orderLineFulfillmentStates","filter","state","remainingQuantity","map","lineItemId","quantity","carrier","channelLabel","fulfillment","lineItemIds","notify","atMs","patch","updatedAtMs","timeline","appendOrderEvent","note","key","extra","remainingReleaseCaps","rows","caps","row","reason","delta","Number","has","set","Math","recordChannelOrderRefund","refundId","amount","amountCents","isInteger","asked","Array","isArray","restock","lineIndex","hostRef","soldOutFlipped","source","refundIds","includes","lineItems","wanted","Map","line","productId","variantId","min","size","where","docs","productIds","Set","keys","index","productSnaps","Promise","all","products","forEach","product","liftLegacyProduct","originals","restockedUnits","restockedLines","ledger","changed","variant","variants","find","inventory","budget","back","adjustVariantInventory","add","push","total","totals","totalCents","before","refundedCents","recorded","full","productStockFields","money","cents","toFixed","currency","parts","join","refund"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAO9E,SAASC,aAAa,QAAQ,iDAAgD;AAC9E,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,qBAAqB,EAAEC,oBAAoB,QAAQ,2BAAuB;AACnF,SAASC,UAAU,QAAQ,cAAa;AACxC,SAASC,oBAAoB,EAAEC,eAAe,QAAQ,oBAAgB;AACtE,SAASC,aAAa,EAAEC,eAAe,QAAQ,oBAAgB;AAC/D,SAASC,mBAAmB,EAAEC,YAAY,QAAQ,qBAAiB;AA4BnE,MAAMC,SAAS;AACf,MAAMC,YAAY;AAClB,MAAMC,cAAc;AACpB,0EAA0E,GAC1E,MAAMC,iBAAiB;AAEvB,MAAMC,aAAaR;AAEnB,sFAAsF,GACtF,MAAMS,uBAAuB,CAACC,UAC5B,CAAC,EAAE,EAAEb,WAAW,UAAUc,MAAM,CAAC,GAAGD,QAAQ,CAAC,EAAEJ,aAAa,EAAEM,MAAM,CAAC,O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IAAI,cAAbL,kBAAmB,CAAC,GAAO8B;gBACxCM,OAAO;oBAAE2E,QAAQ;wBAAEnG,IAAI;wBAAMsC,aAAaoD;wBAAU3E,aAAa0D;wBAAgBkB;oBAAK;gBAAE;YAC1F;QACF;QACA,OAAO;YAAE/G,SAAS;YAAY6G;YAAejB;QAAe;IAC9D;IACA,IAAI1B,kBAAkBlE,QAAQA,OAAO,KAAK,YAAY;QACpD,MAAM7B,oBAAoB;YAAEuB,QAAQI,QAAQJ,MAAM;YAAEuD,QAAQ;QAAuC;IACrG;IACA,OAAOjD;AACT"}
@@ -25,6 +25,7 @@ import { alertLowStockCrossing } from "./low-stock.js";
25
25
  import { stageOrderEvent } from "./order-events.js";
26
26
  import { capRestockLines, resolveTrackedRestockLines, saleReleaseCaps } from "./restock-flag.js";
27
27
  import { completeChannelOrder, recordChannelOrderRefund } from "./channel-order-updates.js";
28
+ import { dropStorefrontPages, soldOutMoved } from "./sold-out-drop.js";
28
29
  const DOC_ID = /^[A-Za-z0-9_-]{1,200}$/;
29
30
  const CHANNEL_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
30
31
  const MAX_LINES = 250;
@@ -375,6 +376,13 @@ const defaultDeps = ()=>({
375
376
  number: result.number
376
377
  }, orderId);
377
378
  for (const crossing of crossings)alertLowStockCrossing(order.hostId, crossing.before, crossing.after);
379
+ // A channel sale that sold a product out reaches the storefront (AGL-4121).
380
+ if (crossings.some((crossing)=>soldOutMoved(crossing.before, crossing.after))) {
381
+ await dropStorefrontPages({
382
+ hostId: order.hostId,
383
+ reason: 'a channel sale sold out a product'
384
+ });
385
+ }
378
386
  const totalLabel = `${(Number(order.totalCents) / 100).toFixed(2)} ${currency}`;
379
387
  const units = order.lines.reduce((sum, line)=>sum + Number(line.quantity), 0);
380
388
  void notifyHostManagers(order.hostId, {
@@ -430,6 +438,9 @@ function alreadyOutcome(recordId, data) {
430
438
  const hostRef = firestore.collection('hosts').doc(request.hostId);
431
439
  const orderRef = hostRef.collection('orders').doc(request.recordId);
432
440
  const nowMs = deps.now();
441
+ // Whether the restock flipped a sold-out verdict the storefront shows
442
+ // (AGL-4121); a retried attempt can only make the drop spurious.
443
+ let soldOutFlipped = false;
433
444
  const outcome = await firestore.runTransaction(async (transaction)=>{
434
445
  var _snapshot_data, _order_fulfillments, _snapshot_data1;
435
446
  const snapshot = await transaction.get(orderRef);
@@ -479,6 +490,9 @@ function alreadyOutcome(recordId, data) {
479
490
  })), {
480
491
  updatedAtMs: nowMs
481
492
  }));
493
+ soldOutFlipped || (soldOutFlipped = soldOutMoved(product, _extends({}, product, {
494
+ variants
495
+ })));
482
496
  for (const line of productLines){
483
497
  transaction.set(hostRef.collection('inventoryAdjustments').doc(createResourceUid()), {
484
498
  productId,
@@ -508,6 +522,12 @@ function alreadyOutcome(recordId, data) {
508
522
  restockedUnits: units
509
523
  };
510
524
  });
525
+ if (soldOutFlipped && outcome.outcome === 'cancelled') {
526
+ await dropStorefrontPages({
527
+ hostId: request.hostId,
528
+ reason: 'a channel cancellation restocked a product'
529
+ });
530
+ }
511
531
  return outcome;
512
532
  }
513
533
  /** The channel's charges on a sale, recorded once it says; a later answer replaces an earlier one. */ export async function recordChannelOrderFees(request, deps = defaultDeps()) {