@zonastery/bursar 2.0.6 → 2.2.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 (379) hide show
  1. package/README.md +33 -4
  2. package/dist/billing/auto-recharge-port.d.ts +11 -0
  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.map +1 -1
  6. package/dist/billing/auto-recharge-service.js +53 -26
  7. package/dist/billing/auto-recharge-service.js.map +1 -1
  8. package/dist/billing/billing-service.d.ts +38 -3
  9. package/dist/billing/billing-service.d.ts.map +1 -1
  10. package/dist/billing/billing-service.js +51 -7
  11. package/dist/billing/billing-service.js.map +1 -1
  12. package/dist/billing/billing-store.d.ts +34 -9
  13. package/dist/billing/billing-store.d.ts.map +1 -1
  14. package/dist/billing/billing-store.js +2 -0
  15. package/dist/billing/billing-store.js.map +1 -1
  16. package/dist/billing/contracts.d.ts +35 -3
  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 +1 -2
  20. package/dist/billing/event-handlers.d.ts.map +1 -1
  21. package/dist/billing/event-handlers.js +69 -29
  22. package/dist/billing/event-handlers.js.map +1 -1
  23. package/dist/billing/event-processor.d.ts +2 -2
  24. package/dist/billing/event-processor.d.ts.map +1 -1
  25. package/dist/billing/event-processor.js +82 -19
  26. package/dist/billing/event-processor.js.map +1 -1
  27. package/dist/billing/financial-event-handlers.d.ts +2 -0
  28. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  29. package/dist/billing/financial-event-handlers.js +168 -44
  30. package/dist/billing/financial-event-handlers.js.map +1 -1
  31. package/dist/billing/index.d.ts +1 -1
  32. package/dist/billing/index.d.ts.map +1 -1
  33. package/dist/billing/index.js.map +1 -1
  34. package/dist/billing/management.d.ts +16 -3
  35. package/dist/billing/management.d.ts.map +1 -1
  36. package/dist/billing/management.js +11 -2
  37. package/dist/billing/management.js.map +1 -1
  38. package/dist/billing/postgres/repositories/auto-recharge.d.ts +13 -1
  39. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  40. package/dist/billing/postgres/repositories/auto-recharge.js +71 -12
  41. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  42. package/dist/billing/postgres/repositories/invoice.d.ts +3 -2
  43. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  44. package/dist/billing/postgres/repositories/invoice.js +33 -3
  45. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  46. package/dist/billing/postgres/repositories/offer.d.ts +5 -1
  47. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  48. package/dist/billing/postgres/repositories/offer.js +7 -10
  49. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  50. package/dist/billing/postgres/repositories/payment.d.ts +6 -1
  51. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  52. package/dist/billing/postgres/repositories/payment.js +25 -16
  53. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  54. package/dist/billing/postgres/repositories/subscription-change.d.ts +1 -0
  55. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -1
  56. package/dist/billing/postgres/repositories/subscription-change.js +25 -4
  57. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
  58. package/dist/billing/postgres/repositories/subscription.d.ts +3 -2
  59. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  60. package/dist/billing/postgres/repositories/subscription.js +44 -48
  61. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  62. package/dist/billing/postgres/repositories/topup.d.ts +6 -1
  63. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  64. package/dist/billing/postgres/repositories/topup.js +27 -10
  65. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  66. package/dist/billing/postgres/store.d.ts +46 -34
  67. package/dist/billing/postgres/store.d.ts.map +1 -1
  68. package/dist/billing/postgres/store.js +152 -126
  69. package/dist/billing/postgres/store.js.map +1 -1
  70. package/dist/billing/service-types.d.ts +0 -1
  71. package/dist/billing/service-types.d.ts.map +1 -1
  72. package/dist/billing/service-types.js.map +1 -1
  73. package/dist/billing/types/auto-recharge.d.ts +2 -0
  74. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  75. package/dist/billing/types/auto-recharge.js.map +1 -1
  76. package/dist/billing/types/catalog.d.ts +1 -0
  77. package/dist/billing/types/catalog.d.ts.map +1 -1
  78. package/dist/billing/types/catalog.js.map +1 -1
  79. package/dist/billing/types/documents.d.ts +15 -1
  80. package/dist/billing/types/documents.d.ts.map +1 -1
  81. package/dist/billing/types/documents.js.map +1 -1
  82. package/dist/billing/types/events.d.ts +2 -0
  83. package/dist/billing/types/events.d.ts.map +1 -1
  84. package/dist/billing/types/events.js +15 -0
  85. package/dist/billing/types/events.js.map +1 -1
  86. package/dist/billing/types/subscriptions.d.ts +12 -0
  87. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  88. package/dist/billing/types/subscriptions.js.map +1 -1
  89. package/dist/breakdown.d.ts +2 -24
  90. package/dist/breakdown.d.ts.map +1 -1
  91. package/dist/breakdown.js +1 -29
  92. package/dist/breakdown.js.map +1 -1
  93. package/dist/bursar.d.ts +13 -21
  94. package/dist/bursar.d.ts.map +1 -1
  95. package/dist/bursar.js +44 -50
  96. package/dist/bursar.js.map +1 -1
  97. package/dist/catalog.d.ts +21 -2
  98. package/dist/catalog.d.ts.map +1 -1
  99. package/dist/catalog.js +27 -4
  100. package/dist/catalog.js.map +1 -1
  101. package/dist/cli.d.ts +3 -0
  102. package/dist/cli.d.ts.map +1 -0
  103. package/dist/cli.js +147 -0
  104. package/dist/cli.js.map +1 -0
  105. package/dist/commerce/plan-change.d.ts +3 -3
  106. package/dist/commerce/plan-change.d.ts.map +1 -1
  107. package/dist/commerce/plan-change.js +14 -7
  108. package/dist/commerce/plan-change.js.map +1 -1
  109. package/dist/commerce/provider-registry.d.ts.map +1 -1
  110. package/dist/commerce/provider-registry.js +8 -2
  111. package/dist/commerce/provider-registry.js.map +1 -1
  112. package/dist/commerce/service.d.ts +2 -0
  113. package/dist/commerce/service.d.ts.map +1 -1
  114. package/dist/commerce/service.js +330 -76
  115. package/dist/commerce/service.js.map +1 -1
  116. package/dist/commerce/types.d.ts +12 -3
  117. package/dist/commerce/types.d.ts.map +1 -1
  118. package/dist/commerce/types.js.map +1 -1
  119. package/dist/config/availability.d.ts +4 -0
  120. package/dist/config/availability.d.ts.map +1 -0
  121. package/dist/config/availability.js +10 -0
  122. package/dist/config/availability.js.map +1 -0
  123. package/dist/config/normalize.d.ts +7 -0
  124. package/dist/config/normalize.d.ts.map +1 -0
  125. package/dist/config/normalize.js +119 -0
  126. package/dist/config/normalize.js.map +1 -0
  127. package/dist/config/parse-access.d.ts.map +1 -1
  128. package/dist/config/parse-access.js +4 -1
  129. package/dist/config/parse-access.js.map +1 -1
  130. package/dist/config/parse-commerce.d.ts +5 -1
  131. package/dist/config/parse-commerce.d.ts.map +1 -1
  132. package/dist/config/parse-commerce.js +79 -22
  133. package/dist/config/parse-commerce.js.map +1 -1
  134. package/dist/config/parse-credits.d.ts.map +1 -1
  135. package/dist/config/parse-credits.js +10 -7
  136. package/dist/config/parse-credits.js.map +1 -1
  137. package/dist/config/parse-plans.d.ts.map +1 -1
  138. package/dist/config/parse-plans.js +31 -15
  139. package/dist/config/parse-plans.js.map +1 -1
  140. package/dist/config/parse-pricing.d.ts.map +1 -1
  141. package/dist/config/parse-pricing.js +42 -27
  142. package/dist/config/parse-pricing.js.map +1 -1
  143. package/dist/config/parse-utils.d.ts +4 -0
  144. package/dist/config/parse-utils.d.ts.map +1 -1
  145. package/dist/config/parse-utils.js +26 -1
  146. package/dist/config/parse-utils.js.map +1 -1
  147. package/dist/config/types.d.ts +8 -4
  148. package/dist/config/types.d.ts.map +1 -1
  149. package/dist/config/types.js.map +1 -1
  150. package/dist/config.d.ts +5 -4
  151. package/dist/config.d.ts.map +1 -1
  152. package/dist/config.js +118 -70
  153. package/dist/config.js.map +1 -1
  154. package/dist/credits/amount.d.ts.map +1 -1
  155. package/dist/credits/amount.js +5 -4
  156. package/dist/credits/amount.js.map +1 -1
  157. package/dist/credits/catalog-runtime.d.ts +15 -2
  158. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  159. package/dist/credits/catalog-runtime.js +77 -21
  160. package/dist/credits/catalog-runtime.js.map +1 -1
  161. package/dist/credits/lease-workflow.d.ts +3 -1
  162. package/dist/credits/lease-workflow.d.ts.map +1 -1
  163. package/dist/credits/lease-workflow.js +47 -38
  164. package/dist/credits/lease-workflow.js.map +1 -1
  165. package/dist/credits/low-balance-monitor.d.ts +2 -7
  166. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  167. package/dist/credits/low-balance-monitor.js +6 -57
  168. package/dist/credits/low-balance-monitor.js.map +1 -1
  169. package/dist/credits/postgres/repositories/analytics.d.ts +3 -3
  170. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  171. package/dist/credits/postgres/repositories/analytics.js +25 -7
  172. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  173. package/dist/credits/postgres/repositories/balance.d.ts +28 -0
  174. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  175. package/dist/credits/postgres/repositories/balance.js +33 -14
  176. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  177. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
  178. package/dist/credits/postgres/repositories/bucket.js +2 -2
  179. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  180. package/dist/credits/postgres/repositories/catalog.d.ts +2 -2
  181. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
  182. package/dist/credits/postgres/repositories/catalog.js +2 -12
  183. package/dist/credits/postgres/repositories/catalog.js.map +1 -1
  184. package/dist/credits/postgres/repositories/deduction.d.ts +2 -0
  185. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  186. package/dist/credits/postgres/repositories/deduction.js +9 -2
  187. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  188. package/dist/credits/postgres/repositories/lease.d.ts +3 -0
  189. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  190. package/dist/credits/postgres/repositories/lease.js +46 -12
  191. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  192. package/dist/credits/postgres/repositories/plan.d.ts +6 -1
  193. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
  194. package/dist/credits/postgres/repositories/plan.js +13 -3
  195. package/dist/credits/postgres/repositories/plan.js.map +1 -1
  196. package/dist/credits/postgres/repositories/team.d.ts +1 -1
  197. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  198. package/dist/credits/postgres/repositories/team.js +9 -5
  199. package/dist/credits/postgres/repositories/team.js.map +1 -1
  200. package/dist/credits/postgres/store.d.ts +30 -20
  201. package/dist/credits/postgres/store.d.ts.map +1 -1
  202. package/dist/credits/postgres/store.js +335 -251
  203. package/dist/credits/postgres/store.js.map +1 -1
  204. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  205. package/dist/credits/postgres/value-mappers.js +4 -4
  206. package/dist/credits/postgres/value-mappers.js.map +1 -1
  207. package/dist/credits/rated-wire.d.ts +7 -0
  208. package/dist/credits/rated-wire.d.ts.map +1 -0
  209. package/dist/credits/rated-wire.js +70 -0
  210. package/dist/credits/rated-wire.js.map +1 -0
  211. package/dist/credits/service-errors.d.ts.map +1 -1
  212. package/dist/credits/service-errors.js +8 -1
  213. package/dist/credits/service-errors.js.map +1 -1
  214. package/dist/credits/service-types.d.ts +5 -7
  215. package/dist/credits/service-types.d.ts.map +1 -1
  216. package/dist/credits/service-types.js.map +1 -1
  217. package/dist/credits/service.d.ts +12 -9
  218. package/dist/credits/service.d.ts.map +1 -1
  219. package/dist/credits/service.js +161 -138
  220. package/dist/credits/service.js.map +1 -1
  221. package/dist/credits/store.d.ts +11 -3
  222. package/dist/credits/store.d.ts.map +1 -1
  223. package/dist/credits/store.js +9 -0
  224. package/dist/credits/store.js.map +1 -1
  225. package/dist/credits/types/account.d.ts +9 -1
  226. package/dist/credits/types/account.d.ts.map +1 -1
  227. package/dist/credits/types/account.js.map +1 -1
  228. package/dist/credits/types/admission.d.ts +1 -0
  229. package/dist/credits/types/admission.d.ts.map +1 -1
  230. package/dist/credits/types/admission.js.map +1 -1
  231. package/dist/credits/types/catalog.d.ts +1 -0
  232. package/dist/credits/types/catalog.d.ts.map +1 -1
  233. package/dist/credits/types/catalog.js.map +1 -1
  234. package/dist/credits/types/grants.d.ts +12 -0
  235. package/dist/credits/types/grants.d.ts.map +1 -1
  236. package/dist/credits/types/grants.js.map +1 -1
  237. package/dist/credits/types/ledger.d.ts +13 -0
  238. package/dist/credits/types/ledger.d.ts.map +1 -1
  239. package/dist/credits/types/ledger.js.map +1 -1
  240. package/dist/credits/types/quotas.d.ts +2 -1
  241. package/dist/credits/types/quotas.d.ts.map +1 -1
  242. package/dist/credits/types/quotas.js.map +1 -1
  243. package/dist/engine.d.ts +4 -1
  244. package/dist/engine.d.ts.map +1 -1
  245. package/dist/engine.js +59 -36
  246. package/dist/engine.js.map +1 -1
  247. package/dist/errors.d.ts +12 -1
  248. package/dist/errors.d.ts.map +1 -1
  249. package/dist/errors.js +13 -0
  250. package/dist/errors.js.map +1 -1
  251. package/dist/expr/evaluator.d.ts.map +1 -1
  252. package/dist/expr/evaluator.js +29 -9
  253. package/dist/expr/evaluator.js.map +1 -1
  254. package/dist/expr/language.js +1 -1
  255. package/dist/expr/language.js.map +1 -1
  256. package/dist/expr.d.ts.map +1 -1
  257. package/dist/expr.js +5 -6
  258. package/dist/expr.js.map +1 -1
  259. package/dist/generated/pricing-config.schema.json +272 -228
  260. package/dist/generated/pricing-config.types.d.ts +128 -79
  261. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  262. package/dist/generated/pricing-config.types.js.map +1 -1
  263. package/dist/index.d.ts +8 -6
  264. package/dist/index.d.ts.map +1 -1
  265. package/dist/index.js +4 -2
  266. package/dist/index.js.map +1 -1
  267. package/dist/load-config-file.d.ts +5 -1
  268. package/dist/load-config-file.d.ts.map +1 -1
  269. package/dist/load-config-file.js +56 -17
  270. package/dist/load-config-file.js.map +1 -1
  271. package/dist/metrics.d.ts +1 -1
  272. package/dist/metrics.d.ts.map +1 -1
  273. package/dist/metrics.js.map +1 -1
  274. package/dist/node.d.ts +2 -2
  275. package/dist/node.d.ts.map +1 -1
  276. package/dist/node.js +1 -1
  277. package/dist/node.js.map +1 -1
  278. package/dist/pricing-decimal.d.ts +7 -0
  279. package/dist/pricing-decimal.d.ts.map +1 -0
  280. package/dist/pricing-decimal.js +43 -0
  281. package/dist/pricing-decimal.js.map +1 -0
  282. package/dist/providers/dodo/better-auth-core.d.ts +1 -1
  283. package/dist/providers/dodo/better-auth-core.d.ts.map +1 -1
  284. package/dist/providers/dodo/better-auth-core.js +2 -2
  285. package/dist/providers/dodo/better-auth-core.js.map +1 -1
  286. package/dist/providers/dodo/better-auth.d.ts.map +1 -1
  287. package/dist/providers/dodo/better-auth.js +16 -2
  288. package/dist/providers/dodo/better-auth.js.map +1 -1
  289. package/dist/providers/dodo/event-mapper.d.ts +1 -1
  290. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  291. package/dist/providers/dodo/event-mapper.js +124 -18
  292. package/dist/providers/dodo/event-mapper.js.map +1 -1
  293. package/dist/providers/dodo/nextjs-core.d.ts +1 -1
  294. package/dist/providers/dodo/nextjs-core.d.ts.map +1 -1
  295. package/dist/providers/dodo/nextjs-core.js +2 -2
  296. package/dist/providers/dodo/nextjs-core.js.map +1 -1
  297. package/dist/providers/dodo/nextjs.d.ts.map +1 -1
  298. package/dist/providers/dodo/nextjs.js +16 -6
  299. package/dist/providers/dodo/nextjs.js.map +1 -1
  300. package/dist/providers/dodo/provider.d.ts +5 -2
  301. package/dist/providers/dodo/provider.d.ts.map +1 -1
  302. package/dist/providers/dodo/provider.js +46 -7
  303. package/dist/providers/dodo/provider.js.map +1 -1
  304. package/dist/providers/dodo/verified-payment-payload.d.ts +6 -0
  305. package/dist/providers/dodo/verified-payment-payload.d.ts.map +1 -0
  306. package/dist/providers/dodo/verified-payment-payload.js +42 -0
  307. package/dist/providers/dodo/verified-payment-payload.js.map +1 -0
  308. package/dist/providers/index.d.ts +1 -1
  309. package/dist/providers/index.d.ts.map +1 -1
  310. package/dist/providers/index.js.map +1 -1
  311. package/dist/providers/mock/provider.d.ts +4 -1
  312. package/dist/providers/mock/provider.d.ts.map +1 -1
  313. package/dist/providers/mock/provider.js +3 -1
  314. package/dist/providers/mock/provider.js.map +1 -1
  315. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  316. package/dist/providers/stripe/event-mapper.js +51 -24
  317. package/dist/providers/stripe/event-mapper.js.map +1 -1
  318. package/dist/providers/stripe/provider.d.ts +4 -1
  319. package/dist/providers/stripe/provider.d.ts.map +1 -1
  320. package/dist/providers/stripe/provider.js +118 -34
  321. package/dist/providers/stripe/provider.js.map +1 -1
  322. package/dist/providers/types.d.ts +16 -2
  323. package/dist/providers/types.d.ts.map +1 -1
  324. package/dist/providers/types.js +9 -0
  325. package/dist/providers/types.js.map +1 -1
  326. package/dist/shared/postgres-client.d.ts +5 -0
  327. package/dist/shared/postgres-client.d.ts.map +1 -1
  328. package/dist/shared/postgres-client.js +72 -11
  329. package/dist/shared/postgres-client.js.map +1 -1
  330. package/dist/shared/postgres-errors.d.ts.map +1 -1
  331. package/dist/shared/postgres-errors.js +6 -0
  332. package/dist/shared/postgres-errors.js.map +1 -1
  333. package/dist/shared/provider-rejection.d.ts +3 -0
  334. package/dist/shared/provider-rejection.d.ts.map +1 -0
  335. package/dist/shared/provider-rejection.js +17 -0
  336. package/dist/shared/provider-rejection.js.map +1 -0
  337. package/dist/shared/timestamp.d.ts +5 -0
  338. package/dist/shared/timestamp.d.ts.map +1 -0
  339. package/dist/shared/timestamp.js +21 -0
  340. package/dist/shared/timestamp.js.map +1 -0
  341. package/dist/starter.yaml +17 -0
  342. package/dist/storage/adapters/clickhouse.d.ts +1 -1
  343. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  344. package/dist/storage/adapters/clickhouse.js +42 -37
  345. package/dist/storage/adapters/clickhouse.js.map +1 -1
  346. package/dist/storage/adapters/s3.d.ts +5 -0
  347. package/dist/storage/adapters/s3.d.ts.map +1 -1
  348. package/dist/storage/adapters/s3.js +46 -14
  349. package/dist/storage/adapters/s3.js.map +1 -1
  350. package/dist/storage/diagnostics.d.ts +3 -7
  351. package/dist/storage/diagnostics.d.ts.map +1 -1
  352. package/dist/storage/diagnostics.js +6 -15
  353. package/dist/storage/diagnostics.js.map +1 -1
  354. package/dist/storage/outbox-worker.d.ts.map +1 -1
  355. package/dist/storage/outbox-worker.js +4 -3
  356. package/dist/storage/outbox-worker.js.map +1 -1
  357. package/dist/storage/ports.d.ts +8 -0
  358. package/dist/storage/ports.d.ts.map +1 -1
  359. package/dist/storage/ports.js.map +1 -1
  360. package/dist/storage/postgres-repository.d.ts +1 -3
  361. package/dist/storage/postgres-repository.d.ts.map +1 -1
  362. package/dist/storage/postgres-repository.js +34 -12
  363. package/dist/storage/postgres-repository.js.map +1 -1
  364. package/dist/storage/raw-json.d.ts +10 -0
  365. package/dist/storage/raw-json.d.ts.map +1 -0
  366. package/dist/storage/raw-json.js +19 -0
  367. package/dist/storage/raw-json.js.map +1 -0
  368. package/dist/storage/runtime.d.ts +15 -10
  369. package/dist/storage/runtime.d.ts.map +1 -1
  370. package/dist/storage/runtime.js +97 -68
  371. package/dist/storage/runtime.js.map +1 -1
  372. package/dist/telemetry/index.d.ts +1 -1
  373. package/dist/telemetry/index.js +1 -1
  374. package/dist/telemetry/index.js.map +1 -1
  375. package/package.json +78 -71
  376. package/dist/credits/queries.d.ts +0 -33
  377. package/dist/credits/queries.d.ts.map +0 -1
  378. package/dist/credits/queries.js +0 -71
  379. package/dist/credits/queries.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"auto-recharge.js","sourceRoot":"","sources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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 { JsonObject, PostgresRow } from \"../../../shared/json.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.json()),\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\ntype AttemptTransitionPath = readonly BillingAutoRechargeAttemptState[];\n\nfunction attemptTransitions(\n entries: ReadonlyArray<readonly [BillingAutoRechargeAttemptState, AttemptTransitionPath]>,\n): ReadonlyMap<BillingAutoRechargeAttemptState, AttemptTransitionPath> {\n return new Map(entries);\n}\n\nconst ATTEMPT_TRANSITION_PATHS = new Map<\n BillingAutoRechargeAttemptState,\n ReadonlyMap<BillingAutoRechargeAttemptState, AttemptTransitionPath>\n>([\n [\n \"claimed\",\n attemptTransitions([\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 ],\n [\n \"submitted\",\n attemptTransitions([\n [\"submitted\", []],\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"processing\", \"succeeded\"]],\n [\"failed\", [\"processing\", \"failed\"]],\n [\"unknown\", [\"processing\", \"unknown\"]],\n [\"action_required\", [\"action_required\"]],\n ]),\n ],\n [\n \"processing\",\n attemptTransitions([\n [\"processing\", []],\n [\"succeeded\", [\"succeeded\"]],\n [\"failed\", [\"failed\"]],\n [\"unknown\", [\"unknown\"]],\n [\"action_required\", [\"action_required\"]],\n ]),\n ],\n [\n \"unknown\",\n attemptTransitions([\n [\"unknown\", []],\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"succeeded\"]],\n [\"failed\", [\"failed\"]],\n [\"action_required\", [\"action_required\"]],\n ]),\n ],\n [\n \"action_required\",\n attemptTransitions([\n [\"action_required\", []],\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"succeeded\"]],\n [\"failed\", [\"failed\"]],\n ]),\n ],\n]);\n\nfunction projectProfile(row: PostgresRow) {\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: PostgresRow) {\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: PostgresRow): 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: PostgresRow): 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?: JsonObject;\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 path = ATTEMPT_TRANSITION_PATHS.get(current)?.get(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?: JsonObject;\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
