@zonastery/bursar 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (404) hide show
  1. package/README.md +189 -62
  2. package/dist/billing/auto-recharge-port.d.ts +3 -3
  3. package/dist/billing/auto-recharge-port.d.ts.map +1 -1
  4. package/dist/billing/auto-recharge-port.js.map +1 -1
  5. package/dist/billing/auto-recharge-service.d.ts +5 -4
  6. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  7. package/dist/billing/auto-recharge-service.js +64 -34
  8. package/dist/billing/auto-recharge-service.js.map +1 -1
  9. package/dist/billing/billing-service.d.ts +5 -5
  10. package/dist/billing/billing-service.d.ts.map +1 -1
  11. package/dist/billing/billing-service.js +2 -2
  12. package/dist/billing/billing-service.js.map +1 -1
  13. package/dist/billing/billing-store.d.ts +10 -9
  14. package/dist/billing/billing-store.d.ts.map +1 -1
  15. package/dist/billing/billing-store.js.map +1 -1
  16. package/dist/billing/contracts.d.ts +31 -31
  17. package/dist/billing/contracts.d.ts.map +1 -1
  18. package/dist/billing/contracts.js.map +1 -1
  19. package/dist/billing/event-handlers.d.ts.map +1 -1
  20. package/dist/billing/event-handlers.js +49 -10
  21. package/dist/billing/event-handlers.js.map +1 -1
  22. package/dist/billing/event-processor.d.ts +1 -0
  23. package/dist/billing/event-processor.d.ts.map +1 -1
  24. package/dist/billing/event-processor.js +37 -10
  25. package/dist/billing/event-processor.js.map +1 -1
  26. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  27. package/dist/billing/financial-event-handlers.js +69 -72
  28. package/dist/billing/financial-event-handlers.js.map +1 -1
  29. package/dist/billing/index.d.ts +2 -1
  30. package/dist/billing/index.d.ts.map +1 -1
  31. package/dist/billing/index.js.map +1 -1
  32. package/dist/billing/management.d.ts +5 -5
  33. package/dist/billing/management.d.ts.map +1 -1
  34. package/dist/billing/management.js +2 -2
  35. package/dist/billing/management.js.map +1 -1
  36. package/dist/billing/policy-window.js.map +1 -1
  37. package/dist/billing/postgres/repositories/auto-recharge.d.ts +3 -3
  38. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  39. package/dist/billing/postgres/repositories/auto-recharge.js +205 -60
  40. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  41. package/dist/billing/postgres/repositories/customer.d.ts.map +1 -1
  42. package/dist/billing/postgres/repositories/customer.js +19 -11
  43. package/dist/billing/postgres/repositories/customer.js.map +1 -1
  44. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
  45. package/dist/billing/postgres/repositories/dispute.js +3 -1
  46. package/dist/billing/postgres/repositories/dispute.js.map +1 -1
  47. package/dist/billing/postgres/repositories/event.d.ts +14 -7
  48. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  49. package/dist/billing/postgres/repositories/event.js +21 -20
  50. package/dist/billing/postgres/repositories/event.js.map +1 -1
  51. package/dist/billing/postgres/repositories/invoice.d.ts +3 -3
  52. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  53. package/dist/billing/postgres/repositories/invoice.js +53 -11
  54. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  55. package/dist/billing/postgres/repositories/offer.d.ts +20 -17
  56. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  57. package/dist/billing/postgres/repositories/offer.js +123 -57
  58. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  59. package/dist/billing/postgres/repositories/payment.d.ts +23 -20
  60. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  61. package/dist/billing/postgres/repositories/payment.js +43 -37
  62. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  63. package/dist/billing/postgres/repositories/preferences.d.ts +3 -9
  64. package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -1
  65. package/dist/billing/postgres/repositories/preferences.js +45 -7
  66. package/dist/billing/postgres/repositories/preferences.js.map +1 -1
  67. package/dist/billing/postgres/repositories/refund.d.ts +1 -1
  68. package/dist/billing/postgres/repositories/refund.d.ts.map +1 -1
  69. package/dist/billing/postgres/repositories/refund.js +13 -9
  70. package/dist/billing/postgres/repositories/refund.js.map +1 -1
  71. package/dist/billing/postgres/repositories/subscription-change.d.ts +15 -0
  72. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -0
  73. package/dist/billing/postgres/repositories/subscription-change.js +234 -0
  74. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -0
  75. package/dist/billing/postgres/repositories/subscription.d.ts +38 -17
  76. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  77. package/dist/billing/postgres/repositories/subscription.js +199 -91
  78. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  79. package/dist/billing/postgres/repositories/topup.d.ts +13 -15
  80. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  81. package/dist/billing/postgres/repositories/topup.js +65 -34
  82. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  83. package/dist/billing/postgres/store.d.ts +23 -14
  84. package/dist/billing/postgres/store.d.ts.map +1 -1
  85. package/dist/billing/postgres/store.js +265 -228
  86. package/dist/billing/postgres/store.js.map +1 -1
  87. package/dist/billing/service-types.d.ts +6 -5
  88. package/dist/billing/service-types.d.ts.map +1 -1
  89. package/dist/billing/service-types.js.map +1 -1
  90. package/dist/billing/types/auto-recharge.d.ts +6 -4
  91. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  92. package/dist/billing/types/auto-recharge.js.map +1 -1
  93. package/dist/billing/types/catalog.d.ts +18 -35
  94. package/dist/billing/types/catalog.d.ts.map +1 -1
  95. package/dist/billing/types/catalog.js.map +1 -1
  96. package/dist/billing/types/common.d.ts +0 -1
  97. package/dist/billing/types/common.d.ts.map +1 -1
  98. package/dist/billing/types/common.js.map +1 -1
  99. package/dist/billing/types/documents.d.ts +38 -12
  100. package/dist/billing/types/documents.d.ts.map +1 -1
  101. package/dist/billing/types/documents.js.map +1 -1
  102. package/dist/billing/types/events.d.ts +2 -0
  103. package/dist/billing/types/events.d.ts.map +1 -1
  104. package/dist/billing/types/events.js +238 -0
  105. package/dist/billing/types/events.js.map +1 -1
  106. package/dist/billing/types/index.js.map +1 -1
  107. package/dist/billing/types/preferences.js.map +1 -1
  108. package/dist/billing/types/subscriptions.d.ts +8 -8
  109. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  110. package/dist/billing/types/subscriptions.js.map +1 -1
  111. package/dist/breakdown.js.map +1 -1
  112. package/dist/browser.js.map +1 -1
  113. package/dist/bursar.d.ts +33 -11
  114. package/dist/bursar.d.ts.map +1 -1
  115. package/dist/bursar.js +58 -22
  116. package/dist/bursar.js.map +1 -1
  117. package/dist/catalog.d.ts +1 -0
  118. package/dist/catalog.d.ts.map +1 -1
  119. package/dist/catalog.js +1 -0
  120. package/dist/catalog.js.map +1 -1
  121. package/dist/commerce/errors.d.ts +4 -14
  122. package/dist/commerce/errors.d.ts.map +1 -1
  123. package/dist/commerce/errors.js +4 -21
  124. package/dist/commerce/errors.js.map +1 -1
  125. package/dist/commerce/index.d.ts +1 -0
  126. package/dist/commerce/index.d.ts.map +1 -1
  127. package/dist/commerce/index.js.map +1 -1
  128. package/dist/commerce/plan-change.js.map +1 -1
  129. package/dist/commerce/provider-registry.d.ts.map +1 -1
  130. package/dist/commerce/provider-registry.js +27 -2
  131. package/dist/commerce/provider-registry.js.map +1 -1
  132. package/dist/commerce/service.d.ts +15 -7
  133. package/dist/commerce/service.d.ts.map +1 -1
  134. package/dist/commerce/service.js +130 -77
  135. package/dist/commerce/service.js.map +1 -1
  136. package/dist/commerce/types.d.ts +33 -13
  137. package/dist/commerce/types.d.ts.map +1 -1
  138. package/dist/commerce/types.js.map +1 -1
  139. package/dist/config/parse-access.js.map +1 -1
  140. package/dist/config/parse-commerce.js.map +1 -1
  141. package/dist/config/parse-credits.js.map +1 -1
  142. package/dist/config/parse-plans.d.ts.map +1 -1
  143. package/dist/config/parse-plans.js +30 -13
  144. package/dist/config/parse-plans.js.map +1 -1
  145. package/dist/config/parse-pricing.d.ts.map +1 -1
  146. package/dist/config/parse-pricing.js +16 -5
  147. package/dist/config/parse-pricing.js.map +1 -1
  148. package/dist/config/parse-utils.js.map +1 -1
  149. package/dist/config/types.d.ts +14 -1
  150. package/dist/config/types.d.ts.map +1 -1
  151. package/dist/config/types.js.map +1 -1
  152. package/dist/config.d.ts +7 -1
  153. package/dist/config.d.ts.map +1 -1
  154. package/dist/config.js +64 -1
  155. package/dist/config.js.map +1 -1
  156. package/dist/credits/{pricing-runtime.d.ts → catalog-runtime.d.ts} +9 -8
  157. package/dist/credits/catalog-runtime.d.ts.map +1 -0
  158. package/dist/credits/{pricing-runtime.js → catalog-runtime.js} +58 -38
  159. package/dist/credits/catalog-runtime.js.map +1 -0
  160. package/dist/credits/events.d.ts +4 -4
  161. package/dist/credits/events.d.ts.map +1 -1
  162. package/dist/credits/events.js +1 -1
  163. package/dist/credits/events.js.map +1 -1
  164. package/dist/credits/lease-workflow.d.ts +14 -14
  165. package/dist/credits/lease-workflow.d.ts.map +1 -1
  166. package/dist/credits/lease-workflow.js +18 -17
  167. package/dist/credits/lease-workflow.js.map +1 -1
  168. package/dist/credits/low-balance-monitor.d.ts +2 -2
  169. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  170. package/dist/credits/low-balance-monitor.js.map +1 -1
  171. package/dist/credits/postgres/repositories/analytics.d.ts +39 -35
  172. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  173. package/dist/credits/postgres/repositories/analytics.js +55 -53
  174. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  175. package/dist/credits/postgres/repositories/balance.d.ts +28 -30
  176. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  177. package/dist/credits/postgres/repositories/balance.js +100 -59
  178. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  179. package/dist/credits/postgres/repositories/bucket.d.ts +14 -8
  180. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
  181. package/dist/credits/postgres/repositories/bucket.js +22 -21
  182. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  183. package/dist/credits/postgres/repositories/catalog.d.ts +31 -0
  184. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -0
  185. package/dist/credits/postgres/repositories/catalog.js +90 -0
  186. package/dist/credits/postgres/repositories/catalog.js.map +1 -0
  187. package/dist/credits/postgres/repositories/deduction.d.ts +32 -21
  188. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  189. package/dist/credits/postgres/repositories/deduction.js +171 -62
  190. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  191. package/dist/credits/postgres/repositories/lease.d.ts +21 -18
  192. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  193. package/dist/credits/postgres/repositories/lease.js +157 -65
  194. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  195. package/dist/credits/postgres/repositories/plan.d.ts +94 -42
  196. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
  197. package/dist/credits/postgres/repositories/plan.js +134 -104
  198. package/dist/credits/postgres/repositories/plan.js.map +1 -1
  199. package/dist/credits/postgres/repositories/team.d.ts +36 -27
  200. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  201. package/dist/credits/postgres/repositories/team.js +96 -52
  202. package/dist/credits/postgres/repositories/team.js.map +1 -1
  203. package/dist/credits/postgres/store.d.ts +31 -21
  204. package/dist/credits/postgres/store.d.ts.map +1 -1
  205. package/dist/credits/postgres/store.js +325 -235
  206. package/dist/credits/postgres/store.js.map +1 -1
  207. package/dist/credits/postgres/value-mappers.d.ts +7 -9
  208. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  209. package/dist/credits/postgres/value-mappers.js +42 -63
  210. package/dist/credits/postgres/value-mappers.js.map +1 -1
  211. package/dist/credits/queries.d.ts +5 -5
  212. package/dist/credits/queries.d.ts.map +1 -1
  213. package/dist/credits/queries.js +4 -4
  214. package/dist/credits/queries.js.map +1 -1
  215. package/dist/credits/service-errors.js.map +1 -1
  216. package/dist/credits/service-types.d.ts +42 -7
  217. package/dist/credits/service-types.d.ts.map +1 -1
  218. package/dist/credits/service-types.js.map +1 -1
  219. package/dist/credits/service.d.ts +51 -58
  220. package/dist/credits/service.d.ts.map +1 -1
  221. package/dist/credits/service.js +178 -113
  222. package/dist/credits/service.js.map +1 -1
  223. package/dist/credits/store.d.ts +25 -22
  224. package/dist/credits/store.d.ts.map +1 -1
  225. package/dist/credits/store.js +9 -5
  226. package/dist/credits/store.js.map +1 -1
  227. package/dist/credits/types/account.d.ts +50 -12
  228. package/dist/credits/types/account.d.ts.map +1 -1
  229. package/dist/credits/types/account.js.map +1 -1
  230. package/dist/credits/types/admission.d.ts +17 -6
  231. package/dist/credits/types/admission.d.ts.map +1 -1
  232. package/dist/credits/types/admission.js.map +1 -1
  233. package/dist/credits/types/analytics.d.ts +2 -2
  234. package/dist/credits/types/analytics.d.ts.map +1 -1
  235. package/dist/credits/types/analytics.js.map +1 -1
  236. package/dist/credits/types/catalog.d.ts +21 -14
  237. package/dist/credits/types/catalog.d.ts.map +1 -1
  238. package/dist/credits/types/catalog.js.map +1 -1
  239. package/dist/credits/types/grants.d.ts +22 -8
  240. package/dist/credits/types/grants.d.ts.map +1 -1
  241. package/dist/credits/types/grants.js.map +1 -1
  242. package/dist/credits/types/index.js.map +1 -1
  243. package/dist/credits/types/ledger.d.ts +19 -0
  244. package/dist/credits/types/ledger.d.ts.map +1 -1
  245. package/dist/credits/types/ledger.js.map +1 -1
  246. package/dist/credits/types/quotas.js.map +1 -1
  247. package/dist/credits/types/teams.d.ts +18 -6
  248. package/dist/credits/types/teams.d.ts.map +1 -1
  249. package/dist/credits/types/teams.js.map +1 -1
  250. package/dist/engine.d.ts.map +1 -1
  251. package/dist/engine.js +24 -10
  252. package/dist/engine.js.map +1 -1
  253. package/dist/errors.d.ts +105 -8
  254. package/dist/errors.d.ts.map +1 -1
  255. package/dist/errors.js +137 -9
  256. package/dist/errors.js.map +1 -1
  257. package/dist/expr/ast.d.ts.map +1 -1
  258. package/dist/expr/ast.js.map +1 -1
  259. package/dist/expr/evaluator.d.ts.map +1 -1
  260. package/dist/expr/evaluator.js +29 -17
  261. package/dist/expr/evaluator.js.map +1 -1
  262. package/dist/expr/language.js.map +1 -1
  263. package/dist/expr/parser.d.ts.map +1 -1
  264. package/dist/expr/parser.js +11 -4
  265. package/dist/expr/parser.js.map +1 -1
  266. package/dist/expr/tokenizer.d.ts.map +1 -1
  267. package/dist/expr/tokenizer.js +17 -13
  268. package/dist/expr/tokenizer.js.map +1 -1
  269. package/dist/expr.d.ts +2 -2
  270. package/dist/expr.d.ts.map +1 -1
  271. package/dist/expr.js +7 -9
  272. package/dist/expr.js.map +1 -1
  273. package/dist/generated/pricing-config.schema.json +30 -9
  274. package/dist/generated/pricing-config.types.d.ts +14 -3
  275. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  276. package/dist/generated/pricing-config.types.js.map +1 -1
  277. package/dist/index.d.ts +11 -7
  278. package/dist/index.d.ts.map +1 -1
  279. package/dist/index.js +2 -2
  280. package/dist/index.js.map +1 -1
  281. package/dist/integrations/better-auth.d.ts +23 -0
  282. package/dist/integrations/better-auth.d.ts.map +1 -0
  283. package/dist/integrations/better-auth.js +54 -0
  284. package/dist/integrations/better-auth.js.map +1 -0
  285. package/dist/{load-pricing-file.d.ts → load-config-file.d.ts} +4 -4
  286. package/dist/load-config-file.d.ts.map +1 -0
  287. package/dist/{load-pricing-file.js → load-config-file.js} +23 -14
  288. package/dist/load-config-file.js.map +1 -0
  289. package/dist/metrics.js.map +1 -1
  290. package/dist/node.d.ts +3 -3
  291. package/dist/node.d.ts.map +1 -1
  292. package/dist/node.js +2 -2
  293. package/dist/node.js.map +1 -1
  294. package/dist/providers/_shared.d.ts +5 -0
  295. package/dist/providers/_shared.d.ts.map +1 -1
  296. package/dist/providers/_shared.js +77 -14
  297. package/dist/providers/_shared.js.map +1 -1
  298. package/dist/providers/dodo/better-auth.d.ts +29 -0
  299. package/dist/providers/dodo/better-auth.d.ts.map +1 -0
  300. package/dist/providers/dodo/better-auth.js +23 -0
  301. package/dist/providers/dodo/better-auth.js.map +1 -0
  302. package/dist/providers/dodo/client-contract.d.ts +32 -70
  303. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  304. package/dist/providers/dodo/client-contract.js.map +1 -1
  305. package/dist/providers/dodo/event-mapper.d.ts +3 -1
  306. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  307. package/dist/providers/dodo/event-mapper.js +219 -148
  308. package/dist/providers/dodo/event-mapper.js.map +1 -1
  309. package/dist/providers/dodo/index.d.ts +5 -2
  310. package/dist/providers/dodo/index.d.ts.map +1 -1
  311. package/dist/providers/dodo/index.js +2 -1
  312. package/dist/providers/dodo/index.js.map +1 -1
  313. package/dist/providers/dodo/nextjs.d.ts +16 -0
  314. package/dist/providers/dodo/nextjs.d.ts.map +1 -0
  315. package/dist/providers/dodo/nextjs.js +16 -0
  316. package/dist/providers/dodo/nextjs.js.map +1 -0
  317. package/dist/providers/dodo/provider.d.ts +30 -11
  318. package/dist/providers/dodo/provider.d.ts.map +1 -1
  319. package/dist/providers/dodo/provider.js +192 -122
  320. package/dist/providers/dodo/provider.js.map +1 -1
  321. package/dist/providers/dodo/react-native.d.ts +56 -0
  322. package/dist/providers/dodo/react-native.d.ts.map +1 -0
  323. package/dist/providers/dodo/react-native.js +57 -0
  324. package/dist/providers/dodo/react-native.js.map +1 -0
  325. package/dist/providers/dodo/webhook-bridge.d.ts +17 -0
  326. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -0
  327. package/dist/providers/dodo/webhook-bridge.js +21 -0
  328. package/dist/providers/dodo/webhook-bridge.js.map +1 -0
  329. package/dist/providers/index.d.ts +1 -1
  330. package/dist/providers/index.d.ts.map +1 -1
  331. package/dist/providers/index.js.map +1 -1
  332. package/dist/providers/mock/index.d.ts +1 -0
  333. package/dist/providers/mock/index.d.ts.map +1 -1
  334. package/dist/providers/mock/index.js.map +1 -1
  335. package/dist/providers/mock/provider.d.ts +8 -8
  336. package/dist/providers/mock/provider.d.ts.map +1 -1
  337. package/dist/providers/mock/provider.js +26 -19
  338. package/dist/providers/mock/provider.js.map +1 -1
  339. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  340. package/dist/providers/stripe/event-mapper.js +214 -173
  341. package/dist/providers/stripe/event-mapper.js.map +1 -1
  342. package/dist/providers/stripe/index.d.ts +1 -0
  343. package/dist/providers/stripe/index.d.ts.map +1 -1
  344. package/dist/providers/stripe/index.js.map +1 -1
  345. package/dist/providers/stripe/provider.d.ts +13 -11
  346. package/dist/providers/stripe/provider.d.ts.map +1 -1
  347. package/dist/providers/stripe/provider.js +287 -107
  348. package/dist/providers/stripe/provider.js.map +1 -1
  349. package/dist/providers/types.d.ts +1 -2
  350. package/dist/providers/types.d.ts.map +1 -1
  351. package/dist/providers/types.js.map +1 -1
  352. package/dist/retry.d.ts +26 -4
  353. package/dist/retry.d.ts.map +1 -1
  354. package/dist/retry.js +65 -23
  355. package/dist/retry.js.map +1 -1
  356. package/dist/shared/diagnostics.d.ts +7 -0
  357. package/dist/shared/diagnostics.d.ts.map +1 -0
  358. package/dist/shared/diagnostics.js +18 -0
  359. package/dist/shared/diagnostics.js.map +1 -0
  360. package/dist/shared/logger.js.map +1 -1
  361. package/dist/shared/postgres-client.d.ts +43 -5
  362. package/dist/shared/postgres-client.d.ts.map +1 -1
  363. package/dist/shared/postgres-client.js +282 -30
  364. package/dist/shared/postgres-client.js.map +1 -1
  365. package/dist/shared/postgres-errors.d.ts +11 -0
  366. package/dist/shared/postgres-errors.d.ts.map +1 -0
  367. package/dist/shared/postgres-errors.js +105 -0
  368. package/dist/shared/postgres-errors.js.map +1 -0
  369. package/dist/shared/postgres-types.js.map +1 -1
  370. package/dist/shared/postgres-validation.d.ts +15 -3
  371. package/dist/shared/postgres-validation.d.ts.map +1 -1
  372. package/dist/shared/postgres-validation.js +58 -14
  373. package/dist/shared/postgres-validation.js.map +1 -1
  374. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  375. package/dist/storage/adapters/clickhouse.js +18 -3
  376. package/dist/storage/adapters/clickhouse.js.map +1 -1
  377. package/dist/storage/adapters/s3.d.ts +0 -6
  378. package/dist/storage/adapters/s3.d.ts.map +1 -1
  379. package/dist/storage/adapters/s3.js +0 -2
  380. package/dist/storage/adapters/s3.js.map +1 -1
  381. package/dist/storage/outbox-worker.d.ts +2 -1
  382. package/dist/storage/outbox-worker.d.ts.map +1 -1
  383. package/dist/storage/outbox-worker.js +17 -3
  384. package/dist/storage/outbox-worker.js.map +1 -1
  385. package/dist/storage/ports.d.ts +1 -1
  386. package/dist/storage/ports.d.ts.map +1 -1
  387. package/dist/storage/ports.js.map +1 -1
  388. package/dist/storage/postgres-repository.d.ts +1 -1
  389. package/dist/storage/postgres-repository.d.ts.map +1 -1
  390. package/dist/storage/postgres-repository.js +13 -3
  391. package/dist/storage/postgres-repository.js.map +1 -1
  392. package/dist/storage/runtime.d.ts +35 -7
  393. package/dist/storage/runtime.d.ts.map +1 -1
  394. package/dist/storage/runtime.js +166 -53
  395. package/dist/storage/runtime.js.map +1 -1
  396. package/package.json +62 -7
  397. package/dist/credits/postgres/repositories/pricing.d.ts +0 -28
  398. package/dist/credits/postgres/repositories/pricing.d.ts.map +0 -1
  399. package/dist/credits/postgres/repositories/pricing.js +0 -70
  400. package/dist/credits/postgres/repositories/pricing.js.map +0 -1
  401. package/dist/credits/pricing-runtime.d.ts.map +0 -1
  402. package/dist/credits/pricing-runtime.js.map +0 -1
  403. package/dist/load-pricing-file.d.ts.map +0 -1
  404. package/dist/load-pricing-file.js.map +0 -1
