@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,13 @@
1
+ import { PricingDecimal } from "../../pricing-decimal.js";
1
2
  import { Decimal } from "decimal.js";
2
3
  import { z } from "zod";
3
- import { StoreClosedError, StoreError } from "../../errors.js";
4
- import { canonicalBursarConfigDict, canonicalCatalogRolloutDict, loadCatalogRollout, loadConfigFromDict, validateCatalogRollout, } from "../../config.js";
5
- import { PostgresClient, } from "../../shared/postgres-client.js";
4
+ import { CatalogNotLoadedError, ConfigError, StaleQuoteError, StoreClosedError, StoreError, } from "../../errors.js";
5
+ import { canonicalParsedBursarConfigDict, canonicalCatalogRolloutDict, loadCatalogRollout, loadConfigFromDict, validateCatalogRollout, } from "../../config.js";
6
+ import { PostgresClient, normalizeTenantId, } from "../../shared/postgres-client.js";
7
+ import { normalizeProviderEnvironment } from "../../providers/environment.js";
6
8
  import { requireStableKey } from "../../shared/idempotency.js";
7
9
  import { CreditStore } from "../store.js";
8
- import { BalanceRepository } from "./repositories/balance.js";
10
+ import { BalanceRepository, } from "./repositories/balance.js";
9
11
  import { DeductionRepository } from "./repositories/deduction.js";
10
12
  import { LeaseRepository } from "./repositories/lease.js";
11
13
  import { CatalogRepository } from "./repositories/catalog.js";
