@zonastery/bursar 2.0.6 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (379) hide show
  1. package/README.md +33 -4
  2. package/dist/billing/auto-recharge-port.d.ts +11 -0
  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.map +1 -1
  6. package/dist/billing/auto-recharge-service.js +53 -26
  7. package/dist/billing/auto-recharge-service.js.map +1 -1
  8. package/dist/billing/billing-service.d.ts +38 -3
  9. package/dist/billing/billing-service.d.ts.map +1 -1
  10. package/dist/billing/billing-service.js +51 -7
  11. package/dist/billing/billing-service.js.map +1 -1
  12. package/dist/billing/billing-store.d.ts +34 -9
  13. package/dist/billing/billing-store.d.ts.map +1 -1
  14. package/dist/billing/billing-store.js +2 -0
  15. package/dist/billing/billing-store.js.map +1 -1
  16. package/dist/billing/contracts.d.ts +35 -3
  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 +1 -2
  20. package/dist/billing/event-handlers.d.ts.map +1 -1
  21. package/dist/billing/event-handlers.js +69 -29
  22. package/dist/billing/event-handlers.js.map +1 -1
  23. package/dist/billing/event-processor.d.ts +2 -2
  24. package/dist/billing/event-processor.d.ts.map +1 -1
  25. package/dist/billing/event-processor.js +82 -19
  26. package/dist/billing/event-processor.js.map +1 -1
  27. package/dist/billing/financial-event-handlers.d.ts +2 -0
  28. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  29. package/dist/billing/financial-event-handlers.js +168 -44
  30. package/dist/billing/financial-event-handlers.js.map +1 -1
  31. package/dist/billing/index.d.ts +1 -1
  32. package/dist/billing/index.d.ts.map +1 -1
  33. package/dist/billing/index.js.map +1 -1
  34. package/dist/billing/management.d.ts +16 -3
  35. package/dist/billing/management.d.ts.map +1 -1
  36. package/dist/billing/management.js +11 -2
  37. package/dist/billing/management.js.map +1 -1
  38. package/dist/billing/postgres/repositories/auto-recharge.d.ts +13 -1
  39. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  40. package/dist/billing/postgres/repositories/auto-recharge.js +71 -12
  41. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  42. package/dist/billing/postgres/repositories/invoice.d.ts +3 -2
  43. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  44. package/dist/billing/postgres/repositories/invoice.js +33 -3
  45. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  46. package/dist/billing/postgres/repositories/offer.d.ts +5 -1
  47. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  48. package/dist/billing/postgres/repositories/offer.js +7 -10
  49. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  50. package/dist/billing/postgres/repositories/payment.d.ts +6 -1
  51. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  52. package/dist/billing/postgres/repositories/payment.js +25 -16
  53. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  54. package/dist/billing/postgres/repositories/subscription-change.d.ts +1 -0
  55. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -1
  56. package/dist/billing/postgres/repositories/subscription-change.js +25 -4
  57. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
  58. package/dist/billing/postgres/repositories/subscription.d.ts +3 -2
  59. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  60. package/dist/billing/postgres/repositories/subscription.js +44 -48
  61. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  62. package/dist/billing/postgres/repositories/topup.d.ts +6 -1
  63. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  64. package/dist/billing/postgres/repositories/topup.js +27 -10
  65. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  66. package/dist/billing/postgres/store.d.ts +46 -34
  67. package/dist/billing/postgres/store.d.ts.map +1 -1
  68. package/dist/billing/postgres/store.js +152 -126
  69. package/dist/billing/postgres/store.js.map +1 -1
  70. package/dist/billing/service-types.d.ts +0 -1
  71. package/dist/billing/service-types.d.ts.map +1 -1
  72. package/dist/billing/service-types.js.map +1 -1
  73. package/dist/billing/types/auto-recharge.d.ts +2 -0
  74. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  75. package/dist/billing/types/auto-recharge.js.map +1 -1
  76. package/dist/billing/types/catalog.d.ts +1 -0
  77. package/dist/billing/types/catalog.d.ts.map +1 -1
  78. package/dist/billing/types/catalog.js.map +1 -1
  79. package/dist/billing/types/documents.d.ts +15 -1
  80. package/dist/billing/types/documents.d.ts.map +1 -1
  81. package/dist/billing/types/documents.js.map +1 -1
  82. package/dist/billing/types/events.d.ts +2 -0
  83. package/dist/billing/types/events.d.ts.map +1 -1
  84. package/dist/billing/types/events.js +15 -0
  85. package/dist/billing/types/events.js.map +1 -1
  86. package/dist/billing/types/subscriptions.d.ts +12 -0
  87. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  88. package/dist/billing/types/subscriptions.js.map +1 -1
  89. package/dist/breakdown.d.ts +2 -24
  90. package/dist/breakdown.d.ts.map +1 -1
  91. package/dist/breakdown.js +1 -29
  92. package/dist/breakdown.js.map +1 -1
  93. package/dist/bursar.d.ts +13 -21
  94. package/dist/bursar.d.ts.map +1 -1
  95. package/dist/bursar.js +44 -50
  96. package/dist/bursar.js.map +1 -1
  97. package/dist/catalog.d.ts +21 -2
  98. package/dist/catalog.d.ts.map +1 -1
  99. package/dist/catalog.js +27 -4
  100. package/dist/catalog.js.map +1 -1
  101. package/dist/cli.d.ts +3 -0
  102. package/dist/cli.d.ts.map +1 -0
  103. package/dist/cli.js +147 -0
  104. package/dist/cli.js.map +1 -0
  105. package/dist/commerce/plan-change.d.ts +3 -3
  106. package/dist/commerce/plan-change.d.ts.map +1 -1
  107. package/dist/commerce/plan-change.js +14 -7
  108. package/dist/commerce/plan-change.js.map +1 -1
  109. package/dist/commerce/provider-registry.d.ts.map +1 -1
  110. package/dist/commerce/provider-registry.js +8 -2
  111. package/dist/commerce/provider-registry.js.map +1 -1
  112. package/dist/commerce/service.d.ts +2 -0
  113. package/dist/commerce/service.d.ts.map +1 -1
  114. package/dist/commerce/service.js +330 -76
  115. package/dist/commerce/service.js.map +1 -1
  116. package/dist/commerce/types.d.ts +12 -3
  117. package/dist/commerce/types.d.ts.map +1 -1
  118. package/dist/commerce/types.js.map +1 -1
  119. package/dist/config/availability.d.ts +4 -0
  120. package/dist/config/availability.d.ts.map +1 -0
  121. package/dist/config/availability.js +10 -0
  122. package/dist/config/availability.js.map +1 -0
  123. package/dist/config/normalize.d.ts +7 -0
  124. package/dist/config/normalize.d.ts.map +1 -0
  125. package/dist/config/normalize.js +119 -0
  126. package/dist/config/normalize.js.map +1 -0
  127. package/dist/config/parse-access.d.ts.map +1 -1
  128. package/dist/config/parse-access.js +4 -1
  129. package/dist/config/parse-access.js.map +1 -1
  130. package/dist/config/parse-commerce.d.ts +5 -1
  131. package/dist/config/parse-commerce.d.ts.map +1 -1
  132. package/dist/config/parse-commerce.js +79 -22
  133. package/dist/config/parse-commerce.js.map +1 -1
  134. package/dist/config/parse-credits.d.ts.map +1 -1
  135. package/dist/config/parse-credits.js +10 -7
  136. package/dist/config/parse-credits.js.map +1 -1
  137. package/dist/config/parse-plans.d.ts.map +1 -1
  138. package/dist/config/parse-plans.js +31 -15
  139. package/dist/config/parse-plans.js.map +1 -1
  140. package/dist/config/parse-pricing.d.ts.map +1 -1
  141. package/dist/config/parse-pricing.js +42 -27
  142. package/dist/config/parse-pricing.js.map +1 -1
  143. package/dist/config/parse-utils.d.ts +4 -0
  144. package/dist/config/parse-utils.d.ts.map +1 -1
  145. package/dist/config/parse-utils.js +26 -1
  146. package/dist/config/parse-utils.js.map +1 -1
  147. package/dist/config/types.d.ts +8 -4
  148. package/dist/config/types.d.ts.map +1 -1
  149. package/dist/config/types.js.map +1 -1
  150. package/dist/config.d.ts +5 -4
  151. package/dist/config.d.ts.map +1 -1
  152. package/dist/config.js +118 -70
  153. package/dist/config.js.map +1 -1
  154. package/dist/credits/amount.d.ts.map +1 -1
  155. package/dist/credits/amount.js +5 -4
  156. package/dist/credits/amount.js.map +1 -1
  157. package/dist/credits/catalog-runtime.d.ts +15 -2
  158. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  159. package/dist/credits/catalog-runtime.js +77 -21
  160. package/dist/credits/catalog-runtime.js.map +1 -1
  161. package/dist/credits/lease-workflow.d.ts +3 -1
  162. package/dist/credits/lease-workflow.d.ts.map +1 -1
  163. package/dist/credits/lease-workflow.js +47 -38
  164. package/dist/credits/lease-workflow.js.map +1 -1
  165. package/dist/credits/low-balance-monitor.d.ts +2 -7
  166. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  167. package/dist/credits/low-balance-monitor.js +6 -57
  168. package/dist/credits/low-balance-monitor.js.map +1 -1
  169. package/dist/credits/postgres/repositories/analytics.d.ts +3 -3
  170. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  171. package/dist/credits/postgres/repositories/analytics.js +25 -7
  172. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  173. package/dist/credits/postgres/repositories/balance.d.ts +28 -0
  174. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  175. package/dist/credits/postgres/repositories/balance.js +33 -14
  176. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  177. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
  178. package/dist/credits/postgres/repositories/bucket.js +2 -2
  179. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  180. package/dist/credits/postgres/repositories/catalog.d.ts +2 -2
  181. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
  182. package/dist/credits/postgres/repositories/catalog.js +2 -12
  183. package/dist/credits/postgres/repositories/catalog.js.map +1 -1
  184. package/dist/credits/postgres/repositories/deduction.d.ts +2 -0
  185. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  186. package/dist/credits/postgres/repositories/deduction.js +9 -2
  187. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  188. package/dist/credits/postgres/repositories/lease.d.ts +3 -0
  189. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  190. package/dist/credits/postgres/repositories/lease.js +46 -12
  191. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  192. package/dist/credits/postgres/repositories/plan.d.ts +6 -1
  193. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
  194. package/dist/credits/postgres/repositories/plan.js +13 -3
  195. package/dist/credits/postgres/repositories/plan.js.map +1 -1
  196. package/dist/credits/postgres/repositories/team.d.ts +1 -1
  197. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  198. package/dist/credits/postgres/repositories/team.js +9 -5
  199. package/dist/credits/postgres/repositories/team.js.map +1 -1
  200. package/dist/credits/postgres/store.d.ts +30 -20
  201. package/dist/credits/postgres/store.d.ts.map +1 -1
  202. package/dist/credits/postgres/store.js +335 -251
  203. package/dist/credits/postgres/store.js.map +1 -1
  204. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  205. package/dist/credits/postgres/value-mappers.js +4 -4
  206. package/dist/credits/postgres/value-mappers.js.map +1 -1
  207. package/dist/credits/rated-wire.d.ts +7 -0
  208. package/dist/credits/rated-wire.d.ts.map +1 -0
  209. package/dist/credits/rated-wire.js +70 -0
  210. package/dist/credits/rated-wire.js.map +1 -0
  211. package/dist/credits/service-errors.d.ts.map +1 -1
  212. package/dist/credits/service-errors.js +8 -1
  213. package/dist/credits/service-errors.js.map +1 -1
  214. package/dist/credits/service-types.d.ts +5 -7
  215. package/dist/credits/service-types.d.ts.map +1 -1
  216. package/dist/credits/service-types.js.map +1 -1
  217. package/dist/credits/service.d.ts +12 -9
  218. package/dist/credits/service.d.ts.map +1 -1
  219. package/dist/credits/service.js +161 -138
  220. package/dist/credits/service.js.map +1 -1
  221. package/dist/credits/store.d.ts +11 -3
  222. package/dist/credits/store.d.ts.map +1 -1
  223. package/dist/credits/store.js +9 -0
  224. package/dist/credits/store.js.map +1 -1
  225. package/dist/credits/types/account.d.ts +9 -1
  226. package/dist/credits/types/account.d.ts.map +1 -1
  227. package/dist/credits/types/account.js.map +1 -1
  228. package/dist/credits/types/admission.d.ts +1 -0
  229. package/dist/credits/types/admission.d.ts.map +1 -1
  230. package/dist/credits/types/admission.js.map +1 -1
  231. package/dist/credits/types/catalog.d.ts +1 -0
  232. package/dist/credits/types/catalog.d.ts.map +1 -1
  233. package/dist/credits/types/catalog.js.map +1 -1
  234. package/dist/credits/types/grants.d.ts +12 -0
  235. package/dist/credits/types/grants.d.ts.map +1 -1
  236. package/dist/credits/types/grants.js.map +1 -1
  237. package/dist/credits/types/ledger.d.ts +13 -0
  238. package/dist/credits/types/ledger.d.ts.map +1 -1
  239. package/dist/credits/types/ledger.js.map +1 -1
  240. package/dist/credits/types/quotas.d.ts +2 -1
  241. package/dist/credits/types/quotas.d.ts.map +1 -1
  242. package/dist/credits/types/quotas.js.map +1 -1
  243. package/dist/engine.d.ts +4 -1
  244. package/dist/engine.d.ts.map +1 -1
  245. package/dist/engine.js +59 -36
  246. package/dist/engine.js.map +1 -1
  247. package/dist/errors.d.ts +12 -1
  248. package/dist/errors.d.ts.map +1 -1
  249. package/dist/errors.js +13 -0
  250. package/dist/errors.js.map +1 -1
  251. package/dist/expr/evaluator.d.ts.map +1 -1
  252. package/dist/expr/evaluator.js +29 -9
  253. package/dist/expr/evaluator.js.map +1 -1
  254. package/dist/expr/language.js +1 -1
  255. package/dist/expr/language.js.map +1 -1
  256. package/dist/expr.d.ts.map +1 -1
  257. package/dist/expr.js +5 -6
  258. package/dist/expr.js.map +1 -1
  259. package/dist/generated/pricing-config.schema.json +272 -228
  260. package/dist/generated/pricing-config.types.d.ts +128 -79
  261. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  262. package/dist/generated/pricing-config.types.js.map +1 -1
  263. package/dist/index.d.ts +8 -6
  264. package/dist/index.d.ts.map +1 -1
  265. package/dist/index.js +4 -2
  266. package/dist/index.js.map +1 -1
  267. package/dist/load-config-file.d.ts +5 -1
  268. package/dist/load-config-file.d.ts.map +1 -1
  269. package/dist/load-config-file.js +56 -17
  270. package/dist/load-config-file.js.map +1 -1
  271. package/dist/metrics.d.ts +1 -1
  272. package/dist/metrics.d.ts.map +1 -1
  273. package/dist/metrics.js.map +1 -1
  274. package/dist/node.d.ts +2 -2
  275. package/dist/node.d.ts.map +1 -1
  276. package/dist/node.js +1 -1
  277. package/dist/node.js.map +1 -1
  278. package/dist/pricing-decimal.d.ts +7 -0
  279. package/dist/pricing-decimal.d.ts.map +1 -0
  280. package/dist/pricing-decimal.js +43 -0
  281. package/dist/pricing-decimal.js.map +1 -0
  282. package/dist/providers/dodo/better-auth-core.d.ts +1 -1
  283. package/dist/providers/dodo/better-auth-core.d.ts.map +1 -1
  284. package/dist/providers/dodo/better-auth-core.js +2 -2
  285. package/dist/providers/dodo/better-auth-core.js.map +1 -1
  286. package/dist/providers/dodo/better-auth.d.ts.map +1 -1
  287. package/dist/providers/dodo/better-auth.js +16 -2
  288. package/dist/providers/dodo/better-auth.js.map +1 -1
  289. package/dist/providers/dodo/event-mapper.d.ts +1 -1
  290. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  291. package/dist/providers/dodo/event-mapper.js +124 -18
  292. package/dist/providers/dodo/event-mapper.js.map +1 -1
  293. package/dist/providers/dodo/nextjs-core.d.ts +1 -1
  294. package/dist/providers/dodo/nextjs-core.d.ts.map +1 -1
  295. package/dist/providers/dodo/nextjs-core.js +2 -2
  296. package/dist/providers/dodo/nextjs-core.js.map +1 -1
  297. package/dist/providers/dodo/nextjs.d.ts.map +1 -1
  298. package/dist/providers/dodo/nextjs.js +16 -6
  299. package/dist/providers/dodo/nextjs.js.map +1 -1
  300. package/dist/providers/dodo/provider.d.ts +5 -2
  301. package/dist/providers/dodo/provider.d.ts.map +1 -1
  302. package/dist/providers/dodo/provider.js +46 -7
  303. package/dist/providers/dodo/provider.js.map +1 -1
  304. package/dist/providers/dodo/verified-payment-payload.d.ts +6 -0
  305. package/dist/providers/dodo/verified-payment-payload.d.ts.map +1 -0
  306. package/dist/providers/dodo/verified-payment-payload.js +42 -0
  307. package/dist/providers/dodo/verified-payment-payload.js.map +1 -0
  308. package/dist/providers/index.d.ts +1 -1
  309. package/dist/providers/index.d.ts.map +1 -1
  310. package/dist/providers/index.js.map +1 -1
  311. package/dist/providers/mock/provider.d.ts +4 -1
  312. package/dist/providers/mock/provider.d.ts.map +1 -1
  313. package/dist/providers/mock/provider.js +3 -1
  314. package/dist/providers/mock/provider.js.map +1 -1
  315. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  316. package/dist/providers/stripe/event-mapper.js +51 -24
  317. package/dist/providers/stripe/event-mapper.js.map +1 -1
  318. package/dist/providers/stripe/provider.d.ts +4 -1
  319. package/dist/providers/stripe/provider.d.ts.map +1 -1
  320. package/dist/providers/stripe/provider.js +118 -34
  321. package/dist/providers/stripe/provider.js.map +1 -1
  322. package/dist/providers/types.d.ts +16 -2
  323. package/dist/providers/types.d.ts.map +1 -1
  324. package/dist/providers/types.js +9 -0
  325. package/dist/providers/types.js.map +1 -1
  326. package/dist/shared/postgres-client.d.ts +5 -0
  327. package/dist/shared/postgres-client.d.ts.map +1 -1
  328. package/dist/shared/postgres-client.js +72 -11
  329. package/dist/shared/postgres-client.js.map +1 -1
  330. package/dist/shared/postgres-errors.d.ts.map +1 -1
  331. package/dist/shared/postgres-errors.js +6 -0
  332. package/dist/shared/postgres-errors.js.map +1 -1
  333. package/dist/shared/provider-rejection.d.ts +3 -0
  334. package/dist/shared/provider-rejection.d.ts.map +1 -0
  335. package/dist/shared/provider-rejection.js +17 -0
  336. package/dist/shared/provider-rejection.js.map +1 -0
  337. package/dist/shared/timestamp.d.ts +5 -0
  338. package/dist/shared/timestamp.d.ts.map +1 -0
  339. package/dist/shared/timestamp.js +21 -0
  340. package/dist/shared/timestamp.js.map +1 -0
  341. package/dist/starter.yaml +17 -0
  342. package/dist/storage/adapters/clickhouse.d.ts +1 -1
  343. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  344. package/dist/storage/adapters/clickhouse.js +42 -37
  345. package/dist/storage/adapters/clickhouse.js.map +1 -1
  346. package/dist/storage/adapters/s3.d.ts +5 -0
  347. package/dist/storage/adapters/s3.d.ts.map +1 -1
  348. package/dist/storage/adapters/s3.js +46 -14
  349. package/dist/storage/adapters/s3.js.map +1 -1
  350. package/dist/storage/diagnostics.d.ts +3 -7
  351. package/dist/storage/diagnostics.d.ts.map +1 -1
  352. package/dist/storage/diagnostics.js +6 -15
  353. package/dist/storage/diagnostics.js.map +1 -1
  354. package/dist/storage/outbox-worker.d.ts.map +1 -1
  355. package/dist/storage/outbox-worker.js +4 -3
  356. package/dist/storage/outbox-worker.js.map +1 -1
  357. package/dist/storage/ports.d.ts +8 -0
  358. package/dist/storage/ports.d.ts.map +1 -1
  359. package/dist/storage/ports.js.map +1 -1
  360. package/dist/storage/postgres-repository.d.ts +1 -3
  361. package/dist/storage/postgres-repository.d.ts.map +1 -1
  362. package/dist/storage/postgres-repository.js +34 -12
  363. package/dist/storage/postgres-repository.js.map +1 -1
  364. package/dist/storage/raw-json.d.ts +10 -0
  365. package/dist/storage/raw-json.d.ts.map +1 -0
  366. package/dist/storage/raw-json.js +19 -0
  367. package/dist/storage/raw-json.js.map +1 -0
  368. package/dist/storage/runtime.d.ts +15 -10
  369. package/dist/storage/runtime.d.ts.map +1 -1
  370. package/dist/storage/runtime.js +97 -68
  371. package/dist/storage/runtime.js.map +1 -1
  372. package/dist/telemetry/index.d.ts +1 -1
  373. package/dist/telemetry/index.js +1 -1
  374. package/dist/telemetry/index.js.map +1 -1
  375. package/package.json +78 -71
  376. package/dist/credits/queries.d.ts +0 -33
  377. package/dist/credits/queries.d.ts.map +0 -1
  378. package/dist/credits/queries.js +0 -71
  379. package/dist/credits/queries.js.map +0 -1
