@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,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { utcTimestamp } from "../../../shared/timestamp.js";
2
3
  import { StoreError } from "../../../errors.js";
3
4
  import { optionalRecordRow, pgBoolean, postgresUuid, requireResultField, safeParse, } from "../../../shared/postgres-validation.js";
4
5
  const timestamp = z
@@ -6,7 +7,9 @@ const timestamp = z
6
7
  z.date().refine((value) => !Number.isNaN(value.getTime())),
7
8
  z.string().datetime({ offset: true }),
8
9
  ])
9
- .transform((value) => (value instanceof Date ? value : new Date(value)).toISOString());
10
+ .transform((value) => value instanceof Date
11
+ ? value.toISOString()
12
+ : utcTimestamp(value).replace(/(\.\d{3})000Z$/, "$1Z"));
10
13
  const SubscriptionStatusSchema = z.enum([
11
14
  "incomplete",
12
15
  "incomplete_expired",
@@ -41,12 +44,6 @@ const PersistedSubscriptionRowSchema = z
41
44
  metadata: z.record(z.string(), z.json()),
42
45
  })
43
46
  .strict();
44
- const CatalogReferenceSchema = z
45
- .object({
46
- offer_id: postgresUuid,
47
- catalog_revision_id: postgresUuid,
48
- })
49
- .strict();
50
47
  const OfferContextSchema = z
51
48
  .object({
52
49
  offer_key: z.string().min(1),
@@ -54,6 +51,7 @@ const OfferContextSchema = z
54
51
  plan_key: z.string().min(1),
55
52
  billing_unit: z.enum(["day", "week", "month", "year"]),
56
53
  billing_count: z.number().int().positive(),
54
+ cycle_grant_amount: z.union([z.string(), z.number()]).nullable().optional(),
57
55
  })
58
56
  .strict();
59
57
  const SubscriptionRowSchema = z
@@ -79,6 +77,7 @@ const SubscriptionRowSchema = z
79
77
  cancel_at_period_end: pgBoolean,
80
78
  interval: z.enum(["day", "week", "month", "year"]),
81
79
  interval_count: z.number().int().positive(),
80
+ cycle_grant_amount: z.union([z.string(), z.number()]).nullable().optional(),
82
81
  metadata: z.record(z.string(), z.json()),
83
82
  })
84
83
  .strict();
@@ -105,6 +104,12 @@ function persistedSubscription(row, context) {
105
104
  metadata: value.metadata,
106
105
  }, context);
107
106
  }
