@zonastery/bursar 2.1.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (334) hide show
  1. package/README.md +20 -3
  2. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  3. package/dist/billing/auto-recharge-service.js +6 -4
  4. package/dist/billing/auto-recharge-service.js.map +1 -1
  5. package/dist/billing/billing-service.d.ts +19 -3
  6. package/dist/billing/billing-service.d.ts.map +1 -1
  7. package/dist/billing/billing-service.js +34 -5
  8. package/dist/billing/billing-service.js.map +1 -1
  9. package/dist/billing/billing-store.d.ts +12 -6
  10. package/dist/billing/billing-store.d.ts.map +1 -1
  11. package/dist/billing/billing-store.js +2 -0
  12. package/dist/billing/billing-store.js.map +1 -1
  13. package/dist/billing/contracts.d.ts +20 -3
  14. package/dist/billing/contracts.d.ts.map +1 -1
  15. package/dist/billing/contracts.js.map +1 -1
  16. package/dist/billing/event-handlers.d.ts +1 -0
  17. package/dist/billing/event-handlers.d.ts.map +1 -1
  18. package/dist/billing/event-handlers.js +40 -13
  19. package/dist/billing/event-handlers.js.map +1 -1
  20. package/dist/billing/event-processor.d.ts +2 -1
  21. package/dist/billing/event-processor.d.ts.map +1 -1
  22. package/dist/billing/event-processor.js +82 -16
  23. package/dist/billing/event-processor.js.map +1 -1
  24. package/dist/billing/financial-event-handlers.d.ts +2 -0
  25. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  26. package/dist/billing/financial-event-handlers.js +160 -48
  27. package/dist/billing/financial-event-handlers.js.map +1 -1
  28. package/dist/billing/index.d.ts +1 -1
  29. package/dist/billing/index.d.ts.map +1 -1
  30. package/dist/billing/index.js.map +1 -1
  31. package/dist/billing/management.d.ts +6 -3
  32. package/dist/billing/management.d.ts.map +1 -1
  33. package/dist/billing/management.js +5 -2
  34. package/dist/billing/management.js.map +1 -1
  35. package/dist/billing/postgres/repositories/auto-recharge.d.ts +3 -1
  36. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  37. package/dist/billing/postgres/repositories/auto-recharge.js +23 -7
  38. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  39. package/dist/billing/postgres/repositories/invoice.d.ts +3 -2
  40. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  41. package/dist/billing/postgres/repositories/invoice.js +33 -3
  42. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  43. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  44. package/dist/billing/postgres/repositories/offer.js +2 -1
  45. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  46. package/dist/billing/postgres/repositories/payment.d.ts +6 -1
  47. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  48. package/dist/billing/postgres/repositories/payment.js +25 -17
  49. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  50. package/dist/billing/postgres/repositories/subscription-change.d.ts +1 -0
  51. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -1
  52. package/dist/billing/postgres/repositories/subscription-change.js +24 -4
  53. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
  54. package/dist/billing/postgres/repositories/subscription.d.ts +1 -0
  55. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  56. package/dist/billing/postgres/repositories/subscription.js +40 -43
  57. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  58. package/dist/billing/postgres/repositories/topup.d.ts +6 -1
  59. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  60. package/dist/billing/postgres/repositories/topup.js +9 -5
  61. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  62. package/dist/billing/postgres/store.d.ts +24 -31
  63. package/dist/billing/postgres/store.d.ts.map +1 -1
  64. package/dist/billing/postgres/store.js +110 -113
  65. package/dist/billing/postgres/store.js.map +1 -1
  66. package/dist/billing/types/catalog.d.ts +1 -0
  67. package/dist/billing/types/catalog.d.ts.map +1 -1
  68. package/dist/billing/types/catalog.js.map +1 -1
  69. package/dist/billing/types/documents.d.ts +15 -1
  70. package/dist/billing/types/documents.d.ts.map +1 -1
  71. package/dist/billing/types/documents.js.map +1 -1
  72. package/dist/billing/types/events.d.ts +2 -0
  73. package/dist/billing/types/events.d.ts.map +1 -1
  74. package/dist/billing/types/events.js +15 -0
  75. package/dist/billing/types/events.js.map +1 -1
  76. package/dist/billing/types/subscriptions.d.ts +10 -0
  77. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  78. package/dist/billing/types/subscriptions.js.map +1 -1
  79. package/dist/breakdown.d.ts +2 -24
  80. package/dist/breakdown.d.ts.map +1 -1
  81. package/dist/breakdown.js +1 -29
  82. package/dist/breakdown.js.map +1 -1
  83. package/dist/bursar.d.ts +5 -17
  84. package/dist/bursar.d.ts.map +1 -1
  85. package/dist/bursar.js +26 -44
  86. package/dist/bursar.js.map +1 -1
  87. package/dist/cli.js +0 -6
  88. package/dist/cli.js.map +1 -1
  89. package/dist/commerce/service.d.ts +1 -0
  90. package/dist/commerce/service.d.ts.map +1 -1
  91. package/dist/commerce/service.js +162 -38
  92. package/dist/commerce/service.js.map +1 -1
  93. package/dist/commerce/types.d.ts +2 -0
  94. package/dist/commerce/types.d.ts.map +1 -1
  95. package/dist/commerce/types.js.map +1 -1
  96. package/dist/config/normalize.d.ts +3 -1
  97. package/dist/config/normalize.d.ts.map +1 -1
  98. package/dist/config/normalize.js +12 -5
  99. package/dist/config/normalize.js.map +1 -1
  100. package/dist/config/parse-access.d.ts.map +1 -1
  101. package/dist/config/parse-access.js +4 -1
  102. package/dist/config/parse-access.js.map +1 -1
  103. package/dist/config/parse-commerce.d.ts.map +1 -1
  104. package/dist/config/parse-commerce.js +32 -17
  105. package/dist/config/parse-commerce.js.map +1 -1
  106. package/dist/config/parse-credits.d.ts.map +1 -1
  107. package/dist/config/parse-credits.js +5 -5
  108. package/dist/config/parse-credits.js.map +1 -1
  109. package/dist/config/parse-plans.d.ts.map +1 -1
  110. package/dist/config/parse-plans.js +13 -9
  111. package/dist/config/parse-plans.js.map +1 -1
  112. package/dist/config/parse-pricing.d.ts.map +1 -1
  113. package/dist/config/parse-pricing.js +7 -5
  114. package/dist/config/parse-pricing.js.map +1 -1
  115. package/dist/config/parse-utils.d.ts +2 -0
  116. package/dist/config/parse-utils.d.ts.map +1 -1
  117. package/dist/config/parse-utils.js +11 -1
  118. package/dist/config/parse-utils.js.map +1 -1
  119. package/dist/config.d.ts +2 -2
  120. package/dist/config.d.ts.map +1 -1
  121. package/dist/config.js +94 -86
  122. package/dist/config.js.map +1 -1
  123. package/dist/credits/amount.d.ts.map +1 -1
  124. package/dist/credits/amount.js +5 -4
  125. package/dist/credits/amount.js.map +1 -1
  126. package/dist/credits/catalog-runtime.d.ts +15 -2
  127. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  128. package/dist/credits/catalog-runtime.js +74 -18
  129. package/dist/credits/catalog-runtime.js.map +1 -1
  130. package/dist/credits/lease-workflow.d.ts +3 -1
  131. package/dist/credits/lease-workflow.d.ts.map +1 -1
  132. package/dist/credits/lease-workflow.js +47 -38
  133. package/dist/credits/lease-workflow.js.map +1 -1
  134. package/dist/credits/low-balance-monitor.d.ts +2 -7
  135. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  136. package/dist/credits/low-balance-monitor.js +6 -57
  137. package/dist/credits/low-balance-monitor.js.map +1 -1
  138. package/dist/credits/postgres/repositories/analytics.d.ts +3 -3
  139. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  140. package/dist/credits/postgres/repositories/analytics.js +25 -7
  141. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  142. package/dist/credits/postgres/repositories/balance.d.ts +28 -0
  143. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  144. package/dist/credits/postgres/repositories/balance.js +33 -14
  145. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  146. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
  147. package/dist/credits/postgres/repositories/bucket.js +2 -2
  148. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  149. package/dist/credits/postgres/repositories/catalog.d.ts +2 -2
  150. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
  151. package/dist/credits/postgres/repositories/catalog.js +2 -12
  152. package/dist/credits/postgres/repositories/catalog.js.map +1 -1
  153. package/dist/credits/postgres/repositories/deduction.d.ts +2 -0
  154. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  155. package/dist/credits/postgres/repositories/deduction.js +9 -2
  156. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  157. package/dist/credits/postgres/repositories/lease.d.ts +3 -0
  158. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  159. package/dist/credits/postgres/repositories/lease.js +46 -12
  160. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  161. package/dist/credits/postgres/repositories/plan.d.ts +1 -1
  162. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
  163. package/dist/credits/postgres/repositories/plan.js +4 -1
  164. package/dist/credits/postgres/repositories/plan.js.map +1 -1
  165. package/dist/credits/postgres/repositories/team.d.ts +1 -1
  166. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  167. package/dist/credits/postgres/repositories/team.js +9 -5
  168. package/dist/credits/postgres/repositories/team.js.map +1 -1
  169. package/dist/credits/postgres/store.d.ts +29 -20
  170. package/dist/credits/postgres/store.d.ts.map +1 -1
  171. package/dist/credits/postgres/store.js +329 -250
  172. package/dist/credits/postgres/store.js.map +1 -1
  173. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  174. package/dist/credits/postgres/value-mappers.js +4 -4
  175. package/dist/credits/postgres/value-mappers.js.map +1 -1
  176. package/dist/credits/rated-wire.d.ts +7 -0
  177. package/dist/credits/rated-wire.d.ts.map +1 -0
  178. package/dist/credits/rated-wire.js +70 -0
  179. package/dist/credits/rated-wire.js.map +1 -0
  180. package/dist/credits/service-errors.d.ts.map +1 -1
  181. package/dist/credits/service-errors.js +8 -1
  182. package/dist/credits/service-errors.js.map +1 -1
  183. package/dist/credits/service-types.d.ts +5 -7
  184. package/dist/credits/service-types.d.ts.map +1 -1
  185. package/dist/credits/service-types.js.map +1 -1
  186. package/dist/credits/service.d.ts +11 -9
  187. package/dist/credits/service.d.ts.map +1 -1
  188. package/dist/credits/service.js +156 -138
  189. package/dist/credits/service.js.map +1 -1
  190. package/dist/credits/store.d.ts +11 -3
  191. package/dist/credits/store.d.ts.map +1 -1
  192. package/dist/credits/store.js +9 -0
  193. package/dist/credits/store.js.map +1 -1
  194. package/dist/credits/types/account.d.ts +9 -1
  195. package/dist/credits/types/account.d.ts.map +1 -1
  196. package/dist/credits/types/account.js.map +1 -1
  197. package/dist/credits/types/admission.d.ts +1 -0
  198. package/dist/credits/types/admission.d.ts.map +1 -1
  199. package/dist/credits/types/admission.js.map +1 -1
  200. package/dist/credits/types/grants.d.ts +12 -0
  201. package/dist/credits/types/grants.d.ts.map +1 -1
  202. package/dist/credits/types/grants.js.map +1 -1
  203. package/dist/credits/types/ledger.d.ts +13 -0
  204. package/dist/credits/types/ledger.d.ts.map +1 -1
  205. package/dist/credits/types/ledger.js.map +1 -1
  206. package/dist/credits/types/quotas.d.ts +2 -1
  207. package/dist/credits/types/quotas.d.ts.map +1 -1
  208. package/dist/credits/types/quotas.js.map +1 -1
  209. package/dist/engine.d.ts.map +1 -1
  210. package/dist/engine.js +51 -34
  211. package/dist/engine.js.map +1 -1
  212. package/dist/errors.d.ts +12 -1
  213. package/dist/errors.d.ts.map +1 -1
  214. package/dist/errors.js +13 -0
  215. package/dist/errors.js.map +1 -1
  216. package/dist/expr/evaluator.d.ts.map +1 -1
  217. package/dist/expr/evaluator.js +29 -9
  218. package/dist/expr/evaluator.js.map +1 -1
  219. package/dist/expr/language.js +1 -1
  220. package/dist/expr/language.js.map +1 -1
  221. package/dist/expr.d.ts.map +1 -1
  222. package/dist/expr.js +5 -6
  223. package/dist/expr.js.map +1 -1
  224. package/dist/generated/pricing-config.schema.json +102 -202
  225. package/dist/generated/pricing-config.types.d.ts +7 -1
  226. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  227. package/dist/generated/pricing-config.types.js.map +1 -1
  228. package/dist/index.d.ts +6 -5
  229. package/dist/index.d.ts.map +1 -1
  230. package/dist/index.js +3 -2
  231. package/dist/index.js.map +1 -1
  232. package/dist/load-config-file.d.ts.map +1 -1
  233. package/dist/load-config-file.js +38 -12
  234. package/dist/load-config-file.js.map +1 -1
  235. package/dist/metrics.d.ts +1 -1
  236. package/dist/metrics.d.ts.map +1 -1
  237. package/dist/metrics.js.map +1 -1
  238. package/dist/node.d.ts +1 -1
  239. package/dist/node.d.ts.map +1 -1
  240. package/dist/node.js.map +1 -1
  241. package/dist/pricing-decimal.d.ts +7 -0
  242. package/dist/pricing-decimal.d.ts.map +1 -0
  243. package/dist/pricing-decimal.js +43 -0
  244. package/dist/pricing-decimal.js.map +1 -0
  245. package/dist/providers/dodo/better-auth-core.d.ts +1 -1
  246. package/dist/providers/dodo/better-auth-core.d.ts.map +1 -1
  247. package/dist/providers/dodo/better-auth-core.js +2 -2
  248. package/dist/providers/dodo/better-auth-core.js.map +1 -1
  249. package/dist/providers/dodo/better-auth.d.ts.map +1 -1
  250. package/dist/providers/dodo/better-auth.js +16 -2
  251. package/dist/providers/dodo/better-auth.js.map +1 -1
  252. package/dist/providers/dodo/event-mapper.d.ts +1 -1
  253. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  254. package/dist/providers/dodo/event-mapper.js +120 -18
  255. package/dist/providers/dodo/event-mapper.js.map +1 -1
  256. package/dist/providers/dodo/nextjs-core.d.ts +1 -1
  257. package/dist/providers/dodo/nextjs-core.d.ts.map +1 -1
  258. package/dist/providers/dodo/nextjs-core.js +2 -2
  259. package/dist/providers/dodo/nextjs-core.js.map +1 -1
  260. package/dist/providers/dodo/nextjs.d.ts.map +1 -1
  261. package/dist/providers/dodo/nextjs.js +16 -6
  262. package/dist/providers/dodo/nextjs.js.map +1 -1
  263. package/dist/providers/dodo/provider.d.ts +5 -2
  264. package/dist/providers/dodo/provider.d.ts.map +1 -1
  265. package/dist/providers/dodo/provider.js +33 -6
  266. package/dist/providers/dodo/provider.js.map +1 -1
  267. package/dist/providers/dodo/verified-payment-payload.d.ts +6 -0
  268. package/dist/providers/dodo/verified-payment-payload.d.ts.map +1 -0
  269. package/dist/providers/dodo/verified-payment-payload.js +42 -0
  270. package/dist/providers/dodo/verified-payment-payload.js.map +1 -0
  271. package/dist/providers/index.d.ts +1 -1
  272. package/dist/providers/index.d.ts.map +1 -1
  273. package/dist/providers/index.js.map +1 -1
  274. package/dist/providers/mock/provider.d.ts +4 -1
  275. package/dist/providers/mock/provider.d.ts.map +1 -1
  276. package/dist/providers/mock/provider.js +3 -1
  277. package/dist/providers/mock/provider.js.map +1 -1
  278. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  279. package/dist/providers/stripe/event-mapper.js +48 -20
  280. package/dist/providers/stripe/event-mapper.js.map +1 -1
  281. package/dist/providers/stripe/provider.d.ts +4 -1
  282. package/dist/providers/stripe/provider.d.ts.map +1 -1
  283. package/dist/providers/stripe/provider.js +64 -23
  284. package/dist/providers/stripe/provider.js.map +1 -1
  285. package/dist/providers/types.d.ts +11 -1
  286. package/dist/providers/types.d.ts.map +1 -1
  287. package/dist/providers/types.js +9 -0
  288. package/dist/providers/types.js.map +1 -1
  289. package/dist/shared/postgres-client.d.ts +3 -0
  290. package/dist/shared/postgres-client.d.ts.map +1 -1
  291. package/dist/shared/postgres-client.js +61 -49
  292. package/dist/shared/postgres-client.js.map +1 -1
  293. package/dist/shared/provider-rejection.d.ts +3 -0
  294. package/dist/shared/provider-rejection.d.ts.map +1 -0
  295. package/dist/shared/provider-rejection.js +17 -0
  296. package/dist/shared/provider-rejection.js.map +1 -0
  297. package/dist/shared/timestamp.d.ts +2 -0
  298. package/dist/shared/timestamp.d.ts.map +1 -1
  299. package/dist/shared/timestamp.js +7 -0
  300. package/dist/shared/timestamp.js.map +1 -1
  301. package/dist/storage/adapters/clickhouse.d.ts +1 -1
  302. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  303. package/dist/storage/adapters/clickhouse.js +18 -17
  304. package/dist/storage/adapters/clickhouse.js.map +1 -1
  305. package/dist/storage/adapters/s3.d.ts +5 -0
  306. package/dist/storage/adapters/s3.d.ts.map +1 -1
  307. package/dist/storage/adapters/s3.js +46 -14
  308. package/dist/storage/adapters/s3.js.map +1 -1
  309. package/dist/storage/diagnostics.d.ts +3 -7
  310. package/dist/storage/diagnostics.d.ts.map +1 -1
  311. package/dist/storage/diagnostics.js +6 -15
  312. package/dist/storage/diagnostics.js.map +1 -1
  313. package/dist/storage/outbox-worker.d.ts.map +1 -1
  314. package/dist/storage/outbox-worker.js +4 -3
  315. package/dist/storage/outbox-worker.js.map +1 -1
  316. package/dist/storage/ports.d.ts +3 -0
  317. package/dist/storage/ports.d.ts.map +1 -1
  318. package/dist/storage/ports.js.map +1 -1
  319. package/dist/storage/postgres-repository.d.ts +1 -3
  320. package/dist/storage/postgres-repository.d.ts.map +1 -1
  321. package/dist/storage/postgres-repository.js +10 -4
  322. package/dist/storage/postgres-repository.js.map +1 -1
  323. package/dist/storage/runtime.d.ts +15 -10
  324. package/dist/storage/runtime.d.ts.map +1 -1
  325. package/dist/storage/runtime.js +74 -68
  326. package/dist/storage/runtime.js.map +1 -1
  327. package/dist/telemetry/index.d.ts +1 -1
  328. package/dist/telemetry/index.js +1 -1
  329. package/dist/telemetry/index.js.map +1 -1
  330. package/package.json +73 -71
  331. package/dist/credits/queries.d.ts +0 -33
  332. package/dist/credits/queries.d.ts.map +0 -1
  333. package/dist/credits/queries.js +0 -71
  334. package/dist/credits/queries.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"financial-event-handlers.js","sourceRoot":"","sources":["../../src/billing/financial-event-handlers.ts"],"names":[],"mappings":"AAKA,MAAM,OAAO,6BAA6B;IAErB,KAAK;IACL,MAAM;IACN,oBAAoB;IACpB,gBAAgB;IAChB,yBAAyB;IAGzB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E,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,iBAAiB,EAAE,CAAC;QACxE,MAAM,IAAI,CAAC,KAAK,CAAC,oBAAoB,CAAC;YACpC,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,iBAAiB,EAAE,KAAK,CAAC,OAAO,CAAC,iBAAiB;YAClD,iBAAiB,EAAE,KAAK,CAAC,OAAO,CAAC,iBAAiB;YAClD,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM;YAC5B,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM;YAC5B,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,iBAAiB,EAAE,KAAK,CAAC,UAAU;SACpC,CAAC,CAAC;QACH,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,gBAAgB,EAAE,CAAC;IACrD,CAAC;CACF","sourcesContent":["import type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { BillingStore } from \"./billing-store.js\";\nimport type { JsonObject } from \"../shared/json.js\";\nimport type { BillingEvent, BillingEventResult, BillingTopupResult } from \"./types/index.js\";\n\nexport class BillingFinancialEventHandlers {\n constructor(\n private readonly store: BillingStore,\n private readonly logger: NormalizedLogger,\n private readonly pastDueGracePeriodMs: number,\n private readonly resolveAccountId: (event: BillingEvent) => Promise<string | null>,\n private readonly handleSubscriptionRenewed: (\n event: BillingEvent,\n ) => Promise<BillingEventResult>,\n private readonly updateCheckoutIntentFromEvent: (\n event: BillingEvent,\n status: \"completed\" | \"failed\" | \"expired\",\n ) => Promise<void>,\n private readonly applyPastDueSubscription: (\n event: BillingEvent,\n graceEndsAt: string,\n ) => Promise<BillingEventResult>,\n ) {}\n\n async handleInvoicePaid(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handleInvoicePaid\", {\n provider: event.provider,\n eventId: event.eventId,\n invoiceId: event.invoice?.providerInvoiceId,\n });\n if (!event.invoice) return { handled: false, error: \"no_invoice_data\" };\n const renewalResult = event.subscription\n ? await this.handleSubscriptionRenewed(event)\n : { handled: true, action: \"invoice_paid\" };\n if (!renewalResult.handled) return renewalResult;\n if (renewalResult.action === \"stale_subscription_event\") return renewalResult;\n const uid = await this.resolveAccountId(event);\n if (uid) {\n await this.store.upsertBillingInvoice({\n provider: event.provider,\n providerInvoiceId: event.invoice.providerInvoiceId,\n providerSubscriptionId: event.subscription?.providerSubscriptionId,\n userId: uid,\n status: event.invoice.status,\n amountPaidMinor: event.invoice.amountPaidMinor,\n amountDueMinor: event.invoice.amountDueMinor,\n currency: event.invoice.currency,\n periodStart: event.invoice.periodStart,\n periodEnd: event.invoice.periodEnd,\n metadata: event.metadata,\n providerUpdatedAt: event.occurredAt,\n });\n }\n return renewalResult;\n }\n\n async handlePaymentSucceeded(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handlePaymentSucceeded\", {\n provider: event.provider,\n eventId: event.eventId,\n amountMinor: event.payment?.amountMinor,\n });\n if (!event.payment) return { handled: false, error: \"no_payment_data\" };\n\n const uid = await this.resolveAccountId(event);\n const refs = event.payment.refs;\n const intentId =\n event.payment.purpose === \"credit_topup\" ? event.metadata?.checkout_intent_id : null;\n const attemptId =\n event.payment.purpose === \"credit_topup\" ? event.metadata?.auto_recharge_attempt_id : null;\n if (\n (intentId != null && (typeof intentId !== \"string\" || !uid)) ||\n (attemptId != null && (typeof attemptId !== \"string\" || !uid))\n ) {\n return { handled: false, error: \"invalid_checkout_intent\" };\n }\n let topupConfig: BillingTopupResult | null = null;\n if (event.payment.purpose === \"credit_topup\" && refs) {\n topupConfig = await this.store.resolveCreditTopup(\n event.provider,\n refs.productId ?? null,\n refs.priceId ?? null,\n typeof intentId === \"string\" ? intentId : undefined,\n uid,\n event.payment.providerPaymentId,\n typeof attemptId === \"string\" ? attemptId : undefined,\n );\n }\n\n let paymentId: string | null = null;\n if (uid) {\n const paymentMetadata: JsonObject | null =\n topupConfig && event.payment.purpose === \"credit_topup\"\n ? { credits_per_unit: topupConfig.creditsPerUnit.toString() }\n : null;\n paymentId = await this.store.upsertBillingPayment({\n provider: event.provider,\n providerPaymentId: event.payment.providerPaymentId,\n userId: uid,\n amountMinor: event.payment.amountMinor,\n taxMinor: event.payment.taxMinor,\n currency: event.payment.currency,\n purpose: event.payment.purpose,\n topupId: topupConfig?.topupId ?? null,\n status: event.payment.status,\n providerUpdatedAt: event.occurredAt,\n metadata: paymentMetadata,\n });\n\n // Dodo represents subscription receipts as payment.succeeded events,\n // while Stripe emits invoice.paid. Materialize the Dodo payment as a\n // paid invoice so invoice history is provider-agnostic.\n if (event.payment.purpose === \"subscription\" && event.subscription) {\n const renewalResult = await this.handleSubscriptionRenewed(event);\n if (!renewalResult.handled) return renewalResult;\n if (renewalResult.action === \"stale_subscription_event\") return renewalResult;\n await this.store.upsertBillingInvoice({\n provider: event.provider,\n providerInvoiceId: event.payment.providerPaymentId,\n providerSubscriptionId: event.subscription.providerSubscriptionId,\n userId: uid,\n status: \"paid\",\n amountPaidMinor: event.payment.amountMinor,\n amountDueMinor: event.payment.amountMinor,\n currency: event.payment.currency,\n periodStart: event.subscription.periodStart,\n periodEnd: event.subscription.periodEnd,\n metadata: event.metadata,\n providerUpdatedAt: event.occurredAt,\n });\n }\n }\n\n if ((intentId || attemptId) && !topupConfig) {\n return { handled: false, error: \"topup_reference_unresolved\" };\n }\n if (topupConfig && event.payment.purpose === \"credit_topup\" && uid) {\n if (\n event.payment.amountMinor < topupConfig.minAmountMinor ||\n event.payment.amountMinor > topupConfig.maxAmountMinor\n ) {\n this.logger.warn(\n `[BillingService] topup amount ${event.payment.amountMinor} exceeds cap ${topupConfig.maxAmountMinor} for topup key ${topupConfig.topupKey} (user ${uid})`,\n );\n return { handled: true, action: \"payment_succeeded_out_of_bounds\" };\n }\n const credits = await this.store.computeTopupCredits(event.payment.amountMinor, topupConfig);\n const quantity =\n topupConfig.amountMinor <= 0 ? 0 : event.payment.amountMinor / topupConfig.amountMinor;\n if (\n credits.gt(0) &&\n paymentId &&\n Number.isSafeInteger(quantity) &&\n topupConfig.creditsPerUnit.gt(0)\n ) {\n const grantId = await this.store.createBillingCreditGrant({\n paymentId,\n topupId: topupConfig.topupId,\n configuredCredits: topupConfig.creditsPerUnit,\n quantity,\n });\n const posting = await this.store.grantBillingCredit(\n grantId,\n `billing:payment:${paymentId}:topup`,\n );\n if (posting.errorCode) return { handled: false, error: posting.errorCode };\n }\n await this.store.updateAutoRechargeAttemptByProviderPayment({\n provider: event.provider,\n providerPaymentId: event.payment.providerPaymentId,\n state: \"succeeded\",\n });\n }\n\n await this.updateCheckoutIntentFromEvent(event, \"completed\");\n\n return { handled: true, action: \"payment_succeeded\" };\n }\n\n async handlePaymentFailed(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handlePaymentFailed\", {\n provider: event.provider,\n eventId: event.eventId,\n });\n if (!event.payment) return { handled: false, error: \"no_payment_data\" };\n const uid = await this.resolveAccountId(event);\n if (uid) {\n await this.store.upsertBillingPayment({\n provider: event.provider,\n providerPaymentId: event.payment.providerPaymentId,\n userId: uid,\n amountMinor: event.payment.amountMinor,\n taxMinor: event.payment.taxMinor,\n currency: event.payment.currency,\n purpose: event.payment.purpose,\n status: event.payment.status,\n providerUpdatedAt: event.occurredAt,\n });\n }\n if (uid && event.subscription) {\n const occurredAt = new Date(event.occurredAt);\n if (Number.isNaN(occurredAt.getTime())) {\n throw new TypeError(\"billing event occurredAt must be a valid instant\");\n }\n const subscriptionResult = await this.applyPastDueSubscription(\n event,\n new Date(occurredAt.getTime() + this.pastDueGracePeriodMs).toISOString(),\n );\n if (subscriptionResult.action === \"stale_subscription_event\") return subscriptionResult;\n }\n await this.store.updateAutoRechargeAttemptByProviderPayment({\n provider: event.provider,\n providerPaymentId: event.payment.providerPaymentId,\n state: \"failed\",\n failureCode: \"provider_payment_failed\",\n });\n await this.updateCheckoutIntentFromEvent(event, \"failed\");\n return { handled: true, action: \"payment_failed_recorded\" };\n }\n\n async handleRefundCreated(event: BillingEvent): Promise<BillingEventResult> {\n if (!event.refund) return { handled: false, error: \"no_refund_data\" };\n const uid = await this.resolveAccountId(event);\n if (uid) {\n const refundId = await this.store.upsertBillingRefund({\n provider: event.provider,\n providerRefundId: event.refund.providerRefundId,\n providerPaymentId: event.refund.providerPaymentId,\n userId: uid,\n amountMinor: event.refund.amountMinor,\n currency: event.refund.currency,\n reason: event.refund.reason,\n status: event.refund.status,\n providerUpdatedAt: event.occurredAt,\n metadata: event.metadata,\n });\n if (event.refund.status === \"succeeded\") {\n const payment = await this.store.getBillingPayment(\n event.provider,\n event.refund.providerPaymentId,\n );\n\n if (payment?.purpose === \"credit_topup\" && payment.id) {\n const grantId = await this.store.getBillingCreditGrantByPayment(String(payment.id));\n if (grantId) {\n const result = await this.store.postBillingRefund(\n refundId,\n grantId,\n event.refund.amountMinor,\n `billing:${event.eventId}:refund`,\n );\n if (!result.errorCode) return { handled: true, action: \"refund_clawback\" };\n }\n }\n }\n }\n return { handled: true, action: \"refund_recorded\" };\n }\n\n async handleDisputeCreated(event: BillingEvent): Promise<BillingEventResult> {\n if (!event.dispute) return { handled: false, error: \"no_dispute_data\" };\n await this.store.upsertBillingDispute({\n provider: event.provider,\n providerDisputeId: event.dispute.providerDisputeId,\n providerPaymentId: event.dispute.providerPaymentId,\n status: event.dispute.status,\n reason: event.dispute.reason,\n metadata: event.metadata,\n providerUpdatedAt: event.occurredAt,\n });\n return { handled: true, action: \"dispute_recorded\" };\n }\n\n async handleDisputeClosed(event: BillingEvent): Promise<BillingEventResult> {\n if (!event.dispute) return { handled: false, error: \"no_dispute_data\" };\n await this.store.upsertBillingDispute({\n provider: event.provider,\n providerDisputeId: event.dispute.providerDisputeId,\n providerPaymentId: event.dispute.providerPaymentId,\n status: event.dispute.status,\n reason: event.dispute.reason,\n metadata: event.metadata,\n providerUpdatedAt: event.occurredAt,\n });\n return { handled: true, action: \"dispute_closed\" };\n }\n}\n"]}
