@zonastery/bursar 0.0.2 → 1.0.1

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 (505) hide show
  1. package/README.md +118 -333
  2. package/dist/billing/auto-recharge-port.d.ts +27 -0
  3. package/dist/billing/auto-recharge-port.d.ts.map +1 -0
  4. package/dist/billing/auto-recharge-port.js +2 -0
  5. package/dist/billing/auto-recharge-port.js.map +1 -0
  6. package/dist/billing/auto-recharge-service.d.ts +43 -0
  7. package/dist/billing/auto-recharge-service.d.ts.map +1 -0
  8. package/dist/billing/auto-recharge-service.js +218 -0
  9. package/dist/billing/auto-recharge-service.js.map +1 -0
  10. package/dist/billing/billing-service.d.ts +71 -0
  11. package/dist/billing/billing-service.d.ts.map +1 -0
  12. package/dist/billing/billing-service.js +172 -0
  13. package/dist/billing/billing-service.js.map +1 -0
  14. package/dist/billing/billing-store.d.ts +45 -13
  15. package/dist/billing/billing-store.d.ts.map +1 -1
  16. package/dist/billing/billing-store.js.map +1 -1
  17. package/dist/billing/contracts.d.ts +149 -0
  18. package/dist/billing/contracts.d.ts.map +1 -0
  19. package/dist/billing/contracts.js +2 -0
  20. package/dist/billing/contracts.js.map +1 -0
  21. package/dist/billing/event-handlers.d.ts +57 -0
  22. package/dist/billing/event-handlers.d.ts.map +1 -0
  23. package/dist/billing/event-handlers.js +684 -0
  24. package/dist/billing/event-handlers.js.map +1 -0
  25. package/dist/billing/event-processor.d.ts +20 -0
  26. package/dist/billing/event-processor.d.ts.map +1 -0
  27. package/dist/billing/event-processor.js +131 -0
  28. package/dist/billing/event-processor.js.map +1 -0
  29. package/dist/billing/financial-event-handlers.d.ts +26 -0
  30. package/dist/billing/financial-event-handlers.d.ts.map +1 -0
  31. package/dist/billing/financial-event-handlers.js +241 -0
  32. package/dist/billing/financial-event-handlers.js.map +1 -0
  33. package/dist/billing/index.d.ts +9 -5
  34. package/dist/billing/index.d.ts.map +1 -1
  35. package/dist/billing/index.js +4 -4
  36. package/dist/billing/index.js.map +1 -1
  37. package/dist/billing/management.d.ts +59 -0
  38. package/dist/billing/management.d.ts.map +1 -0
  39. package/dist/billing/management.js +113 -0
  40. package/dist/billing/management.js.map +1 -0
  41. package/dist/billing/policy-window.d.ts +24 -0
  42. package/dist/billing/policy-window.d.ts.map +1 -0
  43. package/dist/billing/policy-window.js +88 -0
  44. package/dist/billing/policy-window.js.map +1 -0
  45. package/dist/billing/postgres/repositories/auto-recharge.d.ts +32 -0
  46. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -0
  47. package/dist/billing/postgres/repositories/auto-recharge.js +180 -0
  48. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -0
  49. package/dist/billing/postgres/repositories/customer.d.ts +12 -0
  50. package/dist/billing/postgres/repositories/customer.d.ts.map +1 -0
  51. package/dist/billing/postgres/repositories/customer.js +33 -0
  52. package/dist/billing/postgres/repositories/customer.js.map +1 -0
  53. package/dist/billing/postgres/repositories/dispute.d.ts +7 -0
  54. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -0
  55. package/dist/billing/postgres/repositories/dispute.js +18 -0
  56. package/dist/billing/postgres/repositories/dispute.js.map +1 -0
  57. package/dist/billing/postgres/repositories/event.d.ts +21 -0
  58. package/dist/billing/postgres/repositories/event.d.ts.map +1 -0
  59. package/dist/billing/postgres/repositories/event.js +45 -0
  60. package/dist/billing/postgres/repositories/event.js.map +1 -0
  61. package/dist/billing/postgres/repositories/invoice.d.ts +9 -0
  62. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -0
  63. package/dist/billing/postgres/repositories/invoice.js +36 -0
  64. package/dist/billing/postgres/repositories/invoice.js.map +1 -0
  65. package/dist/billing/postgres/repositories/offer.d.ts +26 -0
  66. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -0
  67. package/dist/billing/postgres/repositories/offer.js +73 -0
  68. package/dist/billing/postgres/repositories/offer.js.map +1 -0
  69. package/dist/billing/postgres/repositories/payment.d.ts +32 -0
  70. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -0
  71. package/dist/billing/postgres/repositories/payment.js +78 -0
  72. package/dist/billing/postgres/repositories/payment.js.map +1 -0
  73. package/dist/billing/postgres/repositories/preferences.d.ts +15 -0
  74. package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -0
  75. package/dist/billing/postgres/repositories/preferences.js +23 -0
  76. package/dist/billing/postgres/repositories/preferences.js.map +1 -0
  77. package/dist/billing/postgres/repositories/refund.d.ts +7 -0
  78. package/dist/billing/postgres/repositories/refund.d.ts.map +1 -0
  79. package/dist/billing/postgres/repositories/refund.js +32 -0
  80. package/dist/billing/postgres/repositories/refund.js.map +1 -0
  81. package/dist/billing/postgres/repositories/subscription.d.ts +46 -0
  82. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -0
  83. package/dist/billing/postgres/repositories/subscription.js +187 -0
  84. package/dist/billing/postgres/repositories/subscription.js.map +1 -0
  85. package/dist/billing/postgres/repositories/topup.d.ts +27 -0
  86. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -0
  87. package/dist/billing/postgres/repositories/topup.js +51 -0
  88. package/dist/billing/postgres/repositories/topup.js.map +1 -0
  89. package/dist/billing/postgres/store.d.ts +89 -0
  90. package/dist/billing/postgres/store.d.ts.map +1 -0
  91. package/dist/billing/postgres/store.js +542 -0
  92. package/dist/billing/postgres/store.js.map +1 -0
  93. package/dist/billing/service-types.d.ts +37 -0
  94. package/dist/billing/service-types.d.ts.map +1 -0
  95. package/dist/billing/service-types.js +2 -0
  96. package/dist/billing/service-types.js.map +1 -0
  97. package/dist/billing/types/auto-recharge.d.ts +56 -0
  98. package/dist/billing/types/auto-recharge.d.ts.map +1 -0
  99. package/dist/billing/types/auto-recharge.js +2 -0
  100. package/dist/billing/types/auto-recharge.js.map +1 -0
  101. package/dist/billing/types/catalog.d.ts +47 -0
  102. package/dist/billing/types/catalog.d.ts.map +1 -0
  103. package/dist/billing/types/catalog.js +2 -0
  104. package/dist/billing/types/catalog.js.map +1 -0
  105. package/dist/billing/types/common.d.ts +16 -0
  106. package/dist/billing/types/common.d.ts.map +1 -0
  107. package/dist/billing/types/common.js +2 -0
  108. package/dist/billing/types/common.js.map +1 -0
  109. package/dist/billing/types/documents.d.ts +39 -0
  110. package/dist/billing/types/documents.d.ts.map +1 -0
  111. package/dist/billing/types/documents.js +2 -0
  112. package/dist/billing/types/documents.js.map +1 -0
  113. package/dist/billing/types/events.d.ts +75 -0
  114. package/dist/billing/types/events.d.ts.map +1 -0
  115. package/dist/billing/types/events.js +38 -0
  116. package/dist/billing/types/events.js.map +1 -0
  117. package/dist/billing/types/index.d.ts +8 -0
  118. package/dist/billing/types/index.d.ts.map +1 -0
  119. package/dist/billing/types/index.js +8 -0
  120. package/dist/billing/types/index.js.map +1 -0
  121. package/dist/billing/types/preferences.d.ts +13 -0
  122. package/dist/billing/types/preferences.d.ts.map +1 -0
  123. package/dist/billing/types/preferences.js +2 -0
  124. package/dist/billing/types/preferences.js.map +1 -0
  125. package/dist/billing/types/subscriptions.d.ts +97 -0
  126. package/dist/billing/types/subscriptions.d.ts.map +1 -0
  127. package/dist/billing/types/subscriptions.js +12 -0
  128. package/dist/billing/types/subscriptions.js.map +1 -0
  129. package/dist/breakdown.d.ts +3 -1
  130. package/dist/breakdown.d.ts.map +1 -1
  131. package/dist/breakdown.js +4 -1
  132. package/dist/breakdown.js.map +1 -1
  133. package/dist/browser.d.ts +8 -0
  134. package/dist/browser.d.ts.map +1 -0
  135. package/dist/browser.js +7 -0
  136. package/dist/browser.js.map +1 -0
  137. package/dist/bursar.d.ts +84 -0
  138. package/dist/bursar.d.ts.map +1 -0
  139. package/dist/bursar.js +137 -0
  140. package/dist/bursar.js.map +1 -0
  141. package/dist/catalog.d.ts +62 -0
  142. package/dist/catalog.d.ts.map +1 -0
  143. package/dist/catalog.js +96 -0
  144. package/dist/catalog.js.map +1 -0
  145. package/dist/commerce/errors.d.ts +68 -0
  146. package/dist/commerce/errors.d.ts.map +1 -0
  147. package/dist/commerce/errors.js +105 -0
  148. package/dist/commerce/errors.js.map +1 -0
  149. package/dist/commerce/index.d.ts +6 -0
  150. package/dist/commerce/index.d.ts.map +1 -0
  151. package/dist/commerce/index.js +6 -0
  152. package/dist/commerce/index.js.map +1 -0
  153. package/dist/commerce/plan-change.d.ts +10 -0
  154. package/dist/commerce/plan-change.d.ts.map +1 -0
  155. package/dist/commerce/plan-change.js +42 -0
  156. package/dist/commerce/plan-change.js.map +1 -0
  157. package/dist/commerce/provider-registry.d.ts +18 -0
  158. package/dist/commerce/provider-registry.d.ts.map +1 -0
  159. package/dist/commerce/provider-registry.js +70 -0
  160. package/dist/commerce/provider-registry.js.map +1 -0
  161. package/dist/commerce/service.d.ts +73 -0
  162. package/dist/commerce/service.d.ts.map +1 -0
  163. package/dist/commerce/service.js +1016 -0
  164. package/dist/commerce/service.js.map +1 -0
  165. package/dist/commerce/types.d.ts +225 -0
  166. package/dist/commerce/types.d.ts.map +1 -0
  167. package/dist/commerce/types.js.map +1 -0
  168. package/dist/config/parse-access.d.ts +6 -0
  169. package/dist/config/parse-access.d.ts.map +1 -0
  170. package/dist/config/parse-access.js +72 -0
  171. package/dist/config/parse-access.js.map +1 -0
  172. package/dist/config/parse-commerce.d.ts +3 -0
  173. package/dist/config/parse-commerce.d.ts.map +1 -0
  174. package/dist/config/parse-commerce.js +236 -0
  175. package/dist/config/parse-commerce.js.map +1 -0
  176. package/dist/config/parse-credits.d.ts +3 -0
  177. package/dist/config/parse-credits.d.ts.map +1 -0
  178. package/dist/config/parse-credits.js +99 -0
  179. package/dist/config/parse-credits.js.map +1 -0
  180. package/dist/config/parse-plans.d.ts +5 -0
  181. package/dist/config/parse-plans.d.ts.map +1 -0
  182. package/dist/config/parse-plans.js +142 -0
  183. package/dist/config/parse-plans.js.map +1 -0
  184. package/dist/config/parse-pricing.d.ts +4 -0
  185. package/dist/config/parse-pricing.d.ts.map +1 -0
  186. package/dist/config/parse-pricing.js +252 -0
  187. package/dist/config/parse-pricing.js.map +1 -0
  188. package/dist/config/parse-utils.d.ts +18 -0
  189. package/dist/config/parse-utils.d.ts.map +1 -0
  190. package/dist/config/parse-utils.js +118 -0
  191. package/dist/config/parse-utils.js.map +1 -0
  192. package/dist/config/types.d.ts +340 -0
  193. package/dist/config/types.d.ts.map +1 -0
  194. package/dist/config/types.js +2 -0
  195. package/dist/config/types.js.map +1 -0
  196. package/dist/config.d.ts +12 -23
  197. package/dist/config.d.ts.map +1 -1
  198. package/dist/config.js +141 -377
  199. package/dist/config.js.map +1 -1
  200. package/dist/{stores → credits}/events.d.ts +6 -6
  201. package/dist/credits/events.d.ts.map +1 -0
  202. package/dist/{stores → credits}/events.js +5 -5
  203. package/dist/credits/events.js.map +1 -0
  204. package/dist/credits/lease-workflow.d.ts +90 -0
  205. package/dist/credits/lease-workflow.d.ts.map +1 -0
  206. package/dist/credits/lease-workflow.js +378 -0
  207. package/dist/credits/lease-workflow.js.map +1 -0
  208. package/dist/credits/low-balance-monitor.d.ts +26 -0
  209. package/dist/credits/low-balance-monitor.d.ts.map +1 -0
  210. package/dist/credits/low-balance-monitor.js +110 -0
  211. package/dist/credits/low-balance-monitor.js.map +1 -0
  212. package/dist/credits/postgres/repositories/analytics.d.ts +81 -0
  213. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -0
  214. package/dist/credits/postgres/repositories/analytics.js +153 -0
  215. package/dist/credits/postgres/repositories/analytics.js.map +1 -0
  216. package/dist/credits/postgres/repositories/balance.d.ts +66 -0
  217. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -0
  218. package/dist/credits/postgres/repositories/balance.js +139 -0
  219. package/dist/credits/postgres/repositories/balance.js.map +1 -0
  220. package/dist/credits/postgres/repositories/bucket.d.ts +25 -0
  221. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -0
  222. package/dist/credits/postgres/repositories/bucket.js +52 -0
  223. package/dist/credits/postgres/repositories/bucket.js.map +1 -0
  224. package/dist/credits/postgres/repositories/deduction.d.ts +64 -0
  225. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -0
  226. package/dist/credits/postgres/repositories/deduction.js +154 -0
  227. package/dist/credits/postgres/repositories/deduction.js.map +1 -0
  228. package/dist/credits/postgres/repositories/lease.d.ts +69 -0
  229. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -0
  230. package/dist/credits/postgres/repositories/lease.js +148 -0
  231. package/dist/credits/postgres/repositories/lease.js.map +1 -0
  232. package/dist/credits/postgres/repositories/plan.d.ts +110 -0
  233. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -0
  234. package/dist/credits/postgres/repositories/plan.js +194 -0
  235. package/dist/credits/postgres/repositories/plan.js.map +1 -0
  236. package/dist/credits/postgres/repositories/pricing.d.ts +28 -0
  237. package/dist/credits/postgres/repositories/pricing.d.ts.map +1 -0
  238. package/dist/credits/postgres/repositories/pricing.js +76 -0
  239. package/dist/credits/postgres/repositories/pricing.js.map +1 -0
  240. package/dist/credits/postgres/repositories/team.d.ts +63 -0
  241. package/dist/credits/postgres/repositories/team.d.ts.map +1 -0
  242. package/dist/credits/postgres/repositories/team.js +120 -0
  243. package/dist/credits/postgres/repositories/team.js.map +1 -0
  244. package/dist/credits/postgres/store.d.ts +89 -0
  245. package/dist/credits/postgres/store.d.ts.map +1 -0
  246. package/dist/credits/postgres/store.js +838 -0
  247. package/dist/credits/postgres/store.js.map +1 -0
  248. package/dist/credits/postgres/value-mappers.d.ts +17 -0
  249. package/dist/credits/postgres/value-mappers.d.ts.map +1 -0
  250. package/dist/credits/postgres/value-mappers.js +102 -0
  251. package/dist/credits/postgres/value-mappers.js.map +1 -0
  252. package/dist/credits/pricing-runtime.d.ts +35 -0
  253. package/dist/credits/pricing-runtime.d.ts.map +1 -0
  254. package/dist/credits/pricing-runtime.js +141 -0
  255. package/dist/credits/pricing-runtime.js.map +1 -0
  256. package/dist/credits/queries.d.ts +33 -0
  257. package/dist/credits/queries.d.ts.map +1 -0
  258. package/dist/credits/queries.js +71 -0
  259. package/dist/credits/queries.js.map +1 -0
  260. package/dist/credits/service-errors.d.ts +4 -0
  261. package/dist/credits/service-errors.d.ts.map +1 -0
  262. package/dist/credits/service-errors.js +57 -0
  263. package/dist/credits/service-errors.js.map +1 -0
  264. package/dist/credits/service-types.d.ts +122 -0
  265. package/dist/credits/service-types.d.ts.map +1 -0
  266. package/dist/credits/service-types.js +2 -0
  267. package/dist/credits/service-types.js.map +1 -0
  268. package/dist/credits/service.d.ts +220 -0
  269. package/dist/credits/service.d.ts.map +1 -0
  270. package/dist/credits/service.js +640 -0
  271. package/dist/credits/service.js.map +1 -0
  272. package/dist/credits/store.d.ts +172 -0
  273. package/dist/credits/store.d.ts.map +1 -0
  274. package/dist/{stores/credit-store.js → credits/store.js} +27 -43
  275. package/dist/credits/store.js.map +1 -0
  276. package/dist/credits/types/account.d.ts +82 -0
  277. package/dist/credits/types/account.d.ts.map +1 -0
  278. package/dist/credits/types/account.js +2 -0
  279. package/dist/credits/types/account.js.map +1 -0
  280. package/dist/credits/types/admission.d.ts +39 -0
  281. package/dist/credits/types/admission.d.ts.map +1 -0
  282. package/dist/credits/types/admission.js +2 -0
  283. package/dist/credits/types/admission.js.map +1 -0
  284. package/dist/credits/types/analytics.d.ts +52 -0
  285. package/dist/credits/types/analytics.d.ts.map +1 -0
  286. package/dist/credits/types/analytics.js +2 -0
  287. package/dist/credits/types/analytics.js.map +1 -0
  288. package/dist/credits/types/catalog.d.ts +71 -0
  289. package/dist/credits/types/catalog.d.ts.map +1 -0
  290. package/dist/credits/types/catalog.js +2 -0
  291. package/dist/credits/types/catalog.js.map +1 -0
  292. package/dist/credits/types/grants.d.ts +24 -0
  293. package/dist/credits/types/grants.d.ts.map +1 -0
  294. package/dist/credits/types/grants.js +2 -0
  295. package/dist/credits/types/grants.js.map +1 -0
  296. package/dist/credits/types/index.d.ts +9 -0
  297. package/dist/credits/types/index.d.ts.map +1 -0
  298. package/dist/credits/types/index.js +2 -0
  299. package/dist/credits/types/index.js.map +1 -0
  300. package/dist/credits/types/ledger.d.ts +87 -0
  301. package/dist/credits/types/ledger.d.ts.map +1 -0
  302. package/dist/credits/types/ledger.js +2 -0
  303. package/dist/credits/types/ledger.js.map +1 -0
  304. package/dist/credits/types/quotas.d.ts +40 -0
  305. package/dist/credits/types/quotas.d.ts.map +1 -0
  306. package/dist/credits/types/quotas.js +2 -0
  307. package/dist/credits/types/quotas.js.map +1 -0
  308. package/dist/credits/types/teams.d.ts +44 -0
  309. package/dist/credits/types/teams.d.ts.map +1 -0
  310. package/dist/credits/types/teams.js +2 -0
  311. package/dist/credits/types/teams.js.map +1 -0
  312. package/dist/engine.d.ts +18 -39
  313. package/dist/engine.d.ts.map +1 -1
  314. package/dist/engine.js +169 -145
  315. package/dist/engine.js.map +1 -1
  316. package/dist/errors.d.ts +133 -25
  317. package/dist/errors.d.ts.map +1 -1
  318. package/dist/errors.js +173 -24
  319. package/dist/errors.js.map +1 -1
  320. package/dist/expr/ast.d.ts +46 -0
  321. package/dist/expr/ast.d.ts.map +1 -0
  322. package/dist/expr/ast.js +18 -0
  323. package/dist/expr/ast.js.map +1 -0
  324. package/dist/expr/evaluator.d.ts +4 -0
  325. package/dist/expr/evaluator.d.ts.map +1 -0
  326. package/dist/expr/evaluator.js +144 -0
  327. package/dist/expr/evaluator.js.map +1 -0
  328. package/dist/expr/language.d.ts +5 -0
  329. package/dist/expr/language.d.ts.map +1 -0
  330. package/dist/expr/language.js +73 -0
  331. package/dist/expr/language.js.map +1 -0
  332. package/dist/expr/parser.d.ts +24 -0
  333. package/dist/expr/parser.d.ts.map +1 -0
  334. package/dist/expr/parser.js +175 -0
  335. package/dist/expr/parser.js.map +1 -0
  336. package/dist/expr/tokenizer.d.ts +7 -0
  337. package/dist/expr/tokenizer.d.ts.map +1 -0
  338. package/dist/expr/tokenizer.js +85 -0
  339. package/dist/expr/tokenizer.js.map +1 -0
  340. package/dist/expr.d.ts +7 -58
  341. package/dist/expr.d.ts.map +1 -1
  342. package/dist/expr.js +41 -640
  343. package/dist/expr.js.map +1 -1
  344. package/dist/generated/pricing-config.schema.json +2792 -0
  345. package/dist/generated/pricing-config.types.d.ts +685 -0
  346. package/dist/generated/pricing-config.types.d.ts.map +1 -0
  347. package/dist/generated/pricing-config.types.js +8 -0
  348. package/dist/generated/pricing-config.types.js.map +1 -0
  349. package/dist/index.d.ts +23 -17
  350. package/dist/index.d.ts.map +1 -1
  351. package/dist/index.js +12 -10
  352. package/dist/index.js.map +1 -1
  353. package/dist/load-pricing-file.d.ts.map +1 -1
  354. package/dist/load-pricing-file.js +8 -4
  355. package/dist/load-pricing-file.js.map +1 -1
  356. package/dist/metrics.d.ts +6 -16
  357. package/dist/metrics.d.ts.map +1 -1
  358. package/dist/metrics.js.map +1 -1
  359. package/dist/node.d.ts +9 -2
  360. package/dist/node.d.ts.map +1 -1
  361. package/dist/node.js +6 -2
  362. package/dist/node.js.map +1 -1
  363. package/dist/providers/_shared.d.ts +9 -0
  364. package/dist/providers/_shared.d.ts.map +1 -0
  365. package/dist/providers/_shared.js +52 -0
  366. package/dist/providers/_shared.js.map +1 -0
  367. package/dist/providers/dodo/client-contract.d.ts +106 -0
  368. package/dist/providers/dodo/client-contract.d.ts.map +1 -0
  369. package/dist/providers/dodo/client-contract.js +2 -0
  370. package/dist/providers/dodo/client-contract.js.map +1 -0
  371. package/dist/providers/dodo/event-mapper.d.ts +5 -3
  372. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  373. package/dist/providers/dodo/event-mapper.js +213 -38
  374. package/dist/providers/dodo/event-mapper.js.map +1 -1
  375. package/dist/providers/dodo/index.d.ts +1 -0
  376. package/dist/providers/dodo/index.d.ts.map +1 -1
  377. package/dist/providers/dodo/index.js.map +1 -1
  378. package/dist/providers/dodo/provider.d.ts +24 -14
  379. package/dist/providers/dodo/provider.d.ts.map +1 -1
  380. package/dist/providers/dodo/provider.js +249 -31
  381. package/dist/providers/dodo/provider.js.map +1 -1
  382. package/dist/providers/index.d.ts +3 -1
  383. package/dist/providers/index.d.ts.map +1 -1
  384. package/dist/providers/index.js +1 -0
  385. package/dist/providers/index.js.map +1 -1
  386. package/dist/providers/mock/index.js.map +1 -1
  387. package/dist/providers/mock/provider.d.ts +14 -10
  388. package/dist/providers/mock/provider.d.ts.map +1 -1
  389. package/dist/providers/mock/provider.js +78 -10
  390. package/dist/providers/mock/provider.js.map +1 -1
  391. package/dist/providers/stripe/event-mapper.d.ts +3 -3
  392. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  393. package/dist/providers/stripe/event-mapper.js +139 -30
  394. package/dist/providers/stripe/event-mapper.js.map +1 -1
  395. package/dist/providers/stripe/index.js.map +1 -1
  396. package/dist/providers/stripe/provider.d.ts +21 -12
  397. package/dist/providers/stripe/provider.d.ts.map +1 -1
  398. package/dist/providers/stripe/provider.js +175 -17
  399. package/dist/providers/stripe/provider.js.map +1 -1
  400. package/dist/providers/types.d.ts +128 -32
  401. package/dist/providers/types.d.ts.map +1 -1
  402. package/dist/providers/types.js +17 -1
  403. package/dist/providers/types.js.map +1 -1
  404. package/dist/retry.d.ts +35 -0
  405. package/dist/retry.d.ts.map +1 -0
  406. package/dist/retry.js +70 -0
  407. package/dist/retry.js.map +1 -0
  408. package/dist/shared/diagnostics.d.ts +7 -0
  409. package/dist/shared/diagnostics.d.ts.map +1 -0
  410. package/dist/shared/diagnostics.js +18 -0
  411. package/dist/shared/diagnostics.js.map +1 -0
  412. package/dist/shared/logger.d.ts +10 -0
  413. package/dist/shared/logger.d.ts.map +1 -0
  414. package/dist/shared/logger.js +15 -0
  415. package/dist/shared/logger.js.map +1 -0
  416. package/dist/shared/postgres-client.d.ts +84 -0
  417. package/dist/shared/postgres-client.d.ts.map +1 -0
  418. package/dist/shared/postgres-client.js +337 -0
  419. package/dist/shared/postgres-client.js.map +1 -0
  420. package/dist/shared/postgres-errors.d.ts +11 -0
  421. package/dist/shared/postgres-errors.d.ts.map +1 -0
  422. package/dist/shared/postgres-errors.js +105 -0
  423. package/dist/shared/postgres-errors.js.map +1 -0
  424. package/dist/shared/postgres-types.d.ts +7 -0
  425. package/dist/shared/postgres-types.d.ts.map +1 -0
  426. package/dist/shared/postgres-types.js +2 -0
  427. package/dist/shared/postgres-types.js.map +1 -0
  428. package/dist/shared/postgres-validation.d.ts +8 -0
  429. package/dist/shared/postgres-validation.d.ts.map +1 -0
  430. package/dist/shared/postgres-validation.js +40 -0
  431. package/dist/shared/postgres-validation.js.map +1 -0
  432. package/dist/storage/adapters/clickhouse.d.ts +61 -0
  433. package/dist/storage/adapters/clickhouse.d.ts.map +1 -0
  434. package/dist/storage/adapters/clickhouse.js +347 -0
  435. package/dist/storage/adapters/clickhouse.js.map +1 -0
  436. package/dist/storage/adapters/s3.d.ts +35 -0
  437. package/dist/storage/adapters/s3.d.ts.map +1 -0
  438. package/dist/storage/adapters/s3.js +100 -0
  439. package/dist/storage/adapters/s3.js.map +1 -0
  440. package/dist/storage/outbox-worker.d.ts +41 -0
  441. package/dist/storage/outbox-worker.d.ts.map +1 -0
  442. package/dist/storage/outbox-worker.js +146 -0
  443. package/dist/storage/outbox-worker.js.map +1 -0
  444. package/dist/storage/ports.d.ts +78 -0
  445. package/dist/storage/ports.d.ts.map +1 -0
  446. package/dist/storage/ports.js +2 -0
  447. package/dist/storage/ports.js.map +1 -0
  448. package/dist/storage/postgres-repository.d.ts +14 -0
  449. package/dist/storage/postgres-repository.d.ts.map +1 -0
  450. package/dist/storage/postgres-repository.js +140 -0
  451. package/dist/storage/postgres-repository.js.map +1 -0
  452. package/dist/storage/runtime.d.ts +77 -0
  453. package/dist/storage/runtime.d.ts.map +1 -0
  454. package/dist/storage/runtime.js +369 -0
  455. package/dist/storage/runtime.js.map +1 -0
  456. package/package.json +43 -21
  457. package/dist/allowance.d.ts +0 -48
  458. package/dist/allowance.d.ts.map +0 -1
  459. package/dist/allowance.js +0 -140
  460. package/dist/allowance.js.map +0 -1
  461. package/dist/billing/billing-manager.d.ts +0 -66
  462. package/dist/billing/billing-manager.d.ts.map +0 -1
  463. package/dist/billing/billing-manager.js +0 -560
  464. package/dist/billing/billing-manager.js.map +0 -1
  465. package/dist/billing/billing-types.d.ts +0 -203
  466. package/dist/billing/billing-types.d.ts.map +0 -1
  467. package/dist/billing/billing-types.js +0 -6
  468. package/dist/billing/billing-types.js.map +0 -1
  469. package/dist/billing/memory-billing-store.d.ts +0 -37
  470. package/dist/billing/memory-billing-store.d.ts.map +0 -1
  471. package/dist/billing/memory-billing-store.js +0 -197
  472. package/dist/billing/memory-billing-store.js.map +0 -1
  473. package/dist/billing/postgres-billing-store.d.ts +0 -35
  474. package/dist/billing/postgres-billing-store.d.ts.map +0 -1
  475. package/dist/billing/postgres-billing-store.js +0 -274
  476. package/dist/billing/postgres-billing-store.js.map +0 -1
  477. package/dist/billing/supabase-billing-store.d.ts +0 -29
  478. package/dist/billing/supabase-billing-store.d.ts.map +0 -1
  479. package/dist/billing/supabase-billing-store.js +0 -250
  480. package/dist/billing/supabase-billing-store.js.map +0 -1
  481. package/dist/manager.d.ts +0 -444
  482. package/dist/manager.d.ts.map +0 -1
  483. package/dist/manager.js +0 -1153
  484. package/dist/manager.js.map +0 -1
  485. package/dist/stores/credit-store.d.ts +0 -198
  486. package/dist/stores/credit-store.d.ts.map +0 -1
  487. package/dist/stores/credit-store.js.map +0 -1
  488. package/dist/stores/events.d.ts.map +0 -1
  489. package/dist/stores/events.js.map +0 -1
  490. package/dist/stores/memory-store.d.ts +0 -187
  491. package/dist/stores/memory-store.d.ts.map +0 -1
  492. package/dist/stores/memory-store.js +0 -1890
  493. package/dist/stores/memory-store.js.map +0 -1
  494. package/dist/stores/postgres-store.d.ts +0 -100
  495. package/dist/stores/postgres-store.d.ts.map +0 -1
  496. package/dist/stores/postgres-store.js +0 -891
  497. package/dist/stores/postgres-store.js.map +0 -1
  498. package/dist/stores/supabase-store.d.ts +0 -87
  499. package/dist/stores/supabase-store.d.ts.map +0 -1
  500. package/dist/stores/supabase-store.js +0 -948
  501. package/dist/stores/supabase-store.js.map +0 -1
  502. package/dist/types.d.ts +0 -463
  503. package/dist/types.d.ts.map +0 -1
  504. package/dist/types.js.map +0 -1
  505. /package/dist/{types.js → commerce/types.js} +0 -0