107
+ function subscriptionWithOfferSql(source) {
108
+ return `SELECT s.*, to_char(s.provider_updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS provider_updated_at,
109
+ offer.offer_key, offer.plan_id, offer.plan_key, offer.billing_unit, offer.billing_count, offer.cycle_grant_amount
110
+ FROM ${source} s
111
+ LEFT JOIN LATERAL bursar.get_catalog_offer_context(s.offer_id, s.catalog_revision_id) offer ON true`;
112
+ }
108
113
  export class BillingSubscriptionRepository {
109
114
  query;
110
115
  constructor(query) {
@@ -119,7 +124,7 @@ export class BillingSubscriptionRepository {
119
124
  if (!provider || !providerSubscriptionId) {
120
125
  throw new TypeError("subscription.upsert: subject, provider, subscription, and offer are required");
121
126
  }
122
- const existing = await this.query(`SELECT * FROM bursar.get_billing_subscription_by_provider($1, $2)`, [provider, providerSubscriptionId]);
127
+ const existing = await this.query(`SELECT s.*, to_char(s.provider_updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS provider_updated_at FROM bursar.get_billing_subscription_by_provider($1, $2) s`, [provider, providerSubscriptionId]);
123
128
  const rawExisting = optionalRecordRow(existing, "BillingSubscriptionRepository.upsert.existing");
124
129
  const existingRow = rawExisting === null
125
130
  ? null
@@ -143,7 +148,7 @@ export class BillingSubscriptionRepository {
143
148
  throw new TypeError("subscription.upsert: subject, provider, subscription, and offer are required");
144
149
  }
145
150
  const providerUpdatedAt = safeParse(timestamp, state.providerUpdatedAt, "BillingSubscriptionRepository.upsert.providerUpdatedAt");
146
- const rows = await this.query("SELECT bursar.upsert_billing_subscription($1::uuid,$2,$3,$4,$5::uuid,$6::bursar.billing_subscription_status,$7,$8,$9,$10::jsonb,$11,$12,$13,$14,$15) AS id", [
151
+ const rows = await this.query("SELECT bursar.upsert_billing_subscription($1::uuid,$2,$3,$4,$5::uuid,$6::bursar.billing_subscription_status,$7,$8,$9,$10::jsonb,$11,$12,$13,$14,$15,$16::uuid) AS id", [
147
152
  userId,
148
153
  provider,
149
154
  providerSubscriptionId,
@@ -159,7 +164,13 @@ export class BillingSubscriptionRepository {
159
164
  state.endedAt ?? null,
160
165
  providerUpdatedAt,
161
166
  state.graceEndsAt ?? null,
167
+ state.billingEventId ?? null,
162
168
  ]);
169
+ if (rows.length === 1 && rows[0]?.id === null) {
170
+ throw new StoreError("A blocking subscription already exists for this provider", {
171
+ details: { reason: "blocking_subscription_conflict" },
172
+ });
173
+ }
163
174
  requireResultField(rows, "id", postgresUuid, "BillingSubscriptionRepository.upsert");
164
175
  }
165
176
  map(row) {
@@ -186,18 +197,17 @@ export class BillingSubscriptionRepository {
186
197
  cancel_at_period_end: r.cancel_at_period_end,
187
198
  interval: r.interval,
188
199
  interval_count: r.interval_count,
200
+ cycle_grant_amount: r.cycle_grant_amount,
189
201
  metadata: r.metadata,
190
202
  }, "BillingSubscriptionRepository");
191
203
  }
192
- async withOfferContext(value) {
193
- const reference = safeParse(CatalogReferenceSchema, { offer_id: value.offer_id, catalog_revision_id: value.catalog_revision_id }, "BillingSubscriptionRepository.withOfferContext.reference");
194
- const contextRows = await this.query(`SELECT * FROM bursar.get_catalog_offer_context($1::uuid, $2::uuid)`, [reference.offer_id, reference.catalog_revision_id]);
195
- const rawContext = optionalRecordRow(contextRows, "BillingSubscriptionRepository.withOfferContext");
196
- if (rawContext === null) {
204
+ withOfferContext(rawContext) {
205
+ const value = persistedSubscription(rawContext, "BillingSubscriptionRepository.subscription");
206
+ if (rawContext.offer_key == null) {
197
207
  throw new StoreError("Billing subscription offer context is missing", {
198
208
  details: {
199
- offerId: reference.offer_id,
200
- catalogRevisionId: reference.catalog_revision_id,
209
+ offerId: value.offer_id,
210
+ catalogRevisionId: value.catalog_revision_id,
201
211
  },
202
212
  });
203
213
  }
@@ -207,6 +217,7 @@ export class BillingSubscriptionRepository {
207
217
  plan_key: rawContext.plan_key,
208
218
  billing_unit: rawContext.billing_unit,
209
219
  billing_count: rawContext.billing_count,
220
+ cycle_grant_amount: rawContext.cycle_grant_amount ?? null,
210
221
  }, "BillingSubscriptionRepository.withOfferContext.context");
211
222
  return {
212
223
  ...value,
@@ -217,40 +228,26 @@ export class BillingSubscriptionRepository {
217
228
  };
218
229
  }
219
230
  async get(provider, providerSubscriptionId) {
220
- const rows = await this.query(`SELECT * FROM bursar.get_billing_subscription_by_provider($1, $2)`, [provider, providerSubscriptionId]);
231
+ const rows = await this.query(`${subscriptionWithOfferSql("bursar.get_billing_subscription_by_provider($1, $2)")}`, [provider, providerSubscriptionId]);
221
232
  const row = optionalRecordRow(rows, "BillingSubscriptionRepository.get");
222
- return row === null
223
- ? null
224
- : this.map(await this.withOfferContext(persistedSubscription(row, "BillingSubscriptionRepository.get")));
233
+ return row === null ? null : this.map(this.withOfferContext(row));
225
234
  }
226
235
  async getUserSubscription(userId, statuses) {
227
- const allowed = new Set(safeParse(z.array(SubscriptionStatusSchema), statuses ?? ["active", "trialing"], "BillingSubscriptionRepository.getUserSubscription.statuses"));
228
- const rows = await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [
229
- userId,
230
- ]);
231
- const candidates = rows
232
- .map((row) => persistedSubscription(row, "BillingSubscriptionRepository.getUserSubscription"))
233
- .filter((row) => allowed.has(row.status))
234
- .sort((left, right) => Date.parse(right.provider_updated_at) - Date.parse(left.provider_updated_at));
235
- const selected = candidates[0];
236
- return selected === undefined ? null : this.map(await this.withOfferContext(selected));
236
+ const allowed = safeParse(z.array(SubscriptionStatusSchema), statuses ?? ["active", "trialing"], "BillingSubscriptionRepository.getUserSubscription.statuses");
237
+ const rows = await this.query(`${subscriptionWithOfferSql("bursar.list_billing_subscriptions($1::uuid)")}
238
+ WHERE s.status::text = ANY($2::text[])
239
+ ORDER BY CASE WHEN s.status::text IN ('canceled', 'expired', 'incomplete_expired') THEN 1 ELSE 0 END,
240
+ s.provider_updated_at DESC, s.id DESC LIMIT 1`, [userId, allowed]);
241
+ const row = optionalRecordRow(rows, "BillingSubscriptionRepository.getUserSubscription");
242
+ return row === null ? null : this.map(this.withOfferContext(row));
237
243
  }
238
244
  async getUserSubscriptions(userId) {
239
- const rows = await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [
240
- userId,
241
- ]);
242
- const persisted = rows.map((row) => persistedSubscription(row, "BillingSubscriptionRepository.getUserSubscriptions"));
243
- const enriched = await Promise.all(persisted.map((row) => this.withOfferContext(row)));
244
- return enriched.map((row) => this.map(row));
245
+ const rows = await this.query(`${subscriptionWithOfferSql("bursar.list_billing_subscriptions($1::uuid)")} ORDER BY s.created_at, s.id`, [userId]);
246
+ return rows.map((row) => this.map(this.withOfferContext(row)));
245
247
  }
246
248
  async listExpiredGraceSubscriptions(now, limit = 100) {
247
- const rows = await this.query(`SELECT * FROM bursar.list_expired_grace_subscriptions($1, $2)`, [
248
- now,
249
- limit,
250
- ]);
251
- const persisted = rows.map((row) => persistedSubscription(row, "BillingSubscriptionRepository.listExpiredGraceSubscriptions"));
252
- const enriched = await Promise.all(persisted.map((row) => this.withOfferContext(row)));
253
- return enriched.map((row) => this.map(row));
249
+ const rows = await this.query(`${subscriptionWithOfferSql("bursar.list_expired_grace_subscriptions($1, $2)")} ORDER BY s.grace_ends_at, s.id`, [now, limit]);
250
+ return rows.map((row) => this.map(this.withOfferContext(row)));
254
251
  }
255
252
  async reconcileEntitlement(subjectId, subscriptionId, billingEventId, expectedStatus, expectedProviderUpdatedAt, planAssignedAt, applyEntitlement, reason) {
256
253
  const expectedTimestamp = safeParse(timestamp, expectedProviderUpdatedAt, "BillingSubscriptionRepository.reconcileEntitlement.expectedProviderUpdatedAt");
@@ -1 +1 @@
1
- {"version":3,"file":"subscription.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAQxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,SAAS,GAAG,CAAC;KAChB,KAAK,CAAC;IACL,CAAC,CAAC,IAAI,EAAE,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,KA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CAAC,sBAAsB,IAAI,IAAI;YACpC,KAAK,CAAC,OAAO,IAAI,IAAI;YACrB,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,QAAQ,IAAI,EAAE,CAAC;SACrC,CACF,CAAC;QACF,OAAO,kBAAkB,CACvB,IAAI,EACJ,IAAI,EACJ,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,MAAM,CAAC,EAChE,8CAA8C,CAC/C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type {\n BillingSubscriptionState,\n BillingSubscriptionStatus,\n SubscriptionEntitlementOutcome,\n} from \"../../types/subscriptions.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { JsonObject, PostgresRow } from \"../../../shared/json.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst timestamp = z\n .union([\n z.date().refine((value) => !Number.isNaN(value.getTime())),\n z.string().datetime({ offset: true }),\n ])\n .transform((value) => (value instanceof Date ? value : new Date(value)).toISOString());\nconst SubscriptionStatusSchema = z.enum([\n \"incomplete\",\n \"incomplete_expired\",\n \"trialing\",\n \"active\",\n \"past_due\",\n \"canceled\",\n \"unpaid\",\n \"paused\",\n \"expired\",\n]);\nconst SubscriptionEntitlementOutcomeSchema = z.enum([\"applied\", \"revoked\", \"preserved\", \"stale\"]);\nconst PersistedSubscriptionRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n provider_subscription_id: z.string().min(1),\n provider_customer_id: z.string().min(1).nullable(),\n offer_id: postgresUuid,\n catalog_revision_id: postgresUuid,\n status: SubscriptionStatusSchema,\n current_period_start: timestamp.nullable(),\n current_period_end: timestamp.nullable(),\n trial_end: timestamp.nullable(),\n cancel_at: timestamp.nullable(),\n ended_at: timestamp.nullable(),\n grace_ends_at: timestamp.nullable(),\n grace_expired_at: timestamp.nullable(),\n provider_updated_at: timestamp,\n cancel_at_period_end: pgBoolean,\n metadata: z.record(z.string(), z.json()),\n })\n .strict();\nconst CatalogReferenceSchema = z\n .object({\n offer_id: postgresUuid,\n catalog_revision_id: postgresUuid,\n })\n .strict();\nconst OfferContextSchema = z\n .object({\n offer_key: z.string().min(1),\n plan_id: postgresUuid,\n plan_key: z.string().min(1),\n billing_unit: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n billing_count: z.number().int().positive(),\n })\n .strict();\n\nconst SubscriptionRowSchema = z\n .object({\n id: postgresUuid,\n user_id: postgresUuid,\n provider: z.string().min(1),\n provider_subscription_id: z.string().min(1),\n provider_customer_id: z.string().min(1).nullable(),\n offer_id: postgresUuid,\n offer_key: z.string().min(1),\n plan_id: postgresUuid,\n plan: z.string().min(1),\n status: SubscriptionStatusSchema,\n current_period_start: timestamp.nullable(),\n current_period_end: timestamp.nullable(),\n trial_end: timestamp.nullable(),\n cancel_at: timestamp.nullable(),\n ended_at: timestamp.nullable(),\n grace_ends_at: timestamp.nullable(),\n grace_expired_at: timestamp.nullable(),\n provider_updated_at: timestamp,\n cancel_at_period_end: pgBoolean,\n interval: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n interval_count: z.number().int().positive(),\n metadata: z.record(z.string(), z.json()),\n })\n .strict();\n\nexport type SubscriptionRow = z.infer<typeof SubscriptionRowSchema>;\ntype PersistedSubscriptionRow = z.infer<typeof PersistedSubscriptionRowSchema>;\ntype EnrichedSubscriptionRow = PersistedSubscriptionRow & {\n offer_key: string;\n plan_id: string;\n plan_key: string;\n billing_unit: \"day\" | \"week\" | \"month\" | \"year\";\n billing_count: number;\n plan: string;\n interval: \"day\" | \"week\" | \"month\" | \"year\";\n interval_count: number;\n};\n\nfunction persistedSubscription(row: PostgresRow, context: string): PersistedSubscriptionRow {\n const value = row;\n return safeParse(\n PersistedSubscriptionRowSchema,\n {\n id: value.id,\n subject_id: value.subject_id,\n provider: value.provider,\n provider_subscription_id: value.provider_subscription_id,\n provider_customer_id: value.provider_customer_id,\n offer_id: value.offer_id,\n catalog_revision_id: value.catalog_revision_id,\n status: value.status,\n current_period_start: value.current_period_start,\n current_period_end: value.current_period_end,\n trial_end: value.trial_end,\n cancel_at: value.cancel_at,\n ended_at: value.ended_at,\n grace_ends_at: value.grace_ends_at,\n grace_expired_at: value.grace_expired_at,\n provider_updated_at: value.provider_updated_at,\n cancel_at_period_end: value.cancel_at_period_end,\n metadata: value.metadata,\n },\n context,\n );\n}\n\nexport class BillingSubscriptionRepository {\n constructor(private query: QueryFn) {}\n\n async upsert(state: BillingSubscriptionState): Promise<void> {\n const provider = state.provider;\n const providerSubscriptionId = state.providerSubscriptionId;\n const userId = state.userId;\n let providerCustomerId = state.providerCustomerId ?? null;\n let offerId = state.offerId ?? null;\n\n if (!provider || !providerSubscriptionId) {\n throw new TypeError(\n \"subscription.upsert: subject, provider, subscription, and offer are required\",\n );\n }\n\n const existing = await this.query(\n `SELECT * FROM bursar.get_billing_subscription_by_provider($1, $2)`,\n [provider, providerSubscriptionId],\n );\n const rawExisting = optionalRecordRow(\n existing,\n \"BillingSubscriptionRepository.upsert.existing\",\n );\n const existingRow =\n rawExisting === null\n ? null\n : persistedSubscription(rawExisting, \"BillingSubscriptionRepository.upsert.existing\");\n if (providerCustomerId === null && existingRow !== null) {\n providerCustomerId = existingRow.provider_customer_id;\n }\n if (offerId === null && existingRow !== null) offerId = existingRow.offer_id;\n\n const offerKey = state.offerKey ?? null;\n if (offerId === null && offerKey !== null) {\n const offerRows = await this.query(`SELECT * FROM bursar.resolve_active_catalog_offer($1)`, [\n offerKey,\n ]);\n const offerRow = optionalRecordRow(offerRows, \"BillingSubscriptionRepository.upsert.offer\");\n if (offerRow !== null) {\n offerId = safeParse(\n postgresUuid,\n offerRow.id,\n \"BillingSubscriptionRepository.upsert.offer.id\",\n );\n }\n }\n\n if (!userId || !offerId) {\n throw new TypeError(\n \"subscription.upsert: subject, provider, subscription, and offer are required\",\n );\n }\n const providerUpdatedAt = safeParse(\n timestamp,\n state.providerUpdatedAt,\n \"BillingSubscriptionRepository.upsert.providerUpdatedAt\",\n );\n\n const rows = await this.query(\n \"SELECT bursar.upsert_billing_subscription($1::uuid,$2,$3,$4,$5::uuid,$6::bursar.billing_subscription_status,$7,$8,$9,$10::jsonb,$11,$12,$13,$14,$15) AS id\",\n [\n userId,\n provider,\n providerSubscriptionId,\n providerCustomerId,\n offerId,\n state.status,\n state.currentPeriodStart ?? null,\n state.currentPeriodEnd ?? null,\n state.cancelAtPeriodEnd,\n JSON.stringify(state.metadata ?? {}),\n state.trialEnd ?? null,\n state.cancelAt ?? null,\n state.endedAt ?? null,\n providerUpdatedAt,\n state.graceEndsAt ?? null,\n ],\n );\n requireResultField(rows, \"id\", postgresUuid, \"BillingSubscriptionRepository.upsert\");\n }\n\n private map(row: EnrichedSubscriptionRow): SubscriptionRow {\n const r = row;\n return safeParse(\n SubscriptionRowSchema,\n {\n id: r.id,\n user_id: r.subject_id,\n provider: r.provider,\n provider_subscription_id: r.provider_subscription_id,\n provider_customer_id: r.provider_customer_id,\n offer_id: r.offer_id,\n offer_key: r.offer_key,\n plan_id: r.plan_id,\n plan: r.plan,\n status: r.status,\n current_period_start: r.current_period_start,\n current_period_end: r.current_period_end,\n trial_end: r.trial_end,\n cancel_at: r.cancel_at,\n ended_at: r.ended_at,\n grace_ends_at: r.grace_ends_at,\n grace_expired_at: r.grace_expired_at,\n provider_updated_at: r.provider_updated_at,\n cancel_at_period_end: r.cancel_at_period_end,\n interval: r.interval,\n interval_count: r.interval_count,\n metadata: r.metadata,\n },\n \"BillingSubscriptionRepository\",\n );\n }\n\n private async withOfferContext(\n value: PersistedSubscriptionRow,\n ): Promise<EnrichedSubscriptionRow> {\n const reference = safeParse(\n CatalogReferenceSchema,\n { offer_id: value.offer_id, catalog_revision_id: value.catalog_revision_id },\n \"BillingSubscriptionRepository.withOfferContext.reference\",\n );\n const contextRows = await this.query(\n `SELECT * FROM bursar.get_catalog_offer_context($1::uuid, $2::uuid)`,\n [reference.offer_id, reference.catalog_revision_id],\n );\n const rawContext = optionalRecordRow(\n contextRows,\n \"BillingSubscriptionRepository.withOfferContext\",\n );\n if (rawContext === null) {\n throw new StoreError(\"Billing subscription offer context is missing\", {\n details: {\n offerId: reference.offer_id,\n catalogRevisionId: reference.catalog_revision_id,\n },\n });\n }\n const context = safeParse(\n OfferContextSchema,\n {\n offer_key: rawContext.offer_key,\n plan_id: rawContext.plan_id,\n plan_key: rawContext.plan_key,\n billing_unit: rawContext.billing_unit,\n billing_count: rawContext.billing_count,\n },\n \"BillingSubscriptionRepository.withOfferContext.context\",\n );\n return {\n ...value,\n ...context,\n plan: context.plan_key,\n interval: context.billing_unit,\n interval_count: context.billing_count,\n };\n }\n\n async get(provider: string, providerSubscriptionId: string): Promise<SubscriptionRow | null> {\n const rows = await this.query(\n `SELECT * FROM bursar.get_billing_subscription_by_provider($1, $2)`,\n [provider, providerSubscriptionId],\n );\n const row = optionalRecordRow(rows, \"BillingSubscriptionRepository.get\");\n return row === null\n ? null\n : this.map(\n await this.withOfferContext(\n persistedSubscription(row, \"BillingSubscriptionRepository.get\"),\n ),\n );\n }\n async getUserSubscription(userId: string, statuses?: string[]): Promise<SubscriptionRow | null> {\n const allowed = new Set(\n safeParse(\n z.array(SubscriptionStatusSchema),\n statuses ?? [\"active\", \"trialing\"],\n \"BillingSubscriptionRepository.getUserSubscription.statuses\",\n ),\n );\n const rows = await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [\n userId,\n ]);\n const candidates = rows\n .map((row) => persistedSubscription(row, \"BillingSubscriptionRepository.getUserSubscription\"))\n .filter((row) => allowed.has(row.status))\n .sort(\n (left, right) =>\n Date.parse(right.provider_updated_at) - Date.parse(left.provider_updated_at),\n );\n const selected = candidates[0];\n return selected === undefined ? null : this.map(await this.withOfferContext(selected));\n }\n async getUserSubscriptions(userId: string): Promise<SubscriptionRow[]> {\n const rows = await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [\n userId,\n ]);\n const persisted = rows.map((row) =>\n persistedSubscription(row, \"BillingSubscriptionRepository.getUserSubscriptions\"),\n );\n const enriched = await Promise.all(persisted.map((row) => this.withOfferContext(row)));\n return enriched.map((row) => this.map(row));\n }\n\n async listExpiredGraceSubscriptions(now: string, limit = 100): Promise<SubscriptionRow[]> {\n const rows = await this.query(`SELECT * FROM bursar.list_expired_grace_subscriptions($1, $2)`, [\n now,\n limit,\n ]);\n const persisted = rows.map((row) =>\n persistedSubscription(row, \"BillingSubscriptionRepository.listExpiredGraceSubscriptions\"),\n );\n const enriched = await Promise.all(persisted.map((row) => this.withOfferContext(row)));\n return enriched.map((row) => this.map(row));\n }\n\n async reconcileEntitlement(\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 const expectedTimestamp = safeParse(\n timestamp,\n expectedProviderUpdatedAt,\n \"BillingSubscriptionRepository.reconcileEntitlement.expectedProviderUpdatedAt\",\n );\n const assignmentTimestamp =\n planAssignedAt === null\n ? null\n : safeParse(\n timestamp,\n planAssignedAt,\n \"BillingSubscriptionRepository.reconcileEntitlement.planAssignedAt\",\n );\n const rows = await this.query(\n `SELECT bursar.reconcile_subscription_entitlement(\n $1::uuid, $2::uuid, $3::uuid, $4::bursar.billing_subscription_status,\n $5::timestamptz, $6::timestamptz, $7, $8\n ) AS outcome`,\n [\n subjectId,\n subscriptionId,\n billingEventId,\n expectedStatus,\n expectedTimestamp,\n assignmentTimestamp,\n applyEntitlement,\n reason,\n ],\n );\n return requireResultField(\n rows,\n \"outcome\",\n SubscriptionEntitlementOutcomeSchema,\n \"BillingSubscriptionRepository.reconcileEntitlement\",\n );\n }\n\n async expireGracePeriod(\n subjectId: string,\n subscriptionId: string,\n expectedGraceEndsAt: string,\n expiredAt: string,\n ): Promise<boolean> {\n const rows = await this.query(\n `SELECT bursar.expire_subscription_grace_period($1::uuid, $2::uuid, $3, $4) AS expired`,\n [subjectId, subscriptionId, expectedGraceEndsAt, expiredAt],\n );\n return requireResultField(\n rows,\n \"expired\",\n pgBoolean,\n \"BillingSubscriptionRepository.expireGracePeriod\",\n );\n }\n\n async recordConflict(input: {\n userId?: string | null;\n provider: string;\n duplicateSubscriptionId: string;\n existingSubscriptionId?: string | null;\n eventId?: string | null;\n metadata?: JsonObject;\n }): Promise<string> {\n const rows = await this.query(\n `SELECT bursar.record_subscription_conflict(\n $1::uuid, $2, $3, $4, $5, $6::jsonb\n ) AS id`,\n [\n input.userId ?? null,\n input.provider,\n input.duplicateSubscriptionId,\n input.existingSubscriptionId ?? null,\n input.eventId ?? null,\n JSON.stringify(input.metadata ?? {}),\n ],\n );\n return requireResultField(\n rows,\n \"id\",\n z.union([z.string().min(1), z.number().int()]).transform(String),\n \"BillingSubscriptionRepository.recordConflict\",\n );\n }\n}\n"]}
1
+ {"version":3,"file":"subscription.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAQxB,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,SAAS,GAAG,CAAC;KAChB,KAAK,CAAC;IACL,CAAC,CAAC,IAAI,EAAE,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,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AAC,KAAK,CAC3B;;;oBAGc,EACd;YACE,SAAS;YACT,cAAc;YACd,cAAc;YACd,cAAc;YACd,iBAAiB;YACjB,mBAAmB;YACnB,gBAAgB;YAChB,MAAM;SACP,CACF,CAAC;QACF,OAAO,kBAAkB,CACvB,IAAI,EACJ,SAAS,EACT,oCAAoC,EACpC,oDAAoD,CACrD,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,iBAAiB,CACrB,SAAiB,EACjB,cAAsB,EACtB,mBAA2B,EAC3B,SAAiB;QAEjB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,uFAAuF,EACvF,CAAC,SAAS,EAAE,cAAc,EAAE,mBAAmB,EAAE,SAAS,CAAC,CAC5D,CAAC;QACF,OAAO,kBAAkB,CACvB,IAAI,EACJ,SAAS,EACT,SAAS,EACT,iDAAiD,CAClD,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,KAOpB;QACC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B;;eAES,EACT;YACE,KAAK,CAAC,MAAM,IAAI,IAAI;YACpB,KAAK,CAAC,QAAQ;YACd,KAAK,CAAC,uBAAuB;YAC7B,KAAK,CAAC,sBAAsB,IAAI,IAAI;YACpC,KAAK,CAAC,OAAO,IAAI,IAAI;YACrB,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,QAAQ,IAAI,EAAE,CAAC;SACrC,CACF,CAAC;QACF,OAAO,kBAAkB,CACvB,IAAI,EACJ,IAAI,EACJ,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,MAAM,CAAC,EAChE,8CAA8C,CAC/C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type {\n BillingSubscriptionState,\n BillingSubscriptionStatus,\n SubscriptionEntitlementOutcome,\n} from \"../../types/subscriptions.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { JsonObject, PostgresRow } from \"../../../shared/json.js\";\nimport { utcTimestamp } from \"../../../shared/timestamp.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst timestamp = z\n .union([\n z.date().refine((value) => !Number.isNaN(value.getTime())),\n z.string().datetime({ offset: true }),\n ])\n .transform((value) =>\n value instanceof Date\n ? value.toISOString()\n : utcTimestamp(value).replace(/(\\.\\d{3})000Z$/, \"$1Z\"),\n );\nconst SubscriptionStatusSchema = z.enum([\n \"incomplete\",\n \"incomplete_expired\",\n \"trialing\",\n \"active\",\n \"past_due\",\n \"canceled\",\n \"unpaid\",\n \"paused\",\n \"expired\",\n]);\nconst SubscriptionEntitlementOutcomeSchema = z.enum([\"applied\", \"revoked\", \"preserved\", \"stale\"]);\nconst PersistedSubscriptionRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n provider_subscription_id: z.string().min(1),\n provider_customer_id: z.string().min(1).nullable(),\n offer_id: postgresUuid,\n catalog_revision_id: postgresUuid,\n status: SubscriptionStatusSchema,\n current_period_start: timestamp.nullable(),\n current_period_end: timestamp.nullable(),\n trial_end: timestamp.nullable(),\n cancel_at: timestamp.nullable(),\n ended_at: timestamp.nullable(),\n grace_ends_at: timestamp.nullable(),\n grace_expired_at: timestamp.nullable(),\n provider_updated_at: timestamp,\n cancel_at_period_end: pgBoolean,\n metadata: z.record(z.string(), z.json()),\n })\n .strict();\nconst OfferContextSchema = z\n .object({\n offer_key: z.string().min(1),\n plan_id: postgresUuid,\n plan_key: z.string().min(1),\n billing_unit: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n billing_count: z.number().int().positive(),\n cycle_grant_amount: z.union([z.string(), z.number()]).nullable().optional(),\n })\n .strict();\n\nconst SubscriptionRowSchema = z\n .object({\n id: postgresUuid,\n user_id: postgresUuid,\n provider: z.string().min(1),\n provider_subscription_id: z.string().min(1),\n provider_customer_id: z.string().min(1).nullable(),\n offer_id: postgresUuid,\n offer_key: z.string().min(1),\n plan_id: postgresUuid,\n plan: z.string().min(1),\n status: SubscriptionStatusSchema,\n current_period_start: timestamp.nullable(),\n current_period_end: timestamp.nullable(),\n trial_end: timestamp.nullable(),\n cancel_at: timestamp.nullable(),\n ended_at: timestamp.nullable(),\n grace_ends_at: timestamp.nullable(),\n grace_expired_at: timestamp.nullable(),\n provider_updated_at: timestamp,\n cancel_at_period_end: pgBoolean,\n interval: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n interval_count: z.number().int().positive(),\n cycle_grant_amount: z.union([z.string(), z.number()]).nullable().optional(),\n metadata: z.record(z.string(), z.json()),\n })\n .strict();\n\nexport type SubscriptionRow = z.infer<typeof SubscriptionRowSchema>;\ntype PersistedSubscriptionRow = z.infer<typeof PersistedSubscriptionRowSchema>;\ntype EnrichedSubscriptionRow = PersistedSubscriptionRow & {\n offer_key: string;\n plan_id: string;\n plan_key: string;\n billing_unit: \"day\" | \"week\" | \"month\" | \"year\";\n billing_count: number;\n cycle_grant_amount?: string | number | null;\n plan: string;\n interval: \"day\" | \"week\" | \"month\" | \"year\";\n interval_count: number;\n};\n\nfunction persistedSubscription(row: PostgresRow, context: string): PersistedSubscriptionRow {\n const value = row;\n return safeParse(\n PersistedSubscriptionRowSchema,\n {\n id: value.id,\n subject_id: value.subject_id,\n provider: value.provider,\n provider_subscription_id: value.provider_subscription_id,\n provider_customer_id: value.provider_customer_id,\n offer_id: value.offer_id,\n catalog_revision_id: value.catalog_revision_id,\n status: value.status,\n current_period_start: value.current_period_start,\n current_period_end: value.current_period_end,\n trial_end: value.trial_end,\n cancel_at: value.cancel_at,\n ended_at: value.ended_at,\n grace_ends_at: value.grace_ends_at,\n grace_expired_at: value.grace_expired_at,\n provider_updated_at: value.provider_updated_at,\n cancel_at_period_end: value.cancel_at_period_end,\n metadata: value.metadata,\n },\n context,\n );\n}\n\nfunction subscriptionWithOfferSql(source: string): string {\n return `SELECT s.*, to_char(s.provider_updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS provider_updated_at,\n offer.offer_key, offer.plan_id, offer.plan_key, offer.billing_unit, offer.billing_count, offer.cycle_grant_amount\n FROM ${source} s\n LEFT JOIN LATERAL bursar.get_catalog_offer_context(s.offer_id, s.catalog_revision_id) offer ON true`;\n}\n\nexport class BillingSubscriptionRepository {\n constructor(private query: QueryFn) {}\n\n async upsert(state: BillingSubscriptionState): Promise<void> {\n const provider = state.provider;\n const providerSubscriptionId = state.providerSubscriptionId;\n const userId = state.userId;\n let providerCustomerId = state.providerCustomerId ?? null;\n let offerId = state.offerId ?? null;\n\n if (!provider || !providerSubscriptionId) {\n throw new TypeError(\n \"subscription.upsert: subject, provider, subscription, and offer are required\",\n );\n }\n\n const existing = await this.query(\n `SELECT s.*, to_char(s.provider_updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS provider_updated_at FROM bursar.get_billing_subscription_by_provider($1, $2) s`,\n [provider, providerSubscriptionId],\n );\n const rawExisting = optionalRecordRow(\n existing,\n \"BillingSubscriptionRepository.upsert.existing\",\n );\n const existingRow =\n rawExisting === null\n ? null\n : persistedSubscription(rawExisting, \"BillingSubscriptionRepository.upsert.existing\");\n if (providerCustomerId === null && existingRow !== null) {\n providerCustomerId = existingRow.provider_customer_id;\n }\n if (offerId === null && existingRow !== null) offerId = existingRow.offer_id;\n\n const offerKey = state.offerKey ?? null;\n if (offerId === null && offerKey !== null) {\n const offerRows = await this.query(`SELECT * FROM bursar.resolve_active_catalog_offer($1)`, [\n offerKey,\n ]);\n const offerRow = optionalRecordRow(offerRows, \"BillingSubscriptionRepository.upsert.offer\");\n if (offerRow !== null) {\n offerId = safeParse(\n postgresUuid,\n offerRow.id,\n \"BillingSubscriptionRepository.upsert.offer.id\",\n );\n }\n }\n\n if (!userId || !offerId) {\n throw new TypeError(\n \"subscription.upsert: subject, provider, subscription, and offer are required\",\n );\n }\n const providerUpdatedAt = safeParse(\n timestamp,\n state.providerUpdatedAt,\n \"BillingSubscriptionRepository.upsert.providerUpdatedAt\",\n );\n\n const rows = await this.query(\n \"SELECT bursar.upsert_billing_subscription($1::uuid,$2,$3,$4,$5::uuid,$6::bursar.billing_subscription_status,$7,$8,$9,$10::jsonb,$11,$12,$13,$14,$15,$16::uuid) AS id\",\n [\n userId,\n provider,\n providerSubscriptionId,\n providerCustomerId,\n offerId,\n state.status,\n state.currentPeriodStart ?? null,\n state.currentPeriodEnd ?? null,\n state.cancelAtPeriodEnd,\n JSON.stringify(state.metadata ?? {}),\n state.trialEnd ?? null,\n state.cancelAt ?? null,\n state.endedAt ?? null,\n providerUpdatedAt,\n state.graceEndsAt ?? null,\n state.billingEventId ?? null,\n ],\n );\n if (rows.length === 1 && rows[0]?.id === null) {\n throw new StoreError(\"A blocking subscription already exists for this provider\", {\n details: { reason: \"blocking_subscription_conflict\" },\n });\n }\n requireResultField(rows, \"id\", postgresUuid, \"BillingSubscriptionRepository.upsert\");\n }\n\n private map(row: EnrichedSubscriptionRow): SubscriptionRow {\n const r = row;\n return safeParse(\n SubscriptionRowSchema,\n {\n id: r.id,\n user_id: r.subject_id,\n provider: r.provider,\n provider_subscription_id: r.provider_subscription_id,\n provider_customer_id: r.provider_customer_id,\n offer_id: r.offer_id,\n offer_key: r.offer_key,\n plan_id: r.plan_id,\n plan: r.plan,\n status: r.status,\n current_period_start: r.current_period_start,\n current_period_end: r.current_period_end,\n trial_end: r.trial_end,\n cancel_at: r.cancel_at,\n ended_at: r.ended_at,\n grace_ends_at: r.grace_ends_at,\n grace_expired_at: r.grace_expired_at,\n provider_updated_at: r.provider_updated_at,\n cancel_at_period_end: r.cancel_at_period_end,\n interval: r.interval,\n interval_count: r.interval_count,\n cycle_grant_amount: r.cycle_grant_amount,\n metadata: r.metadata,\n },\n \"BillingSubscriptionRepository\",\n );\n }\n\n private withOfferContext(rawContext: PostgresRow): EnrichedSubscriptionRow {\n const value = persistedSubscription(rawContext, \"BillingSubscriptionRepository.subscription\");\n if (rawContext.offer_key == null) {\n throw new StoreError(\"Billing subscription offer context is missing\", {\n details: {\n offerId: value.offer_id,\n catalogRevisionId: value.catalog_revision_id,\n },\n });\n }\n const context = safeParse(\n OfferContextSchema,\n {\n offer_key: rawContext.offer_key,\n plan_id: rawContext.plan_id,\n plan_key: rawContext.plan_key,\n billing_unit: rawContext.billing_unit,\n billing_count: rawContext.billing_count,\n cycle_grant_amount: rawContext.cycle_grant_amount ?? null,\n },\n \"BillingSubscriptionRepository.withOfferContext.context\",\n );\n return {\n ...value,\n ...context,\n plan: context.plan_key,\n interval: context.billing_unit,\n interval_count: context.billing_count,\n };\n }\n\n async get(provider: string, providerSubscriptionId: string): Promise<SubscriptionRow | null> {\n const rows = await this.query(\n `${subscriptionWithOfferSql(\"bursar.get_billing_subscription_by_provider($1, $2)\")}`,\n [provider, providerSubscriptionId],\n );\n const row = optionalRecordRow(rows, \"BillingSubscriptionRepository.get\");\n return row === null ? null : this.map(this.withOfferContext(row));\n }\n async getUserSubscription(userId: string, statuses?: string[]): Promise<SubscriptionRow | null> {\n const allowed = safeParse(\n z.array(SubscriptionStatusSchema),\n statuses ?? [\"active\", \"trialing\"],\n \"BillingSubscriptionRepository.getUserSubscription.statuses\",\n );\n const rows = await this.query(\n `${subscriptionWithOfferSql(\"bursar.list_billing_subscriptions($1::uuid)\")}\n WHERE s.status::text = ANY($2::text[])\n ORDER BY CASE WHEN s.status::text IN ('canceled', 'expired', 'incomplete_expired') THEN 1 ELSE 0 END,\n s.provider_updated_at DESC, s.id DESC LIMIT 1`,\n [userId, allowed],\n );\n const row = optionalRecordRow(rows, \"BillingSubscriptionRepository.getUserSubscription\");\n return row === null ? null : this.map(this.withOfferContext(row));\n }\n async getUserSubscriptions(userId: string): Promise<SubscriptionRow[]> {\n const rows = await this.query(\n `${subscriptionWithOfferSql(\"bursar.list_billing_subscriptions($1::uuid)\")} ORDER BY s.created_at, s.id`,\n [userId],\n );\n return rows.map((row) => this.map(this.withOfferContext(row)));\n }\n\n async listExpiredGraceSubscriptions(now: string, limit = 100): Promise<SubscriptionRow[]> {\n const rows = await this.query(\n `${subscriptionWithOfferSql(\"bursar.list_expired_grace_subscriptions($1, $2)\")} ORDER BY s.grace_ends_at, s.id`,\n [now, limit],\n );\n return rows.map((row) => this.map(this.withOfferContext(row)));\n }\n\n async reconcileEntitlement(\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 const expectedTimestamp = safeParse(\n timestamp,\n expectedProviderUpdatedAt,\n \"BillingSubscriptionRepository.reconcileEntitlement.expectedProviderUpdatedAt\",\n );\n const assignmentTimestamp =\n planAssignedAt === null\n ? null\n : safeParse(\n timestamp,\n planAssignedAt,\n \"BillingSubscriptionRepository.reconcileEntitlement.planAssignedAt\",\n );\n const rows = await this.query(\n `SELECT bursar.reconcile_subscription_entitlement(\n $1::uuid, $2::uuid, $3::uuid, $4::bursar.billing_subscription_status,\n $5::timestamptz, $6::timestamptz, $7, $8\n ) AS outcome`,\n [\n subjectId,\n subscriptionId,\n billingEventId,\n expectedStatus,\n expectedTimestamp,\n assignmentTimestamp,\n applyEntitlement,\n reason,\n ],\n );\n return requireResultField(\n rows,\n \"outcome\",\n SubscriptionEntitlementOutcomeSchema,\n \"BillingSubscriptionRepository.reconcileEntitlement\",\n );\n }\n\n async expireGracePeriod(\n subjectId: string,\n subscriptionId: string,\n expectedGraceEndsAt: string,\n expiredAt: string,\n ): Promise<boolean> {\n const rows = await this.query(\n `SELECT bursar.expire_subscription_grace_period($1::uuid, $2::uuid, $3, $4) AS expired`,\n [subjectId, subscriptionId, expectedGraceEndsAt, expiredAt],\n );\n return requireResultField(\n rows,\n \"expired\",\n pgBoolean,\n \"BillingSubscriptionRepository.expireGracePeriod\",\n );\n }\n\n async recordConflict(input: {\n userId?: string | null;\n provider: string;\n duplicateSubscriptionId: string;\n existingSubscriptionId?: string | null;\n eventId?: string | null;\n metadata?: JsonObject;\n }): Promise<string> {\n const rows = await this.query(\n `SELECT bursar.record_subscription_conflict(\n $1::uuid, $2, $3, $4, $5, $6::jsonb\n ) AS id`,\n [\n input.userId ?? null,\n input.provider,\n input.duplicateSubscriptionId,\n input.existingSubscriptionId ?? null,\n input.eventId ?? null,\n JSON.stringify(input.metadata ?? {}),\n ],\n );\n return requireResultField(\n rows,\n \"id\",\n z.union([z.string().min(1), z.number().int()]).transform(String),\n \"BillingSubscriptionRepository.recordConflict\",\n );\n }\n}\n"]}
@@ -7,6 +7,11 @@ declare const BillingTopupRowSchema: z.ZodObject<{
7
7
  credits_per_unit: z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodInstanceOf<Decimal>]>, z.ZodTransform<Decimal, string | number | Decimal>>;
8
8
  bucket_key: z.ZodString;
9
9
  amount_minor: z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>, z.ZodTransform<number, string | number>>;
10
+ tax_behavior: z.ZodEnum<{
11
+ exclusive: "exclusive";
12
+ inclusive: "inclusive";
13
+ unspecified: "unspecified";
14
+ }>;
10
15
  currency: z.ZodString;
11
16
  min_quantity: z.ZodNumber;
12
17
  max_quantity: z.ZodNumber;
@@ -17,7 +22,7 @@ export type BillingTopupRow = z.infer<typeof BillingTopupRowSchema>;
17
22
  export declare class BillingTopupRepository {
18
23
  private readonly query;
19
24
  constructor(query: QueryFn);
20
- resolveByPrice(provider: string, priceId: string | null, productId: string | null, checkoutIntentId?: string | null, subjectId?: string | null, providerPaymentId?: string | null, rechargeAttemptId?: string | null): Promise<BillingTopupRow | null>;
25
+ resolveByPrice(provider: string, priceId: string | null, productId: string | null, checkoutIntentId?: string | null, subjectId?: string | null, providerPaymentId?: string | null, rechargeAttemptId?: string | null, billingEventId?: string | null): Promise<BillingTopupRow | null>;
21
26
  resolveByLookup(provider: string, lookupKey: string): Promise<BillingTopupRow | null>;
22
27
  private resolve;
23
28
  }
@@ -1 +1 @@
1
- {"version":3,"file":"topup.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/topup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAajE,QAAA,MAAM,qBAAqB;;;;;;;;;;kBA0BvB,CAAC;AAEL,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAEpE,+CAA+C;AAC/C,qBAAa,sBAAsB;IACrB,OAAO,CAAC,QAAQ,CAAC,KAAK;IAAlC,YAA6B,KAAK,EAAE,OAAO,EAAI;IAEzC,cAAc,CAClB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,GAAG,IAAI,EACtB,SAAS,EAAE,MAAM,GAAG,IAAI,EACxB,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,EAChC,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,EACzB,iBAAiB,CAAC,EAAE,MAAM,GAAG,IAAI,EACjC,iBAAiB,CAAC,EAAE,MAAM,GAAG,IAAI,GAChC,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAYjC;IAEK,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAE1F;YAEa,OAAO;CAwDtB"}
1
+ {"version":3,"file":"topup.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/topup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAajE,QAAA,MAAM,qBAAqB;;;;;;;;;;;;;;;kBA2BvB,CAAC;AAEL,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAEpE,+CAA+C;AAC/C,qBAAa,sBAAsB;IACrB,OAAO,CAAC,QAAQ,CAAC,KAAK;IAAlC,YAA6B,KAAK,EAAE,OAAO,EAAI;IAEzC,cAAc,CAClB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,GAAG,IAAI,EACtB,SAAS,EAAE,MAAM,GAAG,IAAI,EACxB,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,EAChC,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,EACzB,iBAAiB,CAAC,EAAE,MAAM,GAAG,IAAI,EACjC,iBAAiB,CAAC,EAAE,MAAM,GAAG,IAAI,EACjC,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,GAC7B,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAajC;IAEK,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAE1F;YAEa,OAAO;CA2DtB"}
@@ -1,10 +1,11 @@
1
1
  import { Decimal } from "decimal.js";
2
+ import { PricingDecimal } from "../../../pricing-decimal.js";
2
3
  import { z } from "zod";
3
4
  import { StoreError } from "../../../errors.js";
4
5
  import { postgresUuid, safeParse, unwrapJsonb } from "../../../shared/postgres-validation.js";
5
6
  const PositiveDecimalSchema = z
6
7
  .union([z.string(), z.number(), z.instanceof(Decimal)])
7
- .transform((value) => new Decimal(value))
8
+ .transform((value) => new PricingDecimal(value))
8
9
  .refine((value) => value.isFinite() && value.gt(0), "expected a finite positive decimal");
9
10
  const SafeMinorUnitsSchema = z
10
11
  .union([z.string().regex(/^\d+$/), z.number().int().nonnegative().safe()])
@@ -17,6 +18,7 @@ const BillingTopupRowSchema = z
17
18
  credits_per_unit: PositiveDecimalSchema,
18
19
  bucket_key: z.string().min(1),
19
20
  amount_minor: SafeMinorUnitsSchema,
21
+ tax_behavior: z.enum(["inclusive", "exclusive", "unspecified"]),
20
22
  currency: z.string().regex(/^[A-Z]{3}$/),
21
23
  min_quantity: z.number().int().positive(),
22
24
  max_quantity: z.number().int().positive(),
@@ -43,21 +45,21 @@ export class BillingTopupRepository {
43
45
  constructor(query) {
44
46
  this.query = query;
45
47
  }
46
- async resolveByPrice(provider, priceId, productId, checkoutIntentId, subjectId, providerPaymentId, rechargeAttemptId) {
48
+ async resolveByPrice(provider, priceId, productId, checkoutIntentId, subjectId, providerPaymentId, rechargeAttemptId, billingEventId) {
47
49
  const lookupType = priceId !== null ? "price_id" : "product_id";
48
- return this.resolve(provider, lookupType, priceId ?? productId, "resolveByPrice", checkoutIntentId, subjectId, providerPaymentId, rechargeAttemptId);
50
+ return this.resolve(provider, lookupType, priceId ?? productId, "resolveByPrice", checkoutIntentId, subjectId, providerPaymentId, rechargeAttemptId, billingEventId);
49
51
  }
50
52
  async resolveByLookup(provider, lookupKey) {
51
53
  return this.resolve(provider, "external_id", lookupKey, "resolveByLookup");
52
54
  }
53
- async resolve(provider, lookupType, lookupValue, operation, checkoutIntentId, subjectId, providerPaymentId, rechargeAttemptId) {
55
+ async resolve(provider, lookupType, lookupValue, operation, checkoutIntentId, subjectId, providerPaymentId, rechargeAttemptId, billingEventId) {
54
56
  if (!provider.trim())
55
57
  throw new TypeError("provider must not be empty");
56
58
  if (!lookupValue?.trim())
57
59
  return null;
58
60
  const context = `BillingTopupRepository.${operation}`;
59
61
  const rows = providerPaymentId && subjectId
60
- ? await this.query("SELECT * FROM bursar.resolve_purchase_catalog_topup($1::uuid, $2, $3, $4, $5, $6::uuid, $7::uuid)", [
62
+ ? await this.query("SELECT * FROM bursar.resolve_purchase_catalog_topup($1::uuid, $2, $3, $4, $5, $6::uuid, $7::uuid, $8::uuid)", [
61
63
  subjectId,
62
64
  provider,
63
65
  providerPaymentId,
@@ -65,6 +67,7 @@ export class BillingTopupRepository {
65
67
  lookupValue,
66
68
  checkoutIntentId ?? null,
67
69
  rechargeAttemptId ?? null,
70
+ billingEventId ?? null,
68
71
  ])
69
72
  : await this.query("SELECT * FROM bursar.resolve_catalog_topup($1, $2, $3)", [
70
73
  provider,
@@ -85,6 +88,7 @@ export class BillingTopupRepository {
85
88
  credits_per_unit: raw.credits_per_unit,
86
89
  bucket_key: raw.bucket_key,
87
90
  amount_minor: raw.amount_minor,
91
+ tax_behavior: raw.tax_behavior,
88
92
  currency: raw.currency,
89
93
  min_quantity: raw.min_quantity,
90
94
  max_quantity: raw.max_quantity,
@@ -1 +1 @@
1
- {"version":3,"file":"topup.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/topup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,wCAAwC,CAAC;AAE9F,MAAM,qBAAqB,GAAG,CAAC;KAC5B,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC;KACtD,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC;KACxC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,EAAE,IAAI,KAA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AAM,OAAO,GAAG,0BAA0B,SAAS,EAAE,CAAC;QACtD,MAAM,IAAI,GACR,iBAAiB,IAAI,SAAS;YAC5B,CAAC,CAAC,MAAM,IAAI,CAAC,KAAK,CACd,mGAAmG,EACnG;gBACE,SAAS;gBACT,QAAQ;gBACR,iBAAiB;gBACjB,UAAU;gBACV,WAAW;gBACX,gBAAgB,IAAI,IAAI;gBACxB,iBAAiB,IAAI,IAAI;aAC1B,CACF;YACH,CAAC,CAAC,MAAM,IAAI,CAAC,KAAK,CAAC,wDAAwD,EAAE;gBACzE,QAAQ;gBACR,UAAU;gBACV,WAAW;aACZ,CAAC,CAAC;QACT,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACpB,MAAM,IAAI,UAAU,CAAC,GAAG,OAAO,+BAA+B,EAAE;gBAC9D,OAAO,EAAE,EAAE,QAAQ,EAAE,IAAI,CAAC,MAAM,EAAE;aACnC,CAAC,CAAC;QACL,CAAC;QACD,MAAM,GAAG,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;QAC9B,IAAI,GAAG,EAAE,EAAE,IAAI,IAAI;YAAE,OAAO,IAAI,CAAC;QACjC,OAAO,SAAS,CACd,qBAAqB,EACrB;YACE,EAAE,EAAE,GAAG,CAAC,EAAE;YACV,SAAS,EAAE,GAAG,CAAC,SAAS;YACxB,gBAAgB,EAAE,GAAG,CAAC,gBAAgB;YACtC,UAAU,EAAE,GAAG,CAAC,UAAU;YAC1B,YAAY,EAAE,GAAG,CAAC,YAAY;YAC9B,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,YAAY,EAAE,GAAG,CAAC,YAAY;YAC9B,YAAY,EAAE,GAAG,CAAC,YAAY;YAC9B,gBAAgB,EAAE,GAAG,CAAC,gBAAgB;SACvC,EACD,OAAO,CACR,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { z } from \"zod\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport { postgresUuid, safeParse, unwrapJsonb } from \"../../../shared/postgres-validation.js\";\n\nconst PositiveDecimalSchema = z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .transform((value) => new Decimal(value))\n .refine((value) => value.isFinite() && value.gt(0), \"expected a finite positive decimal\");\n\nconst SafeMinorUnitsSchema = 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 BillingTopupRowSchema = z\n .object({\n id: postgresUuid,\n topup_key: z.string().min(1),\n credits_per_unit: PositiveDecimalSchema,\n bucket_key: z.string().min(1),\n amount_minor: SafeMinorUnitsSchema,\n currency: z.string().regex(/^[A-Z]{3}$/),\n min_quantity: z.number().int().positive(),\n max_quantity: z.number().int().positive(),\n default_quantity: z.number().int().positive(),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.max_quantity < row.min_quantity) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"max_quantity is below min_quantity\",\n });\n }\n if (row.default_quantity < row.min_quantity || row.default_quantity > row.max_quantity) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"default_quantity is outside the configured range\",\n });\n }\n });\n\nexport type BillingTopupRow = z.infer<typeof BillingTopupRowSchema>;\n\n/** Repository for credit top-up resolution. */\nexport class BillingTopupRepository {\n constructor(private readonly query: QueryFn) {}\n\n async resolveByPrice(\n provider: string,\n priceId: string | null,\n productId: string | null,\n checkoutIntentId?: string | null,\n subjectId?: string | null,\n providerPaymentId?: string | null,\n rechargeAttemptId?: string | null,\n ): Promise<BillingTopupRow | null> {\n const lookupType = priceId !== null ? \"price_id\" : \"product_id\";\n return this.resolve(\n provider,\n lookupType,\n priceId ?? productId,\n \"resolveByPrice\",\n checkoutIntentId,\n subjectId,\n providerPaymentId,\n rechargeAttemptId,\n );\n }\n\n async resolveByLookup(provider: string, lookupKey: string): Promise<BillingTopupRow | null> {\n return this.resolve(provider, \"external_id\", lookupKey, \"resolveByLookup\");\n }\n\n private async resolve(\n provider: string,\n lookupType: \"price_id\" | \"product_id\" | \"external_id\",\n lookupValue: string | null,\n operation: string,\n checkoutIntentId?: string | null,\n subjectId?: string | null,\n providerPaymentId?: string | null,\n rechargeAttemptId?: string | null,\n ): Promise<BillingTopupRow | null> {\n if (!provider.trim()) throw new TypeError(\"provider must not be empty\");\n if (!lookupValue?.trim()) return null;\n\n const context = `BillingTopupRepository.${operation}`;\n const rows =\n providerPaymentId && subjectId\n ? await this.query(\n \"SELECT * FROM bursar.resolve_purchase_catalog_topup($1::uuid, $2, $3, $4, $5, $6::uuid, $7::uuid)\",\n [\n subjectId,\n provider,\n providerPaymentId,\n lookupType,\n lookupValue,\n checkoutIntentId ?? null,\n rechargeAttemptId ?? null,\n ],\n )\n : await this.query(\"SELECT * FROM bursar.resolve_catalog_topup($1, $2, $3)\", [\n provider,\n lookupType,\n lookupValue,\n ]);\n if (rows.length > 1) {\n throw new StoreError(`${context}: expected at most one top-up`, {\n details: { rowCount: rows.length },\n });\n }\n const raw = unwrapJsonb(rows);\n if (raw?.id == null) return null;\n return safeParse(\n BillingTopupRowSchema,\n {\n id: raw.id,\n topup_key: raw.topup_key,\n credits_per_unit: raw.credits_per_unit,\n bucket_key: raw.bucket_key,\n amount_minor: raw.amount_minor,\n currency: raw.currency,\n min_quantity: raw.min_quantity,\n max_quantity: raw.max_quantity,\n default_quantity: raw.default_quantity,\n },\n context,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"topup.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/topup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;A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AAG,EAAE,EAAE,IAAI,IAAI;YAAE,OAAO,IAAI,CAAC;QACjC,OAAO,SAAS,CACd,qBAAqB,EACrB;YACE,EAAE,EAAE,GAAG,CAAC,EAAE;YACV,SAAS,EAAE,GAAG,CAAC,SAAS;YACxB,gBAAgB,EAAE,GAAG,CAAC,gBAAgB;YACtC,UAAU,EAAE,GAAG,CAAC,UAAU;YAC1B,YAAY,EAAE,GAAG,CAAC,YAAY;YAC9B,YAAY,EAAE,GAAG,CAAC,YAAY;YAC9B,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,YAAY,EAAE,GAAG,CAAC,YAAY;YAC9B,YAAY,EAAE,GAAG,CAAC,YAAY;YAC9B,gBAAgB,EAAE,GAAG,CAAC,gBAAgB;SACvC,EACD,OAAO,CACR,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { PricingDecimal } from \"../../../pricing-decimal.js\";\nimport { z } from \"zod\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport { postgresUuid, safeParse, unwrapJsonb } from \"../../../shared/postgres-validation.js\";\n\nconst PositiveDecimalSchema = z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .transform((value) => new PricingDecimal(value))\n .refine((value) => value.isFinite() && value.gt(0), \"expected a finite positive decimal\");\n\nconst SafeMinorUnitsSchema = 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 BillingTopupRowSchema = z\n .object({\n id: postgresUuid,\n topup_key: z.string().min(1),\n credits_per_unit: PositiveDecimalSchema,\n bucket_key: z.string().min(1),\n amount_minor: SafeMinorUnitsSchema,\n tax_behavior: z.enum([\"inclusive\", \"exclusive\", \"unspecified\"]),\n currency: z.string().regex(/^[A-Z]{3}$/),\n min_quantity: z.number().int().positive(),\n max_quantity: z.number().int().positive(),\n default_quantity: z.number().int().positive(),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.max_quantity < row.min_quantity) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"max_quantity is below min_quantity\",\n });\n }\n if (row.default_quantity < row.min_quantity || row.default_quantity > row.max_quantity) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"default_quantity is outside the configured range\",\n });\n }\n });\n\nexport type BillingTopupRow = z.infer<typeof BillingTopupRowSchema>;\n\n/** Repository for credit top-up resolution. */\nexport class BillingTopupRepository {\n constructor(private readonly query: QueryFn) {}\n\n async resolveByPrice(\n provider: string,\n priceId: string | null,\n productId: string | null,\n checkoutIntentId?: string | null,\n subjectId?: string | null,\n providerPaymentId?: string | null,\n rechargeAttemptId?: string | null,\n billingEventId?: string | null,\n ): Promise<BillingTopupRow | null> {\n const lookupType = priceId !== null ? \"price_id\" : \"product_id\";\n return this.resolve(\n provider,\n lookupType,\n priceId ?? productId,\n \"resolveByPrice\",\n checkoutIntentId,\n subjectId,\n providerPaymentId,\n rechargeAttemptId,\n billingEventId,\n );\n }\n\n async resolveByLookup(provider: string, lookupKey: string): Promise<BillingTopupRow | null> {\n return this.resolve(provider, \"external_id\", lookupKey, \"resolveByLookup\");\n }\n\n private async resolve(\n provider: string,\n lookupType: \"price_id\" | \"product_id\" | \"external_id\",\n lookupValue: string | null,\n operation: string,\n checkoutIntentId?: string | null,\n subjectId?: string | null,\n providerPaymentId?: string | null,\n rechargeAttemptId?: string | null,\n billingEventId?: string | null,\n ): Promise<BillingTopupRow | null> {\n if (!provider.trim()) throw new TypeError(\"provider must not be empty\");\n if (!lookupValue?.trim()) return null;\n\n const context = `BillingTopupRepository.${operation}`;\n const rows =\n providerPaymentId && subjectId\n ? await this.query(\n \"SELECT * FROM bursar.resolve_purchase_catalog_topup($1::uuid, $2, $3, $4, $5, $6::uuid, $7::uuid, $8::uuid)\",\n [\n subjectId,\n provider,\n providerPaymentId,\n lookupType,\n lookupValue,\n checkoutIntentId ?? null,\n rechargeAttemptId ?? null,\n billingEventId ?? null,\n ],\n )\n : await this.query(\"SELECT * FROM bursar.resolve_catalog_topup($1, $2, $3)\", [\n provider,\n lookupType,\n lookupValue,\n ]);\n if (rows.length > 1) {\n throw new StoreError(`${context}: expected at most one top-up`, {\n details: { rowCount: rows.length },\n });\n }\n const raw = unwrapJsonb(rows);\n if (raw?.id == null) return null;\n return safeParse(\n BillingTopupRowSchema,\n {\n id: raw.id,\n topup_key: raw.topup_key,\n credits_per_unit: raw.credits_per_unit,\n bucket_key: raw.bucket_key,\n amount_minor: raw.amount_minor,\n tax_behavior: raw.tax_behavior,\n currency: raw.currency,\n min_quantity: raw.min_quantity,\n max_quantity: raw.max_quantity,\n default_quantity: raw.default_quantity,\n },\n context,\n );\n }\n}\n"]}
@@ -1,6 +1,5 @@
1
- import { Decimal } from "decimal.js";
2
1
  import type { JsonObject } from "../../shared/json.js";
3
- import type { BillingAutoRechargeAttempt, BillingAutoRechargeProfile, BillingCreditPostingResult, BillingCustomerRecord, BillingEventClaim, BillingOfferResult, BillingPaymentRecord, BillingPreferences, BillingSubscriptionChange, BillingSubscriptionChangeInput, BillingSubscriptionState, BillingSubscriptionStatus, SubscriptionEntitlementOutcome, CheckoutIntent, BillingTopupResult } from "../types/index.js";
2
+ import type { BillingAutoRechargeAttempt, BillingAutoRechargeProfile, BillingCreditPostingResult, BillingCustomerRecord, BillingEventClaim, BillingOfferResult, BillingPaymentRecord, BillingPreferences, BillingSubscriptionChange, BillingSubscriptionChangeInput, BillingSubscriptionState, BillingSubscriptionStatus, SubscriptionEntitlementOutcome, CheckoutIntent, BillingTopupResult, ListBillingInvoicesOptions } from "../types/index.js";
4
3
  import { BillingStore } from "../billing-store.js";
5
4
  import type { AutoRechargeAttemptClaim, AutoRechargeAttemptUpdate, AutoRechargeProviderPaymentUpdate, BillingCreditGrantCreate, BillingDisputeUpsert, BillingInvoiceUpsert, BillingPaymentUpsert, BillingRefundUpsert, BillingSubscriptionChangeUpdate, BillingSubscriptionConflictCreate, CheckoutIntentCreate, CheckoutIntentUpdate } from "../contracts.js";
6
5
  import { type PostgresConnectionOptions, type PostgresPool, type PostgresPoolConstructor } from "../../shared/postgres-client.js";
@@ -17,35 +16,28 @@ export interface PostgresBillingStoreOptions extends Omit<PostgresConnectionOpti
17
16
  billingPayloadBackend?: "postgres" | "s3";
18
17
  }
19
18
  export declare class PostgresBillingStore extends BillingStore {
19
+ readonly tenantId: string;
20
20
  private readonly postgres;
21
+ private readonly scoped;
22
+ private readonly options;
21
23
  readonly providerEnvironment: ProviderEnvironment;
22
- private _offer;
23
- private _topup;
24
- private _customer;
25
- private _subscription;
26
- private _event;
27
- private _payment;
28
- private _refund;
29
- private _invoice;
30
- private _dispute;
31
- private _preferences;
32
- private _autoRecharge;
33
- private _subscriptionChange;
24
+ private readonly queryFn;
25
+ private readonly billingOffer;
26
+ private readonly billingTopup;
27
+ private readonly billingCustomer;
28
+ private readonly billingSubscription;
29
+ private readonly billingEvent;
30
+ private readonly billingPayment;
31
+ private readonly billingRefund;
32
+ private readonly billingInvoice;
33
+ private readonly billingDispute;
34
+ private readonly billingPreferences;
35
+ private readonly billingAutoRecharge;
36
+ private readonly billingSubscriptionChange;
34
37
  constructor(options: PostgresBillingStoreOptions);
38
+ withBillingEventTransaction<T>(action: (store: BillingStore) => Promise<T>): Promise<T>;
39
+ observeBillingInvoiceOutcome(provider: string, invoiceId: string, outcome: "paid" | "failed"): Promise<boolean>;
35
40
  close(): Promise<void>;
36
- private get queryFn();
37
- private get billingOffer();
38
- private get billingTopup();
39
- private get billingCustomer();
40
- private get billingSubscription();
41
- private get billingEvent();
42
- private get billingPayment();
43
- private get billingRefund();
44
- private get billingInvoice();
45
- private get billingDispute();
46
- private get billingPreferences();
47
- private get billingAutoRecharge();
48
- private get billingSubscriptionChange();
49
41
  createOrGetCheckoutIntent(input: CheckoutIntentCreate): Promise<CheckoutIntent>;
50
42
  updateCheckoutIntent(id: string, update: CheckoutIntentUpdate): Promise<void>;
51
43
  findCheckoutIntent(subjectId: string, operationKey: string, provider?: string): Promise<{
@@ -69,6 +61,7 @@ export declare class PostgresBillingStore extends BillingStore {
69
61
  getBillingCustomer(provider: string, providerCustomerId: string): Promise<string | null>;
70
62
  getBillingSubscription(provider: string, providerSubscriptionId: string): Promise<BillingSubscriptionState | null>;
71
63
  createBillingSubscriptionChange(input: BillingSubscriptionChangeInput): Promise<BillingSubscriptionChange>;
64
+ findBillingSubscriptionChange(provider: string, subscriptionId: string, operationKey: string): Promise<BillingSubscriptionChange | null>;
72
65
  getOpenBillingSubscriptionChange(provider: string, providerSubscriptionId: string): Promise<BillingSubscriptionChange | null>;
73
66
  listExpiredGraceSubscriptions(now: string, limit?: number): Promise<BillingSubscriptionState[]>;
74
67
  reconcileSubscriptionEntitlement(subjectId: string, subscriptionId: string, billingEventId: string, expectedStatus: BillingSubscriptionStatus, expectedProviderUpdatedAt: string, planAssignedAt: Date | string | null, applyEntitlement: boolean, reason: string): Promise<SubscriptionEntitlementOutcome>;
@@ -78,9 +71,8 @@ export declare class PostgresBillingStore extends BillingStore {
78
71
  getUserSubscriptions(userId: string): Promise<BillingSubscriptionState[]>;
79
72
  recordSubscriptionConflict(input: BillingSubscriptionConflictCreate): Promise<void>;
80
73
  private rowToTopup;
81
- resolveCreditTopup(provider: string, productId?: string | null, priceId?: string | null, checkoutIntentId?: string | null, subjectId?: string | null, providerPaymentId?: string | null, rechargeAttemptId?: string | null): Promise<BillingTopupResult | null>;
74
+ resolveCreditTopup(provider: string, productId?: string | null, priceId?: string | null, checkoutIntentId?: string | null, subjectId?: string | null, providerPaymentId?: string | null, rechargeAttemptId?: string | null, billingEventId?: string | null): Promise<BillingTopupResult | null>;
82
75
  resolveCreditTopupByLookup(provider: string, lookupKey: string): Promise<BillingTopupResult | null>;
83
- computeTopupCredits(amountMinor: number, topupConfig: BillingTopupResult): Promise<Decimal>;
84
76
  upsertBillingPayment(options: BillingPaymentUpsert): Promise<string>;
85
77
  createBillingCreditGrant(input: BillingCreditGrantCreate): Promise<string>;
86
78
  grantBillingCredit(grantId: string, idempotencyKey: string): Promise<BillingCreditPostingResult>;
@@ -88,7 +80,8 @@ export declare class PostgresBillingStore extends BillingStore {
88
80
  postBillingRefund(refundId: string, grantId: string, amountMinor: number, idempotencyKey: string): Promise<BillingCreditPostingResult>;
89
81
  upsertBillingRefund(options: BillingRefundUpsert): Promise<string>;
90
82
  upsertBillingInvoice(options: BillingInvoiceUpsert): Promise<void>;
91
- listBillingInvoices(userId: string): Promise<import("../contracts.js").BillingInvoiceRecord[]>;
83
+ listBillingInvoices(userId: string, options?: ListBillingInvoicesOptions): Promise<import("../index.js").BillingInvoicePage>;
84
+ hasBillingInvoice(userId: string, provider: string, providerInvoiceId: string): Promise<boolean>;
92
85
  upsertBillingDispute(options: BillingDisputeUpsert): Promise<void>;
93
86
  getBillingPayment(provider: string, providerPaymentId: string): Promise<BillingPaymentRecord | null>;
94
87
  private rowToSubscriptionState;
@@ -107,7 +100,7 @@ export declare class PostgresBillingStore extends BillingStore {
107
100
  resumeAutoRechargeProfile(profile: BillingAutoRechargeProfile): Promise<boolean>;
108
101
  claimAutoRechargeAttempt(input: AutoRechargeAttemptClaim): Promise<BillingAutoRechargeAttempt | null>;
109
102
  updateAutoRechargeAttempt(input: AutoRechargeAttemptUpdate): Promise<void>;
110
- updateAutoRechargeAttemptByProviderPayment(input: AutoRechargeProviderPaymentUpdate): Promise<void>;
103
+ updateAutoRechargeAttemptByProviderPayment(input: AutoRechargeProviderPaymentUpdate): Promise<boolean>;
111
104
  getAutoRechargeOperationalWindow(userId: string): Promise<{
112
105
  maxRecharges: number;
113
106
  windowStart: string;
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/billing/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,KAAK,EAAE,UAAU,EAAiB,MAAM,sBAAsB,CAAC;AAC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