+ {"version":3,"file":"auto-recharge.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/auto-recharge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAQhD,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAClF,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,sBAAsB,GAAG,CAAC;KAC7B,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;KAC9C,SAAS,CAAC,MAAM,CAAC;KACjB,IAAI,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC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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 { Decimal } from \"decimal.js\";\nimport { PricingDecimal } from \"../../../pricing-decimal.js\";\nimport { z } from \"zod\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { JsonObject, PostgresRow } from \"../../../shared/json.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 PricingDecimal(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 topup_key: z.string().min(1).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({\n code: z.ZodIssueCode.custom,\n message: \"enabled and state are inconsistent\",\n });\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.json()),\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\ntype AttemptTransitionPath = readonly BillingAutoRechargeAttemptState[];\n\nfunction attemptTransitions(\n entries: ReadonlyArray<readonly [BillingAutoRechargeAttemptState, AttemptTransitionPath]>,\n): ReadonlyMap<BillingAutoRechargeAttemptState, AttemptTransitionPath> {\n return new Map(entries);\n}\n\nconst ATTEMPT_TRANSITION_PATHS = new Map<\n BillingAutoRechargeAttemptState,\n ReadonlyMap<BillingAutoRechargeAttemptState, AttemptTransitionPath>\n>([\n [\n \"claimed\",\n attemptTransitions([\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 ],\n [\n \"submitted\",\n attemptTransitions([\n [\"submitted\", [\"submitted\"]],\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"processing\", \"succeeded\"]],\n [\"failed\", [\"processing\", \"failed\"]],\n [\"unknown\", [\"processing\", \"unknown\"]],\n [\"action_required\", [\"action_required\"]],\n ]),\n ],\n [\n \"processing\",\n attemptTransitions([\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"succeeded\"]],\n [\"failed\", [\"failed\"]],\n [\"unknown\", [\"unknown\"]],\n [\"action_required\", [\"action_required\"]],\n ]),\n ],\n [\n \"unknown\",\n attemptTransitions([\n [\"unknown\", [\"unknown\"]],\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"succeeded\"]],\n [\"failed\", [\"failed\"]],\n [\"action_required\", [\"action_required\"]],\n ]),\n ],\n [\n \"action_required\",\n attemptTransitions([\n [\"action_required\", [\"action_required\"]],\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"succeeded\"]],\n [\"failed\", [\"failed\"]],\n ]),\n ],\n [\"succeeded\", attemptTransitions([[\"succeeded\", [\"succeeded\"]]])],\n [\n \"failed\",\n attemptTransitions([\n [\"failed\", [\"failed\"]],\n [\"succeeded\", [\"succeeded\"]],\n ]),\n ],\n]);\n\nfunction projectProfile(row: PostgresRow) {\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 topup_key: row.topup_key ?? null,\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: PostgresRow) {\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: PostgresRow): 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 topupKey: parsed.topup_key,\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: PostgresRow): 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 resumeProfile(profile: BillingAutoRechargeProfile): Promise<boolean> {\n const rows = await this.query(\n \"SELECT bursar.resume_auto_recharge_profile($1::uuid, $2, $3::uuid, $4, $5) AS updated\",\n [\n profile.userId,\n profile.provider,\n profile.topupId,\n profile.quantity,\n profile.threshold.toString(),\n ],\n );\n return requireResultField(\n rows,\n \"updated\",\n pgBoolean,\n \"BillingAutoRechargeRepository.resumeProfile\",\n );\n }\n\n async upsertProfile(\n profile: BillingAutoRechargeProfile,\n options: { resetCooldown?: boolean } = {},\n ): Promise<void> {\n // Keep the exported compatibility option on the same resume transition.\n if (options.resetCooldown) {\n if (!(await this.resumeProfile(profile)))\n throw new StoreError(`auto-recharge profile update rejected: ${profile.userId}`);\n return;\n }\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\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 ],\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 expectedProductId: string;\n expectedQuantity: number;\n expectedTopupKey: string;\n }): Promise<BillingAutoRechargeAttempt | null> {\n const rows = await this.query(\n \"SELECT * FROM bursar.claim_auto_recharge_attempt($1::uuid, $2, $3, $4, $5)\",\n [\n input.userId,\n input.idempotencyKey,\n input.expectedProductId,\n input.expectedQuantity,\n input.expectedTopupKey,\n ],\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?: JsonObject;\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 path = ATTEMPT_TRANSITION_PATHS.get(current)?.get(input.state);\n if (!path) {\n throw new StoreError(`auto-recharge attempt transition rejected: ${input.id}`, {\n details: {\n attemptId: input.id,\n currentState: current,\n requestedState: input.state,\n },\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?: JsonObject;\n }): Promise<void> {\n return this.advanceAttempt(input);\n }\n\n async updateAttemptByProviderPayment(input: {\n provider: string;\n providerPaymentId: string;\n expectedAttemptId?: string;\n expectedUserId?: string;\n state: BillingAutoRechargeAttemptState;\n failureCode?: string | null;\n failureMessage?: string | null;\n }): Promise<boolean> {\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 false;\n const attempt = attemptFromRow(row);\n if (\n (input.expectedAttemptId && attempt.id !== input.expectedAttemptId) ||\n (input.expectedUserId && attempt.userId !== input.expectedUserId)\n )\n return false;\n // A delayed failure cannot undo a settled payment or rearm its profile.\n if (attempt.state === \"succeeded\" && input.state === \"failed\") return true;\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 return true;\n }\n\n async operationalWindow(userId: string): Promise<{\n maxRecharges: number;\n windowStart: string;\n windowEnd: string;\n count: number;\n } | null> {\n const rows = await this.query(\n \"SELECT * FROM bursar.get_auto_recharge_operational_window($1::uuid)\",\n [userId],\n );\n const row = optionalRecordRow(rows, \"BillingAutoRechargeRepository.operationalWindow\");\n if (!row) return null;\n return {\n maxRecharges: safeParse(positiveInteger, row.max_recharges, \"auto-recharge max\"),\n windowStart: safeParse(timestamp, row.window_start, \"auto-recharge window start\"),\n windowEnd: safeParse(timestamp, row.window_end, \"auto-recharge window end\"),\n count: safeParse(safeNonnegativeInteger, row.attempt_count, \"auto-recharge attempt count\"),\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,10 +1,11 @@
1
1
  import type { QueryFn } from "../../../shared/postgres-types.js";
2
2
  import type { JsonObject } from "../../../shared/json.js";
3
- import type { BillingInvoiceRecord } from "../../types/index.js";
3
+ import type { BillingInvoicePage, ListBillingInvoicesOptions } from "../../types/index.js";
4
4
  export declare class BillingInvoiceRepository {
5
5
  private query;
6
6
  constructor(query: QueryFn);
7
- listForUser(userId: string): Promise<BillingInvoiceRecord[]>;
7
+ listForUser(userId: string, options?: ListBillingInvoicesOptions): Promise<BillingInvoicePage>;
8
+ hasForUser(userId: string, provider: string, providerInvoiceId: string): Promise<boolean>;
8
9
  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: JsonObject, providerUpdatedAt: string): Promise<void>;
9
10
  }
