@zonastery/bursar 1.0.1 → 2.0.1

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 (366) hide show
  1. package/README.md +86 -3
  2. package/dist/billing/auto-recharge-port.d.ts +3 -3
  3. package/dist/billing/auto-recharge-port.d.ts.map +1 -1
  4. package/dist/billing/auto-recharge-port.js.map +1 -1
  5. package/dist/billing/auto-recharge-service.d.ts +5 -4
  6. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  7. package/dist/billing/auto-recharge-service.js +64 -34
  8. package/dist/billing/auto-recharge-service.js.map +1 -1
  9. package/dist/billing/billing-service.d.ts +5 -5
  10. package/dist/billing/billing-service.d.ts.map +1 -1
  11. package/dist/billing/billing-service.js +2 -2
  12. package/dist/billing/billing-service.js.map +1 -1
  13. package/dist/billing/billing-store.d.ts +8 -7
  14. package/dist/billing/billing-store.d.ts.map +1 -1
  15. package/dist/billing/billing-store.js.map +1 -1
  16. package/dist/billing/contracts.d.ts +31 -31
  17. package/dist/billing/contracts.d.ts.map +1 -1
  18. package/dist/billing/contracts.js.map +1 -1
  19. package/dist/billing/event-handlers.d.ts.map +1 -1
  20. package/dist/billing/event-handlers.js +31 -9
  21. package/dist/billing/event-handlers.js.map +1 -1
  22. package/dist/billing/event-processor.d.ts.map +1 -1
  23. package/dist/billing/event-processor.js +2 -1
  24. package/dist/billing/event-processor.js.map +1 -1
  25. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  26. package/dist/billing/financial-event-handlers.js +69 -72
  27. package/dist/billing/financial-event-handlers.js.map +1 -1
  28. package/dist/billing/index.d.ts +1 -1
  29. package/dist/billing/index.d.ts.map +1 -1
  30. package/dist/billing/index.js.map +1 -1
  31. package/dist/billing/management.d.ts +5 -5
  32. package/dist/billing/management.d.ts.map +1 -1
  33. package/dist/billing/management.js +2 -2
  34. package/dist/billing/management.js.map +1 -1
  35. package/dist/billing/postgres/repositories/auto-recharge.d.ts +3 -3
  36. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  37. package/dist/billing/postgres/repositories/auto-recharge.js +202 -59
  38. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  39. package/dist/billing/postgres/repositories/customer.d.ts.map +1 -1
  40. package/dist/billing/postgres/repositories/customer.js +19 -11
  41. package/dist/billing/postgres/repositories/customer.js.map +1 -1
  42. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
  43. package/dist/billing/postgres/repositories/dispute.js +3 -1
  44. package/dist/billing/postgres/repositories/dispute.js.map +1 -1
  45. package/dist/billing/postgres/repositories/event.d.ts +12 -5
  46. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  47. package/dist/billing/postgres/repositories/event.js +18 -15
  48. package/dist/billing/postgres/repositories/event.js.map +1 -1
  49. package/dist/billing/postgres/repositories/invoice.d.ts +3 -3
  50. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  51. package/dist/billing/postgres/repositories/invoice.js +53 -11
  52. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  53. package/dist/billing/postgres/repositories/offer.d.ts +20 -17
  54. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  55. package/dist/billing/postgres/repositories/offer.js +123 -57
  56. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  57. package/dist/billing/postgres/repositories/payment.d.ts +23 -20
  58. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  59. package/dist/billing/postgres/repositories/payment.js +43 -37
  60. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  61. package/dist/billing/postgres/repositories/preferences.d.ts +3 -9
  62. package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -1
  63. package/dist/billing/postgres/repositories/preferences.js +45 -7
  64. package/dist/billing/postgres/repositories/preferences.js.map +1 -1
  65. package/dist/billing/postgres/repositories/refund.d.ts +1 -1
  66. package/dist/billing/postgres/repositories/refund.d.ts.map +1 -1
  67. package/dist/billing/postgres/repositories/refund.js +13 -9
  68. package/dist/billing/postgres/repositories/refund.js.map +1 -1
  69. package/dist/billing/postgres/repositories/subscription-change.d.ts +15 -0
  70. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -0
  71. package/dist/billing/postgres/repositories/subscription-change.js +234 -0
  72. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -0
  73. package/dist/billing/postgres/repositories/subscription.d.ts +38 -17
  74. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  75. package/dist/billing/postgres/repositories/subscription.js +199 -91
  76. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  77. package/dist/billing/postgres/repositories/topup.d.ts +13 -15
  78. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  79. package/dist/billing/postgres/repositories/topup.js +65 -34
  80. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  81. package/dist/billing/postgres/store.d.ts +18 -11
  82. package/dist/billing/postgres/store.d.ts.map +1 -1
  83. package/dist/billing/postgres/store.js +260 -238
  84. package/dist/billing/postgres/store.js.map +1 -1
  85. package/dist/billing/service-types.d.ts +6 -5
  86. package/dist/billing/service-types.d.ts.map +1 -1
  87. package/dist/billing/service-types.js.map +1 -1
  88. package/dist/billing/types/auto-recharge.d.ts +6 -4
  89. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  90. package/dist/billing/types/auto-recharge.js.map +1 -1
  91. package/dist/billing/types/catalog.d.ts +18 -35
  92. package/dist/billing/types/catalog.d.ts.map +1 -1
  93. package/dist/billing/types/catalog.js.map +1 -1
  94. package/dist/billing/types/common.d.ts +0 -1
  95. package/dist/billing/types/common.d.ts.map +1 -1
  96. package/dist/billing/types/common.js.map +1 -1
  97. package/dist/billing/types/documents.d.ts +38 -12
  98. package/dist/billing/types/documents.d.ts.map +1 -1
  99. package/dist/billing/types/documents.js.map +1 -1
  100. package/dist/billing/types/events.d.ts +2 -0
  101. package/dist/billing/types/events.d.ts.map +1 -1
  102. package/dist/billing/types/events.js +238 -0
  103. package/dist/billing/types/events.js.map +1 -1
  104. package/dist/billing/types/subscriptions.d.ts +8 -8
  105. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  106. package/dist/billing/types/subscriptions.js.map +1 -1
  107. package/dist/bursar.d.ts +27 -9
  108. package/dist/bursar.d.ts.map +1 -1
  109. package/dist/bursar.js +48 -20
  110. package/dist/bursar.js.map +1 -1
  111. package/dist/catalog.d.ts +1 -1
  112. package/dist/catalog.d.ts.map +1 -1
  113. package/dist/catalog.js +1 -1
  114. package/dist/catalog.js.map +1 -1
  115. package/dist/commerce/errors.d.ts +1 -10
  116. package/dist/commerce/errors.d.ts.map +1 -1
  117. package/dist/commerce/errors.js +1 -16
  118. package/dist/commerce/errors.js.map +1 -1
  119. package/dist/commerce/index.d.ts +1 -0
  120. package/dist/commerce/index.d.ts.map +1 -1
  121. package/dist/commerce/index.js.map +1 -1
  122. package/dist/commerce/provider-registry.d.ts.map +1 -1
  123. package/dist/commerce/provider-registry.js +27 -2
  124. package/dist/commerce/provider-registry.js.map +1 -1
  125. package/dist/commerce/service.d.ts +15 -7
  126. package/dist/commerce/service.d.ts.map +1 -1
  127. package/dist/commerce/service.js +85 -67
  128. package/dist/commerce/service.js.map +1 -1
  129. package/dist/commerce/types.d.ts +27 -15
  130. package/dist/commerce/types.d.ts.map +1 -1
  131. package/dist/commerce/types.js.map +1 -1
  132. package/dist/config/parse-plans.d.ts.map +1 -1
  133. package/dist/config/parse-plans.js +16 -15
  134. package/dist/config/parse-plans.js.map +1 -1
  135. package/dist/config/parse-pricing.d.ts.map +1 -1
  136. package/dist/config/parse-pricing.js +16 -5
  137. package/dist/config/parse-pricing.js.map +1 -1
  138. package/dist/config/types.d.ts +2 -2
  139. package/dist/config/types.d.ts.map +1 -1
  140. package/dist/config/types.js.map +1 -1
  141. package/dist/credits/{pricing-runtime.d.ts → catalog-runtime.d.ts} +8 -8
  142. package/dist/credits/catalog-runtime.d.ts.map +1 -0
  143. package/dist/credits/{pricing-runtime.js → catalog-runtime.js} +58 -38
  144. package/dist/credits/catalog-runtime.js.map +1 -0
  145. package/dist/credits/events.d.ts +4 -4
  146. package/dist/credits/events.d.ts.map +1 -1
  147. package/dist/credits/events.js +1 -1
  148. package/dist/credits/events.js.map +1 -1
  149. package/dist/credits/lease-workflow.d.ts +14 -14
  150. package/dist/credits/lease-workflow.d.ts.map +1 -1
  151. package/dist/credits/lease-workflow.js +18 -17
  152. package/dist/credits/lease-workflow.js.map +1 -1
  153. package/dist/credits/low-balance-monitor.d.ts +2 -2
  154. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  155. package/dist/credits/low-balance-monitor.js.map +1 -1
  156. package/dist/credits/postgres/repositories/analytics.d.ts +34 -34
  157. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  158. package/dist/credits/postgres/repositories/analytics.js +52 -52
  159. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  160. package/dist/credits/postgres/repositories/balance.d.ts +28 -30
  161. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  162. package/dist/credits/postgres/repositories/balance.js +100 -59
  163. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  164. package/dist/credits/postgres/repositories/bucket.d.ts +14 -8
  165. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
  166. package/dist/credits/postgres/repositories/bucket.js +22 -21
  167. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  168. package/dist/credits/postgres/repositories/catalog.d.ts +31 -0
  169. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -0
  170. package/dist/credits/postgres/repositories/catalog.js +90 -0
  171. package/dist/credits/postgres/repositories/catalog.js.map +1 -0
  172. package/dist/credits/postgres/repositories/deduction.d.ts +28 -26
  173. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  174. package/dist/credits/postgres/repositories/deduction.js +153 -68
  175. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  176. package/dist/credits/postgres/repositories/lease.d.ts +21 -18
  177. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  178. package/dist/credits/postgres/repositories/lease.js +157 -65
  179. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  180. package/dist/credits/postgres/repositories/plan.d.ts +90 -43
  181. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
  182. package/dist/credits/postgres/repositories/plan.js +126 -108
  183. package/dist/credits/postgres/repositories/plan.js.map +1 -1
  184. package/dist/credits/postgres/repositories/team.d.ts +36 -27
  185. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  186. package/dist/credits/postgres/repositories/team.js +96 -52
  187. package/dist/credits/postgres/repositories/team.js.map +1 -1
  188. package/dist/credits/postgres/store.d.ts +23 -18
  189. package/dist/credits/postgres/store.d.ts.map +1 -1
  190. package/dist/credits/postgres/store.js +282 -265
  191. package/dist/credits/postgres/store.js.map +1 -1
  192. package/dist/credits/postgres/value-mappers.d.ts +7 -9
  193. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  194. package/dist/credits/postgres/value-mappers.js +36 -61
  195. package/dist/credits/postgres/value-mappers.js.map +1 -1
  196. package/dist/credits/queries.d.ts +5 -5
  197. package/dist/credits/queries.d.ts.map +1 -1
  198. package/dist/credits/queries.js +4 -4
  199. package/dist/credits/queries.js.map +1 -1
  200. package/dist/credits/service-types.d.ts +42 -7
  201. package/dist/credits/service-types.d.ts.map +1 -1
  202. package/dist/credits/service-types.js.map +1 -1
  203. package/dist/credits/service.d.ts +42 -62
  204. package/dist/credits/service.d.ts.map +1 -1
  205. package/dist/credits/service.js +140 -121
  206. package/dist/credits/service.js.map +1 -1
  207. package/dist/credits/store.d.ts +20 -22
  208. package/dist/credits/store.d.ts.map +1 -1
  209. package/dist/credits/store.js +5 -5
  210. package/dist/credits/store.js.map +1 -1
  211. package/dist/credits/types/account.d.ts +49 -11
  212. package/dist/credits/types/account.d.ts.map +1 -1
  213. package/dist/credits/types/account.js.map +1 -1
  214. package/dist/credits/types/admission.d.ts +17 -6
  215. package/dist/credits/types/admission.d.ts.map +1 -1
  216. package/dist/credits/types/admission.js.map +1 -1
  217. package/dist/credits/types/analytics.d.ts +2 -2
  218. package/dist/credits/types/analytics.d.ts.map +1 -1
  219. package/dist/credits/types/analytics.js.map +1 -1
  220. package/dist/credits/types/catalog.d.ts +20 -15
  221. package/dist/credits/types/catalog.d.ts.map +1 -1
  222. package/dist/credits/types/catalog.js.map +1 -1
  223. package/dist/credits/types/grants.d.ts +22 -8
  224. package/dist/credits/types/grants.d.ts.map +1 -1
  225. package/dist/credits/types/grants.js.map +1 -1
  226. package/dist/credits/types/ledger.d.ts +12 -3
  227. package/dist/credits/types/ledger.d.ts.map +1 -1
  228. package/dist/credits/types/ledger.js.map +1 -1
  229. package/dist/credits/types/teams.d.ts +18 -6
  230. package/dist/credits/types/teams.d.ts.map +1 -1
  231. package/dist/credits/types/teams.js.map +1 -1
  232. package/dist/engine.d.ts.map +1 -1
  233. package/dist/engine.js +24 -10
  234. package/dist/engine.js.map +1 -1
  235. package/dist/errors.d.ts +52 -4
  236. package/dist/errors.d.ts.map +1 -1
  237. package/dist/errors.js +76 -4
  238. package/dist/errors.js.map +1 -1
  239. package/dist/expr/ast.d.ts.map +1 -1
  240. package/dist/expr/ast.js.map +1 -1
  241. package/dist/expr/evaluator.d.ts.map +1 -1
  242. package/dist/expr/evaluator.js +29 -17
  243. package/dist/expr/evaluator.js.map +1 -1
  244. package/dist/expr/parser.d.ts.map +1 -1
  245. package/dist/expr/parser.js +11 -4
  246. package/dist/expr/parser.js.map +1 -1
  247. package/dist/expr/tokenizer.d.ts.map +1 -1
  248. package/dist/expr/tokenizer.js +17 -13
  249. package/dist/expr/tokenizer.js.map +1 -1
  250. package/dist/expr.d.ts +2 -2
  251. package/dist/expr.d.ts.map +1 -1
  252. package/dist/expr.js +5 -7
  253. package/dist/expr.js.map +1 -1
  254. package/dist/generated/pricing-config.schema.json +5 -12
  255. package/dist/generated/pricing-config.types.d.ts +3 -3
  256. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  257. package/dist/generated/pricing-config.types.js.map +1 -1
  258. package/dist/index.d.ts +6 -4
  259. package/dist/index.d.ts.map +1 -1
  260. package/dist/index.js +1 -1
  261. package/dist/index.js.map +1 -1
  262. package/dist/integrations/better-auth.d.ts +23 -0
  263. package/dist/integrations/better-auth.d.ts.map +1 -0
  264. package/dist/integrations/better-auth.js +54 -0
  265. package/dist/integrations/better-auth.js.map +1 -0
  266. package/dist/{load-pricing-file.d.ts → load-config-file.d.ts} +4 -4
  267. package/dist/load-config-file.d.ts.map +1 -0
  268. package/dist/{load-pricing-file.js → load-config-file.js} +15 -10
  269. package/dist/load-config-file.js.map +1 -0
  270. package/dist/node.d.ts +3 -3
  271. package/dist/node.d.ts.map +1 -1
  272. package/dist/node.js +2 -2
  273. package/dist/node.js.map +1 -1
  274. package/dist/providers/_shared.d.ts +5 -0
  275. package/dist/providers/_shared.d.ts.map +1 -1
  276. package/dist/providers/_shared.js +36 -0
  277. package/dist/providers/_shared.js.map +1 -1
  278. package/dist/providers/dodo/better-auth.d.ts +29 -0
  279. package/dist/providers/dodo/better-auth.d.ts.map +1 -0
  280. package/dist/providers/dodo/better-auth.js +23 -0
  281. package/dist/providers/dodo/better-auth.js.map +1 -0
  282. package/dist/providers/dodo/client-contract.d.ts +32 -70
  283. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  284. package/dist/providers/dodo/client-contract.js.map +1 -1
  285. package/dist/providers/dodo/event-mapper.d.ts +3 -1
  286. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  287. package/dist/providers/dodo/event-mapper.js +219 -148
  288. package/dist/providers/dodo/event-mapper.js.map +1 -1
  289. package/dist/providers/dodo/index.d.ts +5 -2
  290. package/dist/providers/dodo/index.d.ts.map +1 -1
  291. package/dist/providers/dodo/index.js +2 -1
  292. package/dist/providers/dodo/index.js.map +1 -1
  293. package/dist/providers/dodo/nextjs.d.ts +16 -0
  294. package/dist/providers/dodo/nextjs.d.ts.map +1 -0
  295. package/dist/providers/dodo/nextjs.js +16 -0
  296. package/dist/providers/dodo/nextjs.js.map +1 -0
  297. package/dist/providers/dodo/provider.d.ts +30 -11
  298. package/dist/providers/dodo/provider.d.ts.map +1 -1
  299. package/dist/providers/dodo/provider.js +192 -122
  300. package/dist/providers/dodo/provider.js.map +1 -1
  301. package/dist/providers/dodo/react-native.d.ts +56 -0
  302. package/dist/providers/dodo/react-native.d.ts.map +1 -0
  303. package/dist/providers/dodo/react-native.js +57 -0
  304. package/dist/providers/dodo/react-native.js.map +1 -0
  305. package/dist/providers/dodo/webhook-bridge.d.ts +17 -0
  306. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -0
  307. package/dist/providers/dodo/webhook-bridge.js +21 -0
  308. package/dist/providers/dodo/webhook-bridge.js.map +1 -0
  309. package/dist/providers/index.d.ts +1 -1
  310. package/dist/providers/index.d.ts.map +1 -1
  311. package/dist/providers/index.js.map +1 -1
  312. package/dist/providers/mock/index.d.ts +1 -0
  313. package/dist/providers/mock/index.d.ts.map +1 -1
  314. package/dist/providers/mock/index.js.map +1 -1
  315. package/dist/providers/mock/provider.d.ts +8 -8
  316. package/dist/providers/mock/provider.d.ts.map +1 -1
  317. package/dist/providers/mock/provider.js +26 -19
  318. package/dist/providers/mock/provider.js.map +1 -1
  319. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  320. package/dist/providers/stripe/event-mapper.js +214 -173
  321. package/dist/providers/stripe/event-mapper.js.map +1 -1
  322. package/dist/providers/stripe/index.d.ts +1 -0
  323. package/dist/providers/stripe/index.d.ts.map +1 -1
  324. package/dist/providers/stripe/index.js.map +1 -1
  325. package/dist/providers/stripe/provider.d.ts +13 -11
  326. package/dist/providers/stripe/provider.d.ts.map +1 -1
  327. package/dist/providers/stripe/provider.js +287 -107
  328. package/dist/providers/stripe/provider.js.map +1 -1
  329. package/dist/providers/types.d.ts +1 -2
  330. package/dist/providers/types.d.ts.map +1 -1
  331. package/dist/providers/types.js.map +1 -1
  332. package/dist/shared/postgres-client.d.ts +5 -0
  333. package/dist/shared/postgres-client.d.ts.map +1 -1
  334. package/dist/shared/postgres-client.js +23 -7
  335. package/dist/shared/postgres-client.js.map +1 -1
  336. package/dist/shared/postgres-validation.d.ts +15 -3
  337. package/dist/shared/postgres-validation.d.ts.map +1 -1
  338. package/dist/shared/postgres-validation.js +58 -14
  339. package/dist/shared/postgres-validation.js.map +1 -1
  340. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  341. package/dist/storage/adapters/clickhouse.js +2 -5
  342. package/dist/storage/adapters/clickhouse.js.map +1 -1
  343. package/dist/storage/adapters/s3.d.ts +0 -6
  344. package/dist/storage/adapters/s3.d.ts.map +1 -1
  345. package/dist/storage/adapters/s3.js +0 -2
  346. package/dist/storage/adapters/s3.js.map +1 -1
  347. package/dist/storage/ports.d.ts +0 -1
  348. package/dist/storage/ports.d.ts.map +1 -1
  349. package/dist/storage/ports.js.map +1 -1
  350. package/dist/storage/postgres-repository.d.ts +1 -1
  351. package/dist/storage/postgres-repository.d.ts.map +1 -1
  352. package/dist/storage/postgres-repository.js +2 -2
  353. package/dist/storage/postgres-repository.js.map +1 -1
  354. package/dist/storage/runtime.d.ts +24 -6
  355. package/dist/storage/runtime.d.ts.map +1 -1
  356. package/dist/storage/runtime.js +87 -30
  357. package/dist/storage/runtime.js.map +1 -1
  358. package/package.json +56 -7
  359. package/dist/credits/postgres/repositories/pricing.d.ts +0 -28
  360. package/dist/credits/postgres/repositories/pricing.d.ts.map +0 -1
  361. package/dist/credits/postgres/repositories/pricing.js +0 -76
  362. package/dist/credits/postgres/repositories/pricing.js.map +0 -1
  363. package/dist/credits/pricing-runtime.d.ts.map +0 -1
  364. package/dist/credits/pricing-runtime.js.map +0 -1
  365. package/dist/load-pricing-file.d.ts.map +0 -1
  366. package/dist/load-pricing-file.js.map +0 -1
