@zonastery/bursar 2.1.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (334) hide show
  1. package/README.md +20 -3
  2. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  3. package/dist/billing/auto-recharge-service.js +6 -4
  4. package/dist/billing/auto-recharge-service.js.map +1 -1
  5. package/dist/billing/billing-service.d.ts +19 -3
  6. package/dist/billing/billing-service.d.ts.map +1 -1
  7. package/dist/billing/billing-service.js +34 -5
  8. package/dist/billing/billing-service.js.map +1 -1
  9. package/dist/billing/billing-store.d.ts +12 -6
  10. package/dist/billing/billing-store.d.ts.map +1 -1
  11. package/dist/billing/billing-store.js +2 -0
  12. package/dist/billing/billing-store.js.map +1 -1
  13. package/dist/billing/contracts.d.ts +20 -3
  14. package/dist/billing/contracts.d.ts.map +1 -1
  15. package/dist/billing/contracts.js.map +1 -1
  16. package/dist/billing/event-handlers.d.ts +1 -0
  17. package/dist/billing/event-handlers.d.ts.map +1 -1
  18. package/dist/billing/event-handlers.js +40 -13
  19. package/dist/billing/event-handlers.js.map +1 -1
  20. package/dist/billing/event-processor.d.ts +2 -1
  21. package/dist/billing/event-processor.d.ts.map +1 -1
  22. package/dist/billing/event-processor.js +82 -16
  23. package/dist/billing/event-processor.js.map +1 -1
  24. package/dist/billing/financial-event-handlers.d.ts +2 -0
  25. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  26. package/dist/billing/financial-event-handlers.js +160 -48
  27. package/dist/billing/financial-event-handlers.js.map +1 -1
  28. package/dist/billing/index.d.ts +1 -1
  29. package/dist/billing/index.d.ts.map +1 -1
  30. package/dist/billing/index.js.map +1 -1
  31. package/dist/billing/management.d.ts +6 -3
  32. package/dist/billing/management.d.ts.map +1 -1
  33. package/dist/billing/management.js +5 -2
  34. package/dist/billing/management.js.map +1 -1
  35. package/dist/billing/postgres/repositories/auto-recharge.d.ts +3 -1
  36. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  37. package/dist/billing/postgres/repositories/auto-recharge.js +23 -7
  38. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  39. package/dist/billing/postgres/repositories/invoice.d.ts +3 -2
  40. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  41. package/dist/billing/postgres/repositories/invoice.js +33 -3
  42. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  43. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  44. package/dist/billing/postgres/repositories/offer.js +2 -1
  45. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  46. package/dist/billing/postgres/repositories/payment.d.ts +6 -1
  47. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  48. package/dist/billing/postgres/repositories/payment.js +25 -17
  49. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  50. package/dist/billing/postgres/repositories/subscription-change.d.ts +1 -0
  51. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -1
  52. package/dist/billing/postgres/repositories/subscription-change.js +24 -4
  53. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
  54. package/dist/billing/postgres/repositories/subscription.d.ts +1 -0
  55. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  56. package/dist/billing/postgres/repositories/subscription.js +40 -43
  57. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  58. package/dist/billing/postgres/repositories/topup.d.ts +6 -1
  59. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  60. package/dist/billing/postgres/repositories/topup.js +9 -5
  61. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  62. package/dist/billing/postgres/store.d.ts +24 -31
  63. package/dist/billing/postgres/store.d.ts.map +1 -1
  64. package/dist/billing/postgres/store.js +110 -113
  65. package/dist/billing/postgres/store.js.map +1 -1
  66. package/dist/billing/types/catalog.d.ts +1 -0
  67. package/dist/billing/types/catalog.d.ts.map +1 -1
  68. package/dist/billing/types/catalog.js.map +1 -1
  69. package/dist/billing/types/documents.d.ts +15 -1
  70. package/dist/billing/types/documents.d.ts.map +1 -1
  71. package/dist/billing/types/documents.js.map +1 -1
  72. package/dist/billing/types/events.d.ts +2 -0
  73. package/dist/billing/types/events.d.ts.map +1 -1
  74. package/dist/billing/types/events.js +15 -0
  75. package/dist/billing/types/events.js.map +1 -1
  76. package/dist/billing/types/subscriptions.d.ts +10 -0
  77. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  78. package/dist/billing/types/subscriptions.js.map +1 -1
  79. package/dist/breakdown.d.ts +2 -24
  80. package/dist/breakdown.d.ts.map +1 -1
  81. package/dist/breakdown.js +1 -29
  82. package/dist/breakdown.js.map +1 -1
  83. package/dist/bursar.d.ts +5 -17
  84. package/dist/bursar.d.ts.map +1 -1
  85. package/dist/bursar.js +26 -44
  86. package/dist/bursar.js.map +1 -1
  87. package/dist/cli.js +0 -6
  88. package/dist/cli.js.map +1 -1
  89. package/dist/commerce/service.d.ts +1 -0
  90. package/dist/commerce/service.d.ts.map +1 -1
  91. package/dist/commerce/service.js +162 -38
  92. package/dist/commerce/service.js.map +1 -1
  93. package/dist/commerce/types.d.ts +2 -0
  94. package/dist/commerce/types.d.ts.map +1 -1
  95. package/dist/commerce/types.js.map +1 -1
  96. package/dist/config/normalize.d.ts +3 -1
  97. package/dist/config/normalize.d.ts.map +1 -1
  98. package/dist/config/normalize.js +12 -5
  99. package/dist/config/normalize.js.map +1 -1
  100. package/dist/config/parse-access.d.ts.map +1 -1
  101. package/dist/config/parse-access.js +4 -1
  102. package/dist/config/parse-access.js.map +1 -1
  103. package/dist/config/parse-commerce.d.ts.map +1 -1
  104. package/dist/config/parse-commerce.js +32 -17
  105. package/dist/config/parse-commerce.js.map +1 -1
  106. package/dist/config/parse-credits.d.ts.map +1 -1
  107. package/dist/config/parse-credits.js +5 -5
  108. package/dist/config/parse-credits.js.map +1 -1
  109. package/dist/config/parse-plans.d.ts.map +1 -1
  110. package/dist/config/parse-plans.js +13 -9
  111. package/dist/config/parse-plans.js.map +1 -1
  112. package/dist/config/parse-pricing.d.ts.map +1 -1
  113. package/dist/config/parse-pricing.js +7 -5
  114. package/dist/config/parse-pricing.js.map +1 -1
  115. package/dist/config/parse-utils.d.ts +2 -0
  116. package/dist/config/parse-utils.d.ts.map +1 -1
  117. package/dist/config/parse-utils.js +11 -1
  118. package/dist/config/parse-utils.js.map +1 -1
  119. package/dist/config.d.ts +2 -2
  120. package/dist/config.d.ts.map +1 -1
  121. package/dist/config.js +94 -86
  122. package/dist/config.js.map +1 -1
  123. package/dist/credits/amount.d.ts.map +1 -1
  124. package/dist/credits/amount.js +5 -4
  125. package/dist/credits/amount.js.map +1 -1
  126. package/dist/credits/catalog-runtime.d.ts +15 -2
  127. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  128. package/dist/credits/catalog-runtime.js +74 -18
  129. package/dist/credits/catalog-runtime.js.map +1 -1
  130. package/dist/credits/lease-workflow.d.ts +3 -1
  131. package/dist/credits/lease-workflow.d.ts.map +1 -1
  132. package/dist/credits/lease-workflow.js +47 -38
  133. package/dist/credits/lease-workflow.js.map +1 -1
  134. package/dist/credits/low-balance-monitor.d.ts +2 -7
  135. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  136. package/dist/credits/low-balance-monitor.js +6 -57
  137. package/dist/credits/low-balance-monitor.js.map +1 -1
  138. package/dist/credits/postgres/repositories/analytics.d.ts +3 -3
  139. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  140. package/dist/credits/postgres/repositories/analytics.js +25 -7
  141. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  142. package/dist/credits/postgres/repositories/balance.d.ts +28 -0
  143. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  144. package/dist/credits/postgres/repositories/balance.js +33 -14
  145. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  146. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
  147. package/dist/credits/postgres/repositories/bucket.js +2 -2
  148. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  149. package/dist/credits/postgres/repositories/catalog.d.ts +2 -2
  150. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
  151. package/dist/credits/postgres/repositories/catalog.js +2 -12
  152. package/dist/credits/postgres/repositories/catalog.js.map +1 -1
  153. package/dist/credits/postgres/repositories/deduction.d.ts +2 -0
  154. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  155. package/dist/credits/postgres/repositories/deduction.js +9 -2
  156. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  157. package/dist/credits/postgres/repositories/lease.d.ts +3 -0
  158. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  159. package/dist/credits/postgres/repositories/lease.js +46 -12
  160. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  161. package/dist/credits/postgres/repositories/plan.d.ts +1 -1
  162. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
  163. package/dist/credits/postgres/repositories/plan.js +4 -1
  164. package/dist/credits/postgres/repositories/plan.js.map +1 -1
  165. package/dist/credits/postgres/repositories/team.d.ts +1 -1
  166. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  167. package/dist/credits/postgres/repositories/team.js +9 -5
  168. package/dist/credits/postgres/repositories/team.js.map +1 -1
  169. package/dist/credits/postgres/store.d.ts +29 -20
  170. package/dist/credits/postgres/store.d.ts.map +1 -1
  171. package/dist/credits/postgres/store.js +329 -250
  172. package/dist/credits/postgres/store.js.map +1 -1
  173. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  174. package/dist/credits/postgres/value-mappers.js +4 -4
  175. package/dist/credits/postgres/value-mappers.js.map +1 -1
  176. package/dist/credits/rated-wire.d.ts +7 -0
  177. package/dist/credits/rated-wire.d.ts.map +1 -0
  178. package/dist/credits/rated-wire.js +70 -0
  179. package/dist/credits/rated-wire.js.map +1 -0
  180. package/dist/credits/service-errors.d.ts.map +1 -1
  181. package/dist/credits/service-errors.js +8 -1
  182. package/dist/credits/service-errors.js.map +1 -1
  183. package/dist/credits/service-types.d.ts +5 -7
  184. package/dist/credits/service-types.d.ts.map +1 -1
  185. package/dist/credits/service-types.js.map +1 -1
  186. package/dist/credits/service.d.ts +11 -9
  187. package/dist/credits/service.d.ts.map +1 -1
  188. package/dist/credits/service.js +156 -138
  189. package/dist/credits/service.js.map +1 -1
  190. package/dist/credits/store.d.ts +11 -3
  191. package/dist/credits/store.d.ts.map +1 -1
  192. package/dist/credits/store.js +9 -0
  193. package/dist/credits/store.js.map +1 -1
  194. package/dist/credits/types/account.d.ts +9 -1
  195. package/dist/credits/types/account.d.ts.map +1 -1
  196. package/dist/credits/types/account.js.map +1 -1
  197. package/dist/credits/types/admission.d.ts +1 -0
  198. package/dist/credits/types/admission.d.ts.map +1 -1
  199. package/dist/credits/types/admission.js.map +1 -1
  200. package/dist/credits/types/grants.d.ts +12 -0
  201. package/dist/credits/types/grants.d.ts.map +1 -1
  202. package/dist/credits/types/grants.js.map +1 -1
  203. package/dist/credits/types/ledger.d.ts +13 -0
  204. package/dist/credits/types/ledger.d.ts.map +1 -1
  205. package/dist/credits/types/ledger.js.map +1 -1
  206. package/dist/credits/types/quotas.d.ts +2 -1
  207. package/dist/credits/types/quotas.d.ts.map +1 -1
  208. package/dist/credits/types/quotas.js.map +1 -1
  209. package/dist/engine.d.ts.map +1 -1
  210. package/dist/engine.js +51 -34
  211. package/dist/engine.js.map +1 -1
  212. package/dist/errors.d.ts +12 -1
  213. package/dist/errors.d.ts.map +1 -1
  214. package/dist/errors.js +13 -0
  215. package/dist/errors.js.map +1 -1
  216. package/dist/expr/evaluator.d.ts.map +1 -1
  217. package/dist/expr/evaluator.js +29 -9
  218. package/dist/expr/evaluator.js.map +1 -1
  219. package/dist/expr/language.js +1 -1
  220. package/dist/expr/language.js.map +1 -1
  221. package/dist/expr.d.ts.map +1 -1
  222. package/dist/expr.js +5 -6
  223. package/dist/expr.js.map +1 -1
  224. package/dist/generated/pricing-config.schema.json +102 -202
  225. package/dist/generated/pricing-config.types.d.ts +7 -1
  226. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  227. package/dist/generated/pricing-config.types.js.map +1 -1
  228. package/dist/index.d.ts +6 -5
  229. package/dist/index.d.ts.map +1 -1
  230. package/dist/index.js +3 -2
  231. package/dist/index.js.map +1 -1
  232. package/dist/load-config-file.d.ts.map +1 -1
  233. package/dist/load-config-file.js +38 -12
  234. package/dist/load-config-file.js.map +1 -1
  235. package/dist/metrics.d.ts +1 -1
  236. package/dist/metrics.d.ts.map +1 -1
  237. package/dist/metrics.js.map +1 -1
  238. package/dist/node.d.ts +1 -1
  239. package/dist/node.d.ts.map +1 -1
  240. package/dist/node.js.map +1 -1
  241. package/dist/pricing-decimal.d.ts +7 -0
  242. package/dist/pricing-decimal.d.ts.map +1 -0
  243. package/dist/pricing-decimal.js +43 -0
  244. package/dist/pricing-decimal.js.map +1 -0
  245. package/dist/providers/dodo/better-auth-core.d.ts +1 -1
  246. package/dist/providers/dodo/better-auth-core.d.ts.map +1 -1
  247. package/dist/providers/dodo/better-auth-core.js +2 -2
  248. package/dist/providers/dodo/better-auth-core.js.map +1 -1
  249. package/dist/providers/dodo/better-auth.d.ts.map +1 -1
  250. package/dist/providers/dodo/better-auth.js +16 -2
  251. package/dist/providers/dodo/better-auth.js.map +1 -1
  252. package/dist/providers/dodo/event-mapper.d.ts +1 -1
  253. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  254. package/dist/providers/dodo/event-mapper.js +120 -18
  255. package/dist/providers/dodo/event-mapper.js.map +1 -1
  256. package/dist/providers/dodo/nextjs-core.d.ts +1 -1
  257. package/dist/providers/dodo/nextjs-core.d.ts.map +1 -1
  258. package/dist/providers/dodo/nextjs-core.js +2 -2
  259. package/dist/providers/dodo/nextjs-core.js.map +1 -1
  260. package/dist/providers/dodo/nextjs.d.ts.map +1 -1
  261. package/dist/providers/dodo/nextjs.js +16 -6
  262. package/dist/providers/dodo/nextjs.js.map +1 -1
  263. package/dist/providers/dodo/provider.d.ts +5 -2
  264. package/dist/providers/dodo/provider.d.ts.map +1 -1
  265. package/dist/providers/dodo/provider.js +33 -6
  266. package/dist/providers/dodo/provider.js.map +1 -1
  267. package/dist/providers/dodo/verified-payment-payload.d.ts +6 -0
  268. package/dist/providers/dodo/verified-payment-payload.d.ts.map +1 -0
  269. package/dist/providers/dodo/verified-payment-payload.js +42 -0
  270. package/dist/providers/dodo/verified-payment-payload.js.map +1 -0
  271. package/dist/providers/index.d.ts +1 -1
  272. package/dist/providers/index.d.ts.map +1 -1
  273. package/dist/providers/index.js.map +1 -1
  274. package/dist/providers/mock/provider.d.ts +4 -1
  275. package/dist/providers/mock/provider.d.ts.map +1 -1
  276. package/dist/providers/mock/provider.js +3 -1
  277. package/dist/providers/mock/provider.js.map +1 -1
  278. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  279. package/dist/providers/stripe/event-mapper.js +48 -20
  280. package/dist/providers/stripe/event-mapper.js.map +1 -1
  281. package/dist/providers/stripe/provider.d.ts +4 -1
  282. package/dist/providers/stripe/provider.d.ts.map +1 -1
  283. package/dist/providers/stripe/provider.js +64 -23
  284. package/dist/providers/stripe/provider.js.map +1 -1
  285. package/dist/providers/types.d.ts +11 -1
  286. package/dist/providers/types.d.ts.map +1 -1
  287. package/dist/providers/types.js +9 -0
  288. package/dist/providers/types.js.map +1 -1
  289. package/dist/shared/postgres-client.d.ts +3 -0
  290. package/dist/shared/postgres-client.d.ts.map +1 -1
  291. package/dist/shared/postgres-client.js +61 -49
  292. package/dist/shared/postgres-client.js.map +1 -1
  293. package/dist/shared/provider-rejection.d.ts +3 -0
  294. package/dist/shared/provider-rejection.d.ts.map +1 -0
  295. package/dist/shared/provider-rejection.js +17 -0
  296. package/dist/shared/provider-rejection.js.map +1 -0
  297. package/dist/shared/timestamp.d.ts +2 -0
  298. package/dist/shared/timestamp.d.ts.map +1 -1
  299. package/dist/shared/timestamp.js +7 -0
  300. package/dist/shared/timestamp.js.map +1 -1
  301. package/dist/storage/adapters/clickhouse.d.ts +1 -1
  302. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  303. package/dist/storage/adapters/clickhouse.js +18 -17
  304. package/dist/storage/adapters/clickhouse.js.map +1 -1
  305. package/dist/storage/adapters/s3.d.ts +5 -0
  306. package/dist/storage/adapters/s3.d.ts.map +1 -1
  307. package/dist/storage/adapters/s3.js +46 -14
  308. package/dist/storage/adapters/s3.js.map +1 -1
  309. package/dist/storage/diagnostics.d.ts +3 -7
  310. package/dist/storage/diagnostics.d.ts.map +1 -1
  311. package/dist/storage/diagnostics.js +6 -15
  312. package/dist/storage/diagnostics.js.map +1 -1
  313. package/dist/storage/outbox-worker.d.ts.map +1 -1
  314. package/dist/storage/outbox-worker.js +4 -3
  315. package/dist/storage/outbox-worker.js.map +1 -1
  316. package/dist/storage/ports.d.ts +3 -0
  317. package/dist/storage/ports.d.ts.map +1 -1
  318. package/dist/storage/ports.js.map +1 -1
  319. package/dist/storage/postgres-repository.d.ts +1 -3
  320. package/dist/storage/postgres-repository.d.ts.map +1 -1
  321. package/dist/storage/postgres-repository.js +10 -4
  322. package/dist/storage/postgres-repository.js.map +1 -1
  323. package/dist/storage/runtime.d.ts +15 -10
  324. package/dist/storage/runtime.d.ts.map +1 -1
  325. package/dist/storage/runtime.js +74 -68
  326. package/dist/storage/runtime.js.map +1 -1
  327. package/dist/telemetry/index.d.ts +1 -1
  328. package/dist/telemetry/index.js +1 -1
  329. package/dist/telemetry/index.js.map +1 -1
  330. package/package.json +73 -71
  331. package/dist/credits/queries.d.ts +0 -33
  332. package/dist/credits/queries.d.ts.map +0 -1
  333. package/dist/credits/queries.js +0 -71
  334. package/dist/credits/queries.js.map +0 -1