@@ -1,11 +1,11 @@
1
1
  import { Decimal } from "decimal.js";
2
2
  import { z } from "zod";
3
- import { CapReachedError, ConfigError, InsufficientCreditsError, RefundError, StoreError, } from "../errors.js";
3
+ import { CapReachedError, ConfigError, IdempotencyConflictError, InsufficientCreditsError, OperationNotAllowedError, RefundError, StoreError, } from "../errors.js";
4
4
  import { raiseDeductError } from "./service-errors.js";
5
5
  import { LowBalanceMonitor } from "./low-balance-monitor.js";
6
- import { CreditQueries } from "./queries.js";
7
6
  import { CatalogRuntime } from "./catalog-runtime.js";
8
7
  import { toDecimal } from "./amount.js";
8
+ import { ratedMeasures, ratedDimensions, callerMetadata } from "./rated-wire.js";
9
9
  import { CreditLeaseWorkflow } from "./lease-workflow.js";
10
10
  import { requireStableKey } from "../shared/idempotency.js";
11
11
  import { getDefaultInstrumentation } from "../telemetry/index.js";
@@ -37,8 +37,16 @@ import { normalizeLogger } from "../shared/logger.js";
37
37
  * low_balance).
38
38
  */
39
39
  export class CreditsService {
40
+ /** Look up a durable charge or lease after an ambiguous outcome. */
41
+ async getOperationReceipt(userId, key, kind) {
42
+ return this.store.getOperationReceipt(userId, requireStableKey(key), kind);
43
+ }
40
44
  store;
41
- queries;
45
+ get providerEnvironment() {
46
+ return this.store.providerEnvironment;
47
+ }
48
+ analytics;
49
+ usageStore;
42
50
  catalogRuntime;
43
51
  leases;
44
52
  emitter = null;
@@ -53,7 +61,8 @@ export class CreditsService {
53
61
  constructor(store, engine, emitter, options) {
54
62
  this.store = store;
55
63
  this.instrumentation = options?.instrumentation ?? getDefaultInstrumentation();
56
- this.queries = new CreditQueries(store, options?.analytics ?? store, options?.usageStore ?? store);
64
+ this.analytics = options?.analytics ?? store;
65
+ this.usageStore = options?.usageStore ?? store;
57
66
  const policy = options?.policy ?? "strict_prepaid";
58
67
  if (!POLICY_PRESETS.has(policy)) {
59
68
  throw new ConfigError(`unknown policy preset '${policy}'; expected one of ${[...POLICY_PRESETS].sort().join(", ")}`);
@@ -91,28 +100,28 @@ export class CreditsService {
91
100
  }
92
101
  }
93
102
  async getActiveCatalog() {
94
- return this.queries.getActiveCatalog();
103
+ return this.store.getActiveCatalog();
95
104
  }
96
105
  async getUserPlan(userId) {
97
- return this.queries.getUserPlan(userId);
106
+ return this.store.getUserPlan(userId);
98
107
  }
99
108
  async checkFeature(userId, feature) {
100
- return this.queries.checkFeature(userId, feature);
109
+ return this.store.checkFeature(userId, feature);
101
110
  }
102
111
  async getQuotaState(userId, quotaKey) {
103
- return this.queries.getQuotaState(userId, quotaKey);
112
+ return this.store.getQuotaState(userId, quotaKey);
104
113
  }
105
114
  async listQuotaEvents(userId, options) {
106
- return this.queries.listQuotaEvents(userId, options);
115
+ return this.store.listQuotaEvents(userId, options);
107
116
  }
108
117
  async startPlanMigration(fromPlanId, toPlanId) {
109
- return this.queries.startPlanMigration(fromPlanId, toPlanId);
118
+ return this.store.startPlanMigration(fromPlanId, toPlanId);
110
119
  }
111
120
  async migratePlanBatch(migrationId, batchSize) {
112
- return this.queries.migratePlanBatch(migrationId, batchSize);
121
+ return this.store.migratePlanBatch(migrationId, batchSize);
113
122
  }
114
123
  async revokeCreditsByEntryType(userId, entryType) {
115
- const result = await this.queries.revokeCreditsByEntryType(userId, entryType);
124
+ const result = await this.store.revokeCreditsByEntryType(userId, entryType);
116
125
  if (result.revoked.gt(0)) {
117
126
  this.emit("credits.revoked", userId, {
118
127
  userId,
@@ -120,6 +129,7 @@ export class CreditsService {
120
129
  amount: result.revoked,
121
130
  balanceAfter: result.balanceAfter,
122
131
  });
132
+ await this.balanceMonitor.signalCrossing(userId, result.balanceAfter.plus(result.revoked), result.balanceAfter);
123
133
  }
124
134
  return result;
125
135
  }
@@ -128,44 +138,57 @@ export class CreditsService {
128
138
  return this.instrumentation.run("credits.grant_program", undefined, () => this.store.executeGrantProgram(request));
129
139
  }
130
140
  async getLedgerEntry(userId, entryId) {
131
- return this.queries.getLedgerEntry(userId, entryId);
141
+ return this.store.getLedgerEntry(userId, entryId);
132
142
  }
133
143
  async getAvailable(userId) {
134
- return this.queries.getAvailable(userId);
144
+ return this.store.getAvailable(userId);
135
145
  }
136
146
  async aggregateStats(start, end) {
137
- return this.queries.aggregateStats(start, end);
147
+ return this.analytics.aggregateStats(start, end);
138
148
  }
139
149
  async spendByUser(start, end) {
140
- return this.queries.spendByUser(start, end);
150
+ return this.analytics.spendByUser(start, end);
141
151
  }
142
152
  async spendByModel(start, end) {
143
- return this.queries.spendByModel(start, end);
153
+ return this.analytics.spendByModel(start, end);
144
154
  }
145
155
  async listLedgerEntries(userId, options) {
146
- return this.queries.listLedgerEntries(userId, options);
156
+ return this.store.listLedgerEntries(userId, options);
147
157
  }
148
158
  async listUsageEntries(userId, options) {
149
- return this.queries.listUsageEntries(userId, options);
159
+ return this.store.listUsageEntries(userId, options);
150
160
  }
151
161
  async listUsageCharges(userId, options) {
152
- return this.queries.listUsageCharges(userId, options);
162
+ return this.usageStore.listUsageCharges(userId, options);
153
163
  }
154
164
  async topUsers(limit, start, end) {
155
- return this.queries.topUsers(limit, start, end);
165
+ return this.analytics.topUsers(limit, start, end);
156
166
  }
157
167
  async dailySpend(start, end) {
158
- return this.queries.dailySpend(start, end);
168
+ return this.analytics.dailySpend(start, end);
159
169
  }
160
170
  /** Emit a credit lifecycle event. No-op if no emitter is configured. */
161
171
  emit(type, userId, data) {
162
172
  this.emitter?.emit({ type, timestamp: new Date(), userId, data });
163
173
  }
164
174
  async emitQuotaEvents(userId, idempotencyKey) {
165
- const events = await this.store.listQuotaEvents(userId, {
166
- idempotencyKey,
167
- limit: 100,
168
- });
175
+ if (!this.emitter)
176
+ return;
177
+ let events;
178
+ try {
179
+ events = await this.store.listQuotaEvents(userId, {
180
+ idempotencyKey,
181
+ limit: 100,
182
+ });
183
+ }
184
+ catch (error) {
185
+ this.logger.warn("[CreditsService] failed to fetch quota events", {
186
+ userId,
187
+ idempotencyKey,
188
+ error: error instanceof Error ? error.message : String(error),
189
+ });
190
+ return;
191
+ }
169
192
  for (const event of events) {
170
193
  const data = {
171
194
  quotaKey: event.quotaKey,
@@ -237,7 +260,10 @@ export class CreditsService {
237
260
  * The event is emitted only after the store write succeeds.
238
261
  */
239
262
  async setUserPlan(userId, planKey, planAssignedAt) {
240
- this.logger.info("[CreditsService] setUserPlan", { planKey, planAssignedAt });
263
+ this.logger.info("[CreditsService] setUserPlan", {
264
+ planKey,
265
+ planAssignedAt,
266
+ });
241
267
  const result = await this.store.setUserPlan(userId, planKey, planAssignedAt);
242
268
  this.emit("credits.plan_changed", userId, {
243
269
  userId,
@@ -283,7 +309,11 @@ export class CreditsService {
283
309
  async addCreditsUninstrumented(userId, amount, options) {
284
310
  const idempotencyKey = requireStableKey(options?.idempotencyKey);
285
311
  const type = options.type ?? "adjustment";
286
- this.logger.info("[CreditsService] addCredits", { amount, type, bucket: options.bucket });
312
+ this.logger.info("[CreditsService] addCredits", {
313
+ amount,
314
+ type,
315
+ bucket: options.bucket,
316
+ });
287
317
  const result = await this.store.addCredits(userId, positiveAmount(amount, "addCredits"), {
288
318
  ...options,
289
319
  type,
@@ -296,7 +326,6 @@ export class CreditsService {
296
326
  type,
297
327
  idempotent: result.idempotent ?? false,
298
328
  });
299
- this.balanceMonitor.rearmAfterCredit(userId, result.newBalance);
300
329
  return result;
301
330
  }
302
331
  /**
@@ -329,6 +358,7 @@ export class CreditsService {
329
358
  idempotent: result.idempotent ?? false,
330
359
  });
331
360
  if (!result.idempotent) {
361
+ await this.balanceMonitor.signalCrossing(userId, result.newBalance.plus(result.amount.abs()), result.newBalance);
332
362
  await this.afterDeduction(userId, "raw", {
333
363
  entryId: result.entryId,
334
364
  userId,
@@ -348,17 +378,15 @@ export class CreditsService {
348
378
  * payment-provider webhook handler (Stripe, etc. — bursar stays
349
379
  * provider-agnostic) to call even on webhook redelivery.
350
380
  *
351
- * 1. At most one of ``expiresAt``/``ttlDays`` may be given (throws
352
- * ``ConfigError`` otherwise).
353
- * 2. When ``ttlDays`` is given, ``expiresAt = now + ttlDays`` days.
354
- * 3. The new cycle is granted via a direct ``store.addCredits`` call
381
+ * 1. Supply a stable absolute ``expiresAt`` across retries, if the grant expires.
382
+ * 2. The new cycle is granted via a direct ``store.addCredits`` call
355
383
  * (bypassing {@link addCredits} so only ``credits.cycle_renewed`` fires,
356
384
  * not a duplicate ``credits.added``), threading ``idempotencyKey`` so a
357
385
  * redelivered webhook replays the prior grant instead of double-crediting.
358
- * 4. Existing bucket credits are never removed here. Subscription renewal
386
+ * 3. Existing bucket credits are never removed here. Subscription renewal
359
387
  * policies that replace prior lots run atomically through BillingService.
360
- * 5. When ``planKey`` is given, assigns it via {@link setUserPlan}.
361
- * 6. Emits ``credits.cycle_renewed`` and returns the grant result.
388
+ * 4. Emits ``credits.cycle_renewed`` and returns the grant result. Plan
389
+ * assignment is a separate operation managed by the caller.
362
390
  */
363
391
  async grantSubscriptionCycle(userId, amount, options) {
364
392
  return this.instrumentation.run("credits.grant_subscription_cycle", undefined, () => this.grantSubscriptionCycleUninstrumented(userId, amount, options));
@@ -368,15 +396,15 @@ export class CreditsService {
368
396
  this.logger.info("[CreditsService] grantSubscriptionCycle", {
369
397
  amount,
370
398
  bucket: options.bucket,
371
- planKey: options.planKey,
372
399
  });
373
- if (options.expiresAt != null && options.ttlDays != null) {
374
- throw new ConfigError("grantSubscriptionCycle: specify at most one of 'expiresAt' or 'ttlDays', not both");
400
+ if ("ttlDays" in options) {
401
+ throw new ConfigError("grantSubscriptionCycle: use a stable absolute expiresAt instead of ttlDays");
402
+ }
403
+ if ("planKey" in options) {
404
+ throw new ConfigError("grantSubscriptionCycle: assign plans separately with setUserPlan");
375
405
  }
376
406
  const bucket = options.bucket ?? "subscription";
377
- const expiresAt = options.ttlDays != null
378
- ? new Date(Date.now() + options.ttlDays * 86_400_000)
379
- : options.expiresAt;
407
+ const expiresAt = options.expiresAt;
380
408
  const amountDec = positiveAmount(amount, "grantSubscriptionCycle");
381
409
  const result = await this.store.addCredits(userId, amountDec, {
382
410
  type: "purchase",
@@ -385,23 +413,11 @@ export class CreditsService {
385
413
  bucket,
386
414
  idempotencyKey,
387
415
  });
388
- // The store contract exposes the mutation's replay result directly, avoiding
389
- // a racy lifetime-balance comparison and an extra database round trip.
390
- const isFreshGrant = !result.idempotent;
391
- if (options.planKey) {
392
- // A fresh cycle intentionally re-anchors plan-assignment windows. On a
393
- // webhook replay, repair a previously interrupted grant->assignment saga
394
- // without re-anchoring an assignment that already succeeded.
395
- if (isFreshGrant || (await this.getUserPlan(userId)).planKey !== options.planKey) {
396
- await this.setUserPlan(userId, options.planKey);
397
- }
398
- }
399
416
  this.emit("credits.cycle_renewed", userId, {
400
417
  entryId: result.entryId,
401
418
  amount: amountDec,
402
419
  newBalance: result.newBalance,
403
420
  bucket,
404
- planKey: options.planKey ?? null,
405
421
  idempotencyKey,
406
422
  idempotent: result.idempotent,
407
423
  });
@@ -447,44 +463,46 @@ export class CreditsService {
447
463
  * typed exception is thrown. No success event is emitted on error.
448
464
  */
449
465
  async deduct(userId, metrics, options) {
450
- return this.instrumentation.run("credits.deduct", undefined, () => this.deductUninstrumented(userId, metrics, options));
466
+ return this.instrumentation.run("credits.deduct", undefined, () => this.catalogRuntime.withFreshQuote(() => this.deductUninstrumented(userId, metrics, options)));
451
467
  }
452
- async deductUninstrumented(userId, metrics, options) {
468
+ async deductUninstrumented(userId, metrics, options, flatJob = false) {
453
469
  await this.maybeLazyExpire(userId);
454
470
  this.logger.debug("[CreditsService] deduct", {
455
471
  model: metrics.dimensions?.model,
456
472
  feature: options.feature,
457
473
  });
458
- const engine = await this.catalogRuntime.engineForUser(userId);
459
474
  const plan = await this.store.getUserPlan(userId);
475
+ const engine = await this.catalogRuntime.engineForPlan(plan);
476
+ const quoteVersion = plan.catalogVersion ?? this.catalogRuntime.pricingVersion(engine);
477
+ if (flatJob && engine.hasMeasure(metrics.operation, "jobs"))
478
+ metrics = { ...metrics, measures: { jobs: 1 } };
460
479
  const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
461
480
  const model = z.string().safeParse(metrics.dimensions?.model).data ?? null;
462
481
  const region = z.string().safeParse(metrics.dimensions?.region).data ?? null;
463
482
  // 1) Calculate cost as an exact Decimal, never truncated.
464
- const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
483
+ const breakdown = engine.calculate(metrics, {
484
+ rateCard: plan.rateCard ?? undefined,
485
+ });
465
486
  const cost = breakdown.total;
487
+ const measures = ratedMeasures(metrics.measures);
488
+ const dimensions = ratedDimensions(metrics.dimensions);
466
489
  // Build ledger metadata: caller fields FIRST, system fields LAST so the
467
490
  // protected system fields win.
468
- const meta = {};
469
- if (options.metadata) {
470
- for (const [k, v] of Object.entries(options.metadata)) {
471
- if (v != null)
472
- meta[k] = v;
473
- }
474
- }
491
+ const meta = callerMetadata(options.metadata, true);
475
492
  meta["operation"] = metrics.operation;
476
- meta["measures"] = { ...(metrics.measures ?? {}) };
477
- meta["dimensions"] = { ...(metrics.dimensions ?? {}) };
478
- meta["breakdownTotal"] = breakdown.total.toString();
479
- meta["idempotencyKey"] = effectiveIdempotencyKey;
493
+ meta["measures"] = measures;
494
+ meta["dimensions"] = dimensions;
495
+ meta["breakdownTotal"] = breakdown.total.toFixed(6);
496
+ meta["idempotency_key"] = effectiveIdempotencyKey;
480
497
  const deductionOptions = {
481
498
  idempotencyKey: effectiveIdempotencyKey,
499
+ expectedPricing: this.catalogRuntime.expectedPricing(plan, quoteVersion),
482
500
  operation: metrics.operation,
483
501
  feature: options.feature ?? null,
484
502
  model,
485
503
  region,
486
- measures: { ...(metrics.measures ?? {}) },
487
- dimensions: { ...(metrics.dimensions ?? {}) },
504
+ measures,
505
+ dimensions,
488
506
  metadata: meta,
489
507
  };
490
508
  // 2) Atomic charge. This records zero-cost usage too, so authorization,
@@ -518,7 +536,7 @@ export class CreditsService {
518
536
  });
519
537
  // low_balance is edge-triggered: only fire when this deduction crossed
520
538
  // the threshold. A replayed (idempotent) result did not move the balance, so
521
- // it never crosses. balanceBefore = balanceAfter + amount charged.
539
+ // it never crosses. The store's amount is already net of allowance.
522
540
  if (!result.idempotent) {
523
541
  const balanceBefore = result.balanceAfter.plus(result.amount);
524
542
  await this.balanceMonitor.signalCrossing(userId, balanceBefore, result.balanceAfter);
@@ -534,34 +552,39 @@ export class CreditsService {
534
552
  * affecting the account balance, such as externally billed usage.
535
553
  */
536
554
  async recordUsage(userId, metrics, options) {
537
- const engine = await this.catalogRuntime.engineForUser(userId);
555
+ return this.catalogRuntime.withFreshQuote(() => this.recordUsageOnce(userId, metrics, options));
556
+ }
557
+ async recordUsageOnce(userId, metrics, options) {
538
558
  const plan = await this.store.getUserPlan(userId);
559
+ const engine = await this.catalogRuntime.engineForPlan(plan);
539
560
  const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
540
561
  const model = z.string().safeParse(metrics.dimensions?.model).data ?? null;
541
562
  const region = z.string().safeParse(metrics.dimensions?.region).data ?? null;
542
- const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
543
- const meta = {};
544
- if (options.metadata) {
545
- for (const [key, value] of Object.entries(options.metadata)) {
546
- if (value != null)
547
- meta[key] = value;
548
- }
549
- }
563
+ const breakdown = engine.calculate(metrics, {
564
+ rateCard: plan.rateCard ?? undefined,
565
+ });
566
+ const measures = ratedMeasures(metrics.measures);
567
+ const dimensions = ratedDimensions(metrics.dimensions);
568
+ const meta = callerMetadata(options.metadata, true);
550
569
  meta.operation = metrics.operation;
551
- meta.measures = { ...(metrics.measures ?? {}) };
552
- meta.dimensions = { ...(metrics.dimensions ?? {}) };
553
- meta.breakdownTotal = breakdown.total.toString();
554
- meta.idempotencyKey = effectiveIdempotencyKey;
570
+ meta.measures = measures;
571
+ meta.dimensions = dimensions;
572
+ meta.breakdownTotal = breakdown.total.toFixed(6);
573
+ meta.idempotency_key = effectiveIdempotencyKey;
555
574
  const result = await this.store.recordUsage(userId, metrics.operation, breakdown.total, {
556
575
  idempotencyKey: effectiveIdempotencyKey,
576
+ expectedPricing: this.catalogRuntime.expectedPricing(plan, plan.catalogVersion ?? this.catalogRuntime.pricingVersion(engine)),
557
577
  operation: metrics.operation,
558
578
  model,
559
579
  region,
560
- measures: { ...(metrics.measures ?? {}) },
561
- dimensions: { ...(metrics.dimensions ?? {}) },
580
+ measures,
581
+ dimensions,
562
582
  metadata: meta,
563
583
  });
564
584
  if (result.error !== null) {
585
+ if (result.error === "idempotency_conflict") {
586
+ throw new IdempotencyConflictError(`Idempotency key conflicts with a prior request. user=${userId}`);
587
+ }
565
588
  throw new StoreError(`Usage record failed: ${result.error}`);
566
589
  }
567
590
  return result;
@@ -576,7 +599,7 @@ export class CreditsService {
576
599
  */
577
600
  /** Deduct the configured fixed cost for one named job. */
578
601
  async deductFlatJob(userId, jobName, options) {
579
- return this.deduct(userId, { operation: jobName, measures: { jobs: 1 } }, options);
602
+ return this.instrumentation.run("credits.deduct", undefined, () => this.catalogRuntime.withFreshQuote(() => this.deductUninstrumented(userId, { operation: jobName }, options, true)));
580
603
  }
581
604
  async refundCredits(entryId, options) {
582
605
  return this.instrumentation.run("credits.refund", undefined, () => this.refundCreditsUninstrumented(entryId, options));
@@ -626,62 +649,62 @@ export class CreditsService {
626
649
  */
627
650
  async deductTeam(teamId, userId, metrics, options) {
628
651
  const idempotencyKey = requireStableKey(options?.idempotencyKey);
629
- await this.maybeLazyExpire(userId);
630
- // Lazy expiry is scoped to the individual member's credits, not the team's
631
- // shared pool — there's no per-team expiry concept.
632
- const engine = await this.catalogRuntime.engineForUser(userId);
633
- const plan = await this.store.getUserPlan(userId);
634
- const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
635
- const cost = breakdown.total;
636
- if (cost.lte(0)) {
637
- const teamBal = await this.store.getTeamBalance(teamId);
638
- if (teamBal === null) {
639
- throw new StoreError(`Team not found: ${teamId}`);
640
- }
641
- return {
642
- entryId: null,
643
- teamId,
644
- userId,
645
- amount: new Decimal(0),
646
- teamBalanceAfter: teamBal.balance,
647
- idempotent: false,
648
- error: null,
652
+ return this.catalogRuntime.withFreshQuote(async () => {
653
+ await this.maybeLazyExpire(userId);
654
+ const plan = await this.store.getUserPlan(userId);
655
+ const engine = await this.catalogRuntime.engineForPlan(plan);
656
+ const breakdown = engine.calculate(metrics, {
657
+ rateCard: plan.rateCard ?? undefined,
658
+ });
659
+ const cost = breakdown.total;
660
+ const teamMetadata = {
661
+ ...callerMetadata(options.metadata, true),
662
+ operation: metrics.operation,
663
+ measures: ratedMeasures(metrics.measures),
664
+ dimensions: ratedDimensions(metrics.dimensions),
665
+ breakdownTotal: breakdown.total.toFixed(6),
649
666
  };
650
- }
651
- const teamMetadata = {
652
- ...(options.metadata ?? {}),
653
- operation: metrics.operation,
654
- measures: { ...(metrics.measures ?? {}) },
655
- dimensions: Object.fromEntries(Object.entries(metrics.dimensions ?? {}).map(([key, value]) => [key, String(value)])),
656
- breakdownTotal: breakdown.total.toString(),
657
- };
658
- const result = await this.store.deductTeam(teamId, userId, cost, {
659
- metadata: teamMetadata,
660
- idempotencyKey,
661
- });
662
- // Surface store errors: emit credits.deduct_failed and throw,
663
- // mirroring the Python credit service implementation. Previously returned a silent
664
- // success-shaped object with an .error field, so failed charges looked OK.
665
- if (result.error !== null) {
666
- this.emit("credits.deduct_failed", userId, {
667
- error: result.error,
668
- amount: cost,
667
+ const result = await this.store.deductTeam(teamId, userId, cost, {
668
+ metadata: teamMetadata,
669
+ idempotencyKey,
670
+ expectedPricing: this.catalogRuntime.expectedPricing(plan, plan.catalogVersion ?? this.catalogRuntime.pricingVersion(engine)),
671
+ });
672
+ // Surface store errors: emit credits.deduct_failed and throw,
673
+ // mirroring the Python credit service implementation. Previously returned a silent
674
+ // success-shaped object with an .error field, so failed charges looked OK.
675
+ if (result.error !== null) {
676
+ this.emit("credits.deduct_failed", userId, {
677
+ error: result.error,
678
+ amount: cost,
679
+ teamId,
680
+ deductType: "team",
681
+ });
682
+ if (result.error === "member_spend_cap_exceeded") {
683
+ throw new CapReachedError(`Team member spend cap exceeded. Team=${teamId}, user=${userId}, requested=${cost}`);
684
+ }
685
+ if (result.error === "idempotency_conflict") {
686
+ throw new IdempotencyConflictError(`Team idempotency key conflicts with a prior request. Team=${teamId}`);
687
+ }
688
+ if (result.error === "not_team_member") {
689
+ throw new OperationNotAllowedError(`Active team membership is required. Team=${teamId}, user=${userId}`);
690
+ }
691
+ if (result.error === "insufficient_credits" || result.error === "insufficient_headroom") {
692
+ throw new InsufficientCreditsError(`Insufficient team credits. Team=${teamId}, user=${userId}, requested=${cost}`);
693
+ }
694
+ throw new StoreError(`Team deduction failed: ${result.error}. Team=${teamId}, user=${userId}`);
695
+ }
696
+ this.emit("credits.deducted", userId, {
697
+ entryId: result.entryId,
698
+ amount: result.amount,
699
+ teamBalanceAfter: result.teamBalanceAfter,
669
700
  teamId,
670
701
  deductType: "team",
671
702
  });
672
- if (result.error === "member_spend_cap_exceeded") {
673
- throw new CapReachedError(`Team member spend cap exceeded. Team=${teamId}, user=${userId}, requested=${cost}`);
703
+ if (!result.idempotent) {
704
+ await this.balanceMonitor.signalCrossing(userId, result.teamBalanceAfter.plus(result.amount), result.teamBalanceAfter, { teamId });
674
705
  }
675
- throw new InsufficientCreditsError(`Team deduction failed: ${result.error}. Team=${teamId}, user=${userId}, requested=${cost}`);
676
- }
677
- this.emit("credits.deducted", userId, {
678
- entryId: result.entryId,
679
- amount: result.amount,
680
- teamBalanceAfter: result.teamBalanceAfter,
681
- teamId,
682
- deductType: "team",
706
+ return result;
683
707
  });
684
- return result;
685
708
  }
686
709
  async runSweep(dryRun, userId) {
687
710
  const result = await this.store.sweepExpiredCredits(dryRun, userId);