@zonastery/bursar 1.0.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (366) hide show
  1. package/README.md +86 -3
  2. package/dist/billing/auto-recharge-port.d.ts +3 -3
  3. package/dist/billing/auto-recharge-port.d.ts.map +1 -1
  4. package/dist/billing/auto-recharge-port.js.map +1 -1
  5. package/dist/billing/auto-recharge-service.d.ts +5 -4
  6. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  7. package/dist/billing/auto-recharge-service.js +64 -34
  8. package/dist/billing/auto-recharge-service.js.map +1 -1
  9. package/dist/billing/billing-service.d.ts +5 -5
  10. package/dist/billing/billing-service.d.ts.map +1 -1
  11. package/dist/billing/billing-service.js +2 -2
  12. package/dist/billing/billing-service.js.map +1 -1
  13. package/dist/billing/billing-store.d.ts +8 -7
  14. package/dist/billing/billing-store.d.ts.map +1 -1
  15. package/dist/billing/billing-store.js.map +1 -1
  16. package/dist/billing/contracts.d.ts +31 -31
  17. package/dist/billing/contracts.d.ts.map +1 -1
  18. package/dist/billing/contracts.js.map +1 -1
  19. package/dist/billing/event-handlers.d.ts.map +1 -1
  20. package/dist/billing/event-handlers.js +31 -9
  21. package/dist/billing/event-handlers.js.map +1 -1
  22. package/dist/billing/event-processor.d.ts.map +1 -1
  23. package/dist/billing/event-processor.js +2 -1
  24. package/dist/billing/event-processor.js.map +1 -1
  25. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  26. package/dist/billing/financial-event-handlers.js +69 -72
  27. package/dist/billing/financial-event-handlers.js.map +1 -1
  28. package/dist/billing/index.d.ts +1 -1
  29. package/dist/billing/index.d.ts.map +1 -1
  30. package/dist/billing/index.js.map +1 -1
  31. package/dist/billing/management.d.ts +5 -5
  32. package/dist/billing/management.d.ts.map +1 -1
  33. package/dist/billing/management.js +2 -2
  34. package/dist/billing/management.js.map +1 -1
  35. package/dist/billing/postgres/repositories/auto-recharge.d.ts +3 -3
  36. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  37. package/dist/billing/postgres/repositories/auto-recharge.js +202 -59
  38. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  39. package/dist/billing/postgres/repositories/customer.d.ts.map +1 -1
  40. package/dist/billing/postgres/repositories/customer.js +19 -11
  41. package/dist/billing/postgres/repositories/customer.js.map +1 -1
  42. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
  43. package/dist/billing/postgres/repositories/dispute.js +3 -1
  44. package/dist/billing/postgres/repositories/dispute.js.map +1 -1
  45. package/dist/billing/postgres/repositories/event.d.ts +12 -5
  46. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  47. package/dist/billing/postgres/repositories/event.js +18 -15
  48. package/dist/billing/postgres/repositories/event.js.map +1 -1
  49. package/dist/billing/postgres/repositories/invoice.d.ts +3 -3
  50. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  51. package/dist/billing/postgres/repositories/invoice.js +53 -11
  52. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  53. package/dist/billing/postgres/repositories/offer.d.ts +20 -17
  54. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  55. package/dist/billing/postgres/repositories/offer.js +123 -57
  56. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  57. package/dist/billing/postgres/repositories/payment.d.ts +23 -20
  58. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  59. package/dist/billing/postgres/repositories/payment.js +43 -37
  60. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  61. package/dist/billing/postgres/repositories/preferences.d.ts +3 -9
  62. package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -1
  63. package/dist/billing/postgres/repositories/preferences.js +45 -7
  64. package/dist/billing/postgres/repositories/preferences.js.map +1 -1
  65. package/dist/billing/postgres/repositories/refund.d.ts +1 -1
  66. package/dist/billing/postgres/repositories/refund.d.ts.map +1 -1
  67. package/dist/billing/postgres/repositories/refund.js +13 -9
  68. package/dist/billing/postgres/repositories/refund.js.map +1 -1
  69. package/dist/billing/postgres/repositories/subscription-change.d.ts +15 -0
  70. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -0
  71. package/dist/billing/postgres/repositories/subscription-change.js +234 -0
  72. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -0
  73. package/dist/billing/postgres/repositories/subscription.d.ts +38 -17
  74. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  75. package/dist/billing/postgres/repositories/subscription.js +199 -91
  76. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  77. package/dist/billing/postgres/repositories/topup.d.ts +13 -15
  78. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  79. package/dist/billing/postgres/repositories/topup.js +65 -34
  80. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  81. package/dist/billing/postgres/store.d.ts +18 -11
  82. package/dist/billing/postgres/store.d.ts.map +1 -1
  83. package/dist/billing/postgres/store.js +260 -238
  84. package/dist/billing/postgres/store.js.map +1 -1
  85. package/dist/billing/service-types.d.ts +6 -5
  86. package/dist/billing/service-types.d.ts.map +1 -1
  87. package/dist/billing/service-types.js.map +1 -1
  88. package/dist/billing/types/auto-recharge.d.ts +6 -4
  89. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  90. package/dist/billing/types/auto-recharge.js.map +1 -1
  91. package/dist/billing/types/catalog.d.ts +18 -35
  92. package/dist/billing/types/catalog.d.ts.map +1 -1
  93. package/dist/billing/types/catalog.js.map +1 -1
  94. package/dist/billing/types/common.d.ts +0 -1
  95. package/dist/billing/types/common.d.ts.map +1 -1
  96. package/dist/billing/types/common.js.map +1 -1
  97. package/dist/billing/types/documents.d.ts +38 -12
  98. package/dist/billing/types/documents.d.ts.map +1 -1
  99. package/dist/billing/types/documents.js.map +1 -1
  100. package/dist/billing/types/events.d.ts +2 -0
  101. package/dist/billing/types/events.d.ts.map +1 -1
  102. package/dist/billing/types/events.js +238 -0
  103. package/dist/billing/types/events.js.map +1 -1
  104. package/dist/billing/types/subscriptions.d.ts +8 -8
  105. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  106. package/dist/billing/types/subscriptions.js.map +1 -1
  107. package/dist/bursar.d.ts +27 -9
  108. package/dist/bursar.d.ts.map +1 -1
  109. package/dist/bursar.js +48 -20
  110. package/dist/bursar.js.map +1 -1
  111. package/dist/catalog.d.ts +1 -1
  112. package/dist/catalog.d.ts.map +1 -1
  113. package/dist/catalog.js +1 -1
  114. package/dist/catalog.js.map +1 -1
  115. package/dist/commerce/errors.d.ts +1 -10
  116. package/dist/commerce/errors.d.ts.map +1 -1
  117. package/dist/commerce/errors.js +1 -16
  118. package/dist/commerce/errors.js.map +1 -1
  119. package/dist/commerce/index.d.ts +1 -0
  120. package/dist/commerce/index.d.ts.map +1 -1
  121. package/dist/commerce/index.js.map +1 -1
  122. package/dist/commerce/provider-registry.d.ts.map +1 -1
  123. package/dist/commerce/provider-registry.js +27 -2
  124. package/dist/commerce/provider-registry.js.map +1 -1
  125. package/dist/commerce/service.d.ts +15 -7
  126. package/dist/commerce/service.d.ts.map +1 -1
  127. package/dist/commerce/service.js +85 -67
  128. package/dist/commerce/service.js.map +1 -1
  129. package/dist/commerce/types.d.ts +27 -15
  130. package/dist/commerce/types.d.ts.map +1 -1
  131. package/dist/commerce/types.js.map +1 -1
  132. package/dist/config/parse-plans.d.ts.map +1 -1
  133. package/dist/config/parse-plans.js +16 -15
  134. package/dist/config/parse-plans.js.map +1 -1
  135. package/dist/config/parse-pricing.d.ts.map +1 -1
  136. package/dist/config/parse-pricing.js +16 -5
  137. package/dist/config/parse-pricing.js.map +1 -1
  138. package/dist/config/types.d.ts +2 -2
  139. package/dist/config/types.d.ts.map +1 -1
  140. package/dist/config/types.js.map +1 -1
  141. package/dist/credits/{pricing-runtime.d.ts → catalog-runtime.d.ts} +8 -8
  142. package/dist/credits/catalog-runtime.d.ts.map +1 -0
  143. package/dist/credits/{pricing-runtime.js → catalog-runtime.js} +58 -38
  144. package/dist/credits/catalog-runtime.js.map +1 -0
  145. package/dist/credits/events.d.ts +4 -4
  146. package/dist/credits/events.d.ts.map +1 -1
  147. package/dist/credits/events.js +1 -1
  148. package/dist/credits/events.js.map +1 -1
  149. package/dist/credits/lease-workflow.d.ts +14 -14
  150. package/dist/credits/lease-workflow.d.ts.map +1 -1
  151. package/dist/credits/lease-workflow.js +18 -17
  152. package/dist/credits/lease-workflow.js.map +1 -1
  153. package/dist/credits/low-balance-monitor.d.ts +2 -2
  154. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  155. package/dist/credits/low-balance-monitor.js.map +1 -1
  156. package/dist/credits/postgres/repositories/analytics.d.ts +34 -34
  157. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  158. package/dist/credits/postgres/repositories/analytics.js +52 -52
  159. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  160. package/dist/credits/postgres/repositories/balance.d.ts +28 -30
  161. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  162. package/dist/credits/postgres/repositories/balance.js +100 -59
  163. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  164. package/dist/credits/postgres/repositories/bucket.d.ts +14 -8
  165. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
  166. package/dist/credits/postgres/repositories/bucket.js +22 -21
  167. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  168. package/dist/credits/postgres/repositories/catalog.d.ts +31 -0
  169. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -0
  170. package/dist/credits/postgres/repositories/catalog.js +90 -0
  171. package/dist/credits/postgres/repositories/catalog.js.map +1 -0
  172. package/dist/credits/postgres/repositories/deduction.d.ts +28 -26
  173. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  174. package/dist/credits/postgres/repositories/deduction.js +153 -68
  175. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  176. package/dist/credits/postgres/repositories/lease.d.ts +21 -18
  177. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  178. package/dist/credits/postgres/repositories/lease.js +157 -65
  179. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  180. package/dist/credits/postgres/repositories/plan.d.ts +90 -43
  181. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
  182. package/dist/credits/postgres/repositories/plan.js +126 -108
  183. package/dist/credits/postgres/repositories/plan.js.map +1 -1
  184. package/dist/credits/postgres/repositories/team.d.ts +36 -27
  185. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  186. package/dist/credits/postgres/repositories/team.js +96 -52
  187. package/dist/credits/postgres/repositories/team.js.map +1 -1
  188. package/dist/credits/postgres/store.d.ts +23 -18
  189. package/dist/credits/postgres/store.d.ts.map +1 -1
  190. package/dist/credits/postgres/store.js +282 -265
  191. package/dist/credits/postgres/store.js.map +1 -1
  192. package/dist/credits/postgres/value-mappers.d.ts +7 -9
  193. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  194. package/dist/credits/postgres/value-mappers.js +36 -61
  195. package/dist/credits/postgres/value-mappers.js.map +1 -1
  196. package/dist/credits/queries.d.ts +5 -5
  197. package/dist/credits/queries.d.ts.map +1 -1
  198. package/dist/credits/queries.js +4 -4
  199. package/dist/credits/queries.js.map +1 -1
  200. package/dist/credits/service-types.d.ts +42 -7
  201. package/dist/credits/service-types.d.ts.map +1 -1
  202. package/dist/credits/service-types.js.map +1 -1
  203. package/dist/credits/service.d.ts +42 -62
  204. package/dist/credits/service.d.ts.map +1 -1
  205. package/dist/credits/service.js +140 -121
  206. package/dist/credits/service.js.map +1 -1
  207. package/dist/credits/store.d.ts +20 -22
  208. package/dist/credits/store.d.ts.map +1 -1
  209. package/dist/credits/store.js +5 -5
  210. package/dist/credits/store.js.map +1 -1
  211. package/dist/credits/types/account.d.ts +49 -11
  212. package/dist/credits/types/account.d.ts.map +1 -1
  213. package/dist/credits/types/account.js.map +1 -1
  214. package/dist/credits/types/admission.d.ts +17 -6
  215. package/dist/credits/types/admission.d.ts.map +1 -1
  216. package/dist/credits/types/admission.js.map +1 -1
  217. package/dist/credits/types/analytics.d.ts +2 -2
  218. package/dist/credits/types/analytics.d.ts.map +1 -1
  219. package/dist/credits/types/analytics.js.map +1 -1
  220. package/dist/credits/types/catalog.d.ts +20 -15
  221. package/dist/credits/types/catalog.d.ts.map +1 -1
  222. package/dist/credits/types/catalog.js.map +1 -1
  223. package/dist/credits/types/grants.d.ts +22 -8
  224. package/dist/credits/types/grants.d.ts.map +1 -1
  225. package/dist/credits/types/grants.js.map +1 -1
  226. package/dist/credits/types/ledger.d.ts +12 -3
  227. package/dist/credits/types/ledger.d.ts.map +1 -1
  228. package/dist/credits/types/ledger.js.map +1 -1
  229. package/dist/credits/types/teams.d.ts +18 -6
  230. package/dist/credits/types/teams.d.ts.map +1 -1
  231. package/dist/credits/types/teams.js.map +1 -1
  232. package/dist/engine.d.ts.map +1 -1
  233. package/dist/engine.js +24 -10
  234. package/dist/engine.js.map +1 -1
  235. package/dist/errors.d.ts +52 -4
  236. package/dist/errors.d.ts.map +1 -1
  237. package/dist/errors.js +76 -4
  238. package/dist/errors.js.map +1 -1
  239. package/dist/expr/ast.d.ts.map +1 -1
  240. package/dist/expr/ast.js.map +1 -1
  241. package/dist/expr/evaluator.d.ts.map +1 -1
  242. package/dist/expr/evaluator.js +29 -17
  243. package/dist/expr/evaluator.js.map +1 -1
  244. package/dist/expr/parser.d.ts.map +1 -1
  245. package/dist/expr/parser.js +11 -4
  246. package/dist/expr/parser.js.map +1 -1
  247. package/dist/expr/tokenizer.d.ts.map +1 -1
  248. package/dist/expr/tokenizer.js +17 -13
  249. package/dist/expr/tokenizer.js.map +1 -1
  250. package/dist/expr.d.ts +2 -2
  251. package/dist/expr.d.ts.map +1 -1
  252. package/dist/expr.js +5 -7
  253. package/dist/expr.js.map +1 -1
  254. package/dist/generated/pricing-config.schema.json +5 -12
  255. package/dist/generated/pricing-config.types.d.ts +3 -3
  256. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  257. package/dist/generated/pricing-config.types.js.map +1 -1
  258. package/dist/index.d.ts +6 -4
  259. package/dist/index.d.ts.map +1 -1
  260. package/dist/index.js +1 -1
  261. package/dist/index.js.map +1 -1
  262. package/dist/integrations/better-auth.d.ts +23 -0
  263. package/dist/integrations/better-auth.d.ts.map +1 -0
  264. package/dist/integrations/better-auth.js +54 -0
  265. package/dist/integrations/better-auth.js.map +1 -0
  266. package/dist/{load-pricing-file.d.ts → load-config-file.d.ts} +4 -4
  267. package/dist/load-config-file.d.ts.map +1 -0
  268. package/dist/{load-pricing-file.js → load-config-file.js} +15 -10
  269. package/dist/load-config-file.js.map +1 -0
  270. package/dist/node.d.ts +3 -3
  271. package/dist/node.d.ts.map +1 -1
  272. package/dist/node.js +2 -2
  273. package/dist/node.js.map +1 -1
  274. package/dist/providers/_shared.d.ts +5 -0
  275. package/dist/providers/_shared.d.ts.map +1 -1
  276. package/dist/providers/_shared.js +36 -0
  277. package/dist/providers/_shared.js.map +1 -1
  278. package/dist/providers/dodo/better-auth.d.ts +29 -0
  279. package/dist/providers/dodo/better-auth.d.ts.map +1 -0
  280. package/dist/providers/dodo/better-auth.js +23 -0
  281. package/dist/providers/dodo/better-auth.js.map +1 -0
  282. package/dist/providers/dodo/client-contract.d.ts +32 -70
  283. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  284. package/dist/providers/dodo/client-contract.js.map +1 -1
  285. package/dist/providers/dodo/event-mapper.d.ts +3 -1
  286. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  287. package/dist/providers/dodo/event-mapper.js +219 -148
  288. package/dist/providers/dodo/event-mapper.js.map +1 -1
  289. package/dist/providers/dodo/index.d.ts +5 -2
  290. package/dist/providers/dodo/index.d.ts.map +1 -1
  291. package/dist/providers/dodo/index.js +2 -1
  292. package/dist/providers/dodo/index.js.map +1 -1
  293. package/dist/providers/dodo/nextjs.d.ts +16 -0
  294. package/dist/providers/dodo/nextjs.d.ts.map +1 -0
  295. package/dist/providers/dodo/nextjs.js +16 -0
  296. package/dist/providers/dodo/nextjs.js.map +1 -0
  297. package/dist/providers/dodo/provider.d.ts +30 -11
  298. package/dist/providers/dodo/provider.d.ts.map +1 -1
  299. package/dist/providers/dodo/provider.js +192 -122
  300. package/dist/providers/dodo/provider.js.map +1 -1
  301. package/dist/providers/dodo/react-native.d.ts +56 -0
  302. package/dist/providers/dodo/react-native.d.ts.map +1 -0
  303. package/dist/providers/dodo/react-native.js +57 -0
  304. package/dist/providers/dodo/react-native.js.map +1 -0
  305. package/dist/providers/dodo/webhook-bridge.d.ts +17 -0
  306. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -0
  307. package/dist/providers/dodo/webhook-bridge.js +21 -0
  308. package/dist/providers/dodo/webhook-bridge.js.map +1 -0
  309. package/dist/providers/index.d.ts +1 -1
  310. package/dist/providers/index.d.ts.map +1 -1
  311. package/dist/providers/index.js.map +1 -1
  312. package/dist/providers/mock/index.d.ts +1 -0
  313. package/dist/providers/mock/index.d.ts.map +1 -1
  314. package/dist/providers/mock/index.js.map +1 -1
  315. package/dist/providers/mock/provider.d.ts +8 -8
  316. package/dist/providers/mock/provider.d.ts.map +1 -1
  317. package/dist/providers/mock/provider.js +26 -19
  318. package/dist/providers/mock/provider.js.map +1 -1
  319. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  320. package/dist/providers/stripe/event-mapper.js +214 -173
  321. package/dist/providers/stripe/event-mapper.js.map +1 -1
  322. package/dist/providers/stripe/index.d.ts +1 -0
  323. package/dist/providers/stripe/index.d.ts.map +1 -1
  324. package/dist/providers/stripe/index.js.map +1 -1
  325. package/dist/providers/stripe/provider.d.ts +13 -11
  326. package/dist/providers/stripe/provider.d.ts.map +1 -1
  327. package/dist/providers/stripe/provider.js +287 -107
  328. package/dist/providers/stripe/provider.js.map +1 -1
  329. package/dist/providers/types.d.ts +1 -2
  330. package/dist/providers/types.d.ts.map +1 -1
  331. package/dist/providers/types.js.map +1 -1
  332. package/dist/shared/postgres-client.d.ts +5 -0
  333. package/dist/shared/postgres-client.d.ts.map +1 -1
  334. package/dist/shared/postgres-client.js +23 -7
  335. package/dist/shared/postgres-client.js.map +1 -1
  336. package/dist/shared/postgres-validation.d.ts +15 -3
  337. package/dist/shared/postgres-validation.d.ts.map +1 -1
  338. package/dist/shared/postgres-validation.js +58 -14
  339. package/dist/shared/postgres-validation.js.map +1 -1
  340. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  341. package/dist/storage/adapters/clickhouse.js +2 -5
  342. package/dist/storage/adapters/clickhouse.js.map +1 -1
  343. package/dist/storage/adapters/s3.d.ts +0 -6
  344. package/dist/storage/adapters/s3.d.ts.map +1 -1
  345. package/dist/storage/adapters/s3.js +0 -2
  346. package/dist/storage/adapters/s3.js.map +1 -1
  347. package/dist/storage/ports.d.ts +0 -1
  348. package/dist/storage/ports.d.ts.map +1 -1
  349. package/dist/storage/ports.js.map +1 -1
  350. package/dist/storage/postgres-repository.d.ts +1 -1
  351. package/dist/storage/postgres-repository.d.ts.map +1 -1
  352. package/dist/storage/postgres-repository.js +2 -2
  353. package/dist/storage/postgres-repository.js.map +1 -1
  354. package/dist/storage/runtime.d.ts +24 -6
  355. package/dist/storage/runtime.d.ts.map +1 -1
  356. package/dist/storage/runtime.js +87 -30
  357. package/dist/storage/runtime.js.map +1 -1
  358. package/package.json +56 -7
  359. package/dist/credits/postgres/repositories/pricing.d.ts +0 -28
  360. package/dist/credits/postgres/repositories/pricing.d.ts.map +0 -1
  361. package/dist/credits/postgres/repositories/pricing.js +0 -76
  362. package/dist/credits/postgres/repositories/pricing.js.map +0 -1
  363. package/dist/credits/pricing-runtime.d.ts.map +0 -1
  364. package/dist/credits/pricing-runtime.js.map +0 -1
  365. package/dist/load-pricing-file.d.ts.map +0 -1
  366. package/dist/load-pricing-file.js.map +0 -1
