@zonastery/bursar 1.0.1 → 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 (366) hide show
  1. package/README.md +86 -3
  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 +8 -7
  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 +31 -9
  21. package/dist/billing/event-handlers.js.map +1 -1
  22. package/dist/billing/event-processor.d.ts.map +1 -1
  23. package/dist/billing/event-processor.js +2 -1
  24. package/dist/billing/event-processor.js.map +1 -1
  25. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  26. package/dist/billing/financial-event-handlers.js +69 -72
  27. package/dist/billing/financial-event-handlers.js.map +1 -1
  28. package/dist/billing/index.d.ts +1 -1
  29. package/dist/billing/index.d.ts.map +1 -1
  30. package/dist/billing/index.js.map +1 -1
  31. package/dist/billing/management.d.ts +5 -5
  32. package/dist/billing/management.d.ts.map +1 -1
  33. package/dist/billing/management.js +2 -2
  34. package/dist/billing/management.js.map +1 -1
  35. package/dist/billing/postgres/repositories/auto-recharge.d.ts +3 -3
  36. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  37. package/dist/billing/postgres/repositories/auto-recharge.js +202 -59
  38. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  39. package/dist/billing/postgres/repositories/customer.d.ts.map +1 -1
  40. package/dist/billing/postgres/repositories/customer.js +19 -11
  41. package/dist/billing/postgres/repositories/customer.js.map +1 -1
  42. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
  43. package/dist/billing/postgres/repositories/dispute.js +3 -1
  44. package/dist/billing/postgres/repositories/dispute.js.map +1 -1
  45. package/dist/billing/postgres/repositories/event.d.ts +12 -5
  46. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  47. package/dist/billing/postgres/repositories/event.js +18 -15
  48. package/dist/billing/postgres/repositories/event.js.map +1 -1
  49. package/dist/billing/postgres/repositories/invoice.d.ts +3 -3
  50. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  51. package/dist/billing/postgres/repositories/invoice.js +53 -11
  52. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  53. package/dist/billing/postgres/repositories/offer.d.ts +20 -17
  54. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  55. package/dist/billing/postgres/repositories/offer.js +123 -57
  56. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  57. package/dist/billing/postgres/repositories/payment.d.ts +23 -20
  58. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  59. package/dist/billing/postgres/repositories/payment.js +43 -37
  60. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  61. package/dist/billing/postgres/repositories/preferences.d.ts +3 -9
  62. package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -1
  63. package/dist/billing/postgres/repositories/preferences.js +45 -7
  64. package/dist/billing/postgres/repositories/preferences.js.map +1 -1
  65. package/dist/billing/postgres/repositories/refund.d.ts +1 -1
  66. package/dist/billing/postgres/repositories/refund.d.ts.map +1 -1
  67. package/dist/billing/postgres/repositories/refund.js +13 -9
  68. package/dist/billing/postgres/repositories/refund.js.map +1 -1
  69. package/dist/billing/postgres/repositories/subscription-change.d.ts +15 -0
  70. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -0
  71. package/dist/billing/postgres/repositories/subscription-change.js +234 -0
  72. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -0
  73. package/dist/billing/postgres/repositories/subscription.d.ts +38 -17
  74. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  75. package/dist/billing/postgres/repositories/subscription.js +199 -91
  76. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  77. package/dist/billing/postgres/repositories/topup.d.ts +13 -15
  78. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  79. package/dist/billing/postgres/repositories/topup.js +65 -34
  80. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  81. package/dist/billing/postgres/store.d.ts +18 -11
  82. package/dist/billing/postgres/store.d.ts.map +1 -1
  83. package/dist/billing/postgres/store.js +260 -238
  84. package/dist/billing/postgres/store.js.map +1 -1
  85. package/dist/billing/service-types.d.ts +6 -5
  86. package/dist/billing/service-types.d.ts.map +1 -1
  87. package/dist/billing/service-types.js.map +1 -1
  88. package/dist/billing/types/auto-recharge.d.ts +6 -4
  89. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  90. package/dist/billing/types/auto-recharge.js.map +1 -1
  91. package/dist/billing/types/catalog.d.ts +18 -35
  92. package/dist/billing/types/catalog.d.ts.map +1 -1
  93. package/dist/billing/types/catalog.js.map +1 -1
  94. package/dist/billing/types/common.d.ts +0 -1
  95. package/dist/billing/types/common.d.ts.map +1 -1
  96. package/dist/billing/types/common.js.map +1 -1
  97. package/dist/billing/types/documents.d.ts +38 -12
  98. package/dist/billing/types/documents.d.ts.map +1 -1
  99. package/dist/billing/types/documents.js.map +1 -1
  100. package/dist/billing/types/events.d.ts +2 -0
  101. package/dist/billing/types/events.d.ts.map +1 -1
  102. package/dist/billing/types/events.js +238 -0
  103. package/dist/billing/types/events.js.map +1 -1
  104. package/dist/billing/types/subscriptions.d.ts +8 -8
  105. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  106. package/dist/billing/types/subscriptions.js.map +1 -1
  107. package/dist/bursar.d.ts +27 -9
  108. package/dist/bursar.d.ts.map +1 -1
  109. package/dist/bursar.js +48 -20
  110. package/dist/bursar.js.map +1 -1
  111. package/dist/catalog.d.ts +1 -1
  112. package/dist/catalog.d.ts.map +1 -1
  113. package/dist/catalog.js +1 -1
  114. package/dist/catalog.js.map +1 -1
  115. package/dist/commerce/errors.d.ts +1 -10
  116. package/dist/commerce/errors.d.ts.map +1 -1
  117. package/dist/commerce/errors.js +1 -16
  118. package/dist/commerce/errors.js.map +1 -1
  119. package/dist/commerce/index.d.ts +1 -0
  120. package/dist/commerce/index.d.ts.map +1 -1
  121. package/dist/commerce/index.js.map +1 -1
  122. package/dist/commerce/provider-registry.d.ts.map +1 -1
  123. package/dist/commerce/provider-registry.js +27 -2
  124. package/dist/commerce/provider-registry.js.map +1 -1
  125. package/dist/commerce/service.d.ts +15 -7
  126. package/dist/commerce/service.d.ts.map +1 -1
  127. package/dist/commerce/service.js +85 -67
  128. package/dist/commerce/service.js.map +1 -1
  129. package/dist/commerce/types.d.ts +27 -15
  130. package/dist/commerce/types.d.ts.map +1 -1
  131. package/dist/commerce/types.js.map +1 -1
  132. package/dist/config/parse-plans.d.ts.map +1 -1
  133. package/dist/config/parse-plans.js +16 -15
  134. package/dist/config/parse-plans.js.map +1 -1
  135. package/dist/config/parse-pricing.d.ts.map +1 -1
  136. package/dist/config/parse-pricing.js +16 -5
  137. package/dist/config/parse-pricing.js.map +1 -1
  138. package/dist/config/types.d.ts +2 -2
  139. package/dist/config/types.d.ts.map +1 -1
  140. package/dist/config/types.js.map +1 -1
  141. package/dist/credits/{pricing-runtime.d.ts → catalog-runtime.d.ts} +8 -8
  142. package/dist/credits/catalog-runtime.d.ts.map +1 -0
  143. package/dist/credits/{pricing-runtime.js → catalog-runtime.js} +58 -38
  144. package/dist/credits/catalog-runtime.js.map +1 -0
  145. package/dist/credits/events.d.ts +4 -4
  146. package/dist/credits/events.d.ts.map +1 -1
  147. package/dist/credits/events.js +1 -1
  148. package/dist/credits/events.js.map +1 -1
  149. package/dist/credits/lease-workflow.d.ts +14 -14
  150. package/dist/credits/lease-workflow.d.ts.map +1 -1
  151. package/dist/credits/lease-workflow.js +18 -17
  152. package/dist/credits/lease-workflow.js.map +1 -1
  153. package/dist/credits/low-balance-monitor.d.ts +2 -2
  154. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  155. package/dist/credits/low-balance-monitor.js.map +1 -1
  156. package/dist/credits/postgres/repositories/analytics.d.ts +34 -34
  157. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  158. package/dist/credits/postgres/repositories/analytics.js +52 -52
  159. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  160. package/dist/credits/postgres/repositories/balance.d.ts +28 -30
  161. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  162. package/dist/credits/postgres/repositories/balance.js +100 -59
  163. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  164. package/dist/credits/postgres/repositories/bucket.d.ts +14 -8
  165. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
  166. package/dist/credits/postgres/repositories/bucket.js +22 -21
  167. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  168. package/dist/credits/postgres/repositories/catalog.d.ts +31 -0
  169. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -0
  170. package/dist/credits/postgres/repositories/catalog.js +90 -0
  171. package/dist/credits/postgres/repositories/catalog.js.map +1 -0
  172. package/dist/credits/postgres/repositories/deduction.d.ts +28 -26
  173. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  174. package/dist/credits/postgres/repositories/deduction.js +153 -68
  175. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  176. package/dist/credits/postgres/repositories/lease.d.ts +21 -18
  177. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  178. package/dist/credits/postgres/repositories/lease.js +157 -65
  179. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  180. package/dist/credits/postgres/repositories/plan.d.ts +90 -43
  181. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
  182. package/dist/credits/postgres/repositories/plan.js +126 -108
  183. package/dist/credits/postgres/repositories/plan.js.map +1 -1
  184. package/dist/credits/postgres/repositories/team.d.ts +36 -27
  185. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  186. package/dist/credits/postgres/repositories/team.js +96 -52
  187. package/dist/credits/postgres/repositories/team.js.map +1 -1
  188. package/dist/credits/postgres/store.d.ts +23 -18
  189. package/dist/credits/postgres/store.d.ts.map +1 -1
  190. package/dist/credits/postgres/store.js +282 -265
  191. package/dist/credits/postgres/store.js.map +1 -1
  192. package/dist/credits/postgres/value-mappers.d.ts +7 -9
  193. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  194. package/dist/credits/postgres/value-mappers.js +36 -61
  195. package/dist/credits/postgres/value-mappers.js.map +1 -1
  196. package/dist/credits/queries.d.ts +5 -5
  197. package/dist/credits/queries.d.ts.map +1 -1
  198. package/dist/credits/queries.js +4 -4
  199. package/dist/credits/queries.js.map +1 -1
  200. package/dist/credits/service-types.d.ts +42 -7
  201. package/dist/credits/service-types.d.ts.map +1 -1
  202. package/dist/credits/service-types.js.map +1 -1
  203. package/dist/credits/service.d.ts +42 -62
  204. package/dist/credits/service.d.ts.map +1 -1
  205. package/dist/credits/service.js +140 -121
  206. package/dist/credits/service.js.map +1 -1
  207. package/dist/credits/store.d.ts +20 -22
  208. package/dist/credits/store.d.ts.map +1 -1
  209. package/dist/credits/store.js +5 -5
  210. package/dist/credits/store.js.map +1 -1
  211. package/dist/credits/types/account.d.ts +49 -11
  212. package/dist/credits/types/account.d.ts.map +1 -1
  213. package/dist/credits/types/account.js.map +1 -1
  214. package/dist/credits/types/admission.d.ts +17 -6
  215. package/dist/credits/types/admission.d.ts.map +1 -1
  216. package/dist/credits/types/admission.js.map +1 -1
  217. package/dist/credits/types/analytics.d.ts +2 -2
  218. package/dist/credits/types/analytics.d.ts.map +1 -1
  219. package/dist/credits/types/analytics.js.map +1 -1
  220. package/dist/credits/types/catalog.d.ts +20 -15
  221. package/dist/credits/types/catalog.d.ts.map +1 -1
  222. package/dist/credits/types/catalog.js.map +1 -1
  223. package/dist/credits/types/grants.d.ts +22 -8
  224. package/dist/credits/types/grants.d.ts.map +1 -1
  225. package/dist/credits/types/grants.js.map +1 -1
  226. package/dist/credits/types/ledger.d.ts +12 -3
  227. package/dist/credits/types/ledger.d.ts.map +1 -1
  228. package/dist/credits/types/ledger.js.map +1 -1
  229. package/dist/credits/types/teams.d.ts +18 -6
  230. package/dist/credits/types/teams.d.ts.map +1 -1
  231. package/dist/credits/types/teams.js.map +1 -1
  232. package/dist/engine.d.ts.map +1 -1
  233. package/dist/engine.js +24 -10
  234. package/dist/engine.js.map +1 -1
  235. package/dist/errors.d.ts +52 -4
  236. package/dist/errors.d.ts.map +1 -1
  237. package/dist/errors.js +76 -4
  238. package/dist/errors.js.map +1 -1
  239. package/dist/expr/ast.d.ts.map +1 -1
  240. package/dist/expr/ast.js.map +1 -1
  241. package/dist/expr/evaluator.d.ts.map +1 -1
  242. package/dist/expr/evaluator.js +29 -17
  243. package/dist/expr/evaluator.js.map +1 -1
  244. package/dist/expr/parser.d.ts.map +1 -1
  245. package/dist/expr/parser.js +11 -4
  246. package/dist/expr/parser.js.map +1 -1
  247. package/dist/expr/tokenizer.d.ts.map +1 -1
  248. package/dist/expr/tokenizer.js +17 -13
  249. package/dist/expr/tokenizer.js.map +1 -1
  250. package/dist/expr.d.ts +2 -2
  251. package/dist/expr.d.ts.map +1 -1
  252. package/dist/expr.js +5 -7
  253. package/dist/expr.js.map +1 -1
  254. package/dist/generated/pricing-config.schema.json +5 -12
  255. package/dist/generated/pricing-config.types.d.ts +3 -3
  256. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  257. package/dist/generated/pricing-config.types.js.map +1 -1
  258. package/dist/index.d.ts +6 -4
  259. package/dist/index.d.ts.map +1 -1
  260. package/dist/index.js +1 -1
  261. package/dist/index.js.map +1 -1
  262. package/dist/integrations/better-auth.d.ts +23 -0
  263. package/dist/integrations/better-auth.d.ts.map +1 -0
  264. package/dist/integrations/better-auth.js +54 -0
  265. package/dist/integrations/better-auth.js.map +1 -0
  266. package/dist/{load-pricing-file.d.ts → load-config-file.d.ts} +4 -4
  267. package/dist/load-config-file.d.ts.map +1 -0
  268. package/dist/{load-pricing-file.js → load-config-file.js} +15 -10
  269. package/dist/load-config-file.js.map +1 -0
  270. package/dist/node.d.ts +3 -3
  271. package/dist/node.d.ts.map +1 -1
  272. package/dist/node.js +2 -2
  273. package/dist/node.js.map +1 -1
  274. package/dist/providers/_shared.d.ts +5 -0
  275. package/dist/providers/_shared.d.ts.map +1 -1
  276. package/dist/providers/_shared.js +36 -0
  277. package/dist/providers/_shared.js.map +1 -1
  278. package/dist/providers/dodo/better-auth.d.ts +29 -0
  279. package/dist/providers/dodo/better-auth.d.ts.map +1 -0
  280. package/dist/providers/dodo/better-auth.js +23 -0
  281. package/dist/providers/dodo/better-auth.js.map +1 -0
  282. package/dist/providers/dodo/client-contract.d.ts +32 -70
  283. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  284. package/dist/providers/dodo/client-contract.js.map +1 -1
  285. package/dist/providers/dodo/event-mapper.d.ts +3 -1
  286. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  287. package/dist/providers/dodo/event-mapper.js +219 -148
  288. package/dist/providers/dodo/event-mapper.js.map +1 -1
  289. package/dist/providers/dodo/index.d.ts +5 -2
  290. package/dist/providers/dodo/index.d.ts.map +1 -1
  291. package/dist/providers/dodo/index.js +2 -1
  292. package/dist/providers/dodo/index.js.map +1 -1
  293. package/dist/providers/dodo/nextjs.d.ts +16 -0
  294. package/dist/providers/dodo/nextjs.d.ts.map +1 -0
  295. package/dist/providers/dodo/nextjs.js +16 -0
  296. package/dist/providers/dodo/nextjs.js.map +1 -0
  297. package/dist/providers/dodo/provider.d.ts +30 -11
  298. package/dist/providers/dodo/provider.d.ts.map +1 -1
  299. package/dist/providers/dodo/provider.js +192 -122
  300. package/dist/providers/dodo/provider.js.map +1 -1
  301. package/dist/providers/dodo/react-native.d.ts +56 -0
  302. package/dist/providers/dodo/react-native.d.ts.map +1 -0
  303. package/dist/providers/dodo/react-native.js +57 -0
  304. package/dist/providers/dodo/react-native.js.map +1 -0
  305. package/dist/providers/dodo/webhook-bridge.d.ts +17 -0
  306. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -0
  307. package/dist/providers/dodo/webhook-bridge.js +21 -0
  308. package/dist/providers/dodo/webhook-bridge.js.map +1 -0
  309. package/dist/providers/index.d.ts +1 -1
  310. package/dist/providers/index.d.ts.map +1 -1
  311. package/dist/providers/index.js.map +1 -1
  312. package/dist/providers/mock/index.d.ts +1 -0
  313. package/dist/providers/mock/index.d.ts.map +1 -1
  314. package/dist/providers/mock/index.js.map +1 -1
  315. package/dist/providers/mock/provider.d.ts +8 -8
  316. package/dist/providers/mock/provider.d.ts.map +1 -1
  317. package/dist/providers/mock/provider.js +26 -19
  318. package/dist/providers/mock/provider.js.map +1 -1
  319. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  320. package/dist/providers/stripe/event-mapper.js +214 -173
  321. package/dist/providers/stripe/event-mapper.js.map +1 -1
  322. package/dist/providers/stripe/index.d.ts +1 -0
  323. package/dist/providers/stripe/index.d.ts.map +1 -1
  324. package/dist/providers/stripe/index.js.map +1 -1
  325. package/dist/providers/stripe/provider.d.ts +13 -11
  326. package/dist/providers/stripe/provider.d.ts.map +1 -1
  327. package/dist/providers/stripe/provider.js +287 -107
  328. package/dist/providers/stripe/provider.js.map +1 -1
  329. package/dist/providers/types.d.ts +1 -2
  330. package/dist/providers/types.d.ts.map +1 -1
  331. package/dist/providers/types.js.map +1 -1
  332. package/dist/shared/postgres-client.d.ts +5 -0
  333. package/dist/shared/postgres-client.d.ts.map +1 -1
  334. package/dist/shared/postgres-client.js +23 -7
  335. package/dist/shared/postgres-client.js.map +1 -1
  336. package/dist/shared/postgres-validation.d.ts +15 -3
  337. package/dist/shared/postgres-validation.d.ts.map +1 -1
  338. package/dist/shared/postgres-validation.js +58 -14
  339. package/dist/shared/postgres-validation.js.map +1 -1
  340. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  341. package/dist/storage/adapters/clickhouse.js +2 -5
  342. package/dist/storage/adapters/clickhouse.js.map +1 -1
  343. package/dist/storage/adapters/s3.d.ts +0 -6
  344. package/dist/storage/adapters/s3.d.ts.map +1 -1
  345. package/dist/storage/adapters/s3.js +0 -2
  346. package/dist/storage/adapters/s3.js.map +1 -1
  347. package/dist/storage/ports.d.ts +0 -1
  348. package/dist/storage/ports.d.ts.map +1 -1
  349. package/dist/storage/ports.js.map +1 -1
  350. package/dist/storage/postgres-repository.d.ts +1 -1
  351. package/dist/storage/postgres-repository.d.ts.map +1 -1
  352. package/dist/storage/postgres-repository.js +2 -2
  353. package/dist/storage/postgres-repository.js.map +1 -1
  354. package/dist/storage/runtime.d.ts +24 -6
  355. package/dist/storage/runtime.d.ts.map +1 -1
  356. package/dist/storage/runtime.js +87 -30
  357. package/dist/storage/runtime.js.map +1 -1
  358. package/package.json +56 -7
  359. package/dist/credits/postgres/repositories/pricing.d.ts +0 -28
  360. package/dist/credits/postgres/repositories/pricing.d.ts.map +0 -1
  361. package/dist/credits/postgres/repositories/pricing.js +0 -76
  362. package/dist/credits/postgres/repositories/pricing.js.map +0 -1
  363. package/dist/credits/pricing-runtime.d.ts.map +0 -1
  364. package/dist/credits/pricing-runtime.js.map +0 -1
  365. package/dist/load-pricing-file.d.ts.map +0 -1
  366. package/dist/load-pricing-file.js.map +0 -1
