@zonastery/bursar 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (404) hide show
  1. package/README.md +189 -62
  2. package/dist/billing/auto-recharge-port.d.ts +3 -3
  3. package/dist/billing/auto-recharge-port.d.ts.map +1 -1
  4. package/dist/billing/auto-recharge-port.js.map +1 -1
  5. package/dist/billing/auto-recharge-service.d.ts +5 -4
  6. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  7. package/dist/billing/auto-recharge-service.js +64 -34
  8. package/dist/billing/auto-recharge-service.js.map +1 -1
  9. package/dist/billing/billing-service.d.ts +5 -5
  10. package/dist/billing/billing-service.d.ts.map +1 -1
  11. package/dist/billing/billing-service.js +2 -2
  12. package/dist/billing/billing-service.js.map +1 -1
  13. package/dist/billing/billing-store.d.ts +10 -9
  14. package/dist/billing/billing-store.d.ts.map +1 -1
  15. package/dist/billing/billing-store.js.map +1 -1
  16. package/dist/billing/contracts.d.ts +31 -31
  17. package/dist/billing/contracts.d.ts.map +1 -1
  18. package/dist/billing/contracts.js.map +1 -1
  19. package/dist/billing/event-handlers.d.ts.map +1 -1
  20. package/dist/billing/event-handlers.js +49 -10
  21. package/dist/billing/event-handlers.js.map +1 -1
  22. package/dist/billing/event-processor.d.ts +1 -0
  23. package/dist/billing/event-processor.d.ts.map +1 -1
  24. package/dist/billing/event-processor.js +37 -10
  25. package/dist/billing/event-processor.js.map +1 -1
  26. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  27. package/dist/billing/financial-event-handlers.js +69 -72
  28. package/dist/billing/financial-event-handlers.js.map +1 -1
  29. package/dist/billing/index.d.ts +2 -1
  30. package/dist/billing/index.d.ts.map +1 -1
  31. package/dist/billing/index.js.map +1 -1
  32. package/dist/billing/management.d.ts +5 -5
  33. package/dist/billing/management.d.ts.map +1 -1
  34. package/dist/billing/management.js +2 -2
  35. package/dist/billing/management.js.map +1 -1
  36. package/dist/billing/policy-window.js.map +1 -1
  37. package/dist/billing/postgres/repositories/auto-recharge.d.ts +3 -3
  38. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  39. package/dist/billing/postgres/repositories/auto-recharge.js +205 -60
  40. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  41. package/dist/billing/postgres/repositories/customer.d.ts.map +1 -1
  42. package/dist/billing/postgres/repositories/customer.js +19 -11
  43. package/dist/billing/postgres/repositories/customer.js.map +1 -1
  44. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
  45. package/dist/billing/postgres/repositories/dispute.js +3 -1
  46. package/dist/billing/postgres/repositories/dispute.js.map +1 -1
  47. package/dist/billing/postgres/repositories/event.d.ts +14 -7
  48. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  49. package/dist/billing/postgres/repositories/event.js +21 -20
  50. package/dist/billing/postgres/repositories/event.js.map +1 -1
  51. package/dist/billing/postgres/repositories/invoice.d.ts +3 -3
  52. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  53. package/dist/billing/postgres/repositories/invoice.js +53 -11
  54. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  55. package/dist/billing/postgres/repositories/offer.d.ts +20 -17
  56. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  57. package/dist/billing/postgres/repositories/offer.js +123 -57
  58. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  59. package/dist/billing/postgres/repositories/payment.d.ts +23 -20
  60. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  61. package/dist/billing/postgres/repositories/payment.js +43 -37
  62. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  63. package/dist/billing/postgres/repositories/preferences.d.ts +3 -9
  64. package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -1
  65. package/dist/billing/postgres/repositories/preferences.js +45 -7
  66. package/dist/billing/postgres/repositories/preferences.js.map +1 -1
  67. package/dist/billing/postgres/repositories/refund.d.ts +1 -1
  68. package/dist/billing/postgres/repositories/refund.d.ts.map +1 -1
  69. package/dist/billing/postgres/repositories/refund.js +13 -9
  70. package/dist/billing/postgres/repositories/refund.js.map +1 -1
  71. package/dist/billing/postgres/repositories/subscription-change.d.ts +15 -0
  72. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -0
  73. package/dist/billing/postgres/repositories/subscription-change.js +234 -0
  74. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -0
  75. package/dist/billing/postgres/repositories/subscription.d.ts +38 -17
  76. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  77. package/dist/billing/postgres/repositories/subscription.js +199 -91
  78. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  79. package/dist/billing/postgres/repositories/topup.d.ts +13 -15
  80. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  81. package/dist/billing/postgres/repositories/topup.js +65 -34
  82. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  83. package/dist/billing/postgres/store.d.ts +23 -14
  84. package/dist/billing/postgres/store.d.ts.map +1 -1
  85. package/dist/billing/postgres/store.js +265 -228
  86. package/dist/billing/postgres/store.js.map +1 -1
  87. package/dist/billing/service-types.d.ts +6 -5
  88. package/dist/billing/service-types.d.ts.map +1 -1
  89. package/dist/billing/service-types.js.map +1 -1
  90. package/dist/billing/types/auto-recharge.d.ts +6 -4
  91. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  92. package/dist/billing/types/auto-recharge.js.map +1 -1
  93. package/dist/billing/types/catalog.d.ts +18 -35
  94. package/dist/billing/types/catalog.d.ts.map +1 -1
  95. package/dist/billing/types/catalog.js.map +1 -1
  96. package/dist/billing/types/common.d.ts +0 -1
  97. package/dist/billing/types/common.d.ts.map +1 -1
  98. package/dist/billing/types/common.js.map +1 -1
  99. package/dist/billing/types/documents.d.ts +38 -12
  100. package/dist/billing/types/documents.d.ts.map +1 -1
  101. package/dist/billing/types/documents.js.map +1 -1
  102. package/dist/billing/types/events.d.ts +2 -0
  103. package/dist/billing/types/events.d.ts.map +1 -1
  104. package/dist/billing/types/events.js +238 -0
  105. package/dist/billing/types/events.js.map +1 -1
  106. package/dist/billing/types/index.js.map +1 -1
  107. package/dist/billing/types/preferences.js.map +1 -1
  108. package/dist/billing/types/subscriptions.d.ts +8 -8
  109. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  110. package/dist/billing/types/subscriptions.js.map +1 -1
  111. package/dist/breakdown.js.map +1 -1
  112. package/dist/browser.js.map +1 -1
  113. package/dist/bursar.d.ts +33 -11
  114. package/dist/bursar.d.ts.map +1 -1
  115. package/dist/bursar.js +58 -22
  116. package/dist/bursar.js.map +1 -1
  117. package/dist/catalog.d.ts +1 -0
  118. package/dist/catalog.d.ts.map +1 -1
  119. package/dist/catalog.js +1 -0
  120. package/dist/catalog.js.map +1 -1
  121. package/dist/commerce/errors.d.ts +4 -14
  122. package/dist/commerce/errors.d.ts.map +1 -1
  123. package/dist/commerce/errors.js +4 -21
  124. package/dist/commerce/errors.js.map +1 -1
  125. package/dist/commerce/index.d.ts +1 -0
  126. package/dist/commerce/index.d.ts.map +1 -1
  127. package/dist/commerce/index.js.map +1 -1
  128. package/dist/commerce/plan-change.js.map +1 -1
  129. package/dist/commerce/provider-registry.d.ts.map +1 -1
  130. package/dist/commerce/provider-registry.js +27 -2
  131. package/dist/commerce/provider-registry.js.map +1 -1
  132. package/dist/commerce/service.d.ts +15 -7
  133. package/dist/commerce/service.d.ts.map +1 -1
  134. package/dist/commerce/service.js +130 -77
  135. package/dist/commerce/service.js.map +1 -1
  136. package/dist/commerce/types.d.ts +33 -13
  137. package/dist/commerce/types.d.ts.map +1 -1
  138. package/dist/commerce/types.js.map +1 -1
  139. package/dist/config/parse-access.js.map +1 -1
  140. package/dist/config/parse-commerce.js.map +1 -1
  141. package/dist/config/parse-credits.js.map +1 -1
  142. package/dist/config/parse-plans.d.ts.map +1 -1
  143. package/dist/config/parse-plans.js +30 -13
  144. package/dist/config/parse-plans.js.map +1 -1
  145. package/dist/config/parse-pricing.d.ts.map +1 -1
  146. package/dist/config/parse-pricing.js +16 -5
  147. package/dist/config/parse-pricing.js.map +1 -1
  148. package/dist/config/parse-utils.js.map +1 -1
  149. package/dist/config/types.d.ts +14 -1
  150. package/dist/config/types.d.ts.map +1 -1
  151. package/dist/config/types.js.map +1 -1
  152. package/dist/config.d.ts +7 -1
  153. package/dist/config.d.ts.map +1 -1
  154. package/dist/config.js +64 -1
  155. package/dist/config.js.map +1 -1
  156. package/dist/credits/{pricing-runtime.d.ts → catalog-runtime.d.ts} +9 -8
  157. package/dist/credits/catalog-runtime.d.ts.map +1 -0
  158. package/dist/credits/{pricing-runtime.js → catalog-runtime.js} +58 -38
  159. package/dist/credits/catalog-runtime.js.map +1 -0
  160. package/dist/credits/events.d.ts +4 -4
  161. package/dist/credits/events.d.ts.map +1 -1
  162. package/dist/credits/events.js +1 -1
  163. package/dist/credits/events.js.map +1 -1
  164. package/dist/credits/lease-workflow.d.ts +14 -14
  165. package/dist/credits/lease-workflow.d.ts.map +1 -1
  166. package/dist/credits/lease-workflow.js +18 -17
  167. package/dist/credits/lease-workflow.js.map +1 -1
  168. package/dist/credits/low-balance-monitor.d.ts +2 -2
  169. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  170. package/dist/credits/low-balance-monitor.js.map +1 -1
  171. package/dist/credits/postgres/repositories/analytics.d.ts +39 -35
  172. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  173. package/dist/credits/postgres/repositories/analytics.js +55 -53
  174. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  175. package/dist/credits/postgres/repositories/balance.d.ts +28 -30
  176. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  177. package/dist/credits/postgres/repositories/balance.js +100 -59
  178. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  179. package/dist/credits/postgres/repositories/bucket.d.ts +14 -8
  180. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
  181. package/dist/credits/postgres/repositories/bucket.js +22 -21
  182. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  183. package/dist/credits/postgres/repositories/catalog.d.ts +31 -0
  184. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -0
  185. package/dist/credits/postgres/repositories/catalog.js +90 -0
  186. package/dist/credits/postgres/repositories/catalog.js.map +1 -0
  187. package/dist/credits/postgres/repositories/deduction.d.ts +32 -21
  188. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  189. package/dist/credits/postgres/repositories/deduction.js +171 -62
  190. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  191. package/dist/credits/postgres/repositories/lease.d.ts +21 -18
  192. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  193. package/dist/credits/postgres/repositories/lease.js +157 -65
  194. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  195. package/dist/credits/postgres/repositories/plan.d.ts +94 -42
  196. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
  197. package/dist/credits/postgres/repositories/plan.js +134 -104
  198. package/dist/credits/postgres/repositories/plan.js.map +1 -1
  199. package/dist/credits/postgres/repositories/team.d.ts +36 -27
  200. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  201. package/dist/credits/postgres/repositories/team.js +96 -52
  202. package/dist/credits/postgres/repositories/team.js.map +1 -1
  203. package/dist/credits/postgres/store.d.ts +31 -21
  204. package/dist/credits/postgres/store.d.ts.map +1 -1
  205. package/dist/credits/postgres/store.js +325 -235
  206. package/dist/credits/postgres/store.js.map +1 -1
  207. package/dist/credits/postgres/value-mappers.d.ts +7 -9
  208. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  209. package/dist/credits/postgres/value-mappers.js +42 -63
  210. package/dist/credits/postgres/value-mappers.js.map +1 -1
  211. package/dist/credits/queries.d.ts +5 -5
  212. package/dist/credits/queries.d.ts.map +1 -1
  213. package/dist/credits/queries.js +4 -4
  214. package/dist/credits/queries.js.map +1 -1
  215. package/dist/credits/service-errors.js.map +1 -1
  216. package/dist/credits/service-types.d.ts +42 -7
  217. package/dist/credits/service-types.d.ts.map +1 -1
  218. package/dist/credits/service-types.js.map +1 -1
  219. package/dist/credits/service.d.ts +51 -58
  220. package/dist/credits/service.d.ts.map +1 -1
  221. package/dist/credits/service.js +178 -113
  222. package/dist/credits/service.js.map +1 -1
  223. package/dist/credits/store.d.ts +25 -22
  224. package/dist/credits/store.d.ts.map +1 -1
  225. package/dist/credits/store.js +9 -5
  226. package/dist/credits/store.js.map +1 -1
  227. package/dist/credits/types/account.d.ts +50 -12
  228. package/dist/credits/types/account.d.ts.map +1 -1
  229. package/dist/credits/types/account.js.map +1 -1
  230. package/dist/credits/types/admission.d.ts +17 -6
  231. package/dist/credits/types/admission.d.ts.map +1 -1
  232. package/dist/credits/types/admission.js.map +1 -1
  233. package/dist/credits/types/analytics.d.ts +2 -2
  234. package/dist/credits/types/analytics.d.ts.map +1 -1
  235. package/dist/credits/types/analytics.js.map +1 -1
  236. package/dist/credits/types/catalog.d.ts +21 -14
  237. package/dist/credits/types/catalog.d.ts.map +1 -1
  238. package/dist/credits/types/catalog.js.map +1 -1
  239. package/dist/credits/types/grants.d.ts +22 -8
  240. package/dist/credits/types/grants.d.ts.map +1 -1
  241. package/dist/credits/types/grants.js.map +1 -1
  242. package/dist/credits/types/index.js.map +1 -1
  243. package/dist/credits/types/ledger.d.ts +19 -0
  244. package/dist/credits/types/ledger.d.ts.map +1 -1
  245. package/dist/credits/types/ledger.js.map +1 -1
  246. package/dist/credits/types/quotas.js.map +1 -1
  247. package/dist/credits/types/teams.d.ts +18 -6
  248. package/dist/credits/types/teams.d.ts.map +1 -1
  249. package/dist/credits/types/teams.js.map +1 -1
  250. package/dist/engine.d.ts.map +1 -1
  251. package/dist/engine.js +24 -10
  252. package/dist/engine.js.map +1 -1
  253. package/dist/errors.d.ts +105 -8
  254. package/dist/errors.d.ts.map +1 -1
  255. package/dist/errors.js +137 -9
  256. package/dist/errors.js.map +1 -1
  257. package/dist/expr/ast.d.ts.map +1 -1
  258. package/dist/expr/ast.js.map +1 -1
  259. package/dist/expr/evaluator.d.ts.map +1 -1
  260. package/dist/expr/evaluator.js +29 -17
  261. package/dist/expr/evaluator.js.map +1 -1
  262. package/dist/expr/language.js.map +1 -1
  263. package/dist/expr/parser.d.ts.map +1 -1
  264. package/dist/expr/parser.js +11 -4
  265. package/dist/expr/parser.js.map +1 -1
  266. package/dist/expr/tokenizer.d.ts.map +1 -1
  267. package/dist/expr/tokenizer.js +17 -13
  268. package/dist/expr/tokenizer.js.map +1 -1
  269. package/dist/expr.d.ts +2 -2
  270. package/dist/expr.d.ts.map +1 -1
  271. package/dist/expr.js +7 -9
  272. package/dist/expr.js.map +1 -1
  273. package/dist/generated/pricing-config.schema.json +30 -9
  274. package/dist/generated/pricing-config.types.d.ts +14 -3
  275. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  276. package/dist/generated/pricing-config.types.js.map +1 -1
  277. package/dist/index.d.ts +11 -7
  278. package/dist/index.d.ts.map +1 -1
  279. package/dist/index.js +2 -2
  280. package/dist/index.js.map +1 -1
  281. package/dist/integrations/better-auth.d.ts +23 -0
  282. package/dist/integrations/better-auth.d.ts.map +1 -0
  283. package/dist/integrations/better-auth.js +54 -0
  284. package/dist/integrations/better-auth.js.map +1 -0
  285. package/dist/{load-pricing-file.d.ts → load-config-file.d.ts} +4 -4
  286. package/dist/load-config-file.d.ts.map +1 -0
  287. package/dist/{load-pricing-file.js → load-config-file.js} +23 -14
  288. package/dist/load-config-file.js.map +1 -0
  289. package/dist/metrics.js.map +1 -1
  290. package/dist/node.d.ts +3 -3
  291. package/dist/node.d.ts.map +1 -1
  292. package/dist/node.js +2 -2
  293. package/dist/node.js.map +1 -1
  294. package/dist/providers/_shared.d.ts +5 -0
  295. package/dist/providers/_shared.d.ts.map +1 -1
  296. package/dist/providers/_shared.js +77 -14
  297. package/dist/providers/_shared.js.map +1 -1
  298. package/dist/providers/dodo/better-auth.d.ts +29 -0
  299. package/dist/providers/dodo/better-auth.d.ts.map +1 -0
  300. package/dist/providers/dodo/better-auth.js +23 -0
  301. package/dist/providers/dodo/better-auth.js.map +1 -0
  302. package/dist/providers/dodo/client-contract.d.ts +32 -70
  303. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  304. package/dist/providers/dodo/client-contract.js.map +1 -1
  305. package/dist/providers/dodo/event-mapper.d.ts +3 -1
  306. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  307. package/dist/providers/dodo/event-mapper.js +219 -148
  308. package/dist/providers/dodo/event-mapper.js.map +1 -1
  309. package/dist/providers/dodo/index.d.ts +5 -2
  310. package/dist/providers/dodo/index.d.ts.map +1 -1
  311. package/dist/providers/dodo/index.js +2 -1
  312. package/dist/providers/dodo/index.js.map +1 -1
  313. package/dist/providers/dodo/nextjs.d.ts +16 -0
  314. package/dist/providers/dodo/nextjs.d.ts.map +1 -0
  315. package/dist/providers/dodo/nextjs.js +16 -0
  316. package/dist/providers/dodo/nextjs.js.map +1 -0
  317. package/dist/providers/dodo/provider.d.ts +30 -11
  318. package/dist/providers/dodo/provider.d.ts.map +1 -1
  319. package/dist/providers/dodo/provider.js +192 -122
  320. package/dist/providers/dodo/provider.js.map +1 -1
  321. package/dist/providers/dodo/react-native.d.ts +56 -0
  322. package/dist/providers/dodo/react-native.d.ts.map +1 -0
  323. package/dist/providers/dodo/react-native.js +57 -0
  324. package/dist/providers/dodo/react-native.js.map +1 -0
  325. package/dist/providers/dodo/webhook-bridge.d.ts +17 -0
  326. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -0
  327. package/dist/providers/dodo/webhook-bridge.js +21 -0
  328. package/dist/providers/dodo/webhook-bridge.js.map +1 -0
  329. package/dist/providers/index.d.ts +1 -1
  330. package/dist/providers/index.d.ts.map +1 -1
  331. package/dist/providers/index.js.map +1 -1
  332. package/dist/providers/mock/index.d.ts +1 -0
  333. package/dist/providers/mock/index.d.ts.map +1 -1
  334. package/dist/providers/mock/index.js.map +1 -1
  335. package/dist/providers/mock/provider.d.ts +8 -8
  336. package/dist/providers/mock/provider.d.ts.map +1 -1
  337. package/dist/providers/mock/provider.js +26 -19
  338. package/dist/providers/mock/provider.js.map +1 -1
  339. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  340. package/dist/providers/stripe/event-mapper.js +214 -173
  341. package/dist/providers/stripe/event-mapper.js.map +1 -1
  342. package/dist/providers/stripe/index.d.ts +1 -0
  343. package/dist/providers/stripe/index.d.ts.map +1 -1
  344. package/dist/providers/stripe/index.js.map +1 -1
  345. package/dist/providers/stripe/provider.d.ts +13 -11
  346. package/dist/providers/stripe/provider.d.ts.map +1 -1
  347. package/dist/providers/stripe/provider.js +287 -107
  348. package/dist/providers/stripe/provider.js.map +1 -1
  349. package/dist/providers/types.d.ts +1 -2
  350. package/dist/providers/types.d.ts.map +1 -1
  351. package/dist/providers/types.js.map +1 -1
  352. package/dist/retry.d.ts +26 -4
  353. package/dist/retry.d.ts.map +1 -1
  354. package/dist/retry.js +65 -23
  355. package/dist/retry.js.map +1 -1
  356. package/dist/shared/diagnostics.d.ts +7 -0
  357. package/dist/shared/diagnostics.d.ts.map +1 -0
  358. package/dist/shared/diagnostics.js +18 -0
  359. package/dist/shared/diagnostics.js.map +1 -0
  360. package/dist/shared/logger.js.map +1 -1
  361. package/dist/shared/postgres-client.d.ts +43 -5
  362. package/dist/shared/postgres-client.d.ts.map +1 -1
  363. package/dist/shared/postgres-client.js +282 -30
  364. package/dist/shared/postgres-client.js.map +1 -1
  365. package/dist/shared/postgres-errors.d.ts +11 -0
  366. package/dist/shared/postgres-errors.d.ts.map +1 -0
  367. package/dist/shared/postgres-errors.js +105 -0
  368. package/dist/shared/postgres-errors.js.map +1 -0
  369. package/dist/shared/postgres-types.js.map +1 -1
  370. package/dist/shared/postgres-validation.d.ts +15 -3
  371. package/dist/shared/postgres-validation.d.ts.map +1 -1
  372. package/dist/shared/postgres-validation.js +58 -14
  373. package/dist/shared/postgres-validation.js.map +1 -1
  374. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  375. package/dist/storage/adapters/clickhouse.js +18 -3
  376. package/dist/storage/adapters/clickhouse.js.map +1 -1
  377. package/dist/storage/adapters/s3.d.ts +0 -6
  378. package/dist/storage/adapters/s3.d.ts.map +1 -1
  379. package/dist/storage/adapters/s3.js +0 -2
  380. package/dist/storage/adapters/s3.js.map +1 -1
  381. package/dist/storage/outbox-worker.d.ts +2 -1
  382. package/dist/storage/outbox-worker.d.ts.map +1 -1
  383. package/dist/storage/outbox-worker.js +17 -3
  384. package/dist/storage/outbox-worker.js.map +1 -1
  385. package/dist/storage/ports.d.ts +1 -1
  386. package/dist/storage/ports.d.ts.map +1 -1
  387. package/dist/storage/ports.js.map +1 -1
  388. package/dist/storage/postgres-repository.d.ts +1 -1
  389. package/dist/storage/postgres-repository.d.ts.map +1 -1
  390. package/dist/storage/postgres-repository.js +13 -3
  391. package/dist/storage/postgres-repository.js.map +1 -1
  392. package/dist/storage/runtime.d.ts +35 -7
  393. package/dist/storage/runtime.d.ts.map +1 -1
  394. package/dist/storage/runtime.js +166 -53
  395. package/dist/storage/runtime.js.map +1 -1
  396. package/package.json +62 -7
  397. package/dist/credits/postgres/repositories/pricing.d.ts +0 -28
  398. package/dist/credits/postgres/repositories/pricing.d.ts.map +0 -1
  399. package/dist/credits/postgres/repositories/pricing.js +0 -70
  400. package/dist/credits/postgres/repositories/pricing.js.map +0 -1
  401. package/dist/credits/pricing-runtime.d.ts.map +0 -1
  402. package/dist/credits/pricing-runtime.js.map +0 -1
  403. package/dist/load-pricing-file.d.ts.map +0 -1
  404. package/dist/load-pricing-file.js.map +0 -1