@@ -1,46 +1,177 @@
1
+ import { z } from "zod";
2
+ import Decimal from "decimal.js";
3
+ import { StoreError } from "../../../errors.js";
1
4
  import { optionalBoundedDiagnosticMessage } from "../../../shared/diagnostics.js";
2
- function iso(value) {
3
- return new Date(String(value)).toISOString();
5
+ import { optionalRecordRow, pgBoolean, postgresUuid, requireResultField, safeParse, } from "../../../shared/postgres-validation.js";
6
+ const safeNonnegativeInteger = z
7
+ .union([z.number(), z.string().regex(/^\d+$/)])
8
+ .transform(Number)
9
+ .pipe(z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER));
10
+ const positiveInteger = safeNonnegativeInteger.pipe(z.number().positive());
11
+ const timestamp = z
12
+ .union([
13
+ z.date().refine((value) => !Number.isNaN(value.getTime())),
14
+ z.string().datetime({ offset: true }),
15
+ ])
16
+ .transform((value) => (value instanceof Date ? value : new Date(value)).toISOString());
17
+ const decimal = z
18
+ .union([z.instanceof(Decimal), z.string().min(1), z.number().finite()])
19
+ .transform((value) => new Decimal(value))
20
+ .refine((value) => value.isFinite() && !value.isNegative(), "expected a non-negative decimal");
21
+ const ProfileRowSchema = z
22
+ .object({
23
+ subject_id: postgresUuid,
24
+ enabled: pgBoolean,
25
+ armed: pgBoolean,
26
+ state: z.enum(["disabled", "active", "paused"]),
27
+ provider: z.string().min(1).nullable(),
28
+ topup_id: postgresUuid.nullable(),
29
+ quantity: positiveInteger,
30
+ threshold: decimal,
31
+ max_charges_per_window: positiveInteger.nullable(),
32
+ window_unit: z.enum(["second", "minute", "hour", "day", "week", "month", "year"]),
33
+ window_count: positiveInteger,
34
+ window_anchor: z.enum(["calendar", "rolling"]),
35
+ window_timezone: z.string().min(1),
36
+ updated_at: timestamp,
37
+ })
38
+ .strict()
39
+ .superRefine((row, ctx) => {
40
+ if (row.enabled !== (row.state !== "disabled")) {
41
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "enabled and state are inconsistent" });
42
+ }
43
+ if (row.enabled && (row.provider === null || row.topup_id === null)) {
44
+ ctx.addIssue({
45
+ code: z.ZodIssueCode.custom,
46
+ message: "enabled profile requires provider and topup_id",
47
+ });
48
+ }
49
+ });
50
+ const AttemptStateSchema = z.enum([
51
+ "claimed",
52
+ "submitted",
53
+ "processing",
54
+ "unknown",
55
+ "succeeded",
56
+ "failed",
57
+ "action_required",
58
+ ]);
59
+ const AttemptRowSchema = z
60
+ .object({
61
+ id: postgresUuid,
62
+ subject_id: postgresUuid,
63
+ provider: z.string().min(1),
64
+ idempotency_key: z.string().min(1),
65
+ provider_attempt_id: z.string().min(1).nullable(),
66
+ topup_id: postgresUuid,
67
+ quantity: positiveInteger,
68
+ state: AttemptStateSchema,
69
+ window_start: timestamp,
70
+ window_end: timestamp,
71
+ quoted_amount_minor: safeNonnegativeInteger.nullable(),
72
+ currency: z
73
+ .string()
74
+ .regex(/^[A-Z]{3}$/)
75
+ .nullable(),
76
+ failure_code: z.string().min(1).nullable(),
77
+ failure_message: z.string().min(1).nullable(),
78
+ metadata: z.record(z.string(), z.unknown()),
79
+ created_at: timestamp,
80
+ updated_at: timestamp,
81
+ })
82
+ .strict()
83
+ .superRefine((row, ctx) => {
84
+ if (new Date(row.window_end).getTime() <= new Date(row.window_start).getTime()) {
85
+ ctx.addIssue({
86
+ code: z.ZodIssueCode.custom,
87
+ message: "window_end must be later than window_start",
88
+ });
89
+ }
90
+ if ((row.quoted_amount_minor === null) !== (row.currency === null)) {
91
+ ctx.addIssue({
92
+ code: z.ZodIssueCode.custom,
93
+ message: "quoted_amount_minor and currency must be present together",
94
+ });
95
+ }
96
+ });
97
+ function projectProfile(row) {
98
+ return {
99
+ subject_id: row.subject_id,
100
+ enabled: row.enabled,
101
+ armed: row.armed,
102
+ state: row.state,
103
+ provider: row.provider,
104
+ topup_id: row.topup_id,
105
+ quantity: row.quantity,
106
+ threshold: row.threshold,
107
+ max_charges_per_window: row.max_charges_per_window,
108
+ window_unit: row.window_unit,
109
+ window_count: row.window_count,
110
+ window_anchor: row.window_anchor,
111
+ window_timezone: row.window_timezone,
112
+ updated_at: row.updated_at,
113
+ };
114
+ }
115
+ function projectAttempt(row) {
116
+ return {
117
+ id: row.id,
118
+ subject_id: row.subject_id,
119
+ provider: row.provider,
120
+ idempotency_key: row.idempotency_key,
121
+ provider_attempt_id: row.provider_attempt_id,
122
+ topup_id: row.topup_id,
123
+ quantity: row.quantity,
124
+ state: row.state,
125
+ window_start: row.window_start,
126
+ window_end: row.window_end,
127
+ quoted_amount_minor: row.quoted_amount_minor,
128
+ currency: row.currency,
129
+ failure_code: row.failure_code,
130
+ failure_message: row.failure_message,
131
+ metadata: row.metadata,
132
+ created_at: row.created_at,
133
+ updated_at: row.updated_at,
134
+ };
4
135
  }