@@ -1,11 +1,14 @@
1
+ import Decimal from "decimal.js";
2
+ import { z } from "zod";
1
3
  import { BillingStore } from "../billing-store.js";
2
4
  import { PostgresClient, } from "../../shared/postgres-client.js";
3
- import { StoreClosedError } from "../../errors.js";
5
+ import { StoreClosedError, StoreError } from "../../errors.js";
4
6
  import { optionalBoundedDiagnosticMessage } from "../../shared/diagnostics.js";
7
+ import { optionalRecordRow, pgBoolean, postgresUuid, requireRecordRow, requireResultField, safeParse, } from "../../shared/postgres-validation.js";
5
8
  import { BillingOfferRepository } from "./repositories/offer.js";
6
9
  import { BillingTopupRepository } from "./repositories/topup.js";
7
10
  import { BillingCustomerRepository } from "./repositories/customer.js";
8
- import { BillingSubscriptionRepository } from "./repositories/subscription.js";
11
+ import { BillingSubscriptionRepository, } from "./repositories/subscription.js";
9
12
  import { BillingEventRepository } from "./repositories/event.js";
10
13
  import { BillingPaymentRepository } from "./repositories/payment.js";
11
14
  import { BillingRefundRepository } from "./repositories/refund.js";
@@ -13,17 +16,58 @@ import { BillingInvoiceRepository } from "./repositories/invoice.js";
13
16
  import { BillingDisputeRepository } from "./repositories/dispute.js";
