@zonastery/bursar 2.0.1 → 2.0.3

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 (285) hide show
  1. package/README.md +22 -14
  2. package/dist/billing/auto-recharge-service.d.ts +1 -1
  3. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  4. package/dist/billing/auto-recharge-service.js +9 -6
  5. package/dist/billing/auto-recharge-service.js.map +1 -1
  6. package/dist/billing/billing-store.d.ts +4 -1
  7. package/dist/billing/billing-store.d.ts.map +1 -1
  8. package/dist/billing/billing-store.js +2 -0
  9. package/dist/billing/billing-store.js.map +1 -1
  10. package/dist/billing/contracts.d.ts +2 -1
  11. package/dist/billing/contracts.d.ts.map +1 -1
  12. package/dist/billing/contracts.js.map +1 -1
  13. package/dist/billing/event-handlers.d.ts +2 -3
  14. package/dist/billing/event-handlers.d.ts.map +1 -1
  15. package/dist/billing/event-handlers.js +38 -49
  16. package/dist/billing/event-handlers.js.map +1 -1
  17. package/dist/billing/event-processor.d.ts.map +1 -1
  18. package/dist/billing/event-processor.js +22 -10
  19. package/dist/billing/event-processor.js.map +1 -1
  20. package/dist/billing/financial-event-handlers.d.ts +2 -2
  21. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  22. package/dist/billing/financial-event-handlers.js +7 -7
  23. package/dist/billing/financial-event-handlers.js.map +1 -1
  24. package/dist/billing/postgres/repositories/auto-recharge.js +1 -1
  25. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  26. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  27. package/dist/billing/postgres/repositories/event.js +33 -1
  28. package/dist/billing/postgres/repositories/event.js.map +1 -1
  29. package/dist/billing/postgres/repositories/offer.d.ts +1 -1
  30. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  31. package/dist/billing/postgres/repositories/offer.js +1 -1
  32. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  33. package/dist/billing/postgres/repositories/topup.d.ts +1 -1
  34. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  35. package/dist/billing/postgres/repositories/topup.js +1 -1
  36. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  37. package/dist/billing/postgres/store.d.ts +6 -2
  38. package/dist/billing/postgres/store.d.ts.map +1 -1
  39. package/dist/billing/postgres/store.js +21 -6
  40. package/dist/billing/postgres/store.js.map +1 -1
  41. package/dist/billing/service-types.d.ts +2 -15
  42. package/dist/billing/service-types.d.ts.map +1 -1
  43. package/dist/billing/service-types.js.map +1 -1
  44. package/dist/billing/types/auto-recharge.d.ts +1 -1
  45. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  46. package/dist/billing/types/auto-recharge.js.map +1 -1
  47. package/dist/billing/types/catalog.d.ts +1 -1
  48. package/dist/billing/types/catalog.d.ts.map +1 -1
  49. package/dist/billing/types/catalog.js.map +1 -1
  50. package/dist/billing/types/documents.d.ts +1 -1
  51. package/dist/billing/types/documents.d.ts.map +1 -1
  52. package/dist/billing/types/documents.js.map +1 -1
  53. package/dist/billing/types/events.d.ts +11 -2
  54. package/dist/billing/types/events.d.ts.map +1 -1
  55. package/dist/billing/types/events.js +2 -2
  56. package/dist/billing/types/events.js.map +1 -1
  57. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  58. package/dist/billing/types/subscriptions.js.map +1 -1
  59. package/dist/breakdown.d.ts +1 -1
  60. package/dist/breakdown.d.ts.map +1 -1
  61. package/dist/breakdown.js +1 -1
  62. package/dist/breakdown.js.map +1 -1
  63. package/dist/bursar.d.ts +21 -11
  64. package/dist/bursar.d.ts.map +1 -1
  65. package/dist/bursar.js +40 -4
  66. package/dist/bursar.js.map +1 -1
  67. package/dist/catalog.d.ts.map +1 -1
  68. package/dist/catalog.js +1 -1
  69. package/dist/catalog.js.map +1 -1
  70. package/dist/commerce/index.d.ts +0 -1
  71. package/dist/commerce/index.d.ts.map +1 -1
  72. package/dist/commerce/index.js +0 -1
  73. package/dist/commerce/index.js.map +1 -1
  74. package/dist/commerce/service.d.ts.map +1 -1
  75. package/dist/commerce/service.js +154 -106
  76. package/dist/commerce/service.js.map +1 -1
  77. package/dist/commerce/types.d.ts +9 -5
  78. package/dist/commerce/types.d.ts.map +1 -1
  79. package/dist/commerce/types.js.map +1 -1
  80. package/dist/config/parse-credits.d.ts.map +1 -1
  81. package/dist/config/parse-credits.js +0 -6
  82. package/dist/config/parse-credits.js.map +1 -1
  83. package/dist/config/parse-utils.d.ts +1 -1
  84. package/dist/config/parse-utils.d.ts.map +1 -1
  85. package/dist/config/parse-utils.js +1 -1
  86. package/dist/config/parse-utils.js.map +1 -1
  87. package/dist/config/types.d.ts +1 -6
  88. package/dist/config/types.d.ts.map +1 -1
  89. package/dist/config/types.js.map +1 -1
  90. package/dist/config.d.ts.map +1 -1
  91. package/dist/config.js +8 -1
  92. package/dist/config.js.map +1 -1
  93. package/dist/credits/amount.d.ts +8 -0
  94. package/dist/credits/amount.d.ts.map +1 -0
  95. package/dist/credits/amount.js +32 -0
  96. package/dist/credits/amount.js.map +1 -0
  97. package/dist/credits/catalog-runtime.d.ts +5 -7
  98. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  99. package/dist/credits/catalog-runtime.js +4 -13
  100. package/dist/credits/catalog-runtime.js.map +1 -1
  101. package/dist/credits/lease-workflow.d.ts +2 -2
  102. package/dist/credits/lease-workflow.d.ts.map +1 -1
  103. package/dist/credits/lease-workflow.js +24 -21
  104. package/dist/credits/lease-workflow.js.map +1 -1
  105. package/dist/credits/low-balance-monitor.d.ts +1 -1
  106. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  107. package/dist/credits/low-balance-monitor.js +3 -4
  108. package/dist/credits/low-balance-monitor.js.map +1 -1
  109. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  110. package/dist/credits/postgres/repositories/balance.js +1 -1
  111. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  112. package/dist/credits/postgres/repositories/bucket.js +1 -1
  113. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  114. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  115. package/dist/credits/postgres/repositories/lease.js +4 -2
  116. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  117. package/dist/credits/postgres/repositories/team.d.ts +2 -1
  118. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  119. package/dist/credits/postgres/repositories/team.js +19 -5
  120. package/dist/credits/postgres/repositories/team.js.map +1 -1
  121. package/dist/credits/postgres/store.d.ts +18 -14
  122. package/dist/credits/postgres/store.d.ts.map +1 -1
  123. package/dist/credits/postgres/store.js +30 -18
  124. package/dist/credits/postgres/store.js.map +1 -1
  125. package/dist/credits/postgres/value-mappers.d.ts +1 -1
  126. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  127. package/dist/credits/postgres/value-mappers.js +1 -1
  128. package/dist/credits/postgres/value-mappers.js.map +1 -1
  129. package/dist/credits/service-errors.d.ts +1 -1
  130. package/dist/credits/service-errors.d.ts.map +1 -1
  131. package/dist/credits/service-errors.js +1 -1
  132. package/dist/credits/service-errors.js.map +1 -1
  133. package/dist/credits/service-types.d.ts +21 -16
  134. package/dist/credits/service-types.d.ts.map +1 -1
  135. package/dist/credits/service-types.js.map +1 -1
  136. package/dist/credits/service.d.ts +21 -17
  137. package/dist/credits/service.d.ts.map +1 -1
  138. package/dist/credits/service.js +81 -38
  139. package/dist/credits/service.js.map +1 -1
  140. package/dist/credits/store.d.ts +26 -23
  141. package/dist/credits/store.d.ts.map +1 -1
  142. package/dist/credits/store.js +4 -2
  143. package/dist/credits/store.js.map +1 -1
  144. package/dist/credits/types/account.d.ts +1 -1
  145. package/dist/credits/types/account.d.ts.map +1 -1
  146. package/dist/credits/types/account.js.map +1 -1
  147. package/dist/credits/types/grants.d.ts.map +1 -1
  148. package/dist/credits/types/grants.js.map +1 -1
  149. package/dist/credits/types/teams.d.ts +1 -0
  150. package/dist/credits/types/teams.d.ts.map +1 -1
  151. package/dist/credits/types/teams.js.map +1 -1
  152. package/dist/engine.js +1 -1
  153. package/dist/engine.js.map +1 -1
  154. package/dist/errors.d.ts +4 -0
  155. package/dist/errors.d.ts.map +1 -1
  156. package/dist/errors.js +34 -0
  157. package/dist/errors.js.map +1 -1
  158. package/dist/expr/ast.d.ts.map +1 -1
  159. package/dist/expr/ast.js.map +1 -1
  160. package/dist/expr/evaluator.d.ts +1 -1
  161. package/dist/expr/evaluator.d.ts.map +1 -1
  162. package/dist/expr/evaluator.js +1 -1
  163. package/dist/expr/evaluator.js.map +1 -1
  164. package/dist/expr/parser.d.ts +1 -0
  165. package/dist/expr/parser.d.ts.map +1 -1
  166. package/dist/expr/parser.js +15 -3
  167. package/dist/expr/parser.js.map +1 -1
  168. package/dist/expr.d.ts +1 -1
  169. package/dist/expr.d.ts.map +1 -1
  170. package/dist/expr.js +1 -1
  171. package/dist/expr.js.map +1 -1
  172. package/dist/generated/pricing-config.schema.json +31 -29
  173. package/dist/generated/pricing-config.types.d.ts +6 -18
  174. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  175. package/dist/generated/pricing-config.types.js.map +1 -1
  176. package/dist/index.d.ts +7 -3
  177. package/dist/index.d.ts.map +1 -1
  178. package/dist/index.js +2 -0
  179. package/dist/index.js.map +1 -1
  180. package/dist/load-config-file.d.ts +2 -3
  181. package/dist/load-config-file.d.ts.map +1 -1
  182. package/dist/load-config-file.js +14 -29
  183. package/dist/load-config-file.js.map +1 -1
  184. package/dist/metrics.d.ts +1 -1
  185. package/dist/metrics.d.ts.map +1 -1
  186. package/dist/metrics.js.map +1 -1
  187. package/dist/node.d.ts +6 -3
  188. package/dist/node.d.ts.map +1 -1
  189. package/dist/node.js +1 -0
  190. package/dist/node.js.map +1 -1
  191. package/dist/providers/_shared.d.ts +3 -3
  192. package/dist/providers/_shared.d.ts.map +1 -1
  193. package/dist/providers/_shared.js +11 -6
  194. package/dist/providers/_shared.js.map +1 -1
  195. package/dist/providers/dodo/client-contract.d.ts +8 -13
  196. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  197. package/dist/providers/dodo/client-contract.js.map +1 -1
  198. package/dist/providers/dodo/event-mapper.d.ts +1 -1
  199. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  200. package/dist/providers/dodo/event-mapper.js +23 -15
  201. package/dist/providers/dodo/event-mapper.js.map +1 -1
  202. package/dist/providers/dodo/provider.d.ts +4 -6
  203. package/dist/providers/dodo/provider.d.ts.map +1 -1
  204. package/dist/providers/dodo/provider.js +44 -82
  205. package/dist/providers/dodo/provider.js.map +1 -1
  206. package/dist/providers/dodo/webhook-bridge.d.ts +1 -2
  207. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
  208. package/dist/providers/dodo/webhook-bridge.js +0 -1
  209. package/dist/providers/dodo/webhook-bridge.js.map +1 -1
  210. package/dist/providers/environment.d.ts +6 -0
  211. package/dist/providers/environment.d.ts.map +1 -0
  212. package/dist/providers/environment.js +10 -0
  213. package/dist/providers/environment.js.map +1 -0
  214. package/dist/providers/index.d.ts +3 -7
  215. package/dist/providers/index.d.ts.map +1 -1
  216. package/dist/providers/index.js +1 -5
  217. package/dist/providers/index.js.map +1 -1
  218. package/dist/providers/mock/provider.d.ts +6 -8
  219. package/dist/providers/mock/provider.d.ts.map +1 -1
  220. package/dist/providers/mock/provider.js +18 -50
  221. package/dist/providers/mock/provider.js.map +1 -1
  222. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  223. package/dist/providers/stripe/event-mapper.js +82 -14
  224. package/dist/providers/stripe/event-mapper.js.map +1 -1
  225. package/dist/providers/stripe/provider.d.ts +3 -3
  226. package/dist/providers/stripe/provider.d.ts.map +1 -1
  227. package/dist/providers/stripe/provider.js +37 -24
  228. package/dist/providers/stripe/provider.js.map +1 -1
  229. package/dist/providers/types.d.ts +9 -20
  230. package/dist/providers/types.d.ts.map +1 -1
  231. package/dist/providers/types.js.map +1 -1
  232. package/dist/shared/diagnostics.d.ts +8 -0
  233. package/dist/shared/diagnostics.d.ts.map +1 -1
  234. package/dist/shared/diagnostics.js +49 -0
  235. package/dist/shared/diagnostics.js.map +1 -1
  236. package/dist/shared/idempotency.d.ts +9 -0
  237. package/dist/shared/idempotency.d.ts.map +1 -0
  238. package/dist/shared/idempotency.js +34 -0
  239. package/dist/shared/idempotency.js.map +1 -0
  240. package/dist/shared/postgres-client.d.ts +7 -0
  241. package/dist/shared/postgres-client.d.ts.map +1 -1
  242. package/dist/shared/postgres-client.js +21 -4
  243. package/dist/shared/postgres-client.js.map +1 -1
  244. package/dist/shared/postgres-errors.d.ts.map +1 -1
  245. package/dist/shared/postgres-errors.js.map +1 -1
  246. package/dist/storage/adapters/clickhouse.d.ts +9 -2
  247. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  248. package/dist/storage/adapters/clickhouse.js +142 -36
  249. package/dist/storage/adapters/clickhouse.js.map +1 -1
  250. package/dist/storage/adapters/s3.d.ts +44 -6
  251. package/dist/storage/adapters/s3.d.ts.map +1 -1
  252. package/dist/storage/adapters/s3.js +59 -21
  253. package/dist/storage/adapters/s3.js.map +1 -1
  254. package/dist/storage/diagnostics.d.ts +105 -0
  255. package/dist/storage/diagnostics.d.ts.map +1 -0
  256. package/dist/storage/diagnostics.js +227 -0
  257. package/dist/storage/diagnostics.js.map +1 -0
  258. package/dist/storage/maintenance.d.ts +88 -0
  259. package/dist/storage/maintenance.d.ts.map +1 -0
  260. package/dist/storage/maintenance.js +266 -0
  261. package/dist/storage/maintenance.js.map +1 -0
  262. package/dist/storage/outbox-worker.d.ts +20 -0
  263. package/dist/storage/outbox-worker.d.ts.map +1 -1
  264. package/dist/storage/outbox-worker.js +172 -42
  265. package/dist/storage/outbox-worker.js.map +1 -1
  266. package/dist/storage/ports.d.ts +43 -1
  267. package/dist/storage/ports.d.ts.map +1 -1
  268. package/dist/storage/ports.js.map +1 -1
  269. package/dist/storage/postgres-repository.d.ts +7 -2
  270. package/dist/storage/postgres-repository.d.ts.map +1 -1
  271. package/dist/storage/postgres-repository.js +155 -54
  272. package/dist/storage/postgres-repository.js.map +1 -1
  273. package/dist/storage/runtime.d.ts +30 -9
  274. package/dist/storage/runtime.d.ts.map +1 -1
  275. package/dist/storage/runtime.js +268 -37
  276. package/dist/storage/runtime.js.map +1 -1
  277. package/dist/telemetry/index.d.ts +37 -0
  278. package/dist/telemetry/index.d.ts.map +1 -0
  279. package/dist/telemetry/index.js +115 -0
  280. package/dist/telemetry/index.js.map +1 -0
  281. package/dist/telemetry/opentelemetry.d.ts +25 -0
  282. package/dist/telemetry/opentelemetry.d.ts.map +1 -0
  283. package/dist/telemetry/opentelemetry.js +74 -0
  284. package/dist/telemetry/opentelemetry.js.map +1 -0
  285. package/package.json +62 -36
