@aglyn/plugins-commerce 1.0.0-beta.143

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 (417) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +10 -0
  3. package/package.json +57 -0
  4. package/src/index.d.ts +38 -0
  5. package/src/index.js +38 -0
  6. package/src/index.js.map +1 -0
  7. package/src/lib/components/account.d.ts +31 -0
  8. package/src/lib/components/account.js +645 -0
  9. package/src/lib/components/account.js.map +1 -0
  10. package/src/lib/components/cart.d.ts +38 -0
  11. package/src/lib/components/cart.js +851 -0
  12. package/src/lib/components/cart.js.map +1 -0
  13. package/src/lib/components/commerce-console-page.d.ts +32 -0
  14. package/src/lib/components/commerce-console-page.js +296 -0
  15. package/src/lib/components/commerce-console-page.js.map +1 -0
  16. package/src/lib/components/commerce-console-sections.d.ts +34 -0
  17. package/src/lib/components/commerce-console-sections.js +62 -0
  18. package/src/lib/components/commerce-console-sections.js.map +1 -0
  19. package/src/lib/components/console/catalog-organization-card.component.d.ts +14 -0
  20. package/src/lib/components/console/catalog-organization-card.component.js +1087 -0
  21. package/src/lib/components/console/catalog-organization-card.component.js.map +1 -0
  22. package/src/lib/components/console/commerce-analytics-card.component.d.ts +27 -0
  23. package/src/lib/components/console/commerce-analytics-card.component.js +310 -0
  24. package/src/lib/components/console/commerce-analytics-card.component.js.map +1 -0
  25. package/src/lib/components/console/commerce-glance-card.component.d.ts +20 -0
  26. package/src/lib/components/console/commerce-glance-card.component.js +340 -0
  27. package/src/lib/components/console/commerce-glance-card.component.js.map +1 -0
  28. package/src/lib/components/console/commerce-stat-tile.component.d.ts +37 -0
  29. package/src/lib/components/console/commerce-stat-tile.component.js +72 -0
  30. package/src/lib/components/console/commerce-stat-tile.component.js.map +1 -0
  31. package/src/lib/components/console/discounts-card.component.d.ts +14 -0
  32. package/src/lib/components/console/discounts-card.component.js +443 -0
  33. package/src/lib/components/console/discounts-card.component.js.map +1 -0
  34. package/src/lib/components/console/entitlement-gate.component.d.ts +76 -0
  35. package/src/lib/components/console/entitlement-gate.component.js +115 -0
  36. package/src/lib/components/console/entitlement-gate.component.js.map +1 -0
  37. package/src/lib/components/console/gift-cards-card.component.d.ts +29 -0
  38. package/src/lib/components/console/gift-cards-card.component.js +379 -0
  39. package/src/lib/components/console/gift-cards-card.component.js.map +1 -0
  40. package/src/lib/components/console/host-coupons-card.component.d.ts +14 -0
  41. package/src/lib/components/console/host-coupons-card.component.js +252 -0
  42. package/src/lib/components/console/host-coupons-card.component.js.map +1 -0
  43. package/src/lib/components/console/host-orders-card.component.d.ts +13 -0
  44. package/src/lib/components/console/host-orders-card.component.js +861 -0
  45. package/src/lib/components/console/host-orders-card.component.js.map +1 -0
  46. package/src/lib/components/console/locations-card.component.d.ts +14 -0
  47. package/src/lib/components/console/locations-card.component.js +256 -0
  48. package/src/lib/components/console/locations-card.component.js.map +1 -0
  49. package/src/lib/components/console/member-posts-card.component.d.ts +8 -0
  50. package/src/lib/components/console/member-posts-card.component.js +283 -0
  51. package/src/lib/components/console/member-posts-card.component.js.map +1 -0
  52. package/src/lib/components/console/newest-site-users-card.component.d.ts +36 -0
  53. package/src/lib/components/console/newest-site-users-card.component.js +126 -0
  54. package/src/lib/components/console/newest-site-users-card.component.js.map +1 -0
  55. package/src/lib/components/console/order-detail-dialog.component.d.ts +28 -0
  56. package/src/lib/components/console/order-detail-dialog.component.js +976 -0
  57. package/src/lib/components/console/order-detail-dialog.component.js.map +1 -0
  58. package/src/lib/components/console/paid-media.d.ts +127 -0
  59. package/src/lib/components/console/paid-media.js +397 -0
  60. package/src/lib/components/console/paid-media.js.map +1 -0
  61. package/src/lib/components/console/payments-settings-card.component.d.ts +13 -0
  62. package/src/lib/components/console/payments-settings-card.component.js +295 -0
  63. package/src/lib/components/console/payments-settings-card.component.js.map +1 -0
  64. package/src/lib/components/console/pos-page.component.d.ts +13 -0
  65. package/src/lib/components/console/pos-page.component.js +916 -0
  66. package/src/lib/components/console/pos-page.component.js.map +1 -0
  67. package/src/lib/components/console/product-editor-dialog.component.d.ts +32 -0
  68. package/src/lib/components/console/product-editor-dialog.component.js +1374 -0
  69. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -0
  70. package/src/lib/components/console/products-hub-card.component.d.ts +16 -0
  71. package/src/lib/components/console/products-hub-card.component.js +1280 -0
  72. package/src/lib/components/console/products-hub-card.component.js.map +1 -0
  73. package/src/lib/components/console/products-hub-zone.component.d.ts +50 -0
  74. package/src/lib/components/console/products-hub-zone.component.js +200 -0
  75. package/src/lib/components/console/products-hub-zone.component.js.map +1 -0
  76. package/src/lib/components/console/recovery-queue-card.component.d.ts +39 -0
  77. package/src/lib/components/console/recovery-queue-card.component.js +262 -0
  78. package/src/lib/components/console/recovery-queue-card.component.js.map +1 -0
  79. package/src/lib/components/console/registers-card.component.d.ts +21 -0
  80. package/src/lib/components/console/registers-card.component.js +296 -0
  81. package/src/lib/components/console/registers-card.component.js.map +1 -0
  82. package/src/lib/components/console/reservations-card.component.d.ts +14 -0
  83. package/src/lib/components/console/reservations-card.component.js +650 -0
  84. package/src/lib/components/console/reservations-card.component.js.map +1 -0
  85. package/src/lib/components/console/reviews-moderation-card.component.d.ts +8 -0
  86. package/src/lib/components/console/reviews-moderation-card.component.js +235 -0
  87. package/src/lib/components/console/reviews-moderation-card.component.js.map +1 -0
  88. package/src/lib/components/console/shipping-settings-card.component.d.ts +38 -0
  89. package/src/lib/components/console/shipping-settings-card.component.js +560 -0
  90. package/src/lib/components/console/shipping-settings-card.component.js.map +1 -0
  91. package/src/lib/components/console/stock-movements-card.component.d.ts +31 -0
  92. package/src/lib/components/console/stock-movements-card.component.js +333 -0
  93. package/src/lib/components/console/stock-movements-card.component.js.map +1 -0
  94. package/src/lib/components/console/store-settings-card.component.d.ts +14 -0
  95. package/src/lib/components/console/store-settings-card.component.js +300 -0
  96. package/src/lib/components/console/store-settings-card.component.js.map +1 -0
  97. package/src/lib/components/console/storefront-tax-summary-card.component.d.ts +73 -0
  98. package/src/lib/components/console/storefront-tax-summary-card.component.js +408 -0
  99. package/src/lib/components/console/storefront-tax-summary-card.component.js.map +1 -0
  100. package/src/lib/components/console/suppliers-card.component.d.ts +8 -0
  101. package/src/lib/components/console/suppliers-card.component.js +328 -0
  102. package/src/lib/components/console/suppliers-card.component.js.map +1 -0
  103. package/src/lib/components/console/tax-settings-card.component.d.ts +14 -0
  104. package/src/lib/components/console/tax-settings-card.component.js +473 -0
  105. package/src/lib/components/console/tax-settings-card.component.js.map +1 -0
  106. package/src/lib/components/gate.d.ts +39 -0
  107. package/src/lib/components/gate.js +202 -0
  108. package/src/lib/components/gate.js.map +1 -0
  109. package/src/lib/components/gated-video.d.ts +40 -0
  110. package/src/lib/components/gated-video.js +366 -0
  111. package/src/lib/components/gated-video.js.map +1 -0
  112. package/src/lib/components/member-feed.d.ts +32 -0
  113. package/src/lib/components/member-feed.js +198 -0
  114. package/src/lib/components/member-feed.js.map +1 -0
  115. package/src/lib/components/member-recovery.d.ts +35 -0
  116. package/src/lib/components/member-recovery.js +313 -0
  117. package/src/lib/components/member-recovery.js.map +1 -0
  118. package/src/lib/components/member-signin.d.ts +35 -0
  119. package/src/lib/components/member-signin.js +257 -0
  120. package/src/lib/components/member-signin.js.map +1 -0
  121. package/src/lib/components/member-signup.d.ts +34 -0
  122. package/src/lib/components/member-signup.js +287 -0
  123. package/src/lib/components/member-signup.js.map +1 -0
  124. package/src/lib/components/newsletter-signup.d.ts +39 -0
  125. package/src/lib/components/newsletter-signup.js +229 -0
  126. package/src/lib/components/newsletter-signup.js.map +1 -0
  127. package/src/lib/components/product-detail.d.ts +38 -0
  128. package/src/lib/components/product-detail.js +1022 -0
  129. package/src/lib/components/product-detail.js.map +1 -0
  130. package/src/lib/components/product-grid.d.ts +67 -0
  131. package/src/lib/components/product-grid.js +909 -0
  132. package/src/lib/components/product-grid.js.map +1 -0
  133. package/src/lib/components/product-reviews.d.ts +32 -0
  134. package/src/lib/components/product-reviews.js +349 -0
  135. package/src/lib/components/product-reviews.js.map +1 -0
  136. package/src/lib/components/related-products.d.ts +33 -0
  137. package/src/lib/components/related-products.js +232 -0
  138. package/src/lib/components/related-products.js.map +1 -0
  139. package/src/lib/components/reservation-widget.d.ts +33 -0
  140. package/src/lib/components/reservation-widget.js +418 -0
  141. package/src/lib/components/reservation-widget.js.map +1 -0
  142. package/src/lib/components/storefront-payment-element-fallback.d.ts +18 -0
  143. package/src/lib/components/storefront-payment-element-fallback.js +51 -0
  144. package/src/lib/components/storefront-payment-element-fallback.js.map +1 -0
  145. package/src/lib/components/storefront-payment-element.d.ts +78 -0
  146. package/src/lib/components/storefront-payment-element.js +156 -0
  147. package/src/lib/components/storefront-payment-element.js.map +1 -0
  148. package/src/lib/components/wishlist.d.ts +46 -0
  149. package/src/lib/components/wishlist.js +304 -0
  150. package/src/lib/components/wishlist.js.map +1 -0
  151. package/src/lib/constants/bundle-common.d.ts +18 -0
  152. package/src/lib/constants/bundle-common.js +18 -0
  153. package/src/lib/constants/bundle-common.js.map +1 -0
  154. package/src/lib/constants/product-filters.d.ts +35 -0
  155. package/src/lib/constants/product-filters.js +109 -0
  156. package/src/lib/constants/product-filters.js.map +1 -0
  157. package/src/lib/model/commerce-cart.d.ts +52 -0
  158. package/src/lib/model/commerce-cart.js +102 -0
  159. package/src/lib/model/commerce-cart.js.map +1 -0
  160. package/src/lib/model/commerce-connect-transfer.d.ts +243 -0
  161. package/src/lib/model/commerce-connect-transfer.js +231 -0
  162. package/src/lib/model/commerce-connect-transfer.js.map +1 -0
  163. package/src/lib/model/commerce-discounts.d.ts +164 -0
  164. package/src/lib/model/commerce-discounts.js +231 -0
  165. package/src/lib/model/commerce-discounts.js.map +1 -0
  166. package/src/lib/model/commerce-dispute.d.ts +124 -0
  167. package/src/lib/model/commerce-dispute.js +225 -0
  168. package/src/lib/model/commerce-dispute.js.map +1 -0
  169. package/src/lib/model/commerce-gift-cards.d.ts +107 -0
  170. package/src/lib/model/commerce-gift-cards.js +121 -0
  171. package/src/lib/model/commerce-gift-cards.js.map +1 -0
  172. package/src/lib/model/commerce-io.d.ts +36 -0
  173. package/src/lib/model/commerce-io.js +245 -0
  174. package/src/lib/model/commerce-io.js.map +1 -0
  175. package/src/lib/model/commerce-orders.d.ts +1040 -0
  176. package/src/lib/model/commerce-orders.js +1022 -0
  177. package/src/lib/model/commerce-orders.js.map +1 -0
  178. package/src/lib/model/commerce-promotions.d.ts +188 -0
  179. package/src/lib/model/commerce-promotions.js +199 -0
  180. package/src/lib/model/commerce-promotions.js.map +1 -0
  181. package/src/lib/model/commerce-reservations.d.ts +175 -0
  182. package/src/lib/model/commerce-reservations.js +157 -0
  183. package/src/lib/model/commerce-reservations.js.map +1 -0
  184. package/src/lib/model/commerce-shipping.d.ts +316 -0
  185. package/src/lib/model/commerce-shipping.js +484 -0
  186. package/src/lib/model/commerce-shipping.js.map +1 -0
  187. package/src/lib/model/commerce-stock-holds.d.ts +199 -0
  188. package/src/lib/model/commerce-stock-holds.js +190 -0
  189. package/src/lib/model/commerce-stock-holds.js.map +1 -0
  190. package/src/lib/model/commerce-subscription-status.d.ts +67 -0
  191. package/src/lib/model/commerce-subscription-status.js +76 -0
  192. package/src/lib/model/commerce-subscription-status.js.map +1 -0
  193. package/src/lib/model/commerce-tax-decision.d.ts +222 -0
  194. package/src/lib/model/commerce-tax-decision.js +165 -0
  195. package/src/lib/model/commerce-tax-decision.js.map +1 -0
  196. package/src/lib/model/commerce-tax.d.ts +176 -0
  197. package/src/lib/model/commerce-tax.js +92 -0
  198. package/src/lib/model/commerce-tax.js.map +1 -0
  199. package/src/lib/model/commerce.d.ts +551 -0
  200. package/src/lib/model/commerce.js +739 -0
  201. package/src/lib/model/commerce.js.map +1 -0
  202. package/src/lib/model/index.d.ts +40 -0
  203. package/src/lib/model/index.js +40 -0
  204. package/src/lib/model/index.js.map +1 -0
  205. package/src/lib/model/order-figures.d.ts +48 -0
  206. package/src/lib/model/order-figures.js +74 -0
  207. package/src/lib/model/order-figures.js.map +1 -0
  208. package/src/lib/model/plugin-permissions.d.ts +23 -0
  209. package/src/lib/model/plugin-permissions.js +34 -0
  210. package/src/lib/model/plugin-permissions.js.map +1 -0
  211. package/src/lib/model/purchase-analytics.d.ts +186 -0
  212. package/src/lib/model/purchase-analytics.js +216 -0
  213. package/src/lib/model/purchase-analytics.js.map +1 -0
  214. package/src/lib/plugin-config.d.ts +62 -0
  215. package/src/lib/plugin-config.js +78 -0
  216. package/src/lib/plugin-config.js.map +1 -0
  217. package/src/lib/plugin.d.ts +28 -0
  218. package/src/lib/plugin.js +147 -0
  219. package/src/lib/plugin.js.map +1 -0
  220. package/src/lib/server/billing-webhook.d.ts +26 -0
  221. package/src/lib/server/billing-webhook.js +4011 -0
  222. package/src/lib/server/billing-webhook.js.map +1 -0
  223. package/src/lib/server/cancel-order.d.ts +87 -0
  224. package/src/lib/server/cancel-order.js +368 -0
  225. package/src/lib/server/cancel-order.js.map +1 -0
  226. package/src/lib/server/cart-checkout.d.ts +25 -0
  227. package/src/lib/server/cart-checkout.js +976 -0
  228. package/src/lib/server/cart-checkout.js.map +1 -0
  229. package/src/lib/server/cart-cookie.d.ts +32 -0
  230. package/src/lib/server/cart-cookie.js +77 -0
  231. package/src/lib/server/cart-cookie.js.map +1 -0
  232. package/src/lib/server/cart.d.ts +34 -0
  233. package/src/lib/server/cart.js +181 -0
  234. package/src/lib/server/cart.js.map +1 -0
  235. package/src/lib/server/catalog.d.ts +127 -0
  236. package/src/lib/server/catalog.js +277 -0
  237. package/src/lib/server/catalog.js.map +1 -0
  238. package/src/lib/server/checkout.d.ts +36 -0
  239. package/src/lib/server/checkout.js +915 -0
  240. package/src/lib/server/checkout.js.map +1 -0
  241. package/src/lib/server/connect.d.ts +26 -0
  242. package/src/lib/server/connect.js +238 -0
  243. package/src/lib/server/connect.js.map +1 -0
  244. package/src/lib/server/contact-refund.d.ts +117 -0
  245. package/src/lib/server/contact-refund.js +196 -0
  246. package/src/lib/server/contact-refund.js.map +1 -0
  247. package/src/lib/server/download.d.ts +39 -0
  248. package/src/lib/server/download.js +206 -0
  249. package/src/lib/server/download.js.map +1 -0
  250. package/src/lib/server/draft-order.d.ts +26 -0
  251. package/src/lib/server/draft-order.js +706 -0
  252. package/src/lib/server/draft-order.js.map +1 -0
  253. package/src/lib/server/feed.d.ts +24 -0
  254. package/src/lib/server/feed.js +59 -0
  255. package/src/lib/server/feed.js.map +1 -0
  256. package/src/lib/server/fulfill-order.d.ts +97 -0
  257. package/src/lib/server/fulfill-order.js +235 -0
  258. package/src/lib/server/fulfill-order.js.map +1 -0
  259. package/src/lib/server/gate.d.ts +36 -0
  260. package/src/lib/server/gate.js +112 -0
  261. package/src/lib/server/gate.js.map +1 -0
  262. package/src/lib/server/gift-cards.d.ts +42 -0
  263. package/src/lib/server/gift-cards.js +219 -0
  264. package/src/lib/server/gift-cards.js.map +1 -0
  265. package/src/lib/server/low-stock.d.ts +49 -0
  266. package/src/lib/server/low-stock.js +60 -0
  267. package/src/lib/server/low-stock.js.map +1 -0
  268. package/src/lib/server/manual-tax-rate.d.ts +82 -0
  269. package/src/lib/server/manual-tax-rate.js +113 -0
  270. package/src/lib/server/manual-tax-rate.js.map +1 -0
  271. package/src/lib/server/member-feed.d.ts +24 -0
  272. package/src/lib/server/member-feed.js +72 -0
  273. package/src/lib/server/member-feed.js.map +1 -0
  274. package/src/lib/server/member-name-search.d.ts +37 -0
  275. package/src/lib/server/member-name-search.js +42 -0
  276. package/src/lib/server/member-name-search.js.map +1 -0
  277. package/src/lib/server/member-post.d.ts +23 -0
  278. package/src/lib/server/member-post.js +166 -0
  279. package/src/lib/server/member-post.js.map +1 -0
  280. package/src/lib/server/membership-account.d.ts +37 -0
  281. package/src/lib/server/membership-account.js +148 -0
  282. package/src/lib/server/membership-account.js.map +1 -0
  283. package/src/lib/server/membership-admin-password.d.ts +33 -0
  284. package/src/lib/server/membership-admin-password.js +202 -0
  285. package/src/lib/server/membership-admin-password.js.map +1 -0
  286. package/src/lib/server/membership-content.d.ts +23 -0
  287. package/src/lib/server/membership-content.js +105 -0
  288. package/src/lib/server/membership-content.js.map +1 -0
  289. package/src/lib/server/membership-login.d.ts +19 -0
  290. package/src/lib/server/membership-login.js +137 -0
  291. package/src/lib/server/membership-login.js.map +1 -0
  292. package/src/lib/server/membership-logout.d.ts +19 -0
  293. package/src/lib/server/membership-logout.js +35 -0
  294. package/src/lib/server/membership-logout.js.map +1 -0
  295. package/src/lib/server/membership-recover.d.ts +60 -0
  296. package/src/lib/server/membership-recover.js +244 -0
  297. package/src/lib/server/membership-recover.js.map +1 -0
  298. package/src/lib/server/membership-register.d.ts +22 -0
  299. package/src/lib/server/membership-register.js +241 -0
  300. package/src/lib/server/membership-register.js.map +1 -0
  301. package/src/lib/server/membership-reset.d.ts +26 -0
  302. package/src/lib/server/membership-reset.js +88 -0
  303. package/src/lib/server/membership-reset.js.map +1 -0
  304. package/src/lib/server/membership-wishlist.d.ts +23 -0
  305. package/src/lib/server/membership-wishlist.js +89 -0
  306. package/src/lib/server/membership-wishlist.js.map +1 -0
  307. package/src/lib/server/membership.d.ts +96 -0
  308. package/src/lib/server/membership.js +222 -0
  309. package/src/lib/server/membership.js.map +1 -0
  310. package/src/lib/server/native-checkout.d.ts +170 -0
  311. package/src/lib/server/native-checkout.js +193 -0
  312. package/src/lib/server/native-checkout.js.map +1 -0
  313. package/src/lib/server/newsletter.d.ts +23 -0
  314. package/src/lib/server/newsletter.js +323 -0
  315. package/src/lib/server/newsletter.js.map +1 -0
  316. package/src/lib/server/notify-restock.d.ts +22 -0
  317. package/src/lib/server/notify-restock.js +84 -0
  318. package/src/lib/server/notify-restock.js.map +1 -0
  319. package/src/lib/server/order-analytics.d.ts +134 -0
  320. package/src/lib/server/order-analytics.js +263 -0
  321. package/src/lib/server/order-analytics.js.map +1 -0
  322. package/src/lib/server/order-figures.d.ts +33 -0
  323. package/src/lib/server/order-figures.js +220 -0
  324. package/src/lib/server/order-figures.js.map +1 -0
  325. package/src/lib/server/paid-media-delivery.d.ts +173 -0
  326. package/src/lib/server/paid-media-delivery.js +212 -0
  327. package/src/lib/server/paid-media-delivery.js.map +1 -0
  328. package/src/lib/server/pos-order.d.ts +54 -0
  329. package/src/lib/server/pos-order.js +1137 -0
  330. package/src/lib/server/pos-order.js.map +1 -0
  331. package/src/lib/server/process-abandoned.d.ts +54 -0
  332. package/src/lib/server/process-abandoned.js +222 -0
  333. package/src/lib/server/process-abandoned.js.map +1 -0
  334. package/src/lib/server/process-restock.d.ts +42 -0
  335. package/src/lib/server/process-restock.js +219 -0
  336. package/src/lib/server/process-restock.js.map +1 -0
  337. package/src/lib/server/product-card.d.ts +29 -0
  338. package/src/lib/server/product-card.js +54 -0
  339. package/src/lib/server/product-card.js.map +1 -0
  340. package/src/lib/server/product.d.ts +70 -0
  341. package/src/lib/server/product.js +105 -0
  342. package/src/lib/server/product.js.map +1 -0
  343. package/src/lib/server/promotion-hold.d.ts +144 -0
  344. package/src/lib/server/promotion-hold.js +174 -0
  345. package/src/lib/server/promotion-hold.js.map +1 -0
  346. package/src/lib/server/reconcile-stock.d.ts +106 -0
  347. package/src/lib/server/reconcile-stock.js +349 -0
  348. package/src/lib/server/reconcile-stock.js.map +1 -0
  349. package/src/lib/server/refund.d.ts +45 -0
  350. package/src/lib/server/refund.js +607 -0
  351. package/src/lib/server/refund.js.map +1 -0
  352. package/src/lib/server/related.d.ts +24 -0
  353. package/src/lib/server/related.js +104 -0
  354. package/src/lib/server/related.js.map +1 -0
  355. package/src/lib/server/reservation-availability.d.ts +23 -0
  356. package/src/lib/server/reservation-availability.js +111 -0
  357. package/src/lib/server/reservation-availability.js.map +1 -0
  358. package/src/lib/server/reserve-stock.d.ts +156 -0
  359. package/src/lib/server/reserve-stock.js +146 -0
  360. package/src/lib/server/reserve-stock.js.map +1 -0
  361. package/src/lib/server/reserve.d.ts +25 -0
  362. package/src/lib/server/reserve.js +426 -0
  363. package/src/lib/server/reserve.js.map +1 -0
  364. package/src/lib/server/restock-flag.d.ts +202 -0
  365. package/src/lib/server/restock-flag.js +449 -0
  366. package/src/lib/server/restock-flag.js.map +1 -0
  367. package/src/lib/server/reviews.d.ts +51 -0
  368. package/src/lib/server/reviews.js +132 -0
  369. package/src/lib/server/reviews.js.map +1 -0
  370. package/src/lib/server/site-page-enricher.d.ts +42 -0
  371. package/src/lib/server/site-page-enricher.js +149 -0
  372. package/src/lib/server/site-page-enricher.js.map +1 -0
  373. package/src/lib/server/site-page-resolver.d.ts +26 -0
  374. package/src/lib/server/site-page-resolver.js +223 -0
  375. package/src/lib/server/site-page-resolver.js.map +1 -0
  376. package/src/lib/server/stock-hold.d.ts +127 -0
  377. package/src/lib/server/stock-hold.js +258 -0
  378. package/src/lib/server/stock-hold.js.map +1 -0
  379. package/src/lib/server/storefront-tax-record.d.ts +22 -0
  380. package/src/lib/server/storefront-tax-record.js +218 -0
  381. package/src/lib/server/storefront-tax-record.js.map +1 -0
  382. package/src/lib/server/storefront-tax.d.ts +197 -0
  383. package/src/lib/server/storefront-tax.js +245 -0
  384. package/src/lib/server/storefront-tax.js.map +1 -0
  385. package/src/lib/server/stream.d.ts +25 -0
  386. package/src/lib/server/stream.js +191 -0
  387. package/src/lib/server/stream.js.map +1 -0
  388. package/src/lib/server/subscription-portal.d.ts +24 -0
  389. package/src/lib/server/subscription-portal.js +91 -0
  390. package/src/lib/server/subscription-portal.js.map +1 -0
  391. package/src/lib/server/supplier-outbox.d.ts +190 -0
  392. package/src/lib/server/supplier-outbox.js +342 -0
  393. package/src/lib/server/supplier-outbox.js.map +1 -0
  394. package/src/lib/server/supplier-update.d.ts +23 -0
  395. package/src/lib/server/supplier-update.js +289 -0
  396. package/src/lib/server/supplier-update.js.map +1 -0
  397. package/src/lib/server/tax-profile.d.ts +29 -0
  398. package/src/lib/server/tax-profile.js +40 -0
  399. package/src/lib/server/tax-profile.js.map +1 -0
  400. package/src/lib/server.d.ts +32 -0
  401. package/src/lib/server.js +311 -0
  402. package/src/lib/server.js.map +1 -0
  403. package/src/lib/site.d.ts +27 -0
  404. package/src/lib/site.js +134 -0
  405. package/src/lib/site.js.map +1 -0
  406. package/src/lib/utils/escape-html.d.ts +41 -0
  407. package/src/lib/utils/escape-html.js +41 -0
  408. package/src/lib/utils/escape-html.js.map +1 -0
  409. package/src/lib/utils/generate-preset-id.d.ts +19 -0
  410. package/src/lib/utils/generate-preset-id.js +25 -0
  411. package/src/lib/utils/generate-preset-id.js.map +1 -0
  412. package/src/lib/utils/member-continue.d.ts +45 -0
  413. package/src/lib/utils/member-continue.js +49 -0
  414. package/src/lib/utils/member-continue.js.map +1 -0
  415. package/src/lib/utils/use-storefront-purchase-event.d.ts +60 -0
  416. package/src/lib/utils/use-storefront-purchase-event.js +142 -0
  417. package/src/lib/utils/use-storefront-purchase-event.js.map +1 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-orders.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Orders model v1 (AGL-283): line items snapshot the product/variant at\n * purchase time (renames and price changes never rewrite history), a\n * small status machine gates transitions, and totals are integer cents.\n * Docs live at `hosts/{hostId}/orders/{id}`; the Stripe webhook creates\n * them and the orders console (AGL-287) drives transitions. Pure — no\n * I/O here.\n */\n\nimport { stripeIdIsTestMode } from '@aglyn/aglyn/app-utils/stripe-deployment-mode'\nimport type { ProductType } from './commerce'\nimport type { StorefrontTaxMode } from './commerce-tax-decision'\n\nexport type OrderStatus =\n | 'pending'\n | 'paid'\n | 'partially_fulfilled'\n | 'fulfilled'\n | 'delivered'\n | 'cancelled'\n | 'refunded'\n\n/**\n * Where the sale came through. `subscription` is a recurring cycle of a\n * PHYSICAL subscription product (AGL-1750): each paid invoice mints one order\n * so fulfilment has something to pick, pack and label against, and so\n * recurring revenue reaches the surfaces that read `orders`. Digital and\n * service subscriptions still record on the subscription document alone —\n * there is nothing to ship, and AGL-1732's \"a subscription is not an order\"\n * stands for them.\n */\nexport type OrderChannel = 'online' | 'pos' | 'draft' | 'subscription'\n\n/** Snapshot of what was bought — self-contained for history. */\nexport interface OrderLineItem {\n productId: string\n variantId?: string\n /** Display snapshot at purchase time. */\n name: string\n variantLabel?: string\n sku?: string\n productType?: ProductType\n quantity: number\n /** Per-unit price in cents at purchase time. */\n unitAmountCents: number\n /** Supplier at purchase time (dropship routing, AGL-289). */\n supplierId?: string\n /** Fulfillment id once this line ships (AGL-288). */\n fulfillmentId?: string\n}\n\nexport interface OrderTotals {\n itemsCents: number\n shippingCents: number\n taxCents: number\n /** Positive number subtracted from the total. */\n discountCents: number\n totalCents: number\n /** Aglyn platform fee (Connect application fee, AGL-278/307). */\n feeCents: number\n}\n\nexport interface OrderAddress {\n name?: string\n line1?: string\n line2?: string\n city?: string\n state?: string\n postalCode?: string\n country?: string\n phone?: string\n}\n\nexport interface OrderTimelineEvent {\n atMs: number\n /** Machine event key, e.g. 'paid', 'fulfilled', 'refund', 'note'. */\n event: string\n /** Human-readable detail shown in the console timeline. */\n detail?: string\n}\n\nexport interface OrderFulfillment {\n id: string\n lineItemIds: number[]\n carrier?: string\n trackingNumber?: string\n trackingUrl?: string\n atMs: number\n}\n\n/**\n * A card dispute against this order's charge (AGL-1787).\n *\n * The DISTINCTION a chargeback carries, kept off `status` on purpose. A lost\n * dispute leaves the order `refunded` — that is what every reader of the status\n * already means by it, and five entitlement gates (`gate.ts`, `download.ts`,\n * `reviews.ts`, `membership-account.ts` and the glance card) match on the\n * literal `'refunded'`, so a new terminal status would have left the shopper\n * their digital downloads and their verified-purchase review. That is AGL-1546\n * reproduced on the tenant side, and the reason this record sits BESIDE the\n * status rather than replacing it: the money question is answered by `status`\n * and `refundedCents`, the \"by what door\" question by this.\n *\n * Written whole rather than merged into, so a second dispute on the same charge\n * cannot inherit the previous one's `outcome` — see the handler.\n */\nexport interface OrderDispute {\n /** Stripe dispute id (`dp_…`). */\n id: string\n /** Stripe's dispute status verbatim, e.g. `needs_response`, `lost`. */\n status: string\n /** Stripe's reason code, e.g. `fraudulent`, `product_not_received`. */\n reason?: string\n /** Disputed cents — a partial dispute is less than the order total. */\n amountCents: number\n openedAtMs: number\n /** Evidence deadline, when Stripe supplied one. */\n evidenceDueByMs?: number\n closedAtMs?: number\n /** `won` | `lost` | `warning_closed`, set once the dispute closes. */\n outcome?: string\n /**\n * Cents this dispute actually reversed on the order — a LOST dispute only,\n * and capped against what was left, so it is not always `amountCents`.\n */\n reversedCents?: number\n /**\n * Stripe transfer-reversal id (`trr_…`) that pulled the seller's share back\n * from the connected account (AGL-1794) — set only when a reversal was\n * actually created or found already sitting on the transfer.\n */\n transferReversalId?: string\n /**\n * Cents pulled back from the CONNECTED account for this lost dispute\n * (AGL-1794). Its presence — 0 included — is the settle marker for the\n * reversal step: 0 means the step ran and found nothing to reverse (no\n * transfer on the charge, or a transfer with nothing left), recorded so a\n * redelivery does not retry a failure no redelivery can fix.\n */\n reversedTransferCents?: number\n}\n\n/**\n * One line whose stock a reversal MAY need to put back (AGL-1797).\n *\n * Only lines the sale actually DECREMENTED appear here — an untracked variant\n * (`inventory == null`) had nothing taken off it, so it has nothing to return,\n * and a digital line is untracked for that same reason rather than by a\n * type test of its own. A merchant who tracks license stock on a digital\n * product does get it back.\n */\nexport interface OrderRestockLine {\n productId: string\n variantId: string\n /**\n * Units this line sold. It is the MOST that can come back, never a claim\n * that they did: on a partial reversal the merchant reversed some of the\n * money and only they know which goods returned.\n */\n quantity: number\n /** Purchase-time snapshots, so a reader renders the prompt with no product read. */\n name?: string\n variantLabel?: string\n /**\n * Which `lineItems` entry this came from, matching `refundedLineItemIds`\n * (AGL-2325).\n *\n * The index rather than the product, because a cart can hold one product on\n * two lines and a line-scoped refund may name only one of them. It is what\n * lets a SECOND partial refund be told apart from a repeat of the first: a\n * reversal naming a line the open question already covers adds nothing, and\n * one naming a line it misses is a new question rather than noise.\n *\n * Absent on a check written before this shipped, and that absence is read as\n * \"covers the whole order\" — the assumption those checks were written under.\n */\n lineIndex?: number\n}\n\n/**\n * Stock left off the shelf by a reversed order, FLAGGED rather than released\n * (AGL-1797).\n *\n * The checkout webhook decrements variant inventory on a sale and nothing put\n * it back, so a fully reversed order read one unit light forever and the error\n * compounded with every return. The fix is not the obvious increment, because\n * an increment is wrong more often than it is right:\n *\n * - a **returned** item genuinely comes back, and stock should rise — but only\n * once it is RECEIVED, and there is no fulfilment event that records receipt\n * (`OrderFulfillment` has no returned state);\n * - a **refund with no return** — goodwill, damaged, lost in post — leaves the\n * goods gone, so incrementing invents stock the merchant does not have and\n * sells something that is not on the shelf. That is worse than the bug it\n * replaces: under-counting refuses a sale, over-counting takes one it cannot\n * fill;\n * - a **chargeback** is the clearest do-not-restock case of all, since the\n * shopper kept the item and took the money back.\n *\n * And the quantities are not always knowable on a partial reversal: a refund\n * requested as an AMOUNT names no line at all, so \"$17 of a $62 order\" selects\n * nothing. `quantity` is an upper bound there and `fullyReversed` says whether\n * it is a tight one.\n *\n * A refund that DID name its lines is scoped to them (AGL-2325). `refund.ts`\n * records `refundedLineItemIds` with the money (AGL-2454), so the flag asks\n * about the lines that reversal withdrew rather than about the whole order —\n * and `lineIndex` on each line is what lets a second partial withdrawing a\n * DIFFERENT line re-ask, instead of being swallowed by the still-open question\n * about the first.\n *\n * So this records the question instead of guessing the answer, and the merchant\n * answers it from the stock adjustment they already have. The release action is\n * NOT rebuilt here: the products hub's \"Adjust stock\" already writes the\n * variant counts and an `InventoryAdjustment` row with a reason.\n */\nexport interface OrderRestockCheck {\n /** Which door the money left by; the two deserve different default wording. */\n kind: 'refund' | 'chargeback'\n /** Inventory-tracked lines only — exactly what the sale decremented. */\n lines: OrderRestockLine[]\n /** Sum of `lines[].quantity`, denormalized so a badge needs no arithmetic. */\n units: number\n /**\n * False when only part of the money came back, which is what makes\n * `quantity` an upper bound rather than a proposal.\n */\n fullyReversed: boolean\n flaggedAtMs: number\n /**\n * Set once a merchant answers. Absent means the question is still open, and\n * it is the only state a fresh reversal will overwrite.\n */\n resolution?: 'restocked' | 'dismissed'\n resolvedAtMs?: number\n /** Console uid that answered. */\n resolvedBy?: string\n}\n\n/**\n * A cart line a paid order could not record (AGL-2149). All that survives a\n * deleted product is what the shopper's cart asked for.\n */\nexport interface OrderUnresolvedLine {\n productId: string\n variantId?: string\n quantity: number\n}\n\n/** `hosts/{hostId}/orders/{id}` doc. */\nexport interface HostOrder {\n /** Human order number, sequential per host (e.g. #1042). */\n number?: number\n status: OrderStatus\n channel?: OrderChannel\n /**\n * Which location's stock this sale came off, for the multi-location counts\n * of AGL-286. Written by the POS register, the only sale path that decrements\n * a location bucket rather than the flat count — and read back when the order\n * is cancelled (AGL-1808), because putting the units on the flat total when\n * the sale took them out of a bucket leaves the two disagreeing, and the next\n * location-aware write recomputes the total from the buckets and silently\n * erases the restock.\n */\n locationId?: string\n /**\n * The register discount that was applied, and the member who applied it\n * (AGL-2161). Present only on a POS order that carries a discount.\n *\n * `totals.discountCents` records that money came off; these record who\n * decided it should. Without them a full comp read exactly like a\n * correctly-priced sale after the fact, on the one channel where a person is\n * standing in front of the goods and can ring whatever they like. The\n * ceiling that bounds `discountPct` is the org's `posMaxDiscountPct` plugin\n * setting, enforced server-side in `pos-order.ts`.\n */\n discountPct?: number\n discountBy?: string\n lineItems?: OrderLineItem[]\n totals?: OrderTotals\n /**\n * WHICH TAX REGIME this order carried (AGL-2451), resolved at the moment the\n * sale decided it and stamped here rather than re-derived later.\n *\n * `totals.taxCents` says how much tax was charged and nothing about who\n * computed it. Those are different facts about whose registration the money\n * is held under: a `stripe-automatic` storefront sale's tax is computed\n * against AGLYN's registrations and settles into Aglyn's balance (MEASURED —\n * see `server/storefront-tax.ts`), while a `manual` one is the merchant's own\n * rate on their own origin. An order that cannot say which one it carried\n * cannot be reconciled against the return, or corrected afterwards.\n *\n * AGL-2440's merchant report reads the authoritative\n * `storefrontTaxCollected` record; this is the same fact on the single order,\n * and both come from `storefrontTaxMode` so the two cannot drift.\n *\n * ## ABSENT MEANS \"NOT RECORDED\" — AND NOTHING MAY DEFAULT IT\n *\n * Every order written before AGL-2451 shipped genuinely has no stamp, and\n * that is the honest reading. `liftLegacyOrder` deliberately does NOT\n * synthesise one the way it synthesises `totals.taxCents: 0`: it runs on the\n * READ path, its result is spread into merge writes, and a defaulted `none`\n * would overwrite a real `stripe-automatic` — the converter-on-partial-writes\n * hazard, in a place where the destroyed value is a tax fact. The console\n * renders an absent mode as unknown, never as `none`\n * (`describeOrderTaxMode`).\n */\n taxMode?: StorefrontTaxMode\n customerEmail?: string | null\n customerName?: string | null\n /** Storefront customer id once accounts exist (AGL-294). */\n customerId?: string\n shippingAddress?: OrderAddress\n billingAddress?: OrderAddress\n timeline?: OrderTimelineEvent[]\n fulfillments?: OrderFulfillment[]\n note?: string\n couponCode?: string\n /** Stripe references for refunds. */\n paymentIntentId?: string\n checkoutSessionId?: string\n /**\n * The recurring cycle this order fulfils (channel `subscription`,\n * AGL-1750). The order's own doc id is the invoice id — that identity is\n * the redelivery key — and these carry the join back to\n * `subscriptions/{subscriptionId}/invoices/{invoiceId}`.\n */\n subscriptionId?: string\n invoiceId?: string\n /** Draft orders (AGL-287): the link sent to the buyer. */\n paymentLinkUrl?: string\n refundedCents?: number\n /**\n * Line indexes an admin refunded BY NAME (AGL-2454), and therefore the lines\n * whose digital entitlements are withdrawn.\n *\n * A refund carries an AMOUNT, not lines — `refund.ts` takes `amountCents`\n * and Stripe knows nothing about what was in the basket — so a partial refund\n * cannot in general be attributed to anything. That is why five entitlement\n * gates matched the literal `'refunded'` on `status` and a 99%-refunded order\n * kept every download, licence key, gated page and verified review.\n *\n * This is the case where attribution IS possible: the console refund dialog\n * lets an admin pick the lines they are refunding, and when it does the\n * amount is computed FROM those lines rather than typed beside them. An\n * amount-only refund still revokes nothing per-line — deciding for the\n * merchant which lines a bare figure covers would be a guess about their\n * goods — but it is no longer silent: `orderRefundState` reports it, the\n * console shows it, and the order timeline records it.\n *\n * Indexes rather than product ids, because a cart can hold two lines of the\n * same product (different variants) and only one may be coming back.\n */\n refundedLineItemIds?: number[]\n /** The card dispute against this charge, open or settled (AGL-1787). */\n dispute?: OrderDispute\n /** Stock a reversal left off the shelf, awaiting the merchant (AGL-1797). */\n restockCheck?: OrderRestockCheck\n /**\n * Cart lines the webhook could not price because the product was deleted\n * between session creation and payment (AGL-2149). Present ONLY on an order\n * that is short of what the shopper was charged: `totals.itemsCents` is\n * missing these lines while `amountCents` still holds the full\n * `amount_total`, and this is the record of which lines the difference is.\n *\n * Deliberately NOT an `OrderLineItem[]`: the product doc is gone, so there is\n * no name, no price and no type to record — only what the cart asked for.\n */\n unresolvedLines?: OrderUnresolvedLine[]\n createdAtMs?: number\n // Legacy Commerce Starter fields (AGL-90) kept readable.\n productId?: string\n amountCents?: number\n feeCents?: number\n}\n\n/**\n * Legal status transitions. Refund/cancel policies: anything paid can\n * refund; only unfulfilled orders cancel (refund instead once shipped).\n *\n * `cancelled` IS NOT TERMINAL, and treating it as one trapped money (AGL-2149).\n * `cancel-order.ts` accepts a **paid** order — `paid: [… 'cancelled' …]` above\n * — and moves no money when it does: it flips the status and returns the stock.\n * `refund.ts` gates on `canTransitionOrder(order.status, 'refunded')`, so with\n * `cancelled: []` the refund door closed behind the cancel and answered \"orders\n * in cancelled cannot refund\" forever. An admin who cancelled a paid order\n * instead of refunding it — the two buttons sit next to each other in the order\n * dialog — had permanently locked the shopper's money out of every refund route\n * this product has. The shopper's only remaining recourse was a chargeback,\n * which costs the merchant the goods, the money AND the dispute fee.\n *\n * Whether cancelling a PAID order should refuse, or refund on the merchant's\n * behalf, is a real product question and is deliberately NOT answered here:\n * either would change what an existing console button does to money. Making the\n * money reachable is the part that must not wait for that answer.\n *\n * A cancelled order that never took money simply has nothing to refund —\n * `refund.ts` resolves no payment intent and answers \"No payment to refund\" —\n * so the widened edge costs a lapsed `pending` order nothing.\n */\nconst ORDER_TRANSITIONS: Record<OrderStatus, OrderStatus[]> = {\n pending: ['paid', 'cancelled'],\n paid: ['partially_fulfilled', 'fulfilled', 'cancelled', 'refunded'],\n partially_fulfilled: ['fulfilled', 'refunded'],\n fulfilled: ['delivered', 'refunded'],\n delivered: ['refunded'],\n cancelled: ['refunded'],\n refunded: [],\n}\n\nexport function canTransitionOrder(\n from: OrderStatus,\n to: OrderStatus,\n): boolean {\n return (ORDER_TRANSITIONS[from] ?? []).includes(to)\n}\n\n/**\n * One money part, coerced to a whole non-negative number of cents (AGL-2224).\n *\n * `Math.max(0, Math.round(x))` is NOT this guard, and the difference is the\n * whole defect: `Math.max` and `Math.min` PROPAGATE `NaN` rather than\n * discarding it, so a single non-finite input made every field below `NaN` and\n * `totalCents` with them. That is not a cosmetic wrong number — it is a number\n * that defeats comparison. `cashReceivedCents < NaN` is `false`, so the POS\n * \"cash received is short\" guard passed a sale that had taken no money; and a\n * `NaN` written to Firestore (a legal double there) poisons every downstream\n * sum, so ONE bad order renders a merchant's whole revenue figure `NaN`\n * forever after.\n *\n * The inputs that can be non-finite are real, not theoretical: a POS\n * `discountPct` that is not a number, a product whose `priceUsd` is a string\n * or absent (`Number(undefined) * 100`), a `taxCents` derived from either. So\n * this coerces at the boundary every order in the product passes through,\n * rather than at each of the five callers, and answers 0 — the only value that\n * cannot silently overstate what the shopper owes.\n */\nconst wholeCents = (value: unknown): number => {\n const cents = Math.round(Number(value ?? 0))\n return Number.isFinite(cents) && cents > 0 ? cents : 0\n}\n\n/**\n * Split `totalCents` across `weights` so the parts sum to it EXACTLY.\n *\n * Largest-remainder (Hamilton) apportionment. Each weight takes its exact\n * share, the shares are floored, and the cents left over by flooring are handed\n * one each to the largest fractional parts, ties going to the lower index so\n * the answer is deterministic for a given input.\n *\n * The exactness is the whole point and it is a money property, not a\n * neatness one: `Math.round` per line loses or invents cents against the total\n * — three lines splitting a 10¢ discount round to 3+3+3=9 and the missing cent\n * has to come from somewhere. A refund built on a split that does not close is\n * a reconciliation defect that surfaces months later against Stripe's numbers.\n *\n * Pure and total. A non-positive total, an empty weight list, or weights that\n * sum to nothing all answer zeros — never a division by zero, never a NaN\n * propagated into an amount someone is charged.\n */\nexport function apportionCents(\n weights: readonly number[],\n totalCents: number,\n): number[] {\n const safe = (weights ?? []).map((weight) =>\n Math.max(0, Math.round(Number(weight ?? 0))),\n )\n const basis = safe.reduce((sum, weight) => sum + weight, 0)\n const total = Math.max(0, Math.round(Number(totalCents ?? 0)))\n if (safe.length === 0 || basis <= 0 || total <= 0) return safe.map(() => 0)\n // Never hand back more than there is to split. A discount larger than the\n // items it came off is a data fault, and apportioning it in full would\n // credit lines with money the order never carried.\n const pot = Math.min(total, basis)\n const exact = safe.map((weight) => (weight * pot) / basis)\n const shares = exact.map((value) => Math.floor(value))\n let remainder = pot - shares.reduce((sum, share) => sum + share, 0)\n const order = exact\n .map((value, index) => ({ index, fraction: value - Math.floor(value) }))\n .sort((a, b) => b.fraction - a.fraction || a.index - b.index)\n for (const entry of order) {\n if (remainder <= 0) break\n shares[entry.index] += 1\n remainder -= 1\n }\n return shares\n}\n\n/**\n * What refunding the named lines is actually worth.\n *\n * A line's LIST value is `unitAmountCents x quantity`, and that is what the\n * refund route used to hand back. It is the wrong number on any order that\n * carried an order-level discount, because the buyer never paid it: a $10\n * coupon on two $50 lines means each line cost $45, and refunding one at $50\n * pays back $5 the buyer never spent. The order then has less left than its\n * remaining line is worth, so the SECOND line refund is refused outright and\n * the merchant cannot finish the job they started.\n *\n * So each line carries its share of the discount, apportioned by list value\n * through {@link apportionCents} — which guarantees the shares sum to the whole\n * discount, so refunding every line returns exactly `itemsCents - discountCents`\n * and no cent is stranded or invented.\n *\n * SHIPPING AND TAX ARE DELIBERATELY NOT IN THIS FIGURE. Refunding a line\n * returns what the goods cost. Shipping is charged for the consignment rather\n * than the line, so no split of it is defensible without knowing whether the\n * parcel still ships; tax follows the goods but is Stripe's to recompute, and\n * an order whose tax was collected under Aglyn's own registration\n * (`taxMode: 'stripe-automatic'`) is not one this function may quietly decide\n * to hand back. Both remain whole-order concerns, refundable by amount.\n *\n * Pure: unknown indexes contribute nothing rather than throwing.\n */\nexport function orderLineRefundCents(\n order: Pick<Partial<HostOrder>, 'lineItems' | 'totals'>,\n lineIndexes: readonly number[],\n): number {\n const lines = order?.lineItems ?? []\n const gross = lines.map((line) =>\n Math.max(\n 0,\n Math.round(Number(line?.unitAmountCents ?? 0)) *\n Math.max(1, Math.round(Number(line?.quantity ?? 1))),\n ),\n )\n const shares = apportionCents(\n gross,\n Math.max(0, Math.round(Number(order?.totals?.discountCents ?? 0))),\n )\n const wanted = new Set(\n (lineIndexes ?? []).filter(\n (index) => Number.isInteger(index) && index >= 0 && index < lines.length,\n ),\n )\n let cents = 0\n for (const index of wanted) cents += gross[index] - shares[index]\n return Math.max(0, cents)\n}\n\n/**\n * A REHEARSAL IS NOT REVENUE.\n *\n * A smoke-test checkout writes a real order document. Stripe never moved money\n * for it — the session id is `cs_test_…` — but every surface that sums paid\n * orders counted it, so a storefront with one test order and no sales reported\n * revenue it had never earned. Found in production: a single $18.00 order from\n * an end-to-end run, standing as the whole platform's storefront revenue.\n *\n * ## Two signals, in order of trust\n *\n * `livemode` is a RECORDED FACT and wins whenever it is present: the webhook\n * knows which Stripe environment an event came from and now writes it onto the\n * order. Only a literal boolean counts, the same three-valued reading every\n * other money gate in this codebase uses.\n *\n * The session id prefix is the FALLBACK, for the orders written before\n * anything recorded the fact. It is Stripe's convention rather than our data,\n * so it lives behind `stripeIdIsTestMode` and is not spelled out here.\n *\n * ## An unknowable order is LIVE\n *\n * An order with no `livemode` and no Stripe session id — a POS cash sale, a\n * folio charge, a draft order paid offline — is real money and is counted.\n * Answering \"test\" for anything we cannot identify would zero genuine sales,\n * which is the one direction this must never fail in: a merchant under-reporting\n * their own revenue has no way to tell it is happening.\n */\nexport function orderIsTestMode(\n order: Pick<Partial<HostOrder>, 'checkoutSessionId'> & {\n livemode?: unknown\n /** The Firestore doc id, which for a storefront order IS the session id. */\n $id?: unknown\n },\n): boolean {\n if (typeof order?.livemode === 'boolean') return !order.livemode\n // `$id` as well as the field: every storefront order is keyed BY its session\n // id, so the doc id carries the same signal and is present on rows read\n // straight out of Firestore even where the field was never written. A POS or\n // draft order has an auto-generated id, which matches no Stripe prefix and\n // correctly reads as live.\n return (\n stripeIdIsTestMode(order?.checkoutSessionId) || stripeIdIsTestMode(order?.$id)\n )\n}\n\n/** Sums line items and folds in shipping/tax/discount/fee, all cents. */\nexport function computeOrderTotals(\n lineItems: OrderLineItem[],\n parts?: Partial<Pick<OrderTotals, 'shippingCents' | 'taxCents' | 'discountCents' | 'feeCents'>>,\n): OrderTotals {\n const itemsCents = (lineItems ?? []).reduce(\n (sum, line) => sum + wholeCents(line?.unitAmountCents * line?.quantity),\n 0,\n )\n const shippingCents = wholeCents(parts?.shippingCents)\n const taxCents = wholeCents(parts?.taxCents)\n const discountCents = Math.min(\n wholeCents(parts?.discountCents),\n itemsCents + shippingCents,\n )\n return {\n itemsCents,\n shippingCents,\n taxCents,\n discountCents,\n feeCents: wholeCents(parts?.feeCents),\n totalCents: itemsCents + shippingCents + taxCents - discountCents,\n }\n}\n\n/**\n * The completed Checkout Session fields an online order's totals are built\n * from. Typed structurally rather than against Stripe's SDK: the plugin talks\n * to Stripe over raw `fetch` and never installs the package.\n */\nexport interface CheckoutSessionTotalsSource {\n amount_total?: unknown\n total_details?: {\n amount_tax?: unknown\n amount_shipping?: unknown\n amount_discount?: unknown\n } | null\n}\n\n/**\n * Stored `OrderTotals` for an `online` order, from the completed session.\n *\n * AGL-1698: the webhook used to read `amount_tax` and `amount_discount` and\n * silently skip their third sibling, so `computeOrderTotals` defaulted\n * `shippingCents` to 0 on every online order while the shipping the shopper\n * paid sat inside `amount_total`. The stored parts then did not sum to the\n * stored total, and every merchant reconciling their own books against these\n * records understated shipping by exactly the amount charged. `amount_shipping`\n * is the figure to read — `shipping_cost.amount_total` carries the same number\n * but is null unless a rate was chosen, whereas `total_details.amount_shipping`\n * is always present and sits beside the two fields already read.\n *\n * `totalCents` still comes from Stripe's `amount_total` verbatim rather than\n * from our arithmetic: `itemsCents` is priced from the host's product docs, so\n * a price edit between session creation and webhook delivery would otherwise\n * make our sum, not Stripe's charge, the stored truth. With shipping passed the\n * two agree by construction — which is now an invariant a fixture can pin\n * rather than a discrepancy that papers over a missing part.\n *\n * Note this also unclamps the discount correctly: `computeOrderTotals` caps\n * `discountCents` at `itemsCents + shippingCents`, so a discount that reached\n * into shipping was previously clamped down as well.\n */\nexport interface CheckoutSessionTotalsParts {\n /** Aglyn's cut, from the session metadata rather than from Stripe. */\n feeCents?: number\n /**\n * Tax we charged as an ordinary Stripe line item (AGL-1711). It is inside\n * `amount_total` but Stripe was never told it was tax, so it is absent from\n * `total_details.amount_tax` and has to be supplied by the caller that built\n * the session. Added to Stripe's figure, not substituted for it: the two are\n * mutually exclusive by construction — `checkout.ts` adds the manual line\n * only in `manual` tax mode and sets `automatic_tax` only in `stripe` mode —\n * so summing is right in every reachable case and correct in principle if\n * both were ever charged at once.\n *\n * A manual-tax SUBSCRIPTION session is the third construction (AGL-1751):\n * there the tax is a real Stripe Tax Rate (a one-time line would bill on\n * the first invoice only), `amount_tax` carries it, and `checkout.ts`\n * writes `metadata[taxCents]` as 0 — the exclusivity this sum rests on,\n * kept from the other side.\n */\n lineItemTaxCents?: number\n /**\n * A discount applied by lowering the unit price we sent to Stripe rather\n * than as a Stripe discount (AGL-1711). Same shape as `lineItemTaxCents`:\n * invisible to `total_details.amount_discount`, so it is added to it.\n */\n pricedInDiscountCents?: number\n}\n\nexport function computeCheckoutSessionTotals(\n lineItems: OrderLineItem[],\n session: CheckoutSessionTotalsSource | null | undefined,\n parts?: CheckoutSessionTotalsParts,\n): OrderTotals {\n const details = session?.total_details ?? {}\n const totals = computeOrderTotals(lineItems, {\n feeCents: Number(parts?.feeCents ?? 0),\n taxCents:\n Number(details?.amount_tax ?? 0) + Number(parts?.lineItemTaxCents ?? 0),\n shippingCents: Number(details?.amount_shipping ?? 0),\n discountCents:\n Number(details?.amount_discount ?? 0) +\n Number(parts?.pricedInDiscountCents ?? 0),\n })\n const amountTotal = Number(session?.amount_total ?? NaN)\n return {\n ...totals,\n totalCents: Number.isFinite(amountTotal) ? amountTotal : totals.totalCents,\n }\n}\n\n/** Non-negative integer cents from an untyped metadata value; 0 otherwise. */\nfunction metadataCents(value: unknown): number {\n const cents = Math.round(Number(value ?? 0))\n return Number.isFinite(cents) && cents > 0 ? cents : 0\n}\n\n/** The buy-now Checkout Session as the webhook sees it — metadata included. */\nexport interface BuyNowSessionSource extends CheckoutSessionTotalsSource {\n metadata?: Record<string, unknown> | null\n}\n\n/** What the host's product doc contributes to the line-item snapshot. */\nexport interface BuyNowProductSnapshot {\n /** Product name at purchase time. */\n name: string\n /** Joined variant options, e.g. `Large / Blue`. */\n variantLabel?: string\n sku?: string\n productType?: ProductType\n supplierId?: string\n}\n\n/**\n * The stored line items and totals for a `commerce-order` (buy-now) session\n * (AGL-1711).\n *\n * ## What was wrong\n *\n * The webhook built the whole order from one number — it read\n * `object.amount_total` into `amountCents`, wrote a single line item with\n * `quantity` literal 1 and `unitAmountCents` set to that `amountCents`, and\n * passed `computeOrderTotals` nothing but `feeCents`.\n *\n * `amount_total` is the ENTIRE charge, so the merchant's record said the\n * product's unit price was the whole session total, that one unit was sold, and\n * that tax and discount were zero. A 3 × $100 purchase recorded as 1 × $300.\n *\n * The dangerous property, and why this outlived AGL-1698: it is not internally\n * inconsistent. `itemsCents` equalled `totalCents`, so the parts summed and any\n * arithmetic check passed while every individual component was wrong. The\n * useful test is not \"do the parts sum\" but \"does each part match what Stripe\n * actually charged\", which is what the fixtures assert component by component.\n *\n * ## Why metadata, when AGL-1698's lesson was to read Stripe's own fields\n *\n * Two of the four parts are genuinely absent from Stripe's decomposition, and\n * `checkout.ts` is what hid them:\n *\n * - **Tax.** In `manual` mode the tax is appended as `line_items[1]`, a normal\n * product line labelled e.g. \"Tax (8.25%)\". Stripe does not know it is tax,\n * so `total_details.amount_tax` is 0 while the money sits in `amount_total`.\n * (In `stripe` mode `automatic_tax` makes `amount_tax` real — and it was not\n * read either, so that tax was lost as well.)\n * - **Discount.** A host coupon is applied by lowering the unit price we send,\n * not as a Stripe discount, so `total_details.amount_discount` is 0.\n *\n * So `checkout.ts` now records both figures, plus the list unit price, in the\n * session metadata as it computes them. This is NOT the reconstruction AGL-1698\n * warned against: the guard there is against pricing from the host's product\n * docs at webhook time, where an edit between session creation and delivery\n * makes our sum disagree with the actual charge. Metadata is a snapshot of the\n * numbers we handed Stripe, frozen at session creation, so it cannot drift.\n * Everything Stripe does know — `amount_total`, `amount_tax`, `amount_shipping`,\n * `amount_discount` — still comes from Stripe, via the shared\n * `computeCheckoutSessionTotals` rather than a parallel decomposition.\n *\n * Shipping is read even though `checkout.ts` declares no `shipping_options`\n * today (AGL-1720): the read is not conditioned on that, so the figure lands on\n * its own the moment buy-now starts charging shipping.\n *\n * ## Sessions created before this change\n *\n * They carry `quantity` (always sent) but none of the three new keys, so the\n * unit price falls back to what Stripe charged per unit, derived from\n * `amount_total` with tax, shipping and discount taken back out. Those orders\n * still reconcile against `amount_total` and their quantity is now right; what\n * cannot be recovered is a priced-in coupon, which stays folded into the unit\n * price exactly as it is today. Deriving from the product doc instead would\n * make `itemsCents` gross with no matching `discountCents`, breaking the sum.\n *\n * ## Worked example — the spec fixture\n *\n * Three $100 units, a 10% host coupon, manual destination tax at 8.25%:\n *\n * listUnit 10000 metadata `unitAmountCents`\n * × quantity 3 metadata `quantity`\n * = itemsCents 30000\n * - discountCents 3000 metadata `discountCents` (priced into the\n * 9000 unit price sent to Stripe)\n * + taxCents 2228 metadata `taxCents` (Stripe `line_items[1]`;\n * `total_details.amount_tax` is 0)\n * + shippingCents 0 Stripe `total_details.amount_shipping`\n * = totalCents 29228 Stripe `amount_total`, verbatim\n *\n * The pre-fix record for the same purchase: `1 × 29228`, tax 0, discount 0 —\n * which also sums to 29228.\n *\n * ## Also the subscription sale record (AGL-1732)\n *\n * `checkout.ts` builds a subscription session with the same function and the\n * same metadata snapshot — only `mode` differs — so the initial charge of a\n * storefront subscription decomposes identically. The webhook's\n * `commerce-subscription` branch stores the result on the subscription\n * document rather than as an order; the arithmetic is the same either way,\n * which is why it lives here and is not duplicated there.\n */\nexport function computeBuyNowOrder(\n session: BuyNowSessionSource | null | undefined,\n snapshot: BuyNowProductSnapshot,\n): { lineItems: OrderLineItem[]; totals: OrderTotals } {\n const metadata = (session?.metadata ?? {}) as Record<string, unknown>\n const details = session?.total_details ?? {}\n const rawQuantity = Math.round(Number(metadata.quantity ?? 1))\n const quantity =\n Number.isFinite(rawQuantity) && rawQuantity > 0 ? rawQuantity : 1\n const lineItemTaxCents = metadataCents(metadata.taxCents)\n const pricedInDiscountCents = metadataCents(metadata.discountCents)\n // What Stripe charged for the goods themselves, used only when the session\n // predates the `unitAmountCents` metadata: strip every non-goods component\n // back out of the total and add the discount back in.\n const goodsCents =\n Number(session?.amount_total ?? 0) -\n Number(details?.amount_tax ?? 0) -\n Number(details?.amount_shipping ?? 0) -\n lineItemTaxCents +\n Number(details?.amount_discount ?? 0) +\n pricedInDiscountCents\n const unitAmountCents =\n metadataCents(metadata.unitAmountCents) ||\n Math.max(0, Math.round(goodsCents / quantity))\n const variantId = String(metadata.variantId ?? '')\n const lineItems: OrderLineItem[] = [\n {\n productId: String(metadata.productId ?? ''),\n ...(variantId ? { variantId } : {}),\n name: snapshot.name,\n ...(snapshot.variantLabel ? { variantLabel: snapshot.variantLabel } : {}),\n ...(snapshot.sku ? { sku: snapshot.sku } : {}),\n ...(snapshot.productType ? { productType: snapshot.productType } : {}),\n ...(snapshot.supplierId ? { supplierId: snapshot.supplierId } : {}),\n quantity,\n unitAmountCents,\n },\n ]\n return {\n lineItems,\n totals: computeCheckoutSessionTotals(lineItems, session, {\n feeCents: metadataCents(metadata.feeCents),\n lineItemTaxCents,\n pricedInDiscountCents,\n }),\n }\n}\n\n/** One line on a Stripe invoice, structurally typed like the session above. */\nexport interface SubscriptionInvoiceLine {\n /** The line total in cents, after any line-level discount, excluding tax. */\n amount?: unknown\n quantity?: unknown\n description?: unknown\n /** True on the credit/charge pair a mid-cycle plan switch generates. */\n proration?: unknown\n price?: {\n unit_amount?: unknown\n recurring?: { interval?: unknown } | null\n } | null\n}\n\n/**\n * The paid-invoice fields a renewal's totals are built from (AGL-1743).\n *\n * ## An invoice is not a Checkout Session\n *\n * This was checked field by field rather than assumed, and the two objects\n * agree on almost nothing:\n *\n * - **There is no `total_details` on an invoice at all.** That object is a\n * Checkout Session field. `computeCheckoutSessionTotals` cannot be handed an\n * invoice — every part would read 0 and the whole renewal would decompose to\n * `amount_total` with nothing in it, which is exactly the AGL-1711 failure\n * shape (internally consistent, individually wrong).\n * - **Tax** is `tax` (a scalar) on the API versions this repo pins, and\n * `total_taxes[]` on newer ones, where the scalar was removed. Both are read,\n * the scalar preferred, because a webhook endpoint's version is dashboard\n * configuration this repo cannot see.\n * - **Discount** is `total_discount_amounts[]`, an array of per-discount\n * amounts, not a single `amount_discount`.\n * - **Shipping** is `shipping_cost.amount_total` — note AGL-1698 preferred\n * `total_details.amount_shipping` over exactly this field ON A SESSION,\n * because there it is null unless a rate was chosen. On an invoice it is the\n * only form there is.\n * - **The fee** is a real field here: a subscription carries\n * `application_fee_percent`, so every invoice reports the resulting\n * `application_fee_amount`. The session path has to read it out of metadata.\n * - **What was bought** is `lines.data[]` rather than the session's metadata\n * snapshot — `checkout.ts` puts only `type`, `hostId` and `productId` on\n * `subscription_data[metadata]`, so the quantity and unit price of a renewal\n * have to come from the invoice itself.\n *\n * The arithmetic is still the shared one: the fields above are mapped onto the\n * session shape and handed to `computeCheckoutSessionTotals`, so a renewal and\n * a sale clamp, sum and reconcile identically.\n */\nexport interface SubscriptionInvoiceSource {\n /** What actually arrived — the figure this records as collected. */\n amount_paid?: unknown\n total?: unknown\n subtotal?: unknown\n /** Total tax; removed in favor of `total_taxes` on newer API versions. */\n tax?: unknown\n total_taxes?: readonly { amount?: unknown }[] | null\n total_tax_amounts?: readonly { amount?: unknown }[] | null\n total_discount_amounts?: readonly { amount?: unknown }[] | null\n shipping_cost?: { amount_total?: unknown } | null\n application_fee_amount?: unknown\n /** Why Stripe raised it: `subscription_cycle`, `subscription_update`, … */\n billing_reason?: unknown\n lines?: { data?: readonly SubscriptionInvoiceLine[] | null } | null\n}\n\n/**\n * The base a subscription invoice's platform fee SHOULD be taken on\n * (AGL-2317): post-discount items, with tax and shipping removed.\n *\n * Every one-time door — `checkout.ts`, `cart-checkout.ts`, `draft-order.ts`,\n * `pos-order.ts` and (since AGL-2315) bookings — sends a cents amount computed\n * on items alone. The recurring door sent `application_fee_percent`, which\n * Stripe applies to the WHOLE invoice, so Aglyn took a cut of sales tax — money\n * that is the state's — and of shipping. On the issue's worked example ($30/mo\n * digital, Business 2%, an 8.25% TX rate) the one-time base is $30.00 → 60¢ and\n * the invoice total is $32.48 → 65¢.\n *\n * `total` and not a re-summed `lines.data[]`, deliberately. Stripe's own total\n * is already net of every invoice-level discount and of any proration CREDIT,\n * both of which `computeSubscriptionInvoiceOrder` drops (it floors a line at 0,\n * which is right for a stored line item and wrong for a fee base — a mid-cycle\n * downgrade credit reduces what the merchant is actually paid). Subtracting the\n * two parts Stripe reports separately leaves exactly what was charged for goods.\n *\n * Tax is read on both spellings for the reason stated on `SubscriptionInvoiceSource`\n * — the scalar was removed on newer API versions and the endpoint's version is\n * dashboard configuration this repo cannot see. Reading only one of them would\n * silently value tax at 0 and hand back the whole invoice total as the base,\n * which is the very bug this closes.\n */\nexport function subscriptionInvoiceFeeBasisCents(\n invoice: SubscriptionInvoiceSource | null | undefined,\n): number {\n const totalCents = metadataCents(invoice?.total)\n if (totalCents <= 0) return 0\n const scalarTax = Number(invoice?.tax ?? NaN)\n const taxCents =\n Number.isFinite(scalarTax) && scalarTax > 0\n ? scalarTax\n : sumAmounts(invoice?.total_taxes ?? invoice?.total_tax_amounts)\n const shippingCents = metadataCents(invoice?.shipping_cost?.amount_total)\n return Math.max(0, totalCents - Math.max(0, taxCents) - shippingCents)\n}\n\n/**\n * What the platform fee on a paid subscription invoice WOULD have been on the\n * items-only base, at the rate Stripe actually applied (AGL-2317).\n *\n * ## The rate is never named here, on purpose\n *\n * Pricing is locked for Sept 1, so this is a BASE correction and must not be\n * able to become a rate change. It therefore takes no plan, no entitlement and\n * no `resolveTransactionFeePct` call: it scales the fee Stripe already charged\n * by `base / total`. Whatever rate produced `application_fee_amount` — the\n * sale-time one, a rate AGL-2289 has since re-priced, or a staff override —\n * comes through untouched, and the only thing removed is the portion that was\n * taken on tax and shipping. A test that changed a rate could not make this\n * function agree with it.\n *\n * `Math.max(1, …)` matches `checkout.ts`: where a rate applies at all, the\n * floor is a cent, never zero. An invoice with no fee, no total, or nothing but\n * tax answers 0 and asks for no correction it cannot justify.\n */\nexport function subscriptionInvoiceItemsOnlyFeeCents(\n invoice: SubscriptionInvoiceSource | null | undefined,\n): number {\n const chargedCents = metadataCents(invoice?.application_fee_amount)\n if (chargedCents <= 0) return 0\n const totalCents = metadataCents(invoice?.total)\n // Nothing to scale against — leave what Stripe took rather than inventing a\n // reduction from a total we cannot read.\n if (totalCents <= 0) return chargedCents\n const basisCents = subscriptionInvoiceFeeBasisCents(invoice)\n if (basisCents <= 0) return 0\n // Tax-free and shipping-free invoices — the majority — land here and are\n // byte-identical to today, which is what makes this safe inside the freeze.\n if (basisCents >= totalCents) return chargedCents\n return Math.max(1, Math.round((chargedCents * basisCents) / totalCents))\n}\n\n/**\n * The recurring goods a storefront subscription's `application_fee_percent`\n * is sized against when a paid invoice re-prices it (AGL-2655).\n *\n * The percent carries Stripe's fixed 30¢ folded into a rate, so it depends\n * on the amount it will be applied to — and the amount that matters is the\n * NEXT cycle's, which nobody has yet. The best predictor is this cycle's\n * items-only basis, for a cycle that bills the full recurring price:\n * `subscription_cycle`, and `subscription_create` for the opening charge.\n * Any other reason — a `subscription_update` proration, a threshold\n * invoice — bills a fraction, and a percent sized on a fraction would be\n * applied to the following full cycle and over-recover on it. Those, and a\n * $0 opening invoice (a trial converts later), fall back to what the sale\n * recorded: the sold lines' price × quantity, the stable figure the\n * subscription bills every cycle it is not being adjusted.\n *\n * Zero when neither source knows — and the caller then leaves the rate as it\n * stands rather than sizing a percent on nothing.\n */\nexport function subscriptionRecurringBasisCents(\n invoice: SubscriptionInvoiceSource | null | undefined,\n soldLineItems:\n | readonly Pick<OrderLineItem, 'quantity' | 'unitAmountCents'>[]\n | null\n | undefined,\n): number {\n const reason = String(invoice?.billing_reason ?? '')\n const billsTheFullPrice =\n reason === 'subscription_cycle' || reason === 'subscription_create'\n const cycleBasis = billsTheFullPrice\n ? subscriptionInvoiceFeeBasisCents(invoice)\n : 0\n if (cycleBasis > 0) return cycleBasis\n return (soldLineItems ?? []).reduce((sum, line) => {\n const unit = Math.round(Number(line?.unitAmountCents ?? 0))\n const quantity = Math.round(Number(line?.quantity ?? 0))\n if (!Number.isFinite(unit) || !Number.isFinite(quantity)) return sum\n return sum + Math.max(0, unit) * Math.max(0, quantity)\n }, 0)\n}\n\n/** Sum of an `[{ amount }]` list, ignoring anything unreadable. */\nfunction sumAmounts(list: readonly { amount?: unknown }[] | null | undefined) {\n return (list ?? []).reduce((sum, entry) => {\n const amount = Number(entry?.amount ?? 0)\n return sum + (Number.isFinite(amount) ? amount : 0)\n }, 0)\n}\n\n/** `price.recurring.interval` when it is one we sell, else undefined. */\nfunction lineInterval(\n line: SubscriptionInvoiceLine | null | undefined,\n): 'month' | 'year' | undefined {\n const interval = line?.price?.recurring?.interval\n return interval === 'month' || interval === 'year' ? interval : undefined\n}\n\n/**\n * The line that describes the SUBSCRIPTION being billed.\n *\n * `lines.data[0]` is not it, for the AGL-1640 reason: a mid-cycle plan switch\n * invoices the proration against the OLD price ahead of the new plan, and an\n * invoice also carries one-off items and credits, any of which can sort first.\n * Prefer a non-proration line stating a cadence; fall back to a proration one,\n * since Stripe requires every recurring item on one subscription to share a\n * cadence; fall back to the first line so a renewal still records a name.\n */\nexport function selectSubscriptionInvoiceLine(\n invoice: SubscriptionInvoiceSource | null | undefined,\n): SubscriptionInvoiceLine | undefined {\n const lines = invoice?.lines?.data ?? []\n return (\n lines.find((line) => !line?.proration && lineInterval(line)) ??\n lines.find((line) => lineInterval(line)) ??\n lines[0]\n )\n}\n\n/**\n * The cadence a paid invoice was billed on, or undefined when it does not say.\n *\n * Never guessed — the same three-state discipline as `billingIntervalFromInvoice`\n * (AGL-1640). Storing `month` for an invoice that did not state one would make\n * the merchant's own record of what a subscriber pays wrong in the one way that\n * cannot be spotted by looking at it.\n */\nexport function subscriptionInvoiceInterval(\n invoice: SubscriptionInvoiceSource | null | undefined,\n): 'month' | 'year' | undefined {\n return lineInterval(selectSubscriptionInvoiceLine(invoice))\n}\n\n/**\n * The stored line items and totals for one paid subscription invoice\n * (AGL-1743) — a renewal, or the opening cycle.\n *\n * `snapshot` supplies the product identity, taken from what the sale already\n * recorded rather than re-derived: an invoice line knows a description and a\n * price, not a productId, a variant or a SKU. It is applied to the\n * subscription's own line only; a proration or one-off line on the same invoice\n * keeps Stripe's description and carries no product identity, because it is not\n * a sale of that product.\n *\n * `totalCents` is Stripe's `amount_paid` verbatim, for the AGL-1698 reason —\n * our sum is priced from lines we did not authorize and must never become the\n * stored truth. Where a customer credit balance covers part of an invoice the\n * parts will therefore exceed the collected total; the collected figure is the\n * one that matters and the invoice's own `total` is stored beside it.\n */\nexport function computeSubscriptionInvoiceOrder(\n invoice: SubscriptionInvoiceSource | null | undefined,\n snapshot: BuyNowProductSnapshot & { productId: string; variantId?: string },\n): { lineItems: OrderLineItem[]; totals: OrderTotals } {\n const subscriptionLine = selectSubscriptionInvoiceLine(invoice)\n const lineItems: OrderLineItem[] = []\n for (const line of invoice?.lines?.data ?? []) {\n const amount = Math.round(Number(line?.amount ?? 0))\n // A credit line (negative proration) is not a sale of anything, and\n // `computeOrderTotals` floors a line at 0 rather than subtracting it.\n // Stripe's own collected total still carries its effect.\n if (!Number.isFinite(amount) || amount <= 0) continue\n const rawQuantity = Math.round(Number(line?.quantity ?? 1))\n const quantity =\n Number.isFinite(rawQuantity) && rawQuantity > 0 ? rawQuantity : 1\n // The list unit price, except on a proration line, where `unit_amount` is\n // the full price and `amount` is only the fraction being billed.\n const listUnit = Math.round(Number(line?.price?.unit_amount ?? 0))\n const unitAmountCents =\n !line?.proration && Number.isFinite(listUnit) && listUnit > 0\n ? listUnit\n : Math.max(0, Math.round(amount / quantity))\n const isSubscriptionLine = line === subscriptionLine\n lineItems.push({\n productId: isSubscriptionLine ? snapshot.productId : '',\n ...(isSubscriptionLine && snapshot.variantId\n ? { variantId: snapshot.variantId }\n : {}),\n name: isSubscriptionLine\n ? snapshot.name\n : String(line?.description ?? 'Adjustment').slice(0, 200),\n ...(isSubscriptionLine && snapshot.variantLabel\n ? { variantLabel: snapshot.variantLabel }\n : {}),\n ...(isSubscriptionLine && snapshot.sku ? { sku: snapshot.sku } : {}),\n ...(isSubscriptionLine && snapshot.productType\n ? { productType: snapshot.productType }\n : {}),\n ...(isSubscriptionLine && snapshot.supplierId\n ? { supplierId: snapshot.supplierId }\n : {}),\n quantity,\n unitAmountCents,\n })\n }\n const scalarTax = Number(invoice?.tax ?? NaN)\n const taxCents =\n Number.isFinite(scalarTax) && scalarTax > 0\n ? scalarTax\n : // `total_taxes` replaced `total_tax_amounts`, which replaced the\n // scalar; they do not coexist, so this cannot double-count.\n sumAmounts(invoice?.total_taxes ?? invoice?.total_tax_amounts)\n return {\n lineItems,\n totals: computeCheckoutSessionTotals(\n lineItems,\n {\n amount_total: invoice?.amount_paid,\n total_details: {\n amount_tax: taxCents,\n amount_shipping: metadataCents(invoice?.shipping_cost?.amount_total),\n amount_discount: sumAmounts(invoice?.total_discount_amounts),\n },\n },\n { feeCents: metadataCents(invoice?.application_fee_amount) },\n ),\n }\n}\n\n/** Display form: `#1042`; falls back to a doc-id stub for legacy rows. */\nexport function formatOrderNumber(order: Pick<HostOrder, 'number'>, docId?: string): string {\n if (order.number != null) return `#${order.number}`\n return docId ? `#${docId.slice(-6).toUpperCase()}` : '#—'\n}\n\n/**\n * Lifts a legacy Commerce Starter order row (flat productId/amountCents)\n * into the v1 shape for display; already-shaped orders pass through.\n */\nexport function liftLegacyOrder(raw: Partial<HostOrder>): HostOrder {\n if (Array.isArray(raw.lineItems) && raw.lineItems.length > 0) {\n return { status: 'paid', ...raw } as HostOrder\n }\n const amountCents = Number(raw.amountCents ?? 0)\n return {\n ...raw,\n status: raw.status ?? 'paid',\n channel: raw.channel ?? 'online',\n lineItems: raw.productId\n ? [\n {\n productId: raw.productId,\n name: 'Product',\n quantity: 1,\n unitAmountCents: amountCents,\n },\n ]\n : [],\n totals: raw.totals ?? {\n itemsCents: amountCents,\n shippingCents: 0,\n taxCents: 0,\n discountCents: 0,\n feeCents: Number(raw.feeCents ?? 0),\n totalCents: amountCents,\n },\n }\n}\n\n/**\n * An orders-console row: the stored doc plus the Firestore id the collection\n * hook attaches. `createdAt` is typed structurally rather than against the\n * Firestore SDK — this module is pure and installs no client.\n */\nexport interface OrderExportRow extends Partial<HostOrder> {\n $id?: string\n createdAt?: { toDate?: () => Date } | null\n}\n\n/**\n * Does this order contain `productId`?\n *\n * Line items first, legacy flat `productId` as the fallback — the same test\n * `gate.ts`, `download.ts` and `reviews.ts` already apply. Only the two\n * buy-now-shaped Stripe paths ever write the flat field, so a legacy-only\n * check silently excludes every cart, POS and draft order.\n */\nexport function orderContainsProduct(\n order: Partial<HostOrder>,\n productId: string,\n): boolean {\n return (\n (order.lineItems ?? []).some((line) => line.productId === productId) ||\n order.productId === productId\n )\n}\n\n/**\n * Line indexes already covered by a recorded fulfillment (AGL-2455).\n *\n * The set the supplier callback and the console's own fulfil both have to\n * reason about, and the reason `status` alone could not: `supplier-update.ts`\n * wrote `status: 'fulfilled'` as a LITERAL, so the first supplier to post\n * tracking on a two-supplier order marked every line shipped — including lines\n * they have never seen — and the second supplier's POST met a 409 because\n * `fulfilled` cannot transition to `fulfilled`. The buyer was told their whole\n * order shipped with one carrier and one tracking number.\n */\nexport function coveredLineItemIds(order: Partial<HostOrder>): Set<number> {\n const covered = new Set<number>()\n for (const fulfillment of order.fulfillments ?? []) {\n for (const index of fulfillment?.lineItemIds ?? []) {\n const line = Math.round(Number(index))\n if (Number.isFinite(line) && line >= 0) covered.add(line)\n }\n }\n return covered\n}\n\n/** Distinct suppliers with at least one line on this order (AGL-2455). */\nexport function orderSupplierIds(order: Partial<HostOrder>): string[] {\n return [\n ...new Set(\n (order.lineItems ?? [])\n .map((line) => String(line.supplierId ?? ''))\n .filter(Boolean),\n ),\n ]\n}\n\n/** Line indexes belonging to one supplier (AGL-2455). */\nexport function supplierLineItemIds(\n order: Partial<HostOrder>,\n supplierId: string,\n): number[] {\n return (order.lineItems ?? [])\n .map((line, index) => ({ line, index }))\n .filter(({ line }) => String(line.supplierId ?? '') === supplierId)\n .map(({ index }) => index)\n}\n\n/**\n * The status an order reaches once `covered` lines are shipped (AGL-2455).\n *\n * COMPUTED from the fulfillment set rather than written as a literal, which is\n * the whole of this issue's third requirement. `partially_fulfilled` has existed\n * in `ORDER_TRANSITIONS` since orders shipped and nothing ever wrote it.\n *\n * An order with no lines at all reads as fulfilled — there is nothing left to\n * ship, and answering `partially_fulfilled` would strand it forever.\n */\nexport function statusAfterFulfilling(\n order: Partial<HostOrder>,\n covered: Set<number>,\n): OrderStatus {\n const lines = order.lineItems ?? []\n if (lines.length === 0) return 'fulfilled'\n return lines.every((_line, index) => covered.has(index))\n ? 'fulfilled'\n : 'partially_fulfilled'\n}\n\n/**\n * Statuses under which an order grants NO entitlement at all (AGL-2454).\n *\n * `pending` has not paid, `cancelled` was undone, `refunded` was given back.\n * The literal list was copied into `download.ts`, `gate.ts`,\n * `membership-account.ts` and `reviews.ts`; it lives here now so a change to\n * what \"withdrawn\" means reaches all of them at once.\n */\nconst WITHDRAWN_ORDER_STATUSES: OrderStatus[] = [\n 'pending',\n 'cancelled',\n 'refunded',\n]\n\n/**\n * How much of this order has been given back (AGL-2454).\n *\n * `full` follows `status` OR the money, because the two can legitimately\n * disagree for a moment: `refund.ts` reserves `refundedCents` before it calls\n * Stripe and flips `status` after, and a lost dispute reverses money on an\n * order whose status is still `paid` until it closes. Reading only the status\n * would treat that window as \"nothing refunded\".\n */\nexport function orderRefundState(\n order: Partial<HostOrder>,\n): 'none' | 'partial' | 'full' {\n const refundedCents = Math.max(0, Number(order.refundedCents ?? 0))\n const totalCents =\n order.totals?.totalCents ?? Number(order.amountCents ?? 0)\n if (order.status === 'refunded') return 'full'\n if (!(refundedCents > 0)) return 'none'\n return totalCents > 0 && refundedCents >= totalCents ? 'full' : 'partial'\n}\n\n/**\n * Is this line's entitlement withdrawn?\n *\n * By INDEX, matching `refundedLineItemIds`. A cart can hold the same product on\n * two lines and only one may be coming back, so a product-keyed test would\n * revoke goods the buyer still owns.\n */\nexport function orderLineRefunded(\n order: Partial<HostOrder>,\n lineIndex: number,\n): boolean {\n return (order.refundedLineItemIds ?? []).includes(lineIndex)\n}\n\n/**\n * THE ONE ENTITLEMENT TEST (AGL-2454). Does this order still entitle the buyer\n * to `productId`?\n *\n * Five gates asked this question and all five asked it as\n * `!['pending','cancelled','refunded'].includes(status) && orderContainsProduct(…)`.\n * That reading is why a partial refund revoked NOTHING: `refund.ts` writes\n * `status: 'refunded'` only when the order is FULLY refunded, so a 99%-refunded\n * order stayed `paid` and every gate said yes — downloads, licence keys, gated\n * content and the right to post a verified review, all still live.\n *\n * Withdrawn now means either of two things, and both had to be expressible in\n * one place or the five gates would drift again:\n *\n * - the whole order is withdrawn by `status`, as before; or\n * - every line carrying this product was refunded BY NAME, which is the case a\n * line-scoped refund creates and the only case where an amount can honestly\n * be attributed to goods.\n *\n * `'any'` asks whether the order still entitles ANYTHING, which is what the\n * membership paywall's subscription-shaped probe needs.\n *\n * The legacy flat `productId` order (one line, no `lineItems`) is lifted by\n * `liftLegacyOrder` before it gets here, so index 0 is its only line and a\n * line-scoped refund of it behaves like a full one.\n */\nexport function orderEntitlesProduct(\n order: Partial<HostOrder>,\n productId: string | 'any',\n): boolean {\n if (WITHDRAWN_ORDER_STATUSES.includes(order.status as OrderStatus)) {\n return false\n }\n const lines = order.lineItems ?? []\n if (productId === 'any') {\n if (lines.length === 0) return true\n return lines.some((_line, index) => !orderLineRefunded(order, index))\n }\n const matching = lines\n .map((line, index) => ({ line, index }))\n .filter(({ line }) => line.productId === productId)\n if (matching.length === 0) {\n // The legacy flat shape, which `liftLegacyOrder` normally converts. Kept so\n // an unlifted row is not silently un-entitled — a false negative here locks\n // a paying buyer out of goods they bought.\n return order.productId === productId\n }\n return matching.some(({ index }) => !orderLineRefunded(order, index))\n}\n\n/**\n * Product ids whose entitlement this order has withdrawn line by line\n * (AGL-2454) — every line for the product refunded, none left standing.\n *\n * What `refund.ts` uses to decide which licence keys to RETIRE. Not \"any line\n * refunded\": a buyer who returned one of two copies still holds the product.\n */\nexport function refundedProductIds(order: Partial<HostOrder>): string[] {\n const lines = order.lineItems ?? []\n const ids = new Set<string>()\n for (const line of lines) {\n if (!ids.has(line.productId) && !orderEntitlesProduct(order, line.productId)) {\n ids.add(line.productId)\n }\n }\n return [...ids]\n}\n\n/**\n * The refund line the console and the merchant read (AGL-2454).\n *\n * Kept in the model because three surfaces show it and \"partially refunded\"\n * must not mean different things on two of them. Empty for an order with\n * nothing refunded — there is nothing to say.\n */\nexport function orderRefundSummary(order: Partial<HostOrder>): string {\n const state = orderRefundState(order)\n if (state === 'none') return ''\n const refundedCents = Math.max(0, Number(order.refundedCents ?? 0))\n const totalCents = order.totals?.totalCents ?? Number(order.amountCents ?? 0)\n if (state === 'full') return `Refunded in full ($${usd(refundedCents)})`\n const revoked = (order.refundedLineItemIds ?? []).length\n const lines = (order.lineItems ?? []).length\n const scope =\n revoked > 0\n ? `${revoked} of ${lines} line${lines === 1 ? '' : 's'} withdrawn`\n : 'no lines withdrawn — refunded by amount'\n return `Partially refunded ($${usd(refundedCents)} of $${usd(\n totalCents,\n )}) — ${scope}`\n}\n\n/** `12345` -> `123.45`, the CSV's money format. */\nfunction usd(cents: number): string {\n return (cents / 100).toFixed(2)\n}\n\n/**\n * Display labels for {@link OrderStatus}, and the MUI chip colour each one\n * carries (AGL-2136). The orders screen advertised on `/product/commerce`\n * shows the status as a COLOURED pill — `Paid`, `Fulfilled`, `Refunded` in\n * three different colours — where the console rendered every status as the\n * same default outlined chip, so the one column a merchant scans first\n * carried no signal at all.\n *\n * Kept in the model rather than in the card because three surfaces render a\n * status (the orders list, the detail dialog and the dashboard glance\n * widget) and a colour that means \"refunded\" on one of them must not mean\n * something else on the next.\n */\nexport const ORDER_STATUS_LABELS: Record<OrderStatus, string> = {\n pending: 'Pending',\n paid: 'Paid',\n partially_fulfilled: 'Partly fulfilled',\n fulfilled: 'Fulfilled',\n delivered: 'Delivered',\n cancelled: 'Canceled',\n refunded: 'Refunded',\n}\n\n/**\n * Chip colour per status. `pending` is deliberately `default` rather than\n * `warning`: an unpaid order is not a problem, it is simply not money yet,\n * and reserving the alarming colours for `cancelled`/`refunded` is what\n * makes them readable at a glance.\n */\nexport const ORDER_STATUS_COLOR: Record<\n OrderStatus,\n 'default' | 'success' | 'info' | 'warning' | 'error'\n> = {\n pending: 'default',\n paid: 'success',\n partially_fulfilled: 'warning',\n fulfilled: 'info',\n delivered: 'info',\n cancelled: 'default',\n refunded: 'error',\n}\n\n/** Display labels for {@link OrderChannel}. */\nexport const ORDER_CHANNEL_LABELS: Record<OrderChannel, string> = {\n online: 'Online',\n pos: 'POS',\n draft: 'Draft',\n subscription: 'Subscription',\n}\n\n/** Human label for a channel, tolerating a legacy/unknown value. */\nexport function orderChannelLabel(channel: string | undefined): string {\n return ORDER_CHANNEL_LABELS[(channel ?? 'online') as OrderChannel] ?? channel ?? 'Online'\n}\n\n/**\n * Net cents an order actually earned: the charged total less anything\n * refunded. The three commerce surfaces each had their own inline copy of\n * this expression; a refunded order counted as revenue on whichever one\n * was written first.\n */\nexport function orderNetCents(order: Partial<HostOrder>): number {\n const gross = Number(\n (order as { totals?: { totalCents?: number } }).totals?.totalCents ??\n (order as { amountCents?: number }).amountCents ??\n 0,\n )\n return gross - Number((order as { refundedCents?: number }).refundedCents ?? 0)\n}\n\n/** Milliseconds an order was created at, across every writer's field shape. */\nexport function orderCreatedAtMs(order: Partial<HostOrder> & {\n createdAtMs?: number\n createdAt?: { seconds?: number; toDate?: () => Date }\n}): number {\n if (typeof order.createdAtMs === 'number') return order.createdAtMs\n const seconds = order.createdAt?.seconds\n if (typeof seconds === 'number') return seconds * 1000\n const date = order.createdAt?.toDate?.()\n return date ? date.getTime() : 0\n}\n\n/** One window's totals, plus how it moved against the window before it. */\nexport interface OrderWindowSummary {\n /** Net revenue in cents over the window. */\n revenueCents: number\n /** Orders counted in the window. */\n orders: number\n /** Average order value in cents, 0 when the window is empty. */\n aovCents: number\n /**\n * Percentage change vs the immediately preceding window of the same\n * length, rounded to one decimal. `null` when the prior window is EMPTY —\n * \"+100%\" against zero is not a growth rate, it is a first sale, and the\n * tile must say nothing rather than say something false.\n */\n revenueDeltaPct: number | null\n ordersDeltaPct: number | null\n aovDeltaPct: number | null\n}\n\nconst ORDER_WINDOW_DAY_MS = 24 * 60 * 60 * 1000\n\n/**\n * Percentage change from `previous` to `current`, or `null` when there is\n * no baseline to divide by.\n */\nfunction deltaPct(current: number, previous: number): number | null {\n if (!previous) return null\n return Math.round(((current - previous) / previous) * 1000) / 10\n}\n\n/**\n * Summarises a window of orders and the window before it (AGL-2136).\n *\n * Every commerce mockup we advertise shows the money tiles carrying a\n * period-over-period delta — `Revenue $26,540 +8.1%` — and the product had\n * no prior-window computation anywhere in the repo, so no surface could\n * have rendered one.\n *\n * `pending` and `cancelled` orders are excluded, matching the analytics\n * card: neither is money. Refunds are subtracted rather than dropped, so a\n * refund inside the window pushes the delta DOWN, which is the whole point\n * of showing it.\n */\nexport function summarizeOrderWindow(\n orders: readonly (Partial<HostOrder> & {\n createdAtMs?: number\n createdAt?: { seconds?: number; toDate?: () => Date }\n })[],\n options: { nowMs: number; days?: number } ,\n): OrderWindowSummary {\n const days = options.days ?? 30\n const spanMs = days * ORDER_WINDOW_DAY_MS\n const { nowMs } = options\n let revenueCents = 0\n let count = 0\n let priorRevenueCents = 0\n let priorCount = 0\n for (const order of orders) {\n const lifted = liftLegacyOrder(order)\n if (lifted.status === 'pending' || lifted.status === 'cancelled') continue\n const age = nowMs - orderCreatedAtMs(order)\n if (age < 0) continue\n if (age < spanMs) {\n revenueCents += orderNetCents(order)\n count += 1\n } else if (age < spanMs * 2) {\n priorRevenueCents += orderNetCents(order)\n priorCount += 1\n }\n }\n const aovCents = count ? Math.round(revenueCents / count) : 0\n const priorAovCents = priorCount\n ? Math.round(priorRevenueCents / priorCount)\n : 0\n return {\n revenueCents,\n orders: count,\n aovCents,\n revenueDeltaPct: deltaPct(revenueCents, priorRevenueCents),\n ordersDeltaPct: deltaPct(count, priorCount),\n aovDeltaPct: deltaPct(aovCents, priorAovCents),\n }\n}\n\n/**\n * Header for {@link buildOrdersCsv}. The original seven columns (AGL-96) keep\n * their names AND their positions, so a saved import mapping — by name or by\n * index — still resolves; the four reconciliation columns are appended.\n */\nexport const ORDERS_CSV_HEADER =\n 'date,product,amountUsd,feeUsd,customerEmail,coupon,orderId,' +\n 'status,channel,refundedUsd,netUsd'\n\n/**\n * The orders console's `orders.csv` (AGL-1747).\n *\n * ## What was wrong\n *\n * The export read `amountCents`, `feeCents` and `productId` — the legacy\n * Commerce Starter flat fields (AGL-90) — and nothing else. Checked writer by\n * writer, only the two buy-now-shaped Stripe paths write them:\n *\n * | Order path | `amountCents` | `productId` |\n * | -- | -- | -- |\n * | buy-now (`commerce-order`, `billing-webhook.ts`) | yes | yes |\n * | cart (`commerce-cart`, `billing-webhook.ts`) | yes | **no** |\n * | POS cash and POS card (`pos-order.ts`) | **no** | **no** |\n * | draft (`draft-order.ts`, paid by `commerce-draft`) | **no** | **no** |\n *\n * So every POS and draft order exported as `$0.00` and every cart order\n * exported with a blank product, each beside a plausible date, email and order\n * id — nothing in the file signals that the number is missing rather than\n * genuinely zero. The console screen was right the whole time: the table row\n * beside the export button, the detail dialog, the analytics card and lifetime\n * purchases all read `totals` with the flat field only as a fallback. The\n * export was the sole reader that had the precedence backwards, and a CSV is\n * the artefact that reaches a bookkeeper.\n *\n * ## What \"correct\" means\n *\n * Per AGL-1711's lesson, the useful test is not \"do the parts sum\" but \"does\n * each column match what was actually charged\" — a total-only assertion passes\n * against a row whose every component is wrong. The spec therefore pins each\n * cell of a worked example individually.\n *\n * ## Refunds\n *\n * `amountUsd` stays gross, which is what it has always meant, and the appended\n * `refundedUsd`/`netUsd` carry the rest. A refunded order previously exported\n * at its gross with nothing beside it to say so — the same class of error, in\n * that the file understated nothing but overstated revenue.\n */\nexport function buildOrdersCsv(\n orders: OrderExportRow[],\n productNames: Record<string, string> = {},\n): string {\n const escape = (cell: string) =>\n /[\",\\n]/.test(cell) ? `\"${cell.replace(/\"/g, '\"\"')}\"` : cell\n return [\n ORDERS_CSV_HEADER,\n ...orders.map((order) => {\n const lifted = liftLegacyOrder(order)\n // The STORED line items, not the lifted ones: `liftLegacyOrder` gives a\n // legacy flat row a synthetic line named \"Product\", which would shadow\n // the real name the `productNames` lookup still recovers for those rows.\n const lineItems = order.lineItems ?? []\n // A cart order has several lines and no single product; name the first\n // and count the rest, the way the table row renders it. `serverTimestamp`\n // reads back null until the write lands, so `createdAtMs` — which every\n // modern writer sets alongside it — covers the local snapshot.\n const date =\n order.createdAt?.toDate?.() ??\n (order.createdAtMs ? new Date(order.createdAtMs) : null)\n const product =\n lineItems[0]?.name ??\n productNames[order.productId ?? ''] ??\n order.productId ??\n ''\n const totalCents = Number(\n lifted.totals?.totalCents ?? order.amountCents ?? 0,\n )\n const feeCents = Number(lifted.totals?.feeCents ?? order.feeCents ?? 0)\n const refundedCents = Number(order.refundedCents ?? 0)\n return [\n date ? date.toISOString() : '',\n lineItems.length > 1\n ? `${product} +${lineItems.length - 1} more`\n : product,\n usd(totalCents),\n usd(feeCents),\n order.customerEmail ?? '',\n order.couponCode ?? '',\n order.$id ?? '',\n lifted.status,\n lifted.channel ?? 'online',\n usd(refundedCents),\n usd(totalCents - refundedCents),\n ]\n .map((cell) => escape(String(cell)))\n .join(',')\n }),\n ].join('\\n')\n}\n\n/** Appends a timeline event immutably (webhook + console share this). */\nexport function appendOrderEvent(\n order: Pick<HostOrder, 'timeline'>,\n event: string,\n detail?: string,\n atMs = Date.now(),\n): OrderTimelineEvent[] {\n return [...(order.timeline ?? []), { atMs, event, ...(detail ? { detail } : {}) }]\n}\n"],"names":["stripeIdIsTestMode","ORDER_TRANSITIONS","pending","paid","partially_fulfilled","fulfilled","delivered","cancelled","refunded","canTransitionOrder","from","to","includes","wholeCents","value","cents","Math","round","Number","isFinite","apportionCents","weights","totalCents","safe","map","weight","max","basis","reduce","sum","total","length","pot","min","exact","shares","floor","remainder","share","order","index","fraction","sort","a","b","entry","orderLineRefundCents","lineIndexes","lines","lineItems","gross","line","unitAmountCents","quantity","totals","discountCents","wanted","Set","filter","isInteger","orderIsTestMode","livemode","checkoutSessionId","$id","computeOrderTotals","parts","itemsCents","shippingCents","taxCents","feeCents","computeCheckoutSessionTotals","session","details","total_details","amount_tax","lineItemTaxCents","amount_shipping","amount_discount","pricedInDiscountCents","amountTotal","amount_total","NaN","metadataCents","computeBuyNowOrder","snapshot","metadata","rawQuantity","goodsCents","variantId","String","productId","name","variantLabel","sku","productType","supplierId","subscriptionInvoiceFeeBasisCents","invoice","scalarTax","tax","sumAmounts","total_taxes","total_tax_amounts","shipping_cost","subscriptionInvoiceItemsOnlyFeeCents","chargedCents","application_fee_amount","basisCents","subscriptionRecurringBasisCents","soldLineItems","reason","billing_reason","billsTheFullPrice","cycleBasis","unit","list","amount","lineInterval","interval","price","recurring","undefined","selectSubscriptionInvoiceLine","data","find","proration","subscriptionInvoiceInterval","computeSubscriptionInvoiceOrder","subscriptionLine","listUnit","unit_amount","isSubscriptionLine","push","description","slice","amount_paid","total_discount_amounts","formatOrderNumber","docId","number","toUpperCase","liftLegacyOrder","raw","Array","isArray","status","amountCents","channel","orderContainsProduct","some","coveredLineItemIds","covered","fulfillment","fulfillments","lineItemIds","add","orderSupplierIds","Boolean","supplierLineItemIds","statusAfterFulfilling","every","_line","has","WITHDRAWN_ORDER_STATUSES","orderRefundState","refundedCents","orderLineRefunded","lineIndex","refundedLineItemIds","orderEntitlesProduct","matching","refundedProductIds","ids","orderRefundSummary","state","usd","revoked","scope","toFixed","ORDER_STATUS_LABELS","ORDER_STATUS_COLOR","ORDER_CHANNEL_LABELS","online","pos","draft","subscription","orderChannelLabel","orderNetCents","orderCreatedAtMs","createdAtMs","seconds","createdAt","date","toDate","getTime","ORDER_WINDOW_DAY_MS","deltaPct","current","previous","summarizeOrderWindow","orders","options","days","spanMs","nowMs","revenueCents","count","priorRevenueCents","priorCount","lifted","age","aovCents","priorAovCents","revenueDeltaPct","ordersDeltaPct","aovDeltaPct","ORDERS_CSV_HEADER","buildOrdersCsv","productNames","escape","cell","test","replace","Date","product","toISOString","customerEmail","couponCode","join","appendOrderEvent","event","detail","atMs","now","timeline"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;CAOC,GAED,SAASA,kBAAkB,QAAQ,gDAA+C;AA+WlF;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GACD,MAAMC,oBAAwD;IAC5DC,SAAS;QAAC;QAAQ;KAAY;IAC9BC,MAAM;QAAC;QAAuB;QAAa;QAAa;KAAW;IACnEC,qBAAqB;QAAC;QAAa;KAAW;IAC9CC,WAAW;QAAC;QAAa;KAAW;IACpCC,WAAW;QAAC;KAAW;IACvBC,WAAW;QAAC;KAAW;IACvBC,UAAU,EAAE;AACd;AAEA,OAAO,SAASC,mBACdC,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AAKiC,WAAW,KAAK;gBAC5BhL,UAAUlB,MAAM,GAAG,IACf,GAAGiM,QAAQ,EAAE,EAAE/K,UAAUlB,MAAM,GAAG,EAAE,KAAK,CAAC,GAC1CiM;gBACJjD,IAAIzJ;gBACJyJ,IAAI1G;iBACJ9B,uBAAAA,MAAM2L,aAAa,YAAnB3L,uBAAuB;iBACvBA,oBAAAA,MAAM4L,UAAU,YAAhB5L,oBAAoB;iBACpBA,aAAAA,MAAMwB,GAAG,YAATxB,aAAa;gBACb0K,OAAOhE,MAAM;iBACbgE,kBAAAA,OAAO9D,OAAO,YAAd8D,kBAAkB;gBAClBlC,IAAIV;gBACJU,IAAIzJ,aAAa+I;aAClB,CACE7I,GAAG,CAAC,CAACoM,OAASD,OAAOlI,OAAOmI,QAC5BQ,IAAI,CAAC;QACV;KACD,CAACA,IAAI,CAAC;AACT;AAEA,uEAAuE,GACvE,OAAO,SAASC,iBACd9L,KAAkC,EAClC+L,KAAa,EACbC,MAAe,EACfC,OAAOT,KAAKU,GAAG,EAAE;QAELlM;IAAZ,OAAO;YAAKA,kBAAAA,MAAMmM,QAAQ,YAAdnM,kBAAkB,EAAE;QAAG;YAAEiM;YAAMF;WAAWC,SAAS;YAAEA;QAAO,IAAI,CAAC;KAAK;AACpF"}
@@ -0,0 +1,188 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * Promotion redemption-slot arithmetic (AGL-2453).
19
+ *
20
+ * A redemption cap was CHECKED at checkout-session creation and COUNTED at the
21
+ * webhook, and nothing re-asked the question in between. The increments were
22
+ * atomic and no tick was ever lost — the cap was simply never re-read. The
23
+ * window between the two is the whole Stripe Checkout Session lifetime, up to
24
+ * 24 hours, so this was never bounded by simultaneity: every shopper who loaded
25
+ * checkout while a `maxRedemptions: 100` promotion sat at 99 passed the gate,
26
+ * got the discount, and the counter finished at 99+N. Two browser tabs
27
+ * reproduce it.
28
+ *
29
+ * This is the AGL-2449 gift-card shape, reused rather than re-invented: the
30
+ * slot is HELD in a transaction at checkout and SETTLED in a transaction at the
31
+ * webhook, against a `holds` map on the promotion document itself. One
32
+ * document, no fan-out, no index. The differences from a gift card are only in
33
+ * the units — a slot is one whole redemption rather than a number of cents, so
34
+ * a hold carries no amount.
35
+ *
36
+ * ## Both redemption paths, or neither
37
+ *
38
+ * Two DIFFERENT objects carry `maxRedemptions` and both increment through the
39
+ * same webhook helper: the typed coupon at `coupons/{code}` (AGL-96 semantics)
40
+ * and the AGL-305 discount at `discounts/{id}`, which is evaluated over every
41
+ * enabled promotion and applies with nothing typed at all. Holding only the
42
+ * typed one would leave the identical silent over-redemption on the path a
43
+ * shopper does not even opt into — a "first 50 customers" promotion enforced
44
+ * only against whoever is not currently mid-checkout. So the arithmetic lives
45
+ * here, in one place, shaped to fit both documents: `HeldPromotion` is the
46
+ * three fields they have in common and nothing else.
47
+ *
48
+ * ## A held slot COUNTS while the session is live
49
+ *
50
+ * This was the owner's call, and it is recorded here because it is the thing a
51
+ * reader will want to argue with. A held-but-unpaid slot reads as REDEEMED for
52
+ * as long as its session can still be paid, and is released when that session
53
+ * expires or is cancelled.
54
+ *
55
+ * The alternative — showing held slots separately and letting a new shopper
56
+ * claim one — reopens the defect for exactly the duration of a live checkout.
57
+ * The two costs are not symmetric: a promotion that oversells is money the
58
+ * merchant did not agree to spend and cannot claw back, while a shopper who
59
+ * sees "code unavailable" during someone else's live checkout tries again and
60
+ * succeeds. Over-holding fails safe; under-holding fails expensive.
61
+ *
62
+ * ## Uncapped promotions hold NOTHING
63
+ *
64
+ * `maxRedemptions == null` means there is no slot to reserve, so no hold is
65
+ * placed, no document is written at checkout, and the webhook keeps the plain
66
+ * `increment(1)`. That is not an optimization for its own sake: it keeps the
67
+ * common promotion — the one with no limit — on exactly the write path it had
68
+ * before this issue, so the blast radius of the fix is the capped case only.
69
+ *
70
+ * ## Expiry is a backstop, not the mechanism
71
+ *
72
+ * Every hold carries `expiresAtMs` and every read prunes, so a crashed process
73
+ * cannot strand a merchant's slot forever. But the release is EXPLICIT: each
74
+ * refusal below the checkout claim drops the hold it placed, and
75
+ * `checkout.session.expired` drops the hold of a session that will never be
76
+ * paid. Relying on the TTL alone would mean a merchant watching a cap of 100
77
+ * sit at 100 for a day after an abandoned cart, with nothing in the product
78
+ * able to explain why.
79
+ */
80
+ /**
81
+ * One in-flight claim on a promotion slot.
82
+ *
83
+ * No `count`: a checkout redeems a promotion exactly once however many lines
84
+ * it discounts, which is what the webhook's `increment(1)` has always meant.
85
+ * A shape that could express two would invite a caller to write it.
86
+ */
87
+ export interface PromotionHold {
88
+ expiresAtMs: number;
89
+ }
90
+ /**
91
+ * The redemption-cap fields shared by `coupons/{code}` and `discounts/{id}`.
92
+ *
93
+ * Deliberately NOT a union of the two document types. The hold arithmetic must
94
+ * behave identically on both or the fix covers one path and not the other, and
95
+ * the cheapest way to guarantee that is to give it no way to tell them apart.
96
+ */
97
+ export interface HeldPromotion {
98
+ maxRedemptions?: number;
99
+ redemptions?: number;
100
+ /** Hold key → hold. Absent on every promotion written before AGL-2453. */
101
+ holds?: Record<string, PromotionHold>;
102
+ }
103
+ /**
104
+ * Stripe Checkout Sessions expire 24h after creation, so a hold outlives any
105
+ * session that can still be paid. A shorter TTL is not the safer choice it
106
+ * looks like: a hold that lapsed while its session was still payable would
107
+ * reopen the very window this closes.
108
+ */
109
+ export declare const PROMOTION_HOLD_TTL_MS: number;
110
+ /** What a shopper is told when every slot is spoken for. */
111
+ export declare const PROMOTION_EXHAUSTED_MESSAGE = "This discount has been fully redeemed";
112
+ /**
113
+ * What a shopper is told when an AUTOMATIC promotion ran out mid-checkout.
114
+ *
115
+ * A separate sentence because the shopper never typed anything: "this discount
116
+ * has been fully redeemed" reads as an accusation against a code they did not
117
+ * enter. Naming the refresh is the recovery — the resolver counts holds too, so
118
+ * the reloaded cart simply prices without the promotion and checks out.
119
+ */
120
+ export declare const PROMOTION_UNAVAILABLE_MESSAGE: string;
121
+ /**
122
+ * The promotion's holds with the lapsed ones dropped.
123
+ *
124
+ * Total, not a filter over a trusted shape: a hold whose `expiresAtMs` is
125
+ * absent or non-numeric is treated as EXPIRED rather than eternal, so a
126
+ * malformed row releases the slot instead of stranding it. A merchant losing a
127
+ * configured slot forever to a corrupt map entry is the one direction that has
128
+ * no recovery inside the product.
129
+ */
130
+ export declare function prunePromotionHolds(holds: Record<string, PromotionHold> | undefined, nowMs: number): Record<string, PromotionHold>;
131
+ /**
132
+ * Slots spoken for right now: settled redemptions plus every live hold.
133
+ *
134
+ * `exceptHoldKey` is how a retry of one attempt does not stand in its own way.
135
+ * The shopper presses the same button twice, the second press re-derives the
136
+ * same hold key, and without this exclusion it would be refused its own slot.
137
+ */
138
+ export declare function promotionClaimedCount(promotion: HeldPromotion | undefined, nowMs: number, exceptHoldKey?: string): number;
139
+ /**
140
+ * Slots left, or `null` when the promotion is uncapped.
141
+ *
142
+ * `null` rather than `Infinity` so a caller cannot accidentally do arithmetic
143
+ * on "no limit" and get a number. Never negative: a cap lowered below the
144
+ * redemptions already taken reads as zero left, not as a debt.
145
+ */
146
+ export declare function promotionRemainingSlots(promotion: HeldPromotion | undefined, nowMs: number, exceptHoldKey?: string): number | null;
147
+ /**
148
+ * Is there no slot left for a NEW claim?
149
+ *
150
+ * The one question both the pre-read (which filters a promotion out of the
151
+ * resolver) and the in-transaction re-read (which refuses the checkout) ask, so
152
+ * the two cannot drift apart — the drift is what AGL-2450 had to extract a
153
+ * shared filter to prevent.
154
+ */
155
+ export declare function promotionExhausted(promotion: HeldPromotion | undefined, nowMs: number, exceptHoldKey?: string): boolean;
156
+ /**
157
+ * How many live checkouts are currently holding a slot.
158
+ *
159
+ * The merchant-facing half of the decision (AGL-2453). The console's promotion
160
+ * and coupon cards read `redemptions / maxRedemptions`, and once a hold counts
161
+ * as spent that figure alone would show a cap of 100 sitting at 100 with no
162
+ * explanation for a merchant looking at 97 orders. This is what the cards name
163
+ * separately, so "held" is a state the merchant can SEE rather than a
164
+ * discrepancy they have to reason about.
165
+ */
166
+ export declare function promotionHeldCount(promotion: HeldPromotion | undefined, nowMs: number): number;
167
+ /**
168
+ * The usage line both console cards print, so the two cannot word it
169
+ * differently. Empty string when the promotion is uncapped and nothing is held
170
+ * — there is no cap to report against.
171
+ */
172
+ export declare function promotionUsageLabel(promotion: HeldPromotion | undefined, nowMs: number): string;
173
+ /**
174
+ * Does settling `holdKey` owe the promotion a redemption?
175
+ *
176
+ * NOT pruned, deliberately, and this is the asymmetry that matters: a hold that
177
+ * lapsed while its session sat unpaid is still owed once that session IS paid.
178
+ * Expiry governs what a NEW checkout may claim, never whether a completed
179
+ * payment is counted — dropping it here would give the shopper a discount the
180
+ * merchant's cap never recorded, which is the original defect arriving through
181
+ * the release path.
182
+ *
183
+ * A hold that is not there settles NOTHING. That is the webhook-redelivery case
184
+ * — the first delivery consumed it — and it is what makes the settlement
185
+ * idempotent under the at-least-once delivery `reconcile-stock.ts:52-58`
186
+ * records this file's callers as living with.
187
+ */
188
+ export declare function promotionSettles(promotion: HeldPromotion | undefined, holdKey: string): boolean;
@@ -0,0 +1,199 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ /**
17
+ * Promotion redemption-slot arithmetic (AGL-2453).
18
+ *
19
+ * A redemption cap was CHECKED at checkout-session creation and COUNTED at the
20
+ * webhook, and nothing re-asked the question in between. The increments were
21
+ * atomic and no tick was ever lost — the cap was simply never re-read. The
22
+ * window between the two is the whole Stripe Checkout Session lifetime, up to
23
+ * 24 hours, so this was never bounded by simultaneity: every shopper who loaded
24
+ * checkout while a `maxRedemptions: 100` promotion sat at 99 passed the gate,
25
+ * got the discount, and the counter finished at 99+N. Two browser tabs
26
+ * reproduce it.
27
+ *
28
+ * This is the AGL-2449 gift-card shape, reused rather than re-invented: the
29
+ * slot is HELD in a transaction at checkout and SETTLED in a transaction at the
30
+ * webhook, against a `holds` map on the promotion document itself. One
31
+ * document, no fan-out, no index. The differences from a gift card are only in
32
+ * the units — a slot is one whole redemption rather than a number of cents, so
33
+ * a hold carries no amount.
34
+ *
35
+ * ## Both redemption paths, or neither
36
+ *
37
+ * Two DIFFERENT objects carry `maxRedemptions` and both increment through the
38
+ * same webhook helper: the typed coupon at `coupons/{code}` (AGL-96 semantics)
39
+ * and the AGL-305 discount at `discounts/{id}`, which is evaluated over every
40
+ * enabled promotion and applies with nothing typed at all. Holding only the
41
+ * typed one would leave the identical silent over-redemption on the path a
42
+ * shopper does not even opt into — a "first 50 customers" promotion enforced
43
+ * only against whoever is not currently mid-checkout. So the arithmetic lives
44
+ * here, in one place, shaped to fit both documents: `HeldPromotion` is the
45
+ * three fields they have in common and nothing else.
46
+ *
47
+ * ## A held slot COUNTS while the session is live
48
+ *
49
+ * This was the owner's call, and it is recorded here because it is the thing a
50
+ * reader will want to argue with. A held-but-unpaid slot reads as REDEEMED for
51
+ * as long as its session can still be paid, and is released when that session
52
+ * expires or is cancelled.
53
+ *
54
+ * The alternative — showing held slots separately and letting a new shopper
55
+ * claim one — reopens the defect for exactly the duration of a live checkout.
56
+ * The two costs are not symmetric: a promotion that oversells is money the
57
+ * merchant did not agree to spend and cannot claw back, while a shopper who
58
+ * sees "code unavailable" during someone else's live checkout tries again and
59
+ * succeeds. Over-holding fails safe; under-holding fails expensive.
60
+ *
61
+ * ## Uncapped promotions hold NOTHING
62
+ *
63
+ * `maxRedemptions == null` means there is no slot to reserve, so no hold is
64
+ * placed, no document is written at checkout, and the webhook keeps the plain
65
+ * `increment(1)`. That is not an optimization for its own sake: it keeps the
66
+ * common promotion — the one with no limit — on exactly the write path it had
67
+ * before this issue, so the blast radius of the fix is the capped case only.
68
+ *
69
+ * ## Expiry is a backstop, not the mechanism
70
+ *
71
+ * Every hold carries `expiresAtMs` and every read prunes, so a crashed process
72
+ * cannot strand a merchant's slot forever. But the release is EXPLICIT: each
73
+ * refusal below the checkout claim drops the hold it placed, and
74
+ * `checkout.session.expired` drops the hold of a session that will never be
75
+ * paid. Relying on the TTL alone would mean a merchant watching a cap of 100
76
+ * sit at 100 for a day after an abandoned cart, with nothing in the product
77
+ * able to explain why.
78
+ */ /**
79
+ * One in-flight claim on a promotion slot.
80
+ *
81
+ * No `count`: a checkout redeems a promotion exactly once however many lines
82
+ * it discounts, which is what the webhook's `increment(1)` has always meant.
83
+ * A shape that could express two would invite a caller to write it.
84
+ */ /**
85
+ * Stripe Checkout Sessions expire 24h after creation, so a hold outlives any
86
+ * session that can still be paid. A shorter TTL is not the safer choice it
87
+ * looks like: a hold that lapsed while its session was still payable would
88
+ * reopen the very window this closes.
89
+ */ export const PROMOTION_HOLD_TTL_MS = 24 * 60 * 60 * 1000;
90
+ /** What a shopper is told when every slot is spoken for. */ export const PROMOTION_EXHAUSTED_MESSAGE = 'This discount has been fully redeemed';
91
+ /**
92
+ * What a shopper is told when an AUTOMATIC promotion ran out mid-checkout.
93
+ *
94
+ * A separate sentence because the shopper never typed anything: "this discount
95
+ * has been fully redeemed" reads as an accusation against a code they did not
96
+ * enter. Naming the refresh is the recovery — the resolver counts holds too, so
97
+ * the reloaded cart simply prices without the promotion and checks out.
98
+ */ export const PROMOTION_UNAVAILABLE_MESSAGE = 'A promotion on your cart has just been fully redeemed. ' + 'Refresh your cart to see the current price.';
99
+ /**
100
+ * The promotion's holds with the lapsed ones dropped.
101
+ *
102
+ * Total, not a filter over a trusted shape: a hold whose `expiresAtMs` is
103
+ * absent or non-numeric is treated as EXPIRED rather than eternal, so a
104
+ * malformed row releases the slot instead of stranding it. A merchant losing a
105
+ * configured slot forever to a corrupt map entry is the one direction that has
106
+ * no recovery inside the product.
107
+ */ export function prunePromotionHolds(holds, nowMs) {
108
+ const live = {};
109
+ for (const [key, hold] of Object.entries(holds != null ? holds : {})){
110
+ const expiresAtMs = Number(hold == null ? void 0 : hold.expiresAtMs);
111
+ if (!Number.isFinite(expiresAtMs) || expiresAtMs <= nowMs) continue;
112
+ live[key] = {
113
+ expiresAtMs
114
+ };
115
+ }
116
+ return live;
117
+ }
118
+ /** Settled redemptions, coerced — a corrupt counter must not read as `-1`. */ function settledCount(promotion) {
119
+ var _ref;
120
+ const count = Math.round(Number((_ref = promotion == null ? void 0 : promotion.redemptions) != null ? _ref : 0));
121
+ return Number.isFinite(count) && count > 0 ? count : 0;
122
+ }
123
+ /**
124
+ * Slots spoken for right now: settled redemptions plus every live hold.
125
+ *
126
+ * `exceptHoldKey` is how a retry of one attempt does not stand in its own way.
127
+ * The shopper presses the same button twice, the second press re-derives the
128
+ * same hold key, and without this exclusion it would be refused its own slot.
129
+ */ export function promotionClaimedCount(promotion, nowMs, exceptHoldKey) {
130
+ const live = prunePromotionHolds(promotion == null ? void 0 : promotion.holds, nowMs);
131
+ if (exceptHoldKey) delete live[exceptHoldKey];
132
+ return settledCount(promotion) + Object.keys(live).length;
133
+ }
134
+ /**
135
+ * Slots left, or `null` when the promotion is uncapped.
136
+ *
137
+ * `null` rather than `Infinity` so a caller cannot accidentally do arithmetic
138
+ * on "no limit" and get a number. Never negative: a cap lowered below the
139
+ * redemptions already taken reads as zero left, not as a debt.
140
+ */ export function promotionRemainingSlots(promotion, nowMs, exceptHoldKey) {
141
+ const max = Number(promotion == null ? void 0 : promotion.maxRedemptions);
142
+ if ((promotion == null ? void 0 : promotion.maxRedemptions) == null || !Number.isFinite(max)) return null;
143
+ return Math.max(0, Math.round(max) - promotionClaimedCount(promotion, nowMs, exceptHoldKey));
144
+ }
145
+ /**
146
+ * Is there no slot left for a NEW claim?
147
+ *
148
+ * The one question both the pre-read (which filters a promotion out of the
149
+ * resolver) and the in-transaction re-read (which refuses the checkout) ask, so
150
+ * the two cannot drift apart — the drift is what AGL-2450 had to extract a
151
+ * shared filter to prevent.
152
+ */ export function promotionExhausted(promotion, nowMs, exceptHoldKey) {
153
+ const remaining = promotionRemainingSlots(promotion, nowMs, exceptHoldKey);
154
+ return remaining != null && remaining <= 0;
155
+ }
156
+ /**
157
+ * How many live checkouts are currently holding a slot.
158
+ *
159
+ * The merchant-facing half of the decision (AGL-2453). The console's promotion
160
+ * and coupon cards read `redemptions / maxRedemptions`, and once a hold counts
161
+ * as spent that figure alone would show a cap of 100 sitting at 100 with no
162
+ * explanation for a merchant looking at 97 orders. This is what the cards name
163
+ * separately, so "held" is a state the merchant can SEE rather than a
164
+ * discrepancy they have to reason about.
165
+ */ export function promotionHeldCount(promotion, nowMs) {
166
+ return Object.keys(prunePromotionHolds(promotion == null ? void 0 : promotion.holds, nowMs)).length;
167
+ }
168
+ /**
169
+ * The usage line both console cards print, so the two cannot word it
170
+ * differently. Empty string when the promotion is uncapped and nothing is held
171
+ * — there is no cap to report against.
172
+ */ export function promotionUsageLabel(promotion, nowMs) {
173
+ const held = promotionHeldCount(promotion, nowMs);
174
+ const settled = settledCount(promotion);
175
+ const cap = (promotion == null ? void 0 : promotion.maxRedemptions) != null ? `/${promotion.maxRedemptions}` : '';
176
+ if (!cap && !held) return `${settled} used`;
177
+ const heldPart = held > 0 ? ` · ${held} held in checkout` : '';
178
+ return `${settled}${cap} used${heldPart}`;
179
+ }
180
+ /**
181
+ * Does settling `holdKey` owe the promotion a redemption?
182
+ *
183
+ * NOT pruned, deliberately, and this is the asymmetry that matters: a hold that
184
+ * lapsed while its session sat unpaid is still owed once that session IS paid.
185
+ * Expiry governs what a NEW checkout may claim, never whether a completed
186
+ * payment is counted — dropping it here would give the shopper a discount the
187
+ * merchant's cap never recorded, which is the original defect arriving through
188
+ * the release path.
189
+ *
190
+ * A hold that is not there settles NOTHING. That is the webhook-redelivery case
191
+ * — the first delivery consumed it — and it is what makes the settlement
192
+ * idempotent under the at-least-once delivery `reconcile-stock.ts:52-58`
193
+ * records this file's callers as living with.
194
+ */ export function promotionSettles(promotion, holdKey) {
195
+ var _ref;
196
+ return Boolean(holdKey) && ((_ref = promotion == null ? void 0 : promotion.holds) != null ? _ref : {})[holdKey] != null;
197
+ }
198
+
199
+ //# sourceMappingURL=commerce-promotions.js.map