@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,16 +1,21 @@
1
1
  import { z } from "zod";
2
- import { pgBoolean, safeParse } from "../../../shared/postgres-validation.js";
2
+ import { pgBoolean, postgresUuid, requireRecordRow, requireResultField, safeParse, } from "../../../shared/postgres-validation.js";
3
3
  const BillingEventRowSchema = z
4
4
  .object({
5
- status: z.string().optional(),
6
- event_id: z.string().uuid().nullable().optional(),
7
- claim_token: z.string().uuid().nullable().optional(),
5
+ status: z.enum([
6
+ "claimed",
7
+ "duplicate",
8
+ "busy",
9
+ "invalid_request",
10
+ "idempotency_conflict",
11
+ "max_retries_exceeded",
12
+ ]),
13
+ event_id: postgresUuid.nullable(),
14
+ claim_token: postgresUuid.nullable(),
8
15
  })
9
- .passthrough();
10
- function booleanResult(rows, key) {
11
- const row = rows[0];
12
- const parsed = pgBoolean.safeParse(row?.[key]);
13
- return parsed.success && parsed.data;
16
+ .strict();
17
+ function booleanResult(rows, key, context) {
18
+ return requireResultField(rows, key, pgBoolean, context);
14
19
  }
15
20
  /** Repository for billing event lifecycle operations. */
16
21
  export class BillingEventRepository {
@@ -26,20 +31,18 @@ export class BillingEventRepository {
26
31
  eventType,
27
32
  metadata,
28
33
  ]);
29
- const row = rows[0];
30
- return row
31
- ? safeParse(BillingEventRowSchema, { ...row, status: row.result, event_id: row.event_id }, "BillingEventRepository.claim")
32
- : null;
34
+ const row = requireRecordRow(rows, "BillingEventRepository.claim");
35
+ return safeParse(BillingEventRowSchema, { event_id: row.event_id, status: row.result, claim_token: row.claim_token }, "BillingEventRepository.claim", { indeterminate: true });
33
36
  }
34
37
  /** Mark a billing event as completed. */
35
38
  async complete(provider, eventId, claimToken) {
36
39
  const rows = await this.query("SELECT bursar.complete_billing_event($1, $2, $3::uuid) AS completed", [provider, eventId, claimToken]);
37
- return booleanResult(rows, "completed");
40
+ return booleanResult(rows, "completed", "BillingEventRepository.complete");
38
41
  }
39
42
  /** Mark a billing event as failed. */
40
43
  async fail(provider, eventId, claimToken, error) {
41
44
  const rows = await this.query("SELECT bursar.fail_billing_event($1, $2, $3::uuid, $4) AS failed", [provider, eventId, claimToken, error ?? null]);
42
- return booleanResult(rows, "failed");
45
+ return booleanResult(rows, "failed", "BillingEventRepository.fail");
43
46
  }
44
47
  }