@@ -1,9 +1,14 @@
1
+ import Decimal from "decimal.js";
2
+ import { z } from "zod";
1
3
  import { BillingStore } from "../billing-store.js";
2
- import { PostgresClient } from "../../shared/postgres-client.js";
4
+ import { PostgresClient, } from "../../shared/postgres-client.js";
5
+ import { StoreClosedError, StoreError } from "../../errors.js";
6
+ import { optionalBoundedDiagnosticMessage } from "../../shared/diagnostics.js";
7
+ import { optionalRecordRow, pgBoolean, postgresUuid, requireRecordRow, requireResultField, safeParse, } from "../../shared/postgres-validation.js";
3
8
  import { BillingOfferRepository } from "./repositories/offer.js";
4
9
  import { BillingTopupRepository } from "./repositories/topup.js";
5
10
  import { BillingCustomerRepository } from "./repositories/customer.js";
6
- import { BillingSubscriptionRepository } from "./repositories/subscription.js";
11
+ import { BillingSubscriptionRepository, } from "./repositories/subscription.js";
7
12
  import { BillingEventRepository } from "./repositories/event.js";
8
13
  import { BillingPaymentRepository } from "./repositories/payment.js";
9
14
  import { BillingRefundRepository } from "./repositories/refund.js";
@@ -11,17 +16,58 @@ import { BillingInvoiceRepository } from "./repositories/invoice.js";
11
16
  import { BillingDisputeRepository } from "./repositories/dispute.js";
