@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
@@ -49,18 +49,8 @@ export class CatalogRepository {
49
49
  return this.publishRevision(config, label, false, { plans: {} });
50
50
  }
51
51
  async publishRevision(config, label, activate = false, rollout = { plans: {} }) {
52
- const published = safeParse(PublishedRevisionSchema, requireRecordRow(await this.callproc("publish_and_activate_catalog", [
53
- 1,
54
- JSON.parse(config),
55
- label,
56
- activate,
57
- rollout,
58
- ]), "CatalogRepository.publishRevision"), "CatalogRepository.publishRevision");
59
- const revision = await this.getCatalogRevision(published.revision_no);
60
- if (!revision) {
61
- throw new StoreError(`Catalog revision ${published.revision_no} disappeared after publication`);
62
- }
63
- return revision;
52
+ const published = safeParse(PublishedRevisionSchema, requireRecordRow(await this.callproc("publish_and_activate_catalog", [1, config, label, activate, rollout]), "CatalogRepository.publishRevision"), "CatalogRepository.publishRevision");
53
+ return published.revision_id;
64
54
  }
65
55
  async getCatalogHistory() {
66
56
  const rows = await this.callproc("list_catalog_revisions", [500]);
@@ -1 +1 @@
1
- {"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAGhD,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,gBAAgB,EAChB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,wBAAwB,GAAG,CAAC;KAC/B,MAAM,CAAC;IACN,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IACrB,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACtC,OAAO,EAAE,CAAC,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE;IAC3C,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC5B,MAAM,EAAE,SAAS;IACjB,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;IAC3D,UAAU,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAA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AAC,KAAK,KAAK,IAAI,CAAC,EAAE,CAAC;YACxE,MAAM,IAAI,UAAU,CAAC,oBAAoB,OAAO,gBAAgB,CAAC,CAAC;QACpE,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,2CAA2C,CAAC,CAAC;IAC9E,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport type { JsonObject, PostgresRow } from \"../../../shared/json.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n requireRecordRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst CatalogRevisionRowSchema = z\n .object({\n id: z.string().min(1),\n config: z.record(z.string(), z.json()),\n version: z.coerce.number().int().positive(),\n label: z.string().nullable(),\n active: pgBoolean,\n status: z.enum([\"draft\", \"published\", \"active\", \"retired\"]),\n created_at: z.union([z.string(), z.date().transform((v) => v.toISOString())]),\n })\n .strict();\nconst PublishedRevisionSchema = z\n .object({\n revision_id: z.string().min(1),\n revision_no: z.coerce.number().int().positive(),\n status: z.enum([\"published\", \"active\"]),\n })\n .strict();\nexport type CatalogRevisionRow = z.infer<typeof CatalogRevisionRowSchema>;\n\nexport class CatalogRepository {\n constructor(private readonly callproc: CallProc) {}\n\n private parseRevision(row: PostgresRow, context: string): CatalogRevisionRow {\n return safeParse(\n CatalogRevisionRowSchema,\n {\n id: row.id,\n config: row.source_document,\n version: row.revision_no,\n label: row.label,\n active: row.status === \"active\",\n status: row.status,\n created_at: row.created_at,\n },\n context,\n );\n }\n\n async getActiveCatalog(): Promise<CatalogRevisionRow | null> {\n const rows = await this.callproc(\"active_catalog_revision\", []);\n const row = optionalRecordRow(rows, \"CatalogRepository.getActiveCatalog\");\n if (row === null || Object.values(row).every((value) => value === null)) return null;\n return this.parseRevision(row, \"CatalogRepository.getActiveCatalog\");\n }\n\n async publishAndActivateCatalog(\n config: string,\n label: string | null,\n rollout: JsonObject,\n ): Promise<CatalogRevisionRow> {\n return this.publishRevision(config, label, true, rollout);\n }\n\n async publishCatalogDraft(config: string, label: string | null): Promise<CatalogRevisionRow> {\n return this.publishRevision(config, label, false, { plans: {} });\n }\n\n private async publishRevision(\n config: string,\n label: string | null,\n activate = false,\n rollout: JsonObject = { plans: {} },\n ): Promise<CatalogRevisionRow> {\n const published = safeParse(\n PublishedRevisionSchema,\n requireRecordRow(\n await this.callproc(\"publish_and_activate_catalog\", [\n 1,\n JSON.parse(config),\n label,\n activate,\n rollout,\n ]),\n \"CatalogRepository.publishRevision\",\n ),\n \"CatalogRepository.publishRevision\",\n );\n const revision = await this.getCatalogRevision(published.revision_no);\n if (!revision) {\n throw new StoreError(\n `Catalog revision ${published.revision_no} disappeared after publication`,\n );\n }\n return revision;\n }\n\n async getCatalogHistory(): Promise<CatalogRevisionRow[]> {\n const rows = await this.callproc(\"list_catalog_revisions\", [500]);\n return (rows ?? []).map((row) => {\n const parsedRow = optionalRecordRow([row], \"CatalogRepository.getCatalogHistory\");\n if (parsedRow === null) {\n throw new StoreError(\"CatalogRepository.getCatalogHistory returned a non-object row\");\n }\n return this.parseRevision(parsedRow, \"CatalogRepository.getCatalogHistory\");\n });\n }\n\n async getCatalogRevision(version: number): Promise<CatalogRevisionRow | null> {\n const rows = await this.callproc(\"catalog_revision_by_number\", [version]);\n const row = optionalRecordRow(rows, \"CatalogRepository.getCatalogRevision\");\n if (row === null || Object.values(row).every((value) => value === null)) return null;\n return this.parseRevision(row, \"CatalogRepository.getCatalogRevision\");\n }\n\n async activateCatalogRevision(version: number, rollout: JsonObject): Promise<CatalogRevisionRow> {\n const rows = await this.callproc(\"activate_catalog_revision\", [version, rollout]);\n const row = optionalRecordRow(rows, \"CatalogRepository.activateCatalogRevision\");\n if (row === null || Object.values(row).every((value) => value === null)) {\n throw new StoreError(`Catalog revision ${version} was not found`);\n }\n return this.parseRevision(row, \"CatalogRepository.activateCatalogRevision\");\n }\n}\n"]}
1
+ {"version":3,"file":"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C5E,IAAI,GAAG,KAAK,IAAI,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,IAAI,CAAC;YAAE,OAAO,IAAI,CAAC;QACrF,OAAO,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,sCAAsC,CAAC,CAAC;IACzE,CAAC;IAED,KAAK,CAAC,uBAAuB,CAAC,OAAe,EAAE,OAAmB;QAChE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,2BAA2B,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC;QAClF,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,2CAA2C,CAAC,CAAC;QACjF,IAAI,GAAG,KAAK,IAAI,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,IAAI,CAAC,EAAE,CAAC;YACxE,MAAM,IAAI,UAAU,CAAC,oBAAoB,OAAO,gBAAgB,CAAC,CAAC;QACpE,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,2CAA2C,CAAC,CAAC;IAC9E,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport type { JsonObject, PostgresRow } from \"../../../shared/json.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n requireRecordRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst CatalogRevisionRowSchema = z\n .object({\n id: z.string().min(1),\n config: z.record(z.string(), z.json()),\n version: z.coerce.number().int().positive(),\n label: z.string().nullable(),\n active: pgBoolean,\n status: z.enum([\"draft\", \"published\", \"active\", \"retired\"]),\n created_at: z.union([z.string(), z.date().transform((v) => v.toISOString())]),\n })\n .strict();\nconst PublishedRevisionSchema = z\n .object({\n revision_id: z.string().min(1),\n revision_no: z.coerce.number().int().positive(),\n status: z.enum([\"published\", \"active\"]),\n })\n .strict();\nexport type CatalogRevisionRow = z.infer<typeof CatalogRevisionRowSchema>;\n\nexport class CatalogRepository {\n constructor(private readonly callproc: CallProc) {}\n\n private parseRevision(row: PostgresRow, context: string): CatalogRevisionRow {\n return safeParse(\n CatalogRevisionRowSchema,\n {\n id: row.id,\n config: row.source_document,\n version: row.revision_no,\n label: row.label,\n active: row.status === \"active\",\n status: row.status,\n created_at: row.created_at,\n },\n context,\n );\n }\n\n async getActiveCatalog(): Promise<CatalogRevisionRow | null> {\n const rows = await this.callproc(\"active_catalog_revision\", []);\n const row = optionalRecordRow(rows, \"CatalogRepository.getActiveCatalog\");\n if (row === null || Object.values(row).every((value) => value === null)) return null;\n return this.parseRevision(row, \"CatalogRepository.getActiveCatalog\");\n }\n\n async publishAndActivateCatalog(\n config: JsonObject,\n label: string | null,\n rollout: JsonObject,\n ): Promise<string> {\n return this.publishRevision(config, label, true, rollout);\n }\n\n async publishCatalogDraft(config: JsonObject, label: string | null): Promise<string> {\n return this.publishRevision(config, label, false, { plans: {} });\n }\n\n private async publishRevision(\n config: JsonObject,\n label: string | null,\n activate = false,\n rollout: JsonObject = { plans: {} },\n ): Promise<string> {\n const published = safeParse(\n PublishedRevisionSchema,\n requireRecordRow(\n await this.callproc(\"publish_and_activate_catalog\", [1, config, label, activate, rollout]),\n \"CatalogRepository.publishRevision\",\n ),\n \"CatalogRepository.publishRevision\",\n );\n return published.revision_id;\n }\n\n async getCatalogHistory(): Promise<CatalogRevisionRow[]> {\n const rows = await this.callproc(\"list_catalog_revisions\", [500]);\n return (rows ?? []).map((row) => {\n const parsedRow = optionalRecordRow([row], \"CatalogRepository.getCatalogHistory\");\n if (parsedRow === null) {\n throw new StoreError(\"CatalogRepository.getCatalogHistory returned a non-object row\");\n }\n return this.parseRevision(parsedRow, \"CatalogRepository.getCatalogHistory\");\n });\n }\n\n async getCatalogRevision(version: number): Promise<CatalogRevisionRow | null> {\n const rows = await this.callproc(\"catalog_revision_by_number\", [version]);\n const row = optionalRecordRow(rows, \"CatalogRepository.getCatalogRevision\");\n if (row === null || Object.values(row).every((value) => value === null)) return null;\n return this.parseRevision(row, \"CatalogRepository.getCatalogRevision\");\n }\n\n async activateCatalogRevision(version: number, rollout: JsonObject): Promise<CatalogRevisionRow> {\n const rows = await this.callproc(\"activate_catalog_revision\", [version, rollout]);\n const row = optionalRecordRow(rows, \"CatalogRepository.activateCatalogRevision\");\n if (row === null || Object.values(row).every((value) => value === null)) {\n throw new StoreError(`Catalog revision ${version} was not found`);\n }\n return this.parseRevision(row, \"CatalogRepository.activateCatalogRevision\");\n }\n}\n"]}
@@ -48,6 +48,8 @@ export interface DeductParams {
48
48
  measures: string;
49
49
  dimensions: string;
50
50
  metadata: string;
51
+ expectedPlanId?: string | null;
52
+ expectedRevisionNo?: number | null;
51
53
  }