14
17
  import { BillingPreferencesRepository } from "./repositories/preferences.js";
15
18
  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);
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
+ };
27
71
  }
28
72
  export class PostgresBillingStore extends BillingStore {
29
73
  postgres;
@@ -38,18 +82,26 @@ export class PostgresBillingStore extends BillingStore {
38
82
  _dispute = null;
39
83
  _preferences = null;
40
84
  _autoRecharge = null;
41
- constructor(poolOrUrl, tenantId, storageOptions) {
85
+ _subscriptionChange = null;
86
+ constructor(options) {
42
87
  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,
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,
53
105
  closedError: () => new StoreClosedError("Billing store has been closed"),
54
106
  });
55
107
  }
@@ -114,9 +166,15 @@ export class PostgresBillingStore extends BillingStore {
114
166
  this._autoRecharge = new BillingAutoRechargeRepository(this.queryFn);
115
167
  return this._autoRecharge;
116
168
  }
169
+ get billingSubscriptionChange() {
170
+ if (!this._subscriptionChange) {
171
+ this._subscriptionChange = new BillingSubscriptionChangeRepository(this.queryFn);
172
+ }
173
+ return this._subscriptionChange;
174
+ }
117
175
  async createOrGetCheckoutIntent(input) {
118
176
  if (!/^[0-9a-fA-F]{64}$/.test(input.requestDigest)) {
119
- throw new Error("requestDigest must be a 32-byte hex string");
177
+ throw new TypeError("requestDigest must be a 32-byte hex string");
120
178
  }
121
179
  const rows = await this.queryFn(`SELECT bursar.create_checkout_intent($1::uuid, $2, $3, $4, decode($5, 'hex'), $6::timestamptz) AS id`, [
122
180
  input.subjectId,
@@ -126,55 +184,79 @@ export class PostgresBillingStore extends BillingStore {
126
184
  input.requestDigest,
127
185
  input.expiresAt,
128
186
  ]);
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");
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
+ }
135
195
  return intent;
136
196
  }
137
197
  async updateCheckoutIntent(id, update) {
138
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]);
139
- if (!rows[0]?.advanced) {
140
- 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
+ });
141
203
  }