@@ -1,73 +1,139 @@
1
+ import Decimal from "decimal.js";
1
2
  import { z } from "zod";
2
- import { pgBoolean, unwrapJsonb, safeParse } from "../../../shared/postgres-validation.js";
3
- const BillingOfferRowSchema = z
3
+ import { StoreError } from "../../../errors.js";
4
+ import { postgresUuid, safeParse, unwrapJsonb } from "../../../shared/postgres-validation.js";
5
+ const PositiveDecimalSchema = z
6
+ .union([z.string(), z.number(), z.instanceof(Decimal)])
7
+ .transform((value) => new Decimal(value))
8
+ .refine((value) => value.isFinite() && value.gt(0), "expected a finite positive decimal");
9
+ const CatalogOfferRowSchema = z
4
10
  .object({
5
- id: z.string().optional(),
6
- plan_id: z.string().nullable().optional(),
7
- offer_key: z.string().optional(),
8
- plan: z.string().nullable().optional(),
9
- interval: z.string().optional(),
10
- interval_count: z.number().optional(),
11
- grant_mode: z.string().optional(),
12
- grant_credits: z
13
- .union([z.string(), z.number()])
14
- .nullable()
15
- .optional(),
16
- grant_bucket: z.string().nullable().optional(),
17
- grant_replace_prior: pgBoolean.nullable().optional(),
11
+ id: postgresUuid,
12
+ catalog_revision_id: postgresUuid,
13
+ offer_key: z.string().min(1),
14
+ plan_key: z.string().min(1),
15
+ billing_unit: z.enum(["day", "week", "month", "year"]),
16
+ billing_count: z.number().int().positive(),
17
+ cycle_grant_amount: PositiveDecimalSchema.nullable(),
18
+ cycle_grant_bucket_key: z.string().min(1).nullable(),
19
+ cycle_grant_renewal: z.enum(["replace_previous", "accumulate"]).nullable(),
18
20
  })