45
48
  //# sourceMappingURL=event.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"event.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/event.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,wCAAwC,CAAC;AAE9E,MAAM,qBAAqB,GAAG,CAAC;KAC5B,MAAM,CAAC;IACN,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC7B,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE;IACjD,WAAW,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE;CACrD,CAAC;KACD,WAAW,EAAE,CAAC;AAIjB,SAAS,aAAa,CAAC,IAAe,EAAE,GAAW;IACjD,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAwC,CAAC;IAC3D,MAAM,MAAM,GAAG,SAAS,CAAC,SAAS,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC/C,OAAO,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,IAAI,CAAC;AACvC,CAAC;AAED,yDAAyD;AACzD,MAAM,OAAO,sBAAsB;IACb;IAApB,YAAoB,KAAc;QAAd,UAAK,GAAL,KAAK,CAAS;IAAG,CAAC;IAEtC,+DAA+D;IAC/D,KAAK,CAAC,KAAK,CACT,QAAgB,EAChB,OAAe,EACf,SAAiB,EACjB,QAAgB;QAEhB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,0DAA0D,EAAE;YACxF,QAAQ;YACR,OAAO;YACP,SAAS;YACT,QAAQ;SACT,CAAC,CAAC;QACH,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAwC,CAAC;QAC3D,OAAO,GAAG;YACR,CAAC,CAAC,SAAS,CACP,qBAAqB,EACrB,EAAE,GAAG,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,QAAQ,EAAE,GAAG,CAAC,QAAQ,EAAE,EACtD,8BAA8B,CAC/B;YACH,CAAC,CAAC,IAAI,CAAC;IACX,CAAC;IAED,yCAAyC;IACzC,KAAK,CAAC,QAAQ,CAAC,QAAgB,EAAE,OAAe,EAAE,UAAkB;QAClE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,qEAAqE,EACrE,CAAC,QAAQ,EAAE,OAAO,EAAE,UAAU,CAAC,CAChC,CAAC;QACF,OAAO,aAAa,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;IAC1C,CAAC;IAED,sCAAsC;IACtC,KAAK,CAAC,IAAI,CACR,QAAgB,EAChB,OAAe,EACf,UAAkB,EAClB,KAAc;QAEd,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,kEAAkE,EAClE,CAAC,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,KAAK,IAAI,IAAI,CAAC,CAC/C,CAAC;QACF,OAAO,aAAa,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IACvC,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport { pgBoolean, safeParse } from \"../../../shared/postgres-validation.js\";\n\nconst BillingEventRowSchema = z\n .object({\n status: z.string().optional(),\n event_id: z.string().uuid().nullable().optional(),\n claim_token: z.string().uuid().nullable().optional(),\n })\n .passthrough();\n\nexport type BillingEventRow = z.infer<typeof BillingEventRowSchema>;\n\nfunction booleanResult(rows: unknown[], key: string): boolean {\n const row = rows[0] as Record<string, unknown> | undefined;\n const parsed = pgBoolean.safeParse(row?.[key]);\n return parsed.success && parsed.data;\n}\n\n/** Repository for billing event lifecycle operations. */\nexport class BillingEventRepository {\n constructor(private query: QueryFn) {}\n\n /** Claim a billing event for processing (idempotent claim). */\n async claim(\n provider: string,\n eventId: string,\n eventType: string,\n metadata: string,\n ): Promise<BillingEventRow | null> {\n const rows = await this.query(\"SELECT * FROM bursar.claim_billing_event($1, $2, $3, $4)\", [\n provider,\n eventId,\n eventType,\n metadata,\n ]);\n const row = rows[0] as Record<string, unknown> | undefined;\n return row\n ? safeParse(\n BillingEventRowSchema,\n { ...row, status: row.result, event_id: row.event_id },\n \"BillingEventRepository.claim\",\n )\n : null;\n }\n\n /** Mark a billing event as completed. */\n async complete(provider: string, eventId: string, claimToken: string): Promise<boolean> {\n const rows = await this.query(\n \"SELECT bursar.complete_billing_event($1, $2, $3::uuid) AS completed\",\n [provider, eventId, claimToken],\n );\n return booleanResult(rows, \"completed\");\n }\n\n /** Mark a billing event as failed. */\n async fail(\n provider: string,\n eventId: string,\n claimToken: string,\n error?: string,\n ): Promise<boolean> {\n const rows = await this.query(\n \"SELECT bursar.fail_billing_event($1, $2, $3::uuid, $4) AS failed\",\n [provider, eventId, claimToken, error ?? null],\n );\n return booleanResult(rows, \"failed\");\n }\n}\n"]}