@@ -5,6 +5,7 @@ declare const CreateTeamRowSchema: z.ZodObject<{
5
5
  name: z.ZodNullable<z.ZodString>;
6
6
  team_subject_id: z.ZodNullable<z.ZodString>;
7
7
  account_id: z.ZodNullable<z.ZodString>;
8
+ idempotent: z.ZodBoolean;
8
9
  error_code: z.ZodNullable<z.ZodString>;
9
10
  }, z.core.$strict>;
10
11
  declare const TeamBalanceRowSchema: z.ZodObject<{
@@ -56,7 +57,7 @@ export declare class TeamRepository {
56
57
  private callproc;
57
58
  constructor(callproc: CallProc);
58
59
  /** Create a new team with an initial balance. */
59
- createTeam(ownerSubjectId: string, name: string, initialBalance: string): Promise<CreateTeamRow>;
60
+ createTeam(ownerSubjectId: string, name: string, idempotencyKey: string, initialBalance: string): Promise<CreateTeamRow>;
60
61
  /** Fetch a team's balance and member count. Returns null if the team does not exist. */
61
62
  getTeamBalance(teamId: string): Promise<TeamBalanceRow | null>;
62
63
  /** Add a member to a team with an optional spend cap. */
@@ -1 +1 @@
1
- {"version":3,"file":"team.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/team.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAgBlE,Q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;IAEtC,iDAAiD;IAC3C,UAAU,CACd,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,MAAM,EACtB,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC,aAAa,CAAC;IAczB,wFAAwF;IAClF,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC;IAQpE,yDAAyD;IACnD,aAAa,CACjB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,MAAM,GAAG,IAAI,GACtB,OAAO,CAAC,gBAAgB,CAAC;IAiB5B,mEAAmE;IAC7D,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC;IAO9D,4EAA4E;IACtE,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IASxE,gEAAgE;IAC1D,UAAU,CACd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,MAAM,EACtB,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,gBAAgB,CAAC;CAoC7B"}
@@ -1,7 +1,8 @@
1
1
  import { z } from "zod";
2
- import Decimal from "decimal.js";
2
+ import { Decimal } from "decimal.js";
3
3
  import { optionalRecordRow, postgresUuid, requireRow, safeParse, } from "../../../shared/postgres-validation.js";
4
4
  import { StoreError } from "../../../errors.js";
5
+ import { quantizeMoney } from "../../../expr.js";
5
6
  const decimal = z.union([z.string().min(1), z.number().finite()]);
6
7
  const safeInteger = z
7
8
  .union([z.number().int(), z.string().regex(/^\d+$/)])
@@ -14,6 +15,7 @@ const CreateTeamRowSchema = z
14
15
  name: z.string().min(1).nullable(),
15
16
  team_subject_id: postgresUuid.nullable(),
16
17
  account_id: postgresUuid.nullable(),
18
+ idempotent: z.boolean(),
17
19
  error_code: z.string().min(1).nullable(),
18
20
  })