@@ -0,0 +1,218 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { loadConfigFromDict } from "../config.js";
3
+ import { resolveAutoRechargeWindow } from "./policy-window.js";
4
+ export class AutoRechargeService {
5
+ billing;
6
+ constructor(billing) {
7
+ this.billing = billing;
8
+ }
9
+ async policy(provider) {
10
+ const raw = await this.billing.getActiveBursarConfig();
11
+ if (!raw)
12
+ return null;
13
+ const config = loadConfigFromDict(raw);
14
+ const auto = config.commerce.autoRecharge;
15
+ if (!auto)
16
+ return null;
17
+ const topupKey = auto.eligibleTopups[0];
18
+ const topup = config.commerce.offers[topupKey];
19
+ if (!topup || topup.type !== "topup")
20
+ return null;
21
+ const reference = topup.providers[provider.provider];
22
+ if (!reference)
23
+ return null;
24
+ const productId = reference.type === "stripe_price"
25
+ ? reference.priceId
26
+ : reference.type === "dodo_product"
27
+ ? reference.productId
28
+ : reference.externalId;
29
+ const resolvedTopup = reference.type === "stripe_price"
30
+ ? await this.billing.resolveTopup(provider.provider, null, productId)
31
+ : reference.type === "dodo_product"
32
+ ? await this.billing.resolveTopup(provider.provider, productId, null)
33
+ : await this.billing.resolveTopupByLookup(provider.provider, productId);
34
+ if (!resolvedTopup)
35
+ return null;
36
+ const period = resolveAutoRechargeWindow(auto.limits.window);
37
+ return {
38
+ enabled: true,
39
+ threshold: Number(auto.balanceBelow.default),
40
+ topupKey,
41
+ topupId: resolvedTopup.topupId,
42
+ quantity: auto.quantity.default,
43
+ maxChargesPerWindow: auto.limits.maxPurchases,
44
+ windowUnit: period.unit,
45
+ windowCount: period.count,
46
+ windowAnchor: period.anchor,
47
+ windowTimezone: period.timezone,
48
+ windowStart: period.start,
49
+ windowEnd: period.end,
50
+ productId,
51
+ };
52
+ }
53
+ async paymentMethod(userId, provider) {
54
+ const customer = await this.billing.getCustomerByUserId(userId, provider.provider);
55
+ if (!customer)
56
+ return null;
57
+ if (!provider.listPaymentMethods) {
58
+ throw new Error(`provider_capability_not_supported:listPaymentMethods:${provider.provider}`);
59
+ }
60
+ const methods = await provider.listPaymentMethods(customer.providerCustomerId);
61
+ const method = (await provider.getDefaultPaymentMethod?.(customer.providerCustomerId)) ??
62
+ methods.find((candidate) => candidate.isDefault) ??
63
+ (methods.length === 1 ? methods[0] : null);
64
+ return method ? { customerId: customer.providerCustomerId, method } : null;
65
+ }
66
+ async quote(input) {
67
+ const policy = await this.policy(input.provider);
68
+ if (!policy || !input.provider.previewSavedPaymentCharge)
69
+ return null;
70
+ const payment = await this.paymentMethod(input.userId, input.provider);
71
+ if (!payment)
72
+ return null;
73
+ return input.provider.previewSavedPaymentCharge({
74
+ customerId: payment.customerId,
75
+ paymentMethodId: payment.method.id,
76
+ productId: policy.productId,
77
+ quantity: policy.quantity,
78
+ metadata: {},
79
+ idempotencyKey: "auto-recharge-preview",
80
+ });
81
+ }
82
+ async getStatus(input) {
83
+ const policy = await this.policy(input.provider);
84
+ if (!policy)
85
+ return null;
86
+ const profile = await this.billing.getAutoRechargeProfile(input.userId);
87
+ const payment = profile?.enabled
88
+ ? await this.paymentMethod(input.userId, input.provider)
89
+ : null;
90
+ const quote = await this.quote(input);
91
+ return {
92
+ enabled: Boolean(profile?.enabled),
93
+ state: profile?.enabled ? profile.state : "disabled",
94
+ thresholdCredits: policy.threshold,
95
+ topupKey: policy.topupKey,
96
+ quantity: policy.quantity,
97
+ maxRecharges: policy.maxChargesPerWindow,
98
+ windowStart: policy.windowStart,
99
+ windowEnd: policy.windowEnd,
100
+ rechargesInWindow: await this.billing.countAutoRechargeAttempts(input.userId, policy.windowStart),
101
+ paymentMethodId: payment?.method.id ?? null,
102
+ paymentMethodLast4: payment?.method.last4 ?? null,
103
+ paymentMethodBrand: payment?.method.brand ?? null,
104
+ suspendedReason: profile?.state === "paused" ? "auto_recharge_paused" : null,
105
+ pendingAttemptId: null,
106
+ quoteAmountMinor: quote?.amountMinor ?? null,
107
+ quoteCurrency: quote?.currency ?? null,
108
+ };
109
+ }
110
+ async enable(input) {
111
+ const policy = await this.policy(input.provider);
112
+ if (!policy)
113
+ throw new Error("auto_recharge_not_configured");
114
+ const payment = await this.paymentMethod(input.userId, input.provider);
115
+ if (!payment)
116
+ throw new Error("payment_method_required");
117
+ const profile = {
118
+ userId: input.userId,
119
+ enabled: true,
120
+ state: "active",
121
+ armed: true,
122
+ provider: input.provider.provider,
123
+ topupId: policy.topupId,
124
+ quantity: policy.quantity,
125
+ threshold: policy.threshold,
126
+ maxChargesPerWindow: policy.maxChargesPerWindow,
127
+ windowUnit: policy.windowUnit,
128
+ windowCount: policy.windowCount,
129
+ windowAnchor: policy.windowAnchor,
130
+ windowTimezone: policy.windowTimezone,
131
+ };
132
+ await this.billing.upsertAutoRechargeProfile(profile);
133
+ await this.processIfNeeded(input);
134
+ return this.getStatus(input);
135
+ }
136
+ async disable(userId) {
137
+ const profile = await this.billing.getAutoRechargeProfile(userId);
138
+ if (!profile)
139
+ return;
140
+ await this.billing.upsertAutoRechargeProfile({
141
+ ...profile,
142
+ enabled: false,
143
+ state: "disabled",
144
+ armed: true,
145
+ });
146
+ }
147
+ async retry(input) {
148
+ const profile = await this.billing.getAutoRechargeProfile(input.userId);
149
+ if (!profile?.enabled)
150
+ throw new Error("auto_recharge_disabled");
151
+ await this.billing.upsertAutoRechargeProfile({
152
+ ...profile,
153
+ state: "active",
154
+ armed: true,
155
+ }, { resetCooldown: true });
156
+ return this.processIfNeeded(input);
157
+ }
158
+ async processIfNeeded(input) {
159
+ const policy = await this.policy(input.provider);
160
+ if (!policy)
161
+ return { outcome: "not_configured" };
162
+ const profile = await this.billing.getAutoRechargeProfile(input.userId);
163
+ if (!profile?.enabled || profile.state !== "active")
164
+ return { outcome: "disabled" };
165
+ if (input.balance >= policy.threshold) {
166
+ return { outcome: "above_threshold" };
167
+ }
168
+ const payment = await this.paymentMethod(input.userId, input.provider);
169
+ if (!payment)
170
+ return { outcome: "failed" };
171
+ const attempt = await this.billing.claimAutoRechargeAttempt({
172
+ userId: input.userId,
173
+ idempotencyKey: `auto-recharge:${input.userId}:${randomUUID()}`,
174
+ });
175
+ if (!attempt)
176
+ return { outcome: "limit_reached" };
177
+ if (!input.provider.chargeSavedPaymentMethod) {
178
+ throw new Error(`provider_capability_not_supported:chargeSavedPaymentMethod:${input.provider.provider}`);
179
+ }
180
+ const charge = await input.provider.chargeSavedPaymentMethod({
181
+ customerId: payment.customerId,
182
+ paymentMethodId: payment.method.id,
183
+ productId: policy.productId,
184
+ quantity: policy.quantity,
185
+ returnUrl: input.returnUrl,
186
+ idempotencyKey: attempt.idempotencyKey,
187
+ metadata: {
188
+ auto_recharge_attempt_id: attempt.id,
189
+ purpose: "credit_topup",
190
+ userId: input.userId,
191
+ },
192
+ });
193
+ if (charge.status === "requires_customer_action") {
194
+ await this.billing.updateAutoRechargeAttempt({
195
+ id: attempt.id,
196
+ state: "action_required",
197
+ providerAttemptId: charge.providerPaymentId ?? null,
198
+ });
199
+ return { outcome: "action_required", charge };
200
+ }
201
+ if (charge.status === "succeeded" || charge.status === "processing") {
202
+ await this.billing.updateAutoRechargeAttempt({
203
+ id: attempt.id,
204
+ state: "processing",
205
+ providerAttemptId: charge.providerPaymentId ?? null,
206
+ });
207
+ return { outcome: "submitted", charge };
208
+ }
209
+ await this.billing.updateAutoRechargeAttempt({
210
+ id: attempt.id,
211
+ state: "failed",
212
+ providerAttemptId: charge.providerPaymentId ?? null,
213
+ failureCode: "payment_failed",
214
+ });
215
+ return { outcome: "failed", charge };
216
+ }
217
+ }
218
+ //# sourceMappingURL=auto-recharge-service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto-recharge-service.js","sourceRoot":"","sources":["../../src/billing/auto-recharge-service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,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CAAC,MAAM,KAAK,0BAA0B,EAAE,CAAC;YACjD,MAAM,IAAI,CAAC,OAAO,CAAC,yBAAyB,CAAC;gBAC3C,EAAE,EAAE,OAAO,CAAC,EAAE;gBACd,KAAK,EAAE,iBAAiB;gBACxB,iBAAiB,EAAE,MAAM,CAAC,iBAAiB,IAAI,IAAI;aACpD,CAAC,CAAC;YACH,OAAO,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,CAAC;QAChD,CAAC;QACD,IAAI,MAAM,CAAC,MAAM,KAAK,WAAW,IAAI,MAAM,CAAC,MAAM,KAAK,YAAY,EAAE,CAAC;YACpE,MAAM,IAAI,CAAC,OAAO,CAAC,yBAAyB,CAAC;gBAC3C,EAAE,EAAE,OAAO,CAAC,EAAE;gBACd,KAAK,EAAE,YAAY;gBACnB,iBAAiB,EAAE,MAAM,CAAC,iBAAiB,IAAI,IAAI;aACpD,CAAC,CAAC;YACH,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,CAAC;QAC1C,CAAC;QAED,MAAM,IAAI,CAAC,OAAO,CAAC,yBAAyB,CAAC;YAC3C,EAAE,EAAE,OAAO,CAAC,EAAE;YACd,KAAK,EAAE,QAAQ;YACf,iBAAiB,EAAE,MAAM,CAAC,iBAAiB,IAAI,IAAI;YACnD,WAAW,EAAE,gBAAgB;SAC9B,CAAC,CAAC;QACH,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC;IACvC,CAAC;CACF","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { loadConfigFromDict } from \"../config.js\";\nimport type { BillingAutoRechargeProfile, BillingAutoRechargeStatus } from \"./types/index.js\";\nimport type {\n PaymentMethodInfo,\n PaymentProvider,\n SavedPaymentChargeQuote,\n SavedPaymentChargeResult,\n} from \"../providers/types.js\";\nimport type { AutoRechargeBillingPort } from \"./auto-recharge-port.js\";\nimport { resolveAutoRechargeWindow } from \"./policy-window.js\";\n\nexport type AutoRechargeOutcome =\n | \"not_configured\"\n | \"disabled\"\n | \"above_threshold\"\n | \"already_processing\"\n | \"limit_reached\"\n | \"submitted\"\n | \"action_required\"\n | \"failed\";\n\nexport interface AutoRechargeProcessResult {\n outcome: AutoRechargeOutcome;\n charge?: SavedPaymentChargeResult | null;\n}\n\ninterface ResolvedAutoRechargePolicy {\n enabled: true;\n threshold: number;\n topupKey: string;\n topupId: string;\n quantity: number;\n maxChargesPerWindow: number;\n windowUnit: \"second\" | \"minute\" | \"hour\" | \"day\" | \"week\" | \"month\" | \"year\";\n windowCount: number;\n windowAnchor: \"calendar\" | \"plan_assignment\" | \"rolling\";\n windowTimezone: string;\n windowStart: string;\n windowEnd: string;\n productId: string;\n}\n\nexport class AutoRechargeService {\n constructor(private readonly billing: AutoRechargeBillingPort) {}\n\n private async policy(provider: PaymentProvider): Promise<ResolvedAutoRechargePolicy | null> {\n const raw = await this.billing.getActiveBursarConfig();\n if (!raw) return null;\n const config = loadConfigFromDict(raw);\n const auto = config.commerce.autoRecharge;\n if (!auto) return null;\n\n const topupKey = auto.eligibleTopups[0];\n const topup = config.commerce.offers[topupKey];\n if (!topup || topup.type !== \"topup\") return null;\n const reference = topup.providers[provider.provider];\n if (!reference) return null;\n\n const productId =\n reference.type === \"stripe_price\"\n ? reference.priceId\n : reference.type === \"dodo_product\"\n ? reference.productId\n : reference.externalId;\n const resolvedTopup =\n reference.type === \"stripe_price\"\n ? await this.billing.resolveTopup(provider.provider, null, productId)\n : reference.type === \"dodo_product\"\n ? await this.billing.resolveTopup(provider.provider, productId, null)\n : await this.billing.resolveTopupByLookup(provider.provider, productId);\n if (!resolvedTopup) return null;\n\n const period = resolveAutoRechargeWindow(auto.limits.window);\n return {\n enabled: true,\n threshold: Number(auto.balanceBelow.default),\n topupKey,\n topupId: resolvedTopup.topupId,\n quantity: auto.quantity.default,\n maxChargesPerWindow: auto.limits.maxPurchases,\n windowUnit: period.unit,\n windowCount: period.count,\n windowAnchor: period.anchor,\n windowTimezone: period.timezone,\n windowStart: period.start,\n windowEnd: period.end,\n productId,\n };\n }\n\n private async paymentMethod(\n userId: string,\n provider: PaymentProvider,\n ): Promise<{ customerId: string; method: PaymentMethodInfo } | null> {\n const customer = await this.billing.getCustomerByUserId(userId, provider.provider);\n if (!customer) return null;\n if (!provider.listPaymentMethods) {\n throw new Error(`provider_capability_not_supported:listPaymentMethods:${provider.provider}`);\n }\n const methods = await provider.listPaymentMethods(customer.providerCustomerId);\n const method =\n (await provider.getDefaultPaymentMethod?.(customer.providerCustomerId)) ??\n methods.find((candidate) => candidate.isDefault) ??\n (methods.length === 1 ? methods[0] : null);\n return method ? { customerId: customer.providerCustomerId, method } : null;\n }\n\n async quote(input: {\n userId: string;\n provider: PaymentProvider;\n }): Promise<SavedPaymentChargeQuote | null> {\n const policy = await this.policy(input.provider);\n if (!policy || !input.provider.previewSavedPaymentCharge) return null;\n const payment = await this.paymentMethod(input.userId, input.provider);\n if (!payment) return null;\n return input.provider.previewSavedPaymentCharge({\n customerId: payment.customerId,\n paymentMethodId: payment.method.id,\n productId: policy.productId,\n quantity: policy.quantity,\n metadata: {},\n idempotencyKey: \"auto-recharge-preview\",\n });\n }\n\n async getStatus(input: {\n userId: string;\n provider: PaymentProvider;\n }): Promise<BillingAutoRechargeStatus | null> {\n const policy = await this.policy(input.provider);\n if (!policy) return null;\n const profile = await this.billing.getAutoRechargeProfile(input.userId);\n const payment = profile?.enabled\n ? await this.paymentMethod(input.userId, input.provider)\n : null;\n const quote = await this.quote(input);\n return {\n enabled: Boolean(profile?.enabled),\n state: profile?.enabled ? profile.state : \"disabled\",\n thresholdCredits: policy.threshold,\n topupKey: policy.topupKey,\n quantity: policy.quantity,\n maxRecharges: policy.maxChargesPerWindow,\n windowStart: policy.windowStart,\n windowEnd: policy.windowEnd,\n rechargesInWindow: await this.billing.countAutoRechargeAttempts(\n input.userId,\n policy.windowStart,\n ),\n paymentMethodId: payment?.method.id ?? null,\n paymentMethodLast4: payment?.method.last4 ?? null,\n paymentMethodBrand: payment?.method.brand ?? null,\n suspendedReason: profile?.state === \"paused\" ? \"auto_recharge_paused\" : null,\n pendingAttemptId: null,\n quoteAmountMinor: quote?.amountMinor ?? null,\n quoteCurrency: quote?.currency ?? null,\n };\n }\n\n async enable(input: {\n userId: string;\n provider: PaymentProvider;\n balance: number;\n returnUrl?: string;\n consentReference?: string;\n }): Promise<BillingAutoRechargeStatus | null> {\n const policy = await this.policy(input.provider);\n if (!policy) throw new Error(\"auto_recharge_not_configured\");\n const payment = await this.paymentMethod(input.userId, input.provider);\n if (!payment) throw new Error(\"payment_method_required\");\n\n const profile: BillingAutoRechargeProfile = {\n userId: input.userId,\n enabled: true,\n state: \"active\",\n armed: true,\n provider: input.provider.provider,\n topupId: policy.topupId,\n quantity: policy.quantity,\n threshold: policy.threshold,\n maxChargesPerWindow: policy.maxChargesPerWindow,\n windowUnit: policy.windowUnit,\n windowCount: policy.windowCount,\n windowAnchor: policy.windowAnchor,\n windowTimezone: policy.windowTimezone,\n };\n await this.billing.upsertAutoRechargeProfile(profile);\n await this.processIfNeeded(input);\n return this.getStatus(input);\n }\n\n async disable(userId: string): Promise<void> {\n const profile = await this.billing.getAutoRechargeProfile(userId);\n if (!profile) return;\n await this.billing.upsertAutoRechargeProfile({\n ...profile,\n enabled: false,\n state: \"disabled\",\n armed: true,\n });\n }\n\n async retry(input: {\n userId: string;\n provider: PaymentProvider;\n balance: number;\n returnUrl?: string;\n }): Promise<AutoRechargeProcessResult> {\n const profile = await this.billing.getAutoRechargeProfile(input.userId);\n if (!profile?.enabled) throw new Error(\"auto_recharge_disabled\");\n await this.billing.upsertAutoRechargeProfile(\n {\n ...profile,\n state: \"active\",\n armed: true,\n },\n { resetCooldown: true },\n );\n return this.processIfNeeded(input);\n }\n\n async processIfNeeded(input: {\n userId: string;\n provider: PaymentProvider;\n balance: number;\n returnUrl?: string;\n }): Promise<AutoRechargeProcessResult> {\n const policy = await this.policy(input.provider);\n if (!policy) return { outcome: \"not_configured\" };\n const profile = await this.billing.getAutoRechargeProfile(input.userId);\n if (!profile?.enabled || profile.state !== \"active\") return { outcome: \"disabled\" };\n if (input.balance >= policy.threshold) {\n return { outcome: \"above_threshold\" };\n }\n\n const payment = await this.paymentMethod(input.userId, input.provider);\n if (!payment) return { outcome: \"failed\" };\n const attempt = await this.billing.claimAutoRechargeAttempt({\n userId: input.userId,\n idempotencyKey: `auto-recharge:${input.userId}:${randomUUID()}`,\n });\n if (!attempt) return { outcome: \"limit_reached\" };\n\n if (!input.provider.chargeSavedPaymentMethod) {\n throw new Error(\n `provider_capability_not_supported:chargeSavedPaymentMethod:${input.provider.provider}`,\n );\n }\n const charge = await input.provider.chargeSavedPaymentMethod({\n customerId: payment.customerId,\n paymentMethodId: payment.method.id,\n productId: policy.productId,\n quantity: policy.quantity,\n returnUrl: input.returnUrl,\n idempotencyKey: attempt.idempotencyKey,\n metadata: {\n auto_recharge_attempt_id: attempt.id,\n purpose: \"credit_topup\",\n userId: input.userId,\n },\n });\n if (charge.status === \"requires_customer_action\") {\n await this.billing.updateAutoRechargeAttempt({\n id: attempt.id,\n state: \"action_required\",\n providerAttemptId: charge.providerPaymentId ?? null,\n });\n return { outcome: \"action_required\", charge };\n }\n if (charge.status === \"succeeded\" || charge.status === \"processing\") {\n await this.billing.updateAutoRechargeAttempt({\n id: attempt.id,\n state: \"processing\",\n providerAttemptId: charge.providerPaymentId ?? null,\n });\n return { outcome: \"submitted\", charge };\n }\n\n await this.billing.updateAutoRechargeAttempt({\n id: attempt.id,\n state: \"failed\",\n providerAttemptId: charge.providerPaymentId ?? null,\n failureCode: \"payment_failed\",\n });\n return { outcome: \"failed\", charge };\n }\n}\n"]}
@@ -0,0 +1,71 @@
1
+ import type { BillingStore } from "./billing-store.js";
2
+ import type { BillingAutoRechargeAttempt, BillingAutoRechargeProfile, BillingCustomerRecord, BillingEvent, BillingEventResult, BillingOfferResult, BillingPreferences, BillingSubscriptionChange, BillingSubscriptionChangeInput, BillingSubscriptionState, BillingTopupResult, CheckoutIntent } from "./types/index.js";
3
+ import { AutoRechargeService } from "./auto-recharge-service.js";
4
+ import type { BillingServiceOptions } from "./service-types.js";
5
+ export type { BillingProvisioningPort, BillingServiceOptions } from "./service-types.js";
6
+ /**
7
+ * Provider-agnostic billing lifecycle state machine.
8
+ * Mirrors the Python billing service implementation.
9
+ */
10
+ export declare class BillingService {
11
+ readonly autoRecharge: AutoRechargeService;
12
+ private readonly store;
13
+ private readonly management;
14
+ private readonly events;
15
+ get hasProvisioning(): boolean;
16
+ constructor(store: BillingStore, options?: BillingServiceOptions);
17
+ createOrGetCheckoutIntent(input: Parameters<BillingStore["createOrGetCheckoutIntent"]>[0]): Promise<CheckoutIntent>;
18
+ updateCheckoutIntent(id: string, update: Parameters<BillingStore["updateCheckoutIntent"]>[1]): Promise<void>;
19
+ getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null>;
20
+ getActiveSubscription(userId: string): Promise<BillingSubscriptionState | null>;
21
+ getUserPreferences(userId: string): Promise<BillingPreferences | null>;
22
+ listBillingInvoices(userId: string): Promise<import("./contracts.js").BillingInvoiceInfo[]>;
23
+ upsertBillingSubscription(state: BillingSubscriptionState): Promise<void>;
24
+ createBillingSubscriptionChange(input: BillingSubscriptionChangeInput): Promise<BillingSubscriptionChange>;
25
+ getOpenBillingSubscriptionChange(provider: string, providerSubscriptionId: string): Promise<BillingSubscriptionChange | null>;
26
+ updateBillingSubscriptionChange(id: string, update: Parameters<BillingStore["updateBillingSubscriptionChange"]>[1]): Promise<void>;
27
+ recordSubscriptionConflict(input: Parameters<BillingStore["recordSubscriptionConflict"]>[0]): Promise<void>;
28
+ updateUserPreferences(preferences: BillingPreferences): Promise<void>;
29
+ getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null>;
30
+ getActiveBursarConfig(): Promise<Record<string, unknown> | null>;
31
+ listCancellableProviderSubscriptionIds(userId: string): Promise<string[]>;
32
+ listCancellableSubscriptions(userId: string): Promise<BillingSubscriptionState[]>;
33
+ pseudonymizeFinancialSubject(userId: string): Promise<void>;
34
+ upsertAutoRechargeProfile(profile: BillingAutoRechargeProfile, options?: {
35
+ resetCooldown?: boolean;
36
+ }): Promise<void>;
37
+ claimAutoRechargeAttempt(input: {
38
+ userId: string;
39
+ idempotencyKey: string;
40
+ }): Promise<BillingAutoRechargeAttempt | null>;
41
+ updateAutoRechargeAttempt(input: {
42
+ id: string;
43
+ state: string;
44
+ providerAttemptId?: string | null;
45
+ failureCode?: string | null;
46
+ failureMessage?: string | null;
47
+ metadata?: Record<string, unknown>;
48
+ }): Promise<void>;
49
+ updateAutoRechargeAttemptByProviderPayment(input: {
50
+ provider: string;
51
+ providerPaymentId: string;
52
+ state: string;
53
+ failureCode?: string | null;
54
+ failureMessage?: string | null;
55
+ }): Promise<void>;
56
+ countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number>;
57
+ getCustomerByUserId(userId: string, provider?: string | null): Promise<BillingCustomerRecord | null>;
58
+ resolveOffer(provider: string, productId?: string | null, priceId?: string | null): Promise<BillingOfferResult | null>;
59
+ resolveOfferByLookup(provider: string, lookupKey: string): Promise<BillingOfferResult | null>;
60
+ resolveTopup(provider: string, productId?: string | null, priceId?: string | null): Promise<BillingTopupResult | null>;
61
+ resolveTopupByLookup(provider: string, lookupKey: string): Promise<BillingTopupResult | null>;
62
+ upsertCustomer(provider: string, providerCustomerId: string, userId: string, email?: string | null): Promise<void>;
63
+ getUserSubscription(userId: string): Promise<BillingSubscriptionState | null>;
64
+ getBlockingSubscription(userId: string): Promise<BillingSubscriptionState | null>;
65
+ expirePastDueGracePeriods(now?: Date): Promise<number>;
66
+ private expireGraceIfNeeded;
67
+ /** Invalidate cached provider offer resolution. */
68
+ invalidateOfferCache(): void;
69
+ ingestBillingEvent(event: BillingEvent): Promise<BillingEventResult>;
70
+ }
71
+ //# sourceMappingURL=billing-service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"billing-service.d.ts","sourceRoot":"","sources":["../../src/billing/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E,MAAM,EAChB,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAI/B,YAAY,CAChB,QAAQ,EAAE,MAAM,EAChB,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,EACzB,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,GACtB,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAI/B,oBAAoB,CACxB,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAI/B,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;IAIV,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,wBAAwB,GAAG,IAAI,CAAC;IAY7E,uBAAuB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,wBAAwB,GAAG,IAAI,CAAC;IAUjF,yBAAyB,CAAC,GAAG,OAAa,GAAG,OAAO,CAAC,MAAM,CAAC;YAmCpD,mBAAmB;IA4BjC,mDAAmD;IACnD,oBAAoB,IAAI,IAAI;IAItB,kBAAkB,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,kBAAkB,CAAC;CAG3E"}
@@ -0,0 +1,172 @@
1
+ import { SUBSCRIPTION_STATUS } from "./types/index.js";
2
+ import { AutoRechargeService } from "./auto-recharge-service.js";
3
+ import { BillingEventProcessor } from "./event-processor.js";
4
+ import { BillingManagement } from "./management.js";
5
+ /**
6
+ * Provider-agnostic billing lifecycle state machine.
7
+ * Mirrors the Python billing service implementation.
8
+ */
9
+ export class BillingService {
10
+ autoRecharge;
11
+ store;
12
+ management;
13
+ events;
14
+ get hasProvisioning() {
15
+ return this.events.hasProvisioning;
16
+ }
17
+ constructor(store, options) {
18
+ this.store = store;
19
+ this.management = new BillingManagement(store);
20
+ this.events = new BillingEventProcessor(store, options);
21
+ this.autoRecharge = new AutoRechargeService(this);
22
+ }
23
+ async createOrGetCheckoutIntent(input) {
24
+ return this.management.createOrGetCheckoutIntent(input);
25
+ }
26
+ async updateCheckoutIntent(id, update) {
27
+ await this.management.updateCheckoutIntent(id, update);
28
+ }
29
+ async getCheckoutIntent(id, subjectId) {
30
+ return this.management.getCheckoutIntent(id, subjectId);
31
+ }
32
+ async getActiveSubscription(userId) {
33
+ return this.management.getActiveSubscription(userId);
34
+ }
35
+ async getUserPreferences(userId) {
36
+ return this.management.getUserPreferences(userId);
37
+ }
38
+ async listBillingInvoices(userId) {
39
+ return this.management.listBillingInvoices(userId);
40
+ }
41
+ async upsertBillingSubscription(state) {
42
+ await this.management.upsertBillingSubscription(state);
43
+ }
44
+ async createBillingSubscriptionChange(input) {
45
+ return this.management.createBillingSubscriptionChange(input);
46
+ }
47
+ async getOpenBillingSubscriptionChange(provider, providerSubscriptionId) {
48
+ return this.management.getOpenBillingSubscriptionChange(provider, providerSubscriptionId);
49
+ }
50
+ async updateBillingSubscriptionChange(id, update) {
51
+ await this.management.updateBillingSubscriptionChange(id, update);
52
+ }
53
+ async recordSubscriptionConflict(input) {
54
+ await this.management.recordSubscriptionConflict(input);
55
+ }
56
+ async updateUserPreferences(preferences) {
57
+ await this.management.updateUserPreferences(preferences);
58
+ }
59
+ async getAutoRechargeProfile(userId) {
60
+ return this.management.getAutoRechargeProfile(userId);
61
+ }
62
+ async getActiveBursarConfig() {
63
+ return this.management.getActiveBursarConfig();
64
+ }
65
+ async listCancellableProviderSubscriptionIds(userId) {
66
+ return this.management.listCancellableProviderSubscriptionIds(userId);
67
+ }
68
+ async listCancellableSubscriptions(userId) {
69
+ return this.management.listCancellableSubscriptions(userId);
70
+ }
71
+ async pseudonymizeFinancialSubject(userId) {
72
+ await this.management.pseudonymizeFinancialSubject(userId);
73
+ }
74
+ async upsertAutoRechargeProfile(profile, options) {
75
+ await this.management.upsertAutoRechargeProfile(profile, options);
76
+ }
77
+ async claimAutoRechargeAttempt(input) {
78
+ return this.management.claimAutoRechargeAttempt(input);
79
+ }
80
+ async updateAutoRechargeAttempt(input) {
81
+ await this.management.updateAutoRechargeAttempt(input);
82
+ }
83
+ async updateAutoRechargeAttemptByProviderPayment(input) {
84
+ await this.management.updateAutoRechargeAttemptByProviderPayment(input);
85
+ }
86
+ async countAutoRechargeAttempts(userId, since) {
87
+ return this.management.countAutoRechargeAttempts(userId, since);
88
+ }
89
+ async getCustomerByUserId(userId, provider) {
90
+ return this.management.getCustomerByUserId(userId, provider);
91
+ }
92
+ async resolveOffer(provider, productId, priceId) {
93
+ return this.management.resolveOffer(provider, productId, priceId);
94
+ }
95
+ async resolveOfferByLookup(provider, lookupKey) {
96
+ return this.management.resolveOfferByLookup(provider, lookupKey);
97
+ }
98
+ async resolveTopup(provider, productId, priceId) {
99
+ return this.management.resolveTopup(provider, productId, priceId);
100
+ }
101
+ async resolveTopupByLookup(provider, lookupKey) {
102
+ return this.management.resolveTopupByLookup(provider, lookupKey);
103
+ }
104
+ async upsertCustomer(provider, providerCustomerId, userId, email) {
105
+ await this.management.upsertCustomer(provider, providerCustomerId, userId, email);
106
+ }
107
+ async getUserSubscription(userId) {
108
+ const subscription = await this.store.getUserSubscription(userId, [
109
+ SUBSCRIPTION_STATUS.ACTIVE,
110
+ SUBSCRIPTION_STATUS.TRIALING,
111
+ SUBSCRIPTION_STATUS.CANCELED,
112
+ SUBSCRIPTION_STATUS.PAST_DUE,
113
+ SUBSCRIPTION_STATUS.INCOMPLETE,
114
+ // EXPIRED excluded — expired subscriptions are not "current" for billing purposes.
115
+ ]);
116
+ return this.expireGraceIfNeeded(subscription);
117
+ }
118
+ async getBlockingSubscription(userId) {
119
+ const subscription = await this.store.getUserSubscription(userId, [
120
+ SUBSCRIPTION_STATUS.ACTIVE,
121
+ SUBSCRIPTION_STATUS.TRIALING,
122
+ SUBSCRIPTION_STATUS.PAST_DUE,
123
+ SUBSCRIPTION_STATUS.INCOMPLETE,
124
+ ]);
125
+ return this.expireGraceIfNeeded(subscription);
126
+ }
127
+ async expirePastDueGracePeriods(now = new Date()) {
128
+ if (!this.events.hasProvisioning)
129
+ return 0;
130
+ const asOf = now.toISOString();
131
+ const candidates = await this.store.listExpiredGraceSubscriptions(asOf);
132
+ let expiredCount = 0;
133
+ for (const candidate of candidates) {
134
+ if (!candidate.subscriptionId || !candidate.graceEndsAt)
135
+ continue;
136
+ const current = await this.store.getBillingSubscription(candidate.provider, candidate.providerSubscriptionId);
137
+ if (current?.status !== "past_due" ||
138
+ current.graceEndsAt !== candidate.graceEndsAt ||
139
+ current.graceExpiredAt) {
140
+ continue;
141
+ }
142
+ await this.events.revokeIfCurrentSubscription(candidate.userId, candidate.providerSubscriptionId);
143
+ if (await this.store.markSubscriptionGraceExpired(candidate.subscriptionId, candidate.graceEndsAt, asOf)) {
144
+ expiredCount += 1;
145
+ }
146
+ }
147
+ return expiredCount;
148
+ }
149
+ async expireGraceIfNeeded(subscription) {
150
+ if (!subscription ||
151
+ !this.events.hasProvisioning ||
152
+ subscription.status !== "past_due" ||
153
+ subscription.graceExpiredAt ||
154
+ !subscription.graceEndsAt ||
155
+ new Date(subscription.graceEndsAt).getTime() > Date.now() ||
156
+ !subscription.subscriptionId) {
157
+ return subscription;
158
+ }
159
+ await this.events.revokeIfCurrentSubscription(subscription.userId, subscription.providerSubscriptionId);
160
+ const expiredAt = new Date().toISOString();
161
+ const marked = await this.store.markSubscriptionGraceExpired(subscription.subscriptionId, subscription.graceEndsAt, expiredAt);
162
+ return marked ? { ...subscription, graceExpiredAt: expiredAt } : subscription;
163
+ }
164
+ /** Invalidate cached provider offer resolution. */
165
+ invalidateOfferCache() {
166
+ this.events.invalidateOfferCache();
167
+ }
168
+ async ingestBillingEvent(event) {
169
+ return this.events.ingestBillingEvent(event);
170
+ }
171
+ }
172
+ //# sourceMappingURL=billing-service.js.map
@@ -0,0 +1 @@
1
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CAAC;YACpB,CAAC;QACH,CAAC;QACD,OAAO,YAAY,CAAC;IACtB,CAAC;IAEO,KAAK,CAAC,mBAAmB,CAC/B,YAA6C;QAE7C,IACE,CAAC,YAAY;YACb,CAAC,IAAI,CAAC,MAAM,CAAC,eAAe;YAC5B,YAAY,CAAC,MAAM,KAAK,UAAU;YAClC,YAAY,CAAC,cAAc;YAC3B,CAAC,YAAY,CAAC,WAAW;YACzB,IAAI,IAAI,CAAC,YAAY,CAAC,WAAW,CAAC,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,GAAG,EAAE;YACzD,CAAC,YAAY,CAAC,cAAc,EAC5B,CAAC;YACD,OAAO,YAAY,CAAC;QACtB,CAAC;QAED,MAAM,IAAI,CAAC,MAAM,CAAC,2BAA2B,CAC3C,YAAY,CAAC,MAAM,EACnB,YAAY,CAAC,sBAAsB,CACpC,CAAC;QACF,MAAM,SAAS,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;QAC3C,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,4BAA4B,CAC1D,YAAY,CAAC,cAAc,EAC3B,YAAY,CAAC,WAAW,EACxB,SAAS,CACV,CAAC;QACF,OAAO,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,YAAY,EAAE,cAAc,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,YAAY,CAAC;IAChF,CAAC;IAED,mDAAmD;IACnD,oBAAoB;QAClB,IAAI,CAAC,MAAM,CAAC,oBAAoB,EAAE,CAAC;IACrC,CAAC;IAED,KAAK,CAAC,kBAAkB,CAAC,KAAmB;QAC1C,OAAO,IAAI,CAAC,MAAM,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAC/C,CAAC;CACF","sourcesContent":["import type { BillingStore } from \"./billing-store.js\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeProfile,\n BillingCustomerRecord,\n BillingEvent,\n BillingEventResult,\n BillingOfferResult,\n BillingPreferences,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionState,\n BillingTopupResult,\n CheckoutIntent,\n} from \"./types/index.js\";\nimport { SUBSCRIPTION_STATUS } from \"./types/index.js\";\nimport { AutoRechargeService } from \"./auto-recharge-service.js\";\nimport { BillingEventProcessor } from \"./event-processor.js\";\nimport { BillingManagement } from \"./management.js\";\nimport type { BillingServiceOptions } from \"./service-types.js\";\nexport type { BillingProvisioningPort, BillingServiceOptions } from \"./service-types.js\";\n\n/**\n * Provider-agnostic billing lifecycle state machine.\n * Mirrors the Python billing service implementation.\n */\nexport class BillingService {\n readonly autoRecharge: AutoRechargeService;\n private readonly store: BillingStore;\n private readonly management: BillingManagement;\n private readonly events: BillingEventProcessor;\n\n get hasProvisioning(): boolean {\n return this.events.hasProvisioning;\n }\n\n constructor(store: BillingStore, options?: BillingServiceOptions) {\n this.store = store;\n this.management = new BillingManagement(store);\n this.events = new BillingEventProcessor(store, options);\n this.autoRecharge = new AutoRechargeService(this);\n }\n\n async createOrGetCheckoutIntent(\n input: Parameters<BillingStore[\"createOrGetCheckoutIntent\"]>[0],\n ): Promise<CheckoutIntent> {\n return this.management.createOrGetCheckoutIntent(input);\n }\n\n async updateCheckoutIntent(\n id: string,\n update: Parameters<BillingStore[\"updateCheckoutIntent\"]>[1],\n ): Promise<void> {\n await this.management.updateCheckoutIntent(id, update);\n }\n\n async getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null> {\n return this.management.getCheckoutIntent(id, subjectId);\n }\n\n async getActiveSubscription(userId: string): Promise<BillingSubscriptionState | null> {\n return this.management.getActiveSubscription(userId);\n }\n\n async getUserPreferences(userId: string): Promise<BillingPreferences | null> {\n return this.management.getUserPreferences(userId);\n }\n\n async listBillingInvoices(userId: string) {\n return this.management.listBillingInvoices(userId);\n }\n\n async upsertBillingSubscription(state: BillingSubscriptionState): Promise<void> {\n await this.management.upsertBillingSubscription(state);\n }\n\n async createBillingSubscriptionChange(\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n return this.management.createBillingSubscriptionChange(input);\n }\n\n async getOpenBillingSubscriptionChange(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.management.getOpenBillingSubscriptionChange(provider, providerSubscriptionId);\n }\n\n async updateBillingSubscriptionChange(\n id: string,\n update: Parameters<BillingStore[\"updateBillingSubscriptionChange\"]>[1],\n ): Promise<void> {\n await this.management.updateBillingSubscriptionChange(id, update);\n }\n\n async recordSubscriptionConflict(\n input: Parameters<BillingStore[\"recordSubscriptionConflict\"]>[0],\n ): Promise<void> {\n await this.management.recordSubscriptionConflict(input);\n }\n\n async updateUserPreferences(preferences: BillingPreferences): Promise<void> {\n await this.management.updateUserPreferences(preferences);\n }\n\n async getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n return this.management.getAutoRechargeProfile(userId);\n }\n\n async getActiveBursarConfig(): Promise<Record<string, unknown> | null> {\n return this.management.getActiveBursarConfig();\n }\n\n async listCancellableProviderSubscriptionIds(userId: string): Promise<string[]> {\n return this.management.listCancellableProviderSubscriptionIds(userId);\n }\n\n async listCancellableSubscriptions(userId: string): Promise<BillingSubscriptionState[]> {\n return this.management.listCancellableSubscriptions(userId);\n }\n\n async pseudonymizeFinancialSubject(userId: string): Promise<void> {\n await this.management.pseudonymizeFinancialSubject(userId);\n }\n\n async upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void> {\n await this.management.upsertAutoRechargeProfile(profile, options);\n }\n\n async claimAutoRechargeAttempt(input: {\n userId: string;\n idempotencyKey: string;\n }): Promise<BillingAutoRechargeAttempt | null> {\n return this.management.claimAutoRechargeAttempt(input);\n }\n\n async updateAutoRechargeAttempt(input: {\n id: string;\n state: string;\n providerAttemptId?: string | null;\n failureCode?: string | null;\n failureMessage?: string | null;\n metadata?: Record<string, unknown>;\n }): Promise<void> {\n await this.management.updateAutoRechargeAttempt(input);\n }\n\n async updateAutoRechargeAttemptByProviderPayment(input: {\n provider: string;\n providerPaymentId: string;\n state: string;\n failureCode?: string | null;\n failureMessage?: string | null;\n }): Promise<void> {\n await this.management.updateAutoRechargeAttemptByProviderPayment(input);\n }\n\n async countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number> {\n return this.management.countAutoRechargeAttempts(userId, since);\n }\n\n async getCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null> {\n return this.management.getCustomerByUserId(userId, provider);\n }\n\n async resolveOffer(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingOfferResult | null> {\n return this.management.resolveOffer(provider, productId, priceId);\n }\n\n async resolveOfferByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingOfferResult | null> {\n return this.management.resolveOfferByLookup(provider, lookupKey);\n }\n\n async resolveTopup(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingTopupResult | null> {\n return this.management.resolveTopup(provider, productId, priceId);\n }\n\n async resolveTopupByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingTopupResult | null> {\n return this.management.resolveTopupByLookup(provider, lookupKey);\n }\n\n async upsertCustomer(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email?: string | null,\n ): Promise<void> {\n await this.management.upsertCustomer(provider, providerCustomerId, userId, email);\n }\n\n async getUserSubscription(userId: string): Promise<BillingSubscriptionState | null> {\n const subscription = await this.store.getUserSubscription(userId, [\n SUBSCRIPTION_STATUS.ACTIVE,\n SUBSCRIPTION_STATUS.TRIALING,\n SUBSCRIPTION_STATUS.CANCELED,\n SUBSCRIPTION_STATUS.PAST_DUE,\n SUBSCRIPTION_STATUS.INCOMPLETE,\n // EXPIRED excluded — expired subscriptions are not \"current\" for billing purposes.\n ]);\n return this.expireGraceIfNeeded(subscription);\n }\n\n async getBlockingSubscription(userId: string): Promise<BillingSubscriptionState | null> {\n const subscription = await this.store.getUserSubscription(userId, [\n SUBSCRIPTION_STATUS.ACTIVE,\n SUBSCRIPTION_STATUS.TRIALING,\n SUBSCRIPTION_STATUS.PAST_DUE,\n SUBSCRIPTION_STATUS.INCOMPLETE,\n ]);\n return this.expireGraceIfNeeded(subscription);\n }\n\n async expirePastDueGracePeriods(now = new Date()): Promise<number> {\n if (!this.events.hasProvisioning) return 0;\n const asOf = now.toISOString();\n const candidates = await this.store.listExpiredGraceSubscriptions(asOf);\n let expiredCount = 0;\n for (const candidate of candidates) {\n if (!candidate.subscriptionId || !candidate.graceEndsAt) continue;\n const current = await this.store.getBillingSubscription(\n candidate.provider,\n candidate.providerSubscriptionId,\n );\n if (\n current?.status !== \"past_due\" ||\n current.graceEndsAt !== candidate.graceEndsAt ||\n current.graceExpiredAt\n ) {\n continue;\n }\n await this.events.revokeIfCurrentSubscription(\n candidate.userId,\n candidate.providerSubscriptionId,\n );\n if (\n await this.store.markSubscriptionGraceExpired(\n candidate.subscriptionId,\n candidate.graceEndsAt,\n asOf,\n )\n ) {\n expiredCount += 1;\n }\n }\n return expiredCount;\n }\n\n private async expireGraceIfNeeded(\n subscription: BillingSubscriptionState | null,\n ): Promise<BillingSubscriptionState | null> {\n if (\n !subscription ||\n !this.events.hasProvisioning ||\n subscription.status !== \"past_due\" ||\n subscription.graceExpiredAt ||\n !subscription.graceEndsAt ||\n new Date(subscription.graceEndsAt).getTime() > Date.now() ||\n !subscription.subscriptionId\n ) {\n return subscription;\n }\n\n await this.events.revokeIfCurrentSubscription(\n subscription.userId,\n subscription.providerSubscriptionId,\n );\n const expiredAt = new Date().toISOString();\n const marked = await this.store.markSubscriptionGraceExpired(\n subscription.subscriptionId,\n subscription.graceEndsAt,\n expiredAt,\n );\n return marked ? { ...subscription, graceExpiredAt: expiredAt } : subscription;\n }\n\n /** Invalidate cached provider offer resolution. */\n invalidateOfferCache(): void {\n this.events.invalidateOfferCache();\n }\n\n async ingestBillingEvent(event: BillingEvent): Promise<BillingEventResult> {\n return this.events.ingestBillingEvent(event);\n }\n}\n"]}
@@ -1,4 +1,5 @@
1
- import type { BillingConfig, BillingEventClaim, BillingSubscriptionState } from "./billing-types.js";
1
+ import type { BillingAutoRechargeAttempt, BillingAutoRechargeProfile, BillingCustomerRecord, BillingEventClaim, BillingOfferResult, BillingPreferences, BillingSubscriptionChange, BillingSubscriptionChangeInput, BillingSubscriptionState, CheckoutIntent, BillingTopupResult, BillingInvoiceInfo } from "./types/index.js";
2
+ import type { AutoRechargeAttemptClaim, AutoRechargeAttemptUpdate, AutoRechargeProviderPaymentUpdate, BillingCreditGrantCreate, BillingDisputeUpsert, BillingInvoiceUpsert, BillingPaymentUpsert, BillingRefundUpsert, BillingSubscriptionChangeUpdate, BillingSubscriptionConflictCreate, CheckoutIntentCreate, CheckoutIntentUpdate } from "./contracts.js";
2
3
  /**
3
4
  * Abstract billing store — provider-agnostic persistence layer for
4
5
  * subscription lifecycle state.
@@ -6,22 +7,53 @@ import type { BillingConfig, BillingEventClaim, BillingSubscriptionState } from
6
7
  * Mirrors Python bursar/billing/store.py.
7
8
  */