142
204
  }
143
205
  async getCheckoutIntent(id, subjectId) {
144
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
+ }
145
214
  const row = rows[0];
146
- 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"));
147
227
  }
148
228
  rowToCheckoutIntent(row) {
149
229
  return {
150
- id: String(row.id),
151
- subjectId: String(row.subject_id),
152
- provider: String(row.provider),
230
+ id: row.id,
231
+ subjectId: row.subject_id,
232
+ provider: row.provider,
153
233
  checkoutKind: row.checkout_kind,
154
- productKey: String(row.product_key),
234
+ productKey: row.product_key,
155
235
  requestDigest: Buffer.from(row.request_digest).toString("hex"),
156
236
  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(),
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,
160
240
  };
161
241
  }
162
242
  rowToOffer(row) {
163
- if (!row?.offer_key || !row.id)
243
+ if (!row)
164
244
  return null;
165
245
  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
- },
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
+ },
178
260
  };
179
261
  }
180
262
  async resolveBillingOffer(provider, productId, priceId) {
@@ -187,22 +269,30 @@ export class PostgresBillingStore extends BillingStore {
187
269
  }
188
270
  async claimBillingEvent(provider, eventId, eventType, envelope) {
189
271
  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") {
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
+ }
195
278
  return {
196
279
  status: "claimed",
197
- claimToken: r.claim_token,
198
- billingEventId: r.event_id,
280
+ claimToken: result.claim_token,
281
+ billingEventId: result.event_id,
199
282
  };
200
283
  }