5
136
  function profileFromRow(row) {
137
+ const parsed = safeParse(ProfileRowSchema, projectProfile(row), "BillingAutoRechargeRepository.profile");
6
138
  return {
7
- userId: String(row.subject_id),
8
- enabled: Boolean(row.enabled),
9
- armed: Boolean(row.armed),
10
- state: String(row.state),
11
- provider: row.provider == null ? null : String(row.provider),
12
- topupId: row.topup_id == null ? null : String(row.topup_id),
13
- quantity: Number(row.quantity),
14
- threshold: Number(row.threshold),
15
- maxChargesPerWindow: row.max_charges_per_window == null ? null : Number(row.max_charges_per_window),
16
- windowUnit: String(row.window_unit),
17
- windowCount: Number(row.window_count),
18
- windowAnchor: String(row.window_anchor),
19
- windowTimezone: String(row.window_timezone),
20
- updatedAt: row.updated_at == null ? null : iso(row.updated_at),
139
+ userId: parsed.subject_id,
140
+ enabled: parsed.enabled,
141
+ armed: parsed.armed,
142
+ state: parsed.state,
143
+ provider: parsed.provider,
144
+ topupId: parsed.topup_id,
145
+ quantity: parsed.quantity,
146
+ threshold: parsed.threshold,
147
+ maxChargesPerWindow: parsed.max_charges_per_window,
148
+ windowUnit: parsed.window_unit,
149
+ windowCount: parsed.window_count,
150
+ windowAnchor: parsed.window_anchor,
151
+ windowTimezone: parsed.window_timezone,
152
+ updatedAt: parsed.updated_at,
21
153
  };
22
154
  }