@@ -4,24 +4,30 @@ import { CapReachedError, ConfigError, InsufficientCreditsError, RefundError, St
4
4
  import { raiseDeductError } from "./service-errors.js";
5
5
  import { LowBalanceMonitor } from "./low-balance-monitor.js";
6
6
  import { CreditQueries } from "./queries.js";
7
- import { PricingRuntime, toDecimal } from "./pricing-runtime.js";
7
+ import { CatalogRuntime, toDecimal } from "./catalog-runtime.js";
8
8
  import { CreditLeaseWorkflow } from "./lease-workflow.js";
9
9
  /**
10
- * Default lease TTL (seconds) for ``reserve``/``runBilled`` (interface plan §3).
10
+ * Default lease TTL (seconds) for ``reserve`` and ``runBilled``.
11
11
  * Long batch/agentic jobs call the configured lease TTL before this elapses.
12
12
  */
13
13
  const DEFAULT_LEASE_TTL_SECONDS = 600;
14
14
  const POLICY_PRESETS = new Set(["strict_prepaid", "overdraft"]);
15
+ function positiveAmount(value, operation) {
16
+ const amount = toDecimal(value);
17
+ if (!amount.isFinite() || !amount.gt(0)) {
18
+ throw new RangeError(`${operation} amount must be finite and greater than zero`);
19
+ }
20
+ return amount;
21
+ }
15
22
  import { normalizeLogger } from "../shared/logger.js";
16
23
  /**
17
24
  * Orchestrates credit operations.
18
25
  *
19
26
  * The deduction path is a single atomic, idempotency-keyed store call
20
27
  * (``deductWithAllowance``) that consumes free allowance, enforces plan policy,
21
- * and debits the net amount in one transaction
22
- * (contract §2). The manager is a thin layer that calculates the cost, maps
28
+ * and debits the net amount in one transaction. The service calculates the cost, maps
23
29
  * the store's typed ``error`` codes to exceptions, and emits lifecycle events
24
- * **only after** the operation has succeeded (contract §6).
30
+ * **only after** the operation has succeeded.
25
31
  *
26
32
  * Optionally accepts a ``CreditEventEmitter`` to emit lifecycle events
27
33
  * (deducted, deduct_failed, added, refunded, refund_failed, expired,
@@ -30,7 +36,7 @@ import { normalizeLogger } from "../shared/logger.js";
30
36
  export class CreditsService {
31
37
  store;
32
38
  queries;
33
- pricing;
39
+ catalogRuntime;
34
40
  leases;
35
41
  emitter = null;
36
42
  balanceMonitor;
@@ -52,10 +58,10 @@ export class CreditsService {
52
58
  this.logger = normalizeLogger(options?.logger);
53
59
  if (options?.postDeduction)
54
60
  this.postDeductionHooks.add(options.postDeduction);
55
- this.pricing = new PricingRuntime(store, engine ?? null, this.logger, options?.pricingTtl ?? 300_000);
61
+ this.catalogRuntime = new CatalogRuntime(store, engine ?? null, this.logger, options?.catalogCacheTtlMs ?? 300_000);
56
62
  this.balanceMonitor = new LowBalanceMonitor(options?.lowBalance, (type, userId, data) => this.emit(type, userId, data), this.logger);
57
63
  this.lazyExpiry = options?.lazyExpiry ?? false;
58
- this.leases = new CreditLeaseWorkflow(store, this.pricing, this.logger, this.balanceMonitor, policy, options?.overdraftFloor != null ? toDecimal(options.overdraftFloor) : null, options?.maxConcurrent ?? null, options?.defaultTtlSeconds ?? DEFAULT_LEASE_TTL_SECONDS, (type, userId, data) => this.emit(type, userId, data), (userId, idempotencyKey) => this.emitQuotaEvents(userId, idempotencyKey), (userId) => this.maybeLazyExpire(userId), (userId, result) => this.afterDeduction(userId, "settle", result));
64
+ this.leases = new CreditLeaseWorkflow(store, this.catalogRuntime, this.logger, this.balanceMonitor, policy, options?.overdraftFloor != null ? toDecimal(options.overdraftFloor) : null, options?.maxConcurrent ?? null, options?.defaultTtlSeconds ?? DEFAULT_LEASE_TTL_SECONDS, (type, userId, data) => this.emit(type, userId, data), (userId, idempotencyKey) => this.emitQuotaEvents(userId, idempotencyKey), (userId) => this.maybeLazyExpire(userId), (userId, result) => this.afterDeduction(userId, "settle", result));
59
65
  }
60
66
  /**
61
67
  * Register an awaited post-commit deduction hook. A failing hook is logged
@@ -79,8 +85,8 @@ export class CreditsService {
79
85
  }
80
86
  }
81
87
  }
82
- async getActivePricing() {
83
- return this.queries.getActivePricing();
88
+ async getActiveCatalog() {
89
+ return this.queries.getActiveCatalog();
84
90
  }
85
91
  async getUserPlan(userId) {
86
92
  return this.queries.getUserPlan(userId);
@@ -101,7 +107,16 @@ export class CreditsService {
101
107
  return this.queries.migratePlanBatch(migrationId, batchSize);
102
108
  }
103
109
  async revokeCreditsByEntryType(userId, entryType) {
104
- return this.queries.revokeCreditsByEntryType(userId, entryType);
110
+ const result = await this.queries.revokeCreditsByEntryType(userId, entryType);
111
+ if (result.revoked.gt(0)) {
112
+ this.emit("credits.revoked", userId, {
113
+ userId,
114
+ entryType,
115
+ amount: result.revoked,
116
+ balanceAfter: result.balanceAfter,
117
+ });
118
+ }
119
+ return result;
105
120
  }
106
121
  /** Execute an application-driven catalog grant program. */
107
122
  async executeGrantProgram(request) {
@@ -163,62 +178,58 @@ export class CreditsService {
163
178
  }
164
179
  }
165
180
  }