201
- if (s === "duplicate")
284
+ if (result.status === "duplicate")
202
285
  return { status: "duplicate" };
203
- if (s === "busy")
286
+ if (result.status === "busy")
204
287
  return { status: "busy" };
205
- 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
+ });
206
296
  }
207
297
  async completeBillingEvent(provider, eventId, claimToken) {
208
298
  return this.billingEvent.complete(provider, eventId, claimToken);
@@ -227,31 +317,19 @@ export class PostgresBillingStore extends BillingStore {
227
317
  }
228
318
  async createBillingSubscriptionChange(input) {
229
319
  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");
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
+ });
248
328
  }
249
- return this.rowToSubscriptionChange(changeRows[0]);
329
+ return this.billingSubscriptionChange.create(subscription.id, input);
250
330
  }
251
331
  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);
332
+ return this.billingSubscriptionChange.getOpen(provider, providerSubscriptionId);
255
333
  }
256
334
  async listExpiredGraceSubscriptions(now, limit = 100) {
257
335
  const rows = await this.billingSubscription.listExpiredGraceSubscriptions(now, limit);
@@ -261,17 +339,7 @@ export class PostgresBillingStore extends BillingStore {
261
339
  return this.billingSubscription.markGraceExpired(subscriptionId, expectedGraceEndsAt, expiredAt);
262
340
  }
263
341
  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
- }
342
+ await this.billingSubscriptionChange.update(id, update);
275
343
  }