19
21
  .strict()
@@ -31,6 +33,12 @@ const CreateTeamRowSchema = z
31
33
  message: "failed team creation cannot expose identity fields",
32
34
  });
33
35
  }
36
+ if (row.error_code !== null && row.idempotent) {
37
+ context.addIssue({
38
+ code: "custom",
39
+ message: "failed team creation cannot be idempotent",
40
+ });
41
+ }
34
42
  });
35
43
  const TeamBalanceRowSchema = z
36
44
  .object({
@@ -103,8 +111,13 @@ export class TeamRepository {
103
111
  this.callproc = callproc;
104
112
  }
105
113
  /** Create a new team with an initial balance. */
106
- async createTeam(ownerSubjectId, name, initialBalance) {
107
- const rows = await this.callproc("create_team", [ownerSubjectId, name, initialBalance]);
114
+ async createTeam(ownerSubjectId, name, idempotencyKey, initialBalance) {
115
+ const rows = await this.callproc("create_team", [
116
+ ownerSubjectId,
117
+ name,
118
+ idempotencyKey,
119
+ initialBalance,
120
+ ]);
108
121
  return safeParse(CreateTeamRowSchema, requireRow(rows, "TeamRepository.createTeam"), "TeamRepository.createTeam");
109
122
  }
110
123
  /** Fetch a team's balance and member count. Returns null if the team does not exist. */
@@ -145,7 +158,8 @@ export class TeamRepository {
145
158
  metadata,
146
159
  ]);
147
160
  const row = safeParse(TeamDeductionRpcRowSchema, requireRow(rows, "TeamRepository.deductTeam"), "TeamRepository.deductTeam");
148
- if (row.error_code === null && !new Decimal(row.amount).equals(amount)) {
161
+ if (row.error_code === null &&
162
+ !new Decimal(row.amount).equals(quantizeMoney(new Decimal(amount)))) {
149
163
  throw new StoreError("TeamRepository.deductTeam: committed amount differs from the request", {
150
164
  indeterminate: true,
151
165
  });
@@ -154,7 +168,7 @@ export class TeamRepository {
154
168
  entry_id: row.entry_id,
155
169
  team_id: row.team_id,
156
170
  user_id: row.subject_id,
157
- amount,
171
+ amount: row.error_code === null ? row.amount : amount,
158
172
  team_balance_after: row.balance_after,
159
173
  replayed: row.replayed,
160
174
  error: row.error_code,
@@ -1 +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AAS,CACnB,yBAAyB,EACzB,UAAU,CAAC,IAAI,EAAE,2BAA2B,CAAC,EAC7C,2BAA2B,CAC5B,CAAC;QACF,IAAI,GAAG,CAAC,UAAU,KAAK,IAAI,IAAI,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;YACvE,MAAM,IAAI,UAAU,CAAC,sEAAsE,EAAE;gBAC3F,aAAa,EAAE,IAAI;aACpB,CAAC,CAAC;QACL,CAAC;QACD,OAAO,SAAS,CACd,sBAAsB,EACtB;YACE,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,OAAO,EAAE,GAAG,CAAC,UAAU;YACvB,MAAM;YACN,kBAAkB,EAAE,GAAG,CAAC,aAAa;YACrC,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,KAAK,EAAE,GAAG,CAAC,UAAU;SACtB,EACD,2BAA2B,CAC5B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport Decimal from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\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 teamRole = z.enum([\"owner\", \"admin\", \"member\"]);\n\nconst CreateTeamRowSchema = z\n .object({\n team_id: postgresUuid.nullable(),\n name: z.string().min(1).nullable(),\n team_subject_id: postgresUuid.nullable(),\n account_id: postgresUuid.nullable(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n const identifiers = [row.team_id, row.name, row.team_subject_id, row.account_id];\n if (row.error_code === null && identifiers.some((value) => value === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team creation requires identity fields\",\n });\n }\n if (row.error_code !== null && identifiers.some((value) => value !== null)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team creation cannot expose identity fields\",\n });\n }\n });\n\nconst TeamBalanceRowSchema = z\n .object({\n team_id: postgresUuid,\n name: z.string().min(1),\n balance: decimal,\n member_count: safeInteger,\n })\n .strict();\n\nconst AddTeamMemberRowSchema = z\n .object({\n team_id: postgresUuid,\n user_id: postgresUuid,\n role: teamRole,\n })\n .strict();\n\nconst TeamMemberRowSchema = z\n .object({\n user_id: postgresUuid,\n role: teamRole,\n spend_cap: decimal.nullable(),\n total_spent: decimal,\n })\n .strict();\n\nconst TeamDeductionRpcRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n subject_id: postgresUuid,\n amount: decimal,\n balance_after: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict();\n\nconst TeamDeductionRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n user_id: postgresUuid,\n amount: decimal,\n team_balance_after: decimal.nullable(),\n error: z.string().min(1).nullable(),\n replayed: z.boolean(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error === null && (row.entry_id == null || row.team_balance_after === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team deductions require entry and balance fields\",\n });\n }\n if (row.error !== null && (row.entry_id !== null || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team deductions cannot be replayed or committed\",\n });\n }\n });\n\nexport type CreateTeamRow = z.infer<typeof CreateTeamRowSchema>;\nexport type TeamBalanceRow = z.infer<typeof TeamBalanceRowSchema>;\nexport type AddTeamMemberRow = z.infer<typeof AddTeamMemberRowSchema>;\nexport type TeamMemberRow = z.infer<typeof TeamMemberRowSchema>;\nexport type TeamDeductionRow = z.infer<typeof TeamDeductionRowSchema>;\n\n/** Repository for team credit operations.\n *\n * All methods call Postgres RPCs via the callproc function.\n * Returns None when the RPC returns no rows.\n * Returns typed models for successful results.\n */\nexport class TeamRepository {\n constructor(private callproc: CallProc) {}\n\n /** Create a new team with an initial balance. */\n async createTeam(\n ownerSubjectId: string,\n name: string,\n initialBalance: string,\n ): Promise<CreateTeamRow> {\n const rows = await this.callproc(\"create_team\", [ownerSubjectId, name, initialBalance]);\n return safeParse(\n CreateTeamRowSchema,\n requireRow(rows, \"TeamRepository.createTeam\"),\n \"TeamRepository.createTeam\",\n );\n }\n\n /** Fetch a team's balance and member count. Returns null if the team does not exist. */\n async getTeamBalance(teamId: string): Promise<TeamBalanceRow | null> {\n const rows = await this.callproc(\"get_team_balance\", [teamId]);\n const row = optionalRecordRow(rows, \"TeamRepository.getTeamBalance\");\n return row === null\n ? null\n : safeParse(TeamBalanceRowSchema, row, \"TeamRepository.getTeamBalance\");\n }\n\n /** Add a member to a team with an optional spend cap. */\n async addTeamMember(\n teamId: string,\n userId: string,\n role: string,\n spendCap: string | null,\n ): Promise<AddTeamMemberRow> {\n const rows = await this.callproc(\"set_team_member\", [teamId, userId, role, spendCap]);\n const added = safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.addTeamMember\"),\n \"TeamRepository.addTeamMember\",\n );\n if (!added) {\n throw new StoreError(\"TeamRepository.addTeamMember: set_team_member returned false\");\n }\n return safeParse(\n AddTeamMemberRowSchema,\n { team_id: teamId, user_id: userId, role },\n \"TeamRepository.addTeamMember\",\n );\n }\n\n /** List all members of a team with their spend caps and totals. */\n async getTeamMembers(teamId: string): Promise<TeamMemberRow[]> {\n const rows = await this.callproc(\"list_team_members\", [teamId]);\n return (rows ?? []).map((r) =>\n safeParse(TeamMemberRowSchema, r, \"TeamRepository.getTeamMembers\"),\n );\n }\n\n /** Remove a team member, returning false when absent or the final owner. */\n async removeTeamMember(teamId: string, userId: string): Promise<boolean> {\n const rows = await this.callproc(\"remove_team_member\", [teamId, userId]);\n return safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.removeTeamMember\"),\n \"TeamRepository.removeTeamMember\",\n );\n }\n\n /** Deduct credits from a team's balance on behalf of a user. */\n async deductTeam(\n teamId: string,\n userId: string,\n amount: string,\n idempotencyKey: string,\n operation: string,\n metadata: string,\n ): Promise<TeamDeductionRow> {\n const rows = await this.callproc(\"deduct_team\", [\n teamId,\n userId,\n amount,\n idempotencyKey,\n operation,\n metadata,\n ]);\n const row = safeParse(\n TeamDeductionRpcRowSchema,\n requireRow(rows, \"TeamRepository.deductTeam\"),\n \"TeamRepository.deductTeam\",\n );\n if (row.error_code === null && !new Decimal(row.amount).equals(amount)) {\n throw new StoreError(\"TeamRepository.deductTeam: committed amount differs from the request\", {\n indeterminate: true,\n });\n }\n return safeParse(\n TeamDeductionRowSchema,\n {\n entry_id: row.entry_id,\n team_id: row.team_id,\n user_id: row.subject_id,\n amount,\n team_balance_after: row.balance_after,\n replayed: row.replayed,\n error: row.error_code,\n },\n \"TeamRepository.deductTeam\",\n );\n }\n}\n"]}
1
+ {"version":3,"file":"team.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/team.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,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,WAAW,GAAG,CAAC;KAClB,KAAK,CAAC,CAAC,CAAC,CAAC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AAC,sEAAsE,EAAE;gBAC3F,aAAa,EAAE,IAAI;aACpB,CAAC,CAAC;QACL,CAAC;QACD,OAAO,SAAS,CACd,sBAAsB,EACtB;YACE,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,OAAO,EAAE,GAAG,CAAC,UAAU;YACvB,MAAM,EAAE,GAAG,CAAC,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM;YACrD,kBAAkB,EAAE,GAAG,CAAC,aAAa;YACrC,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,KAAK,EAAE,GAAG,CAAC,UAAU;SACtB,EACD,2BAA2B,CAC5B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { Decimal } from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.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 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 teamRole = z.enum([\"owner\", \"admin\", \"member\"]);\n\nconst CreateTeamRowSchema = z\n .object({\n team_id: postgresUuid.nullable(),\n name: z.string().min(1).nullable(),\n team_subject_id: postgresUuid.nullable(),\n account_id: postgresUuid.nullable(),\n idempotent: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n const identifiers = [row.team_id, row.name, row.team_subject_id, row.account_id];\n if (row.error_code === null && identifiers.some((value) => value === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team creation requires identity fields\",\n });\n }\n if (row.error_code !== null && identifiers.some((value) => value !== null)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team creation cannot expose identity fields\",\n });\n }\n if (row.error_code !== null && row.idempotent) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team creation cannot be idempotent\",\n });\n }\n });\n\nconst TeamBalanceRowSchema = z\n .object({\n team_id: postgresUuid,\n name: z.string().min(1),\n balance: decimal,\n member_count: safeInteger,\n })\n .strict();\n\nconst AddTeamMemberRowSchema = z\n .object({\n team_id: postgresUuid,\n user_id: postgresUuid,\n role: teamRole,\n })\n .strict();\n\nconst TeamMemberRowSchema = z\n .object({\n user_id: postgresUuid,\n role: teamRole,\n spend_cap: decimal.nullable(),\n total_spent: decimal,\n })\n .strict();\n\nconst TeamDeductionRpcRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n subject_id: postgresUuid,\n amount: decimal,\n balance_after: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict();\n\nconst TeamDeductionRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n user_id: postgresUuid,\n amount: decimal,\n team_balance_after: decimal.nullable(),\n error: z.string().min(1).nullable(),\n replayed: z.boolean(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error === null && (row.entry_id == null || row.team_balance_after === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team deductions require entry and balance fields\",\n });\n }\n if (row.error !== null && (row.entry_id !== null || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team deductions cannot be replayed or committed\",\n });\n }\n });\n\nexport type CreateTeamRow = z.infer<typeof CreateTeamRowSchema>;\nexport type TeamBalanceRow = z.infer<typeof TeamBalanceRowSchema>;\nexport type AddTeamMemberRow = z.infer<typeof AddTeamMemberRowSchema>;\nexport type TeamMemberRow = z.infer<typeof TeamMemberRowSchema>;\nexport type TeamDeductionRow = z.infer<typeof TeamDeductionRowSchema>;\n\n/** Repository for team credit operations.\n *\n * All methods call Postgres RPCs via the callproc function.\n * Returns None when the RPC returns no rows.\n * Returns typed models for successful results.\n */\nexport class TeamRepository {\n constructor(private callproc: CallProc) {}\n\n /** Create a new team with an initial balance. */\n async createTeam(\n ownerSubjectId: string,\n name: string,\n idempotencyKey: string,\n initialBalance: string,\n ): Promise<CreateTeamRow> {\n const rows = await this.callproc(\"create_team\", [\n ownerSubjectId,\n name,\n idempotencyKey,\n initialBalance,\n ]);\n return safeParse(\n CreateTeamRowSchema,\n requireRow(rows, \"TeamRepository.createTeam\"),\n \"TeamRepository.createTeam\",\n );\n }\n\n /** Fetch a team's balance and member count. Returns null if the team does not exist. */\n async getTeamBalance(teamId: string): Promise<TeamBalanceRow | null> {\n const rows = await this.callproc(\"get_team_balance\", [teamId]);\n const row = optionalRecordRow(rows, \"TeamRepository.getTeamBalance\");\n return row === null\n ? null\n : safeParse(TeamBalanceRowSchema, row, \"TeamRepository.getTeamBalance\");\n }\n\n /** Add a member to a team with an optional spend cap. */\n async addTeamMember(\n teamId: string,\n userId: string,\n role: string,\n spendCap: string | null,\n ): Promise<AddTeamMemberRow> {\n const rows = await this.callproc(\"set_team_member\", [teamId, userId, role, spendCap]);\n const added = safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.addTeamMember\"),\n \"TeamRepository.addTeamMember\",\n );\n if (!added) {\n throw new StoreError(\"TeamRepository.addTeamMember: set_team_member returned false\");\n }\n return safeParse(\n AddTeamMemberRowSchema,\n { team_id: teamId, user_id: userId, role },\n \"TeamRepository.addTeamMember\",\n );\n }\n\n /** List all members of a team with their spend caps and totals. */\n async getTeamMembers(teamId: string): Promise<TeamMemberRow[]> {\n const rows = await this.callproc(\"list_team_members\", [teamId]);\n return (rows ?? []).map((r) =>\n safeParse(TeamMemberRowSchema, r, \"TeamRepository.getTeamMembers\"),\n );\n }\n\n /** Remove a team member, returning false when absent or the final owner. */\n async removeTeamMember(teamId: string, userId: string): Promise<boolean> {\n const rows = await this.callproc(\"remove_team_member\", [teamId, userId]);\n return safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.removeTeamMember\"),\n \"TeamRepository.removeTeamMember\",\n );\n }\n\n /** Deduct credits from a team's balance on behalf of a user. */\n async deductTeam(\n teamId: string,\n userId: string,\n amount: string,\n idempotencyKey: string,\n operation: string,\n metadata: string,\n ): Promise<TeamDeductionRow> {\n const rows = await this.callproc(\"deduct_team\", [\n teamId,\n userId,\n amount,\n idempotencyKey,\n operation,\n metadata,\n ]);\n const row = safeParse(\n TeamDeductionRpcRowSchema,\n requireRow(rows, \"TeamRepository.deductTeam\"),\n \"TeamRepository.deductTeam\",\n );\n if (\n row.error_code === null &&\n !new Decimal(row.amount).equals(quantizeMoney(new Decimal(amount)))\n ) {\n throw new StoreError(\"TeamRepository.deductTeam: committed amount differs from the request\", {\n indeterminate: true,\n });\n }\n return safeParse(\n TeamDeductionRowSchema,\n {\n entry_id: row.entry_id,\n team_id: row.team_id,\n user_id: row.subject_id,\n amount: row.error_code === null ? row.amount : amount,\n team_balance_after: row.balance_after,\n replayed: row.replayed,\n error: row.error_code,\n },\n \"TeamRepository.deductTeam\",\n );\n }\n}\n"]}
@@ -1,9 +1,10 @@
1
- import Decimal from "decimal.js";
2
- import { type CatalogRollout } from "../../config.js";
1
+ import { Decimal } from "decimal.js";
2
+ import { type BursarConfigData, type CatalogRollout } from "../../config.js";
3
3
  import { type PostgresConnectionOptions, type PostgresPool, type PostgresPoolConstructor } from "../../shared/postgres-client.js";
4
- import type { AddCreditsResult, AddTeamMemberResult, AggregateStats, AllowanceResult, AvailableResult, BalanceResult, CheckFeatureResult, CreateTeamResult, CreditMetadata, DailySpendRow, DeductionResult, DeductWithAllowanceOptions, ExecuteGrantProgramRequest, GrantProgramAwardResult, GetUserPlanResult, LeaseResult, LeasePricingContext, ListLedgerEntriesOptions, ListUsageChargesOptions, ListQuotaEventsOptions, ListUsageEntriesOptions, PlanMigrationBatchResult, PlanMigrationStartResult, QuotaEvent, QuotaState, LedgerPage, UsageChargePage, UsageRecordResult, CatalogRevisionSummary, CatalogRevision, RefundResult, RevokeCreditsResult, ReleaseResult, SetUserPlanResult, SpendByModelRow, SpendByUserRow, SweepResult, TeamBalanceResult, TeamDeductionResult, TeamMember, TeamRole, BucketBalancesResult, TopUserRow, UnsetUserPlanResult, LedgerEntry } from "../types/index.js";
4
+ import type { AddCreditsResult, AddTeamMemberResult, AggregateStats, AllowanceResult, AvailableResult, BalanceResult, CheckFeatureResult, CreateTeamResult, DailySpendRow, DeductionResult, DeductWithAllowanceOptions, ExecuteGrantProgramRequest, GrantProgramAwardResult, GetUserPlanResult, LeaseResult, LeasePricingContext, ListLedgerEntriesOptions, ListUsageChargesOptions, ListQuotaEventsOptions, ListUsageEntriesOptions, PlanMigrationBatchResult, PlanMigrationStartResult, QuotaEvent, QuotaState, LedgerPage, UsageChargePage, UsageRecordResult, CatalogRevisionSummary, CatalogRevision, RefundResult, RevokeCreditsResult, ReleaseResult, SetUserPlanResult, SpendByModelRow, SpendByUserRow, SweepResult, TeamBalanceResult, TeamDeductionResult, TeamMember, TeamRole, BucketBalancesResult, TopUserRow, UnsetUserPlanResult, LedgerEntry } from "../types/index.js";
5
+ import type { AddCreditsOptions, DeductTeamOptions, RefundCreditsOptions } from "../service-types.js";
5
6
  import { CreditStore } from "../store.js";
6
- import type { CreateLeaseOptions, SettleLeaseOptions } from "../store.js";
7
+ import type { CreateLeaseOptions, CreateTeamOptions, SettleLeaseOptions } from "../store.js";
7
8
  export type PgPool = PostgresPool;
8
9
  export type PgPoolConstructor = PostgresPoolConstructor;
9
10
  /** Construction options for the PostgreSQL credit store. */
@@ -12,11 +13,14 @@ export interface PostgresStoreOptions extends PostgresConnectionOptions {
12
13
  postgres: string | PgPool;
13
14
  /** Tenant UUID bound to every store transaction. */
14
15
  tenantId: string;
16
+ /** Explicit financial namespace for catalog provider references. */
17
+ providerEnvironment: NonNullable<PostgresConnectionOptions["providerEnvironment"]>;
15
18
  /** Injectable `pg.Pool` constructor for custom runtimes and tests. */
16
19
  poolConstructor?: PgPoolConstructor;
17
20
  usageBackend?: "postgres" | "clickhouse";
18
21
  }
19
22
  export declare class PostgresStore extends CreditStore {
23
+ readonly providerEnvironment: NonNullable<PostgresConnectionOptions["providerEnvironment"]>;
20
24
  private readonly postgres;
21
25
  private _balanceRepo;
22
26
  private _deductionRepo;
@@ -41,10 +45,10 @@ export declare class PostgresStore extends CreditStore {
41
45
  private static readonly SCALAR_RPC_NAMES;
42
46
  private callproc;
43
47
  getBalance(userId: string): Promise<BalanceResult>;
44
- addCredits(userId: string, amount: Decimal, type?: string, metadata?: CreditMetadata | null, expiresAt?: Date | null, bucket?: string | null, idempotencyKey?: string | null): Promise<AddCreditsResult>;
45
- deductWithAllowance(userId: string, amount: Decimal, options?: DeductWithAllowanceOptions): Promise<DeductionResult>;
46
- recordUsage(userId: string, operation: string, amount: Decimal, options?: DeductWithAllowanceOptions): Promise<UsageRecordResult>;
47
- createLease(userId: string, amount: Decimal, operationType: string, options?: CreateLeaseOptions): Promise<LeaseResult>;
48
+ addCredits(userId: string, amount: Decimal, options: AddCreditsOptions): Promise<AddCreditsResult>;
49
+ deductWithAllowance(userId: string, amount: Decimal, options: DeductWithAllowanceOptions): Promise<DeductionResult>;
50
+ recordUsage(userId: string, operation: string, amount: Decimal, options: DeductWithAllowanceOptions): Promise<UsageRecordResult>;
51
+ createLease(userId: string, amount: Decimal, operationType: string, options: CreateLeaseOptions): Promise<LeaseResult>;
48
52
  settleLease(userId: string, leaseId: string, amount: Decimal, options?: SettleLeaseOptions): Promise<DeductionResult>;
49
53
  getLeasePricingContext(userId: string, leaseId: string): Promise<LeasePricingContext | null>;
50
54
  releaseLease(userId: string, leaseId: string): Promise<ReleaseResult>;
@@ -53,11 +57,11 @@ export declare class PostgresStore extends CreditStore {
53
57
  getAvailable(userId: string): Promise<AvailableResult>;
54
58
  getActiveCatalog(): Promise<CatalogRevision | null>;
55
59
  private loadActiveCatalog;
56
- publishAndActivateCatalog(config: Record<string, unknown>, label?: string | null, rollout?: CatalogRollout | Record<string, unknown> | null): Promise<string>;
57
- publishCatalogDraft(config: Record<string, unknown>, label?: string | null): Promise<string>;
60
+ publishAndActivateCatalog(config: BursarConfigData, label?: string | null, rollout?: CatalogRollout | null): Promise<string>;
61
+ publishCatalogDraft(config: BursarConfigData, label?: string | null): Promise<string>;
58
62
  getCatalogHistory(): Promise<CatalogRevisionSummary[]>;
59
63
  getCatalogRevision(version: number): Promise<CatalogRevision | null>;
60
- activateCatalogRevision(version: number, rollout?: CatalogRollout | Record<string, unknown> | null): Promise<string>;
64
+ activateCatalogRevision(version: number, rollout?: CatalogRollout | null): Promise<string>;
61
65
  getUserPlan(userId: string): Promise<GetUserPlanResult>;
62
66
  checkFeature(userId: string, feature: string): Promise<CheckFeatureResult>;
63
67
  setUserPlan(userId: string, planKey: string, planAssignedAt?: Date | null): Promise<SetUserPlanResult>;
@@ -70,7 +74,7 @@ export declare class PostgresStore extends CreditStore {
70
74
  listQuotaEvents(userId: string, options?: ListQuotaEventsOptions): Promise<QuotaEvent[]>;
71
75
  checkAllowance(userId: string): Promise<AllowanceResult | null>;
72
76
  revokeCreditsByEntryType(userId: string, entryType: string): Promise<RevokeCreditsResult>;
73
- refundCredits(entryId: string, amount?: Decimal, reason?: string, metadata?: CreditMetadata | null, idempotencyKey?: string | null): Promise<RefundResult>;
77
+ refundCredits(entryId: string, options: RefundCreditsOptions): Promise<RefundResult>;
74
78
  aggregateStats(start: Date, end: Date): Promise<AggregateStats>;
75
79
  spendByUser(start: Date, end: Date): Promise<SpendByUserRow[]>;
76
80
  spendByModel(start: Date, end: Date): Promise<SpendByModelRow[]>;
@@ -81,12 +85,12 @@ export declare class PostgresStore extends CreditStore {
81
85
  listLedgerEntries(userId: string, options?: ListLedgerEntriesOptions): Promise<LedgerPage>;
82
86
  listUsageEntries(userId: string, options?: ListUsageEntriesOptions): Promise<LedgerPage>;
83
87
  listUsageCharges(userId: string, options?: ListUsageChargesOptions): Promise<UsageChargePage>;
84
- createTeam(ownerSubjectId: string, name: string, initialBalance?: Decimal): Promise<CreateTeamResult>;
88
+ createTeam(ownerSubjectId: string, name: string, options: CreateTeamOptions): Promise<CreateTeamResult>;
85
89
  getTeamBalance(teamId: string): Promise<TeamBalanceResult | null>;
86
90
  addTeamMember(teamId: string, userId: string, role?: TeamRole, spendCap?: Decimal | null): Promise<AddTeamMemberResult>;
87
91
  getTeamMembers(teamId: string): Promise<TeamMember[]>;
88
92
  removeTeamMember(teamId: string, userId: string): Promise<boolean>;
89
- deductTeam(teamId: string, userId: string, amount: Decimal, metadata?: CreditMetadata | null, idempotencyKey?: string | null): Promise<TeamDeductionResult>;
93
+ deductTeam(teamId: string, userId: string, amount: Decimal, options: DeductTeamOptions): Promise<TeamDeductionResult>;
90
94
  sweepExpiredCredits(dryRun?: boolean, userId?: string, limit?: number): Promise<SweepResult>;
91
95
  getBucketBalances(userId: string): Promise<BucketBalancesResult>;
92
96
  executeGrantProgram(request: ExecuteGrantProgramRequest): Promise<GrantProgramAwardResult[]>;
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/credits/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AAGjC,OAAO,EAML,KAAK,cAAc,EACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAEL,KAAK,yBAAyB,EAC9B,KAAK,YAAY,EACjB,KAAK,uBAAuB,EAC7B,MAAM,iCAAiC,CAAC;AACzC,OAAO,KAAK,EACV,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,eAAe,EACf,aAAa,EACb,kBAAkB,EAClB,gBAAgB,EAChB,cAAc,EACd,aAAa,EACb,eAAe,EACf,0BAA0B,EAC1B,0BAA0B,EAC1B,uBAAuB,EACvB,iBAAiB,EACjB,WAAW,EACX,mBAAmB,EACnB,wBAAwB,EACxB,uBAAuB,EACvB,sBAAsB,EACtB,uBAAuB,EACvB,wBAAwB,EACxB,wBAAwB,EACxB,UAAU,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M,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,IAAI,GAAE,QAAmB,EACzB,QAAQ,CAAC,EAAE,OAAO,GAAG,IAAI,GACxB,OAAO,CAAC,mBAAmB,CAAC;IAczB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC;IAUrD,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAIlE,UAAU,CACd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,OAAO,EACf,OAAO,EAAE,iBAAiB,GACzB,OAAO,CAAC,mBAAmB,CAAC;IAsCzB,mBAAmB,CAAC,MAAM,UAAQ,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,KAAK,SAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IAYvF,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAYhE,mBAAmB,CACvB,OAAO,EAAE,0BAA0B,GAClC,OAAO,CAAC,uBAAuB,EAAE,CAAC;CAiCtC"}
@@ -1,8 +1,8 @@
1
- import Decimal from "decimal.js";
2
- import { randomUUID } from "node:crypto";
1
+ import { Decimal } from "decimal.js";
3
2
  import { StoreClosedError, StoreError } from "../../errors.js";
4
3
  import { canonicalBursarConfigDict, canonicalCatalogRolloutDict, loadCatalogRollout, loadConfigFromDict, validateCatalogRollout, } from "../../config.js";
5
4
  import { PostgresClient, } from "../../shared/postgres-client.js";
5
+ import { requireStableKey } from "../../shared/idempotency.js";
6
6
  import { CreditStore } from "../store.js";
7
7
  import { BalanceRepository } from "./repositories/balance.js";
8
8
  import { DeductionRepository } from "./repositories/deduction.js";
@@ -23,6 +23,7 @@ function requireText(value, context) {
23
23
  return value;
24
24
  }
25
25
  export class PostgresStore extends CreditStore {
26
+ providerEnvironment;
26
27
  postgres;
27
28
  _balanceRepo = null;
28
29
  _deductionRepo = null;
@@ -88,8 +89,10 @@ export class PostgresStore extends CreditStore {
88
89
  if (typeof options.postgres !== "string" && options.poolConstructor !== undefined) {
89
90
  throw new TypeError("poolConstructor cannot be used with an existing PostgreSQL pool");
90
91
  }
92
+ this.providerEnvironment = options.providerEnvironment;
91
93
  this.postgres = new PostgresClient(options.postgres, {
92
94
  tenantId: options.tenantId,
95
+ providerEnvironment: options.providerEnvironment,
93
96
  usageBackend: options.usageBackend,
94
97
  poolConstructor: options.poolConstructor,
95
98
  connectionTimeoutMs: options.connectionTimeoutMs,
@@ -145,12 +148,13 @@ export class PostgresStore extends CreditStore {
145
148
  lifetimePurchased: dec(row.lifetime_purchased),
146
149
  };
147
150
  }
148
- async addCredits(userId, amount, type = "adjustment", metadata, expiresAt, bucket, idempotencyKey) {
149
- const meta = { ...(metadata ?? {}) };
150
- if (expiresAt) {
151
- meta.expires_at = expiresAt instanceof Date ? expiresAt.toISOString() : String(expiresAt);
151
+ async addCredits(userId, amount, options) {
152
+ const stableKey = requireStableKey(options?.idempotencyKey);
153
+ const meta = { ...(options?.metadata ?? {}) };
154
+ if (options?.expiresAt) {
155
+ meta.expires_at = options.expiresAt.toISOString();
152
156
  }
153
- const row = await this.balanceRepo.addCredits(userId, decParam(amount), type, JSON.stringify(meta), expiresAt ? expiresAt.toISOString() : null, bucket ?? null, idempotencyKey ?? `credit:${randomUUID()}`);
157
+ const row = await this.balanceRepo.addCredits(userId, decParam(amount), options?.type ?? "adjustment", JSON.stringify(meta), options?.expiresAt?.toISOString() ?? null, options?.bucket ?? null, stableKey);
154
158
  if (row.error !== null) {
155
159
  throw new StoreError(`post_credit: ${row.error}`);
156
160
  }
@@ -165,7 +169,7 @@ export class PostgresStore extends CreditStore {
165
169
  };
166
170
  }
167
171
  async deductWithAllowance(userId, amount, options) {
168
- const idempotencyKey = options?.idempotencyKey ?? `usage:${randomUUID()}`;
172
+ const idempotencyKey = requireStableKey(options?.idempotencyKey);
169
173
  const operation = options?.operation ??
170
174
  (typeof options?.metadata?.operation === "string" ? options.metadata.operation : "usage");
171
175
  const model = options?.model ?? null;
@@ -212,7 +216,7 @@ export class PostgresStore extends CreditStore {
212
216
  };
213
217
  }
214
218
  async recordUsage(userId, operation, amount, options) {
215
- const idempotencyKey = options?.idempotencyKey ?? `usage-record:${randomUUID()}`;
219
+ const idempotencyKey = requireStableKey(options?.idempotencyKey);
216
220
  const row = await this.deductionRepo.recordUsage({
217
221
  userId,
218
222
  operation,
@@ -243,11 +247,12 @@ export class PostgresStore extends CreditStore {
243
247
  };
244
248
  }
245
249
  async createLease(userId, amount, operationType, options) {
250
+ const idempotencyKey = requireStableKey(options?.idempotencyKey);
246
251
  const row = await this.leaseRepo.createLease({
247
252
  userId,
248
253
  amount: decParam(amount),
249
254
  operationType,
250
- idempotencyKey: options?.idempotencyKey ?? `lease:${randomUUID()}`,
255
+ idempotencyKey,
251
256
  ttlSeconds: options?.ttlSeconds ?? DEFAULT_LEASE_TTL_SECONDS,
252
257
  metadata: JSON.stringify(options?.metadata ?? {}),
253
258
  feature: options?.feature ?? null,
@@ -283,11 +288,14 @@ export class PostgresStore extends CreditStore {
283
288
  };
284
289
  }
285
290
  async settleLease(userId, leaseId, amount, options) {
291
+ const idempotencyKey = options?.idempotencyKey === undefined
292
+ ? `lease:${leaseId}:settle`
293
+ : requireStableKey(options.idempotencyKey);
286
294
  const row = await this.leaseRepo.settleLease({
287
295
  userId,
288
296
  leaseId,
289
297
  amount: decParam(amount),
290
- idempotencyKey: options?.idempotencyKey ?? `lease:${leaseId}:settle`,
298
+ idempotencyKey,
291
299
  feature: options?.feature ?? null,
292
300
  model: options?.model ?? null,
293
301
  region: options?.region ?? null,
@@ -617,8 +625,9 @@ export class PostgresStore extends CreditStore {
617
625
  balanceAfter: dec(row.balance_after),
618
626
  };
619
627
  }
620
- async refundCredits(entryId, amount, reason, metadata, idempotencyKey) {
621
- const row = await this.deductionRepo.refundCredits(entryId, amount != null ? decParam(amount) : null, idempotencyKey ?? `refund:${entryId}:${amount != null ? decParam(amount) : "remaining"}`, reason ?? null, JSON.stringify(metadata ?? {}));
628
+ async refundCredits(entryId, options) {
629
+ const stableKey = requireStableKey(options?.idempotencyKey);
630
+ const row = await this.deductionRepo.refundCredits(entryId, options?.amount != null ? decParam(new Decimal(options.amount)) : null, stableKey, options?.reason ?? null, JSON.stringify(options?.metadata ?? {}));
622
631
  if (row.error !== null) {
623
632
  return {
624
633
  refundEntryId: null,
@@ -729,13 +738,16 @@ export class PostgresStore extends CreditStore {
729
738
  nextCursor: hasMore && last ? { eventAt: last.eventAt, usageId: last.usageId } : null,
730
739
  };
731
740
  }
732
- async createTeam(ownerSubjectId, name, initialBalance = ZERO) {
733
- const row = await this.teamRepo.createTeam(ownerSubjectId, name, decParam(initialBalance));
741
+ async createTeam(ownerSubjectId, name, options) {
742
+ const idempotencyKey = requireStableKey(options?.idempotencyKey);
743
+ const initialBalance = options?.initialBalance ?? ZERO;
744
+ const row = await this.teamRepo.createTeam(ownerSubjectId, name, idempotencyKey, decParam(initialBalance));
734
745
  if (row.error_code !== null)
735
746
  throw new StoreError(row.error_code);
736
747
  return {
737
748
  teamId: requireText(row.team_id, "create_team"),
738
749
  name: requireText(row.name, "create_team"),
750
+ idempotent: row.idempotent,
739
751
  };
740
752
  }
741
753
  async getTeamBalance(teamId) {
@@ -769,9 +781,9 @@ export class PostgresStore extends CreditStore {
769
781
  async removeTeamMember(teamId, userId) {
770
782
  return this.teamRepo.removeTeamMember(teamId, userId);
771
783
  }
772
- async deductTeam(teamId, userId, amount, metadata, idempotencyKey) {
773
- const meta = { ...(metadata ?? {}) };
774
- const effectiveIdempotencyKey = idempotencyKey ?? `team-usage:${randomUUID()}`;
784
+ async deductTeam(teamId, userId, amount, options) {
785
+ const meta = { ...(options?.metadata ?? {}) };
786
+ const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
775
787
  meta.idempotency_key = effectiveIdempotencyKey;
776
788
  const operation = typeof meta.operation === "string" && meta.operation.length > 0
777
789
  ? meta.operation