@@ -17,6 +19,11 @@ import { ZERO, decimalParameter as decParam, decimalRecord as decRecord, decimal
17
19
  const DEFAULT_LEASE_TTL_SECONDS = 600;
18
20
  const DEFAULT_PAGE_SIZE = 50;
19
21
  const MAX_PAGE_SIZE = 200;
22
+ function validateAnalyticsRange(start, end) {
23
+ if (!(start instanceof Date) || !(end instanceof Date) || !(end > start)) {
24
+ throw new RangeError("analytics requires end after start");
25
+ }
26
+ }
20
27
  function requireText(value, context) {
21
28
  const parsed = z.string().min(1).safeParse(value);
22
29
  if (!parsed.success) {
@@ -24,65 +31,102 @@ function requireText(value, context) {
24
31
  }
25
32
  return parsed.data;
26
33
  }
27
- export class PostgresStore extends CreditStore {
28
- providerEnvironment;
29
- postgres;
30
- _balanceRepo = null;
31
- _deductionRepo = null;
32
- _leaseRepo = null;
33
- _catalogRepo = null;
34
- _planRepo = null;
35
- _analyticsRepo = null;
36
- _teamRepo = null;
37
- _bucketRepo = null;
38
- get balanceRepo() {
39
- if (!this._balanceRepo) {
40
- this._balanceRepo = new BalanceRepository(this.callproc.bind(this));
41
- }
42
- return this._balanceRepo;
43
- }
44
- get deductionRepo() {
45
- if (!this._deductionRepo) {
46
- this._deductionRepo = new DeductionRepository(this.callproc.bind(this));
47
- }
48
- return this._deductionRepo;
49
- }
50
- get leaseRepo() {
51
- if (!this._leaseRepo) {
52
- this._leaseRepo = new LeaseRepository(this.callproc.bind(this));
53
- }
54
- return this._leaseRepo;
55
- }
56
- get catalogRepo() {
57
- if (!this._catalogRepo) {
58
- this._catalogRepo = new CatalogRepository(this.callproc.bind(this));
59
- }
60
- return this._catalogRepo;
61
- }
62
- get planRepo() {
63
- if (!this._planRepo) {
64
- this._planRepo = new PlanRepository(this.callproc.bind(this));
65
- }
66
- return this._planRepo;
67
- }
68
- get analyticsRepo() {
69
- if (!this._analyticsRepo) {
70
- this._analyticsRepo = new AnalyticsRepository(this.callproc.bind(this));
71
- }
72
- return this._analyticsRepo;
34
+ function mapDeduction(row, userId, procedure) {
35
+ if (row.error !== null) {
36
+ return {
37
+ entryId: null,
38
+ usageChargeId: row.charge_id != null ? String(row.charge_id) : null,
39
+ userId,
40
+ amount: dec(row.amount),
41
+ allowanceConsumed: dec(row.allowance_consumed),
42
+ balanceAfter: row.balance_after == null ? null : dec(row.balance_after),
43
+ idempotent: false,
44
+ error: row.error,
45
+ bucketBreakdown: null,
46
+ };
73
47
  }
74
- get teamRepo() {
75
- if (!this._teamRepo) {
76
- this._teamRepo = new TeamRepository(this.callproc.bind(this));
77
- }
78
- return this._teamRepo;
48
+ return {
49
+ entryId: row.entry_id == null ? null : requireText(row.entry_id, procedure),
50
+ usageChargeId: requireText(row.charge_id, procedure),
51
+ userId,
52
+ amount: dec(row.amount),
53
+ allowanceConsumed: dec(row.allowance_consumed),
54
+ balanceAfter: dec(row.balance_after),
55
+ idempotent: row.idempotent,
56
+ error: null,
57
+ bucketBreakdown: decRecord(row.bucket_breakdown),
58
+ };
59
+ }
60
+ function mapAvailable(userId, row) {
61
+ if (row === null)
62
+ return { userId, balance: ZERO, reserved: ZERO, available: ZERO };
63
+ return {
64
+ userId,
65
+ balance: dec(row.balance),
66
+ reserved: dec(row.reserved),
67
+ available: dec(row.available),
68
+ };
69
+ }
70
+ function mapStaleQuote(error) {
71
+ if (error instanceof StoreError && error.details?.sqlState === "PZ003") {
72
+ throw new StaleQuoteError("Pricing changed before admission", {
73
+ cause: error,
74
+ });
79
75
  }
80
- get bucketRepo() {
81
- if (!this._bucketRepo) {
82
- this._bucketRepo = new BucketRepository(this.callproc.bind(this));
76
+ throw error;
77
+ }
78
+ export class PostgresStore extends CreditStore {
79
+ async getOperationReceipt(userId, key, kind) {
80
+ if (kind !== "charge" && kind !== "lease")
81
+ throw new TypeError("kind must be charge or lease");
82
+ const rows = await this.callproc("get_operation_receipt", [
83
+ userId,
84
+ requireStableKey(key),
85
+ kind,
86
+ ]);
87
+ if (rows.length === 0)
88
+ return null;
89
+ const schema = z.object({
90
+ kind: z.enum(["charge", "lease"]),
91
+ receipt_id: z.string(),
92
+ operation: z.string(),
93
+ requested: z.string(),
94
+ charged: z.string().nullable(),
95
+ allowance_amount: z.string(),
96
+ status: z.string(),
97
+ expires_at: z.union([z.string(), z.date()]).nullable(),
98
+ ledger_entry_id: z.string().nullable(),
99
+ usage_charge_id: z.string().nullable(),
100
+ });
101
+ const parsed = schema.safeParse(rows[0]);
102
+ if (rows.length !== 1 || !parsed.success || parsed.data.kind !== kind) {
103
+ throw new StoreError("get_operation_receipt returned a malformed result");
83
104
  }
84
- return this._bucketRepo;
105
+ const row = parsed.data;
106
+ return {
107
+ kind: row.kind,
108
+ receiptId: row.receipt_id,
109
+ operation: row.operation,
110
+ requested: dec(row.requested),
111
+ charged: row.charged === null ? null : dec(row.charged),
112
+ allowanceAmount: dec(row.allowance_amount),
113
+ status: row.status,
114
+ expiresAt: row.expires_at instanceof Date ? row.expires_at.toISOString() : row.expires_at,
115
+ ledgerEntryId: row.ledger_entry_id,
116
+ usageChargeId: row.usage_charge_id,
117
+ };
85
118
  }
119
+ tenantId;
120
+ providerEnvironment;
121
+ postgres;
122
+ balanceRepo;
123
+ deductionRepo;
124
+ leaseRepo;
125
+ catalogRepo;
126
+ planRepo;
127
+ analyticsRepo;
128
+ teamRepo;
129
+ bucketRepo;
86
130
  constructor(options) {
87
131
  super();
88
132
  if (!z.object({}).safeParse(options).success) {
@@ -91,10 +135,11 @@ export class PostgresStore extends CreditStore {
91
135
  if (options.poolConstructor !== undefined && !z.string().safeParse(options.postgres).success) {
92
136
  throw new TypeError("poolConstructor cannot be used with an existing PostgreSQL pool");
93
137
  }
94
- this.providerEnvironment = options.providerEnvironment;
138
+ this.tenantId = normalizeTenantId(options.tenantId);
139
+ this.providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);
95
140
  this.postgres = new PostgresClient(options.postgres, {
96
- tenantId: options.tenantId,
97
- providerEnvironment: options.providerEnvironment,
141
+ tenantId: this.tenantId,
142
+ providerEnvironment: this.providerEnvironment,
98
143
  usageBackend: options.usageBackend,
99
144
  poolConstructor: options.poolConstructor,
100
145
  connectionTimeoutMs: options.connectionTimeoutMs,
@@ -104,16 +149,55 @@ export class PostgresStore extends CreditStore {
104
149
  maxConnections: options.maxConnections,
105
150
  applicationName: options.applicationName,
106
151
  onPoolError: options.onPoolError,
152
+ instrumentation: options.instrumentation,
107
153
  closedError: () => new StoreClosedError("Credit store has been closed"),
108
154
  });
155
+ const callproc = this.callproc.bind(this);
156
+ this.balanceRepo = new BalanceRepository(callproc);
157
+ this.deductionRepo = new DeductionRepository(callproc);
158
+ this.leaseRepo = new LeaseRepository(callproc);
159
+ this.catalogRepo = new CatalogRepository(callproc);
160
+ this.planRepo = new PlanRepository(callproc);
161
+ this.analyticsRepo = new AnalyticsRepository(callproc);
162
+ this.teamRepo = new TeamRepository(callproc);
163
+ this.bucketRepo = new BucketRepository(callproc);
109
164
  }
110
165
  async query(text, params) {
111
166
  return this.postgres.query(text, params);
112
167
  }
168
+ /** Check the same tenant-scoped connection used by financial operations. */
169
+ async checkReachability() {
170
+ const rows = await this.query("SELECT 1 AS bursar_reachable");
171
+ if (rows.length !== 1 || rows[0]?.bursar_reachable !== 1) {
172
+ throw new Error("PostgreSQL reachability check returned an invalid result");
173
+ }
174
+ }
175
+ withUsageBackend(expected, action) {
176
+ return this.postgres.withUsageBackend(expected, action);
177
+ }
113
178
  async close() {
114
179
  await this.postgres.close();
115
180
  }
116
181
  static RPC_NAME_RE = /^[a-z_][a-z0-9_]*$/;
182
+ // Cast cursor timestamps to text before pg can truncate their microseconds.
183
+ static CURSOR_PROJECTIONS = new Map([
184
+ [
185
+ "list_ledger",
186
+ "entry_id, account_id, actor_user_id, amount, entry_type, operation, reference_entry_id, " +
187
+ "idempotency_key, metadata, created_at::text AS created_at",
188
+ ],
189
+ [
190
+ "list_usage_charges",
191
+ "usage_id, account_id, operation, requested, charged, allowance_requested, allowance_covered, " +
192
+ "billing_disposition, feature, model, region, event_at::text AS event_at, " +
193
+ "idempotency_key, metadata, created_at",
194
+ ],
195
+ [
196
+ "list_subject_quota_events",
197
+ "event_id, quota_key, operation_key, measure_key, event_type, threshold_percent, " +
198
+ "idempotency_key, usage_charge_id, created_at::text AS created_at",
199
+ ],
200
+ ]);
117
201
  static SCALAR_RPC_NAMES = new Set([
118
202
  "apply_due_plan_assignment_changes",
119
203
  "release_lease",
@@ -123,12 +207,13 @@ export class PostgresStore extends CreditStore {
123
207
  "start_plan_migration",
124
208
  "unassign_plan",
125
209
  ]);
126
- async callproc(name, params) {
210
+ async callproc(name, params, query = this.postgres.query) {
127
211
  if (!PostgresStore.RPC_NAME_RE.test(name)) {
128
212
  throw new StoreError(`Invalid RPC name: ${name}`);
129
213
  }
130
214
  const placeholders = params.map((_, i) => `$${i + 1}`).join(", ");
131
- const rows = await this.query(`SELECT * FROM bursar.${name}(${placeholders})`, params);
215
+ const sql = `SELECT ${PostgresStore.CURSOR_PROJECTIONS.get(name) ?? "*"} FROM bursar.${name}(${placeholders})`;
216
+ const rows = await query(sql, params);
132
217
  if (PostgresStore.SCALAR_RPC_NAMES.has(name) && rows.length === 1) {
133
218
  const row = rows[0];
134
219
  if (row === undefined)
@@ -160,19 +245,22 @@ export class PostgresStore extends CreditStore {
160
245
  if (options?.expiresAt) {
161
246
  meta.expires_at = options.expiresAt.toISOString();
162
247
  }
163
- const row = await this.balanceRepo.addCredits(userId, decParam(amount), options?.type ?? "adjustment", JSON.stringify(meta), options?.expiresAt?.toISOString() ?? null, options?.bucket ?? null, stableKey);
164
- if (row.error !== null) {
165
- throw new StoreError(`post_credit: ${row.error}`);
166
- }
167
- return {
168
- entryId: requireText(row.entry_id, "post_credit"),
169
- userId: row.user_id,
170
- amount: dec(row.amount),
171
- newBalance: dec(row.new_balance),
172
- lifetimePurchased: dec(row.lifetime_purchased),
173
- bucket: row.bucket,
174
- idempotent: row.idempotent,
175
- };
248
+ return this.postgres.withTransaction(async (query) => {
249
+ const repository = new BalanceRepository((name, params) => this.callproc(name, params, query));
250
+ const row = await repository.addCredits(userId, decParam(amount), options?.type ?? "adjustment", JSON.stringify(meta), options?.expiresAt?.toISOString() ?? null, options?.bucket ?? null, stableKey);
251
+ if (row.error !== null) {
252
+ throw new StoreError(`post_credit: ${row.error}`);
253
+ }
254
+ return {
255
+ entryId: requireText(row.entry_id, "post_credit"),
256
+ userId: row.user_id,
257
+ amount: dec(row.amount),
258
+ newBalance: dec(row.new_balance),
259
+ lifetimePurchased: dec(row.lifetime_purchased),
260
+ bucket: row.bucket,
261
+ idempotent: row.idempotent,
262
+ };
263
+ });
176
264
  }
177
265
  async deductWithAllowance(userId, amount, options) {
178
266
  const idempotencyKey = requireStableKey(options?.idempotencyKey);
@@ -185,46 +273,31 @@ export class PostgresStore extends CreditStore {
185
273
  const feature = options?.feature ?? null;
186
274
  const measures = options?.measures ?? {};
187
275
  const dimensions = options?.dimensions ?? {};
188
- const row = await this.deductionRepo.deductWithAllowance({
189
- userId,
190
- operation,
191
- amount: decParam(amount),
192
- idempotencyKey,
193
- feature,
194
- model,
195
- region,
196
- measures: JSON.stringify(measures),
197
- dimensions: JSON.stringify(dimensions),
198
- metadata: JSON.stringify(metadata ?? {}),
199
- });
200
- if (row.error !== null) {
201
- return {
202
- entryId: null,
203
- usageChargeId: row.charge_id != null ? String(row.charge_id) : null,
276
+ return this.postgres.withTransaction(async (query) => {
277
+ const repository = new DeductionRepository((name, params) => this.callproc(name, params, query));
278
+ const row = await repository
279
+ .deductWithAllowance({
204
280
  userId,
205
- amount: dec(row.amount),
206
- allowanceConsumed: dec(row.allowance_consumed),
207
- balanceAfter: row.balance_after == null ? null : dec(row.balance_after),
208
- idempotent: false,
209
- error: row.error,
210
- bucketBreakdown: null,
211
- };
212
- }
213
- return {
214
- entryId: row.entry_id == null ? null : requireText(row.entry_id, "charge_usage_for_operation"),
215
- usageChargeId: requireText(row.charge_id, "charge_usage_for_operation"),
216
- userId,
217
- amount: dec(row.amount),
218
- allowanceConsumed: dec(row.allowance_consumed),
219
- balanceAfter: dec(row.balance_after),
220
- idempotent: row.idempotent,
221
- error: null,
222
- bucketBreakdown: decRecord(row.bucket_breakdown),
223
- };
281
+ operation,
282
+ amount: decParam(amount),
283
+ idempotencyKey,
284
+ feature,
285
+ model,
286
+ region,
287
+ measures: JSON.stringify(measures),
288
+ dimensions: JSON.stringify(dimensions),
289
+ metadata: JSON.stringify(metadata ?? {}),
290
+ expectedPlanId: options.expectedPricing?.planId ?? null,
291
+ expectedRevisionNo: options.expectedPricing?.catalogVersion ?? null,
292
+ })
293
+ .catch(mapStaleQuote);
294
+ return mapDeduction(row, userId, "charge_usage_for_operation");
295
+ });
224
296
  }
225
297
  async recordUsage(userId, operation, amount, options) {
226
298
  const idempotencyKey = requireStableKey(options?.idempotencyKey);
227
- const row = await this.deductionRepo.recordUsage({
299
+ const row = await this.deductionRepo
300
+ .recordUsage({
228
301
  userId,
229
302
  operation,
230
303
  amount: decParam(amount),
@@ -235,7 +308,10 @@ export class PostgresStore extends CreditStore {
235
308
  measures: JSON.stringify(options?.measures ?? {}),
236
309
  dimensions: JSON.stringify(options?.dimensions ?? {}),
237
310
  metadata: JSON.stringify(options?.metadata ?? {}),
238
- });
311
+ expectedPlanId: options.expectedPricing?.planId ?? null,
312
+ expectedRevisionNo: options.expectedPricing?.catalogVersion ?? null,
313
+ })
314
+ .catch(mapStaleQuote);
239
315
  if (row.error_code !== null) {
240
316
  return {
241
317
  usageId: null,
@@ -255,85 +331,73 @@ export class PostgresStore extends CreditStore {
255
331
  }
256
332
  async createLease(userId, amount, operationType, options) {
257
333
  const idempotencyKey = requireStableKey(options?.idempotencyKey);
258
- const row = await this.leaseRepo.createLease({
259
- userId,
260
- amount: decParam(amount),
261
- operationType,
262
- idempotencyKey,
263
- ttlSeconds: options?.ttlSeconds ?? DEFAULT_LEASE_TTL_SECONDS,
264
- metadata: JSON.stringify(options?.metadata ?? {}),
265
- feature: options?.feature ?? null,
266
- measures: JSON.stringify(options?.measures ?? {}),
267
- dimensions: JSON.stringify(options?.dimensions ?? {}),
268
- minimumBalance: options?.floor == null ? null : decParam(options.floor),
269
- maxConcurrent: options?.maxConcurrent ?? null,
270
- });
271
- const availability = await this.getAvailable(userId);
272
- if (row.error !== null) {
273
- return {
274
- leaseId: null,
334
+ return this.postgres.withTransaction(async (query) => {
335
+ const callproc = (name, params) => this.callproc(name, params, query);
336
+ const repository = new LeaseRepository(callproc);
337
+ const row = await repository
338
+ .createLease({
275
339
  userId,
276
- amount: row.amount == null ? null : dec(row.amount),
340
+ amount: decParam(amount),
341
+ operationType,
342
+ idempotencyKey,
343
+ ttlSeconds: options?.ttlSeconds ?? DEFAULT_LEASE_TTL_SECONDS,
344
+ metadata: JSON.stringify(options?.metadata ?? {}),
345
+ feature: options?.feature ?? null,
346
+ measures: JSON.stringify(options?.measures ?? {}),
347
+ dimensions: JSON.stringify(options?.dimensions ?? {}),
348
+ minimumBalance: options?.floor == null ? null : decParam(options.floor),
349
+ maxConcurrent: options?.maxConcurrent ?? null,
350
+ expectedPlanId: options.expectedPricing?.planId ?? null,
351
+ expectedRevisionNo: options.expectedPricing?.catalogVersion ?? null,
352
+ })
353
+ .catch(mapStaleQuote);
354
+ const availability = mapAvailable(userId, await new BalanceRepository(callproc).getAvailable(userId));
355
+ if (row.error !== null) {
356
+ return {
357
+ leaseId: null,
358
+ userId,
359
+ amount: row.amount == null ? null : dec(row.amount),
360
+ available: availability.available,
361
+ reservedTotal: availability.reserved,
362
+ minimumBalance: row.minimum_balance == null ? null : dec(row.minimum_balance),
363
+ billingMode: options?.billingMode ?? "strict",
364
+ expiresAt: null,
365
+ error: row.error,
366
+ };
367
+ }
368
+ return {
369
+ leaseId: requireText(row.lease_id, "create_lease_for_operation"),
370
+ userId: row.user_id,
371
+ amount: dec(row.amount),
277
372
  available: availability.available,
278
373
  reservedTotal: availability.reserved,
279
- minimumBalance: row.minimum_balance == null ? null : dec(row.minimum_balance),
280
- billingMode: options?.billingMode ?? "strict",
281
- expiresAt: null,
282
- error: row.error,
374
+ minimumBalance: dec(row.minimum_balance),
375
+ billingMode: dec(row.minimum_balance).lt(0) ? "overdraft" : "strict",
376
+ expiresAt: requireText(row.expires_at, "create_lease_for_operation"),
377
+ error: null,
283
378
  };
284
- }
285
- return {
286
- leaseId: requireText(row.lease_id, "create_lease_for_operation"),
287
- userId: row.user_id,
288
- amount: dec(row.amount),
289
- available: availability.available,
290
- reservedTotal: availability.reserved,
291
- minimumBalance: dec(row.minimum_balance),
292
- billingMode: dec(row.minimum_balance).lt(0) ? "overdraft" : "strict",
293
- expiresAt: requireText(row.expires_at, "create_lease_for_operation"),
294
- error: null,
295
- };
379
+ });
296
380
  }
297
381
  async settleLease(userId, leaseId, amount, options) {
298
382
  const idempotencyKey = options?.idempotencyKey === undefined
299
383
  ? `lease:${leaseId}:settle`
300
384
  : requireStableKey(options.idempotencyKey);
301
- const row = await this.leaseRepo.settleLease({
302
- userId,
303
- leaseId,
304
- amount: decParam(amount),
305
- idempotencyKey,
306
- feature: options?.feature ?? null,
307
- model: options?.model ?? null,
308
- region: options?.region ?? null,
309
- measures: JSON.stringify(options?.measures ?? {}),
310
- dimensions: JSON.stringify(options?.dimensions ?? {}),
311
- metadata: JSON.stringify(options?.metadata ?? {}),
312
- });
313
- if (row.error !== null) {
314
- return {
315
- entryId: null,
316
- usageChargeId: row.charge_id != null ? String(row.charge_id) : null,
385
+ return this.postgres.withTransaction(async (query) => {
386
+ const repository = new LeaseRepository((name, params) => this.callproc(name, params, query));
387
+ const row = await repository.settleLease({
317
388
  userId,
318
- amount: dec(row.amount),
319
- allowanceConsumed: dec(row.allowance_consumed),
320
- balanceAfter: row.balance_after == null ? null : dec(row.balance_after),
321
- idempotent: false,
322
- error: row.error,
323
- bucketBreakdown: null,
324
- };
325
- }
326
- return {
327
- entryId: row.entry_id == null ? null : requireText(row.entry_id, "settle_lease"),
328
- usageChargeId: requireText(row.charge_id, "settle_lease"),
329
- userId,
330
- amount: dec(row.amount),
331
- allowanceConsumed: dec(row.allowance_consumed),
332
- balanceAfter: dec(row.balance_after),
333
- idempotent: row.idempotent,
334
- error: null,
335
- bucketBreakdown: decRecord(row.bucket_breakdown),
336
- };
389
+ leaseId,
390
+ amount: decParam(amount),
391
+ idempotencyKey,
392
+ feature: options?.feature ?? null,
393
+ model: options?.model ?? null,
394
+ region: options?.region ?? null,
395
+ measures: JSON.stringify(options?.measures ?? {}),
396
+ dimensions: JSON.stringify(options?.dimensions ?? {}),
397
+ metadata: JSON.stringify(options?.metadata ?? {}),
398
+ });
399
+ return mapDeduction(row, userId, "settle_lease");
400
+ });
337
401
  }
338
402
  async getLeasePricingContext(userId, leaseId) {
339
403
  const row = await this.leaseRepo.getPricingContext(userId, leaseId);
@@ -341,6 +405,7 @@ export class PostgresStore extends CreditStore {
341
405
  return null;
342
406
  return {
343
407
  catalogVersion: row.catalog_revision_no,
408
+ operationType: row.operation,
344
409
  planId: row.plan_id ?? null,
345
410
  planKey: row.plan_key ?? null,
346
411
  rateCard: row.rate_card ?? null,
@@ -359,33 +424,36 @@ export class PostgresStore extends CreditStore {
359
424
  if (!Number.isInteger(ttlSeconds) || ttlSeconds < 1) {
360
425
  throw new RangeError("ttlSeconds must be a positive integer");
361
426
  }
362
- const row = await this.leaseRepo.renewLease(userId, leaseId, ttlSeconds);
363
- const availability = await this.getAvailable(userId);
364
- if (row.error !== null) {
427
+ return this.postgres.withTransaction(async (query) => {
428
+ const callproc = (name, params) => this.callproc(name, params, query);
429
+ const row = await new LeaseRepository(callproc).renewLease(userId, leaseId, ttlSeconds);
430
+ const availability = mapAvailable(userId, await new BalanceRepository(callproc).getAvailable(userId));
431
+ if (row.error !== null) {
432
+ return {
433
+ leaseId: null,
434
+ userId,
435
+ amount: row.amount == null ? null : dec(row.amount),
436
+ available: availability.available,
437
+ reservedTotal: availability.reserved,
438
+ minimumBalance: row.minimum_balance == null ? null : dec(row.minimum_balance),
439
+ billingMode: row.minimum_balance != null && dec(row.minimum_balance).lt(0) ? "overdraft" : "strict",
440
+ expiresAt: null,
441
+ error: row.error,
442
+ };
443
+ }
444
+ const minimumBalance = dec(row.minimum_balance);
365
445
  return {
366
- leaseId: null,
446
+ leaseId: requireText(row.lease_id, "renew_lease"),
367
447
  userId,
368
- amount: row.amount == null ? null : dec(row.amount),
448
+ amount: dec(row.amount),
369
449
  available: availability.available,
370
450
  reservedTotal: availability.reserved,
371
- minimumBalance: row.minimum_balance == null ? null : dec(row.minimum_balance),
372
- billingMode: row.minimum_balance != null && dec(row.minimum_balance).lt(0) ? "overdraft" : "strict",
373
- expiresAt: null,
374
- error: row.error,
451
+ minimumBalance,
452
+ billingMode: minimumBalance.lt(0) ? "overdraft" : "strict",
453
+ expiresAt: requireText(row.expires_at, "renew_lease"),
454
+ error: null,
375
455
  };
376
- }
377
- const minimumBalance = dec(row.minimum_balance);
378
- return {
379
- leaseId: requireText(row.lease_id, "renew_lease"),
380
- userId,
381
- amount: dec(row.amount),
382
- available: availability.available,
383
- reservedTotal: availability.reserved,
384
- minimumBalance,
385
- billingMode: minimumBalance.lt(0) ? "overdraft" : "strict",
386
- expiresAt: requireText(row.expires_at, "renew_lease"),
387
- error: null,
388
- };
456
+ });
389
457
  }
390
458
  async expireLeases(limit = 100) {
391
459
  if (!Number.isInteger(limit) || limit < 1 || limit > 1000) {
@@ -394,16 +462,7 @@ export class PostgresStore extends CreditStore {
394
462
  return this.leaseRepo.expireLeases(limit);
395
463
  }
396
464
  async getAvailable(userId) {
397
- const row = await this.balanceRepo.getAvailable(userId);
398
- if (row === null) {
399
- return { userId, balance: ZERO, reserved: ZERO, available: ZERO };
400
- }
401
- return {
402
- userId,
403
- balance: dec(row.balance),
404
- reserved: dec(row.reserved),
405
- available: dec(row.available),
406
- };
465
+ return mapAvailable(userId, await this.balanceRepo.getAvailable(userId));
407
466
  }
408
467
  async getActiveCatalog() {
409
468
  return this.loadActiveCatalog();
@@ -413,16 +472,14 @@ export class PostgresStore extends CreditStore {
413
472
  return row === null ? null : normalizeCatalogRevision(row);
414
473
  }
415
474
  async publishAndActivateCatalog(config, label, rollout) {
416
- const canonical = canonicalBursarConfigDict(config);
417
- const parsed = loadConfigFromDict(canonical);
475
+ const parsed = loadConfigFromDict(config, this.providerEnvironment);
476
+ const canonical = canonicalParsedBursarConfigDict(parsed);
418
477
  const rolloutDocument = canonicalCatalogRolloutDict(validateCatalogRollout(parsed, loadCatalogRollout(rollout ?? {})));
419
- const row = await this.catalogRepo.publishAndActivateCatalog(JSON.stringify(canonical), label ?? null, rolloutDocument);
420
- return row.id;
478
+ return this.catalogRepo.publishAndActivateCatalog(canonical, label ?? null, rolloutDocument);
421
479
  }
422
480
  async publishCatalogDraft(config, label) {
423
- const canonical = canonicalBursarConfigDict(config);
424
- const row = await this.catalogRepo.publishCatalogDraft(JSON.stringify(canonical), label ?? null);
425
- return row.id;
481
+ const canonical = canonicalParsedBursarConfigDict(loadConfigFromDict(config, this.providerEnvironment));
482
+ return this.catalogRepo.publishCatalogDraft(canonical, label ?? null);
426
483
  }
427
484
  async getCatalogHistory() {
428
485
  const rows = await this.catalogRepo.getCatalogHistory();
@@ -442,7 +499,7 @@ export class PostgresStore extends CreditStore {
442
499
  const target = await this.getCatalogRevision(version);
443
500
  const parsedRollout = loadCatalogRollout(rollout ?? {});
444
501
  if (target != null) {
445
- validateCatalogRollout(loadConfigFromDict(target.config), parsedRollout);
502
+ validateCatalogRollout(loadConfigFromDict(target.config, this.providerEnvironment), parsedRollout);
446
503
  }
447
504
  const row = await this.catalogRepo.activateCatalogRevision(version, canonicalCatalogRolloutDict(parsedRollout));
448
505
  return row.id;
@@ -461,6 +518,7 @@ export class PostgresStore extends CreditStore {
461
518
  creditPolicy: null,
462
519
  admission: null,
463
520
  allowedOperations: [],
521
+ operationAccess: null,
464
522
  planAssignedAt: null,
465
523
  planAssignmentEndsAt: null,
466
524
  assignmentSourceType: null,
@@ -517,6 +575,7 @@ export class PostgresStore extends CreditStore {
517
575
  operations: admissionOperations,
518
576
  },
519
577
  allowedOperations: row.allowed_operations,
578
+ operationAccess: row.operation_access,
520
579
  planAssignedAt: row.plan_assigned_at,
521
580
  planAssignmentEndsAt: row.plan_assignment_ends_at,
522
581
  assignmentSourceType: row.assignment_source_type,
@@ -596,7 +655,7 @@ export class PostgresStore extends CreditStore {
596
655
  if (options?.afterId != null && options.after == null) {
597
656
  throw new TypeError("afterId requires after");
598
657
  }
599
- const rows = await this.planRepo.listQuotaEvents(userId, options?.after?.toISOString() ?? null, limit, options?.idempotencyKey ?? null, options?.afterId ?? null);
658
+ const rows = await this.planRepo.listQuotaEvents(userId, options?.after instanceof Date ? options.after.toISOString() : (options?.after ?? null), limit, options?.idempotencyKey ?? null, options?.afterId ?? null);
600
659
  return rows.map((row) => ({
601
660
  eventId: row.event_id,
602
661
  quotaKey: row.quota_key,
@@ -634,7 +693,7 @@ export class PostgresStore extends CreditStore {
634
693
  }
635
694
  async refundCredits(entryId, options) {
636
695
  const stableKey = requireStableKey(options?.idempotencyKey);
637
- const row = await this.deductionRepo.refundCredits(entryId, options?.amount != null ? decParam(new Decimal(options.amount)) : null, stableKey, options?.reason ?? null, JSON.stringify(options?.metadata ?? {}));
696
+ const row = await this.deductionRepo.refundCredits(entryId, options?.amount != null ? decParam(new PricingDecimal(options.amount)) : null, stableKey, options?.reason ?? null, JSON.stringify(options?.metadata ?? {}));
638
697
  if (row.error !== null) {
639
698
  return {
640
699
  refundEntryId: null,
@@ -657,9 +716,7 @@ export class PostgresStore extends CreditStore {
657
716
  };
658
717
  }
659
718
  async aggregateStats(start, end) {
660
- if (!(start instanceof Date) || !(end instanceof Date) || end <= start) {
661
- throw new RangeError("aggregateStats requires end after start");
662
- }
719
+ validateAnalyticsRange(start, end);
663
720
  const row = await this.analyticsRepo.aggregateStats(start.toISOString(), end.toISOString());
664
721
  return {
665
722
  totalCreditsConsumed: dec(row.total_credits_consumed),
@@ -670,6 +727,7 @@ export class PostgresStore extends CreditStore {
670
727
  };
671
728
  }
672
729
  async spendByUser(start, end) {
730
+ validateAnalyticsRange(start, end);
673
731
  const rows = await this.analyticsRepo.spendByUser(start.toISOString(), end.toISOString());
674
732
  return (rows ?? []).map((r) => ({
675
733
  userId: r.user_id,
@@ -678,6 +736,7 @@ export class PostgresStore extends CreditStore {
678
736
  }));
679
737
  }
680
738
  async spendByModel(start, end) {
739
+ validateAnalyticsRange(start, end);
681
740
  const rows = await this.analyticsRepo.spendByModel(start.toISOString(), end.toISOString());
682
741
  return (rows ?? []).map((r) => ({
683
742
  model: r.model,
@@ -686,6 +745,10 @@ export class PostgresStore extends CreditStore {
686
745
  }));
687
746
  }
688
747
  async topUsers(limit, start, end) {
748
+ if (!Number.isInteger(limit) || limit < 1 || limit > 10_000) {
749
+ throw new RangeError("topUsers limit must be between 1 and 10000");
750
+ }
751
+ validateAnalyticsRange(start, end);
689
752
  const rows = await this.analyticsRepo.topUsers(limit, start.toISOString(), end.toISOString());
690
753
  return (rows ?? []).map((r) => ({
691
754
  userId: r.user_id,
@@ -693,6 +756,7 @@ export class PostgresStore extends CreditStore {
693
756
  }));
694
757
  }
695
758
  async dailySpend(start, end) {
759
+ validateAnalyticsRange(start, end);
696
760
  const rows = await this.analyticsRepo.dailySpend(start.toISOString(), end.toISOString());
697
761
  return (rows ?? []).map((r) => ({
698
762
  date: r.date,
@@ -791,11 +855,15 @@ export class PostgresStore extends CreditStore {
791
855
  return this.teamRepo.removeTeamMember(teamId, userId);
792
856
  }
793
857
  async deductTeam(teamId, userId, amount, options) {
858
+ if (amount.isNegative() && !amount.isZero())
859
+ throw new RangeError("team deduction amount must be non-negative");
794
860
  const meta = { ...(options?.metadata ?? {}) };
795
861
  const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
796
862
  meta.idempotency_key = effectiveIdempotencyKey;
797
863
  const operation = z.string().min(1).safeParse(meta.operation).data ?? "team_usage";
798
- const row = await this.teamRepo.deductTeam(teamId, userId, decParam(amount), effectiveIdempotencyKey, operation, JSON.stringify(meta));
864
+ const row = await this.teamRepo
865
+ .deductTeam(teamId, userId, decParam(amount), effectiveIdempotencyKey, operation, JSON.stringify(meta), options.expectedPricing?.planId ?? null, options.expectedPricing?.catalogVersion ?? null)
866
+ .catch(mapStaleQuote);
799
867
  if (row.error !== null) {
800
868
  return {
801
869
  entryId: null,
@@ -808,7 +876,7 @@ export class PostgresStore extends CreditStore {
808
876
  };
809
877
  }
810
878
  return {
811
- entryId: requireText(row.entry_id, "deduct_team"),
879
+ entryId: row.entry_id,
812
880
  teamId: row.team_id,
813
881
  userId: row.user_id,
814
882
  amount: dec(row.amount),
@@ -847,28 +915,44 @@ export class PostgresStore extends CreditStore {
847
915
  region: request.region ?? null,
848
916
  metadata: JSON.stringify(request.metadata ?? {}),
849
917
  });
850
- return rows.map((row) => {
851
- if (row.error_code !== null) {
852
- return {
853
- grantEventId: null,
854
- grantAwardId: null,
855
- recipientSubjectId: null,
856
- ledgerEntryId: null,
857
- amount: null,
858
- replayed: false,
859
- error: row.error_code,
860
- };
918
+ return rows.map(grantProgramAward);
919
+ }
920
+ async provisionAccount(input) {
921
+ const row = await this.balanceRepo.provisionAccount(input);
922
+ if (row.error_code !== null) {
923
+ if (row.error_code === "missing_active_catalog") {
924
+ throw new CatalogNotLoadedError("No active Bursar catalog is available");
861
925
  }
862
- return {
863
- grantEventId: requireText(row.grant_event_id, "execute_grant_program"),
864
- grantAwardId: requireText(row.grant_award_id, "execute_grant_program"),
865
- recipientSubjectId: requireText(row.recipient_subject_id, "execute_grant_program"),
866
- ledgerEntryId: requireText(row.ledger_entry_id, "execute_grant_program"),
867
- amount: dec(row.amount),
868
- replayed: row.replayed,
869
- error: null,
870
- };
871
- });
926
+ throw new ConfigError("The active catalog has no default account plan");
927
+ }
928
+ return {
929
+ accountId: input.accountId,
930
+ planKey: row.plan_key,
931
+ planAssigned: row.plan_assigned,
932
+ grants: row.grants.map(grantProgramAward),
933
+ };
934
+ }
935
+ }
936
+ function grantProgramAward(row) {
937
+ if (row.error_code !== null) {
938
+ return {
939
+ grantEventId: null,
940
+ grantAwardId: null,
941
+ recipientSubjectId: null,
942
+ ledgerEntryId: null,
943
+ amount: null,
944
+ replayed: false,
945
+ error: row.error_code,
946
+ };
872
947
  }
948
+ return {
949
+ grantEventId: requireText(row.grant_event_id, "execute_grant_program"),
950
+ grantAwardId: requireText(row.grant_award_id, "execute_grant_program"),
951
+ recipientSubjectId: requireText(row.recipient_subject_id, "execute_grant_program"),
952
+ ledgerEntryId: requireText(row.ledger_entry_id, "execute_grant_program"),
953
+ amount: dec(row.amount),
954
+ replayed: row.replayed,
955
+ error: null,
956
+ };
873
957
  }
874
958
  //# sourceMappingURL=store.js.map