10
11
  //# sourceMappingURL=invoice.d.ts.map
@@ -1 +1 @@
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,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAgCjE,qBAAa,wBAAwB;IACvB,OAAO,CAAC,KAAK;IAAzB,YAAoB,KAAK,EAAE,OAAO,EAAI;IAEhC,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,EAAE,CAAC,CA4BjE;IAEK,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,UAAU,EACpB,iBAAiB,EAAE,MAAM,GACxB,OAAO,CAAC,IAAI,CAAC,CAmBf;CACF"}
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,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,KAAK,EACV,kBAAkB,EAElB,0BAA0B,EAC3B,MAAM,sBAAsB,CAAC;AAgC9B,qBAAa,wBAAwB;IACvB,OAAO,CAAC,KAAK;IAAzB,YAAoB,KAAK,EAAE,OAAO,EAAI;IAEhC,WAAW,CACf,MAAM,EAAE,MAAM,EACd,OAAO,GAAE,0BAA+B,GACvC,OAAO,CAAC,kBAAkB,CAAC,CA8D7B;IAEK,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAO9F;IAEK,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,UAAU,EACpB,iBAAiB,EAAE,MAAM,GACxB,OAAO,CAAC,IAAI,CAAC,CAmBf;CACF"}
@@ -28,9 +28,23 @@ export class BillingInvoiceRepository {
28
28
  constructor(query) {
29
29
  this.query = query;
30
30
  }
31
- async listForUser(userId) {
32
- const rows = await this.query(`SELECT * FROM bursar.list_billing_invoices($1::uuid)`, [userId]);
33
- return rows.map((row) => {
31
+ async listForUser(userId, options = {}) {
32
+ const pageSize = options.limit ?? 100;
33
+ if (!Number.isSafeInteger(pageSize) || pageSize < 1 || pageSize > 100) {
34
+ throw new TypeError("invoice limit must be an integer between 1 and 100");
35
+ }
36
+ const beforeSortAt = options.cursor
37
+ ? safeParse(z.string().datetime({ offset: true }), options.cursor.sortAt, "invoice cursor sortAt")
38
+ : null;
39
+ const beforeId = options.cursor
40
+ ? safeParse(postgresUuid, options.cursor.id, "invoice cursor id")
41
+ : null;
42
+ // Format the cursor in PostgreSQL: pg's Date conversion truncates
43
+ // microseconds and can otherwise skip invoices at the page boundary.
44
+ const rows = await this.query(`SELECT i.*, to_char(COALESCE(i.period_end, i.created_at) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS cursor_sort_at
45
+ FROM bursar.list_billing_invoices($1::uuid, $2::timestamptz, $3::uuid, $4) i
46
+ ORDER BY COALESCE(i.period_end, i.created_at) DESC, i.id DESC`, [userId, beforeSortAt, beforeId, pageSize + 1]);
47
+ const items = rows.slice(0, pageSize).map((row) => {
34
48
  const parsed = safeParse(InvoiceRowSchema, {
35
49
  provider: row.provider,
36
50
  provider_invoice_id: row.provider_invoice_id,
@@ -52,6 +66,22 @@ export class BillingInvoiceRepository {
52
66
  periodEnd: parsed.period_end,
53
67
  };
54
68
  });
69
+ const last = rows[pageSize - 1];
70
+ const nextCursor = rows.length > pageSize && last
71
+ ? {
72
+ sortAt: safeParse(z.string().datetime({ offset: true }), last.cursor_sort_at, "BillingInvoiceRepository.listForUser.cursor"),
73
+ id: safeParse(postgresUuid, last.id, "BillingInvoiceRepository.listForUser.id"),
74
+ }
75
+ : null;
76
+ return { items, nextCursor };
77
+ }
78
+ async hasForUser(userId, provider, providerInvoiceId) {
79
+ const rows = await this.query("SELECT bursar.has_billing_invoice($1::uuid, $2, $3) AS found", [
80
+ userId,
81
+ provider,
82
+ providerInvoiceId,
83
+ ]);
84
+ return requireResultField(rows, "found", z.boolean(), "BillingInvoiceRepository.hasForUser");
55
85
  }
56
86
  async upsert(subjectId, provider, providerInvoiceId, subscriptionId, status, amountPaidMinor, amountDueMinor, currency, periodStart, periodEnd, metadata, providerUpdatedAt) {
57
87
  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`, [
@@ -1 +1 @@
1
- {"version":3,"file":"invoice.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/invoice.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB,OAAO,EACL,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,cAAc,GAAG,CAAC;KACrB,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;KACzE,SAAS,CAAC,MAAM,CAAC;KACjB,MAAM,CAAC,MAAM,CAAC,aAAa,EAAE,2DAA2D,CAAC,CAAC;AAC7F,MAAM,iBAAiB,GAAG,CAAC;KACxB,KAAK,CAAC;IACL,CAAC,CAAC,IAAI,EAAE,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IAC1D,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;CACtC,CAAC;KACD,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;KAC3E,QAAQ,EAAE,CAAC;AAEd,MAAM,gBAAgB,GAAG,CAAC;KACvB,MAAM,CAAC;IACN,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3B,mBAAmB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,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,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,QAAoB,EACpB,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 { JsonObject } from \"../../../shared/json.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 const parsed = safeParse(\n InvoiceRowSchema,\n {\n provider: row.provider,\n provider_invoice_id: row.provider_invoice_id,\n status: row.status,\n amount_paid_minor: row.amount_paid_minor,\n amount_due_minor: row.amount_due_minor,\n currency: row.currency,\n period_start: row.period_start,\n period_end: row.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: JsonObject,\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\");\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YAAY,EAAE,IAAI,CAAC,EAAE,EAAE,yCAAyC,CAAC;aAChF;YACH,CAAC,CAAC,IAAI,CAAC;QACX,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC;IAC/B,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,MAAc,EAAE,QAAgB,EAAE,iBAAyB;QAC1E,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,8DAA8D,EAAE;YAC5F,MAAM;YACN,QAAQ;YACR,iBAAiB;SAClB,CAAC,CAAC;QACH,OAAO,kBAAkB,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,OAAO,EAAE,EAAE,qCAAqC,CAAC,CAAC;IAC/F,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,QAAoB,EACpB,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 { JsonObject } from \"../../../shared/json.js\";\nimport type {\n BillingInvoicePage,\n BillingInvoiceRecord,\n ListBillingInvoicesOptions,\n} 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(\n userId: string,\n options: ListBillingInvoicesOptions = {},\n ): Promise<BillingInvoicePage> {\n const pageSize = options.limit ?? 100;\n if (!Number.isSafeInteger(pageSize) || pageSize < 1 || pageSize > 100) {\n throw new TypeError(\"invoice limit must be an integer between 1 and 100\");\n }\n const beforeSortAt = options.cursor\n ? safeParse(\n z.string().datetime({ offset: true }),\n options.cursor.sortAt,\n \"invoice cursor sortAt\",\n )\n : null;\n const beforeId = options.cursor\n ? safeParse(postgresUuid, options.cursor.id, \"invoice cursor id\")\n : null;\n // Format the cursor in PostgreSQL: pg's Date conversion truncates\n // microseconds and can otherwise skip invoices at the page boundary.\n const rows = await this.query(\n `SELECT i.*, to_char(COALESCE(i.period_end, i.created_at) AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS cursor_sort_at\n FROM bursar.list_billing_invoices($1::uuid, $2::timestamptz, $3::uuid, $4) i\n ORDER BY COALESCE(i.period_end, i.created_at) DESC, i.id DESC`,\n [userId, beforeSortAt, beforeId, pageSize + 1],\n );\n const items = rows.slice(0, pageSize).map((row) => {\n const parsed = safeParse(\n InvoiceRowSchema,\n {\n provider: row.provider,\n provider_invoice_id: row.provider_invoice_id,\n status: row.status,\n amount_paid_minor: row.amount_paid_minor,\n amount_due_minor: row.amount_due_minor,\n currency: row.currency,\n period_start: row.period_start,\n period_end: row.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 const last = rows[pageSize - 1];\n const nextCursor =\n rows.length > pageSize && last\n ? {\n sortAt: safeParse(\n z.string().datetime({ offset: true }),\n last.cursor_sort_at,\n \"BillingInvoiceRepository.listForUser.cursor\",\n ),\n id: safeParse(postgresUuid, last.id, \"BillingInvoiceRepository.listForUser.id\"),\n }\n : null;\n return { items, nextCursor };\n }\n\n async hasForUser(userId: string, provider: string, providerInvoiceId: string): Promise<boolean> {\n const rows = await this.query(\"SELECT bursar.has_billing_invoice($1::uuid, $2, $3) AS found\", [\n userId,\n provider,\n providerInvoiceId,\n ]);\n return requireResultField(rows, \"found\", z.boolean(), \"BillingInvoiceRepository.hasForUser\");\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: JsonObject,\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"]}
@@ -21,7 +21,11 @@ export type BillingOfferRow = BillingOfferRowBase & ({
21
21
  export declare class BillingOfferRepository {
22
22
  private readonly query;
23
23
  constructor(query: QueryFn);
24
- resolveByPrice(provider: string, priceId: string | null, productId: string | null): Promise<BillingOfferRow | null>;
24
+ resolveByPrice(provider: string, priceId: string | null, productId: string | null, checkout?: {
25
+ accountId: string;
26
+ intentId: string;
27
+ lookupKey?: string | null;
28
+ }): Promise<BillingOfferRow | null>;
25
29
  resolveByLookup(provider: string, lookupKey: string): Promise<BillingOfferRow | null>;
26
30
  private resolve;
27
31
  }
@@ -1 +1 @@
1
- {"version":3,"file":"offer.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/offer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAGrC,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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,EAAE,MAAM,GAAG,IAAI,EACxB,QAAQ,CAAC,EAAE;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,GAC5E,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAUjC;IAEK,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAE1F;YAEa,OAAO;CAuGtB"}
@@ -1,10 +1,11 @@
1
+ import { PricingDecimal } from "../../../pricing-decimal.js";
1
2
  import { Decimal } from "decimal.js";
2
3
  import { z } from "zod";
3
4
  import { StoreError } from "../../../errors.js";
4
5
  import { postgresUuid, safeParse, unwrapJsonb } from "../../../shared/postgres-validation.js";
5
6
  const PositiveDecimalSchema = z
6
7
  .union([z.string(), z.number(), z.instanceof(Decimal)])
7
- .transform((value) => new Decimal(value))
8
+ .transform((value) => new PricingDecimal(value))
8
9
  .refine((value) => value.isFinite() && value.gt(0), "expected a finite positive decimal");
9
10
  const CatalogOfferRowSchema = z
10
11
  .object({
@@ -48,24 +49,20 @@ export class BillingOfferRepository {
48
49
  constructor(query) {
49
50
  this.query = query;
50
51
  }
51
- async resolveByPrice(provider, priceId, productId) {
52
- const lookupType = priceId !== null ? "price_id" : "product_id";
53
- return this.resolve(provider, lookupType, priceId ?? productId, "resolveByPrice");
52
+ async resolveByPrice(provider, priceId, productId, checkout) {
53
+ const lookupType = priceId !== null ? "price_id" : productId !== null ? "product_id" : "external_id";
54
+ return this.resolve(provider, lookupType, priceId ?? productId ?? checkout?.lookupKey ?? null, "resolveByPrice", checkout);
54
55
  }
55
56
  async resolveByLookup(provider, lookupKey) {
56
57
  return this.resolve(provider, "external_id", lookupKey, "resolveByLookup");
57
58
  }
58
- async resolve(provider, lookupType, lookupValue, operation) {
59
+ async resolve(provider, lookupType, lookupValue, operation, checkout) {
59
60
  if (!provider.trim())
60
61
  throw new TypeError("provider must not be empty");
61
62
  if (!lookupValue?.trim())
62
63
  return null;
63
64
  const context = `BillingOfferRepository.${operation}`;
64
- const rows = await this.query("SELECT * FROM bursar.resolve_catalog_offer($1, $2, $3)", [
65
- provider,
66
- lookupType,
67
- lookupValue,
68
- ]);
65
+ const rows = await this.query("SELECT * FROM bursar.resolve_catalog_offer($1, $2, $3, $4::uuid, $5::uuid)", [provider, lookupType, lookupValue, checkout?.accountId ?? null, checkout?.intentId ?? null]);
69
66
  if (rows.length > 1) {
70
67
  throw new StoreError(`${context}: expected at most one offer`, {
71
68
  details: { rowCount: rows.length },
@@ -1 +1 @@
1
- {"version":3,"file":"offer.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/offer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,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,CAAC,QAAQ,EAAE,IAAI,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,oCAAoC,CAAC,CAAC;AAE5F,MAAM,qBAAqB,GAAG,CAAC;KAC5B,MAAM,CAAC;IACN,EAAE,EAAE,YAAY;IAChB,mBAAmB,EAAE,YAAY;IACjC,SAAS,EAAE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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];\n if (rawContext === undefined) {\n throw new StoreError(\"BillingOfferRepository: catalog plan context is missing\", {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\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
+ {"version":3,"file":"offer.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/offer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,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,cAAc,CAAC,KAAK,CAAC,CAAC;KAC/C,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,EAAE,IAAI,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,oCAAoC,CAAC,CAAC;AAE5F,MAAM,qBAAqB,GAAG,CAAC;KAC5B,MAAM,CAAC;IACN,EAAE,EAAE,YAAY;IAChB,mBAAmB,EAAE,YAAY;IACjC,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC5B,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3B,YAAY,EAAE,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KAAK,IAAI,EAAE,CAAC;YACtC,OAAO;gBACL,GAAG,aAAa;gBAChB,YAAY,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 { PricingDecimal } from \"../../../pricing-decimal.js\";\nimport { 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 PricingDecimal(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 checkout?: { accountId: string; intentId: string; lookupKey?: string | null },\n ): Promise<BillingOfferRow | null> {\n const lookupType =\n priceId !== null ? \"price_id\" : productId !== null ? \"product_id\" : \"external_id\";\n return this.resolve(\n provider,\n lookupType,\n priceId ?? productId ?? checkout?.lookupKey ?? null,\n \"resolveByPrice\",\n checkout,\n );\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 checkout?: { accountId: string; intentId: string; lookupKey?: string | null },\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(\n \"SELECT * FROM bursar.resolve_catalog_offer($1, $2, $3, $4::uuid, $5::uuid)\",\n [provider, lookupType, lookupValue, checkout?.accountId ?? null, checkout?.intentId ?? null],\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];\n if (rawContext === undefined) {\n throw new StoreError(\"BillingOfferRepository: catalog plan context is missing\", {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\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,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import type { QueryFn } from "../../../shared/postgres-types.js";
3
+ import type { BillingPaymentUpsert } from "../../contracts.js";
3
4
  declare const BillingPaymentRowSchema: z.ZodObject<{
4
5
  id: z.ZodString;
5
6
  provider: z.ZodString;
@@ -15,8 +16,12 @@ declare const BillingPaymentRowSchema: z.ZodObject<{
15
16
  }>;
16
17
  status: z.ZodEnum<{
17
18
  canceled: "canceled";
19
+ disputed: "disputed";
18
20
  failed: "failed";
21
+ partially_refunded: "partially_refunded";
19
22
  pending: "pending";
23
+ refunded: "refunded";
24
+ requires_action: "requires_action";
20
25
  succeeded: "succeeded";
21
26
  }>;
22
27
  provider_updated_at: z.ZodUnion<readonly [z.ZodString, z.ZodDate]>;
@@ -27,7 +32,7 @@ export type ForRefundRow = BillingPaymentRow;
27
32
  export declare class BillingPaymentRepository {
28
33
  private query;
29
34
  constructor(query: QueryFn);
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>;
35
+ upsert(input: BillingPaymentUpsert): Promise<string>;
31
36
  getForRefund(provider: string, providerPaymentId: string): Promise<ForRefundRow | null>;
32
37
  getDirect(provider: string, providerPaymentId: string): Promise<BillingPaymentRow | null>;
33
38
  }
@@ -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;AAcjE,QAAA,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;;;kBAelB,CAAC;AACZ,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,uBAAuB,CAAC,CAAC;AACxE,MAAM,MAAM,YAAY,GAAG,iBAAiB,CAAC;AAuB7C,qBAAa,wBAAwB;IACvB,OAAO,CAAC,KAAK;IAAzB,YAAoB,KAAK,EAAE,OAAO,EAAI;IAChC,MAAM,CACV,QAAQ,EAAE,MAAM,EAChB,iBAAiB,EAAE,MAAM,EACzB,iBAAiB,EAAE,MAAM,GAAG,IAAI,EAChC,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,cAAc,GAAG,cAAc,EACxC,QAAQ,EAAE,MAAM,GAAG,IAAI,EACvB,MAAM,EAAE,SAAS,GAAG,WAAW,GAAG,QAAQ,GAAG,UAAU,EACvD,iBAAiB,EAAE,MAAM,GACxB,OAAO,CAAC,MAAM,CAAC,CAwBjB;IACK,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAO5F;IACK,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC,CAO9F;CACF"}
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;AAEjE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAa/D,QAAA,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;;kBAwBlB,CAAC;AACZ,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,uBAAuB,CAAC,CAAC;AACxE,MAAM,MAAM,YAAY,GAAG,iBAAiB,CAAC;AAuB7C,qBAAa,wBAAwB;IACvB,OAAO,CAAC,KAAK;IAAzB,YAAoB,KAAK,EAAE,OAAO,EAAI;IAChC,MAAM,CAAC,KAAK,EAAE,oBAAoB,GAAG,OAAO,CAAC,MAAM,CAAC,CA2BzD;IACK,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAO5F;IACK,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC,CAO9F;CACF"}
@@ -15,7 +15,16 @@ const BillingPaymentRowSchema = z
15
15
  tax_minor: PgSafeMinorUnitsSchema,
16
16
  currency: z.string().regex(/^[A-Z]{3}$/),
17
17
  purpose: z.enum(["subscription", "credit_topup"]),
18
- status: z.enum(["pending", "succeeded", "failed", "canceled"]),
18
+ status: z.enum([
19
+ "pending",
20
+ "requires_action",
21
+ "succeeded",
22
+ "failed",
23
+ "canceled",
24
+ "refunded",
25
+ "partially_refunded",
26
+ "disputed",
27
+ ]),
19
28
  provider_updated_at: z.union([z.string().datetime({ offset: true }), z.date()]),
20
29
  metadata: z.record(z.string(), z.json()),
21
30
  })
@@ -41,34 +50,34 @@ export class BillingPaymentRepository {
41
50
  constructor(query) {
42
51
  this.query = query;
43
52
  }
44
- async upsert(provider, providerPaymentId, providerInvoiceId, userId, amountMinor, taxMinor, currency, purpose, metadata, status, providerUpdatedAt) {
53
+ async upsert(input) {
54
+ const { userId, purpose } = input;
45
55
  if (!userId)
46
56
  throw new TypeError("billing payment requires a subject");
47
57
  if (purpose !== "subscription" && purpose !== "credit_topup") {
48
58
  throw new TypeError("billing payment requires a known purpose");
49
59
  }
50
60
  const rows = await this.query(`SELECT bursar.upsert_billing_payment(
51
- $1::uuid,$2,$3,$4,$5,$6,$7,$8::bursar.billing_payment_status,$9,$10,$11::jsonb
61
+ $1::uuid,$2,$3,$4,$5,$6,$7,$8::bursar.billing_payment_status,$9,$10,$11::jsonb,$12::uuid,$13::uuid
52
62
  ) AS id`, [
53
63
  userId,
54
- provider,
55
- providerPaymentId,
56
- amountMinor,
57
- taxMinor,
58
- currency,
64
+ input.provider,
65
+ input.providerPaymentId,
66
+ input.amountMinor,
67
+ input.taxMinor,
68
+ input.currency,
59
69
  purpose,
60
- status,
61
- providerUpdatedAt,
62
- providerInvoiceId,
63
- metadata ?? "{}",
70
+ input.status,
71
+ input.providerUpdatedAt,
72
+ input.providerInvoiceId ?? null,
73
+ JSON.stringify(input.metadata ?? {}),
74
+ input.topupId ?? null,
75
+ input.billingEventId ?? null,
64
76
  ]);
65
77
  return requireResultField(rows, "id", postgresUuid, "BillingPaymentRepository.upsert");
66
78
  }
67
79
  async getForRefund(provider, providerPaymentId) {
68
- const rows = await this.query("SELECT * FROM bursar.get_billing_payment_by_provider($1,$2)", [
69
- provider,
70
- providerPaymentId,
71
- ]);
80
+ const rows = await this.query(`SELECT p.*, to_char(p.provider_updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS provider_updated_at FROM bursar.get_billing_payment_by_provider($1,$2) p`, [provider, providerPaymentId]);
72
81
  const row = optionalRecordRow(rows, "BillingPaymentRepository.getForRefund");
73
82
  return row === null ? null : parsePaymentRow(row, "BillingPaymentRepository.getForRefund");
74
83
  }
@@ -1 +1 @@
1
- {"version":3,"file":"payment.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/payment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,sBAAsB,GAAG,CAAC,CAAC,KAAK,CAAC;IACrC,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC;IACzB,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE;CACtC,CAAC,CAAC;AAEH,MAAM,uBAAuB,GAAG,CAAC;KAC9B,MAAM,CAAC;IACN,EAAE,EAAE,YAAY;IAChB,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3B,mBAAmB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IACtC,mBAAmB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC1C,UAAU,EAAE,YAAY;IACxB,YAAY,EAAE,sBAAsB;IACpC,SAAS,EAAE,sBAAsB;IACjC,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,YAAY,CAAC;IACxC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;IACjD,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,WAAW,EAAE,QAAQ,EAAE,UAAU,CAAC,CAAC;IAC9D,mBAAmB,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,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C;YAC7D,MAAM,IAAI,SAAS,CAAC,0CAA0C,CAAC,CAAC;QAClE,CAAC;QACD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B;;eAES,EACT;YACE,MAAM;YACN,QAAQ;YACR,iBAAiB;YACjB,WAAW;YACX,QAAQ;YACR,QAAQ;YACR,OAAO;YACP,MAAM;YACN,iBAAiB;YACjB,iBAAiB;YACjB,QAAQ,IAAI,IAAI;SACjB,CACF,CAAC;QACF,OAAO,kBAAkB,CAAC,IAAI,EAAE,IAAI,EAAE,YAAY,EAAE,iCAAiC,CAAC,CAAC;IACzF,CAAC;IACD,KAAK,CAAC,YAAY,CAAC,QAAgB,EAAE,iBAAyB;QAC5D,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,6DAA6D,EAAE;YAC3F,QAAQ;YACR,iBAAiB;SAClB,CAAC,CAAC;QACH,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,uCAAuC,CAAC,CAAC;QAC7E,OAAO,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,GAAG,EAAE,uCAAuC,CAAC,CAAC;IAC7F,CAAC;IACD,KAAK,CAAC,SAAS,CAAC,QAAgB,EAAE,iBAAyB;QACzD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,6DAA6D,EAAE;YAC3F,QAAQ;YACR,iBAAiB;SAClB,CAAC,CAAC;QACH,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,oCAAoC,CAAC,CAAC;QAC1E,OAAO,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,GAAG,EAAE,oCAAoC,CAAC,CAAC;IAC1F,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { PostgresRow } from \"../../../shared/json.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst PgSafeMinorUnitsSchema = z.union([\n z.string().regex(/^\\d+$/),\n z.number().int().nonnegative().safe(),\n]);\n\nconst BillingPaymentRowSchema = z\n .object({\n id: postgresUuid,\n provider: z.string().min(1),\n provider_payment_id: z.string().min(1),\n provider_invoice_id: z.string().nullable(),\n subject_id: postgresUuid,\n amount_minor: PgSafeMinorUnitsSchema,\n tax_minor: PgSafeMinorUnitsSchema,\n currency: z.string().regex(/^[A-Z]{3}$/),\n purpose: z.enum([\"subscription\", \"credit_topup\"]),\n status: z.enum([\"pending\", \"succeeded\", \"failed\", \"canceled\"]),\n provider_updated_at: z.union([z.string().datetime({ offset: true }), z.date()]),\n metadata: z.record(z.string(), z.json()),\n })\n .strict();\nexport type BillingPaymentRow = z.infer<typeof BillingPaymentRowSchema>;\nexport type ForRefundRow = BillingPaymentRow;\n\nfunction parsePaymentRow(row: PostgresRow, context: string): BillingPaymentRow {\n return safeParse(\n BillingPaymentRowSchema,\n {\n id: row.id,\n provider: row.provider,\n provider_payment_id: row.provider_payment_id,\n provider_invoice_id: row.provider_invoice_id,\n subject_id: row.subject_id,\n amount_minor: row.amount_minor,\n tax_minor: row.tax_minor,\n currency: row.currency,\n purpose: row.purpose,\n status: row.status,\n provider_updated_at: row.provider_updated_at,\n metadata: row.metadata,\n },\n context,\n );\n}\n\nexport class BillingPaymentRepository {\n constructor(private query: QueryFn) {}\n async upsert(\n provider: string,\n providerPaymentId: string,\n providerInvoiceId: string | null,\n userId: string,\n amountMinor: number,\n taxMinor: number,\n currency: string,\n purpose: \"subscription\" | \"credit_topup\",\n metadata: string | null,\n status: \"pending\" | \"succeeded\" | \"failed\" | \"canceled\",\n providerUpdatedAt: string,\n ): Promise<string> {\n if (!userId) throw new TypeError(\"billing payment requires a subject\");\n if (purpose !== \"subscription\" && purpose !== \"credit_topup\") {\n throw new TypeError(\"billing payment requires a known purpose\");\n }\n const rows = await this.query(\n `SELECT bursar.upsert_billing_payment(\n $1::uuid,$2,$3,$4,$5,$6,$7,$8::bursar.billing_payment_status,$9,$10,$11::jsonb\n ) AS id`,\n [\n userId,\n provider,\n providerPaymentId,\n amountMinor,\n taxMinor,\n currency,\n purpose,\n status,\n providerUpdatedAt,\n providerInvoiceId,\n metadata ?? \"{}\",\n ],\n );\n return requireResultField(rows, \"id\", postgresUuid, \"BillingPaymentRepository.upsert\");\n }\n async getForRefund(provider: string, providerPaymentId: string): Promise<ForRefundRow | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_payment_by_provider($1,$2)\", [\n provider,\n providerPaymentId,\n ]);\n const row = optionalRecordRow(rows, \"BillingPaymentRepository.getForRefund\");\n return row === null ? null : parsePaymentRow(row, \"BillingPaymentRepository.getForRefund\");\n }\n async getDirect(provider: string, providerPaymentId: string): Promise<BillingPaymentRow | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_payment_by_provider($1,$2)\", [\n provider,\n providerPaymentId,\n ]);\n const row = optionalRecordRow(rows, \"BillingPaymentRepository.getDirect\");\n return row === null ? null : parsePaymentRow(row, \"BillingPaymentRepository.getDirect\");\n }\n}\n"]}
1
+ {"version":3,"file":"payment.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/payment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,sBAAsB,GAAG,CAAC,CAAC,KAAK,CAAC;IACrC,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC;IACzB,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE;CACtC,CAAC,CAAC;AAEH,MAAM,uBAAuB,GAAG,CAAC;KAC9B,MAAM,CAAC;IACN,EAA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,EAAE,iBAAyB;QAC5D,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,4KAA4K,EAC5K,CAAC,QAAQ,EAAE,iBAAiB,CAAC,CAC9B,CAAC;QACF,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,uCAAuC,CAAC,CAAC;QAC7E,OAAO,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,GAAG,EAAE,uCAAuC,CAAC,CAAC;IAC7F,CAAC;IACD,KAAK,CAAC,SAAS,CAAC,QAAgB,EAAE,iBAAyB;QACzD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,6DAA6D,EAAE;YAC3F,QAAQ;YACR,iBAAiB;SAClB,CAAC,CAAC;QACH,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,oCAAoC,CAAC,CAAC;QAC1E,OAAO,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,GAAG,EAAE,oCAAoC,CAAC,CAAC;IAC1F,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { PostgresRow } from \"../../../shared/json.js\";\nimport type { BillingPaymentUpsert } from \"../../contracts.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst PgSafeMinorUnitsSchema = z.union([\n z.string().regex(/^\\d+$/),\n z.number().int().nonnegative().safe(),\n]);\n\nconst BillingPaymentRowSchema = z\n .object({\n id: postgresUuid,\n provider: z.string().min(1),\n provider_payment_id: z.string().min(1),\n provider_invoice_id: z.string().nullable(),\n subject_id: postgresUuid,\n amount_minor: PgSafeMinorUnitsSchema,\n tax_minor: PgSafeMinorUnitsSchema,\n currency: z.string().regex(/^[A-Z]{3}$/),\n purpose: z.enum([\"subscription\", \"credit_topup\"]),\n status: z.enum([\n \"pending\",\n \"requires_action\",\n \"succeeded\",\n \"failed\",\n \"canceled\",\n \"refunded\",\n \"partially_refunded\",\n \"disputed\",\n ]),\n provider_updated_at: z.union([z.string().datetime({ offset: true }), z.date()]),\n metadata: z.record(z.string(), z.json()),\n })\n .strict();\nexport type BillingPaymentRow = z.infer<typeof BillingPaymentRowSchema>;\nexport type ForRefundRow = BillingPaymentRow;\n\nfunction parsePaymentRow(row: PostgresRow, context: string): BillingPaymentRow {\n return safeParse(\n BillingPaymentRowSchema,\n {\n id: row.id,\n provider: row.provider,\n provider_payment_id: row.provider_payment_id,\n provider_invoice_id: row.provider_invoice_id,\n subject_id: row.subject_id,\n amount_minor: row.amount_minor,\n tax_minor: row.tax_minor,\n currency: row.currency,\n purpose: row.purpose,\n status: row.status,\n provider_updated_at: row.provider_updated_at,\n metadata: row.metadata,\n },\n context,\n );\n}\n\nexport class BillingPaymentRepository {\n constructor(private query: QueryFn) {}\n async upsert(input: BillingPaymentUpsert): Promise<string> {\n const { userId, purpose } = input;\n if (!userId) throw new TypeError(\"billing payment requires a subject\");\n if (purpose !== \"subscription\" && purpose !== \"credit_topup\") {\n throw new TypeError(\"billing payment requires a known purpose\");\n }\n const rows = await this.query(\n `SELECT bursar.upsert_billing_payment(\n $1::uuid,$2,$3,$4,$5,$6,$7,$8::bursar.billing_payment_status,$9,$10,$11::jsonb,$12::uuid,$13::uuid\n ) AS id`,\n [\n userId,\n input.provider,\n input.providerPaymentId,\n input.amountMinor,\n input.taxMinor,\n input.currency,\n purpose,\n input.status,\n input.providerUpdatedAt,\n input.providerInvoiceId ?? null,\n JSON.stringify(input.metadata ?? {}),\n input.topupId ?? null,\n input.billingEventId ?? null,\n ],\n );\n return requireResultField(rows, \"id\", postgresUuid, \"BillingPaymentRepository.upsert\");\n }\n async getForRefund(provider: string, providerPaymentId: string): Promise<ForRefundRow | null> {\n const rows = await this.query(\n `SELECT p.*, to_char(p.provider_updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS provider_updated_at FROM bursar.get_billing_payment_by_provider($1,$2) p`,\n [provider, providerPaymentId],\n );\n const row = optionalRecordRow(rows, \"BillingPaymentRepository.getForRefund\");\n return row === null ? null : parsePaymentRow(row, \"BillingPaymentRepository.getForRefund\");\n }\n async getDirect(provider: string, providerPaymentId: string): Promise<BillingPaymentRow | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_payment_by_provider($1,$2)\", [\n provider,\n providerPaymentId,\n ]);\n const row = optionalRecordRow(rows, \"BillingPaymentRepository.getDirect\");\n return row === null ? null : parsePaymentRow(row, \"BillingPaymentRepository.getDirect\");\n }\n}\n"]}
@@ -7,6 +7,7 @@ export declare class BillingSubscriptionChangeRepository {
7
7
  constructor(query: QueryFn);
8
8
  create(subscriptionId: string, input: BillingSubscriptionChangeInput): Promise<BillingSubscriptionChange>;
9
9
  getById(id: string): Promise<BillingSubscriptionChange | null>;
10
+ find(provider: string, subscriptionId: string, operationKey: string): Promise<BillingSubscriptionChange | null>;
10
11
  getOpen(provider: string, providerSubscriptionId: string): Promise<BillingSubscriptionChange | null>;
11
12
  update(id: string, update: BillingSubscriptionChangeUpdate): Promise<void>;
12
13
  private parseOptional;
@@ -1 +1 @@
1
- {"version":3,"file":"subscription-change.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription-change.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAO,KAAK,EACV,yBAAyB,EACzB,8BAA8B,EAE/B,MAAM,sBAAsB,CAAC;AAG9B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AA4HjE,uEAAuE;AACvE,qBAAa,mCAAmC;IAClC,OAAO,CAAC,QAAQ,CAAC,KAAK;IAAlC,YAA6B,KAAK,EAAE,OAAO,EAAI;IAEzC,MAAM,CACV,cAAc,EAAE,MAAM,EACtB,KAAK,EAAE,8BAA8B,GACpC,OAAO,CAAC,yBAAyB,CAAC,CAqCpC;IAEK,OAAO,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC,CAMnE;IAEK,OAAO,CACX,QAAQ,EAAE,MAAM,EAChB,sBAAsB,EAAE,MAAM,GAC7B,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC,CAM3C;IAEK,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,+BAA+B,GAAG,OAAO,CAAC,IAAI,CAAC,CAkB/E;YAEa,aAAa;YAyBb,gBAAgB;CA6C/B"}
1
+ {"version":3,"file":"subscription-change.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription-change.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAO,KAAK,EACV,yBAAyB,EACzB,8BAA8B,EAE/B,MAAM,sBAAsB,CAAC;AAG9B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAkIjE,uEAAuE;AACvE,qBAAa,mCAAmC;IAClC,OAAO,CAAC,QAAQ,CAAC,KAAK;IAAlC,YAA6B,KAAK,EAAE,OAAO,EAAI;IAEzC,MAAM,CACV,cAAc,EAAE,MAAM,EACtB,KAAK,EAAE,8BAA8B,GACpC,OAAO,CAAC,yBAAyB,CAAC,CA8CpC;IAEK,OAAO,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC,CAMnE;IAEK,IAAI,CACR,QAAQ,EAAE,MAAM,EAChB,cAAc,EAAE,MAAM,EACtB,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC,CAM3C;IAEK,OAAO,CACX,QAAQ,EAAE,MAAM,EAChB,sBAAsB,EAAE,MAAM,GAC7B,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC,CAM3C;IAEK,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,+BAA+B,GAAG,OAAO,CAAC,IAAI,CAAC,CAkB/E;YAEa,aAAa;YA2Bb,gBAAgB;CA6C/B"}