19
- .passthrough();
21
+ .strict()
22
+ .superRefine((row, ctx) => {
23
+ const grantFields = [
24
+ row.cycle_grant_amount,
25
+ row.cycle_grant_bucket_key,
26
+ row.cycle_grant_renewal,
27
+ ];
28
+ if (grantFields.some((value) => value !== null) &&
29
+ grantFields.some((value) => value === null)) {
30
+ ctx.addIssue({
31
+ code: z.ZodIssueCode.custom,
32
+ message: "cycle grant fields must either all be set or all be null",
33
+ });
34
+ }
35
+ });
36
+ const OfferContextRowSchema = z
37
+ .object({
38
+ offer_key: z.string().min(1),
39
+ plan_id: postgresUuid,
40
+ plan_key: z.string().min(1),
41
+ billing_unit: z.enum(["day", "week", "month", "year"]),
42
+ billing_count: z.number().int().positive(),
43
+ })
44
+ .strict();
20
45
  /** Repository for billing offer resolution. */
21
46
  export class BillingOfferRepository {
22
47
  query;
23
48
  constructor(query) {
24
49
  this.query = query;
25
50
  }
26
- /** Resolve a billing offer by price ID and product ID. */
27
51
  async resolveByPrice(provider, priceId, productId) {
52
+ const lookupType = priceId !== null ? "price_id" : "product_id";
53
+ return this.resolve(provider, lookupType, priceId ?? productId, "resolveByPrice");
54
+ }
55
+ async resolveByLookup(provider, lookupKey) {
56
+ return this.resolve(provider, "external_id", lookupKey, "resolveByLookup");
57
+ }
58
+ async resolve(provider, lookupType, lookupValue, operation) {
59
+ if (!provider.trim())
60
+ throw new TypeError("provider must not be empty");
61
+ if (!lookupValue?.trim())
62
+ return null;
63
+ const context = `BillingOfferRepository.${operation}`;
28
64
  const rows = await this.query("SELECT * FROM bursar.resolve_catalog_offer($1, $2, $3)", [
29
65
  provider,
30
- priceId != null ? "price_id" : "product_id",
31
- priceId ?? productId,
66
+ lookupType,
67
+ lookupValue,
32
68
  ]);
33
- const data = unwrapJsonb(rows);
34
- const planRows = (await this.query("SELECT * FROM bursar.resolve_catalog_plan($1, $2, $3)", [
35
- provider,
36
- priceId != null ? "price_id" : "product_id",
37
- priceId ?? productId,
38
- ]));
39
- return data && data.offer_key != null
40
- ? safeParse(BillingOfferRowSchema, {
41
- ...data,
42
- plan_id: planRows[0]?.id,
43
- plan: data.plan_key,
44
- interval: data.billing_unit,
45
- interval_count: data.billing_count,
46
- grant_mode: data.cycle_grant_amount == null ? undefined : "cycle_grant",
47
- grant_credits: data.cycle_grant_amount,
48
- grant_bucket: data.cycle_grant_bucket_key,
49
- grant_replace_prior: data.cycle_grant_renewal === "replace_previous",
50
- }, "BillingOfferRepository.resolveByPrice")
51
- : null;
52
- }
53
- /** Resolve a billing offer by provider lookup key. */
54
- async resolveByLookup(provider, lookupKey) {
55
- const rows = await this.query("SELECT * FROM bursar.resolve_catalog_offer($1, 'external_id', $2)", [provider, lookupKey]);
56
- const data = unwrapJsonb(rows);
57
- const planRows = (await this.query("SELECT * FROM bursar.resolve_catalog_plan($1, 'external_id', $2)", [provider, lookupKey]));
58
- return data && data.offer_key != null
59
- ? safeParse(BillingOfferRowSchema, {
60
- ...data,
61
- plan_id: planRows[0]?.id,
62
- plan: data.plan_key,
63
- interval: data.billing_unit,
64
- interval_count: data.billing_count,
65
- grant_mode: data.cycle_grant_amount == null ? undefined : "cycle_grant",
66
- grant_credits: data.cycle_grant_amount,
67
- grant_bucket: data.cycle_grant_bucket_key,
68
- grant_replace_prior: data.cycle_grant_renewal === "replace_previous",
69
- }, "BillingOfferRepository.resolveByLookup")
70
- : null;
69
+ if (rows.length > 1) {
70
+ throw new StoreError(`${context}: expected at most one offer`, {
71
+ details: { rowCount: rows.length },
72
+ });
73
+ }
74
+ const raw = unwrapJsonb(rows);
75
+ if (raw?.id == null)
76
+ return null;
77
+ const offer = safeParse(CatalogOfferRowSchema, {
78
+ id: raw.id,
79
+ catalog_revision_id: raw.catalog_revision_id,
80
+ offer_key: raw.offer_key,
81
+ plan_key: raw.plan_key,
82
+ billing_unit: raw.billing_unit,
83
+ billing_count: raw.billing_count,
84
+ cycle_grant_amount: raw.cycle_grant_amount,
85
+ cycle_grant_bucket_key: raw.cycle_grant_bucket_key,
86
+ cycle_grant_renewal: raw.cycle_grant_renewal,
87
+ }, context);
88
+ const contextRows = await this.query("SELECT * FROM bursar.get_catalog_offer_context($1::uuid, $2::uuid)", [offer.id, offer.catalog_revision_id]);
89
+ if (contextRows.length !== 1) {
90
+ throw new StoreError(`${context}: catalog plan context is missing`, {
91
+ details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },
92
+ });
93
+ }
94
+ const rawContext = contextRows[0];
95
+ const offerContext = safeParse(OfferContextRowSchema, {
96
+ offer_key: rawContext.offer_key,
97
+ plan_id: rawContext.plan_id,
98
+ plan_key: rawContext.plan_key,
99
+ billing_unit: rawContext.billing_unit,
100
+ billing_count: rawContext.billing_count,
101
+ }, `${context}.context`);
102
+ if (offerContext.offer_key !== offer.offer_key ||
103
+ offerContext.plan_key !== offer.plan_key ||
104
+ offerContext.billing_unit !== offer.billing_unit ||
105
+ offerContext.billing_count !== offer.billing_count) {
106
+ throw new StoreError(`${context}: catalog plan context does not match the resolved offer`, {
107
+ details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },
108
+ });
109
+ }
110
+ const resolvedOffer = {
111
+ id: offer.id,
112
+ planId: offerContext.plan_id,
113
+ offerKey: offer.offer_key,
114
+ plan: offer.plan_key,
115
+ interval: offer.billing_unit,
116
+ intervalCount: offer.billing_count,
117
+ };
118
+ if (offer.cycle_grant_amount === null) {
119
+ return {
120
+ ...resolvedOffer,
121
+ grantCredits: null,
122
+ grantBucket: null,
123
+ grantReplacePrior: false,
124
+ };
125
+ }
126
+ if (offer.cycle_grant_bucket_key === null || offer.cycle_grant_renewal === null) {
127
+ throw new StoreError(`${context}: resolved offer has an incomplete cycle grant`, {
128
+ details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },
129
+ });
130
+ }
131
+ return {
132
+ ...resolvedOffer,
133
+ grantCredits: offer.cycle_grant_amount,
134
+ grantBucket: offer.cycle_grant_bucket_key,
135
+ grantReplacePrior: offer.cycle_grant_renewal === "replace_previous",
136
+ };
71
137
  }