8
9
  export declare abstract class BillingStore {
9
- abstract syncBillingFromConfig(config: BillingConfig): Promise<void>;
10
- abstract resolveBillingOffer(provider: string, productId?: string | null, priceId?: string | null): Promise<Record<string, unknown> | null>;
11
- abstract claimBillingEvent(provider: string, eventId: string, eventType: string): Promise<BillingEventClaim>;
12
- abstract completeBillingEvent(provider: string, eventId: string): Promise<void>;
13
- abstract failBillingEvent(provider: string, eventId: string): Promise<void>;
10
+ abstract createOrGetCheckoutIntent(input: CheckoutIntentCreate): Promise<CheckoutIntent>;
11
+ abstract updateCheckoutIntent(id: string, update: CheckoutIntentUpdate): Promise<void>;
12
+ abstract getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null>;
13
+ abstract resolveBillingOffer(provider: string, productId?: string | null, priceId?: string | null): Promise<BillingOfferResult | null>;
14
+ abstract claimBillingEvent(provider: string, eventId: string, eventType: string, envelope?: Record<string, unknown>): Promise<BillingEventClaim>;
15
+ abstract completeBillingEvent(provider: string, eventId: string, claimToken: string): Promise<boolean>;
16
+ abstract failBillingEvent(provider: string, eventId: string, claimToken: string, error?: string): Promise<boolean>;
14
17
  abstract upsertBillingCustomer(provider: string, providerCustomerId: string, userId: string, email?: string | null): Promise<void>;
15
18
  abstract upsertBillingSubscription(state: BillingSubscriptionState): Promise<void>;
16
19
  abstract getBillingCustomer(provider: string, providerCustomerId: string): Promise<string | null>;
17
20
  abstract getBillingSubscription(provider: string, providerSubscriptionId: string): Promise<BillingSubscriptionState | null>;
18
- abstract getUserSubscription(userId: string): Promise<BillingSubscriptionState | null>;
19
- abstract resolveCreditTopup(provider: string, productId?: string | null, priceId?: string | null): Promise<Record<string, unknown> | null>;
20
- abstract computeTopupCredits(amountMinor: number, topupConfig: Record<string, unknown>): Promise<number>;
21
- abstract upsertBillingPayment(provider: string, providerPaymentId: string, providerInvoiceId?: string | null, userId?: string | null, amountMinor?: number, taxMinor?: number | null, currency?: string | null, purpose?: string, metadata?: Record<string, unknown> | null): Promise<void>;
22
- abstract upsertBillingRefund(provider: string, providerRefundId: string, providerPaymentId?: string | null, userId?: string | null, amountMinor?: number, currency?: string | null, reason?: string | null, metadata?: Record<string, unknown> | null): Promise<void>;
23
- abstract upsertBillingInvoice(provider: string, providerInvoiceId: string, providerSubscriptionId?: string | null, userId?: string | null, status?: string | null, amountPaidMinor?: number | null, amountDueMinor?: number | null, currency?: string | null, periodStart?: string | null, periodEnd?: string | null, metadata?: Record<string, unknown> | null): Promise<void>;
24
- abstract upsertBillingDispute(provider: string, providerDisputeId: string, providerPaymentId?: string | null, userId?: string | null, status?: string, reason?: string | null, metadata?: Record<string, unknown> | null): Promise<void>;
21
+ abstract createBillingSubscriptionChange(input: BillingSubscriptionChangeInput): Promise<BillingSubscriptionChange>;
22
+ abstract getOpenBillingSubscriptionChange(provider: string, providerSubscriptionId: string): Promise<BillingSubscriptionChange | null>;
23
+ abstract listExpiredGraceSubscriptions(now: string, limit?: number): Promise<BillingSubscriptionState[]>;
24
+ abstract markSubscriptionGraceExpired(subscriptionId: string, expectedGraceEndsAt: string, expiredAt?: string): Promise<boolean>;
25
+ abstract updateBillingSubscriptionChange(id: string, update: BillingSubscriptionChangeUpdate): Promise<void>;
26
+ abstract getUserSubscription(userId: string, statuses?: string[]): Promise<BillingSubscriptionState | null>;
27
+ abstract resolveCreditTopup(provider: string, productId?: string | null, priceId?: string | null): Promise<BillingTopupResult | null>;
28
+ abstract resolveCreditTopupByLookup(provider: string, lookupKey: string): Promise<BillingTopupResult | null>;
29
+ abstract resolveBillingOfferByLookup(provider: string, lookupKey: string): Promise<BillingOfferResult | null>;
30
+ abstract computeTopupCredits(amountMinor: number, topupConfig: BillingTopupResult): Promise<number>;
31
+ abstract upsertBillingPayment(options: BillingPaymentUpsert): Promise<string>;
32
+ abstract createBillingCreditGrant(input: BillingCreditGrantCreate): Promise<string>;
33
+ abstract grantBillingCredit(grantId: string, idempotencyKey: string): Promise<Record<string, unknown>>;
34
+ abstract getBillingCreditGrantByPayment(paymentId: string): Promise<string | null>;
35
+ abstract postBillingRefund(refundId: string, grantId: string, amountMinor: number, idempotencyKey: string): Promise<Record<string, unknown>>;
36
+ abstract listBillingInvoices(userId: string): Promise<BillingInvoiceInfo[]>;
37
+ abstract upsertBillingRefund(options: BillingRefundUpsert): Promise<string>;
38
+ abstract upsertBillingInvoice(options: BillingInvoiceUpsert): Promise<void>;
39
+ abstract upsertBillingDispute(options: BillingDisputeUpsert): Promise<void>;
25
40
  abstract getBillingPayment(provider: string, providerPaymentId: string): Promise<Record<string, unknown> | null>;
41
+ abstract getActiveBursarConfig(): Promise<Record<string, unknown> | null>;
42
+ abstract pseudonymizeFinancialSubject(userId: string): Promise<boolean>;
43
+ abstract getUserSubscriptions(userId: string): Promise<BillingSubscriptionState[]>;
44
+ abstract recordSubscriptionConflict(input: BillingSubscriptionConflictCreate): Promise<void>;
45
+ /** Select a current provider subscription as the subject's entitlement source. */
46
+ abstract selectSubscriptionEntitlementSource(userId: string, provider: string, providerSubscriptionId?: string | null): Promise<boolean>;
47
+ abstract getBillingPreferences(userId: string): Promise<BillingPreferences | null>;
48
+ abstract upsertBillingPreferences(prefs: BillingPreferences): Promise<void>;
49
+ abstract getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null>;
50
+ abstract upsertAutoRechargeProfile(profile: BillingAutoRechargeProfile, options?: {
51
+ resetCooldown?: boolean;
52
+ }): Promise<void>;
53
+ abstract claimAutoRechargeAttempt(input: AutoRechargeAttemptClaim): Promise<BillingAutoRechargeAttempt | null>;
54
+ abstract updateAutoRechargeAttempt(input: AutoRechargeAttemptUpdate): Promise<void>;
55
+ abstract updateAutoRechargeAttemptByProviderPayment(input: AutoRechargeProviderPaymentUpdate): Promise<void>;
56
+ abstract countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number>;
57
+ abstract getBillingCustomerByUserId(userId: string, provider?: string | null): Promise<BillingCustomerRecord | null>;
26
58
  }
27
59
  //# sourceMappingURL=billing-store.d.ts.map