1
+ {"version":3,"file":"event.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/event.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EACL,SAAS,EACT,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,qBAAqB,GAAG,CAAC;KAC5B,MAAM,CAAC;IACN,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC;QACb,SAAS;QACT,WAAW;QACX,MAAM;QACN,iBAAiB;QACjB,sBAAsB;QACtB,sBAAsB;KACvB,CAAC;IACF,QAAQ,EAAE,YAAY,CAAC,QAAQ,EAAE;IACjC,WAAW,EAAE,YAAY,CAAC,QAAQ,EAAE;CACrC,CAAC;KACD,MAAM,EAAE,CAAC;AAIZ,S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O,EAAE,UAAU,EAAE,KAAK,IAAI,IAAI,CAAC,CAC/C,CAAC;QACF,OAAO,aAAa,CAAC,IAAI,EAAE,QAAQ,EAAE,6BAA6B,CAAC,CAAC;IACtE,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport {\n pgBoolean,\n postgresUuid,\n requireRecordRow,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst BillingEventRowSchema = z\n .object({\n status: z.enum([\n \"claimed\",\n \"duplicate\",\n \"busy\",\n \"invalid_request\",\n \"idempotency_conflict\",\n \"max_retries_exceeded\",\n ]),\n event_id: postgresUuid.nullable(),\n claim_token: postgresUuid.nullable(),\n })\n .strict();\n\nexport type BillingEventRow = z.infer<typeof BillingEventRowSchema>;\n\nfunction booleanResult(rows: unknown[], key: string, context: string): boolean {\n return requireResultField(rows, key, pgBoolean, context);\n}\n\n/** Repository for billing event lifecycle operations. */\nexport class BillingEventRepository {\n constructor(private query: QueryFn) {}\n\n /** Claim a billing event for processing (idempotent claim). */\n async claim(\n provider: string,\n eventId: string,\n eventType: string,\n metadata: string,\n ): Promise<BillingEventRow> {\n const rows = await this.query(\"SELECT * FROM bursar.claim_billing_event($1, $2, $3, $4)\", [\n provider,\n eventId,\n eventType,\n metadata,\n ]);\n const row = requireRecordRow(rows, \"BillingEventRepository.claim\");\n return safeParse(\n BillingEventRowSchema,\n { event_id: row.event_id, status: row.result, claim_token: row.claim_token },\n \"BillingEventRepository.claim\",\n { indeterminate: true },\n );\n }\n\n /** Mark a billing event as completed. */\n async complete(provider: string, eventId: string, claimToken: string): Promise<boolean> {\n const rows = await this.query(\n \"SELECT bursar.complete_billing_event($1, $2, $3::uuid) AS completed\",\n [provider, eventId, claimToken],\n );\n return booleanResult(rows, \"completed\", \"BillingEventRepository.complete\");\n }\n\n /** Mark a billing event as failed. */\n async fail(\n provider: string,\n eventId: string,\n claimToken: string,\n error?: string,\n ): Promise<boolean> {\n const rows = await this.query(\n \"SELECT bursar.fail_billing_event($1, $2, $3::uuid, $4) AS failed\",\n [provider, eventId, claimToken, error ?? null],\n );\n return booleanResult(rows, \"failed\", \"BillingEventRepository.fail\");\n }\n}\n"]}
@@ -1,9 +1,9 @@
1
1
  import type { QueryFn } from "../../../shared/postgres-types.js";
2
- import type { BillingInvoiceInfo } from "../../types/index.js";
2
+ import type { BillingInvoiceRecord } from "../../types/index.js";
3
3
  export declare class BillingInvoiceRepository {
4
4
  private query;
5
5
  constructor(query: QueryFn);
6
- listForUser(userId: string): Promise<BillingInvoiceInfo[]>;
7
- upsert(subjectId: string, provider: string, providerInvoiceId: string, subscriptionId: string | null, status: string | null, amountPaidMinor: number | null, amountDueMinor: number | null, currency: string, periodStart: string | null, periodEnd: string | null, metadata: Record<string, unknown>, providerUpdatedAt: string): Promise<void>;
6
+ listForUser(userId: string): Promise<BillingInvoiceRecord[]>;
7
+ upsert(subjectId: string, provider: string, providerInvoiceId: string, subscriptionId: string | null, status: "draft" | "open" | "paid" | "void" | "uncollectible", amountPaidMinor: number, amountDueMinor: number, currency: string, periodStart: string | null, periodEnd: string | null, metadata: Record<string, unknown>, providerUpdatedAt: string): Promise<void>;
8
8
  }
9
9
  //# sourceMappingURL=invoice.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"invoice.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/invoice.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE/D,qBAAa,wBAAwB;IACvB,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAE5B,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,EAAE,CAAC;IAc1D,MAAM,CACV,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,iBAAiB,EAAE,MAAM,EACzB,cAAc,EAAE,MAAM,GAAG,IAAI,EAC7B,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,eAAe,EAAE,MAAM,GAAG,IAAI,EAC9B,cAAc,EAAE,MAAM,GAAG,IAAI,EAC7B,QAAQ,EAAE,MAAM,EAChB,WAAW,EAAE,MAAM,GAAG,IAAI,EAC1B,SAAS,EAAE,MAAM,GAAG,IAAI,EACxB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACjC,iBAAiB,EAAE,MAAM,GACxB,OAAO,CAAC,IAAI,CAAC;CAmBjB"}