276
344
  async getUserSubscription(userId, statuses) {
277
345
  const r = await this.billingSubscription.getUserSubscription(userId, statuses);
@@ -290,20 +358,22 @@ export class PostgresBillingStore extends BillingStore {
290
358
  return this.billingSubscription.selectEntitlementSource(userId, provider, providerSubscriptionId);
291
359
  }
292
360
  rowToTopup(r) {
293
- if (!r?.topup_key || !r.id)
361
+ if (!r)
294
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");
295
365
  return {
296
- topupId: String(r.id),
366
+ topupId: r.id,
297
367
  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),
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,
307
377
  };
308
378
  }
309
379
  async resolveCreditTopup(provider, productId, priceId) {
@@ -315,201 +385,153 @@ export class PostgresBillingStore extends BillingStore {
315
385
  return this.rowToTopup(r);
316
386
  }
317
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
+ }
318
391
  const unitAmount = topupConfig.amountMinor;
319
- const creditsPer = topupConfig.creditsPerUnit ?? 0;
320
- if (!unitAmount || amountMinor % unitAmount !== 0)
321
- return 0;
392
+ if (unitAmount <= 0 || amountMinor % unitAmount !== 0)
393
+ return new Decimal(0);
322
394
  const quantity = amountMinor / unitAmount;
