@aglyn/plugins-commerce 1.0.0-beta.230 → 1.0.0-beta.232

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 (609) hide show
  1. package/package.json +13 -13
  2. package/src/index.d.ts +0 -1
  3. package/src/index.js +0 -1
  4. package/src/index.js.map +1 -1
  5. package/src/lib/barcode/barcode-decode.d.ts +71 -0
  6. package/src/lib/barcode/barcode-decode.js +498 -0
  7. package/src/lib/barcode/barcode-decode.js.map +1 -0
  8. package/src/lib/barcode/barcode-encode.d.ts +44 -0
  9. package/src/lib/barcode/barcode-encode.js +138 -0
  10. package/src/lib/barcode/barcode-encode.js.map +1 -0
  11. package/src/lib/barcode/barcode-scanner.component.d.ts +23 -0
  12. package/src/lib/barcode/barcode-scanner.component.js +260 -0
  13. package/src/lib/barcode/barcode-scanner.component.js.map +1 -0
  14. package/src/lib/barcode/scan-button.component.d.ts +10 -0
  15. package/src/lib/barcode/scan-button.component.js +62 -0
  16. package/src/lib/barcode/scan-button.component.js.map +1 -0
  17. package/src/lib/barcode/scanner-wedge.d.ts +35 -0
  18. package/src/lib/barcode/scanner-wedge.js +108 -0
  19. package/src/lib/barcode/scanner-wedge.js.map +1 -0
  20. package/src/lib/components/account.js +10 -1
  21. package/src/lib/components/account.js.map +1 -1
  22. package/src/lib/components/cart-extras.d.ts +45 -0
  23. package/src/lib/components/cart-extras.js +127 -0
  24. package/src/lib/components/cart-extras.js.map +1 -0
  25. package/src/lib/components/cart.js +82 -15
  26. package/src/lib/components/cart.js.map +1 -1
  27. package/src/lib/components/checkout-return-notice.d.ts +26 -0
  28. package/src/lib/components/checkout-return-notice.js +48 -0
  29. package/src/lib/components/checkout-return-notice.js.map +1 -0
  30. package/src/lib/components/commerce-console-page.js +124 -0
  31. package/src/lib/components/commerce-console-page.js.map +1 -1
  32. package/src/lib/components/commerce-console-sections.d.ts +1 -1
  33. package/src/lib/components/commerce-console-sections.js +4 -0
  34. package/src/lib/components/commerce-console-sections.js.map +1 -1
  35. package/src/lib/components/console/bulk-fulfill.d.ts +44 -0
  36. package/src/lib/components/console/bulk-fulfill.js +84 -0
  37. package/src/lib/components/console/bulk-fulfill.js.map +1 -0
  38. package/src/lib/components/console/catalog-organization-card.component.js +1 -0
  39. package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
  40. package/src/lib/components/console/customer-notifications-card.component.d.ts +19 -0
  41. package/src/lib/components/console/customer-notifications-card.component.js +149 -0
  42. package/src/lib/components/console/customer-notifications-card.component.js.map +1 -0
  43. package/src/lib/components/console/host-orders-card.component.js +88 -6
  44. package/src/lib/components/console/host-orders-card.component.js.map +1 -1
  45. package/src/lib/components/console/locations-card.component.js +164 -57
  46. package/src/lib/components/console/locations-card.component.js.map +1 -1
  47. package/src/lib/components/console/order-detail-dialog.component.js +209 -61
  48. package/src/lib/components/console/order-detail-dialog.component.js.map +1 -1
  49. package/src/lib/components/console/order-fulfillment-panel.component.d.ts +48 -0
  50. package/src/lib/components/console/order-fulfillment-panel.component.js +542 -0
  51. package/src/lib/components/console/order-fulfillment-panel.component.js.map +1 -0
  52. package/src/lib/components/console/order-invoice.component.d.ts +33 -0
  53. package/src/lib/components/console/order-invoice.component.js +81 -0
  54. package/src/lib/components/console/order-invoice.component.js.map +1 -0
  55. package/src/lib/components/console/order-receipt-resend.component.d.ts +21 -0
  56. package/src/lib/components/console/order-receipt-resend.component.js +203 -0
  57. package/src/lib/components/console/order-receipt-resend.component.js.map +1 -0
  58. package/src/lib/components/console/order-returns.component.d.ts +36 -0
  59. package/src/lib/components/console/order-returns.component.js +142 -0
  60. package/src/lib/components/console/order-returns.component.js.map +1 -0
  61. package/src/lib/components/console/order-shipping-actions.component.d.ts +54 -0
  62. package/src/lib/components/console/order-shipping-actions.component.js +149 -0
  63. package/src/lib/components/console/order-shipping-actions.component.js.map +1 -0
  64. package/src/lib/components/console/order-webhooks-card.component.d.ts +50 -0
  65. package/src/lib/components/console/order-webhooks-card.component.js +623 -0
  66. package/src/lib/components/console/order-webhooks-card.component.js.map +1 -0
  67. package/src/lib/components/console/order-zones.d.ts +155 -0
  68. package/src/lib/components/console/order-zones.js +40 -0
  69. package/src/lib/components/console/order-zones.js.map +1 -0
  70. package/src/lib/components/console/payment-methods-card.component.d.ts +67 -0
  71. package/src/lib/components/console/payment-methods-card.component.js +395 -0
  72. package/src/lib/components/console/payment-methods-card.component.js.map +1 -0
  73. package/src/lib/components/console/pos/pos-api.d.ts +124 -0
  74. package/src/lib/components/console/pos/pos-api.js +101 -0
  75. package/src/lib/components/console/pos/pos-api.js.map +1 -0
  76. package/src/lib/components/console/pos/pos-cart-panel.component.d.ts +36 -0
  77. package/src/lib/components/console/pos/pos-cart-panel.component.js +160 -0
  78. package/src/lib/components/console/pos/pos-cart-panel.component.js.map +1 -0
  79. package/src/lib/components/console/pos/pos-item-dialog.component.d.ts +39 -0
  80. package/src/lib/components/console/pos/pos-item-dialog.component.js +352 -0
  81. package/src/lib/components/console/pos/pos-item-dialog.component.js.map +1 -0
  82. package/src/lib/components/console/pos/pos-product-grid.component.d.ts +47 -0
  83. package/src/lib/components/console/pos/pos-product-grid.component.js +272 -0
  84. package/src/lib/components/console/pos/pos-product-grid.component.js.map +1 -0
  85. package/src/lib/components/console/pos/pos-receipt-panel.component.d.ts +27 -0
  86. package/src/lib/components/console/pos/pos-receipt-panel.component.js +282 -0
  87. package/src/lib/components/console/pos/pos-receipt-panel.component.js.map +1 -0
  88. package/src/lib/components/console/pos/pos-tender-dialogs.component.d.ts +53 -0
  89. package/src/lib/components/console/pos/pos-tender-dialogs.component.js +445 -0
  90. package/src/lib/components/console/pos/pos-tender-dialogs.component.js.map +1 -0
  91. package/src/lib/components/console/pos/pos-tender-panel.component.d.ts +31 -0
  92. package/src/lib/components/console/pos/pos-tender-panel.component.js +640 -0
  93. package/src/lib/components/console/pos/pos-tender-panel.component.js.map +1 -0
  94. package/src/lib/components/console/pos/use-pos-display.d.ts +43 -0
  95. package/src/lib/components/console/pos/use-pos-display.js +161 -0
  96. package/src/lib/components/console/pos/use-pos-display.js.map +1 -0
  97. package/src/lib/components/console/pos-devices-card.component.d.ts +14 -0
  98. package/src/lib/components/console/pos-devices-card.component.js +546 -0
  99. package/src/lib/components/console/pos-devices-card.component.js.map +1 -0
  100. package/src/lib/components/console/pos-display/brand-screen.d.ts +33 -0
  101. package/src/lib/components/console/pos-display/brand-screen.js +85 -0
  102. package/src/lib/components/console/pos-display/brand-screen.js.map +1 -0
  103. package/src/lib/components/console/pos-display/cart-screen.d.ts +29 -0
  104. package/src/lib/components/console/pos-display/cart-screen.js +166 -0
  105. package/src/lib/components/console/pos-display/cart-screen.js.map +1 -0
  106. package/src/lib/components/console/pos-display/pairing-screen.d.ts +24 -0
  107. package/src/lib/components/console/pos-display/pairing-screen.js +127 -0
  108. package/src/lib/components/console/pos-display/pairing-screen.js.map +1 -0
  109. package/src/lib/components/console/pos-display/pos-display-api.d.ts +90 -0
  110. package/src/lib/components/console/pos-display/pos-display-api.js +140 -0
  111. package/src/lib/components/console/pos-display/pos-display-api.js.map +1 -0
  112. package/src/lib/components/console/pos-display/receipt-screen.d.ts +35 -0
  113. package/src/lib/components/console/pos-display/receipt-screen.js +200 -0
  114. package/src/lib/components/console/pos-display/receipt-screen.js.map +1 -0
  115. package/src/lib/components/console/pos-display/tip-screen.d.ts +36 -0
  116. package/src/lib/components/console/pos-display/tip-screen.js +211 -0
  117. package/src/lib/components/console/pos-display/tip-screen.js.map +1 -0
  118. package/src/lib/components/console/pos-display-page.component.d.ts +16 -0
  119. package/src/lib/components/console/pos-display-page.component.js +407 -0
  120. package/src/lib/components/console/pos-display-page.component.js.map +1 -0
  121. package/src/lib/components/console/pos-ops/pos-customer-lookup.component.d.ts +40 -0
  122. package/src/lib/components/console/pos-ops/pos-customer-lookup.component.js +289 -0
  123. package/src/lib/components/console/pos-ops/pos-customer-lookup.component.js.map +1 -0
  124. package/src/lib/components/console/pos-ops/pos-last-receipt.component.d.ts +34 -0
  125. package/src/lib/components/console/pos-ops/pos-last-receipt.component.js +61 -0
  126. package/src/lib/components/console/pos-ops/pos-last-receipt.component.js.map +1 -0
  127. package/src/lib/components/console/pos-ops/pos-operations-bar.component.d.ts +38 -0
  128. package/src/lib/components/console/pos-ops/pos-operations-bar.component.js +129 -0
  129. package/src/lib/components/console/pos-ops/pos-operations-bar.component.js.map +1 -0
  130. package/src/lib/components/console/pos-ops/pos-ops-api.d.ts +37 -0
  131. package/src/lib/components/console/pos-ops/pos-ops-api.js +60 -0
  132. package/src/lib/components/console/pos-ops/pos-ops-api.js.map +1 -0
  133. package/src/lib/components/console/pos-ops/pos-pin-pad.component.d.ts +48 -0
  134. package/src/lib/components/console/pos-ops/pos-pin-pad.component.js +220 -0
  135. package/src/lib/components/console/pos-ops/pos-pin-pad.component.js.map +1 -0
  136. package/src/lib/components/console/pos-ops/pos-receipt-actions.component.d.ts +63 -0
  137. package/src/lib/components/console/pos-ops/pos-receipt-actions.component.js +186 -0
  138. package/src/lib/components/console/pos-ops/pos-receipt-actions.component.js.map +1 -0
  139. package/src/lib/components/console/pos-ops/pos-receipt.d.ts +39 -0
  140. package/src/lib/components/console/pos-ops/pos-receipt.js +182 -0
  141. package/src/lib/components/console/pos-ops/pos-receipt.js.map +1 -0
  142. package/src/lib/components/console/pos-ops/pos-return-dialog.component.d.ts +40 -0
  143. package/src/lib/components/console/pos-ops/pos-return-dialog.component.js +465 -0
  144. package/src/lib/components/console/pos-ops/pos-return-dialog.component.js.map +1 -0
  145. package/src/lib/components/console/pos-ops/pos-shift-history-card.component.d.ts +29 -0
  146. package/src/lib/components/console/pos-ops/pos-shift-history-card.component.js +253 -0
  147. package/src/lib/components/console/pos-ops/pos-shift-history-card.component.js.map +1 -0
  148. package/src/lib/components/console/pos-ops/pos-shift-panel.component.d.ts +34 -0
  149. package/src/lib/components/console/pos-ops/pos-shift-panel.component.js +494 -0
  150. package/src/lib/components/console/pos-ops/pos-shift-panel.component.js.map +1 -0
  151. package/src/lib/components/console/pos-ops/pos-shift-report.component.d.ts +37 -0
  152. package/src/lib/components/console/pos-ops/pos-shift-report.component.js +102 -0
  153. package/src/lib/components/console/pos-ops/pos-shift-report.component.js.map +1 -0
  154. package/src/lib/components/console/pos-ops/pos-staff-pins-card.component.d.ts +30 -0
  155. package/src/lib/components/console/pos-ops/pos-staff-pins-card.component.js +277 -0
  156. package/src/lib/components/console/pos-ops/pos-staff-pins-card.component.js.map +1 -0
  157. package/src/lib/components/console/pos-ops/register-ops.d.ts +28 -0
  158. package/src/lib/components/console/pos-ops/register-ops.js +28 -0
  159. package/src/lib/components/console/pos-ops/register-ops.js.map +1 -0
  160. package/src/lib/components/console/pos-ops/use-pos-cashier.d.ts +46 -0
  161. package/src/lib/components/console/pos-ops/use-pos-cashier.js +128 -0
  162. package/src/lib/components/console/pos-ops/use-pos-cashier.js.map +1 -0
  163. package/src/lib/components/console/pos-ops/use-pos-sale-receipt.d.ts +36 -0
  164. package/src/lib/components/console/pos-ops/use-pos-sale-receipt.js +64 -0
  165. package/src/lib/components/console/pos-ops/use-pos-sale-receipt.js.map +1 -0
  166. package/src/lib/components/console/pos-page.component.d.ts +13 -5
  167. package/src/lib/components/console/pos-page.component.js +756 -654
  168. package/src/lib/components/console/pos-page.component.js.map +1 -1
  169. package/src/lib/components/console/pos-zones.d.ts +23 -0
  170. package/src/lib/components/console/pos-zones.js +31 -0
  171. package/src/lib/components/console/pos-zones.js.map +1 -0
  172. package/src/lib/components/console/product-editor-dialog.component.js +61 -71
  173. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  174. package/src/lib/components/console/product-labels-dialog.component.d.ts +13 -0
  175. package/src/lib/components/console/product-labels-dialog.component.js +197 -0
  176. package/src/lib/components/console/product-labels-dialog.component.js.map +1 -0
  177. package/src/lib/components/console/product-register-fields.component.d.ts +19 -0
  178. package/src/lib/components/console/product-register-fields.component.js +241 -0
  179. package/src/lib/components/console/product-register-fields.component.js.map +1 -0
  180. package/src/lib/components/console/product-zones.d.ts +44 -0
  181. package/src/lib/components/console/product-zones.js.map +1 -1
  182. package/src/lib/components/console/products-hub-card.component.js +23 -20
  183. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  184. package/src/lib/components/console/register-hardware-card.component.d.ts +33 -0
  185. package/src/lib/components/console/register-hardware-card.component.js +826 -0
  186. package/src/lib/components/console/register-hardware-card.component.js.map +1 -0
  187. package/src/lib/components/console/registers-card.component.js +24 -5
  188. package/src/lib/components/console/registers-card.component.js.map +1 -1
  189. package/src/lib/components/console/return-actions.d.ts +38 -0
  190. package/src/lib/components/console/return-actions.js +76 -0
  191. package/src/lib/components/console/return-actions.js.map +1 -0
  192. package/src/lib/components/console/return-detail-dialog.component.d.ts +34 -0
  193. package/src/lib/components/console/return-detail-dialog.component.js +718 -0
  194. package/src/lib/components/console/return-detail-dialog.component.js.map +1 -0
  195. package/src/lib/components/console/return-settings-card.component.d.ts +34 -0
  196. package/src/lib/components/console/return-settings-card.component.js +195 -0
  197. package/src/lib/components/console/return-settings-card.component.js.map +1 -0
  198. package/src/lib/components/console/return-zones.d.ts +87 -0
  199. package/src/lib/components/console/return-zones.js +31 -0
  200. package/src/lib/components/console/return-zones.js.map +1 -0
  201. package/src/lib/components/console/returns-card.component.d.ts +45 -0
  202. package/src/lib/components/console/returns-card.component.js +159 -0
  203. package/src/lib/components/console/returns-card.component.js.map +1 -0
  204. package/src/lib/components/console/shipping-settings-card.component.js +161 -5
  205. package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
  206. package/src/lib/components/console/shippingeasy-card.component.d.ts +59 -0
  207. package/src/lib/components/console/shippingeasy-card.component.js +378 -0
  208. package/src/lib/components/console/shippingeasy-card.component.js.map +1 -0
  209. package/src/lib/components/console/shipstation-card.component.d.ts +35 -0
  210. package/src/lib/components/console/shipstation-card.component.js +345 -0
  211. package/src/lib/components/console/shipstation-card.component.js.map +1 -0
  212. package/src/lib/components/console/start-return-dialog.component.d.ts +40 -0
  213. package/src/lib/components/console/start-return-dialog.component.js +243 -0
  214. package/src/lib/components/console/start-return-dialog.component.js.map +1 -0
  215. package/src/lib/components/console/stock-movements-card.component.js +2 -1
  216. package/src/lib/components/console/stock-movements-card.component.js.map +1 -1
  217. package/src/lib/components/console/store-settings-card.component.js +2 -66
  218. package/src/lib/components/console/store-settings-card.component.js.map +1 -1
  219. package/src/lib/components/console/store-zones.d.ts +42 -0
  220. package/src/lib/components/console/store-zones.js +39 -0
  221. package/src/lib/components/console/store-zones.js.map +1 -0
  222. package/src/lib/components/console/storefront-tax-summary-card.component.js +1 -0
  223. package/src/lib/components/console/storefront-tax-summary-card.component.js.map +1 -1
  224. package/src/lib/components/order-status.d.ts +36 -0
  225. package/src/lib/components/order-status.js +502 -0
  226. package/src/lib/components/order-status.js.map +1 -0
  227. package/src/lib/components/product-detail.js +41 -2
  228. package/src/lib/components/product-detail.js.map +1 -1
  229. package/src/lib/components/return-request.d.ts +32 -0
  230. package/src/lib/components/return-request.js +576 -0
  231. package/src/lib/components/return-request.js.map +1 -0
  232. package/src/lib/components/storefront-payment-appearance.d.ts +32 -0
  233. package/src/lib/components/storefront-payment-appearance.js +114 -0
  234. package/src/lib/components/storefront-payment-appearance.js.map +1 -0
  235. package/src/lib/components/storefront-payment-element.d.ts +57 -1
  236. package/src/lib/components/storefront-payment-element.js +332 -33
  237. package/src/lib/components/storefront-payment-element.js.map +1 -1
  238. package/src/lib/constants/order-status.d.ts +22 -0
  239. package/src/lib/constants/order-status.js +22 -0
  240. package/src/lib/constants/order-status.js.map +1 -0
  241. package/src/lib/constants/return-request.d.ts +27 -0
  242. package/src/lib/constants/return-request.js +32 -0
  243. package/src/lib/constants/return-request.js.map +1 -0
  244. package/src/lib/constants/stock-movement-query.js +2 -1
  245. package/src/lib/constants/stock-movement-query.js.map +1 -1
  246. package/src/lib/declarations.console-server.js +9 -0
  247. package/src/lib/declarations.console-server.js.map +1 -1
  248. package/src/lib/declarations.server.d.ts +2 -1
  249. package/src/lib/declarations.server.js +68 -1
  250. package/src/lib/declarations.server.js.map +1 -1
  251. package/src/lib/model/buyer-notifications.d.ts +59 -0
  252. package/src/lib/model/buyer-notifications.js +97 -0
  253. package/src/lib/model/buyer-notifications.js.map +1 -0
  254. package/src/lib/model/commerce-orders.d.ts +171 -2
  255. package/src/lib/model/commerce-orders.js +26 -16
  256. package/src/lib/model/commerce-orders.js.map +1 -1
  257. package/src/lib/model/commerce-payment-methods.d.ts +146 -0
  258. package/src/lib/model/commerce-payment-methods.js +247 -0
  259. package/src/lib/model/commerce-payment-methods.js.map +1 -0
  260. package/src/lib/model/commerce-pos-ops.d.ts +437 -0
  261. package/src/lib/model/commerce-pos-ops.js +721 -0
  262. package/src/lib/model/commerce-pos-ops.js.map +1 -0
  263. package/src/lib/model/commerce-pos.d.ts +263 -0
  264. package/src/lib/model/commerce-pos.js +375 -0
  265. package/src/lib/model/commerce-pos.js.map +1 -0
  266. package/src/lib/model/commerce-printers.d.ts +211 -0
  267. package/src/lib/model/commerce-printers.js +181 -0
  268. package/src/lib/model/commerce-printers.js.map +1 -0
  269. package/src/lib/model/commerce-receipt.d.ts +97 -0
  270. package/src/lib/model/commerce-receipt.js +180 -0
  271. package/src/lib/model/commerce-receipt.js.map +1 -0
  272. package/src/lib/model/commerce-returns.d.ts +207 -0
  273. package/src/lib/model/commerce-returns.js +300 -0
  274. package/src/lib/model/commerce-returns.js.map +1 -0
  275. package/src/lib/model/commerce-shipping.d.ts +44 -1
  276. package/src/lib/model/commerce-shipping.js +53 -9
  277. package/src/lib/model/commerce-shipping.js.map +1 -1
  278. package/src/lib/model/commerce-tax-engine.d.ts +90 -0
  279. package/src/lib/model/commerce-tax-engine.js +129 -0
  280. package/src/lib/model/commerce-tax-engine.js.map +1 -0
  281. package/src/lib/model/commerce.d.ts +91 -2
  282. package/src/lib/model/commerce.js +89 -1
  283. package/src/lib/model/commerce.js.map +1 -1
  284. package/src/lib/model/index.d.ts +16 -0
  285. package/src/lib/model/index.js +16 -0
  286. package/src/lib/model/index.js.map +1 -1
  287. package/src/lib/model/order-events.d.ts +154 -0
  288. package/src/lib/model/order-events.js +153 -0
  289. package/src/lib/model/order-events.js.map +1 -0
  290. package/src/lib/model/order-fulfillment.d.ts +117 -0
  291. package/src/lib/model/order-fulfillment.js +217 -0
  292. package/src/lib/model/order-fulfillment.js.map +1 -0
  293. package/src/lib/model/order-history.d.ts +58 -0
  294. package/src/lib/model/order-history.js +22 -0
  295. package/src/lib/model/order-history.js.map +1 -0
  296. package/src/lib/model/order-list-fields.d.ts +9 -1
  297. package/src/lib/model/order-list-fields.js +7 -1
  298. package/src/lib/model/order-list-fields.js.map +1 -1
  299. package/src/lib/model/order-shipping-export.d.ts +91 -0
  300. package/src/lib/model/order-shipping-export.js +192 -0
  301. package/src/lib/model/order-shipping-export.js.map +1 -0
  302. package/src/lib/model/order-status-view.d.ts +103 -0
  303. package/src/lib/model/order-status-view.js +156 -0
  304. package/src/lib/model/order-status-view.js.map +1 -0
  305. package/src/lib/model/order-webhooks.d.ts +142 -0
  306. package/src/lib/model/order-webhooks.js +91 -0
  307. package/src/lib/model/order-webhooks.js.map +1 -0
  308. package/src/lib/model/product-channel.d.ts +56 -0
  309. package/src/lib/model/product-channel.js +86 -0
  310. package/src/lib/model/product-channel.js.map +1 -0
  311. package/src/lib/model/product-modifiers.d.ts +80 -0
  312. package/src/lib/model/product-modifiers.js +140 -0
  313. package/src/lib/model/product-modifiers.js.map +1 -0
  314. package/src/lib/model/product-write.d.ts +186 -0
  315. package/src/lib/model/product-write.js +116 -0
  316. package/src/lib/model/product-write.js.map +1 -0
  317. package/src/lib/model/shippingeasy.d.ts +94 -0
  318. package/src/lib/model/shippingeasy.js +267 -0
  319. package/src/lib/model/shippingeasy.js.map +1 -0
  320. package/src/lib/model/shipstation.d.ts +125 -0
  321. package/src/lib/model/shipstation.js +399 -0
  322. package/src/lib/model/shipstation.js.map +1 -0
  323. package/src/lib/model/smart-collection-reads.d.ts +32 -0
  324. package/src/lib/model/smart-collection-reads.js +63 -0
  325. package/src/lib/model/smart-collection-reads.js.map +1 -0
  326. package/src/lib/model/tracking-url.d.ts +74 -0
  327. package/src/lib/model/tracking-url.js +159 -0
  328. package/src/lib/model/tracking-url.js.map +1 -0
  329. package/src/lib/plugin-config.d.ts +13 -0
  330. package/src/lib/plugin-config.js +77 -5
  331. package/src/lib/plugin-config.js.map +1 -1
  332. package/src/lib/plugin.js +26 -0
  333. package/src/lib/plugin.js.map +1 -1
  334. package/src/lib/pos-ops-config.d.ts +39 -0
  335. package/src/lib/pos-ops-config.js +88 -0
  336. package/src/lib/pos-ops-config.js.map +1 -0
  337. package/src/lib/printing/print-document.d.ts +106 -0
  338. package/src/lib/printing/print-document.js +464 -0
  339. package/src/lib/printing/print-document.js.map +1 -0
  340. package/src/lib/printing/product-labels.d.ts +58 -0
  341. package/src/lib/printing/product-labels.js +116 -0
  342. package/src/lib/printing/product-labels.js.map +1 -0
  343. package/src/lib/printing/render-epson.d.ts +57 -0
  344. package/src/lib/printing/render-epson.js +135 -0
  345. package/src/lib/printing/render-epson.js.map +1 -0
  346. package/src/lib/printing/render-star.d.ts +45 -0
  347. package/src/lib/printing/render-star.js +100 -0
  348. package/src/lib/printing/render-star.js.map +1 -0
  349. package/src/lib/printing/render-text.d.ts +25 -0
  350. package/src/lib/printing/render-text.js +53 -0
  351. package/src/lib/printing/render-text.js.map +1 -0
  352. package/src/lib/server/api-v1/openapi.js +27 -4
  353. package/src/lib/server/api-v1/openapi.js.map +1 -1
  354. package/src/lib/server/api-v1/order-view.d.ts +67 -0
  355. package/src/lib/server/api-v1/order-view.js +120 -0
  356. package/src/lib/server/api-v1/order-view.js.map +1 -0
  357. package/src/lib/server/api-v1/orders-and-products.js +58 -65
  358. package/src/lib/server/api-v1/orders-and-products.js.map +1 -1
  359. package/src/lib/server/billing-webhook.js +135 -28
  360. package/src/lib/server/billing-webhook.js.map +1 -1
  361. package/src/lib/server/cancel-order.js +29 -0
  362. package/src/lib/server/cancel-order.js.map +1 -1
  363. package/src/lib/server/carrier-rates-availability.d.ts +26 -0
  364. package/src/lib/server/carrier-rates-availability.js +76 -0
  365. package/src/lib/server/carrier-rates-availability.js.map +1 -0
  366. package/src/lib/server/carrier-shipping.d.ts +84 -0
  367. package/src/lib/server/carrier-shipping.js +135 -0
  368. package/src/lib/server/carrier-shipping.js.map +1 -0
  369. package/src/lib/server/cart-checkout.d.ts +2 -0
  370. package/src/lib/server/cart-checkout.js +226 -22
  371. package/src/lib/server/cart-checkout.js.map +1 -1
  372. package/src/lib/server/channel-order-updates.d.ts +50 -0
  373. package/src/lib/server/channel-order-updates.js +290 -0
  374. package/src/lib/server/channel-order-updates.js.map +1 -0
  375. package/src/lib/server/channel-orders.d.ts +85 -0
  376. package/src/lib/server/channel-orders.js +543 -0
  377. package/src/lib/server/channel-orders.js.map +1 -0
  378. package/src/lib/server/checkout-extras.d.ts +64 -0
  379. package/src/lib/server/checkout-extras.js +157 -0
  380. package/src/lib/server/checkout-extras.js.map +1 -0
  381. package/src/lib/server/{feed.d.ts → checkout-status.d.ts} +2 -7
  382. package/src/lib/server/checkout-status.js +111 -0
  383. package/src/lib/server/checkout-status.js.map +1 -0
  384. package/src/lib/server/checkout.js +86 -9
  385. package/src/lib/server/checkout.js.map +1 -1
  386. package/src/lib/server/draft-order.js +34 -5
  387. package/src/lib/server/draft-order.js.map +1 -1
  388. package/src/lib/server/fulfill-order.d.ts +127 -10
  389. package/src/lib/server/fulfill-order.js +451 -49
  390. package/src/lib/server/fulfill-order.js.map +1 -1
  391. package/src/lib/server/legacy-feed.d.ts +28 -0
  392. package/src/lib/server/legacy-feed.js +52 -0
  393. package/src/lib/server/legacy-feed.js.map +1 -0
  394. package/src/lib/server/native-checkout.d.ts +34 -15
  395. package/src/lib/server/native-checkout.js +32 -17
  396. package/src/lib/server/native-checkout.js.map +1 -1
  397. package/src/lib/server/order-event-host-emit.d.ts +23 -0
  398. package/src/lib/server/order-event-host-emit.js +30 -0
  399. package/src/lib/server/order-event-host-emit.js.map +1 -0
  400. package/src/lib/server/order-event-triggers.d.ts +37 -0
  401. package/src/lib/server/order-event-triggers.js +119 -0
  402. package/src/lib/server/order-event-triggers.js.map +1 -0
  403. package/src/lib/server/order-events.d.ts +62 -0
  404. package/src/lib/server/order-events.js +109 -0
  405. package/src/lib/server/order-events.js.map +1 -0
  406. package/src/lib/server/order-history.d.ts +23 -0
  407. package/src/lib/server/order-history.js +65 -0
  408. package/src/lib/server/order-history.js.map +1 -0
  409. package/src/lib/server/order-notifications.d.ts +185 -0
  410. package/src/lib/server/order-notifications.js +567 -0
  411. package/src/lib/server/order-notifications.js.map +1 -0
  412. package/src/lib/server/order-receipt-send.d.ts +39 -0
  413. package/src/lib/server/order-receipt-send.js +151 -0
  414. package/src/lib/server/order-receipt-send.js.map +1 -0
  415. package/src/lib/server/order-status-token.d.ts +31 -0
  416. package/src/lib/server/order-status-token.js +75 -0
  417. package/src/lib/server/order-status-token.js.map +1 -0
  418. package/src/lib/server/order-status.d.ts +58 -0
  419. package/src/lib/server/order-status.js +141 -0
  420. package/src/lib/server/order-status.js.map +1 -0
  421. package/src/lib/server/order-webhooks.d.ts +108 -0
  422. package/src/lib/server/order-webhooks.js +622 -0
  423. package/src/lib/server/order-webhooks.js.map +1 -0
  424. package/src/lib/server/orders-shipping-prepare.d.ts +26 -0
  425. package/src/lib/server/orders-shipping-prepare.js +121 -0
  426. package/src/lib/server/orders-shipping-prepare.js.map +1 -0
  427. package/src/lib/server/payment-method-domains.d.ts +209 -0
  428. package/src/lib/server/payment-method-domains.js +444 -0
  429. package/src/lib/server/payment-method-domains.js.map +1 -0
  430. package/src/lib/server/payment-methods.d.ts +77 -0
  431. package/src/lib/server/payment-methods.js +284 -0
  432. package/src/lib/server/payment-methods.js.map +1 -0
  433. package/src/lib/server/pos-auth.d.ts +50 -0
  434. package/src/lib/server/pos-auth.js +121 -0
  435. package/src/lib/server/pos-auth.js.map +1 -0
  436. package/src/lib/server/pos-customer.d.ts +49 -0
  437. package/src/lib/server/pos-customer.js +257 -0
  438. package/src/lib/server/pos-customer.js.map +1 -0
  439. package/src/lib/server/pos-display.d.ts +57 -0
  440. package/src/lib/server/pos-display.js +419 -0
  441. package/src/lib/server/pos-display.js.map +1 -0
  442. package/src/lib/server/pos-fee-month.d.ts +34 -0
  443. package/src/lib/server/pos-fee-month.js +36 -0
  444. package/src/lib/server/pos-fee-month.js.map +1 -0
  445. package/src/lib/server/pos-ops-gate.d.ts +161 -0
  446. package/src/lib/server/pos-ops-gate.js +295 -0
  447. package/src/lib/server/pos-ops-gate.js.map +1 -0
  448. package/src/lib/server/pos-ops-routes.d.ts +22 -0
  449. package/src/lib/server/pos-ops-routes.js +36 -0
  450. package/src/lib/server/pos-ops-routes.js.map +1 -0
  451. package/src/lib/server/pos-order.d.ts +1 -18
  452. package/src/lib/server/pos-order.js +222 -42
  453. package/src/lib/server/pos-order.js.map +1 -1
  454. package/src/lib/server/pos-payment.d.ts +39 -0
  455. package/src/lib/server/pos-payment.js +922 -0
  456. package/src/lib/server/pos-payment.js.map +1 -0
  457. package/src/lib/server/pos-print.d.ts +82 -0
  458. package/src/lib/server/pos-print.js +193 -0
  459. package/src/lib/server/pos-print.js.map +1 -0
  460. package/src/lib/server/pos-readers.d.ts +27 -0
  461. package/src/lib/server/pos-readers.js +276 -0
  462. package/src/lib/server/pos-readers.js.map +1 -0
  463. package/src/lib/server/pos-refund-authority.d.ts +60 -0
  464. package/src/lib/server/pos-refund-authority.js +72 -0
  465. package/src/lib/server/pos-refund-authority.js.map +1 -0
  466. package/src/lib/server/pos-return.d.ts +58 -0
  467. package/src/lib/server/pos-return.js +891 -0
  468. package/src/lib/server/pos-return.js.map +1 -0
  469. package/src/lib/server/pos-sale-stamp.d.ts +66 -0
  470. package/src/lib/server/pos-sale-stamp.js +84 -0
  471. package/src/lib/server/pos-sale-stamp.js.map +1 -0
  472. package/src/lib/server/pos-sale.d.ts +170 -0
  473. package/src/lib/server/pos-sale.js +461 -0
  474. package/src/lib/server/pos-sale.js.map +1 -0
  475. package/src/lib/server/pos-shift.d.ts +45 -0
  476. package/src/lib/server/pos-shift.js +484 -0
  477. package/src/lib/server/pos-shift.js.map +1 -0
  478. package/src/lib/server/pos-staff-pin.d.ts +26 -0
  479. package/src/lib/server/pos-staff-pin.js +339 -0
  480. package/src/lib/server/pos-staff-pin.js.map +1 -0
  481. package/src/lib/server/pos-stripe.d.ts +91 -0
  482. package/src/lib/server/pos-stripe.js +129 -0
  483. package/src/lib/server/pos-stripe.js.map +1 -0
  484. package/src/lib/server/pos-terminal-connection-token.d.ts +48 -0
  485. package/src/lib/server/pos-terminal-connection-token.js +166 -0
  486. package/src/lib/server/pos-terminal-connection-token.js.map +1 -0
  487. package/src/lib/server/pos-terminal.d.ts +218 -0
  488. package/src/lib/server/pos-terminal.js +1014 -0
  489. package/src/lib/server/pos-terminal.js.map +1 -0
  490. package/src/lib/server/print-queue.d.ts +124 -0
  491. package/src/lib/server/print-queue.js +301 -0
  492. package/src/lib/server/print-queue.js.map +1 -0
  493. package/src/lib/server/printer-poll.d.ts +75 -0
  494. package/src/lib/server/printer-poll.js +325 -0
  495. package/src/lib/server/printer-poll.js.map +1 -0
  496. package/src/lib/server/printer-secret.d.ts +39 -0
  497. package/src/lib/server/printer-secret.js +56 -0
  498. package/src/lib/server/printer-secret.js.map +1 -0
  499. package/src/lib/server/printers.d.ts +114 -0
  500. package/src/lib/server/printers.js +546 -0
  501. package/src/lib/server/printers.js.map +1 -0
  502. package/src/lib/server/product-catalog.d.ts +42 -0
  503. package/src/lib/server/product-catalog.js +309 -0
  504. package/src/lib/server/product-catalog.js.map +1 -0
  505. package/src/lib/server/product-drafts.d.ts +5 -1
  506. package/src/lib/server/product-drafts.js +3 -3
  507. package/src/lib/server/product-drafts.js.map +1 -1
  508. package/src/lib/server/product-writer.d.ts +19 -0
  509. package/src/lib/server/product-writer.js +261 -0
  510. package/src/lib/server/product-writer.js.map +1 -0
  511. package/src/lib/server/products-write.d.ts +61 -0
  512. package/src/lib/server/products-write.js +375 -0
  513. package/src/lib/server/products-write.js.map +1 -0
  514. package/src/lib/server/refund.js +110 -45
  515. package/src/lib/server/refund.js.map +1 -1
  516. package/src/lib/server/reserve.js +2 -0
  517. package/src/lib/server/reserve.js.map +1 -1
  518. package/src/lib/server/return-status-action.d.ts +37 -0
  519. package/src/lib/server/return-status-action.js +57 -0
  520. package/src/lib/server/return-status-action.js.map +1 -0
  521. package/src/lib/server/returns.d.ts +119 -0
  522. package/src/lib/server/returns.js +938 -0
  523. package/src/lib/server/returns.js.map +1 -0
  524. package/src/lib/server/shipment-records.d.ts +36 -0
  525. package/src/lib/server/shipment-records.js +289 -0
  526. package/src/lib/server/shipment-records.js.map +1 -0
  527. package/src/lib/server/shipping-connector-gates.d.ts +40 -0
  528. package/src/lib/server/shipping-connector-gates.js +97 -0
  529. package/src/lib/server/shipping-connector-gates.js.map +1 -0
  530. package/src/lib/server/shipping-connectors.d.ts +29 -0
  531. package/src/lib/server/shipping-connectors.js +236 -0
  532. package/src/lib/server/shipping-connectors.js.map +1 -0
  533. package/src/lib/server/shippingeasy.d.ts +238 -0
  534. package/src/lib/server/shippingeasy.js +787 -0
  535. package/src/lib/server/shippingeasy.js.map +1 -0
  536. package/src/lib/server/shipstation.d.ts +129 -0
  537. package/src/lib/server/shipstation.js +483 -0
  538. package/src/lib/server/shipstation.js.map +1 -0
  539. package/src/lib/server/site-page-resolver.d.ts +5 -0
  540. package/src/lib/server/site-page-resolver.js +156 -1
  541. package/src/lib/server/site-page-resolver.js.map +1 -1
  542. package/src/lib/server/stock-levels.d.ts +21 -0
  543. package/src/lib/server/stock-levels.js +263 -0
  544. package/src/lib/server/stock-levels.js.map +1 -0
  545. package/src/lib/server/stripe-refund.d.ts +47 -0
  546. package/src/lib/server/stripe-refund.js +87 -0
  547. package/src/lib/server/stripe-refund.js.map +1 -0
  548. package/src/lib/server/supplier-update.js +46 -5
  549. package/src/lib/server/supplier-update.js.map +1 -1
  550. package/src/lib/server/tax-engine-quote.d.ts +47 -0
  551. package/src/lib/server/tax-engine-quote.js +105 -0
  552. package/src/lib/server/tax-engine-quote.js.map +1 -0
  553. package/src/lib/server.js +143 -2
  554. package/src/lib/server.js.map +1 -1
  555. package/src/lib/site.js +12 -0
  556. package/src/lib/site.js.map +1 -1
  557. package/src/lib/subprocessors.d.ts +26 -0
  558. package/src/lib/subprocessors.js +50 -0
  559. package/src/lib/subprocessors.js.map +1 -0
  560. package/src/lib/tenant-emails.js +461 -3
  561. package/src/lib/tenant-emails.js.map +1 -1
  562. package/src/lib/testing/fake-firestore.d.ts +45 -0
  563. package/src/lib/testing/fake-firestore.js +189 -0
  564. package/src/lib/testing/fake-firestore.js.map +1 -0
  565. package/src/lib/testing/memory-firestore.d.ts +136 -0
  566. package/src/lib/testing/memory-firestore.js +282 -0
  567. package/src/lib/testing/memory-firestore.js.map +1 -0
  568. package/src/lib/testing/pos-ops-harness.d.ts +50 -0
  569. package/src/lib/testing/pos-ops-harness.js +184 -0
  570. package/src/lib/testing/pos-ops-harness.js.map +1 -0
  571. package/src/lib/testing/pos-ops-memory-firestore.d.ts +55 -0
  572. package/src/lib/testing/pos-ops-memory-firestore.js +376 -0
  573. package/src/lib/testing/pos-ops-memory-firestore.js.map +1 -0
  574. package/src/lib/transfer/products.server.d.ts +5 -0
  575. package/src/lib/transfer/products.server.js +2 -2
  576. package/src/lib/transfer/products.server.js.map +1 -1
  577. package/src/lib/transfer/records-transfer.d.ts +11 -1
  578. package/src/lib/transfer/records-transfer.js +127 -5
  579. package/src/lib/transfer/records-transfer.js.map +1 -1
  580. package/src/lib/transfer/records.server.d.ts +9 -2
  581. package/src/lib/transfer/records.server.js +58 -7
  582. package/src/lib/transfer/records.server.js.map +1 -1
  583. package/src/lib/transfer/register-transfer-resources.js +40 -1
  584. package/src/lib/transfer/register-transfer-resources.js.map +1 -1
  585. package/src/lib/transfer/register-transfer-ui.js +4 -1
  586. package/src/lib/transfer/register-transfer-ui.js.map +1 -1
  587. package/src/lib/transfer/shipping-presets.d.ts +23 -0
  588. package/src/lib/transfer/shipping-presets.js +156 -0
  589. package/src/lib/transfer/shipping-presets.js.map +1 -0
  590. package/src/lib/transfer/tracking-transfer.d.ts +101 -0
  591. package/src/lib/transfer/tracking-transfer.js +546 -0
  592. package/src/lib/transfer/tracking-transfer.js.map +1 -0
  593. package/src/lib/transfer/tracking.server.d.ts +37 -0
  594. package/src/lib/transfer/tracking.server.js +393 -0
  595. package/src/lib/transfer/tracking.server.js.map +1 -0
  596. package/src/lib/transfer/transfer-keys.d.ts +2 -1
  597. package/src/lib/transfer/transfer-keys.js +6 -2
  598. package/src/lib/transfer/transfer-keys.js.map +1 -1
  599. package/src/lib/utils/code128.d.ts +37 -0
  600. package/src/lib/utils/code128.js +199 -0
  601. package/src/lib/utils/code128.js.map +1 -0
  602. package/src/lib/utils/order-invoice.d.ts +55 -0
  603. package/src/lib/utils/order-invoice.js +127 -0
  604. package/src/lib/utils/order-invoice.js.map +1 -0
  605. package/src/lib/utils/use-checkout-return-notice.d.ts +34 -0
  606. package/src/lib/utils/use-checkout-return-notice.js +78 -0
  607. package/src/lib/utils/use-checkout-return-notice.js.map +1 -0
  608. package/src/lib/server/feed.js +0 -69
  609. package/src/lib/server/feed.js.map +0 -1