52
54
  /** Repository for credit deduction operations. */
53
55
  export declare class DeductionRepository {
@@ -1 +1 @@
1
- {"version":3,"file":"deduction.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/deduction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAWlE,eAAO,MAAM,kBAAkB;;;;;;;;;;kBAgC3B,CAAC;AA2BL,QAAA,MAAM,eAAe;;;;;;;kBA6BjB,CAAC;AAaL,QAAA,MAAM,eAAe;;;;;;kBAgBjB,CAAC;AAEL,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAC9D,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe,CAAC,CAAC;AACxD,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe,CAAC,CAAC;AAExD,QAAA,MAAM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AAC,YAAY,CAAC,CA8CrE;IAED,0EAA0E;IACpE,WAAW,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,cAAc,CAAC,CA8B/D;IAED,0CAA0C;IACpC,aAAa,CACjB,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,SAAS,CAAC,CAyBpB;IAED,0CAA0C;IACpC,wBAAwB,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,CAcpF;CACF"}
@@ -18,7 +18,7 @@ export const DeductionRowSchema = z
18
18
  if (row.error === null && (row.charge_id === null || row.balance_after === null)) {
19
19
  context.addIssue({
20
20
  code: "custom",
21
- message: "successful usage charges require a receipt and committed balance",
21
+ message: "successful usage charges require a receipt and balance",
22
22
  });
23
23
  }
24
24
  if (row.error !== null &&
@@ -44,7 +44,10 @@ const ChargeRpcRowSchema = z
44
44
  .strict()
45
45
  .superRefine((row, context) => {
46
46
  if (row.error_code === null && row.charge_id === null) {
47
- context.addIssue({ code: "custom", message: "successful usage charges require a receipt" });
47
+ context.addIssue({
48
+ code: "custom",
49
+ message: "successful usage charges require a receipt",
50
+ });
48
51
  }
49
52
  if (row.error_code !== null &&
50
53
  (row.charge_id !== null || row.ledger_entry_id !== null || row.replayed)) {
@@ -161,6 +164,8 @@ export class DeductionRepository {
161
164
  params.metadata,
162
165
  params.measures,
163
166
  params.dimensions,
167
+ params.expectedPlanId ?? null,
168
+ params.expectedRevisionNo ?? null,
164
169
  ]);
165
170
  const row = safeParse(ChargeRpcRowSchema, requireRow(rows, "DeductionRepository.deductWithAllowance"), "DeductionRepository.deductWithAllowance");
166
171
  const details = row.error_code != null
@@ -195,6 +200,8 @@ export class DeductionRepository {
195
200
  params.metadata,
196
201
  params.measures,
197
202
  params.dimensions,
203
+ params.expectedPlanId ?? null,
204
+ params.expectedRevisionNo ?? null,
198
205
  ]);
199
206
  const row = safeParse(UsageRecordRpcRowSchema, requireRow(rows, "DeductionRepository.recordUsage"), "DeductionRepository.recordUsage");
200
207
  return safeParse(UsageRecordRowSchema, {
@@ -1 +1 @@
1
- {"version":3,"file":"deduction.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/deduction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,gBAAgB,EAChB,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAE3E,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC;KAChC,MAAM,CAAC;IACN,SAAS,EAAE,YAAY,CAAC,QAAQ,EAAE;IAClC,QAAQ,EAAE,YAAY,CAAC,QAAQ,EAAE;IACjC,MAAM,EAAE,OAAO;IACf,aAAa,EAAE,OAAO,CAAC,QAAQ,EAAE;IACjC,kBAAkB,EAAE,OAAO;IAC3B,UAAU,EAAE,CAAC,CAAC,OAAO,EAAE;IACvB,gBAAgB,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE;IACjE,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE;IACnC,OAAO,EAAE,YAAY;CACtB,CAAC;KACD,MAAM,EAAE;KACR,WAAW,CAAC,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE;IAC5B,IAAI,GA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CAAC,UAAU;YACvB,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,WAAW,EAAE,GAAG,CAAC,aAAa;YAC9B,gBAAgB,EAAE,IAAI;YACtB,KAAK,EAAE,GAAG,CAAC,UAAU;SACtB,EACD,mCAAmC,CACpC,CAAC;IACJ,CAAC;IAED,0CAA0C;IAC1C,KAAK,CAAC,wBAAwB,CAAC,MAAc,EAAE,SAAiB;QAC9D,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,qCAAqC,EAAE,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;QAC7F,MAAM,GAAG,GAAG,gBAAgB,CAAC,IAAI,EAAE,8CAA8C,CAAC,CAAC;QACnF,OAAO,SAAS,CACd,eAAe,EACf;YACE,OAAO,EAAE,MAAM;YACf,UAAU,EAAE,SAAS;YACrB,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,aAAa,EAAE,GAAG,CAAC,aAAa;YAChC,UAAU,EAAE,GAAG,CAAC,UAAU;SAC3B,EACD,8CAA8C,CAC/C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRecordRow,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\n\nexport const DeductionRowSchema = z\n .object({\n charge_id: postgresUuid.nullable(),\n entry_id: postgresUuid.nullable(),\n amount: decimal,\n balance_after: decimal.nullable(),\n allowance_consumed: decimal,\n idempotent: z.boolean(),\n bucket_breakdown: z.record(z.string().min(1), decimal).nullable(),\n error: z.string().min(1).nullable(),\n user_id: postgresUuid,\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error === null && (row.charge_id === null || row.balance_after === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful usage charges require a receipt and committed balance\",\n });\n }\n if (\n row.error !== null &&\n (row.charge_id !== null ||\n row.entry_id !== null ||\n row.balance_after !== null ||\n row.idempotent)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed usage charges cannot expose committed fields\",\n });\n }\n });\n\nconst ChargeRpcRowSchema = z\n .object({\n charge_id: postgresUuid.nullable(),\n ledger_entry_id: postgresUuid.nullable(),\n charged: decimal,\n allowance_covered: decimal,\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && row.charge_id === null) {\n context.addIssue({ code: \"custom\", message: \"successful usage charges require a receipt\" });\n }\n if (\n row.error_code !== null &&\n (row.charge_id !== null || row.ledger_entry_id !== null || row.replayed)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed usage charges cannot expose committed fields\",\n });\n }\n });\n\nconst RefundRowSchema = z\n .object({\n refund_entry_id: postgresUuid.nullable(),\n user_id: postgresUuid.nullable(),\n amount: decimal.nullable(),\n new_balance: decimal.nullable(),\n bucket_breakdown: z.record(z.string().min(1), decimal).nullable(),\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.refund_entry_id === null ||\n row.user_id === null ||\n row.amount === null ||\n row.new_balance === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful refunds require identity and balance fields\",\n });\n }\n if (row.error !== null && (row.refund_entry_id !== null || row.bucket_breakdown !== null)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed refunds cannot expose committed fields\",\n });\n }\n });\n\nconst RefundRpcRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n subject_id: postgresUuid.nullable(),\n amount: decimal.nullable(),\n balance_after: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict();\n\nconst RevokeRowSchema = z\n .object({\n user_id: postgresUuid,\n entry_type: z.string().min(1),\n revoked: decimal,\n balance_after: decimal.nullable(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && row.balance_after === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful revocations require a committed balance\",\n });\n }\n });\n\nexport type DeductionRow = z.infer<typeof DeductionRowSchema>;\nexport type RefundRow = z.infer<typeof RefundRowSchema>;\nexport type RevokeRow = z.infer<typeof RevokeRowSchema>;\n\nconst UsageRecordRowSchema = z\n .object({\n charge_id: postgresUuid.nullable(),\n requested: decimal,\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && row.charge_id === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful usage records require a charge receipt\",\n });\n }\n if (row.error_code !== null && (row.charge_id !== null || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed usage records cannot expose committed fields\",\n });\n }\n });\n\nconst UsageRecordRpcRowSchema = z\n .object({\n charge_id: postgresUuid.nullable(),\n requested: decimal,\n ledger_entry_id: postgresUuid.nullable(),\n charged: decimal,\n allowance_covered: decimal,\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict();\n\nexport type UsageRecordRow = z.infer<typeof UsageRecordRowSchema>;\n\n/** Typed input for the plan-aware operation charge RPC. */\nexport interface DeductParams {\n userId: string;\n operation: string;\n amount: string;\n idempotencyKey: string;\n feature: string | null;\n model: string | null;\n region: string | null;\n measures: string;\n dimensions: string;\n metadata: string;\n}\n\n/** Repository for credit deduction operations. */\nexport class DeductionRepository {\n constructor(private callproc: CallProc) {}\n\n /** Atomically deduct credits with allowance, entitlement, quota, and credit-policy enforcement. */\n async deductWithAllowance(params: DeductParams): Promise<DeductionRow> {\n const rows = await this.callproc(\"charge_usage_for_operation\", [\n params.userId,\n params.operation,\n params.amount,\n params.idempotencyKey,\n params.feature,\n params.model,\n params.region,\n params.metadata,\n params.measures,\n params.dimensions,\n ]);\n const row = safeParse(\n ChargeRpcRowSchema,\n requireRow(rows, \"DeductionRepository.deductWithAllowance\"),\n \"DeductionRepository.deductWithAllowance\",\n );\n const details =\n row.error_code != null\n ? null\n : optionalRecordRow(\n await this.callproc(\"get_credit_operation_details\", [\n params.userId,\n row.ledger_entry_id ?? null,\n params.idempotencyKey,\n ]),\n \"DeductionRepository.deductWithAllowance.details\",\n );\n return safeParse(\n DeductionRowSchema,\n {\n charge_id: row.charge_id,\n user_id: params.userId,\n entry_id: row.ledger_entry_id,\n amount: row.charged,\n allowance_consumed: row.allowance_covered,\n balance_after: row.error_code === null ? details?.balance_after : null,\n bucket_breakdown: row.error_code === null ? details?.bucket_breakdown : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"DeductionRepository.deductWithAllowance\",\n );\n }\n\n /** Append a priced usage event without creating another balance debit. */\n async recordUsage(params: DeductParams): Promise<UsageRecordRow> {\n const rows = await this.callproc(\"record_usage\", [\n params.userId,\n params.operation,\n params.amount,\n params.idempotencyKey,\n params.feature,\n params.model,\n params.region,\n params.metadata,\n params.measures,\n params.dimensions,\n ]);\n const row = safeParse(\n UsageRecordRpcRowSchema,\n requireRow(rows, \"DeductionRepository.recordUsage\"),\n \"DeductionRepository.recordUsage\",\n );\n return safeParse(\n UsageRecordRowSchema,\n {\n charge_id: row.charge_id,\n requested: row.requested,\n replayed: row.replayed,\n error_code: row.error_code,\n },\n \"DeductionRepository.recordUsage\",\n );\n }\n\n /** Refund a previous credit deduction. */\n async refundCredits(\n entryId: string,\n amount: string | null,\n idempotencyKey: string,\n reason: string | null,\n metadata: string,\n ): Promise<RefundRow> {\n const rows = await this.callproc(\"refund_credit_by_entry\", [\n entryId,\n amount,\n idempotencyKey,\n reason,\n metadata,\n ]);\n const row = safeParse(\n RefundRpcRowSchema,\n requireRow(rows, \"DeductionRepository.refundCredits\"),\n \"DeductionRepository.refundCredits\",\n );\n return safeParse(\n RefundRowSchema,\n {\n refund_entry_id: row.entry_id,\n user_id: row.subject_id,\n amount: row.amount,\n new_balance: row.balance_after,\n bucket_breakdown: null,\n error: row.error_code,\n },\n \"DeductionRepository.refundCredits\",\n );\n }\n\n /** Revoke credits by transaction type. */\n async revokeCreditsByEntryType(userId: string, entryType: string): Promise<RevokeRow> {\n const rows = await this.callproc(\"revoke_subject_credits_by_operation\", [userId, entryType]);\n const row = requireRecordRow(rows, \"DeductionRepository.revokeCreditsByEntryType\");\n return safeParse(\n RevokeRowSchema,\n {\n user_id: userId,\n entry_type: entryType,\n revoked: row.revoked,\n balance_after: row.balance_after,\n error_code: row.error_code,\n },\n \"DeductionRepository.revokeCreditsByEntryType\",\n );\n }\n}\n"]}
1
+ {"version":3,"file":"deduction.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/deduction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,gBAAgB,EAChB,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAE3E,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC;KAChC,MAAM,CAAC;IACN,SAAS,EAAE,YAAY,CAAC,QAAQ,EAAE;IAClC,QAAQ,EAAE,YAAY,CAAC,QAAQ,EAAE;IACjC,MAAM,EAAE,OAAO;IACf,aAAa,EAAE,OAAO,CAAC,QAAQ,EAAE;IACjC,kBAAkB,EAAE,OAAO;IAC3B,UAAU,EAAE,CAAC,CAAC,OAAO,EAAE;IACvB,gBAAgB,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE;IACjE,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,E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O;YACP,MAAM;YACN,cAAc;YACd,MAAM;YACN,QAAQ;SACT,CAAC,CAAC;QACH,MAAM,GAAG,GAAG,SAAS,CACnB,kBAAkB,EAClB,UAAU,CAAC,IAAI,EAAE,mCAAmC,CAAC,EACrD,mCAAmC,CACpC,CAAC;QACF,OAAO,SAAS,CACd,eAAe,EACf;YACE,eAAe,EAAE,GAAG,CAAC,QAAQ;YAC7B,OAAO,EAAE,GAAG,CAAC,UAAU;YACvB,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,WAAW,EAAE,GAAG,CAAC,aAAa;YAC9B,gBAAgB,EAAE,IAAI;YACtB,KAAK,EAAE,GAAG,CAAC,UAAU;SACtB,EACD,mCAAmC,CACpC,CAAC;IACJ,CAAC;IAED,0CAA0C;IAC1C,KAAK,CAAC,wBAAwB,CAAC,MAAc,EAAE,SAAiB;QAC9D,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,qCAAqC,EAAE,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;QAC7F,MAAM,GAAG,GAAG,gBAAgB,CAAC,IAAI,EAAE,8CAA8C,CAAC,CAAC;QACnF,OAAO,SAAS,CACd,eAAe,EACf;YACE,OAAO,EAAE,MAAM;YACf,UAAU,EAAE,SAAS;YACrB,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,aAAa,EAAE,GAAG,CAAC,aAAa;YAChC,UAAU,EAAE,GAAG,CAAC,UAAU;SAC3B,EACD,8CAA8C,CAC/C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRecordRow,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\n\nexport const DeductionRowSchema = z\n .object({\n charge_id: postgresUuid.nullable(),\n entry_id: postgresUuid.nullable(),\n amount: decimal,\n balance_after: decimal.nullable(),\n allowance_consumed: decimal,\n idempotent: z.boolean(),\n bucket_breakdown: z.record(z.string().min(1), decimal).nullable(),\n error: z.string().min(1).nullable(),\n user_id: postgresUuid,\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error === null && (row.charge_id === null || row.balance_after === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful usage charges require a receipt and balance\",\n });\n }\n if (\n row.error !== null &&\n (row.charge_id !== null ||\n row.entry_id !== null ||\n row.balance_after !== null ||\n row.idempotent)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed usage charges cannot expose committed fields\",\n });\n }\n });\n\nconst ChargeRpcRowSchema = z\n .object({\n charge_id: postgresUuid.nullable(),\n ledger_entry_id: postgresUuid.nullable(),\n charged: decimal,\n allowance_covered: decimal,\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && row.charge_id === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful usage charges require a receipt\",\n });\n }\n if (\n row.error_code !== null &&\n (row.charge_id !== null || row.ledger_entry_id !== null || row.replayed)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed usage charges cannot expose committed fields\",\n });\n }\n });\n\nconst RefundRowSchema = z\n .object({\n refund_entry_id: postgresUuid.nullable(),\n user_id: postgresUuid.nullable(),\n amount: decimal.nullable(),\n new_balance: decimal.nullable(),\n bucket_breakdown: z.record(z.string().min(1), decimal).nullable(),\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.refund_entry_id === null ||\n row.user_id === null ||\n row.amount === null ||\n row.new_balance === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful refunds require identity and balance fields\",\n });\n }\n if (row.error !== null && (row.refund_entry_id !== null || row.bucket_breakdown !== null)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed refunds cannot expose committed fields\",\n });\n }\n });\n\nconst RefundRpcRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n subject_id: postgresUuid.nullable(),\n amount: decimal.nullable(),\n balance_after: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict();\n\nconst RevokeRowSchema = z\n .object({\n user_id: postgresUuid,\n entry_type: z.string().min(1),\n revoked: decimal,\n balance_after: decimal.nullable(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && row.balance_after === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful revocations require a committed balance\",\n });\n }\n });\n\nexport type DeductionRow = z.infer<typeof DeductionRowSchema>;\nexport type RefundRow = z.infer<typeof RefundRowSchema>;\nexport type RevokeRow = z.infer<typeof RevokeRowSchema>;\n\nconst UsageRecordRowSchema = z\n .object({\n charge_id: postgresUuid.nullable(),\n requested: decimal,\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && row.charge_id === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful usage records require a charge receipt\",\n });\n }\n if (row.error_code !== null && (row.charge_id !== null || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed usage records cannot expose committed fields\",\n });\n }\n });\n\nconst UsageRecordRpcRowSchema = z\n .object({\n charge_id: postgresUuid.nullable(),\n requested: decimal,\n ledger_entry_id: postgresUuid.nullable(),\n charged: decimal,\n allowance_covered: decimal,\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict();\n\nexport type UsageRecordRow = z.infer<typeof UsageRecordRowSchema>;\n\n/** Typed input for the plan-aware operation charge RPC. */\nexport interface DeductParams {\n userId: string;\n operation: string;\n amount: string;\n idempotencyKey: string;\n feature: string | null;\n model: string | null;\n region: string | null;\n measures: string;\n dimensions: string;\n metadata: string;\n expectedPlanId?: string | null;\n expectedRevisionNo?: number | null;\n}\n\n/** Repository for credit deduction operations. */\nexport class DeductionRepository {\n constructor(private callproc: CallProc) {}\n\n /** Atomically deduct credits with allowance, entitlement, quota, and credit-policy enforcement. */\n async deductWithAllowance(params: DeductParams): Promise<DeductionRow> {\n const rows = await this.callproc(\"charge_usage_for_operation\", [\n params.userId,\n params.operation,\n params.amount,\n params.idempotencyKey,\n params.feature,\n params.model,\n params.region,\n params.metadata,\n params.measures,\n params.dimensions,\n params.expectedPlanId ?? null,\n params.expectedRevisionNo ?? null,\n ]);\n const row = safeParse(\n ChargeRpcRowSchema,\n requireRow(rows, \"DeductionRepository.deductWithAllowance\"),\n \"DeductionRepository.deductWithAllowance\",\n );\n const details =\n row.error_code != null\n ? null\n : optionalRecordRow(\n await this.callproc(\"get_credit_operation_details\", [\n params.userId,\n row.ledger_entry_id ?? null,\n params.idempotencyKey,\n ]),\n \"DeductionRepository.deductWithAllowance.details\",\n );\n return safeParse(\n DeductionRowSchema,\n {\n charge_id: row.charge_id,\n user_id: params.userId,\n entry_id: row.ledger_entry_id,\n amount: row.charged,\n allowance_consumed: row.allowance_covered,\n balance_after: row.error_code === null ? details?.balance_after : null,\n bucket_breakdown: row.error_code === null ? details?.bucket_breakdown : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"DeductionRepository.deductWithAllowance\",\n );\n }\n\n /** Append a priced usage event without creating another balance debit. */\n async recordUsage(params: DeductParams): Promise<UsageRecordRow> {\n const rows = await this.callproc(\"record_usage\", [\n params.userId,\n params.operation,\n params.amount,\n params.idempotencyKey,\n params.feature,\n params.model,\n params.region,\n params.metadata,\n params.measures,\n params.dimensions,\n params.expectedPlanId ?? null,\n params.expectedRevisionNo ?? null,\n ]);\n const row = safeParse(\n UsageRecordRpcRowSchema,\n requireRow(rows, \"DeductionRepository.recordUsage\"),\n \"DeductionRepository.recordUsage\",\n );\n return safeParse(\n UsageRecordRowSchema,\n {\n charge_id: row.charge_id,\n requested: row.requested,\n replayed: row.replayed,\n error_code: row.error_code,\n },\n \"DeductionRepository.recordUsage\",\n );\n }\n\n /** Refund a previous credit deduction. */\n async refundCredits(\n entryId: string,\n amount: string | null,\n idempotencyKey: string,\n reason: string | null,\n metadata: string,\n ): Promise<RefundRow> {\n const rows = await this.callproc(\"refund_credit_by_entry\", [\n entryId,\n amount,\n idempotencyKey,\n reason,\n metadata,\n ]);\n const row = safeParse(\n RefundRpcRowSchema,\n requireRow(rows, \"DeductionRepository.refundCredits\"),\n \"DeductionRepository.refundCredits\",\n );\n return safeParse(\n RefundRowSchema,\n {\n refund_entry_id: row.entry_id,\n user_id: row.subject_id,\n amount: row.amount,\n new_balance: row.balance_after,\n bucket_breakdown: null,\n error: row.error_code,\n },\n \"DeductionRepository.refundCredits\",\n );\n }\n\n /** Revoke credits by transaction type. */\n async revokeCreditsByEntryType(userId: string, entryType: string): Promise<RevokeRow> {\n const rows = await this.callproc(\"revoke_subject_credits_by_operation\", [userId, entryType]);\n const row = requireRecordRow(rows, \"DeductionRepository.revokeCreditsByEntryType\");\n return safeParse(\n RevokeRowSchema,\n {\n user_id: userId,\n entry_type: entryType,\n revoked: row.revoked,\n balance_after: row.balance_after,\n error_code: row.error_code,\n },\n \"DeductionRepository.revokeCreditsByEntryType\",\n );\n }\n}\n"]}
@@ -24,6 +24,7 @@ declare const LeasePricingContextRowSchema: z.ZodObject<{
24
24
  plan_id: z.ZodNullable<z.ZodString>;
25
25
  plan_key: z.ZodNullable<z.ZodString>;
26
26
  rate_card: z.ZodNullable<z.ZodString>;
27
+ operation: z.ZodString;
27
28
  }, z.core.$strict>;
28
29
  export type LeaseRow = z.infer<typeof LeaseRowSchema>;
29
30
  export type ReleaseRow = z.infer<typeof ReleaseRowSchema>;
@@ -45,6 +46,8 @@ export declare class LeaseRepository {
45
46
  dimensions: string;
46
47
  minimumBalance: string | null;
47
48
  maxConcurrent: number | null;
49
+ expectedPlanId?: string | null;
50
+ expectedRevisionNo?: number | null;
48
51
  }): Promise<LeaseRow>;
49
52
  /** Charge the actual cost against a lease and mark it settled. */
50
53
  settleLease(params: {
@@ -1 +1 @@
1
- {"version":3,"file":"l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AU,EAAE,MAAM,CAAC;QACnB,QAAQ,EAAE,MAAM,CAAC;KAClB,GAAG,OAAO,CAAC,YAAY,CAAC,CAoExB;IAED,wEAAwE;IAClE,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,sBAAsB,GAAG,IAAI,CAAC,CAM/F;IAED,qDAAqD;IAC/C,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAevE;IAED,4EAA4E;IACtE,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqCvF;IAED,uEAAuE;IACjE,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAQjD;CACF"}
@@ -1,14 +1,17 @@
1
+ import { PricingDecimal } from "../../../pricing-decimal.js";
1
2
  import { z } from "zod";
2
3
  import { DeductionRowSchema } from "./deduction.js";
3
4
  import { optionalRecordRow, postgresUuid, requireRow, safeParse, } from "../../../shared/postgres-validation.js";
4
5
  import { StoreError } from "../../../errors.js";
5
- import { Decimal } from "decimal.js";
6
6
  import { quantizeMoney } from "../../../expr.js";
7
7
  const decimal = z.union([z.string().min(1), z.number().finite()]);
8
8
  const timestamp = z.union([z.string().min(1), z.date()]).transform((value, context) => {
9
9
  const parsed = value instanceof Date ? value : new Date(value);
10
10
  if (Number.isNaN(parsed.getTime())) {
11
- context.addIssue({ code: "custom", message: "expected a valid timestamp" });
11
+ context.addIssue({
12
+ code: "custom",
13
+ message: "expected a valid timestamp",
14
+ });
12
15
  return z.NEVER;
13
16
  }
14
17
  return parsed.toISOString();
@@ -18,7 +21,8 @@ const safeInteger = z
18
21
  .transform(Number)
19
22
  .refine(Number.isSafeInteger, "expected a safe integer");
20
23
  const leaseStatus = z.enum(["active", "settling", "settled", "released", "expired"]);
21
- const LeaseMutationRpcRowSchema = z
24
+ // Acquisition may replay a terminal lease. Such a receipt must not authorize work.
25
+ const LeaseAcquireRpcRowSchema = z
22
26
  .object({
23
27
  lease_id: postgresUuid.nullable(),
24
28
  status: leaseStatus,
@@ -27,6 +31,14 @@ const LeaseMutationRpcRowSchema = z
27
31
  })
28
32
  .strict()
29
33
  .superRefine((row, context) => {
34
+ if (row.error_code === null && row.lease_id === null) {
35
+ context.addIssue({
36
+ code: "custom",
37
+ message: "successful lease acquisition requires an identity",
38
+ });
39
+ }
40
+ });
41
+ const LeaseMutationRpcRowSchema = LeaseAcquireRpcRowSchema.superRefine((row, context) => {
30
42
  if (row.error_code === null && (row.lease_id === null || row.status !== "active")) {
31
43
  context.addIssue({
32
44
  code: "custom",
@@ -102,11 +114,15 @@ const LeasePricingContextRowSchema = z
102
114
  plan_id: postgresUuid.nullable(),
103
115
  plan_key: z.string().min(1).nullable(),
104
116
  rate_card: z.string().min(1).nullable(),
117
+ operation: z.string().min(1),
105
118
  })
106
119
  .strict()
107
120
  .superRefine((row, context) => {
108
121
  if ((row.plan_id === null) !== (row.plan_key === null)) {
109
- context.addIssue({ code: "custom", message: "lease plan identity fields are inconsistent" });
122
+ context.addIssue({
123
+ code: "custom",
124
+ message: "lease plan identity fields are inconsistent",
125
+ });
110
126
  }
111
127
  });
112
128
  /** Repository for lease lifecycle operations (admission control). */
@@ -129,16 +145,19 @@ export class LeaseRepository {
129
145
  params.dimensions,
130
146
  params.minimumBalance,
131
147
  params.maxConcurrent,
148
+ params.expectedPlanId ?? null,
149
+ params.expectedRevisionNo ?? null,
132
150
  ]);
133
- const row = safeParse(LeaseMutationRpcRowSchema, requireRow(rows, "LeaseRepository.createLease"), "LeaseRepository.createLease");
134
- if (row.error_code !== null) {
151
+ const row = safeParse(LeaseAcquireRpcRowSchema, requireRow(rows, "LeaseRepository.createLease"), "LeaseRepository.createLease");
152
+ if (row.error_code !== null || row.status !== "active") {
153
+ const error = row.error_code ?? `${row.status}_lease`;
135
154
  return safeParse(LeaseRowSchema, {
136
155
  lease_id: null,
137
156
  user_id: params.userId,
138
157
  amount: null,
139
158
  expires_at: null,
140
159
  minimum_balance: null,
141
- error: row.error_code,
160
+ error,
142
161
  }, "LeaseRepository.createLease");
143
162
  }
144
163
  const lease = optionalRecordRow(await this.callproc("get_credit_lease", [params.userId, row.lease_id]), "LeaseRepository.createLease.details");
@@ -167,10 +186,8 @@ export class LeaseRepository {
167
186
  ]);
168
187
  const row = safeParse(SettleLeaseRpcRowSchema, requireRow(rows, "LeaseRepository.settleLease"), "LeaseRepository.settleLease");
169
188
  if (row.error_code === null &&
170
- !new Decimal(row.settled_amount).equals(quantizeMoney(new Decimal(params.amount)))) {
171
- throw new StoreError("LeaseRepository.settleLease: committed amount differs from the request", {
172
- indeterminate: true,
173
- });
189
+ !new PricingDecimal(row.settled_amount).equals(quantizeMoney(new PricingDecimal(params.amount)))) {
190
+ throw new StoreError("LeaseRepository.settleLease: settled amount differs from the request");
174
191
  }
175
192
  const charge = row.error_code == null
176
193
  ? optionalRecordRow(await this.callproc("get_credit_operation_details", [
@@ -179,11 +196,28 @@ export class LeaseRepository {
179
196
  params.idempotencyKey,
180
197
  ]), "LeaseRepository.settleLease.details")
181
198
  : null;
199
+ let netAmount = params.amount;
200
+ if (row.error_code === null) {
201
+ const allowance = decimal.safeParse(charge?.allowance_covered);
202
+ if (!allowance.success) {
203
+ throw new StoreError("LeaseRepository.settleLease: missing settlement allowance");
204
+ }
205
+ try {
206
+ const gross = new PricingDecimal(row.settled_amount);
207
+ const covered = new PricingDecimal(allowance.data);
208
+ if (!gross.isFinite() || !covered.isFinite() || covered.lt(0) || covered.gt(gross))
209
+ throw new Error("invalid allowance");
210
+ netAmount = gross.minus(covered).toString();
211
+ }
212
+ catch {
213
+ throw new StoreError("LeaseRepository.settleLease: invalid settlement allowance");
214
+ }
215
+ }
182
216
  return safeParse(DeductionRowSchema, {
183
217
  charge_id: row.charge_id,
184
218
  user_id: params.userId,
185
219
  entry_id: row.ledger_entry_id,
186
- amount: row.error_code === null ? row.settled_amount : params.amount,
220
+ amount: netAmount,
187
221
  allowance_consumed: row.error_code === null ? charge?.allowance_covered : "0",
188
222
  balance_after: row.error_code === null ? charge?.balance_after : null,
189
223
  bucket_breakdown: row.error_code === null ? charge?.bucket_breakdown : null,
@@ -1 +1 @@
1
- {"version":3,"file":"lease.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/lease.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAC3E,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,CAAU,CAAC,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE;IAC7F,MAAM,MAAM,GAAG,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;IAC/D,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC;QACnC,OAAO,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AAE,IAAI;gBAChB,eAAe,EAAE,IAAI;gBACrB,KAAK,EAAE,GAAG,CAAC,UAAU;aACtB,EACD,4BAA4B,CAC7B,CAAC;QACJ,CAAC;QACD,MAAM,KAAK,GAAG,iBAAiB,CAC7B,MAAM,IAAI,CAAC,QAAQ,CAAC,kBAAkB,EAAE,CAAC,MAAM,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC,EAC/D,oCAAoC,CACrC,CAAC;QACF,OAAO,SAAS,CACd,cAAc,EACd;YACE,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,OAAO,EAAE,MAAM;YACf,MAAM,EAAE,GAAG,CAAC,eAAe;YAC3B,UAAU,EAAE,KAAK,EAAE,UAAU;YAC7B,eAAe,EAAE,KAAK,EAAE,eAAe;YACvC,KAAK,EAAE,IAAI;SACZ,EACD,4BAA4B,CAC7B,CAAC;IACJ,CAAC;IAED,uEAAuE;IACvE,KAAK,CAAC,YAAY,CAAC,KAAa;QAC9B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,eAAe,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;QAC3D,MAAM,GAAG,GAAG,SAAS,CACnB,CAAC,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAC9D,UAAU,CAAC,IAAI,EAAE,8BAA8B,CAAC,EAChD,8BAA8B,CAC/B,CAAC;QACF,OAAO,GAAG,CAAC,OAAO,CAAC;IACrB,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { DeductionRowSchema } from \"./deduction.js\";\nimport type { DeductionRow } from \"./deduction.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport { Decimal } from \"decimal.js\";\nimport { quantizeMoney } from \"../../../expr.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst timestamp = z.union([z.string().min(1), z.date()] as const).transform((value, context) => {\n const parsed = value instanceof Date ? value : new Date(value);\n if (Number.isNaN(parsed.getTime())) {\n context.addIssue({ code: \"custom\", message: \"expected a valid timestamp\" });\n return z.NEVER;\n }\n return parsed.toISOString();\n});\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst leaseStatus = z.enum([\"active\", \"settling\", \"settled\", \"released\", \"expired\"]);\n\nconst LeaseMutationRpcRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n status: leaseStatus,\n reserved_amount: decimal,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && (row.lease_id === null || row.status !== \"active\")) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease mutations require an active lease\",\n });\n }\n });\n\nconst SettleLeaseRpcRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n charge_id: postgresUuid.nullable(),\n settled_amount: decimal,\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && row.charge_id === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease settlement requires a charge receipt\",\n });\n }\n if (\n row.error_code !== null &&\n (row.ledger_entry_id !== null || row.charge_id !== null || row.replayed)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease settlement cannot expose committed fields\",\n });\n }\n });\n\nconst LeaseRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n user_id: postgresUuid,\n amount: decimal.nullable(),\n minimum_balance: decimal.nullable(),\n expires_at: timestamp.nullable(),\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.lease_id === null ||\n row.amount === null ||\n row.minimum_balance === null ||\n row.expires_at === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease acquisition requires lease and policy fields\",\n });\n }\n if (\n row.error !== null &&\n (row.lease_id !== null ||\n row.amount !== null ||\n row.minimum_balance !== null ||\n row.expires_at !== null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease mutations cannot expose committed fields\",\n });\n }\n });\n\nconst ReleaseRowSchema = z\n .object({\n released: z.boolean(),\n reason: leaseStatus.or(z.literal(\"missing_lease\")).nullable(),\n })\n .strict();\n\nconst LeasePricingContextRowSchema = z\n .object({\n catalog_revision_no: safeInteger,\n plan_id: postgresUuid.nullable(),\n plan_key: z.string().min(1).nullable(),\n rate_card: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if ((row.plan_id === null) !== (row.plan_key === null)) {\n context.addIssue({ code: \"custom\", message: \"lease plan identity fields are inconsistent\" });\n }\n });\n\nexport type LeaseRow = z.infer<typeof LeaseRowSchema>;\nexport type ReleaseRow = z.infer<typeof ReleaseRowSchema>;\nexport type LeasePricingContextRow = z.infer<typeof LeasePricingContextRowSchema>;\n\n/** Repository for lease lifecycle operations (admission control). */\nexport class LeaseRepository {\n constructor(private callproc: CallProc) {}\n\n /** Atomically acquire a lease (hold) — admission control. */\n async createLease(params: {\n userId: string;\n amount: string;\n operationType: string;\n idempotencyKey: string;\n ttlSeconds: number;\n metadata: string;\n feature: string | null;\n measures: string;\n dimensions: string;\n minimumBalance: string | null;\n maxConcurrent: number | null;\n }): Promise<LeaseRow> {\n const rows = await this.callproc(\"create_lease_for_operation\", [\n params.userId,\n params.operationType,\n params.amount,\n params.idempotencyKey,\n `${params.ttlSeconds} seconds`,\n params.metadata,\n params.feature,\n params.measures,\n params.dimensions,\n params.minimumBalance,\n params.maxConcurrent,\n ]);\n const row = safeParse(\n LeaseMutationRpcRowSchema,\n requireRow(rows, \"LeaseRepository.createLease\"),\n \"LeaseRepository.createLease\",\n );\n if (row.error_code !== null) {\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: params.userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error: row.error_code,\n },\n \"LeaseRepository.createLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [params.userId, row.lease_id]),\n \"LeaseRepository.createLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: params.userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.createLease\",\n );\n }\n\n /** Charge the actual cost against a lease and mark it settled. */\n async settleLease(params: {\n userId: string;\n leaseId: string;\n amount: string;\n idempotencyKey: string;\n feature: string | null;\n model: string | null;\n region: string | null;\n measures: string;\n dimensions: string;\n metadata: string;\n }): Promise<DeductionRow> {\n const rows = await this.callproc(\"settle_lease\", [\n params.userId,\n params.leaseId,\n params.amount,\n params.idempotencyKey,\n params.feature,\n params.model,\n params.region,\n params.measures,\n params.dimensions,\n params.metadata,\n ]);\n const row = safeParse(\n SettleLeaseRpcRowSchema,\n requireRow(rows, \"LeaseRepository.settleLease\"),\n \"LeaseRepository.settleLease\",\n );\n if (\n row.error_code === null &&\n !new Decimal(row.settled_amount).equals(quantizeMoney(new Decimal(params.amount)))\n ) {\n throw new StoreError(\n \"LeaseRepository.settleLease: committed amount differs from the request\",\n {\n indeterminate: true,\n },\n );\n }\n const charge =\n row.error_code == null\n ? optionalRecordRow(\n await this.callproc(\"get_credit_operation_details\", [\n params.userId,\n row.ledger_entry_id ?? null,\n params.idempotencyKey,\n ]),\n \"LeaseRepository.settleLease.details\",\n )\n : null;\n return safeParse(\n DeductionRowSchema,\n {\n charge_id: row.charge_id,\n user_id: params.userId,\n entry_id: row.ledger_entry_id,\n amount: row.error_code === null ? row.settled_amount : params.amount,\n allowance_consumed: row.error_code === null ? charge?.allowance_covered : \"0\",\n balance_after: row.error_code === null ? charge?.balance_after : null,\n bucket_breakdown: row.error_code === null ? charge?.bucket_breakdown : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"LeaseRepository.settleLease\",\n );\n }\n\n /** Return the immutable pricing context captured at lease admission. */\n async getPricingContext(userId: string, leaseId: string): Promise<LeasePricingContextRow | null> {\n const rows = await this.callproc(\"get_credit_lease_pricing_context\", [userId, leaseId]);\n const row = optionalRecordRow(rows, \"LeaseRepository.getPricingContext\");\n return row === null\n ? null\n : safeParse(LeasePricingContextRowSchema, row, \"LeaseRepository.getPricingContext\");\n }\n\n /** Release a lease without charging — idempotent. */\n async releaseLease(userId: string, leaseId: string): Promise<ReleaseRow> {\n const rows = await this.callproc(\"release_lease\", [userId, leaseId]);\n const status = safeParse(\n leaseStatus.or(z.literal(\"missing_lease\")),\n requireRow(rows, \"LeaseRepository.releaseLease\"),\n \"LeaseRepository.releaseLease\",\n );\n return safeParse(\n ReleaseRowSchema,\n {\n released: status === \"released\",\n reason: status === \"released\" ? null : status,\n },\n \"LeaseRepository.releaseLease\",\n );\n }\n\n /** Extend an active lease without changing its captured policy snapshot. */\n async renewLease(userId: string, leaseId: string, ttlSeconds: number): Promise<LeaseRow> {\n const rows = await this.callproc(\"renew_lease\", [userId, leaseId, `${ttlSeconds} seconds`]);\n const row = safeParse(\n LeaseMutationRpcRowSchema,\n requireRow(rows, \"LeaseRepository.renewLease\"),\n \"LeaseRepository.renewLease\",\n );\n if (row.error_code !== null) {\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error: row.error_code,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [userId, row.lease_id]),\n \"LeaseRepository.renewLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n\n /** Expire a bounded batch of leases and release their reservations. */\n async expireLeases(limit: number): Promise<number> {\n const rows = await this.callproc(\"expire_leases\", [limit]);\n const row = safeParse(\n z.object({ expired: z.number().int().nonnegative() }).strict(),\n requireRow(rows, \"LeaseRepository.expireLeases\"),\n \"LeaseRepository.expireLeases\",\n );\n return row.expired;\n }\n}\n"]}
1
+ {"version":3,"file":"lease.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/lease.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAC3E,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,CAAU,CAAC,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE;IAC7F,MAAM,MAAM,GAAG,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;IAC/D,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,EAAE,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E,QAAQ,EAAE,IAAI;gBACd,OAAO,EAAE,MAAM;gBACf,MAAM,EAAE,IAAI;gBACZ,UAAU,EAAE,IAAI;gBAChB,eAAe,EAAE,IAAI;gBACrB,KAAK,EAAE,GAAG,CAAC,UAAU;aACtB,EACD,4BAA4B,CAC7B,CAAC;QACJ,CAAC;QACD,MAAM,KAAK,GAAG,iBAAiB,CAC7B,MAAM,IAAI,CAAC,QAAQ,CAAC,kBAAkB,EAAE,CAAC,MAAM,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC,EAC/D,oCAAoC,CACrC,CAAC;QACF,OAAO,SAAS,CACd,cAAc,EACd;YACE,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,OAAO,EAAE,MAAM;YACf,MAAM,EAAE,GAAG,CAAC,eAAe;YAC3B,UAAU,EAAE,KAAK,EAAE,UAAU;YAC7B,eAAe,EAAE,KAAK,EAAE,eAAe;YACvC,KAAK,EAAE,IAAI;SACZ,EACD,4BAA4B,CAC7B,CAAC;IACJ,CAAC;IAED,uEAAuE;IACvE,KAAK,CAAC,YAAY,CAAC,KAAa;QAC9B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,eAAe,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;QAC3D,MAAM,GAAG,GAAG,SAAS,CACnB,CAAC,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAC9D,UAAU,CAAC,IAAI,EAAE,8BAA8B,CAAC,EAChD,8BAA8B,CAC/B,CAAC;QACF,OAAO,GAAG,CAAC,OAAO,CAAC;IACrB,CAAC;CACF","sourcesContent":["import { PricingDecimal } from \"../../../pricing-decimal.js\";\nimport { z } from \"zod\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { DeductionRowSchema } from \"./deduction.js\";\nimport type { DeductionRow } from \"./deduction.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport { quantizeMoney } from \"../../../expr.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst timestamp = z.union([z.string().min(1), z.date()] as const).transform((value, context) => {\n const parsed = value instanceof Date ? value : new Date(value);\n if (Number.isNaN(parsed.getTime())) {\n context.addIssue({\n code: \"custom\",\n message: \"expected a valid timestamp\",\n });\n return z.NEVER;\n }\n return parsed.toISOString();\n});\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst leaseStatus = z.enum([\"active\", \"settling\", \"settled\", \"released\", \"expired\"]);\n\n// Acquisition may replay a terminal lease. Such a receipt must not authorize work.\nconst LeaseAcquireRpcRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n status: leaseStatus,\n reserved_amount: decimal,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && row.lease_id === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease acquisition requires an identity\",\n });\n }\n });\n\nconst LeaseMutationRpcRowSchema = LeaseAcquireRpcRowSchema.superRefine((row, context) => {\n if (row.error_code === null && (row.lease_id === null || row.status !== \"active\")) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease mutations require an active lease\",\n });\n }\n});\n\nconst SettleLeaseRpcRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n charge_id: postgresUuid.nullable(),\n settled_amount: decimal,\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && row.charge_id === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease settlement requires a charge receipt\",\n });\n }\n if (\n row.error_code !== null &&\n (row.ledger_entry_id !== null || row.charge_id !== null || row.replayed)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease settlement cannot expose committed fields\",\n });\n }\n });\n\nconst LeaseRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n user_id: postgresUuid,\n amount: decimal.nullable(),\n minimum_balance: decimal.nullable(),\n expires_at: timestamp.nullable(),\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.lease_id === null ||\n row.amount === null ||\n row.minimum_balance === null ||\n row.expires_at === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease acquisition requires lease and policy fields\",\n });\n }\n if (\n row.error !== null &&\n (row.lease_id !== null ||\n row.amount !== null ||\n row.minimum_balance !== null ||\n row.expires_at !== null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease mutations cannot expose committed fields\",\n });\n }\n });\n\nconst ReleaseRowSchema = z\n .object({\n released: z.boolean(),\n reason: leaseStatus.or(z.literal(\"missing_lease\")).nullable(),\n })\n .strict();\n\nconst LeasePricingContextRowSchema = z\n .object({\n catalog_revision_no: safeInteger,\n plan_id: postgresUuid.nullable(),\n plan_key: z.string().min(1).nullable(),\n rate_card: z.string().min(1).nullable(),\n operation: z.string().min(1),\n })\n .strict()\n .superRefine((row, context) => {\n if ((row.plan_id === null) !== (row.plan_key === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"lease plan identity fields are inconsistent\",\n });\n }\n });\n\nexport type LeaseRow = z.infer<typeof LeaseRowSchema>;\nexport type ReleaseRow = z.infer<typeof ReleaseRowSchema>;\nexport type LeasePricingContextRow = z.infer<typeof LeasePricingContextRowSchema>;\n\n/** Repository for lease lifecycle operations (admission control). */\nexport class LeaseRepository {\n constructor(private callproc: CallProc) {}\n\n /** Atomically acquire a lease (hold) — admission control. */\n async createLease(params: {\n userId: string;\n amount: string;\n operationType: string;\n idempotencyKey: string;\n ttlSeconds: number;\n metadata: string;\n feature: string | null;\n measures: string;\n dimensions: string;\n minimumBalance: string | null;\n maxConcurrent: number | null;\n expectedPlanId?: string | null;\n expectedRevisionNo?: number | null;\n }): Promise<LeaseRow> {\n const rows = await this.callproc(\"create_lease_for_operation\", [\n params.userId,\n params.operationType,\n params.amount,\n params.idempotencyKey,\n `${params.ttlSeconds} seconds`,\n params.metadata,\n params.feature,\n params.measures,\n params.dimensions,\n params.minimumBalance,\n params.maxConcurrent,\n params.expectedPlanId ?? null,\n params.expectedRevisionNo ?? null,\n ]);\n const row = safeParse(\n LeaseAcquireRpcRowSchema,\n requireRow(rows, \"LeaseRepository.createLease\"),\n \"LeaseRepository.createLease\",\n );\n if (row.error_code !== null || row.status !== \"active\") {\n const error = row.error_code ?? `${row.status}_lease`;\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: params.userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error,\n },\n \"LeaseRepository.createLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [params.userId, row.lease_id]),\n \"LeaseRepository.createLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: params.userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.createLease\",\n );\n }\n\n /** Charge the actual cost against a lease and mark it settled. */\n async settleLease(params: {\n userId: string;\n leaseId: string;\n amount: string;\n idempotencyKey: string;\n feature: string | null;\n model: string | null;\n region: string | null;\n measures: string;\n dimensions: string;\n metadata: string;\n }): Promise<DeductionRow> {\n const rows = await this.callproc(\"settle_lease\", [\n params.userId,\n params.leaseId,\n params.amount,\n params.idempotencyKey,\n params.feature,\n params.model,\n params.region,\n params.measures,\n params.dimensions,\n params.metadata,\n ]);\n const row = safeParse(\n SettleLeaseRpcRowSchema,\n requireRow(rows, \"LeaseRepository.settleLease\"),\n \"LeaseRepository.settleLease\",\n );\n if (\n row.error_code === null &&\n !new PricingDecimal(row.settled_amount).equals(\n quantizeMoney(new PricingDecimal(params.amount)),\n )\n ) {\n throw new StoreError(\"LeaseRepository.settleLease: settled amount differs from the request\");\n }\n const charge =\n row.error_code == null\n ? optionalRecordRow(\n await this.callproc(\"get_credit_operation_details\", [\n params.userId,\n row.ledger_entry_id ?? null,\n params.idempotencyKey,\n ]),\n \"LeaseRepository.settleLease.details\",\n )\n : null;\n let netAmount = params.amount;\n if (row.error_code === null) {\n const allowance = decimal.safeParse(charge?.allowance_covered);\n if (!allowance.success) {\n throw new StoreError(\"LeaseRepository.settleLease: missing settlement allowance\");\n }\n try {\n const gross = new PricingDecimal(row.settled_amount);\n const covered = new PricingDecimal(allowance.data);\n if (!gross.isFinite() || !covered.isFinite() || covered.lt(0) || covered.gt(gross))\n throw new Error(\"invalid allowance\");\n netAmount = gross.minus(covered).toString();\n } catch {\n throw new StoreError(\"LeaseRepository.settleLease: invalid settlement allowance\");\n }\n }\n return safeParse(\n DeductionRowSchema,\n {\n charge_id: row.charge_id,\n user_id: params.userId,\n entry_id: row.ledger_entry_id,\n amount: netAmount,\n allowance_consumed: row.error_code === null ? charge?.allowance_covered : \"0\",\n balance_after: row.error_code === null ? charge?.balance_after : null,\n bucket_breakdown: row.error_code === null ? charge?.bucket_breakdown : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"LeaseRepository.settleLease\",\n );\n }\n\n /** Return the immutable pricing context captured at lease admission. */\n async getPricingContext(userId: string, leaseId: string): Promise<LeasePricingContextRow | null> {\n const rows = await this.callproc(\"get_credit_lease_pricing_context\", [userId, leaseId]);\n const row = optionalRecordRow(rows, \"LeaseRepository.getPricingContext\");\n return row === null\n ? null\n : safeParse(LeasePricingContextRowSchema, row, \"LeaseRepository.getPricingContext\");\n }\n\n /** Release a lease without charging — idempotent. */\n async releaseLease(userId: string, leaseId: string): Promise<ReleaseRow> {\n const rows = await this.callproc(\"release_lease\", [userId, leaseId]);\n const status = safeParse(\n leaseStatus.or(z.literal(\"missing_lease\")),\n requireRow(rows, \"LeaseRepository.releaseLease\"),\n \"LeaseRepository.releaseLease\",\n );\n return safeParse(\n ReleaseRowSchema,\n {\n released: status === \"released\",\n reason: status === \"released\" ? null : status,\n },\n \"LeaseRepository.releaseLease\",\n );\n }\n\n /** Extend an active lease without changing its captured policy snapshot. */\n async renewLease(userId: string, leaseId: string, ttlSeconds: number): Promise<LeaseRow> {\n const rows = await this.callproc(\"renew_lease\", [userId, leaseId, `${ttlSeconds} seconds`]);\n const row = safeParse(\n LeaseMutationRpcRowSchema,\n requireRow(rows, \"LeaseRepository.renewLease\"),\n \"LeaseRepository.renewLease\",\n );\n if (row.error_code !== null) {\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error: row.error_code,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [userId, row.lease_id]),\n \"LeaseRepository.renewLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n\n /** Expire a bounded batch of leases and release their reservations. */\n async expireLeases(limit: number): Promise<number> {\n const rows = await this.callproc(\"expire_leases\", [limit]);\n const row = safeParse(\n z.object({ expired: z.number().int().nonnegative() }).strict(),\n requireRow(rows, \"LeaseRepository.expireLeases\"),\n \"LeaseRepository.expireLeases\",\n );\n return row.expired;\n }\n}\n"]}
@@ -125,7 +125,7 @@ declare const QuotaEventRowSchema: z.ZodObject<{
125
125
  threshold_percent: z.ZodNullable<z.ZodNumber>;
126
126
  idempotency_key: z.ZodString;
127
127
  usage_charge_id: z.ZodNullable<z.ZodString>;
128
- created_at: z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodDate]>, z.ZodTransform<Date, string | Date>>, z.ZodTransform<string, Date>>;
128
+ created_at: z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodDate]>, z.ZodTransform<string, string | Date>>;
129
129
  }, z.core.$strict>;
130
130
  export type UnsetPlanRow = z.infer<typeof UnsetPlanRowSchema>;
131
131
  export type UserPlanRow = z.infer<typeof UserPlanRowSchema>;
@@ -1 +1 @@
1
- {"version":3,"file":"plan.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/plan.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AA8BlE,QAAA,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAwDnB,CAAC;AAEL,QAAA,MAAM,oBAAoB;;;;;;;;;kBAQf,CAAC;AAEZ,QAAA,MAAM,oBAAoB;;;;;;;;;;;;;;;kBASf,CAAC;AAEZ,QAAA,MAAM,kBAAkB;;;;;kBAOb,CAAC;AAEZ,QAAA,MAAM,kBAAkB;;kBAIb,CAAC;AAEZ,QAAA,MAAM,2BAA2B,aAAe,CAAC;AACjD,QAAA,MAAM,2BAA2B;;;;kBAMtB,CAAC;AACZ,QAAA,MAAM,mBAAmB;;;;;;;;;;;;;;;;;kBAgBd,CAAC;AACZ,QAAA,MAAM,mBAAmB;;;;;;;;;;;;;kBAYd,CAAC;AAEZ,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAC9D,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAC5D,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC;AAClE,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC;AAClE,MAAM,MAAM,YAAY,GA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AC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC,CAYzD;IAED,0EAA0E;IACpE,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAO1E;IAED,iEAAiE;IAC3D,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAOxD;IAED,+CAA+C;IACzC,kBAAkB,CACtB,UAAU,EAAE,MAAM,GAAG,IAAI,EACzB,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,qBAAqB,CAAC,CAOhC;IAEK,gBAAgB,CAAC,WAAW,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,qBAAqB,CAAC,CAO9F;IAEK,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC,CAKtF;IAEK,eAAe,CACnB,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GAAG,IAAI,EACpB,KAAK,EAAE,MAAM,EACb,cAAc,EAAE,MAAM,GAAG,IAAI,EAC7B,OAAO,EAAE,MAAM,GAAG,IAAI,GACrB,OAAO,CAAC,aAAa,EAAE,CAAC,CAW1B;IAEK,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAMjE;CACF"}
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { optionalRecordRow, postgresUuid, requireRow, safeParse, } from "../../../shared/postgres-validation.js";
3
3
  import { StoreError } from "../../../errors.js";
4
+ import { utcTimestamp } from "../../../shared/timestamp.js";
4
5
  const decimal = z.union([z.string().min(1), z.number().finite()]);
5
6
  const timestamp = z.union([z.string().min(1), z.date()]).transform((value, context) => {
6
7
  const parsed = value instanceof Date ? value : new Date(value);
@@ -143,7 +144,9 @@ const QuotaEventRowSchema = z
143
144
  threshold_percent: z.number().finite().min(0).max(100).nullable(),
144
145
  idempotency_key: z.string().min(1),
145
146
  usage_charge_id: postgresUuid.nullable(),
146
- created_at: timestamp.transform((value) => value.toISOString()),
147
+ created_at: z
148
+ .union([z.string().min(1), z.date()])
149
+ .transform((value) => (value instanceof Date ? value.toISOString() : utcTimestamp(value))),
147
150
  })
148
151
  .strict();
149
152
  /** Repository for plan management operations. */