72
138
  }
73
139
  //# sourceMappingURL=offer.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"offer.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/offer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,wCAAwC,CAAC;AAE3F,MAAM,qBAAqB,GAAG,CAAC;KAC5B,MAAM,CAAC;IACN,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IACzB,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE;IACzC,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAChC,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ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ACL,CAAC;QACD,OAAO;YACL,GAAG,aAAa;YAChB,YAAY,EAAE,KAAK,CAAC,kBAAkB;YACtC,WAAW,EAAE,KAAK,CAAC,sBAAsB;YACzC,iBAAiB,EAAE,KAAK,CAAC,mBAAmB,KAAK,kBAAkB;SACpE,CAAC;IACJ,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\nimport { z } from \"zod\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport { postgresUuid, safeParse, unwrapJsonb } from \"../../../shared/postgres-validation.js\";\n\nconst PositiveDecimalSchema = z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .transform((value) => new Decimal(value))\n .refine((value) => value.isFinite() && value.gt(0), \"expected a finite positive decimal\");\n\nconst CatalogOfferRowSchema = z\n .object({\n id: postgresUuid,\n catalog_revision_id: postgresUuid,\n offer_key: z.string().min(1),\n plan_key: z.string().min(1),\n billing_unit: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n billing_count: z.number().int().positive(),\n cycle_grant_amount: PositiveDecimalSchema.nullable(),\n cycle_grant_bucket_key: z.string().min(1).nullable(),\n cycle_grant_renewal: z.enum([\"replace_previous\", \"accumulate\"]).nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n const grantFields = [\n row.cycle_grant_amount,\n row.cycle_grant_bucket_key,\n row.cycle_grant_renewal,\n ];\n if (\n grantFields.some((value) => value !== null) &&\n grantFields.some((value) => value === null)\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"cycle grant fields must either all be set or all be null\",\n });\n }\n });\n\nconst OfferContextRowSchema = z\n .object({\n offer_key: z.string().min(1),\n plan_id: postgresUuid,\n plan_key: z.string().min(1),\n billing_unit: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n billing_count: z.number().int().positive(),\n })\n .strict();\n\ninterface BillingOfferRowBase {\n id: string;\n planId: string;\n offerKey: string;\n plan: string;\n interval: \"day\" | \"week\" | \"month\" | \"year\";\n intervalCount: number;\n}\n\nexport type BillingOfferRow = BillingOfferRowBase &\n (\n | {\n grantCredits: null;\n grantBucket: null;\n grantReplacePrior: false;\n }\n | {\n grantCredits: Decimal;\n grantBucket: string;\n grantReplacePrior: boolean;\n }\n );\n\n/** Repository for billing offer resolution. */\nexport class BillingOfferRepository {\n constructor(private readonly query: QueryFn) {}\n\n async resolveByPrice(\n provider: string,\n priceId: string | null,\n productId: string | null,\n ): Promise<BillingOfferRow | null> {\n const lookupType = priceId !== null ? \"price_id\" : \"product_id\";\n return this.resolve(provider, lookupType, priceId ?? productId, \"resolveByPrice\");\n }\n\n async resolveByLookup(provider: string, lookupKey: string): Promise<BillingOfferRow | null> {\n return this.resolve(provider, \"external_id\", lookupKey, \"resolveByLookup\");\n }\n\n private async resolve(\n provider: string,\n lookupType: \"price_id\" | \"product_id\" | \"external_id\",\n lookupValue: string | null,\n operation: string,\n ): Promise<BillingOfferRow | null> {\n if (!provider.trim()) throw new TypeError(\"provider must not be empty\");\n if (!lookupValue?.trim()) return null;\n\n const context = `BillingOfferRepository.${operation}`;\n const rows = await this.query(\"SELECT * FROM bursar.resolve_catalog_offer($1, $2, $3)\", [\n provider,\n lookupType,\n lookupValue,\n ]);\n if (rows.length > 1) {\n throw new StoreError(`${context}: expected at most one offer`, {\n details: { rowCount: rows.length },\n });\n }\n const raw = unwrapJsonb(rows);\n if (raw?.id == null) return null;\n const offer = safeParse(\n CatalogOfferRowSchema,\n {\n id: raw.id,\n catalog_revision_id: raw.catalog_revision_id,\n offer_key: raw.offer_key,\n plan_key: raw.plan_key,\n billing_unit: raw.billing_unit,\n billing_count: raw.billing_count,\n cycle_grant_amount: raw.cycle_grant_amount,\n cycle_grant_bucket_key: raw.cycle_grant_bucket_key,\n cycle_grant_renewal: raw.cycle_grant_renewal,\n },\n context,\n );\n\n const contextRows = await this.query(\n \"SELECT * FROM bursar.get_catalog_offer_context($1::uuid, $2::uuid)\",\n [offer.id, offer.catalog_revision_id],\n );\n if (contextRows.length !== 1) {\n throw new StoreError(`${context}: catalog plan context is missing`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n const rawContext = contextRows[0] as Record<string, unknown>;\n const offerContext = safeParse(\n OfferContextRowSchema,\n {\n offer_key: rawContext.offer_key,\n plan_id: rawContext.plan_id,\n plan_key: rawContext.plan_key,\n billing_unit: rawContext.billing_unit,\n billing_count: rawContext.billing_count,\n },\n `${context}.context`,\n );\n if (\n offerContext.offer_key !== offer.offer_key ||\n offerContext.plan_key !== offer.plan_key ||\n offerContext.billing_unit !== offer.billing_unit ||\n offerContext.billing_count !== offer.billing_count\n ) {\n throw new StoreError(`${context}: catalog plan context does not match the resolved offer`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n\n const resolvedOffer: BillingOfferRowBase = {\n id: offer.id,\n planId: offerContext.plan_id,\n offerKey: offer.offer_key,\n plan: offer.plan_key,\n interval: offer.billing_unit,\n intervalCount: offer.billing_count,\n };\n if (offer.cycle_grant_amount === null) {\n return {\n ...resolvedOffer,\n grantCredits: null,\n grantBucket: null,\n grantReplacePrior: false,\n };\n }\n if (offer.cycle_grant_bucket_key === null || offer.cycle_grant_renewal === null) {\n throw new StoreError(`${context}: resolved offer has an incomplete cycle grant`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n return {\n ...resolvedOffer,\n grantCredits: offer.cycle_grant_amount,\n grantBucket: offer.cycle_grant_bucket_key,\n grantReplacePrior: offer.cycle_grant_renewal === \"replace_previous\",\n };\n }\n}\n"]}