@@ -1,7 +1,8 @@
1
+ import { PricingDecimal } from "../../pricing-decimal.js";
1
2
  import { Decimal } from "decimal.js";
2
3
  import { z } from "zod";
3
4
  import { BillingStore } from "../billing-store.js";
4
- import { PostgresClient, } from "../../shared/postgres-client.js";
5
+ import { PostgresClient, normalizeTenantId, } from "../../shared/postgres-client.js";
5
6
  import { normalizeProviderEnvironment, } from "../../providers/environment.js";
6
7
  import { StoreClosedError, StoreError } from "../../errors.js";
7
8
  import { optionalBoundedDiagnosticMessage } from "../../shared/diagnostics.js";
@@ -29,7 +30,7 @@ const BillingCreditPostingRowSchema = z
29
30
  balance_after: z
30
31
  .union([z.string(), z.number(), z.instanceof(Decimal)])
31
32
  .nullable()
32
- .transform((value) => (value === null ? null : new Decimal(value))),
33
+ .transform((value) => (value === null ? null : new PricingDecimal(value))),
33
34
  replayed: pgBoolean,
34
35
  error_code: z.string().min(1).nullable(),
35
36
  })
@@ -52,6 +53,7 @@ const CheckoutIntentRowSchema = z
52
53
  request_digest: z.instanceof(Uint8Array).refine((value) => value.byteLength === 32),
53
54
  status: z.enum(["open", "completed", "failed", "expired"]),
54
55
  provider_session_id: z.string().min(1).nullable(),
56
+ provider_customer_id: z.string().min(1).nullable(),
55
57
  checkout_url: z.string().min(1).nullable(),
56
58
  expires_at: z.union([z.string().datetime({ offset: true }), z.date()]),
57
59
  })
@@ -71,120 +73,110 @@ function billingCreditPostingResult(rows, context) {
71
73
  errorCode: row.error_code,
72
74
  };
73
75
  }