166
- /** Load pricing from a raw dict and sync it. */
167
- async publishPricingFromDict(data) {
168
- await this.pricing.publishFromDict(data);
169
- }
170
- /** Load the active pricing config from the store. */
171
- async loadPricingFromStore() {
172
- await this.pricing.loadFromStore();
181
+ /** Load the active catalog revision from the store. */
182
+ async loadCatalogFromStore() {
183
+ await this.catalogRuntime.loadFromStore();
173
184
  }
174
185
  /**
175
186
  * If the cached PricingEngine is stale (TTL expired), reload it from the
176
187
  * store. Concurrent callers are deduplicated via the underlying
177
- * ``lru-cache.fetch()`` — only one ``loadPricingFromStore`` runs and all
188
+ * ``lru-cache.fetch()`` — only one ``loadCatalogFromStore`` runs and all
178
189
  * callers await the same result.
179
190
  *
180
- * When ``pricingTtl`` is ``0``, this is a no-op (the consumer must call
181
- * ``loadPricingFromStore`` manually).
191
+ * When ``catalogCacheTtlMs`` is ``0``, this is a no-op (the consumer must call
192
+ * ``loadCatalogFromStore`` manually).
182
193
  */
183
- async refreshIfStale() {
184
- await this.pricing.refreshIfStale();
194
+ async refreshCatalogIfStale() {
195
+ await this.catalogRuntime.refreshIfStale();
185
196
  }
186
197
  /**
187
- * Invalidate the pricing cache so the next ``refreshIfStale`` call
188
- * reloads from the store. Useful after a manual ``loadPricingFromStore``
198
+ * Invalidate the catalog cache so the next ``refreshCatalogIfStale`` call
199
+ * reloads from the store. Useful after a manual ``loadCatalogFromStore``
189
200
  * that bypasses the cache, or when the consumer knows the remote config
190
201
  * has changed.
191
202
  */
192
- invalidatePricing() {
193
- this.pricing.invalidate();
203
+ invalidateCatalog() {
204
+ this.catalogRuntime.invalidate();
194
205
  }
195
206
  /**
196
- * Publish new pricing and update the engine in one call.
207
+ * Publish and activate a catalog revision, then update the local engine.
197
208
  *
198
- * H10: the store write is now **awaited** (was a fire-and-forget `void`), so
209
+ * The store write is awaited, so
199
210
  * a persistence failure surfaces to the caller instead of becoming an
200
211
  * unhandled promise rejection.
201
212
  */
202
- async publishPricing(config, label, rollout) {
203
- await this.pricing.publish(config, label, rollout);
213
+ async publishAndActivateCatalog(config, label, rollout) {
214
+ return this.catalogRuntime.publishAndActivate(config, label, rollout);
204
215
  }
205
216
  /** Publish a validated, inactive catalog draft. */
206
- async publishPricingDraft(config, label) {
207
- return this.pricing.publishDraft(config, label);
217
+ async publishCatalogDraft(config, label) {
218
+ return this.catalogRuntime.publishDraft(config, label);
208
219
  }
209
220
  /** Activate an existing catalog version and reload the local engine. */
210
- async activatePricing(version, rollout) {
211
- return this.pricing.activate(version, rollout);
221
+ async activateCatalogRevision(version, rollout) {
222
+ return this.catalogRuntime.activateRevision(version, rollout);
212
223
  }
213
224
  /** The current PricingEngine, or null if not loaded. */
214
225
  get pricingEngine() {
215
- return this.pricing.currentEngine;
226
+ return this.catalogRuntime.currentEngine;
216
227
  }
217
228
  /**
218
229
  * Set a user's subscription plan and emit ``credits.plan_changed``.
219
230
  *
220
231
  * The store call is awaited so a persistence failure surfaces to the caller.
221
- * The event is emitted only after the store write succeeds (contract §6).
232
+ * The event is emitted only after the store write succeeds.
222
233
  */
223
234
  async setUserPlan(userId, planKey, planAssignedAt) {
224
235
  this.logger.info("[CreditsService] setUserPlan", { planKey, planAssignedAt });
@@ -226,18 +237,21 @@ export class CreditsService {
226
237
  this.emit("credits.plan_changed", userId, {
227
238
  userId,
228
239
  planKey,
229
- planAssignedAt: result.planAssignedAt ?? null,
240
+ planAssignedAt: result.planAssignedAt,
241
+ assignmentState: result.assignmentState,
230
242
  timestamp: new Date().toISOString(),
231
243
  });
244
+ return result;
232
245
  }
233
246
  /** Unset a user's subscription plan and emit the plan-change event. */
234
247
  async unsetUserPlan(userId) {
235
- await this.store.unsetUserPlan(userId);
248
+ const result = await this.store.unsetUserPlan(userId);
236
249
  this.emit("credits.plan_changed", userId, {
237
250
  userId,
238
251
  planKey: null,
239
252
  timestamp: new Date().toISOString(),
240
253
  });
254
+ return result;
241
255
  }
242
256
  /** Pin or unpin the user's current assignment revision. */
243
257
  async setPlanRevisionPin(userId, pinned) {
@@ -261,7 +275,7 @@ export class CreditsService {
261
275
  async addCredits(userId, amount, options) {
262
276
  const type = options?.type ?? "adjustment";
263
277
  this.logger.info("[CreditsService] addCredits", { amount, type, bucket: options?.bucket });
264
- const result = await this.store.addCredits(userId, toDecimal(amount), type, options?.metadata, options?.expiresAt, options?.bucket, options?.idempotencyKey);
278
+ const result = await this.store.addCredits(userId, positiveAmount(amount, "addCredits"), type, options?.metadata, options?.expiresAt, options?.bucket, options?.idempotencyKey);
265
279
  this.emit("credits.added", userId, {
266
280
  entryId: result.entryId,
267
281
  amount: result.amount,
@@ -287,21 +301,27 @@ export class CreditsService {
287
301
  entryType,
288
302
  bucket: options?.bucket,
289
303
  });
290
- const result = await this.store.addCredits(userId, toDecimal(amount).neg(), entryType, options?.metadata ?? null, null, options?.bucket ?? undefined, undefined);
304
+ const result = await this.store.addCredits(userId, positiveAmount(amount, "deductCredits").neg(), entryType, options?.metadata ?? null, null, options?.bucket ?? undefined, options?.idempotencyKey);
291
305
  this.emit("credits.deducted", userId, {
292
306
  entryId: result.entryId,
293
307
  amount: result.amount,
294
308
  newBalance: result.newBalance,
295
309
  entryType,
296
- });
297
- await this.afterDeduction(userId, "raw", {
298
- entryId: result.entryId,
299
- userId,
300
- amount: result.amount.abs(),
301
- allowanceConsumed: new Decimal(0),
302
- balanceAfter: result.newBalance,
303
310
  idempotent: result.idempotent ?? false,
304
311
  });
312
+ if (!result.idempotent) {
313
+ await this.afterDeduction(userId, "raw", {
314
+ entryId: result.entryId,
315
+ userId,
316
+ amount: result.amount.abs(),
317
+ allowanceConsumed: new Decimal(0),
318
+ balanceAfter: result.newBalance,
319
+ idempotent: false,
320
+ usageChargeId: null,
321
+ error: null,
322
+ bucketBreakdown: null,
323
+ });
324
+ }
305
325
  return result;
306
326
  }
307
327
  /**
@@ -312,14 +332,12 @@ export class CreditsService {
312
332
  * 1. At most one of ``expiresAt``/``ttlDays`` may be given (throws
313
333
  * ``ConfigError`` otherwise).
314
334
  * 2. When ``ttlDays`` is given, ``expiresAt = now + ttlDays`` days.
315
- * 3. When ``replacePrior`` (default ``true``), any remaining balance in
316
- * ``bucket`` is expired immediately via a direct ``store.addCredits``
317
- * negative adjustment — naturally idempotent (a replay finds the bucket
318
- * already at zero and skips the call).
319
- * 4. The new cycle is granted via a direct ``store.addCredits`` call
335
+ * 3. The new cycle is granted via a direct ``store.addCredits`` call
320
336
  * (bypassing {@link addCredits} so only ``credits.cycle_renewed`` fires,
321
337
  * not a duplicate ``credits.added``), threading ``idempotencyKey`` so a
322
338
  * redelivered webhook replays the prior grant instead of double-crediting.
339
+ * 4. Existing bucket credits are never removed here. Subscription renewal
340
+ * policies that replace prior lots run atomically through BillingService.
323
341
  * 5. When ``planKey`` is given, assigns it via {@link setUserPlan}.
324
342
  * 6. Emits ``credits.cycle_renewed`` and returns the grant result.
325
343
  */
@@ -333,32 +351,21 @@ export class CreditsService {
333
351
  throw new ConfigError("grantSubscriptionCycle: specify at most one of 'expiresAt' or 'ttlDays', not both");
334
352
  }
335
353
  const bucket = options?.bucket ?? "subscription";
336
- const replacePrior = options?.replacePrior ?? true;
337
354
  const expiresAt = options?.ttlDays != null
338
355
  ? new Date(Date.now() + options.ttlDays * 86_400_000)
339
356
  : options?.expiresAt;
340
- const amountDec = toDecimal(amount);
341
- // Snapshot the bucket's leftover balance before granting. A redelivered
342
- // webhook must skip the replace-prior wipe as well as the duplicate grant.
343
- let priorLeftover = new Decimal(0);
344
- if (replacePrior) {
345
- const bucketsBefore = await this.getBucketBalances(userId);
346
- const current = bucketsBefore.buckets.find((t) => t.bucketKey === bucket);
347
- if (current)
348
- priorLeftover = current.balance;
349
- }
350
- let result = await this.store.addCredits(userId, amountDec, "purchase", options?.metadata, expiresAt, bucket, options?.idempotencyKey);
357
+ const amountDec = positiveAmount(amount, "grantSubscriptionCycle");
358
+ const result = await this.store.addCredits(userId, amountDec, "purchase", options?.metadata, expiresAt, bucket, options?.idempotencyKey);
351
359
  // The store contract exposes the mutation's replay result directly, avoiding
352
360
  // a racy lifetime-balance comparison and an extra database round trip.
353
361
  const isFreshGrant = !result.idempotent;
354
- if (replacePrior && isFreshGrant && priorLeftover.gt(0)) {
355
- await this.store.addCredits(userId, priorLeftover.negated(), "adjustment", { reason: "cycle_replaced" }, undefined, bucket);
356
- // Reflect the post-replace balance so the returned result is accurate
357
- // (the grant call above only knows the pre-replace balance).
358
- result = { ...result, newBalance: (await this.getBalance(userId)).balance };
359
- }
360
362
  if (options?.planKey) {
361
- await this.setUserPlan(userId, options.planKey);
363
+ // A fresh cycle intentionally re-anchors plan-assignment windows. On a
364
+ // webhook replay, repair a previously interrupted grant->assignment saga
365
+ // without re-anchoring an assignment that already succeeded.
366
+ if (isFreshGrant || (await this.getUserPlan(userId)).planKey !== options.planKey) {
367
+ await this.setUserPlan(userId, options.planKey);
368
+ }
362
369
  }
363
370
  this.emit("credits.cycle_renewed", userId, {
364
371
  entryId: result.entryId,
@@ -367,10 +374,11 @@ export class CreditsService {
367
374
  bucket,
368
375
  planKey: options?.planKey ?? null,
369
376
  idempotencyKey: options?.idempotencyKey ?? null,
377
+ idempotent: result.idempotent,
370
378
  });
371
379
  return result;
372
380
  }
373
- // ── Lease lifecycle: atomic admission (interface plan §3/§4) ────────
381
+ // ── Lease lifecycle: atomic admission ───────────────────────────────
374
382
  async reserve(userId, metricsOrAmount, options) {
375
383
  return this.leases.reserve(userId, metricsOrAmount, options);
376
384
  }
@@ -399,7 +407,7 @@ export class CreditsService {
399
407
  return this.leases.beginBilledOperation(userId, options);
400
408
  }
401
409
  /**
402
- * Full deduction flow as one atomic store call (contract §2).
410
+ * Full deduction flow as one atomic store call.
403
411
  *
404
412
  * 1. ``breakdown = engine.calculate(metrics)``; ``cost = breakdown.total``
405
413
  * (exact `Decimal`, **no truncation**).
@@ -409,22 +417,23 @@ export class CreditsService {
409
417
  * On a store ``error`` a ``credits.deduct_failed`` event is emitted and a
410
418
  * typed exception is thrown. No success event is emitted on error.
411
419
  */
412
- async deduct(userId, metrics, idempotencyKey, metadata,
413
- /** Entitlement feature required for this operation. */
414
- feature) {
420
+ async deduct(userId, metrics, options) {
415
421
  await this.maybeLazyExpire(userId);
416
- this.logger.debug("[CreditsService] deduct", { model: metrics.dimensions?.model, feature });
417
- const engine = await this.pricing.engineForUser(userId);
422
+ this.logger.debug("[CreditsService] deduct", {
423
+ model: metrics.dimensions?.model,
424
+ feature: options?.feature,
425
+ });
426
+ const engine = await this.catalogRuntime.engineForUser(userId);
418
427
  const plan = await this.store.getUserPlan(userId);
419
- const effectiveIdempotencyKey = idempotencyKey ?? `usage:${randomUUID()}`;
420
- // 1) Calculate cost — exact Decimal, never truncated (H1).
428
+ const effectiveIdempotencyKey = options?.idempotencyKey ?? `usage:${randomUUID()}`;
429
+ // 1) Calculate cost as an exact Decimal, never truncated.
421
430
  const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
422
431
  const cost = breakdown.total;
423
432
  // Build ledger metadata: caller fields FIRST, system fields LAST so the
424
- // system fields win (contract §5 / M7).
433
+ // protected system fields win.
425
434
  const meta = {};
426
- if (metadata) {
427
- for (const [k, v] of Object.entries(metadata)) {
435
+ if (options?.metadata) {
436
+ for (const [k, v] of Object.entries(options.metadata)) {
428
437
  if (v != null)
429
438
  meta[k] = v;
430
439
  }
@@ -434,10 +443,10 @@ export class CreditsService {
434
443
  meta["dimensions"] = { ...(metrics.dimensions ?? {}) };
435
444
  meta["breakdownTotal"] = breakdown.total.toString();
436
445
  meta["idempotencyKey"] = effectiveIdempotencyKey;
437
- const options = {
446
+ const deductionOptions = {
438
447
  idempotencyKey: effectiveIdempotencyKey,
439
448
  operation: metrics.operation,
440
- feature: feature ?? null,
449
+ feature: options?.feature ?? null,
441
450
  model: typeof metrics.dimensions?.model === "string" ? metrics.dimensions.model : null,
442
451
  region: typeof metrics.dimensions?.region === "string" ? metrics.dimensions.region : null,
443
452
  measures: { ...(metrics.measures ?? {}) },
@@ -446,8 +455,8 @@ export class CreditsService {
446
455
  };
447
456
  // 2) Atomic charge. This records zero-cost usage too, so authorization,
448
457
  // quotas, and usage history cannot be bypassed by a free rate.
449
- const result = await this.store.deductWithAllowance(userId, cost, options);
450
- if (result.error) {
458
+ const result = await this.store.deductWithAllowance(userId, cost, deductionOptions);
459
+ if (result.error !== null) {
451
460
  if (result.error === "quota_exceeded") {
452
461
  await this.emitQuotaEvents(userId, effectiveIdempotencyKey);
453
462
  }
@@ -455,7 +464,7 @@ export class CreditsService {
455
464
  error: result.error,
456
465
  amount: cost,
457
466
  model: metrics.dimensions?.model,
458
- feature,
467
+ feature: options?.feature,
459
468
  });
460
469
  this.emit("credits.deduct_failed", userId, {
461
470
  error: result.error,
@@ -473,7 +482,7 @@ export class CreditsService {
473
482
  model: metrics.dimensions?.model ?? null,
474
483
  idempotent: result.idempotent,
475
484
  });
476
- // low_balance is EDGE-triggered (M18): only fire when THIS deduction crossed
485
+ // low_balance is edge-triggered: only fire when this deduction crossed
477
486
  // the threshold. A replayed (idempotent) result did not move the balance, so
478
487
  // it never crosses. balanceBefore = balanceAfter + amount charged.
479
488
  if (!result.idempotent) {
@@ -487,18 +496,17 @@ export class CreditsService {
487
496
  /**
488
497
  * Record priced usage for a workflow without debiting the account again.
489
498
  *
490
- * This is intended for child work inside a fixed-price operation. The
491
- * parent operation remains the only customer debit; the returned usage row
492
- * preserves the child cost and metadata in Bursar's usage journal.
499
+ * This supports priced usage receipts that should be retained without
500
+ * affecting the account balance, such as externally billed usage.
493
501
  */
494
- async recordUsage(userId, metrics, idempotencyKey, metadata) {
495
- const engine = await this.pricing.engineForUser(userId);
502
+ async recordUsage(userId, metrics, options) {
503
+ const engine = await this.catalogRuntime.engineForUser(userId);
496
504
  const plan = await this.store.getUserPlan(userId);
497
- const effectiveIdempotencyKey = idempotencyKey ?? `usage-record:${randomUUID()}`;
505
+ const effectiveIdempotencyKey = options?.idempotencyKey ?? `usage-record:${randomUUID()}`;
498
506
  const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
499
507
  const meta = {};
500
- if (metadata) {
501
- for (const [key, value] of Object.entries(metadata)) {
508
+ if (options?.metadata) {
509
+ for (const [key, value] of Object.entries(options.metadata)) {
502
510
  if (value != null)
503
511
  meta[key] = value;
504
512
  }
@@ -517,7 +525,7 @@ export class CreditsService {
517
525
  dimensions: { ...(metrics.dimensions ?? {}) },
518
526
  metadata: meta,
519
527
  });
520
- if (result.error) {
528
+ if (result.error !== null) {
521
529
  throw new StoreError(`Usage record failed: ${result.error}`);
522
530
  }
523
531
  return result;
@@ -531,23 +539,29 @@ export class CreditsService {
531
539
  * refund).
532
540
  */
533
541
  /** Deduct the configured fixed cost for one named job. */
534
- async deductFlatJob(userId, jobName, idempotencyKey, metadata, feature) {
535
- return this.deduct(userId, { operation: jobName, measures: { jobs: 1 } }, idempotencyKey, metadata, feature);
536
- }
537
- async refundCredits(entryId, amount, reason, metadata, idempotencyKey) {
538
- const refundAmount = amount != null ? toDecimal(amount) : undefined;
539
- this.logger.info("[CreditsService] refundCredits", { entryId, refundAmount, reason });
540
- const result = await this.store.refundCredits(entryId, refundAmount, reason, metadata, idempotencyKey);
541
- if (result.error) {
542
+ async deductFlatJob(userId, jobName, options) {
543
+ return this.deduct(userId, { operation: jobName, measures: { jobs: 1 } }, options);
544
+ }
545
+ async refundCredits(entryId, options) {
546
+ const refundAmount = options?.amount != null ? positiveAmount(options.amount, "refundCredits") : undefined;
547
+ this.logger.info("[CreditsService] refundCredits", {
548
+ entryId,
549
+ refundAmount,
550
+ reason: options?.reason,
551
+ });
552
+ const result = await this.store.refundCredits(entryId, refundAmount, options?.reason, options?.metadata, options?.idempotencyKey);
553
+ if (result.error !== null) {
542
554
  this.logger.warn("[CreditsService] refundCredits failed", {
543
555
  entryId,
544
556
  error: result.error,
545
557
  });
546
- this.emit("credits.refund_failed", result.userId, {
547
- entryId,
548
- error: result.error,
549
- reason: reason ?? null,
550
- });
558
+ if (result.userId !== null) {
559
+ this.emit("credits.refund_failed", result.userId, {
560
+ entryId,
561
+ error: result.error,
562
+ reason: options?.reason ?? null,
563
+ });
564
+ }
551
565
  throw new RefundError(`Refund rejected: ${result.error}`);
552
566
  }
553
567
  this.emit("credits.refunded", result.userId, {
@@ -555,7 +569,7 @@ export class CreditsService {
555
569
  refundEntryId: result.refundEntryId,
556
570
  amount: result.amount,
557
571
  newBalance: result.newBalance,
558
- reason: reason ?? null,
572
+ reason: options?.reason ?? null,
559
573
  });
560
574
  return result;
561
575
  }
@@ -564,38 +578,43 @@ export class CreditsService {
564
578
  *
565
579
  * Calculates the cost via the pricing engine (exact `Decimal`, no truncation),
566
580
  * then debits the team balance. Threads an optional ``idempotencyKey`` through
567
- * to the store so retried team charges are not double-counted (H12).
581
+ * to the store so retried team charges are not double-counted.
568
582
  */
569
- async deductTeam(teamId, userId, metrics, idempotencyKey, metadata) {
583
+ async deductTeam(teamId, userId, metrics, options) {
570
584
  await this.maybeLazyExpire(userId);
571
585
  // Lazy expiry is scoped to the individual member's credits, not the team's
572
586
  // shared pool — there's no per-team expiry concept.
573
- const engine = await this.pricing.engineForUser(userId);
587
+ const engine = await this.catalogRuntime.engineForUser(userId);
574
588
  const plan = await this.store.getUserPlan(userId);
575
589
  const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
576
590
  const cost = breakdown.total;
577
591
  if (cost.lte(0)) {
578
592
  const teamBal = await this.store.getTeamBalance(teamId);
593
+ if (teamBal === null) {
594
+ throw new StoreError(`Team not found: ${teamId}`);
595
+ }
579
596
  return {
580
- entryId: "",
597
+ entryId: null,
581
598
  teamId,
582
599
  userId,
583
600
  amount: new Decimal(0),
584
601
  teamBalanceAfter: teamBal.balance,
602
+ idempotent: false,
603
+ error: null,
585
604
  };
586
605
  }
587
606
  const teamMetadata = {
588
- ...(metadata ?? {}),
607
+ ...(options?.metadata ?? {}),
589
608
  operation: metrics.operation,
590
609
  measures: { ...(metrics.measures ?? {}) },
591
610
  dimensions: Object.fromEntries(Object.entries(metrics.dimensions ?? {}).map(([key, value]) => [key, String(value)])),
592
611
  breakdownTotal: breakdown.total.toString(),
593
612
  };
594
- const result = await this.store.deductTeam(teamId, userId, cost, teamMetadata, idempotencyKey);
595
- // H2 fix: surface store errors — emit credits.deduct_failed and throw,
613
+ const result = await this.store.deductTeam(teamId, userId, cost, teamMetadata, options?.idempotencyKey);
614
+ // Surface store errors: emit credits.deduct_failed and throw,
596
615
  // mirroring the Python credit service implementation. Previously returned a silent
597
616
  // success-shaped object with an .error field, so failed charges looked OK.
598
- if (result.error) {
617
+ if (result.error !== null) {
599
618
  this.emit("credits.deduct_failed", userId, {
600
619
  error: result.error,
601
620
  amount: cost,