@@ -1,30 +1,33 @@
1
1
  import { z } from "zod";
2
2
  import type { QueryFn } from "../../../shared/postgres-types.js";
3
3
  declare const BillingPaymentRowSchema: z.ZodObject<{
4
- provider: z.ZodOptional<z.ZodString>;
5
- provider_payment_id: z.ZodOptional<z.ZodString>;
6
- subject_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
7
- user_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
8
- amount_minor: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
9
- tax_minor: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
10
- currency: z.ZodOptional<z.ZodString>;
11
- purpose: z.ZodOptional<z.ZodNullable<z.ZodString>>;
12
- status: z.ZodOptional<z.ZodString>;
13
- provider_updated_at: z.ZodOptional<z.ZodUnknown>;
14
- metadata: z.ZodOptional<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
15
- }, z.core.$loose>;
16
- declare const ForRefundRowSchema: z.ZodObject<{
17
- credits_per_unit: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
18
- credits_per_major_unit: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
19
- tier: z.ZodOptional<z.ZodString>;
20
- deposit_to: z.ZodOptional<z.ZodString>;
21
- }, z.core.$loose>;
4
+ id: z.ZodString;
5
+ provider: z.ZodString;
6
+ provider_payment_id: z.ZodString;
7
+ provider_invoice_id: z.ZodNullable<z.ZodString>;
8
+ subject_id: z.ZodString;
9
+ amount_minor: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
10
+ tax_minor: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
11
+ currency: z.ZodString;
12
+ purpose: z.ZodEnum<{
13
+ subscription: "subscription";
14
+ credit_topup: "credit_topup";
15
+ }>;
16
+ status: z.ZodEnum<{
17
+ pending: "pending";
18
+ succeeded: "succeeded";
19
+ failed: "failed";
20
+ canceled: "canceled";
21
+ }>;
22
+ provider_updated_at: z.ZodUnion<readonly [z.ZodString, z.ZodDate]>;
23
+ metadata: z.ZodRecord<z.ZodString, z.ZodUnknown>;
24
+ }, z.core.$strict>;
22
25
  export type BillingPaymentRow = z.infer<typeof BillingPaymentRowSchema>;