1
+ {"version":3,"file":"invoice.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/invoice.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAgCjE,qBAAa,wBAAwB;IACvB,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAE5B,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,EAAE,CAAC;IAkC5D,MAAM,CACV,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,iBAAiB,EAAE,MAAM,EACzB,cAAc,EAAE,MAAM,GAAG,IAAI,EAC7B,MAAM,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,eAAe,EAC5D,eAAe,EAAE,MAAM,EACvB,cAAc,EAAE,MAAM,EACtB,QAAQ,EAAE,MAAM,EAChB,WAAW,EAAE,MAAM,GAAG,IAAI,EAC1B,SAAS,EAAE,MAAM,GAAG,IAAI,EACxB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACjC,iBAAiB,EAAE,MAAM,GACxB,OAAO,CAAC,IAAI,CAAC;CAoBjB"}
@@ -1,3 +1,28 @@
1
+ import { z } from "zod";
2
+ import { postgresUuid, requireResultField, safeParse, } from "../../../shared/postgres-validation.js";
3
+ const safeMinorUnits = z
4
+ .union([z.number().int().nonnegative().safe(), z.string().regex(/^\d+$/)])
5
+ .transform(Number)
6
+ .refine(Number.isSafeInteger, "minor-unit amount exceeds JavaScript's safe integer range");
7
+ const optionalTimestamp = z
8
+ .union([
9
+ z.date().refine((value) => !Number.isNaN(value.getTime())),
10
+ z.string().datetime({ offset: true }),
11
+ ])
12
+ .transform((value) => (value instanceof Date ? value.toISOString() : value))
13
+ .nullable();
14
+ const InvoiceRowSchema = z
15
+ .object({
16
+ provider: z.string().min(1),
17
+ provider_invoice_id: z.string().min(1),
18
+ status: z.enum(["draft", "open", "paid", "void", "uncollectible"]),
19
+ amount_paid_minor: safeMinorUnits,
20
+ amount_due_minor: safeMinorUnits,
21
+ currency: z.string().regex(/^[A-Z]{3}$/),
22
+ period_start: optionalTimestamp,
23
+ period_end: optionalTimestamp,
24
+ })
25
+ .strict();
1
26
  export class BillingInvoiceRepository {
2
27
  query;
3
28
  constructor(query) {
@@ -5,19 +30,35 @@ export class BillingInvoiceRepository {
5
30
  }
6
31
  async listForUser(userId) {
7
32
  const rows = await this.query(`SELECT * FROM bursar.list_billing_invoices($1::uuid)`, [userId]);
8
- return rows.map((row) => ({
9
- provider: String(row.provider),
10
- providerInvoiceId: String(row.provider_invoice_id),
11
- status: row.status == null ? null : String(row.status),
12
- amountPaidMinor: row.amount_paid_minor == null ? null : Number(row.amount_paid_minor),
13
- amountDueMinor: row.amount_due_minor == null ? null : Number(row.amount_due_minor),
14
- currency: row.currency == null ? null : String(row.currency),
15
- periodStart: row.period_start == null ? null : String(row.period_start),
16
- periodEnd: row.period_end == null ? null : String(row.period_end),
17
- }));
33
+ return rows.map((row) => {
34
+ if (typeof row !== "object" || row === null || Array.isArray(row)) {
35
+ throw new TypeError("BillingInvoiceRepository.listForUser expected an object row");
36
+ }
37
+ const raw = row;
38
+ const parsed = safeParse(InvoiceRowSchema, {
39
+ provider: raw.provider,
40
+ provider_invoice_id: raw.provider_invoice_id,
41
+ status: raw.status,
42
+ amount_paid_minor: raw.amount_paid_minor,
43
+ amount_due_minor: raw.amount_due_minor,
44
+ currency: raw.currency,
45
+ period_start: raw.period_start,
46
+ period_end: raw.period_end,
47
+ }, "BillingInvoiceRepository.listForUser");
48
+ return {
49
+ provider: parsed.provider,
50
+ providerInvoiceId: parsed.provider_invoice_id,
51
+ status: parsed.status,
52
+ amountPaidMinor: parsed.amount_paid_minor,
53
+ amountDueMinor: parsed.amount_due_minor,
54
+ currency: parsed.currency,
55
+ periodStart: parsed.period_start,
56
+ periodEnd: parsed.period_end,
57
+ };
58
+ });
18
59
  }
19
60
  async upsert(subjectId, provider, providerInvoiceId, subscriptionId, status, amountPaidMinor, amountDueMinor, currency, periodStart, periodEnd, metadata, providerUpdatedAt) {
20
- await this.query(`SELECT bursar.upsert_billing_invoice($1::uuid, $2, $3, $4::uuid, $5, $6, $7, $8, $9, $10, $11::jsonb, $12)`, [
61
+ const rows = await this.query(`SELECT bursar.upsert_billing_invoice($1::uuid, $2, $3, $4::uuid, $5, $6, $7, $8, $9, $10, $11::jsonb, $12) AS id`, [
21
62
  subjectId,
22
63
  provider,
23
64
  providerInvoiceId,
@@ -31,6 +72,7 @@ export class BillingInvoiceRepository {
31
72
  JSON.stringify(metadata),
32
73
  providerUpdatedAt,
33
74
  ]);
75
+ requireResultField(rows, "id", postgresUuid, "BillingInvoiceRepository.upsert");
34
76
  }
35
77
  }
36
78
  //# sourceMappingURL=invoice.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"invoice.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/invoice.ts"],"names":[],"mappings":"AAGA,MAAM,OAAO,wBAAwB;IACf;IAApB,YAAoB,KAAc;QAAd,UAAK,GAAL,KAAK,CAAS;IAAG,CAAC;IAEtC,KAAK,CAAC,WAAW,CAAC,MAAc;QAC9B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAA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iBAAyB;QAEzB,MAAM,IAAI,CAAC,KAAK,CACd,4GAA4G,EAC5G;YACE,SAAS;YACT,QAAQ;YACR,iBAAiB;YACjB,cAAc;YACd,MAAM;YACN,cAAc;YACd,eAAe;YACf,QAAQ;YACR,WAAW;YACX,SAAS;YACT,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC;YACxB,iBAAiB;SAClB,CACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { BillingInvoiceInfo } from \"../../types/index.js\";\n\nexport class BillingInvoiceRepository {\n constructor(private query: QueryFn) {}\n\n async listForUser(userId: string): Promise<BillingInvoiceInfo[]> {\n const rows = await this.query(`SELECT * FROM bursar.list_billing_invoices($1::uuid)`, [userId]);\n return (rows as Array<Record<string, unknown>>).map((row) => ({\n provider: String(row.provider),\n providerInvoiceId: String(row.provider_invoice_id),\n status: row.status == null ? null : String(row.status),\n amountPaidMinor: row.amount_paid_minor == null ? null : Number(row.amount_paid_minor),\n amountDueMinor: row.amount_due_minor == null ? null : Number(row.amount_due_minor),\n currency: row.currency == null ? null : String(row.currency),\n periodStart: row.period_start == null ? null : String(row.period_start),\n periodEnd: row.period_end == null ? null : String(row.period_end),\n }));\n }\n\n async upsert(\n subjectId: string,\n provider: string,\n providerInvoiceId: string,\n subscriptionId: string | null,\n status: string | null,\n amountPaidMinor: number | null,\n amountDueMinor: number | null,\n currency: string,\n periodStart: string | null,\n periodEnd: string | null,\n metadata: Record<string, unknown>,\n providerUpdatedAt: string,\n ): Promise<void> {\n await this.query(\n `SELECT bursar.upsert_billing_invoice($1::uuid, $2, $3, $4::uuid, $5, $6, $7, $8, $9, $10, $11::jsonb, $12)`,\n [\n subjectId,\n provider,\n providerInvoiceId,\n subscriptionId,\n status,\n amountDueMinor,\n amountPaidMinor,\n currency,\n periodStart,\n periodEnd,\n JSON.stringify(metadata),\n providerUpdatedAt,\n ],\n );\n }\n}\n"]}
1
+ {"version":3,"file":"invo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,MAAM,CAAC,mBAAmB;gBAC7C,MAAM,EAAE,MAAM,CAAC,MAAM;gBACrB,eAAe,EAAE,MAAM,CAAC,iBAAiB;gBACzC,cAAc,EAAE,MAAM,CAAC,gBAAgB;gBACvC,QAAQ,EAAE,MAAM,CAAC,QAAQ;gBACzB,WAAW,EAAE,MAAM,CAAC,YAAY;gBAChC,SAAS,EAAE,MAAM,CAAC,UAAU;aACE,CAAC;QACnC,CAAC,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,MAAM,CACV,SAAiB,EACjB,QAAgB,EAChB,iBAAyB,EACzB,cAA6B,EAC7B,MAA4D,EAC5D,eAAuB,EACvB,cAAsB,EACtB,QAAgB,EAChB,WAA0B,EAC1B,SAAwB,EACxB,QAAiC,EACjC,iBAAyB;QAEzB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,kHAAkH,EAClH;YACE,SAAS;YACT,QAAQ;YACR,iBAAiB;YACjB,cAAc;YACd,MAAM;YACN,cAAc;YACd,eAAe;YACf,QAAQ;YACR,WAAW;YACX,SAAS;YACT,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 { z } from \"zod\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { BillingInvoiceRecord } from \"../../types/index.js\";\nimport {\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst safeMinorUnits = z\n .union([z.number().int().nonnegative().safe(), z.string().regex(/^\\d+$/)])\n .transform(Number)\n .refine(Number.isSafeInteger, \"minor-unit amount exceeds JavaScript's safe integer range\");\nconst optionalTimestamp = 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.toISOString() : value))\n .nullable();\n\nconst InvoiceRowSchema = z\n .object({\n provider: z.string().min(1),\n provider_invoice_id: z.string().min(1),\n status: z.enum([\"draft\", \"open\", \"paid\", \"void\", \"uncollectible\"]),\n amount_paid_minor: safeMinorUnits,\n amount_due_minor: safeMinorUnits,\n currency: z.string().regex(/^[A-Z]{3}$/),\n period_start: optionalTimestamp,\n period_end: optionalTimestamp,\n })\n .strict();\n\nexport class BillingInvoiceRepository {\n constructor(private query: QueryFn) {}\n\n async listForUser(userId: string): Promise<BillingInvoiceRecord[]> {\n const rows = await this.query(`SELECT * FROM bursar.list_billing_invoices($1::uuid)`, [userId]);\n return rows.map((row) => {\n if (typeof row !== \"object\" || row === null || Array.isArray(row)) {\n throw new TypeError(\"BillingInvoiceRepository.listForUser expected an object row\");\n }\n const raw = row as Record<string, unknown>;\n const parsed = safeParse(\n InvoiceRowSchema,\n {\n provider: raw.provider,\n provider_invoice_id: raw.provider_invoice_id,\n status: raw.status,\n amount_paid_minor: raw.amount_paid_minor,\n amount_due_minor: raw.amount_due_minor,\n currency: raw.currency,\n period_start: raw.period_start,\n period_end: raw.period_end,\n },\n \"BillingInvoiceRepository.listForUser\",\n );\n return {\n provider: parsed.provider,\n providerInvoiceId: parsed.provider_invoice_id,\n status: parsed.status,\n amountPaidMinor: parsed.amount_paid_minor,\n amountDueMinor: parsed.amount_due_minor,\n currency: parsed.currency,\n periodStart: parsed.period_start,\n periodEnd: parsed.period_end,\n } satisfies BillingInvoiceRecord;\n });\n }\n\n async upsert(\n subjectId: string,\n provider: string,\n providerInvoiceId: string,\n subscriptionId: string | null,\n status: \"draft\" | \"open\" | \"paid\" | \"void\" | \"uncollectible\",\n amountPaidMinor: number,\n amountDueMinor: number,\n currency: string,\n periodStart: string | null,\n periodEnd: string | null,\n metadata: Record<string, unknown>,\n providerUpdatedAt: string,\n ): Promise<void> {\n const rows = await this.query(\n `SELECT bursar.upsert_billing_invoice($1::uuid, $2, $3, $4::uuid, $5, $6, $7, $8, $9, $10, $11::jsonb, $12) AS id`,\n [\n subjectId,\n provider,\n providerInvoiceId,\n subscriptionId,\n status,\n amountDueMinor,\n amountPaidMinor,\n currency,\n periodStart,\n periodEnd,\n JSON.stringify(metadata),\n providerUpdatedAt,\n ],\n );\n requireResultField(rows, \"id\", postgresUuid, \"BillingInvoiceRepository.upsert\");\n }\n}\n"]}
@@ -1,26 +1,29 @@
1
- import { z } from "zod";
1
+ import Decimal from "decimal.js";
2
2
  import type { QueryFn } from "../../../shared/postgres-types.js";
3
- declare const BillingOfferRowSchema: z.ZodObject<{
4
- id: z.ZodOptional<z.ZodString>;
5
- plan_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
6
- offer_key: z.ZodOptional<z.ZodString>;
7
- plan: z.ZodOptional<z.ZodNullable<z.ZodString>>;
8
- interval: z.ZodOptional<z.ZodString>;
9
- interval_count: z.ZodOptional<z.ZodNumber>;
10
- grant_mode: z.ZodOptional<z.ZodString>;
11
- grant_credits: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
12
- grant_bucket: z.ZodOptional<z.ZodNullable<z.ZodString>>;
13
- grant_replace_prior: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString, z.ZodNumber]>, z.ZodTransform<boolean, string | number | boolean>>>>;
14
- }, z.core.$loose>;
15
- export type BillingOfferRow = z.infer<typeof BillingOfferRowSchema>;
3
+ interface BillingOfferRowBase {
4
+ id: string;
5
+ planId: string;
6
+ offerKey: string;
7
+ plan: string;
8
+ interval: "day" | "week" | "month" | "year";
9
+ intervalCount: number;
10
+ }
11
+ export type BillingOfferRow = BillingOfferRowBase & ({
12
+ grantCredits: null;
13
+ grantBucket: null;
14
+ grantReplacePrior: false;
15
+ } | {
16
+ grantCredits: Decimal;
17
+ grantBucket: string;
18
+ grantReplacePrior: boolean;
19
+ });
16
20
  /** Repository for billing offer resolution. */
17
21
  export declare class BillingOfferRepository {
18
- private query;
22
+ private readonly query;
19
23
  constructor(query: QueryFn);
20
- /** Resolve a billing offer by price ID and product ID. */
21
24
  resolveByPrice(provider: string, priceId: string | null, productId: string | null): Promise<BillingOfferRow | null>;
22
- /** Resolve a billing offer by provider lookup key. */
23
25
  resolveByLookup(provider: string, lookupKey: string): Promise<BillingOfferRow | null>;
26
+ private resolve;
24
27
  }
25
28
  export {};
26
29
  //# sourceMappingURL=offer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"offer.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/offer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAGjE,QAAA,MAAM,qBAAqB;;;;;;;;;;;iBAgBX,CAAC;AAEjB,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAEpE,+CAA+C;AAC/C,qBAAa,sBAAsB;IACrB,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAElC,0DAA0D;IACpD,cAAc,CAClB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,GAAG,IAAI,EACtB,SAAS,EAAE,MAAM,GAAG,IAAI,GACvB,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;IA+BlC,sDAAsD;IAChD,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;CA4B5F"}
1
+ {"version":3,"file":"offer.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/offer.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AAGjC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAgDjE,UAAU,mBAAmB;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,KAAK,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;IAC5C,aAAa,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,MAAM,eAAe,GAAG,mBAAmB,GAC/C,CACI;IACE,YAAY,EAAE,IAAI,CAAC;IACnB,WAAW,EAAE,IAAI,CAAC;IAClB,iBAAiB,EAAE,KAAK,CAAC;CAC1B,GACD;IACE,YAAY,EAAE,OAAO,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,EAAE,OAAO,CAAC;CAC5B,CACJ,CAAC;AAEJ,+CAA+C;AAC/C,qBAAa,sBAAsB;IACrB,OAAO,CAAC,QAAQ,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAErC,cAAc,CAClB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,GAAG,IAAI,EACtB,SAAS,EAAE,MAAM,GAAG,IAAI,GACvB,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;IAK5B,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;YAI7E,OAAO;CAkGtB"}
@@ -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,EAAE,CAAC,QAAQ,EAAE;IACtC,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC/B,cAAc,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC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mB,EAAE,IAAI,CAAC,mBAAmB,KAAK,kBAAkB;aACrE,EACD,wCAAwC,CACzC;YACH,CAAC,CAAC,IAAI,CAAC;IACX,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport { pgBoolean, unwrapJsonb, safeParse } from \"../../../shared/postgres-validation.js\";\n\nconst BillingOfferRowSchema = z\n .object({\n id: z.string().optional(),\n plan_id: z.string().nullable().optional(),\n offer_key: z.string().optional(),\n plan: z.string().nullable().optional(),\n interval: z.string().optional(),\n interval_count: z.number().optional(),\n grant_mode: z.string().optional(),\n grant_credits: z\n .union([z.string(), z.number()] as const)\n .nullable()\n .optional(),\n grant_bucket: z.string().nullable().optional(),\n grant_replace_prior: pgBoolean.nullable().optional(),\n })\n .passthrough();\n\nexport type BillingOfferRow = z.infer<typeof BillingOfferRowSchema>;\n\n/** Repository for billing offer resolution. */\nexport class BillingOfferRepository {\n constructor(private query: QueryFn) {}\n\n /** Resolve a billing offer by price ID and product ID. */\n async resolveByPrice(\n provider: string,\n priceId: string | null,\n productId: string | null,\n ): Promise<BillingOfferRow | null> {\n const rows = await this.query(\"SELECT * FROM bursar.resolve_catalog_offer($1, $2, $3)\", [\n provider,\n priceId != null ? \"price_id\" : \"product_id\",\n priceId ?? productId,\n ]);\n const data = unwrapJsonb(rows);\n const planRows = (await this.query(\"SELECT * FROM bursar.resolve_catalog_plan($1, $2, $3)\", [\n provider,\n priceId != null ? \"price_id\" : \"product_id\",\n priceId ?? productId,\n ])) as Array<Record<string, unknown>>;\n return data && data.offer_key != null\n ? safeParse(\n BillingOfferRowSchema,\n {\n ...data,\n plan_id: planRows[0]?.id,\n plan: data.plan_key,\n interval: data.billing_unit,\n interval_count: data.billing_count,\n grant_mode: data.cycle_grant_amount == null ? undefined : \"cycle_grant\",\n grant_credits: data.cycle_grant_amount,\n grant_bucket: data.cycle_grant_bucket_key,\n grant_replace_prior: data.cycle_grant_renewal === \"replace_previous\",\n },\n \"BillingOfferRepository.resolveByPrice\",\n )\n : null;\n }\n\n /** Resolve a billing offer by provider lookup key. */\n async resolveByLookup(provider: string, lookupKey: string): Promise<BillingOfferRow | null> {\n const rows = await this.query(\n \"SELECT * FROM bursar.resolve_catalog_offer($1, 'external_id', $2)\",\n [provider, lookupKey],\n );\n const data = unwrapJsonb(rows);\n const planRows = (await this.query(\n \"SELECT * FROM bursar.resolve_catalog_plan($1, 'external_id', $2)\",\n [provider, lookupKey],\n )) as Array<Record<string, unknown>>;\n return data && data.offer_key != null\n ? safeParse(\n BillingOfferRowSchema,\n {\n ...data,\n plan_id: planRows[0]?.id,\n plan: data.plan_key,\n interval: data.billing_unit,\n interval_count: data.billing_count,\n grant_mode: data.cycle_grant_amount == null ? undefined : \"cycle_grant\",\n grant_credits: data.cycle_grant_amount,\n grant_bucket: data.cycle_grant_bucket_key,\n grant_replace_prior: data.cycle_grant_renewal === \"replace_previous\",\n },\n \"BillingOfferRepository.resolveByLookup\",\n )\n : null;\n }\n}\n"]}
1
+ {"version":3,"file":"offer.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/offer.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,wCAAwC,CAAC;AAE9F,MAAM,qBAAqB,GAAG,CAAC;KAC5B,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC;KACtD,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC;KACxC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,C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EAAE,IAAI;gBAClB,WAAW,EAAE,IAAI;gBACjB,iBAAiB,EAAE,KAAK;aACzB,CAAC;QACJ,CAAC;QACD,IAAI,KAAK,CAAC,sBAAsB,KAAK,IAAI,IAAI,KAAK,CAAC,mBAAmB,KAAK,IAAI,EAAE,CAAC;YAChF,MAAM,IAAI,UAAU,CAAC,GAAG,OAAO,gDAAgD,EAAE;gBAC/E,OAAO,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,EAAE,iBAAiB,EAAE,KAAK,CAAC,mBAAmB,EAAE;aAC7E,CAAC,CAAC;QACL,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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