@@ -22,7 +22,12 @@ import { createHash } from "crypto";
22
22
  import { recordPluginPersonRefund } from "@aglyn/aglyn/plugin-manager/plugin-person-records";
23
23
  import { applyGiftCardRiskToOrder } from "./gift-card-risk.js";
24
24
  import { flagOrderRestock } from "./restock-flag.js";
25
+ import { notifyOrderBuyer } from "./order-notifications.js";
26
+ import { ORDER_REFUNDED_EVENT } from "../model/order-events.js";
27
+ import { raiseOrderEvent } from "./order-events.js";
25
28
  import { reverseOrderConversion } from "@aglyn/aglyn/plugin-manager/plugin-conversion-credit";
29
+ import { createStripeRefund } from "./stripe-refund.js";
30
+ import { posRegisterRefundAuthority } from "./pos-refund-authority.js";
26
31
  /**
27
32
  * Retires the licence keys a refund withdrew (AGL-2454).
28
33
  *
@@ -143,7 +148,8 @@ import { reverseOrderConversion } from "@aglyn/aglyn/plugin-manager/plugin-conve
143
148
  }
144
149
  let claim = null;
145
150
  try {
146
- var _hostSnapshot_get, _order_lineItems, _order_paymentIntentId;
151
+ var _hostSnapshot_get, _order_lineItems, _order_paymentRefunds, _ref1, _ref2, _ref3;
152
+ var _membership_permissions;
147
153
  const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
148
154
  const firestore = firebaseAdmin.app().firestore();
149
155
  const hostRef = firestore.collection('hosts').doc(hostId);
@@ -159,11 +165,6 @@ import { reverseOrderConversion } from "@aglyn/aglyn/plugin-manager/plugin-conve
159
165
  // it stays: `memberRoles` is the projection the rules read, so dropping it
160
166
  // here would let this route and the database disagree.
161
167
  const memberRole = ((_hostSnapshot_get = hostSnapshot.get('memberRoles')) != null ? _hostSnapshot_get : {})[decoded.uid];
162
- if (memberRole !== 'admin') {
163
- return res.status(403).json({
164
- error: 'Refunds require a site admin'
165
- });
166
- }
167
168
  // The second is WHOSE admin, and it is the one this gate was missing.
168
169
  //
169
170
  // `memberRoles` is a per-host projection of `hostAccess`, and
@@ -188,9 +189,16 @@ import { reverseOrderConversion } from "@aglyn/aglyn/plugin-manager/plugin-conve
188
189
  const membership = await resolveOrgPermissions(decoded.uid, {
189
190
  hostId
190
191
  });
191
- if (!membership.orgWide || membership.hostRole !== 'admin') {
192
+ const workspaceAdmin = memberRole === 'admin' && membership.orgWide === true && membership.hostRole === 'admin';
193
+ // THE REGISTER'S OWN REFUNDS (AGL-3609). A member who works the register
194
+ // — `admin` or `editor` on this site with `managePos` — may refund a POS
195
+ // order up to the site's cashier refund limit, and above it with a
196
+ // workspace admin's PIN. Decided below, once the order and the amount are
197
+ // known; every other refund still needs the workspace admin above.
198
+ const registerStaff = !workspaceAdmin && (memberRole === 'admin' || memberRole === 'editor') && ((_membership_permissions = membership.permissions) == null ? void 0 : _membership_permissions.managePos) === true;
199
+ if (!workspaceAdmin && !registerStaff) {
192
200
  return res.status(403).json({
193
- error: 'Refunds require an admin of the whole workspace'
201
+ error: memberRole !== 'admin' ? 'Refunds require a site admin' : 'Refunds require an admin of the whole workspace'
194
202
  });
195
203
  }
196
204
  const orderRef = hostRef.collection('orders').doc(orderId);
@@ -201,6 +209,19 @@ import { reverseOrderConversion } from "@aglyn/aglyn/plugin-manager/plugin-conve
201
209
  });
202
210
  }
203
211
  const order = CommerceModel.liftLegacyOrder(orderSnapshot.data());
212
+ if (registerStaff) {
213
+ var _ref4, _body_registerId;
214
+ const authority = await posRegisterRefundAuthority({
215
+ hostId,
216
+ hostRef,
217
+ order,
218
+ amountCents,
219
+ lineCents: requestedLineIds.length ? CommerceModel.orderLineRefundCents(order, requestedLineIds) : null,
220
+ registerId: String((_ref4 = (_body_registerId = body.registerId) != null ? _body_registerId : order.registerId) != null ? _ref4 : ''),
221
+ managerAssertion: body.managerAssertion
222
+ });
223
+ if ('body' in authority) return res.status(403).json(authority.body);
224
+ }
204
225
  // Replay a settled attempt before anything else can reject it. This read
205
226
  // is only a short-circuit, never the dedupe primitive — the atomic
206
227
  // `create()` below is. It has to run ahead of the status guard because a
@@ -284,7 +305,11 @@ import { reverseOrderConversion } from "@aglyn/aglyn/plugin-manager/plugin-conve
284
305
  error: 'That amount is less than the lines you selected are worth. ' + 'Refund the full value of those lines, or refund an amount ' + 'without selecting lines.'
285
306
  });
286
307
  }
287
- const paymentIntentId = (_order_paymentIntentId = order.paymentIntentId) != null ? _order_paymentIntentId : // Legacy rows stored the checkout session as the doc id; resolve
308
+ // A register sale paid with SEVERAL cards (AGL-3607) has no single
309
+ // charge to refund: each refund is taken from one card that can cover it.
310
+ const splitCards = CommerceModel.orderPayments(order).filter((payment)=>payment.status === 'succeeded' && CommerceModel.isCardPaymentMethod(payment.method) && Boolean(payment.paymentIntentId));
311
+ const splitRefunds = (_order_paymentRefunds = order.paymentRefunds) != null ? _order_paymentRefunds : {};
312
+ let paymentIntentId = (_ref1 = (_ref2 = splitCards.length > 1 ? splitCards[0].paymentIntentId : undefined) != null ? _ref2 : order.paymentIntentId) != null ? _ref1 : // Legacy rows stored the checkout session as the doc id; resolve
288
313
  // the payment intent from Stripe.
289
314
  await (async ()=>{
290
315
  const response = await fetch(`https://api.stripe.com/v1/checkout/sessions/${orderId}`, {
@@ -310,10 +335,10 @@ import { reverseOrderConversion } from "@aglyn/aglyn/plugin-manager/plugin-conve
310
335
  if (claimRef) {
311
336
  const ownerOrg = await getOrgForHost(hostId);
312
337
  try {
313
- var _ref1;
338
+ var _ref5;
314
339
  var _ownerOrg_org;
315
340
  await claimRef.create({
316
- orgId: String((_ref1 = ownerOrg == null ? void 0 : (_ownerOrg_org = ownerOrg.org) == null ? void 0 : _ownerOrg_org.id) != null ? _ref1 : '') || null,
341
+ orgId: String((_ref5 = ownerOrg == null ? void 0 : (_ownerOrg_org = ownerOrg.org) == null ? void 0 : _ownerOrg_org.id) != null ? _ref5 : '') || null,
317
342
  hostId,
318
343
  orderId,
319
344
  kind: 'commerce-refund',
@@ -421,27 +446,41 @@ import { reverseOrderConversion } from "@aglyn/aglyn/plugin-manager/plugin-conve
421
446
  error: `Only $${(refundCents / 100).toFixed(2)} is left to refund on this ` + `order, and the lines you selected are worth $${(namedLinesCents / 100).toFixed(2)}. Refund an amount without selecting lines instead.`
422
447
  });
423
448
  }
424
- const params = new URLSearchParams({
425
- payment_intent: String(paymentIntentId),
426
- amount: String(refundCents),
427
- reverse_transfer: 'true',
428
- refund_application_fee: 'true'
429
- });
430
- const response = await fetch('https://api.stripe.com/v1/refunds', {
431
- method: 'POST',
432
- headers: _extends({
433
- Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
434
- 'Content-Type': 'application/x-www-form-urlencoded'
435
- }, (claim == null ? void 0 : claim.stripeKey) ? {
436
- 'Idempotency-Key': claim.stripeKey
437
- } : {}),
438
- body: params.toString()
449
+ if (splitCards.length > 1) {
450
+ // The card this refund comes off: the first with enough left on it.
451
+ // A refund larger than any one card refuses with the largest that
452
+ // fits, rather than splitting money across charges unasked; a part a
453
+ // customer paid in cash or by gift card is handed back at the till.
454
+ const capacity = (payment)=>{
455
+ var _payment_tipCents, _splitRefunds_String;
456
+ return payment.amountCents + Number((_payment_tipCents = payment.tipCents) != null ? _payment_tipCents : 0) - Number((_splitRefunds_String = splitRefunds[String(payment.paymentIntentId)]) != null ? _splitRefunds_String : 0);
457
+ };
458
+ const card = splitCards.find((payment)=>capacity(payment) >= refundCents);
459
+ if (!card) {
460
+ await firestore.runTransaction(async (transaction)=>{
461
+ var _get;
462
+ const current = Number((_get = (await transaction.get(orderRef)).get('refundedCents')) != null ? _get : 0);
463
+ transaction.set(orderRef, {
464
+ refundedCents: Math.max(0, current - refundCents)
465
+ }, {
466
+ merge: true
467
+ });
468
+ }).catch(()=>undefined);
469
+ await (claim == null ? void 0 : claim.release());
470
+ const largest = Math.max(0, ...splitCards.map(capacity));
471
+ return res.status(409).json({
472
+ error: 'This sale was paid with several cards, and no one card has ' + `$${(refundCents / 100).toFixed(2)} left to refund. Refund at most ` + `$${(largest / 100).toFixed(2)} at a time; hand back any part paid ` + 'in cash or by gift card at the register.'
473
+ });
474
+ }
475
+ paymentIntentId = String(card.paymentIntentId);
476
+ }
477
+ const refund = await createStripeRefund({
478
+ paymentIntentId: String(paymentIntentId),
479
+ amountCents: refundCents,
480
+ idempotencyKey: (_ref3 = claim == null ? void 0 : claim.stripeKey) != null ? _ref3 : null
439
481
  });
440
- const refund = await response.json();
441
- if (!response.ok) {
442
- var _ref2, _ref3;
443
- var _refund_error, _refund_error1;
444
- console.error('Stripe refund error', refund == null ? void 0 : refund.error);
482
+ if ('error' in refund) {
483
+ console.error('Stripe refund error', refund.code, refund.error);
445
484
  // Stripe said no, so we KNOW no money moved: give the reservation back
446
485
  // and let the same attempt be tried again.
447
486
  await firestore.runTransaction(async (transaction)=>{
@@ -457,22 +496,14 @@ import { reverseOrderConversion } from "@aglyn/aglyn/plugin-manager/plugin-conve
457
496
  // Stripe refusing BECAUSE OF A DISPUTE is the guard above arriving by
458
497
  // the other door — our order document simply didn't know yet (webhook
459
498
  // lag, or an order from before disputes were subscribed at all). Same
460
- // answer, same accuracy: a 409 naming the dispute, not a 502 reading
461
- // "The charge you're attempting to refund has been charged back", which
462
- // an admin has no reason to connect to the Refund button they pressed.
463
- const stripeCode = String((_ref2 = refund == null ? void 0 : (_refund_error = refund.error) == null ? void 0 : _refund_error.code) != null ? _ref2 : '');
464
- if (stripeCode === 'charge_disputed' || stripeCode === 'refund_disputed_payment') {
465
- return res.status(409).json({
466
- error: 'Stripe refused this refund because the charge is disputed. ' + 'Respond to the dispute or accept it in the Stripe dashboard; ' + 'refund any remainder once it settles.'
467
- });
468
- }
469
- return res.status(502).json({
470
- error: (_ref3 = refund == null ? void 0 : (_refund_error1 = refund.error) == null ? void 0 : _refund_error1.message) != null ? _ref3 : 'Refund failed'
499
+ // answer, same accuracy: a 409 naming the dispute (`createStripeRefund`
500
+ // words it), not a 502 reading "The charge you're attempting to refund
501
+ // has been charged back", which an admin has no reason to connect to
502
+ // the Refund button they pressed.
503
+ return res.status(refund.status === 409 ? 409 : 502).json({
504
+ error: refund.error
471
505
  });
472
506
  }
473
- // SETTLE. Re-read inside the transaction: a concurrent partial may have
474
- // reserved against the same order, and the timeline must be appended to
475
- // whatever is there now rather than to the snapshot read at the top.
476
507
  let refundedCents = 0;
477
508
  let fullyRefunded = false;
478
509
  let closedTheOrder = false;
@@ -491,6 +522,13 @@ import { reverseOrderConversion } from "@aglyn/aglyn/plugin-manager/plugin-conve
491
522
  closedTheOrder = fullyRefunded && fresh.status !== 'refunded';
492
523
  transaction.set(orderRef, _extends({}, fullyRefunded ? {
493
524
  status: 'refunded'
525
+ } : {}, {
526
+ // What a shipping tool's feed asks to learn of it (AGL-3613).
527
+ updatedAtMs: Date.now()
528
+ }, splitCards.length > 1 ? {
529
+ paymentRefunds: {
530
+ [String(paymentIntentId)]: firebaseAdmin.firestore.FieldValue.increment(refundCents)
531
+ }
494
532
  } : {}, requestedLineIds.length > 0 ? {
495
533
  refundedLineItemIds: firebaseAdmin.firestore.FieldValue.arrayUnion(...requestedLineIds)
496
534
  } : {}, {
@@ -614,6 +652,33 @@ import { reverseOrderConversion } from "@aglyn/aglyn/plugin-manager/plugin-conve
614
652
  kind: 'refund',
615
653
  closedTheOrder
616
654
  });
655
+ // The buyer is told what came back (AGL-3610), once per Stripe refund id —
656
+ // a keyed retry replays at the claim above and never reaches here.
657
+ await notifyOrderBuyer({
658
+ hostId,
659
+ orderId
660
+ }, 'refunded', {
661
+ refundId: refund.refundId,
662
+ refundCents,
663
+ refundLineIndexes: requestedLineIds,
664
+ fullyRefunded
665
+ });
666
+ // Other plugins and the merchant's webhooks hear it too (AGL-3611), once per refund.
667
+ await raiseOrderEvent(ORDER_REFUNDED_EVENT, {
668
+ hostId,
669
+ orderId,
670
+ key: `refund:${refund.refundId || idempotencyKey}`,
671
+ extra: {
672
+ refund: {
673
+ id: refund.refundId || null,
674
+ amountCents: refundCents,
675
+ lineItemIds: [
676
+ ...requestedLineIds != null ? requestedLineIds : []
677
+ ],
678
+ full: Boolean(fullyRefunded)
679
+ }
680
+ }
681
+ });
617
682
  return res.status(200).json(payload);
618
683
  } catch (error) {
619
684
  console.error(error);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/refund.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport { createHash } from 'crypto'\nimport { recordPluginPersonRefund } from '@aglyn/aglyn/plugin-manager/plugin-person-records'\nimport { applyGiftCardRiskToOrder } from './gift-card-risk'\nimport { flagOrderRestock } from './restock-flag'\nimport { reverseOrderConversion } from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\n\n/**\n * A claim on one refund attempt (AGL-1696), the same primitive the POS sale\n * path uses (AGL-1691, `cab8aa36e`).\n */\ninterface RefundClaim {\n /** Stripe idempotency key for this attempt, or null when no key was sent. */\n stripeKey: string | null\n record: (status: number, body: unknown) => Promise<void>\n release: () => Promise<void>\n}\n\n/**\n * Retires the licence keys a refund withdrew (AGL-2454).\n *\n * Reads the order back so the decision is made from what actually SETTLED\n * rather than from what this request asked for — a concurrent partial may have\n * closed a line between the two — and retires only the keys of products the\n * order no longer entitles at all. `refundedProductIds` is deliberately strict\n * about that: a buyer who returned one of two copies still holds the product,\n * so nothing is retired for them.\n *\n * `revokedAtMs` with `assignedAtMs` left standing is the retired state. Keeping\n * `assignedAtMs` matters: `assignLicenseKeys` claims from\n * `where('assignedAtMs','==',null)`, so clearing it would put the key straight\n * back in front of the next buyer — the reissue this must not do.\n *\n * Swallows everything. The refund has already moved money.\n */\nasync function retireLicenseKeys(\n hostRef: FirebaseFirestore.DocumentReference,\n orderRef: FirebaseFirestore.DocumentReference,\n orderId: string,\n): Promise<number> {\n try {\n const fresh = CommerceModel.liftLegacyOrder(\n ((await orderRef.get()).data() ?? {}) as any,\n )\n const withdrawn = new Set(CommerceModel.refundedProductIds(fresh))\n if (withdrawn.size === 0) return 0\n const assigned = await hostRef\n .collection('licenseKeys')\n .where('orderId', '==', orderId)\n .limit(500)\n .get()\n let retired = 0\n for (const keySnapshot of assigned.docs) {\n if (!withdrawn.has(String(keySnapshot.get('productId') ?? ''))) continue\n // Already retired by an earlier partial, or by the merchant's own Revoke\n // button. Skipped so a second refund does not restamp the timestamp and\n // make the retirement look newer than it is.\n if (keySnapshot.get('revokedAtMs') != null) continue\n await keySnapshot.ref\n .set({ revokedAtMs: Date.now(), revokedOrderId: orderId }, { merge: true })\n .catch(() => undefined)\n retired++\n }\n if (retired > 0) {\n await orderRef\n .update({\n timeline: firebaseAdmin.firestore.FieldValue.arrayUnion({\n atMs: Date.now(),\n event: 'license-retired',\n detail:\n `${retired} license key${retired === 1 ? '' : 's'} retired. ` +\n 'The buyer already holds the key string, so it is not returned ' +\n 'to the pool — reissuing it would give two people one secret.',\n }),\n })\n .catch(() => undefined)\n }\n return retired\n } catch (error) {\n console.error('License key retirement failed', orderId, error)\n return 0\n }\n}\n\n/**\n * Order refunds (AGL-287): full or partial via Stripe, site-admin only\n * (it moves money). Destination charges reverse the transfer and the\n * platform fee proportionally. Full refunds transition the order to\n * `refunded`; partial refunds accumulate `refundedCents` and stay in\n * the current status.\n *\n * Two SEPARATE controls guard the money (AGL-1696), and conflating them is\n * how the original went wrong:\n *\n * - The idempotency key stops a DUPLICATE refund — one attempt sent twice\n * because the response was lost, the admin double-clicked, or a client\n * retried. It is minted per attempt by the console and deliberately not\n * derived from the order or the amount: two $10 refunds on a $50 order are\n * two real refunds, exactly as a cashier ringing the same coffee twice is a\n * real second sale.\n * - The cap stops an OVER-refund — several partials summing past what was\n * captured, including two admins refunding at once, where the two attempts\n * are genuinely distinct and no key can help. That needs the counter read\n * and written inside one transaction.\n *\n * The original had a cap that looked like both and was neither: it read\n * `refundedCents` and wrote it back only AFTER the Stripe call, outside any\n * transaction. A guard that reads state the guarded operation writes too late\n * is not a guard — measured, two concurrent refunds each sent a full $50 to\n * Stripe with no idempotency header on either.\n */\nexport const refundHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({ error: 'Payments are not configured.' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const orderId = String(body.orderId ?? '')\n const amountCents = body.amountCents == null ? null : Number(body.amountCents)\n /**\n * Lines the admin is refunding BY NAME (AGL-2454), and therefore the lines\n * whose digital entitlements come back. Optional: an amount-only refund is\n * still a legal refund and still revokes nothing per-line — see the guard\n * below for why that is a decision rather than an oversight.\n */\n const requestedLineIds: number[] = Array.isArray(body.lineItemIds)\n ? [\n ...new Set(\n (body.lineItemIds as unknown[])\n .map((value) => Math.round(Number(value)))\n .filter((value) => Number.isFinite(value) && value >= 0),\n ),\n ].sort((a, b) => a - b)\n : []\n // One refund attempt, minted by the console. Node lowercases incoming\n // headers, but read both spellings — the plugin API request type makes no\n // promise about casing.\n const idempotencyKey = String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n )\n .trim()\n .slice(0, 200)\n if (!hostId || !orderId) {\n return res.status(400).json({ error: 'Missing hostId or orderId' })\n }\n\n let claim: RefundClaim | null = null\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // TWO CHECKS, and they answer different questions (AGL-2372).\n //\n // The first is the HOST-level fact the Firestore rules also enforce, and\n // it stays: `memberRoles` is the projection the rules read, so dropping it\n // here would let this route and the database disagree.\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (memberRole !== 'admin') {\n return res.status(403).json({ error: 'Refunds require a site admin' })\n }\n // The second is WHOSE admin, and it is the one this gate was missing.\n //\n // `memberRoles` is a per-host projection of `hostAccess`, and\n // `/api/hosts/members` will grant a SITE COLLABORATOR `admin` on one site\n // (`hostAccess: { [hostId]: 'admin' }`, `allHosts: false`). That writes the\n // literal string `'admin'` into `memberRoles[uid]` — byte-identical to an\n // org owner's. So the check above cannot tell a contractor invited to run\n // one microsite from the person who owns the business, and refunding is\n // money leaving that business.\n //\n // `orgWide` is the discriminator, and it needs no new role: it is\n // `isOrgWideMember` (AGL-1026) — owner/admin of the org, an explicit\n // `allHosts` member, or the legacy pre-`allHosts` shape — and it is false\n // for every scoped collaborator. Same pairing `pos-order.ts` uses.\n //\n // BOTH halves are required. `hostRole` is re-tested rather than assumed\n // from `memberRole`: an org-wide member can still be scoped down to\n // `editor` on this host, and `resolveOrgPermissions` is the resolver that\n // knows it. It fails CLOSED on a lookup error when a host is named\n // (AGL-506), and `denied()` returns `orgWide: false` / `hostRole: null`,\n // so an absent membership refuses rather than folding to permitted.\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.orgWide || membership.hostRole !== 'admin') {\n return res\n .status(403)\n .json({ error: 'Refunds require an admin of the whole workspace' })\n }\n const orderRef = hostRef.collection('orders').doc(orderId)\n const orderSnapshot = await orderRef.get()\n if (!orderSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown order' })\n }\n const order = CommerceModel.liftLegacyOrder(orderSnapshot.data() as any)\n\n // Replay a settled attempt before anything else can reject it. This read\n // is only a short-circuit, never the dedupe primitive — the atomic\n // `create()` below is. It has to run ahead of the status guard because a\n // retried FULL refund would otherwise be answered \"orders in refunded\n // cannot refund\", which is the right money outcome reported as a failure,\n // and an admin who reads it as a failure refunds again by hand.\n const claimRef = idempotencyKey\n ? firestore\n .collection('apiIdempotency')\n .doc(\n createHash('sha256')\n // Scoped by the order, so a client that reused one key across\n // two orders cannot dedupe two legitimately distinct refunds.\n // NOT by the amount: that would swallow a real second partial.\n .update(`refund:${hostId}:${orderId}:${idempotencyKey}`)\n .digest('hex'),\n )\n : null\n if (claimRef) {\n const prior = await claimRef.get()\n const priorResponse = prior.get('response')\n if (priorResponse) {\n return res\n .status(Number(prior.get('responseStatus') ?? 200))\n .json(priorResponse)\n }\n }\n\n if (!CommerceModel.canTransitionOrder(order.status, 'refunded')) {\n return res\n .status(409)\n .json({ error: `Orders in \"${order.status}\" cannot refund` })\n }\n // A refund does not withdraw a dispute (AGL-1809). While a chargeback is\n // formally open the bank has already pulled the disputed funds, Stripe's\n // refund API refuses the charge (`charge_disputed`), and a refund that did\n // go through would pay the shopper twice — the merchant loses the refund\n // AND the dispute plus its fee. Refused HERE, before the claim and the\n // reservation, so a refusal burns no idempotency key and strands nothing:\n // no state has been written yet (AGL-1754's contract). An open INQUIRY\n // (`warning_*`) deliberately passes — no funds have moved and Stripe names\n // a full refund as the way to resolve one before it escalates — and the\n // status guard above already turns away a LOST dispute, which parked the\n // order in `refunded`. This reads the pre-transaction snapshot; a dispute\n // webhook racing this exact request is caught by the `charge_disputed`\n // mapping on the Stripe response below.\n if (CommerceModel.orderDisputeBlocksRefund(order)) {\n return res.status(409).json({\n error:\n 'A chargeback is open on this order, so it was not refunded. ' +\n 'Refunding would not withdraw the dispute — the bank has already ' +\n 'taken the disputed amount, and a refund on top of it would pay ' +\n 'the shopper twice. Respond to the dispute or accept it in the ' +\n 'Stripe dashboard; refund any remainder once it settles.',\n })\n }\n // WHAT THE NAMED LINES ARE WORTH, AND WHY THE AMOUNT MAY NOT BE LESS\n // (AGL-2454).\n //\n // A refund carries an amount, not lines — that is the blocker this issue\n // names, and `restock-flag.ts:48-55` already records it for stock. It\n // cannot be solved by inference: deciding for the merchant which lines a\n // bare figure covers would be a guess about their goods. It CAN be solved\n // by asking, which is what naming lines does, and the amount is then\n // derived from them rather than typed beside them.\n //\n // An explicit `amountCents` may still be LARGER (the admin is refunding the\n // line plus its share of tax or shipping, which this items-only sum does\n // not include). It may not be SMALLER: revoking a line the refund did not\n // actually cover is the silent over-revocation this issue forbids in the\n // same breath as silent under-revocation.\n const orderLines = order.lineItems ?? []\n const invalidLine = requestedLineIds.find(\n (index) => index >= orderLines.length,\n )\n if (invalidLine != null) {\n return res\n .status(400)\n .json({ error: `Line ${invalidLine} is not on this order` })\n }\n // NET OF THE ORDER'S DISCOUNT, not the list price.\n //\n // This was the bare `unitAmountCents x quantity`, which is what the line\n // was LISTED at rather than what the buyer paid for it. On a discounted\n // order the two differ, and both directions of the error land on the\n // merchant: a $10 coupon over two $50 lines means each line cost $45, so\n // refunding one at $50 gave back $5 that was never taken, and the order\n // then held less than its remaining line was worth — so the second line\n // refund hit the cap below and was refused outright, leaving the merchant\n // unable to finish a refund they had already half-issued.\n //\n // `orderLineRefundCents` apportions the discount across every line by list\n // value and returns the named lines' share, so refunding all of them sums\n // to exactly what was charged and no cent is stranded or invented.\n const namedLinesCents = CommerceModel.orderLineRefundCents(\n order,\n requestedLineIds,\n )\n if (\n requestedLineIds.length > 0 &&\n amountCents != null &&\n Math.round(amountCents) < namedLinesCents\n ) {\n return res.status(400).json({\n error:\n 'That amount is less than the lines you selected are worth. ' +\n 'Refund the full value of those lines, or refund an amount ' +\n 'without selecting lines.',\n })\n }\n const paymentIntentId =\n order.paymentIntentId ??\n // Legacy rows stored the checkout session as the doc id; resolve\n // the payment intent from Stripe.\n (await (async () => {\n const response = await fetch(\n `https://api.stripe.com/v1/checkout/sessions/${orderId}`,\n {\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n },\n },\n )\n const session = await response.json()\n return response.ok ? session?.payment_intent : null\n })())\n if (!paymentIntentId) {\n return res.status(409).json({ error: 'No payment to refund' })\n }\n\n // Point of no return: everything past here moves money. The claim is\n // `create()` — Firestore rejects a create on an existing document, and\n // that rejection IS the dedupe primitive. A read-then-write would race\n // exactly the double-submit it exists to stop. Storage reuses the REST\n // API's shape and its `orgId` field (AGL-618) rather than inventing a\n // second replay store, so `eraseOrgIdempotencyKeys` (AGL-1448) already\n // sweeps these on org erasure with no change there.\n if (claimRef) {\n const ownerOrg = await getOrgForHost(hostId)\n try {\n await claimRef.create({\n orgId: String(ownerOrg?.org?.id ?? '') || null,\n hostId,\n orderId,\n kind: 'commerce-refund',\n status: 'pending',\n createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n createdAtMs: Date.now(),\n // The second writer into `apiIdempotency` (AGL-1978). The shared\n // `claimAttempt` stamps this too; this local copy has to as well,\n // or refund claims are the one shape the TTL policy silently never\n // reaches — a policy that governs most of a collection reads, from\n // the outside, exactly like one that governs all of it.\n expiresAt: Aglyn.apiIdempotencyExpiry(),\n })\n } catch {\n const prior = await claimRef.get()\n const priorResponse = prior.get('response')\n if (priorResponse) {\n return res\n .status(Number(prior.get('responseStatus') ?? 200))\n .json(priorResponse)\n }\n // In flight, or stranded by a process that died mid-refund. Fail\n // CLOSED: the alternative is sending the money a second time.\n return res\n .status(409)\n .json({ error: 'This refund is already being processed' })\n }\n claim = {\n // The same digest goes to Stripe. That is the half that costs real\n // money: it covers the window where our claim is written but the\n // response never arrives, and makes Stripe replay its own refund\n // instead of moving the funds again.\n stripeKey: claimRef.id,\n record: async (status, payload) => {\n await claimRef\n .set(\n {\n status: 'done',\n responseStatus: status,\n response: payload,\n settledAtMs: Date.now(),\n },\n { merge: true },\n )\n .catch(() => undefined)\n },\n release: async () => {\n await claimRef.delete().catch(() => undefined)\n },\n }\n }\n\n // RESERVE. The cap is read and written in one transaction, so two\n // concurrent refunds cannot both see the same `refundedCents` — which is\n // the whole failure the old ordering had, since it wrote the counter only\n // after Stripe had already been asked to move the money. Reserving BEFORE\n // the call rather than after also fails in the safe direction: a lost\n // response leaves the amount counted, so the retry refunds less, never\n // more.\n let refundCents = 0\n let totalCents = 0\n await firestore.runTransaction(async (transaction) => {\n const fresh = CommerceModel.liftLegacyOrder(\n ((await transaction.get(orderRef)).data() ?? {}) as any,\n )\n totalCents = fresh.totals?.totalCents ?? Number(fresh.amountCents ?? 0)\n const alreadyRefunded = Number(fresh.refundedCents ?? 0)\n const remaining = totalCents - alreadyRefunded\n // Named lines with no amount refund exactly what those lines are worth;\n // named lines WITH an amount use the amount (already guarded above as\n // no smaller than the lines). Neither is the whole order, which is what\n // `amountCents == null` alone still means.\n const asked =\n amountCents != null\n ? Math.round(amountCents)\n : requestedLineIds.length > 0\n ? namedLinesCents\n : remaining\n refundCents = Math.min(asked, remaining)\n if (!(refundCents > 0)) {\n refundCents = 0\n return\n }\n transaction.set(\n orderRef,\n { refundedCents: alreadyRefunded + refundCents },\n { merge: true },\n )\n })\n if (!(refundCents > 0)) {\n // Nothing moved, so the attempt key is released rather than burned.\n await claim?.release()\n return res.status(400).json({ error: 'Nothing left to refund' })\n }\n // The cap bit into the named lines (AGL-2454): earlier partials have left\n // less on this order than the selected lines are worth. REFUSED rather\n // than refunded-and-revoked, because revoking a line for less than its\n // value is precisely the silent over-revocation this issue forbids. The\n // reservation is given back — the same compensation a Stripe refusal does\n // below, and for the same reason: nothing has left the account yet.\n if (requestedLineIds.length > 0 && refundCents < namedLinesCents) {\n await firestore\n .runTransaction(async (transaction) => {\n const current = Number(\n (await transaction.get(orderRef)).get('refundedCents') ?? 0,\n )\n transaction.set(\n orderRef,\n { refundedCents: Math.max(0, current - refundCents) },\n { merge: true },\n )\n })\n .catch(() => undefined)\n await claim?.release()\n return res.status(409).json({\n error:\n `Only $${(refundCents / 100).toFixed(2)} is left to refund on this ` +\n `order, and the lines you selected are worth $${(\n namedLinesCents / 100\n ).toFixed(2)}. Refund an amount without selecting lines instead.`,\n })\n }\n\n const params = new URLSearchParams({\n payment_intent: String(paymentIntentId),\n amount: String(refundCents),\n reverse_transfer: 'true',\n refund_application_fee: 'true',\n })\n const response = await fetch('https://api.stripe.com/v1/refunds', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...(claim?.stripeKey\n ? { 'Idempotency-Key': claim.stripeKey }\n : {}),\n },\n body: params.toString(),\n })\n const refund = await response.json()\n if (!response.ok) {\n console.error('Stripe refund error', refund?.error)\n // Stripe said no, so we KNOW no money moved: give the reservation back\n // and let the same attempt be tried again.\n await firestore\n .runTransaction(async (transaction) => {\n const current = Number(\n (await transaction.get(orderRef)).get('refundedCents') ?? 0,\n )\n transaction.set(\n orderRef,\n { refundedCents: Math.max(0, current - refundCents) },\n { merge: true },\n )\n })\n .catch(() => undefined)\n await claim?.release()\n // Stripe refusing BECAUSE OF A DISPUTE is the guard above arriving by\n // the other door — our order document simply didn't know yet (webhook\n // lag, or an order from before disputes were subscribed at all). Same\n // answer, same accuracy: a 409 naming the dispute, not a 502 reading\n // \"The charge you're attempting to refund has been charged back\", which\n // an admin has no reason to connect to the Refund button they pressed.\n const stripeCode = String(refund?.error?.code ?? '')\n if (\n stripeCode === 'charge_disputed' ||\n stripeCode === 'refund_disputed_payment'\n ) {\n return res.status(409).json({\n error:\n 'Stripe refused this refund because the charge is disputed. ' +\n 'Respond to the dispute or accept it in the Stripe dashboard; ' +\n 'refund any remainder once it settles.',\n })\n }\n return res\n .status(502)\n .json({ error: refund?.error?.message ?? 'Refund failed' })\n }\n\n // SETTLE. Re-read inside the transaction: a concurrent partial may have\n // reserved against the same order, and the timeline must be appended to\n // whatever is there now rather than to the snapshot read at the top.\n let refundedCents = 0\n let fullyRefunded = false\n let closedTheOrder = false\n await firestore.runTransaction(async (transaction) => {\n const fresh = CommerceModel.liftLegacyOrder(\n ((await transaction.get(orderRef)).data() ?? {}) as any,\n )\n refundedCents = Number(fresh.refundedCents ?? 0)\n fullyRefunded = refundedCents >= totalCents\n // Whether THIS settle moved the order into `refunded`, which is not the\n // same question as whether the order is now fully refunded (AGL-1754).\n // Two partials that between them close an order can both reserve before\n // either settles, so both re-read the completed total and both compute\n // `fullyRefunded`. Writing `status: 'refunded'` twice is harmless;\n // incrementing a count twice is not. Reading the status inside the same\n // transaction that writes it makes the flip observable exactly once.\n closedTheOrder = fullyRefunded && fresh.status !== 'refunded'\n transaction.set(\n orderRef,\n {\n ...(fullyRefunded ? { status: 'refunded' } : {}),\n // The entitlement withdrawal, recorded WITH the money (AGL-2454).\n // `arrayUnion` rather than a written-back array: two admins refunding\n // different lines at once must not erase each other's, and this\n // transaction re-reads the order but a written array would still lose\n // a concurrent settle that committed between the two.\n ...(requestedLineIds.length > 0\n ? {\n refundedLineItemIds:\n firebaseAdmin.firestore.FieldValue.arrayUnion(\n ...requestedLineIds,\n ),\n }\n : {}),\n timeline: CommerceModel.appendOrderEvent(\n fresh,\n 'refund',\n `$${(refundCents / 100).toFixed(2)} refunded` +\n (fullyRefunded\n ? ' (full)'\n : requestedLineIds.length > 0\n ? ` — ${requestedLineIds.length} line${\n requestedLineIds.length === 1 ? '' : 's'\n } withdrawn`\n : ' — refunded by amount, no lines withdrawn'),\n ),\n },\n { merge: true },\n )\n })\n const payload = { refundedCents, fullyRefunded }\n await claim?.record(200, payload)\n // LICENCE KEYS ARE RETIRED, NEVER RETURNED TO THE POOL (AGL-2454).\n //\n // `assignLicenseKeys` stamps `assignedAtMs`, `orderId` and `email` onto a\n // pool document and nothing anywhere ever set them back — so a refunded\n // order consumed the merchant's key forever, and a merchant who sold one\n // key out of a hundred and refunded it had ninety-nine, permanently.\n //\n // Returning it to the pool is NOT the fix, and this is the decision the\n // issue asked for: the key string was mailed in the receipt and cannot be\n // invalidated by anything we own, so re-issuing it to the next paying\n // customer would hand two people one working secret. That is worse than\n // losing the key. A third state — retired: neither assigned to a live order\n // nor available — is the honest record, and `revokedAtMs` already IS that\n // state: the console's key dialog has written exactly this pair since it\n // shipped, so this reuses the merchant's own vocabulary rather than\n // inventing a second one.\n //\n // Best-effort and after the response is recorded, matching the contact and\n // restock ledgers below: the money has moved and nothing here may fail a\n // refund that already left the merchant's account.\n await retireLicenseKeys(hostRef, orderRef, orderId)\n // GIFT CARDS THE REFUND TOOK BACK ARE VOIDED (AGL-3363). The money went\n // back to the card that paid, so what is left on the cards that money\n // bought goes too — every card on a full refund, and on a partial one\n // only the cards bought by the lines it withdrew. A refund by amount with\n // no lines named withdraws nothing, so it voids nothing. Same best-effort\n // placement as the key retirement above: the refund has already moved.\n if (fullyRefunded || requestedLineIds.length > 0) {\n await applyGiftCardRiskToOrder({\n firestore,\n hostRef,\n orderId,\n action: {\n kind: 'void',\n reason: 'refund',\n ...(fullyRefunded\n ? {}\n : {\n productIds: requestedLineIds\n .map((index) => String(order.lineItems?.[index]?.productId ?? ''))\n .filter(Boolean),\n }),\n },\n })\n }\n // The customer's side of the ledger (AGL-1754). Everything above records\n // the money on the ORDER; without this the buyer's `ltvCents` still counts\n // a sale they returned, and only ever rises.\n //\n // Placed AFTER the attempt is recorded so a slow contacts write cannot\n // strand the claim: a retry that arrives while this is in flight replays\n // the recorded 200 instead of being turned away with \"already being\n // processed\". Awaited rather than fired off with `void` — the handler is\n // serverless, and work left running past the response is work the\n // container may be frozen before it finishes. The seam never throws, so\n // awaiting adds no way for this to fail a refund that has already left\n // the merchant's account.\n //\n // Through the plugin that keeps people (AGL-3080): what a refund does to\n // the customer's record is that plugin's to decide, and commerce writes\n // none of it.\n //\n // Amount is THIS attempt's `refundCents`, already capped against what was\n // left, so several partials sum to at most the order total — the same\n // number the order's own `refundedCents` follows. The retried and racing\n // cases need no key of their own: a keyed retry never reaches here (it\n // replays at the claim), and a keyless one is a genuinely new refund that\n // moved more money and should be counted.\n await recordPluginPersonRefund({\n hostId,\n refId: orderId,\n email: order.customerEmail,\n amountCents: refundCents,\n closedTheSale: closedTheOrder,\n })\n /*\n * The campaign's side of the same ledger.\n *\n * If a campaign was credited with this order, that credit is now partly\n * or wholly wrong — a campaign cannot go on being paid for a sale the\n * merchant reversed, and revenue attribution that only ever rises is the\n * flattering half of a measurement. Recorded beside the gross rather than\n * subtracted from it, for the reason the customer's record keeps its\n * refunds beside what they spent.\n *\n * Keyed by the ORDER and not by the buyer, so it needs no email and works\n * for a guest checkout: the attribution record holds which campaign and\n * which currency, and this reads them back. Same placement, same\n * swallow-all contract and same awaited call as the two ledgers around\n * it — nothing here may fail a refund that has already left the\n * merchant's account.\n */\n await reverseOrderConversion({\n hostId,\n orderId,\n amountCents: refundCents,\n closedTheOrder,\n })\n // The shelf's side of the ledger (AGL-1797). The sale decremented variant\n // inventory and nothing put it back, so a fully refunded order read one\n // unit light forever. This FLAGS rather than releases — a refund with no\n // return leaves the goods gone, and inventing stock the merchant does not\n // have is worse than under-counting it — and the merchant answers from the\n // stock adjustment they already have. Same placement and same swallow-all\n // contract as the contact write above, for the same reason: the money has\n // moved and the order records it, so nothing here may fail the refund.\n await flagOrderRestock({ hostId, orderId, kind: 'refund', closedTheOrder })\n return res.status(200).json(payload)\n } catch (error) {\n console.error(error)\n // Deliberately NOT released, which is where this diverges from the POS\n // sale path (AGL-1691). If the refund call threw we do not know whether\n // Stripe moved the money, and the two failure directions are not\n // symmetric: a stranded key costs a support ticket, a released one costs a\n // second refund. The retry gets a 409 and a human reconciles.\n return res.status(500).json({ error: 'Refund failed' })\n }\n}\n"],"names":["Aglyn","CommerceModel","firebaseAdmin","getOrgForHost","resolveOrgPermissions","createHash","recordPluginPersonRefund","applyGiftCardRiskToOrder","flagOrderRestock","reverseOrderConversion","retireLicenseKeys","hostRef","orderRef","orderId","fresh","liftLegacyOrder","get","data","withdrawn","Set","refundedProductIds","size","assigned","collection","where","limit","retired","keySnapshot","docs","has","String","ref","set","revokedAtMs","Date","now","revokedOrderId","merge","catch","undefined","update","timeline","firestore","FieldValue","arrayUnion","atMs","event","detail","error","console","refundHandler","req","res","body","method","status","json","process","env","STRIPE_SECRET_KEY","authorization","headers","idToken","startsWith","slice","length","JSON","parse","hostId","amountCents","Number","requestedLineIds","Array","isArray","lineItemIds","map","value","Math","round","filter","isFinite","sort","a","b","idempotencyKey","trim","claim","hostSnapshot","order","decoded","app","auth","verifyIdToken","doc","exists","memberRole","uid","membership","orgWide","hostRole","orderSnapshot","claimRef","digest","prior","priorResponse","canTransitionOrder","orderDisputeBlocksRefund","orderLines","lineItems","invalidLine","find","index","namedLinesCents","orderLineRefundCents","paymentIntentId","response","fetch","Authorization","session","ok","payment_intent","ownerOrg","create","orgId","org","id","kind","createdAt","serverTimestamp","createdAtMs","expiresAt","apiIdempotencyExpiry","stripeKey","record","payload","responseStatus","settledAtMs","release","delete","refundCents","totalCents","runTransaction","transaction","totals","alreadyRefunded","refundedCents","remaining","asked","min","current","max","toFixed","params","URLSearchParams","amount","reverse_transfer","refund_application_fee","toString","refund","stripeCode","code","message","fullyRefunded","closedTheOrder","refundedLineItemIds","appendOrderEvent","action","reason","productIds","productId","Boolean","refId","email","customerEmail","closedTheSale"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,sBAAqB;AAC5C,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AAEvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,UAAU,QAAQ,SAAQ;AACnC,SAASC,wBAAwB,QAAQ,oDAAmD;AAC5F,SAASC,wBAAwB,QAAQ,sBAAkB;AAC3D,SAASC,gBAAgB,QAAQ,oBAAgB;AACjD,SAASC,sBAAsB,QAAQ,uDAAsD;AAa7F;;;;;;;;;;;;;;;;CAgBC,GACD,eAAeC,kBACbC,OAA4C,EAC5CC,QAA6C,EAC7CC,OAAe;IAEf,IAAI;YAEC;QADH,MAAMC,QAAQb,cAAcc,eAAe,EACxC,QAAA,AAAC,CAAA,MAAMH,SAASI,GAAG,EAAC,EAAGC,IAAI,cAA3B,QAAiC,CAAC;QAErC,MAAMC,YAAY,IAAIC,IAAIlB,cAAcmB,kBAAkB,CAACN;QAC3D,IAAII,UAAUG,IAAI,KAAK,GAAG,OAAO;QACjC,MAAMC,WAAW,MAAMX,QACpBY,UAAU,CAAC,eACXC,KAAK,CAAC,WAAW,MAAMX,SACvBY,KAAK,CAAC,KACNT,GAAG;QACN,IAAIU,UAAU;QACd,KAAK,MAAMC,eAAeL,SAASM,IAAI,CAAE;gBACbD;YAA1B,IAAI,CAACT,UAAUW,GAAG,CAACC,QAAOH,mBAAAA,YAAYX,GAAG,CAAC,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QAC1E,wEAAwE;QACxE,yEAAyE;QACzE,0EAA0E;QAC1E,2EAA2E;QAC3E,0EAA0E;QAC1E,0EAA0E;QAC1E,uEAAuE;QACvE,MAAM3J,iBAAiB;YAAE4D;YAAQvD;YAASiH,MAAM;YAAUqC;QAAe;QACzE,OAAO/G,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC8E;IAC9B,EAAE,OAAOtF,OAAO;QACdC,QAAQD,KAAK,CAACA;QACd,uEAAuE;QACvE,wEAAwE;QACxE,iEAAiE;QACjE,2EAA2E;QAC3E,8DAA8D;QAC9D,OAAOI,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAER,OAAO;QAAgB;IACvD;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/refund.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport { createHash } from 'crypto'\nimport { recordPluginPersonRefund } from '@aglyn/aglyn/plugin-manager/plugin-person-records'\nimport { applyGiftCardRiskToOrder } from './gift-card-risk'\nimport { flagOrderRestock } from './restock-flag'\nimport { notifyOrderBuyer } from './order-notifications'\nimport { ORDER_REFUNDED_EVENT } from '../model/order-events'\nimport { raiseOrderEvent } from './order-events'\nimport { reverseOrderConversion } from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport { createStripeRefund } from './stripe-refund'\nimport { posRegisterRefundAuthority } from './pos-refund-authority'\n\n/**\n * A claim on one refund attempt (AGL-1696), the same primitive the POS sale\n * path uses (AGL-1691, `cab8aa36e`).\n */\ninterface RefundClaim {\n /** Stripe idempotency key for this attempt, or null when no key was sent. */\n stripeKey: string | null\n record: (status: number, body: unknown) => Promise<void>\n release: () => Promise<void>\n}\n\n/**\n * Retires the licence keys a refund withdrew (AGL-2454).\n *\n * Reads the order back so the decision is made from what actually SETTLED\n * rather than from what this request asked for — a concurrent partial may have\n * closed a line between the two — and retires only the keys of products the\n * order no longer entitles at all. `refundedProductIds` is deliberately strict\n * about that: a buyer who returned one of two copies still holds the product,\n * so nothing is retired for them.\n *\n * `revokedAtMs` with `assignedAtMs` left standing is the retired state. Keeping\n * `assignedAtMs` matters: `assignLicenseKeys` claims from\n * `where('assignedAtMs','==',null)`, so clearing it would put the key straight\n * back in front of the next buyer — the reissue this must not do.\n *\n * Swallows everything. The refund has already moved money.\n */\nasync function retireLicenseKeys(\n hostRef: FirebaseFirestore.DocumentReference,\n orderRef: FirebaseFirestore.DocumentReference,\n orderId: string,\n): Promise<number> {\n try {\n const fresh = CommerceModel.liftLegacyOrder(\n ((await orderRef.get()).data() ?? {}) as any,\n )\n const withdrawn = new Set(CommerceModel.refundedProductIds(fresh))\n if (withdrawn.size === 0) return 0\n const assigned = await hostRef\n .collection('licenseKeys')\n .where('orderId', '==', orderId)\n .limit(500)\n .get()\n let retired = 0\n for (const keySnapshot of assigned.docs) {\n if (!withdrawn.has(String(keySnapshot.get('productId') ?? ''))) continue\n // Already retired by an earlier partial, or by the merchant's own Revoke\n // button. Skipped so a second refund does not restamp the timestamp and\n // make the retirement look newer than it is.\n if (keySnapshot.get('revokedAtMs') != null) continue\n await keySnapshot.ref\n .set({ revokedAtMs: Date.now(), revokedOrderId: orderId }, { merge: true })\n .catch(() => undefined)\n retired++\n }\n if (retired > 0) {\n await orderRef\n .update({\n timeline: firebaseAdmin.firestore.FieldValue.arrayUnion({\n atMs: Date.now(),\n event: 'license-retired',\n detail:\n `${retired} license key${retired === 1 ? '' : 's'} retired. ` +\n 'The buyer already holds the key string, so it is not returned ' +\n 'to the pool — reissuing it would give two people one secret.',\n }),\n })\n .catch(() => undefined)\n }\n return retired\n } catch (error) {\n console.error('License key retirement failed', orderId, error)\n return 0\n }\n}\n\n/**\n * Order refunds (AGL-287): full or partial via Stripe, site-admin only\n * (it moves money). Destination charges reverse the transfer and the\n * platform fee proportionally. Full refunds transition the order to\n * `refunded`; partial refunds accumulate `refundedCents` and stay in\n * the current status.\n *\n * Two SEPARATE controls guard the money (AGL-1696), and conflating them is\n * how the original went wrong:\n *\n * - The idempotency key stops a DUPLICATE refund — one attempt sent twice\n * because the response was lost, the admin double-clicked, or a client\n * retried. It is minted per attempt by the console and deliberately not\n * derived from the order or the amount: two $10 refunds on a $50 order are\n * two real refunds, exactly as a cashier ringing the same coffee twice is a\n * real second sale.\n * - The cap stops an OVER-refund — several partials summing past what was\n * captured, including two admins refunding at once, where the two attempts\n * are genuinely distinct and no key can help. That needs the counter read\n * and written inside one transaction.\n *\n * The original had a cap that looked like both and was neither: it read\n * `refundedCents` and wrote it back only AFTER the Stripe call, outside any\n * transaction. A guard that reads state the guarded operation writes too late\n * is not a guard — measured, two concurrent refunds each sent a full $50 to\n * Stripe with no idempotency header on either.\n */\nexport const refundHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({ error: 'Payments are not configured.' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const orderId = String(body.orderId ?? '')\n const amountCents = body.amountCents == null ? null : Number(body.amountCents)\n /**\n * Lines the admin is refunding BY NAME (AGL-2454), and therefore the lines\n * whose digital entitlements come back. Optional: an amount-only refund is\n * still a legal refund and still revokes nothing per-line — see the guard\n * below for why that is a decision rather than an oversight.\n */\n const requestedLineIds: number[] = Array.isArray(body.lineItemIds)\n ? [\n ...new Set(\n (body.lineItemIds as unknown[])\n .map((value) => Math.round(Number(value)))\n .filter((value) => Number.isFinite(value) && value >= 0),\n ),\n ].sort((a, b) => a - b)\n : []\n // One refund attempt, minted by the console. Node lowercases incoming\n // headers, but read both spellings — the plugin API request type makes no\n // promise about casing.\n const idempotencyKey = String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n )\n .trim()\n .slice(0, 200)\n if (!hostId || !orderId) {\n return res.status(400).json({ error: 'Missing hostId or orderId' })\n }\n\n let claim: RefundClaim | null = null\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // TWO CHECKS, and they answer different questions (AGL-2372).\n //\n // The first is the HOST-level fact the Firestore rules also enforce, and\n // it stays: `memberRoles` is the projection the rules read, so dropping it\n // here would let this route and the database disagree.\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n // The second is WHOSE admin, and it is the one this gate was missing.\n //\n // `memberRoles` is a per-host projection of `hostAccess`, and\n // `/api/hosts/members` will grant a SITE COLLABORATOR `admin` on one site\n // (`hostAccess: { [hostId]: 'admin' }`, `allHosts: false`). That writes the\n // literal string `'admin'` into `memberRoles[uid]` — byte-identical to an\n // org owner's. So the check above cannot tell a contractor invited to run\n // one microsite from the person who owns the business, and refunding is\n // money leaving that business.\n //\n // `orgWide` is the discriminator, and it needs no new role: it is\n // `isOrgWideMember` (AGL-1026) — owner/admin of the org, an explicit\n // `allHosts` member, or the legacy pre-`allHosts` shape — and it is false\n // for every scoped collaborator. Same pairing `pos-order.ts` uses.\n //\n // BOTH halves are required. `hostRole` is re-tested rather than assumed\n // from `memberRole`: an org-wide member can still be scoped down to\n // `editor` on this host, and `resolveOrgPermissions` is the resolver that\n // knows it. It fails CLOSED on a lookup error when a host is named\n // (AGL-506), and `denied()` returns `orgWide: false` / `hostRole: null`,\n // so an absent membership refuses rather than folding to permitted.\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n const workspaceAdmin =\n memberRole === 'admin' &&\n membership.orgWide === true &&\n membership.hostRole === 'admin'\n // THE REGISTER'S OWN REFUNDS (AGL-3609). A member who works the register\n // — `admin` or `editor` on this site with `managePos` — may refund a POS\n // order up to the site's cashier refund limit, and above it with a\n // workspace admin's PIN. Decided below, once the order and the amount are\n // known; every other refund still needs the workspace admin above.\n const registerStaff =\n !workspaceAdmin &&\n (memberRole === 'admin' || memberRole === 'editor') &&\n membership.permissions?.managePos === true\n if (!workspaceAdmin && !registerStaff) {\n return res.status(403).json({\n error:\n memberRole !== 'admin'\n ? 'Refunds require a site admin'\n : 'Refunds require an admin of the whole workspace',\n })\n }\n const orderRef = hostRef.collection('orders').doc(orderId)\n const orderSnapshot = await orderRef.get()\n if (!orderSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown order' })\n }\n const order = CommerceModel.liftLegacyOrder(orderSnapshot.data() as any)\n if (registerStaff) {\n const authority = await posRegisterRefundAuthority({\n hostId,\n hostRef,\n order,\n amountCents,\n lineCents: requestedLineIds.length\n ? CommerceModel.orderLineRefundCents(order, requestedLineIds)\n : null,\n registerId: String(body.registerId ?? (order as { registerId?: string }).registerId ?? ''),\n managerAssertion: body.managerAssertion,\n })\n if ('body' in authority) return res.status(403).json(authority.body)\n }\n\n // Replay a settled attempt before anything else can reject it. This read\n // is only a short-circuit, never the dedupe primitive — the atomic\n // `create()` below is. It has to run ahead of the status guard because a\n // retried FULL refund would otherwise be answered \"orders in refunded\n // cannot refund\", which is the right money outcome reported as a failure,\n // and an admin who reads it as a failure refunds again by hand.\n const claimRef = idempotencyKey\n ? firestore\n .collection('apiIdempotency')\n .doc(\n createHash('sha256')\n // Scoped by the order, so a client that reused one key across\n // two orders cannot dedupe two legitimately distinct refunds.\n // NOT by the amount: that would swallow a real second partial.\n .update(`refund:${hostId}:${orderId}:${idempotencyKey}`)\n .digest('hex'),\n )\n : null\n if (claimRef) {\n const prior = await claimRef.get()\n const priorResponse = prior.get('response')\n if (priorResponse) {\n return res\n .status(Number(prior.get('responseStatus') ?? 200))\n .json(priorResponse)\n }\n }\n\n if (!CommerceModel.canTransitionOrder(order.status, 'refunded')) {\n return res\n .status(409)\n .json({ error: `Orders in \"${order.status}\" cannot refund` })\n }\n // A refund does not withdraw a dispute (AGL-1809). While a chargeback is\n // formally open the bank has already pulled the disputed funds, Stripe's\n // refund API refuses the charge (`charge_disputed`), and a refund that did\n // go through would pay the shopper twice — the merchant loses the refund\n // AND the dispute plus its fee. Refused HERE, before the claim and the\n // reservation, so a refusal burns no idempotency key and strands nothing:\n // no state has been written yet (AGL-1754's contract). An open INQUIRY\n // (`warning_*`) deliberately passes — no funds have moved and Stripe names\n // a full refund as the way to resolve one before it escalates — and the\n // status guard above already turns away a LOST dispute, which parked the\n // order in `refunded`. This reads the pre-transaction snapshot; a dispute\n // webhook racing this exact request is caught by the `charge_disputed`\n // mapping on the Stripe response below.\n if (CommerceModel.orderDisputeBlocksRefund(order)) {\n return res.status(409).json({\n error:\n 'A chargeback is open on this order, so it was not refunded. ' +\n 'Refunding would not withdraw the dispute — the bank has already ' +\n 'taken the disputed amount, and a refund on top of it would pay ' +\n 'the shopper twice. Respond to the dispute or accept it in the ' +\n 'Stripe dashboard; refund any remainder once it settles.',\n })\n }\n // WHAT THE NAMED LINES ARE WORTH, AND WHY THE AMOUNT MAY NOT BE LESS\n // (AGL-2454).\n //\n // A refund carries an amount, not lines — that is the blocker this issue\n // names, and `restock-flag.ts:48-55` already records it for stock. It\n // cannot be solved by inference: deciding for the merchant which lines a\n // bare figure covers would be a guess about their goods. It CAN be solved\n // by asking, which is what naming lines does, and the amount is then\n // derived from them rather than typed beside them.\n //\n // An explicit `amountCents` may still be LARGER (the admin is refunding the\n // line plus its share of tax or shipping, which this items-only sum does\n // not include). It may not be SMALLER: revoking a line the refund did not\n // actually cover is the silent over-revocation this issue forbids in the\n // same breath as silent under-revocation.\n const orderLines = order.lineItems ?? []\n const invalidLine = requestedLineIds.find(\n (index) => index >= orderLines.length,\n )\n if (invalidLine != null) {\n return res\n .status(400)\n .json({ error: `Line ${invalidLine} is not on this order` })\n }\n // NET OF THE ORDER'S DISCOUNT, not the list price.\n //\n // This was the bare `unitAmountCents x quantity`, which is what the line\n // was LISTED at rather than what the buyer paid for it. On a discounted\n // order the two differ, and both directions of the error land on the\n // merchant: a $10 coupon over two $50 lines means each line cost $45, so\n // refunding one at $50 gave back $5 that was never taken, and the order\n // then held less than its remaining line was worth — so the second line\n // refund hit the cap below and was refused outright, leaving the merchant\n // unable to finish a refund they had already half-issued.\n //\n // `orderLineRefundCents` apportions the discount across every line by list\n // value and returns the named lines' share, so refunding all of them sums\n // to exactly what was charged and no cent is stranded or invented.\n const namedLinesCents = CommerceModel.orderLineRefundCents(\n order,\n requestedLineIds,\n )\n if (\n requestedLineIds.length > 0 &&\n amountCents != null &&\n Math.round(amountCents) < namedLinesCents\n ) {\n return res.status(400).json({\n error:\n 'That amount is less than the lines you selected are worth. ' +\n 'Refund the full value of those lines, or refund an amount ' +\n 'without selecting lines.',\n })\n }\n // A register sale paid with SEVERAL cards (AGL-3607) has no single\n // charge to refund: each refund is taken from one card that can cover it.\n const splitCards = CommerceModel.orderPayments(order).filter(\n (payment) =>\n payment.status === 'succeeded' &&\n CommerceModel.isCardPaymentMethod(payment.method) &&\n Boolean(payment.paymentIntentId),\n )\n const splitRefunds = (order as { paymentRefunds?: Record<string, number> }).paymentRefunds ?? {}\n let paymentIntentId =\n (splitCards.length > 1 ? splitCards[0].paymentIntentId : undefined) ??\n order.paymentIntentId ??\n // Legacy rows stored the checkout session as the doc id; resolve\n // the payment intent from Stripe.\n (await (async () => {\n const response = await fetch(\n `https://api.stripe.com/v1/checkout/sessions/${orderId}`,\n {\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n },\n },\n )\n const session = await response.json()\n return response.ok ? session?.payment_intent : null\n })())\n if (!paymentIntentId) {\n return res.status(409).json({ error: 'No payment to refund' })\n }\n\n // Point of no return: everything past here moves money. The claim is\n // `create()` — Firestore rejects a create on an existing document, and\n // that rejection IS the dedupe primitive. A read-then-write would race\n // exactly the double-submit it exists to stop. Storage reuses the REST\n // API's shape and its `orgId` field (AGL-618) rather than inventing a\n // second replay store, so `eraseOrgIdempotencyKeys` (AGL-1448) already\n // sweeps these on org erasure with no change there.\n if (claimRef) {\n const ownerOrg = await getOrgForHost(hostId)\n try {\n await claimRef.create({\n orgId: String(ownerOrg?.org?.id ?? '') || null,\n hostId,\n orderId,\n kind: 'commerce-refund',\n status: 'pending',\n createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n createdAtMs: Date.now(),\n // The second writer into `apiIdempotency` (AGL-1978). The shared\n // `claimAttempt` stamps this too; this local copy has to as well,\n // or refund claims are the one shape the TTL policy silently never\n // reaches — a policy that governs most of a collection reads, from\n // the outside, exactly like one that governs all of it.\n expiresAt: Aglyn.apiIdempotencyExpiry(),\n })\n } catch {\n const prior = await claimRef.get()\n const priorResponse = prior.get('response')\n if (priorResponse) {\n return res\n .status(Number(prior.get('responseStatus') ?? 200))\n .json(priorResponse)\n }\n // In flight, or stranded by a process that died mid-refund. Fail\n // CLOSED: the alternative is sending the money a second time.\n return res\n .status(409)\n .json({ error: 'This refund is already being processed' })\n }\n claim = {\n // The same digest goes to Stripe. That is the half that costs real\n // money: it covers the window where our claim is written but the\n // response never arrives, and makes Stripe replay its own refund\n // instead of moving the funds again.\n stripeKey: claimRef.id,\n record: async (status, payload) => {\n await claimRef\n .set(\n {\n status: 'done',\n responseStatus: status,\n response: payload,\n settledAtMs: Date.now(),\n },\n { merge: true },\n )\n .catch(() => undefined)\n },\n release: async () => {\n await claimRef.delete().catch(() => undefined)\n },\n }\n }\n\n // RESERVE. The cap is read and written in one transaction, so two\n // concurrent refunds cannot both see the same `refundedCents` — which is\n // the whole failure the old ordering had, since it wrote the counter only\n // after Stripe had already been asked to move the money. Reserving BEFORE\n // the call rather than after also fails in the safe direction: a lost\n // response leaves the amount counted, so the retry refunds less, never\n // more.\n let refundCents = 0\n let totalCents = 0\n await firestore.runTransaction(async (transaction) => {\n const fresh = CommerceModel.liftLegacyOrder(\n ((await transaction.get(orderRef)).data() ?? {}) as any,\n )\n totalCents = fresh.totals?.totalCents ?? Number(fresh.amountCents ?? 0)\n const alreadyRefunded = Number(fresh.refundedCents ?? 0)\n const remaining = totalCents - alreadyRefunded\n // Named lines with no amount refund exactly what those lines are worth;\n // named lines WITH an amount use the amount (already guarded above as\n // no smaller than the lines). Neither is the whole order, which is what\n // `amountCents == null` alone still means.\n const asked =\n amountCents != null\n ? Math.round(amountCents)\n : requestedLineIds.length > 0\n ? namedLinesCents\n : remaining\n refundCents = Math.min(asked, remaining)\n if (!(refundCents > 0)) {\n refundCents = 0\n return\n }\n transaction.set(\n orderRef,\n { refundedCents: alreadyRefunded + refundCents },\n { merge: true },\n )\n })\n if (!(refundCents > 0)) {\n // Nothing moved, so the attempt key is released rather than burned.\n await claim?.release()\n return res.status(400).json({ error: 'Nothing left to refund' })\n }\n // The cap bit into the named lines (AGL-2454): earlier partials have left\n // less on this order than the selected lines are worth. REFUSED rather\n // than refunded-and-revoked, because revoking a line for less than its\n // value is precisely the silent over-revocation this issue forbids. The\n // reservation is given back — the same compensation a Stripe refusal does\n // below, and for the same reason: nothing has left the account yet.\n if (requestedLineIds.length > 0 && refundCents < namedLinesCents) {\n await firestore\n .runTransaction(async (transaction) => {\n const current = Number(\n (await transaction.get(orderRef)).get('refundedCents') ?? 0,\n )\n transaction.set(\n orderRef,\n { refundedCents: Math.max(0, current - refundCents) },\n { merge: true },\n )\n })\n .catch(() => undefined)\n await claim?.release()\n return res.status(409).json({\n error:\n `Only $${(refundCents / 100).toFixed(2)} is left to refund on this ` +\n `order, and the lines you selected are worth $${(\n namedLinesCents / 100\n ).toFixed(2)}. Refund an amount without selecting lines instead.`,\n })\n }\n\n if (splitCards.length > 1) {\n // The card this refund comes off: the first with enough left on it.\n // A refund larger than any one card refuses with the largest that\n // fits, rather than splitting money across charges unasked; a part a\n // customer paid in cash or by gift card is handed back at the till.\n const capacity = (payment: CommerceModel.OrderPayment) =>\n payment.amountCents +\n Number(payment.tipCents ?? 0) -\n Number(splitRefunds[String(payment.paymentIntentId)] ?? 0)\n const card = splitCards.find((payment) => capacity(payment) >= refundCents)\n if (!card) {\n await firestore\n .runTransaction(async (transaction) => {\n const current = Number(\n (await transaction.get(orderRef)).get('refundedCents') ?? 0,\n )\n transaction.set(\n orderRef,\n { refundedCents: Math.max(0, current - refundCents) },\n { merge: true },\n )\n })\n .catch(() => undefined)\n await claim?.release()\n const largest = Math.max(0, ...splitCards.map(capacity))\n return res.status(409).json({\n error:\n 'This sale was paid with several cards, and no one card has ' +\n `$${(refundCents / 100).toFixed(2)} left to refund. Refund at most ` +\n `$${(largest / 100).toFixed(2)} at a time; hand back any part paid ` +\n 'in cash or by gift card at the register.',\n })\n }\n paymentIntentId = String(card.paymentIntentId)\n }\n\n const refund = await createStripeRefund({\n paymentIntentId: String(paymentIntentId),\n amountCents: refundCents,\n idempotencyKey: claim?.stripeKey ?? null,\n })\n if ('error' in refund) {\n console.error('Stripe refund error', refund.code, refund.error)\n // Stripe said no, so we KNOW no money moved: give the reservation back\n // and let the same attempt be tried again.\n await firestore\n .runTransaction(async (transaction) => {\n const current = Number(\n (await transaction.get(orderRef)).get('refundedCents') ?? 0,\n )\n transaction.set(\n orderRef,\n { refundedCents: Math.max(0, current - refundCents) },\n { merge: true },\n )\n })\n .catch(() => undefined)\n await claim?.release()\n // Stripe refusing BECAUSE OF A DISPUTE is the guard above arriving by\n // the other door — our order document simply didn't know yet (webhook\n // lag, or an order from before disputes were subscribed at all). Same\n // answer, same accuracy: a 409 naming the dispute (`createStripeRefund`\n // words it), not a 502 reading \"The charge you're attempting to refund\n // has been charged back\", which an admin has no reason to connect to\n // the Refund button they pressed.\n return res.status(refund.status === 409 ? 409 : 502).json({ error: refund.error })\n }\n\n let refundedCents = 0\n let fullyRefunded = false\n let closedTheOrder = false\n await firestore.runTransaction(async (transaction) => {\n const fresh = CommerceModel.liftLegacyOrder(\n ((await transaction.get(orderRef)).data() ?? {}) as any,\n )\n refundedCents = Number(fresh.refundedCents ?? 0)\n fullyRefunded = refundedCents >= totalCents\n // Whether THIS settle moved the order into `refunded`, which is not the\n // same question as whether the order is now fully refunded (AGL-1754).\n // Two partials that between them close an order can both reserve before\n // either settles, so both re-read the completed total and both compute\n // `fullyRefunded`. Writing `status: 'refunded'` twice is harmless;\n // incrementing a count twice is not. Reading the status inside the same\n // transaction that writes it makes the flip observable exactly once.\n closedTheOrder = fullyRefunded && fresh.status !== 'refunded'\n transaction.set(\n orderRef,\n {\n ...(fullyRefunded ? { status: 'refunded' } : {}),\n // What a shipping tool's feed asks to learn of it (AGL-3613).\n updatedAtMs: Date.now(),\n // Which card a split register sale's refund came off (AGL-3607).\n ...(splitCards.length > 1\n ? {\n paymentRefunds: {\n [String(paymentIntentId)]:\n firebaseAdmin.firestore.FieldValue.increment(refundCents),\n },\n }\n : {}),\n // The entitlement withdrawal, recorded WITH the money (AGL-2454).\n // `arrayUnion` rather than a written-back array: two admins refunding\n // different lines at once must not erase each other's, and this\n // transaction re-reads the order but a written array would still lose\n // a concurrent settle that committed between the two.\n ...(requestedLineIds.length > 0\n ? {\n refundedLineItemIds:\n firebaseAdmin.firestore.FieldValue.arrayUnion(\n ...requestedLineIds,\n ),\n }\n : {}),\n timeline: CommerceModel.appendOrderEvent(\n fresh,\n 'refund',\n `$${(refundCents / 100).toFixed(2)} refunded` +\n (fullyRefunded\n ? ' (full)'\n : requestedLineIds.length > 0\n ? ` — ${requestedLineIds.length} line${\n requestedLineIds.length === 1 ? '' : 's'\n } withdrawn`\n : ' — refunded by amount, no lines withdrawn'),\n ),\n },\n { merge: true },\n )\n })\n const payload = { refundedCents, fullyRefunded }\n await claim?.record(200, payload)\n // LICENCE KEYS ARE RETIRED, NEVER RETURNED TO THE POOL (AGL-2454).\n //\n // `assignLicenseKeys` stamps `assignedAtMs`, `orderId` and `email` onto a\n // pool document and nothing anywhere ever set them back — so a refunded\n // order consumed the merchant's key forever, and a merchant who sold one\n // key out of a hundred and refunded it had ninety-nine, permanently.\n //\n // Returning it to the pool is NOT the fix, and this is the decision the\n // issue asked for: the key string was mailed in the receipt and cannot be\n // invalidated by anything we own, so re-issuing it to the next paying\n // customer would hand two people one working secret. That is worse than\n // losing the key. A third state — retired: neither assigned to a live order\n // nor available — is the honest record, and `revokedAtMs` already IS that\n // state: the console's key dialog has written exactly this pair since it\n // shipped, so this reuses the merchant's own vocabulary rather than\n // inventing a second one.\n //\n // Best-effort and after the response is recorded, matching the contact and\n // restock ledgers below: the money has moved and nothing here may fail a\n // refund that already left the merchant's account.\n await retireLicenseKeys(hostRef, orderRef, orderId)\n // GIFT CARDS THE REFUND TOOK BACK ARE VOIDED (AGL-3363). The money went\n // back to the card that paid, so what is left on the cards that money\n // bought goes too — every card on a full refund, and on a partial one\n // only the cards bought by the lines it withdrew. A refund by amount with\n // no lines named withdraws nothing, so it voids nothing. Same best-effort\n // placement as the key retirement above: the refund has already moved.\n if (fullyRefunded || requestedLineIds.length > 0) {\n await applyGiftCardRiskToOrder({\n firestore,\n hostRef,\n orderId,\n action: {\n kind: 'void',\n reason: 'refund',\n ...(fullyRefunded\n ? {}\n : {\n productIds: requestedLineIds\n .map((index) => String(order.lineItems?.[index]?.productId ?? ''))\n .filter(Boolean),\n }),\n },\n })\n }\n // The customer's side of the ledger (AGL-1754). Everything above records\n // the money on the ORDER; without this the buyer's `ltvCents` still counts\n // a sale they returned, and only ever rises.\n //\n // Placed AFTER the attempt is recorded so a slow contacts write cannot\n // strand the claim: a retry that arrives while this is in flight replays\n // the recorded 200 instead of being turned away with \"already being\n // processed\". Awaited rather than fired off with `void` — the handler is\n // serverless, and work left running past the response is work the\n // container may be frozen before it finishes. The seam never throws, so\n // awaiting adds no way for this to fail a refund that has already left\n // the merchant's account.\n //\n // Through the plugin that keeps people (AGL-3080): what a refund does to\n // the customer's record is that plugin's to decide, and commerce writes\n // none of it.\n //\n // Amount is THIS attempt's `refundCents`, already capped against what was\n // left, so several partials sum to at most the order total — the same\n // number the order's own `refundedCents` follows. The retried and racing\n // cases need no key of their own: a keyed retry never reaches here (it\n // replays at the claim), and a keyless one is a genuinely new refund that\n // moved more money and should be counted.\n await recordPluginPersonRefund({\n hostId,\n refId: orderId,\n email: order.customerEmail,\n amountCents: refundCents,\n closedTheSale: closedTheOrder,\n })\n /*\n * The campaign's side of the same ledger.\n *\n * If a campaign was credited with this order, that credit is now partly\n * or wholly wrong — a campaign cannot go on being paid for a sale the\n * merchant reversed, and revenue attribution that only ever rises is the\n * flattering half of a measurement. Recorded beside the gross rather than\n * subtracted from it, for the reason the customer's record keeps its\n * refunds beside what they spent.\n *\n * Keyed by the ORDER and not by the buyer, so it needs no email and works\n * for a guest checkout: the attribution record holds which campaign and\n * which currency, and this reads them back. Same placement, same\n * swallow-all contract and same awaited call as the two ledgers around\n * it — nothing here may fail a refund that has already left the\n * merchant's account.\n */\n await reverseOrderConversion({\n hostId,\n orderId,\n amountCents: refundCents,\n closedTheOrder,\n })\n // The shelf's side of the ledger (AGL-1797). The sale decremented variant\n // inventory and nothing put it back, so a fully refunded order read one\n // unit light forever. This FLAGS rather than releases — a refund with no\n // return leaves the goods gone, and inventing stock the merchant does not\n // have is worse than under-counting it — and the merchant answers from the\n // stock adjustment they already have. Same placement and same swallow-all\n // contract as the contact write above, for the same reason: the money has\n // moved and the order records it, so nothing here may fail the refund.\n await flagOrderRestock({ hostId, orderId, kind: 'refund', closedTheOrder })\n // The buyer is told what came back (AGL-3610), once per Stripe refund id —\n // a keyed retry replays at the claim above and never reaches here.\n await notifyOrderBuyer({ hostId, orderId }, 'refunded', { refundId: refund.refundId, refundCents, refundLineIndexes: requestedLineIds, fullyRefunded })\n // Other plugins and the merchant's webhooks hear it too (AGL-3611), once per refund.\n await raiseOrderEvent(ORDER_REFUNDED_EVENT, { hostId, orderId, key: `refund:${refund.refundId || idempotencyKey}`, extra: { refund: { id: refund.refundId || null, amountCents: refundCents, lineItemIds: [...(requestedLineIds ?? [])], full: Boolean(fullyRefunded) } } })\n return res.status(200).json(payload)\n } catch (error) {\n console.error(error)\n // Deliberately NOT released, which is where this diverges from the POS\n // sale path (AGL-1691). If the refund call threw we do not know whether\n // Stripe moved the money, and the two failure directions are not\n // symmetric: a stranded key costs a support ticket, a released one costs a\n // second refund. The retry gets a 409 and a human reconciles.\n return res.status(500).json({ error: 'Refund failed' })\n }\n}\n"],"names":["Aglyn","CommerceModel","firebaseAdmin","getOrgForHost","resolveOrgPermissions","createHash","recordPluginPersonRefund","applyGiftCardRiskToOrder","flagOrderRestock","notifyOrderBuyer","ORDER_REFUNDED_EVENT","raiseOrderEvent","reverseOrderConversion","createStripeRefund","posRegisterRefundAuthority","retireLicenseKeys","hostRef","orderRef","orderId","fresh","liftLegacyOrder","get","data","withdrawn","Set","refundedProductIds","size","assigned","collection","where","limit","retired","keySnapshot","docs","has","String","ref","set","revokedAtMs","Date","now","revokedOrderId","merge","catch","undefined","update","timeline","firestore","FieldValue","arrayUnion","atMs","event","detail","error","console","refundHandler","req","res","body","method","status","json","process","env","STRIPE_SECRET_KEY","authorization","headers","idToken","startsWith","slice","length","JSON","parse","hostId","amountCents","Number","requestedLineIds","Array","isArray","lineItemIds","map","value","Math","round","filter","isFinite","sort","a","b","idempotencyKey","trim","claim","hostSnapshot","order","splitCards","membership","decoded","app","auth","verifyIdToken","doc","exists","memberRole","uid","workspaceAdmin","orgWide","hostRole","registerStaff","permissions","managePos","orderSnapshot","authority","lineCents","orderLineRefundCents","registerId","managerAssertion","claimRef","digest","prior","priorResponse","canTransitionOrder","orderDisputeBlocksRefund","orderLines","lineItems","invalidLine","find","index","namedLinesCents","orderPayments","payment","isCardPaymentMethod","Boolean","paymentIntentId","splitRefunds","paymentRefunds","response","fetch","Authorization","session","ok","payment_intent","ownerOrg","create","orgId","org","id","kind","createdAt","serverTimestamp","createdAtMs","expiresAt","apiIdempotencyExpiry","stripeKey","record","payload","responseStatus","settledAtMs","release","delete","refundCents","totalCents","runTransaction","transaction","totals","alreadyRefunded","refundedCents","remaining","asked","min","current","max","toFixed","capacity","tipCents","card","largest","refund","code","fullyRefunded","closedTheOrder","updatedAtMs","increment","refundedLineItemIds","appendOrderEvent","action","reason","productIds","productId","refId","email","customerEmail","closedTheSale","refundId","refundLineIndexes","key","extra","full"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,sBAAqB;AAC5C,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AAEvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,UAAU,QAAQ,SAAQ;AACnC,SAASC,wBAAwB,QAAQ,oDAAmD;AAC5F,SAASC,wBAAwB,QAAQ,sBAAkB;AAC3D,SAASC,gBAAgB,QAAQ,oBAAgB;AACjD,SAASC,gBAAgB,QAAQ,2BAAuB;AACxD,SAASC,oBAAoB,QAAQ,2BAAuB;AAC5D,SAASC,eAAe,QAAQ,oBAAgB;AAChD,SAASC,sBAAsB,QAAQ,uDAAsD;AAC7F,SAASC,kBAAkB,QAAQ,qBAAiB;AACpD,SAASC,0BAA0B,QAAQ,4BAAwB;AAanE;;;;;;;;;;;;;;;;CAgBC,GACD,eAAeC,kBACbC,OAA4C,EAC5CC,QAA6C,EAC7CC,OAAe;IAEf,IAAI;YAEC;QADH,MAAMC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1K,iBAAiB;YAAEgE;YAAQvD;QAAQ,GAAG,YAAY;YAAE8K,UAAUhB,OAAOgB,QAAQ;YAAEjC;YAAakC,mBAAmBrH;YAAkBsG;QAAc;QACrJ,qFAAqF;QACrF,MAAMvK,gBAAgBD,sBAAsB;YAAE+D;YAAQvD;YAASgL,KAAK,CAAC,OAAO,EAAElB,OAAOgB,QAAQ,IAAIvG,gBAAgB;YAAE0G,OAAO;gBAAEnB,QAAQ;oBAAE/B,IAAI+B,OAAOgB,QAAQ,IAAI;oBAAMtH,aAAaqF;oBAAahF,aAAa;2BAAKH,2BAAAA,mBAAoB,EAAE;qBAAE;oBAAEwH,MAAMjE,QAAQ+C;gBAAe;YAAE;QAAE;QAC1Q,OAAOzH,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC6F;IAC9B,EAAE,OAAOrG,OAAO;QACdC,QAAQD,KAAK,CAACA;QACd,uEAAuE;QACvE,wEAAwE;QACxE,iEAAiE;QACjE,2EAA2E;QAC3E,8DAA8D;QAC9D,OAAOI,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAER,OAAO;QAAgB;IACvD;AACF,EAAC"}
@@ -395,6 +395,8 @@ import { checkoutSessionCardAuthenticationParams } from "@aglyn/tenant-data-admi
395
395
  'metadata[taxCents]': String(lodgingTax.taxCents),
396
396
  'metadata[taxPct]': String(lodgingTax.pct)
397
397
  } : {}));
398
+ // The merchant's payment method choices hold for a stay too (AGL-3629).
399
+ CommerceModel.appendStorefrontPaymentMethodParams(params, CommerceModel.resolveStorefrontPaymentMethodControls(CommerceModel.normalizeStorefrontPaymentMethodSettings(storeSnapshot.get('paymentMethods'))));
398
400
  const response = await fetch('https://api.stripe.com/v1/checkout/sessions', {
399
401
  method: 'POST',
400
402
  headers: _extends({