23
- export type ForRefundRow = z.infer<typeof ForRefundRowSchema>;
26
+ export type ForRefundRow = BillingPaymentRow;
24
27
  export declare class BillingPaymentRepository {
25
28
  private query;
26
29
  constructor(query: QueryFn);
27
- upsert(provider: string, providerPaymentId: string, providerInvoiceId: string | null, userId: string | null, amountMinor: number, taxMinor: number | null, currency: string, purpose: string | null, metadata: string | null, status: string, providerUpdatedAt: string): Promise<string>;
30
+ upsert(provider: string, providerPaymentId: string, providerInvoiceId: string | null, userId: string, amountMinor: number, taxMinor: number, currency: string, purpose: "subscription" | "credit_topup", metadata: string | null, status: "pending" | "succeeded" | "failed" | "canceled", providerUpdatedAt: string): Promise<string>;
28
31
  getForRefund(provider: string, providerPaymentId: string): Promise<ForRefundRow | null>;
29
32
  getDirect(provider: string, providerPaymentId: string): Promise<BillingPaymentRow | null>;
30
33
  }
@@ -1 +1 @@
1
- {"version":3,"file":"payment.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/payment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAGjE,QAAA,MAAM,uBAAuB;;;;;;;;;;;;iBAcb,CAAC;AACjB,QAAA,MAAM,kBAAkB;;;;;iBAOR,CAAC;AACjB,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,uBAAuB,CAAC,CAAC;AACxE,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAE9D,qBAAa,wBAAwB;IACvB,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAC5B,MAAM,CACV,QAAQ,EAAE,MAAM,EAChB,iBAAiB,EAAE,MAAM,EACzB,iBAAiB,EAAE,MAAM,GAAG,IAAI,EAChC,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,MAAM,GAAG,IAAI,EACv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C,MAAM,CAAC;IAyBZ,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IAQvF,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC;CAQhG"}
@@ -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;IACz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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"}
1
+ {"version":3,"file":"preferences.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/preferences.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,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YAC5C,kBAAkB,EAAE,MAAM,CAAC,mBAAmB;YAC9C,WAAW,EAAE,MAAM,CAAC,YAAY;YAChC,gBAAgB,EAAE,MAAM,CAAC,iBAAiB;SAC3C,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,KAAyB;QACpC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,mFAAmF,EACnF;YACE,KAAK,CAAC,MAAM;YACZ,KAAK,CAAC,YAAY;YAClB,KAAK,CAAC,iBAAiB;YACvB,KAAK,CAAC,kBAAkB;YACxB,KAAK,CAAC,WAAW;YACjB,KAAK,CAAC,gBAAgB;SACvB,CACF,CAAC;QACF,MAAM,OAAO,GAAG,kBAAkB,CAChC,IAAI,EACJ,SAAS,EACT,SAAS,EACT,qCAAqC,CACtC,CAAC;QACF,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,MAAM,IAAI,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