@zonastery/bursar 1.0.1 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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,28 +1,41 @@
1
1
  import { z } from "zod";
2
- import { safeParse } from "../../../shared/postgres-validation.js";
2
+ import { optionalRecordRow, postgresUuid, requireResultField, safeParse, } from "../../../shared/postgres-validation.js";
3
+ const PgSafeMinorUnitsSchema = z.union([
4
+ z.string().regex(/^\d+$/),
5
+ z.number().int().nonnegative().safe(),
6
+ ]);
3
7
  const BillingPaymentRowSchema = z
4
8
  .object({
5
- provider: z.string().optional(),
6
- provider_payment_id: z.string().optional(),
7
- subject_id: z.string().nullable().optional(),
8
- user_id: z.string().nullable().optional(),
9
- amount_minor: z.union([z.string(), z.number()]).optional(),
10
- tax_minor: z.union([z.string(), z.number()]).nullable().optional(),
11
- currency: z.string().optional(),
12
- purpose: z.string().nullable().optional(),
13
- status: z.string().optional(),
14
- provider_updated_at: z.unknown().optional(),
15
- metadata: z.record(z.string(), z.unknown()).nullable().optional(),
9
+ id: postgresUuid,
10
+ provider: z.string().min(1),
11
+ provider_payment_id: z.string().min(1),
12
+ provider_invoice_id: z.string().nullable(),
13
+ subject_id: postgresUuid,
14
+ amount_minor: PgSafeMinorUnitsSchema,
15
+ tax_minor: PgSafeMinorUnitsSchema,
16
+ currency: z.string().regex(/^[A-Z]{3}$/),
17
+ purpose: z.enum(["subscription", "credit_topup"]),
18
+ status: z.enum(["pending", "succeeded", "failed", "canceled"]),
19
+ provider_updated_at: z.union([z.string().datetime({ offset: true }), z.date()]),
20
+ metadata: z.record(z.string(), z.unknown()),
16
21
  })