1
+ {"version":3,"file":"financial-event-handlers.js","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O,EAAE,KAAK,EAAE,KAAK,EAAE,iBAAiB,EAAE,CAAC;QACxE,MAAM,IAAI,CAAC,KAAK,CAAC,oBAAoB,CAAC;YACpC,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,iBAAiB,EAAE,KAAK,CAAC,OAAO,CAAC,iBAAiB;YAClD,iBAAiB,EAAE,KAAK,CAAC,OAAO,CAAC,iBAAiB;YAClD,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM;YAC5B,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM;YAC5B,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,iBAAiB,EAAE,KAAK,CAAC,UAAU;SACpC,CAAC,CAAC;QACH,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,gBAAgB,EAAE,CAAC;IACrD,CAAC;CACF","sourcesContent":["import type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { BillingStore } from \"./billing-store.js\";\nimport type { JsonObject } from \"../shared/json.js\";\nimport { compareTimestamps } from \"../shared/timestamp.js\";\nimport type { BillingEvent, BillingEventResult, BillingTopupResult } from \"./types/index.js\";\n\nexport class BillingFinancialEventHandlers {\n constructor(\n private readonly store: BillingStore,\n private readonly logger: NormalizedLogger,\n private readonly pastDueGracePeriodMs: number,\n private readonly resolveAccountId: (event: BillingEvent) => Promise<string | null>,\n private readonly handleSubscriptionRenewed: (\n event: BillingEvent,\n ) => Promise<BillingEventResult>,\n private readonly updateCheckoutIntentFromEvent: (\n event: BillingEvent,\n status: \"completed\" | \"failed\" | \"expired\",\n ) => Promise<void>,\n private readonly applyPastDueSubscription: (\n event: BillingEvent,\n graceEndsAt: string,\n ) => Promise<BillingEventResult>,\n ) {}\n\n async handleInvoicePaid(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handleInvoicePaid\", {\n provider: event.provider,\n eventId: event.eventId,\n invoiceId: event.invoice?.providerInvoiceId,\n });\n if (!event.invoice || event.invoice.status !== \"paid\") {\n return { handled: false, error: \"invalid_paid_invoice\" };\n }\n const uid = await this.resolveAccountId(event);\n if (!uid) return { handled: false, error: \"account_not_found\" };\n const renewalResult =\n event.subscription && event.subscription.cyclePayment !== false\n ? await this.handleSubscriptionRenewed(event)\n : { handled: true, action: \"invoice_paid\" };\n if (!renewalResult.handled) return renewalResult;\n if (uid) {\n await this.store.upsertBillingInvoice({\n provider: event.provider,\n providerInvoiceId: event.invoice.providerInvoiceId,\n providerSubscriptionId: event.subscription?.providerSubscriptionId,\n userId: uid,\n status: event.invoice.status,\n amountPaidMinor: event.invoice.amountPaidMinor,\n amountDueMinor: event.invoice.amountDueMinor,\n currency: event.invoice.currency,\n periodStart: event.invoice.periodStart,\n periodEnd: event.invoice.periodEnd,\n metadata: event.metadata,\n providerUpdatedAt: event.occurredAt,\n });\n }\n if (event.subscription?.cyclePayment !== false) {\n await this.updateCheckoutIntentFromEvent(event, \"completed\");\n }\n return renewalResult;\n }\n\n async handlePaymentSucceeded(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handlePaymentSucceeded\", {\n provider: event.provider,\n eventId: event.eventId,\n amountMinor: event.payment?.amountMinor,\n });\n if (!event.payment) return { handled: false, error: \"no_payment_data\" };\n\n const uid = await this.resolveAccountId(event);\n if (!uid) {\n return { handled: false, error: \"account_not_found\" };\n }\n const refs = event.payment.refs;\n const intentId =\n event.payment.purpose === \"credit_topup\" ? event.metadata?.checkout_intent_id : null;\n const attemptId =\n event.payment.purpose === \"credit_topup\" ? event.metadata?.auto_recharge_attempt_id : null;\n if (\n (intentId != null && (typeof intentId !== \"string\" || !uid)) ||\n (attemptId != null && (typeof attemptId !== \"string\" || !uid))\n ) {\n return { handled: false, error: \"invalid_checkout_intent\" };\n }\n let topupConfig: BillingTopupResult | null = null;\n if (event.payment.purpose === \"credit_topup\" && refs) {\n topupConfig = await this.store.resolveCreditTopup(\n event.provider,\n refs.productId ?? null,\n refs.priceId ?? null,\n typeof intentId === \"string\" ? intentId : undefined,\n uid,\n event.payment.providerPaymentId,\n typeof attemptId === \"string\" ? attemptId : undefined,\n event.billingEventId,\n );\n }\n if (event.payment.purpose === \"credit_topup\" && !topupConfig) {\n return { handled: false, error: \"topup_reference_unresolved\" };\n }\n\n let paymentId: string | null = null;\n if (uid) {\n const subscriptionInvoiceId =\n event.payment.purpose === \"subscription\" && event.subscription\n ? (event.invoice?.providerInvoiceId ?? event.payment.providerPaymentId)\n : null;\n const paymentMetadata: JsonObject | null =\n topupConfig && event.payment.purpose === \"credit_topup\"\n ? { credits_per_unit: topupConfig.creditsPerUnit.toString() }\n : null;\n paymentId = await this.store.upsertBillingPayment({\n billingEventId: event.billingEventId,\n provider: event.provider,\n providerPaymentId: event.payment.providerPaymentId,\n providerInvoiceId: subscriptionInvoiceId,\n userId: uid,\n amountMinor: event.payment.amountMinor,\n taxMinor: event.payment.taxMinor,\n currency: event.payment.currency,\n purpose: event.payment.purpose,\n topupId: topupConfig?.topupId ?? null,\n status: event.payment.status,\n providerUpdatedAt: event.occurredAt,\n metadata: paymentMetadata,\n });\n\n const payment = await this.store.getBillingPayment(\n event.provider,\n event.payment.providerPaymentId,\n );\n if (!payment) return { handled: false, error: \"payment_not_found\" };\n if (payment.status !== \"succeeded\") {\n return { handled: true, action: \"stale_payment_event\" };\n }\n\n // Dodo represents subscription receipts as payment.succeeded events,\n // while Stripe emits invoice.paid. Materialize the Dodo payment as a\n // paid invoice so invoice history is provider-agnostic.\n if (subscriptionInvoiceId && event.subscription) {\n if (event.subscription.cyclePayment !== false) {\n const renewalResult = await this.handleSubscriptionRenewed(event);\n if (!renewalResult.handled) return renewalResult;\n }\n await this.store.upsertBillingInvoice({\n provider: event.provider,\n providerInvoiceId: subscriptionInvoiceId,\n providerSubscriptionId: event.subscription.providerSubscriptionId,\n userId: uid,\n status: \"paid\",\n amountPaidMinor: event.payment.amountMinor,\n amountDueMinor: event.payment.amountMinor,\n currency: event.payment.currency,\n periodStart: event.subscription.periodStart,\n periodEnd: event.subscription.periodEnd,\n metadata: event.metadata,\n providerUpdatedAt: event.occurredAt,\n });\n }\n }\n\n if (topupConfig && event.payment.purpose === \"credit_topup\" && uid) {\n if (event.payment.currency !== topupConfig.currency) {\n return { handled: false, error: \"topup_currency_mismatch\" };\n }\n // Payment amounts exclude tax; inclusive catalog prices include it.\n const chargeAmount =\n topupConfig.taxBehavior === \"inclusive\"\n ? event.payment.amountMinor + event.payment.taxMinor\n : event.payment.amountMinor;\n if (!Number.isSafeInteger(chargeAmount)) {\n return { handled: false, error: \"topup_amount_out_of_bounds\" };\n }\n if (chargeAmount < topupConfig.minAmountMinor || chargeAmount > topupConfig.maxAmountMinor) {\n this.logger.warn(\n `[BillingService] topup amount ${event.payment.amountMinor} exceeds cap ${topupConfig.maxAmountMinor} for topup key ${topupConfig.topupKey} (user ${uid})`,\n );\n return { handled: false, error: \"topup_amount_out_of_bounds\" };\n }\n const quantity = topupConfig.amountMinor <= 0 ? 0 : chargeAmount / topupConfig.amountMinor;\n if (\n !paymentId ||\n !Number.isSafeInteger(quantity) ||\n quantity < topupConfig.minQuantity ||\n quantity > topupConfig.maxQuantity ||\n !topupConfig.creditsPerUnit.gt(0)\n ) {\n return { handled: false, error: \"invalid_topup_quantity\" };\n }\n const grantId = await this.store.createBillingCreditGrant({\n paymentId,\n topupId: topupConfig.topupId,\n configuredCredits: topupConfig.creditsPerUnit,\n quantity,\n });\n const posting = await this.store.grantBillingCredit(\n grantId,\n `billing:payment:${paymentId}:topup`,\n );\n if (posting.errorCode) return { handled: false, error: posting.errorCode };\n const matchedAttempt = await this.store.updateAutoRechargeAttemptByProviderPayment({\n provider: event.provider,\n providerPaymentId: event.payment.providerPaymentId,\n expectedAttemptId: typeof attemptId === \"string\" ? attemptId : undefined,\n expectedUserId: typeof attemptId === \"string\" ? uid : undefined,\n state: \"succeeded\",\n });\n if (attemptId && !matchedAttempt) {\n return { handled: false, error: \"recharge_payment_not_bound\" };\n }\n }\n\n if (event.subscription?.cyclePayment !== false) {\n await this.updateCheckoutIntentFromEvent(event, \"completed\");\n }\n\n return { handled: true, action: \"payment_succeeded\" };\n }\n\n /** A settled invoice can still have a distinct failed payment attempt. */\n async recordStaleInvoicePayment(event: BillingEvent): Promise<BillingEventResult> {\n const payment = event.payment;\n const invoiceId = event.invoice?.providerInvoiceId;\n if (!payment || !invoiceId || payment.providerPaymentId === invoiceId) {\n return { handled: true, action: \"stale_payment_event\" };\n }\n const uid = await this.resolveAccountId(event);\n if (!uid) return { handled: false, error: \"account_not_found\" };\n const existing = await this.store.getBillingPayment(event.provider, payment.providerPaymentId);\n if (!existing || existing.status === \"pending\" || existing.status === \"requires_action\") {\n await this.store.upsertBillingPayment({\n provider: event.provider,\n providerPaymentId: payment.providerPaymentId,\n providerInvoiceId: invoiceId,\n userId: uid,\n amountMinor: payment.amountMinor,\n taxMinor: payment.taxMinor,\n currency: payment.currency,\n purpose: payment.purpose,\n status: \"failed\",\n providerUpdatedAt: event.occurredAt,\n });\n }\n return { handled: true, action: \"stale_payment_event\" };\n }\n\n async handlePaymentFailed(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handlePaymentFailed\", {\n provider: event.provider,\n eventId: event.eventId,\n });\n if (event.eventType === \"invoice.payment_failed\" && !event.invoice) {\n return { handled: false, error: \"no_invoice_data\" };\n }\n if (!event.payment && event.eventType !== \"invoice.payment_failed\") {\n return { handled: false, error: \"no_payment_data\" };\n }\n const uid = await this.resolveAccountId(event);\n if (!uid) return { handled: false, error: \"account_not_found\" };\n if (event.payment) {\n await this.store.upsertBillingPayment({\n provider: event.provider,\n providerPaymentId: event.payment.providerPaymentId,\n providerInvoiceId: event.invoice?.providerInvoiceId ?? null,\n userId: uid,\n amountMinor: event.payment.amountMinor,\n taxMinor: event.payment.taxMinor,\n currency: event.payment.currency,\n purpose: event.payment.purpose,\n status: event.payment.status,\n providerUpdatedAt: event.occurredAt,\n });\n const payment = await this.store.getBillingPayment(\n event.provider,\n event.payment.providerPaymentId,\n );\n if (!payment) return { handled: false, error: \"payment_not_found\" };\n if (\n (payment.status !== \"failed\" && payment.status !== \"canceled\") ||\n compareTimestamps(payment.providerUpdatedAt, event.occurredAt) > 0\n ) {\n return { handled: true, action: \"stale_payment_event\" };\n }\n }\n if (uid && event.subscription && event.subscription.cyclePayment !== false) {\n const existing = await this.store.getBillingSubscription(\n event.provider,\n event.subscription.providerSubscriptionId,\n );\n // A different invoice may fail at the same provider timestamp as a paid\n // receipt. Preserve the payment fact, but do not overwrite subscription\n // state when the provider has not supplied an ordering between them.\n if (\n existing &&\n existing.status !== \"past_due\" &&\n compareTimestamps(existing.providerUpdatedAt, event.occurredAt) === 0\n ) {\n return { handled: true, action: \"stale_subscription_event\" };\n }\n const occurredAt = new Date(event.occurredAt);\n if (Number.isNaN(occurredAt.getTime())) {\n throw new TypeError(\"billing event occurredAt must be a valid instant\");\n }\n const subscriptionResult = await this.applyPastDueSubscription(\n event,\n new Date(occurredAt.getTime() + this.pastDueGracePeriodMs).toISOString(),\n );\n if (!subscriptionResult.handled || subscriptionResult.action === \"stale_subscription_event\") {\n return subscriptionResult;\n }\n }\n const attemptId = event.metadata?.auto_recharge_attempt_id;\n if (attemptId != null && (typeof attemptId !== \"string\" || !uid)) {\n return { handled: false, error: \"invalid_recharge_attempt\" };\n }\n if (event.payment) {\n const matchedAttempt = await this.store.updateAutoRechargeAttemptByProviderPayment({\n provider: event.provider,\n providerPaymentId: event.payment.providerPaymentId,\n expectedAttemptId: typeof attemptId === \"string\" ? attemptId : undefined,\n expectedUserId: typeof attemptId === \"string\" ? uid : undefined,\n state: \"failed\",\n failureCode: \"provider_payment_failed\",\n });\n if (attemptId && !matchedAttempt) {\n return { handled: false, error: \"recharge_payment_not_bound\" };\n }\n } else if (attemptId) {\n return { handled: false, error: \"recharge_payment_not_bound\" };\n }\n if (event.subscription?.cyclePayment !== false) {\n await this.updateCheckoutIntentFromEvent(event, \"failed\");\n }\n return { handled: true, action: \"payment_failed_recorded\" };\n }\n\n async handleRefundCreated(event: BillingEvent): Promise<BillingEventResult> {\n if (!event.refund) return { handled: false, error: \"no_refund_data\" };\n const uid = await this.resolveAccountId(event);\n if (!uid) return { handled: false, error: \"account_not_found\" };\n if (uid) {\n const refundId = await this.store.upsertBillingRefund({\n provider: event.provider,\n providerRefundId: event.refund.providerRefundId,\n providerPaymentId: event.refund.providerPaymentId,\n userId: uid,\n amountMinor: event.refund.amountMinor,\n currency: event.refund.currency,\n reason: event.refund.reason,\n status: event.refund.status,\n providerUpdatedAt: event.occurredAt,\n metadata: event.metadata,\n });\n if (event.refund.status === \"succeeded\") {\n const payment = await this.store.getBillingPayment(\n event.provider,\n event.refund.providerPaymentId,\n );\n\n if (payment?.purpose === \"credit_topup\" && payment.id) {\n const grantId = await this.store.getBillingCreditGrantByPayment(String(payment.id));\n if (grantId) {\n const result = await this.store.postBillingRefund(\n refundId,\n grantId,\n event.refund.amountMinor,\n `billing:${event.eventId}:refund`,\n );\n if (!result.errorCode) return { handled: true, action: \"refund_clawback\" };\n if (\n result.errorCode !== \"refund_not_succeeded\" &&\n result.errorCode !== \"refund_credit_rounds_to_zero\"\n ) {\n return { handled: false, error: result.errorCode };\n }\n } else {\n return { handled: false, error: \"refund_grant_not_found\" };\n }\n }\n }\n }\n return { handled: true, action: \"refund_recorded\" };\n }\n\n async handleDisputeCreated(event: BillingEvent): Promise<BillingEventResult> {\n if (!event.dispute) return { handled: false, error: \"no_dispute_data\" };\n await this.store.upsertBillingDispute({\n provider: event.provider,\n providerDisputeId: event.dispute.providerDisputeId,\n providerPaymentId: event.dispute.providerPaymentId,\n status: event.dispute.status,\n reason: event.dispute.reason,\n metadata: event.metadata,\n providerUpdatedAt: event.occurredAt,\n });\n return { handled: true, action: \"dispute_recorded\" };\n }\n\n async handleDisputeClosed(event: BillingEvent): Promise<BillingEventResult> {\n if (!event.dispute) return { handled: false, error: \"no_dispute_data\" };\n await this.store.upsertBillingDispute({\n provider: event.provider,\n providerDisputeId: event.dispute.providerDisputeId,\n providerPaymentId: event.dispute.providerPaymentId,\n status: event.dispute.status,\n reason: event.dispute.reason,\n metadata: event.metadata,\n providerUpdatedAt: event.occurredAt,\n });\n return { handled: true, action: \"dispute_closed\" };\n }\n}\n"]}
@@ -7,5 +7,5 @@ export type { AutoRechargeAttemptClaim, AutoRechargeAttemptUpdate, AutoRechargeP
7
7
  export { AUTO_RECHARGE_STATES, BillingEventType } from "./types/index.js";
8
8
  export { AutoRechargeService } from "./auto-recharge-service.js";
9
9
  export type { AutoRechargeOutcome, AutoRechargeProcessResult } from "./auto-recharge-service.js";
10
- export type { BillingAutoRechargeAttempt, BillingAutoRechargeAttemptState, BillingAutoRechargeProfile, BillingAutoRechargeStatus, BillingCreditPostingResult, BillingCustomerInfo, BillingCustomerRecord, BillingDisputeInfo, BillingEvent, BillingEventClaim, BillingEventHandler, BillingEventResult, BillingInvoiceInfo, BillingInvoiceRecord, BillingOfferInterval, BillingPaymentInfo, BillingPaymentRecord, BillingPreferences, BillingRefundInfo, BillingSubscriptionInfo, BillingSubscriptionChange, BillingSubscriptionChangeInput, BillingSubscriptionOfferContext, BillingSubscriptionChangeState, BillingSubscriptionState, BillingSubscriptionStatus, CheckoutIntent, CheckoutIntentStatus, EntitlementMode, ProviderRef, SubscriptionGrant, SubscriptionEntitlementOutcome, } from "./types/index.js";
10
+ export type { BillingAutoRechargeAttempt, BillingAutoRechargeAttemptState, BillingAutoRechargeProfile, BillingAutoRechargeStatus, BillingCreditPostingResult, BillingCustomerInfo, BillingCustomerRecord, BillingDisputeInfo, BillingEvent, BillingEventClaim, BillingEventHandler, BillingEventResult, BillingInvoiceInfo, BillingInvoiceRecord, BillingInvoiceCursor, BillingInvoicePage, ListBillingInvoicesOptions, BillingOfferInterval, BillingPaymentInfo, BillingPaymentRecord, BillingPreferences, BillingRefundInfo, BillingSubscriptionInfo, BillingSubscriptionChange, BillingSubscriptionChangeInput, BillingSubscriptionOfferContext, BillingSubscriptionChangeState, BillingSubscriptionState, BillingSubscriptionStatus, CheckoutIntent, CheckoutIntentStatus, EntitlementMode, ProviderRef, SubscriptionGrant, SubscriptionEntitlementOutcome, } from "./types/index.js";
11
11
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/billing/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,YAAY,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AACvE,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,YAAY,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAC3F,YAAY,EACV,wBAAwB,EACxB,yBAAyB,EACzB,iCAAiC,EACjC,wBAAwB,EACxB,oBAAoB,EACpB,gBAAgB,EAChB,oBAAoB,EACpB,oBAAoB,EACpB,mBAAmB,EACnB,+BAA+B,EAC/B,iCAAiC,EACjC,oBAAoB,EACpB,oBAAoB,GACrB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAC1E,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,YAAY,EAAE,mBAAmB,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AAEjG,YAAY,EACV,0BAA0B,EAC1B,+BAA+B,EAC/B,0BAA0B,EAC1B,yBAAyB,EACzB,0BAA0B,EAC1B,mBAAmB,EACnB,qBAAqB,EACrB,kBAAkB,EAClB,YAAY,EACZ,iBAAiB,EACjB,mBAAmB,EACnB,kBAAkB,EAClB,kBAAkB,EAClB,oBAAoB,EACpB,oBAAoB,EACpB,kBAAkB,EAClB,oBAAoB,EACpB,kBAAkB,EAClB,iBAAiB,EACjB,uBAAuB,EACvB,yBAAyB,EACzB,8BAA8B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B,EACpB,kBAAkB,EAClB,iBAAiB,EACjB,uBAAuB,EACvB,yBAAyB,EACzB,8BAA8B,EAC9B,+BAA+B,EAC/B,8BAA8B,EAC9B,wBAAwB,EACxB,yBAAyB,EACzB,cAAc,EACd,oBAAoB,EACpB,eAAe,EACf,WAAW,EACX,iBAAiB,EACjB,8BAA8B,GAC/B,MAAM,kBAAkB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/billing/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAE3D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAkBtD,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAC1E,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC","sourcesContent":["export { BillingStore } from \"./billing-store.js\";\nexport { PostgresBillingStore } from \"./postgres/store.js\";\nexport type { PostgresBillingStoreOptions } from \"./postgres/store.js\";\nexport { BillingService } from \"./billing-service.js\";\nexport type { BillingServiceOptions, BillingProvisioningPort } from \"./billing-service.js\";\nexport type {\n AutoRechargeAttemptClaim,\n AutoRechargeAttemptUpdate,\n AutoRechargeProviderPaymentUpdate,\n BillingCreditGrantCreate,\n BillingDisputeUpsert,\n BillingEventSink,\n BillingInvoiceUpsert,\n BillingPaymentUpsert,\n BillingRefundUpsert,\n BillingSubscriptionChangeUpdate,\n BillingSubscriptionConflictCreate,\n CheckoutIntentCreate,\n CheckoutIntentUpdate,\n} from \"./contracts.js\";\n\nexport { AUTO_RECHARGE_STATES, BillingEventType } from \"./types/index.js\";\nexport { AutoRechargeService } from \"./auto-recharge-service.js\";\nexport type { AutoRechargeOutcome, AutoRechargeProcessResult } from \"./auto-recharge-service.js\";\n\nexport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeAttemptState,\n BillingAutoRechargeProfile,\n BillingAutoRechargeStatus,\n BillingCreditPostingResult,\n BillingCustomerInfo,\n BillingCustomerRecord,\n BillingDisputeInfo,\n BillingEvent,\n BillingEventClaim,\n BillingEventHandler,\n BillingEventResult,\n BillingInvoiceInfo,\n BillingInvoiceRecord,\n BillingOfferInterval,\n BillingPaymentInfo,\n BillingPaymentRecord,\n BillingPreferences,\n BillingRefundInfo,\n BillingSubscriptionInfo,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionOfferContext,\n BillingSubscriptionChangeState,\n BillingSubscriptionState,\n BillingSubscriptionStatus,\n CheckoutIntent,\n CheckoutIntentStatus,\n EntitlementMode,\n ProviderRef,\n SubscriptionGrant,\n SubscriptionEntitlementOutcome,\n} from \"./types/index.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/billing/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAE3D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAkBtD,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAC1E,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC","sourcesContent":["export { BillingStore } from \"./billing-store.js\";\nexport { PostgresBillingStore } from \"./postgres/store.js\";\nexport type { PostgresBillingStoreOptions } from \"./postgres/store.js\";\nexport { BillingService } from \"./billing-service.js\";\nexport type { BillingServiceOptions, BillingProvisioningPort } from \"./billing-service.js\";\nexport type {\n AutoRechargeAttemptClaim,\n AutoRechargeAttemptUpdate,\n AutoRechargeProviderPaymentUpdate,\n BillingCreditGrantCreate,\n BillingDisputeUpsert,\n BillingEventSink,\n BillingInvoiceUpsert,\n BillingPaymentUpsert,\n BillingRefundUpsert,\n BillingSubscriptionChangeUpdate,\n BillingSubscriptionConflictCreate,\n CheckoutIntentCreate,\n CheckoutIntentUpdate,\n} from \"./contracts.js\";\n\nexport { AUTO_RECHARGE_STATES, BillingEventType } from \"./types/index.js\";\nexport { AutoRechargeService } from \"./auto-recharge-service.js\";\nexport type { AutoRechargeOutcome, AutoRechargeProcessResult } from \"./auto-recharge-service.js\";\n\nexport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeAttemptState,\n BillingAutoRechargeProfile,\n BillingAutoRechargeStatus,\n BillingCreditPostingResult,\n BillingCustomerInfo,\n BillingCustomerRecord,\n BillingDisputeInfo,\n BillingEvent,\n BillingEventClaim,\n BillingEventHandler,\n BillingEventResult,\n BillingInvoiceInfo,\n BillingInvoiceRecord,\n BillingInvoiceCursor,\n BillingInvoicePage,\n ListBillingInvoicesOptions,\n BillingOfferInterval,\n BillingPaymentInfo,\n BillingPaymentRecord,\n BillingPreferences,\n BillingRefundInfo,\n BillingSubscriptionInfo,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionOfferContext,\n BillingSubscriptionChangeState,\n BillingSubscriptionState,\n BillingSubscriptionStatus,\n CheckoutIntent,\n CheckoutIntentStatus,\n EntitlementMode,\n ProviderRef,\n SubscriptionGrant,\n SubscriptionEntitlementOutcome,\n} from \"./types/index.js\";\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { BillingStore } from "./billing-store.js";
2
- import type { BillingAutoRechargeAttempt, BillingAutoRechargeAttemptState, BillingAutoRechargeProfile, BillingCustomerRecord, BillingOfferResult, BillingPreferences, BillingSubscriptionChange, BillingSubscriptionChangeInput, BillingSubscriptionState, BillingTopupResult, CheckoutIntent } from "./types/index.js";
2
+ import type { BillingAutoRechargeAttempt, BillingAutoRechargeAttemptState, BillingAutoRechargeProfile, BillingCustomerRecord, BillingOfferResult, BillingPreferences, BillingSubscriptionChange, BillingSubscriptionChangeInput, BillingSubscriptionState, BillingTopupResult, CheckoutIntent, ListBillingInvoicesOptions } from "./types/index.js";
3
3
  import type { JsonObject } from "../shared/json.js";
4
4
  /**
5
5
  * Public billing reads and commands that delegate directly to BillingStore.
@@ -15,9 +15,10 @@ export declare class BillingManagement {
15
15
  getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null>;
16
16
  getActiveSubscription(userId: string): Promise<BillingSubscriptionState | null>;
17
17
  getUserPreferences(userId: string): Promise<BillingPreferences | null>;
18
- listBillingInvoices(userId: string): Promise<import("./contracts.js").BillingInvoiceRecord[]>;
18
+ listBillingInvoices(userId: string, options?: ListBillingInvoicesOptions): Promise<import("./index.js").BillingInvoicePage>;
19
19
  upsertBillingSubscription(state: BillingSubscriptionState): Promise<void>;
20
20
  createBillingSubscriptionChange(input: BillingSubscriptionChangeInput): Promise<BillingSubscriptionChange>;
21
+ findBillingSubscriptionChange(provider: string, subscriptionId: string, operationKey: string): Promise<BillingSubscriptionChange | null>;
21
22
  getOpenBillingSubscriptionChange(provider: string, providerSubscriptionId: string): Promise<BillingSubscriptionChange | null>;
22
23
  updateBillingSubscriptionChange(id: string, update: Parameters<BillingStore["updateBillingSubscriptionChange"]>[1]): Promise<void>;
23
24
  recordSubscriptionConflict(input: Parameters<BillingStore["recordSubscriptionConflict"]>[0]): Promise<void>;
@@ -49,10 +50,12 @@ export declare class BillingManagement {
49
50
  updateAutoRechargeAttemptByProviderPayment(input: {
50
51
  provider: string;
51
52
  providerPaymentId: string;
53
+ expectedAttemptId?: string;
54
+ expectedUserId?: string;
52
55
  state: BillingAutoRechargeAttemptState;
53
56
  failureCode?: string | null;
54
57
  failureMessage?: string | null;
55
- }): Promise<void>;
58
+ }): Promise<boolean>;
56
59
  getAutoRechargeOperationalWindow(userId: string): Promise<{
57
60
  maxRecharges: number;
58
61
  windowStart: string;
@@ -1 +1 @@
1
- {"version":3,"file":"management.d.ts","sourceRoot":"","sources":["../../src/billing/management.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,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G,IAAI,CAAC,CAEpC;IAEK,oBAAoB,CACxB,QAAQ,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;CACF"}
@@ -28,8 +28,8 @@ export class BillingManagement {
28
28
  async getUserPreferences(userId) {
29
29
  return this.store.getBillingPreferences(userId);
30
30
  }
31
- async listBillingInvoices(userId) {
32
- return this.store.listBillingInvoices(userId);
31
+ async listBillingInvoices(userId, options) {
32
+ return this.store.listBillingInvoices(userId, options);
33
33
  }
34
34
  async upsertBillingSubscription(state) {
35
35
  await this.store.upsertBillingSubscription(state);
@@ -37,6 +37,9 @@ export class BillingManagement {
37
37
  async createBillingSubscriptionChange(input) {
38
38
  return this.store.createBillingSubscriptionChange(input);
39
39
  }
40
+ async findBillingSubscriptionChange(provider, subscriptionId, operationKey) {
41
+ return this.store.findBillingSubscriptionChange(provider, subscriptionId, operationKey);
42
+ }
40
43
  async getOpenBillingSubscriptionChange(provider, providerSubscriptionId) {
41
44
  return this.store.getOpenBillingSubscriptionChange(provider, providerSubscriptionId);
42
45
  }
@@ -1 +1 @@
1
- {"version":3,"file":"management.js","sourceRoot":"","sources":["../../src/billing/management.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAGvD;;;;;GAKG;AACH,MAAM,OAAO,iBAAiB;IACC,KAAK;IAAlC,YAA6B,KAAmB;qBAAnB,KAAK;IAAiB,CAAC;IAEpD,KAAK,CAAC,yBAAyB,CAAC,KAA+D;QAC7F,OAAO,IAAI,CAAC,KAAK,CAAC,yBAAyB,CAAC,KAAK,CAAC,CAAC;IACrD,CAAC;IAED,KAAK,CAA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QAEvB,OAAO,IAAI,CAAC,KAAK,CAAC,mBAAmB,CAAC,QAAQ,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;IACtE,CAAC;IAED,KAAK,CAAC,oBAAoB,CACxB,QAAgB,EAChB,SAAiB;QAEjB,OAAO,IAAI,CAAC,KAAK,CAAC,2BAA2B,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;IACrE,CAAC;IAED,KAAK,CAAC,YAAY,CAChB,QAAgB,EAChB,SAAyB,EACzB,OAAuB;QAEvB,OAAO,IAAI,CAAC,KAAK,CAAC,kBAAkB,CAAC,QAAQ,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;IACrE,CAAC;IAED,KAAK,CAAC,oBAAoB,CACxB,QAAgB,EAChB,SAAiB;QAEjB,OAAO,IAAI,CAAC,KAAK,CAAC,0BAA0B,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;IACpE,CAAC;IAED,KAAK,CAAC,cAAc,CAClB,QAAgB,EAChB,kBAA0B,EAC1B,MAAc,EACd,KAAqB;QAErB,MAAM,IAAI,CAAC,KAAK,CAAC,qBAAqB,CAAC,QAAQ,EAAE,kBAAkB,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;IACtF,CAAC;CACF","sourcesContent":["import type { BillingStore } from \"./billing-store.js\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeAttemptState,\n BillingAutoRechargeProfile,\n BillingCustomerRecord,\n BillingOfferResult,\n BillingPreferences,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionState,\n BillingSubscriptionStatus,\n BillingTopupResult,\n CheckoutIntent,\n} from \"./types/index.js\";\nimport { SUBSCRIPTION_STATUS } from \"./types/index.js\";\nimport type { JsonObject } from \"../shared/json.js\";\n\n/**\n * Public billing reads and commands that delegate directly to BillingStore.\n *\n * Webhook lifecycle orchestration lives in BillingService; this class keeps\n * the stable facade surface separate from that state machine.\n */\nexport class BillingManagement {\n constructor(private readonly store: BillingStore) {}\n\n async createOrGetCheckoutIntent(input: Parameters<BillingStore[\"createOrGetCheckoutIntent\"]>[0]) {\n return this.store.createOrGetCheckoutIntent(input);\n }\n\n async updateCheckoutIntent(\n id: string,\n update: Parameters<BillingStore[\"updateCheckoutIntent\"]>[1],\n ): Promise<void> {\n await this.store.updateCheckoutIntent(id, update);\n }\n\n async getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null> {\n return this.store.getCheckoutIntent(id, subjectId);\n }\n\n async getActiveSubscription(userId: string): Promise<BillingSubscriptionState | null> {\n return this.store.getUserSubscription(userId, [\n SUBSCRIPTION_STATUS.ACTIVE,\n SUBSCRIPTION_STATUS.TRIALING,\n ]);\n }\n\n async getUserPreferences(userId: string): Promise<BillingPreferences | null> {\n return this.store.getBillingPreferences(userId);\n }\n\n async listBillingInvoices(userId: string) {\n return this.store.listBillingInvoices(userId);\n }\n\n async upsertBillingSubscription(state: BillingSubscriptionState): Promise<void> {\n await this.store.upsertBillingSubscription(state);\n }\n\n async createBillingSubscriptionChange(\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n return this.store.createBillingSubscriptionChange(input);\n }\n\n async getOpenBillingSubscriptionChange(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.store.getOpenBillingSubscriptionChange(provider, providerSubscriptionId);\n }\n\n async updateBillingSubscriptionChange(\n id: string,\n update: Parameters<BillingStore[\"updateBillingSubscriptionChange\"]>[1],\n ): Promise<void> {\n await this.store.updateBillingSubscriptionChange(id, update);\n }\n\n async recordSubscriptionConflict(\n input: Parameters<BillingStore[\"recordSubscriptionConflict\"]>[0],\n ): Promise<void> {\n await this.store.recordSubscriptionConflict(input);\n }\n\n async updateUserPreferences(preferences: BillingPreferences): Promise<void> {\n await this.store.upsertBillingPreferences(preferences);\n }\n\n async getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n return this.store.getAutoRechargeProfile(userId);\n }\n\n async getActiveCatalogDocument(): Promise<JsonObject | null> {\n return this.store.getActiveCatalogDocument();\n }\n\n async listCancellableProviderSubscriptionIds(userId: string): Promise<string[]> {\n const subscriptions = await this.listCancellableSubscriptions(userId);\n return subscriptions.map((subscription) => subscription.providerSubscriptionId);\n }\n\n async listCancellableSubscriptions(userId: string): Promise<BillingSubscriptionState[]> {\n const cancellableStatuses = new Set<BillingSubscriptionStatus>([\n SUBSCRIPTION_STATUS.ACTIVE,\n SUBSCRIPTION_STATUS.TRIALING,\n SUBSCRIPTION_STATUS.PAST_DUE,\n SUBSCRIPTION_STATUS.INCOMPLETE,\n SUBSCRIPTION_STATUS.UNPAID,\n SUBSCRIPTION_STATUS.PAUSED,\n ]);\n const subscriptions = await this.store.getUserSubscriptions(userId);\n return subscriptions.filter(\n (subscription) =>\n subscription.status != null &&\n cancellableStatuses.has(subscription.status) &&\n Boolean(subscription.providerSubscriptionId),\n );\n }\n\n async pseudonymizeFinancialSubject(userId: string): Promise<void> {\n await this.store.pseudonymizeFinancialSubject(userId);\n }\n\n async upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void> {\n return this.store.upsertAutoRechargeProfile(profile, options);\n }\n\n async resumeAutoRechargeProfile(profile: BillingAutoRechargeProfile): Promise<boolean> {\n return this.store.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.store.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 return this.store.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 return this.store.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.store.getAutoRechargeOperationalWindow(userId);\n }\n\n async countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number> {\n return this.store.countAutoRechargeAttempts(userId, since);\n }\n\n async getCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null> {\n return this.store.getBillingCustomerByUserId(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.store.resolveBillingOffer(provider, productId, priceId);\n }\n\n async resolveOfferByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingOfferResult | null> {\n return this.store.resolveBillingOfferByLookup(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.store.resolveCreditTopup(provider, productId, priceId);\n }\n\n async resolveTopupByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingTopupResult | null> {\n return this.store.resolveCreditTopupByLookup(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.store.upsertBillingCustomer(provider, providerCustomerId, userId, email);\n }\n}\n"]}
1
+ {"version":3,"file":"management.js","sourceRoot":"","sources":["../../src/billing/management.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAGvD;;;;;GAKG;AACH,MAAM,OAAO,iBAAiB;IACC,KAAK;IAAlC,YAA6B,KAAmB;qBAAnB,KAAK;IAAiB,CAAC;IAEpD,KAAK,CAAC,yBAAyB,CAAC,KAA+D;QAC7F,OAAO,IAA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AC,KAAK,CAAC,yBAAyB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC7D,CAAC;IAED,KAAK,CAAC,mBAAmB,CACvB,MAAc,EACd,QAAwB;QAExB,OAAO,IAAI,CAAC,KAAK,CAAC,0BAA0B,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACjE,CAAC;IAED,KAAK,CAAC,YAAY,CAChB,QAAgB,EAChB,SAAyB,EACzB,OAAuB;QAEvB,OAAO,IAAI,CAAC,KAAK,CAAC,mBAAmB,CAAC,QAAQ,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;IACtE,CAAC;IAED,KAAK,CAAC,oBAAoB,CACxB,QAAgB,EAChB,SAAiB;QAEjB,OAAO,IAAI,CAAC,KAAK,CAAC,2BAA2B,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;IACrE,CAAC;IAED,KAAK,CAAC,YAAY,CAChB,QAAgB,EAChB,SAAyB,EACzB,OAAuB;QAEvB,OAAO,IAAI,CAAC,KAAK,CAAC,kBAAkB,CAAC,QAAQ,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;IACrE,CAAC;IAED,KAAK,CAAC,oBAAoB,CACxB,QAAgB,EAChB,SAAiB;QAEjB,OAAO,IAAI,CAAC,KAAK,CAAC,0BAA0B,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;IACpE,CAAC;IAED,KAAK,CAAC,cAAc,CAClB,QAAgB,EAChB,kBAA0B,EAC1B,MAAc,EACd,KAAqB;QAErB,MAAM,IAAI,CAAC,KAAK,CAAC,qBAAqB,CAAC,QAAQ,EAAE,kBAAkB,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;IACtF,CAAC;CACF","sourcesContent":["import type { BillingStore } from \"./billing-store.js\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeAttemptState,\n BillingAutoRechargeProfile,\n BillingCustomerRecord,\n BillingOfferResult,\n BillingPreferences,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionState,\n BillingSubscriptionStatus,\n BillingTopupResult,\n CheckoutIntent,\n ListBillingInvoicesOptions,\n} from \"./types/index.js\";\nimport { SUBSCRIPTION_STATUS } from \"./types/index.js\";\nimport type { JsonObject } from \"../shared/json.js\";\n\n/**\n * Public billing reads and commands that delegate directly to BillingStore.\n *\n * Webhook lifecycle orchestration lives in BillingService; this class keeps\n * the stable facade surface separate from that state machine.\n */\nexport class BillingManagement {\n constructor(private readonly store: BillingStore) {}\n\n async createOrGetCheckoutIntent(input: Parameters<BillingStore[\"createOrGetCheckoutIntent\"]>[0]) {\n return this.store.createOrGetCheckoutIntent(input);\n }\n\n async updateCheckoutIntent(\n id: string,\n update: Parameters<BillingStore[\"updateCheckoutIntent\"]>[1],\n ): Promise<void> {\n await this.store.updateCheckoutIntent(id, update);\n }\n\n async getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null> {\n return this.store.getCheckoutIntent(id, subjectId);\n }\n\n async getActiveSubscription(userId: string): Promise<BillingSubscriptionState | null> {\n return this.store.getUserSubscription(userId, [\n SUBSCRIPTION_STATUS.ACTIVE,\n SUBSCRIPTION_STATUS.TRIALING,\n ]);\n }\n\n async getUserPreferences(userId: string): Promise<BillingPreferences | null> {\n return this.store.getBillingPreferences(userId);\n }\n\n async listBillingInvoices(userId: string, options?: ListBillingInvoicesOptions) {\n return this.store.listBillingInvoices(userId, options);\n }\n\n async upsertBillingSubscription(state: BillingSubscriptionState): Promise<void> {\n await this.store.upsertBillingSubscription(state);\n }\n\n async createBillingSubscriptionChange(\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n return this.store.createBillingSubscriptionChange(input);\n }\n\n async findBillingSubscriptionChange(\n provider: string,\n subscriptionId: string,\n operationKey: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.store.findBillingSubscriptionChange(provider, subscriptionId, operationKey);\n }\n\n async getOpenBillingSubscriptionChange(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.store.getOpenBillingSubscriptionChange(provider, providerSubscriptionId);\n }\n\n async updateBillingSubscriptionChange(\n id: string,\n update: Parameters<BillingStore[\"updateBillingSubscriptionChange\"]>[1],\n ): Promise<void> {\n await this.store.updateBillingSubscriptionChange(id, update);\n }\n\n async recordSubscriptionConflict(\n input: Parameters<BillingStore[\"recordSubscriptionConflict\"]>[0],\n ): Promise<void> {\n await this.store.recordSubscriptionConflict(input);\n }\n\n async updateUserPreferences(preferences: BillingPreferences): Promise<void> {\n await this.store.upsertBillingPreferences(preferences);\n }\n\n async getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n return this.store.getAutoRechargeProfile(userId);\n }\n\n async getActiveCatalogDocument(): Promise<JsonObject | null> {\n return this.store.getActiveCatalogDocument();\n }\n\n async listCancellableProviderSubscriptionIds(userId: string): Promise<string[]> {\n const subscriptions = await this.listCancellableSubscriptions(userId);\n return subscriptions.map((subscription) => subscription.providerSubscriptionId);\n }\n\n async listCancellableSubscriptions(userId: string): Promise<BillingSubscriptionState[]> {\n const cancellableStatuses = new Set<BillingSubscriptionStatus>([\n SUBSCRIPTION_STATUS.ACTIVE,\n SUBSCRIPTION_STATUS.TRIALING,\n SUBSCRIPTION_STATUS.PAST_DUE,\n SUBSCRIPTION_STATUS.INCOMPLETE,\n SUBSCRIPTION_STATUS.UNPAID,\n SUBSCRIPTION_STATUS.PAUSED,\n ]);\n const subscriptions = await this.store.getUserSubscriptions(userId);\n return subscriptions.filter(\n (subscription) =>\n subscription.status != null &&\n cancellableStatuses.has(subscription.status) &&\n Boolean(subscription.providerSubscriptionId),\n );\n }\n\n async pseudonymizeFinancialSubject(userId: string): Promise<void> {\n await this.store.pseudonymizeFinancialSubject(userId);\n }\n\n async upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void> {\n return this.store.upsertAutoRechargeProfile(profile, options);\n }\n\n async resumeAutoRechargeProfile(profile: BillingAutoRechargeProfile): Promise<boolean> {\n return this.store.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.store.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 return this.store.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.store.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.store.getAutoRechargeOperationalWindow(userId);\n }\n\n async countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number> {\n return this.store.countAutoRechargeAttempts(userId, since);\n }\n\n async getCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null> {\n return this.store.getBillingCustomerByUserId(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.store.resolveBillingOffer(provider, productId, priceId);\n }\n\n async resolveOfferByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingOfferResult | null> {\n return this.store.resolveBillingOfferByLookup(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.store.resolveCreditTopup(provider, productId, priceId);\n }\n\n async resolveTopupByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingTopupResult | null> {\n return this.store.resolveCreditTopupByLookup(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.store.upsertBillingCustomer(provider, providerCustomerId, userId, email);\n }\n}\n"]}
@@ -28,10 +28,12 @@ export declare class BillingAutoRechargeRepository {
28
28
  updateAttemptByProviderPayment(input: {
29
29
  provider: string;
30
30
  providerPaymentId: string;
31
+ expectedAttemptId?: string;
32
+ expectedUserId?: string;
31
33
  state: BillingAutoRechargeAttemptState;
32
34
  failureCode?: string | null;
33
35
  failureMessage?: string | null;
34
- }): Promise<void>;
36
+ }): Promise<boolean>;
35
37
  operationalWindow(userId: string): Promise<{
36
38
  maxRecharges: number;
37
39
  windowStart: string;
@@ -1 +1 @@
1
- {"version":3,"file":"auto-recharge.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/auto-recharge.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,KAAK,EAAE,UAAU,EAAe,MAAM,yBAAyB,CAAC;AACvE,OAAO,KAAK,EACV,0BAA0B,EAC1B,+BAA+B,EAC/B,0BAA0B,EAC3B,MAAM,sBAAsB,CAAC;AA2Q9B,qBAAa,6BAA6B;IAC5B,OAAO,CAAC,QAAQ,CAAC,KAAK;IAAlC,YAA6B,KAAK,EAAE,OAAO,EAAI;IAEzC,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,0BAA0B,GAAG,IAAI,CAAC,CAM3E;IAEK,aAAa,CAAC,OAAO,EAAE,0BAA0B,GAAG,OAAO,CAAC,OAAO,CAAC,CAiBzE;IAEK,aAAa,CACjB,OAAO,EAAE,0BAA0B,EACnC,OAAO,GAAE;QAAE,aAAa,CAAC,EAAE,OAAO,CAAA;KAAO,GACxC,OAAO,CAAC,IAAI,CAAC,CAgCf;IAEK,YAAY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B,CAAC,KAAK,EAAE;QAC1C,QAAQ,EAAE,MAAM,CAAC;QACjB,iBAAiB,EAAE,MAAM,CAAC;QAC1B,iBAAiB,CAAC,EAAE,MAAM,CAAC;QAC3B,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,KAAK,EAAE,+BAA+B,CAAC;QACvC,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QAC5B,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;KAChC,GAAG,OAAO,CAAC,OAAO,CAAC,CA0BnB;IAEK,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;QAC/C,YAAY,EAAE,MAAM,CAAC;QACrB,WAAW,EAAE,MAAM,CAAC;QACpB,SAAS,EAAE,MAAM,CAAC;QAClB,KAAK,EAAE,MAAM,CAAC;KACf,GAAG,IAAI,CAAC,CAaR;IAEK,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAkBzE;CACF"}
@@ -1,5 +1,6 @@
1
- import { z } from "zod";
2
1
  import { Decimal } from "decimal.js";
2
+ import { PricingDecimal } from "../../../pricing-decimal.js";
3
+ import { z } from "zod";
3
4
  import { StoreError } from "../../../errors.js";
4
5
  import { optionalBoundedDiagnosticMessage } from "../../../shared/diagnostics.js";
5
6
  import { optionalRecordRow, pgBoolean, postgresUuid, requireResultField, safeParse, } from "../../../shared/postgres-validation.js";
@@ -16,7 +17,7 @@ const timestamp = z
16
17
  .transform((value) => (value instanceof Date ? value : new Date(value)).toISOString());
17
18
  const decimal = z
18
19
  .union([z.instanceof(Decimal), z.string().min(1), z.number().finite()])
19
- .transform((value) => new Decimal(value))
20
+ .transform((value) => new PricingDecimal(value))
20
21
  .refine((value) => value.isFinite() && !value.isNegative(), "expected a non-negative decimal");
21
22
  const ProfileRowSchema = z
22
23
  .object({
@@ -116,7 +117,7 @@ const ATTEMPT_TRANSITION_PATHS = new Map([
116
117
  [
117
118
  "submitted",
118
119
  attemptTransitions([
119
- ["submitted", []],
120
+ ["submitted", ["submitted"]],
120
121
  ["processing", ["processing"]],
121
122
  ["succeeded", ["processing", "succeeded"]],
122
123
  ["failed", ["processing", "failed"]],
@@ -127,7 +128,7 @@ const ATTEMPT_TRANSITION_PATHS = new Map([
127
128
  [
128
129
  "processing",
129
130
  attemptTransitions([
130
- ["processing", []],
131
+ ["processing", ["processing"]],
131
132
  ["succeeded", ["succeeded"]],
132
133
  ["failed", ["failed"]],
133
134
  ["unknown", ["unknown"]],
@@ -137,7 +138,7 @@ const ATTEMPT_TRANSITION_PATHS = new Map([
137
138
  [
138
139
  "unknown",
139
140
  attemptTransitions([
140
- ["unknown", []],
141
+ ["unknown", ["unknown"]],
141
142
  ["processing", ["processing"]],
142
143
  ["succeeded", ["succeeded"]],
143
144
  ["failed", ["failed"]],
@@ -147,12 +148,20 @@ const ATTEMPT_TRANSITION_PATHS = new Map([
147
148
  [
148
149
  "action_required",
149
150
  attemptTransitions([
150
- ["action_required", []],
151
+ ["action_required", ["action_required"]],
151
152
  ["processing", ["processing"]],
152
153
  ["succeeded", ["succeeded"]],
153
154
  ["failed", ["failed"]],
154
155
  ]),
155
156
  ],
157
+ ["succeeded", attemptTransitions([["succeeded", ["succeeded"]]])],
158
+ [
159
+ "failed",
160
+ attemptTransitions([
161
+ ["failed", ["failed"]],
162
+ ["succeeded", ["succeeded"]],
163
+ ]),
164
+ ],
156
165
  ]);
157
166
  function projectProfile(row) {
158
167
  return {
@@ -347,8 +356,14 @@ export class BillingAutoRechargeRepository {
347
356
  const rows = await this.query(`SELECT * FROM bursar.get_auto_recharge_attempt_by_provider($1, $2)`, [input.provider, input.providerPaymentId]);
348
357
  const row = optionalRecordRow(rows, "BillingAutoRechargeRepository.updateAttemptByProviderPayment");
349
358
  if (row === null)
350
- return;
359
+ return false;
351
360
  const attempt = attemptFromRow(row);
361
+ if ((input.expectedAttemptId && attempt.id !== input.expectedAttemptId) ||
362
+ (input.expectedUserId && attempt.userId !== input.expectedUserId))
363
+ return false;
364
+ // A delayed failure cannot undo a settled payment or rearm its profile.
365
+ if (attempt.state === "succeeded" && input.state === "failed")
366
+ return true;
352
367
  await this.advanceAttempt({
353
368
  id: attempt.id,
354
369
  state: input.state,
@@ -356,6 +371,7 @@ export class BillingAutoRechargeRepository {
356
371
  failureCode: input.failureCode,
357
372
  failureMessage: input.failureMessage,
358
373
  });
374
+ return true;
359
375
  }
360
376
  async operationalWindow(userId) {
361
377
  const rows = await this.query("SELECT * FROM bursar.get_auto_recharge_operational_window($1::uuid)", [userId]);
@@ -1 +1 @@
1
- {"version":3,"file":"auto-recharge.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/auto-recharge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAQhD,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAClF,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,sBAAsB,GAAG,CAAC;KAC7B,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;KAC9C,SAAS,CAAC,MAAM,CAAC;KACjB,IAAI,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC,CAAC;AACrE,MAAM,eAAe,GAAG,sBAAsB,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAC;AAC3E,MAAM,SAA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ACjF,SAAS,EAAE,SAAS,CAAC,SAAS,EAAE,GAAG,CAAC,UAAU,EAAE,0BAA0B,CAAC;YAC3E,KAAK,EAAE,SAAS,CAAC,sBAAsB,EAAE,GAAG,CAAC,aAAa,EAAE,6BAA6B,CAAC;SAC3F,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,aAAa,CAAC,MAAc,EAAE,KAAoB;QACtD,MAAM,SAAS,GAAG,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;QAClE,IAAI,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC;YACtC,MAAM,IAAI,SAAS,CAAC,wDAAwD,CAAC,CAAC;QAChF,CAAC;QACD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,gFAAgF,EAChF,CAAC,MAAM,EAAE,SAAS,CAAC,WAAW,EAAE,CAAC,CAClC,CAAC;QACF,OAAO,kBAAkB,CACvB,IAAI,EACJ,OAAO,EACP,CAAC;aACE,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;aAC9C,SAAS,CAAC,MAAM,CAAC;aACjB,IAAI,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,CAAC,EAC9C,6CAA6C,CAC9C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { Decimal } from \"decimal.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { JsonObject, PostgresRow } from \"../../../shared/json.js\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeAttemptState,\n BillingAutoRechargeProfile,\n} from \"../../types/index.js\";\nimport { optionalBoundedDiagnosticMessage } from \"../../../shared/diagnostics.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst safeNonnegativeInteger = z\n .union([z.number(), z.string().regex(/^\\d+$/)])\n .transform(Number)\n .pipe(z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER));\nconst positiveInteger = safeNonnegativeInteger.pipe(z.number().positive());\nconst timestamp = z\n .union([\n z.date().refine((value) => !Number.isNaN(value.getTime())),\n z.string().datetime({ offset: true }),\n ])\n .transform((value) => (value instanceof Date ? value : new Date(value)).toISOString());\nconst decimal = z\n .union([z.instanceof(Decimal), z.string().min(1), z.number().finite()])\n .transform((value) => new Decimal(value))\n .refine((value) => value.isFinite() && !value.isNegative(), \"expected a non-negative decimal\");\n\nconst ProfileRowSchema = z\n .object({\n subject_id: postgresUuid,\n enabled: pgBoolean,\n armed: pgBoolean,\n state: z.enum([\"disabled\", \"active\", \"paused\"]),\n provider: z.string().min(1).nullable(),\n topup_id: postgresUuid.nullable(),\n topup_key: z.string().min(1).nullable(),\n quantity: positiveInteger,\n threshold: decimal,\n max_charges_per_window: positiveInteger.nullable(),\n window_unit: z.enum([\"second\", \"minute\", \"hour\", \"day\", \"week\", \"month\", \"year\"]),\n window_count: positiveInteger,\n window_anchor: z.enum([\"calendar\", \"rolling\"]),\n window_timezone: z.string().min(1),\n updated_at: timestamp,\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.enabled !== (row.state !== \"disabled\")) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"enabled and state are inconsistent\",\n });\n }\n if (row.enabled && (row.provider === null || row.topup_id === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"enabled profile requires provider and topup_id\",\n });\n }\n });\n\nconst AttemptStateSchema = z.enum([\n \"claimed\",\n \"submitted\",\n \"processing\",\n \"unknown\",\n \"succeeded\",\n \"failed\",\n \"action_required\",\n]);\nconst AttemptRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n idempotency_key: z.string().min(1),\n provider_attempt_id: z.string().min(1).nullable(),\n topup_id: postgresUuid,\n quantity: positiveInteger,\n state: AttemptStateSchema,\n window_start: timestamp,\n window_end: timestamp,\n quoted_amount_minor: safeNonnegativeInteger.nullable(),\n currency: z\n .string()\n .regex(/^[A-Z]{3}$/)\n .nullable(),\n failure_code: z.string().min(1).nullable(),\n failure_message: z.string().min(1).nullable(),\n metadata: z.record(z.string(), z.json()),\n created_at: timestamp,\n updated_at: timestamp,\n })\n .strict()\n .superRefine((row, ctx) => {\n if (new Date(row.window_end).getTime() <= new Date(row.window_start).getTime()) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"window_end must be later than window_start\",\n });\n }\n if ((row.quoted_amount_minor === null) !== (row.currency === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"quoted_amount_minor and currency must be present together\",\n });\n }\n });\n\ntype AttemptTransitionPath = readonly BillingAutoRechargeAttemptState[];\n\nfunction attemptTransitions(\n entries: ReadonlyArray<readonly [BillingAutoRechargeAttemptState, AttemptTransitionPath]>,\n): ReadonlyMap<BillingAutoRechargeAttemptState, AttemptTransitionPath> {\n return new Map(entries);\n}\n\nconst ATTEMPT_TRANSITION_PATHS = new Map<\n BillingAutoRechargeAttemptState,\n ReadonlyMap<BillingAutoRechargeAttemptState, AttemptTransitionPath>\n>([\n [\n \"claimed\",\n attemptTransitions([\n [\"submitted\", [\"submitted\"]],\n [\"processing\", [\"submitted\", \"processing\"]],\n [\"succeeded\", [\"submitted\", \"processing\", \"succeeded\"]],\n [\"failed\", [\"submitted\", \"processing\", \"failed\"]],\n [\"unknown\", [\"submitted\", \"processing\", \"unknown\"]],\n [\"action_required\", [\"submitted\", \"action_required\"]],\n ]),\n ],\n [\n \"submitted\",\n attemptTransitions([\n [\"submitted\", []],\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"processing\", \"succeeded\"]],\n [\"failed\", [\"processing\", \"failed\"]],\n [\"unknown\", [\"processing\", \"unknown\"]],\n [\"action_required\", [\"action_required\"]],\n ]),\n ],\n [\n \"processing\",\n attemptTransitions([\n [\"processing\", []],\n [\"succeeded\", [\"succeeded\"]],\n [\"failed\", [\"failed\"]],\n [\"unknown\", [\"unknown\"]],\n [\"action_required\", [\"action_required\"]],\n ]),\n ],\n [\n \"unknown\",\n attemptTransitions([\n [\"unknown\", []],\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"succeeded\"]],\n [\"failed\", [\"failed\"]],\n [\"action_required\", [\"action_required\"]],\n ]),\n ],\n [\n \"action_required\",\n attemptTransitions([\n [\"action_required\", []],\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"succeeded\"]],\n [\"failed\", [\"failed\"]],\n ]),\n ],\n]);\n\nfunction projectProfile(row: PostgresRow) {\n return {\n subject_id: row.subject_id,\n enabled: row.enabled,\n armed: row.armed,\n state: row.state,\n provider: row.provider,\n topup_id: row.topup_id,\n topup_key: row.topup_key ?? null,\n quantity: row.quantity,\n threshold: row.threshold,\n max_charges_per_window: row.max_charges_per_window,\n window_unit: row.window_unit,\n window_count: row.window_count,\n window_anchor: row.window_anchor,\n window_timezone: row.window_timezone,\n updated_at: row.updated_at,\n };\n}\n\nfunction projectAttempt(row: PostgresRow) {\n return {\n id: row.id,\n subject_id: row.subject_id,\n provider: row.provider,\n idempotency_key: row.idempotency_key,\n provider_attempt_id: row.provider_attempt_id,\n topup_id: row.topup_id,\n quantity: row.quantity,\n state: row.state,\n window_start: row.window_start,\n window_end: row.window_end,\n quoted_amount_minor: row.quoted_amount_minor,\n currency: row.currency,\n failure_code: row.failure_code,\n failure_message: row.failure_message,\n metadata: row.metadata,\n created_at: row.created_at,\n updated_at: row.updated_at,\n };\n}\n\nfunction profileFromRow(row: PostgresRow): BillingAutoRechargeProfile {\n const parsed = safeParse(\n ProfileRowSchema,\n projectProfile(row),\n \"BillingAutoRechargeRepository.profile\",\n );\n return {\n userId: parsed.subject_id,\n enabled: parsed.enabled,\n armed: parsed.armed,\n state: parsed.state,\n provider: parsed.provider,\n topupId: parsed.topup_id,\n topupKey: parsed.topup_key,\n quantity: parsed.quantity,\n threshold: parsed.threshold,\n maxChargesPerWindow: parsed.max_charges_per_window,\n windowUnit: parsed.window_unit,\n windowCount: parsed.window_count,\n windowAnchor: parsed.window_anchor,\n windowTimezone: parsed.window_timezone,\n updatedAt: parsed.updated_at,\n };\n}\n\nfunction attemptFromRow(row: PostgresRow): BillingAutoRechargeAttempt {\n const parsed = safeParse(\n AttemptRowSchema,\n projectAttempt(row),\n \"BillingAutoRechargeRepository.attempt\",\n );\n return {\n id: parsed.id,\n userId: parsed.subject_id,\n provider: parsed.provider,\n idempotencyKey: parsed.idempotency_key,\n providerAttemptId: parsed.provider_attempt_id,\n topupId: parsed.topup_id,\n quantity: parsed.quantity,\n state: parsed.state,\n windowStart: parsed.window_start,\n windowEnd: parsed.window_end,\n quotedAmountMinor: parsed.quoted_amount_minor,\n currency: parsed.currency,\n failureCode: parsed.failure_code,\n failureMessage: parsed.failure_message,\n metadata: parsed.metadata,\n createdAt: parsed.created_at,\n updatedAt: parsed.updated_at,\n };\n}\n\nexport class BillingAutoRechargeRepository {\n constructor(private readonly query: QueryFn) {}\n\n async getProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_auto_recharge_profile($1::uuid)\", [\n userId,\n ]);\n const row = optionalRecordRow(rows, \"BillingAutoRechargeRepository.getProfile\");\n return row === null ? null : profileFromRow(row);\n }\n\n async resumeProfile(profile: BillingAutoRechargeProfile): Promise<boolean> {\n const rows = await this.query(\n \"SELECT bursar.resume_auto_recharge_profile($1::uuid, $2, $3::uuid, $4, $5) AS updated\",\n [\n profile.userId,\n profile.provider,\n profile.topupId,\n profile.quantity,\n profile.threshold.toString(),\n ],\n );\n return requireResultField(\n rows,\n \"updated\",\n pgBoolean,\n \"BillingAutoRechargeRepository.resumeProfile\",\n );\n }\n\n async upsertProfile(\n profile: BillingAutoRechargeProfile,\n options: { resetCooldown?: boolean } = {},\n ): Promise<void> {\n // Keep the exported compatibility option on the same resume transition.\n if (options.resetCooldown) {\n if (!(await this.resumeProfile(profile)))\n throw new StoreError(`auto-recharge profile update rejected: ${profile.userId}`);\n return;\n }\n const rows = await this.query(\n `SELECT bursar.upsert_auto_recharge_profile(\n $1::uuid, $2, $3, $4::uuid, $5, $6, $7, $8, $9, $10, $11, $12, $13\n ) AS updated`,\n [\n profile.userId,\n profile.enabled,\n profile.provider,\n profile.topupId,\n profile.quantity,\n profile.threshold.toString(),\n profile.maxChargesPerWindow,\n profile.windowUnit,\n profile.windowCount,\n profile.windowAnchor,\n profile.windowTimezone,\n profile.armed,\n profile.state,\n ],\n );\n if (\n !requireResultField(rows, \"updated\", pgBoolean, \"BillingAutoRechargeRepository.upsertProfile\")\n ) {\n throw new StoreError(`auto-recharge profile update rejected: ${profile.userId}`);\n }\n }\n\n async claimAttempt(input: {\n userId: string;\n idempotencyKey: string;\n expectedProductId: string;\n expectedQuantity: number;\n expectedTopupKey: string;\n }): Promise<BillingAutoRechargeAttempt | null> {\n const rows = await this.query(\n \"SELECT * FROM bursar.claim_auto_recharge_attempt($1::uuid, $2, $3, $4, $5)\",\n [\n input.userId,\n input.idempotencyKey,\n input.expectedProductId,\n input.expectedQuantity,\n input.expectedTopupKey,\n ],\n );\n const row = optionalRecordRow(rows, \"BillingAutoRechargeRepository.claimAttempt\");\n return row === null ? null : attemptFromRow(row);\n }\n\n private async advanceAttempt(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 const failureMessage = optionalBoundedDiagnosticMessage(input.failureMessage);\n const currentRows = await this.query(\n \"SELECT * FROM bursar.get_auto_recharge_attempt($1::uuid)\",\n [input.id],\n );\n const currentRow = optionalRecordRow(\n currentRows,\n \"BillingAutoRechargeRepository.advanceAttempt.current\",\n );\n if (currentRow === null) {\n throw new StoreError(`auto-recharge attempt not found: ${input.id}`, {\n details: { attemptId: input.id },\n });\n }\n const current = safeParse(\n AttemptStateSchema,\n currentRow.state,\n \"BillingAutoRechargeRepository.advanceAttempt.current.state\",\n );\n const path = ATTEMPT_TRANSITION_PATHS.get(current)?.get(input.state);\n if (!path) {\n throw new StoreError(`auto-recharge attempt transition rejected: ${input.id}`, {\n details: {\n attemptId: input.id,\n currentState: current,\n requestedState: input.state,\n },\n });\n }\n for (const state of path) {\n const rows = await this.query(\n `SELECT bursar.advance_auto_recharge_attempt(\n $1::uuid,\n $2::bursar.recharge_attempt_status,\n $3,\n $4,\n $5,\n $6::jsonb\n ) AS advanced`,\n [\n input.id,\n state,\n input.providerAttemptId ?? null,\n input.failureCode ?? null,\n failureMessage,\n JSON.stringify(input.metadata ?? {}),\n ],\n );\n if (\n !requireResultField(\n rows,\n \"advanced\",\n pgBoolean,\n \"BillingAutoRechargeRepository.advanceAttempt\",\n )\n ) {\n throw new StoreError(`auto-recharge attempt transition rejected: ${input.id}`, {\n details: { attemptId: input.id, requestedState: state },\n });\n }\n }\n }\n\n async updateAttempt(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 return this.advanceAttempt(input);\n }\n\n async updateAttemptByProviderPayment(input: {\n provider: string;\n providerPaymentId: string;\n state: BillingAutoRechargeAttemptState;\n failureCode?: string | null;\n failureMessage?: string | null;\n }): Promise<void> {\n const rows = await this.query(\n `SELECT * FROM bursar.get_auto_recharge_attempt_by_provider($1, $2)`,\n [input.provider, input.providerPaymentId],\n );\n const row = optionalRecordRow(\n rows,\n \"BillingAutoRechargeRepository.updateAttemptByProviderPayment\",\n );\n if (row === null) return;\n const attempt = attemptFromRow(row);\n await this.advanceAttempt({\n id: attempt.id,\n state: input.state,\n providerAttemptId: input.providerPaymentId,\n failureCode: input.failureCode,\n failureMessage: input.failureMessage,\n });\n }\n\n async operationalWindow(userId: string): Promise<{\n maxRecharges: number;\n windowStart: string;\n windowEnd: string;\n count: number;\n } | null> {\n const rows = await this.query(\n \"SELECT * FROM bursar.get_auto_recharge_operational_window($1::uuid)\",\n [userId],\n );\n const row = optionalRecordRow(rows, \"BillingAutoRechargeRepository.operationalWindow\");\n if (!row) return null;\n return {\n maxRecharges: safeParse(positiveInteger, row.max_recharges, \"auto-recharge max\"),\n windowStart: safeParse(timestamp, row.window_start, \"auto-recharge window start\"),\n windowEnd: safeParse(timestamp, row.window_end, \"auto-recharge window end\"),\n count: safeParse(safeNonnegativeInteger, row.attempt_count, \"auto-recharge attempt count\"),\n };\n }\n\n async countAttempts(userId: string, since: string | Date): Promise<number> {\n const sinceDate = since instanceof Date ? since : new Date(since);\n if (Number.isNaN(sinceDate.getTime())) {\n throw new TypeError(\"auto-recharge attempt boundary must be a valid instant\");\n }\n const rows = await this.query(\n `SELECT bursar.count_auto_recharge_attempts($1::uuid, $2::timestamptz) AS count`,\n [userId, sinceDate.toISOString()],\n );\n return requireResultField(\n rows,\n \"count\",\n z\n .union([z.number(), z.string().regex(/^\\d+$/)])\n .transform(Number)\n .pipe(z.number().int().nonnegative().safe()),\n \"BillingAutoRechargeRepository.countAttempts\",\n );\n }\n}\n"]}
1
+ {"version":3,"file":"auto-recharge.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/auto-recharge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAQhD,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAClF,OAAO,EACL,iBAAiB,EACjB,SAAS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AAU,EAAE,0BAA0B,CAAC;YAC3E,KAAK,EAAE,SAAS,CAAC,sBAAsB,EAAE,GAAG,CAAC,aAAa,EAAE,6BAA6B,CAAC;SAC3F,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,aAAa,CAAC,MAAc,EAAE,KAAoB;QACtD,MAAM,SAAS,GAAG,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;QAClE,IAAI,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC;YACtC,MAAM,IAAI,SAAS,CAAC,wDAAwD,CAAC,CAAC;QAChF,CAAC;QACD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,gFAAgF,EAChF,CAAC,MAAM,EAAE,SAAS,CAAC,WAAW,EAAE,CAAC,CAClC,CAAC;QACF,OAAO,kBAAkB,CACvB,IAAI,EACJ,OAAO,EACP,CAAC;aACE,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;aAC9C,SAAS,CAAC,MAAM,CAAC;aACjB,IAAI,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,CAAC,EAC9C,6CAA6C,CAC9C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { PricingDecimal } from \"../../../pricing-decimal.js\";\nimport { z } from \"zod\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { JsonObject, PostgresRow } from \"../../../shared/json.js\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeAttemptState,\n BillingAutoRechargeProfile,\n} from \"../../types/index.js\";\nimport { optionalBoundedDiagnosticMessage } from \"../../../shared/diagnostics.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst safeNonnegativeInteger = z\n .union([z.number(), z.string().regex(/^\\d+$/)])\n .transform(Number)\n .pipe(z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER));\nconst positiveInteger = safeNonnegativeInteger.pipe(z.number().positive());\nconst timestamp = z\n .union([\n z.date().refine((value) => !Number.isNaN(value.getTime())),\n z.string().datetime({ offset: true }),\n ])\n .transform((value) => (value instanceof Date ? value : new Date(value)).toISOString());\nconst decimal = z\n .union([z.instanceof(Decimal), z.string().min(1), z.number().finite()])\n .transform((value) => new PricingDecimal(value))\n .refine((value) => value.isFinite() && !value.isNegative(), \"expected a non-negative decimal\");\n\nconst ProfileRowSchema = z\n .object({\n subject_id: postgresUuid,\n enabled: pgBoolean,\n armed: pgBoolean,\n state: z.enum([\"disabled\", \"active\", \"paused\"]),\n provider: z.string().min(1).nullable(),\n topup_id: postgresUuid.nullable(),\n topup_key: z.string().min(1).nullable(),\n quantity: positiveInteger,\n threshold: decimal,\n max_charges_per_window: positiveInteger.nullable(),\n window_unit: z.enum([\"second\", \"minute\", \"hour\", \"day\", \"week\", \"month\", \"year\"]),\n window_count: positiveInteger,\n window_anchor: z.enum([\"calendar\", \"rolling\"]),\n window_timezone: z.string().min(1),\n updated_at: timestamp,\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.enabled !== (row.state !== \"disabled\")) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"enabled and state are inconsistent\",\n });\n }\n if (row.enabled && (row.provider === null || row.topup_id === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"enabled profile requires provider and topup_id\",\n });\n }\n });\n\nconst AttemptStateSchema = z.enum([\n \"claimed\",\n \"submitted\",\n \"processing\",\n \"unknown\",\n \"succeeded\",\n \"failed\",\n \"action_required\",\n]);\nconst AttemptRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n idempotency_key: z.string().min(1),\n provider_attempt_id: z.string().min(1).nullable(),\n topup_id: postgresUuid,\n quantity: positiveInteger,\n state: AttemptStateSchema,\n window_start: timestamp,\n window_end: timestamp,\n quoted_amount_minor: safeNonnegativeInteger.nullable(),\n currency: z\n .string()\n .regex(/^[A-Z]{3}$/)\n .nullable(),\n failure_code: z.string().min(1).nullable(),\n failure_message: z.string().min(1).nullable(),\n metadata: z.record(z.string(), z.json()),\n created_at: timestamp,\n updated_at: timestamp,\n })\n .strict()\n .superRefine((row, ctx) => {\n if (new Date(row.window_end).getTime() <= new Date(row.window_start).getTime()) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"window_end must be later than window_start\",\n });\n }\n if ((row.quoted_amount_minor === null) !== (row.currency === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"quoted_amount_minor and currency must be present together\",\n });\n }\n });\n\ntype AttemptTransitionPath = readonly BillingAutoRechargeAttemptState[];\n\nfunction attemptTransitions(\n entries: ReadonlyArray<readonly [BillingAutoRechargeAttemptState, AttemptTransitionPath]>,\n): ReadonlyMap<BillingAutoRechargeAttemptState, AttemptTransitionPath> {\n return new Map(entries);\n}\n\nconst ATTEMPT_TRANSITION_PATHS = new Map<\n BillingAutoRechargeAttemptState,\n ReadonlyMap<BillingAutoRechargeAttemptState, AttemptTransitionPath>\n>([\n [\n \"claimed\",\n attemptTransitions([\n [\"submitted\", [\"submitted\"]],\n [\"processing\", [\"submitted\", \"processing\"]],\n [\"succeeded\", [\"submitted\", \"processing\", \"succeeded\"]],\n [\"failed\", [\"submitted\", \"processing\", \"failed\"]],\n [\"unknown\", [\"submitted\", \"processing\", \"unknown\"]],\n [\"action_required\", [\"submitted\", \"action_required\"]],\n ]),\n ],\n [\n \"submitted\",\n attemptTransitions([\n [\"submitted\", [\"submitted\"]],\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"processing\", \"succeeded\"]],\n [\"failed\", [\"processing\", \"failed\"]],\n [\"unknown\", [\"processing\", \"unknown\"]],\n [\"action_required\", [\"action_required\"]],\n ]),\n ],\n [\n \"processing\",\n attemptTransitions([\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"succeeded\"]],\n [\"failed\", [\"failed\"]],\n [\"unknown\", [\"unknown\"]],\n [\"action_required\", [\"action_required\"]],\n ]),\n ],\n [\n \"unknown\",\n attemptTransitions([\n [\"unknown\", [\"unknown\"]],\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"succeeded\"]],\n [\"failed\", [\"failed\"]],\n [\"action_required\", [\"action_required\"]],\n ]),\n ],\n [\n \"action_required\",\n attemptTransitions([\n [\"action_required\", [\"action_required\"]],\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"succeeded\"]],\n [\"failed\", [\"failed\"]],\n ]),\n ],\n [\"succeeded\", attemptTransitions([[\"succeeded\", [\"succeeded\"]]])],\n [\n \"failed\",\n attemptTransitions([\n [\"failed\", [\"failed\"]],\n [\"succeeded\", [\"succeeded\"]],\n ]),\n ],\n]);\n\nfunction projectProfile(row: PostgresRow) {\n return {\n subject_id: row.subject_id,\n enabled: row.enabled,\n armed: row.armed,\n state: row.state,\n provider: row.provider,\n topup_id: row.topup_id,\n topup_key: row.topup_key ?? null,\n quantity: row.quantity,\n threshold: row.threshold,\n max_charges_per_window: row.max_charges_per_window,\n window_unit: row.window_unit,\n window_count: row.window_count,\n window_anchor: row.window_anchor,\n window_timezone: row.window_timezone,\n updated_at: row.updated_at,\n };\n}\n\nfunction projectAttempt(row: PostgresRow) {\n return {\n id: row.id,\n subject_id: row.subject_id,\n provider: row.provider,\n idempotency_key: row.idempotency_key,\n provider_attempt_id: row.provider_attempt_id,\n topup_id: row.topup_id,\n quantity: row.quantity,\n state: row.state,\n window_start: row.window_start,\n window_end: row.window_end,\n quoted_amount_minor: row.quoted_amount_minor,\n currency: row.currency,\n failure_code: row.failure_code,\n failure_message: row.failure_message,\n metadata: row.metadata,\n created_at: row.created_at,\n updated_at: row.updated_at,\n };\n}\n\nfunction profileFromRow(row: PostgresRow): BillingAutoRechargeProfile {\n const parsed = safeParse(\n ProfileRowSchema,\n projectProfile(row),\n \"BillingAutoRechargeRepository.profile\",\n );\n return {\n userId: parsed.subject_id,\n enabled: parsed.enabled,\n armed: parsed.armed,\n state: parsed.state,\n provider: parsed.provider,\n topupId: parsed.topup_id,\n topupKey: parsed.topup_key,\n quantity: parsed.quantity,\n threshold: parsed.threshold,\n maxChargesPerWindow: parsed.max_charges_per_window,\n windowUnit: parsed.window_unit,\n windowCount: parsed.window_count,\n windowAnchor: parsed.window_anchor,\n windowTimezone: parsed.window_timezone,\n updatedAt: parsed.updated_at,\n };\n}\n\nfunction attemptFromRow(row: PostgresRow): BillingAutoRechargeAttempt {\n const parsed = safeParse(\n AttemptRowSchema,\n projectAttempt(row),\n \"BillingAutoRechargeRepository.attempt\",\n );\n return {\n id: parsed.id,\n userId: parsed.subject_id,\n provider: parsed.provider,\n idempotencyKey: parsed.idempotency_key,\n providerAttemptId: parsed.provider_attempt_id,\n topupId: parsed.topup_id,\n quantity: parsed.quantity,\n state: parsed.state,\n windowStart: parsed.window_start,\n windowEnd: parsed.window_end,\n quotedAmountMinor: parsed.quoted_amount_minor,\n currency: parsed.currency,\n failureCode: parsed.failure_code,\n failureMessage: parsed.failure_message,\n metadata: parsed.metadata,\n createdAt: parsed.created_at,\n updatedAt: parsed.updated_at,\n };\n}\n\nexport class BillingAutoRechargeRepository {\n constructor(private readonly query: QueryFn) {}\n\n async getProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_auto_recharge_profile($1::uuid)\", [\n userId,\n ]);\n const row = optionalRecordRow(rows, \"BillingAutoRechargeRepository.getProfile\");\n return row === null ? null : profileFromRow(row);\n }\n\n async resumeProfile(profile: BillingAutoRechargeProfile): Promise<boolean> {\n const rows = await this.query(\n \"SELECT bursar.resume_auto_recharge_profile($1::uuid, $2, $3::uuid, $4, $5) AS updated\",\n [\n profile.userId,\n profile.provider,\n profile.topupId,\n profile.quantity,\n profile.threshold.toString(),\n ],\n );\n return requireResultField(\n rows,\n \"updated\",\n pgBoolean,\n \"BillingAutoRechargeRepository.resumeProfile\",\n );\n }\n\n async upsertProfile(\n profile: BillingAutoRechargeProfile,\n options: { resetCooldown?: boolean } = {},\n ): Promise<void> {\n // Keep the exported compatibility option on the same resume transition.\n if (options.resetCooldown) {\n if (!(await this.resumeProfile(profile)))\n throw new StoreError(`auto-recharge profile update rejected: ${profile.userId}`);\n return;\n }\n const rows = await this.query(\n `SELECT bursar.upsert_auto_recharge_profile(\n $1::uuid, $2, $3, $4::uuid, $5, $6, $7, $8, $9, $10, $11, $12, $13\n ) AS updated`,\n [\n profile.userId,\n profile.enabled,\n profile.provider,\n profile.topupId,\n profile.quantity,\n profile.threshold.toString(),\n profile.maxChargesPerWindow,\n profile.windowUnit,\n profile.windowCount,\n profile.windowAnchor,\n profile.windowTimezone,\n profile.armed,\n profile.state,\n ],\n );\n if (\n !requireResultField(rows, \"updated\", pgBoolean, \"BillingAutoRechargeRepository.upsertProfile\")\n ) {\n throw new StoreError(`auto-recharge profile update rejected: ${profile.userId}`);\n }\n }\n\n async claimAttempt(input: {\n userId: string;\n idempotencyKey: string;\n expectedProductId: string;\n expectedQuantity: number;\n expectedTopupKey: string;\n }): Promise<BillingAutoRechargeAttempt | null> {\n const rows = await this.query(\n \"SELECT * FROM bursar.claim_auto_recharge_attempt($1::uuid, $2, $3, $4, $5)\",\n [\n input.userId,\n input.idempotencyKey,\n input.expectedProductId,\n input.expectedQuantity,\n input.expectedTopupKey,\n ],\n );\n const row = optionalRecordRow(rows, \"BillingAutoRechargeRepository.claimAttempt\");\n return row === null ? null : attemptFromRow(row);\n }\n\n private async advanceAttempt(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 const failureMessage = optionalBoundedDiagnosticMessage(input.failureMessage);\n const currentRows = await this.query(\n \"SELECT * FROM bursar.get_auto_recharge_attempt($1::uuid)\",\n [input.id],\n );\n const currentRow = optionalRecordRow(\n currentRows,\n \"BillingAutoRechargeRepository.advanceAttempt.current\",\n );\n if (currentRow === null) {\n throw new StoreError(`auto-recharge attempt not found: ${input.id}`, {\n details: { attemptId: input.id },\n });\n }\n const current = safeParse(\n AttemptStateSchema,\n currentRow.state,\n \"BillingAutoRechargeRepository.advanceAttempt.current.state\",\n );\n const path = ATTEMPT_TRANSITION_PATHS.get(current)?.get(input.state);\n if (!path) {\n throw new StoreError(`auto-recharge attempt transition rejected: ${input.id}`, {\n details: {\n attemptId: input.id,\n currentState: current,\n requestedState: input.state,\n },\n });\n }\n for (const state of path) {\n const rows = await this.query(\n `SELECT bursar.advance_auto_recharge_attempt(\n $1::uuid,\n $2::bursar.recharge_attempt_status,\n $3,\n $4,\n $5,\n $6::jsonb\n ) AS advanced`,\n [\n input.id,\n state,\n input.providerAttemptId ?? null,\n input.failureCode ?? null,\n failureMessage,\n JSON.stringify(input.metadata ?? {}),\n ],\n );\n if (\n !requireResultField(\n rows,\n \"advanced\",\n pgBoolean,\n \"BillingAutoRechargeRepository.advanceAttempt\",\n )\n ) {\n throw new StoreError(`auto-recharge attempt transition rejected: ${input.id}`, {\n details: { attemptId: input.id, requestedState: state },\n });\n }\n }\n }\n\n async updateAttempt(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 return this.advanceAttempt(input);\n }\n\n async updateAttemptByProviderPayment(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 const rows = await this.query(\n `SELECT * FROM bursar.get_auto_recharge_attempt_by_provider($1, $2)`,\n [input.provider, input.providerPaymentId],\n );\n const row = optionalRecordRow(\n rows,\n \"BillingAutoRechargeRepository.updateAttemptByProviderPayment\",\n );\n if (row === null) return false;\n const attempt = attemptFromRow(row);\n if (\n (input.expectedAttemptId && attempt.id !== input.expectedAttemptId) ||\n (input.expectedUserId && attempt.userId !== input.expectedUserId)\n )\n return false;\n // A delayed failure cannot undo a settled payment or rearm its profile.\n if (attempt.state === \"succeeded\" && input.state === \"failed\") return true;\n await this.advanceAttempt({\n id: attempt.id,\n state: input.state,\n providerAttemptId: input.providerPaymentId,\n failureCode: input.failureCode,\n failureMessage: input.failureMessage,\n });\n return true;\n }\n\n async operationalWindow(userId: string): Promise<{\n maxRecharges: number;\n windowStart: string;\n windowEnd: string;\n count: number;\n } | null> {\n const rows = await this.query(\n \"SELECT * FROM bursar.get_auto_recharge_operational_window($1::uuid)\",\n [userId],\n );\n const row = optionalRecordRow(rows, \"BillingAutoRechargeRepository.operationalWindow\");\n if (!row) return null;\n return {\n maxRecharges: safeParse(positiveInteger, row.max_recharges, \"auto-recharge max\"),\n windowStart: safeParse(timestamp, row.window_start, \"auto-recharge window start\"),\n windowEnd: safeParse(timestamp, row.window_end, \"auto-recharge window end\"),\n count: safeParse(safeNonnegativeInteger, row.attempt_count, \"auto-recharge attempt count\"),\n };\n }\n\n async countAttempts(userId: string, since: string | Date): Promise<number> {\n const sinceDate = since instanceof Date ? since : new Date(since);\n if (Number.isNaN(sinceDate.getTime())) {\n throw new TypeError(\"auto-recharge attempt boundary must be a valid instant\");\n }\n const rows = await this.query(\n `SELECT bursar.count_auto_recharge_attempts($1::uuid, $2::timestamptz) AS count`,\n [userId, sinceDate.toISOString()],\n );\n return requireResultField(\n rows,\n \"count\",\n z\n .union([z.number(), z.string().regex(/^\\d+$/)])\n .transform(Number)\n .pipe(z.number().int().nonnegative().safe()),\n \"BillingAutoRechargeRepository.countAttempts\",\n );\n }\n}\n"]}
@@ -1,10 +1,11 @@
1
1
  import type { QueryFn } from "../../../shared/postgres-types.js";
2
2
  import type { JsonObject } from "../../../shared/json.js";
3
- import type { BillingInvoiceRecord } from "../../types/index.js";
3
+ import type { BillingInvoicePage, ListBillingInvoicesOptions } from "../../types/index.js";
4
4
  export declare class BillingInvoiceRepository {
5
5
  private query;
6
6
  constructor(query: QueryFn);
7
- listForUser(userId: string): Promise<BillingInvoiceRecord[]>;
7
+ listForUser(userId: string, options?: ListBillingInvoicesOptions): Promise<BillingInvoicePage>;
8
+ hasForUser(userId: string, provider: string, providerInvoiceId: string): Promise<boolean>;
8
9
  upsert(subjectId: string, provider: string, providerInvoiceId: string, subscriptionId: string | null, status: "draft" | "open" | "paid" | "void" | "uncollectible", amountPaidMinor: number, amountDueMinor: number, currency: string, periodStart: string | null, periodEnd: string | null, metadata: JsonObject, providerUpdatedAt: string): Promise<void>;
9
10
  }
10
11
  //# sourceMappingURL=invoice.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"invoice.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/invoice.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAgCjE,qBAAa,wBAAwB;IACvB,OAAO,CAAC,KAAK;IAAzB,YAAoB,KAAK,EAAE,OAAO,EAAI;IAEhC,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,EAAE,CAAC,CA4BjE;IAEK,MAAM,CACV,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,iBAAiB,EAAE,MAAM,EACzB,cAAc,EAAE,MAAM,GAAG,IAAI,EAC7B,MAAM,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,eAAe,EAC5D,eAAe,EAAE,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