@zonastery/bursar 2.1.1 → 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 (334) hide show
  1. package/README.md +20 -3
  2. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  3. package/dist/billing/auto-recharge-service.js +6 -4
  4. package/dist/billing/auto-recharge-service.js.map +1 -1
  5. package/dist/billing/billing-service.d.ts +19 -3
  6. package/dist/billing/billing-service.d.ts.map +1 -1
  7. package/dist/billing/billing-service.js +34 -5
  8. package/dist/billing/billing-service.js.map +1 -1
  9. package/dist/billing/billing-store.d.ts +12 -6
  10. package/dist/billing/billing-store.d.ts.map +1 -1
  11. package/dist/billing/billing-store.js +2 -0
  12. package/dist/billing/billing-store.js.map +1 -1
  13. package/dist/billing/contracts.d.ts +20 -3
  14. package/dist/billing/contracts.d.ts.map +1 -1
  15. package/dist/billing/contracts.js.map +1 -1
  16. package/dist/billing/event-handlers.d.ts +1 -0
  17. package/dist/billing/event-handlers.d.ts.map +1 -1
  18. package/dist/billing/event-handlers.js +40 -13
  19. package/dist/billing/event-handlers.js.map +1 -1
  20. package/dist/billing/event-processor.d.ts +2 -1
  21. package/dist/billing/event-processor.d.ts.map +1 -1
  22. package/dist/billing/event-processor.js +82 -16
  23. package/dist/billing/event-processor.js.map +1 -1
  24. package/dist/billing/financial-event-handlers.d.ts +2 -0
  25. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  26. package/dist/billing/financial-event-handlers.js +160 -48
  27. package/dist/billing/financial-event-handlers.js.map +1 -1
  28. package/dist/billing/index.d.ts +1 -1
  29. package/dist/billing/index.d.ts.map +1 -1
  30. package/dist/billing/index.js.map +1 -1
  31. package/dist/billing/management.d.ts +6 -3
  32. package/dist/billing/management.d.ts.map +1 -1
  33. package/dist/billing/management.js +5 -2
  34. package/dist/billing/management.js.map +1 -1
  35. package/dist/billing/postgres/repositories/auto-recharge.d.ts +3 -1
  36. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  37. package/dist/billing/postgres/repositories/auto-recharge.js +23 -7
  38. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  39. package/dist/billing/postgres/repositories/invoice.d.ts +3 -2
  40. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  41. package/dist/billing/postgres/repositories/invoice.js +33 -3
  42. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  43. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  44. package/dist/billing/postgres/repositories/offer.js +2 -1
  45. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  46. package/dist/billing/postgres/repositories/payment.d.ts +6 -1
  47. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  48. package/dist/billing/postgres/repositories/payment.js +25 -17
  49. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  50. package/dist/billing/postgres/repositories/subscription-change.d.ts +1 -0
  51. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -1
  52. package/dist/billing/postgres/repositories/subscription-change.js +24 -4
  53. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
  54. package/dist/billing/postgres/repositories/subscription.d.ts +1 -0
  55. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  56. package/dist/billing/postgres/repositories/subscription.js +40 -43
  57. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  58. package/dist/billing/postgres/repositories/topup.d.ts +6 -1
  59. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  60. package/dist/billing/postgres/repositories/topup.js +9 -5
  61. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  62. package/dist/billing/postgres/store.d.ts +24 -31
  63. package/dist/billing/postgres/store.d.ts.map +1 -1
  64. package/dist/billing/postgres/store.js +110 -113
  65. package/dist/billing/postgres/store.js.map +1 -1
  66. package/dist/billing/types/catalog.d.ts +1 -0
  67. package/dist/billing/types/catalog.d.ts.map +1 -1
  68. package/dist/billing/types/catalog.js.map +1 -1
  69. package/dist/billing/types/documents.d.ts +15 -1
  70. package/dist/billing/types/documents.d.ts.map +1 -1
  71. package/dist/billing/types/documents.js.map +1 -1
  72. package/dist/billing/types/events.d.ts +2 -0
  73. package/dist/billing/types/events.d.ts.map +1 -1
  74. package/dist/billing/types/events.js +15 -0
  75. package/dist/billing/types/events.js.map +1 -1
  76. package/dist/billing/types/subscriptions.d.ts +10 -0
  77. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  78. package/dist/billing/types/subscriptions.js.map +1 -1
  79. package/dist/breakdown.d.ts +2 -24
  80. package/dist/breakdown.d.ts.map +1 -1
  81. package/dist/breakdown.js +1 -29
  82. package/dist/breakdown.js.map +1 -1
  83. package/dist/bursar.d.ts +5 -17
  84. package/dist/bursar.d.ts.map +1 -1
  85. package/dist/bursar.js +26 -44
  86. package/dist/bursar.js.map +1 -1
  87. package/dist/cli.js +0 -6
  88. package/dist/cli.js.map +1 -1
  89. package/dist/commerce/service.d.ts +1 -0
  90. package/dist/commerce/service.d.ts.map +1 -1
  91. package/dist/commerce/service.js +162 -38
  92. package/dist/commerce/service.js.map +1 -1
  93. package/dist/commerce/types.d.ts +2 -0
  94. package/dist/commerce/types.d.ts.map +1 -1
  95. package/dist/commerce/types.js.map +1 -1
  96. package/dist/config/normalize.d.ts +3 -1
  97. package/dist/config/normalize.d.ts.map +1 -1
  98. package/dist/config/normalize.js +12 -5
  99. package/dist/config/normalize.js.map +1 -1
  100. package/dist/config/parse-access.d.ts.map +1 -1
  101. package/dist/config/parse-access.js +4 -1
  102. package/dist/config/parse-access.js.map +1 -1
  103. package/dist/config/parse-commerce.d.ts.map +1 -1
  104. package/dist/config/parse-commerce.js +32 -17
  105. package/dist/config/parse-commerce.js.map +1 -1
  106. package/dist/config/parse-credits.d.ts.map +1 -1
  107. package/dist/config/parse-credits.js +5 -5
  108. package/dist/config/parse-credits.js.map +1 -1
  109. package/dist/config/parse-plans.d.ts.map +1 -1
  110. package/dist/config/parse-plans.js +13 -9
  111. package/dist/config/parse-plans.js.map +1 -1
  112. package/dist/config/parse-pricing.d.ts.map +1 -1
  113. package/dist/config/parse-pricing.js +7 -5
  114. package/dist/config/parse-pricing.js.map +1 -1
  115. package/dist/config/parse-utils.d.ts +2 -0
  116. package/dist/config/parse-utils.d.ts.map +1 -1
  117. package/dist/config/parse-utils.js +11 -1
  118. package/dist/config/parse-utils.js.map +1 -1
  119. package/dist/config.d.ts +2 -2
  120. package/dist/config.d.ts.map +1 -1
  121. package/dist/config.js +94 -86
  122. package/dist/config.js.map +1 -1
  123. package/dist/credits/amount.d.ts.map +1 -1
  124. package/dist/credits/amount.js +5 -4
  125. package/dist/credits/amount.js.map +1 -1
  126. package/dist/credits/catalog-runtime.d.ts +15 -2
  127. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  128. package/dist/credits/catalog-runtime.js +74 -18
  129. package/dist/credits/catalog-runtime.js.map +1 -1
  130. package/dist/credits/lease-workflow.d.ts +3 -1
  131. package/dist/credits/lease-workflow.d.ts.map +1 -1
  132. package/dist/credits/lease-workflow.js +47 -38
  133. package/dist/credits/lease-workflow.js.map +1 -1
  134. package/dist/credits/low-balance-monitor.d.ts +2 -7
  135. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  136. package/dist/credits/low-balance-monitor.js +6 -57
  137. package/dist/credits/low-balance-monitor.js.map +1 -1
  138. package/dist/credits/postgres/repositories/analytics.d.ts +3 -3
  139. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  140. package/dist/credits/postgres/repositories/analytics.js +25 -7
  141. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  142. package/dist/credits/postgres/repositories/balance.d.ts +28 -0
  143. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  144. package/dist/credits/postgres/repositories/balance.js +33 -14
  145. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  146. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
  147. package/dist/credits/postgres/repositories/bucket.js +2 -2
  148. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  149. package/dist/credits/postgres/repositories/catalog.d.ts +2 -2
  150. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
  151. package/dist/credits/postgres/repositories/catalog.js +2 -12
  152. package/dist/credits/postgres/repositories/catalog.js.map +1 -1
  153. package/dist/credits/postgres/repositories/deduction.d.ts +2 -0
  154. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  155. package/dist/credits/postgres/repositories/deduction.js +9 -2
  156. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  157. package/dist/credits/postgres/repositories/lease.d.ts +3 -0
  158. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  159. package/dist/credits/postgres/repositories/lease.js +46 -12
  160. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  161. package/dist/credits/postgres/repositories/plan.d.ts +1 -1
  162. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
  163. package/dist/credits/postgres/repositories/plan.js +4 -1
  164. package/dist/credits/postgres/repositories/plan.js.map +1 -1
  165. package/dist/credits/postgres/repositories/team.d.ts +1 -1
  166. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  167. package/dist/credits/postgres/repositories/team.js +9 -5
  168. package/dist/credits/postgres/repositories/team.js.map +1 -1
  169. package/dist/credits/postgres/store.d.ts +29 -20
  170. package/dist/credits/postgres/store.d.ts.map +1 -1
  171. package/dist/credits/postgres/store.js +329 -250
  172. package/dist/credits/postgres/store.js.map +1 -1
  173. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  174. package/dist/credits/postgres/value-mappers.js +4 -4
  175. package/dist/credits/postgres/value-mappers.js.map +1 -1
  176. package/dist/credits/rated-wire.d.ts +7 -0
  177. package/dist/credits/rated-wire.d.ts.map +1 -0
  178. package/dist/credits/rated-wire.js +70 -0
  179. package/dist/credits/rated-wire.js.map +1 -0
  180. package/dist/credits/service-errors.d.ts.map +1 -1
  181. package/dist/credits/service-errors.js +8 -1
  182. package/dist/credits/service-errors.js.map +1 -1
  183. package/dist/credits/service-types.d.ts +5 -7
  184. package/dist/credits/service-types.d.ts.map +1 -1
  185. package/dist/credits/service-types.js.map +1 -1
  186. package/dist/credits/service.d.ts +11 -9
  187. package/dist/credits/service.d.ts.map +1 -1
  188. package/dist/credits/service.js +156 -138
  189. package/dist/credits/service.js.map +1 -1
  190. package/dist/credits/store.d.ts +11 -3
  191. package/dist/credits/store.d.ts.map +1 -1
  192. package/dist/credits/store.js +9 -0
  193. package/dist/credits/store.js.map +1 -1
  194. package/dist/credits/types/account.d.ts +9 -1
  195. package/dist/credits/types/account.d.ts.map +1 -1
  196. package/dist/credits/types/account.js.map +1 -1
  197. package/dist/credits/types/admission.d.ts +1 -0
  198. package/dist/credits/types/admission.d.ts.map +1 -1
  199. package/dist/credits/types/admission.js.map +1 -1
  200. package/dist/credits/types/grants.d.ts +12 -0
  201. package/dist/credits/types/grants.d.ts.map +1 -1
  202. package/dist/credits/types/grants.js.map +1 -1
  203. package/dist/credits/types/ledger.d.ts +13 -0
  204. package/dist/credits/types/ledger.d.ts.map +1 -1
  205. package/dist/credits/types/ledger.js.map +1 -1
  206. package/dist/credits/types/quotas.d.ts +2 -1
  207. package/dist/credits/types/quotas.d.ts.map +1 -1
  208. package/dist/credits/types/quotas.js.map +1 -1
  209. package/dist/engine.d.ts.map +1 -1
  210. package/dist/engine.js +51 -34
  211. package/dist/engine.js.map +1 -1
  212. package/dist/errors.d.ts +12 -1
  213. package/dist/errors.d.ts.map +1 -1
  214. package/dist/errors.js +13 -0
  215. package/dist/errors.js.map +1 -1
  216. package/dist/expr/evaluator.d.ts.map +1 -1
  217. package/dist/expr/evaluator.js +29 -9
  218. package/dist/expr/evaluator.js.map +1 -1
  219. package/dist/expr/language.js +1 -1
  220. package/dist/expr/language.js.map +1 -1
  221. package/dist/expr.d.ts.map +1 -1
  222. package/dist/expr.js +5 -6
  223. package/dist/expr.js.map +1 -1
  224. package/dist/generated/pricing-config.schema.json +102 -202
  225. package/dist/generated/pricing-config.types.d.ts +7 -1
  226. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  227. package/dist/generated/pricing-config.types.js.map +1 -1
  228. package/dist/index.d.ts +6 -5
  229. package/dist/index.d.ts.map +1 -1
  230. package/dist/index.js +3 -2
  231. package/dist/index.js.map +1 -1
  232. package/dist/load-config-file.d.ts.map +1 -1
  233. package/dist/load-config-file.js +38 -12
  234. package/dist/load-config-file.js.map +1 -1
  235. package/dist/metrics.d.ts +1 -1
  236. package/dist/metrics.d.ts.map +1 -1
  237. package/dist/metrics.js.map +1 -1
  238. package/dist/node.d.ts +1 -1
  239. package/dist/node.d.ts.map +1 -1
  240. package/dist/node.js.map +1 -1
  241. package/dist/pricing-decimal.d.ts +7 -0
  242. package/dist/pricing-decimal.d.ts.map +1 -0
  243. package/dist/pricing-decimal.js +43 -0
  244. package/dist/pricing-decimal.js.map +1 -0
  245. package/dist/providers/dodo/better-auth-core.d.ts +1 -1
  246. package/dist/providers/dodo/better-auth-core.d.ts.map +1 -1
  247. package/dist/providers/dodo/better-auth-core.js +2 -2
  248. package/dist/providers/dodo/better-auth-core.js.map +1 -1
  249. package/dist/providers/dodo/better-auth.d.ts.map +1 -1
  250. package/dist/providers/dodo/better-auth.js +16 -2
  251. package/dist/providers/dodo/better-auth.js.map +1 -1
  252. package/dist/providers/dodo/event-mapper.d.ts +1 -1
  253. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  254. package/dist/providers/dodo/event-mapper.js +120 -18
  255. package/dist/providers/dodo/event-mapper.js.map +1 -1
  256. package/dist/providers/dodo/nextjs-core.d.ts +1 -1
  257. package/dist/providers/dodo/nextjs-core.d.ts.map +1 -1
  258. package/dist/providers/dodo/nextjs-core.js +2 -2
  259. package/dist/providers/dodo/nextjs-core.js.map +1 -1
  260. package/dist/providers/dodo/nextjs.d.ts.map +1 -1
  261. package/dist/providers/dodo/nextjs.js +16 -6
  262. package/dist/providers/dodo/nextjs.js.map +1 -1
  263. package/dist/providers/dodo/provider.d.ts +5 -2
  264. package/dist/providers/dodo/provider.d.ts.map +1 -1
  265. package/dist/providers/dodo/provider.js +33 -6
  266. package/dist/providers/dodo/provider.js.map +1 -1
  267. package/dist/providers/dodo/verified-payment-payload.d.ts +6 -0
  268. package/dist/providers/dodo/verified-payment-payload.d.ts.map +1 -0
  269. package/dist/providers/dodo/verified-payment-payload.js +42 -0
  270. package/dist/providers/dodo/verified-payment-payload.js.map +1 -0
  271. package/dist/providers/index.d.ts +1 -1
  272. package/dist/providers/index.d.ts.map +1 -1
  273. package/dist/providers/index.js.map +1 -1
  274. package/dist/providers/mock/provider.d.ts +4 -1
  275. package/dist/providers/mock/provider.d.ts.map +1 -1
  276. package/dist/providers/mock/provider.js +3 -1
  277. package/dist/providers/mock/provider.js.map +1 -1
  278. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  279. package/dist/providers/stripe/event-mapper.js +48 -20
  280. package/dist/providers/stripe/event-mapper.js.map +1 -1
  281. package/dist/providers/stripe/provider.d.ts +4 -1
  282. package/dist/providers/stripe/provider.d.ts.map +1 -1
  283. package/dist/providers/stripe/provider.js +64 -23
  284. package/dist/providers/stripe/provider.js.map +1 -1
  285. package/dist/providers/types.d.ts +11 -1
  286. package/dist/providers/types.d.ts.map +1 -1
  287. package/dist/providers/types.js +9 -0
  288. package/dist/providers/types.js.map +1 -1
  289. package/dist/shared/postgres-client.d.ts +3 -0
  290. package/dist/shared/postgres-client.d.ts.map +1 -1
  291. package/dist/shared/postgres-client.js +61 -49
  292. package/dist/shared/postgres-client.js.map +1 -1
  293. package/dist/shared/provider-rejection.d.ts +3 -0
  294. package/dist/shared/provider-rejection.d.ts.map +1 -0
  295. package/dist/shared/provider-rejection.js +17 -0
  296. package/dist/shared/provider-rejection.js.map +1 -0
  297. package/dist/shared/timestamp.d.ts +2 -0
  298. package/dist/shared/timestamp.d.ts.map +1 -1
  299. package/dist/shared/timestamp.js +7 -0
  300. package/dist/shared/timestamp.js.map +1 -1
  301. package/dist/storage/adapters/clickhouse.d.ts +1 -1
  302. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  303. package/dist/storage/adapters/clickhouse.js +18 -17
  304. package/dist/storage/adapters/clickhouse.js.map +1 -1
  305. package/dist/storage/adapters/s3.d.ts +5 -0
  306. package/dist/storage/adapters/s3.d.ts.map +1 -1
  307. package/dist/storage/adapters/s3.js +46 -14
  308. package/dist/storage/adapters/s3.js.map +1 -1
  309. package/dist/storage/diagnostics.d.ts +3 -7
  310. package/dist/storage/diagnostics.d.ts.map +1 -1
  311. package/dist/storage/diagnostics.js +6 -15
  312. package/dist/storage/diagnostics.js.map +1 -1
  313. package/dist/storage/outbox-worker.d.ts.map +1 -1
  314. package/dist/storage/outbox-worker.js +4 -3
  315. package/dist/storage/outbox-worker.js.map +1 -1
  316. package/dist/storage/ports.d.ts +3 -0
  317. package/dist/storage/ports.d.ts.map +1 -1
  318. package/dist/storage/ports.js.map +1 -1
  319. package/dist/storage/postgres-repository.d.ts +1 -3
  320. package/dist/storage/postgres-repository.d.ts.map +1 -1
  321. package/dist/storage/postgres-repository.js +10 -4
  322. package/dist/storage/postgres-repository.js.map +1 -1
  323. package/dist/storage/runtime.d.ts +15 -10
  324. package/dist/storage/runtime.d.ts.map +1 -1
  325. package/dist/storage/runtime.js +74 -68
  326. package/dist/storage/runtime.js.map +1 -1
  327. package/dist/telemetry/index.d.ts +1 -1
  328. package/dist/telemetry/index.js +1 -1
  329. package/dist/telemetry/index.js.map +1 -1
  330. package/package.json +73 -71
  331. package/dist/credits/queries.d.ts +0 -33
  332. package/dist/credits/queries.d.ts.map +0 -1
  333. package/dist/credits/queries.js +0 -71
  334. 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,12 +149,29 @@ 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
