@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
package/README.md CHANGED
@@ -101,6 +101,17 @@ document:
101
101
  await bursar.catalog.publishAndActivate(config);
102
102
  ```
103
103
 
104
+ Low-balance notifications are emitted when a committed debit crosses a configured
105
+ threshold from above. They use the balance change for that operation, including
106
+ the net debit after allowance, and need no process-local rearming after grants or
107
+ refunds. Team deductions include `teamId` in the notification data. These are
108
+ in-process notifications, so durable delivery requires an application-owned
109
+ mechanism.
110
+
111
+ Successful usage deductions and lease settlements report `amount` as the net
112
+ credit balance debit after allowance; `allowanceConsumed` reports the portion
113
+ covered by allowance separately. An allowance-only charge has an `amount` of zero.
114
+
104
115
  ## Framework integrations
105
116
 
106
117
  Framework integrations are optional subpaths; the credits, metering, and
@@ -212,6 +223,10 @@ try {
212
223
  }
213
224
  ```
214
225
 
226
+ When supplying `operationType` for a reservation or affordability check, it
227
+ must match the operation in the usage metrics. When settling a reservation, the metrics
228
+ operation must also match the reserved operation.
229
+
215
230
  `StoreError.indeterminate` means a transport failure occurred when a mutation
216
231
  may have reached PostgreSQL. Retry only with the same idempotency key. A plain
217
232
  `StoreError` is deliberately non-retryable; custom stores should throw
@@ -245,9 +260,10 @@ for the full S3 and ClickHouse setup.
245
260
 
246
261
  ```bash
247
262
  cd javascript
248
- bun ci # Bun 1.4.4; installs the committed bun.lock
263
+ bun ci # Bun 1.4.5; installs the committed bun.lock
249
264
  bun run typecheck
250
- bun run test # integration tests use a disposable testcontainer by default
265
+ bun run test # full suite; requires disposable PostgreSQL
266
+ bun run test:unit # database-free suites only
251
267
  bun run lint
252
268
  bun run build
253
269
  ```
@@ -255,7 +271,8 @@ bun run build
255
271
  Bun manages development dependencies and scripts; consumers of the published
256
272
  package do not need it. See
