@aglyn/plugins-commerce 1.0.0-beta.143

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (417) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +10 -0
  3. package/package.json +57 -0
  4. package/src/index.d.ts +38 -0
  5. package/src/index.js +38 -0
  6. package/src/index.js.map +1 -0
  7. package/src/lib/components/account.d.ts +31 -0
  8. package/src/lib/components/account.js +645 -0
  9. package/src/lib/components/account.js.map +1 -0
  10. package/src/lib/components/cart.d.ts +38 -0
  11. package/src/lib/components/cart.js +851 -0
  12. package/src/lib/components/cart.js.map +1 -0
  13. package/src/lib/components/commerce-console-page.d.ts +32 -0
  14. package/src/lib/components/commerce-console-page.js +296 -0
  15. package/src/lib/components/commerce-console-page.js.map +1 -0
  16. package/src/lib/components/commerce-console-sections.d.ts +34 -0
  17. package/src/lib/components/commerce-console-sections.js +62 -0
  18. package/src/lib/components/commerce-console-sections.js.map +1 -0
  19. package/src/lib/components/console/catalog-organization-card.component.d.ts +14 -0
  20. package/src/lib/components/console/catalog-organization-card.component.js +1087 -0
  21. package/src/lib/components/console/catalog-organization-card.component.js.map +1 -0
  22. package/src/lib/components/console/commerce-analytics-card.component.d.ts +27 -0
  23. package/src/lib/components/console/commerce-analytics-card.component.js +310 -0
  24. package/src/lib/components/console/commerce-analytics-card.component.js.map +1 -0
  25. package/src/lib/components/console/commerce-glance-card.component.d.ts +20 -0
  26. package/src/lib/components/console/commerce-glance-card.component.js +340 -0
  27. package/src/lib/components/console/commerce-glance-card.component.js.map +1 -0
  28. package/src/lib/components/console/commerce-stat-tile.component.d.ts +37 -0
  29. package/src/lib/components/console/commerce-stat-tile.component.js +72 -0
  30. package/src/lib/components/console/commerce-stat-tile.component.js.map +1 -0
  31. package/src/lib/components/console/discounts-card.component.d.ts +14 -0
  32. package/src/lib/components/console/discounts-card.component.js +443 -0
  33. package/src/lib/components/console/discounts-card.component.js.map +1 -0
  34. package/src/lib/components/console/entitlement-gate.component.d.ts +76 -0
  35. package/src/lib/components/console/entitlement-gate.component.js +115 -0
  36. package/src/lib/components/console/entitlement-gate.component.js.map +1 -0
  37. package/src/lib/components/console/gift-cards-card.component.d.ts +29 -0
  38. package/src/lib/components/console/gift-cards-card.component.js +379 -0
  39. package/src/lib/components/console/gift-cards-card.component.js.map +1 -0
  40. package/src/lib/components/console/host-coupons-card.component.d.ts +14 -0
  41. package/src/lib/components/console/host-coupons-card.component.js +252 -0
  42. package/src/lib/components/console/host-coupons-card.component.js.map +1 -0
  43. package/src/lib/components/console/host-orders-card.component.d.ts +13 -0
  44. package/src/lib/components/console/host-orders-card.component.js +861 -0
  45. package/src/lib/components/console/host-orders-card.component.js.map +1 -0
  46. package/src/lib/components/console/locations-card.component.d.ts +14 -0
  47. package/src/lib/components/console/locations-card.component.js +256 -0
  48. package/src/lib/components/console/locations-card.component.js.map +1 -0
  49. package/src/lib/components/console/member-posts-card.component.d.ts +8 -0
  50. package/src/lib/components/console/member-posts-card.component.js +283 -0
  51. package/src/lib/components/console/member-posts-card.component.js.map +1 -0
  52. package/src/lib/components/console/newest-site-users-card.component.d.ts +36 -0
  53. package/src/lib/components/console/newest-site-users-card.component.js +126 -0
  54. package/src/lib/components/console/newest-site-users-card.component.js.map +1 -0
  55. package/src/lib/components/console/order-detail-dialog.component.d.ts +28 -0
  56. package/src/lib/components/console/order-detail-dialog.component.js +976 -0
  57. package/src/lib/components/console/order-detail-dialog.component.js.map +1 -0
  58. package/src/lib/components/console/paid-media.d.ts +127 -0
  59. package/src/lib/components/console/paid-media.js +397 -0
  60. package/src/lib/components/console/paid-media.js.map +1 -0
  61. package/src/lib/components/console/payments-settings-card.component.d.ts +13 -0
  62. package/src/lib/components/console/payments-settings-card.component.js +295 -0
  63. package/src/lib/components/console/payments-settings-card.component.js.map +1 -0
  64. package/src/lib/components/console/pos-page.component.d.ts +13 -0
  65. package/src/lib/components/console/pos-page.component.js +916 -0
  66. package/src/lib/components/console/pos-page.component.js.map +1 -0
  67. package/src/lib/components/console/product-editor-dialog.component.d.ts +32 -0
  68. package/src/lib/components/console/product-editor-dialog.component.js +1374 -0
  69. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -0
  70. package/src/lib/components/console/products-hub-card.component.d.ts +16 -0
  71. package/src/lib/components/console/products-hub-card.component.js +1280 -0
  72. package/src/lib/components/console/products-hub-card.component.js.map +1 -0
  73. package/src/lib/components/console/products-hub-zone.component.d.ts +50 -0
  74. package/src/lib/components/console/products-hub-zone.component.js +200 -0
  75. package/src/lib/components/console/products-hub-zone.component.js.map +1 -0
  76. package/src/lib/components/console/recovery-queue-card.component.d.ts +39 -0
  77. package/src/lib/components/console/recovery-queue-card.component.js +262 -0
  78. package/src/lib/components/console/recovery-queue-card.component.js.map +1 -0
  79. package/src/lib/components/console/registers-card.component.d.ts +21 -0
  80. package/src/lib/components/console/registers-card.component.js +296 -0
  81. package/src/lib/components/console/registers-card.component.js.map +1 -0
  82. package/src/lib/components/console/reservations-card.component.d.ts +14 -0
  83. package/src/lib/components/console/reservations-card.component.js +650 -0
  84. package/src/lib/components/console/reservations-card.component.js.map +1 -0
  85. package/src/lib/components/console/reviews-moderation-card.component.d.ts +8 -0
  86. package/src/lib/components/console/reviews-moderation-card.component.js +235 -0
  87. package/src/lib/components/console/reviews-moderation-card.component.js.map +1 -0
  88. package/src/lib/components/console/shipping-settings-card.component.d.ts +38 -0
  89. package/src/lib/components/console/shipping-settings-card.component.js +560 -0
  90. package/src/lib/components/console/shipping-settings-card.component.js.map +1 -0
  91. package/src/lib/components/console/stock-movements-card.component.d.ts +31 -0
  92. package/src/lib/components/console/stock-movements-card.component.js +333 -0
  93. package/src/lib/components/console/stock-movements-card.component.js.map +1 -0
  94. package/src/lib/components/console/store-settings-card.component.d.ts +14 -0
  95. package/src/lib/components/console/store-settings-card.component.js +300 -0
  96. package/src/lib/components/console/store-settings-card.component.js.map +1 -0
  97. package/src/lib/components/console/storefront-tax-summary-card.component.d.ts +73 -0
  98. package/src/lib/components/console/storefront-tax-summary-card.component.js +408 -0
  99. package/src/lib/components/console/storefront-tax-summary-card.component.js.map +1 -0
  100. package/src/lib/components/console/suppliers-card.component.d.ts +8 -0
  101. package/src/lib/components/console/suppliers-card.component.js +328 -0
  102. package/src/lib/components/console/suppliers-card.component.js.map +1 -0
  103. package/src/lib/components/console/tax-settings-card.component.d.ts +14 -0
  104. package/src/lib/components/console/tax-settings-card.component.js +473 -0
  105. package/src/lib/components/console/tax-settings-card.component.js.map +1 -0
  106. package/src/lib/components/gate.d.ts +39 -0
  107. package/src/lib/components/gate.js +202 -0
  108. package/src/lib/components/gate.js.map +1 -0
  109. package/src/lib/components/gated-video.d.ts +40 -0
  110. package/src/lib/components/gated-video.js +366 -0
  111. package/src/lib/components/gated-video.js.map +1 -0
  112. package/src/lib/components/member-feed.d.ts +32 -0
  113. package/src/lib/components/member-feed.js +198 -0
  114. package/src/lib/components/member-feed.js.map +1 -0
  115. package/src/lib/components/member-recovery.d.ts +35 -0
  116. package/src/lib/components/member-recovery.js +313 -0
  117. package/src/lib/components/member-recovery.js.map +1 -0
  118. package/src/lib/components/member-signin.d.ts +35 -0
  119. package/src/lib/components/member-signin.js +257 -0
  120. package/src/lib/components/member-signin.js.map +1 -0
  121. package/src/lib/components/member-signup.d.ts +34 -0
  122. package/src/lib/components/member-signup.js +287 -0
  123. package/src/lib/components/member-signup.js.map +1 -0
  124. package/src/lib/components/newsletter-signup.d.ts +39 -0
  125. package/src/lib/components/newsletter-signup.js +229 -0
  126. package/src/lib/components/newsletter-signup.js.map +1 -0
  127. package/src/lib/components/product-detail.d.ts +38 -0
  128. package/src/lib/components/product-detail.js +1022 -0
  129. package/src/lib/components/product-detail.js.map +1 -0
  130. package/src/lib/components/product-grid.d.ts +67 -0
  131. package/src/lib/components/product-grid.js +909 -0
  132. package/src/lib/components/product-grid.js.map +1 -0
  133. package/src/lib/components/product-reviews.d.ts +32 -0
  134. package/src/lib/components/product-reviews.js +349 -0
  135. package/src/lib/components/product-reviews.js.map +1 -0
  136. package/src/lib/components/related-products.d.ts +33 -0
  137. package/src/lib/components/related-products.js +232 -0
  138. package/src/lib/components/related-products.js.map +1 -0
  139. package/src/lib/components/reservation-widget.d.ts +33 -0
  140. package/src/lib/components/reservation-widget.js +418 -0
  141. package/src/lib/components/reservation-widget.js.map +1 -0
  142. package/src/lib/components/storefront-payment-element-fallback.d.ts +18 -0
  143. package/src/lib/components/storefront-payment-element-fallback.js +51 -0
  144. package/src/lib/components/storefront-payment-element-fallback.js.map +1 -0
  145. package/src/lib/components/storefront-payment-element.d.ts +78 -0
  146. package/src/lib/components/storefront-payment-element.js +156 -0
  147. package/src/lib/components/storefront-payment-element.js.map +1 -0
  148. package/src/lib/components/wishlist.d.ts +46 -0
  149. package/src/lib/components/wishlist.js +304 -0
  150. package/src/lib/components/wishlist.js.map +1 -0
  151. package/src/lib/constants/bundle-common.d.ts +18 -0
  152. package/src/lib/constants/bundle-common.js +18 -0
  153. package/src/lib/constants/bundle-common.js.map +1 -0
  154. package/src/lib/constants/product-filters.d.ts +35 -0
  155. package/src/lib/constants/product-filters.js +109 -0
  156. package/src/lib/constants/product-filters.js.map +1 -0
  157. package/src/lib/model/commerce-cart.d.ts +52 -0
  158. package/src/lib/model/commerce-cart.js +102 -0
  159. package/src/lib/model/commerce-cart.js.map +1 -0
  160. package/src/lib/model/commerce-connect-transfer.d.ts +243 -0
  161. package/src/lib/model/commerce-connect-transfer.js +231 -0
  162. package/src/lib/model/commerce-connect-transfer.js.map +1 -0
  163. package/src/lib/model/commerce-discounts.d.ts +164 -0
  164. package/src/lib/model/commerce-discounts.js +231 -0
  165. package/src/lib/model/commerce-discounts.js.map +1 -0
  166. package/src/lib/model/commerce-dispute.d.ts +124 -0
  167. package/src/lib/model/commerce-dispute.js +225 -0
  168. package/src/lib/model/commerce-dispute.js.map +1 -0
  169. package/src/lib/model/commerce-gift-cards.d.ts +107 -0
  170. package/src/lib/model/commerce-gift-cards.js +121 -0
  171. package/src/lib/model/commerce-gift-cards.js.map +1 -0
  172. package/src/lib/model/commerce-io.d.ts +36 -0
  173. package/src/lib/model/commerce-io.js +245 -0
  174. package/src/lib/model/commerce-io.js.map +1 -0
  175. package/src/lib/model/commerce-orders.d.ts +1040 -0
  176. package/src/lib/model/commerce-orders.js +1022 -0
  177. package/src/lib/model/commerce-orders.js.map +1 -0
  178. package/src/lib/model/commerce-promotions.d.ts +188 -0
  179. package/src/lib/model/commerce-promotions.js +199 -0
  180. package/src/lib/model/commerce-promotions.js.map +1 -0
  181. package/src/lib/model/commerce-reservations.d.ts +175 -0
  182. package/src/lib/model/commerce-reservations.js +157 -0
  183. package/src/lib/model/commerce-reservations.js.map +1 -0
  184. package/src/lib/model/commerce-shipping.d.ts +316 -0
  185. package/src/lib/model/commerce-shipping.js +484 -0
  186. package/src/lib/model/commerce-shipping.js.map +1 -0
  187. package/src/lib/model/commerce-stock-holds.d.ts +199 -0
  188. package/src/lib/model/commerce-stock-holds.js +190 -0
  189. package/src/lib/model/commerce-stock-holds.js.map +1 -0
  190. package/src/lib/model/commerce-subscription-status.d.ts +67 -0
  191. package/src/lib/model/commerce-subscription-status.js +76 -0
  192. package/src/lib/model/commerce-subscription-status.js.map +1 -0
  193. package/src/lib/model/commerce-tax-decision.d.ts +222 -0
  194. package/src/lib/model/commerce-tax-decision.js +165 -0
  195. package/src/lib/model/commerce-tax-decision.js.map +1 -0
  196. package/src/lib/model/commerce-tax.d.ts +176 -0
  197. package/src/lib/model/commerce-tax.js +92 -0
  198. package/src/lib/model/commerce-tax.js.map +1 -0
  199. package/src/lib/model/commerce.d.ts +551 -0
  200. package/src/lib/model/commerce.js +739 -0
  201. package/src/lib/model/commerce.js.map +1 -0
  202. package/src/lib/model/index.d.ts +40 -0
  203. package/src/lib/model/index.js +40 -0
  204. package/src/lib/model/index.js.map +1 -0
  205. package/src/lib/model/order-figures.d.ts +48 -0
  206. package/src/lib/model/order-figures.js +74 -0
  207. package/src/lib/model/order-figures.js.map +1 -0
  208. package/src/lib/model/plugin-permissions.d.ts +23 -0
  209. package/src/lib/model/plugin-permissions.js +34 -0
  210. package/src/lib/model/plugin-permissions.js.map +1 -0
  211. package/src/lib/model/purchase-analytics.d.ts +186 -0
  212. package/src/lib/model/purchase-analytics.js +216 -0
  213. package/src/lib/model/purchase-analytics.js.map +1 -0
  214. package/src/lib/plugin-config.d.ts +62 -0
  215. package/src/lib/plugin-config.js +78 -0
  216. package/src/lib/plugin-config.js.map +1 -0
  217. package/src/lib/plugin.d.ts +28 -0
  218. package/src/lib/plugin.js +147 -0
  219. package/src/lib/plugin.js.map +1 -0
  220. package/src/lib/server/billing-webhook.d.ts +26 -0
  221. package/src/lib/server/billing-webhook.js +4011 -0
  222. package/src/lib/server/billing-webhook.js.map +1 -0
  223. package/src/lib/server/cancel-order.d.ts +87 -0
  224. package/src/lib/server/cancel-order.js +368 -0
  225. package/src/lib/server/cancel-order.js.map +1 -0
  226. package/src/lib/server/cart-checkout.d.ts +25 -0
  227. package/src/lib/server/cart-checkout.js +976 -0
  228. package/src/lib/server/cart-checkout.js.map +1 -0
  229. package/src/lib/server/cart-cookie.d.ts +32 -0
  230. package/src/lib/server/cart-cookie.js +77 -0
  231. package/src/lib/server/cart-cookie.js.map +1 -0
  232. package/src/lib/server/cart.d.ts +34 -0
  233. package/src/lib/server/cart.js +181 -0
  234. package/src/lib/server/cart.js.map +1 -0
  235. package/src/lib/server/catalog.d.ts +127 -0
  236. package/src/lib/server/catalog.js +277 -0
  237. package/src/lib/server/catalog.js.map +1 -0
  238. package/src/lib/server/checkout.d.ts +36 -0
  239. package/src/lib/server/checkout.js +915 -0
  240. package/src/lib/server/checkout.js.map +1 -0
  241. package/src/lib/server/connect.d.ts +26 -0
  242. package/src/lib/server/connect.js +238 -0
  243. package/src/lib/server/connect.js.map +1 -0
  244. package/src/lib/server/contact-refund.d.ts +117 -0
  245. package/src/lib/server/contact-refund.js +196 -0
  246. package/src/lib/server/contact-refund.js.map +1 -0
  247. package/src/lib/server/download.d.ts +39 -0
  248. package/src/lib/server/download.js +206 -0
  249. package/src/lib/server/download.js.map +1 -0
  250. package/src/lib/server/draft-order.d.ts +26 -0
  251. package/src/lib/server/draft-order.js +706 -0
  252. package/src/lib/server/draft-order.js.map +1 -0
  253. package/src/lib/server/feed.d.ts +24 -0
  254. package/src/lib/server/feed.js +59 -0
  255. package/src/lib/server/feed.js.map +1 -0
  256. package/src/lib/server/fulfill-order.d.ts +97 -0
  257. package/src/lib/server/fulfill-order.js +235 -0
  258. package/src/lib/server/fulfill-order.js.map +1 -0
  259. package/src/lib/server/gate.d.ts +36 -0
  260. package/src/lib/server/gate.js +112 -0
  261. package/src/lib/server/gate.js.map +1 -0
  262. package/src/lib/server/gift-cards.d.ts +42 -0
  263. package/src/lib/server/gift-cards.js +219 -0
  264. package/src/lib/server/gift-cards.js.map +1 -0
  265. package/src/lib/server/low-stock.d.ts +49 -0
  266. package/src/lib/server/low-stock.js +60 -0
  267. package/src/lib/server/low-stock.js.map +1 -0
  268. package/src/lib/server/manual-tax-rate.d.ts +82 -0
  269. package/src/lib/server/manual-tax-rate.js +113 -0
  270. package/src/lib/server/manual-tax-rate.js.map +1 -0
  271. package/src/lib/server/member-feed.d.ts +24 -0
  272. package/src/lib/server/member-feed.js +72 -0
  273. package/src/lib/server/member-feed.js.map +1 -0
  274. package/src/lib/server/member-name-search.d.ts +37 -0
  275. package/src/lib/server/member-name-search.js +42 -0
  276. package/src/lib/server/member-name-search.js.map +1 -0
  277. package/src/lib/server/member-post.d.ts +23 -0
  278. package/src/lib/server/member-post.js +166 -0
  279. package/src/lib/server/member-post.js.map +1 -0
  280. package/src/lib/server/membership-account.d.ts +37 -0
  281. package/src/lib/server/membership-account.js +148 -0
  282. package/src/lib/server/membership-account.js.map +1 -0
  283. package/src/lib/server/membership-admin-password.d.ts +33 -0
  284. package/src/lib/server/membership-admin-password.js +202 -0
  285. package/src/lib/server/membership-admin-password.js.map +1 -0
  286. package/src/lib/server/membership-content.d.ts +23 -0
  287. package/src/lib/server/membership-content.js +105 -0
  288. package/src/lib/server/membership-content.js.map +1 -0
  289. package/src/lib/server/membership-login.d.ts +19 -0
  290. package/src/lib/server/membership-login.js +137 -0
  291. package/src/lib/server/membership-login.js.map +1 -0
  292. package/src/lib/server/membership-logout.d.ts +19 -0
  293. package/src/lib/server/membership-logout.js +35 -0
  294. package/src/lib/server/membership-logout.js.map +1 -0
  295. package/src/lib/server/membership-recover.d.ts +60 -0
  296. package/src/lib/server/membership-recover.js +244 -0
  297. package/src/lib/server/membership-recover.js.map +1 -0
  298. package/src/lib/server/membership-register.d.ts +22 -0
  299. package/src/lib/server/membership-register.js +241 -0
  300. package/src/lib/server/membership-register.js.map +1 -0
  301. package/src/lib/server/membership-reset.d.ts +26 -0
  302. package/src/lib/server/membership-reset.js +88 -0
  303. package/src/lib/server/membership-reset.js.map +1 -0
  304. package/src/lib/server/membership-wishlist.d.ts +23 -0
  305. package/src/lib/server/membership-wishlist.js +89 -0
  306. package/src/lib/server/membership-wishlist.js.map +1 -0
  307. package/src/lib/server/membership.d.ts +96 -0
  308. package/src/lib/server/membership.js +222 -0
  309. package/src/lib/server/membership.js.map +1 -0
  310. package/src/lib/server/native-checkout.d.ts +170 -0
  311. package/src/lib/server/native-checkout.js +193 -0
  312. package/src/lib/server/native-checkout.js.map +1 -0
  313. package/src/lib/server/newsletter.d.ts +23 -0
  314. package/src/lib/server/newsletter.js +323 -0
  315. package/src/lib/server/newsletter.js.map +1 -0
  316. package/src/lib/server/notify-restock.d.ts +22 -0
  317. package/src/lib/server/notify-restock.js +84 -0
  318. package/src/lib/server/notify-restock.js.map +1 -0
  319. package/src/lib/server/order-analytics.d.ts +134 -0
  320. package/src/lib/server/order-analytics.js +263 -0
  321. package/src/lib/server/order-analytics.js.map +1 -0
  322. package/src/lib/server/order-figures.d.ts +33 -0
  323. package/src/lib/server/order-figures.js +220 -0
  324. package/src/lib/server/order-figures.js.map +1 -0
  325. package/src/lib/server/paid-media-delivery.d.ts +173 -0
  326. package/src/lib/server/paid-media-delivery.js +212 -0
  327. package/src/lib/server/paid-media-delivery.js.map +1 -0
  328. package/src/lib/server/pos-order.d.ts +54 -0
  329. package/src/lib/server/pos-order.js +1137 -0
  330. package/src/lib/server/pos-order.js.map +1 -0
  331. package/src/lib/server/process-abandoned.d.ts +54 -0
  332. package/src/lib/server/process-abandoned.js +222 -0
  333. package/src/lib/server/process-abandoned.js.map +1 -0
  334. package/src/lib/server/process-restock.d.ts +42 -0
  335. package/src/lib/server/process-restock.js +219 -0
  336. package/src/lib/server/process-restock.js.map +1 -0
  337. package/src/lib/server/product-card.d.ts +29 -0
  338. package/src/lib/server/product-card.js +54 -0
  339. package/src/lib/server/product-card.js.map +1 -0
  340. package/src/lib/server/product.d.ts +70 -0
  341. package/src/lib/server/product.js +105 -0
  342. package/src/lib/server/product.js.map +1 -0
  343. package/src/lib/server/promotion-hold.d.ts +144 -0
  344. package/src/lib/server/promotion-hold.js +174 -0
  345. package/src/lib/server/promotion-hold.js.map +1 -0
  346. package/src/lib/server/reconcile-stock.d.ts +106 -0
  347. package/src/lib/server/reconcile-stock.js +349 -0
  348. package/src/lib/server/reconcile-stock.js.map +1 -0
  349. package/src/lib/server/refund.d.ts +45 -0
  350. package/src/lib/server/refund.js +607 -0
  351. package/src/lib/server/refund.js.map +1 -0
  352. package/src/lib/server/related.d.ts +24 -0
  353. package/src/lib/server/related.js +104 -0
  354. package/src/lib/server/related.js.map +1 -0
  355. package/src/lib/server/reservation-availability.d.ts +23 -0
  356. package/src/lib/server/reservation-availability.js +111 -0
  357. package/src/lib/server/reservation-availability.js.map +1 -0
  358. package/src/lib/server/reserve-stock.d.ts +156 -0
  359. package/src/lib/server/reserve-stock.js +146 -0
  360. package/src/lib/server/reserve-stock.js.map +1 -0
  361. package/src/lib/server/reserve.d.ts +25 -0
  362. package/src/lib/server/reserve.js +426 -0
  363. package/src/lib/server/reserve.js.map +1 -0
  364. package/src/lib/server/restock-flag.d.ts +202 -0
  365. package/src/lib/server/restock-flag.js +449 -0
  366. package/src/lib/server/restock-flag.js.map +1 -0
  367. package/src/lib/server/reviews.d.ts +51 -0
  368. package/src/lib/server/reviews.js +132 -0
  369. package/src/lib/server/reviews.js.map +1 -0
  370. package/src/lib/server/site-page-enricher.d.ts +42 -0
  371. package/src/lib/server/site-page-enricher.js +149 -0
  372. package/src/lib/server/site-page-enricher.js.map +1 -0
  373. package/src/lib/server/site-page-resolver.d.ts +26 -0
  374. package/src/lib/server/site-page-resolver.js +223 -0
  375. package/src/lib/server/site-page-resolver.js.map +1 -0
  376. package/src/lib/server/stock-hold.d.ts +127 -0
  377. package/src/lib/server/stock-hold.js +258 -0
  378. package/src/lib/server/stock-hold.js.map +1 -0
  379. package/src/lib/server/storefront-tax-record.d.ts +22 -0
  380. package/src/lib/server/storefront-tax-record.js +218 -0
  381. package/src/lib/server/storefront-tax-record.js.map +1 -0
  382. package/src/lib/server/storefront-tax.d.ts +197 -0
  383. package/src/lib/server/storefront-tax.js +245 -0
  384. package/src/lib/server/storefront-tax.js.map +1 -0
  385. package/src/lib/server/stream.d.ts +25 -0
  386. package/src/lib/server/stream.js +191 -0
  387. package/src/lib/server/stream.js.map +1 -0
  388. package/src/lib/server/subscription-portal.d.ts +24 -0
  389. package/src/lib/server/subscription-portal.js +91 -0
  390. package/src/lib/server/subscription-portal.js.map +1 -0
  391. package/src/lib/server/supplier-outbox.d.ts +190 -0
  392. package/src/lib/server/supplier-outbox.js +342 -0
  393. package/src/lib/server/supplier-outbox.js.map +1 -0
  394. package/src/lib/server/supplier-update.d.ts +23 -0
  395. package/src/lib/server/supplier-update.js +289 -0
  396. package/src/lib/server/supplier-update.js.map +1 -0
  397. package/src/lib/server/tax-profile.d.ts +29 -0
  398. package/src/lib/server/tax-profile.js +40 -0
  399. package/src/lib/server/tax-profile.js.map +1 -0
  400. package/src/lib/server.d.ts +32 -0
  401. package/src/lib/server.js +311 -0
  402. package/src/lib/server.js.map +1 -0
  403. package/src/lib/site.d.ts +27 -0
  404. package/src/lib/site.js +134 -0
  405. package/src/lib/site.js.map +1 -0
  406. package/src/lib/utils/escape-html.d.ts +41 -0
  407. package/src/lib/utils/escape-html.js +41 -0
  408. package/src/lib/utils/escape-html.js.map +1 -0
  409. package/src/lib/utils/generate-preset-id.d.ts +19 -0
  410. package/src/lib/utils/generate-preset-id.js +25 -0
  411. package/src/lib/utils/generate-preset-id.js.map +1 -0
  412. package/src/lib/utils/member-continue.d.ts +45 -0
  413. package/src/lib/utils/member-continue.js +49 -0
  414. package/src/lib/utils/member-continue.js.map +1 -0
  415. package/src/lib/utils/use-storefront-purchase-event.d.ts +60 -0
  416. package/src/lib/utils/use-storefront-purchase-event.js +142 -0
  417. package/src/lib/utils/use-storefront-purchase-event.js.map +1 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/draft-order.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { connectLinkageIsReady } from '@aglyn/tenant-data-admin/server/stripe-account-mode'\nimport { resolveManualTaxRateId } from './manual-tax-rate'\nimport {\n type PromotionSlotHold,\n holdPromotionSlot,\n promotionHoldKey,\n} from './promotion-hold'\nimport {\n buildRoute,\n claimAttempt,\n Route,\n type AttemptClaim,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\n\n/**\n * Draft orders (AGL-287, Shopify parity): a manager builds an order in\n * the console and sends the buyer a payment link. Creates the order doc\n * (status `pending`, channel `draft`) with a sequential number, then a\n * Stripe Checkout session on the merchant's connected account whose\n * webhook completion flips the SAME doc to `paid`\n * (metadata type `commerce-draft`).\n */\nexport const draftOrderHandler: 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 productId = String(body.productId ?? '')\n const variantId = String(body.variantId ?? '')\n const quantity = Math.max(1, Math.min(99, Math.round(Number(body.quantity ?? 1))))\n const email = String(body.email ?? '').trim()\n // A code the MERCHANT types while composing the order (AGL-305). The\n // storefront doors read this same field name, so one resolver answers it the\n // same way whoever pressed the button.\n const couponCode = String(body.couponCode ?? '').trim()\n // One draft attempt, minted by the console dialog (AGL-1697). Node\n // lowercases incoming headers, but read both spellings — the plugin API\n // request type makes no promise about casing.\n const idempotencyKey = String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n ).trim().slice(0, 200)\n if (!hostId || !productId) {\n return res.status(400).json({ error: 'Missing hostId or productId' })\n }\n\n let claim: AttemptClaim | null = null\n /**\n * The redemption slot this attempt reserved (AGL-305), hoisted so every\n * refusal below the claim — and the catch — can hand it back. A throw after\n * the hold is placed is exactly the case where a slot would otherwise stand\n * invisibly against the merchant's cap until its TTL lapsed, and this path\n * rolls its order document back on two of those refusals already.\n */\n let discountSlot: PromotionSlotHold | null = null\n let discountHoldKey = ''\n const releaseDiscountSlot = async (): Promise<void> => {\n const slot = discountSlot\n discountSlot = null\n discountHoldKey = ''\n if (slot) await slot.release()\n }\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // AN ALLOWLIST (AGL-2262), matching `cancel-order.ts`, `fulfill-order.ts`\n // and the Firestore rules, whose host-write predicate is\n // `hostMemberRole(hostId) in ['admin','editor']`. The old\n // `!role || role === 'viewer'` denylist caught the stranger but admitted\n // every OTHER string — a legacy value, a typo, any role added later — on\n // the one route that mints a live Stripe payment link. `HostAccessRole`\n // has since grown an `author` (AGL-2334), which this allowlist refuses on\n // purpose — an author edits content and does not mint payment links — and\n // which the old denylist would have admitted. That is the allowlist form\n // earning its keep on a union that changed under it.\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return res.status(403).json({ error: 'Not permitted' })\n }\n const productSnapshot = await hostRef\n .collection('products')\n .doc(productId)\n .get()\n const raw = productSnapshot.data() as any\n if (!raw || raw.deletedAt) {\n return res.status(404).json({ error: 'Unknown product' })\n }\n const product = CommerceModel.liftLegacyProduct(raw)\n const variant = variantId\n ? product.variants.find((item) => item.id === variantId)\n : product.variants[0]\n if (!variant) return res.status(404).json({ error: 'Unknown variant' })\n // A variant with no price yet (AGL-2916) cannot be invoiced: the link\n // would ask for nothing, or for no amount at all.\n if (!CommerceModel.variantHasPrice(variant)) {\n return res.status(400).json({ error: `Set a price for ${product.name} before selling it.` })\n }\n\n // Merchant account like the storefront checkout (AGL-284).\n const ownerOrg = await getOrgForHost(hostId)\n // Plan gate, re-asked per request exactly as the storefront checkout\n // asks it (AGL-1873, the AGL-481 pattern): a free or lapsed org must not\n // keep minting payment links — at the free plan's 0% transaction fee —\n // through the one commerce door that skipped the entitlement. Sits\n // ABOVE the attempt claim with the other deterministic refusals, so it\n // never burns the merchant's idempotency key.\n if (!Aglyn.checkEntitlement(ownerOrg?.org as any, 'commerce')) {\n return res.status(403).json({ error: 'Selling is not enabled' })\n }\n const ownerId = ownerOrg?.org?.ownerUid\n const ownerProfile = ownerId\n ? await firestore.collection('profiles').doc(String(ownerId)).get()\n : null\n const accountId = ownerProfile?.get('stripeAccountId')\n if (\n !connectLinkageIsReady(\n {\n accountId,\n chargesEnabled: ownerProfile?.get('stripeChargesEnabled'),\n accountLivemode: ownerProfile?.get('stripeAccountLivemode'),\n },\n { subject: `draft order host ${hostId}` },\n )\n ) {\n return res.status(409).json({ error: 'Payments are not set up yet' })\n }\n\n // Stripe returns the merchant to the console Products page. This was\n // `/{hostDocId}/products`, the pre-AGL-621/622 shape, so paying (or\n // cancelling) a draft order landed on a 404 (AGL-685). Console products\n // is the plugin route keyed by org slug + host SUBDOMAIN; server code\n // cannot call useConsoleHostRoute, so resolve them here. Without both,\n // fall back to the origin root rather than a fabricated dead path.\n const consoleSubdomain = (\n await firestore.collection('hostIndex').doc(hostId).get()\n ).get('subdomain') as string | undefined\n const consoleOrgSlug = ownerOrg?.org?.slug as string | undefined\n const origin = req.headers.origin ?? `https://${req.headers.host}`\n const consoleProductsUrl =\n consoleOrgSlug && consoleSubdomain\n ? `${origin}${buildRoute(Route.HOST_PLUGIN, {\n orgSlug: consoleOrgSlug,\n host: consoleSubdomain,\n pluginSlug: 'products',\n })}`\n : origin\n\n // WHAT THE COUNT SAYS, said out loud (AGL-2452).\n //\n // This handler contained no `canPurchase` and no `stockShortfall` — no\n // reference to inventory of any kind. It is the door that mints a LIVE,\n // payable Stripe link, and it would mint one for a sold-out variant whose\n // merchant had chosen `oversellPolicy: 'deny'`, with the `commerce-draft`\n // webhook branch then completing it into a `paid` order. `pos-order.ts`'s\n // own comment asserts \"every storefront door gates on it\"; that claim was\n // false for this one.\n //\n // WARN, NEVER BLOCK, matching the register (AGL-2357, the decision).\n // Both of these are MERCHANT-initiated doors rather than shopper-initiated\n // ones — the merchant may well be taking a deliberate pre-order or\n // backorder — so a stale count must not refuse a sale the merchant means to\n // make. What the merchant is entitled to is to be TOLD, which is the part\n // that was missing entirely. The refusal variant is a separate decision and\n // is not taken here.\n //\n // Computed from the SERVER's product document, and reported on the same\n // `stockWarnings` key and in the same `StockShortfall` shape the register\n // already returns, so one console surface can read either door.\n const shortfall = CommerceModel.stockShortfall(\n product,\n variantId || product.variants[0]?.id,\n quantity,\n )\n const stockWarnings: CommerceModel.StockShortfall[] = shortfall\n ? [\n {\n productId,\n ...(variantId ? { variantId } : {}),\n name: product.name,\n requested: quantity,\n available: shortfall.available,\n },\n ]\n : []\n\n const unitAmountCents = Math.round(Number(variant.priceUsd) * 100)\n const lineItems: CommerceModel.OrderLineItem[] = [\n {\n productId,\n ...(variantId ? { variantId } : {}),\n name: product.name,\n ...(variant.sku ? { sku: variant.sku } : {}),\n productType: product.type,\n quantity,\n unitAmountCents,\n },\n ]\n const itemsCents = unitAmountCents * quantity\n // THE DISCOUNTS HUB, ON THIS PATH TOO (AGL-305).\n //\n // `hosts/{hostId}/discounts` reached the cart and buy-now and stopped\n // there, so a store running \"Summer sale, 10% off\" sold at 10% off through\n // both storefront doors and at FULL price the moment the merchant invoiced\n // the same buyer for the same goods through a payment link. No code has to\n // be typed for that gap to open: an automatic promotion applies itself on\n // the storefront and applied itself nowhere here, so the merchant's own\n // payment link quietly undercut — and here overcharged against — their own\n // advertised price.\n //\n // Resolved through the SAME `resolveDiscount` the other doors use, so one\n // code cannot mean two amounts.\n //\n // RESOLVED BEFORE THE TAX BLOCK BELOW, and that ordering is the whole\n // point rather than a convenience: the manual rate is computed against\n // `chargedItemsCents`, so the discount lands BEFORE tax and the taxable\n // base is the discounted one. It has to be — the session applies that same\n // rate as `line_items[0][tax_rates][0]`, which Stripe evaluates against the\n // line amount it actually charges. Reducing the line while taxing the list\n // price would make our stored `taxCents` disagree with the tax Stripe\n // collects, on every discounted draft.\n const draftDiscountLines = [{ productId, amountCents: itemsCents }]\n const hubDiscounts = await hostRef.collection('discounts').limit(100).get()\n const resolvedDiscount = CommerceModel.resolveDiscount(\n hubDiscounts.docs.map((docSnapshot) => ({\n ...(docSnapshot.data() as CommerceModel.HostDiscount),\n $id: docSnapshot.id,\n })),\n {\n ...(couponCode ? { code: couponCode } : {}),\n subtotalCents: itemsCents,\n productIds: [productId],\n lines: draftDiscountLines,\n },\n )\n // Above the claim and above the order write with every other deterministic\n // refusal, so a merchant who fixes the code and presses Send again strands\n // no `pending` draft and burns no key. A code that RESOLVES but confers\n // nothing leaves through here too — `codeProblem` carries the benefit's own\n // reason — which is what stops this door repeating the defect that charged\n // full shipping on a free-shipping code.\n if (resolvedDiscount?.codeProblem) {\n return res.status(400).json({ error: resolvedDiscount.codeProblem })\n }\n const appliedDiscountId =\n resolvedDiscount && resolvedDiscount.benefit.kind !== 'none'\n ? resolvedDiscount.discountId\n : ''\n const discountCents = appliedDiscountId ? resolvedDiscount!.discountCents : 0\n // Stripe's charge minimum is 50¢ — never price a payment link below it,\n // the same floor buy-now applies.\n const chargedItemsCents = discountCents\n ? Math.max(50, itemsCents - discountCents)\n : itemsCents\n // What was ACTUALLY taken off, after that floor. The stored totals record\n // this rather than the resolver's figure, so the parts sum to the total on\n // a draft the floor moved.\n const appliedDiscountCents = itemsCents - chargedItemsCents\n // The fee and `totals` are both built BELOW the shipping plan (AGL-2152):\n // Stripe's card cost rides the whole payment-link total, so neither can be\n // known until the tax (AGL-1953) and the shipping options are.\n\n // Shipping (AGL-1792), from the same settings document the two storefront\n // paths read. This handler contained no `shipping` string at all: a\n // merchant who configured zones and rates collected them on a cart\n // (AGL-1707) and on buy-now (AGL-1720), and nothing when they invoiced the\n // same buyer for the same parcel through a payment link. The session\n // collected no address either, so the merchant was not even told where to\n // send it — the webhook records one now that Stripe is asked for it.\n //\n // The premise AGL-1792 filed this under was that \"the destination IS known\n // — the merchant typed it\". It is not: the draft dialog collects a product,\n // a variant, a quantity and an email, and this handler reads exactly those.\n // So the destination is as unknown here as it is in the cart, and the same\n // asking machinery applies rather than none of it.\n //\n // CONDITIONAL on the product being physical, exactly as buy-now is: this\n // dialog invoices downloads and consulting too, and charging that buyer\n // postage would be worse than the bug. A missing `type` reads as physical,\n // matching the fee ladder above — the two reads must not disagree about\n // what a part-migrated doc is. The one-time condition buy-now also carries\n // is structural here: this path only ever builds `mode: 'payment'`.\n //\n // RESOLVED BEFORE THE ORDER DOCUMENT, because the plan can refuse and the\n // order is written before Stripe is called. Refusing after it would strand\n // a `pending` draft on the merchant's orders list for every attempt —\n // this path's version of the orphaned coupon AGL-1721 kept out of the cart.\n const storeSettings = await hostRef\n .collection('settings')\n .doc('store')\n .get()\n const shippingSettings = storeSettings.get('shipping') as\n CommerceModel.ShippingSettings | undefined\n\n // Taxes (AGL-1953), from the same settings document. This handler had no\n // tax code at all in either mode, so a merchant who invoiced a buyer for\n // the same product they sell on the storefront charged them no tax — the\n // cart's defect, one door over, and worse here because the merchant\n // composed this order deliberately and would reasonably assume it matched\n // their store.\n //\n // Origin-based, exactly as buy-now and the cart resolve it. The AGL-1792\n // note above already established the premise: this dialog collects a\n // product, a variant, a quantity and an email, so the DESTINATION is as\n // unknown here as it is in the cart.\n //\n // Computed pure and BEFORE the claim so the stored totals can carry it;\n // the Stripe object it needs is minted below the point of no return.\n const taxSettings = (storeSettings.get('tax') ?? {}) as CommerceModel.TaxSettings\n // AGL-1999: an unset tax mode is NOT a decision, and it must not sell.\n // `mode` was `undefined` for every store whose owner never opened the\n // Taxes card — the default state of every new storefront — and each\n // branch below tested for a specific string, so no branch was taken, no\n // tax was computed, and the shopper was charged an untaxed total. See\n // `commerce-tax-decision.ts` for why refusing beats defaulting to either\n // mode. `mode: 'none'` is the explicit opt-out and passes straight\n // through.\n const taxDecision = CommerceModel.storefrontTaxDecision({\n settings: taxSettings,\n taxExempt: product.taxExempt,\n })\n if (taxDecision.kind === 'undecided') {\n return res\n .status(409)\n .json({ error: CommerceModel.STOREFRONT_TAX_UNDECIDED_MESSAGE })\n }\n const taxMisconfigured =\n CommerceModel.storefrontTaxMisconfiguration(taxSettings)\n if (taxMisconfigured) {\n // AGL-2145: the merchant DECIDED to collect and the sale would have\n // charged zero anyway — an unfinished settings card, not a\n // jurisdiction miss. Refused in the same words and the same place as\n // the undecided case above.\n return res.status(409).json({ error: taxMisconfigured })\n }\n const useStripeTax = taxDecision.kind === 'stripe-automatic'\n const manualRate =\n taxDecision.kind === 'manual' &&\n !taxSettings.pricesIncludeTax\n ? CommerceModel.resolveTaxRate(taxSettings, taxSettings.origin ?? {})\n : null\n // THE DISCOUNTED BASE (AGL-305). `chargedItemsCents` is what the line\n // will actually be worth, and the session applies this same rate to that\n // line as a Stripe Tax Rate — so taxing `itemsCents` here would record a\n // figure Stripe never charges.\n const taxCents = manualRate\n ? CommerceModel.computeTaxCents(chargedItemsCents, manualRate.pct)\n : 0\n // Stripe Tax mode leaves this 0 at composition time and the webhook folds\n // the computed figure in — the same additive shape AGL-1792 used for\n // shipping, and for the same reason: only Stripe knows it.\n const shippingPlan =\n (product.type ?? 'physical') === 'physical'\n ? CommerceModel.planCheckoutShipping(\n shippingSettings,\n {\n subtotalCents: itemsCents,\n totalGrams:\n Math.max(0, Number(variant.weightGrams ?? 0)) * quantity,\n },\n body.shippingCountry,\n )\n : { countries: CommerceModel.CHECKOUT_SHIPPING_COUNTRIES, options: [] }\n if (shippingPlan.refusal === 'destination-required') {\n return res.status(400).json({\n error: 'Choose where this order ships to.',\n needsShippingCountry: true,\n shippingCountries: [...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES],\n })\n }\n if (shippingPlan.refusal === 'destination-unserved') {\n const declared = CommerceModel.normalizeCheckoutShippingCountry(\n body.shippingCountry,\n )\n return res.status(409).json({\n error: `This store does not ship to ${\n CommerceModel.CHECKOUT_SHIPPING_COUNTRY_NAMES[declared as string] ??\n 'that country'\n }.`,\n needsShippingCountry: true,\n shippingCountries: [...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES],\n })\n }\n // No rate of the merchant's reaches this order (AGL-2232). Above the\n // order write and the payment link, like every other refusal here, so a\n // manager who fixes the tier table and presses Send again strands nothing.\n if (shippingPlan.refusal === 'cart-unpriceable') {\n return res\n .status(409)\n .json({ error: CommerceModel.CART_UNPRICEABLE_SHIPPING_MESSAGE })\n }\n // FREE SHIPPING IS A ZEROED RATE, NOT A REDUCTION (AGL-305), the same\n // construction the cart uses and for the same reason: nothing has picked a\n // rate yet, so there is no amount to take off. The buyer chooses after the\n // link is minted, so the only exact answer is to offer every rate at zero.\n //\n // Every rate rather than the cheapest, because `free_shipping` carries no\n // field naming one — and zeroing them all keeps the fee, the transfer floor\n // and the ceiling below honest, since all three read these same options.\n //\n // Derived from `shippingPlan.options` and read EVERYWHERE below in its\n // place; a reader that reached past this to `shippingPlan.options` would\n // price carriage the buyer is not being charged for.\n const shippingOptions =\n resolvedDiscount?.freeShipping === true\n ? shippingPlan.options.map((option) => ({ ...option, amountCents: 0 }))\n : shippingPlan.options\n\n // THE PLATFORM FEE (AGL-2152) — the advertised take PLUS Stripe's card\n // cost, passed through at cost. A payment link is a destination charge, so\n // Stripe debits 2.9% + 30¢ from the PLATFORM's balance; the old take-only\n // figure meant every tier carrying a 0% rate invoiced a buyer at a loss to\n // Aglyn, and Starter's 2% is below 2.9% so it lost money at every size too.\n //\n // `?? 'physical'` (AGL-2251), matching `checkout.ts` and the cart. Without\n // it a product doc carrying no `type` fell to `resolveTransactionFeePct`'s\n // digital branch, so a merchant's payment link took a different cut of the\n // same product than their storefront did.\n //\n // The base is the whole card total: the goods, the manual tax line, and the DEAREST shipping\n // option the link offers (the buyer picks after the link is minted and\n // `application_fee_amount` is fixed at creation, so reaching for the\n // cheapest would put the difference back on Aglyn). A store on Stripe Tax\n // is the one residual — that tax is computed inside Stripe afterwards.\n const shippingCeilingCents = shippingOptions.reduce(\n (most, option) =>\n Math.max(most, Math.max(0, Number(option.amountCents ?? 0))),\n 0,\n )\n // Both bases are the DISCOUNTED goods (AGL-305). The platform take is a\n // cut of what the merchant actually sells for, and Stripe's card cost is\n // passed through on what the card actually runs for — reading `itemsCents`\n // here would invoice the merchant a fee on money nobody paid.\n const feeCents = Aglyn.resolveTransactionFeeCents(\n ownerOrg?.org as any,\n product.type ?? 'physical',\n chargedItemsCents,\n chargedItemsCents + taxCents + shippingCeilingCents,\n )\n // Stripe Tax mode leaves the tax 0 at composition time and the webhook\n // folds the computed figure in — the same additive shape AGL-1792 used for\n // shipping, and for the same reason: only Stripe knows it.\n const totals = CommerceModel.computeOrderTotals(lineItems, {\n feeCents,\n taxCents,\n // The line item still carries the LIST price, so the discount has to be\n // a named part of the totals or `itemsCents - discountCents + tax` would\n // not be the number on the payment link.\n discountCents: appliedDiscountCents,\n })\n\n // THE LINK CHARGES `chargedItemsCents`, EXACTLY (the AGL-2159 construction,\n // reused here because this path grew the same problem the moment it grew a\n // discount).\n //\n // A Stripe line is `quantity` units at ONE integer `unit_amount`, so it can\n // only express totals divisible by `quantity` — and a percentage discount\n // does not respect that. Dividing and multiplying back misses the intended\n // total by up to `quantity / 2` cents in either direction, which on this\n // path is worse than on buy-now: the frozen `totals` above are written to\n // the order document BEFORE the session is minted, so a link that charged\n // a different number would leave the merchant's own books disagreeing with\n // what their buyer paid, permanently and silently.\n //\n // So when the total does not divide evenly, the line becomes ONE unit at\n // the exact total with the count moved into the display name. The real\n // quantity is carried by the order document's line item, which is\n // untouched, so nothing downstream can tell the difference.\n //\n // The even case — every undiscounted draft, and most discounted ones —\n // keeps the per-unit shape byte for byte.\n const evenUnitAmountCents = Math.floor(chargedItemsCents / quantity)\n const remainderCents = chargedItemsCents - evenUnitAmountCents * quantity\n const chargedQuantity = remainderCents === 0 ? quantity : 1\n const chargedUnitAmountCents =\n remainderCents === 0 ? evenUnitAmountCents : chargedItemsCents\n const chargedLineName = `${product.name}${\n remainderCents === 0 ? '' : ` × ${quantity}`\n }`.slice(0, 120)\n\n // Point of no return (AGL-1697): everything past here writes an order and\n // mints a live payment link. Every deterministic refusal — unknown\n // product, payments not set up, the shipping-destination ask — sits above\n // this line, so none of them burns the key: the merchant fixes the input\n // and presses the same button. Before the claim, a double-submit minted a\n // SECOND order doc, burned a second sequential number, and returned two\n // live payment links bound to different orders, both payable.\n const claimed = await claimAttempt(firestore, {\n kind: 'commerce-draft',\n scopeId: hostId,\n orgId: String(ownerOrg?.org?.id ?? ''),\n key: idempotencyKey,\n busyMessage: 'This draft order is already being created',\n })\n if ('replay' in claimed) {\n return res.status(claimed.replay.status).json(claimed.replay.body)\n }\n claim = claimed.claim\n\n // THE REDEMPTION SLOT IS RESERVED HERE (AGL-305), on the same terms the\n // storefront doors reserve it.\n //\n // A payment link lives until the buyer pays it, so between this handler and\n // the `commerce-draft` webhook branch that settles the slot there is a\n // window measured in days — far wider than a Checkout Session's. Reading\n // `redemptions` and hoping would let a merchant mint ten links against a\n // cap of one and have all ten pay.\n //\n // BELOW the claim because the hold is keyed by the attempt: a retry of one\n // attempt must be able to re-claim the slot it already holds rather than be\n // refused by it. An uncapped promotion writes nothing and returns an empty\n // `holdKey`, which is what tells the webhook to fall back to the plain\n // increment.\n if (appliedDiscountId) {\n const slot = await holdPromotionSlot({\n firestore,\n ref: hostRef.collection('discounts').doc(appliedDiscountId),\n holdKey: promotionHoldKey(claimed.claim.stripeKey),\n label: `draft discount ${appliedDiscountId}`,\n })\n if (!slot.ok) {\n // Refused rather than quietly repriced, and that is deliberate for the\n // AUTOMATIC case too: the merchant composed this order at a price the\n // promotion was part of, and minting the link at full price would\n // invoice their buyer more than the store advertises without saying so.\n // Nothing has been written yet, so the key goes back and the retry\n // prices correctly — `resolveDiscount` counts live holds and simply\n // stops offering an exhausted promotion.\n await claim.release()\n return res.status(409).json({\n error:\n couponCode && resolvedDiscount?.discount.code\n ? CommerceModel.PROMOTION_EXHAUSTED_MESSAGE\n : CommerceModel.PROMOTION_UNAVAILABLE_MESSAGE,\n })\n }\n if (slot.holdKey) {\n discountSlot = slot\n discountHoldKey = slot.holdKey\n }\n }\n\n // Order doc first (transactional number), then the payment link.\n const orderRef = hostRef.collection('orders').doc()\n const counterRef = hostRef.collection('counters').doc('orders')\n await firestore.runTransaction(async (transaction) => {\n const counter = await transaction.get(counterRef)\n const number = Number(counter.get('next') ?? 1)\n transaction.set(counterRef, { next: number + 1 }, { merge: true })\n transaction.set(orderRef, {\n number,\n status: 'pending',\n channel: 'draft',\n lineItems,\n totals,\n // WHICH TAX REGIME THIS ORDER IS COMPOSED UNDER (AGL-2451), from the\n // decision taken above rather than from the frozen `taxCents` — a\n // Stripe Tax draft freezes 0 there and only the paid session knows the\n // figure, so a mode read back off the amount would call it `none`.\n //\n // Stamped at composition so a draft that is never paid still says what\n // it was priced under, and RESTATED by the `commerce-draft` webhook\n // branch from the session that actually charged it. The webhook's is\n // authoritative — it has Stripe's computed tax in hand — and for a\n // manual draft the two agree by construction.\n taxMode: CommerceModel.storefrontTaxModeForDecision(\n taxDecision,\n taxCents,\n ),\n customerEmail: email || null,\n timeline: [\n {\n atMs: Date.now(),\n event: 'draft',\n detail: `Draft created by ${decoded.email ?? decoded.uid}`,\n },\n ],\n createdAtMs: Date.now(),\n createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n })\n })\n\n // The tax rate is minted here, BELOW the claim, because it creates a real\n // Stripe object (AGL-1953). Cached per host, so it is usually a read.\n let draftTaxRateId = ''\n if (taxCents > 0 && manualRate) {\n draftTaxRateId =\n (await resolveManualTaxRateId({\n hostRef,\n taxPct: manualRate.pct,\n taxLabel: manualRate.label || `Tax (${manualRate.pct}%)`,\n ...(claim.stripeKey\n ? { headers: { 'Idempotency-Key': `${claim.stripeKey}-tax-rate` } }\n : {}),\n })) ?? ''\n if (!draftTaxRateId) {\n // A VISIBLE refusal rather than an untaxed payment link — the silent\n // under-collection is the defect. The order doc is rolled back the\n // same way the session failure below rolls it back.\n await orderRef.delete().catch(() => undefined)\n await releaseDiscountSlot()\n await claim.release()\n return res.status(502).json({ error: 'Payment link creation failed' })\n }\n }\n const params = new URLSearchParams({\n mode: 'payment',\n ...(useStripeTax ? { 'automatic_tax[enabled]': 'true' } : {}),\n ...(draftTaxRateId ? { 'line_items[0][tax_rates][0]': draftTaxRateId } : {}),\n 'line_items[0][quantity]': String(chargedQuantity),\n 'line_items[0][price_data][currency]': 'usd',\n 'line_items[0][price_data][unit_amount]': String(chargedUnitAmountCents),\n 'line_items[0][price_data][product_data][name]': chargedLineName,\n // THE CONNECT SPLIT (AGL-1956). A Stripe Tax payment link computes its\n // tax against AGLYN's registrations and Aglyn remits it (AGL-1904), so\n // the merchant gets a FIXED `transfer_data[amount]` and no\n // `application_fee_amount`: the fee form transfers `amount_total − fee`,\n // and `amount_total` includes that tax. A manual-rate or untaxed link is\n // unchanged. See `commerce-connect-transfer.ts`.\n ...CommerceModel.destinationChargeParams({\n accountId: String(accountId),\n feeCents,\n taxOwner: useStripeTax ? 'platform' : 'merchant',\n // The DISCOUNTED goods (AGL-305): this is what the merchant is\n // transferred, and paying out the list price on a discounted link\n // would move money Stripe never collected.\n merchantGoodsCents: chargedItemsCents,\n shippingFloorCents: CommerceModel.shippingFloorCents(shippingOptions),\n }),\n ...(email ? { customer_email: email } : {}),\n success_url: `${consoleProductsUrl}?draft=paid`,\n cancel_url: `${consoleProductsUrl}?draft=canceled`,\n 'metadata[type]': 'commerce-draft',\n 'metadata[hostId]': hostId,\n 'metadata[orderId]': orderRef.id,\n 'metadata[productId]': productId,\n ...(variantId ? { 'metadata[variantId]': variantId } : {}),\n 'metadata[feeCents]': String(feeCents),\n // WHAT THE WEBHOOK SETTLES (AGL-305), in the field names the\n // `checkout.session.completed` branch already reads for the cart. The\n // hold key's ABSENCE is what tells it to fall back to the unconditional\n // increment, which is right for an uncapped promotion.\n ...(appliedDiscountId\n ? { 'metadata[discountId]': appliedDiscountId }\n : {}),\n ...(discountHoldKey ? { 'metadata[discountHoldKey]': discountHoldKey } : {}),\n // See the AGL-1956 note in `checkout.ts` — recorded only on the shape\n // where the merchant's payout is no longer the whole charge.\n ...(useStripeTax\n ? {\n 'metadata[transferCents]': String(\n CommerceModel.platformLiableTransferCents({\n feeCents,\n merchantGoodsCents: chargedItemsCents,\n shippingFloorCents:\n CommerceModel.shippingFloorCents(shippingOptions),\n }),\n ),\n 'metadata[transferShippingCents]': String(\n CommerceModel.shippingFloorCents(shippingOptions),\n ),\n }\n : {}),\n })\n // Both keys or neither (AGL-1720's rule, inherited). Stripe will not apply\n // a shipping rate without an address to ship to, and a merchant who\n // configured nothing plans to no options and so gets neither — a payment\n // link byte-identical to the one this handler built before shipping\n // existed on it.\n if (shippingOptions.length > 0) {\n CommerceModel.appendShippingAddressCollectionParams(\n params,\n shippingPlan.countries,\n )\n CommerceModel.appendCheckoutShippingParams(params, shippingOptions)\n }\n const response = await fetch(\n 'https://api.stripe.com/v1/checkout/sessions',\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n // The half that is a live payment link (AGL-1697). Stripe replays\n // the existing session for a repeated key instead of opening a\n // second one on the merchant's account, which covers the window\n // where our claim is written but the response never arrives.\n ...(claim.stripeKey ? { 'Idempotency-Key': claim.stripeKey } : {}),\n },\n body: params.toString(),\n },\n )\n const session = (await response.json()) as {\n url?: string\n id?: string\n error?: any\n }\n if (!response.ok || !session.url) {\n console.error('Stripe draft-order error', session.error)\n await orderRef.delete().catch(() => undefined)\n // The draft did not happen — hand the key back rather than locking this\n // dialog out over one flaky moment. The retry re-derives the SAME\n // digest, so if Stripe did create the session it replays it.\n await releaseDiscountSlot()\n await claim.release()\n return res.status(502).json({ error: 'Payment link creation failed' })\n }\n await orderRef.set(\n { checkoutSessionId: session.id, paymentLinkUrl: session.url },\n { merge: true },\n )\n // Spread on the same terms as the register's: present only when there is\n // something to say, so a caller can test the key rather than a length.\n const payload = {\n orderId: orderRef.id,\n url: session.url,\n ...(stockWarnings.length > 0 ? { stockWarnings } : {}),\n }\n await claim.record(200, payload)\n return res.status(200).json(payload)\n } catch (error) {\n console.error(error)\n // Release on the way out so a transient failure does not strand the key\n // (AGL-1691's rule). The order write may or may not have landed; the\n // merchant reconciles from the orders list, the same position they were\n // in before this endpoint had a claim at all. The redemption slot goes\n // back for the same reason — a throw is the one path that would otherwise\n // leave it standing against the cap until its TTL lapsed.\n await releaseDiscountSlot()\n await claim?.release()\n return res.status(500).json({ error: 'Draft order failed' })\n }\n}\n"],"names":["Aglyn","CommerceModel","firebaseAdmin","getOrgForHost","connectLinkageIsReady","resolveManualTaxRateId","holdPromotionSlot","promotionHoldKey","buildRoute","claimAttempt","Route","draftOrderHandler","req","res","body","method","status","json","error","process","env","STRIPE_SECRET_KEY","authorization","String","headers","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","productId","variantId","quantity","Math","max","min","round","Number","email","trim","couponCode","idempotencyKey","claim","discountSlot","discountHoldKey","releaseDiscountSlot","slot","release","hostSnapshot","storeSettings","taxSettings","product","variant","ownerOrg","decoded","app","auth","verifyIdToken","firestore","hostRef","collection","doc","get","exists","memberRole","uid","productSnapshot","raw","data","deletedAt","liftLegacyProduct","variants","find","item","id","variantHasPrice","name","checkEntitlement","org","ownerId","ownerUid","ownerProfile","accountId","chargesEnabled","accountLivemode","subject","consoleSubdomain","consoleOrgSlug","slug","origin","host","consoleProductsUrl","HOST_PLUGIN","orgSlug","pluginSlug","shortfall","stockShortfall","stockWarnings","requested","available","unitAmountCents","priceUsd","lineItems","sku","productType","type","itemsCents","draftDiscountLines","amountCents","hubDiscounts","limit","resolvedDiscount","resolveDiscount","docs","map","docSnapshot","$id","code","subtotalCents","productIds","lines","codeProblem","appliedDiscountId","benefit","kind","discountId","discountCents","chargedItemsCents","appliedDiscountCents","shippingSettings","taxDecision","storefrontTaxDecision","settings","taxExempt","STOREFRONT_TAX_UNDECIDED_MESSAGE","taxMisconfigured","storefrontTaxMisconfiguration","useStripeTax","manualRate","pricesIncludeTax","resolveTaxRate","taxCents","computeTaxCents","pct","shippingPlan","planCheckoutShipping","totalGrams","weightGrams","shippingCountry","countries","CHECKOUT_SHIPPING_COUNTRIES","options","refusal","needsShippingCountry","shippingCountries","declared","normalizeCheckoutShippingCountry","CHECKOUT_SHIPPING_COUNTRY_NAMES","CART_UNPRICEABLE_SHIPPING_MESSAGE","shippingOptions","freeShipping","option","shippingCeilingCents","reduce","most","feeCents","resolveTransactionFeeCents","totals","computeOrderTotals","evenUnitAmountCents","floor","remainderCents","chargedQuantity","chargedUnitAmountCents","chargedLineName","claimed","scopeId","orgId","key","busyMessage","replay","ref","holdKey","stripeKey","label","ok","discount","PROMOTION_EXHAUSTED_MESSAGE","PROMOTION_UNAVAILABLE_MESSAGE","orderRef","counterRef","runTransaction","transaction","counter","number","set","next","merge","channel","taxMode","storefrontTaxModeForDecision","customerEmail","timeline","atMs","Date","now","event","detail","createdAtMs","createdAt","FieldValue","serverTimestamp","draftTaxRateId","taxPct","taxLabel","delete","catch","params","URLSearchParams","mode","destinationChargeParams","taxOwner","merchantGoodsCents","shippingFloorCents","customer_email","success_url","cancel_url","platformLiableTransferCents","appendShippingAddressCollectionParams","appendCheckoutShippingParams","response","fetch","Authorization","toString","session","url","console","checkoutSessionId","paymentLinkUrl","payload","orderId","record"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,sBAAqB;AAC5C,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,sDAAqD;AAC3F,SAASC,sBAAsB,QAAQ,uBAAmB;AAC1D,SAEEC,iBAAiB,EACjBC,gBAAgB,QACX,sBAAkB;AACzB,SACEC,UAAU,EACVC,YAAY,EACZC,KAAK,QAGA,sBAAqB;AAE5B;;;;;;;CAOC,GACD,OAAO,MAAMC,oBAAsC,OAAOC,KAAKC;QAOhCD,4BAM4BA,WACnCE,cACGA,iBACAA,iBACmCA,gBACvCA,aAIKA,kBAKxBF,MAAAA;IA1BF,IAAIA,IAAIG,MAAM,KAAK,QAAQ;QACzB,OAAOF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SAAS7C,EAAE,IAAI,CAACiD,QAAQC,GAAG,EAAE;YAChCC,QAAQ7N,KAAK,CAAC,4BAA4B2N,QAAQ3N,KAAK;YACvD,MAAM8K,SAAS0B,MAAM,GAAGC,KAAK,CAAC,IAAM9L;YACpC,wEAAwE;YACxE,kEAAkE;YAClE,6DAA6D;YAC7D,MAAMmB;YACN,MAAMH,MAAMK,OAAO;YACnB,OAAOrC,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO;YAA+B;QACtE;QACA,MAAM8K,SAASM,GAAG,CAChB;YAAE0C,mBAAmBH,QAAQhK,EAAE;YAAEoK,gBAAgBJ,QAAQC,GAAG;QAAC,GAC7D;YAAEtC,OAAO;QAAK;QAEhB,yEAAyE;QACzE,uEAAuE;QACvE,MAAM0C,UAAU;YACdC,SAASnD,SAASnH,EAAE;YACpBiK,KAAKD,QAAQC,GAAG;WACZ1I,cAAcxE,MAAM,GAAG,IAAI;YAAEwE;QAAc,IAAI,CAAC;QAEtD,MAAMvD,MAAMuM,MAAM,CAAC,KAAKF;QACxB,OAAOrO,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAACiO;IAC9B,EAAE,OAAOhO,OAAO;QACd6N,QAAQ7N,KAAK,CAACA;QACd,wEAAwE;QACxE,qEAAqE;QACrE,wEAAwE;QACxE,uEAAuE;QACvE,0EAA0E;QAC1E,0DAA0D;QAC1D,MAAM8B;QACN,OAAMH,yBAAAA,MAAOK,OAAO;QACpB,OAAOrC,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;AACF,EAAC"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import type { PluginApiHandler } from '@aglyn/aglyn/server';
18
+ /**
19
+ * Google Merchant Center product feed (AGL-299): RSS 2.0 with the g:
20
+ * namespace over active products — one item per product (default
21
+ * variant pricing; per-variant feeds can come later). Submit
22
+ * `https://{site}/api/commerce/feed?hostId={id}` in Merchant Center.
23
+ */
24
+ export declare const feedHandler: PluginApiHandler;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { _ as _extends } from "@swc/helpers/_/_extends";
17
+ import * as CommerceModel from "../model/index.js";
18
+ import { firebaseAdmin } from "@aglyn/tenant-data-admin";
19
+ function escapeXml(text) {
20
+ return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
21
+ }
22
+ /**
23
+ * Google Merchant Center product feed (AGL-299): RSS 2.0 with the g:
24
+ * namespace over active products — one item per product (default
25
+ * variant pricing; per-variant feeds can come later). Submit
26
+ * `https://{site}/api/commerce/feed?hostId={id}` in Merchant Center.
27
+ */ export const feedHandler = async (req, res)=>{
28
+ var _req_query_hostId;
29
+ const hostId = String((_req_query_hostId = req.query.hostId) != null ? _req_query_hostId : '');
30
+ if (!hostId) return res.status(400).send('Missing hostId');
31
+ try {
32
+ var _req_headers_host;
33
+ const firestore = firebaseAdmin.app().firestore();
34
+ const hostRef = firestore.collection('hosts').doc(hostId);
35
+ const productsSnapshot = await hostRef.collection('products').limit(500).get();
36
+ const requestHost = String((_req_headers_host = req.headers['host']) != null ? _req_headers_host : '');
37
+ const base = `https://${requestHost}`;
38
+ const items = productsSnapshot.docs.map((docSnapshot)=>_extends({}, CommerceModel.liftLegacyProduct(docSnapshot.data()), {
39
+ $id: docSnapshot.id
40
+ })).filter((product)=>!product.deletedAt && product.status === 'active').map((product)=>{
41
+ var _ref, _product_description;
42
+ var _product_mediaUrls;
43
+ const [minPrice] = CommerceModel.productPriceRange(product);
44
+ const inventory = CommerceModel.productInventory(product);
45
+ const availability = inventory != null && inventory <= 0 && product.oversellPolicy !== 'backorder' ? 'out_of_stock' : 'in_stock';
46
+ const image = (_ref = (_product_mediaUrls = product.mediaUrls) == null ? void 0 : _product_mediaUrls[0]) != null ? _ref : product.imageUrl;
47
+ return ' <item>\n' + ` <g:id>${escapeXml(product.$id)}</g:id>\n` + ` <g:title>${escapeXml(product.name)}</g:title>\n` + ` <g:description>${escapeXml((_product_description = product.description) != null ? _product_description : product.name)}</g:description>\n` + ` <g:link>${escapeXml(`${base}/products/${product.slug}`)}</g:link>\n` + (image ? ` <g:image_link>${escapeXml(image)}</g:image_link>\n` : '') + ` <g:price>${minPrice.toFixed(2)} USD</g:price>\n` + ` <g:availability>${availability}</g:availability>\n` + ` <g:condition>new</g:condition>\n` + ' </item>';
48
+ });
49
+ const xml = '<?xml version="1.0" encoding="UTF-8"?>\n' + '<rss version="2.0" xmlns:g="http://base.google.com/ns/1.0">\n' + ' <channel>\n' + ` <title>${escapeXml(requestHost)} products</title>\n` + ` <link>${escapeXml(base)}</link>\n` + ' <description>Product feed</description>\n' + items.join('\n') + '\n </channel>\n</rss>\n';
50
+ res.setHeader('Content-Type', 'application/xml');
51
+ res.setHeader('Cache-Control', 's-maxage=3600, stale-while-revalidate');
52
+ return res.status(200).send(xml);
53
+ } catch (error) {
54
+ console.error(error);
55
+ return res.status(500).send('Feed unavailable');
56
+ }
57
+ };
58
+
59
+ //# sourceMappingURL=feed.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/feed.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\n\nfunction escapeXml(text: string): string {\n return text\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n}\n\n/**\n * Google Merchant Center product feed (AGL-299): RSS 2.0 with the g:\n * namespace over active products — one item per product (default\n * variant pricing; per-variant feeds can come later). Submit\n * `https://{site}/api/commerce/feed?hostId={id}` in Merchant Center.\n */\nexport const feedHandler: PluginApiHandler = async (req, res) => {\n const hostId = String(req.query.hostId ?? '')\n if (!hostId) return res.status(400).send('Missing hostId')\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const productsSnapshot = await hostRef\n .collection('products')\n .limit(500)\n .get()\n const requestHost = String(req.headers['host'] ?? '')\n const base = `https://${requestHost}`\n const items = productsSnapshot.docs\n .map((docSnapshot) => ({\n ...CommerceModel.liftLegacyProduct(docSnapshot.data() as any),\n $id: docSnapshot.id,\n }))\n .filter(\n (product) => !product.deletedAt && product.status === 'active',\n )\n .map((product) => {\n const [minPrice] = CommerceModel.productPriceRange(product)\n const inventory = CommerceModel.productInventory(product)\n const availability =\n inventory != null &&\n inventory <= 0 &&\n product.oversellPolicy !== 'backorder'\n ? 'out_of_stock'\n : 'in_stock'\n const image = product.mediaUrls?.[0] ?? product.imageUrl\n return (\n ' <item>\\n' +\n ` <g:id>${escapeXml(product.$id)}</g:id>\\n` +\n ` <g:title>${escapeXml(product.name)}</g:title>\\n` +\n ` <g:description>${escapeXml(product.description ?? product.name)}</g:description>\\n` +\n ` <g:link>${escapeXml(`${base}/products/${product.slug}`)}</g:link>\\n` +\n (image\n ? ` <g:image_link>${escapeXml(image)}</g:image_link>\\n`\n : '') +\n ` <g:price>${minPrice.toFixed(2)} USD</g:price>\\n` +\n ` <g:availability>${availability}</g:availability>\\n` +\n ` <g:condition>new</g:condition>\\n` +\n ' </item>'\n )\n })\n const xml =\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n' +\n '<rss version=\"2.0\" xmlns:g=\"http://base.google.com/ns/1.0\">\\n' +\n ' <channel>\\n' +\n ` <title>${escapeXml(requestHost)} products</title>\\n` +\n ` <link>${escapeXml(base)}</link>\\n` +\n ' <description>Product feed</description>\\n' +\n items.join('\\n') +\n '\\n </channel>\\n</rss>\\n'\n res.setHeader('Content-Type', 'application/xml')\n res.setHeader('Cache-Control', 's-maxage=3600, stale-while-revalidate')\n return res.status(200).send(xml)\n } catch (error) {\n console.error(error)\n return res.status(500).send('Feed unavailable')\n }\n}\n"],"names":["CommerceModel","firebaseAdmin","escapeXml","text","replace","feedHandler","req","res","hostId","String","query","status","send","firestore","app","hostRef","collection","doc","productsSnapshot","limit","get","requestHost","headers","base","items","docs","map","docSnapshot","liftLegacyProduct","data","$id","id","filter","product","deletedAt","minPrice","productPriceRange","inventory","productInventory","availability","oversellPolicy","image","mediaUrls","imageUrl","name","description","slug","toFixed","xml","join","setHeader","error","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAID,YAAYA,mBAAmB,oBAAU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mBAAIA,QAAQU,QAAQ;YACxD,OACE,iBACA,CAAC,YAAY,EAAEzC,UAAU+B,QAAQH,GAAG,EAAE,SAAS,CAAC,GAChD,CAAC,eAAe,EAAE5B,UAAU+B,QAAQW,IAAI,EAAE,YAAY,CAAC,GACvD,CAAC,qBAAqB,EAAE1C,WAAU+B,uBAAAA,QAAQY,WAAW,YAAnBZ,uBAAuBA,QAAQW,IAAI,EAAE,kBAAkB,CAAC,GAC1F,CAAC,cAAc,EAAE1C,UAAU,GAAGqB,KAAK,UAAU,EAAEU,QAAQa,IAAI,EAAE,EAAE,WAAW,CAAC,GAC1EL,CAAAA,QACG,CAAC,oBAAoB,EAAEvC,UAAUuC,OAAO,iBAAiB,CAAC,GAC1D,EAAC,IACL,CAAC,eAAe,EAAEN,SAASY,OAAO,CAAC,GAAG,gBAAgB,CAAC,GACvD,CAAC,sBAAsB,EAAER,aAAa,mBAAmB,CAAC,GAC1D,CAAC,sCAAsC,CAAC,GACxC;QAEJ;QACF,MAAMS,MACJ,6CACA,kEACA,kBACA,CAAC,WAAW,EAAE9C,UAAUmB,aAAa,mBAAmB,CAAC,GACzD,CAAC,UAAU,EAAEnB,UAAUqB,MAAM,SAAS,CAAC,GACvC,kDACAC,MAAMyB,IAAI,CAAC,QACX;QACF1C,IAAI2C,SAAS,CAAC,gBAAgB;QAC9B3C,IAAI2C,SAAS,CAAC,iBAAiB;QAC/B,OAAO3C,IAAII,MAAM,CAAC,KAAKC,IAAI,CAACoC;IAC9B,EAAE,OAAOG,OAAO;QACdC,QAAQD,KAAK,CAACA;QACd,OAAO5C,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;IAC9B;AACF,EAAC"}
@@ -0,0 +1,97 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { type PluginApiHandler, type RecordShipmentOutcome, type RecordShipmentRequest } from '@aglyn/aglyn/server';
18
+ /**
19
+ * Record a shipment — the transaction, with NO authorization of any kind
20
+ * (AGL-2461).
21
+ *
22
+ * This is the whole of what `fulfillOrderHandler` used to do below its auth
23
+ * preamble, lifted out unchanged so a SECOND caller can have it: the customer
24
+ * REST API's `PATCH /v1/sites/{id}/orders/{id}`, which authenticates an org
25
+ * API key and so shares not one line of this function's former preamble.
26
+ *
27
+ * Lifted rather than copied, and that is the entire point of the change. The
28
+ * console app may not import this library (the `scope:app` boundary), so the
29
+ * alternative on the table was a second `ORDER_TRANSITIONS` inside `/v1` —
30
+ * two tables that drift into the API writing a status the console forbids.
31
+ * One implementation, reached from the app through the core
32
+ * `registerOrderFulfilmentService` registry, is the fix; see that registry's
33
+ * docblock for why the edge runs that way.
34
+ *
35
+ * **The caller authorizes.** Everything this function knows is the transition
36
+ * rule. It does not know who is asking, and it will happily move any order on
37
+ * any host — `hostId` is taken on trust because its two callers establish
38
+ * trust in ways that have nothing in common (a Firebase uid in `memberRoles`
39
+ * for the console; an org credential that owns the host for `/v1`).
40
+ *
41
+ * Every guarantee AGL-1819 built is inside the transaction and therefore
42
+ * inherited by both callers: `canTransitionOrder` is re-asked under the write
43
+ * so a stale caller cannot skip a state, the already-in-target case returns
44
+ * without writing so a retry cannot append a duplicate shipment, and
45
+ * `lineItemIds` and the timeline are computed from the transaction's OWN read
46
+ * so a note landed from another tab survives.
47
+ */
48
+ export declare function recordOrderShipment({ hostId, orderId, to, carrier, trackingNumber, }: RecordShipmentRequest): Promise<RecordShipmentOutcome>;
49
+ /**
50
+ * Fulfil and mark-delivered, with the transition re-asked under the write
51
+ * (AGL-1819) — the last two order-status writes the console made with a client
52
+ * `updateDoc`, moved behind the same shape as `cancel-order.ts`.
53
+ *
54
+ * THE STALE-DIALOG HOLE IS THE SAME ONE AGL-1818 CLOSED FOR CANCEL.
55
+ * `canTransitionOrder` was consulted only to RENDER the buttons, so a dialog
56
+ * opened on a `paid` order that was refunded (or cancelled) in another tab
57
+ * could still write `fulfilled` straight onto it — `ORDER_TRANSITIONS` stayed
58
+ * advisory because nothing consulted it on the way IN. Re-reading the order
59
+ * inside the transaction that writes the status is what turns the table into
60
+ * a guarantee; the race comes back as a 409 naming the state that refused.
61
+ *
62
+ * ONE ROUTE FOR THE TWO FULFILMENT-SIDE TRANSITIONS, and ONLY those. They are
63
+ * the same act — a forward status flip plus a timeline entry, no stock moved,
64
+ * no money moved — so they share a handler parameterized on `to`. It refuses
65
+ * every other target with a 400 on purpose: `cancelled` releases stock under
66
+ * its own transaction (`cancel-order.ts`) and `refunded` moves money
67
+ * (`refund.ts`), so admitting them here would hand callers a door around
68
+ * exactly the specifics those routes exist to enforce.
69
+ *
70
+ * NO STOCK MOVES HERE. The sale decremented inventory when the money landed
71
+ * (see `cancel-order.ts`'s header); shipping the goods changes what is on the
72
+ * shelf not at all. An open `restockCheck` — a partial refund's question,
73
+ * flagged before the merchant ships the rest — survives untouched: the write
74
+ * is an `update()` naming only status, fulfillments and timeline, and the
75
+ * question is still the merchant's to answer.
76
+ *
77
+ * NO NOTIFICATION EITHER, matching the client write this replaces: the
78
+ * merchant fulfilled the order themselves, and `notifyHostManagers` would
79
+ * tell them what they just did. (`supplier-update.ts` notifies because there
80
+ * the SUPPLIER acted and the merchant is the one who needs to hear it.)
81
+ *
82
+ * ONCE. A retried request — a lost response, a second click — finds the order
83
+ * already in the target status and returns success WITHOUT writing: appending
84
+ * a second copy of the same fulfillment is the double this guard exists to
85
+ * stop. It reports `already: true` so the console can say so. A fulfil retried
86
+ * after the order moved on to `delivered` in another tab is a 409 instead,
87
+ * which is the truth: that state cannot be fulfilled (again).
88
+ *
89
+ * THE SERVER'S ORDER, NOT THE DIALOG'S: `lineItemIds` and the timeline append
90
+ * are computed from the transaction's own read, so a note landed from another
91
+ * tab survives — the client write it replaces appended to the dialog's stale
92
+ * copy and dropped it.
93
+ *
94
+ * Role gate: `admin` and `editor`, the role the client write already had
95
+ * under the rules' host catch-all — same reasoning as `cancel-order.ts`.
96
+ */
97
+ export declare const fulfillOrderHandler: PluginApiHandler;
@@ -0,0 +1,235 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ import * as CommerceModel from "../model/index.js";
18
+ import { createResourceUid } from "@aglyn/aglyn/server";
19
+ import { firebaseAdmin } from "@aglyn/tenant-data-admin";
20
+ /**
21
+ * Record a shipment — the transaction, with NO authorization of any kind
22
+ * (AGL-2461).
23
+ *
24
+ * This is the whole of what `fulfillOrderHandler` used to do below its auth
25
+ * preamble, lifted out unchanged so a SECOND caller can have it: the customer
26
+ * REST API's `PATCH /v1/sites/{id}/orders/{id}`, which authenticates an org
27
+ * API key and so shares not one line of this function's former preamble.
28
+ *
29
+ * Lifted rather than copied, and that is the entire point of the change. The
30
+ * console app may not import this library (the `scope:app` boundary), so the
31
+ * alternative on the table was a second `ORDER_TRANSITIONS` inside `/v1` —
32
+ * two tables that drift into the API writing a status the console forbids.
33
+ * One implementation, reached from the app through the core
34
+ * `registerOrderFulfilmentService` registry, is the fix; see that registry's
35
+ * docblock for why the edge runs that way.
36
+ *
37
+ * **The caller authorizes.** Everything this function knows is the transition
38
+ * rule. It does not know who is asking, and it will happily move any order on
39
+ * any host — `hostId` is taken on trust because its two callers establish
40
+ * trust in ways that have nothing in common (a Firebase uid in `memberRoles`
41
+ * for the console; an org credential that owns the host for `/v1`).
42
+ *
43
+ * Every guarantee AGL-1819 built is inside the transaction and therefore
44
+ * inherited by both callers: `canTransitionOrder` is re-asked under the write
45
+ * so a stale caller cannot skip a state, the already-in-target case returns
46
+ * without writing so a retry cannot append a duplicate shipment, and
47
+ * `lineItemIds` and the timeline are computed from the transaction's OWN read
48
+ * so a note landed from another tab survives.
49
+ */ export async function recordOrderShipment({ hostId, orderId, to, carrier, trackingNumber }) {
50
+ const firestore = firebaseAdmin.app().firestore();
51
+ const orderRef = firestore.collection('hosts').doc(hostId).collection('orders').doc(orderId);
52
+ return firestore.runTransaction(async (transaction)=>{
53
+ var _snapshot_data, _order_fulfillments, _order_lineItems;
54
+ const snapshot = await transaction.get(orderRef);
55
+ if (!snapshot.exists) return {
56
+ outcome: 'no_such_order'
57
+ };
58
+ const order = CommerceModel.liftLegacyOrder((_snapshot_data = snapshot.data()) != null ? _snapshot_data : {});
59
+ // A redelivered click, or the second of two admins. Success because it
60
+ // IS the state the caller asked for — but nothing is written, so a
61
+ // retry cannot append a second copy of the same fulfillment.
62
+ if (order.status === to) return {
63
+ outcome: 'already'
64
+ };
65
+ if (!CommerceModel.canTransitionOrder(order.status, to)) {
66
+ return {
67
+ outcome: 'blocked',
68
+ from: order.status
69
+ };
70
+ }
71
+ const atMs = Date.now();
72
+ const patch = to === 'fulfilled' ? {
73
+ status: 'fulfilled',
74
+ fulfillments: [
75
+ ...(_order_fulfillments = order.fulfillments) != null ? _order_fulfillments : [],
76
+ _extends({
77
+ id: createResourceUid(),
78
+ lineItemIds: ((_order_lineItems = order.lineItems) != null ? _order_lineItems : []).map((_line, index)=>index)
79
+ }, carrier ? {
80
+ carrier
81
+ } : {}, trackingNumber ? {
82
+ trackingNumber
83
+ } : {}, {
84
+ atMs
85
+ })
86
+ ],
87
+ timeline: CommerceModel.appendOrderEvent(order, 'fulfilled', trackingNumber ? `${carrier || 'Shipped'} ${trackingNumber}` : 'Fulfilled', atMs)
88
+ } : {
89
+ status: 'delivered',
90
+ timeline: CommerceModel.appendOrderEvent(order, 'delivered', undefined, atMs)
91
+ };
92
+ transaction.update(orderRef, patch);
93
+ return {
94
+ outcome: 'recorded'
95
+ };
96
+ });
97
+ }
98
+ /**
99
+ * Fulfil and mark-delivered, with the transition re-asked under the write
100
+ * (AGL-1819) — the last two order-status writes the console made with a client
101
+ * `updateDoc`, moved behind the same shape as `cancel-order.ts`.
102
+ *
103
+ * THE STALE-DIALOG HOLE IS THE SAME ONE AGL-1818 CLOSED FOR CANCEL.
104
+ * `canTransitionOrder` was consulted only to RENDER the buttons, so a dialog
105
+ * opened on a `paid` order that was refunded (or cancelled) in another tab
106
+ * could still write `fulfilled` straight onto it — `ORDER_TRANSITIONS` stayed
107
+ * advisory because nothing consulted it on the way IN. Re-reading the order
108
+ * inside the transaction that writes the status is what turns the table into
109
+ * a guarantee; the race comes back as a 409 naming the state that refused.
110
+ *
111
+ * ONE ROUTE FOR THE TWO FULFILMENT-SIDE TRANSITIONS, and ONLY those. They are
112
+ * the same act — a forward status flip plus a timeline entry, no stock moved,
113
+ * no money moved — so they share a handler parameterized on `to`. It refuses
114
+ * every other target with a 400 on purpose: `cancelled` releases stock under
115
+ * its own transaction (`cancel-order.ts`) and `refunded` moves money
116
+ * (`refund.ts`), so admitting them here would hand callers a door around
117
+ * exactly the specifics those routes exist to enforce.
118
+ *
119
+ * NO STOCK MOVES HERE. The sale decremented inventory when the money landed
120
+ * (see `cancel-order.ts`'s header); shipping the goods changes what is on the
121
+ * shelf not at all. An open `restockCheck` — a partial refund's question,
122
+ * flagged before the merchant ships the rest — survives untouched: the write
123
+ * is an `update()` naming only status, fulfillments and timeline, and the
124
+ * question is still the merchant's to answer.
125
+ *
126
+ * NO NOTIFICATION EITHER, matching the client write this replaces: the
127
+ * merchant fulfilled the order themselves, and `notifyHostManagers` would
128
+ * tell them what they just did. (`supplier-update.ts` notifies because there
129
+ * the SUPPLIER acted and the merchant is the one who needs to hear it.)
130
+ *
131
+ * ONCE. A retried request — a lost response, a second click — finds the order
132
+ * already in the target status and returns success WITHOUT writing: appending
133
+ * a second copy of the same fulfillment is the double this guard exists to
134
+ * stop. It reports `already: true` so the console can say so. A fulfil retried
135
+ * after the order moved on to `delivered` in another tab is a 409 instead,
136
+ * which is the truth: that state cannot be fulfilled (again).
137
+ *
138
+ * THE SERVER'S ORDER, NOT THE DIALOG'S: `lineItemIds` and the timeline append
139
+ * are computed from the transaction's own read, so a note landed from another
140
+ * tab survives — the client write it replaces appended to the dialog's stale
141
+ * copy and dropped it.
142
+ *
143
+ * Role gate: `admin` and `editor`, the role the client write already had
144
+ * under the rules' host catch-all — same reasoning as `cancel-order.ts`.
145
+ */ export const fulfillOrderHandler = async (req, res)=>{
146
+ var _req_headers_authorization, _req_body, _body_hostId, _body_orderId, _body_to, _body_carrier, _body_trackingNumber;
147
+ if (req.method !== 'POST') {
148
+ return res.status(405).json({
149
+ error: 'Method not allowed'
150
+ });
151
+ }
152
+ const authorization = String((_req_headers_authorization = req.headers.authorization) != null ? _req_headers_authorization : '');
153
+ const idToken = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : undefined;
154
+ if (!idToken) return res.status(401).json({
155
+ error: 'Unauthenticated'
156
+ });
157
+ const body = typeof req.body === 'string' ? JSON.parse(req.body) : (_req_body = req.body) != null ? _req_body : {};
158
+ const hostId = String((_body_hostId = body.hostId) != null ? _body_hostId : '');
159
+ const orderId = String((_body_orderId = body.orderId) != null ? _body_orderId : '');
160
+ if (!hostId || !orderId) {
161
+ return res.status(400).json({
162
+ error: 'Missing hostId or orderId'
163
+ });
164
+ }
165
+ // Firestore reserves `__…__` ids and `.doc()` throws SYNCHRONOUSLY on one,
166
+ // which would surface as a 500 on a caller's typo rather than the 400 it is.
167
+ if (/^__.*__$/.test(hostId) || /^__.*__$/.test(orderId)) {
168
+ return res.status(400).json({
169
+ error: 'Missing hostId or orderId'
170
+ });
171
+ }
172
+ const to = String((_body_to = body.to) != null ? _body_to : '');
173
+ if (to !== 'fulfilled' && to !== 'delivered') {
174
+ // Deliberately NOT a generic transition endpoint — see the header.
175
+ return res.status(400).json({
176
+ error: 'to must be fulfilled or delivered'
177
+ });
178
+ }
179
+ const carrier = String((_body_carrier = body.carrier) != null ? _body_carrier : '').slice(0, 40);
180
+ const trackingNumber = String((_body_trackingNumber = body.trackingNumber) != null ? _body_trackingNumber : '').slice(0, 60);
181
+ try {
182
+ var _hostSnapshot_get;
183
+ const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
184
+ const firestore = firebaseAdmin.app().firestore();
185
+ const hostRef = firestore.collection('hosts').doc(hostId);
186
+ const hostSnapshot = await hostRef.get();
187
+ if (!hostSnapshot.exists) {
188
+ return res.status(404).json({
189
+ error: 'Unknown site'
190
+ });
191
+ }
192
+ const memberRole = ((_hostSnapshot_get = hostSnapshot.get('memberRoles')) != null ? _hostSnapshot_get : {})[decoded.uid];
193
+ if (memberRole !== 'admin' && memberRole !== 'editor') {
194
+ return res.status(403).json({
195
+ error: 'Not permitted'
196
+ });
197
+ }
198
+ // Authorized above; the shipment itself is the shared transaction. The
199
+ // wire shape below is unchanged — the console dialog branches on `ok`,
200
+ // `already` and the 409's `error` string, and this route's contract is
201
+ // with that dialog, not with the registry's vocabulary.
202
+ const outcome = await recordOrderShipment({
203
+ hostId,
204
+ orderId,
205
+ to,
206
+ carrier,
207
+ trackingNumber
208
+ });
209
+ if (outcome.outcome === 'no_such_order') {
210
+ return res.status(404).json({
211
+ error: 'Unknown order'
212
+ });
213
+ }
214
+ if (outcome.outcome === 'blocked') {
215
+ return res.status(409).json({
216
+ error: to === 'delivered' ? `Orders in "${outcome.from}" cannot be marked delivered` : `Orders in "${outcome.from}" cannot be fulfilled`
217
+ });
218
+ }
219
+ return res.status(200).json(outcome.outcome === 'already' ? {
220
+ ok: true,
221
+ already: true
222
+ } : {
223
+ ok: true
224
+ });
225
+ } catch (error) {
226
+ // Nothing landed — the transaction is all-or-nothing — so the order is
227
+ // still where it was and the merchant can try again.
228
+ console.error('fulfillOrder failed', error);
229
+ return res.status(500).json({
230
+ error: to === 'delivered' ? 'Mark delivered failed' : 'Fulfill failed'
231
+ });
232
+ }
233
+ };
234
+
235
+ //# sourceMappingURL=fulfill-order.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/fulfill-order.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as CommerceModel from '../model'\nimport {\n createResourceUid,\n type OrderFulfilmentTarget,\n type PluginApiHandler,\n type RecordShipmentOutcome,\n type RecordShipmentRequest,\n} from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\n\n/**\n * Record a shipment — the transaction, with NO authorization of any kind\n * (AGL-2461).\n *\n * This is the whole of what `fulfillOrderHandler` used to do below its auth\n * preamble, lifted out unchanged so a SECOND caller can have it: the customer\n * REST API's `PATCH /v1/sites/{id}/orders/{id}`, which authenticates an org\n * API key and so shares not one line of this function's former preamble.\n *\n * Lifted rather than copied, and that is the entire point of the change. The\n * console app may not import this library (the `scope:app` boundary), so the\n * alternative on the table was a second `ORDER_TRANSITIONS` inside `/v1` —\n * two tables that drift into the API writing a status the console forbids.\n * One implementation, reached from the app through the core\n * `registerOrderFulfilmentService` registry, is the fix; see that registry's\n * docblock for why the edge runs that way.\n *\n * **The caller authorizes.** Everything this function knows is the transition\n * rule. It does not know who is asking, and it will happily move any order on\n * any host — `hostId` is taken on trust because its two callers establish\n * trust in ways that have nothing in common (a Firebase uid in `memberRoles`\n * for the console; an org credential that owns the host for `/v1`).\n *\n * Every guarantee AGL-1819 built is inside the transaction and therefore\n * inherited by both callers: `canTransitionOrder` is re-asked under the write\n * so a stale caller cannot skip a state, the already-in-target case returns\n * without writing so a retry cannot append a duplicate shipment, and\n * `lineItemIds` and the timeline are computed from the transaction's OWN read\n * so a note landed from another tab survives.\n */\nexport async function recordOrderShipment({\n hostId,\n orderId,\n to,\n carrier,\n trackingNumber,\n}: RecordShipmentRequest): Promise<RecordShipmentOutcome> {\n const firestore = firebaseAdmin.app().firestore()\n const orderRef = firestore\n .collection('hosts')\n .doc(hostId)\n .collection('orders')\n .doc(orderId)\n\n return firestore.runTransaction(\n async (transaction): Promise<RecordShipmentOutcome> => {\n const snapshot = await transaction.get(orderRef)\n if (!snapshot.exists) return { outcome: 'no_such_order' }\n const order = CommerceModel.liftLegacyOrder(\n (snapshot.data() ?? {}) as never,\n )\n // A redelivered click, or the second of two admins. Success because it\n // IS the state the caller asked for — but nothing is written, so a\n // retry cannot append a second copy of the same fulfillment.\n if (order.status === to) return { outcome: 'already' }\n if (!CommerceModel.canTransitionOrder(order.status, to)) {\n return { outcome: 'blocked', from: order.status }\n }\n\n const atMs = Date.now()\n const patch: Record<string, unknown> =\n to === 'fulfilled'\n ? {\n status: 'fulfilled',\n fulfillments: [\n ...(order.fulfillments ?? []),\n {\n id: createResourceUid(),\n lineItemIds: (order.lineItems ?? []).map(\n (_line, index) => index,\n ),\n ...(carrier ? { carrier } : {}),\n ...(trackingNumber ? { trackingNumber } : {}),\n atMs,\n } satisfies CommerceModel.OrderFulfillment,\n ],\n timeline: CommerceModel.appendOrderEvent(\n order,\n 'fulfilled',\n trackingNumber\n ? `${carrier || 'Shipped'} ${trackingNumber}`\n : 'Fulfilled',\n atMs,\n ),\n }\n : {\n status: 'delivered',\n timeline: CommerceModel.appendOrderEvent(\n order,\n 'delivered',\n undefined,\n atMs,\n ),\n }\n transaction.update(orderRef, patch)\n return { outcome: 'recorded' }\n },\n )\n}\n\n/**\n * Fulfil and mark-delivered, with the transition re-asked under the write\n * (AGL-1819) — the last two order-status writes the console made with a client\n * `updateDoc`, moved behind the same shape as `cancel-order.ts`.\n *\n * THE STALE-DIALOG HOLE IS THE SAME ONE AGL-1818 CLOSED FOR CANCEL.\n * `canTransitionOrder` was consulted only to RENDER the buttons, so a dialog\n * opened on a `paid` order that was refunded (or cancelled) in another tab\n * could still write `fulfilled` straight onto it — `ORDER_TRANSITIONS` stayed\n * advisory because nothing consulted it on the way IN. Re-reading the order\n * inside the transaction that writes the status is what turns the table into\n * a guarantee; the race comes back as a 409 naming the state that refused.\n *\n * ONE ROUTE FOR THE TWO FULFILMENT-SIDE TRANSITIONS, and ONLY those. They are\n * the same act — a forward status flip plus a timeline entry, no stock moved,\n * no money moved — so they share a handler parameterized on `to`. It refuses\n * every other target with a 400 on purpose: `cancelled` releases stock under\n * its own transaction (`cancel-order.ts`) and `refunded` moves money\n * (`refund.ts`), so admitting them here would hand callers a door around\n * exactly the specifics those routes exist to enforce.\n *\n * NO STOCK MOVES HERE. The sale decremented inventory when the money landed\n * (see `cancel-order.ts`'s header); shipping the goods changes what is on the\n * shelf not at all. An open `restockCheck` — a partial refund's question,\n * flagged before the merchant ships the rest — survives untouched: the write\n * is an `update()` naming only status, fulfillments and timeline, and the\n * question is still the merchant's to answer.\n *\n * NO NOTIFICATION EITHER, matching the client write this replaces: the\n * merchant fulfilled the order themselves, and `notifyHostManagers` would\n * tell them what they just did. (`supplier-update.ts` notifies because there\n * the SUPPLIER acted and the merchant is the one who needs to hear it.)\n *\n * ONCE. A retried request — a lost response, a second click — finds the order\n * already in the target status and returns success WITHOUT writing: appending\n * a second copy of the same fulfillment is the double this guard exists to\n * stop. It reports `already: true` so the console can say so. A fulfil retried\n * after the order moved on to `delivered` in another tab is a 409 instead,\n * which is the truth: that state cannot be fulfilled (again).\n *\n * THE SERVER'S ORDER, NOT THE DIALOG'S: `lineItemIds` and the timeline append\n * are computed from the transaction's own read, so a note landed from another\n * tab survives — the client write it replaces appended to the dialog's stale\n * copy and dropped it.\n *\n * Role gate: `admin` and `editor`, the role the client write already had\n * under the rules' host catch-all — same reasoning as `cancel-order.ts`.\n */\nexport const fulfillOrderHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const orderId = String(body.orderId ?? '')\n if (!hostId || !orderId) {\n return res.status(400).json({ error: 'Missing hostId or orderId' })\n }\n // Firestore reserves `__…__` ids and `.doc()` throws SYNCHRONOUSLY on one,\n // which would surface as a 500 on a caller's typo rather than the 400 it is.\n if (/^__.*__$/.test(hostId) || /^__.*__$/.test(orderId)) {\n return res.status(400).json({ error: 'Missing hostId or orderId' })\n }\n const to = String(body.to ?? '') as OrderFulfilmentTarget\n if (to !== 'fulfilled' && to !== 'delivered') {\n // Deliberately NOT a generic transition endpoint — see the header.\n return res.status(400).json({ error: 'to must be fulfilled or delivered' })\n }\n const carrier = String(body.carrier ?? '').slice(0, 40)\n const trackingNumber = String(body.trackingNumber ?? '').slice(0, 60)\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return res.status(403).json({ error: 'Not permitted' })\n }\n\n // Authorized above; the shipment itself is the shared transaction. The\n // wire shape below is unchanged — the console dialog branches on `ok`,\n // `already` and the 409's `error` string, and this route's contract is\n // with that dialog, not with the registry's vocabulary.\n const outcome = await recordOrderShipment({\n hostId,\n orderId,\n to,\n carrier,\n trackingNumber,\n })\n if (outcome.outcome === 'no_such_order') {\n return res.status(404).json({ error: 'Unknown order' })\n }\n if (outcome.outcome === 'blocked') {\n return res.status(409).json({\n error:\n to === 'delivered'\n ? `Orders in \"${outcome.from}\" cannot be marked delivered`\n : `Orders in \"${outcome.from}\" cannot be fulfilled`,\n })\n }\n return res\n .status(200)\n .json(\n outcome.outcome === 'already' ? { ok: true, already: true } : { ok: true },\n )\n } catch (error) {\n // Nothing landed — the transaction is all-or-nothing — so the order is\n // still where it was and the merchant can try again.\n console.error('fulfillOrder failed', error)\n return res.status(500).json({\n error: to === 'delivered' ? 'Mark delivered failed' : 'Fulfill failed',\n })\n }\n}\n"],"names":["CommerceModel","createResourceUid","firebaseAdmin","recordOrderShipment","hostId","orderId","to","carrier","trackingNumber","firestore","app","orderRef","collection","doc","runTransaction","transaction","snapshot","order","get","exists","outcome","liftLegacyOrder","data","status","canTransitionOrder","from","atMs","Date","now","patch","fulfillments","id","lineItemIds","lineItems","map","_line","index","timeline","appendOrderEvent","undefined","update","fulfillOrderHandler","req","res","body","method","json","error","authorization","String","headers","idToken","startsWith","slice","length","JSON","parse","test","hostSnapshot","decoded","auth","verifyIdToken","hostRef","memberRole","uid","ok","already","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,mBAAmB,oBAAU;AACzC,SACEC,iBAAiB,QAKZ,sBAAqB;AAC5B,SAASC,aAAa,QAAQ,2BAA0B;AAExD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BC,GACD,OAAO,eAAeC,oBAAoB,EACxCC,MAAM,EACNC,OAAO,EACPC,EAAE,EACFC,OAAO,EAC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