12
17
  import { BillingPreferencesRepository } from "./repositories/preferences.js";
13
18
  import { BillingAutoRechargeRepository } from "./repositories/auto-recharge.js";
14
- function toIso(value) {
15
- if (!value)
16
- return null;
17
- if (typeof value === "string")
18
- return value;
19
- if (value instanceof Date)
20
- return value.toISOString();
21
- if (typeof value["toISOString"] === "function") {
22
- return value.toISOString();
23
- }
24
- return String(value);
19
+ import { BillingSubscriptionChangeRepository } from "./repositories/subscription-change.js";
20
+ const PgSafeMinorUnitsSchema = z
21
+ .union([z.string().regex(/^\d+$/), z.number().int().nonnegative().safe()])
22
+ .transform(Number)
23
+ .refine(Number.isSafeInteger, "minor-unit amount exceeds JavaScript's safe integer range");
24
+ const BillingCreditPostingRowSchema = z
25
+ .object({
26
+ ledger_entry_id: postgresUuid.nullable(),
27
+ balance_after: z
28
+ .union([z.string(), z.number(), z.instanceof(Decimal)])
29
+ .nullable()
30
+ .transform((value) => (value === null ? null : new Decimal(value))),
31
+ replayed: pgBoolean,
32
+ error_code: z.string().min(1).nullable(),
33
+ })
34
+ .strict()
35
+ .superRefine((row, ctx) => {
36
+ if (row.error_code === null && (row.ledger_entry_id === null || row.balance_after === null)) {
37
+ ctx.addIssue({
38
+ code: z.ZodIssueCode.custom,
39
+ message: "successful posting requires ledger_entry_id and balance_after",
40
+ });
41
+ }
42
+ });
43
+ const CheckoutIntentRowSchema = z
44
+ .object({
45
+ id: postgresUuid,
46
+ subject_id: postgresUuid,
47
+ provider: z.string().min(1),
48
+ checkout_kind: z.enum(["subscription", "credit_topup"]),
49
+ product_key: z.string().min(1),
50
+ request_digest: z.instanceof(Uint8Array).refine((value) => value.byteLength === 32),
51
+ status: z.enum(["open", "completed", "failed", "expired"]),
52
+ provider_session_id: z.string().min(1).nullable(),
53
+ checkout_url: z.string().min(1).nullable(),
54
+ expires_at: z.union([z.string().datetime({ offset: true }), z.date()]),
55
+ })
56
+ .strict();
57
+ function billingCreditPostingResult(rows, context) {
58
+ const raw = requireRecordRow(rows, context);
59
+ const row = safeParse(BillingCreditPostingRowSchema, {
60
+ ledger_entry_id: raw.ledger_entry_id,
61
+ balance_after: raw.balance_after,
62
+ replayed: raw.replayed,
63
+ error_code: raw.error_code,
64
+ }, context, { indeterminate: true });
65
+ return {
66
+ ledgerEntryId: row.ledger_entry_id,
67
+ balanceAfter: row.balance_after,
68
+ replayed: row.replayed,
69
+ errorCode: row.error_code,
70
+ };
25
71
  }
26
72
  export class PostgresBillingStore extends BillingStore {
27
73
  postgres;
@@ -36,11 +82,27 @@ export class PostgresBillingStore extends BillingStore {
36
82
  _dispute = null;
37
83
  _preferences = null;
38
84
  _autoRecharge = null;
39
- constructor(poolOrUrl, tenantId, storageOptions) {
85
+ _subscriptionChange = null;
86
+ constructor(options) {
40
87
  super();
41
- this.postgres = new PostgresClient(poolOrUrl, {
42
- tenantId,
43
- billingPayloadBackend: storageOptions?.billingPayloadBackend,
88
+ if (typeof options !== "object" || options === null) {
89
+ throw new TypeError("PostgresBillingStore options are required");
90
+ }
91
+ if (typeof options.postgres !== "string" && options.poolConstructor !== undefined) {
92
+ throw new TypeError("poolConstructor cannot be used with an existing PostgreSQL pool");
93
+ }
94
+ this.postgres = new PostgresClient(options.postgres, {
95
+ tenantId: options.tenantId,
96
+ poolConstructor: options.poolConstructor,
97
+ billingPayloadBackend: options.billingPayloadBackend,
98
+ connectionTimeoutMs: options.connectionTimeoutMs,
99
+ statementTimeoutMs: options.statementTimeoutMs,
100
+ idleTransactionTimeoutMs: options.idleTransactionTimeoutMs,
101
+ idleTimeoutMs: options.idleTimeoutMs,
102
+ maxConnections: options.maxConnections,
103
+ applicationName: options.applicationName,
104
+ onPoolError: options.onPoolError,
105
+ closedError: () => new StoreClosedError("Billing store has been closed"),
44
106
  });
45
107
  }
46
108
  async close() {
@@ -104,9 +166,15 @@ export class PostgresBillingStore extends BillingStore {
104
166
  this._autoRecharge = new BillingAutoRechargeRepository(this.queryFn);
105
167
  return this._autoRecharge;
106
168
  }
169
+ get billingSubscriptionChange() {
170
+ if (!this._subscriptionChange) {
171
+ this._subscriptionChange = new BillingSubscriptionChangeRepository(this.queryFn);
172
+ }
173
+ return this._subscriptionChange;
174
+ }
107
175
  async createOrGetCheckoutIntent(input) {
108
176
  if (!/^[0-9a-fA-F]{64}$/.test(input.requestDigest)) {
109
- throw new Error("requestDigest must be a 32-byte hex string");
177
+ throw new TypeError("requestDigest must be a 32-byte hex string");
110
178
  }
111
179
  const rows = await this.queryFn(`SELECT bursar.create_checkout_intent($1::uuid, $2, $3, $4, decode($5, 'hex'), $6::timestamptz) AS id`, [
112
180
  input.subjectId,
@@ -116,55 +184,79 @@ export class PostgresBillingStore extends BillingStore {
116
184
  input.requestDigest,
117
185
  input.expiresAt,
118
186
  ]);
119
- const id = rows[0]?.id;
120
- if (!id)
121
- throw new Error("checkout intent creation returned no ID");
122
- const intent = await this.getCheckoutIntent(String(id), input.subjectId);
123
- if (!intent)
124
- throw new Error("checkout intent creation returned no row");
187
+ const id = requireResultField(rows, "id", postgresUuid, "PostgresBillingStore.createOrGetCheckoutIntent");
188
+ const intent = await this.getCheckoutIntent(id, input.subjectId);
189
+ if (!intent) {
190
+ throw new StoreError("checkout intent could not be read after creation", {
191
+ indeterminate: true,
192
+ details: { checkoutIntentId: id },
193
+ });
194
+ }
125
195
  return intent;
126
196
  }
127
197
  async updateCheckoutIntent(id, update) {
128
198
  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]);
129
- if (!rows[0]?.advanced) {
130
- throw new Error(`checkout intent transition rejected: ${id}`);
199
+ if (!requireResultField(rows, "advanced", pgBoolean, "PostgresBillingStore.updateCheckoutIntent")) {
200
+ throw new StoreError(`checkout intent transition rejected: ${id}`, {
201
+ details: { checkoutIntentId: id },
202
+ });
131
203
  }
132
204
  }
133
205
  async getCheckoutIntent(id, subjectId) {
134
206
  const rows = await this.queryFn(`SELECT * FROM bursar.get_checkout_intent($1::uuid, $2::uuid)`, [id, subjectId]);
207
+ if (rows.length === 0)
208
+ return null;
209
+ if (rows.length !== 1) {
210
+ throw new StoreError("getCheckoutIntent: expected at most one row", {
211
+ details: { rowCount: rows.length, checkoutIntentId: id },
212
+ });
213
+ }
135
214
  const row = rows[0];
136
- return row?.id == null ? null : this.rowToCheckoutIntent(row);
215
+ return this.rowToCheckoutIntent(safeParse(CheckoutIntentRowSchema, {
216
+ id: row.id,
217
+ subject_id: row.subject_id,
218
+ provider: row.provider,
219
+ checkout_kind: row.checkout_kind,
220
+ product_key: row.product_key,
221
+ request_digest: row.request_digest,
222
+ status: row.status,
223
+ provider_session_id: row.provider_session_id,
224
+ checkout_url: row.checkout_url,
225
+ expires_at: row.expires_at,
226
+ }, "PostgresBillingStore.getCheckoutIntent"));
137
227
  }
138
228
  rowToCheckoutIntent(row) {
139
229
  return {
140
- id: String(row.id),
141
- subjectId: String(row.subject_id),
142
- provider: String(row.provider),
230
+ id: row.id,
231
+ subjectId: row.subject_id,
232
+ provider: row.provider,
143
233
  checkoutKind: row.checkout_kind,
144
- productKey: String(row.product_key),
234
+ productKey: row.product_key,
145
235
  requestDigest: Buffer.from(row.request_digest).toString("hex"),
146
236
  status: row.status,
147
- providerSessionId: row.provider_session_id == null ? null : String(row.provider_session_id),
148
- checkoutUrl: row.checkout_url == null ? null : String(row.checkout_url),
149
- expiresAt: toIso(row.expires_at) ?? new Date(0).toISOString(),
237
+ providerSessionId: row.provider_session_id,
238
+ checkoutUrl: row.checkout_url,
239
+ expiresAt: row.expires_at instanceof Date ? row.expires_at.toISOString() : row.expires_at,
150
240
  };
151
241
  }
152
242
  rowToOffer(row) {
153
- if (!row?.offer_key || !row.id)
243
+ if (!row)
154
244
  return null;
155
245
  return {
156
- offerId: String(row.id),
157
- offerKey: String(row.offer_key),
158
- planId: row.plan_id == null ? null : String(row.plan_id),
159
- plan: row.plan == null ? null : String(row.plan),
160
- interval: row.interval == null ? "month" : String(row.interval),
161
- intervalCount: Number(row.interval_count ?? 1),
162
- grant: {
163
- mode: row.grant_mode == null ? undefined : String(row.grant_mode),
164
- credits: row.grant_credits == null ? null : Number(row.grant_credits),
165
- bucket: row.grant_bucket == null ? undefined : String(row.grant_bucket),
166
- replacePrior: row.grant_replace_prior === true,
167
- },
246
+ offerId: row.id,
247
+ offerKey: row.offerKey,
248
+ planId: row.planId,
249
+ plan: row.plan,
250
+ interval: row.interval,
251
+ intervalCount: row.intervalCount,
252
+ grant: row.grantCredits === null
253
+ ? null
254
+ : {
255
+ mode: "cycle_grant",
256
+ credits: row.grantCredits,
257
+ bucket: row.grantBucket,
258
+ replacePrior: row.grantReplacePrior,
259
+ },
168
260
  };
169
261
  }
170
262
  async resolveBillingOffer(provider, productId, priceId) {
@@ -177,28 +269,36 @@ export class PostgresBillingStore extends BillingStore {
177
269
  }
178
270
  async claimBillingEvent(provider, eventId, eventType, envelope) {
179
271
  const result = await this.billingEvent.claim(provider, eventId, eventType, JSON.stringify(envelope ?? { eventType }));
180
- if (!result)
181
- return { status: "retry" };
182
- const r = result;
183
- const s = r.status;
184
- if (s === "claimed" && typeof r.claim_token === "string" && typeof r.event_id === "string") {
272
+ if (result.status === "claimed") {
273
+ if (result.claim_token === null || result.event_id === null) {
274
+ throw new StoreError("Billing event claim returned no claim identifiers", {
275
+ details: { provider, eventId },
276
+ });
277
+ }
185
278
  return {
186
279
  status: "claimed",
187
- claimToken: r.claim_token,
188
- billingEventId: r.event_id,
280
+ claimToken: result.claim_token,
281
+ billingEventId: result.event_id,
189
282
  };
190
283
  }
191
- if (s === "duplicate")
284
+ if (result.status === "duplicate")
192
285
  return { status: "duplicate" };
193
- if (s === "busy")
286
+ if (result.status === "busy")
194
287
  return { status: "busy" };
195
- return { status: "retry" };
288
+ if (result.status === "invalid_request" ||
289
+ result.status === "idempotency_conflict" ||
290
+ result.status === "max_retries_exceeded") {
291
+ return { status: "retry" };
292
+ }
293
+ throw new StoreError("Billing event claim returned an unsupported status", {
294
+ details: { provider, eventId, status: result.status },
295
+ });
196
296
  }
197
297
  async completeBillingEvent(provider, eventId, claimToken) {
198
- await this.billingEvent.complete(provider, eventId, claimToken);
298
+ return this.billingEvent.complete(provider, eventId, claimToken);
199
299
  }
200
300
  async failBillingEvent(provider, eventId, claimToken, error) {
201
- await this.billingEvent.fail(provider, eventId, claimToken, error);
301
+ return this.billingEvent.fail(provider, eventId, claimToken, optionalBoundedDiagnosticMessage(error) ?? undefined);
202
302
  }
203
303
  async upsertBillingCustomer(provider, providerCustomerId, userId, email) {
204
304
  await this.billingCustomer.upsert(provider, providerCustomerId, userId, email ?? null);
@@ -217,31 +317,19 @@ export class PostgresBillingStore extends BillingStore {
217
317
  }
218
318
  async createBillingSubscriptionChange(input) {
219
319
  const subscription = await this.billingSubscription.get(input.provider, input.providerSubscriptionId);
220
- if (!subscription?.id)
221
- throw new Error("subscription change requires a persisted subscription");
222
- const rows = await this.queryFn(`SELECT * FROM bursar.open_subscription_change(
223
- $1::uuid, $2::uuid, $3::timestamptz, $4, $5, $6
224
- )`, [
225
- subscription.id,
226
- input.toOfferId,
227
- input.effectiveAt,
228
- input.effective,
229
- input.idempotencyKey,
230
- input.prorationBehavior ?? "provider_default",
231
- ]);
232
- const result = rows[0] ?? {};
233
- if (result.error_code)
234
- throw new Error(`subscription change: ${String(result.error_code)}`);
235
- const changeRows = await this.queryFn(`SELECT * FROM bursar.get_billing_subscription_change($1::bigint)`, [result.change_id]);
236
- if (changeRows[0]?.id == null) {
237
- throw new Error("subscription change creation returned no row");
320
+ if (!subscription?.id) {
321
+ throw new StoreError("subscription change requires a persisted subscription", {
322
+ retryable: true,
323
+ details: {
324
+ provider: input.provider,
325
+ providerSubscriptionId: input.providerSubscriptionId,
326
+ },
327
+ });
238
328
  }
239
- return this.rowToSubscriptionChange(changeRows[0]);
329
+ return this.billingSubscriptionChange.create(subscription.id, input);
240
330
  }
241
331
  async getOpenBillingSubscriptionChange(provider, providerSubscriptionId) {
242
- const rows = await this.queryFn(`SELECT * FROM bursar.get_open_billing_subscription_change($1, $2)`, [provider, providerSubscriptionId]);
243
- const row = rows[0];
244
- return row?.id == null ? null : this.rowToSubscriptionChange(row);
332
+ return this.billingSubscriptionChange.getOpen(provider, providerSubscriptionId);
245
333
  }
246
334
  async listExpiredGraceSubscriptions(now, limit = 100) {
247
335
  const rows = await this.billingSubscription.listExpiredGraceSubscriptions(now, limit);
@@ -251,12 +339,7 @@ export class PostgresBillingStore extends BillingStore {
251
339
  return this.billingSubscription.markGraceExpired(subscriptionId, expectedGraceEndsAt, expiredAt);
252
340
  }
253
341
  async updateBillingSubscriptionChange(id, update) {
254
- if (!update.state)
255
- return;
256
- const rows = await this.queryFn(`SELECT bursar.advance_subscription_change($1::bigint, $2, $3, $4) AS advanced`, [id, update.state, update.providerOperationId ?? null, update.errorMessage ?? null]);
257
- if (!rows[0]?.advanced) {
258
- throw new Error(`subscription change transition rejected: ${id}`);
259
- }
342
+ await this.billingSubscriptionChange.update(id, update);
260
343
  }
261
344
  async getUserSubscription(userId, statuses) {
262
345
  const r = await this.billingSubscription.getUserSubscription(userId, statuses);
@@ -275,20 +358,22 @@ export class PostgresBillingStore extends BillingStore {
275
358
  return this.billingSubscription.selectEntitlementSource(userId, provider, providerSubscriptionId);
276
359
  }
277
360
  rowToTopup(r) {
278
- if (!r?.topup_key || !r.id)
361
+ if (!r)
279
362
  return null;
363
+ const minAmountMinor = safeParse(PgSafeMinorUnitsSchema, r.amount_minor * r.min_quantity, "PostgresBillingStore.rowToTopup.minAmountMinor");
364
+ const maxAmountMinor = safeParse(PgSafeMinorUnitsSchema, r.amount_minor * r.max_quantity, "PostgresBillingStore.rowToTopup.maxAmountMinor");
280
365
  return {
281
- topupId: String(r.id),
366
+ topupId: r.id,
282
367
  topupKey: r.topup_key,
283
- creditsPerUnit: Number(r.credits_per_unit ?? r.credits_per_major_unit ?? 1000),
284
- depositTo: r.bucket_key || "purchased",
285
- amountMinor: r.amount_minor == null ? undefined : Number(r.amount_minor),
286
- currency: r.currency == null ? undefined : String(r.currency),
287
- minQuantity: r.min_quantity == null ? undefined : Number(r.min_quantity),
288
- maxQuantity: r.max_quantity == null ? undefined : Number(r.max_quantity),
289
- defaultQuantity: r.default_quantity == null ? undefined : Number(r.default_quantity),
290
- minAmountMinor: r.amount_minor == null ? undefined : Number(r.amount_minor) * Number(r.min_quantity ?? 1),
291
- maxAmountMinor: r.amount_minor == null ? undefined : Number(r.amount_minor) * Number(r.max_quantity ?? 1),
368
+ creditsPerUnit: r.credits_per_unit,
369
+ depositTo: r.bucket_key,
370
+ amountMinor: r.amount_minor,
371
+ currency: r.currency,
372
+ minQuantity: r.min_quantity,
373
+ maxQuantity: r.max_quantity,
374
+ defaultQuantity: r.default_quantity,
375
+ minAmountMinor,
376
+ maxAmountMinor,
292
377
  };
293
378
  }
294
379
  async resolveCreditTopup(provider, productId, priceId) {
@@ -300,201 +385,153 @@ export class PostgresBillingStore extends BillingStore {
300
385
  return this.rowToTopup(r);
301
386
  }
302
387
  async computeTopupCredits(amountMinor, topupConfig) {
388
+ if (!Number.isSafeInteger(amountMinor) || amountMinor < 0) {
389
+ throw new TypeError("amountMinor must be a non-negative safe integer");
390
+ }
303
391
  const unitAmount = topupConfig.amountMinor;
304
- const creditsPer = topupConfig.creditsPerUnit ?? 0;
305
- if (!unitAmount || amountMinor % unitAmount !== 0)
306
- return 0;
392
+ if (unitAmount <= 0 || amountMinor % unitAmount !== 0)
393
+ return new Decimal(0);
307
394
  const quantity = amountMinor / unitAmount;
308
- if (quantity < (topupConfig.minQuantity ?? 1) || quantity > (topupConfig.maxQuantity ?? 1)) {
309
- return 0;
395
+ if (quantity < topupConfig.minQuantity || quantity > topupConfig.maxQuantity) {
396
+ return new Decimal(0);
310
397
  }
311
- return quantity * creditsPer;
398
+ return topupConfig.creditsPerUnit.mul(quantity);
312
399
  }
313
400
  async upsertBillingPayment(options) {
314
- 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());
401
+ return this.billingPayment.upsert(options.provider, options.providerPaymentId, options.providerInvoiceId ?? null, options.userId, options.amountMinor, options.taxMinor, options.currency, options.purpose, options.metadata ? JSON.stringify(options.metadata) : null, options.status, options.providerUpdatedAt);
315
402
  }
316
403
  async createBillingCreditGrant(input) {
317
404
  const rows = await this.queryFn("SELECT bursar.create_billing_credit_grant($1::uuid, $2::uuid, $3::uuid, $4, $5, $6::uuid) AS id", [
318
405
  input.paymentId ?? null,
319
406
  input.subscriptionId ?? null,
320
407
  input.topupId ?? null,
321
- input.configuredCredits,
322
- input.quantity ?? 1,
408
+ input.configuredCredits.toString(),
409
+ input.quantity,
323
410
  input.billingEventId ?? null,
324
411
  ]);
325
- const id = rows[0]?.id;
326
- if (!id)
327
- throw new Error("billing credit grant creation returned no ID");
328
- return String(id);
412
+ return requireResultField(rows, "id", postgresUuid, "PostgresBillingStore.createBillingCreditGrant");
329
413
  }
330
414
  async grantBillingCredit(grantId, idempotencyKey) {
331
415
  const rows = await this.queryFn("SELECT * FROM bursar.grant_billing_credit($1::uuid, $2)", [
332
416
  grantId,
333
417
  idempotencyKey,
334
418
  ]);
335
- return rows[0] ?? {};
419
+ return billingCreditPostingResult(rows, "PostgresBillingStore.grantBillingCredit");
336
420
  }
337
421
  async getBillingCreditGrantByPayment(paymentId) {
338
422
  const rows = await this.queryFn(`SELECT * FROM bursar.get_billing_credit_grant_by_payment($1::uuid)`, [paymentId]);
339
- const id = rows[0]?.id;
340
- return id ? String(id) : null;
423
+ const row = optionalRecordRow(rows, "PostgresBillingStore.getBillingCreditGrantByPayment");
424
+ return row === null
425
+ ? null
426
+ : safeParse(postgresUuid, row.id, "PostgresBillingStore.getBillingCreditGrantByPayment.id");
341
427
  }
342
428
  async postBillingRefund(refundId, grantId, amountMinor, idempotencyKey) {
343
429
  const rows = await this.queryFn("SELECT * FROM bursar.post_billing_refund($1::uuid, $2::uuid, $3, $4)", [refundId, grantId, amountMinor, idempotencyKey]);
344
- return rows[0] ?? {};
430
+ return billingCreditPostingResult(rows, "PostgresBillingStore.postBillingRefund");
345
431
  }
346
432
  async upsertBillingRefund(options) {
347
- 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());
433
+ return this.billingRefund.upsert(options.provider, options.providerRefundId, options.providerPaymentId, options.userId, options.amountMinor, options.currency, options.reason ?? null, options.metadata ? JSON.stringify(options.metadata) : null, options.status, options.providerUpdatedAt);
348
434
  }
349
435
  async upsertBillingInvoice(options) {
350
436
  const subscription = options.providerSubscriptionId
351
437
  ? await this.billingSubscription.get(options.provider, options.providerSubscriptionId)
352
438
  : null;
353
- const subjectId = options.userId ?? (subscription?.subject_id ? String(subscription.subject_id) : null);
354
- if (!subjectId)
355
- throw new Error("invoice subject is required");
356
- 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());
439
+ if (options.providerSubscriptionId && !subscription) {
440
+ throw new StoreError("invoice subscription is not available", {
441
+ retryable: true,
442
+ details: {
443
+ provider: options.provider,
444
+ providerInvoiceId: options.providerInvoiceId,
445
+ providerSubscriptionId: options.providerSubscriptionId ?? null,
446
+ },
447
+ });
448
+ }
449
+ await this.billingInvoice.upsert(options.userId, options.provider, options.providerInvoiceId, subscription?.id ? String(subscription.id) : null, options.status, options.amountDueMinor, options.amountPaidMinor, options.currency, options.periodStart ?? null, options.periodEnd ?? null, options.metadata ?? {}, options.providerUpdatedAt);
357
450
  }
358
451
  async listBillingInvoices(userId) {
359
452
  return this.billingInvoice.listForUser(userId);
360
453
  }
361
454
  async upsertBillingDispute(options) {
362
- const payment = options.providerPaymentId
363
- ? await this.billingPayment.getForRefund(options.provider, options.providerPaymentId)
364
- : null;
365
- if (!payment?.id)
366
- throw new Error("dispute payment is required");
367
- 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());
455
+ const payment = await this.billingPayment.getForRefund(options.provider, options.providerPaymentId);
456
+ if (!payment?.id) {
457
+ throw new StoreError("dispute payment is required", {
458
+ retryable: true,
459
+ details: {
460
+ provider: options.provider,
461
+ providerDisputeId: options.providerDisputeId,
462
+ providerPaymentId: options.providerPaymentId ?? null,
463
+ },
464
+ });
465
+ }
466
+ await this.billingDispute.upsert(options.provider, options.providerDisputeId, String(payment.id), options.status, options.reason ?? null, options.metadata ?? {}, options.providerUpdatedAt);
368
467
  }
369
468
  async getBillingPayment(provider, providerPaymentId) {
370
- const result = await this.billingPayment.getForRefund(provider, providerPaymentId);
371
- if (!result)
469
+ const row = await this.billingPayment.getForRefund(provider, providerPaymentId);
470
+ if (!row)
372
471
  return null;
373
- const row = result;
374
472
  return {
375
473
  id: row.id,
376
474
  provider: row.provider,
377
475
  providerPaymentId: row.provider_payment_id,
378
476
  providerInvoiceId: row.provider_invoice_id,
379
477
  userId: row.subject_id,
380
- amountMinor: row.amount_minor == null ? null : Number(row.amount_minor),
381
- taxMinor: row.tax_minor == null ? null : Number(row.tax_minor),
478
+ amountMinor: safeParse(PgSafeMinorUnitsSchema, row.amount_minor, "PostgresBillingStore.getBillingPayment.amountMinor"),
479
+ taxMinor: safeParse(PgSafeMinorUnitsSchema, row.tax_minor, "PostgresBillingStore.getBillingPayment.taxMinor"),
382
480
  currency: row.currency,
383
481
  purpose: row.purpose,
384
482
  status: row.status,
385
- providerUpdatedAt: toIso(row.provider_updated_at),
483
+ providerUpdatedAt: row.provider_updated_at instanceof Date
484
+ ? row.provider_updated_at.toISOString()
485
+ : row.provider_updated_at,
386
486
  metadata: row.metadata,
387
487
  };
388
488
  }
389
489
  rowToSubscriptionState(r) {
390
490
  return {
391
- subscriptionId: r.id ? String(r.id) : null,
392
- userId: String(r.user_id),
393
- provider: String(r.provider),
394
- providerSubscriptionId: String(r.provider_subscription_id),
395
- providerCustomerId: r.provider_customer_id ? String(r.provider_customer_id) : null,
396
- offerId: r.offer_id ? String(r.offer_id) : null,
397
- offerKey: r.offer_key ? String(r.offer_key) : null,
398
- plan: r.plan ? String(r.plan) : null,
399
- status: (r.status ? String(r.status) : "incomplete"),
400
- currentPeriodStart: toIso(r.current_period_start),
401
- currentPeriodEnd: toIso(r.current_period_end),
402
- trialEnd: toIso(r.trial_end),
403
- cancelAt: toIso(r.cancel_at),
404
- endedAt: toIso(r.ended_at),
405
- graceEndsAt: toIso(r.grace_ends_at),
406
- graceExpiredAt: toIso(r.grace_expired_at),
407
- providerUpdatedAt: toIso(r.provider_updated_at),
408
- cancelAtPeriodEnd: Boolean(r.cancel_at_period_end),
409
- interval: r.interval ? String(r.interval) : null,
410
- intervalCount: r.interval_count ? Number(r.interval_count) : null,
411
- metadata: r.metadata && typeof r.metadata === "object"
412
- ? r.metadata
413
- : null,
491
+ subscriptionId: r.id,
492
+ userId: r.user_id,
493
+ provider: r.provider,
494
+ providerSubscriptionId: r.provider_subscription_id,
495
+ providerCustomerId: r.provider_customer_id,
496
+ offerId: r.offer_id,
497
+ offerKey: r.offer_key,
498
+ planId: r.plan_id,
499
+ plan: r.plan,
500
+ status: r.status,
501
+ currentPeriodStart: r.current_period_start,
502
+ currentPeriodEnd: r.current_period_end,
503
+ trialEnd: r.trial_end,
504
+ cancelAt: r.cancel_at,
505
+ endedAt: r.ended_at,
506
+ graceEndsAt: r.grace_ends_at,
507
+ graceExpiredAt: r.grace_expired_at,
508
+ providerUpdatedAt: r.provider_updated_at,
509
+ cancelAtPeriodEnd: r.cancel_at_period_end,
510
+ interval: r.interval,
511
+ intervalCount: r.interval_count,
512
+ metadata: r.metadata,
414
513
  };
415
514
  }
416
- async getSubscriptionOfferContexts(r) {
417
- const rows = await this.queryFn(`SELECT requested.side, requested.offer_id, context.*
418
- FROM (
419
- VALUES
420
- ('from', $1::uuid, $2::uuid),
421
- ('to', $3::uuid, $4::uuid)
422
- ) AS requested(side, offer_id, catalog_revision_id)
423
- CROSS JOIN LATERAL bursar.get_catalog_offer_context(
424
- requested.offer_id,
425
- requested.catalog_revision_id
426
- ) AS context`, [r.from_offer_id, r.from_catalog_revision_id, r.to_offer_id, r.to_catalog_revision_id]);
427
- const bySide = new Map(rows.map((row) => {
428
- const context = row;
429
- return [String(context.side), context];
430
- }));
431
- const mapContext = (side) => {
432
- const context = bySide.get(side);
433
- if (context?.offer_key == null) {
434
- throw new Error(`subscription change ${side}-offer context not found`);
435
- }
436
- return {
437
- offerId: String(context.offer_id),
438
- offerKey: String(context.offer_key),
439
- planId: context.plan_id ? String(context.plan_id) : null,
440
- plan: context.plan_key ? String(context.plan_key) : null,
441
- interval: context.billing_unit ? String(context.billing_unit) : null,
442
- intervalCount: context.billing_count == null ? null : Number(context.billing_count),
443
- };
444
- };
445
- return { fromOffer: mapContext("from"), toOffer: mapContext("to") };
446
- }
447
- async rowToSubscriptionChange(r) {
448
- const { fromOffer, toOffer } = await this.getSubscriptionOfferContexts(r);
449
- return {
450
- id: String(r.id),
451
- subscriptionId: String(r.subscription_id),
452
- fromOfferId: String(r.from_offer_id),
453
- toOfferId: String(r.to_offer_id),
454
- fromOffer,
455
- toOffer,
456
- effectiveAt: toIso(r.effective_at),
457
- effective: String(r.effective_behavior),
458
- state: String(r.state),
459
- prorationBehavior: String(r.proration_behavior),
460
- idempotencyKey: String(r.idempotency_key),
461
- providerOperationId: r.provider_operation_id ? String(r.provider_operation_id) : null,
462
- errorMessage: r.error_message ? String(r.error_message) : null,
463
- };
464
- }
465
- async getActiveBursarConfig() {
515
+ async getActiveCatalogDocument() {
466
516
  const rows = await this.queryFn("SELECT * FROM bursar.active_catalog_revision()", []);
467
- if (!rows || rows.length === 0)
517
+ if (rows.length === 0)
468
518
  return null;
469
- return (rows[0]?.source_document ??
470
- null);
519
+ if (rows.length !== 1 || typeof rows[0] !== "object" || rows[0] === null) {
520
+ throw new StoreError("active catalog revision returned a malformed row", {
521
+ details: { rowCount: rows.length },
522
+ });
523
+ }
524
+ return safeParse(z.record(z.string(), z.unknown()), rows[0].source_document, "PostgresBillingStore.getActiveCatalogDocument");
471
525
  }
472
526
  async pseudonymizeFinancialSubject(userId) {
473
527
  const rows = await this.queryFn(`SELECT bursar.pseudonymize_financial_subject($1::uuid) AS pseudonymized`, [userId]);
474
- return rows[0]?.pseudonymized === true;
528
+ return requireResultField(rows, "pseudonymized", pgBoolean, "PostgresBillingStore.pseudonymizeFinancialSubject");
475
529
  }
476
530
  async getBillingPreferences(userId) {
477
- const row = await this.billingPreferences.get(userId);
478
- if (!row || row.subject_id == null)
479
- return null;
480
- return {
481
- userId: String(row.subject_id),
482
- autoRecharge: Boolean(row.auto_recharge),
483
- overageProtection: Boolean(row.overage_protection),
484
- emailNotifications: Boolean(row.email_notifications),
485
- usageAlerts: Boolean(row.usage_alerts),
486
- invoiceReminders: Boolean(row.invoice_reminders),
487
- };
531
+ return this.billingPreferences.get(userId);
488
532
  }
489
533
  async upsertBillingPreferences(prefs) {
490
- await this.billingPreferences.upsert({
491
- userId: prefs.userId,
492
- autoRecharge: prefs.autoRecharge,
493
- overageProtection: prefs.overageProtection,
494
- emailNotifications: prefs.emailNotifications,
495
- usageAlerts: prefs.usageAlerts,
496
- invoiceReminders: prefs.invoiceReminders,
497
- });
534
+ await this.billingPreferences.upsert(prefs);
498
535
  }
499
536
  async getAutoRechargeProfile(userId) {
500
537
  return this.billingAutoRecharge.getProfile(userId);