257
273
  [CONTRIBUTING.md](https://github.com/Zonastery/bursar/blob/main/CONTRIBUTING.md).
258
- An externally supplied `DATABASE_URL` also requires
274
+ The full suite starts a disposable testcontainer by default and fails if it
275
+ cannot start PostgreSQL. An externally supplied `DATABASE_URL` also requires
259
276
  `BURSAR_ALLOW_DATABASE_RESET=1`; the integration harness truncates Bursar data.
260
277
 
261
278
  ## License
@@ -1 +1 @@
1
- {"version":3,"file":"auto-recharge-service.d.ts","sourceRoot":"","sources":["../../src/billing/auto-recharge-service.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;A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AC3B,GAAG,OAAO,CAAC,uBAAuB,GAAG,IAAI,CAAC,CAM1C;IAEK,SAAS,CAAC,KAAK,EAAE;QACrB,MAAM,EAAE,MAAM,CAAC;QACf,QAAQ,EAAE,eAAe,CAAC;KAC3B,GAAG,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC,CA4B5C;IAEK,MAAM,CAAC,KAAK,EAAE;QAClB,MAAM,EAAE,MAAM,CAAC;QACf,QAAQ,EAAE,eAAe,CAAC;QAC1B,OAAO,EAAE,OAAO,CAAC;QACjB,SAAS,CAAC,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC,CAyB5C;IAEK,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAS3C;IAEK,KAAK,CAAC,KAAK,EAAE;QACjB,MAAM,EAAE,MAAM,CAAC;QACf,QAAQ,EAAE,eAAe,CAAC;QAC1B,OAAO,EAAE,OAAO,CAAC;QACjB,SAAS,CAAC,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CASrC;IAEK,eAAe,CAAC,KAAK,EAAE;QAC3B,MAAM,EAAE,MAAM,CAAC;QACf,QAAQ,EAAE,eAAe,CAAC;QAC1B,OAAO,EAAE,OAAO,CAAC;QACjB,SAAS,CAAC,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CA4FrC;CACF"}
@@ -211,10 +211,12 @@ export class AutoRechargeService {
211
211
  });
212
212
  if (!attempt)
213
213
  return { outcome: "limit_reached" };
214
- // A transport error leaves the provider outcome unknown. The database
215
- // returns that in-flight attempt on the next claim; replay the provider
216
- // request with its original key so a committed charge cannot be duplicated.
217
- if (attempt.idempotencyKey !== idempotencyKey && attempt.state !== "unknown") {
214
+ // An existing attempt may have reached the provider. Its original request
215
+ // is not stored and provider idempotency keys can expire, so reconstructing
216
+ // and resending it could charge twice. If no payment ID was bound before
217
+ // the response was lost, an operator must verify and bind it before replaying
218
+ // the verified payment webhook.
219
+ if (attempt.idempotencyKey !== idempotencyKey) {
218
220
  return { outcome: "already_processing" };
219
221
  }
220
222
  let charge;
@@ -1 +1 @@
1
- {"version":3,"file":"auto-recharge-service.js","sourceRoot":"","sources":["../../src/billing/auto-recharge-service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AACpF,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EACL,yBAAyB,EACzB,8BAA8B,EAC9B,0BAA0B,EAC1B,mCAAmC,GACpC,MAAM,cAAc,CAAC;AAStB,OAAO,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EAAE,0BAA0B,EAAE,MAAM,0BAA0B,CAAC;AAiCtE,MAAM,OAAO,mBAAmB;IACD,OAAO;IAApC,YAA6B,OAAgC;uBAAhC,OAAO;IAA4B,CAAC;IAEzD,KAAK,CAAC,MAAM,CAClB,QAAyB,EACzB,OAA2C;QAE3C,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,wBAAwB,EAAE,CAAC;QAC1D,IAAI,CAAC,GAAG;YAAE,OAAO,IAAI,CAAC;QACtB,MAAM,MAAM,GAAG,kBAAkB,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC;QACzE,MAAM,IAAI,GAAG,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC;QAC1C,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QAEvB,MAAM,QAAQ,GAAG,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,cAAc,C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,OAAO,CAAC,yBAAyB,CAAC;gBAC3C,EAAE,EAAE,OAAO,CAAC,EAAE;gBACd,KAAK,EAAE,YAAY;gBACnB,iBAAiB,EAAE,MAAM,CAAC,iBAAiB,IAAI,IAAI;aACpD,CAAC,CAAC;YACH,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,CAAC;QAC1C,CAAC;QAED,MAAM,IAAI,CAAC,OAAO,CAAC,yBAAyB,CAAC;YAC3C,EAAE,EAAE,OAAO,CAAC,EAAE;YACd,KAAK,EAAE,QAAQ;YACf,iBAAiB,EAAE,MAAM,CAAC,iBAAiB,IAAI,IAAI;YACnD,WAAW,EAAE,gBAAgB;SAC9B,CAAC,CAAC;QACH,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC;IACvC,CAAC;CACF","sourcesContent":["import { offerIsAvailable } from \"../config/availability.js\";\nimport { hasProviderBinding, resolveProviderId } from \"../config/parse-commerce.js\";\nimport { Decimal } from \"decimal.js\";\nimport { loadConfigFromDict } from \"../config.js\";\nimport {\n AutoRechargeDisabledError,\n AutoRechargeNotConfiguredError,\n PaymentMethodRequiredError,\n ProviderCapabilityNotSupportedError,\n} from \"../errors.js\";\nimport type { BillingAutoRechargeProfile, BillingAutoRechargeStatus } from \"./types/index.js\";\nimport type {\n PaymentMethodInfo,\n PaymentProvider,\n SavedPaymentChargeQuote,\n SavedPaymentChargeResult,\n} from \"../providers/types.js\";\nimport type { AutoRechargeBillingPort } from \"./auto-recharge-port.js\";\nimport { resolveAutoRechargeWindow } from \"./policy-window.js\";\nimport { persistedDiagnosticSummary } from \"../shared/diagnostics.js\";\n\nexport type AutoRechargeOutcome =\n | \"not_configured\"\n | \"disabled\"\n | \"above_threshold\"\n | \"already_processing\"\n | \"limit_reached\"\n | \"submitted\"\n | \"action_required\"\n | \"failed\";\n\nexport interface AutoRechargeProcessResult {\n outcome: AutoRechargeOutcome;\n charge?: SavedPaymentChargeResult | null;\n}\n\ninterface ResolvedAutoRechargePolicy {\n enabled: true;\n threshold: Decimal;\n topupKey: string;\n topupId: string;\n quantity: number;\n maxChargesPerWindow: number;\n windowUnit: \"second\" | \"minute\" | \"hour\" | \"day\" | \"week\" | \"month\" | \"year\";\n windowCount: number;\n windowAnchor: \"calendar\" | \"rolling\";\n windowTimezone: string;\n windowStart: string;\n windowEnd: string;\n productId: string;\n}\n\nexport class AutoRechargeService {\n constructor(private readonly billing: AutoRechargeBillingPort) {}\n\n private async policy(\n provider: PaymentProvider,\n profile?: BillingAutoRechargeProfile | null,\n ): Promise<ResolvedAutoRechargePolicy | null> {\n const raw = await this.billing.getActiveCatalogDocument();\n if (!raw) return null;\n const config = loadConfigFromDict(raw, this.billing.providerEnvironment);\n const auto = config.commerce.autoRecharge;\n if (!auto) return null;\n\n const topupKey = profile?.enabled ? profile.topupKey : auto.eligibleTopups[0];\n if (!topupKey || !auto.eligibleTopups.includes(topupKey)) return null;\n const quantity = profile?.enabled ? profile.quantity : auto.quantity.default;\n if (quantity < auto.quantity.minimum || quantity > auto.quantity.maximum) return null;\n const topup = config.commerce.offers[topupKey];\n if (!topup || topup.type !== \"topup\" || !offerIsAvailable(topup.availability)) return null;\n if (\n profile?.enabled &&\n (profile.threshold.lt(auto.balanceBelow.minimum) ||\n profile.threshold.gt(auto.balanceBelow.maximum))\n )\n return null;\n if (topup.price.amountMinor > auto.limits.maxChargeMinor / quantity) return null;\n const reference = topup.providers[provider.provider];\n if (!reference) return null;\n const referenceId =\n reference.type === \"stripe_price\"\n ? reference.priceId\n : reference.type === \"dodo_product\"\n ? reference.productId\n : reference.externalId;\n if (\n typeof referenceId !== \"string\" &&\n (!this.billing.providerEnvironment ||\n !hasProviderBinding(reference, this.billing.providerEnvironment))\n )\n return null;\n\n const productId = resolveProviderId(referenceId, this.billing.providerEnvironment);\n const resolvedTopup =\n reference.type === \"stripe_price\"\n ? await this.billing.resolveTopup(provider.provider, null, productId)\n : reference.type === \"dodo_product\"\n ? await this.billing.resolveTopup(provider.provider, productId, null)\n : await this.billing.resolveTopupByLookup(provider.provider, productId);\n if (!resolvedTopup) return null;\n\n const period = resolveAutoRechargeWindow(auto.limits.window);\n return {\n enabled: true,\n threshold: profile?.enabled ? profile.threshold : auto.balanceBelow.default,\n topupKey,\n topupId: resolvedTopup.topupId,\n quantity,\n maxChargesPerWindow: auto.limits.maxPurchases,\n windowUnit: period.unit,\n windowCount: period.count,\n windowAnchor: period.anchor,\n windowTimezone: period.timezone,\n windowStart: period.start,\n windowEnd: period.end,\n productId,\n };\n }\n\n private async paymentMethod(\n userId: string,\n provider: PaymentProvider,\n ): Promise<{ customerId: string; method: PaymentMethodInfo } | null> {\n const customer = await this.billing.getCustomerByUserId(userId, provider.provider);\n if (!customer) return null;\n if (!provider.listPaymentMethods) {\n throw new ProviderCapabilityNotSupportedError(provider.provider, \"listPaymentMethods\");\n }\n const methods = await provider.listPaymentMethods(customer.providerCustomerId);\n const method =\n methods.find((candidate) => candidate.isDefault) ??\n (methods.length === 1 ? methods[0] : null);\n return method ? { customerId: customer.providerCustomerId, method } : null;\n }\n\n private preview(\n provider: PaymentProvider,\n policy: ResolvedAutoRechargePolicy,\n payment: { customerId: string; method: PaymentMethodInfo },\n ): Promise<SavedPaymentChargeQuote> | null {\n if (!provider.previewSavedPaymentCharge) return null;\n return provider.previewSavedPaymentCharge({\n customerId: payment.customerId,\n paymentMethodId: payment.method.id,\n productId: policy.productId,\n quantity: policy.quantity,\n metadata: {},\n idempotencyKey: \"auto-recharge-preview\",\n });\n }\n\n async quote(input: {\n userId: string;\n provider: PaymentProvider;\n }): Promise<SavedPaymentChargeQuote | null> {\n const policy = await this.policy(input.provider);\n if (!policy) return null;\n const payment = await this.paymentMethod(input.userId, input.provider);\n if (!payment) return null;\n return this.preview(input.provider, policy, payment);\n }\n\n async getStatus(input: {\n userId: string;\n provider: PaymentProvider;\n }): Promise<BillingAutoRechargeStatus | null> {\n const profile = await this.billing.getAutoRechargeProfile(input.userId);\n const policy = await this.policy(input.provider, profile);\n if (!policy) return null;\n const window = await this.billing.getAutoRechargeOperationalWindow(input.userId);\n if (!window) return null;\n const payment = profile?.enabled\n ? await this.paymentMethod(input.userId, input.provider)\n : null;\n const quote = payment ? await this.preview(input.provider, policy, payment) : null;\n return {\n enabled: Boolean(profile?.enabled),\n state: profile?.enabled ? profile.state : \"disabled\",\n thresholdCredits: policy.threshold,\n topupKey: policy.topupKey,\n quantity: policy.quantity,\n maxRecharges: window.maxRecharges,\n windowStart: window.windowStart,\n windowEnd: window.windowEnd,\n rechargesInWindow: window.count,\n paymentMethodId: payment?.method.id ?? null,\n paymentMethodLast4: payment?.method.last4 ?? null,\n paymentMethodBrand: payment?.method.brand ?? null,\n suspendedReason: profile?.state === \"paused\" ? \"auto_recharge_paused\" : null,\n pendingAttemptId: null,\n quoteAmountMinor: quote?.amountMinor ?? null,\n quoteCurrency: quote?.currency ?? null,\n };\n }\n\n async enable(input: {\n userId: string;\n provider: PaymentProvider;\n balance: Decimal;\n returnUrl?: string;\n }): Promise<BillingAutoRechargeStatus | null> {\n const policy = await this.policy(input.provider);\n if (!policy) throw new AutoRechargeNotConfiguredError();\n const payment = await this.paymentMethod(input.userId, input.provider);\n if (!payment) throw new PaymentMethodRequiredError();\n\n const profile: BillingAutoRechargeProfile = {\n userId: input.userId,\n enabled: true,\n state: \"active\",\n armed: true,\n provider: input.provider.provider,\n topupId: policy.topupId,\n topupKey: policy.topupKey,\n quantity: policy.quantity,\n threshold: policy.threshold,\n maxChargesPerWindow: policy.maxChargesPerWindow,\n windowUnit: policy.windowUnit,\n windowCount: policy.windowCount,\n windowAnchor: policy.windowAnchor,\n windowTimezone: policy.windowTimezone,\n };\n await this.billing.upsertAutoRechargeProfile(profile);\n await this.processIfNeeded(input);\n return this.getStatus(input);\n }\n\n async disable(userId: string): Promise<void> {\n const profile = await this.billing.getAutoRechargeProfile(userId);\n if (!profile) return;\n await this.billing.upsertAutoRechargeProfile({\n ...profile,\n enabled: false,\n state: \"disabled\",\n armed: true,\n });\n }\n\n async retry(input: {\n userId: string;\n provider: PaymentProvider;\n balance: Decimal;\n returnUrl?: string;\n }): Promise<AutoRechargeProcessResult> {\n const profile = await this.billing.getAutoRechargeProfile(input.userId);\n if (!profile?.enabled) throw new AutoRechargeDisabledError();\n const policy = await this.policy(input.provider, profile);\n if (!policy || profile.provider !== input.provider.provider)\n return { outcome: \"not_configured\" };\n if (!(await this.billing.resumeAutoRechargeProfile(profile)))\n return { outcome: \"not_configured\" };\n return this.processIfNeeded(input);\n }\n\n async processIfNeeded(input: {\n userId: string;\n provider: PaymentProvider;\n balance: Decimal;\n returnUrl?: string;\n }): Promise<AutoRechargeProcessResult> {\n const profile = await this.billing.getAutoRechargeProfile(input.userId);\n if (!profile?.enabled || profile.state !== \"active\") return { outcome: \"disabled\" };\n const policy = await this.policy(input.provider, profile);\n if (!policy) return { outcome: \"not_configured\" };\n if (profile.provider !== input.provider.provider) return { outcome: \"not_configured\" };\n if (input.balance.gte(policy.threshold)) {\n return { outcome: \"above_threshold\" };\n }\n\n const payment = await this.paymentMethod(input.userId, input.provider);\n if (!payment) return { outcome: \"failed\" };\n if (!input.provider.chargeSavedPaymentMethod) {\n throw new ProviderCapabilityNotSupportedError(\n input.provider.provider,\n \"chargeSavedPaymentMethod\",\n );\n }\n const idempotencyKey = `auto-recharge:${input.userId}:${globalThis.crypto.randomUUID()}`;\n const attempt = await this.billing.claimAutoRechargeAttempt({\n userId: input.userId,\n idempotencyKey,\n expectedProductId: policy.productId,\n expectedQuantity: policy.quantity,\n expectedTopupKey: policy.topupKey,\n });\n if (!attempt) return { outcome: \"limit_reached\" };\n // A transport error leaves the provider outcome unknown. The database\n // returns that in-flight attempt on the next claim; replay the provider\n // request with its original key so a committed charge cannot be duplicated.\n if (attempt.idempotencyKey !== idempotencyKey && attempt.state !== \"unknown\") {\n return { outcome: \"already_processing\" };\n }\n\n let charge: SavedPaymentChargeResult;\n try {\n charge = await input.provider.chargeSavedPaymentMethod({\n customerId: payment.customerId,\n paymentMethodId: payment.method.id,\n productId: policy.productId,\n quantity: policy.quantity,\n returnUrl: input.returnUrl,\n idempotencyKey: attempt.idempotencyKey,\n metadata: {\n auto_recharge_attempt_id: attempt.id,\n purpose: \"credit_topup\",\n bursar_account_id: input.userId,\n },\n });\n } catch (cause) {\n await this.billing.updateAutoRechargeAttempt({\n id: attempt.id,\n state: \"unknown\",\n failureCode: \"provider_request_failed\",\n failureMessage: persistedDiagnosticSummary(cause, \"auto_recharge_provider_failed\"),\n });\n throw cause;\n }\n if (charge.status === \"requires_customer_action\") {\n await this.billing.updateAutoRechargeAttempt({\n id: attempt.id,\n state: \"action_required\",\n providerAttemptId: charge.providerPaymentId ?? null,\n });\n return { outcome: \"action_required\", charge };\n }\n if (\n charge.status === \"succeeded\" ||\n charge.status === \"processing\" ||\n charge.status === \"requires_merchant_action\" ||\n charge.status === \"requires_confirmation\" ||\n charge.status === \"requires_capture\" ||\n charge.status === \"partially_captured\" ||\n charge.status === \"partially_captured_and_capturable\"\n ) {\n await this.billing.updateAutoRechargeAttempt({\n id: attempt.id,\n state: \"processing\",\n providerAttemptId: charge.providerPaymentId ?? null,\n });\n return { outcome: \"submitted\", charge };\n }\n\n await this.billing.updateAutoRechargeAttempt({\n id: attempt.id,\n state: \"failed\",\n providerAttemptId: charge.providerPaymentId ?? null,\n failureCode: \"payment_failed\",\n });\n return { outcome: \"failed\", charge };\n }\n}\n"]}
1
+ {"version":3,"file":"auto-recharge-service.js","sourceRoot":"","sources":["../../src/billing/auto-recharge-service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AACpF,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EACL,yBAAyB,EACzB,8BAA8B,EAC9B,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AAE,CAAC;IACvC,CAAC;CACF","sourcesContent":["import { offerIsAvailable } from \"../config/availability.js\";\nimport { hasProviderBinding, resolveProviderId } from \"../config/parse-commerce.js\";\nimport { Decimal } from \"decimal.js\";\nimport { loadConfigFromDict } from \"../config.js\";\nimport {\n AutoRechargeDisabledError,\n AutoRechargeNotConfiguredError,\n PaymentMethodRequiredError,\n ProviderCapabilityNotSupportedError,\n} from \"../errors.js\";\nimport type { BillingAutoRechargeProfile, BillingAutoRechargeStatus } from \"./types/index.js\";\nimport type {\n PaymentMethodInfo,\n PaymentProvider,\n SavedPaymentChargeQuote,\n SavedPaymentChargeResult,\n} from \"../providers/types.js\";\nimport type { AutoRechargeBillingPort } from \"./auto-recharge-port.js\";\nimport { resolveAutoRechargeWindow } from \"./policy-window.js\";\nimport { persistedDiagnosticSummary } from \"../shared/diagnostics.js\";\n\nexport type AutoRechargeOutcome =\n | \"not_configured\"\n | \"disabled\"\n | \"above_threshold\"\n | \"already_processing\"\n | \"limit_reached\"\n | \"submitted\"\n | \"action_required\"\n | \"failed\";\n\nexport interface AutoRechargeProcessResult {\n outcome: AutoRechargeOutcome;\n charge?: SavedPaymentChargeResult | null;\n}\n\ninterface ResolvedAutoRechargePolicy {\n enabled: true;\n threshold: Decimal;\n topupKey: string;\n topupId: string;\n quantity: number;\n maxChargesPerWindow: number;\n windowUnit: \"second\" | \"minute\" | \"hour\" | \"day\" | \"week\" | \"month\" | \"year\";\n windowCount: number;\n windowAnchor: \"calendar\" | \"rolling\";\n windowTimezone: string;\n windowStart: string;\n windowEnd: string;\n productId: string;\n}\n\nexport class AutoRechargeService {\n constructor(private readonly billing: AutoRechargeBillingPort) {}\n\n private async policy(\n provider: PaymentProvider,\n profile?: BillingAutoRechargeProfile | null,\n ): Promise<ResolvedAutoRechargePolicy | null> {\n const raw = await this.billing.getActiveCatalogDocument();\n if (!raw) return null;\n const config = loadConfigFromDict(raw, this.billing.providerEnvironment);\n const auto = config.commerce.autoRecharge;\n if (!auto) return null;\n\n const topupKey = profile?.enabled ? profile.topupKey : auto.eligibleTopups[0];\n if (!topupKey || !auto.eligibleTopups.includes(topupKey)) return null;\n const quantity = profile?.enabled ? profile.quantity : auto.quantity.default;\n if (quantity < auto.quantity.minimum || quantity > auto.quantity.maximum) return null;\n const topup = config.commerce.offers[topupKey];\n if (!topup || topup.type !== \"topup\" || !offerIsAvailable(topup.availability)) return null;\n if (\n profile?.enabled &&\n (profile.threshold.lt(auto.balanceBelow.minimum) ||\n profile.threshold.gt(auto.balanceBelow.maximum))\n )\n return null;\n if (topup.price.amountMinor > auto.limits.maxChargeMinor / quantity) return null;\n const reference = topup.providers[provider.provider];\n if (!reference) return null;\n const referenceId =\n reference.type === \"stripe_price\"\n ? reference.priceId\n : reference.type === \"dodo_product\"\n ? reference.productId\n : reference.externalId;\n if (\n typeof referenceId !== \"string\" &&\n (!this.billing.providerEnvironment ||\n !hasProviderBinding(reference, this.billing.providerEnvironment))\n )\n return null;\n\n const productId = resolveProviderId(referenceId, this.billing.providerEnvironment);\n const resolvedTopup =\n reference.type === \"stripe_price\"\n ? await this.billing.resolveTopup(provider.provider, null, productId)\n : reference.type === \"dodo_product\"\n ? await this.billing.resolveTopup(provider.provider, productId, null)\n : await this.billing.resolveTopupByLookup(provider.provider, productId);\n if (!resolvedTopup) return null;\n\n const period = resolveAutoRechargeWindow(auto.limits.window);\n return {\n enabled: true,\n threshold: profile?.enabled ? profile.threshold : auto.balanceBelow.default,\n topupKey,\n topupId: resolvedTopup.topupId,\n quantity,\n maxChargesPerWindow: auto.limits.maxPurchases,\n windowUnit: period.unit,\n windowCount: period.count,\n windowAnchor: period.anchor,\n windowTimezone: period.timezone,\n windowStart: period.start,\n windowEnd: period.end,\n productId,\n };\n }\n\n private async paymentMethod(\n userId: string,\n provider: PaymentProvider,\n ): Promise<{ customerId: string; method: PaymentMethodInfo } | null> {\n const customer = await this.billing.getCustomerByUserId(userId, provider.provider);\n if (!customer) return null;\n if (!provider.listPaymentMethods) {\n throw new ProviderCapabilityNotSupportedError(provider.provider, \"listPaymentMethods\");\n }\n const methods = await provider.listPaymentMethods(customer.providerCustomerId);\n const method =\n methods.find((candidate) => candidate.isDefault) ??\n (methods.length === 1 ? methods[0] : null);\n return method ? { customerId: customer.providerCustomerId, method } : null;\n }\n\n private preview(\n provider: PaymentProvider,\n policy: ResolvedAutoRechargePolicy,\n payment: { customerId: string; method: PaymentMethodInfo },\n ): Promise<SavedPaymentChargeQuote> | null {\n if (!provider.previewSavedPaymentCharge) return null;\n return provider.previewSavedPaymentCharge({\n customerId: payment.customerId,\n paymentMethodId: payment.method.id,\n productId: policy.productId,\n quantity: policy.quantity,\n metadata: {},\n idempotencyKey: \"auto-recharge-preview\",\n });\n }\n\n async quote(input: {\n userId: string;\n provider: PaymentProvider;\n }): Promise<SavedPaymentChargeQuote | null> {\n const policy = await this.policy(input.provider);\n if (!policy) return null;\n const payment = await this.paymentMethod(input.userId, input.provider);\n if (!payment) return null;\n return this.preview(input.provider, policy, payment);\n }\n\n async getStatus(input: {\n userId: string;\n provider: PaymentProvider;\n }): Promise<BillingAutoRechargeStatus | null> {\n const profile = await this.billing.getAutoRechargeProfile(input.userId);\n const policy = await this.policy(input.provider, profile);\n if (!policy) return null;\n const window = await this.billing.getAutoRechargeOperationalWindow(input.userId);\n if (!window) return null;\n const payment = profile?.enabled\n ? await this.paymentMethod(input.userId, input.provider)\n : null;\n const quote = payment ? await this.preview(input.provider, policy, payment) : null;\n return {\n enabled: Boolean(profile?.enabled),\n state: profile?.enabled ? profile.state : \"disabled\",\n thresholdCredits: policy.threshold,\n topupKey: policy.topupKey,\n quantity: policy.quantity,\n maxRecharges: window.maxRecharges,\n windowStart: window.windowStart,\n windowEnd: window.windowEnd,\n rechargesInWindow: window.count,\n paymentMethodId: payment?.method.id ?? null,\n paymentMethodLast4: payment?.method.last4 ?? null,\n paymentMethodBrand: payment?.method.brand ?? null,\n suspendedReason: profile?.state === \"paused\" ? \"auto_recharge_paused\" : null,\n pendingAttemptId: null,\n quoteAmountMinor: quote?.amountMinor ?? null,\n quoteCurrency: quote?.currency ?? null,\n };\n }\n\n async enable(input: {\n userId: string;\n provider: PaymentProvider;\n balance: Decimal;\n returnUrl?: string;\n }): Promise<BillingAutoRechargeStatus | null> {\n const policy = await this.policy(input.provider);\n if (!policy) throw new AutoRechargeNotConfiguredError();\n const payment = await this.paymentMethod(input.userId, input.provider);\n if (!payment) throw new PaymentMethodRequiredError();\n\n const profile: BillingAutoRechargeProfile = {\n userId: input.userId,\n enabled: true,\n state: \"active\",\n armed: true,\n provider: input.provider.provider,\n topupId: policy.topupId,\n topupKey: policy.topupKey,\n quantity: policy.quantity,\n threshold: policy.threshold,\n maxChargesPerWindow: policy.maxChargesPerWindow,\n windowUnit: policy.windowUnit,\n windowCount: policy.windowCount,\n windowAnchor: policy.windowAnchor,\n windowTimezone: policy.windowTimezone,\n };\n await this.billing.upsertAutoRechargeProfile(profile);\n await this.processIfNeeded(input);\n return this.getStatus(input);\n }\n\n async disable(userId: string): Promise<void> {\n const profile = await this.billing.getAutoRechargeProfile(userId);\n if (!profile) return;\n await this.billing.upsertAutoRechargeProfile({\n ...profile,\n enabled: false,\n state: \"disabled\",\n armed: true,\n });\n }\n\n async retry(input: {\n userId: string;\n provider: PaymentProvider;\n balance: Decimal;\n returnUrl?: string;\n }): Promise<AutoRechargeProcessResult> {\n const profile = await this.billing.getAutoRechargeProfile(input.userId);\n if (!profile?.enabled) throw new AutoRechargeDisabledError();\n const policy = await this.policy(input.provider, profile);\n if (!policy || profile.provider !== input.provider.provider)\n return { outcome: \"not_configured\" };\n if (!(await this.billing.resumeAutoRechargeProfile(profile)))\n return { outcome: \"not_configured\" };\n return this.processIfNeeded(input);\n }\n\n async processIfNeeded(input: {\n userId: string;\n provider: PaymentProvider;\n balance: Decimal;\n returnUrl?: string;\n }): Promise<AutoRechargeProcessResult> {\n const profile = await this.billing.getAutoRechargeProfile(input.userId);\n if (!profile?.enabled || profile.state !== \"active\") return { outcome: \"disabled\" };\n const policy = await this.policy(input.provider, profile);\n if (!policy) return { outcome: \"not_configured\" };\n if (profile.provider !== input.provider.provider) return { outcome: \"not_configured\" };\n if (input.balance.gte(policy.threshold)) {\n return { outcome: \"above_threshold\" };\n }\n\n const payment = await this.paymentMethod(input.userId, input.provider);\n if (!payment) return { outcome: \"failed\" };\n if (!input.provider.chargeSavedPaymentMethod) {\n throw new ProviderCapabilityNotSupportedError(\n input.provider.provider,\n \"chargeSavedPaymentMethod\",\n );\n }\n const idempotencyKey = `auto-recharge:${input.userId}:${globalThis.crypto.randomUUID()}`;\n const attempt = await this.billing.claimAutoRechargeAttempt({\n userId: input.userId,\n idempotencyKey,\n expectedProductId: policy.productId,\n expectedQuantity: policy.quantity,\n expectedTopupKey: policy.topupKey,\n });\n if (!attempt) return { outcome: \"limit_reached\" };\n // An existing attempt may have reached the provider. Its original request\n // is not stored and provider idempotency keys can expire, so reconstructing\n // and resending it could charge twice. If no payment ID was bound before\n // the response was lost, an operator must verify and bind it before replaying\n // the verified payment webhook.\n if (attempt.idempotencyKey !== idempotencyKey) {\n return { outcome: \"already_processing\" };\n }\n\n let charge: SavedPaymentChargeResult;\n try {\n charge = await input.provider.chargeSavedPaymentMethod({\n customerId: payment.customerId,\n paymentMethodId: payment.method.id,\n productId: policy.productId,\n quantity: policy.quantity,\n returnUrl: input.returnUrl,\n idempotencyKey: attempt.idempotencyKey,\n metadata: {\n auto_recharge_attempt_id: attempt.id,\n purpose: \"credit_topup\",\n bursar_account_id: input.userId,\n },\n });\n } catch (cause) {\n await this.billing.updateAutoRechargeAttempt({\n id: attempt.id,\n state: \"unknown\",\n failureCode: \"provider_request_failed\",\n failureMessage: persistedDiagnosticSummary(cause, \"auto_recharge_provider_failed\"),\n });\n throw cause;\n }\n if (charge.status === \"requires_customer_action\") {\n await this.billing.updateAutoRechargeAttempt({\n id: attempt.id,\n state: \"action_required\",\n providerAttemptId: charge.providerPaymentId ?? null,\n });\n return { outcome: \"action_required\", charge };\n }\n if (\n charge.status === \"succeeded\" ||\n charge.status === \"processing\" ||\n charge.status === \"requires_merchant_action\" ||\n charge.status === \"requires_confirmation\" ||\n charge.status === \"requires_capture\" ||\n charge.status === \"partially_captured\" ||\n charge.status === \"partially_captured_and_capturable\"\n ) {\n await this.billing.updateAutoRechargeAttempt({\n id: attempt.id,\n state: \"processing\",\n providerAttemptId: charge.providerPaymentId ?? null,\n });\n return { outcome: \"submitted\", charge };\n }\n\n await this.billing.updateAutoRechargeAttempt({\n id: attempt.id,\n state: \"failed\",\n providerAttemptId: charge.providerPaymentId ?? null,\n failureCode: \"payment_failed\",\n });\n return { outcome: \"failed\", charge };\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { BillingStore } from "./billing-store.js";
2
- import type { BillingAutoRechargeAttempt, BillingAutoRechargeAttemptState, BillingAutoRechargeProfile, BillingCustomerRecord, BillingEvent, BillingEventResult, BillingOfferResult, BillingPreferences, BillingSubscriptionChange, BillingSubscriptionChangeInput, BillingSubscriptionState, BillingTopupResult, CheckoutIntent } from "./types/index.js";
2
+ import type { BillingAutoRechargeAttempt, BillingAutoRechargeAttemptState, BillingAutoRechargeProfile, BillingCustomerRecord, BillingEvent, BillingEventResult, BillingOfferResult, BillingPreferences, BillingSubscriptionChange, BillingSubscriptionChangeInput, BillingSubscriptionState, BillingTopupResult, CheckoutIntent, ListBillingInvoicesOptions } from "./types/index.js";
3
3
  import { AutoRechargeService } from "./auto-recharge-service.js";
4
4
  import type { BillingServiceOptions } from "./service-types.js";
5
5
  import type { JsonObject } from "../shared/json.js";
@@ -25,9 +25,17 @@ export declare class BillingService {
25
25
  getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null>;
26
26
  getActiveSubscription(userId: string): Promise<BillingSubscriptionState | null>;
27
27
  getUserPreferences(userId: string): Promise<BillingPreferences | null>;
28
- listBillingInvoices(userId: string): Promise<import("./contracts.js").BillingInvoiceRecord[]>;
28
+ listBillingInvoices(userId: string, options?: ListBillingInvoicesOptions): Promise<import("./index.js").BillingInvoicePage>;
29
+ hasBillingInvoice(userId: string, provider: string, providerInvoiceId: string): Promise<boolean>;
30
+ getOwnedBillingPaymentDocument(userId: string, provider: string, providerPaymentId: string, providerDocumentId: string, options?: {
31
+ requireInvoiceLink?: boolean;
32
+ }): Promise<{
33
+ providerPaymentId: string;
34
+ providerInvoiceId: string | null;
35
+ } | null>;
29
36
  upsertBillingSubscription(state: BillingSubscriptionState): Promise<void>;
30
37
  createBillingSubscriptionChange(input: BillingSubscriptionChangeInput): Promise<BillingSubscriptionChange>;
38
+ findBillingSubscriptionChange(provider: string, subscriptionId: string, operationKey: string): Promise<BillingSubscriptionChange | null>;
31
39
  getOpenBillingSubscriptionChange(provider: string, providerSubscriptionId: string): Promise<BillingSubscriptionChange | null>;
32
40
  updateBillingSubscriptionChange(id: string, update: Parameters<BillingStore["updateBillingSubscriptionChange"]>[1]): Promise<void>;
33
41
  recordSubscriptionConflict(input: Parameters<BillingStore["recordSubscriptionConflict"]>[0]): Promise<void>;
@@ -52,6 +60,12 @@ export declare class BillingService {
52
60
  expectedQuantity: number;
53
61
  expectedTopupKey: string;
54
62
  }): Promise<BillingAutoRechargeAttempt | null>;
63
+ /**
64
+ * Advance a recharge attempt. To reconcile an unknown provider outcome,
65
+ * first independently verify the provider payment and its attempt, subject,
66
+ * amount and currency; bind its ID with state `processing`, then replay the
67
+ * verified payment webhook. Never infer the payment solely from metadata.
68
+ */
55
69
  updateAutoRechargeAttempt(input: {
56
70
  id: string;
57
71
  state: BillingAutoRechargeAttemptState;
@@ -63,10 +77,12 @@ export declare class BillingService {
63
77
  updateAutoRechargeAttemptByProviderPayment(input: {
64
78
  provider: string;
65
79
  providerPaymentId: string;
80
+ expectedAttemptId?: string;
81
+ expectedUserId?: string;
66
82
  state: BillingAutoRechargeAttemptState;
67
83
  failureCode?: string | null;
68
84
  failureMessage?: string | null;
69
- }): Promise<void>;
85
+ }): Promise<boolean>;
70
86
  getAutoRechargeOperationalWindow(userId: string): Promise<{
71
87
  maxRecharges: number;
72
88
  windowStart: string;
@@ -1 +1 @@
1
- {"version":3,"file":"billing-service.d.ts","sourceRoot":"","sources":["../../src/billing/billing-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EACV,0BAA0B,EAC1B,+BAA+B,EAC/B,0BAA0B,EAC1B,qBAAqB,EACrB,YAAY,EACZ,kBAAkB,EAClB,kBAAkB,EAClB,kBAAkB,EAClB,yBAAyB,EACzB,8BAA8B,EAC9B,wBAAwB,EACxB,kBAAkB,EAClB,cAAc,EACf,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAGjE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAChE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,YAAY,EAAE,uBAAuB,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAEzF;;;GAGG;AACH,qBAAa,cAAc;IACzB,QAAQ,CAAC,YAAY,EAAE,mBAAmB,CAAC;IAC3C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAe;IAErC,IAAI,mBAAmB,4CAEtB;IACD,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAoB;IAC/C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAwB;IAE/C,IAAI,eAAe,IAAI,OAAO,CAE7B;IAED,YAAY,KAAK,EAAE,YAAY,EAAE,OAAO,CAAC,EAAE,qBAAqB,EAK/D;IAEK,yBAAyB,CAC7B,KAAK,EAAE,UAAU,CAAC,YAAY,CAAC,2BAA2B,CAAC,CAAC,CAAC,CAAC,CAAC,GAC9D,OAAO,CAAC,cAAc,CAAC,CAEzB;IAEK,oBAAoB,CACxB,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,UAAU,CAAC,YAAY,CAAC,sBAAsB,C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Q,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAEpC;IAEK,cAAc,CAClB,QAAQ,EAAE,MAAM,EAChB,kBAAkB,EAAE,MAAM,EAC1B,MAAM,EAAE,MAAM,EACd,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,GACpB,OAAO,CAAC,IAAI,CAAC,CAEf;IAEK,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,wBAAwB,GAAG,IAAI,CAAC,CAYlF;IAEK,uBAAuB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,wBAAwB,GAAG,IAAI,CAAC,CAQtF;IAEK,yBAAyB,CAAC,GAAG,OAAa,GAAG,OAAO,CAAC,MAAM,CAAC,CAmBjE;YAEa,mBAAmB;IAyBjC,mDAAmD;IACnD,oBAAoB,IAAI,IAAI,CAE3B;IAEK,kBAAkB,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAEzE;CACF"}
@@ -41,8 +41,26 @@ export class BillingService {
41
41
  async getUserPreferences(userId) {
42
42
  return this.management.getUserPreferences(userId);
43
43
  }
44
- async listBillingInvoices(userId) {
45
- return this.management.listBillingInvoices(userId);
44
+ async listBillingInvoices(userId, options) {
45
+ return this.management.listBillingInvoices(userId, options);
46
+ }
47
+ async hasBillingInvoice(userId, provider, providerInvoiceId) {
48
+ return this.store.hasBillingInvoice(userId, provider, providerInvoiceId);
49
+ }
50
+ async getOwnedBillingPaymentDocument(userId, provider, providerPaymentId, providerDocumentId, options) {
51
+ const payment = await this.store.getBillingPayment(provider, providerPaymentId);
52
+ if (payment !== null &&
53
+ payment.userId === userId &&
54
+ payment.provider === provider &&
55
+ payment.providerPaymentId === providerPaymentId &&
56
+ (payment.providerInvoiceId === providerDocumentId ||
57
+ (!options?.requireInvoiceLink && payment.providerPaymentId === providerDocumentId))) {
58
+ return {
59
+ providerPaymentId: payment.providerPaymentId,
60
+ providerInvoiceId: payment.providerInvoiceId,
61
+ };
62
+ }
63
+ return null;
46
64
  }
47
65
  async upsertBillingSubscription(state) {
48
66
  await this.management.upsertBillingSubscription(state);
@@ -50,6 +68,9 @@ export class BillingService {
50
68
  async createBillingSubscriptionChange(input) {
51
69
  return this.management.createBillingSubscriptionChange(input);
52
70
  }
71
+ async findBillingSubscriptionChange(provider, subscriptionId, operationKey) {
72
+ return this.management.findBillingSubscriptionChange(provider, subscriptionId, operationKey);
73
+ }
53
74
  async getOpenBillingSubscriptionChange(provider, providerSubscriptionId) {
54
75
  return this.management.getOpenBillingSubscriptionChange(provider, providerSubscriptionId);
55
76
  }
@@ -89,11 +110,17 @@ export class BillingService {
89
110
  async claimAutoRechargeAttempt(input) {
90
111
  return this.management.claimAutoRechargeAttempt(input);
91
112
  }
113
+ /**
114
+ * Advance a recharge attempt. To reconcile an unknown provider outcome,
115
+ * first independently verify the provider payment and its attempt, subject,
116
+ * amount and currency; bind its ID with state `processing`, then replay the
117
+ * verified payment webhook. Never infer the payment solely from metadata.
118
+ */
92
119
  async updateAutoRechargeAttempt(input) {
93
120
  await this.management.updateAutoRechargeAttempt(input);
94
121
  }
95
122
  async updateAutoRechargeAttemptByProviderPayment(input) {
96
- await this.management.updateAutoRechargeAttemptByProviderPayment(input);
123
+ return this.management.updateAutoRechargeAttemptByProviderPayment(input);
97
124
  }
98
125
  async getAutoRechargeOperationalWindow(userId) {
99
126
  return this.management.getAutoRechargeOperationalWindow(userId);
@@ -120,13 +147,15 @@ export class BillingService {
120
147
  await this.management.upsertCustomer(provider, providerCustomerId, userId, email);
121
148
  }
122
149
  async getUserSubscription(userId) {
150
+ // Keep an older active subscription visible when a historical provider
151
+ // reports its cancellation later. Only fall back to canceled history when
152
+ // no current subscription exists.
123
153
  const subscription = await this.store.getUserSubscription(userId, [
124
154
  SUBSCRIPTION_STATUS.ACTIVE,
125
155
  SUBSCRIPTION_STATUS.TRIALING,
126
- SUBSCRIPTION_STATUS.CANCELED,
127
156
  SUBSCRIPTION_STATUS.PAST_DUE,
128
157
  SUBSCRIPTION_STATUS.INCOMPLETE,
129
- // EXPIRED excluded — expired subscriptions are not "current" for billing purposes.
158
+ SUBSCRIPTION_STATUS.CANCELED,
130
159
  ]);
131
160
  return this.expireGraceIfNeeded(subscription);
132
161
  }
@@ -1 +1 @@
1
- {"version":3,"file":"billing-service.js","sourceRoot":"","sources":["../../src/billing/billing-service.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAKpD;;;GAGG;AACH,MAAM,OAAO,cAAc;IAChB,YAAY,CAAsB;IAC1B,KAAK,CAAe;IAErC,IAAI,mBAAmB;QACrB,OAAO,IAAI,CAAC,KAAK,CAAC,mBAAmB,CAAC;IACxC,CAAC;IACgB,UAAU,CAAoB;IAC9B,MAAM,CAAwB;IAE/C,IAAI,eAAe;QACjB,OAAO,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC;IACrC,CAAC;IAED,YAAY,KAAmB,EAAE,OAA+B;QAC9D,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,UAAU,GAAG,IAAI,iBAAiB,CAAC,KAAK,CAAC,CAAC;QAC/C,IAAI,CAAC,MAAM,GAAG,IAAI,qBAAqB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;QACxD,IAAI,CAAC,YAAY,GAAG,IAAI,mBAAmB,CAAC,IAAI,CAAC,CAAC;IACpD,CAAC;IAED,KAAK,CAAC,yBAAyB,CAC7B,KAA+D;QAE/D,OAAO,IAAI,CAAC,UAAU,CAAC,yBAAyB,CAAC,KAAK,CAAC,CAAC;IAC1D,CAAC;IAED,KAAK,CAAC,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IAChF,CAAC;IAED,mDAAmD;IACnD,oBAAoB;QAClB,IAAI,CAAC,MAAM,CAAC,oBAAoB,EAAE,CAAC;IACrC,CAAC;IAED,KAAK,CAAC,kBAAkB,CAAC,KAAmB;QAC1C,OAAO,IAAI,CAAC,MAAM,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAC/C,CAAC;CACF","sourcesContent":["import type { BillingStore } from \"./billing-store.js\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeAttemptState,\n BillingAutoRechargeProfile,\n BillingCustomerRecord,\n BillingEvent,\n BillingEventResult,\n BillingOfferResult,\n BillingPreferences,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionState,\n BillingTopupResult,\n CheckoutIntent,\n} from \"./types/index.js\";\nimport { SUBSCRIPTION_STATUS } from \"./types/index.js\";\nimport { AutoRechargeService } from \"./auto-recharge-service.js\";\nimport { BillingEventProcessor } from \"./event-processor.js\";\nimport { BillingManagement } from \"./management.js\";\nimport type { BillingServiceOptions } from \"./service-types.js\";\nimport type { JsonObject } from \"../shared/json.js\";\nexport type { BillingProvisioningPort, BillingServiceOptions } from \"./service-types.js\";\n\n/**\n * Provider-agnostic billing lifecycle state machine.\n * Mirrors the Python billing service implementation.\n */\nexport class BillingService {\n readonly autoRecharge: AutoRechargeService;\n private readonly store: BillingStore;\n\n get providerEnvironment() {\n return this.store.providerEnvironment;\n }\n private readonly management: BillingManagement;\n private readonly events: BillingEventProcessor;\n\n get hasProvisioning(): boolean {\n return this.events.hasProvisioning;\n }\n\n constructor(store: BillingStore, options?: BillingServiceOptions) {\n this.store = store;\n this.management = new BillingManagement(store);\n this.events = new BillingEventProcessor(store, options);\n this.autoRecharge = new AutoRechargeService(this);\n }\n\n async createOrGetCheckoutIntent(\n input: Parameters<BillingStore[\"createOrGetCheckoutIntent\"]>[0],\n ): Promise<CheckoutIntent> {\n return this.management.createOrGetCheckoutIntent(input);\n }\n\n async updateCheckoutIntent(\n id: string,\n update: Parameters<BillingStore[\"updateCheckoutIntent\"]>[1],\n ): Promise<void> {\n await this.management.updateCheckoutIntent(id, update);\n }\n\n async findCheckoutIntent(subjectId: string, operationKey: string, provider?: string) {\n return this.store.findCheckoutIntent(subjectId, operationKey, provider);\n }\n\n async getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null> {\n return this.management.getCheckoutIntent(id, subjectId);\n }\n\n async getActiveSubscription(userId: string): Promise<BillingSubscriptionState | null> {\n return this.management.getActiveSubscription(userId);\n }\n\n async getUserPreferences(userId: string): Promise<BillingPreferences | null> {\n return this.management.getUserPreferences(userId);\n }\n\n async listBillingInvoices(userId: string) {\n return this.management.listBillingInvoices(userId);\n }\n\n async upsertBillingSubscription(state: BillingSubscriptionState): Promise<void> {\n await this.management.upsertBillingSubscription(state);\n }\n\n async createBillingSubscriptionChange(\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n return this.management.createBillingSubscriptionChange(input);\n }\n\n async getOpenBillingSubscriptionChange(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.management.getOpenBillingSubscriptionChange(provider, providerSubscriptionId);\n }\n\n async updateBillingSubscriptionChange(\n id: string,\n update: Parameters<BillingStore[\"updateBillingSubscriptionChange\"]>[1],\n ): Promise<void> {\n await this.management.updateBillingSubscriptionChange(id, update);\n }\n\n async recordSubscriptionConflict(\n input: Parameters<BillingStore[\"recordSubscriptionConflict\"]>[0],\n ): Promise<void> {\n await this.management.recordSubscriptionConflict(input);\n }\n\n async updateUserPreferences(preferences: BillingPreferences): Promise<void> {\n await this.management.updateUserPreferences(preferences);\n }\n\n async getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n return this.management.getAutoRechargeProfile(userId);\n }\n\n async getActiveCatalogRevision(): Promise<{ id: string; config: JsonObject } | null> {\n return this.store.getActiveCatalogRevision();\n }\n\n async getActiveCatalogDocument(): Promise<JsonObject | null> {\n return this.management.getActiveCatalogDocument();\n }\n\n async listCancellableProviderSubscriptionIds(userId: string): Promise<string[]> {\n return this.management.listCancellableProviderSubscriptionIds(userId);\n }\n\n async listCancellableSubscriptions(userId: string): Promise<BillingSubscriptionState[]> {\n return this.management.listCancellableSubscriptions(userId);\n }\n\n async pseudonymizeFinancialSubject(userId: string): Promise<void> {\n await this.management.pseudonymizeFinancialSubject(userId);\n }\n\n async upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void> {\n await this.management.upsertAutoRechargeProfile(profile, options);\n }\n\n async resumeAutoRechargeProfile(profile: BillingAutoRechargeProfile): Promise<boolean> {\n return this.management.resumeAutoRechargeProfile(profile);\n }\n\n async claimAutoRechargeAttempt(input: {\n userId: string;\n idempotencyKey: string;\n expectedProductId: string;\n expectedQuantity: number;\n expectedTopupKey: string;\n }): Promise<BillingAutoRechargeAttempt | null> {\n return this.management.claimAutoRechargeAttempt(input);\n }\n\n async updateAutoRechargeAttempt(input: {\n id: string;\n state: BillingAutoRechargeAttemptState;\n providerAttemptId?: string | null;\n failureCode?: string | null;\n failureMessage?: string | null;\n metadata?: JsonObject;\n }): Promise<void> {\n await this.management.updateAutoRechargeAttempt(input);\n }\n\n async updateAutoRechargeAttemptByProviderPayment(input: {\n provider: string;\n providerPaymentId: string;\n state: BillingAutoRechargeAttemptState;\n failureCode?: string | null;\n failureMessage?: string | null;\n }): Promise<void> {\n await this.management.updateAutoRechargeAttemptByProviderPayment(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.management.getAutoRechargeOperationalWindow(userId);\n }\n\n async countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number> {\n return this.management.countAutoRechargeAttempts(userId, since);\n }\n\n async getCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null> {\n return this.management.getCustomerByUserId(userId, provider);\n }\n\n async resolveOffer(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingOfferResult | null> {\n return this.management.resolveOffer(provider, productId, priceId);\n }\n\n async resolveOfferByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingOfferResult | null> {\n return this.management.resolveOfferByLookup(provider, lookupKey);\n }\n\n async resolveTopup(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingTopupResult | null> {\n return this.management.resolveTopup(provider, productId, priceId);\n }\n\n async resolveTopupByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingTopupResult | null> {\n return this.management.resolveTopupByLookup(provider, lookupKey);\n }\n\n async upsertCustomer(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email?: string | null,\n ): Promise<void> {\n await this.management.upsertCustomer(provider, providerCustomerId, userId, email);\n }\n\n async getUserSubscription(userId: string): Promise<BillingSubscriptionState | null> {\n const subscription = await this.store.getUserSubscription(userId, [\n SUBSCRIPTION_STATUS.ACTIVE,\n SUBSCRIPTION_STATUS.TRIALING,\n SUBSCRIPTION_STATUS.CANCELED,\n SUBSCRIPTION_STATUS.PAST_DUE,\n SUBSCRIPTION_STATUS.INCOMPLETE,\n // EXPIRED excluded — expired subscriptions are not \"current\" for billing purposes.\n ]);\n return this.expireGraceIfNeeded(subscription);\n }\n\n async getBlockingSubscription(userId: string): Promise<BillingSubscriptionState | null> {\n const subscription = await this.store.getUserSubscription(userId, [\n SUBSCRIPTION_STATUS.ACTIVE,\n SUBSCRIPTION_STATUS.TRIALING,\n SUBSCRIPTION_STATUS.PAST_DUE,\n SUBSCRIPTION_STATUS.INCOMPLETE,\n ]);\n return this.expireGraceIfNeeded(subscription);\n }\n\n async expirePastDueGracePeriods(now = new Date()): Promise<number> {\n if (!this.events.hasProvisioning) return 0;\n const asOf = now.toISOString();\n const candidates = await this.store.listExpiredGraceSubscriptions(asOf);\n let expiredCount = 0;\n for (const candidate of candidates) {\n if (!candidate.subscriptionId || !candidate.graceEndsAt) continue;\n if (\n await this.store.expireSubscriptionGracePeriod(\n candidate.userId,\n candidate.subscriptionId,\n candidate.graceEndsAt,\n asOf,\n )\n ) {\n expiredCount += 1;\n }\n }\n return expiredCount;\n }\n\n private async expireGraceIfNeeded(\n subscription: BillingSubscriptionState | null,\n ): Promise<BillingSubscriptionState | null> {\n if (\n !subscription ||\n !this.events.hasProvisioning ||\n subscription.status !== \"past_due\" ||\n subscription.graceExpiredAt ||\n !subscription.graceEndsAt ||\n new Date(subscription.graceEndsAt).getTime() > Date.now() ||\n !subscription.subscriptionId\n ) {\n return subscription;\n }\n\n const expiredAt = new Date().toISOString();\n const marked = await this.store.expireSubscriptionGracePeriod(\n subscription.userId,\n subscription.subscriptionId,\n subscription.graceEndsAt,\n expiredAt,\n );\n return marked ? { ...subscription, graceExpiredAt: expiredAt } : subscription;\n }\n\n /** Invalidate cached provider offer resolution. */\n invalidateOfferCache(): void {\n this.events.invalidateOfferCache();\n }\n\n async ingestBillingEvent(event: BillingEvent): Promise<BillingEventResult> {\n return this.events.ingestBillingEvent(event);\n }\n}\n"]}
1
+ {"version":3,"file":"billing-service.js","sourceRoot":"","sources":["../../src/billing/billing-service.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAKpD;;;GAGG;AACH,MAAM,OAAO,cAAc;IAChB,YAAY,CAAsB;IAC1B,KAAK,CAAe;IAErC,IAAI,mBAAmB;QACrB,OAAO,IAAI,CAAC,KAAK,CAAC,mBAAmB,CAAC;IACxC,CAAC;IACgB,UAAU,CAAoB;IAC9B,MAAM,CAAwB;IAE/C,IAAI,eAAe;QACjB,OAAO,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC;I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C,WAAW,EAAE,CAAC;QAC3C,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,6BAA6B,CAC3D,YAAY,CAAC,MAAM,EACnB,YAAY,CAAC,cAAc,EAC3B,YAAY,CAAC,WAAW,EACxB,SAAS,CACV,CAAC;QACF,OAAO,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,YAAY,EAAE,cAAc,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,YAAY,CAAC;IAChF,CAAC;IAED,mDAAmD;IACnD,oBAAoB;QAClB,IAAI,CAAC,MAAM,CAAC,oBAAoB,EAAE,CAAC;IACrC,CAAC;IAED,KAAK,CAAC,kBAAkB,CAAC,KAAmB;QAC1C,OAAO,IAAI,CAAC,MAAM,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAC/C,CAAC;CACF","sourcesContent":["import type { BillingStore } from \"./billing-store.js\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeAttemptState,\n BillingAutoRechargeProfile,\n BillingCustomerRecord,\n BillingEvent,\n BillingEventResult,\n BillingOfferResult,\n BillingPreferences,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionState,\n BillingTopupResult,\n CheckoutIntent,\n ListBillingInvoicesOptions,\n} from \"./types/index.js\";\nimport { SUBSCRIPTION_STATUS } from \"./types/index.js\";\nimport { AutoRechargeService } from \"./auto-recharge-service.js\";\nimport { BillingEventProcessor } from \"./event-processor.js\";\nimport { BillingManagement } from \"./management.js\";\nimport type { BillingServiceOptions } from \"./service-types.js\";\nimport type { JsonObject } from \"../shared/json.js\";\nexport type { BillingProvisioningPort, BillingServiceOptions } from \"./service-types.js\";\n\n/**\n * Provider-agnostic billing lifecycle state machine.\n * Mirrors the Python billing service implementation.\n */\nexport class BillingService {\n readonly autoRecharge: AutoRechargeService;\n private readonly store: BillingStore;\n\n get providerEnvironment() {\n return this.store.providerEnvironment;\n }\n private readonly management: BillingManagement;\n private readonly events: BillingEventProcessor;\n\n get hasProvisioning(): boolean {\n return this.events.hasProvisioning;\n }\n\n constructor(store: BillingStore, options?: BillingServiceOptions) {\n this.store = store;\n this.management = new BillingManagement(store);\n this.events = new BillingEventProcessor(store, options);\n this.autoRecharge = new AutoRechargeService(this);\n }\n\n async createOrGetCheckoutIntent(\n input: Parameters<BillingStore[\"createOrGetCheckoutIntent\"]>[0],\n ): Promise<CheckoutIntent> {\n return this.management.createOrGetCheckoutIntent(input);\n }\n\n async updateCheckoutIntent(\n id: string,\n update: Parameters<BillingStore[\"updateCheckoutIntent\"]>[1],\n ): Promise<void> {\n await this.management.updateCheckoutIntent(id, update);\n }\n\n async findCheckoutIntent(subjectId: string, operationKey: string, provider?: string) {\n return this.store.findCheckoutIntent(subjectId, operationKey, provider);\n }\n\n async getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null> {\n return this.management.getCheckoutIntent(id, subjectId);\n }\n\n async getActiveSubscription(userId: string): Promise<BillingSubscriptionState | null> {\n return this.management.getActiveSubscription(userId);\n }\n\n async getUserPreferences(userId: string): Promise<BillingPreferences | null> {\n return this.management.getUserPreferences(userId);\n }\n\n async listBillingInvoices(userId: string, options?: ListBillingInvoicesOptions) {\n return this.management.listBillingInvoices(userId, options);\n }\n\n async hasBillingInvoice(userId: string, provider: string, providerInvoiceId: string) {\n return this.store.hasBillingInvoice(userId, provider, providerInvoiceId);\n }\n\n async getOwnedBillingPaymentDocument(\n userId: string,\n provider: string,\n providerPaymentId: string,\n providerDocumentId: string,\n options?: { requireInvoiceLink?: boolean },\n ): Promise<{\n providerPaymentId: string;\n providerInvoiceId: string | null;\n } | null> {\n const payment = await this.store.getBillingPayment(provider, providerPaymentId);\n if (\n payment !== null &&\n payment.userId === userId &&\n payment.provider === provider &&\n payment.providerPaymentId === providerPaymentId &&\n (payment.providerInvoiceId === providerDocumentId ||\n (!options?.requireInvoiceLink && payment.providerPaymentId === providerDocumentId))\n ) {\n return {\n providerPaymentId: payment.providerPaymentId,\n providerInvoiceId: payment.providerInvoiceId,\n };\n }\n return null;\n }\n\n async upsertBillingSubscription(state: BillingSubscriptionState): Promise<void> {\n await this.management.upsertBillingSubscription(state);\n }\n\n async createBillingSubscriptionChange(\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n return this.management.createBillingSubscriptionChange(input);\n }\n\n async findBillingSubscriptionChange(\n provider: string,\n subscriptionId: string,\n operationKey: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.management.findBillingSubscriptionChange(provider, subscriptionId, operationKey);\n }\n\n async getOpenBillingSubscriptionChange(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.management.getOpenBillingSubscriptionChange(provider, providerSubscriptionId);\n }\n\n async updateBillingSubscriptionChange(\n id: string,\n update: Parameters<BillingStore[\"updateBillingSubscriptionChange\"]>[1],\n ): Promise<void> {\n await this.management.updateBillingSubscriptionChange(id, update);\n }\n\n async recordSubscriptionConflict(\n input: Parameters<BillingStore[\"recordSubscriptionConflict\"]>[0],\n ): Promise<void> {\n await this.management.recordSubscriptionConflict(input);\n }\n\n async updateUserPreferences(preferences: BillingPreferences): Promise<void> {\n await this.management.updateUserPreferences(preferences);\n }\n\n async getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n return this.management.getAutoRechargeProfile(userId);\n }\n\n async getActiveCatalogRevision(): Promise<{\n id: string;\n config: JsonObject;\n } | null> {\n return this.store.getActiveCatalogRevision();\n }\n\n async getActiveCatalogDocument(): Promise<JsonObject | null> {\n return this.management.getActiveCatalogDocument();\n }\n\n async listCancellableProviderSubscriptionIds(userId: string): Promise<string[]> {\n return this.management.listCancellableProviderSubscriptionIds(userId);\n }\n\n async listCancellableSubscriptions(userId: string): Promise<BillingSubscriptionState[]> {\n return this.management.listCancellableSubscriptions(userId);\n }\n\n async pseudonymizeFinancialSubject(userId: string): Promise<void> {\n await this.management.pseudonymizeFinancialSubject(userId);\n }\n\n async upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void> {\n await this.management.upsertAutoRechargeProfile(profile, options);\n }\n\n async resumeAutoRechargeProfile(profile: BillingAutoRechargeProfile): Promise<boolean> {\n return this.management.resumeAutoRechargeProfile(profile);\n }\n\n async claimAutoRechargeAttempt(input: {\n userId: string;\n idempotencyKey: string;\n expectedProductId: string;\n expectedQuantity: number;\n expectedTopupKey: string;\n }): Promise<BillingAutoRechargeAttempt | null> {\n return this.management.claimAutoRechargeAttempt(input);\n }\n\n /**\n * Advance a recharge attempt. To reconcile an unknown provider outcome,\n * first independently verify the provider payment and its attempt, subject,\n * amount and currency; bind its ID with state `processing`, then replay the\n * verified payment webhook. Never infer the payment solely from metadata.\n */\n async updateAutoRechargeAttempt(input: {\n id: string;\n state: BillingAutoRechargeAttemptState;\n providerAttemptId?: string | null;\n failureCode?: string | null;\n failureMessage?: string | null;\n metadata?: JsonObject;\n }): Promise<void> {\n await this.management.updateAutoRechargeAttempt(input);\n }\n\n async updateAutoRechargeAttemptByProviderPayment(input: {\n provider: string;\n providerPaymentId: string;\n expectedAttemptId?: string;\n expectedUserId?: string;\n state: BillingAutoRechargeAttemptState;\n failureCode?: string | null;\n failureMessage?: string | null;\n }): Promise<boolean> {\n return this.management.updateAutoRechargeAttemptByProviderPayment(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.management.getAutoRechargeOperationalWindow(userId);\n }\n\n async countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number> {\n return this.management.countAutoRechargeAttempts(userId, since);\n }\n\n async getCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null> {\n return this.management.getCustomerByUserId(userId, provider);\n }\n\n async resolveOffer(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingOfferResult | null> {\n return this.management.resolveOffer(provider, productId, priceId);\n }\n\n async resolveOfferByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingOfferResult | null> {\n return this.management.resolveOfferByLookup(provider, lookupKey);\n }\n\n async resolveTopup(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingTopupResult | null> {\n return this.management.resolveTopup(provider, productId, priceId);\n }\n\n async resolveTopupByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingTopupResult | null> {\n return this.management.resolveTopupByLookup(provider, lookupKey);\n }\n\n async upsertCustomer(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email?: string | null,\n ): Promise<void> {\n await this.management.upsertCustomer(provider, providerCustomerId, userId, email);\n }\n\n async getUserSubscription(userId: string): Promise<BillingSubscriptionState | null> {\n // Keep an older active subscription visible when a historical provider\n // reports its cancellation later. Only fall back to canceled history when\n // no current subscription exists.\n const subscription = await this.store.getUserSubscription(userId, [\n SUBSCRIPTION_STATUS.ACTIVE,\n SUBSCRIPTION_STATUS.TRIALING,\n SUBSCRIPTION_STATUS.PAST_DUE,\n SUBSCRIPTION_STATUS.INCOMPLETE,\n SUBSCRIPTION_STATUS.CANCELED,\n ]);\n return this.expireGraceIfNeeded(subscription);\n }\n\n async getBlockingSubscription(userId: string): Promise<BillingSubscriptionState | null> {\n const subscription = await this.store.getUserSubscription(userId, [\n SUBSCRIPTION_STATUS.ACTIVE,\n SUBSCRIPTION_STATUS.TRIALING,\n SUBSCRIPTION_STATUS.PAST_DUE,\n SUBSCRIPTION_STATUS.INCOMPLETE,\n ]);\n return this.expireGraceIfNeeded(subscription);\n }\n\n async expirePastDueGracePeriods(now = new Date()): Promise<number> {\n if (!this.events.hasProvisioning) return 0;\n const asOf = now.toISOString();\n const candidates = await this.store.listExpiredGraceSubscriptions(asOf);\n let expiredCount = 0;\n for (const candidate of candidates) {\n if (!candidate.subscriptionId || !candidate.graceEndsAt) continue;\n if (\n await this.store.expireSubscriptionGracePeriod(\n candidate.userId,\n candidate.subscriptionId,\n candidate.graceEndsAt,\n asOf,\n )\n ) {\n expiredCount += 1;\n }\n }\n return expiredCount;\n }\n\n private async expireGraceIfNeeded(\n subscription: BillingSubscriptionState | null,\n ): Promise<BillingSubscriptionState | null> {\n if (\n !subscription ||\n !this.events.hasProvisioning ||\n subscription.status !== \"past_due\" ||\n subscription.graceExpiredAt ||\n !subscription.graceEndsAt ||\n new Date(subscription.graceEndsAt).getTime() > Date.now() ||\n !subscription.subscriptionId\n ) {\n return subscription;\n }\n\n const expiredAt = new Date().toISOString();\n const marked = await this.store.expireSubscriptionGracePeriod(\n subscription.userId,\n subscription.subscriptionId,\n subscription.graceEndsAt,\n expiredAt,\n );\n return marked ? { ...subscription, graceExpiredAt: expiredAt } : subscription;\n }\n\n /** Invalidate cached provider offer resolution. */\n invalidateOfferCache(): void {\n this.events.invalidateOfferCache();\n }\n\n async ingestBillingEvent(event: BillingEvent): Promise<BillingEventResult> {\n return this.events.ingestBillingEvent(event);\n }\n}\n"]}
@@ -1,6 +1,5 @@
1
- import type { BillingAutoRechargeAttempt, BillingAutoRechargeProfile, BillingCustomerRecord, BillingCreditPostingResult, BillingEventClaim, BillingOfferResult, BillingPaymentRecord, BillingPreferences, BillingSubscriptionChange, BillingSubscriptionChangeInput, BillingSubscriptionState, BillingSubscriptionStatus, SubscriptionEntitlementOutcome, CheckoutIntent, BillingTopupResult, BillingInvoiceRecord } from "./types/index.js";
1
+ import type { BillingAutoRechargeAttempt, BillingAutoRechargeProfile, BillingCustomerRecord, BillingCreditPostingResult, BillingEventClaim, BillingOfferResult, BillingPaymentRecord, BillingPreferences, BillingSubscriptionChange, BillingSubscriptionChangeInput, BillingSubscriptionState, BillingSubscriptionStatus, SubscriptionEntitlementOutcome, CheckoutIntent, BillingTopupResult, BillingInvoicePage, ListBillingInvoicesOptions } from "./types/index.js";
2
2
  import type { AutoRechargeAttemptClaim, AutoRechargeAttemptUpdate, AutoRechargeProviderPaymentUpdate, BillingCreditGrantCreate, BillingDisputeUpsert, BillingInvoiceUpsert, BillingPaymentUpsert, BillingRefundUpsert, BillingSubscriptionChangeUpdate, BillingSubscriptionConflictCreate, CheckoutIntentCreate, CheckoutIntentUpdate } from "./contracts.js";
3
- import type { Decimal } from "decimal.js";
4
3
  import type { ProviderEnvironment } from "../providers/environment.js";
5
4
  import type { JsonObject } from "../shared/json.js";
6
5
  /**
@@ -10,8 +9,14 @@ import type { JsonObject } from "../shared/json.js";
10
9
  * Mirrors Python bursar/billing/store.py.
11
10
  */
12
11
  export declare abstract class BillingStore {
12
+ /** Tenant bound to this store, when the backend partitions data by tenant. */
13
+ readonly tenantId?: string;
13
14
  /** Exposed by environment-partitioned stores so composition can reject drift. */
14
15
  readonly providerEnvironment?: ProviderEnvironment;
16
+ /** Atomically apply event writes and finalization. The scoped store must not escape the callback. */
17
+ abstract withBillingEventTransaction<T>(action: (store: BillingStore) => Promise<T>): Promise<T>;
18
+ /** Serialize and order payment outcomes for an invoice within the event transaction. */
19
+ abstract observeBillingInvoiceOutcome(provider: string, invoiceId: string, outcome: "paid" | "failed"): Promise<boolean>;
15
20
  abstract createOrGetCheckoutIntent(input: CheckoutIntentCreate): Promise<CheckoutIntent>;
16
21
  abstract updateCheckoutIntent(id: string, update: CheckoutIntentUpdate): Promise<void>;
17
22
  abstract getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null>;
@@ -32,22 +37,23 @@ export declare abstract class BillingStore {
32
37
  abstract getBillingCustomer(provider: string, providerCustomerId: string): Promise<string | null>;
33
38
  abstract getBillingSubscription(provider: string, providerSubscriptionId: string): Promise<BillingSubscriptionState | null>;
34
39
  abstract createBillingSubscriptionChange(input: BillingSubscriptionChangeInput): Promise<BillingSubscriptionChange>;
40
+ abstract findBillingSubscriptionChange(provider: string, subscriptionId: string, operationKey: string): Promise<BillingSubscriptionChange | null>;
35
41
  abstract getOpenBillingSubscriptionChange(provider: string, providerSubscriptionId: string): Promise<BillingSubscriptionChange | null>;
36
42
  abstract listExpiredGraceSubscriptions(now: string, limit?: number): Promise<BillingSubscriptionState[]>;
37
43
  abstract reconcileSubscriptionEntitlement(subjectId: string, subscriptionId: string, billingEventId: string, expectedStatus: BillingSubscriptionStatus, expectedProviderUpdatedAt: string, planAssignedAt: Date | string | null, applyEntitlement: boolean, reason: string): Promise<SubscriptionEntitlementOutcome>;
38
44
  abstract expireSubscriptionGracePeriod(subjectId: string, subscriptionId: string, expectedGraceEndsAt: string, expiredAt: string): Promise<boolean>;
39
45
  abstract updateBillingSubscriptionChange(id: string, update: BillingSubscriptionChangeUpdate): Promise<void>;
40
46
  abstract getUserSubscription(userId: string, statuses?: string[]): Promise<BillingSubscriptionState | null>;
41
- abstract resolveCreditTopup(provider: string, productId?: string | null, priceId?: string | null, checkoutIntentId?: string | null, subjectId?: string | null, providerPaymentId?: string | null, rechargeAttemptId?: string | null): Promise<BillingTopupResult | null>;
47
+ abstract 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>;
42
48
  abstract resolveCreditTopupByLookup(provider: string, lookupKey: string): Promise<BillingTopupResult | null>;
43
49
  abstract resolveBillingOfferByLookup(provider: string, lookupKey: string): Promise<BillingOfferResult | null>;
44
- abstract computeTopupCredits(amountMinor: number, topupConfig: BillingTopupResult): Promise<Decimal>;
45
50
  abstract upsertBillingPayment(options: BillingPaymentUpsert): Promise<string>;
46
51
  abstract createBillingCreditGrant(input: BillingCreditGrantCreate): Promise<string>;
47
52
  abstract grantBillingCredit(grantId: string, idempotencyKey: string): Promise<BillingCreditPostingResult>;
48
53
  abstract getBillingCreditGrantByPayment(paymentId: string): Promise<string | null>;
49
54
  abstract postBillingRefund(refundId: string, grantId: string, amountMinor: number, idempotencyKey: string): Promise<BillingCreditPostingResult>;
50
- abstract listBillingInvoices(userId: string): Promise<BillingInvoiceRecord[]>;
55
+ abstract listBillingInvoices(userId: string, options?: ListBillingInvoicesOptions): Promise<BillingInvoicePage>;
56
+ abstract hasBillingInvoice(userId: string, provider: string, providerInvoiceId: string): Promise<boolean>;
51
57
  abstract upsertBillingRefund(options: BillingRefundUpsert): Promise<string>;
52
58
  abstract upsertBillingInvoice(options: BillingInvoiceUpsert): Promise<void>;
53
59
  abstract upsertBillingDispute(options: BillingDisputeUpsert): Promise<void>;
@@ -69,7 +75,7 @@ export declare abstract class BillingStore {
69
75
  abstract resumeAutoRechargeProfile(profile: BillingAutoRechargeProfile): Promise<boolean>;
70
76
  abstract claimAutoRechargeAttempt(input: AutoRechargeAttemptClaim): Promise<BillingAutoRechargeAttempt | null>;
71
77
  abstract updateAutoRechargeAttempt(input: AutoRechargeAttemptUpdate): Promise<void>;
72
- abstract updateAutoRechargeAttemptByProviderPayment(input: AutoRechargeProviderPaymentUpdate): Promise<void>;
78
+ abstract updateAutoRechargeAttemptByProviderPayment(input: AutoRechargeProviderPaymentUpdate): Promise<boolean>;
73
79
  abstract getAutoRechargeOperationalWindow(userId: string): Promise<{
74
80
  maxRecharges: number;
75
81
  windowStart: string;
@@ -1 +1 @@
1
- {"version":3,"file":"billing-store.d.ts","sourceRoot":"","sources":["../../src/billing/billing-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,0BAA0B,EAC1B,0BAA0B,EAC1B,qBAAqB,EACrB,0BAA0B,EAC1B,iBAAiB,EACjB,kBAAkB,EAClB,oBAAoB,EACpB,kBAAkB,EAClB,yBAAyB,EACzB,8BAA8B,EAC9B,wBAAwB,EACxB,yBAAyB,EACzB,8BAA8B,EAC9B,cAAc,EACd,kBAAkB,EAClB,oBAAoB,EACrB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EACV,wBAAwB,EACxB,yBAAyB,EACzB,iCAAiC,EACjC,wBAAwB,EACxB,oBAAoB,EACpB,oBAAoB,EACpB,oBAAoB,EACpB,mBAAmB,EACnB,+BAA+B,EAC/B,iCAAiC,EACjC,oBAAoB,EACpB,oBAAoB,EACrB,MAA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AM,EACd,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GACvB,OAAO,CAAC,qBAAqB,GAAG,IAAI,CAAC,CAAC;CAC1C"}
@@ -5,6 +5,8 @@
5
5
  * Mirrors Python bursar/billing/store.py.
6
6
  */
7
7
  export class BillingStore {
8
+ /** Tenant bound to this store, when the backend partitions data by tenant. */
9
+ tenantId;
8
10
  /** Exposed by environment-partitioned stores so composition can reject drift. */
9
11
  providerEnvironment;
10
12
  }
@@ -1 +1 @@
1
- {"version":3,"file":"billing-store.js","sourceRoot":"","sources":["../../src/billing/billing-store.ts"],"names":[],"mappings":"AAoCA;;;;;GAKG;AACH,MAAM,OAAgB,YAAY;IAChC,iFAAiF;IACxE,mBAAmB,CAAuB;CA2LpD","sourcesContent":["import type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeProfile,\n BillingCustomerRecord,\n BillingCreditPostingResult,\n BillingEventClaim,\n BillingOfferResult,\n BillingPaymentRecord,\n BillingPreferences,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionState,\n BillingSubscriptionStatus,\n SubscriptionEntitlementOutcome,\n CheckoutIntent,\n BillingTopupResult,\n BillingInvoiceRecord,\n} from \"./types/index.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 { Decimal } from \"decimal.js\";\nimport type { ProviderEnvironment } from \"../providers/environment.js\";\nimport type { JsonObject } from \"../shared/json.js\";\n\n/**\n * Abstract billing store — provider-agnostic persistence layer for\n * subscription lifecycle state.\n *\n * Mirrors Python bursar/billing/store.py.\n */\nexport abstract class BillingStore {\n /** Exposed by environment-partitioned stores so composition can reject drift. */\n readonly providerEnvironment?: ProviderEnvironment;\n\n abstract createOrGetCheckoutIntent(input: CheckoutIntentCreate): Promise<CheckoutIntent>;\n\n abstract updateCheckoutIntent(id: string, update: CheckoutIntentUpdate): Promise<void>;\n\n abstract getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null>;\n\n abstract findCheckoutIntent(\n subjectId: string,\n operationKey: string,\n provider?: string,\n ): Promise<{ intent: CheckoutIntent; catalog: JsonObject } | null>;\n\n abstract 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\n abstract claimBillingEvent(\n provider: string,\n eventId: string,\n eventType: string,\n envelope?: JsonObject,\n ): Promise<BillingEventClaim>;\n\n abstract completeBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n ): Promise<boolean>;\n\n abstract failBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n error?: string,\n ): Promise<boolean>;\n\n abstract upsertBillingCustomer(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email?: string | null,\n ): Promise<void>;\n\n abstract upsertBillingSubscription(state: BillingSubscriptionState): Promise<void>;\n\n abstract getBillingCustomer(provider: string, providerCustomerId: string): Promise<string | null>;\n\n abstract getBillingSubscription(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionState | null>;\n\n abstract createBillingSubscriptionChange(\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange>;\n\n abstract getOpenBillingSubscriptionChange(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null>;\n\n abstract listExpiredGraceSubscriptions(\n now: string,\n limit?: number,\n ): Promise<BillingSubscriptionState[]>;\n\n abstract 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\n abstract expireSubscriptionGracePeriod(\n subjectId: string,\n subscriptionId: string,\n expectedGraceEndsAt: string,\n expiredAt: string,\n ): Promise<boolean>;\n\n abstract updateBillingSubscriptionChange(\n id: string,\n update: BillingSubscriptionChangeUpdate,\n ): Promise<void>;\n\n abstract getUserSubscription(\n userId: string,\n statuses?: string[],\n ): Promise<BillingSubscriptionState | null>;\n\n abstract 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 abstract resolveCreditTopupByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingTopupResult | null>;\n\n abstract resolveBillingOfferByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingOfferResult | null>;\n\n abstract computeTopupCredits(\n amountMinor: number,\n topupConfig: BillingTopupResult,\n ): Promise<Decimal>;\n\n abstract upsertBillingPayment(options: BillingPaymentUpsert): Promise<string>;\n abstract createBillingCreditGrant(input: BillingCreditGrantCreate): Promise<string>;\n abstract grantBillingCredit(\n grantId: string,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult>;\n abstract getBillingCreditGrantByPayment(paymentId: string): Promise<string | null>;\n abstract postBillingRefund(\n refundId: string,\n grantId: string,\n amountMinor: number,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult>;\n\n abstract listBillingInvoices(userId: string): Promise<BillingInvoiceRecord[]>;\n\n abstract upsertBillingRefund(options: BillingRefundUpsert): Promise<string>;\n\n abstract upsertBillingInvoice(options: BillingInvoiceUpsert): Promise<void>;\n\n abstract upsertBillingDispute(options: BillingDisputeUpsert): Promise<void>;\n\n abstract getBillingPayment(\n provider: string,\n providerPaymentId: string,\n ): Promise<BillingPaymentRecord | null>;\n\n abstract getActiveCatalogDocument(): Promise<JsonObject | null>;\n abstract getActiveCatalogRevision(): Promise<{ id: string; config: JsonObject } | null>;\n\n abstract pseudonymizeFinancialSubject(userId: string): Promise<boolean>;\n\n abstract getUserSubscriptions(userId: string): Promise<BillingSubscriptionState[]>;\n\n abstract recordSubscriptionConflict(input: BillingSubscriptionConflictCreate): Promise<void>;\n\n abstract getBillingPreferences(userId: string): Promise<BillingPreferences | null>;\n\n abstract upsertBillingPreferences(prefs: BillingPreferences): Promise<void>;\n abstract getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null>;\n abstract upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void>;\n abstract resumeAutoRechargeProfile(profile: BillingAutoRechargeProfile): Promise<boolean>;\n abstract claimAutoRechargeAttempt(\n input: AutoRechargeAttemptClaim,\n ): Promise<BillingAutoRechargeAttempt | null>;\n abstract updateAutoRechargeAttempt(input: AutoRechargeAttemptUpdate): Promise<void>;\n abstract updateAutoRechargeAttemptByProviderPayment(\n input: AutoRechargeProviderPaymentUpdate,\n ): Promise<void>;\n abstract getAutoRechargeOperationalWindow(userId: string): Promise<{\n maxRecharges: number;\n windowStart: string;\n windowEnd: string;\n count: number;\n } | null>;\n abstract countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number>;\n\n abstract getBillingCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null>;\n}\n"]}
1
+ {"version":3,"file":"billing-store.js","sourceRoot":"","sources":["../../src/billing/billing-store.ts"],"names":[],"mappings":"AAoCA;;;;;GAKG;AACH,MAAM,OAAgB,YAAY;IAChC,8EAA8E;IACrE,QAAQ,CAAU;IAC3B,iFAAiF;IACxE,mBAAmB,CAAuB;CAsNpD","sourcesContent":["import type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeProfile,\n BillingCustomerRecord,\n BillingCreditPostingResult,\n BillingEventClaim,\n BillingOfferResult,\n BillingPaymentRecord,\n BillingPreferences,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionState,\n BillingSubscriptionStatus,\n SubscriptionEntitlementOutcome,\n CheckoutIntent,\n BillingTopupResult,\n BillingInvoicePage,\n ListBillingInvoicesOptions,\n} from \"./types/index.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 { ProviderEnvironment } from \"../providers/environment.js\";\nimport type { JsonObject } from \"../shared/json.js\";\n\n/**\n * Abstract billing store — provider-agnostic persistence layer for\n * subscription lifecycle state.\n *\n * Mirrors Python bursar/billing/store.py.\n */\nexport abstract class BillingStore {\n /** Tenant bound to this store, when the backend partitions data by tenant. */\n readonly tenantId?: string;\n /** Exposed by environment-partitioned stores so composition can reject drift. */\n readonly providerEnvironment?: ProviderEnvironment;\n\n /** Atomically apply event writes and finalization. The scoped store must not escape the callback. */\n abstract withBillingEventTransaction<T>(action: (store: BillingStore) => Promise<T>): Promise<T>;\n\n /** Serialize and order payment outcomes for an invoice within the event transaction. */\n abstract observeBillingInvoiceOutcome(\n provider: string,\n invoiceId: string,\n outcome: \"paid\" | \"failed\",\n ): Promise<boolean>;\n\n abstract createOrGetCheckoutIntent(input: CheckoutIntentCreate): Promise<CheckoutIntent>;\n\n abstract updateCheckoutIntent(id: string, update: CheckoutIntentUpdate): Promise<void>;\n\n abstract getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null>;\n\n abstract findCheckoutIntent(\n subjectId: string,\n operationKey: string,\n provider?: string,\n ): Promise<{ intent: CheckoutIntent; catalog: JsonObject } | null>;\n\n abstract 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\n abstract claimBillingEvent(\n provider: string,\n eventId: string,\n eventType: string,\n envelope?: JsonObject,\n ): Promise<BillingEventClaim>;\n\n abstract completeBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n ): Promise<boolean>;\n\n abstract failBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n error?: string,\n ): Promise<boolean>;\n\n abstract upsertBillingCustomer(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email?: string | null,\n ): Promise<void>;\n\n abstract upsertBillingSubscription(state: BillingSubscriptionState): Promise<void>;\n\n abstract getBillingCustomer(provider: string, providerCustomerId: string): Promise<string | null>;\n\n abstract getBillingSubscription(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionState | null>;\n\n abstract createBillingSubscriptionChange(\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange>;\n\n abstract findBillingSubscriptionChange(\n provider: string,\n subscriptionId: string,\n operationKey: string,\n ): Promise<BillingSubscriptionChange | null>;\n\n abstract getOpenBillingSubscriptionChange(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null>;\n\n abstract listExpiredGraceSubscriptions(\n now: string,\n limit?: number,\n ): Promise<BillingSubscriptionState[]>;\n\n abstract 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\n abstract expireSubscriptionGracePeriod(\n subjectId: string,\n subscriptionId: string,\n expectedGraceEndsAt: string,\n expiredAt: string,\n ): Promise<boolean>;\n\n abstract updateBillingSubscriptionChange(\n id: string,\n update: BillingSubscriptionChangeUpdate,\n ): Promise<void>;\n\n abstract getUserSubscription(\n userId: string,\n statuses?: string[],\n ): Promise<BillingSubscriptionState | null>;\n\n abstract 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 abstract resolveCreditTopupByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingTopupResult | null>;\n\n abstract resolveBillingOfferByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingOfferResult | null>;\n\n abstract upsertBillingPayment(options: BillingPaymentUpsert): Promise<string>;\n abstract createBillingCreditGrant(input: BillingCreditGrantCreate): Promise<string>;\n abstract grantBillingCredit(\n grantId: string,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult>;\n abstract getBillingCreditGrantByPayment(paymentId: string): Promise<string | null>;\n abstract postBillingRefund(\n refundId: string,\n grantId: string,\n amountMinor: number,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult>;\n\n abstract listBillingInvoices(\n userId: string,\n options?: ListBillingInvoicesOptions,\n ): Promise<BillingInvoicePage>;\n abstract hasBillingInvoice(\n userId: string,\n provider: string,\n providerInvoiceId: string,\n ): Promise<boolean>;\n\n abstract upsertBillingRefund(options: BillingRefundUpsert): Promise<string>;\n\n abstract upsertBillingInvoice(options: BillingInvoiceUpsert): Promise<void>;\n\n abstract upsertBillingDispute(options: BillingDisputeUpsert): Promise<void>;\n\n abstract getBillingPayment(\n provider: string,\n providerPaymentId: string,\n ): Promise<BillingPaymentRecord | null>;\n\n abstract getActiveCatalogDocument(): Promise<JsonObject | null>;\n abstract getActiveCatalogRevision(): Promise<{\n id: string;\n config: JsonObject;\n } | null>;\n\n abstract pseudonymizeFinancialSubject(userId: string): Promise<boolean>;\n\n abstract getUserSubscriptions(userId: string): Promise<BillingSubscriptionState[]>;\n\n abstract recordSubscriptionConflict(input: BillingSubscriptionConflictCreate): Promise<void>;\n\n abstract getBillingPreferences(userId: string): Promise<BillingPreferences | null>;\n\n abstract upsertBillingPreferences(prefs: BillingPreferences): Promise<void>;\n abstract getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null>;\n abstract upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void>;\n abstract resumeAutoRechargeProfile(profile: BillingAutoRechargeProfile): Promise<boolean>;\n abstract claimAutoRechargeAttempt(\n input: AutoRechargeAttemptClaim,\n ): Promise<BillingAutoRechargeAttempt | null>;\n abstract updateAutoRechargeAttempt(input: AutoRechargeAttemptUpdate): Promise<void>;\n abstract updateAutoRechargeAttemptByProviderPayment(\n input: AutoRechargeProviderPaymentUpdate,\n ): Promise<boolean>;\n abstract getAutoRechargeOperationalWindow(userId: string): Promise<{\n maxRecharges: number;\n windowStart: string;\n windowEnd: string;\n count: number;\n } | null>;\n abstract countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number>;\n\n abstract getBillingCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null>;\n}\n"]}