323
- if (quantity < (topupConfig.minQuantity ?? 1) || quantity > (topupConfig.maxQuantity ?? 1)) {
324
- return 0;
395
+ if (quantity < topupConfig.minQuantity || quantity > topupConfig.maxQuantity) {
396
+ return new Decimal(0);
325
397
  }
326
- return quantity * creditsPer;
398
+ return topupConfig.creditsPerUnit.mul(quantity);
327
399
  }
328
400
  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());
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);
330
402
  }
331
403
  async createBillingCreditGrant(input) {
332
404
  const rows = await this.queryFn("SELECT bursar.create_billing_credit_grant($1::uuid, $2::uuid, $3::uuid, $4, $5, $6::uuid) AS id", [
333
405
  input.paymentId ?? null,
334
406
  input.subscriptionId ?? null,
335
407
  input.topupId ?? null,
336
- input.configuredCredits,
337
- input.quantity ?? 1,
408
+ input.configuredCredits.toString(),
409
+ input.quantity,
338
410
  input.billingEventId ?? null,
339
411
  ]);
340
- const id = rows[0]?.id;
341
- if (!id)
342
- throw new Error("billing credit grant creation returned no ID");
343
- return String(id);
412
+ return requireResultField(rows, "id", postgresUuid, "PostgresBillingStore.createBillingCreditGrant");
344
413
  }