76
+ const transactionScope = Symbol("billing transaction scope");
74
77
  export class PostgresBillingStore extends BillingStore {
78
+ tenantId;
75
79
  postgres;
80
+ scoped;
81
+ options;
76
82
  providerEnvironment;
77
- _offer = null;
78
- _topup = null;
79
- _customer = null;
80
- _subscription = null;
81
- _event = null;
82
- _payment = null;
83
- _refund = null;
84
- _invoice = null;
85
- _dispute = null;
86
- _preferences = null;
87
- _autoRecharge = null;
88
- _subscriptionChange = null;
83
+ queryFn;
84
+ billingOffer;
85
+ billingTopup;
86
+ billingCustomer;
87
+ billingSubscription;
88
+ billingEvent;
89
+ billingPayment;
90
+ billingRefund;
91
+ billingInvoice;
92
+ billingDispute;
93
+ billingPreferences;
94
+ billingAutoRecharge;
95
+ billingSubscriptionChange;
89
96
  constructor(options) {
90
97
  super();
98
+ // SAFETY: Only this module can attach the private transaction scope symbol.
99
+ const scope = options[transactionScope];
100
+ this.options = { ...options };
101
+ this.scoped = scope !== undefined;
91
102
  if (!z.object({}).safeParse(options).success) {
92
103
  throw new TypeError("PostgresBillingStore options are required");
93
104
  }
94
105
  if (!z.string().safeParse(options.postgres).success && options.poolConstructor !== undefined) {
95
106
  throw new TypeError("poolConstructor cannot be used with an existing PostgreSQL pool");
96
107
  }
97
- const providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);
98
- this.providerEnvironment = providerEnvironment;
99
- this.postgres = new PostgresClient(options.postgres, {
100
- tenantId: options.tenantId,
101
- providerEnvironment,
102
- poolConstructor: options.poolConstructor,
103
- billingPayloadBackend: options.billingPayloadBackend,
104
- connectionTimeoutMs: options.connectionTimeoutMs,
105
- statementTimeoutMs: options.statementTimeoutMs,
106
- idleTransactionTimeoutMs: options.idleTransactionTimeoutMs,
107
- idleTimeoutMs: options.idleTimeoutMs,
108
- maxConnections: options.maxConnections,
109
- applicationName: options.applicationName,
110
- onPoolError: options.onPoolError,
111
- closedError: () => new StoreClosedError("Billing store has been closed"),
108
+ this.tenantId = normalizeTenantId(options.tenantId);
109
+ this.providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);
110
+ this.postgres =
111
+ scope?.postgres ??
112
+ new PostgresClient(options.postgres, {
113
+ tenantId: this.tenantId,
114
+ providerEnvironment: this.providerEnvironment,
115
+ poolConstructor: options.poolConstructor,
116
+ billingPayloadBackend: options.billingPayloadBackend,
117
+ connectionTimeoutMs: options.connectionTimeoutMs,
118
+ statementTimeoutMs: options.statementTimeoutMs,
119
+ idleTransactionTimeoutMs: options.idleTransactionTimeoutMs,
120
+ idleTimeoutMs: options.idleTimeoutMs,
121
+ maxConnections: options.maxConnections,
122
+ applicationName: options.applicationName,
123
+ onPoolError: options.onPoolError,
124
+ instrumentation: options.instrumentation,
125
+ closedError: () => new StoreClosedError("Billing store has been closed"),
126
+ });
127
+ this.queryFn = scope?.query ?? this.postgres.query;
128
+ this.billingOffer = new BillingOfferRepository(this.queryFn);
129
+ this.billingTopup = new BillingTopupRepository(this.queryFn);
130
+ this.billingCustomer = new BillingCustomerRepository(this.queryFn);
131
+ this.billingSubscription = new BillingSubscriptionRepository(this.queryFn);
132
+ this.billingEvent = new BillingEventRepository(this.queryFn);
133
+ this.billingPayment = new BillingPaymentRepository(this.queryFn);
134
+ this.billingRefund = new BillingRefundRepository(this.queryFn);
135
+ this.billingInvoice = new BillingInvoiceRepository(this.queryFn);
136
+ this.billingDispute = new BillingDisputeRepository(this.queryFn);
137
+ this.billingPreferences = new BillingPreferencesRepository(this.queryFn);
138
+ this.billingAutoRecharge = new BillingAutoRechargeRepository(this.queryFn);
139
+ this.billingSubscriptionChange = new BillingSubscriptionChangeRepository(this.queryFn);
140
+ }
141
+ async withBillingEventTransaction(action) {
142
+ if (this.scoped)
143
+ throw new TypeError("Nested billing event transactions are not supported");
144
+ return this.postgres.withTransaction(async (transactionQuery) => {
145
+ let active = true;
146
+ const queryFn = (text, params) => {
147
+ if (!active)
148
+ throw new StoreClosedError("Billing transaction has ended");
149
+ return transactionQuery(text, params);
150
+ };
151
+ const options = {
152
+ ...this.options,
153
+ [transactionScope]: { postgres: this.postgres, query: queryFn },
154
+ };
155
+ const scoped = new PostgresBillingStore(options);
156
+ try {
157
+ return await action(scoped);
158
+ }
159
+ finally {
160
+ active = false;
161
+ }
112
162
  });
113
163
  }
164
+ async observeBillingInvoiceOutcome(provider, invoiceId, outcome) {
165
+ const rows = await this.queryFn("SELECT bursar.observe_billing_invoice_outcome($1, $2, $3) AS accepted", [provider, invoiceId, outcome]);
166
+ return requireResultField(rows, "accepted", pgBoolean, "observeBillingInvoiceOutcome");
167
+ }
114
168
  async close() {
169
+ if (this.scoped)
170
+ throw new TypeError("Cannot close a scoped billing store");
115
171
  await this.postgres.close();
116
172
  }
117
- get queryFn() {
118
- return this.postgres.query;
119
- }
120
- get billingOffer() {
121
- if (!this._offer)
122
- this._offer = new BillingOfferRepository(this.queryFn);
123
- return this._offer;
124
- }
125
- get billingTopup() {
126
- if (!this._topup)
127
- this._topup = new BillingTopupRepository(this.queryFn);
128
- return this._topup;
129
- }
130
- get billingCustomer() {
131
- if (!this._customer)
132
- this._customer = new BillingCustomerRepository(this.queryFn);
133
- return this._customer;
134
- }
135
- get billingSubscription() {
136
- if (!this._subscription)
137
- this._subscription = new BillingSubscriptionRepository(this.queryFn);
138
- return this._subscription;
139
- }
140
- get billingEvent() {
141
- if (!this._event)
142
- this._event = new BillingEventRepository(this.queryFn);
143
- return this._event;
144
- }
145
- get billingPayment() {
146
- if (!this._payment)
147
- this._payment = new BillingPaymentRepository(this.queryFn);
148
- return this._payment;
149
- }
150
- get billingRefund() {
151
- if (!this._refund)
152
- this._refund = new BillingRefundRepository(this.queryFn);
153
- return this._refund;
154
- }
155
- get billingInvoice() {
156
- if (!this._invoice)
157
- this._invoice = new BillingInvoiceRepository(this.queryFn);
158
- return this._invoice;
159
- }
160
- get billingDispute() {
161
- if (!this._dispute)
162
- this._dispute = new BillingDisputeRepository(this.queryFn);
163
- return this._dispute;
164
- }
165
- get billingPreferences() {
166
- if (!this._preferences)
167
- this._preferences = new BillingPreferencesRepository(this.queryFn);
168
- return this._preferences;
169
- }
170
- get billingAutoRecharge() {
171
- if (!this._autoRecharge)
172
- this._autoRecharge = new BillingAutoRechargeRepository(this.queryFn);
173
- return this._autoRecharge;
174
- }
175
- get billingSubscriptionChange() {
176
- if (!this._subscriptionChange) {
177
- this._subscriptionChange = new BillingSubscriptionChangeRepository(this.queryFn);
178
- }
179
- return this._subscriptionChange;
180
- }
181
173
  async createOrGetCheckoutIntent(input) {
182
174
  const operationKey = requireStableKey(input.operationKey, "operationKey");
183
175
  if (!/^[0-9a-fA-F]{64}$/.test(input.requestDigest)) {
184
176
  throw new TypeError("requestDigest must be a 32-byte hex string");
185
177
  }
186
178
  const rows = await this.queryFn(`SELECT bursar.create_checkout_intent(
187
- $1::uuid, $2, $3, $4, $5, decode($6, 'hex'), $7::timestamptz, NULL, NULL, $8, $9::uuid, $10::uuid
179
+ $1::uuid, $2, $3, $4, $5, decode($6, 'hex'), $7::timestamptz, NULL, NULL, $8, $9::uuid, $10::uuid, $11
188
180
  ) AS id`, [
189
181
  input.subjectId,
190
182
  input.provider,
@@ -196,6 +188,7 @@ export class PostgresBillingStore extends BillingStore {
196
188
  input.region ?? null,
197
189
  input.expectedRevisionId ?? null,
198
190
  input.accountId ?? input.subjectId,
191
+ input.providerCustomerId ?? null,
199
192
  ]);
200
193
  const id = requireResultField(rows, "id", postgresUuid, "PostgresBillingStore.createOrGetCheckoutIntent");
201
194
  const intent = await this.getCheckoutIntent(id, input.subjectId);
@@ -208,7 +201,14 @@ export class PostgresBillingStore extends BillingStore {
208
201
  return intent;
209
202
  }
210
203
  async updateCheckoutIntent(id, update) {
211
- const rows = await this.queryFn(`SELECT bursar.advance_checkout_intent($1::uuid, $2, $3, $4) AS advanced`, [id, update.status ?? null, update.providerSessionId ?? null, update.checkoutUrl ?? null]);
204
+ const rows = await this.queryFn(`SELECT bursar.advance_checkout_intent($1::uuid, $2, $3, $4, $5, $6::uuid) AS advanced`, [
205
+ id,
206
+ update.status ?? null,
207
+ update.providerSessionId ?? null,
208
+ update.checkoutUrl ?? null,
209
+ update.expectedOwner?.provider ?? null,
210
+ update.expectedOwner?.accountId ?? null,
211
+ ]);
212
212
  if (!requireResultField(rows, "advanced", pgBoolean, "PostgresBillingStore.updateCheckoutIntent")) {
213
213
  throw new StoreError(`checkout intent transition rejected: ${id}`, {
214
214
  details: { checkoutIntentId: id },
@@ -254,6 +254,7 @@ export class PostgresBillingStore extends BillingStore {
254
254
  request_digest: row.request_digest,
255
255
  status: row.status,
256
256
  provider_session_id: row.provider_session_id,
257
+ provider_customer_id: row.provider_customer_id,
257
258
  checkout_url: row.checkout_url,
258
259
  expires_at: row.expires_at,
259
260
  }, "PostgresBillingStore.getCheckoutIntent"));
@@ -268,6 +269,7 @@ export class PostgresBillingStore extends BillingStore {
268
269
  requestDigest: Buffer.from(row.request_digest).toString("hex"),
269
270
  status: row.status,
270
271
  providerSessionId: row.provider_session_id,
272
+ providerCustomerId: row.provider_customer_id,
271
273
  checkoutUrl: row.checkout_url,
272
274
  expiresAt: row.expires_at instanceof Date ? row.expires_at.toISOString() : row.expires_at,
273
275
  };
@@ -366,6 +368,9 @@ export class PostgresBillingStore extends BillingStore {
366
368
  }
367
369
  return this.billingSubscriptionChange.create(subscription.id, input);
368
370
  }
371
+ async findBillingSubscriptionChange(provider, subscriptionId, operationKey) {
372
+ return this.billingSubscriptionChange.find(provider, subscriptionId, operationKey);
373
+ }
369
374
  async getOpenBillingSubscriptionChange(provider, providerSubscriptionId) {
370
375
  return this.billingSubscriptionChange.getOpen(provider, providerSubscriptionId);
371
376
  }
@@ -406,6 +411,7 @@ export class PostgresBillingStore extends BillingStore {
406
411
  creditsPerUnit: r.credits_per_unit,
407
412
  depositTo: r.bucket_key,
408
413
  amountMinor: r.amount_minor,
414
+ taxBehavior: r.tax_behavior,
409
415
  currency: r.currency,
410
416
  minQuantity: r.min_quantity,
411
417
  maxQuantity: r.max_quantity,
@@ -414,29 +420,16 @@ export class PostgresBillingStore extends BillingStore {
414
420
  maxAmountMinor,
415
421
  };
416
422
  }
417
- async resolveCreditTopup(provider, productId, priceId, checkoutIntentId, subjectId, providerPaymentId, rechargeAttemptId) {
418
- const r = await this.billingTopup.resolveByPrice(provider, priceId ?? null, productId ?? null, checkoutIntentId, subjectId, providerPaymentId, rechargeAttemptId);
423
+ async resolveCreditTopup(provider, productId, priceId, checkoutIntentId, subjectId, providerPaymentId, rechargeAttemptId, billingEventId) {
424
+ const r = await this.billingTopup.resolveByPrice(provider, priceId ?? null, productId ?? null, checkoutIntentId, subjectId, providerPaymentId, rechargeAttemptId, billingEventId);
419
425
  return this.rowToTopup(r);
420
426
  }
421
427
  async resolveCreditTopupByLookup(provider, lookupKey) {
422
428
  const r = await this.billingTopup.resolveByLookup(provider, lookupKey);
423
429
  return this.rowToTopup(r);
424
430
  }
425
- async computeTopupCredits(amountMinor, topupConfig) {
426
- if (!Number.isSafeInteger(amountMinor) || amountMinor < 0) {
427
- throw new TypeError("amountMinor must be a non-negative safe integer");
428
- }
429
- const unitAmount = topupConfig.amountMinor;
430
- if (unitAmount <= 0 || amountMinor % unitAmount !== 0)
431
- return new Decimal(0);
432
- const quantity = amountMinor / unitAmount;
433
- if (quantity < topupConfig.minQuantity || quantity > topupConfig.maxQuantity) {
434
- return new Decimal(0);
435
- }
436
- return topupConfig.creditsPerUnit.mul(quantity);
437
- }
438
431
  async upsertBillingPayment(options) {
439
- return this.billingPayment.upsert(options.provider, options.providerPaymentId, options.providerInvoiceId ?? null, options.userId, options.amountMinor, options.taxMinor, options.currency, options.purpose, options.metadata ? JSON.stringify(options.metadata) : null, options.status, options.providerUpdatedAt, options.topupId ?? null);
432
+ return this.billingPayment.upsert(options);
440
433
  }
441
434
  async createBillingCreditGrant(input) {
442
435
  const rows = await this.queryFn("SELECT bursar.create_billing_credit_grant($1::uuid, $2::uuid, $3::uuid, $4, $5, $6::uuid) AS id", [
@@ -486,8 +479,11 @@ export class PostgresBillingStore extends BillingStore {
486
479
  }
487
480
  await this.billingInvoice.upsert(options.userId, options.provider, options.providerInvoiceId, subscription?.id ? String(subscription.id) : null, options.status, options.amountDueMinor, options.amountPaidMinor, options.currency, options.periodStart ?? null, options.periodEnd ?? null, options.metadata ?? {}, options.providerUpdatedAt);
488
481
  }
489
- async listBillingInvoices(userId) {
490
- return this.billingInvoice.listForUser(userId);
482
+ async listBillingInvoices(userId, options) {
483
+ return this.billingInvoice.listForUser(userId, options);
484
+ }
485
+ async hasBillingInvoice(userId, provider, providerInvoiceId) {
486
+ return this.billingInvoice.hasForUser(userId, provider, providerInvoiceId);
491
487
  }
492
488
  async upsertBillingDispute(options) {
493
489
  const payment = await this.billingPayment.getForRefund(options.provider, options.providerPaymentId);
@@ -526,6 +522,7 @@ export class PostgresBillingStore extends BillingStore {
526
522
  }
527
523
  rowToSubscriptionState(r) {
528
524
  return {
525
+ cycleGrantCredits: r.cycle_grant_amount == null ? null : new PricingDecimal(r.cycle_grant_amount),
529
526
  subscriptionId: r.id,
530
527
  userId: r.user_id,
531
528
  provider: r.provider,
@@ -1 +1 @@
1
- {"version":3,"file":"store.js","sourceRoot":"","sources":["../../../src/billing/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAmBxB,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAgBnD,OAAO,EACL,cAAc,GAIf,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,4BAA4B,GAE7B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC/D,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAC/D,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,SAAS,GACV,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,sBAAsB,EAAwB,MAAM,yBAAyB,CAAC;AACvF,OAAO,EAAE,sBAAsB,EAAwB,MAAM,yBAAyB,CAAC;AACvF,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EACL,6BAA6B,GAE9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AACjE,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,MAAM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9B,MAAc,EACd,QAAwB;QAExB,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,WAAW,CAAC,MAAM,EAAE,QAAQ,IAAI,IAAI,CAAC,CAAC;QAChF,IAAI,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QACzB,OAAO;YACL,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,kBAAkB,EAAE,MAAM,CAAC,kBAAkB;SAC9C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { z } from \"zod\";\nimport type { JsonObject, PostgresValue } from \"../../shared/json.js\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeProfile,\n BillingCreditPostingResult,\n BillingCustomerRecord,\n BillingEventClaim,\n BillingOfferResult,\n BillingPaymentRecord,\n BillingPreferences,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionState,\n BillingSubscriptionStatus,\n SubscriptionEntitlementOutcome,\n CheckoutIntent,\n BillingTopupResult,\n} from \"../types/index.js\";\nimport { BillingStore } from \"../billing-store.js\";\nimport type {\n AutoRechargeAttemptClaim,\n AutoRechargeAttemptUpdate,\n AutoRechargeProviderPaymentUpdate,\n BillingCreditGrantCreate,\n BillingDisputeUpsert,\n BillingInvoiceUpsert,\n BillingPaymentUpsert,\n BillingRefundUpsert,\n BillingSubscriptionChangeUpdate,\n BillingSubscriptionConflictCreate,\n CheckoutIntentCreate,\n CheckoutIntentUpdate,\n} from \"../contracts.js\";\nimport type { QueryFn } from \"../../shared/postgres-types.js\";\nimport {\n PostgresClient,\n type PostgresConnectionOptions,\n type PostgresPool,\n type PostgresPoolConstructor,\n} from \"../../shared/postgres-client.js\";\nimport {\n normalizeProviderEnvironment,\n type ProviderEnvironment,\n} from \"../../providers/environment.js\";\nimport { StoreClosedError, StoreError } from \"../../errors.js\";\nimport { optionalBoundedDiagnosticMessage } from \"../../shared/diagnostics.js\";\nimport { requireStableKey } from \"../../shared/idempotency.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireRecordRow,\n requireResultField,\n safeParse,\n} from \"../../shared/postgres-validation.js\";\nimport { BillingOfferRepository, type BillingOfferRow } from \"./repositories/offer.js\";\nimport { BillingTopupRepository, type BillingTopupRow } from \"./repositories/topup.js\";\nimport { BillingCustomerRepository } from \"./repositories/customer.js\";\nimport {\n BillingSubscriptionRepository,\n type SubscriptionRow,\n} from \"./repositories/subscription.js\";\nimport { BillingEventRepository } from \"./repositories/event.js\";\nimport { BillingPaymentRepository } from \"./repositories/payment.js\";\nimport { BillingRefundRepository } from \"./repositories/refund.js\";\nimport { BillingInvoiceRepository } from \"./repositories/invoice.js\";\nimport { BillingDisputeRepository } from \"./repositories/dispute.js\";\nimport { BillingPreferencesRepository } from \"./repositories/preferences.js\";\nimport { BillingAutoRechargeRepository } from \"./repositories/auto-recharge.js\";\nimport { BillingSubscriptionChangeRepository } from \"./repositories/subscription-change.js\";\n\nconst PgSafeMinorUnitsSchema = z\n .union([z.string().regex(/^\\d+$/), z.number().int().nonnegative().safe()])\n .transform(Number)\n .refine(Number.isSafeInteger, \"minor-unit amount exceeds JavaScript's safe integer range\");\n\nconst BillingCreditPostingRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n balance_after: z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .nullable()\n .transform((value) => (value === null ? null : new Decimal(value))),\n replayed: pgBoolean,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.error_code === null && (row.ledger_entry_id === null || row.balance_after === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"successful posting requires ledger_entry_id and balance_after\",\n });\n }\n });\n\nconst CheckoutIntentRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n checkout_kind: z.enum([\"subscription\", \"credit_topup\"]),\n product_key: z.string().min(1),\n request_digest: z.instanceof(Uint8Array).refine((value) => value.byteLength === 32),\n status: z.enum([\"open\", \"completed\", \"failed\", \"expired\"]),\n provider_session_id: z.string().min(1).nullable(),\n checkout_url: z.string().min(1).nullable(),\n expires_at: z.union([z.string().datetime({ offset: true }), z.date()]),\n })\n .strict();\n\nfunction billingCreditPostingResult(\n rows: readonly PostgresValue[] | null | undefined,\n context: string,\n): BillingCreditPostingResult {\n const raw = requireRecordRow(rows, context);\n const row = safeParse(\n BillingCreditPostingRowSchema,\n {\n ledger_entry_id: raw.ledger_entry_id,\n balance_after: raw.balance_after,\n replayed: raw.replayed,\n error_code: raw.error_code,\n },\n context,\n { indeterminate: true },\n );\n return {\n ledgerEntryId: row.ledger_entry_id,\n balanceAfter: row.balance_after,\n replayed: row.replayed,\n errorCode: row.error_code,\n };\n}\n\nexport interface PostgresBillingStoreOptions extends Omit<\n PostgresConnectionOptions,\n \"providerEnvironment\"\n> {\n /** PostgreSQL connection string or an application-owned pool. */\n postgres: PostgresPool | string;\n /** Tenant UUID bound to every store transaction. */\n tenantId: string;\n /** Explicit financial namespace; billing stores never guess live vs test. */\n providerEnvironment: ProviderEnvironment;\n /** Injectable `pg.Pool` constructor for custom runtimes and tests. */\n poolConstructor?: PostgresPoolConstructor;\n billingPayloadBackend?: \"postgres\" | \"s3\";\n}\n\nexport class PostgresBillingStore extends BillingStore {\n private readonly postgres: PostgresClient;\n readonly providerEnvironment: ProviderEnvironment;\n\n private _offer: BillingOfferRepository | null = null;\n private _topup: BillingTopupRepository | null = null;\n private _customer: BillingCustomerRepository | null = null;\n private _subscription: BillingSubscriptionRepository | null = null;\n private _event: BillingEventRepository | null = null;\n private _payment: BillingPaymentRepository | null = null;\n private _refund: BillingRefundRepository | null = null;\n private _invoice: BillingInvoiceRepository | null = null;\n private _dispute: BillingDisputeRepository | null = null;\n private _preferences: BillingPreferencesRepository | null = null;\n private _autoRecharge: BillingAutoRechargeRepository | null = null;\n private _subscriptionChange: BillingSubscriptionChangeRepository | null = null;\n constructor(options: PostgresBillingStoreOptions) {\n super();\n if (!z.object({}).safeParse(options).success) {\n throw new TypeError(\"PostgresBillingStore options are required\");\n }\n if (!z.string().safeParse(options.postgres).success && options.poolConstructor !== undefined) {\n throw new TypeError(\"poolConstructor cannot be used with an existing PostgreSQL pool\");\n }\n const providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);\n this.providerEnvironment = providerEnvironment;\n this.postgres = new PostgresClient(options.postgres, {\n tenantId: options.tenantId,\n providerEnvironment,\n poolConstructor: options.poolConstructor,\n billingPayloadBackend: options.billingPayloadBackend,\n connectionTimeoutMs: options.connectionTimeoutMs,\n statementTimeoutMs: options.statementTimeoutMs,\n idleTransactionTimeoutMs: options.idleTransactionTimeoutMs,\n idleTimeoutMs: options.idleTimeoutMs,\n maxConnections: options.maxConnections,\n applicationName: options.applicationName,\n onPoolError: options.onPoolError,\n closedError: () => new StoreClosedError(\"Billing store has been closed\"),\n });\n }\n\n async close(): Promise<void> {\n await this.postgres.close();\n }\n\n private get queryFn(): QueryFn {\n return this.postgres.query;\n }\n\n private get billingOffer(): BillingOfferRepository {\n if (!this._offer) this._offer = new BillingOfferRepository(this.queryFn);\n return this._offer;\n }\n\n private get billingTopup(): BillingTopupRepository {\n if (!this._topup) this._topup = new BillingTopupRepository(this.queryFn);\n return this._topup;\n }\n\n private get billingCustomer(): BillingCustomerRepository {\n if (!this._customer) this._customer = new BillingCustomerRepository(this.queryFn);\n return this._customer;\n }\n\n private get billingSubscription(): BillingSubscriptionRepository {\n if (!this._subscription) this._subscription = new BillingSubscriptionRepository(this.queryFn);\n return this._subscription;\n }\n\n private get billingEvent(): BillingEventRepository {\n if (!this._event) this._event = new BillingEventRepository(this.queryFn);\n return this._event;\n }\n\n private get billingPayment(): BillingPaymentRepository {\n if (!this._payment) this._payment = new BillingPaymentRepository(this.queryFn);\n return this._payment;\n }\n\n private get billingRefund(): BillingRefundRepository {\n if (!this._refund) this._refund = new BillingRefundRepository(this.queryFn);\n return this._refund;\n }\n\n private get billingInvoice(): BillingInvoiceRepository {\n if (!this._invoice) this._invoice = new BillingInvoiceRepository(this.queryFn);\n return this._invoice;\n }\n\n private get billingDispute(): BillingDisputeRepository {\n if (!this._dispute) this._dispute = new BillingDisputeRepository(this.queryFn);\n return this._dispute;\n }\n\n private get billingPreferences(): BillingPreferencesRepository {\n if (!this._preferences) this._preferences = new BillingPreferencesRepository(this.queryFn);\n return this._preferences;\n }\n\n private get billingAutoRecharge(): BillingAutoRechargeRepository {\n if (!this._autoRecharge) this._autoRecharge = new BillingAutoRechargeRepository(this.queryFn);\n return this._autoRecharge;\n }\n\n private get billingSubscriptionChange(): BillingSubscriptionChangeRepository {\n if (!this._subscriptionChange) {\n this._subscriptionChange = new BillingSubscriptionChangeRepository(this.queryFn);\n }\n return this._subscriptionChange;\n }\n\n async createOrGetCheckoutIntent(input: CheckoutIntentCreate): Promise<CheckoutIntent> {\n const operationKey = requireStableKey(input.operationKey, \"operationKey\");\n if (!/^[0-9a-fA-F]{64}$/.test(input.requestDigest)) {\n throw new TypeError(\"requestDigest must be a 32-byte hex string\");\n }\n const rows = await this.queryFn(\n `SELECT bursar.create_checkout_intent(\n $1::uuid, $2, $3, $4, $5, decode($6, 'hex'), $7::timestamptz, NULL, NULL, $8, $9::uuid, $10::uuid\n ) AS id`,\n [\n input.subjectId,\n input.provider,\n operationKey,\n input.checkoutKind,\n input.productKey,\n input.requestDigest,\n input.expiresAt,\n input.region ?? null,\n input.expectedRevisionId ?? null,\n input.accountId ?? input.subjectId,\n ],\n );\n const id = requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createOrGetCheckoutIntent\",\n );\n const intent = await this.getCheckoutIntent(id, input.subjectId);\n if (!intent) {\n throw new StoreError(\"checkout intent could not be read after creation\", {\n indeterminate: true,\n details: { checkoutIntentId: id },\n });\n }\n return intent;\n }\n\n async updateCheckoutIntent(id: string, update: CheckoutIntentUpdate): Promise<void> {\n const rows = await this.queryFn(\n `SELECT bursar.advance_checkout_intent($1::uuid, $2, $3, $4) AS advanced`,\n [id, update.status ?? null, update.providerSessionId ?? null, update.checkoutUrl ?? null],\n );\n if (\n !requireResultField(rows, \"advanced\", pgBoolean, \"PostgresBillingStore.updateCheckoutIntent\")\n ) {\n throw new StoreError(`checkout intent transition rejected: ${id}`, {\n details: { checkoutIntentId: id },\n });\n }\n }\n\n override async findCheckoutIntent(\n subjectId: string,\n operationKey: string,\n provider?: string,\n ): Promise<{ intent: CheckoutIntent; catalog: JsonObject } | null> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.find_checkout_intent($1::uuid, $2, $3)\", [\n subjectId,\n operationKey,\n provider ?? null,\n ]);\n if (rows.length === 0) return null;\n if (rows.length !== 1)\n throw new StoreError(\"checkout operation key matches multiple providers\");\n const row = rows[0]!;\n const id = safeParse(postgresUuid, row.intent_id, \"findCheckoutIntent.id\");\n const catalog = safeParse(\n z.record(z.string(), z.json()),\n row.source_document,\n \"findCheckoutIntent.catalog\",\n );\n const intent = await this.getCheckoutIntent(id, subjectId);\n if (!intent) throw new StoreError(\"checkout intent disappeared\");\n return { intent, catalog };\n }\n\n async getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_checkout_intent($1::uuid, $2::uuid)`,\n [id, subjectId],\n );\n if (rows.length === 0) return null;\n if (rows.length !== 1) {\n throw new StoreError(\"getCheckoutIntent: expected at most one row\", {\n details: { rowCount: rows.length, checkoutIntentId: id },\n });\n }\n const row = rows[0];\n if (!row) throw new StoreError(\"getCheckoutIntent: expected one row\");\n return this.rowToCheckoutIntent(\n safeParse(\n CheckoutIntentRowSchema,\n {\n id: row.id,\n subject_id: row.subject_id,\n provider: row.provider,\n checkout_kind: row.checkout_kind,\n product_key: row.product_key,\n request_digest: row.request_digest,\n status: row.status,\n provider_session_id: row.provider_session_id,\n checkout_url: row.checkout_url,\n expires_at: row.expires_at,\n },\n \"PostgresBillingStore.getCheckoutIntent\",\n ),\n );\n }\n\n private rowToCheckoutIntent(row: z.infer<typeof CheckoutIntentRowSchema>): CheckoutIntent {\n return {\n id: row.id,\n subjectId: row.subject_id,\n provider: row.provider,\n checkoutKind: row.checkout_kind,\n productKey: row.product_key,\n requestDigest: Buffer.from(row.request_digest).toString(\"hex\"),\n status: row.status,\n providerSessionId: row.provider_session_id,\n checkoutUrl: row.checkout_url,\n expiresAt: row.expires_at instanceof Date ? row.expires_at.toISOString() : row.expires_at,\n };\n }\n\n private rowToOffer(row: BillingOfferRow | null): BillingOfferResult | null {\n if (!row) return null;\n return {\n offerId: row.id,\n offerKey: row.offerKey,\n planId: row.planId,\n plan: row.plan,\n interval: row.interval,\n intervalCount: row.intervalCount,\n grant:\n row.grantCredits === null\n ? null\n : {\n mode: \"cycle_grant\",\n credits: row.grantCredits,\n bucket: row.grantBucket,\n replacePrior: row.grantReplacePrior,\n },\n };\n }\n\n async resolveBillingOffer(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n checkout?: { accountId: string; intentId: string; lookupKey?: string | null },\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByPrice(\n provider,\n priceId ?? null,\n productId ?? null,\n checkout,\n );\n return this.rowToOffer(r);\n }\n\n async resolveBillingOfferByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByLookup(provider, lookupKey);\n return this.rowToOffer(r);\n }\n\n async claimBillingEvent(\n provider: string,\n eventId: string,\n eventType: string,\n envelope?: JsonObject,\n ): Promise<BillingEventClaim> {\n const result = await this.billingEvent.claim(\n provider,\n eventId,\n eventType,\n JSON.stringify(envelope ?? { eventType }),\n );\n if (result.status === \"claimed\") {\n if (result.claim_token === null || result.event_id === null) {\n throw new StoreError(\"Billing event claim returned no claim identifiers\", {\n details: { provider, eventId },\n });\n }\n return {\n status: \"claimed\" as const,\n claimToken: result.claim_token,\n billingEventId: result.event_id,\n };\n }\n if (result.status === \"duplicate\") return { status: \"duplicate\" as const };\n if (result.status === \"busy\") return { status: \"busy\" as const };\n if (result.status === \"invalid_request\") return { status: \"invalid_request\" as const };\n if (result.status === \"idempotency_conflict\" || result.status === \"max_retries_exceeded\") {\n if (result.event_id === null) {\n throw new StoreError(\"Billing event terminal claim returned no event identifier\", {\n details: { provider, eventId, status: result.status },\n });\n }\n return { status: result.status, billingEventId: result.event_id };\n }\n throw new StoreError(\"Billing event claim returned an unsupported status\", {\n details: { provider, eventId, status: result.status },\n });\n }\n\n async completeBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n ): Promise<boolean> {\n return this.billingEvent.complete(provider, eventId, claimToken);\n }\n\n async failBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n error?: string,\n ): Promise<boolean> {\n return this.billingEvent.fail(\n provider,\n eventId,\n claimToken,\n optionalBoundedDiagnosticMessage(error) ?? undefined,\n );\n }\n\n async upsertBillingCustomer(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email?: string | null,\n ): Promise<void> {\n await this.billingCustomer.upsert(provider, providerCustomerId, userId, email ?? null);\n }\n\n async upsertBillingSubscription(state: BillingSubscriptionState): Promise<void> {\n await this.billingSubscription.upsert(state);\n }\n\n async getBillingCustomer(provider: string, providerCustomerId: string): Promise<string | null> {\n return this.billingCustomer.get(provider, providerCustomerId);\n }\n\n async getBillingSubscription(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.get(provider, providerSubscriptionId);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async createBillingSubscriptionChange(\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n const subscription = await this.billingSubscription.get(\n input.provider,\n input.providerSubscriptionId,\n );\n if (!subscription?.id) {\n throw new StoreError(\"subscription change requires a persisted subscription\", {\n retryable: true,\n details: {\n provider: input.provider,\n providerSubscriptionId: input.providerSubscriptionId,\n },\n });\n }\n return this.billingSubscriptionChange.create(subscription.id, input);\n }\n\n async getOpenBillingSubscriptionChange(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.billingSubscriptionChange.getOpen(provider, providerSubscriptionId);\n }\n\n async listExpiredGraceSubscriptions(\n now: string,\n limit = 100,\n ): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.listExpiredGraceSubscriptions(now, limit);\n return rows.map((row) => this.rowToSubscriptionState(row));\n }\n\n async reconcileSubscriptionEntitlement(\n subjectId: string,\n subscriptionId: string,\n billingEventId: string,\n expectedStatus: BillingSubscriptionStatus,\n expectedProviderUpdatedAt: string,\n planAssignedAt: Date | string | null,\n applyEntitlement: boolean,\n reason: string,\n ): Promise<SubscriptionEntitlementOutcome> {\n return this.billingSubscription.reconcileEntitlement(\n subjectId,\n subscriptionId,\n billingEventId,\n expectedStatus,\n expectedProviderUpdatedAt,\n planAssignedAt,\n applyEntitlement,\n reason,\n );\n }\n\n async expireSubscriptionGracePeriod(\n subjectId: string,\n subscriptionId: string,\n expectedGraceEndsAt: string,\n expiredAt: string,\n ): Promise<boolean> {\n return this.billingSubscription.expireGracePeriod(\n subjectId,\n subscriptionId,\n expectedGraceEndsAt,\n expiredAt,\n );\n }\n\n async updateBillingSubscriptionChange(\n id: string,\n update: BillingSubscriptionChangeUpdate,\n ): Promise<void> {\n await this.billingSubscriptionChange.update(id, update);\n }\n\n async getUserSubscription(\n userId: string,\n statuses?: string[],\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.getUserSubscription(userId, statuses);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async getUserSubscriptions(userId: string): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.getUserSubscriptions(userId);\n return rows.map((r) => this.rowToSubscriptionState(r));\n }\n\n async recordSubscriptionConflict(input: BillingSubscriptionConflictCreate): Promise<void> {\n await this.billingSubscription.recordConflict(input);\n }\n\n private rowToTopup(r: BillingTopupRow | null): BillingTopupResult | null {\n if (!r) return null;\n const minAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.min_quantity,\n \"PostgresBillingStore.rowToTopup.minAmountMinor\",\n );\n const maxAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.max_quantity,\n \"PostgresBillingStore.rowToTopup.maxAmountMinor\",\n );\n return {\n topupId: r.id,\n topupKey: r.topup_key,\n creditsPerUnit: r.credits_per_unit,\n depositTo: r.bucket_key,\n amountMinor: r.amount_minor,\n currency: r.currency,\n minQuantity: r.min_quantity,\n maxQuantity: r.max_quantity,\n defaultQuantity: r.default_quantity,\n minAmountMinor,\n maxAmountMinor,\n };\n }\n\n async resolveCreditTopup(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n checkoutIntentId?: string | null,\n subjectId?: string | null,\n providerPaymentId?: string | null,\n rechargeAttemptId?: string | null,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByPrice(\n provider,\n priceId ?? null,\n productId ?? null,\n checkoutIntentId,\n subjectId,\n providerPaymentId,\n rechargeAttemptId,\n );\n return this.rowToTopup(r);\n }\n\n async resolveCreditTopupByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByLookup(provider, lookupKey);\n return this.rowToTopup(r);\n }\n\n async computeTopupCredits(\n amountMinor: number,\n topupConfig: BillingTopupResult,\n ): Promise<Decimal> {\n if (!Number.isSafeInteger(amountMinor) || amountMinor < 0) {\n throw new TypeError(\"amountMinor must be a non-negative safe integer\");\n }\n const unitAmount = topupConfig.amountMinor;\n if (unitAmount <= 0 || amountMinor % unitAmount !== 0) return new Decimal(0);\n const quantity = amountMinor / unitAmount;\n if (quantity < topupConfig.minQuantity || quantity > topupConfig.maxQuantity) {\n return new Decimal(0);\n }\n return topupConfig.creditsPerUnit.mul(quantity);\n }\n\n async upsertBillingPayment(options: BillingPaymentUpsert): Promise<string> {\n return this.billingPayment.upsert(\n options.provider,\n options.providerPaymentId,\n options.providerInvoiceId ?? null,\n options.userId,\n options.amountMinor,\n options.taxMinor,\n options.currency,\n options.purpose,\n options.metadata ? JSON.stringify(options.metadata) : null,\n options.status,\n options.providerUpdatedAt,\n options.topupId ?? null,\n );\n }\n\n async createBillingCreditGrant(input: BillingCreditGrantCreate): Promise<string> {\n const rows = await this.queryFn(\n \"SELECT bursar.create_billing_credit_grant($1::uuid, $2::uuid, $3::uuid, $4, $5, $6::uuid) AS id\",\n [\n input.paymentId ?? null,\n input.subscriptionId ?? null,\n input.topupId ?? null,\n input.configuredCredits.toString(),\n input.quantity,\n input.billingEventId ?? null,\n ],\n );\n return requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createBillingCreditGrant\",\n );\n }\n\n async grantBillingCredit(\n grantId: string,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.grant_billing_credit($1::uuid, $2)\", [\n grantId,\n idempotencyKey,\n ]);\n return billingCreditPostingResult(rows, \"PostgresBillingStore.grantBillingCredit\");\n }\n\n async getBillingCreditGrantByPayment(paymentId: string): Promise<string | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_billing_credit_grant_by_payment($1::uuid)`,\n [paymentId],\n );\n const row = optionalRecordRow(rows, \"PostgresBillingStore.getBillingCreditGrantByPayment\");\n return row === null\n ? null\n : safeParse(postgresUuid, row.id, \"PostgresBillingStore.getBillingCreditGrantByPayment.id\");\n }\n\n async postBillingRefund(\n refundId: string,\n grantId: string,\n amountMinor: number,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\n \"SELECT * FROM bursar.post_billing_refund($1::uuid, $2::uuid, $3, $4)\",\n [refundId, grantId, amountMinor, idempotencyKey],\n );\n return billingCreditPostingResult(rows, \"PostgresBillingStore.postBillingRefund\");\n }\n\n async upsertBillingRefund(options: BillingRefundUpsert): Promise<string> {\n return this.billingRefund.upsert(\n options.provider,\n options.providerRefundId,\n options.providerPaymentId,\n options.userId,\n options.amountMinor,\n options.currency,\n options.reason ?? null,\n options.metadata ? JSON.stringify(options.metadata) : null,\n options.status,\n options.providerUpdatedAt,\n );\n }\n\n async upsertBillingInvoice(options: BillingInvoiceUpsert): Promise<void> {\n const subscription = options.providerSubscriptionId\n ? await this.billingSubscription.get(options.provider, options.providerSubscriptionId)\n : null;\n if (options.providerSubscriptionId && !subscription) {\n throw new StoreError(\"invoice subscription is not available\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerInvoiceId: options.providerInvoiceId,\n providerSubscriptionId: options.providerSubscriptionId ?? null,\n },\n });\n }\n await this.billingInvoice.upsert(\n options.userId,\n options.provider,\n options.providerInvoiceId,\n subscription?.id ? String(subscription.id) : null,\n options.status,\n options.amountDueMinor,\n options.amountPaidMinor,\n options.currency,\n options.periodStart ?? null,\n options.periodEnd ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async listBillingInvoices(userId: string) {\n return this.billingInvoice.listForUser(userId);\n }\n\n async upsertBillingDispute(options: BillingDisputeUpsert): Promise<void> {\n const payment = await this.billingPayment.getForRefund(\n options.provider,\n options.providerPaymentId,\n );\n if (!payment?.id) {\n throw new StoreError(\"dispute payment is required\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerDisputeId: options.providerDisputeId,\n providerPaymentId: options.providerPaymentId ?? null,\n },\n });\n }\n await this.billingDispute.upsert(\n options.provider,\n options.providerDisputeId,\n String(payment.id),\n options.status,\n options.reason ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async getBillingPayment(\n provider: string,\n providerPaymentId: string,\n ): Promise<BillingPaymentRecord | null> {\n const row = await this.billingPayment.getForRefund(provider, providerPaymentId);\n if (!row) return null;\n return {\n id: row.id,\n provider: row.provider,\n providerPaymentId: row.provider_payment_id,\n providerInvoiceId: row.provider_invoice_id,\n userId: row.subject_id,\n amountMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.amount_minor,\n \"PostgresBillingStore.getBillingPayment.amountMinor\",\n ),\n taxMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.tax_minor,\n \"PostgresBillingStore.getBillingPayment.taxMinor\",\n ),\n currency: row.currency,\n purpose: row.purpose,\n status: row.status,\n providerUpdatedAt:\n row.provider_updated_at instanceof Date\n ? row.provider_updated_at.toISOString()\n : row.provider_updated_at,\n metadata: row.metadata,\n };\n }\n\n private rowToSubscriptionState(r: SubscriptionRow): BillingSubscriptionState {\n return {\n subscriptionId: r.id,\n userId: r.user_id,\n provider: r.provider,\n providerSubscriptionId: r.provider_subscription_id,\n providerCustomerId: r.provider_customer_id,\n offerId: r.offer_id,\n offerKey: r.offer_key,\n planId: r.plan_id,\n plan: r.plan,\n status: r.status,\n currentPeriodStart: r.current_period_start,\n currentPeriodEnd: r.current_period_end,\n trialEnd: r.trial_end,\n cancelAt: r.cancel_at,\n endedAt: r.ended_at,\n graceEndsAt: r.grace_ends_at,\n graceExpiredAt: r.grace_expired_at,\n providerUpdatedAt: r.provider_updated_at,\n cancelAtPeriodEnd: r.cancel_at_period_end,\n interval: r.interval,\n intervalCount: r.interval_count,\n metadata: r.metadata,\n };\n }\n\n async getActiveCatalogRevision(): Promise<{ id: string; config: JsonObject } | null> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.active_catalog_revision()\", []);\n const row = optionalRecordRow(rows, \"PostgresBillingStore.getActiveCatalogRevision\");\n if (row === null) return null;\n return {\n id: safeParse(postgresUuid, row.id, \"PostgresBillingStore.getActiveCatalogRevision.id\"),\n config: safeParse(\n z.record(z.string(), z.json()),\n row.source_document,\n \"PostgresBillingStore.getActiveCatalogRevision.config\",\n ),\n };\n }\n\n async getActiveCatalogDocument(): Promise<JsonObject | null> {\n return (await this.getActiveCatalogRevision())?.config ?? null;\n }\n\n async pseudonymizeFinancialSubject(userId: string): Promise<boolean> {\n const rows = await this.queryFn(\n `SELECT bursar.pseudonymize_financial_subject($1::uuid) AS pseudonymized`,\n [userId],\n );\n return requireResultField(\n rows,\n \"pseudonymized\",\n pgBoolean,\n \"PostgresBillingStore.pseudonymizeFinancialSubject\",\n );\n }\n\n async getBillingPreferences(userId: string): Promise<BillingPreferences | null> {\n return this.billingPreferences.get(userId);\n }\n\n async upsertBillingPreferences(prefs: BillingPreferences): Promise<void> {\n await this.billingPreferences.upsert(prefs);\n }\n\n async getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n return this.billingAutoRecharge.getProfile(userId);\n }\n\n async upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void> {\n return this.billingAutoRecharge.upsertProfile(profile, options);\n }\n\n async resumeAutoRechargeProfile(profile: BillingAutoRechargeProfile): Promise<boolean> {\n return this.billingAutoRecharge.resumeProfile(profile);\n }\n\n async claimAutoRechargeAttempt(\n input: AutoRechargeAttemptClaim,\n ): Promise<BillingAutoRechargeAttempt | null> {\n return this.billingAutoRecharge.claimAttempt(input);\n }\n\n async updateAutoRechargeAttempt(input: AutoRechargeAttemptUpdate): Promise<void> {\n return this.billingAutoRecharge.updateAttempt(input);\n }\n\n async updateAutoRechargeAttemptByProviderPayment(\n input: AutoRechargeProviderPaymentUpdate,\n ): Promise<void> {\n return this.billingAutoRecharge.updateAttemptByProviderPayment(input);\n }\n\n async getAutoRechargeOperationalWindow(userId: string): Promise<{\n maxRecharges: number;\n windowStart: string;\n windowEnd: string;\n count: number;\n } | null> {\n return this.billingAutoRecharge.operationalWindow(userId);\n }\n\n async countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number> {\n return this.billingAutoRecharge.countAttempts(userId, since);\n }\n\n async getBillingCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null> {\n const result = await this.billingCustomer.getByUserId(userId, provider ?? null);\n if (!result) return null;\n return {\n provider: result.provider,\n providerCustomerId: result.providerCustomerId,\n };\n }\n}\n"]}
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../../src/billing/postgres/store.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B,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,WAAW,CAAC,MAAM,EAAE,QAAQ,IAAI,IAAI,CAAC,CAAC;QAChF,IAAI,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QACzB,OAAO;YACL,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,kBAAkB,EAAE,MAAM,CAAC,kBAAkB;SAC9C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { PricingDecimal } from \"../../pricing-decimal.js\";\nimport { Decimal } from \"decimal.js\";\nimport { z } from \"zod\";\nimport type { JsonObject, PostgresValue } from \"../../shared/json.js\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeProfile,\n BillingCreditPostingResult,\n BillingCustomerRecord,\n BillingEventClaim,\n BillingOfferResult,\n BillingPaymentRecord,\n BillingPreferences,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionState,\n BillingSubscriptionStatus,\n SubscriptionEntitlementOutcome,\n CheckoutIntent,\n BillingTopupResult,\n ListBillingInvoicesOptions,\n} from \"../types/index.js\";\nimport { BillingStore } from \"../billing-store.js\";\nimport type {\n AutoRechargeAttemptClaim,\n AutoRechargeAttemptUpdate,\n AutoRechargeProviderPaymentUpdate,\n BillingCreditGrantCreate,\n BillingDisputeUpsert,\n BillingInvoiceUpsert,\n BillingPaymentUpsert,\n BillingRefundUpsert,\n BillingSubscriptionChangeUpdate,\n BillingSubscriptionConflictCreate,\n CheckoutIntentCreate,\n CheckoutIntentUpdate,\n} from \"../contracts.js\";\nimport type { QueryFn } from \"../../shared/postgres-types.js\";\nimport {\n PostgresClient,\n normalizeTenantId,\n type PostgresConnectionOptions,\n type PostgresPool,\n type PostgresPoolConstructor,\n} from \"../../shared/postgres-client.js\";\nimport {\n normalizeProviderEnvironment,\n type ProviderEnvironment,\n} from \"../../providers/environment.js\";\nimport { StoreClosedError, StoreError } from \"../../errors.js\";\nimport { optionalBoundedDiagnosticMessage } from \"../../shared/diagnostics.js\";\nimport { requireStableKey } from \"../../shared/idempotency.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireRecordRow,\n requireResultField,\n safeParse,\n} from \"../../shared/postgres-validation.js\";\nimport { BillingOfferRepository, type BillingOfferRow } from \"./repositories/offer.js\";\nimport { BillingTopupRepository, type BillingTopupRow } from \"./repositories/topup.js\";\nimport { BillingCustomerRepository } from \"./repositories/customer.js\";\nimport {\n BillingSubscriptionRepository,\n type SubscriptionRow,\n} from \"./repositories/subscription.js\";\nimport { BillingEventRepository } from \"./repositories/event.js\";\nimport { BillingPaymentRepository } from \"./repositories/payment.js\";\nimport { BillingRefundRepository } from \"./repositories/refund.js\";\nimport { BillingInvoiceRepository } from \"./repositories/invoice.js\";\nimport { BillingDisputeRepository } from \"./repositories/dispute.js\";\nimport { BillingPreferencesRepository } from \"./repositories/preferences.js\";\nimport { BillingAutoRechargeRepository } from \"./repositories/auto-recharge.js\";\nimport { BillingSubscriptionChangeRepository } from \"./repositories/subscription-change.js\";\n\nconst PgSafeMinorUnitsSchema = z\n .union([z.string().regex(/^\\d+$/), z.number().int().nonnegative().safe()])\n .transform(Number)\n .refine(Number.isSafeInteger, \"minor-unit amount exceeds JavaScript's safe integer range\");\n\nconst BillingCreditPostingRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n balance_after: z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .nullable()\n .transform((value) => (value === null ? null : new PricingDecimal(value))),\n replayed: pgBoolean,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.error_code === null && (row.ledger_entry_id === null || row.balance_after === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"successful posting requires ledger_entry_id and balance_after\",\n });\n }\n });\n\nconst CheckoutIntentRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n checkout_kind: z.enum([\"subscription\", \"credit_topup\"]),\n product_key: z.string().min(1),\n request_digest: z.instanceof(Uint8Array).refine((value) => value.byteLength === 32),\n status: z.enum([\"open\", \"completed\", \"failed\", \"expired\"]),\n provider_session_id: z.string().min(1).nullable(),\n provider_customer_id: z.string().min(1).nullable(),\n checkout_url: z.string().min(1).nullable(),\n expires_at: z.union([z.string().datetime({ offset: true }), z.date()]),\n })\n .strict();\n\nfunction billingCreditPostingResult(\n rows: readonly PostgresValue[] | null | undefined,\n context: string,\n): BillingCreditPostingResult {\n const raw = requireRecordRow(rows, context);\n const row = safeParse(\n BillingCreditPostingRowSchema,\n {\n ledger_entry_id: raw.ledger_entry_id,\n balance_after: raw.balance_after,\n replayed: raw.replayed,\n error_code: raw.error_code,\n },\n context,\n { indeterminate: true },\n );\n return {\n ledgerEntryId: row.ledger_entry_id,\n balanceAfter: row.balance_after,\n replayed: row.replayed,\n errorCode: row.error_code,\n };\n}\n\nexport interface PostgresBillingStoreOptions extends Omit<\n PostgresConnectionOptions,\n \"providerEnvironment\"\n> {\n /** PostgreSQL connection string or an application-owned pool. */\n postgres: PostgresPool | string;\n /** Tenant UUID bound to every store transaction. */\n tenantId: string;\n /** Explicit financial namespace; billing stores never guess live vs test. */\n providerEnvironment: ProviderEnvironment;\n /** Injectable `pg.Pool` constructor for custom runtimes and tests. */\n poolConstructor?: PostgresPoolConstructor;\n billingPayloadBackend?: \"postgres\" | \"s3\";\n}\n\nconst transactionScope = Symbol(\"billing transaction scope\");\ntype ScopedBillingOptions = PostgresBillingStoreOptions & {\n [transactionScope]?: { postgres: PostgresClient; query: QueryFn };\n};\n\nexport class PostgresBillingStore extends BillingStore {\n readonly tenantId: string;\n private readonly postgres: PostgresClient;\n private readonly scoped: boolean;\n private readonly options: PostgresBillingStoreOptions;\n readonly providerEnvironment: ProviderEnvironment;\n\n private readonly queryFn: QueryFn;\n private readonly billingOffer: BillingOfferRepository;\n private readonly billingTopup: BillingTopupRepository;\n private readonly billingCustomer: BillingCustomerRepository;\n private readonly billingSubscription: BillingSubscriptionRepository;\n private readonly billingEvent: BillingEventRepository;\n private readonly billingPayment: BillingPaymentRepository;\n private readonly billingRefund: BillingRefundRepository;\n private readonly billingInvoice: BillingInvoiceRepository;\n private readonly billingDispute: BillingDisputeRepository;\n private readonly billingPreferences: BillingPreferencesRepository;\n private readonly billingAutoRecharge: BillingAutoRechargeRepository;\n private readonly billingSubscriptionChange: BillingSubscriptionChangeRepository;\n\n constructor(options: PostgresBillingStoreOptions) {\n super();\n // SAFETY: Only this module can attach the private transaction scope symbol.\n const scope = (options as ScopedBillingOptions)[transactionScope];\n this.options = { ...options };\n this.scoped = scope !== undefined;\n if (!z.object({}).safeParse(options).success) {\n throw new TypeError(\"PostgresBillingStore options are required\");\n }\n if (!z.string().safeParse(options.postgres).success && options.poolConstructor !== undefined) {\n throw new TypeError(\"poolConstructor cannot be used with an existing PostgreSQL pool\");\n }\n this.tenantId = normalizeTenantId(options.tenantId);\n this.providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);\n this.postgres =\n scope?.postgres ??\n new PostgresClient(options.postgres, {\n tenantId: this.tenantId,\n providerEnvironment: this.providerEnvironment,\n poolConstructor: options.poolConstructor,\n billingPayloadBackend: options.billingPayloadBackend,\n connectionTimeoutMs: options.connectionTimeoutMs,\n statementTimeoutMs: options.statementTimeoutMs,\n idleTransactionTimeoutMs: options.idleTransactionTimeoutMs,\n idleTimeoutMs: options.idleTimeoutMs,\n maxConnections: options.maxConnections,\n applicationName: options.applicationName,\n onPoolError: options.onPoolError,\n instrumentation: options.instrumentation,\n closedError: () => new StoreClosedError(\"Billing store has been closed\"),\n });\n this.queryFn = scope?.query ?? this.postgres.query;\n this.billingOffer = new BillingOfferRepository(this.queryFn);\n this.billingTopup = new BillingTopupRepository(this.queryFn);\n this.billingCustomer = new BillingCustomerRepository(this.queryFn);\n this.billingSubscription = new BillingSubscriptionRepository(this.queryFn);\n this.billingEvent = new BillingEventRepository(this.queryFn);\n this.billingPayment = new BillingPaymentRepository(this.queryFn);\n this.billingRefund = new BillingRefundRepository(this.queryFn);\n this.billingInvoice = new BillingInvoiceRepository(this.queryFn);\n this.billingDispute = new BillingDisputeRepository(this.queryFn);\n this.billingPreferences = new BillingPreferencesRepository(this.queryFn);\n this.billingAutoRecharge = new BillingAutoRechargeRepository(this.queryFn);\n this.billingSubscriptionChange = new BillingSubscriptionChangeRepository(this.queryFn);\n }\n\n override async withBillingEventTransaction<T>(\n action: (store: BillingStore) => Promise<T>,\n ): Promise<T> {\n if (this.scoped) throw new TypeError(\"Nested billing event transactions are not supported\");\n return this.postgres.withTransaction(async (transactionQuery) => {\n let active = true;\n const queryFn: QueryFn = (text, params) => {\n if (!active) throw new StoreClosedError(\"Billing transaction has ended\");\n return transactionQuery(text, params);\n };\n const options: ScopedBillingOptions = {\n ...this.options,\n [transactionScope]: { postgres: this.postgres, query: queryFn },\n };\n const scoped = new PostgresBillingStore(options);\n try {\n return await action(scoped);\n } finally {\n active = false;\n }\n });\n }\n\n override async observeBillingInvoiceOutcome(\n provider: string,\n invoiceId: string,\n outcome: \"paid\" | \"failed\",\n ): Promise<boolean> {\n const rows = await this.queryFn(\n \"SELECT bursar.observe_billing_invoice_outcome($1, $2, $3) AS accepted\",\n [provider, invoiceId, outcome],\n );\n return requireResultField(rows, \"accepted\", pgBoolean, \"observeBillingInvoiceOutcome\");\n }\n\n async close(): Promise<void> {\n if (this.scoped) throw new TypeError(\"Cannot close a scoped billing store\");\n await this.postgres.close();\n }\n\n async createOrGetCheckoutIntent(input: CheckoutIntentCreate): Promise<CheckoutIntent> {\n const operationKey = requireStableKey(input.operationKey, \"operationKey\");\n if (!/^[0-9a-fA-F]{64}$/.test(input.requestDigest)) {\n throw new TypeError(\"requestDigest must be a 32-byte hex string\");\n }\n const rows = await this.queryFn(\n `SELECT bursar.create_checkout_intent(\n $1::uuid, $2, $3, $4, $5, decode($6, 'hex'), $7::timestamptz, NULL, NULL, $8, $9::uuid, $10::uuid, $11\n ) AS id`,\n [\n input.subjectId,\n input.provider,\n operationKey,\n input.checkoutKind,\n input.productKey,\n input.requestDigest,\n input.expiresAt,\n input.region ?? null,\n input.expectedRevisionId ?? null,\n input.accountId ?? input.subjectId,\n input.providerCustomerId ?? null,\n ],\n );\n const id = requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createOrGetCheckoutIntent\",\n );\n const intent = await this.getCheckoutIntent(id, input.subjectId);\n if (!intent) {\n throw new StoreError(\"checkout intent could not be read after creation\", {\n indeterminate: true,\n details: { checkoutIntentId: id },\n });\n }\n return intent;\n }\n\n async updateCheckoutIntent(id: string, update: CheckoutIntentUpdate): Promise<void> {\n const rows = await this.queryFn(\n `SELECT bursar.advance_checkout_intent($1::uuid, $2, $3, $4, $5, $6::uuid) AS advanced`,\n [\n id,\n update.status ?? null,\n update.providerSessionId ?? null,\n update.checkoutUrl ?? null,\n update.expectedOwner?.provider ?? null,\n update.expectedOwner?.accountId ?? null,\n ],\n );\n if (\n !requireResultField(rows, \"advanced\", pgBoolean, \"PostgresBillingStore.updateCheckoutIntent\")\n ) {\n throw new StoreError(`checkout intent transition rejected: ${id}`, {\n details: { checkoutIntentId: id },\n });\n }\n }\n\n override async findCheckoutIntent(\n subjectId: string,\n operationKey: string,\n provider?: string,\n ): Promise<{ intent: CheckoutIntent; catalog: JsonObject } | null> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.find_checkout_intent($1::uuid, $2, $3)\", [\n subjectId,\n operationKey,\n provider ?? null,\n ]);\n if (rows.length === 0) return null;\n if (rows.length !== 1)\n throw new StoreError(\"checkout operation key matches multiple providers\");\n const row = rows[0]!;\n const id = safeParse(postgresUuid, row.intent_id, \"findCheckoutIntent.id\");\n const catalog = safeParse(\n z.record(z.string(), z.json()),\n row.source_document,\n \"findCheckoutIntent.catalog\",\n );\n const intent = await this.getCheckoutIntent(id, subjectId);\n if (!intent) throw new StoreError(\"checkout intent disappeared\");\n return { intent, catalog };\n }\n\n async getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_checkout_intent($1::uuid, $2::uuid)`,\n [id, subjectId],\n );\n if (rows.length === 0) return null;\n if (rows.length !== 1) {\n throw new StoreError(\"getCheckoutIntent: expected at most one row\", {\n details: { rowCount: rows.length, checkoutIntentId: id },\n });\n }\n const row = rows[0];\n if (!row) throw new StoreError(\"getCheckoutIntent: expected one row\");\n return this.rowToCheckoutIntent(\n safeParse(\n CheckoutIntentRowSchema,\n {\n id: row.id,\n subject_id: row.subject_id,\n provider: row.provider,\n checkout_kind: row.checkout_kind,\n product_key: row.product_key,\n request_digest: row.request_digest,\n status: row.status,\n provider_session_id: row.provider_session_id,\n provider_customer_id: row.provider_customer_id,\n checkout_url: row.checkout_url,\n expires_at: row.expires_at,\n },\n \"PostgresBillingStore.getCheckoutIntent\",\n ),\n );\n }\n\n private rowToCheckoutIntent(row: z.infer<typeof CheckoutIntentRowSchema>): CheckoutIntent {\n return {\n id: row.id,\n subjectId: row.subject_id,\n provider: row.provider,\n checkoutKind: row.checkout_kind,\n productKey: row.product_key,\n requestDigest: Buffer.from(row.request_digest).toString(\"hex\"),\n status: row.status,\n providerSessionId: row.provider_session_id,\n providerCustomerId: row.provider_customer_id,\n checkoutUrl: row.checkout_url,\n expiresAt: row.expires_at instanceof Date ? row.expires_at.toISOString() : row.expires_at,\n };\n }\n\n private rowToOffer(row: BillingOfferRow | null): BillingOfferResult | null {\n if (!row) return null;\n return {\n offerId: row.id,\n offerKey: row.offerKey,\n planId: row.planId,\n plan: row.plan,\n interval: row.interval,\n intervalCount: row.intervalCount,\n grant:\n row.grantCredits === null\n ? null\n : {\n mode: \"cycle_grant\",\n credits: row.grantCredits,\n bucket: row.grantBucket,\n replacePrior: row.grantReplacePrior,\n },\n };\n }\n\n async resolveBillingOffer(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n checkout?: {\n accountId: string;\n intentId: string;\n lookupKey?: string | null;\n },\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByPrice(\n provider,\n priceId ?? null,\n productId ?? null,\n checkout,\n );\n return this.rowToOffer(r);\n }\n\n async resolveBillingOfferByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByLookup(provider, lookupKey);\n return this.rowToOffer(r);\n }\n\n async claimBillingEvent(\n provider: string,\n eventId: string,\n eventType: string,\n envelope?: JsonObject,\n ): Promise<BillingEventClaim> {\n const result = await this.billingEvent.claim(\n provider,\n eventId,\n eventType,\n JSON.stringify(envelope ?? { eventType }),\n );\n if (result.status === \"claimed\") {\n if (result.claim_token === null || result.event_id === null) {\n throw new StoreError(\"Billing event claim returned no claim identifiers\", {\n details: { provider, eventId },\n });\n }\n return {\n status: \"claimed\" as const,\n claimToken: result.claim_token,\n billingEventId: result.event_id,\n };\n }\n if (result.status === \"duplicate\") return { status: \"duplicate\" as const };\n if (result.status === \"busy\") return { status: \"busy\" as const };\n if (result.status === \"invalid_request\") return { status: \"invalid_request\" as const };\n if (result.status === \"idempotency_conflict\" || result.status === \"max_retries_exceeded\") {\n if (result.event_id === null) {\n throw new StoreError(\"Billing event terminal claim returned no event identifier\", {\n details: { provider, eventId, status: result.status },\n });\n }\n return { status: result.status, billingEventId: result.event_id };\n }\n throw new StoreError(\"Billing event claim returned an unsupported status\", {\n details: { provider, eventId, status: result.status },\n });\n }\n\n async completeBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n ): Promise<boolean> {\n return this.billingEvent.complete(provider, eventId, claimToken);\n }\n\n async failBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n error?: string,\n ): Promise<boolean> {\n return this.billingEvent.fail(\n provider,\n eventId,\n claimToken,\n optionalBoundedDiagnosticMessage(error) ?? undefined,\n );\n }\n\n async upsertBillingCustomer(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email?: string | null,\n ): Promise<void> {\n await this.billingCustomer.upsert(provider, providerCustomerId, userId, email ?? null);\n }\n\n async upsertBillingSubscription(state: BillingSubscriptionState): Promise<void> {\n await this.billingSubscription.upsert(state);\n }\n\n async getBillingCustomer(provider: string, providerCustomerId: string): Promise<string | null> {\n return this.billingCustomer.get(provider, providerCustomerId);\n }\n\n async getBillingSubscription(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.get(provider, providerSubscriptionId);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async createBillingSubscriptionChange(\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n const subscription = await this.billingSubscription.get(\n input.provider,\n input.providerSubscriptionId,\n );\n if (!subscription?.id) {\n throw new StoreError(\"subscription change requires a persisted subscription\", {\n retryable: true,\n details: {\n provider: input.provider,\n providerSubscriptionId: input.providerSubscriptionId,\n },\n });\n }\n return this.billingSubscriptionChange.create(subscription.id, input);\n }\n\n async findBillingSubscriptionChange(\n provider: string,\n subscriptionId: string,\n operationKey: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.billingSubscriptionChange.find(provider, subscriptionId, operationKey);\n }\n\n async getOpenBillingSubscriptionChange(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.billingSubscriptionChange.getOpen(provider, providerSubscriptionId);\n }\n\n async listExpiredGraceSubscriptions(\n now: string,\n limit = 100,\n ): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.listExpiredGraceSubscriptions(now, limit);\n return rows.map((row) => this.rowToSubscriptionState(row));\n }\n\n async reconcileSubscriptionEntitlement(\n subjectId: string,\n subscriptionId: string,\n billingEventId: string,\n expectedStatus: BillingSubscriptionStatus,\n expectedProviderUpdatedAt: string,\n planAssignedAt: Date | string | null,\n applyEntitlement: boolean,\n reason: string,\n ): Promise<SubscriptionEntitlementOutcome> {\n return this.billingSubscription.reconcileEntitlement(\n subjectId,\n subscriptionId,\n billingEventId,\n expectedStatus,\n expectedProviderUpdatedAt,\n planAssignedAt,\n applyEntitlement,\n reason,\n );\n }\n\n async expireSubscriptionGracePeriod(\n subjectId: string,\n subscriptionId: string,\n expectedGraceEndsAt: string,\n expiredAt: string,\n ): Promise<boolean> {\n return this.billingSubscription.expireGracePeriod(\n subjectId,\n subscriptionId,\n expectedGraceEndsAt,\n expiredAt,\n );\n }\n\n async updateBillingSubscriptionChange(\n id: string,\n update: BillingSubscriptionChangeUpdate,\n ): Promise<void> {\n await this.billingSubscriptionChange.update(id, update);\n }\n\n async getUserSubscription(\n userId: string,\n statuses?: string[],\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.getUserSubscription(userId, statuses);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async getUserSubscriptions(userId: string): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.getUserSubscriptions(userId);\n return rows.map((r) => this.rowToSubscriptionState(r));\n }\n\n async recordSubscriptionConflict(input: BillingSubscriptionConflictCreate): Promise<void> {\n await this.billingSubscription.recordConflict(input);\n }\n\n private rowToTopup(r: BillingTopupRow | null): BillingTopupResult | null {\n if (!r) return null;\n const minAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.min_quantity,\n \"PostgresBillingStore.rowToTopup.minAmountMinor\",\n );\n const maxAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.max_quantity,\n \"PostgresBillingStore.rowToTopup.maxAmountMinor\",\n );\n return {\n topupId: r.id,\n topupKey: r.topup_key,\n creditsPerUnit: r.credits_per_unit,\n depositTo: r.bucket_key,\n amountMinor: r.amount_minor,\n taxBehavior: r.tax_behavior,\n currency: r.currency,\n minQuantity: r.min_quantity,\n maxQuantity: r.max_quantity,\n defaultQuantity: r.default_quantity,\n minAmountMinor,\n maxAmountMinor,\n };\n }\n\n async resolveCreditTopup(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n checkoutIntentId?: string | null,\n subjectId?: string | null,\n providerPaymentId?: string | null,\n rechargeAttemptId?: string | null,\n billingEventId?: string | null,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByPrice(\n provider,\n priceId ?? null,\n productId ?? null,\n checkoutIntentId,\n subjectId,\n providerPaymentId,\n rechargeAttemptId,\n billingEventId,\n );\n return this.rowToTopup(r);\n }\n\n async resolveCreditTopupByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByLookup(provider, lookupKey);\n return this.rowToTopup(r);\n }\n\n async upsertBillingPayment(options: BillingPaymentUpsert): Promise<string> {\n return this.billingPayment.upsert(options);\n }\n\n async createBillingCreditGrant(input: BillingCreditGrantCreate): Promise<string> {\n const rows = await this.queryFn(\n \"SELECT bursar.create_billing_credit_grant($1::uuid, $2::uuid, $3::uuid, $4, $5, $6::uuid) AS id\",\n [\n input.paymentId ?? null,\n input.subscriptionId ?? null,\n input.topupId ?? null,\n input.configuredCredits.toString(),\n input.quantity,\n input.billingEventId ?? null,\n ],\n );\n return requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createBillingCreditGrant\",\n );\n }\n\n async grantBillingCredit(\n grantId: string,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.grant_billing_credit($1::uuid, $2)\", [\n grantId,\n idempotencyKey,\n ]);\n return billingCreditPostingResult(rows, \"PostgresBillingStore.grantBillingCredit\");\n }\n\n async getBillingCreditGrantByPayment(paymentId: string): Promise<string | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_billing_credit_grant_by_payment($1::uuid)`,\n [paymentId],\n );\n const row = optionalRecordRow(rows, \"PostgresBillingStore.getBillingCreditGrantByPayment\");\n return row === null\n ? null\n : safeParse(postgresUuid, row.id, \"PostgresBillingStore.getBillingCreditGrantByPayment.id\");\n }\n\n async postBillingRefund(\n refundId: string,\n grantId: string,\n amountMinor: number,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\n \"SELECT * FROM bursar.post_billing_refund($1::uuid, $2::uuid, $3, $4)\",\n [refundId, grantId, amountMinor, idempotencyKey],\n );\n return billingCreditPostingResult(rows, \"PostgresBillingStore.postBillingRefund\");\n }\n\n async upsertBillingRefund(options: BillingRefundUpsert): Promise<string> {\n return this.billingRefund.upsert(\n options.provider,\n options.providerRefundId,\n options.providerPaymentId,\n options.userId,\n options.amountMinor,\n options.currency,\n options.reason ?? null,\n options.metadata ? JSON.stringify(options.metadata) : null,\n options.status,\n options.providerUpdatedAt,\n );\n }\n\n async upsertBillingInvoice(options: BillingInvoiceUpsert): Promise<void> {\n const subscription = options.providerSubscriptionId\n ? await this.billingSubscription.get(options.provider, options.providerSubscriptionId)\n : null;\n if (options.providerSubscriptionId && !subscription) {\n throw new StoreError(\"invoice subscription is not available\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerInvoiceId: options.providerInvoiceId,\n providerSubscriptionId: options.providerSubscriptionId ?? null,\n },\n });\n }\n await this.billingInvoice.upsert(\n options.userId,\n options.provider,\n options.providerInvoiceId,\n subscription?.id ? String(subscription.id) : null,\n options.status,\n options.amountDueMinor,\n options.amountPaidMinor,\n options.currency,\n options.periodStart ?? null,\n options.periodEnd ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async listBillingInvoices(userId: string, options?: ListBillingInvoicesOptions) {\n return this.billingInvoice.listForUser(userId, options);\n }\n\n async hasBillingInvoice(userId: string, provider: string, providerInvoiceId: string) {\n return this.billingInvoice.hasForUser(userId, provider, providerInvoiceId);\n }\n\n async upsertBillingDispute(options: BillingDisputeUpsert): Promise<void> {\n const payment = await this.billingPayment.getForRefund(\n options.provider,\n options.providerPaymentId,\n );\n if (!payment?.id) {\n throw new StoreError(\"dispute payment is required\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerDisputeId: options.providerDisputeId,\n providerPaymentId: options.providerPaymentId ?? null,\n },\n });\n }\n await this.billingDispute.upsert(\n options.provider,\n options.providerDisputeId,\n String(payment.id),\n options.status,\n options.reason ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async getBillingPayment(\n provider: string,\n providerPaymentId: string,\n ): Promise<BillingPaymentRecord | null> {\n const row = await this.billingPayment.getForRefund(provider, providerPaymentId);\n if (!row) return null;\n return {\n id: row.id,\n provider: row.provider,\n providerPaymentId: row.provider_payment_id,\n providerInvoiceId: row.provider_invoice_id,\n userId: row.subject_id,\n amountMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.amount_minor,\n \"PostgresBillingStore.getBillingPayment.amountMinor\",\n ),\n taxMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.tax_minor,\n \"PostgresBillingStore.getBillingPayment.taxMinor\",\n ),\n currency: row.currency,\n purpose: row.purpose,\n status: row.status,\n providerUpdatedAt:\n row.provider_updated_at instanceof Date\n ? row.provider_updated_at.toISOString()\n : row.provider_updated_at,\n metadata: row.metadata,\n };\n }\n\n private rowToSubscriptionState(r: SubscriptionRow): BillingSubscriptionState {\n return {\n cycleGrantCredits:\n r.cycle_grant_amount == null ? null : new PricingDecimal(r.cycle_grant_amount),\n subscriptionId: r.id,\n userId: r.user_id,\n provider: r.provider,\n providerSubscriptionId: r.provider_subscription_id,\n providerCustomerId: r.provider_customer_id,\n offerId: r.offer_id,\n offerKey: r.offer_key,\n planId: r.plan_id,\n plan: r.plan,\n status: r.status,\n currentPeriodStart: r.current_period_start,\n currentPeriodEnd: r.current_period_end,\n trialEnd: r.trial_end,\n cancelAt: r.cancel_at,\n endedAt: r.ended_at,\n graceEndsAt: r.grace_ends_at,\n graceExpiredAt: r.grace_expired_at,\n providerUpdatedAt: r.provider_updated_at,\n cancelAtPeriodEnd: r.cancel_at_period_end,\n interval: r.interval,\n intervalCount: r.interval_count,\n metadata: r.metadata,\n };\n }\n\n async getActiveCatalogRevision(): Promise<{\n id: string;\n config: JsonObject;\n } | null> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.active_catalog_revision()\", []);\n const row = optionalRecordRow(rows, \"PostgresBillingStore.getActiveCatalogRevision\");\n if (row === null) return null;\n return {\n id: safeParse(postgresUuid, row.id, \"PostgresBillingStore.getActiveCatalogRevision.id\"),\n config: safeParse(\n z.record(z.string(), z.json()),\n row.source_document,\n \"PostgresBillingStore.getActiveCatalogRevision.config\",\n ),\n };\n }\n\n async getActiveCatalogDocument(): Promise<JsonObject | null> {\n return (await this.getActiveCatalogRevision())?.config ?? null;\n }\n\n async pseudonymizeFinancialSubject(userId: string): Promise<boolean> {\n const rows = await this.queryFn(\n `SELECT bursar.pseudonymize_financial_subject($1::uuid) AS pseudonymized`,\n [userId],\n );\n return requireResultField(\n rows,\n \"pseudonymized\",\n pgBoolean,\n \"PostgresBillingStore.pseudonymizeFinancialSubject\",\n );\n }\n\n async getBillingPreferences(userId: string): Promise<BillingPreferences | null> {\n return this.billingPreferences.get(userId);\n }\n\n async upsertBillingPreferences(prefs: BillingPreferences): Promise<void> {\n await this.billingPreferences.upsert(prefs);\n }\n\n async getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n return this.billingAutoRecharge.getProfile(userId);\n }\n\n async upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void> {\n return this.billingAutoRecharge.upsertProfile(profile, options);\n }\n\n async resumeAutoRechargeProfile(profile: BillingAutoRechargeProfile): Promise<boolean> {\n return this.billingAutoRecharge.resumeProfile(profile);\n }\n\n async claimAutoRechargeAttempt(\n input: AutoRechargeAttemptClaim,\n ): Promise<BillingAutoRechargeAttempt | null> {\n return this.billingAutoRecharge.claimAttempt(input);\n }\n\n async updateAutoRechargeAttempt(input: AutoRechargeAttemptUpdate): Promise<void> {\n return this.billingAutoRecharge.updateAttempt(input);\n }\n\n async updateAutoRechargeAttemptByProviderPayment(\n input: AutoRechargeProviderPaymentUpdate,\n ): Promise<boolean> {\n return this.billingAutoRecharge.updateAttemptByProviderPayment(input);\n }\n\n async getAutoRechargeOperationalWindow(userId: string): Promise<{\n maxRecharges: number;\n windowStart: string;\n windowEnd: string;\n count: number;\n } | null> {\n return this.billingAutoRecharge.operationalWindow(userId);\n }\n\n async countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number> {\n return this.billingAutoRecharge.countAttempts(userId, since);\n }\n\n async getBillingCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null> {\n const result = await this.billingCustomer.getByUserId(userId, provider ?? null);\n if (!result) return null;\n return {\n provider: result.provider,\n providerCustomerId: result.providerCustomerId,\n };\n }\n}\n"]}
@@ -20,6 +20,7 @@ export interface BillingTopupResult {
20
20
  creditsPerUnit: Decimal;
21
21
  depositTo: string;
22
22
  amountMinor: number;
23
+ taxBehavior: "inclusive" | "exclusive" | "unspecified";
23
24
  currency: string;
24
25
  minQuantity: number;
25
26
  maxQuantity: number;