23
155
  function attemptFromRow(row) {
156
+ const parsed = safeParse(AttemptRowSchema, projectAttempt(row), "BillingAutoRechargeRepository.attempt");
24
157
  return {
25
- id: String(row.id),
26
- userId: String(row.subject_id),
27
- provider: String(row.provider),
28
- idempotencyKey: String(row.idempotency_key),
29
- providerAttemptId: row.provider_attempt_id == null ? null : String(row.provider_attempt_id),
30
- topupId: String(row.topup_id),
31
- quantity: Number(row.quantity),
32
- state: String(row.state),
33
- windowStart: iso(row.window_start),
34
- windowEnd: iso(row.window_end),
35
- quotedAmountMinor: row.quoted_amount_minor == null ? null : Number(row.quoted_amount_minor),
36
- currency: row.currency == null ? null : String(row.currency),
37
- failureCode: row.failure_code == null ? null : String(row.failure_code),
38
- failureMessage: row.failure_message == null ? null : String(row.failure_message),
39
- metadata: row.metadata != null && typeof row.metadata === "object" && !Array.isArray(row.metadata)
40
- ? row.metadata
41
- : {},
42
- createdAt: iso(row.created_at),
43
- updatedAt: iso(row.updated_at),
158
+ id: parsed.id,
159
+ userId: parsed.subject_id,
160
+ provider: parsed.provider,
161
+ idempotencyKey: parsed.idempotency_key,
162
+ providerAttemptId: parsed.provider_attempt_id,
163
+ topupId: parsed.topup_id,
164
+ quantity: parsed.quantity,
165
+ state: parsed.state,
166
+ windowStart: parsed.window_start,
167
+ windowEnd: parsed.window_end,
168
+ quotedAmountMinor: parsed.quoted_amount_minor,
169
+ currency: parsed.currency,
170
+ failureCode: parsed.failure_code,
171
+ failureMessage: parsed.failure_message,
172
+ metadata: parsed.metadata,
173
+ createdAt: parsed.created_at,
174
+ updatedAt: parsed.updated_at,
44
175
  };
45
176
  }