345
414
  async grantBillingCredit(grantId, idempotencyKey) {
346
415
  const rows = await this.queryFn("SELECT * FROM bursar.grant_billing_credit($1::uuid, $2)", [
347
416
  grantId,
348
417
  idempotencyKey,
349
418
  ]);
350
- return rows[0] ?? {};
419
+ return billingCreditPostingResult(rows, "PostgresBillingStore.grantBillingCredit");
351
420
  }
352
421
  async getBillingCreditGrantByPayment(paymentId) {
353
422
  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;
423
+ const row = optionalRecordRow(rows, "PostgresBillingStore.getBillingCreditGrantByPayment");
424
+ return row === null
425
+ ? null
426
+ : safeParse(postgresUuid, row.id, "PostgresBillingStore.getBillingCreditGrantByPayment.id");
356
427
  }
357
428
  async postBillingRefund(refundId, grantId, amountMinor, idempotencyKey) {
358
429
  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] ?? {};
430
+ return billingCreditPostingResult(rows, "PostgresBillingStore.postBillingRefund");
360
431
  }
361
432
  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());
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);
363
434
  }
364
435
  async upsertBillingInvoice(options) {
365
436
  const subscription = options.providerSubscriptionId
366
437
  ? await this.billingSubscription.get(options.provider, options.providerSubscriptionId)
367
438
  : 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());
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);
372
450
  }
373
451
  async listBillingInvoices(userId) {
374
452
  return this.billingInvoice.listForUser(userId);
375
453
  }
376
454
  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());
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);
383
467
  }
384
468
  async getBillingPayment(provider, providerPaymentId) {
385
- const result = await this.billingPayment.getForRefund(provider, providerPaymentId);
386
- if (!result)
469
+ const row = await this.billingPayment.getForRefund(provider, providerPaymentId);
470
+ if (!row)
387
471
  return null;
388
- const row = result;
389
472
  return {
390
473
  id: row.id,
391
474
  provider: row.provider,
392
475
  providerPaymentId: row.provider_payment_id,
393
476
  providerInvoiceId: row.provider_invoice_id,
394
477
  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),
478
+ amountMinor: safeParse(PgSafeMinorUnitsSchema, row.amount_minor, "PostgresBillingStore.getBillingPayment.amountMinor"),
479
+ taxMinor: safeParse(PgSafeMinorUnitsSchema, row.tax_minor, "PostgresBillingStore.getBillingPayment.taxMinor"),
397
480
  currency: row.currency,
398
481
  purpose: row.purpose,
399
482
  status: row.status,
400
- 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,
401
486
  metadata: row.metadata,
402
487
  };
403
488
  }
404
489
  rowToSubscriptionState(r) {
405
490
  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,
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,
429
513
  };
430
514
  }
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() {
515
+ async getActiveCatalogDocument() {
481
516
  const rows = await this.queryFn("SELECT * FROM bursar.active_catalog_revision()", []);
482
- if (!rows || rows.length === 0)
517
+ if (rows.length === 0)
483
518
  return null;
484
- return (rows[0]?.source_document ??
485
- 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");
486
525
  }
487
526
  async pseudonymizeFinancialSubject(userId) {
488
527
  const rows = await this.queryFn(`SELECT bursar.pseudonymize_financial_subject($1::uuid) AS pseudonymized`, [userId]);
489
- return rows[0]?.pseudonymized === true;
528
+ return requireResultField(rows, "pseudonymized", pgBoolean, "PostgresBillingStore.pseudonymizeFinancialSubject");
490
529
  }
491
530
  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
- };
531
+ return this.billingPreferences.get(userId);
503
532
  }
504
533
  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
- });
534
+ await this.billingPreferences.upsert(prefs);
513
535
  }
514
536
  async getAutoRechargeProfile(userId) {
515
537
  return this.billingAutoRecharge.getProfile(userId);