+ }
113
175
  withUsageBackend(expected, action) {
114
176
  return this.postgres.withUsageBackend(expected, action);
115
177
  }
@@ -117,6 +179,25 @@ export class PostgresStore extends CreditStore {
117
179
  await this.postgres.close();
118
180
  }
119
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
+ ]);
120
201
  static SCALAR_RPC_NAMES = new Set([
121
202
  "apply_due_plan_assignment_changes",
122
203
  "release_lease",
@@ -126,12 +207,13 @@ export class PostgresStore extends CreditStore {
126
207
  "start_plan_migration",
127
208
  "unassign_plan",
128
209
  ]);
129
- async callproc(name, params) {
210
+ async callproc(name, params, query = this.postgres.query) {
130
211
  if (!PostgresStore.RPC_NAME_RE.test(name)) {
131
212
  throw new StoreError(`Invalid RPC name: ${name}`);
132
213
  }
133
214
  const placeholders = params.map((_, i) => `$${i + 1}`).join(", ");
134
- 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);
135
217
  if (PostgresStore.SCALAR_RPC_NAMES.has(name) && rows.length === 1) {
136
218
  const row = rows[0];
137
219
  if (row === undefined)
@@ -163,19 +245,22 @@ export class PostgresStore extends CreditStore {
163
245
  if (options?.expiresAt) {
164
246
  meta.expires_at = options.expiresAt.toISOString();
165
247
  }
166
- const row = await this.balanceRepo.addCredits(userId, decParam(amount), options?.type ?? "adjustment", JSON.stringify(meta), options?.expiresAt?.toISOString() ?? null, options?.bucket ?? null, stableKey);
167
- if (row.error !== null) {
168
- throw new StoreError(`post_credit: ${row.error}`);
169
- }
170
- return {
171
- entryId: requireText(row.entry_id, "post_credit"),
172
- userId: row.user_id,
173
- amount: dec(row.amount),
174
- newBalance: dec(row.new_balance),
175
- lifetimePurchased: dec(row.lifetime_purchased),
176
- bucket: row.bucket,
177
- idempotent: row.idempotent,
178
- };
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
+ });
179
264
  }
180
265
  async deductWithAllowance(userId, amount, options) {
181
266
  const idempotencyKey = requireStableKey(options?.idempotencyKey);
@@ -188,46 +273,31 @@ export class PostgresStore extends CreditStore {
188
273
  const feature = options?.feature ?? null;
189
274
  const measures = options?.measures ?? {};
190
275
  const dimensions = options?.dimensions ?? {};
191
- const row = await this.deductionRepo.deductWithAllowance({
192
- userId,
193
- operation,
194
- amount: decParam(amount),
195
- idempotencyKey,
196
- feature,
197
- model,
198
- region,
199
- measures: JSON.stringify(measures),
200
- dimensions: JSON.stringify(dimensions),
201
- metadata: JSON.stringify(metadata ?? {}),
202
- });
203
- if (row.error !== null) {
204
- return {
205
- entryId: null,
206
- 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({
207
280
  userId,
208
- amount: dec(row.amount),
209
- allowanceConsumed: dec(row.allowance_consumed),
210
- balanceAfter: row.balance_after == null ? null : dec(row.balance_after),
211
- idempotent: false,
212
- error: row.error,
213
- bucketBreakdown: null,
214
- };
215
- }
216
- return {
217
- entryId: row.entry_id == null ? null : requireText(row.entry_id, "charge_usage_for_operation"),
218
- usageChargeId: requireText(row.charge_id, "charge_usage_for_operation"),
219
- userId,
220
- amount: dec(row.amount),
221
- allowanceConsumed: dec(row.allowance_consumed),
222
- balanceAfter: dec(row.balance_after),
223
- idempotent: row.idempotent,
224
- error: null,
225
- bucketBreakdown: decRecord(row.bucket_breakdown),
226
- };
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
+ });
227
296
  }
228
297
  async recordUsage(userId, operation, amount, options) {
229
298
  const idempotencyKey = requireStableKey(options?.idempotencyKey);
230
- const row = await this.deductionRepo.recordUsage({
299
+ const row = await this.deductionRepo
300
+ .recordUsage({
231
301
  userId,
232
302
  operation,
233
303
  amount: decParam(amount),
@@ -238,7 +308,10 @@ export class PostgresStore extends CreditStore {
238
308
  measures: JSON.stringify(options?.measures ?? {}),
239
309
  dimensions: JSON.stringify(options?.dimensions ?? {}),
240
310
  metadata: JSON.stringify(options?.metadata ?? {}),
241
- });
311
+ expectedPlanId: options.expectedPricing?.planId ?? null,
312
+ expectedRevisionNo: options.expectedPricing?.catalogVersion ?? null,
313
+ })
314
+ .catch(mapStaleQuote);
242
315
  if (row.error_code !== null) {
243
316
  return {
244
317
  usageId: null,
@@ -258,85 +331,73 @@ export class PostgresStore extends CreditStore {
258
331
  }
259
332
  async createLease(userId, amount, operationType, options) {
260
333
  const idempotencyKey = requireStableKey(options?.idempotencyKey);
261
- const row = await this.leaseRepo.createLease({
262
- userId,
263
- amount: decParam(amount),
264
- operationType,
265
- idempotencyKey,
266
- ttlSeconds: options?.ttlSeconds ?? DEFAULT_LEASE_TTL_SECONDS,
267
- metadata: JSON.stringify(options?.metadata ?? {}),
268
- feature: options?.feature ?? null,
269
- measures: JSON.stringify(options?.measures ?? {}),
270
- dimensions: JSON.stringify(options?.dimensions ?? {}),
271
- minimumBalance: options?.floor == null ? null : decParam(options.floor),
272
- maxConcurrent: options?.maxConcurrent ?? null,
273
- });
274
- const availability = await this.getAvailable(userId);
275
- if (row.error !== null) {
276
- return {
277
- 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({
278
339
  userId,
279
- 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),
280
372
  available: availability.available,
281
373
  reservedTotal: availability.reserved,
282
- minimumBalance: row.minimum_balance == null ? null : dec(row.minimum_balance),
283
- billingMode: options?.billingMode ?? "strict",
284
- expiresAt: null,
285
- 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,
286
378
  };
287
- }
288
- return {
289
- leaseId: requireText(row.lease_id, "create_lease_for_operation"),
290
- userId: row.user_id,
291
- amount: dec(row.amount),
292
- available: availability.available,
293
- reservedTotal: availability.reserved,
294
- minimumBalance: dec(row.minimum_balance),
295
- billingMode: dec(row.minimum_balance).lt(0) ? "overdraft" : "strict",
296
- expiresAt: requireText(row.expires_at, "create_lease_for_operation"),
297
- error: null,
298
- };
379
+ });
299
380
  }
300
381
  async settleLease(userId, leaseId, amount, options) {
301
382
  const idempotencyKey = options?.idempotencyKey === undefined
302
383
  ? `lease:${leaseId}:settle`
303
384
  : requireStableKey(options.idempotencyKey);
304
- const row = await this.leaseRepo.settleLease({
305
- userId,
306
- leaseId,
307
- amount: decParam(amount),
308
- idempotencyKey,
309
- feature: options?.feature ?? null,
310
- model: options?.model ?? null,
311
- region: options?.region ?? null,
312
- measures: JSON.stringify(options?.measures ?? {}),
313
- dimensions: JSON.stringify(options?.dimensions ?? {}),
314
- metadata: JSON.stringify(options?.metadata ?? {}),
315
- });
316
- if (row.error !== null) {
317
- return {
318
- entryId: null,
319
- 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({
320
388
  userId,
321
- amount: dec(row.amount),
322
- allowanceConsumed: dec(row.allowance_consumed),
323
- balanceAfter: row.balance_after == null ? null : dec(row.balance_after),
324
- idempotent: false,
325
- error: row.error,
326
- bucketBreakdown: null,
327
- };
328
- }
329
- return {
330
- entryId: row.entry_id == null ? null : requireText(row.entry_id, "settle_lease"),
331
- usageChargeId: requireText(row.charge_id, "settle_lease"),
332
- userId,
333
- amount: dec(row.amount),
334
- allowanceConsumed: dec(row.allowance_consumed),
335
- balanceAfter: dec(row.balance_after),
336
- idempotent: row.idempotent,
337
- error: null,
338
- bucketBreakdown: decRecord(row.bucket_breakdown),
339
- };
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
+ });
340
401
  }
341
402
  async getLeasePricingContext(userId, leaseId) {
342
403
  const row = await this.leaseRepo.getPricingContext(userId, leaseId);
@@ -344,6 +405,7 @@ export class PostgresStore extends CreditStore {
344
405
  return null;
345
406
  return {
346
407
  catalogVersion: row.catalog_revision_no,
408
+ operationType: row.operation,
347
409
  planId: row.plan_id ?? null,
348
410
  planKey: row.plan_key ?? null,
349
411
  rateCard: row.rate_card ?? null,
@@ -362,33 +424,36 @@ export class PostgresStore extends CreditStore {
362
424
  if (!Number.isInteger(ttlSeconds) || ttlSeconds < 1) {
363
425
  throw new RangeError("ttlSeconds must be a positive integer");
364
426
  }
365
- const row = await this.leaseRepo.renewLease(userId, leaseId, ttlSeconds);
366
- const availability = await this.getAvailable(userId);
367
- 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);
368
445
  return {
369
- leaseId: null,
446
+ leaseId: requireText(row.lease_id, "renew_lease"),
370
447
  userId,
371
- amount: row.amount == null ? null : dec(row.amount),
448
+ amount: dec(row.amount),
372
449
  available: availability.available,
373
450
  reservedTotal: availability.reserved,
374
- minimumBalance: row.minimum_balance == null ? null : dec(row.minimum_balance),
375
- billingMode: row.minimum_balance != null && dec(row.minimum_balance).lt(0) ? "overdraft" : "strict",
376
- expiresAt: null,
377
- error: row.error,
451
+ minimumBalance,
452
+ billingMode: minimumBalance.lt(0) ? "overdraft" : "strict",
453
+ expiresAt: requireText(row.expires_at, "renew_lease"),
454
+ error: null,
378
455
  };
379
- }
380
- const minimumBalance = dec(row.minimum_balance);
381
- return {
382
- leaseId: requireText(row.lease_id, "renew_lease"),
383
- userId,
384
- amount: dec(row.amount),
385
- available: availability.available,
386
- reservedTotal: availability.reserved,
387
- minimumBalance,
388
- billingMode: minimumBalance.lt(0) ? "overdraft" : "strict",
389
- expiresAt: requireText(row.expires_at, "renew_lease"),
390
- error: null,
391
- };
456
+ });
392
457
  }
393
458
  async expireLeases(limit = 100) {
394
459
  if (!Number.isInteger(limit) || limit < 1 || limit > 1000) {
@@ -397,16 +462,7 @@ export class PostgresStore extends CreditStore {
397
462
  return this.leaseRepo.expireLeases(limit);
398
463
  }
399
464
  async getAvailable(userId) {
400
- const row = await this.balanceRepo.getAvailable(userId);
401
- if (row === null) {
402
- return { userId, balance: ZERO, reserved: ZERO, available: ZERO };
403
- }
404
- return {
405
- userId,
406
- balance: dec(row.balance),
407
- reserved: dec(row.reserved),
408
- available: dec(row.available),
409
- };
465
+ return mapAvailable(userId, await this.balanceRepo.getAvailable(userId));
410
466
  }
411
467
  async getActiveCatalog() {
412
468
  return this.loadActiveCatalog();
@@ -416,16 +472,14 @@ export class PostgresStore extends CreditStore {
416
472
  return row === null ? null : normalizeCatalogRevision(row);
417
473
  }
418
474
  async publishAndActivateCatalog(config, label, rollout) {
419
- const canonical = canonicalBursarConfigDict(config, this.providerEnvironment);
420
- const parsed = loadConfigFromDict(canonical, this.providerEnvironment);
475
+ const parsed = loadConfigFromDict(config, this.providerEnvironment);
476
+ const canonical = canonicalParsedBursarConfigDict(parsed);
421
477
  const rolloutDocument = canonicalCatalogRolloutDict(validateCatalogRollout(parsed, loadCatalogRollout(rollout ?? {})));
422
- const row = await this.catalogRepo.publishAndActivateCatalog(JSON.stringify(canonical), label ?? null, rolloutDocument);
423
- return row.id;
478
+ return this.catalogRepo.publishAndActivateCatalog(canonical, label ?? null, rolloutDocument);
424
479
  }
425
480
  async publishCatalogDraft(config, label) {
426
- const canonical = canonicalBursarConfigDict(config, this.providerEnvironment);
427
- const row = await this.catalogRepo.publishCatalogDraft(JSON.stringify(canonical), label ?? null);
428
- return row.id;
481
+ const canonical = canonicalParsedBursarConfigDict(loadConfigFromDict(config, this.providerEnvironment));
482
+ return this.catalogRepo.publishCatalogDraft(canonical, label ?? null);
429
483
  }
430
484
  async getCatalogHistory() {
431
485
  const rows = await this.catalogRepo.getCatalogHistory();
@@ -601,7 +655,7 @@ export class PostgresStore extends CreditStore {
601
655
  if (options?.afterId != null && options.after == null) {
602
656
  throw new TypeError("afterId requires after");
603
657
  }
604
- 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);
605
659
  return rows.map((row) => ({
606
660
  eventId: row.event_id,
607
661
  quotaKey: row.quota_key,
@@ -639,7 +693,7 @@ export class PostgresStore extends CreditStore {
639
693
  }
640
694
  async refundCredits(entryId, options) {
641
695
  const stableKey = requireStableKey(options?.idempotencyKey);
642
- 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 ?? {}));
643
697
  if (row.error !== null) {
644
698
  return {
645
699
  refundEntryId: null,
@@ -662,9 +716,7 @@ export class PostgresStore extends CreditStore {
662
716
  };
663
717
  }
664
718
  async aggregateStats(start, end) {
665
- if (!(start instanceof Date) || !(end instanceof Date) || end <= start) {
666
- throw new RangeError("aggregateStats requires end after start");
667
- }
719
+ validateAnalyticsRange(start, end);
668
720
  const row = await this.analyticsRepo.aggregateStats(start.toISOString(), end.toISOString());
669
721
  return {
670
722
  totalCreditsConsumed: dec(row.total_credits_consumed),
@@ -675,6 +727,7 @@ export class PostgresStore extends CreditStore {
675
727
  };
676
728
  }
677
729
  async spendByUser(start, end) {
730
+ validateAnalyticsRange(start, end);
678
731
  const rows = await this.analyticsRepo.spendByUser(start.toISOString(), end.toISOString());
679
732
  return (rows ?? []).map((r) => ({
680
733
  userId: r.user_id,
@@ -683,6 +736,7 @@ export class PostgresStore extends CreditStore {
683
736
  }));
684
737
  }
685
738
  async spendByModel(start, end) {
739
+ validateAnalyticsRange(start, end);
686
740
  const rows = await this.analyticsRepo.spendByModel(start.toISOString(), end.toISOString());
687
741
  return (rows ?? []).map((r) => ({
688
742
  model: r.model,
@@ -691,6 +745,10 @@ export class PostgresStore extends CreditStore {
691
745
  }));
692
746
  }
693
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);
694
752
  const rows = await this.analyticsRepo.topUsers(limit, start.toISOString(), end.toISOString());
695
753
  return (rows ?? []).map((r) => ({
696
754
  userId: r.user_id,
@@ -698,6 +756,7 @@ export class PostgresStore extends CreditStore {
698
756
  }));
699
757
  }
700
758
  async dailySpend(start, end) {
759
+ validateAnalyticsRange(start, end);
701
760
  const rows = await this.analyticsRepo.dailySpend(start.toISOString(), end.toISOString());
702
761
  return (rows ?? []).map((r) => ({
703
762
  date: r.date,
@@ -796,11 +855,15 @@ export class PostgresStore extends CreditStore {
796
855
  return this.teamRepo.removeTeamMember(teamId, userId);
797
856
  }
798
857
  async deductTeam(teamId, userId, amount, options) {
858
+ if (amount.isNegative() && !amount.isZero())
859
+ throw new RangeError("team deduction amount must be non-negative");
799
860
  const meta = { ...(options?.metadata ?? {}) };
800
861
  const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
801
862
  meta.idempotency_key = effectiveIdempotencyKey;
802
863
  const operation = z.string().min(1).safeParse(meta.operation).data ?? "team_usage";
803
- 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);
804
867
  if (row.error !== null) {
805
868
  return {
806
869
  entryId: null,
@@ -813,7 +876,7 @@ export class PostgresStore extends CreditStore {
813
876
  };
814
877
  }
815
878
  return {
816
- entryId: requireText(row.entry_id, "deduct_team"),
879
+ entryId: row.entry_id,
817
880
  teamId: row.team_id,
818
881
  userId: row.user_id,
819
882
  amount: dec(row.amount),
@@ -852,28 +915,44 @@ export class PostgresStore extends CreditStore {
852
915
  region: request.region ?? null,
853
916
  metadata: JSON.stringify(request.metadata ?? {}),
854
917
  });
855
- return rows.map((row) => {
856
- if (row.error_code !== null) {
857
- return {
858
- grantEventId: null,
859
- grantAwardId: null,
860
- recipientSubjectId: null,
861
- ledgerEntryId: null,
862
- amount: null,
863
- replayed: false,
864
- error: row.error_code,
865
- };
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");
866
925
  }
867
- return {
868
- grantEventId: requireText(row.grant_event_id, "execute_grant_program"),
869
- grantAwardId: requireText(row.grant_award_id, "execute_grant_program"),
870
- recipientSubjectId: requireText(row.recipient_subject_id, "execute_grant_program"),
871
- ledgerEntryId: requireText(row.ledger_entry_id, "execute_grant_program"),
872
- amount: dec(row.amount),
873
- replayed: row.replayed,
874
- error: null,
875
- };
876
- });
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
+ };
877
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
+ };
878
957
  }
879
958
  //# sourceMappingURL=store.js.map