46
177
  export class BillingAutoRechargeRepository {
@@ -52,8 +183,8 @@ export class BillingAutoRechargeRepository {
52
183
  const rows = await this.query("SELECT * FROM bursar.get_auto_recharge_profile($1::uuid)", [
53
184
  userId,
54
185
  ]);
55
- const row = rows[0];
56
- return row?.subject_id == null ? null : profileFromRow(row);
186
+ const row = optionalRecordRow(rows, "BillingAutoRechargeRepository.getProfile");
187
+ return row === null ? null : profileFromRow(row);
57
188
  }
58
189
  async upsertProfile(profile, options = {}) {
59
190
  const rows = await this.query(`SELECT bursar.upsert_auto_recharge_profile(
@@ -64,7 +195,7 @@ export class BillingAutoRechargeRepository {
64
195
  profile.provider,
65
196
  profile.topupId,
66
197
  profile.quantity,
67
- profile.threshold,
198
+ profile.threshold.toString(),
68
199
  profile.maxChargesPerWindow,
69
200
  profile.windowUnit,
70
201
  profile.windowCount,
@@ -74,19 +205,25 @@ export class BillingAutoRechargeRepository {
74
205
  profile.state,
75
206
  options.resetCooldown ?? false,
76
207
  ]);
77
- if (!rows[0]?.updated) {
78
- throw new Error(`auto-recharge profile update rejected: ${profile.userId}`);
208
+ if (!requireResultField(rows, "updated", pgBoolean, "BillingAutoRechargeRepository.upsertProfile")) {
209
+ throw new StoreError(`auto-recharge profile update rejected: ${profile.userId}`);
79
210
  }
80
211
  }
81
212
  async claimAttempt(input) {
82
213
  const rows = await this.query("SELECT * FROM bursar.claim_auto_recharge_attempt($1::uuid, $2)", [input.userId, input.idempotencyKey]);
83
- const row = rows[0];
84
- return row?.id == null ? null : attemptFromRow(row);
214
+ const row = optionalRecordRow(rows, "BillingAutoRechargeRepository.claimAttempt");
215
+ return row === null ? null : attemptFromRow(row);
85
216
  }
86
217
  async advanceAttempt(input) {
87
218
  const failureMessage = optionalBoundedDiagnosticMessage(input.failureMessage);
88
219
  const currentRows = await this.query("SELECT * FROM bursar.get_auto_recharge_attempt($1::uuid)", [input.id]);
89
- const current = String(currentRows[0]?.state ?? "");
220
+ const currentRow = optionalRecordRow(currentRows, "BillingAutoRechargeRepository.advanceAttempt.current");
221
+ if (currentRow === null) {
222
+ throw new StoreError(`auto-recharge attempt not found: ${input.id}`, {
223
+ details: { attemptId: input.id },
224
+ });
225
+ }
226
+ const current = safeParse(AttemptStateSchema, currentRow.state, "BillingAutoRechargeRepository.advanceAttempt.current.state");
90
227
  const paths = {
91
228
  claimed: {
92
229
  submitted: ["submitted"],
@@ -127,7 +264,9 @@ export class BillingAutoRechargeRepository {
127
264
  };
128
265
  const path = paths[current]?.[input.state];
129
266
  if (!path) {
130
- throw new Error(`auto-recharge attempt transition rejected: ${input.id}`);
267
+ throw new StoreError(`auto-recharge attempt transition rejected: ${input.id}`, {
268
+ details: { attemptId: input.id, currentState: current, requestedState: input.state },
269
+ });
131
270
  }
132
271
  for (const state of path) {
133
272
  const rows = await this.query(`SELECT bursar.advance_auto_recharge_attempt(
@@ -145,8 +284,10 @@ export class BillingAutoRechargeRepository {
145
284
  failureMessage,
146
285
  JSON.stringify(input.metadata ?? {}),
147
286
  ]);
148
- if (!rows[0]?.advanced) {
149
- throw new Error(`auto-recharge attempt transition rejected: ${input.id}`);
287
+ if (!requireResultField(rows, "advanced", pgBoolean, "BillingAutoRechargeRepository.advanceAttempt")) {
288
+ throw new StoreError(`auto-recharge attempt transition rejected: ${input.id}`, {
289
+ details: { attemptId: input.id, requestedState: state },
290
+ });
150
291
  }
151
292
  }
152
293
  }
@@ -155,18 +296,17 @@ export class BillingAutoRechargeRepository {
155
296
  }
156
297
  async updateAttemptByProviderPayment(input) {
157
298
  const rows = await this.query(`SELECT * FROM bursar.get_auto_recharge_attempt_by_provider($1, $2)`, [input.provider, input.providerPaymentId]);
158
- for (const row of rows) {
159
- if (row.id == null) {
160
- continue;
161
- }
162
- await this.advanceAttempt({
163
- id: String(row.id),
164
- state: input.state,
165
- providerAttemptId: input.providerPaymentId,
166
- failureCode: input.failureCode,
167
- failureMessage: input.failureMessage,
168
- });
169
- }
299
+ const row = optionalRecordRow(rows, "BillingAutoRechargeRepository.updateAttemptByProviderPayment");
300
+ if (row === null)
301
+ return;
302
+ const attempt = attemptFromRow(row);
303
+ await this.advanceAttempt({
304
+ id: attempt.id,
305
+ state: input.state,
306
+ providerAttemptId: input.providerPaymentId,
307
+ failureCode: input.failureCode,
308
+ failureMessage: input.failureMessage,
309
+ });
170
310
  }
171
311
  async countAttempts(userId, since) {
172
312
  const sinceDate = since instanceof Date ? since : new Date(since);
@@ -174,7 +314,10 @@ export class BillingAutoRechargeRepository {
174
314
  throw new TypeError("auto-recharge attempt boundary must be a valid instant");
175
315
  }
176
316
  const rows = await this.query(`SELECT bursar.count_auto_recharge_attempts($1::uuid, $2::timestamptz) AS count`, [userId, sinceDate.toISOString()]);
177
- return Number(rows[0]?.count ?? 0);
317
+ return requireResultField(rows, "count", z
318
+ .union([z.number(), z.string().regex(/^\d+$/)])
319
+ .transform(Number)
320
+ .pipe(z.number().int().nonnegative().safe()), "BillingAutoRechargeRepository.countAttempts");
178
321
  }
179
322
  }
180
323
  //# sourceMappingURL=auto-recharge.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"auto-recharge.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/auto-recharge.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAElF,SAAS,GAAG,CAAC,KAAc;IACzB,OAAO,IAAI,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;AAC/C,CAAC;AAED,SAAS,cAAc,CAAC,GAA4B;IAClD,OAAO;QACL,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC;QAC9B,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC;QAC7B,KAAK,EAAE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC;QACzB,KAAK,EAAE,MAAM,CAAC,GAAG,CAAC,KAAK,CAAwC;QAC/D,QAAQ,EAAE,GAAG,CAAC,QAAQ,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;QAC5D,OAAO,EAAE,GAAG,CAAC,QAAQ,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;QAC3D,QAAQ,EAAE,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;QAC9B,SAAS,EAAE,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC;QAChC,mBAAmB,EACjB,GAAG,CAAC,sBAAsB,IAAI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G,CAAC,EAAE,CAAC;gBAClB,KAAK,EAAE,KAAK,CAAC,KAAK;gBAClB,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;gBAC1C,WAAW,EAAE,KAAK,CAAC,WAAW;gBAC9B,cAAc,EAAE,KAAK,CAAC,cAAc;aACrC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,KAAK,CAAC,aAAa,CAAC,MAAc,EAAE,KAAoB;QACtD,MAAM,SAAS,GAAG,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;QAClE,IAAI,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC;YACtC,MAAM,IAAI,SAAS,CAAC,wDAAwD,CAAC,CAAC;QAChF,CAAC;QACD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,gFAAgF,EAChF,CAAC,MAAM,EAAE,SAAS,CAAC,WAAW,EAAE,CAAC,CAClC,CAAC;QACF,OAAO,MAAM,CAAE,IAAI,CAAC,CAAC,CAAyC,EAAE,KAAK,IAAI,CAAC,CAAC,CAAC;IAC9E,CAAC;CACF","sourcesContent":["import type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { BillingAutoRechargeAttempt, BillingAutoRechargeProfile } from \"../../types/index.js\";\nimport { optionalBoundedDiagnosticMessage } from \"../../../shared/diagnostics.js\";\n\nfunction iso(value: unknown): string {\n return new Date(String(value)).toISOString();\n}\n\nfunction profileFromRow(row: Record<string, unknown>): BillingAutoRechargeProfile {\n return {\n userId: String(row.subject_id),\n enabled: Boolean(row.enabled),\n armed: Boolean(row.armed),\n state: String(row.state) as BillingAutoRechargeProfile[\"state\"],\n provider: row.provider == null ? null : String(row.provider),\n topupId: row.topup_id == null ? null : String(row.topup_id),\n quantity: Number(row.quantity),\n threshold: Number(row.threshold),\n maxChargesPerWindow:\n row.max_charges_per_window == null ? null : Number(row.max_charges_per_window),\n windowUnit: String(row.window_unit) as BillingAutoRechargeProfile[\"windowUnit\"],\n windowCount: Number(row.window_count),\n windowAnchor: String(row.window_anchor) as BillingAutoRechargeProfile[\"windowAnchor\"],\n windowTimezone: String(row.window_timezone),\n updatedAt: row.updated_at == null ? null : iso(row.updated_at),\n };\n}\n\nfunction attemptFromRow(row: Record<string, unknown>): BillingAutoRechargeAttempt {\n return {\n id: String(row.id),\n userId: String(row.subject_id),\n provider: String(row.provider),\n idempotencyKey: String(row.idempotency_key),\n providerAttemptId: row.provider_attempt_id == null ? null : String(row.provider_attempt_id),\n topupId: String(row.topup_id),\n quantity: Number(row.quantity),\n state: String(row.state) as BillingAutoRechargeAttempt[\"state\"],\n windowStart: iso(row.window_start),\n windowEnd: iso(row.window_end),\n quotedAmountMinor: row.quoted_amount_minor == null ? null : Number(row.quoted_amount_minor),\n currency: row.currency == null ? null : String(row.currency),\n failureCode: row.failure_code == null ? null : String(row.failure_code),\n failureMessage: row.failure_message == null ? null : String(row.failure_message),\n metadata:\n row.metadata != null && typeof row.metadata === \"object\" && !Array.isArray(row.metadata)\n ? (row.metadata as Record<string, unknown>)\n : {},\n createdAt: iso(row.created_at),\n updatedAt: iso(row.updated_at),\n };\n}\n\nexport class BillingAutoRechargeRepository {\n constructor(private readonly query: QueryFn) {}\n\n async getProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_auto_recharge_profile($1::uuid)\", [\n userId,\n ]);\n const row = rows[0] as Record<string, unknown> | undefined;\n return row?.subject_id == null ? null : profileFromRow(row);\n }\n\n async upsertProfile(\n profile: BillingAutoRechargeProfile,\n options: { resetCooldown?: boolean } = {},\n ): Promise<void> {\n const rows = await this.query(\n `SELECT bursar.upsert_auto_recharge_profile(\n $1::uuid, $2, $3, $4::uuid, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14\n ) AS updated`,\n [\n profile.userId,\n profile.enabled,\n profile.provider,\n profile.topupId,\n profile.quantity,\n profile.threshold,\n profile.maxChargesPerWindow,\n profile.windowUnit,\n profile.windowCount,\n profile.windowAnchor,\n profile.windowTimezone,\n profile.armed,\n profile.state,\n options.resetCooldown ?? false,\n ],\n );\n if (!(rows[0] as Record<string, unknown> | undefined)?.updated) {\n throw new Error(`auto-recharge profile update rejected: ${profile.userId}`);\n }\n }\n\n async claimAttempt(input: {\n userId: string;\n idempotencyKey: string;\n }): Promise<BillingAutoRechargeAttempt | null> {\n const rows = await this.query(\n \"SELECT * FROM bursar.claim_auto_recharge_attempt($1::uuid, $2)\",\n [input.userId, input.idempotencyKey],\n );\n const row = rows[0] as Record<string, unknown> | undefined;\n return row?.id == null ? null : attemptFromRow(row);\n }\n\n private async advanceAttempt(input: {\n id: string;\n state: string;\n providerAttemptId?: string | null;\n failureCode?: string | null;\n failureMessage?: string | null;\n metadata?: Record<string, unknown>;\n }): Promise<void> {\n const failureMessage = optionalBoundedDiagnosticMessage(input.failureMessage);\n const currentRows = await this.query(\n \"SELECT * FROM bursar.get_auto_recharge_attempt($1::uuid)\",\n [input.id],\n );\n const current = String((currentRows[0] as Record<string, unknown> | undefined)?.state ?? \"\");\n const paths: Record<string, Record<string, string[]>> = {\n claimed: {\n submitted: [\"submitted\"],\n processing: [\"submitted\", \"processing\"],\n succeeded: [\"submitted\", \"processing\", \"succeeded\"],\n failed: [\"submitted\", \"processing\", \"failed\"],\n unknown: [\"submitted\", \"processing\", \"unknown\"],\n action_required: [\"submitted\", \"action_required\"],\n },\n submitted: {\n submitted: [],\n processing: [\"processing\"],\n succeeded: [\"processing\", \"succeeded\"],\n failed: [\"processing\", \"failed\"],\n unknown: [\"processing\", \"unknown\"],\n action_required: [\"action_required\"],\n },\n processing: {\n processing: [],\n succeeded: [\"succeeded\"],\n failed: [\"failed\"],\n unknown: [\"unknown\"],\n action_required: [\"action_required\"],\n },\n unknown: {\n unknown: [],\n processing: [\"processing\"],\n succeeded: [\"succeeded\"],\n failed: [\"failed\"],\n action_required: [\"action_required\"],\n },\n action_required: {\n action_required: [],\n processing: [\"processing\"],\n succeeded: [\"succeeded\"],\n failed: [\"failed\"],\n },\n };\n const path = paths[current]?.[input.state];\n if (!path) {\n throw new Error(`auto-recharge attempt transition rejected: ${input.id}`);\n }\n for (const state of path) {\n const rows = await this.query(\n `SELECT bursar.advance_auto_recharge_attempt(\n $1::uuid,\n $2::bursar.recharge_attempt_status,\n $3,\n $4,\n $5,\n $6::jsonb\n ) AS advanced`,\n [\n input.id,\n state,\n input.providerAttemptId ?? null,\n input.failureCode ?? null,\n failureMessage,\n JSON.stringify(input.metadata ?? {}),\n ],\n );\n if (!(rows[0] as Record<string, unknown> | undefined)?.advanced) {\n throw new Error(`auto-recharge attempt transition rejected: ${input.id}`);\n }\n }\n }\n\n async updateAttempt(input: {\n id: string;\n state: string;\n providerAttemptId?: string | null;\n failureCode?: string | null;\n failureMessage?: string | null;\n metadata?: Record<string, unknown>;\n }): Promise<void> {\n return this.advanceAttempt(input);\n }\n\n async updateAttemptByProviderPayment(input: {\n provider: string;\n providerPaymentId: string;\n state: string;\n failureCode?: string | null;\n failureMessage?: string | null;\n }): Promise<void> {\n const rows = await this.query(\n `SELECT * FROM bursar.get_auto_recharge_attempt_by_provider($1, $2)`,\n [input.provider, input.providerPaymentId],\n );\n for (const row of rows as Array<Record<string, unknown>>) {\n if (row.id == null) {\n continue;\n }\n await this.advanceAttempt({\n id: String(row.id),\n state: input.state,\n providerAttemptId: input.providerPaymentId,\n failureCode: input.failureCode,\n failureMessage: input.failureMessage,\n });\n }\n }\n\n async countAttempts(userId: string, since: string | Date): Promise<number> {\n const sinceDate = since instanceof Date ? since : new Date(since);\n if (Number.isNaN(sinceDate.getTime())) {\n throw new TypeError(\"auto-recharge attempt boundary must be a valid instant\");\n }\n const rows = await this.query(\n `SELECT bursar.count_auto_recharge_attempts($1::uuid, $2::timestamptz) AS count`,\n [userId, sinceDate.toISOString()],\n );\n return Number((rows[0] as Record<string, unknown> | undefined)?.count ?? 0);\n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I,CAAC,cAAc,CAAC;YACxB,EAAE,EAAE,OAAO,CAAC,EAAE;YACd,KAAK,EAAE,KAAK,CAAC,KAAK;YAClB,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;YAC1C,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,aAAa,CAAC,MAAc,EAAE,KAAoB;QACtD,MAAM,SAAS,GAAG,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;QAClE,IAAI,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC;YACtC,MAAM,IAAI,SAAS,CAAC,wDAAwD,CAAC,CAAC;QAChF,CAAC;QACD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,gFAAgF,EAChF,CAAC,MAAM,EAAE,SAAS,CAAC,WAAW,EAAE,CAAC,CAClC,CAAC;QACF,OAAO,kBAAkB,CACvB,IAAI,EACJ,OAAO,EACP,CAAC;aACE,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;aAC9C,SAAS,CAAC,MAAM,CAAC;aACjB,IAAI,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,CAAC,EAC9C,6CAA6C,CAC9C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport Decimal from \"decimal.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeAttemptState,\n BillingAutoRechargeProfile,\n} from \"../../types/index.js\";\nimport { optionalBoundedDiagnosticMessage } from \"../../../shared/diagnostics.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst safeNonnegativeInteger = z\n .union([z.number(), z.string().regex(/^\\d+$/)])\n .transform(Number)\n .pipe(z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER));\nconst positiveInteger = safeNonnegativeInteger.pipe(z.number().positive());\nconst timestamp = z\n .union([\n z.date().refine((value) => !Number.isNaN(value.getTime())),\n z.string().datetime({ offset: true }),\n ])\n .transform((value) => (value instanceof Date ? value : new Date(value)).toISOString());\nconst decimal = z\n .union([z.instanceof(Decimal), z.string().min(1), z.number().finite()])\n .transform((value) => new Decimal(value))\n .refine((value) => value.isFinite() && !value.isNegative(), \"expected a non-negative decimal\");\n\nconst ProfileRowSchema = z\n .object({\n subject_id: postgresUuid,\n enabled: pgBoolean,\n armed: pgBoolean,\n state: z.enum([\"disabled\", \"active\", \"paused\"]),\n provider: z.string().min(1).nullable(),\n topup_id: postgresUuid.nullable(),\n quantity: positiveInteger,\n threshold: decimal,\n max_charges_per_window: positiveInteger.nullable(),\n window_unit: z.enum([\"second\", \"minute\", \"hour\", \"day\", \"week\", \"month\", \"year\"]),\n window_count: positiveInteger,\n window_anchor: z.enum([\"calendar\", \"rolling\"]),\n window_timezone: z.string().min(1),\n updated_at: timestamp,\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.enabled !== (row.state !== \"disabled\")) {\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: \"enabled and state are inconsistent\" });\n }\n if (row.enabled && (row.provider === null || row.topup_id === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"enabled profile requires provider and topup_id\",\n });\n }\n });\n\nconst AttemptStateSchema = z.enum([\n \"claimed\",\n \"submitted\",\n \"processing\",\n \"unknown\",\n \"succeeded\",\n \"failed\",\n \"action_required\",\n]);\nconst AttemptRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n idempotency_key: z.string().min(1),\n provider_attempt_id: z.string().min(1).nullable(),\n topup_id: postgresUuid,\n quantity: positiveInteger,\n state: AttemptStateSchema,\n window_start: timestamp,\n window_end: timestamp,\n quoted_amount_minor: safeNonnegativeInteger.nullable(),\n currency: z\n .string()\n .regex(/^[A-Z]{3}$/)\n .nullable(),\n failure_code: z.string().min(1).nullable(),\n failure_message: z.string().min(1).nullable(),\n metadata: z.record(z.string(), z.unknown()),\n created_at: timestamp,\n updated_at: timestamp,\n })\n .strict()\n .superRefine((row, ctx) => {\n if (new Date(row.window_end).getTime() <= new Date(row.window_start).getTime()) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"window_end must be later than window_start\",\n });\n }\n if ((row.quoted_amount_minor === null) !== (row.currency === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"quoted_amount_minor and currency must be present together\",\n });\n }\n });\n\nfunction projectProfile(row: Record<string, unknown>): Record<string, unknown> {\n return {\n subject_id: row.subject_id,\n enabled: row.enabled,\n armed: row.armed,\n state: row.state,\n provider: row.provider,\n topup_id: row.topup_id,\n quantity: row.quantity,\n threshold: row.threshold,\n max_charges_per_window: row.max_charges_per_window,\n window_unit: row.window_unit,\n window_count: row.window_count,\n window_anchor: row.window_anchor,\n window_timezone: row.window_timezone,\n updated_at: row.updated_at,\n };\n}\n\nfunction projectAttempt(row: Record<string, unknown>): Record<string, unknown> {\n return {\n id: row.id,\n subject_id: row.subject_id,\n provider: row.provider,\n idempotency_key: row.idempotency_key,\n provider_attempt_id: row.provider_attempt_id,\n topup_id: row.topup_id,\n quantity: row.quantity,\n state: row.state,\n window_start: row.window_start,\n window_end: row.window_end,\n quoted_amount_minor: row.quoted_amount_minor,\n currency: row.currency,\n failure_code: row.failure_code,\n failure_message: row.failure_message,\n metadata: row.metadata,\n created_at: row.created_at,\n updated_at: row.updated_at,\n };\n}\n\nfunction profileFromRow(row: Record<string, unknown>): BillingAutoRechargeProfile {\n const parsed = safeParse(\n ProfileRowSchema,\n projectProfile(row),\n \"BillingAutoRechargeRepository.profile\",\n );\n return {\n userId: parsed.subject_id,\n enabled: parsed.enabled,\n armed: parsed.armed,\n state: parsed.state,\n provider: parsed.provider,\n topupId: parsed.topup_id,\n quantity: parsed.quantity,\n threshold: parsed.threshold,\n maxChargesPerWindow: parsed.max_charges_per_window,\n windowUnit: parsed.window_unit,\n windowCount: parsed.window_count,\n windowAnchor: parsed.window_anchor,\n windowTimezone: parsed.window_timezone,\n updatedAt: parsed.updated_at,\n };\n}\n\nfunction attemptFromRow(row: Record<string, unknown>): BillingAutoRechargeAttempt {\n const parsed = safeParse(\n AttemptRowSchema,\n projectAttempt(row),\n \"BillingAutoRechargeRepository.attempt\",\n );\n return {\n id: parsed.id,\n userId: parsed.subject_id,\n provider: parsed.provider,\n idempotencyKey: parsed.idempotency_key,\n providerAttemptId: parsed.provider_attempt_id,\n topupId: parsed.topup_id,\n quantity: parsed.quantity,\n state: parsed.state,\n windowStart: parsed.window_start,\n windowEnd: parsed.window_end,\n quotedAmountMinor: parsed.quoted_amount_minor,\n currency: parsed.currency,\n failureCode: parsed.failure_code,\n failureMessage: parsed.failure_message,\n metadata: parsed.metadata,\n createdAt: parsed.created_at,\n updatedAt: parsed.updated_at,\n };\n}\n\nexport class BillingAutoRechargeRepository {\n constructor(private readonly query: QueryFn) {}\n\n async getProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_auto_recharge_profile($1::uuid)\", [\n userId,\n ]);\n const row = optionalRecordRow(rows, \"BillingAutoRechargeRepository.getProfile\");\n return row === null ? null : profileFromRow(row);\n }\n\n async upsertProfile(\n profile: BillingAutoRechargeProfile,\n options: { resetCooldown?: boolean } = {},\n ): Promise<void> {\n const rows = await this.query(\n `SELECT bursar.upsert_auto_recharge_profile(\n $1::uuid, $2, $3, $4::uuid, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14\n ) AS updated`,\n [\n profile.userId,\n profile.enabled,\n profile.provider,\n profile.topupId,\n profile.quantity,\n profile.threshold.toString(),\n profile.maxChargesPerWindow,\n profile.windowUnit,\n profile.windowCount,\n profile.windowAnchor,\n profile.windowTimezone,\n profile.armed,\n profile.state,\n options.resetCooldown ?? false,\n ],\n );\n if (\n !requireResultField(rows, \"updated\", pgBoolean, \"BillingAutoRechargeRepository.upsertProfile\")\n ) {\n throw new StoreError(`auto-recharge profile update rejected: ${profile.userId}`);\n }\n }\n\n async claimAttempt(input: {\n userId: string;\n idempotencyKey: string;\n }): Promise<BillingAutoRechargeAttempt | null> {\n const rows = await this.query(\n \"SELECT * FROM bursar.claim_auto_recharge_attempt($1::uuid, $2)\",\n [input.userId, input.idempotencyKey],\n );\n const row = optionalRecordRow(rows, \"BillingAutoRechargeRepository.claimAttempt\");\n return row === null ? null : attemptFromRow(row);\n }\n\n private async advanceAttempt(input: {\n id: string;\n state: BillingAutoRechargeAttemptState;\n providerAttemptId?: string | null;\n failureCode?: string | null;\n failureMessage?: string | null;\n metadata?: Record<string, unknown>;\n }): Promise<void> {\n const failureMessage = optionalBoundedDiagnosticMessage(input.failureMessage);\n const currentRows = await this.query(\n \"SELECT * FROM bursar.get_auto_recharge_attempt($1::uuid)\",\n [input.id],\n );\n const currentRow = optionalRecordRow(\n currentRows,\n \"BillingAutoRechargeRepository.advanceAttempt.current\",\n );\n if (currentRow === null) {\n throw new StoreError(`auto-recharge attempt not found: ${input.id}`, {\n details: { attemptId: input.id },\n });\n }\n const current = safeParse(\n AttemptStateSchema,\n currentRow.state,\n \"BillingAutoRechargeRepository.advanceAttempt.current.state\",\n );\n const paths: Partial<\n Record<\n BillingAutoRechargeAttemptState,\n Partial<Record<BillingAutoRechargeAttemptState, BillingAutoRechargeAttemptState[]>>\n >\n > = {\n claimed: {\n submitted: [\"submitted\"],\n processing: [\"submitted\", \"processing\"],\n succeeded: [\"submitted\", \"processing\", \"succeeded\"],\n failed: [\"submitted\", \"processing\", \"failed\"],\n unknown: [\"submitted\", \"processing\", \"unknown\"],\n action_required: [\"submitted\", \"action_required\"],\n },\n submitted: {\n submitted: [],\n processing: [\"processing\"],\n succeeded: [\"processing\", \"succeeded\"],\n failed: [\"processing\", \"failed\"],\n unknown: [\"processing\", \"unknown\"],\n action_required: [\"action_required\"],\n },\n processing: {\n processing: [],\n succeeded: [\"succeeded\"],\n failed: [\"failed\"],\n unknown: [\"unknown\"],\n action_required: [\"action_required\"],\n },\n unknown: {\n unknown: [],\n processing: [\"processing\"],\n succeeded: [\"succeeded\"],\n failed: [\"failed\"],\n action_required: [\"action_required\"],\n },\n action_required: {\n action_required: [],\n processing: [\"processing\"],\n succeeded: [\"succeeded\"],\n failed: [\"failed\"],\n },\n };\n const path = paths[current]?.[input.state];\n if (!path) {\n throw new StoreError(`auto-recharge attempt transition rejected: ${input.id}`, {\n details: { attemptId: input.id, currentState: current, requestedState: input.state },\n });\n }\n for (const state of path) {\n const rows = await this.query(\n `SELECT bursar.advance_auto_recharge_attempt(\n $1::uuid,\n $2::bursar.recharge_attempt_status,\n $3,\n $4,\n $5,\n $6::jsonb\n ) AS advanced`,\n [\n input.id,\n state,\n input.providerAttemptId ?? null,\n input.failureCode ?? null,\n failureMessage,\n JSON.stringify(input.metadata ?? {}),\n ],\n );\n if (\n !requireResultField(\n rows,\n \"advanced\",\n pgBoolean,\n \"BillingAutoRechargeRepository.advanceAttempt\",\n )\n ) {\n throw new StoreError(`auto-recharge attempt transition rejected: ${input.id}`, {\n details: { attemptId: input.id, requestedState: state },\n });\n }\n }\n }\n\n async updateAttempt(input: {\n id: string;\n state: BillingAutoRechargeAttemptState;\n providerAttemptId?: string | null;\n failureCode?: string | null;\n failureMessage?: string | null;\n metadata?: Record<string, unknown>;\n }): Promise<void> {\n return this.advanceAttempt(input);\n }\n\n async updateAttemptByProviderPayment(input: {\n provider: string;\n providerPaymentId: string;\n state: BillingAutoRechargeAttemptState;\n failureCode?: string | null;\n failureMessage?: string | null;\n }): Promise<void> {\n const rows = await this.query(\n `SELECT * FROM bursar.get_auto_recharge_attempt_by_provider($1, $2)`,\n [input.provider, input.providerPaymentId],\n );\n const row = optionalRecordRow(\n rows,\n \"BillingAutoRechargeRepository.updateAttemptByProviderPayment\",\n );\n if (row === null) return;\n const attempt = attemptFromRow(row);\n await this.advanceAttempt({\n id: attempt.id,\n state: input.state,\n providerAttemptId: input.providerPaymentId,\n failureCode: input.failureCode,\n failureMessage: input.failureMessage,\n });\n }\n\n async countAttempts(userId: string, since: string | Date): Promise<number> {\n const sinceDate = since instanceof Date ? since : new Date(since);\n if (Number.isNaN(sinceDate.getTime())) {\n throw new TypeError(\"auto-recharge attempt boundary must be a valid instant\");\n }\n const rows = await this.query(\n `SELECT bursar.count_auto_recharge_attempts($1::uuid, $2::timestamptz) AS count`,\n [userId, sinceDate.toISOString()],\n );\n return requireResultField(\n rows,\n \"count\",\n z\n .union([z.number(), z.string().regex(/^\\d+$/)])\n .transform(Number)\n .pipe(z.number().int().nonnegative().safe()),\n \"BillingAutoRechargeRepository.countAttempts\",\n );\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"customer.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/customer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAEjE,qBAAa,yBAAyB;IACxB,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAE5B,MAAM,CACV,QAAQ,EAAE,MAAM,EAChB,kBAAkB,EAAE,MAAM,EAC1B,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GAAG,IAAI,GACnB,OAAO,CAAC,IAAI,CAAC;IASV,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,kBAAkB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IASzE,WAAW,CACf,MAAM,EAAE,MAAM,EACd,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GACvB,OAAO,CAAC;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,kBAAkB,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;CASpE"}
1
+ {"version":3,"file":"customer.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/customer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAiBjE,qBAAa,yBAAyB;IACxB,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAE5B,MAAM,CACV,QAAQ,EAAE,MAAM,EAChB,kBAAkB,EAAE,MAAM,EAC1B,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GAAG,IAAI,GACnB,OAAO,CAAC,IAAI,CAAC;IAQV,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,kBAAkB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAWzE,WAAW,CACf,MAAM,EAAE,MAAM,EACd,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GACvB,OAAO,CAAC;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,kBAAkB,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;CAUpE"}
@@ -1,33 +1,41 @@
1
+ import { z } from "zod";
2
+ import { optionalRecordRow, postgresUuid, requireResultField, safeParse, } from "../../../shared/postgres-validation.js";
3
+ const CustomerRowSchema = z.object({
4
+ subject_id: postgresUuid,
5
+ });
6
+ const CustomerByUserRowSchema = z.object({
7
+ provider: z.string().min(1),
8
+ provider_customer_id: z.string().min(1),
9
+ });
1
10
  export class BillingCustomerRepository {
2
11
  query;
3
12
  constructor(query) {
4
13
  this.query = query;
5
14
  }
6
15
  async upsert(provider, providerCustomerId, userId, email) {
7
- await this.query("SELECT bursar.upsert_billing_customer($1::uuid, $2, $3, $4)", [
8
- userId,
9
- provider,
10
- providerCustomerId,
11
- email,
12
- ]);
16
+ const rows = await this.query("SELECT bursar.upsert_billing_customer($1::uuid, $2, $3, $4) AS id", [userId, provider, providerCustomerId, email]);
17
+ requireResultField(rows, "id", postgresUuid, "BillingCustomerRepository.upsert");
13
18
  }
14
19
  async get(provider, providerCustomerId) {
15
20
  const rows = await this.query("SELECT * FROM bursar.get_billing_customer_by_provider($1, $2)", [
16
21
  provider,
17
22
  providerCustomerId,
18
23
  ]);
19
- const row = rows[0];
20
- return row?.subject_id == null ? null : String(row.subject_id);
24
+ const row = optionalRecordRow(rows, "BillingCustomerRepository.get");
25
+ return row === null
26
+ ? null
27
+ : safeParse(CustomerRowSchema, row, "BillingCustomerRepository.get").subject_id;
21
28
  }
22
29
  async getByUserId(userId, provider) {
23
30
  const rows = await this.query("SELECT * FROM bursar.get_billing_customer($1::uuid, $2)", [
24
31
  userId,
25
32
  provider ?? null,
26
33
  ]);
27
- const row = rows[0];
28
- if (!row)
34
+ const row = optionalRecordRow(rows, "BillingCustomerRepository.getByUserId");
35
+ if (row === null)
29
36
  return null;
30
- return { provider: String(row.provider), providerCustomerId: String(row.provider_customer_id) };
37
+ const parsed = safeParse(CustomerByUserRowSchema, row, "BillingCustomerRepository.getByUserId");
38
+ return { provider: parsed.provider, providerCustomerId: parsed.provider_customer_id };
31
39
  }
32
40
  }
33
41
  //# sourceMappingURL=customer.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"customer.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/customer.ts"],"names":[],"mappings":"AAEA,MAAM,OAAO,yBAAyB;IAChB;IAApB,YAAoB,KAAc;QAAd,UAAK,GAAL,KAAK,CAAS;IAAG,CAAC;IAEtC,KAAK,CAAC,MAAM,CACV,QAAgB,EAChB,kBAA0B,EAC1B,MAAc,EACd,KAAoB;QAEpB,MAAM,IAAI,CAAC,KAAK,CAAC,6DAA6D,EAAE;YAC9E,MAAM;YACN,QAAQ;YACR,kBAAkB;YAClB,KAAK;SACN,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,QAAgB,EAAE,kBAA0B;QACpD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,+DAA+D,EAAE;YAC7F,QAAQ;YACR,kBAAkB;SACnB,CAAC,CAAC;QACH,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAwC,CAAC;QAC3D,OAAO,GAAG,EAAE,UAAU,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IACjE,CAAC;IAED,KAAK,CAAC,WAAW,CACf,MAAc,EACd,QAAwB;QAExB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,yDAAyD,EAAE;YACvF,MAAM;YACN,QAAQ,IAAI,IAAI;SACjB,CAAC,CAAC;QACH,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAwC,CAAC;QAC3D,IAAI,CAAC,GAAG;YAAE,OAAO,IAAI,CAAC;QACtB,OAAO,EAAE,QAAQ,EAAE,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,kBAAkB,EAAE,MAAM,CAAC,GAAG,CAAC,oBAAoB,CAAC,EAAE,CAAC;IAClG,CAAC;CACF","sourcesContent":["import type { QueryFn } from \"../../../shared/postgres-types.js\";\n\nexport class BillingCustomerRepository {\n constructor(private query: QueryFn) {}\n\n async upsert(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email: string | null,\n ): Promise<void> {\n await this.query(\"SELECT bursar.upsert_billing_customer($1::uuid, $2, $3, $4)\", [\n userId,\n provider,\n providerCustomerId,\n email,\n ]);\n }\n\n async get(provider: string, providerCustomerId: string): Promise<string | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_customer_by_provider($1, $2)\", [\n provider,\n providerCustomerId,\n ]);\n const row = rows[0] as Record<string, unknown> | undefined;\n return row?.subject_id == null ? null : String(row.subject_id);\n }\n\n async getByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<{ provider: string; providerCustomerId: string } | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_customer($1::uuid, $2)\", [\n userId,\n provider ?? null,\n ]);\n const row = rows[0] as Record<string, unknown> | undefined;\n if (!row) return null;\n return { provider: String(row.provider), providerCustomerId: String(row.provider_customer_id) };\n }\n}\n"]}
1
+ {"version":3,"file":"customer.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/customer.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,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC;IACjC,UAAU,EAAE,YAAY;CACzB,CAAC,CAAC;AAEH,MAAM,uBAAuB,GAAG,CAAC,CAAC,MAAM,CAAC;IACvC,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3B,oBAAoB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;CACxC,CAAC,CAAC;AAEH,MAAM,OAAO,yBAAyB;IAChB;IAApB,YAAoB,KAAc;QAAd,UAAK,GAAL,KAAK,CAAS;IAAG,CAAC;IAEtC,KAAK,CAAC,MAAM,CACV,QAAgB,EAChB,kBAA0B,EAC1B,MAAc,EACd,KAAoB;QAEpB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,mEAAmE,EACnE,CAAC,MAAM,EAAE,QAAQ,EAAE,kBAAkB,EAAE,KAAK,CAAC,CAC9C,CAAC;QACF,kBAAkB,CAAC,IAAI,EAAE,IAAI,EAAE,YAAY,EAAE,kCAAkC,CAAC,CAAC;IACnF,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,QAAgB,EAAE,kBAA0B;QACpD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,+DAA+D,EAAE;YAC7F,QAAQ;YACR,kBAAkB;SACnB,CAAC,CAAC;QACH,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,+BAA+B,CAAC,CAAC;QACrE,OAAO,GAAG,KAAK,IAAI;YACjB,CAAC,CAAC,IAAI;YACN,CAAC,CAAC,SAAS,CAAC,iBAAiB,EAAE,GAAG,EAAE,+BAA+B,CAAC,CAAC,UAAU,CAAC;IACpF,CAAC;IAED,KAAK,CAAC,WAAW,CACf,MAAc,EACd,QAAwB;QAExB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,yDAAyD,EAAE;YACvF,MAAM;YACN,QAAQ,IAAI,IAAI;SACjB,CAAC,CAAC;QACH,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,uCAAuC,CAAC,CAAC;QAC7E,IAAI,GAAG,KAAK,IAAI;YAAE,OAAO,IAAI,CAAC;QAC9B,MAAM,MAAM,GAAG,SAAS,CAAC,uBAAuB,EAAE,GAAG,EAAE,uCAAuC,CAAC,CAAC;QAChG,OAAO,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,kBAAkB,EAAE,MAAM,CAAC,oBAAoB,EAAE,CAAC;IACxF,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 CustomerRowSchema = z.object({\n subject_id: postgresUuid,\n});\n\nconst CustomerByUserRowSchema = z.object({\n provider: z.string().min(1),\n provider_customer_id: z.string().min(1),\n});\n\nexport class BillingCustomerRepository {\n constructor(private query: QueryFn) {}\n\n async upsert(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email: string | null,\n ): Promise<void> {\n const rows = await this.query(\n \"SELECT bursar.upsert_billing_customer($1::uuid, $2, $3, $4) AS id\",\n [userId, provider, providerCustomerId, email],\n );\n requireResultField(rows, \"id\", postgresUuid, \"BillingCustomerRepository.upsert\");\n }\n\n async get(provider: string, providerCustomerId: string): Promise<string | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_customer_by_provider($1, $2)\", [\n provider,\n providerCustomerId,\n ]);\n const row = optionalRecordRow(rows, \"BillingCustomerRepository.get\");\n return row === null\n ? null\n : safeParse(CustomerRowSchema, row, \"BillingCustomerRepository.get\").subject_id;\n }\n\n async getByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<{ provider: string; providerCustomerId: string } | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_customer($1::uuid, $2)\", [\n userId,\n provider ?? null,\n ]);\n const row = optionalRecordRow(rows, \"BillingCustomerRepository.getByUserId\");\n if (row === null) return null;\n const parsed = safeParse(CustomerByUserRowSchema, row, \"BillingCustomerRepository.getByUserId\");\n return { provider: parsed.provider, providerCustomerId: parsed.provider_customer_id };\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"dispute.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/dispute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAEjE,qBAAa,wBAAwB;IACvB,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAE5B,MAAM,CACV,QAAQ,EAAE,MAAM,EAChB,iBAAiB,EAAE,MAAM,EACzB,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACjC,iBAAiB,EAAE,MAAM,GACxB,OAAO,CAAC,IAAI,CAAC;CAcjB"}
1
+ {"version":3,"file":"dispute.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/dispute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAGjE,qBAAa,wBAAwB;IACvB,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAE5B,MAAM,CACV,QAAQ,EAAE,MAAM,EAChB,iBAAiB,EAAE,MAAM,EACzB,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACjC,iBAAiB,EAAE,MAAM,GACxB,OAAO,CAAC,IAAI,CAAC;CAejB"}
@@ -1,10 +1,11 @@
1
+ import { postgresUuid, requireResultField } from "../../../shared/postgres-validation.js";
1
2
  export class BillingDisputeRepository {
2
3
  query;
3
4
  constructor(query) {
4
5
  this.query = query;
5
6
  }
6
7
  async upsert(provider, providerDisputeId, paymentId, status, reason, metadata, providerUpdatedAt) {
7
- await this.query(`SELECT bursar.upsert_billing_dispute($1, $2, $3::uuid, $4, $5, $6::jsonb, $7)`, [
8
+ const rows = await this.query(`SELECT bursar.upsert_billing_dispute($1, $2, $3::uuid, $4, $5, $6::jsonb, $7) AS id`, [
8
9
  provider,
9
10
  providerDisputeId,
10
11
  paymentId,
@@ -13,6 +14,7 @@ export class BillingDisputeRepository {
13
14
  JSON.stringify(metadata),
14
15
  providerUpdatedAt,
15
16
  ]);
17
+ requireResultField(rows, "id", postgresUuid, "BillingDisputeRepository.upsert");
16
18
  }
17
19
  }
18
20
  //# sourceMappingURL=dispute.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"dispute.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/dispute.ts"],"names":[],"mappings":"AAEA,MAAM,OAAO,wBAAwB;IACf;IAApB,YAAoB,KAAc;QAAd,UAAK,GAAL,KAAK,CAAS;IAAG,CAAC;IAEtC,KAAK,CAAC,MAAM,CACV,QAAgB,EAChB,iBAAyB,EACzB,SAAiB,EACjB,MAAc,EACd,MAAqB,EACrB,QAAiC,EACjC,iBAAyB;QAEzB,MAAM,IAAI,CAAC,KAAK,CACd,+EAA+E,EAC/E;YACE,QAAQ;YACR,iBAAiB;YACjB,SAAS;YACT,MAAM;YACN,MAAM;YACN,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC;YACxB,iBAAiB;SAClB,CACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import type { QueryFn } from \"../../../shared/postgres-types.js\";\n\nexport class BillingDisputeRepository {\n constructor(private query: QueryFn) {}\n\n async upsert(\n provider: string,\n providerDisputeId: string,\n paymentId: string,\n status: string,\n reason: string | null,\n metadata: Record<string, unknown>,\n providerUpdatedAt: string,\n ): Promise<void> {\n await this.query(\n `SELECT bursar.upsert_billing_dispute($1, $2, $3::uuid, $4, $5, $6::jsonb, $7)`,\n [\n provider,\n providerDisputeId,\n paymentId,\n status,\n reason,\n JSON.stringify(metadata),\n providerUpdatedAt,\n ],\n );\n }\n}\n"]}
1
+ {"version":3,"file":"dispute.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/dispute.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,wCAAwC,CAAC;AAE1F,MAAM,OAAO,wBAAwB;IACf;IAApB,YAAoB,KAAc;QAAd,UAAK,GAAL,KAAK,CAAS;IAAG,CAAC;IAEtC,KAAK,CAAC,MAAM,CACV,QAAgB,EAChB,iBAAyB,EACzB,SAAiB,EACjB,MAAc,EACd,MAAqB,EACrB,QAAiC,EACjC,iBAAyB;QAEzB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,qFAAqF,EACrF;YACE,QAAQ;YACR,iBAAiB;YACjB,SAAS;YACT,MAAM;YACN,MAAM;YACN,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC;YACxB,iBAAiB;SAClB,CACF,CAAC;QACF,kBAAkB,CAAC,IAAI,EAAE,IAAI,EAAE,YAAY,EAAE,iCAAiC,CAAC,CAAC;IAClF,CAAC;CACF","sourcesContent":["import type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport { postgresUuid, requireResultField } from \"../../../shared/postgres-validation.js\";\n\nexport class BillingDisputeRepository {\n constructor(private query: QueryFn) {}\n\n async upsert(\n provider: string,\n providerDisputeId: string,\n paymentId: string,\n status: string,\n reason: string | null,\n metadata: Record<string, unknown>,\n providerUpdatedAt: string,\n ): Promise<void> {\n const rows = await this.query(\n `SELECT bursar.upsert_billing_dispute($1, $2, $3::uuid, $4, $5, $6::jsonb, $7) AS id`,\n [\n provider,\n providerDisputeId,\n paymentId,\n status,\n reason,\n JSON.stringify(metadata),\n providerUpdatedAt,\n ],\n );\n requireResultField(rows, \"id\", postgresUuid, \"BillingDisputeRepository.upsert\");\n }\n}\n"]}
@@ -1,17 +1,24 @@
1
1
  import { z } from "zod";
2
2
  import type { QueryFn } from "../../../shared/postgres-types.js";
3
3
  declare const BillingEventRowSchema: z.ZodObject<{
4
- status: z.ZodOptional<z.ZodString>;
5
- event_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
6
- claim_token: z.ZodOptional<z.ZodNullable<z.ZodString>>;
7
- }, z.core.$loose>;
4
+ status: z.ZodEnum<{
5
+ invalid_request: "invalid_request";
6
+ claimed: "claimed";
7
+ duplicate: "duplicate";
8
+ busy: "busy";
9
+ idempotency_conflict: "idempotency_conflict";
10
+ max_retries_exceeded: "max_retries_exceeded";
11
+ }>;
12
+ event_id: z.ZodNullable<z.ZodString>;
13
+ claim_token: z.ZodNullable<z.ZodString>;
14
+ }, z.core.$strict>;
8
15
  export type BillingEventRow = z.infer<typeof BillingEventRowSchema>;
9
16
  /** Repository for billing event lifecycle operations. */
10
17
  export declare class BillingEventRepository {
11
18
  private query;
12
19
  constructor(query: QueryFn);
13
20
  /** Claim a billing event for processing (idempotent claim). */
14
- claim(provider: string, eventId: string, eventType: string, metadata: string): Promise<BillingEventRow | null>;
21
+ claim(provider: string, eventId: string, eventType: string, metadata: string): Promise<BillingEventRow>;
15
22
  /** Mark a billing event as completed. */
16
23
  complete(provider: string, eventId: string, claimToken: string): Promise<boolean>;
17
24
  /** Mark a billing event as failed. */
@@ -1 +1 @@
1
- {"version":3,"file":"event.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/event.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAGjE,QAAA,MAAM,qBAAqB;;;;iBAMX,CAAC;AAEjB,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAQpE,yDAAyD;AACzD,qBAAa,sBAAsB;IACrB,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAElC,+DAA+D;IACzD,KAAK,CACT,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;IAiBlC,yCAAyC;IACnC,QAAQ,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAQvF,sCAAsC;IAChC,IAAI,CACR,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,UAAU,EAAE,MAAM,EAClB,KAAK,CAAC,EAAE,MAAM,GACb,OAAO,CAAC,OAAO,CAAC;CAOpB"}
1
+ {"version":3,"file":"event.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/event.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AASjE,QAAA,MAAM,qBAAqB;;;;;;;;;;;kBAahB,CAAC;AAEZ,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qB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