17
- .passthrough();
18
- const ForRefundRowSchema = z
19
- .object({
20
- credits_per_unit: z.union([z.string(), z.number()]).nullable().optional(),
21
- credits_per_major_unit: z.union([z.string(), z.number()]).nullable().optional(),
22
- tier: z.string().optional(),
23
- deposit_to: z.string().optional(),
24
- })
25
- .passthrough();
22
+ .strict();
23
+ function parsePaymentRow(row, context) {
24
+ return safeParse(BillingPaymentRowSchema, {
25
+ id: row.id,
26
+ provider: row.provider,
27
+ provider_payment_id: row.provider_payment_id,
28
+ provider_invoice_id: row.provider_invoice_id,
29
+ subject_id: row.subject_id,
30
+ amount_minor: row.amount_minor,
31
+ tax_minor: row.tax_minor,
32
+ currency: row.currency,
33
+ purpose: row.purpose,
34
+ status: row.status,
35
+ provider_updated_at: row.provider_updated_at,
36
+ metadata: row.metadata,
37
+ }, context);
38
+ }
26
39
  export class BillingPaymentRepository {
27
40
  query;
28
41
  constructor(query) {
@@ -30,18 +43,18 @@ export class BillingPaymentRepository {
30
43
  }
31
44
  async upsert(provider, providerPaymentId, providerInvoiceId, userId, amountMinor, taxMinor, currency, purpose, metadata, status, providerUpdatedAt) {
32
45
  if (!userId)
33
- throw new Error("billing payment requires a subject");
46
+ throw new TypeError("billing payment requires a subject");
34
47
  if (purpose !== "subscription" && purpose !== "credit_topup") {
35
- throw new Error("billing payment requires a known purpose");
48
+ throw new TypeError("billing payment requires a known purpose");
36
49
  }
37
50
  const rows = await this.query(`SELECT bursar.upsert_billing_payment(
38
51
  $1::uuid,$2,$3,$4,$5,$6,$7,$8::bursar.billing_payment_status,$9,$10,$11::jsonb
39
- )`, [
52
+ ) AS id`, [
40
53
  userId,
41
54
  provider,
42
55
  providerPaymentId,
43
56
  amountMinor,
44
- taxMinor ?? 0,
57
+ taxMinor,
45
58
  currency,
46
59
  purpose,
47
60
  status,
@@ -49,30 +62,23 @@ export class BillingPaymentRepository {
49
62
  providerInvoiceId,
50
63
  metadata ?? "{}",
51
64
  ]);
52
- const id = rows[0]?.upsert_billing_payment;
53
- if (!id)
54
- throw new Error("billing payment upsert returned no ID");
55
- return String(id);
65
+ return requireResultField(rows, "id", postgresUuid, "BillingPaymentRepository.upsert");
56
66
  }
57
67
  async getForRefund(provider, providerPaymentId) {
58
68
  const rows = await this.query("SELECT * FROM bursar.get_billing_payment_by_provider($1,$2)", [
59
69
  provider,
60
70
  providerPaymentId,
61
71
  ]);
62
- const row = rows[0];
63
- return row?.id == null
64
- ? null
65
- : safeParse(ForRefundRowSchema, row, "BillingPaymentRepository.getForRefund");
72
+ const row = optionalRecordRow(rows, "BillingPaymentRepository.getForRefund");
73
+ return row === null ? null : parsePaymentRow(row, "BillingPaymentRepository.getForRefund");
66
74
  }
67
75
  async getDirect(provider, providerPaymentId) {
68
76
  const rows = await this.query("SELECT * FROM bursar.get_billing_payment_by_provider($1,$2)", [
69
77
  provider,
70
78
  providerPaymentId,
71
79
  ]);
72
- const row = rows[0];
73
- return row?.id == null
74
- ? null
75
- : safeParse(BillingPaymentRowSchema, row, "BillingPaymentRepository.getDirect");
80
+ const row = optionalRecordRow(rows, "BillingPaymentRepository.getDirect");
81
+ return row === null ? null : parsePaymentRow(row, "BillingPaymentRepository.getDirect");
76
82
  }
77
83
  }
78
84
  //# sourceMappingURL=payment.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"payment.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/payment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,SAAS,EAAE,MAAM,wCAAwC,CAAC;AAEnE,MAAM,uBAAuB,GAAG,CAAC;KAC9B,MAAM,CAAC;IACN,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC/B,mBAAmB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC1C,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE;IAC5C,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE;IACzC,YAAY,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,QAAQ,EAAE;IAC1D,SAAS,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE;IAClE,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC/B,OAAO,EAA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,CAAC,CAAC,SAAS,CAAC,uBAAuB,EAAE,GAAG,EAAE,oCAAoC,CAAC,CAAC;IACpF,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport { safeParse } from \"../../../shared/postgres-validation.js\";\n\nconst BillingPaymentRowSchema = z\n .object({\n provider: z.string().optional(),\n provider_payment_id: z.string().optional(),\n subject_id: z.string().nullable().optional(),\n user_id: z.string().nullable().optional(),\n amount_minor: z.union([z.string(), z.number()]).optional(),\n tax_minor: z.union([z.string(), z.number()]).nullable().optional(),\n currency: z.string().optional(),\n purpose: z.string().nullable().optional(),\n status: z.string().optional(),\n provider_updated_at: z.unknown().optional(),\n metadata: z.record(z.string(), z.unknown()).nullable().optional(),\n })\n .passthrough();\nconst ForRefundRowSchema = z\n .object({\n credits_per_unit: z.union([z.string(), z.number()]).nullable().optional(),\n credits_per_major_unit: z.union([z.string(), z.number()]).nullable().optional(),\n tier: z.string().optional(),\n deposit_to: z.string().optional(),\n })\n .passthrough();\nexport type BillingPaymentRow = z.infer<typeof BillingPaymentRowSchema>;\nexport type ForRefundRow = z.infer<typeof ForRefundRowSchema>;\n\nexport class BillingPaymentRepository {\n constructor(private query: QueryFn) {}\n async upsert(\n provider: string,\n providerPaymentId: string,\n providerInvoiceId: string | null,\n userId: string | null,\n amountMinor: number,\n taxMinor: number | null,\n currency: string,\n purpose: string | null,\n metadata: string | null,\n status: string,\n providerUpdatedAt: string,\n ): Promise<string> {\n if (!userId) throw new Error(\"billing payment requires a subject\");\n if (purpose !== \"subscription\" && purpose !== \"credit_topup\") {\n throw new Error(\"billing payment requires a known purpose\");\n }\n const rows = await this.query(\n `SELECT bursar.upsert_billing_payment(\n $1::uuid,$2,$3,$4,$5,$6,$7,$8::bursar.billing_payment_status,$9,$10,$11::jsonb\n )`,\n [\n userId,\n provider,\n providerPaymentId,\n amountMinor,\n taxMinor ?? 0,\n currency,\n purpose,\n status,\n providerUpdatedAt,\n providerInvoiceId,\n metadata ?? \"{}\",\n ],\n );\n const id = (rows[0] as Record<string, unknown> | undefined)?.upsert_billing_payment;\n if (!id) throw new Error(\"billing payment upsert returned no ID\");\n return String(id);\n }\n async getForRefund(provider: string, providerPaymentId: string): Promise<ForRefundRow | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_payment_by_provider($1,$2)\", [\n provider,\n providerPaymentId,\n ]);\n const row = rows[0] as Record<string, unknown> | undefined;\n return row?.id == null\n ? null\n : safeParse(ForRefundRowSchema, row, \"BillingPaymentRepository.getForRefund\");\n }\n async getDirect(provider: string, providerPaymentId: string): Promise<BillingPaymentRow | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_payment_by_provider($1,$2)\", [\n provider,\n providerPaymentId,\n ]);\n const row = rows[0] as Record<string, unknown> | undefined;\n return row?.id == null\n ? null\n : safeParse(BillingPaymentRowSchema, row, \"BillingPaymentRepository.getDirect\");\n }\n}\n"]}
1
+ {"version":3,"file":"payment.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/payment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,sBAAsB,GAAG,CAAC,CAAC,KAAK,CAAC;IACrC,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC;IACzB,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE;CACtC,CAAC,CAAC;AAEH,MAAM,uBAAuB,GAAG,CAAC;KAC9B,MAAM,CAAC;IACN,EAAE,EAAE,YAAY;IAChB,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3B,mBAAmB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAA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D,KAAK,CAAC,SAAS,CAAC,QAAgB,EAAE,iBAAyB;QACzD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,6DAA6D,EAAE;YAC3F,QAAQ;YACR,iBAAiB;SAClB,CAAC,CAAC;QACH,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,oCAAoC,CAAC,CAAC;QAC1E,OAAO,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,GAAG,EAAE,oCAAoC,CAAC,CAAC;IAC1F,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst PgSafeMinorUnitsSchema = z.union([\n z.string().regex(/^\\d+$/),\n z.number().int().nonnegative().safe(),\n]);\n\nconst BillingPaymentRowSchema = z\n .object({\n id: postgresUuid,\n provider: z.string().min(1),\n provider_payment_id: z.string().min(1),\n provider_invoice_id: z.string().nullable(),\n subject_id: postgresUuid,\n amount_minor: PgSafeMinorUnitsSchema,\n tax_minor: PgSafeMinorUnitsSchema,\n currency: z.string().regex(/^[A-Z]{3}$/),\n purpose: z.enum([\"subscription\", \"credit_topup\"]),\n status: z.enum([\"pending\", \"succeeded\", \"failed\", \"canceled\"]),\n provider_updated_at: z.union([z.string().datetime({ offset: true }), z.date()]),\n metadata: z.record(z.string(), z.unknown()),\n })\n .strict();\nexport type BillingPaymentRow = z.infer<typeof BillingPaymentRowSchema>;\nexport type ForRefundRow = BillingPaymentRow;\n\nfunction parsePaymentRow(row: Record<string, unknown>, context: string): BillingPaymentRow {\n return safeParse(\n BillingPaymentRowSchema,\n {\n id: row.id,\n provider: row.provider,\n provider_payment_id: row.provider_payment_id,\n provider_invoice_id: row.provider_invoice_id,\n subject_id: row.subject_id,\n amount_minor: row.amount_minor,\n tax_minor: row.tax_minor,\n currency: row.currency,\n purpose: row.purpose,\n status: row.status,\n provider_updated_at: row.provider_updated_at,\n metadata: row.metadata,\n },\n context,\n );\n}\n\nexport class BillingPaymentRepository {\n constructor(private query: QueryFn) {}\n async upsert(\n provider: string,\n providerPaymentId: string,\n providerInvoiceId: string | null,\n userId: string,\n amountMinor: number,\n taxMinor: number,\n currency: string,\n purpose: \"subscription\" | \"credit_topup\",\n metadata: string | null,\n status: \"pending\" | \"succeeded\" | \"failed\" | \"canceled\",\n providerUpdatedAt: string,\n ): Promise<string> {\n if (!userId) throw new TypeError(\"billing payment requires a subject\");\n if (purpose !== \"subscription\" && purpose !== \"credit_topup\") {\n throw new TypeError(\"billing payment requires a known purpose\");\n }\n const rows = await this.query(\n `SELECT bursar.upsert_billing_payment(\n $1::uuid,$2,$3,$4,$5,$6,$7,$8::bursar.billing_payment_status,$9,$10,$11::jsonb\n ) AS id`,\n [\n userId,\n provider,\n providerPaymentId,\n amountMinor,\n taxMinor,\n currency,\n purpose,\n status,\n providerUpdatedAt,\n providerInvoiceId,\n metadata ?? \"{}\",\n ],\n );\n return requireResultField(rows, \"id\", postgresUuid, \"BillingPaymentRepository.upsert\");\n }\n async getForRefund(provider: string, providerPaymentId: string): Promise<ForRefundRow | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_payment_by_provider($1,$2)\", [\n provider,\n providerPaymentId,\n ]);\n const row = optionalRecordRow(rows, \"BillingPaymentRepository.getForRefund\");\n return row === null ? null : parsePaymentRow(row, \"BillingPaymentRepository.getForRefund\");\n }\n async getDirect(provider: string, providerPaymentId: string): Promise<BillingPaymentRow | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_payment_by_provider($1,$2)\", [\n provider,\n providerPaymentId,\n ]);\n const row = optionalRecordRow(rows, \"BillingPaymentRepository.getDirect\");\n return row === null ? null : parsePaymentRow(row, \"BillingPaymentRepository.getDirect\");\n }\n}\n"]}
@@ -1,15 +1,9 @@
1
1
  import type { QueryFn } from "../../../shared/postgres-types.js";
2
+ import type { BillingPreferences } from "../../types/index.js";
2
3
  export declare class BillingPreferencesRepository {
3
4
  private query;
4
5
  constructor(query: QueryFn);
5
- get(userId: string): Promise<Record<string, unknown> | null>;
6
- upsert(prefs: {
7
- userId: string;
8
- autoRecharge?: boolean;
9
- overageProtection?: boolean;
10
- emailNotifications?: boolean;
11
- usageAlerts?: boolean;
12
- invoiceReminders?: boolean;
13
- }): Promise<void>;
6
+ get(userId: string): Promise<BillingPreferences | null>;
7
+ upsert(prefs: BillingPreferences): Promise<void>;
14
8
  }
15
9
  //# sourceMappingURL=preferences.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"preferences.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/preferences.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAEjE,qBAAa,4BAA4B;IAC3B,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAE5B,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IAO5D,MAAM,CAAC,KAAK,EAAE;QAClB,MAAM,EAAE,MAAM,CAAC;QACf,YAAY,CAAC,EAAE,OAAO,CAAC;QACvB,iBAAiB,CAAC,EAAE,OAAO,CAAC;QAC5B,kBAAkB,CAAC,EAAE,OAAO,CAAC;QAC7B,WAAW,CAAC,EAAE,OAAO,CAAC;QACtB,gBAAgB,CAAC,EAAE,OAAO,CAAC;KAC5B,GAAG,OAAO,CAAC,IAAI,CAAC;CAUlB"}
1
+ {"version":3,"file":"preferences.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/preferences.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAEjE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAoB/D,qBAAa,4BAA4B;IAC3B,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAE5B,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IA8BvD,MAAM,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC;CAwBvD"}
@@ -1,3 +1,16 @@
1
+ import { z } from "zod";
2
+ import { StoreError } from "../../../errors.js";
3
+ import { optionalRecordRow, pgBoolean, postgresUuid, requireResultField, safeParse, } from "../../../shared/postgres-validation.js";
4
+ const BillingPreferencesRowSchema = z
5
+ .object({
6
+ subject_id: postgresUuid,
7
+ auto_recharge: pgBoolean,
8
+ overage_protection: pgBoolean,
9
+ email_notifications: pgBoolean,
10
+ usage_alerts: pgBoolean,
11
+ invoice_reminders: pgBoolean,
12
+ })
13
+ .strict();
1
14
  export class BillingPreferencesRepository {
2
15
  query;
3
16
  constructor(query) {
@@ -7,17 +20,42 @@ export class BillingPreferencesRepository {
7
20
  const rows = await this.query("SELECT * FROM bursar.get_billing_preferences($1::uuid)", [
8
21
  userId,
9
22
  ]);
10
- return rows[0] ?? null;
23
+ const row = optionalRecordRow(rows, "BillingPreferencesRepository.get");
24
+ if (row === null) {
25
+ return null;
26
+ }
27
+ const parsed = safeParse(BillingPreferencesRowSchema, {
28
+ subject_id: row.subject_id,
29
+ auto_recharge: row.auto_recharge,
30
+ overage_protection: row.overage_protection,
31
+ email_notifications: row.email_notifications,
32
+ usage_alerts: row.usage_alerts,
33
+ invoice_reminders: row.invoice_reminders,
34
+ }, "BillingPreferencesRepository.get");
35
+ return {
36
+ userId: parsed.subject_id,
37
+ autoRecharge: parsed.auto_recharge,
38
+ overageProtection: parsed.overage_protection,
39
+ emailNotifications: parsed.email_notifications,
40
+ usageAlerts: parsed.usage_alerts,
41
+ invoiceReminders: parsed.invoice_reminders,
42
+ };
11
43
  }
12
44
  async upsert(prefs) {
13
- await this.query("SELECT bursar.upsert_billing_preferences($1::uuid, $2, $3, $4, $5, $6)", [
45
+ const rows = await this.query("SELECT bursar.upsert_billing_preferences($1::uuid, $2, $3, $4, $5, $6) AS updated", [
14
46
  prefs.userId,
15
- prefs.autoRecharge ?? false,
16
- prefs.overageProtection ?? true,
17
- prefs.emailNotifications ?? true,
18
- prefs.usageAlerts ?? true,
19
- prefs.invoiceReminders ?? false,
47
+ prefs.autoRecharge,
48
+ prefs.overageProtection,
49
+ prefs.emailNotifications,
50
+ prefs.usageAlerts,
51
+ prefs.invoiceReminders,
20
52
  ]);
53
+ const updated = requireResultField(rows, "updated", pgBoolean, "BillingPreferencesRepository.upsert");
54
+ if (!updated) {
55
+ throw new StoreError("BillingPreferencesRepository.upsert: update was rejected", {
56
+ indeterminate: true,
57
+ });
58
+ }
21
59
  }
22
60
  }
23
61
  //# sourceMappingURL=preferences.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"preferences.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/preferences.ts"],"names":[],"mappings":"AAEA,MAAM,OAAO,4BAA4B;IACnB;IAApB,YAAoB,KAAc;QAAd,UAAK,GAAL,KAAK,CAAS;IAAG,CAAC;IAEtC,KAAK,CAAC,GAAG,CAAC,MAAc;QACtB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,wDAAwD,EAAE;YACtF,MAAM;SACP,CAAC,CAAC;QACH,OAAQ,IAAI,CAAC,CAAC,CAAyC,IAAI,IAAI,CAAC;IAClE,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,KAOZ;QACC,MAAM,IAAI,CAAC,KAAK,CAAC,wEAAwE,EAAE;YACzF,KAAK,CAAC,MAAM;YACZ,KAAK,CAAC,YAAY,IAAI,KAAK;YAC3B,KAAK,CAAC,iBAAiB,IAAI,IAAI;YAC/B,KAAK,CAAC,kBAAkB,IAAI,IAAI;YAChC,KAAK,CAAC,WAAW,IAAI,IAAI;YACzB,KAAK,CAAC,gBAAgB,IAAI,KAAK;SAChC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type { QueryFn } from \"../../../shared/postgres-types.js\";\n\nexport class BillingPreferencesRepository {\n constructor(private query: QueryFn) {}\n\n async get(userId: string): Promise<Record<string, unknown> | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_preferences($1::uuid)\", [\n userId,\n ]);\n return (rows[0] as Record<string, unknown> | undefined) ?? null;\n }\n\n async upsert(prefs: {\n userId: string;\n autoRecharge?: boolean;\n overageProtection?: boolean;\n emailNotifications?: boolean;\n usageAlerts?: boolean;\n invoiceReminders?: boolean;\n }): Promise<void> {\n await this.query(\"SELECT bursar.upsert_billing_preferences($1::uuid, $2, $3, $4, $5, $6)\", [\n prefs.userId,\n prefs.autoRecharge ?? false,\n prefs.overageProtection ?? true,\n prefs.emailNotifications ?? true,\n prefs.usageAlerts ?? true,\n prefs.invoiceReminders ?? false,\n ]);\n }\n}\n"]}
1
+ {"version":3,"file":"preferences.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/preferences.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,2BAA2B,GAAG,CAAC;KAClC,MAAM,CAAC;IACN,UAAU,EAAE,YAAY;IACxB,aAAa,EAAE,SAAS;IACxB,kBAAkB,EAAE,SAAS;IAC7B,mBAAmB,EAAE,SAAS;IAC9B,YAAY,EAAE,SAAS;IACvB,iBAAiB,EAAE,SAAS;CAC7B,CAAC;KACD,MAAM,EAAE,CAAC;AAEZ,MAAM,OAAO,4BAA4B;IACnB;IAApB,YAAoB,KAAc;QAAd,UAAK,GAAL,KAAK,CAAS;IAAG,CAAC;IAEtC,KAAK,CAAC,GAAG,CAAC,MAAc;QACtB,MA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AAI,UAAU,CAAC,0DAA0D,EAAE;gBAC/E,aAAa,EAAE,IAAI;aACpB,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { BillingPreferences } from \"../../types/index.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst BillingPreferencesRowSchema = z\n .object({\n subject_id: postgresUuid,\n auto_recharge: pgBoolean,\n overage_protection: pgBoolean,\n email_notifications: pgBoolean,\n usage_alerts: pgBoolean,\n invoice_reminders: pgBoolean,\n })\n .strict();\n\nexport class BillingPreferencesRepository {\n constructor(private query: QueryFn) {}\n\n async get(userId: string): Promise<BillingPreferences | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_preferences($1::uuid)\", [\n userId,\n ]);\n const row = optionalRecordRow(rows, \"BillingPreferencesRepository.get\");\n if (row === null) {\n return null;\n }\n const parsed = safeParse(\n BillingPreferencesRowSchema,\n {\n subject_id: row.subject_id,\n auto_recharge: row.auto_recharge,\n overage_protection: row.overage_protection,\n email_notifications: row.email_notifications,\n usage_alerts: row.usage_alerts,\n invoice_reminders: row.invoice_reminders,\n },\n \"BillingPreferencesRepository.get\",\n );\n return {\n userId: parsed.subject_id,\n autoRecharge: parsed.auto_recharge,\n overageProtection: parsed.overage_protection,\n emailNotifications: parsed.email_notifications,\n usageAlerts: parsed.usage_alerts,\n invoiceReminders: parsed.invoice_reminders,\n };\n }\n\n async upsert(prefs: BillingPreferences): Promise<void> {\n const rows = await this.query(\n \"SELECT bursar.upsert_billing_preferences($1::uuid, $2, $3, $4, $5, $6) AS updated\",\n [\n prefs.userId,\n prefs.autoRecharge,\n prefs.overageProtection,\n prefs.emailNotifications,\n prefs.usageAlerts,\n prefs.invoiceReminders,\n ],\n );\n const updated = requireResultField(\n rows,\n \"updated\",\n pgBoolean,\n \"BillingPreferencesRepository.upsert\",\n );\n if (!updated) {\n throw new StoreError(\"BillingPreferencesRepository.upsert: update was rejected\", {\n indeterminate: true,\n });\n }\n }\n}\n"]}
@@ -2,6 +2,6 @@ import type { QueryFn } from "../../../shared/postgres-types.js";
2
2
  export declare class BillingRefundRepository {
3
3
  private query;
4
4
  constructor(query: QueryFn);
5
- upsert(provider: string, providerRefundId: string, providerPaymentId: string | null, userId: string | null, amountMinor: number, currency: string, reason: string | null, metadata: string | null, status: string, providerUpdatedAt: string): Promise<string>;
5
+ upsert(provider: string, providerRefundId: string, providerPaymentId: string, userId: string, amountMinor: number, currency: string, reason: string | null, metadata: string | null, status: string, providerUpdatedAt: string): Promise<string>;
6
6
  }
7
7
  //# sourceMappingURL=refund.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"refund.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/refund.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAEjE,qBAAa,uBAAuB;IACtB,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAE5B,MAAM,CACV,QAAQ,EAAE,MAAM,EAChB,gBAAgB,EAAE,MAAM,EACxB,iBAAiB,EAAE,MAAM,GAAG,IAAI,EAChC,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,QAAQ,EAAE,MAAM,GAAG,IAAI,EACvB,MAAM,EAAE,MAAM,EACd,iBAAiB,EAAE,MAAM,GACxB,OAAO,CAAC,MAAM,CAAC;CA4BnB"}
1
+ {"version":3,"file":"refund.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/refund.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAQjE,qBAAa,uBAAuB;IACtB,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAE5B,MAAM,CACV,QAAQ,EAAE,MAAM,EAChB,gBAAgB,EAAE,MAAM,EACxB,iBAAiB,EAAE,MAAM,EACzB,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,QAAQ,EAAE,MAAM,GAAG,IAAI,EACvB,MAAM,EAAE,MAAM,EACd,iBAAiB,EAAE,MAAM,GACxB,OAAO,CAAC,MAAM,CAAC;CAoCnB"}
@@ -1,3 +1,5 @@
1
+ import { StoreError } from "../../../errors.js";
2
+ import { optionalRecordRow, postgresUuid, requireResultField, safeParse, } from "../../../shared/postgres-validation.js";
1
3
  export class BillingRefundRepository {
2
4
  query;
3
5
  constructor(query) {
@@ -5,14 +7,19 @@ export class BillingRefundRepository {
5
7
  }
6
8
  async upsert(provider, providerRefundId, providerPaymentId, userId, amountMinor, currency, reason, metadata, status, providerUpdatedAt) {
7
9
  if (!providerPaymentId)
8
- throw new Error("refund requires providerPaymentId");
10
+ throw new TypeError("refund requires providerPaymentId");
9
11
  const payments = await this.query("SELECT * FROM bursar.get_billing_payment_by_provider($1, $2)", [provider, providerPaymentId]);
10
- const paymentId = payments[0]?.id;
11
- if (!paymentId)
12
- throw new Error("refund payment not found");
12
+ const payment = optionalRecordRow(payments, "BillingRefundRepository.upsert.payment");
13
+ if (payment === null) {
14
+ throw new StoreError("refund payment not found", {
15
+ retryable: true,
16
+ details: { provider, providerPaymentId },
17
+ });
18
+ }
19
+ const paymentId = safeParse(postgresUuid, payment.id, "BillingRefundRepository.upsert.payment.id");
13
20
  const rows = await this.query(`SELECT bursar.upsert_billing_refund(
14
21
  $1::uuid, $2, $3, $4, $5, $6, $7::uuid, $8::char(3), $9::jsonb
15
- )`, [
22
+ ) AS id`, [
16
23
  paymentId,
17
24
  providerRefundId,
18
25
  amountMinor,
@@ -23,10 +30,7 @@ export class BillingRefundRepository {
23
30
  currency,
24
31
  metadata ?? "{}",
25
32
  ]);
26
- const refundId = rows[0]?.upsert_billing_refund;
27
- if (!refundId)
28
- throw new Error("billing refund upsert returned no ID");
29
- return String(refundId);
33
+ return requireResultField(rows, "id", postgresUuid, "BillingRefundRepository.upsert");
30
34
  }
31
35
  }
32
36
  //# sourceMappingURL=refund.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"refund.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/refund.ts"],"names":[],"mappings":"AAEA,MAAM,OAAO,uBAAuB;IACd;IAApB,YAAoB,KAAc;QAAd,UAAK,GAAL,KAAK,CAAS;IAAG,CAAC;IAEtC,KAAK,CAAC,MAAM,CACV,QAAgB,EAChB,gBAAwB,EACxB,iBAAgC,EAChC,MAAqB,EACrB,WAAmB,EACnB,QAAgB,EAChB,MAAqB,EACrB,QAAuB,EACvB,MAAc,EACd,iBAAyB;QAEzB,IAAI,CAAC,iBAAiB;YAAE,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;QAC7E,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,KAAK,CAC/B,8DAA8D,EAC9D,CAAC,QAAQ,EAAE,iBAAiB,CAAC,CAC9B,CAAC;QACF,MAAM,SAAS,GAAI,QAAQ,CAAC,CAAC,CAAyC,EAAE,EAAE,CAAC;QAC3E,IAAI,CAAC,SAAS;YAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;QAC5D,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B;;SAEG,EACH;YACE,SAAS;YACT,gBAAgB;YAChB,WAAW;YACX,MAAM;YACN,MAAM;YACN,iBAAiB;YACjB,MAAM;YACN,QAAQ;YACR,QAAQ,IAAI,IAAI;SACjB,CACF,CAAC;QACF,MAAM,QAAQ,GAAI,IAAI,CAAC,CAAC,CAAyC,EAAE,qBAAqB,CAAC;QACzF,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;QACvE,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC;IAC1B,CAAC;CACF","sourcesContent":["import type { QueryFn } from \"../../../shared/postgres-types.js\";\n\nexport class BillingRefundRepository {\n constructor(private query: QueryFn) {}\n\n async upsert(\n provider: string,\n providerRefundId: string,\n providerPaymentId: string | null,\n userId: string | null,\n amountMinor: number,\n currency: string,\n reason: string | null,\n metadata: string | null,\n status: string,\n providerUpdatedAt: string,\n ): Promise<string> {\n if (!providerPaymentId) throw new Error(\"refund requires providerPaymentId\");\n const payments = await this.query(\n \"SELECT * FROM bursar.get_billing_payment_by_provider($1, $2)\",\n [provider, providerPaymentId],\n );\n const paymentId = (payments[0] as Record<string, unknown> | undefined)?.id;\n if (!paymentId) throw new Error(\"refund payment not found\");\n const rows = await this.query(\n `SELECT bursar.upsert_billing_refund(\n $1::uuid, $2, $3, $4, $5, $6, $7::uuid, $8::char(3), $9::jsonb\n )`,\n [\n paymentId,\n providerRefundId,\n amountMinor,\n status,\n reason,\n providerUpdatedAt,\n userId,\n currency,\n metadata ?? \"{}\",\n ],\n );\n const refundId = (rows[0] as Record<string, unknown> | undefined)?.upsert_billing_refund;\n if (!refundId) throw new Error(\"billing refund upsert returned no ID\");\n return String(refundId);\n }\n}\n"]}
1
+ {"version":3,"file":"refund.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/refund.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,OAAO,uBAAuB;IACd;IAApB,YAAoB,KAAc;QAAd,UAAK,GAAL,KAAK,CAAS;IAAG,CAAC;IAEtC,KAAK,CAAC,MAAM,CACV,QAAgB,EAChB,gBAAwB,EACxB,iBAAyB,EACzB,MAAc,EACd,WAAmB,EACnB,QAAgB,EAChB,MAAqB,EACrB,QAAuB,EACvB,MAAc,EACd,iBAAyB;QAEzB,IAAI,CAAC,iBAAiB;YAAE,MAAM,IAAI,SAAS,CAAC,mCAAmC,CAAC,CAAC;QACjF,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,KAAK,CAC/B,8DAA8D,EAC9D,CAAC,QAAQ,EAAE,iBAAiB,CAAC,CAC9B,CAAC;QACF,MAAM,OAAO,GAAG,iBAAiB,CAAC,QAAQ,EAAE,wCAAwC,CAAC,CAAC;QACtF,IAAI,OAAO,KAAK,IAAI,EAAE,CAAC;YACrB,MAAM,IAAI,UAAU,CAAC,0BAA0B,EAAE;gBAC/C,SAAS,EAAE,IAAI;gBACf,OAAO,EAAE,EAAE,QAAQ,EAAE,iBAAiB,EAAE;aACzC,CAAC,CAAC;QACL,CAAC;QACD,MAAM,SAAS,GAAG,SAAS,CACzB,YAAY,EACZ,OAAO,CAAC,EAAE,EACV,2CAA2C,CAC5C,CAAC;QACF,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B;;eAES,EACT;YACE,SAAS;YACT,gBAAgB;YAChB,WAAW;YACX,MAAM;YACN,MAAM;YACN,iBAAiB;YACjB,MAAM;YACN,QAAQ;YACR,QAAQ,IAAI,IAAI;SACjB,CACF,CAAC;QACF,OAAO,kBAAkB,CAAC,IAAI,EAAE,IAAI,EAAE,YAAY,EAAE,gCAAgC,CAAC,CAAC;IACxF,CAAC;CACF","sourcesContent":["import { StoreError } from \"../../../errors.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nexport class BillingRefundRepository {\n constructor(private query: QueryFn) {}\n\n async upsert(\n provider: string,\n providerRefundId: string,\n providerPaymentId: string,\n userId: string,\n amountMinor: number,\n currency: string,\n reason: string | null,\n metadata: string | null,\n status: string,\n providerUpdatedAt: string,\n ): Promise<string> {\n if (!providerPaymentId) throw new TypeError(\"refund requires providerPaymentId\");\n const payments = await this.query(\n \"SELECT * FROM bursar.get_billing_payment_by_provider($1, $2)\",\n [provider, providerPaymentId],\n );\n const payment = optionalRecordRow(payments, \"BillingRefundRepository.upsert.payment\");\n if (payment === null) {\n throw new StoreError(\"refund payment not found\", {\n retryable: true,\n details: { provider, providerPaymentId },\n });\n }\n const paymentId = safeParse(\n postgresUuid,\n payment.id,\n \"BillingRefundRepository.upsert.payment.id\",\n );\n const rows = await this.query(\n `SELECT bursar.upsert_billing_refund(\n $1::uuid, $2, $3, $4, $5, $6, $7::uuid, $8::char(3), $9::jsonb\n ) AS id`,\n [\n paymentId,\n providerRefundId,\n amountMinor,\n status,\n reason,\n providerUpdatedAt,\n userId,\n currency,\n metadata ?? \"{}\",\n ],\n );\n return requireResultField(rows, \"id\", postgresUuid, \"BillingRefundRepository.upsert\");\n }\n}\n"]}
@@ -0,0 +1,15 @@
1
+ import type { BillingSubscriptionChangeUpdate } from "../../contracts.js";
2
+ import type { BillingSubscriptionChange, BillingSubscriptionChangeInput } from "../../types/index.js";
3
+ import type { QueryFn } from "../../../shared/postgres-types.js";
4
+ /** Persistence boundary for durable subscription offer transitions. */
5
+ export declare class BillingSubscriptionChangeRepository {
6
+ private readonly query;
7
+ constructor(query: QueryFn);
8
+ create(subscriptionId: string, input: BillingSubscriptionChangeInput): Promise<BillingSubscriptionChange>;
9
+ getById(id: string): Promise<BillingSubscriptionChange | null>;
10
+ getOpen(provider: string, providerSubscriptionId: string): Promise<BillingSubscriptionChange | null>;
11
+ update(id: string, update: BillingSubscriptionChangeUpdate): Promise<void>;
12
+ private parseOptional;
13
+ private getOfferContexts;
14
+ }
15
+ //# sourceMappingURL=subscription-change.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subscription-change.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription-change.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAO,KAAK,EACV,yBAAyB,EACzB,8BAA8B,EAE/B,MAAM,sBAAsB,CAAC;AAG9B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AA2HjE,uEAAuE;AACvE,qBAAa,mCAAmC;IAClC,OAAO,CAAC,QAAQ,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAErC,MAAM,CACV,cAAc,EAAE,MAAM,EACtB,KAAK,EAAE,8BAA8B,GACpC,OAAO,CAAC,yBAAyB,CAAC;IAuC/B,OAAO,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC;IAQ9D,OAAO,CACX,QAAQ,EAAE,MAAM,EAChB,sBAAsB,EAAE,MAAM,GAC7B,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC;IAQtC,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,+BAA+B,GAAG,OAAO,CAAC,IAAI,CAAC;YAoBlE,aAAa;YAyBb,gBAAgB;CAmD/B"}
@@ -0,0 +1,234 @@
1
+ import { z } from "zod";
2
+ import { StoreError } from "../../../errors.js";
3
+ import { optionalBoundedDiagnosticMessage } from "../../../shared/diagnostics.js";
4
+ import { optionalRecordRow, pgBoolean, postgresUuid, requireRecordRow, requireResultField, safeParse, } from "../../../shared/postgres-validation.js";
5
+ const timestamp = z
6
+ .union([
7
+ z.string().datetime({ offset: true }),
8
+ z.date().refine((value) => !Number.isNaN(value.getTime())),
9
+ ])
10
+ .transform((value) => (value instanceof Date ? value.toISOString() : value));
11
+ const positiveBigint = z
12
+ .union([z.string().regex(/^[1-9]\d*$/), z.number().int().positive().safe()])
13
+ .transform(String);
14
+ const changeState = z.enum(["awaiting_payment", "scheduled", "applied", "failed", "canceled"]);
15
+ const effectiveBehavior = z.enum(["immediate", "renewal"]);
16
+ const prorationBehavior = z.enum(["provider_default", "invoice_immediately", "none"]);
17
+ const OpenChangeResultSchema = z
18
+ .object({
19
+ change_id: positiveBigint.nullable(),
20
+ state: changeState.nullable(),
21
+ error_code: z
22
+ .enum([
23
+ "invalid_request",
24
+ "missing_subscription",
25
+ "invalid_target_offer",
26
+ "idempotency_conflict",
27
+ "open_change_exists",
28
+ ])
29
+ .nullable(),
30
+ })
31
+ .strict()
32
+ .superRefine((row, ctx) => {
33
+ const succeeded = row.error_code === null;
34
+ if (succeeded !== (row.change_id !== null && row.state !== null)) {
35
+ ctx.addIssue({
36
+ code: z.ZodIssueCode.custom,
37
+ message: "subscription-change result has inconsistent success fields",
38
+ });
39
+ }
40
+ });
41
+ const ChangeRowSchema = z
42
+ .object({
43
+ id: positiveBigint,
44
+ subscription_id: postgresUuid,
45
+ from_offer_id: postgresUuid,
46
+ from_catalog_revision_id: postgresUuid,
47
+ to_offer_id: postgresUuid,
48
+ to_catalog_revision_id: postgresUuid,
49
+ effective_at: timestamp.nullable(),
50
+ effective_behavior: effectiveBehavior,
51
+ state: changeState,
52
+ proration_behavior: prorationBehavior,
53
+ idempotency_key: z.string().min(1),
54
+ provider_operation_id: z.string().min(1).nullable(),
55
+ error_message: z.string().min(1).max(8192).nullable(),
56
+ })
57
+ .strict();
58
+ const OfferContextRowSchema = z
59
+ .object({
60
+ side: z.enum(["from", "to"]),
61
+ offer_id: postgresUuid,
62
+ offer_key: z.string().min(1),
63
+ plan_id: postgresUuid,
64
+ plan_key: z.string().min(1),
65
+ billing_unit: z.enum(["day", "week", "month", "year"]),
66
+ billing_count: z.number().int().positive(),
67
+ })
68
+ .strict();
69
+ function projectChange(row) {
70
+ return {
71
+ id: row.id,
72
+ subscription_id: row.subscription_id,
73
+ from_offer_id: row.from_offer_id,
74
+ from_catalog_revision_id: row.from_catalog_revision_id,
75
+ to_offer_id: row.to_offer_id,
76
+ to_catalog_revision_id: row.to_catalog_revision_id,
77
+ effective_at: row.effective_at,
78
+ effective_behavior: row.effective_behavior,
79
+ state: row.state,
80
+ proration_behavior: row.proration_behavior,
81
+ idempotency_key: row.idempotency_key,
82
+ provider_operation_id: row.provider_operation_id,
83
+ error_message: row.error_message,
84
+ };
85
+ }
86
+ function projectContext(row) {
87
+ return {
88
+ side: row.side,
89
+ offer_id: row.offer_id,
90
+ offer_key: row.offer_key,
91
+ plan_id: row.plan_id,
92
+ plan_key: row.plan_key,
93
+ billing_unit: row.billing_unit,
94
+ billing_count: row.billing_count,
95
+ };
96
+ }
97
+ function publicContext(row) {
98
+ return {
99
+ offerId: row.offer_id,
100
+ offerKey: row.offer_key,
101
+ planId: row.plan_id,
102
+ plan: row.plan_key,
103
+ interval: row.billing_unit,
104
+ intervalCount: row.billing_count,
105
+ };
106
+ }
107
+ /** Persistence boundary for durable subscription offer transitions. */
108
+ export class BillingSubscriptionChangeRepository {
109
+ query;
110
+ constructor(query) {
111
+ this.query = query;
112
+ }
113
+ async create(subscriptionId, input) {
114
+ const rows = await this.query(`SELECT * FROM bursar.open_subscription_change(
115
+ $1::uuid, $2::uuid, $3::timestamptz, $4, $5, $6
116
+ )`, [
117
+ subscriptionId,
118
+ input.toOfferId,
119
+ input.effectiveAt,
120
+ input.effective,
121
+ input.idempotencyKey,
122
+ input.prorationBehavior ?? "provider_default",
123
+ ]);
124
+ const raw = requireRecordRow(rows, "BillingSubscriptionChangeRepository.create");
125
+ const result = safeParse(OpenChangeResultSchema, { change_id: raw.change_id, state: raw.state, error_code: raw.error_code }, "BillingSubscriptionChangeRepository.create", { indeterminate: true });
126
+ if (result.error_code !== null) {
127
+ throw new StoreError(`subscription change rejected: ${result.error_code}`, {
128
+ details: { errorCode: result.error_code },
129
+ });
130
+ }
131
+ if (result.change_id === null) {
132
+ throw new StoreError("subscription change returned no identifier", { indeterminate: true });
133
+ }
134
+ const change = await this.getById(result.change_id);
135
+ if (change === null) {
136
+ throw new StoreError("subscription change could not be read after creation", {
137
+ indeterminate: true,
138
+ details: { subscriptionChangeId: result.change_id },
139
+ });
140
+ }
141
+ return change;
142
+ }
143
+ async getById(id) {
144
+ const rows = await this.query("SELECT * FROM bursar.get_billing_subscription_change($1::bigint)", [id]);
145
+ return this.parseOptional(rows, "BillingSubscriptionChangeRepository.getById");
146
+ }
147
+ async getOpen(provider, providerSubscriptionId) {
148
+ const rows = await this.query("SELECT * FROM bursar.get_open_billing_subscription_change($1, $2)", [provider, providerSubscriptionId]);
149
+ return this.parseOptional(rows, "BillingSubscriptionChangeRepository.getOpen");
150
+ }
151
+ async update(id, update) {
152
+ if (update.state === undefined)
153
+ return;
154
+ const rows = await this.query("SELECT bursar.advance_subscription_change($1::bigint, $2, $3, $4) AS advanced", [
155
+ id,
156
+ update.state,
157
+ update.providerOperationId ?? null,
158
+ optionalBoundedDiagnosticMessage(update.errorMessage),
159
+ ]);
160
+ if (!requireResultField(rows, "advanced", pgBoolean, "BillingSubscriptionChangeRepository.update")) {
161
+ throw new StoreError(`subscription change transition rejected: ${id}`, {
162
+ details: { subscriptionChangeId: id },
163
+ });
164
+ }
165
+ }
166
+ async parseOptional(rows, context) {
167
+ const raw = optionalRecordRow(rows, context);
168
+ if (raw === null)
169
+ return null;
170
+ const row = safeParse(ChangeRowSchema, projectChange(raw), context);
171
+ const contexts = await this.getOfferContexts(row, context);
172
+ return {
173
+ id: row.id,
174
+ subscriptionId: row.subscription_id,
175
+ fromOfferId: row.from_offer_id,
176
+ toOfferId: row.to_offer_id,
177
+ fromOffer: publicContext(contexts.from),
178
+ toOffer: publicContext(contexts.to),
179
+ effectiveAt: row.effective_at,
180
+ effective: row.effective_behavior,
181
+ state: row.state,
182
+ prorationBehavior: row.proration_behavior,
183
+ idempotencyKey: row.idempotency_key,
184
+ providerOperationId: row.provider_operation_id,
185
+ errorMessage: row.error_message,
186
+ };
187
+ }
188
+ async getOfferContexts(row, context) {
189
+ const rows = await this.query(`SELECT requested.side, requested.offer_id, offer_context.*
190
+ FROM (
191
+ VALUES
192
+ ('from', $1::uuid, $2::uuid),
193
+ ('to', $3::uuid, $4::uuid)
194
+ ) AS requested(side, offer_id, catalog_revision_id)
195
+ CROSS JOIN LATERAL bursar.get_catalog_offer_context(
196
+ requested.offer_id,
197
+ requested.catalog_revision_id
198
+ ) AS offer_context`, [
199
+ row.from_offer_id,
200
+ row.from_catalog_revision_id,
201
+ row.to_offer_id,
202
+ row.to_catalog_revision_id,
203
+ ]);
204
+ if (rows.length !== 2) {
205
+ throw new StoreError(`${context}: expected both subscription-change offer contexts`, {
206
+ details: { subscriptionChangeId: row.id, rowCount: rows.length },
207
+ });
208
+ }
209
+ const parsed = rows.map((candidate, index) => {
210
+ if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate)) {
211
+ throw new StoreError(`${context}: malformed subscription-change offer context`, {
212
+ details: { subscriptionChangeId: row.id, index },
213
+ });
214
+ }
215
+ const record = candidate;
216
+ return safeParse(OfferContextRowSchema, projectContext(record), `${context}.context`);
217
+ });
218
+ const bySide = new Map(parsed.map((candidate) => [candidate.side, candidate]));
219
+ const from = bySide.get("from");
220
+ const to = bySide.get("to");
221
+ if (bySide.size !== 2 || from === undefined || to === undefined) {
222
+ throw new StoreError(`${context}: duplicate or missing subscription-change offer context`, {
223
+ details: { subscriptionChangeId: row.id },
224
+ });
225
+ }
226
+ if (from.offer_id !== row.from_offer_id || to.offer_id !== row.to_offer_id) {
227
+ throw new StoreError(`${context}: subscription-change offer context does not match`, {
228
+ details: { subscriptionChangeId: row.id },
229
+ });
230
+ }
231
+ return { from, to };
232
+ }
233
+ }
234
+ //# sourceMappingURL=subscription-change.js.map