@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,89 @@
1
+ import type { BillingAutoRechargeAttempt, BillingAutoRechargeProfile, BillingCustomerRecord, BillingEventClaim, BillingOfferResult, BillingPreferences, BillingSubscriptionChange, BillingSubscriptionChangeInput, BillingSubscriptionState, CheckoutIntent, BillingTopupResult } from "../types/index.js";
2
+ import { BillingStore } from "../billing-store.js";
3
+ import type { AutoRechargeAttemptClaim, AutoRechargeAttemptUpdate, AutoRechargeProviderPaymentUpdate, BillingCreditGrantCreate, BillingDisputeUpsert, BillingInvoiceUpsert, BillingPaymentUpsert, BillingRefundUpsert, BillingSubscriptionChangeUpdate, BillingSubscriptionConflictCreate, CheckoutIntentCreate, CheckoutIntentUpdate } from "../contracts.js";
4
+ import { type PostgresConnectionOptions, type PostgresPool } from "../../shared/postgres-client.js";
5
+ export interface PostgresBillingStoreOptions extends PostgresConnectionOptions {
6
+ billingPayloadBackend?: "postgres" | "s3";
7
+ }
8
+ export declare class PostgresBillingStore extends BillingStore {
9
+ private readonly postgres;
10
+ private _offer;
11
+ private _topup;
12
+ private _customer;
13
+ private _subscription;
14
+ private _event;
15
+ private _payment;
16
+ private _refund;
17
+ private _invoice;
18
+ private _dispute;
19
+ private _preferences;
20
+ private _autoRecharge;
21
+ constructor(poolOrUrl: PostgresPool | string, tenantId: string, storageOptions?: PostgresBillingStoreOptions);
22
+ close(): Promise<void>;
23
+ private get queryFn();
24
+ private get billingOffer();
25
+ private get billingTopup();
26
+ private get billingCustomer();
27
+ private get billingSubscription();
28
+ private get billingEvent();
29
+ private get billingPayment();
30
+ private get billingRefund();
31
+ private get billingInvoice();
32
+ private get billingDispute();
33
+ private get billingPreferences();
34
+ private get billingAutoRecharge();
35
+ createOrGetCheckoutIntent(input: CheckoutIntentCreate): Promise<CheckoutIntent>;
36
+ updateCheckoutIntent(id: string, update: CheckoutIntentUpdate): Promise<void>;
37
+ getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null>;
38
+ private rowToCheckoutIntent;
39
+ private rowToOffer;
40
+ resolveBillingOffer(provider: string, productId?: string | null, priceId?: string | null): Promise<BillingOfferResult | null>;
41
+ resolveBillingOfferByLookup(provider: string, lookupKey: string): Promise<BillingOfferResult | null>;
42
+ claimBillingEvent(provider: string, eventId: string, eventType: string, envelope?: Record<string, unknown>): Promise<BillingEventClaim>;
43
+ completeBillingEvent(provider: string, eventId: string, claimToken: string): Promise<boolean>;
44
+ failBillingEvent(provider: string, eventId: string, claimToken: string, error?: string): Promise<boolean>;
45
+ upsertBillingCustomer(provider: string, providerCustomerId: string, userId: string, email?: string | null): Promise<void>;
46
+ upsertBillingSubscription(state: BillingSubscriptionState): Promise<void>;
47
+ getBillingCustomer(provider: string, providerCustomerId: string): Promise<string | null>;
48
+ getBillingSubscription(provider: string, providerSubscriptionId: string): Promise<BillingSubscriptionState | null>;
49
+ createBillingSubscriptionChange(input: BillingSubscriptionChangeInput): Promise<BillingSubscriptionChange>;
50
+ getOpenBillingSubscriptionChange(provider: string, providerSubscriptionId: string): Promise<BillingSubscriptionChange | null>;
51
+ listExpiredGraceSubscriptions(now: string, limit?: number): Promise<BillingSubscriptionState[]>;
52
+ markSubscriptionGraceExpired(subscriptionId: string, expectedGraceEndsAt: string, expiredAt?: string): Promise<boolean>;
53
+ updateBillingSubscriptionChange(id: string, update: BillingSubscriptionChangeUpdate): Promise<void>;
54
+ getUserSubscription(userId: string, statuses?: string[]): Promise<BillingSubscriptionState | null>;
55
+ getUserSubscriptions(userId: string): Promise<BillingSubscriptionState[]>;
56
+ recordSubscriptionConflict(input: BillingSubscriptionConflictCreate): Promise<void>;
57
+ selectSubscriptionEntitlementSource(userId: string, provider: string, providerSubscriptionId?: string | null): Promise<boolean>;
58
+ private rowToTopup;
59
+ resolveCreditTopup(provider: string, productId?: string | null, priceId?: string | null): Promise<BillingTopupResult | null>;
60
+ resolveCreditTopupByLookup(provider: string, lookupKey: string): Promise<BillingTopupResult | null>;
61
+ computeTopupCredits(amountMinor: number, topupConfig: BillingTopupResult): Promise<number>;
62
+ upsertBillingPayment(options: BillingPaymentUpsert): Promise<string>;
63
+ createBillingCreditGrant(input: BillingCreditGrantCreate): Promise<string>;
64
+ grantBillingCredit(grantId: string, idempotencyKey: string): Promise<Record<string, unknown>>;
65
+ getBillingCreditGrantByPayment(paymentId: string): Promise<string | null>;
66
+ postBillingRefund(refundId: string, grantId: string, amountMinor: number, idempotencyKey: string): Promise<Record<string, unknown>>;
67
+ upsertBillingRefund(options: BillingRefundUpsert): Promise<string>;
68
+ upsertBillingInvoice(options: BillingInvoiceUpsert): Promise<void>;
69
+ listBillingInvoices(userId: string): Promise<import("../contracts.js").BillingInvoiceInfo[]>;
70
+ upsertBillingDispute(options: BillingDisputeUpsert): Promise<void>;
71
+ getBillingPayment(provider: string, providerPaymentId: string): Promise<Record<string, unknown> | null>;
72
+ private rowToSubscriptionState;
73
+ private getSubscriptionOfferContexts;
74
+ private rowToSubscriptionChange;
75
+ getActiveBursarConfig(): Promise<Record<string, unknown> | null>;
76
+ pseudonymizeFinancialSubject(userId: string): Promise<boolean>;
77
+ getBillingPreferences(userId: string): Promise<BillingPreferences | null>;
78
+ upsertBillingPreferences(prefs: BillingPreferences): Promise<void>;
79
+ getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null>;
80
+ upsertAutoRechargeProfile(profile: BillingAutoRechargeProfile, options?: {
81
+ resetCooldown?: boolean;
82
+ }): Promise<void>;
83
+ claimAutoRechargeAttempt(input: AutoRechargeAttemptClaim): Promise<BillingAutoRechargeAttempt | null>;
84
+ updateAutoRechargeAttempt(input: AutoRechargeAttemptUpdate): Promise<void>;
85
+ updateAutoRechargeAttemptByProviderPayment(input: AutoRechargeProviderPaymentUpdate): Promise<void>;
86
+ countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number>;
87
+ getBillingCustomerByUserId(userId: string, provider?: string | null): Promise<BillingCustomerRecord | null>;
88
+ }
89
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/billing/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,0BAA0B,EAC1B,0BAA0B,EAC1B,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,EAClB,yBAAyB,EACzB,8BAA8B,EAE9B,wBAAwB,EAExB,cAAc,EACd,kBAAkB,EACnB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EACV,wBAAwB,EACxB,yBAAyB,EACzB,iCAAiC,EACjC,wBAAwB,EACxB,oBAAoB,EACpB,oBAAoB,EACpB,oBAAoB,EACpB,mBAAmB,EACnB,+BAA+B,EAC/B,iCAAiC,EACjC,oBAAoB,EACpB,oBAAoB,EACrB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAEL,KAAK,yBAAyB,EAC9B,KAAK,YAAY,EAClB,MAAM,iCAAiC,CAAC;AAyBzC,MAAM,WAAW,2BAA4B,SAAQ,yBAAyB;IAC5E,qBAAqB,CAAC,EAAE,UAAU,GAAG,IAAI,CAAC;CAC3C;AAED,qBAAa,oBAAqB,SAAQ,YAAY;IACpD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAiB;IAE1C,OAAO,CAAC,MAAM,CAAuC;IACrD,OAAO,CAAC,MAAM,CAAuC;IACrD,OAAO,CAAC,SAAS,CAA0C;IAC3D,OAAO,CAAC,aAAa,CAA8C;IACnE,OAAO,CAAC,MAAM,CAAuC;IACrD,OAAO,CAAC,QAAQ,CAAyC;IACzD,OAAO,CAAC,OAAO,CAAwC;IACvD,OAAO,CAAC,QAAQ,CAAyC;IACzD,OAAO,CAAC,QAAQ,CAAyC;IACzD,OAAO,CAAC,YAAY,CAA6C;IACjE,OAAO,CAAC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,GAAG,IAAI,CAAC;IAIvC,yBAAyB,CAAC,KAAK,EAAE,yBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC;IAI1E,0CAA0C,CAC9C,KAAK,EAAE,iCAAiC,GACvC,OAAO,CAAC,IAAI,CAAC;IAIV,yBAAyB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC;IAIhF,0BAA0B,CAC9B,MAAM,EAAE,MAAM,EACd,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GACvB,OAAO,CAAC,qBAAqB,GAAG,IAAI,CAAC;CAQzC"}
@@ -0,0 +1,542 @@
1
+ import { BillingStore } from "../billing-store.js";
2
+ import { PostgresClient, } from "../../shared/postgres-client.js";
3
+ import { StoreClosedError } from "../../errors.js";
4
+ import { optionalBoundedDiagnosticMessage } from "../../shared/diagnostics.js";
5
+ import { BillingOfferRepository } from "./repositories/offer.js";
6
+ import { BillingTopupRepository } from "./repositories/topup.js";
7
+ import { BillingCustomerRepository } from "./repositories/customer.js";
8
+ import { BillingSubscriptionRepository } from "./repositories/subscription.js";
9
+ import { BillingEventRepository } from "./repositories/event.js";
10
+ import { BillingPaymentRepository } from "./repositories/payment.js";
11
+ import { BillingRefundRepository } from "./repositories/refund.js";
12
+ import { BillingInvoiceRepository } from "./repositories/invoice.js";
13
+ import { BillingDisputeRepository } from "./repositories/dispute.js";
14
+ import { BillingPreferencesRepository } from "./repositories/preferences.js";
15
+ import { BillingAutoRechargeRepository } from "./repositories/auto-recharge.js";
16
+ function toIso(value) {
17
+ if (!value)
18
+ return null;
19
+ if (typeof value === "string")
20
+ return value;
21
+ if (value instanceof Date)
22
+ return value.toISOString();
23
+ if (typeof value["toISOString"] === "function") {
24
+ return value.toISOString();
25
+ }
26
+ return String(value);
27
+ }
28
+ export class PostgresBillingStore extends BillingStore {
29
+ postgres;
30
+ _offer = null;
31
+ _topup = null;
32
+ _customer = null;
33
+ _subscription = null;
34
+ _event = null;
35
+ _payment = null;
36
+ _refund = null;
37
+ _invoice = null;
38
+ _dispute = null;
39
+ _preferences = null;
40
+ _autoRecharge = null;
41
+ constructor(poolOrUrl, tenantId, storageOptions) {
42
+ super();
43
+ this.postgres = new PostgresClient(poolOrUrl, {
44
+ tenantId,
45
+ billingPayloadBackend: storageOptions?.billingPayloadBackend,
46
+ connectionTimeoutMs: storageOptions?.connectionTimeoutMs,
47
+ statementTimeoutMs: storageOptions?.statementTimeoutMs,
48
+ idleTransactionTimeoutMs: storageOptions?.idleTransactionTimeoutMs,
49
+ idleTimeoutMs: storageOptions?.idleTimeoutMs,
50
+ maxConnections: storageOptions?.maxConnections,
51
+ applicationName: storageOptions?.applicationName,
52
+ onPoolError: storageOptions?.onPoolError,
53
+ closedError: () => new StoreClosedError("Billing store has been closed"),
54
+ });
55
+ }
56
+ async close() {
57
+ await this.postgres.close();
58
+ }
59
+ get queryFn() {
60
+ return this.postgres.query;
61
+ }
62
+ get billingOffer() {
63
+ if (!this._offer)
64
+ this._offer = new BillingOfferRepository(this.queryFn);
65
+ return this._offer;
66
+ }
67
+ get billingTopup() {
68
+ if (!this._topup)
69
+ this._topup = new BillingTopupRepository(this.queryFn);
70
+ return this._topup;
71
+ }
72
+ get billingCustomer() {
73
+ if (!this._customer)
74
+ this._customer = new BillingCustomerRepository(this.queryFn);
75
+ return this._customer;
76
+ }
77
+ get billingSubscription() {
78
+ if (!this._subscription)
79
+ this._subscription = new BillingSubscriptionRepository(this.queryFn);
80
+ return this._subscription;
81
+ }
82
+ get billingEvent() {
83
+ if (!this._event)
84
+ this._event = new BillingEventRepository(this.queryFn);
85
+ return this._event;
86
+ }
87
+ get billingPayment() {
88
+ if (!this._payment)
89
+ this._payment = new BillingPaymentRepository(this.queryFn);
90
+ return this._payment;
91
+ }
92
+ get billingRefund() {
93
+ if (!this._refund)
94
+ this._refund = new BillingRefundRepository(this.queryFn);
95
+ return this._refund;
96
+ }
97
+ get billingInvoice() {
98
+ if (!this._invoice)
99
+ this._invoice = new BillingInvoiceRepository(this.queryFn);
100
+ return this._invoice;
101
+ }
102
+ get billingDispute() {
103
+ if (!this._dispute)
104
+ this._dispute = new BillingDisputeRepository(this.queryFn);
105
+ return this._dispute;
106
+ }
107
+ get billingPreferences() {
108
+ if (!this._preferences)
109
+ this._preferences = new BillingPreferencesRepository(this.queryFn);
110
+ return this._preferences;
111
+ }
112
+ get billingAutoRecharge() {
113
+ if (!this._autoRecharge)
114
+ this._autoRecharge = new BillingAutoRechargeRepository(this.queryFn);
115
+ return this._autoRecharge;
116
+ }
117
+ async createOrGetCheckoutIntent(input) {
118
+ if (!/^[0-9a-fA-F]{64}$/.test(input.requestDigest)) {
119
+ throw new Error("requestDigest must be a 32-byte hex string");
120
+ }
121
+ const rows = await this.queryFn(`SELECT bursar.create_checkout_intent($1::uuid, $2, $3, $4, decode($5, 'hex'), $6::timestamptz) AS id`, [
122
+ input.subjectId,
123
+ input.provider,
124
+ input.checkoutKind,
125
+ input.productKey,
126
+ input.requestDigest,
127
+ input.expiresAt,
128
+ ]);
129
+ const id = rows[0]?.id;
130
+ if (!id)
131
+ throw new Error("checkout intent creation returned no ID");
132
+ const intent = await this.getCheckoutIntent(String(id), input.subjectId);
133
+ if (!intent)
134
+ throw new Error("checkout intent creation returned no row");
135
+ return intent;
136
+ }
137
+ async updateCheckoutIntent(id, update) {
138
+ const rows = await this.queryFn(`SELECT bursar.advance_checkout_intent($1::uuid, $2, $3, $4) AS advanced`, [id, update.status ?? null, update.providerSessionId ?? null, update.checkoutUrl ?? null]);
139
+ if (!rows[0]?.advanced) {
140
+ throw new Error(`checkout intent transition rejected: ${id}`);
141
+ }
142
+ }
143
+ async getCheckoutIntent(id, subjectId) {
144
+ const rows = await this.queryFn(`SELECT * FROM bursar.get_checkout_intent($1::uuid, $2::uuid)`, [id, subjectId]);
145
+ const row = rows[0];
146
+ return row?.id == null ? null : this.rowToCheckoutIntent(row);
147
+ }
148
+ rowToCheckoutIntent(row) {
149
+ return {
150
+ id: String(row.id),
151
+ subjectId: String(row.subject_id),
152
+ provider: String(row.provider),
153
+ checkoutKind: row.checkout_kind,
154
+ productKey: String(row.product_key),
155
+ requestDigest: Buffer.from(row.request_digest).toString("hex"),
156
+ status: row.status,
157
+ providerSessionId: row.provider_session_id == null ? null : String(row.provider_session_id),
158
+ checkoutUrl: row.checkout_url == null ? null : String(row.checkout_url),
159
+ expiresAt: toIso(row.expires_at) ?? new Date(0).toISOString(),
160
+ };
161
+ }
162
+ rowToOffer(row) {
163
+ if (!row?.offer_key || !row.id)
164
+ return null;
165
+ return {
166
+ offerId: String(row.id),
167
+ offerKey: String(row.offer_key),
168
+ planId: row.plan_id == null ? null : String(row.plan_id),
169
+ plan: row.plan == null ? null : String(row.plan),
170
+ interval: row.interval == null ? "month" : String(row.interval),
171
+ intervalCount: Number(row.interval_count ?? 1),
172
+ grant: {
173
+ mode: row.grant_mode == null ? undefined : String(row.grant_mode),
174
+ credits: row.grant_credits == null ? null : Number(row.grant_credits),
175
+ bucket: row.grant_bucket == null ? undefined : String(row.grant_bucket),
176
+ replacePrior: row.grant_replace_prior === true,
177
+ },
178
+ };
179
+ }
180
+ async resolveBillingOffer(provider, productId, priceId) {
181
+ const r = await this.billingOffer.resolveByPrice(provider, priceId ?? null, productId ?? null);
182
+ return this.rowToOffer(r);
183
+ }
184
+ async resolveBillingOfferByLookup(provider, lookupKey) {
185
+ const r = await this.billingOffer.resolveByLookup(provider, lookupKey);
186
+ return this.rowToOffer(r);
187
+ }
188
+ async claimBillingEvent(provider, eventId, eventType, envelope) {
189
+ const result = await this.billingEvent.claim(provider, eventId, eventType, JSON.stringify(envelope ?? { eventType }));
190
+ if (!result)
191
+ return { status: "retry" };
192
+ const r = result;
193
+ const s = r.status;
194
+ if (s === "claimed" && typeof r.claim_token === "string" && typeof r.event_id === "string") {
195
+ return {
196
+ status: "claimed",
197
+ claimToken: r.claim_token,
198
+ billingEventId: r.event_id,
199
+ };
200
+ }
201
+ if (s === "duplicate")
202
+ return { status: "duplicate" };
203
+ if (s === "busy")
204
+ return { status: "busy" };
205
+ return { status: "retry" };
206
+ }
207
+ async completeBillingEvent(provider, eventId, claimToken) {
208
+ return this.billingEvent.complete(provider, eventId, claimToken);
209
+ }
210
+ async failBillingEvent(provider, eventId, claimToken, error) {
211
+ return this.billingEvent.fail(provider, eventId, claimToken, optionalBoundedDiagnosticMessage(error) ?? undefined);
212
+ }
213
+ async upsertBillingCustomer(provider, providerCustomerId, userId, email) {
214
+ await this.billingCustomer.upsert(provider, providerCustomerId, userId, email ?? null);
215
+ }
216
+ async upsertBillingSubscription(state) {
217
+ await this.billingSubscription.upsert(state);
218
+ }
219
+ async getBillingCustomer(provider, providerCustomerId) {
220
+ return this.billingCustomer.get(provider, providerCustomerId);
221
+ }
222
+ async getBillingSubscription(provider, providerSubscriptionId) {
223
+ const r = await this.billingSubscription.get(provider, providerSubscriptionId);
224
+ if (!r)
225
+ return null;
226
+ return this.rowToSubscriptionState(r);
227
+ }
228
+ async createBillingSubscriptionChange(input) {
229
+ const subscription = await this.billingSubscription.get(input.provider, input.providerSubscriptionId);
230
+ if (!subscription?.id)
231
+ throw new Error("subscription change requires a persisted subscription");
232
+ const rows = await this.queryFn(`SELECT * FROM bursar.open_subscription_change(
233
+ $1::uuid, $2::uuid, $3::timestamptz, $4, $5, $6
234
+ )`, [
235
+ subscription.id,
236
+ input.toOfferId,
237
+ input.effectiveAt,
238
+ input.effective,
239
+ input.idempotencyKey,
240
+ input.prorationBehavior ?? "provider_default",
241
+ ]);
242
+ const result = rows[0] ?? {};
243
+ if (result.error_code)
244
+ throw new Error(`subscription change: ${String(result.error_code)}`);
245
+ const changeRows = await this.queryFn(`SELECT * FROM bursar.get_billing_subscription_change($1::bigint)`, [result.change_id]);
246
+ if (changeRows[0]?.id == null) {
247
+ throw new Error("subscription change creation returned no row");
248
+ }
249
+ return this.rowToSubscriptionChange(changeRows[0]);
250
+ }
251
+ async getOpenBillingSubscriptionChange(provider, providerSubscriptionId) {
252
+ const rows = await this.queryFn(`SELECT * FROM bursar.get_open_billing_subscription_change($1, $2)`, [provider, providerSubscriptionId]);
253
+ const row = rows[0];
254
+ return row?.id == null ? null : this.rowToSubscriptionChange(row);
255
+ }
256
+ async listExpiredGraceSubscriptions(now, limit = 100) {
257
+ const rows = await this.billingSubscription.listExpiredGraceSubscriptions(now, limit);
258
+ return rows.map((row) => this.rowToSubscriptionState(row));
259
+ }
260
+ async markSubscriptionGraceExpired(subscriptionId, expectedGraceEndsAt, expiredAt = new Date().toISOString()) {
261
+ return this.billingSubscription.markGraceExpired(subscriptionId, expectedGraceEndsAt, expiredAt);
262
+ }
263
+ async updateBillingSubscriptionChange(id, update) {
264
+ if (!update.state)
265
+ return;
266
+ const rows = await this.queryFn(`SELECT bursar.advance_subscription_change($1::bigint, $2, $3, $4) AS advanced`, [
267
+ id,
268
+ update.state,
269
+ update.providerOperationId ?? null,
270
+ optionalBoundedDiagnosticMessage(update.errorMessage),
271
+ ]);
272
+ if (!rows[0]?.advanced) {
273
+ throw new Error(`subscription change transition rejected: ${id}`);
274
+ }
275
+ }
276
+ async getUserSubscription(userId, statuses) {
277
+ const r = await this.billingSubscription.getUserSubscription(userId, statuses);
278
+ if (!r)
279
+ return null;
280
+ return this.rowToSubscriptionState(r);
281
+ }
282
+ async getUserSubscriptions(userId) {
283
+ const rows = await this.billingSubscription.getUserSubscriptions(userId);
284
+ return rows.map((r) => this.rowToSubscriptionState(r));
285
+ }
286
+ async recordSubscriptionConflict(input) {
287
+ await this.billingSubscription.recordConflict(input);
288
+ }
289
+ async selectSubscriptionEntitlementSource(userId, provider, providerSubscriptionId) {
290
+ return this.billingSubscription.selectEntitlementSource(userId, provider, providerSubscriptionId);
291
+ }
292
+ rowToTopup(r) {
293
+ if (!r?.topup_key || !r.id)
294
+ return null;
295
+ return {
296
+ topupId: String(r.id),
297
+ topupKey: r.topup_key,
298
+ creditsPerUnit: Number(r.credits_per_unit ?? r.credits_per_major_unit ?? 1000),
299
+ depositTo: r.bucket_key || "purchased",
300
+ amountMinor: r.amount_minor == null ? undefined : Number(r.amount_minor),
301
+ currency: r.currency == null ? undefined : String(r.currency),
302
+ minQuantity: r.min_quantity == null ? undefined : Number(r.min_quantity),
303
+ maxQuantity: r.max_quantity == null ? undefined : Number(r.max_quantity),
304
+ defaultQuantity: r.default_quantity == null ? undefined : Number(r.default_quantity),
305
+ minAmountMinor: r.amount_minor == null ? undefined : Number(r.amount_minor) * Number(r.min_quantity ?? 1),
306
+ maxAmountMinor: r.amount_minor == null ? undefined : Number(r.amount_minor) * Number(r.max_quantity ?? 1),
307
+ };
308
+ }
309
+ async resolveCreditTopup(provider, productId, priceId) {
310
+ const r = await this.billingTopup.resolveByPrice(provider, priceId ?? null, productId ?? null);
311
+ return this.rowToTopup(r);
312
+ }
313
+ async resolveCreditTopupByLookup(provider, lookupKey) {
314
+ const r = await this.billingTopup.resolveByLookup(provider, lookupKey);
315
+ return this.rowToTopup(r);
316
+ }
317
+ async computeTopupCredits(amountMinor, topupConfig) {
318
+ const unitAmount = topupConfig.amountMinor;
319
+ const creditsPer = topupConfig.creditsPerUnit ?? 0;
320
+ if (!unitAmount || amountMinor % unitAmount !== 0)
321
+ return 0;
322
+ const quantity = amountMinor / unitAmount;
323
+ if (quantity < (topupConfig.minQuantity ?? 1) || quantity > (topupConfig.maxQuantity ?? 1)) {
324
+ return 0;
325
+ }
326
+ return quantity * creditsPer;
327
+ }
328
+ async upsertBillingPayment(options) {
329
+ return this.billingPayment.upsert(options.provider, options.providerPaymentId, options.providerInvoiceId ?? null, options.userId ?? null, options.amountMinor ?? 0, options.taxMinor ?? null, options.currency ?? "USD", options.purpose ?? null, options.metadata ? JSON.stringify(options.metadata) : null, options.status ?? "succeeded", options.providerUpdatedAt ?? new Date().toISOString());
330
+ }
331
+ async createBillingCreditGrant(input) {
332
+ const rows = await this.queryFn("SELECT bursar.create_billing_credit_grant($1::uuid, $2::uuid, $3::uuid, $4, $5, $6::uuid) AS id", [
333
+ input.paymentId ?? null,
334
+ input.subscriptionId ?? null,
335
+ input.topupId ?? null,
336
+ input.configuredCredits,
337
+ input.quantity ?? 1,
338
+ input.billingEventId ?? null,
339
+ ]);
340
+ const id = rows[0]?.id;
341
+ if (!id)
342
+ throw new Error("billing credit grant creation returned no ID");
343
+ return String(id);
344
+ }
345
+ async grantBillingCredit(grantId, idempotencyKey) {
346
+ const rows = await this.queryFn("SELECT * FROM bursar.grant_billing_credit($1::uuid, $2)", [
347
+ grantId,
348
+ idempotencyKey,
349
+ ]);
350
+ return rows[0] ?? {};
351
+ }
352
+ async getBillingCreditGrantByPayment(paymentId) {
353
+ const rows = await this.queryFn(`SELECT * FROM bursar.get_billing_credit_grant_by_payment($1::uuid)`, [paymentId]);
354
+ const id = rows[0]?.id;
355
+ return id ? String(id) : null;
356
+ }
357
+ async postBillingRefund(refundId, grantId, amountMinor, idempotencyKey) {
358
+ const rows = await this.queryFn("SELECT * FROM bursar.post_billing_refund($1::uuid, $2::uuid, $3, $4)", [refundId, grantId, amountMinor, idempotencyKey]);
359
+ return rows[0] ?? {};
360
+ }
361
+ async upsertBillingRefund(options) {
362
+ return this.billingRefund.upsert(options.provider, options.providerRefundId, options.providerPaymentId ?? null, options.userId ?? null, options.amountMinor ?? 0, options.currency ?? "USD", options.reason ?? null, options.metadata ? JSON.stringify(options.metadata) : null, options.status ?? "pending", options.providerUpdatedAt ?? new Date().toISOString());
363
+ }
364
+ async upsertBillingInvoice(options) {
365
+ const subscription = options.providerSubscriptionId
366
+ ? await this.billingSubscription.get(options.provider, options.providerSubscriptionId)
367
+ : null;
368
+ const subjectId = options.userId ?? (subscription?.subject_id ? String(subscription.subject_id) : null);
369
+ if (!subjectId)
370
+ throw new Error("invoice subject is required");
371
+ await this.billingInvoice.upsert(subjectId, options.provider, options.providerInvoiceId, subscription?.id ? String(subscription.id) : null, options.status ?? null, options.amountDueMinor ?? null, options.amountPaidMinor ?? null, options.currency ?? "USD", options.periodStart ?? null, options.periodEnd ?? null, options.metadata ?? {}, options.providerUpdatedAt ?? new Date().toISOString());
372
+ }
373
+ async listBillingInvoices(userId) {
374
+ return this.billingInvoice.listForUser(userId);
375
+ }
376
+ async upsertBillingDispute(options) {
377
+ const payment = options.providerPaymentId
378
+ ? await this.billingPayment.getForRefund(options.provider, options.providerPaymentId)
379
+ : null;
380
+ if (!payment?.id)
381
+ throw new Error("dispute payment is required");
382
+ await this.billingDispute.upsert(options.provider, options.providerDisputeId, String(payment.id), options.status ?? "needs_response", options.reason ?? null, options.metadata ?? {}, options.providerUpdatedAt ?? new Date().toISOString());
383
+ }
384
+ async getBillingPayment(provider, providerPaymentId) {
385
+ const result = await this.billingPayment.getForRefund(provider, providerPaymentId);
386
+ if (!result)
387
+ return null;
388
+ const row = result;
389
+ return {
390
+ id: row.id,
391
+ provider: row.provider,
392
+ providerPaymentId: row.provider_payment_id,
393
+ providerInvoiceId: row.provider_invoice_id,
394
+ userId: row.subject_id,
395
+ amountMinor: row.amount_minor == null ? null : Number(row.amount_minor),
396
+ taxMinor: row.tax_minor == null ? null : Number(row.tax_minor),
397
+ currency: row.currency,
398
+ purpose: row.purpose,
399
+ status: row.status,
400
+ providerUpdatedAt: toIso(row.provider_updated_at),
401
+ metadata: row.metadata,
402
+ };
403
+ }
404
+ rowToSubscriptionState(r) {
405
+ return {
406
+ subscriptionId: r.id ? String(r.id) : null,
407
+ userId: String(r.user_id),
408
+ provider: String(r.provider),
409
+ providerSubscriptionId: String(r.provider_subscription_id),
410
+ providerCustomerId: r.provider_customer_id ? String(r.provider_customer_id) : null,
411
+ offerId: r.offer_id ? String(r.offer_id) : null,
412
+ offerKey: r.offer_key ? String(r.offer_key) : null,
413
+ plan: r.plan ? String(r.plan) : null,
414
+ status: (r.status ? String(r.status) : "incomplete"),
415
+ currentPeriodStart: toIso(r.current_period_start),
416
+ currentPeriodEnd: toIso(r.current_period_end),
417
+ trialEnd: toIso(r.trial_end),
418
+ cancelAt: toIso(r.cancel_at),
419
+ endedAt: toIso(r.ended_at),
420
+ graceEndsAt: toIso(r.grace_ends_at),
421
+ graceExpiredAt: toIso(r.grace_expired_at),
422
+ providerUpdatedAt: toIso(r.provider_updated_at),
423
+ cancelAtPeriodEnd: Boolean(r.cancel_at_period_end),
424
+ interval: r.interval ? String(r.interval) : null,
425
+ intervalCount: r.interval_count ? Number(r.interval_count) : null,
426
+ metadata: r.metadata && typeof r.metadata === "object"
427
+ ? r.metadata
428
+ : null,
429
+ };
430
+ }
431
+ async getSubscriptionOfferContexts(r) {
432
+ const rows = await this.queryFn(`SELECT requested.side, requested.offer_id, context.*
433
+ FROM (
434
+ VALUES
435
+ ('from', $1::uuid, $2::uuid),
436
+ ('to', $3::uuid, $4::uuid)
437
+ ) AS requested(side, offer_id, catalog_revision_id)
438
+ CROSS JOIN LATERAL bursar.get_catalog_offer_context(
439
+ requested.offer_id,
440
+ requested.catalog_revision_id
441
+ ) AS context`, [r.from_offer_id, r.from_catalog_revision_id, r.to_offer_id, r.to_catalog_revision_id]);
442
+ const bySide = new Map(rows.map((row) => {
443
+ const context = row;
444
+ return [String(context.side), context];
445
+ }));
446
+ const mapContext = (side) => {
447
+ const context = bySide.get(side);
448
+ if (context?.offer_key == null) {
449
+ throw new Error(`subscription change ${side}-offer context not found`);
450
+ }
451
+ return {
452
+ offerId: String(context.offer_id),
453
+ offerKey: String(context.offer_key),
454
+ planId: context.plan_id ? String(context.plan_id) : null,
455
+ plan: context.plan_key ? String(context.plan_key) : null,
456
+ interval: context.billing_unit ? String(context.billing_unit) : null,
457
+ intervalCount: context.billing_count == null ? null : Number(context.billing_count),
458
+ };
459
+ };
460
+ return { fromOffer: mapContext("from"), toOffer: mapContext("to") };
461
+ }
462
+ async rowToSubscriptionChange(r) {
463
+ const { fromOffer, toOffer } = await this.getSubscriptionOfferContexts(r);
464
+ return {
465
+ id: String(r.id),
466
+ subscriptionId: String(r.subscription_id),
467
+ fromOfferId: String(r.from_offer_id),
468
+ toOfferId: String(r.to_offer_id),
469
+ fromOffer,
470
+ toOffer,
471
+ effectiveAt: toIso(r.effective_at),
472
+ effective: String(r.effective_behavior),
473
+ state: String(r.state),
474
+ prorationBehavior: String(r.proration_behavior),
475
+ idempotencyKey: String(r.idempotency_key),
476
+ providerOperationId: r.provider_operation_id ? String(r.provider_operation_id) : null,
477
+ errorMessage: r.error_message ? String(r.error_message) : null,
478
+ };
479
+ }
480
+ async getActiveBursarConfig() {
481
+ const rows = await this.queryFn("SELECT * FROM bursar.active_catalog_revision()", []);
482
+ if (!rows || rows.length === 0)
483
+ return null;
484
+ return (rows[0]?.source_document ??
485
+ null);
486
+ }
487
+ async pseudonymizeFinancialSubject(userId) {
488
+ const rows = await this.queryFn(`SELECT bursar.pseudonymize_financial_subject($1::uuid) AS pseudonymized`, [userId]);
489
+ return rows[0]?.pseudonymized === true;
490
+ }
491
+ async getBillingPreferences(userId) {
492
+ const row = await this.billingPreferences.get(userId);
493
+ if (!row || row.subject_id == null)
494
+ return null;
495
+ return {
496
+ userId: String(row.subject_id),
497
+ autoRecharge: Boolean(row.auto_recharge),
498
+ overageProtection: Boolean(row.overage_protection),
499
+ emailNotifications: Boolean(row.email_notifications),
500
+ usageAlerts: Boolean(row.usage_alerts),
501
+ invoiceReminders: Boolean(row.invoice_reminders),
502
+ };
503
+ }
504
+ async upsertBillingPreferences(prefs) {
505
+ await this.billingPreferences.upsert({
506
+ userId: prefs.userId,
507
+ autoRecharge: prefs.autoRecharge,
508
+ overageProtection: prefs.overageProtection,
509
+ emailNotifications: prefs.emailNotifications,
510
+ usageAlerts: prefs.usageAlerts,
511
+ invoiceReminders: prefs.invoiceReminders,
512
+ });
513
+ }
514
+ async getAutoRechargeProfile(userId) {
515
+ return this.billingAutoRecharge.getProfile(userId);
516
+ }
517
+ async upsertAutoRechargeProfile(profile, options) {
518
+ return this.billingAutoRecharge.upsertProfile(profile, options);
519
+ }
520
+ async claimAutoRechargeAttempt(input) {
521
+ return this.billingAutoRecharge.claimAttempt(input);
522
+ }
523
+ async updateAutoRechargeAttempt(input) {
524
+ return this.billingAutoRecharge.updateAttempt(input);
525
+ }
526
+ async updateAutoRechargeAttemptByProviderPayment(input) {
527
+ return this.billingAutoRecharge.updateAttemptByProviderPayment(input);
528
+ }
529
+ async countAutoRechargeAttempts(userId, since) {
530
+ return this.billingAutoRecharge.countAttempts(userId, since);
531
+ }
532
+ async getBillingCustomerByUserId(userId, provider) {
533
+ const result = await this.billingCustomer.getByUserId(userId, provider ?? null);
534
+ if (!result)
535
+ return null;
536
+ return {
537
+ provider: result.provider,
538
+ providerCustomerId: result.providerCustomerId,
539
+ };
540
+ }
541
+ }
542
+ //# sourceMappingURL=store.js.map