@zonastery/bursar 2.0.3 → 2.0.4

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 (341) hide show
  1. package/dist/billing/auto-recharge-port.d.ts +3 -2
  2. package/dist/billing/auto-recharge-port.d.ts.map +1 -1
  3. package/dist/billing/auto-recharge-port.js.map +1 -1
  4. package/dist/billing/auto-recharge-service.js +3 -3
  5. package/dist/billing/auto-recharge-service.js.map +1 -1
  6. package/dist/billing/billing-service.d.ts +3 -2
  7. package/dist/billing/billing-service.d.ts.map +1 -1
  8. package/dist/billing/billing-service.js +2 -10
  9. package/dist/billing/billing-service.js.map +1 -1
  10. package/dist/billing/billing-store.d.ts +6 -6
  11. package/dist/billing/billing-store.d.ts.map +1 -1
  12. package/dist/billing/billing-store.js.map +1 -1
  13. package/dist/billing/contracts.d.ts +8 -7
  14. package/dist/billing/contracts.d.ts.map +1 -1
  15. package/dist/billing/contracts.js.map +1 -1
  16. package/dist/billing/event-handlers.d.ts +5 -9
  17. package/dist/billing/event-handlers.d.ts.map +1 -1
  18. package/dist/billing/event-handlers.js +191 -285
  19. package/dist/billing/event-handlers.js.map +1 -1
  20. package/dist/billing/event-processor.d.ts +1 -1
  21. package/dist/billing/event-processor.d.ts.map +1 -1
  22. package/dist/billing/event-processor.js +32 -23
  23. package/dist/billing/event-processor.js.map +1 -1
  24. package/dist/billing/financial-event-handlers.d.ts +3 -9
  25. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  26. package/dist/billing/financial-event-handlers.js +10 -12
  27. package/dist/billing/financial-event-handlers.js.map +1 -1
  28. package/dist/billing/index.d.ts +1 -1
  29. package/dist/billing/index.d.ts.map +1 -1
  30. package/dist/billing/index.js.map +1 -1
  31. package/dist/billing/management.d.ts +3 -2
  32. package/dist/billing/management.d.ts.map +1 -1
  33. package/dist/billing/management.js.map +1 -1
  34. package/dist/billing/postgres/repositories/auto-recharge.d.ts +2 -1
  35. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  36. package/dist/billing/postgres/repositories/auto-recharge.js +58 -40
  37. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  38. package/dist/billing/postgres/repositories/dispute.d.ts +2 -1
  39. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
  40. package/dist/billing/postgres/repositories/dispute.js.map +1 -1
  41. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  42. package/dist/billing/postgres/repositories/event.js.map +1 -1
  43. package/dist/billing/postgres/repositories/invoice.d.ts +2 -1
  44. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  45. package/dist/billing/postgres/repositories/invoice.js +8 -12
  46. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  47. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  48. package/dist/billing/postgres/repositories/offer.js +5 -0
  49. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  50. package/dist/billing/postgres/repositories/payment.d.ts +1 -1
  51. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  52. package/dist/billing/postgres/repositories/payment.js +1 -1
  53. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  54. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -1
  55. package/dist/billing/postgres/repositories/subscription-change.js +1 -9
  56. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
  57. package/dist/billing/postgres/repositories/subscription.d.ts +6 -6
  58. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  59. package/dist/billing/postgres/repositories/subscription.js +29 -30
  60. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  61. package/dist/billing/postgres/store.d.ts +6 -5
  62. package/dist/billing/postgres/store.d.ts.map +1 -1
  63. package/dist/billing/postgres/store.js +15 -13
  64. package/dist/billing/postgres/store.js.map +1 -1
  65. package/dist/billing/types/auto-recharge.d.ts +2 -1
  66. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  67. package/dist/billing/types/auto-recharge.js.map +1 -1
  68. package/dist/billing/types/documents.d.ts +2 -1
  69. package/dist/billing/types/documents.d.ts.map +1 -1
  70. package/dist/billing/types/documents.js.map +1 -1
  71. package/dist/billing/types/events.d.ts +3 -2
  72. package/dist/billing/types/events.d.ts.map +1 -1
  73. package/dist/billing/types/events.js +73 -39
  74. package/dist/billing/types/events.js.map +1 -1
  75. package/dist/billing/types/subscriptions.d.ts +4 -1
  76. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  77. package/dist/billing/types/subscriptions.js.map +1 -1
  78. package/dist/breakdown.d.ts +3 -2
  79. package/dist/breakdown.d.ts.map +1 -1
  80. package/dist/breakdown.js.map +1 -1
  81. package/dist/bursar.d.ts.map +1 -1
  82. package/dist/bursar.js +4 -3
  83. package/dist/bursar.js.map +1 -1
  84. package/dist/catalog.d.ts.map +1 -1
  85. package/dist/catalog.js +45 -42
  86. package/dist/catalog.js.map +1 -1
  87. package/dist/commerce/provider-registry.d.ts.map +1 -1
  88. package/dist/commerce/provider-registry.js +11 -6
  89. package/dist/commerce/provider-registry.js.map +1 -1
  90. package/dist/commerce/service.d.ts.map +1 -1
  91. package/dist/commerce/service.js +16 -22
  92. package/dist/commerce/service.js.map +1 -1
  93. package/dist/commerce/types.d.ts.map +1 -1
  94. package/dist/commerce/types.js.map +1 -1
  95. package/dist/config/parse-access.d.ts +5 -2
  96. package/dist/config/parse-access.d.ts.map +1 -1
  97. package/dist/config/parse-access.js +60 -41
  98. package/dist/config/parse-access.js.map +1 -1
  99. package/dist/config/parse-commerce.d.ts +2 -1
  100. package/dist/config/parse-commerce.d.ts.map +1 -1
  101. package/dist/config/parse-commerce.js +49 -29
  102. package/dist/config/parse-commerce.js.map +1 -1
  103. package/dist/config/parse-credits.d.ts +2 -1
  104. package/dist/config/parse-credits.d.ts.map +1 -1
  105. package/dist/config/parse-credits.js +39 -23
  106. package/dist/config/parse-credits.js.map +1 -1
  107. package/dist/config/parse-plans.d.ts +7 -2
  108. package/dist/config/parse-plans.d.ts.map +1 -1
  109. package/dist/config/parse-plans.js +49 -22
  110. package/dist/config/parse-plans.js.map +1 -1
  111. package/dist/config/parse-pricing.d.ts +2 -1
  112. package/dist/config/parse-pricing.d.ts.map +1 -1
  113. package/dist/config/parse-pricing.js +41 -31
  114. package/dist/config/parse-pricing.js.map +1 -1
  115. package/dist/config/parse-utils.d.ts +15 -11
  116. package/dist/config/parse-utils.d.ts.map +1 -1
  117. package/dist/config/parse-utils.js +90 -27
  118. package/dist/config/parse-utils.js.map +1 -1
  119. package/dist/config/types.d.ts.map +1 -1
  120. package/dist/config/types.js.map +1 -1
  121. package/dist/config.d.ts +6 -5
  122. package/dist/config.d.ts.map +1 -1
  123. package/dist/config.js +65 -35
  124. package/dist/config.js.map +1 -1
  125. package/dist/credits/amount.d.ts +1 -1
  126. package/dist/credits/amount.d.ts.map +1 -1
  127. package/dist/credits/amount.js +5 -4
  128. package/dist/credits/amount.js.map +1 -1
  129. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  130. package/dist/credits/catalog-runtime.js +2 -3
  131. package/dist/credits/catalog-runtime.js.map +1 -1
  132. package/dist/credits/events.d.ts +12 -1
  133. package/dist/credits/events.d.ts.map +1 -1
  134. package/dist/credits/events.js +35 -21
  135. package/dist/credits/events.js.map +1 -1
  136. package/dist/credits/lease-workflow.d.ts +2 -1
  137. package/dist/credits/lease-workflow.d.ts.map +1 -1
  138. package/dist/credits/lease-workflow.js +3 -2
  139. package/dist/credits/lease-workflow.js.map +1 -1
  140. package/dist/credits/low-balance-monitor.d.ts +2 -1
  141. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  142. package/dist/credits/low-balance-monitor.js.map +1 -1
  143. package/dist/credits/postgres/repositories/analytics.d.ts +2 -2
  144. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  145. package/dist/credits/postgres/repositories/analytics.js +14 -6
  146. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  147. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  148. package/dist/credits/postgres/repositories/balance.js +6 -6
  149. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  150. package/dist/credits/postgres/repositories/catalog.d.ts +4 -3
  151. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
  152. package/dist/credits/postgres/repositories/catalog.js +4 -3
  153. package/dist/credits/postgres/repositories/catalog.js.map +1 -1
  154. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  155. package/dist/credits/postgres/repositories/deduction.js +2 -2
  156. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  157. package/dist/credits/postgres/repositories/plan.d.ts +1 -1
  158. package/dist/credits/postgres/store.d.ts +3 -2
  159. package/dist/credits/postgres/store.d.ts.map +1 -1
  160. package/dist/credits/postgres/store.js +17 -10
  161. package/dist/credits/postgres/store.js.map +1 -1
  162. package/dist/credits/postgres/value-mappers.d.ts +4 -3
  163. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  164. package/dist/credits/postgres/value-mappers.js +10 -11
  165. package/dist/credits/postgres/value-mappers.js.map +1 -1
  166. package/dist/credits/service.d.ts.map +1 -1
  167. package/dist/credits/service.js +10 -5
  168. package/dist/credits/service.js.map +1 -1
  169. package/dist/credits/store.d.ts +5 -4
  170. package/dist/credits/store.d.ts.map +1 -1
  171. package/dist/credits/store.js.map +1 -1
  172. package/dist/credits/types/account.d.ts +5 -4
  173. package/dist/credits/types/account.d.ts.map +1 -1
  174. package/dist/credits/types/account.js.map +1 -1
  175. package/dist/credits/types/catalog.d.ts +2 -1
  176. package/dist/credits/types/catalog.d.ts.map +1 -1
  177. package/dist/credits/types/catalog.js.map +1 -1
  178. package/dist/credits/types/grants.d.ts.map +1 -1
  179. package/dist/credits/types/grants.js.map +1 -1
  180. package/dist/credits/types/ledger.d.ts +3 -2
  181. package/dist/credits/types/ledger.d.ts.map +1 -1
  182. package/dist/credits/types/ledger.js.map +1 -1
  183. package/dist/engine.d.ts +2 -2
  184. package/dist/engine.d.ts.map +1 -1
  185. package/dist/engine.js +39 -10
  186. package/dist/engine.js.map +1 -1
  187. package/dist/errors.d.ts +7 -4
  188. package/dist/errors.d.ts.map +1 -1
  189. package/dist/errors.js +18 -11
  190. package/dist/errors.js.map +1 -1
  191. package/dist/expr/ast.d.ts.map +1 -1
  192. package/dist/expr/ast.js.map +1 -1
  193. package/dist/expr/parser.d.ts.map +1 -1
  194. package/dist/expr/parser.js.map +1 -1
  195. package/dist/expr/tokenizer.d.ts.map +1 -1
  196. package/dist/expr/tokenizer.js +34 -12
  197. package/dist/expr/tokenizer.js.map +1 -1
  198. package/dist/expr.d.ts.map +1 -1
  199. package/dist/expr.js +12 -6
  200. package/dist/expr.js.map +1 -1
  201. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  202. package/dist/generated/pricing-config.types.js.map +1 -1
  203. package/dist/integrations/better-auth.d.ts +4 -1
  204. package/dist/integrations/better-auth.d.ts.map +1 -1
  205. package/dist/integrations/better-auth.js +7 -4
  206. package/dist/integrations/better-auth.js.map +1 -1
  207. package/dist/load-config-file.d.ts +2 -1
  208. package/dist/load-config-file.d.ts.map +1 -1
  209. package/dist/load-config-file.js +19 -13
  210. package/dist/load-config-file.js.map +1 -1
  211. package/dist/metrics.d.ts +2 -1
  212. package/dist/metrics.d.ts.map +1 -1
  213. package/dist/metrics.js.map +1 -1
  214. package/dist/node.d.ts +1 -1
  215. package/dist/node.d.ts.map +1 -1
  216. package/dist/node.js.map +1 -1
  217. package/dist/providers/_shared.d.ts +8 -5
  218. package/dist/providers/_shared.d.ts.map +1 -1
  219. package/dist/providers/_shared.js +15 -11
  220. package/dist/providers/_shared.js.map +1 -1
  221. package/dist/providers/dodo/better-auth-core.d.ts +32 -0
  222. package/dist/providers/dodo/better-auth-core.d.ts.map +1 -0
  223. package/dist/providers/dodo/better-auth-core.js +14 -0
  224. package/dist/providers/dodo/better-auth-core.js.map +1 -0
  225. package/dist/providers/dodo/better-auth.d.ts +5 -7
  226. package/dist/providers/dodo/better-auth.d.ts.map +1 -1
  227. package/dist/providers/dodo/better-auth.js +16 -13
  228. package/dist/providers/dodo/better-auth.js.map +1 -1
  229. package/dist/providers/dodo/client-contract.d.ts +11 -10
  230. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  231. package/dist/providers/dodo/client-contract.js.map +1 -1
  232. package/dist/providers/dodo/event-mapper.d.ts +7 -4
  233. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  234. package/dist/providers/dodo/event-mapper.js +121 -113
  235. package/dist/providers/dodo/event-mapper.js.map +1 -1
  236. package/dist/providers/dodo/nextjs-core.d.ts +22 -0
  237. package/dist/providers/dodo/nextjs-core.d.ts.map +1 -0
  238. package/dist/providers/dodo/nextjs-core.js +14 -0
  239. package/dist/providers/dodo/nextjs-core.js.map +1 -0
  240. package/dist/providers/dodo/nextjs.d.ts +5 -7
  241. package/dist/providers/dodo/nextjs.d.ts.map +1 -1
  242. package/dist/providers/dodo/nextjs.js +11 -10
  243. package/dist/providers/dodo/nextjs.js.map +1 -1
  244. package/dist/providers/dodo/provider.d.ts +3 -3
  245. package/dist/providers/dodo/provider.d.ts.map +1 -1
  246. package/dist/providers/dodo/provider.js +42 -35
  247. package/dist/providers/dodo/provider.js.map +1 -1
  248. package/dist/providers/dodo/react-native-core.d.ts +56 -0
  249. package/dist/providers/dodo/react-native-core.d.ts.map +1 -0
  250. package/dist/providers/dodo/react-native-core.js +56 -0
  251. package/dist/providers/dodo/react-native-core.js.map +1 -0
  252. package/dist/providers/dodo/react-native.d.ts +6 -50
  253. package/dist/providers/dodo/react-native.d.ts.map +1 -1
  254. package/dist/providers/dodo/react-native.js +5 -49
  255. package/dist/providers/dodo/react-native.js.map +1 -1
  256. package/dist/providers/dodo/webhook-bridge.d.ts +4 -2
  257. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
  258. package/dist/providers/dodo/webhook-bridge.js.map +1 -1
  259. package/dist/providers/environment.d.ts +1 -1
  260. package/dist/providers/environment.d.ts.map +1 -1
  261. package/dist/providers/environment.js +4 -2
  262. package/dist/providers/environment.js.map +1 -1
  263. package/dist/providers/mock/provider.d.ts.map +1 -1
  264. package/dist/providers/mock/provider.js +5 -10
  265. package/dist/providers/mock/provider.js.map +1 -1
  266. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  267. package/dist/providers/stripe/event-mapper.js +33 -9
  268. package/dist/providers/stripe/event-mapper.js.map +1 -1
  269. package/dist/providers/stripe/provider.d.ts.map +1 -1
  270. package/dist/providers/stripe/provider.js +100 -60
  271. package/dist/providers/stripe/provider.js.map +1 -1
  272. package/dist/providers/types.d.ts.map +1 -1
  273. package/dist/providers/types.js.map +1 -1
  274. package/dist/retry.d.ts.map +1 -1
  275. package/dist/retry.js +16 -9
  276. package/dist/retry.js.map +1 -1
  277. package/dist/shared/diagnostics.d.ts +5 -5
  278. package/dist/shared/diagnostics.d.ts.map +1 -1
  279. package/dist/shared/diagnostics.js +32 -22
  280. package/dist/shared/diagnostics.js.map +1 -1
  281. package/dist/shared/idempotency.d.ts +4 -3
  282. package/dist/shared/idempotency.d.ts.map +1 -1
  283. package/dist/shared/idempotency.js +21 -10
  284. package/dist/shared/idempotency.js.map +1 -1
  285. package/dist/shared/json.d.ts +28 -0
  286. package/dist/shared/json.d.ts.map +1 -0
  287. package/dist/shared/json.js +41 -0
  288. package/dist/shared/json.js.map +1 -0
  289. package/dist/shared/logger.d.ts +10 -4
  290. package/dist/shared/logger.d.ts.map +1 -1
  291. package/dist/shared/logger.js.map +1 -1
  292. package/dist/shared/postgres-client.d.ts +8 -6
  293. package/dist/shared/postgres-client.d.ts.map +1 -1
  294. package/dist/shared/postgres-client.js +69 -47
  295. package/dist/shared/postgres-client.js.map +1 -1
  296. package/dist/shared/postgres-errors.d.ts +1 -1
  297. package/dist/shared/postgres-errors.d.ts.map +1 -1
  298. package/dist/shared/postgres-errors.js +32 -31
  299. package/dist/shared/postgres-errors.js.map +1 -1
  300. package/dist/shared/postgres-types.d.ts +3 -2
  301. package/dist/shared/postgres-types.d.ts.map +1 -1
  302. package/dist/shared/postgres-types.js.map +1 -1
  303. package/dist/shared/postgres-validation.d.ts +7 -6
  304. package/dist/shared/postgres-validation.d.ts.map +1 -1
  305. package/dist/shared/postgres-validation.js +17 -10
  306. package/dist/shared/postgres-validation.js.map +1 -1
  307. package/dist/storage/adapters/clickhouse.d.ts +11 -4
  308. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  309. package/dist/storage/adapters/clickhouse.js +8 -6
  310. package/dist/storage/adapters/clickhouse.js.map +1 -1
  311. package/dist/storage/adapters/s3.d.ts +28 -5
  312. package/dist/storage/adapters/s3.d.ts.map +1 -1
  313. package/dist/storage/adapters/s3.js +48 -33
  314. package/dist/storage/adapters/s3.js.map +1 -1
  315. package/dist/storage/diagnostics.d.ts +1 -1
  316. package/dist/storage/diagnostics.js +13 -12
  317. package/dist/storage/diagnostics.js.map +1 -1
  318. package/dist/storage/maintenance.d.ts.map +1 -1
  319. package/dist/storage/maintenance.js +31 -25
  320. package/dist/storage/maintenance.js.map +1 -1
  321. package/dist/storage/outbox-worker.d.ts +1 -1
  322. package/dist/storage/outbox-worker.js +18 -18
  323. package/dist/storage/outbox-worker.js.map +1 -1
  324. package/dist/storage/ports.d.ts +10 -7
  325. package/dist/storage/ports.d.ts.map +1 -1
  326. package/dist/storage/ports.js.map +1 -1
  327. package/dist/storage/postgres-repository.d.ts +3 -1
  328. package/dist/storage/postgres-repository.d.ts.map +1 -1
  329. package/dist/storage/postgres-repository.js +10 -4
  330. package/dist/storage/postgres-repository.js.map +1 -1
  331. package/dist/storage/runtime.d.ts +1 -1
  332. package/dist/storage/runtime.d.ts.map +1 -1
  333. package/dist/storage/runtime.js +165 -182
  334. package/dist/storage/runtime.js.map +1 -1
  335. package/dist/telemetry/index.d.ts +10 -6
  336. package/dist/telemetry/index.d.ts.map +1 -1
  337. package/dist/telemetry/index.js +26 -23
  338. package/dist/telemetry/index.js.map +1 -1
  339. package/dist/telemetry/opentelemetry.js +3 -3
  340. package/dist/telemetry/opentelemetry.js.map +1 -1
  341. package/package.json +14 -14
@@ -1 +1 @@
1
- {"version":3,"file":"subscription.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,SAAS,GAAG,CAAC;KAChB,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,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;AACzF,MAAM,wBAAwB,GAAG,CAAC,CAAC,IAAI,CAAC;IACtC,YAAY;IACZ,oBAAoB;IACpB,UAAU;IACV,QAAQ;IACR,UAAU;IACV,UAAU;IACV,QAAQ;IACR,QAAQ;IACR,SAAS;CACV,CAAC,CAAC;AACH,MAAM,8BAA8B,GAAG,CAAC;KACrC,MAAM,CAAC;IACN,EAAE,EAAE,YAAY;IAChB,UAAU,EAAE,YAAY;IACxB,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3B,wBAAwB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;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I,WAAW,EAAE,EAAE,IAAI,IAAI;YAAE,OAAO,KAAK,CAAC;QAE1C,MAAM,YAAY,GAAG,MAAM,IAAI,CAAC,KAAK,CACnC,yEAAyE,EACzE,CAAC,MAAM,EAAE,WAAW,CAAC,EAAE,CAAC,CACzB,CAAC;QACF,IACE,CAAC,kBAAkB,CACjB,YAAY,EACZ,UAAU,EACV,SAAS,EACT,uDAAuD,CACxD,EACD,CAAC;YACD,MAAM,IAAI,UAAU,CAAC,wDAAwD,CAAC,CAAC;QACjF,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { BillingSubscriptionState } from \"../../types/subscriptions.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\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 SubscriptionStatusSchema = z.enum([\n \"incomplete\",\n \"incomplete_expired\",\n \"trialing\",\n \"active\",\n \"past_due\",\n \"canceled\",\n \"unpaid\",\n \"paused\",\n \"expired\",\n]);\nconst PersistedSubscriptionRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n provider_subscription_id: z.string().min(1),\n provider_customer_id: z.string().min(1).nullable(),\n offer_id: postgresUuid,\n catalog_revision_id: postgresUuid,\n status: SubscriptionStatusSchema,\n current_period_start: timestamp.nullable(),\n current_period_end: timestamp.nullable(),\n trial_end: timestamp.nullable(),\n cancel_at: timestamp.nullable(),\n ended_at: timestamp.nullable(),\n grace_ends_at: timestamp.nullable(),\n grace_expired_at: timestamp.nullable(),\n provider_updated_at: timestamp,\n cancel_at_period_end: pgBoolean,\n metadata: z.record(z.string(), z.unknown()),\n })\n .strict();\nconst CatalogReferenceSchema = z\n .object({\n offer_id: postgresUuid,\n catalog_revision_id: postgresUuid,\n })\n .strict();\nconst OfferContextSchema = 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\nconst SubscriptionRowSchema = z\n .object({\n id: postgresUuid,\n user_id: postgresUuid,\n provider: z.string().min(1),\n provider_subscription_id: z.string().min(1),\n provider_customer_id: z.string().min(1).nullable(),\n offer_id: postgresUuid,\n offer_key: z.string().min(1),\n plan_id: postgresUuid,\n plan: z.string().min(1),\n status: SubscriptionStatusSchema,\n current_period_start: timestamp.nullable(),\n current_period_end: timestamp.nullable(),\n trial_end: timestamp.nullable(),\n cancel_at: timestamp.nullable(),\n ended_at: timestamp.nullable(),\n grace_ends_at: timestamp.nullable(),\n grace_expired_at: timestamp.nullable(),\n provider_updated_at: timestamp,\n cancel_at_period_end: pgBoolean,\n interval: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n interval_count: z.number().int().positive(),\n metadata: z.record(z.string(), z.unknown()),\n })\n .strict();\n\nexport type SubscriptionRow = z.infer<typeof SubscriptionRowSchema>;\ntype PersistedSubscriptionRow = z.infer<typeof PersistedSubscriptionRowSchema>;\n\nfunction record(value: unknown, context: string): Record<string, unknown> {\n return safeParse(z.record(z.string(), z.unknown()), value, context);\n}\n\nfunction persistedSubscription(row: unknown, context: string): PersistedSubscriptionRow {\n const value = record(row, context);\n return safeParse(\n PersistedSubscriptionRowSchema,\n {\n id: value.id,\n subject_id: value.subject_id,\n provider: value.provider,\n provider_subscription_id: value.provider_subscription_id,\n provider_customer_id: value.provider_customer_id,\n offer_id: value.offer_id,\n catalog_revision_id: value.catalog_revision_id,\n status: value.status,\n current_period_start: value.current_period_start,\n current_period_end: value.current_period_end,\n trial_end: value.trial_end,\n cancel_at: value.cancel_at,\n ended_at: value.ended_at,\n grace_ends_at: value.grace_ends_at,\n grace_expired_at: value.grace_expired_at,\n provider_updated_at: value.provider_updated_at,\n cancel_at_period_end: value.cancel_at_period_end,\n metadata: value.metadata,\n },\n context,\n );\n}\n\nexport class BillingSubscriptionRepository {\n constructor(private query: QueryFn) {}\n\n async upsert(state: BillingSubscriptionState): Promise<void> {\n const provider = state.provider;\n const providerSubscriptionId = state.providerSubscriptionId;\n const userId = state.userId;\n let providerCustomerId = state.providerCustomerId ?? null;\n let offerId = state.offerId ?? null;\n\n if (!provider || !providerSubscriptionId) {\n throw new TypeError(\n \"subscription.upsert: subject, provider, subscription, and offer are required\",\n );\n }\n\n const existing = await this.query(\n `SELECT * FROM bursar.get_billing_subscription_by_provider($1, $2)`,\n [provider, providerSubscriptionId],\n );\n const rawExisting = optionalRecordRow(\n existing,\n \"BillingSubscriptionRepository.upsert.existing\",\n );\n const existingRow =\n rawExisting === null\n ? null\n : persistedSubscription(rawExisting, \"BillingSubscriptionRepository.upsert.existing\");\n if (providerCustomerId === null && existingRow !== null) {\n providerCustomerId = existingRow.provider_customer_id;\n }\n if (offerId === null && existingRow !== null) offerId = existingRow.offer_id;\n\n const offerKey = state.offerKey ?? null;\n if (offerId === null && offerKey !== null) {\n const offerRows = await this.query(`SELECT * FROM bursar.resolve_active_catalog_offer($1)`, [\n offerKey,\n ]);\n const offerRow = optionalRecordRow(offerRows, \"BillingSubscriptionRepository.upsert.offer\");\n if (offerRow !== null) {\n offerId = safeParse(\n postgresUuid,\n offerRow.id,\n \"BillingSubscriptionRepository.upsert.offer.id\",\n );\n }\n }\n\n if (!userId || !offerId) {\n throw new TypeError(\n \"subscription.upsert: subject, provider, subscription, and offer are required\",\n );\n }\n const providerUpdatedAt = safeParse(\n timestamp,\n state.providerUpdatedAt,\n \"BillingSubscriptionRepository.upsert.providerUpdatedAt\",\n );\n\n const rows = await this.query(\n \"SELECT bursar.upsert_billing_subscription($1::uuid,$2,$3,$4,$5::uuid,$6::bursar.billing_subscription_status,$7,$8,$9,$10::jsonb,$11,$12,$13,$14,$15) AS id\",\n [\n userId,\n provider,\n providerSubscriptionId,\n providerCustomerId,\n offerId,\n state.status,\n state.currentPeriodStart ?? null,\n state.currentPeriodEnd ?? null,\n state.cancelAtPeriodEnd,\n JSON.stringify(state.metadata ?? {}),\n state.trialEnd ?? null,\n state.cancelAt ?? null,\n state.endedAt ?? null,\n providerUpdatedAt,\n state.graceEndsAt ?? null,\n ],\n );\n requireResultField(rows, \"id\", postgresUuid, \"BillingSubscriptionRepository.upsert\");\n }\n\n private map(row: unknown): SubscriptionRow {\n const r = record(row, \"BillingSubscriptionRepository.map\");\n return safeParse(\n SubscriptionRowSchema,\n {\n id: r.id,\n user_id: r.subject_id,\n provider: r.provider,\n provider_subscription_id: r.provider_subscription_id,\n provider_customer_id: r.provider_customer_id,\n offer_id: r.offer_id,\n offer_key: r.offer_key,\n plan_id: r.plan_id,\n plan: r.plan,\n status: r.status,\n current_period_start: r.current_period_start,\n current_period_end: r.current_period_end,\n trial_end: r.trial_end,\n cancel_at: r.cancel_at,\n ended_at: r.ended_at,\n grace_ends_at: r.grace_ends_at,\n grace_expired_at: r.grace_expired_at,\n provider_updated_at: r.provider_updated_at,\n cancel_at_period_end: r.cancel_at_period_end,\n interval: r.interval,\n interval_count: r.interval_count,\n metadata: r.metadata,\n },\n \"BillingSubscriptionRepository\",\n );\n }\n\n private async withOfferContext(\n value: PersistedSubscriptionRow,\n ): Promise<Record<string, unknown>> {\n const reference = safeParse(\n CatalogReferenceSchema,\n { offer_id: value.offer_id, catalog_revision_id: value.catalog_revision_id },\n \"BillingSubscriptionRepository.withOfferContext.reference\",\n );\n const contextRows = await this.query(\n `SELECT * FROM bursar.get_catalog_offer_context($1::uuid, $2::uuid)`,\n [reference.offer_id, reference.catalog_revision_id],\n );\n const rawContext = optionalRecordRow(\n contextRows,\n \"BillingSubscriptionRepository.withOfferContext\",\n );\n if (rawContext === null) {\n throw new StoreError(\"Billing subscription offer context is missing\", {\n details: {\n offerId: reference.offer_id,\n catalogRevisionId: reference.catalog_revision_id,\n },\n });\n }\n const context = safeParse(\n OfferContextSchema,\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 \"BillingSubscriptionRepository.withOfferContext.context\",\n );\n return {\n ...value,\n ...context,\n plan: context.plan_key,\n interval: context.billing_unit,\n interval_count: context.billing_count,\n };\n }\n\n async get(provider: string, providerSubscriptionId: string): Promise<SubscriptionRow | null> {\n const rows = await this.query(\n `SELECT * FROM bursar.get_billing_subscription_by_provider($1, $2)`,\n [provider, providerSubscriptionId],\n );\n const row = optionalRecordRow(rows, \"BillingSubscriptionRepository.get\");\n return row === null\n ? null\n : this.map(\n await this.withOfferContext(\n persistedSubscription(row, \"BillingSubscriptionRepository.get\"),\n ),\n );\n }\n async getUserSubscription(userId: string, statuses?: string[]): Promise<SubscriptionRow | null> {\n const allowed = new Set(\n safeParse(\n z.array(SubscriptionStatusSchema),\n statuses ?? [\"active\", \"trialing\"],\n \"BillingSubscriptionRepository.getUserSubscription.statuses\",\n ),\n );\n const rows = await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [\n userId,\n ]);\n const candidates = rows\n .map((row) => persistedSubscription(row, \"BillingSubscriptionRepository.getUserSubscription\"))\n .filter((row) => allowed.has(row.status))\n .sort(\n (left, right) =>\n Date.parse(right.provider_updated_at) - Date.parse(left.provider_updated_at),\n );\n const selected = candidates[0];\n return selected === undefined ? null : this.map(await this.withOfferContext(selected));\n }\n async getUserSubscriptions(userId: string): Promise<SubscriptionRow[]> {\n const rows = await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [\n userId,\n ]);\n const persisted = rows.map((row) =>\n persistedSubscription(row, \"BillingSubscriptionRepository.getUserSubscriptions\"),\n );\n const enriched = await Promise.all(persisted.map((row) => this.withOfferContext(row)));\n return enriched.map((row) => this.map(row));\n }\n\n async listExpiredGraceSubscriptions(now: string, limit = 100): Promise<SubscriptionRow[]> {\n const rows = await this.query(`SELECT * FROM bursar.list_expired_grace_subscriptions($1, $2)`, [\n now,\n limit,\n ]);\n const persisted = rows.map((row) =>\n persistedSubscription(row, \"BillingSubscriptionRepository.listExpiredGraceSubscriptions\"),\n );\n const enriched = await Promise.all(persisted.map((row) => this.withOfferContext(row)));\n return enriched.map((row) => this.map(row));\n }\n\n async markGraceExpired(\n subscriptionId: string,\n expectedGraceEndsAt: string,\n expiredAt: string,\n ): Promise<boolean> {\n const rows = await this.query(\n `SELECT bursar.mark_subscription_grace_expired($1::uuid, $2, $3) AS marked`,\n [subscriptionId, expectedGraceEndsAt, expiredAt],\n );\n return requireResultField(\n rows,\n \"marked\",\n pgBoolean,\n \"BillingSubscriptionRepository.markGraceExpired\",\n );\n }\n\n async recordConflict(input: {\n userId?: string | null;\n provider: string;\n duplicateSubscriptionId: string;\n existingSubscriptionId?: string | null;\n eventId?: string | null;\n metadata?: Record<string, unknown>;\n }): Promise<string> {\n const rows = await this.query(\n `SELECT bursar.record_subscription_conflict(\n $1::uuid, $2, $3, $4, $5, $6::jsonb\n ) AS id`,\n [\n input.userId ?? null,\n input.provider,\n input.duplicateSubscriptionId,\n input.existingSubscriptionId ?? null,\n input.eventId ?? null,\n JSON.stringify(input.metadata ?? {}),\n ],\n );\n return requireResultField(\n rows,\n \"id\",\n z.union([z.string().min(1), z.number().int()]).transform(String),\n \"BillingSubscriptionRepository.recordConflict\",\n );\n }\n\n /** Select a provider subscription without modifying provider-reported state. */\n async selectEntitlementSource(\n userId: string,\n provider: string,\n providerSubscriptionId?: string | null,\n ): Promise<boolean> {\n const eligibleStatuses = new Set([\"trialing\", \"active\", \"past_due\", \"paused\"]);\n const rows = await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [\n userId,\n ]);\n const replacement = rows\n .map((row) =>\n persistedSubscription(row, \"BillingSubscriptionRepository.selectEntitlementSource\"),\n )\n .filter(\n (row) =>\n row.provider === provider &&\n eligibleStatuses.has(row.status) &&\n (!providerSubscriptionId || row.provider_subscription_id === providerSubscriptionId),\n )\n .sort(\n (left, right) =>\n Date.parse(right.provider_updated_at) - Date.parse(left.provider_updated_at),\n )[0];\n\n if (replacement?.id == null) return false;\n\n const selectedRows = await this.query(\n `SELECT bursar.select_entitlement_source($1::uuid, $2::uuid) AS selected`,\n [userId, replacement.id],\n );\n if (\n !requireResultField(\n selectedRows,\n \"selected\",\n pgBoolean,\n \"BillingSubscriptionRepository.selectEntitlementSource\",\n )\n ) {\n throw new StoreError(\"subscription entitlement source selection was rejected\");\n }\n\n return true;\n }\n}\n"]}
1
+ {"version":3,"file":"subscription.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAQxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,SAAS,GAAG,CAAC;KAChB,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,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;AACzF,MAAM,wBAAwB,GAAG,CAAC,CAAC,IAAI,CAAC;IACtC,Y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G,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,MAAM,CAAC,EAChE,8CAA8C,CAC/C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type {\n BillingSubscriptionState,\n BillingSubscriptionStatus,\n SubscriptionEntitlementOutcome,\n} from \"../../types/subscriptions.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { JsonObject, PostgresRow } from \"../../../shared/json.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\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 SubscriptionStatusSchema = z.enum([\n \"incomplete\",\n \"incomplete_expired\",\n \"trialing\",\n \"active\",\n \"past_due\",\n \"canceled\",\n \"unpaid\",\n \"paused\",\n \"expired\",\n]);\nconst SubscriptionEntitlementOutcomeSchema = z.enum([\"applied\", \"revoked\", \"preserved\", \"stale\"]);\nconst PersistedSubscriptionRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n provider_subscription_id: z.string().min(1),\n provider_customer_id: z.string().min(1).nullable(),\n offer_id: postgresUuid,\n catalog_revision_id: postgresUuid,\n status: SubscriptionStatusSchema,\n current_period_start: timestamp.nullable(),\n current_period_end: timestamp.nullable(),\n trial_end: timestamp.nullable(),\n cancel_at: timestamp.nullable(),\n ended_at: timestamp.nullable(),\n grace_ends_at: timestamp.nullable(),\n grace_expired_at: timestamp.nullable(),\n provider_updated_at: timestamp,\n cancel_at_period_end: pgBoolean,\n metadata: z.record(z.string(), z.json()),\n })\n .strict();\nconst CatalogReferenceSchema = z\n .object({\n offer_id: postgresUuid,\n catalog_revision_id: postgresUuid,\n })\n .strict();\nconst OfferContextSchema = 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\nconst SubscriptionRowSchema = z\n .object({\n id: postgresUuid,\n user_id: postgresUuid,\n provider: z.string().min(1),\n provider_subscription_id: z.string().min(1),\n provider_customer_id: z.string().min(1).nullable(),\n offer_id: postgresUuid,\n offer_key: z.string().min(1),\n plan_id: postgresUuid,\n plan: z.string().min(1),\n status: SubscriptionStatusSchema,\n current_period_start: timestamp.nullable(),\n current_period_end: timestamp.nullable(),\n trial_end: timestamp.nullable(),\n cancel_at: timestamp.nullable(),\n ended_at: timestamp.nullable(),\n grace_ends_at: timestamp.nullable(),\n grace_expired_at: timestamp.nullable(),\n provider_updated_at: timestamp,\n cancel_at_period_end: pgBoolean,\n interval: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n interval_count: z.number().int().positive(),\n metadata: z.record(z.string(), z.json()),\n })\n .strict();\n\nexport type SubscriptionRow = z.infer<typeof SubscriptionRowSchema>;\ntype PersistedSubscriptionRow = z.infer<typeof PersistedSubscriptionRowSchema>;\ntype EnrichedSubscriptionRow = PersistedSubscriptionRow & {\n offer_key: string;\n plan_id: string;\n plan_key: string;\n billing_unit: \"day\" | \"week\" | \"month\" | \"year\";\n billing_count: number;\n plan: string;\n interval: \"day\" | \"week\" | \"month\" | \"year\";\n interval_count: number;\n};\n\nfunction persistedSubscription(row: PostgresRow, context: string): PersistedSubscriptionRow {\n const value = row;\n return safeParse(\n PersistedSubscriptionRowSchema,\n {\n id: value.id,\n subject_id: value.subject_id,\n provider: value.provider,\n provider_subscription_id: value.provider_subscription_id,\n provider_customer_id: value.provider_customer_id,\n offer_id: value.offer_id,\n catalog_revision_id: value.catalog_revision_id,\n status: value.status,\n current_period_start: value.current_period_start,\n current_period_end: value.current_period_end,\n trial_end: value.trial_end,\n cancel_at: value.cancel_at,\n ended_at: value.ended_at,\n grace_ends_at: value.grace_ends_at,\n grace_expired_at: value.grace_expired_at,\n provider_updated_at: value.provider_updated_at,\n cancel_at_period_end: value.cancel_at_period_end,\n metadata: value.metadata,\n },\n context,\n );\n}\n\nexport class BillingSubscriptionRepository {\n constructor(private query: QueryFn) {}\n\n async upsert(state: BillingSubscriptionState): Promise<void> {\n const provider = state.provider;\n const providerSubscriptionId = state.providerSubscriptionId;\n const userId = state.userId;\n let providerCustomerId = state.providerCustomerId ?? null;\n let offerId = state.offerId ?? null;\n\n if (!provider || !providerSubscriptionId) {\n throw new TypeError(\n \"subscription.upsert: subject, provider, subscription, and offer are required\",\n );\n }\n\n const existing = await this.query(\n `SELECT * FROM bursar.get_billing_subscription_by_provider($1, $2)`,\n [provider, providerSubscriptionId],\n );\n const rawExisting = optionalRecordRow(\n existing,\n \"BillingSubscriptionRepository.upsert.existing\",\n );\n const existingRow =\n rawExisting === null\n ? null\n : persistedSubscription(rawExisting, \"BillingSubscriptionRepository.upsert.existing\");\n if (providerCustomerId === null && existingRow !== null) {\n providerCustomerId = existingRow.provider_customer_id;\n }\n if (offerId === null && existingRow !== null) offerId = existingRow.offer_id;\n\n const offerKey = state.offerKey ?? null;\n if (offerId === null && offerKey !== null) {\n const offerRows = await this.query(`SELECT * FROM bursar.resolve_active_catalog_offer($1)`, [\n offerKey,\n ]);\n const offerRow = optionalRecordRow(offerRows, \"BillingSubscriptionRepository.upsert.offer\");\n if (offerRow !== null) {\n offerId = safeParse(\n postgresUuid,\n offerRow.id,\n \"BillingSubscriptionRepository.upsert.offer.id\",\n );\n }\n }\n\n if (!userId || !offerId) {\n throw new TypeError(\n \"subscription.upsert: subject, provider, subscription, and offer are required\",\n );\n }\n const providerUpdatedAt = safeParse(\n timestamp,\n state.providerUpdatedAt,\n \"BillingSubscriptionRepository.upsert.providerUpdatedAt\",\n );\n\n const rows = await this.query(\n \"SELECT bursar.upsert_billing_subscription($1::uuid,$2,$3,$4,$5::uuid,$6::bursar.billing_subscription_status,$7,$8,$9,$10::jsonb,$11,$12,$13,$14,$15) AS id\",\n [\n userId,\n provider,\n providerSubscriptionId,\n providerCustomerId,\n offerId,\n state.status,\n state.currentPeriodStart ?? null,\n state.currentPeriodEnd ?? null,\n state.cancelAtPeriodEnd,\n JSON.stringify(state.metadata ?? {}),\n state.trialEnd ?? null,\n state.cancelAt ?? null,\n state.endedAt ?? null,\n providerUpdatedAt,\n state.graceEndsAt ?? null,\n ],\n );\n requireResultField(rows, \"id\", postgresUuid, \"BillingSubscriptionRepository.upsert\");\n }\n\n private map(row: EnrichedSubscriptionRow): SubscriptionRow {\n const r = row;\n return safeParse(\n SubscriptionRowSchema,\n {\n id: r.id,\n user_id: r.subject_id,\n provider: r.provider,\n provider_subscription_id: r.provider_subscription_id,\n provider_customer_id: r.provider_customer_id,\n offer_id: r.offer_id,\n offer_key: r.offer_key,\n plan_id: r.plan_id,\n plan: r.plan,\n status: r.status,\n current_period_start: r.current_period_start,\n current_period_end: r.current_period_end,\n trial_end: r.trial_end,\n cancel_at: r.cancel_at,\n ended_at: r.ended_at,\n grace_ends_at: r.grace_ends_at,\n grace_expired_at: r.grace_expired_at,\n provider_updated_at: r.provider_updated_at,\n cancel_at_period_end: r.cancel_at_period_end,\n interval: r.interval,\n interval_count: r.interval_count,\n metadata: r.metadata,\n },\n \"BillingSubscriptionRepository\",\n );\n }\n\n private async withOfferContext(\n value: PersistedSubscriptionRow,\n ): Promise<EnrichedSubscriptionRow> {\n const reference = safeParse(\n CatalogReferenceSchema,\n { offer_id: value.offer_id, catalog_revision_id: value.catalog_revision_id },\n \"BillingSubscriptionRepository.withOfferContext.reference\",\n );\n const contextRows = await this.query(\n `SELECT * FROM bursar.get_catalog_offer_context($1::uuid, $2::uuid)`,\n [reference.offer_id, reference.catalog_revision_id],\n );\n const rawContext = optionalRecordRow(\n contextRows,\n \"BillingSubscriptionRepository.withOfferContext\",\n );\n if (rawContext === null) {\n throw new StoreError(\"Billing subscription offer context is missing\", {\n details: {\n offerId: reference.offer_id,\n catalogRevisionId: reference.catalog_revision_id,\n },\n });\n }\n const context = safeParse(\n OfferContextSchema,\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 \"BillingSubscriptionRepository.withOfferContext.context\",\n );\n return {\n ...value,\n ...context,\n plan: context.plan_key,\n interval: context.billing_unit,\n interval_count: context.billing_count,\n };\n }\n\n async get(provider: string, providerSubscriptionId: string): Promise<SubscriptionRow | null> {\n const rows = await this.query(\n `SELECT * FROM bursar.get_billing_subscription_by_provider($1, $2)`,\n [provider, providerSubscriptionId],\n );\n const row = optionalRecordRow(rows, \"BillingSubscriptionRepository.get\");\n return row === null\n ? null\n : this.map(\n await this.withOfferContext(\n persistedSubscription(row, \"BillingSubscriptionRepository.get\"),\n ),\n );\n }\n async getUserSubscription(userId: string, statuses?: string[]): Promise<SubscriptionRow | null> {\n const allowed = new Set(\n safeParse(\n z.array(SubscriptionStatusSchema),\n statuses ?? [\"active\", \"trialing\"],\n \"BillingSubscriptionRepository.getUserSubscription.statuses\",\n ),\n );\n const rows = await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [\n userId,\n ]);\n const candidates = rows\n .map((row) => persistedSubscription(row, \"BillingSubscriptionRepository.getUserSubscription\"))\n .filter((row) => allowed.has(row.status))\n .sort(\n (left, right) =>\n Date.parse(right.provider_updated_at) - Date.parse(left.provider_updated_at),\n );\n const selected = candidates[0];\n return selected === undefined ? null : this.map(await this.withOfferContext(selected));\n }\n async getUserSubscriptions(userId: string): Promise<SubscriptionRow[]> {\n const rows = await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [\n userId,\n ]);\n const persisted = rows.map((row) =>\n persistedSubscription(row, \"BillingSubscriptionRepository.getUserSubscriptions\"),\n );\n const enriched = await Promise.all(persisted.map((row) => this.withOfferContext(row)));\n return enriched.map((row) => this.map(row));\n }\n\n async listExpiredGraceSubscriptions(now: string, limit = 100): Promise<SubscriptionRow[]> {\n const rows = await this.query(`SELECT * FROM bursar.list_expired_grace_subscriptions($1, $2)`, [\n now,\n limit,\n ]);\n const persisted = rows.map((row) =>\n persistedSubscription(row, \"BillingSubscriptionRepository.listExpiredGraceSubscriptions\"),\n );\n const enriched = await Promise.all(persisted.map((row) => this.withOfferContext(row)));\n return enriched.map((row) => this.map(row));\n }\n\n async reconcileEntitlement(\n subjectId: string,\n subscriptionId: string,\n billingEventId: string,\n expectedStatus: BillingSubscriptionStatus,\n expectedProviderUpdatedAt: string,\n planAssignedAt: Date | string | null,\n applyEntitlement: boolean,\n terminalPlanKey: string | null,\n reason: string,\n ): Promise<SubscriptionEntitlementOutcome> {\n const expectedTimestamp = safeParse(\n timestamp,\n expectedProviderUpdatedAt,\n \"BillingSubscriptionRepository.reconcileEntitlement.expectedProviderUpdatedAt\",\n );\n const assignmentTimestamp =\n planAssignedAt === null\n ? null\n : safeParse(\n timestamp,\n planAssignedAt,\n \"BillingSubscriptionRepository.reconcileEntitlement.planAssignedAt\",\n );\n const rows = await this.query(\n `SELECT bursar.reconcile_subscription_entitlement(\n $1::uuid, $2::uuid, $3::uuid, $4::bursar.billing_subscription_status,\n $5::timestamptz, $6::timestamptz, $7, $8, $9\n ) AS outcome`,\n [\n subjectId,\n subscriptionId,\n billingEventId,\n expectedStatus,\n expectedTimestamp,\n assignmentTimestamp,\n applyEntitlement,\n terminalPlanKey,\n reason,\n ],\n );\n return requireResultField(\n rows,\n \"outcome\",\n SubscriptionEntitlementOutcomeSchema,\n \"BillingSubscriptionRepository.reconcileEntitlement\",\n );\n }\n\n async expireGracePeriod(\n subjectId: string,\n subscriptionId: string,\n expectedGraceEndsAt: string,\n expiredAt: string,\n terminalPlanKey: string | null,\n ): Promise<boolean> {\n const rows = await this.query(\n `SELECT bursar.expire_subscription_grace_period($1::uuid, $2::uuid, $3, $4, $5) AS expired`,\n [subjectId, subscriptionId, expectedGraceEndsAt, expiredAt, terminalPlanKey],\n );\n return requireResultField(\n rows,\n \"expired\",\n pgBoolean,\n \"BillingSubscriptionRepository.expireGracePeriod\",\n );\n }\n\n async recordConflict(input: {\n userId?: string | null;\n provider: string;\n duplicateSubscriptionId: string;\n existingSubscriptionId?: string | null;\n eventId?: string | null;\n metadata?: JsonObject;\n }): Promise<string> {\n const rows = await this.query(\n `SELECT bursar.record_subscription_conflict(\n $1::uuid, $2, $3, $4, $5, $6::jsonb\n ) AS id`,\n [\n input.userId ?? null,\n input.provider,\n input.duplicateSubscriptionId,\n input.existingSubscriptionId ?? null,\n input.eventId ?? null,\n JSON.stringify(input.metadata ?? {}),\n ],\n );\n return requireResultField(\n rows,\n \"id\",\n z.union([z.string().min(1), z.number().int()]).transform(String),\n \"BillingSubscriptionRepository.recordConflict\",\n );\n }\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import { Decimal } from "decimal.js";
2
- import type { BillingAutoRechargeAttempt, BillingAutoRechargeProfile, BillingCreditPostingResult, BillingCustomerRecord, BillingEventClaim, BillingOfferResult, BillingPaymentRecord, BillingPreferences, BillingSubscriptionChange, BillingSubscriptionChangeInput, BillingSubscriptionState, CheckoutIntent, BillingTopupResult } from "../types/index.js";
2
+ import type { JsonObject } from "../../shared/json.js";
3
+ import type { BillingAutoRechargeAttempt, BillingAutoRechargeProfile, BillingCreditPostingResult, BillingCustomerRecord, BillingEventClaim, BillingOfferResult, BillingPaymentRecord, BillingPreferences, BillingSubscriptionChange, BillingSubscriptionChangeInput, BillingSubscriptionState, BillingSubscriptionStatus, SubscriptionEntitlementOutcome, CheckoutIntent, BillingTopupResult } from "../types/index.js";
3
4
  import { BillingStore } from "../billing-store.js";
4
5
  import type { AutoRechargeAttemptClaim, AutoRechargeAttemptUpdate, AutoRechargeProviderPaymentUpdate, BillingCreditGrantCreate, BillingDisputeUpsert, BillingInvoiceUpsert, BillingPaymentUpsert, BillingRefundUpsert, BillingSubscriptionChangeUpdate, BillingSubscriptionConflictCreate, CheckoutIntentCreate, CheckoutIntentUpdate } from "../contracts.js";
5
6
  import { type PostgresConnectionOptions, type PostgresPool, type PostgresPoolConstructor } from "../../shared/postgres-client.js";
@@ -52,7 +53,7 @@ export declare class PostgresBillingStore extends BillingStore {
52
53
  private rowToOffer;
53
54
  resolveBillingOffer(provider: string, productId?: string | null, priceId?: string | null): Promise<BillingOfferResult | null>;
54
55
  resolveBillingOfferByLookup(provider: string, lookupKey: string): Promise<BillingOfferResult | null>;
55
- claimBillingEvent(provider: string, eventId: string, eventType: string, envelope?: Record<string, unknown>): Promise<BillingEventClaim>;
56
+ claimBillingEvent(provider: string, eventId: string, eventType: string, envelope?: JsonObject): Promise<BillingEventClaim>;
56
57
  completeBillingEvent(provider: string, eventId: string, claimToken: string): Promise<boolean>;
57
58
  failBillingEvent(provider: string, eventId: string, claimToken: string, error?: string): Promise<boolean>;
58
59
  upsertBillingCustomer(provider: string, providerCustomerId: string, userId: string, email?: string | null): Promise<void>;
@@ -62,12 +63,12 @@ export declare class PostgresBillingStore extends BillingStore {
62
63
  createBillingSubscriptionChange(input: BillingSubscriptionChangeInput): Promise<BillingSubscriptionChange>;
63
64
  getOpenBillingSubscriptionChange(provider: string, providerSubscriptionId: string): Promise<BillingSubscriptionChange | null>;
64
65
  listExpiredGraceSubscriptions(now: string, limit?: number): Promise<BillingSubscriptionState[]>;
65
- markSubscriptionGraceExpired(subscriptionId: string, expectedGraceEndsAt: string, expiredAt?: string): Promise<boolean>;
66
+ reconcileSubscriptionEntitlement(subjectId: string, subscriptionId: string, billingEventId: string, expectedStatus: BillingSubscriptionStatus, expectedProviderUpdatedAt: string, planAssignedAt: Date | string | null, applyEntitlement: boolean, terminalPlanKey: string | null, reason: string): Promise<SubscriptionEntitlementOutcome>;
67
+ expireSubscriptionGracePeriod(subjectId: string, subscriptionId: string, expectedGraceEndsAt: string, expiredAt: string, terminalPlanKey: string | null): Promise<boolean>;
66
68
  updateBillingSubscriptionChange(id: string, update: BillingSubscriptionChangeUpdate): Promise<void>;
67
69
  getUserSubscription(userId: string, statuses?: string[]): Promise<BillingSubscriptionState | null>;
68
70
  getUserSubscriptions(userId: string): Promise<BillingSubscriptionState[]>;
69
71
  recordSubscriptionConflict(input: BillingSubscriptionConflictCreate): Promise<void>;
70
- selectSubscriptionEntitlementSource(userId: string, provider: string, providerSubscriptionId?: string | null): Promise<boolean>;
71
72
  private rowToTopup;
72
73
  resolveCreditTopup(provider: string, productId?: string | null, priceId?: string | null): Promise<BillingTopupResult | null>;
73
74
  resolveCreditTopupByLookup(provider: string, lookupKey: string): Promise<BillingTopupResult | null>;
@@ -83,7 +84,7 @@ export declare class PostgresBillingStore extends BillingStore {
83
84
  upsertBillingDispute(options: BillingDisputeUpsert): Promise<void>;
84
85
  getBillingPayment(provider: string, providerPaymentId: string): Promise<BillingPaymentRecord | null>;
85
86
  private rowToSubscriptionState;
86
- getActiveCatalogDocument(): Promise<Record<string, unknown> | null>;
87
+ getActiveCatalogDocument(): Promise<JsonObject | null>;
87
88
  pseudonymizeFinancialSubject(userId: string): Promise<boolean>;
88
89
  getBillingPreferences(userId: string): Promise<BillingPreferences | null>;
89
90
  upsertBillingPreferences(prefs: BillingPreferences): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/billing/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,KAAK,EACV,0BAA0B,EAC1B,0BAA0B,EAC1B,0BAA0B,EAC1B,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EAClB,oBAAoB,EACpB,kBAAkB,EAClB,yBAAyB,EACzB,8BAA8B,EAC9B,wBAAwB,EACxB,cAAc,EACd,kBAAkB,EACnB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EACV,wBAAwB,EACxB,yBAAyB,EACzB,iCAAiC,EACjC,wBAAwB,EACxB,oBAA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AAM,GACxB,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC;IA8BvC,OAAO,CAAC,sBAAsB;IA2BxB,wBAAwB,IAAI,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC;IAetD,4BAA4B,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAa9D,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAIzE,wBAAwB,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC;IAIlE,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,0BAA0B,GAAG,IAAI,CAAC;IAIlF,yBAAyB,CAC7B,OAAO,EAAE,0BAA0B,EACnC,OAAO,CAAC,EAAE;QAAE,aAAa,CAAC,EAAE,OAAO,CAAA;KAAE,GACpC,OAAO,CAAC,IAAI,CAAC;IAIV,wBAAwB,CAC5B,KAAK,EAAE,wBAAwB,GAC9B,OAAO,CAAC,0BAA0B,GAAG,IAAI,CAAC;IAIvC,yBAAyB,CAAC,KAAK,EAAE,yBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC;IAI1E,0CAA0C,CAC9C,KAAK,EAAE,iCAAiC,GACvC,OAAO,CAAC,IAAI,CAAC;IAIV,yBAAyB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC;IAIhF,0BAA0B,CAC9B,MAAM,EAAE,MAAM,EACd,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GACvB,OAAO,CAAC,qBAAqB,GAAG,IAAI,CAAC;CAQzC"}
@@ -88,10 +88,10 @@ export class PostgresBillingStore extends BillingStore {
88
88
  _subscriptionChange = null;
89
89
  constructor(options) {
90
90
  super();
91
- if (typeof options !== "object" || options === null) {
91
+ if (!z.object({}).safeParse(options).success) {
92
92
  throw new TypeError("PostgresBillingStore options are required");
93
93
  }
94
- if (typeof options.postgres !== "string" && options.poolConstructor !== undefined) {
94
+ if (!z.string().safeParse(options.postgres).success && options.poolConstructor !== undefined) {
95
95
  throw new TypeError("poolConstructor cannot be used with an existing PostgreSQL pool");
96
96
  }
97
97
  const providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);
@@ -222,6 +222,8 @@ export class PostgresBillingStore extends BillingStore {
222
222
  });
223
223
  }
224
224
  const row = rows[0];
225
+ if (!row)
226
+ throw new StoreError("getCheckoutIntent: expected one row");
225
227
  return this.rowToCheckoutIntent(safeParse(CheckoutIntentRowSchema, {
226
228
  id: row.id,
227
229
  subject_id: row.subject_id,
@@ -350,8 +352,11 @@ export class PostgresBillingStore extends BillingStore {
350
352
  const rows = await this.billingSubscription.listExpiredGraceSubscriptions(now, limit);
351
353
  return rows.map((row) => this.rowToSubscriptionState(row));
352
354
  }
353
- async markSubscriptionGraceExpired(subscriptionId, expectedGraceEndsAt, expiredAt = new Date().toISOString()) {
354
- return this.billingSubscription.markGraceExpired(subscriptionId, expectedGraceEndsAt, expiredAt);
355
+ async reconcileSubscriptionEntitlement(subjectId, subscriptionId, billingEventId, expectedStatus, expectedProviderUpdatedAt, planAssignedAt, applyEntitlement, terminalPlanKey, reason) {
356
+ return this.billingSubscription.reconcileEntitlement(subjectId, subscriptionId, billingEventId, expectedStatus, expectedProviderUpdatedAt, planAssignedAt, applyEntitlement, terminalPlanKey, reason);
357
+ }
358
+ async expireSubscriptionGracePeriod(subjectId, subscriptionId, expectedGraceEndsAt, expiredAt, terminalPlanKey) {
359
+ return this.billingSubscription.expireGracePeriod(subjectId, subscriptionId, expectedGraceEndsAt, expiredAt, terminalPlanKey);
355
360
  }
356
361
  async updateBillingSubscriptionChange(id, update) {
357
362
  await this.billingSubscriptionChange.update(id, update);
@@ -369,9 +374,6 @@ export class PostgresBillingStore extends BillingStore {
369
374
  async recordSubscriptionConflict(input) {
370
375
  await this.billingSubscription.recordConflict(input);
371
376
  }
372
- async selectSubscriptionEntitlementSource(userId, provider, providerSubscriptionId) {
373
- return this.billingSubscription.selectEntitlementSource(userId, provider, providerSubscriptionId);
374
- }
375
377
  rowToTopup(r) {
376
378
  if (!r)
377
379
  return null;
@@ -529,14 +531,14 @@ export class PostgresBillingStore extends BillingStore {
529
531
  }
530
532
  async getActiveCatalogDocument() {
531
533
  const rows = await this.queryFn("SELECT * FROM bursar.active_catalog_revision()", []);
532
- if (rows.length === 0)
534
+ const row = optionalRecordRow(rows, "PostgresBillingStore.getActiveCatalogDocument");
535
+ if (row === null)
533
536
  return null;
534
- if (rows.length !== 1 || typeof rows[0] !== "object" || rows[0] === null) {
535
- throw new StoreError("active catalog revision returned a malformed row", {
536
- details: { rowCount: rows.length },
537
- });
537
+ const sourceDocument = row.source_document;
538
+ if (sourceDocument === undefined) {
539
+ throw new StoreError("active catalog revision returned no source document");
538
540
  }
539
- return safeParse(z.record(z.string(), z.unknown()), rows[0].source_document, "PostgresBillingStore.getActiveCatalogDocument");
541
+ return safeParse(z.record(z.string(), z.json()), sourceDocument, "PostgresBillingStore.getActiveCatalogDocument");
540
542
  }
541
543
  async pseudonymizeFinancialSubject(userId) {
542
544
  const rows = await this.queryFn(`SELECT bursar.pseudonymize_financial_subject($1::uuid) AS pseudonymized`, [userId]);
@@ -1 +1 @@
1
- {"version":3,"file":"store.js","sourceRoot":"","sources":["../../../src/billing/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAgBxB,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAgBnD,OAAO,EACL,cAAc,GAIf,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,4BAA4B,GAE7B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC/D,OAAO,EAAE,gCAAgC,EAAE,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K,CAAC,CAAC;IACxE,CAAC;IAED,KAAK,CAAC,yBAAyB,CAAC,MAAc,EAAE,KAAoB;QAClE,OAAO,IAAI,CAAC,mBAAmB,CAAC,aAAa,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC/D,CAAC;IAED,KAAK,CAAC,0BAA0B,CAC9B,MAAc,EACd,QAAwB;QAExB,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,WAAW,CAAC,MAAM,EAAE,QAAQ,IAAI,IAAI,CAAC,CAAC;QAChF,IAAI,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QACzB,OAAO;YACL,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,kBAAkB,EAAE,MAAM,CAAC,kBAAkB;SAC9C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { z } from \"zod\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeProfile,\n BillingCreditPostingResult,\n BillingCustomerRecord,\n BillingEventClaim,\n BillingOfferResult,\n BillingPaymentRecord,\n BillingPreferences,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionState,\n CheckoutIntent,\n BillingTopupResult,\n} from \"../types/index.js\";\nimport { BillingStore } from \"../billing-store.js\";\nimport type {\n AutoRechargeAttemptClaim,\n AutoRechargeAttemptUpdate,\n AutoRechargeProviderPaymentUpdate,\n BillingCreditGrantCreate,\n BillingDisputeUpsert,\n BillingInvoiceUpsert,\n BillingPaymentUpsert,\n BillingRefundUpsert,\n BillingSubscriptionChangeUpdate,\n BillingSubscriptionConflictCreate,\n CheckoutIntentCreate,\n CheckoutIntentUpdate,\n} from \"../contracts.js\";\nimport type { QueryFn } from \"../../shared/postgres-types.js\";\nimport {\n PostgresClient,\n type PostgresConnectionOptions,\n type PostgresPool,\n type PostgresPoolConstructor,\n} from \"../../shared/postgres-client.js\";\nimport {\n normalizeProviderEnvironment,\n type ProviderEnvironment,\n} from \"../../providers/environment.js\";\nimport { StoreClosedError, StoreError } from \"../../errors.js\";\nimport { optionalBoundedDiagnosticMessage } from \"../../shared/diagnostics.js\";\nimport { requireStableKey } from \"../../shared/idempotency.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireRecordRow,\n requireResultField,\n safeParse,\n} from \"../../shared/postgres-validation.js\";\nimport { BillingOfferRepository, type BillingOfferRow } from \"./repositories/offer.js\";\nimport { BillingTopupRepository, type BillingTopupRow } from \"./repositories/topup.js\";\nimport { BillingCustomerRepository } from \"./repositories/customer.js\";\nimport {\n BillingSubscriptionRepository,\n type SubscriptionRow,\n} from \"./repositories/subscription.js\";\nimport { BillingEventRepository } from \"./repositories/event.js\";\nimport { BillingPaymentRepository } from \"./repositories/payment.js\";\nimport { BillingRefundRepository } from \"./repositories/refund.js\";\nimport { BillingInvoiceRepository } from \"./repositories/invoice.js\";\nimport { BillingDisputeRepository } from \"./repositories/dispute.js\";\nimport { BillingPreferencesRepository } from \"./repositories/preferences.js\";\nimport { BillingAutoRechargeRepository } from \"./repositories/auto-recharge.js\";\nimport { BillingSubscriptionChangeRepository } from \"./repositories/subscription-change.js\";\n\nconst PgSafeMinorUnitsSchema = z\n .union([z.string().regex(/^\\d+$/), z.number().int().nonnegative().safe()])\n .transform(Number)\n .refine(Number.isSafeInteger, \"minor-unit amount exceeds JavaScript's safe integer range\");\n\nconst BillingCreditPostingRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n balance_after: z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .nullable()\n .transform((value) => (value === null ? null : new Decimal(value))),\n replayed: pgBoolean,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.error_code === null && (row.ledger_entry_id === null || row.balance_after === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"successful posting requires ledger_entry_id and balance_after\",\n });\n }\n });\n\nconst CheckoutIntentRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n checkout_kind: z.enum([\"subscription\", \"credit_topup\"]),\n product_key: z.string().min(1),\n request_digest: z.instanceof(Uint8Array).refine((value) => value.byteLength === 32),\n status: z.enum([\"open\", \"completed\", \"failed\", \"expired\"]),\n provider_session_id: z.string().min(1).nullable(),\n checkout_url: z.string().min(1).nullable(),\n expires_at: z.union([z.string().datetime({ offset: true }), z.date()]),\n })\n .strict();\n\nfunction billingCreditPostingResult(\n rows: readonly unknown[] | null | undefined,\n context: string,\n): BillingCreditPostingResult {\n const raw = requireRecordRow(rows, context);\n const row = safeParse(\n BillingCreditPostingRowSchema,\n {\n ledger_entry_id: raw.ledger_entry_id,\n balance_after: raw.balance_after,\n replayed: raw.replayed,\n error_code: raw.error_code,\n },\n context,\n { indeterminate: true },\n );\n return {\n ledgerEntryId: row.ledger_entry_id,\n balanceAfter: row.balance_after,\n replayed: row.replayed,\n errorCode: row.error_code,\n };\n}\n\nexport interface PostgresBillingStoreOptions extends Omit<\n PostgresConnectionOptions,\n \"providerEnvironment\"\n> {\n /** PostgreSQL connection string or an application-owned pool. */\n postgres: PostgresPool | string;\n /** Tenant UUID bound to every store transaction. */\n tenantId: string;\n /** Explicit financial namespace; billing stores never guess live vs test. */\n providerEnvironment: ProviderEnvironment;\n /** Injectable `pg.Pool` constructor for custom runtimes and tests. */\n poolConstructor?: PostgresPoolConstructor;\n billingPayloadBackend?: \"postgres\" | \"s3\";\n}\n\nexport class PostgresBillingStore extends BillingStore {\n private readonly postgres: PostgresClient;\n readonly providerEnvironment: ProviderEnvironment;\n\n private _offer: BillingOfferRepository | null = null;\n private _topup: BillingTopupRepository | null = null;\n private _customer: BillingCustomerRepository | null = null;\n private _subscription: BillingSubscriptionRepository | null = null;\n private _event: BillingEventRepository | null = null;\n private _payment: BillingPaymentRepository | null = null;\n private _refund: BillingRefundRepository | null = null;\n private _invoice: BillingInvoiceRepository | null = null;\n private _dispute: BillingDisputeRepository | null = null;\n private _preferences: BillingPreferencesRepository | null = null;\n private _autoRecharge: BillingAutoRechargeRepository | null = null;\n private _subscriptionChange: BillingSubscriptionChangeRepository | null = null;\n constructor(options: PostgresBillingStoreOptions) {\n super();\n if (typeof options !== \"object\" || options === null) {\n throw new TypeError(\"PostgresBillingStore options are required\");\n }\n if (typeof options.postgres !== \"string\" && options.poolConstructor !== undefined) {\n throw new TypeError(\"poolConstructor cannot be used with an existing PostgreSQL pool\");\n }\n const providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);\n this.providerEnvironment = providerEnvironment;\n this.postgres = new PostgresClient(options.postgres, {\n tenantId: options.tenantId,\n providerEnvironment,\n poolConstructor: options.poolConstructor,\n billingPayloadBackend: options.billingPayloadBackend,\n connectionTimeoutMs: options.connectionTimeoutMs,\n statementTimeoutMs: options.statementTimeoutMs,\n idleTransactionTimeoutMs: options.idleTransactionTimeoutMs,\n idleTimeoutMs: options.idleTimeoutMs,\n maxConnections: options.maxConnections,\n applicationName: options.applicationName,\n onPoolError: options.onPoolError,\n closedError: () => new StoreClosedError(\"Billing store has been closed\"),\n });\n }\n\n async close(): Promise<void> {\n await this.postgres.close();\n }\n\n private get queryFn(): QueryFn {\n return this.postgres.query;\n }\n\n private get billingOffer(): BillingOfferRepository {\n if (!this._offer) this._offer = new BillingOfferRepository(this.queryFn);\n return this._offer;\n }\n\n private get billingTopup(): BillingTopupRepository {\n if (!this._topup) this._topup = new BillingTopupRepository(this.queryFn);\n return this._topup;\n }\n\n private get billingCustomer(): BillingCustomerRepository {\n if (!this._customer) this._customer = new BillingCustomerRepository(this.queryFn);\n return this._customer;\n }\n\n private get billingSubscription(): BillingSubscriptionRepository {\n if (!this._subscription) this._subscription = new BillingSubscriptionRepository(this.queryFn);\n return this._subscription;\n }\n\n private get billingEvent(): BillingEventRepository {\n if (!this._event) this._event = new BillingEventRepository(this.queryFn);\n return this._event;\n }\n\n private get billingPayment(): BillingPaymentRepository {\n if (!this._payment) this._payment = new BillingPaymentRepository(this.queryFn);\n return this._payment;\n }\n\n private get billingRefund(): BillingRefundRepository {\n if (!this._refund) this._refund = new BillingRefundRepository(this.queryFn);\n return this._refund;\n }\n\n private get billingInvoice(): BillingInvoiceRepository {\n if (!this._invoice) this._invoice = new BillingInvoiceRepository(this.queryFn);\n return this._invoice;\n }\n\n private get billingDispute(): BillingDisputeRepository {\n if (!this._dispute) this._dispute = new BillingDisputeRepository(this.queryFn);\n return this._dispute;\n }\n\n private get billingPreferences(): BillingPreferencesRepository {\n if (!this._preferences) this._preferences = new BillingPreferencesRepository(this.queryFn);\n return this._preferences;\n }\n\n private get billingAutoRecharge(): BillingAutoRechargeRepository {\n if (!this._autoRecharge) this._autoRecharge = new BillingAutoRechargeRepository(this.queryFn);\n return this._autoRecharge;\n }\n\n private get billingSubscriptionChange(): BillingSubscriptionChangeRepository {\n if (!this._subscriptionChange) {\n this._subscriptionChange = new BillingSubscriptionChangeRepository(this.queryFn);\n }\n return this._subscriptionChange;\n }\n\n async createOrGetCheckoutIntent(input: CheckoutIntentCreate): Promise<CheckoutIntent> {\n const operationKey = requireStableKey(input.operationKey, \"operationKey\");\n if (!/^[0-9a-fA-F]{64}$/.test(input.requestDigest)) {\n throw new TypeError(\"requestDigest must be a 32-byte hex string\");\n }\n const rows = await this.queryFn(\n `SELECT bursar.create_checkout_intent(\n $1::uuid, $2, $3, $4, $5, decode($6, 'hex'), $7::timestamptz\n ) AS id`,\n [\n input.subjectId,\n input.provider,\n operationKey,\n input.checkoutKind,\n input.productKey,\n input.requestDigest,\n input.expiresAt,\n ],\n );\n const id = requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createOrGetCheckoutIntent\",\n );\n const intent = await this.getCheckoutIntent(id, input.subjectId);\n if (!intent) {\n throw new StoreError(\"checkout intent could not be read after creation\", {\n indeterminate: true,\n details: { checkoutIntentId: id },\n });\n }\n return intent;\n }\n\n async updateCheckoutIntent(id: string, update: CheckoutIntentUpdate): Promise<void> {\n const rows = await this.queryFn(\n `SELECT bursar.advance_checkout_intent($1::uuid, $2, $3, $4) AS advanced`,\n [id, update.status ?? null, update.providerSessionId ?? null, update.checkoutUrl ?? null],\n );\n if (\n !requireResultField(rows, \"advanced\", pgBoolean, \"PostgresBillingStore.updateCheckoutIntent\")\n ) {\n throw new StoreError(`checkout intent transition rejected: ${id}`, {\n details: { checkoutIntentId: id },\n });\n }\n }\n\n async getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_checkout_intent($1::uuid, $2::uuid)`,\n [id, subjectId],\n );\n if (rows.length === 0) return null;\n if (rows.length !== 1) {\n throw new StoreError(\"getCheckoutIntent: expected at most one row\", {\n details: { rowCount: rows.length, checkoutIntentId: id },\n });\n }\n const row = rows[0] as Record<string, unknown>;\n return this.rowToCheckoutIntent(\n safeParse(\n CheckoutIntentRowSchema,\n {\n id: row.id,\n subject_id: row.subject_id,\n provider: row.provider,\n checkout_kind: row.checkout_kind,\n product_key: row.product_key,\n request_digest: row.request_digest,\n status: row.status,\n provider_session_id: row.provider_session_id,\n checkout_url: row.checkout_url,\n expires_at: row.expires_at,\n },\n \"PostgresBillingStore.getCheckoutIntent\",\n ),\n );\n }\n\n private rowToCheckoutIntent(row: z.infer<typeof CheckoutIntentRowSchema>): CheckoutIntent {\n return {\n id: row.id,\n subjectId: row.subject_id,\n provider: row.provider,\n checkoutKind: row.checkout_kind,\n productKey: row.product_key,\n requestDigest: Buffer.from(row.request_digest).toString(\"hex\"),\n status: row.status,\n providerSessionId: row.provider_session_id,\n checkoutUrl: row.checkout_url,\n expiresAt: row.expires_at instanceof Date ? row.expires_at.toISOString() : row.expires_at,\n };\n }\n\n private rowToOffer(row: BillingOfferRow | null): BillingOfferResult | null {\n if (!row) return null;\n return {\n offerId: row.id,\n offerKey: row.offerKey,\n planId: row.planId,\n plan: row.plan,\n interval: row.interval,\n intervalCount: row.intervalCount,\n grant:\n row.grantCredits === null\n ? null\n : {\n mode: \"cycle_grant\",\n credits: row.grantCredits,\n bucket: row.grantBucket,\n replacePrior: row.grantReplacePrior,\n },\n };\n }\n\n async resolveBillingOffer(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByPrice(provider, priceId ?? null, productId ?? null);\n return this.rowToOffer(r);\n }\n\n async resolveBillingOfferByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByLookup(provider, lookupKey);\n return this.rowToOffer(r);\n }\n\n async claimBillingEvent(\n provider: string,\n eventId: string,\n eventType: string,\n envelope?: Record<string, unknown>,\n ): Promise<BillingEventClaim> {\n const result = await this.billingEvent.claim(\n provider,\n eventId,\n eventType,\n JSON.stringify(envelope ?? { eventType }),\n );\n if (result.status === \"claimed\") {\n if (result.claim_token === null || result.event_id === null) {\n throw new StoreError(\"Billing event claim returned no claim identifiers\", {\n details: { provider, eventId },\n });\n }\n return {\n status: \"claimed\" as const,\n claimToken: result.claim_token,\n billingEventId: result.event_id,\n };\n }\n if (result.status === \"duplicate\") return { status: \"duplicate\" as const };\n if (result.status === \"busy\") return { status: \"busy\" as const };\n if (result.status === \"invalid_request\") return { status: \"invalid_request\" as const };\n if (result.status === \"idempotency_conflict\" || result.status === \"max_retries_exceeded\") {\n if (result.event_id === null) {\n throw new StoreError(\"Billing event terminal claim returned no event identifier\", {\n details: { provider, eventId, status: result.status },\n });\n }\n return { status: result.status, billingEventId: result.event_id };\n }\n throw new StoreError(\"Billing event claim returned an unsupported status\", {\n details: { provider, eventId, status: result.status },\n });\n }\n\n async completeBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n ): Promise<boolean> {\n return this.billingEvent.complete(provider, eventId, claimToken);\n }\n\n async failBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n error?: string,\n ): Promise<boolean> {\n return this.billingEvent.fail(\n provider,\n eventId,\n claimToken,\n optionalBoundedDiagnosticMessage(error) ?? undefined,\n );\n }\n\n async upsertBillingCustomer(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email?: string | null,\n ): Promise<void> {\n await this.billingCustomer.upsert(provider, providerCustomerId, userId, email ?? null);\n }\n\n async upsertBillingSubscription(state: BillingSubscriptionState): Promise<void> {\n await this.billingSubscription.upsert(state);\n }\n\n async getBillingCustomer(provider: string, providerCustomerId: string): Promise<string | null> {\n return this.billingCustomer.get(provider, providerCustomerId);\n }\n\n async getBillingSubscription(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.get(provider, providerSubscriptionId);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async createBillingSubscriptionChange(\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n const subscription = await this.billingSubscription.get(\n input.provider,\n input.providerSubscriptionId,\n );\n if (!subscription?.id) {\n throw new StoreError(\"subscription change requires a persisted subscription\", {\n retryable: true,\n details: {\n provider: input.provider,\n providerSubscriptionId: input.providerSubscriptionId,\n },\n });\n }\n return this.billingSubscriptionChange.create(subscription.id, input);\n }\n\n async getOpenBillingSubscriptionChange(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.billingSubscriptionChange.getOpen(provider, providerSubscriptionId);\n }\n\n async listExpiredGraceSubscriptions(\n now: string,\n limit = 100,\n ): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.listExpiredGraceSubscriptions(now, limit);\n return rows.map((row) => this.rowToSubscriptionState(row));\n }\n\n async markSubscriptionGraceExpired(\n subscriptionId: string,\n expectedGraceEndsAt: string,\n expiredAt = new Date().toISOString(),\n ): Promise<boolean> {\n return this.billingSubscription.markGraceExpired(\n subscriptionId,\n expectedGraceEndsAt,\n expiredAt,\n );\n }\n\n async updateBillingSubscriptionChange(\n id: string,\n update: BillingSubscriptionChangeUpdate,\n ): Promise<void> {\n await this.billingSubscriptionChange.update(id, update);\n }\n\n async getUserSubscription(\n userId: string,\n statuses?: string[],\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.getUserSubscription(userId, statuses);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async getUserSubscriptions(userId: string): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.getUserSubscriptions(userId);\n return rows.map((r) => this.rowToSubscriptionState(r));\n }\n\n async recordSubscriptionConflict(input: BillingSubscriptionConflictCreate): Promise<void> {\n await this.billingSubscription.recordConflict(input);\n }\n\n async selectSubscriptionEntitlementSource(\n userId: string,\n provider: string,\n providerSubscriptionId?: string | null,\n ): Promise<boolean> {\n return this.billingSubscription.selectEntitlementSource(\n userId,\n provider,\n providerSubscriptionId,\n );\n }\n\n private rowToTopup(r: BillingTopupRow | null): BillingTopupResult | null {\n if (!r) return null;\n const minAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.min_quantity,\n \"PostgresBillingStore.rowToTopup.minAmountMinor\",\n );\n const maxAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.max_quantity,\n \"PostgresBillingStore.rowToTopup.maxAmountMinor\",\n );\n return {\n topupId: r.id,\n topupKey: r.topup_key,\n creditsPerUnit: r.credits_per_unit,\n depositTo: r.bucket_key,\n amountMinor: r.amount_minor,\n currency: r.currency,\n minQuantity: r.min_quantity,\n maxQuantity: r.max_quantity,\n defaultQuantity: r.default_quantity,\n minAmountMinor,\n maxAmountMinor,\n };\n }\n\n async resolveCreditTopup(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByPrice(provider, priceId ?? null, productId ?? null);\n return this.rowToTopup(r);\n }\n\n async resolveCreditTopupByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByLookup(provider, lookupKey);\n return this.rowToTopup(r);\n }\n\n async computeTopupCredits(\n amountMinor: number,\n topupConfig: BillingTopupResult,\n ): Promise<Decimal> {\n if (!Number.isSafeInteger(amountMinor) || amountMinor < 0) {\n throw new TypeError(\"amountMinor must be a non-negative safe integer\");\n }\n const unitAmount = topupConfig.amountMinor;\n if (unitAmount <= 0 || amountMinor % unitAmount !== 0) return new Decimal(0);\n const quantity = amountMinor / unitAmount;\n if (quantity < topupConfig.minQuantity || quantity > topupConfig.maxQuantity) {\n return new Decimal(0);\n }\n return topupConfig.creditsPerUnit.mul(quantity);\n }\n\n async upsertBillingPayment(options: BillingPaymentUpsert): Promise<string> {\n return this.billingPayment.upsert(\n options.provider,\n options.providerPaymentId,\n options.providerInvoiceId ?? null,\n options.userId,\n options.amountMinor,\n options.taxMinor,\n options.currency,\n options.purpose,\n options.metadata ? JSON.stringify(options.metadata) : null,\n options.status,\n options.providerUpdatedAt,\n );\n }\n\n async createBillingCreditGrant(input: BillingCreditGrantCreate): Promise<string> {\n const rows = await this.queryFn(\n \"SELECT bursar.create_billing_credit_grant($1::uuid, $2::uuid, $3::uuid, $4, $5, $6::uuid) AS id\",\n [\n input.paymentId ?? null,\n input.subscriptionId ?? null,\n input.topupId ?? null,\n input.configuredCredits.toString(),\n input.quantity,\n input.billingEventId ?? null,\n ],\n );\n return requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createBillingCreditGrant\",\n );\n }\n\n async grantBillingCredit(\n grantId: string,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.grant_billing_credit($1::uuid, $2)\", [\n grantId,\n idempotencyKey,\n ]);\n return billingCreditPostingResult(rows, \"PostgresBillingStore.grantBillingCredit\");\n }\n\n async getBillingCreditGrantByPayment(paymentId: string): Promise<string | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_billing_credit_grant_by_payment($1::uuid)`,\n [paymentId],\n );\n const row = optionalRecordRow(rows, \"PostgresBillingStore.getBillingCreditGrantByPayment\");\n return row === null\n ? null\n : safeParse(postgresUuid, row.id, \"PostgresBillingStore.getBillingCreditGrantByPayment.id\");\n }\n\n async postBillingRefund(\n refundId: string,\n grantId: string,\n amountMinor: number,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\n \"SELECT * FROM bursar.post_billing_refund($1::uuid, $2::uuid, $3, $4)\",\n [refundId, grantId, amountMinor, idempotencyKey],\n );\n return billingCreditPostingResult(rows, \"PostgresBillingStore.postBillingRefund\");\n }\n\n async upsertBillingRefund(options: BillingRefundUpsert): Promise<string> {\n return this.billingRefund.upsert(\n options.provider,\n options.providerRefundId,\n options.providerPaymentId,\n options.userId,\n options.amountMinor,\n options.currency,\n options.reason ?? null,\n options.metadata ? JSON.stringify(options.metadata) : null,\n options.status,\n options.providerUpdatedAt,\n );\n }\n\n async upsertBillingInvoice(options: BillingInvoiceUpsert): Promise<void> {\n const subscription = options.providerSubscriptionId\n ? await this.billingSubscription.get(options.provider, options.providerSubscriptionId)\n : null;\n if (options.providerSubscriptionId && !subscription) {\n throw new StoreError(\"invoice subscription is not available\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerInvoiceId: options.providerInvoiceId,\n providerSubscriptionId: options.providerSubscriptionId ?? null,\n },\n });\n }\n await this.billingInvoice.upsert(\n options.userId,\n options.provider,\n options.providerInvoiceId,\n subscription?.id ? String(subscription.id) : null,\n options.status,\n options.amountDueMinor,\n options.amountPaidMinor,\n options.currency,\n options.periodStart ?? null,\n options.periodEnd ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async listBillingInvoices(userId: string) {\n return this.billingInvoice.listForUser(userId);\n }\n\n async upsertBillingDispute(options: BillingDisputeUpsert): Promise<void> {\n const payment = await this.billingPayment.getForRefund(\n options.provider,\n options.providerPaymentId,\n );\n if (!payment?.id) {\n throw new StoreError(\"dispute payment is required\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerDisputeId: options.providerDisputeId,\n providerPaymentId: options.providerPaymentId ?? null,\n },\n });\n }\n await this.billingDispute.upsert(\n options.provider,\n options.providerDisputeId,\n String(payment.id),\n options.status,\n options.reason ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async getBillingPayment(\n provider: string,\n providerPaymentId: string,\n ): Promise<BillingPaymentRecord | null> {\n const row = await this.billingPayment.getForRefund(provider, providerPaymentId);\n if (!row) return null;\n return {\n id: row.id,\n provider: row.provider,\n providerPaymentId: row.provider_payment_id,\n providerInvoiceId: row.provider_invoice_id,\n userId: row.subject_id,\n amountMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.amount_minor,\n \"PostgresBillingStore.getBillingPayment.amountMinor\",\n ),\n taxMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.tax_minor,\n \"PostgresBillingStore.getBillingPayment.taxMinor\",\n ),\n currency: row.currency,\n purpose: row.purpose,\n status: row.status,\n providerUpdatedAt:\n row.provider_updated_at instanceof Date\n ? row.provider_updated_at.toISOString()\n : row.provider_updated_at,\n metadata: row.metadata,\n };\n }\n\n private rowToSubscriptionState(r: SubscriptionRow): BillingSubscriptionState {\n return {\n subscriptionId: r.id,\n userId: r.user_id,\n provider: r.provider,\n providerSubscriptionId: r.provider_subscription_id,\n providerCustomerId: r.provider_customer_id,\n offerId: r.offer_id,\n offerKey: r.offer_key,\n planId: r.plan_id,\n plan: r.plan,\n status: r.status,\n currentPeriodStart: r.current_period_start,\n currentPeriodEnd: r.current_period_end,\n trialEnd: r.trial_end,\n cancelAt: r.cancel_at,\n endedAt: r.ended_at,\n graceEndsAt: r.grace_ends_at,\n graceExpiredAt: r.grace_expired_at,\n providerUpdatedAt: r.provider_updated_at,\n cancelAtPeriodEnd: r.cancel_at_period_end,\n interval: r.interval,\n intervalCount: r.interval_count,\n metadata: r.metadata,\n };\n }\n\n async getActiveCatalogDocument(): Promise<Record<string, unknown> | null> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.active_catalog_revision()\", []);\n if (rows.length === 0) return null;\n if (rows.length !== 1 || typeof rows[0] !== \"object\" || rows[0] === null) {\n throw new StoreError(\"active catalog revision returned a malformed row\", {\n details: { rowCount: rows.length },\n });\n }\n return safeParse(\n z.record(z.string(), z.unknown()),\n (rows[0] as Record<string, unknown>).source_document,\n \"PostgresBillingStore.getActiveCatalogDocument\",\n );\n }\n\n async pseudonymizeFinancialSubject(userId: string): Promise<boolean> {\n const rows = await this.queryFn(\n `SELECT bursar.pseudonymize_financial_subject($1::uuid) AS pseudonymized`,\n [userId],\n );\n return requireResultField(\n rows,\n \"pseudonymized\",\n pgBoolean,\n \"PostgresBillingStore.pseudonymizeFinancialSubject\",\n );\n }\n\n async getBillingPreferences(userId: string): Promise<BillingPreferences | null> {\n return this.billingPreferences.get(userId);\n }\n\n async upsertBillingPreferences(prefs: BillingPreferences): Promise<void> {\n await this.billingPreferences.upsert(prefs);\n }\n\n async getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n return this.billingAutoRecharge.getProfile(userId);\n }\n\n async upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void> {\n return this.billingAutoRecharge.upsertProfile(profile, options);\n }\n\n async claimAutoRechargeAttempt(\n input: AutoRechargeAttemptClaim,\n ): Promise<BillingAutoRechargeAttempt | null> {\n return this.billingAutoRecharge.claimAttempt(input);\n }\n\n async updateAutoRechargeAttempt(input: AutoRechargeAttemptUpdate): Promise<void> {\n return this.billingAutoRecharge.updateAttempt(input);\n }\n\n async updateAutoRechargeAttemptByProviderPayment(\n input: AutoRechargeProviderPaymentUpdate,\n ): Promise<void> {\n return this.billingAutoRecharge.updateAttemptByProviderPayment(input);\n }\n\n async countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number> {\n return this.billingAutoRecharge.countAttempts(userId, since);\n }\n\n async getBillingCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null> {\n const result = await this.billingCustomer.getByUserId(userId, provider ?? null);\n if (!result) return null;\n return {\n provider: result.provider,\n providerCustomerId: result.providerCustomerId,\n };\n }\n}\n"]}
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../../src/billing/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAmBxB,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAgBnD,OAAO,EACL,cAAc,GAIf,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,4BAA4B,GAE7B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC/D,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAC/D,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,SAAS,GACV,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,sBAAsB,EAAwB,MAAM,yBAAyB,CAAC;AACvF,OAAO,EAAE,sBAAsB,EAAwB,MAAM,yBAAyB,CAAC;AACvF,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EACL,6BAA6B,GAE9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AACjE,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,4BAA4B,EAAE,MAAM,+BAA+B,CAAC;AAC7E,OAAO,EAAE,6BAA6B,EA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from \"zod\";\nimport type { JsonObject, PostgresValue } from \"../../shared/json.js\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeProfile,\n BillingCreditPostingResult,\n BillingCustomerRecord,\n BillingEventClaim,\n BillingOfferResult,\n BillingPaymentRecord,\n BillingPreferences,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionState,\n BillingSubscriptionStatus,\n SubscriptionEntitlementOutcome,\n CheckoutIntent,\n BillingTopupResult,\n} from \"../types/index.js\";\nimport { BillingStore } from \"../billing-store.js\";\nimport type {\n AutoRechargeAttemptClaim,\n AutoRechargeAttemptUpdate,\n AutoRechargeProviderPaymentUpdate,\n BillingCreditGrantCreate,\n BillingDisputeUpsert,\n BillingInvoiceUpsert,\n BillingPaymentUpsert,\n BillingRefundUpsert,\n BillingSubscriptionChangeUpdate,\n BillingSubscriptionConflictCreate,\n CheckoutIntentCreate,\n CheckoutIntentUpdate,\n} from \"../contracts.js\";\nimport type { QueryFn } from \"../../shared/postgres-types.js\";\nimport {\n PostgresClient,\n type PostgresConnectionOptions,\n type PostgresPool,\n type PostgresPoolConstructor,\n} from \"../../shared/postgres-client.js\";\nimport {\n normalizeProviderEnvironment,\n type ProviderEnvironment,\n} from \"../../providers/environment.js\";\nimport { StoreClosedError, StoreError } from \"../../errors.js\";\nimport { optionalBoundedDiagnosticMessage } from \"../../shared/diagnostics.js\";\nimport { requireStableKey } from \"../../shared/idempotency.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireRecordRow,\n requireResultField,\n safeParse,\n} from \"../../shared/postgres-validation.js\";\nimport { BillingOfferRepository, type BillingOfferRow } from \"./repositories/offer.js\";\nimport { BillingTopupRepository, type BillingTopupRow } from \"./repositories/topup.js\";\nimport { BillingCustomerRepository } from \"./repositories/customer.js\";\nimport {\n BillingSubscriptionRepository,\n type SubscriptionRow,\n} from \"./repositories/subscription.js\";\nimport { BillingEventRepository } from \"./repositories/event.js\";\nimport { BillingPaymentRepository } from \"./repositories/payment.js\";\nimport { BillingRefundRepository } from \"./repositories/refund.js\";\nimport { BillingInvoiceRepository } from \"./repositories/invoice.js\";\nimport { BillingDisputeRepository } from \"./repositories/dispute.js\";\nimport { BillingPreferencesRepository } from \"./repositories/preferences.js\";\nimport { BillingAutoRechargeRepository } from \"./repositories/auto-recharge.js\";\nimport { BillingSubscriptionChangeRepository } from \"./repositories/subscription-change.js\";\n\nconst PgSafeMinorUnitsSchema = z\n .union([z.string().regex(/^\\d+$/), z.number().int().nonnegative().safe()])\n .transform(Number)\n .refine(Number.isSafeInteger, \"minor-unit amount exceeds JavaScript's safe integer range\");\n\nconst BillingCreditPostingRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n balance_after: z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .nullable()\n .transform((value) => (value === null ? null : new Decimal(value))),\n replayed: pgBoolean,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.error_code === null && (row.ledger_entry_id === null || row.balance_after === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"successful posting requires ledger_entry_id and balance_after\",\n });\n }\n });\n\nconst CheckoutIntentRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n checkout_kind: z.enum([\"subscription\", \"credit_topup\"]),\n product_key: z.string().min(1),\n request_digest: z.instanceof(Uint8Array).refine((value) => value.byteLength === 32),\n status: z.enum([\"open\", \"completed\", \"failed\", \"expired\"]),\n provider_session_id: z.string().min(1).nullable(),\n checkout_url: z.string().min(1).nullable(),\n expires_at: z.union([z.string().datetime({ offset: true }), z.date()]),\n })\n .strict();\n\nfunction billingCreditPostingResult(\n rows: readonly PostgresValue[] | null | undefined,\n context: string,\n): BillingCreditPostingResult {\n const raw = requireRecordRow(rows, context);\n const row = safeParse(\n BillingCreditPostingRowSchema,\n {\n ledger_entry_id: raw.ledger_entry_id,\n balance_after: raw.balance_after,\n replayed: raw.replayed,\n error_code: raw.error_code,\n },\n context,\n { indeterminate: true },\n );\n return {\n ledgerEntryId: row.ledger_entry_id,\n balanceAfter: row.balance_after,\n replayed: row.replayed,\n errorCode: row.error_code,\n };\n}\n\nexport interface PostgresBillingStoreOptions extends Omit<\n PostgresConnectionOptions,\n \"providerEnvironment\"\n> {\n /** PostgreSQL connection string or an application-owned pool. */\n postgres: PostgresPool | string;\n /** Tenant UUID bound to every store transaction. */\n tenantId: string;\n /** Explicit financial namespace; billing stores never guess live vs test. */\n providerEnvironment: ProviderEnvironment;\n /** Injectable `pg.Pool` constructor for custom runtimes and tests. */\n poolConstructor?: PostgresPoolConstructor;\n billingPayloadBackend?: \"postgres\" | \"s3\";\n}\n\nexport class PostgresBillingStore extends BillingStore {\n private readonly postgres: PostgresClient;\n readonly providerEnvironment: ProviderEnvironment;\n\n private _offer: BillingOfferRepository | null = null;\n private _topup: BillingTopupRepository | null = null;\n private _customer: BillingCustomerRepository | null = null;\n private _subscription: BillingSubscriptionRepository | null = null;\n private _event: BillingEventRepository | null = null;\n private _payment: BillingPaymentRepository | null = null;\n private _refund: BillingRefundRepository | null = null;\n private _invoice: BillingInvoiceRepository | null = null;\n private _dispute: BillingDisputeRepository | null = null;\n private _preferences: BillingPreferencesRepository | null = null;\n private _autoRecharge: BillingAutoRechargeRepository | null = null;\n private _subscriptionChange: BillingSubscriptionChangeRepository | null = null;\n constructor(options: PostgresBillingStoreOptions) {\n super();\n if (!z.object({}).safeParse(options).success) {\n throw new TypeError(\"PostgresBillingStore options are required\");\n }\n if (!z.string().safeParse(options.postgres).success && options.poolConstructor !== undefined) {\n throw new TypeError(\"poolConstructor cannot be used with an existing PostgreSQL pool\");\n }\n const providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);\n this.providerEnvironment = providerEnvironment;\n this.postgres = new PostgresClient(options.postgres, {\n tenantId: options.tenantId,\n providerEnvironment,\n poolConstructor: options.poolConstructor,\n billingPayloadBackend: options.billingPayloadBackend,\n connectionTimeoutMs: options.connectionTimeoutMs,\n statementTimeoutMs: options.statementTimeoutMs,\n idleTransactionTimeoutMs: options.idleTransactionTimeoutMs,\n idleTimeoutMs: options.idleTimeoutMs,\n maxConnections: options.maxConnections,\n applicationName: options.applicationName,\n onPoolError: options.onPoolError,\n closedError: () => new StoreClosedError(\"Billing store has been closed\"),\n });\n }\n\n async close(): Promise<void> {\n await this.postgres.close();\n }\n\n private get queryFn(): QueryFn {\n return this.postgres.query;\n }\n\n private get billingOffer(): BillingOfferRepository {\n if (!this._offer) this._offer = new BillingOfferRepository(this.queryFn);\n return this._offer;\n }\n\n private get billingTopup(): BillingTopupRepository {\n if (!this._topup) this._topup = new BillingTopupRepository(this.queryFn);\n return this._topup;\n }\n\n private get billingCustomer(): BillingCustomerRepository {\n if (!this._customer) this._customer = new BillingCustomerRepository(this.queryFn);\n return this._customer;\n }\n\n private get billingSubscription(): BillingSubscriptionRepository {\n if (!this._subscription) this._subscription = new BillingSubscriptionRepository(this.queryFn);\n return this._subscription;\n }\n\n private get billingEvent(): BillingEventRepository {\n if (!this._event) this._event = new BillingEventRepository(this.queryFn);\n return this._event;\n }\n\n private get billingPayment(): BillingPaymentRepository {\n if (!this._payment) this._payment = new BillingPaymentRepository(this.queryFn);\n return this._payment;\n }\n\n private get billingRefund(): BillingRefundRepository {\n if (!this._refund) this._refund = new BillingRefundRepository(this.queryFn);\n return this._refund;\n }\n\n private get billingInvoice(): BillingInvoiceRepository {\n if (!this._invoice) this._invoice = new BillingInvoiceRepository(this.queryFn);\n return this._invoice;\n }\n\n private get billingDispute(): BillingDisputeRepository {\n if (!this._dispute) this._dispute = new BillingDisputeRepository(this.queryFn);\n return this._dispute;\n }\n\n private get billingPreferences(): BillingPreferencesRepository {\n if (!this._preferences) this._preferences = new BillingPreferencesRepository(this.queryFn);\n return this._preferences;\n }\n\n private get billingAutoRecharge(): BillingAutoRechargeRepository {\n if (!this._autoRecharge) this._autoRecharge = new BillingAutoRechargeRepository(this.queryFn);\n return this._autoRecharge;\n }\n\n private get billingSubscriptionChange(): BillingSubscriptionChangeRepository {\n if (!this._subscriptionChange) {\n this._subscriptionChange = new BillingSubscriptionChangeRepository(this.queryFn);\n }\n return this._subscriptionChange;\n }\n\n async createOrGetCheckoutIntent(input: CheckoutIntentCreate): Promise<CheckoutIntent> {\n const operationKey = requireStableKey(input.operationKey, \"operationKey\");\n if (!/^[0-9a-fA-F]{64}$/.test(input.requestDigest)) {\n throw new TypeError(\"requestDigest must be a 32-byte hex string\");\n }\n const rows = await this.queryFn(\n `SELECT bursar.create_checkout_intent(\n $1::uuid, $2, $3, $4, $5, decode($6, 'hex'), $7::timestamptz\n ) AS id`,\n [\n input.subjectId,\n input.provider,\n operationKey,\n input.checkoutKind,\n input.productKey,\n input.requestDigest,\n input.expiresAt,\n ],\n );\n const id = requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createOrGetCheckoutIntent\",\n );\n const intent = await this.getCheckoutIntent(id, input.subjectId);\n if (!intent) {\n throw new StoreError(\"checkout intent could not be read after creation\", {\n indeterminate: true,\n details: { checkoutIntentId: id },\n });\n }\n return intent;\n }\n\n async updateCheckoutIntent(id: string, update: CheckoutIntentUpdate): Promise<void> {\n const rows = await this.queryFn(\n `SELECT bursar.advance_checkout_intent($1::uuid, $2, $3, $4) AS advanced`,\n [id, update.status ?? null, update.providerSessionId ?? null, update.checkoutUrl ?? null],\n );\n if (\n !requireResultField(rows, \"advanced\", pgBoolean, \"PostgresBillingStore.updateCheckoutIntent\")\n ) {\n throw new StoreError(`checkout intent transition rejected: ${id}`, {\n details: { checkoutIntentId: id },\n });\n }\n }\n\n async getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_checkout_intent($1::uuid, $2::uuid)`,\n [id, subjectId],\n );\n if (rows.length === 0) return null;\n if (rows.length !== 1) {\n throw new StoreError(\"getCheckoutIntent: expected at most one row\", {\n details: { rowCount: rows.length, checkoutIntentId: id },\n });\n }\n const row = rows[0];\n if (!row) throw new StoreError(\"getCheckoutIntent: expected one row\");\n return this.rowToCheckoutIntent(\n safeParse(\n CheckoutIntentRowSchema,\n {\n id: row.id,\n subject_id: row.subject_id,\n provider: row.provider,\n checkout_kind: row.checkout_kind,\n product_key: row.product_key,\n request_digest: row.request_digest,\n status: row.status,\n provider_session_id: row.provider_session_id,\n checkout_url: row.checkout_url,\n expires_at: row.expires_at,\n },\n \"PostgresBillingStore.getCheckoutIntent\",\n ),\n );\n }\n\n private rowToCheckoutIntent(row: z.infer<typeof CheckoutIntentRowSchema>): CheckoutIntent {\n return {\n id: row.id,\n subjectId: row.subject_id,\n provider: row.provider,\n checkoutKind: row.checkout_kind,\n productKey: row.product_key,\n requestDigest: Buffer.from(row.request_digest).toString(\"hex\"),\n status: row.status,\n providerSessionId: row.provider_session_id,\n checkoutUrl: row.checkout_url,\n expiresAt: row.expires_at instanceof Date ? row.expires_at.toISOString() : row.expires_at,\n };\n }\n\n private rowToOffer(row: BillingOfferRow | null): BillingOfferResult | null {\n if (!row) return null;\n return {\n offerId: row.id,\n offerKey: row.offerKey,\n planId: row.planId,\n plan: row.plan,\n interval: row.interval,\n intervalCount: row.intervalCount,\n grant:\n row.grantCredits === null\n ? null\n : {\n mode: \"cycle_grant\",\n credits: row.grantCredits,\n bucket: row.grantBucket,\n replacePrior: row.grantReplacePrior,\n },\n };\n }\n\n async resolveBillingOffer(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByPrice(provider, priceId ?? null, productId ?? null);\n return this.rowToOffer(r);\n }\n\n async resolveBillingOfferByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByLookup(provider, lookupKey);\n return this.rowToOffer(r);\n }\n\n async claimBillingEvent(\n provider: string,\n eventId: string,\n eventType: string,\n envelope?: JsonObject,\n ): Promise<BillingEventClaim> {\n const result = await this.billingEvent.claim(\n provider,\n eventId,\n eventType,\n JSON.stringify(envelope ?? { eventType }),\n );\n if (result.status === \"claimed\") {\n if (result.claim_token === null || result.event_id === null) {\n throw new StoreError(\"Billing event claim returned no claim identifiers\", {\n details: { provider, eventId },\n });\n }\n return {\n status: \"claimed\" as const,\n claimToken: result.claim_token,\n billingEventId: result.event_id,\n };\n }\n if (result.status === \"duplicate\") return { status: \"duplicate\" as const };\n if (result.status === \"busy\") return { status: \"busy\" as const };\n if (result.status === \"invalid_request\") return { status: \"invalid_request\" as const };\n if (result.status === \"idempotency_conflict\" || result.status === \"max_retries_exceeded\") {\n if (result.event_id === null) {\n throw new StoreError(\"Billing event terminal claim returned no event identifier\", {\n details: { provider, eventId, status: result.status },\n });\n }\n return { status: result.status, billingEventId: result.event_id };\n }\n throw new StoreError(\"Billing event claim returned an unsupported status\", {\n details: { provider, eventId, status: result.status },\n });\n }\n\n async completeBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n ): Promise<boolean> {\n return this.billingEvent.complete(provider, eventId, claimToken);\n }\n\n async failBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n error?: string,\n ): Promise<boolean> {\n return this.billingEvent.fail(\n provider,\n eventId,\n claimToken,\n optionalBoundedDiagnosticMessage(error) ?? undefined,\n );\n }\n\n async upsertBillingCustomer(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email?: string | null,\n ): Promise<void> {\n await this.billingCustomer.upsert(provider, providerCustomerId, userId, email ?? null);\n }\n\n async upsertBillingSubscription(state: BillingSubscriptionState): Promise<void> {\n await this.billingSubscription.upsert(state);\n }\n\n async getBillingCustomer(provider: string, providerCustomerId: string): Promise<string | null> {\n return this.billingCustomer.get(provider, providerCustomerId);\n }\n\n async getBillingSubscription(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.get(provider, providerSubscriptionId);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async createBillingSubscriptionChange(\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n const subscription = await this.billingSubscription.get(\n input.provider,\n input.providerSubscriptionId,\n );\n if (!subscription?.id) {\n throw new StoreError(\"subscription change requires a persisted subscription\", {\n retryable: true,\n details: {\n provider: input.provider,\n providerSubscriptionId: input.providerSubscriptionId,\n },\n });\n }\n return this.billingSubscriptionChange.create(subscription.id, input);\n }\n\n async getOpenBillingSubscriptionChange(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.billingSubscriptionChange.getOpen(provider, providerSubscriptionId);\n }\n\n async listExpiredGraceSubscriptions(\n now: string,\n limit = 100,\n ): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.listExpiredGraceSubscriptions(now, limit);\n return rows.map((row) => this.rowToSubscriptionState(row));\n }\n\n async reconcileSubscriptionEntitlement(\n subjectId: string,\n subscriptionId: string,\n billingEventId: string,\n expectedStatus: BillingSubscriptionStatus,\n expectedProviderUpdatedAt: string,\n planAssignedAt: Date | string | null,\n applyEntitlement: boolean,\n terminalPlanKey: string | null,\n reason: string,\n ): Promise<SubscriptionEntitlementOutcome> {\n return this.billingSubscription.reconcileEntitlement(\n subjectId,\n subscriptionId,\n billingEventId,\n expectedStatus,\n expectedProviderUpdatedAt,\n planAssignedAt,\n applyEntitlement,\n terminalPlanKey,\n reason,\n );\n }\n\n async expireSubscriptionGracePeriod(\n subjectId: string,\n subscriptionId: string,\n expectedGraceEndsAt: string,\n expiredAt: string,\n terminalPlanKey: string | null,\n ): Promise<boolean> {\n return this.billingSubscription.expireGracePeriod(\n subjectId,\n subscriptionId,\n expectedGraceEndsAt,\n expiredAt,\n terminalPlanKey,\n );\n }\n\n async updateBillingSubscriptionChange(\n id: string,\n update: BillingSubscriptionChangeUpdate,\n ): Promise<void> {\n await this.billingSubscriptionChange.update(id, update);\n }\n\n async getUserSubscription(\n userId: string,\n statuses?: string[],\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.getUserSubscription(userId, statuses);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async getUserSubscriptions(userId: string): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.getUserSubscriptions(userId);\n return rows.map((r) => this.rowToSubscriptionState(r));\n }\n\n async recordSubscriptionConflict(input: BillingSubscriptionConflictCreate): Promise<void> {\n await this.billingSubscription.recordConflict(input);\n }\n\n private rowToTopup(r: BillingTopupRow | null): BillingTopupResult | null {\n if (!r) return null;\n const minAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.min_quantity,\n \"PostgresBillingStore.rowToTopup.minAmountMinor\",\n );\n const maxAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.max_quantity,\n \"PostgresBillingStore.rowToTopup.maxAmountMinor\",\n );\n return {\n topupId: r.id,\n topupKey: r.topup_key,\n creditsPerUnit: r.credits_per_unit,\n depositTo: r.bucket_key,\n amountMinor: r.amount_minor,\n currency: r.currency,\n minQuantity: r.min_quantity,\n maxQuantity: r.max_quantity,\n defaultQuantity: r.default_quantity,\n minAmountMinor,\n maxAmountMinor,\n };\n }\n\n async resolveCreditTopup(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByPrice(provider, priceId ?? null, productId ?? null);\n return this.rowToTopup(r);\n }\n\n async resolveCreditTopupByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByLookup(provider, lookupKey);\n return this.rowToTopup(r);\n }\n\n async computeTopupCredits(\n amountMinor: number,\n topupConfig: BillingTopupResult,\n ): Promise<Decimal> {\n if (!Number.isSafeInteger(amountMinor) || amountMinor < 0) {\n throw new TypeError(\"amountMinor must be a non-negative safe integer\");\n }\n const unitAmount = topupConfig.amountMinor;\n if (unitAmount <= 0 || amountMinor % unitAmount !== 0) return new Decimal(0);\n const quantity = amountMinor / unitAmount;\n if (quantity < topupConfig.minQuantity || quantity > topupConfig.maxQuantity) {\n return new Decimal(0);\n }\n return topupConfig.creditsPerUnit.mul(quantity);\n }\n\n async upsertBillingPayment(options: BillingPaymentUpsert): Promise<string> {\n return this.billingPayment.upsert(\n options.provider,\n options.providerPaymentId,\n options.providerInvoiceId ?? null,\n options.userId,\n options.amountMinor,\n options.taxMinor,\n options.currency,\n options.purpose,\n options.metadata ? JSON.stringify(options.metadata) : null,\n options.status,\n options.providerUpdatedAt,\n );\n }\n\n async createBillingCreditGrant(input: BillingCreditGrantCreate): Promise<string> {\n const rows = await this.queryFn(\n \"SELECT bursar.create_billing_credit_grant($1::uuid, $2::uuid, $3::uuid, $4, $5, $6::uuid) AS id\",\n [\n input.paymentId ?? null,\n input.subscriptionId ?? null,\n input.topupId ?? null,\n input.configuredCredits.toString(),\n input.quantity,\n input.billingEventId ?? null,\n ],\n );\n return requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createBillingCreditGrant\",\n );\n }\n\n async grantBillingCredit(\n grantId: string,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.grant_billing_credit($1::uuid, $2)\", [\n grantId,\n idempotencyKey,\n ]);\n return billingCreditPostingResult(rows, \"PostgresBillingStore.grantBillingCredit\");\n }\n\n async getBillingCreditGrantByPayment(paymentId: string): Promise<string | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_billing_credit_grant_by_payment($1::uuid)`,\n [paymentId],\n );\n const row = optionalRecordRow(rows, \"PostgresBillingStore.getBillingCreditGrantByPayment\");\n return row === null\n ? null\n : safeParse(postgresUuid, row.id, \"PostgresBillingStore.getBillingCreditGrantByPayment.id\");\n }\n\n async postBillingRefund(\n refundId: string,\n grantId: string,\n amountMinor: number,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\n \"SELECT * FROM bursar.post_billing_refund($1::uuid, $2::uuid, $3, $4)\",\n [refundId, grantId, amountMinor, idempotencyKey],\n );\n return billingCreditPostingResult(rows, \"PostgresBillingStore.postBillingRefund\");\n }\n\n async upsertBillingRefund(options: BillingRefundUpsert): Promise<string> {\n return this.billingRefund.upsert(\n options.provider,\n options.providerRefundId,\n options.providerPaymentId,\n options.userId,\n options.amountMinor,\n options.currency,\n options.reason ?? null,\n options.metadata ? JSON.stringify(options.metadata) : null,\n options.status,\n options.providerUpdatedAt,\n );\n }\n\n async upsertBillingInvoice(options: BillingInvoiceUpsert): Promise<void> {\n const subscription = options.providerSubscriptionId\n ? await this.billingSubscription.get(options.provider, options.providerSubscriptionId)\n : null;\n if (options.providerSubscriptionId && !subscription) {\n throw new StoreError(\"invoice subscription is not available\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerInvoiceId: options.providerInvoiceId,\n providerSubscriptionId: options.providerSubscriptionId ?? null,\n },\n });\n }\n await this.billingInvoice.upsert(\n options.userId,\n options.provider,\n options.providerInvoiceId,\n subscription?.id ? String(subscription.id) : null,\n options.status,\n options.amountDueMinor,\n options.amountPaidMinor,\n options.currency,\n options.periodStart ?? null,\n options.periodEnd ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async listBillingInvoices(userId: string) {\n return this.billingInvoice.listForUser(userId);\n }\n\n async upsertBillingDispute(options: BillingDisputeUpsert): Promise<void> {\n const payment = await this.billingPayment.getForRefund(\n options.provider,\n options.providerPaymentId,\n );\n if (!payment?.id) {\n throw new StoreError(\"dispute payment is required\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerDisputeId: options.providerDisputeId,\n providerPaymentId: options.providerPaymentId ?? null,\n },\n });\n }\n await this.billingDispute.upsert(\n options.provider,\n options.providerDisputeId,\n String(payment.id),\n options.status,\n options.reason ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async getBillingPayment(\n provider: string,\n providerPaymentId: string,\n ): Promise<BillingPaymentRecord | null> {\n const row = await this.billingPayment.getForRefund(provider, providerPaymentId);\n if (!row) return null;\n return {\n id: row.id,\n provider: row.provider,\n providerPaymentId: row.provider_payment_id,\n providerInvoiceId: row.provider_invoice_id,\n userId: row.subject_id,\n amountMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.amount_minor,\n \"PostgresBillingStore.getBillingPayment.amountMinor\",\n ),\n taxMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.tax_minor,\n \"PostgresBillingStore.getBillingPayment.taxMinor\",\n ),\n currency: row.currency,\n purpose: row.purpose,\n status: row.status,\n providerUpdatedAt:\n row.provider_updated_at instanceof Date\n ? row.provider_updated_at.toISOString()\n : row.provider_updated_at,\n metadata: row.metadata,\n };\n }\n\n private rowToSubscriptionState(r: SubscriptionRow): BillingSubscriptionState {\n return {\n subscriptionId: r.id,\n userId: r.user_id,\n provider: r.provider,\n providerSubscriptionId: r.provider_subscription_id,\n providerCustomerId: r.provider_customer_id,\n offerId: r.offer_id,\n offerKey: r.offer_key,\n planId: r.plan_id,\n plan: r.plan,\n status: r.status,\n currentPeriodStart: r.current_period_start,\n currentPeriodEnd: r.current_period_end,\n trialEnd: r.trial_end,\n cancelAt: r.cancel_at,\n endedAt: r.ended_at,\n graceEndsAt: r.grace_ends_at,\n graceExpiredAt: r.grace_expired_at,\n providerUpdatedAt: r.provider_updated_at,\n cancelAtPeriodEnd: r.cancel_at_period_end,\n interval: r.interval,\n intervalCount: r.interval_count,\n metadata: r.metadata,\n };\n }\n\n async getActiveCatalogDocument(): Promise<JsonObject | null> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.active_catalog_revision()\", []);\n const row = optionalRecordRow(rows, \"PostgresBillingStore.getActiveCatalogDocument\");\n if (row === null) return null;\n const sourceDocument = row.source_document;\n if (sourceDocument === undefined) {\n throw new StoreError(\"active catalog revision returned no source document\");\n }\n return safeParse(\n z.record(z.string(), z.json()),\n sourceDocument,\n \"PostgresBillingStore.getActiveCatalogDocument\",\n );\n }\n\n async pseudonymizeFinancialSubject(userId: string): Promise<boolean> {\n const rows = await this.queryFn(\n `SELECT bursar.pseudonymize_financial_subject($1::uuid) AS pseudonymized`,\n [userId],\n );\n return requireResultField(\n rows,\n \"pseudonymized\",\n pgBoolean,\n \"PostgresBillingStore.pseudonymizeFinancialSubject\",\n );\n }\n\n async getBillingPreferences(userId: string): Promise<BillingPreferences | null> {\n return this.billingPreferences.get(userId);\n }\n\n async upsertBillingPreferences(prefs: BillingPreferences): Promise<void> {\n await this.billingPreferences.upsert(prefs);\n }\n\n async getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n return this.billingAutoRecharge.getProfile(userId);\n }\n\n async upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void> {\n return this.billingAutoRecharge.upsertProfile(profile, options);\n }\n\n async claimAutoRechargeAttempt(\n input: AutoRechargeAttemptClaim,\n ): Promise<BillingAutoRechargeAttempt | null> {\n return this.billingAutoRecharge.claimAttempt(input);\n }\n\n async updateAutoRechargeAttempt(input: AutoRechargeAttemptUpdate): Promise<void> {\n return this.billingAutoRecharge.updateAttempt(input);\n }\n\n async updateAutoRechargeAttemptByProviderPayment(\n input: AutoRechargeProviderPaymentUpdate,\n ): Promise<void> {\n return this.billingAutoRecharge.updateAttemptByProviderPayment(input);\n }\n\n async countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number> {\n return this.billingAutoRecharge.countAttempts(userId, since);\n }\n\n async getBillingCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null> {\n const result = await this.billingCustomer.getByUserId(userId, provider ?? null);\n if (!result) return null;\n return {\n provider: result.provider,\n providerCustomerId: result.providerCustomerId,\n };\n }\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import type { Decimal } from "decimal.js";
2
+ import type { JsonObject } from "../../shared/json.js";
2
3
  export declare const AUTO_RECHARGE_STATES: readonly ["disabled", "active", "paused"];
3
4
  export type BillingAutoRechargeState = (typeof AUTO_RECHARGE_STATES)[number];
4
5
  export type BillingAutoRechargeAttemptState = "claimed" | "submitted" | "processing" | "unknown" | "succeeded" | "failed" | "action_required";
@@ -33,7 +34,7 @@ export interface BillingAutoRechargeAttempt {
33
34
  currency: string | null;
34
35
  failureCode: string | null;
35
36
  failureMessage: string | null;
36
- metadata: Record<string, unknown>;
37
+ metadata: JsonObject;
37
38
  createdAt: string;
38
39
  updatedAt: string;
39
40
  }
@@ -1 +1 @@
1
- {"version":3,"file":"auto-recharge.d.ts","sourceRoot":"","sources":["../../../src/billing/types/auto-recharge.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1C,eAAO,MAAM,oBAAoB,2CAA4C,CAAC;AAC9E,MAAM,MAAM,wBAAwB,GAAG,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,CAAC;AAE7E,MAAM,MAAM,+BAA+B,GACzC,SAAS,GAAG,WAAW,GAAG,YAAY,GAAG,SAAS,GAAG,WAAW,GAAG,QAAQ,GAAG,iBAAiB,CAAC;AAElG,MAAM,WAAW,0BAA0B;IACzC,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,EAAE,wBAAwB,CAAC;IAChC,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,OAAO,CAAC;IACnB,mBAAmB,EAAE,MAAM,GAAG,IAAI,CAAC;IACnC,UAAU,EAAE,QAAQ,GAAG,QAAQ,GAAG,MAAM,GAAG,KAAK,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;IAC7E,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,UAAU,GAAG,SAAS,CAAC;IACrC,cAAc,EAAE,MAA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ge.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,UAAU,EAAE,QAAQ,EAAE,QAAQ,CAAU,CAAC","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\nexport const AUTO_RECHARGE_STATES = [\"disabled\", \"active\", \"paused\"] as const;\nexport type BillingAutoRechargeState = (typeof AUTO_RECHARGE_STATES)[number];\n\nexport type BillingAutoRechargeAttemptState =\n \"claimed\" | \"submitted\" | \"processing\" | \"unknown\" | \"succeeded\" | \"failed\" | \"action_required\";\n\nexport interface BillingAutoRechargeProfile {\n userId: string;\n enabled: boolean;\n state: BillingAutoRechargeState;\n armed?: boolean;\n provider: string | null;\n topupId: string | null;\n quantity: number;\n threshold: Decimal;\n maxChargesPerWindow: number | null;\n windowUnit: \"second\" | \"minute\" | \"hour\" | \"day\" | \"week\" | \"month\" | \"year\";\n windowCount: number;\n windowAnchor: \"calendar\" | \"rolling\";\n windowTimezone: string;\n updatedAt?: string | null;\n}\n\nexport interface BillingAutoRechargeAttempt {\n id: string;\n userId: string;\n provider: string;\n idempotencyKey: string;\n providerAttemptId: string | null;\n topupId: string;\n quantity: number;\n state: BillingAutoRechargeAttemptState;\n windowStart: string;\n windowEnd: string;\n quotedAmountMinor: number | null;\n currency: string | null;\n failureCode: string | null;\n failureMessage: string | null;\n metadata: Record<string, unknown>;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface BillingAutoRechargeStatus {\n enabled: boolean;\n state: BillingAutoRechargeState;\n thresholdCredits: Decimal;\n topupKey: string;\n quantity: number;\n maxRecharges: number;\n windowStart: string;\n windowEnd: string;\n rechargesInWindow: number;\n paymentMethodId: string | null;\n paymentMethodLast4: string | null;\n paymentMethodBrand: string | null;\n suspendedReason: string | null;\n pendingAttemptId: string | null;\n quoteAmountMinor: number | null;\n quoteCurrency: string | null;\n}\n"]}
1
+ {"version":3,"file":"auto-recharge.js","sourceRoot":"","sources":["../../../src/billing/types/auto-recharge.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,UAAU,EAAE,QAAQ,EAAE,QAAQ,CAAU,CAAC","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport type { JsonObject } from \"../../shared/json.js\";\n\nexport const AUTO_RECHARGE_STATES = [\"disabled\", \"active\", \"paused\"] as const;\nexport type BillingAutoRechargeState = (typeof AUTO_RECHARGE_STATES)[number];\n\nexport type BillingAutoRechargeAttemptState =\n | \"claimed\"\n | \"submitted\"\n | \"processing\"\n | \"unknown\"\n | \"succeeded\"\n | \"failed\"\n | \"action_required\";\n\nexport interface BillingAutoRechargeProfile {\n userId: string;\n enabled: boolean;\n state: BillingAutoRechargeState;\n armed?: boolean;\n provider: string | null;\n topupId: string | null;\n quantity: number;\n threshold: Decimal;\n maxChargesPerWindow: number | null;\n windowUnit: \"second\" | \"minute\" | \"hour\" | \"day\" | \"week\" | \"month\" | \"year\";\n windowCount: number;\n windowAnchor: \"calendar\" | \"rolling\";\n windowTimezone: string;\n updatedAt?: string | null;\n}\n\nexport interface BillingAutoRechargeAttempt {\n id: string;\n userId: string;\n provider: string;\n idempotencyKey: string;\n providerAttemptId: string | null;\n topupId: string;\n quantity: number;\n state: BillingAutoRechargeAttemptState;\n windowStart: string;\n windowEnd: string;\n quotedAmountMinor: number | null;\n currency: string | null;\n failureCode: string | null;\n failureMessage: string | null;\n metadata: JsonObject;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface BillingAutoRechargeStatus {\n enabled: boolean;\n state: BillingAutoRechargeState;\n thresholdCredits: Decimal;\n topupKey: string;\n quantity: number;\n maxRecharges: number;\n windowStart: string;\n windowEnd: string;\n rechargesInWindow: number;\n paymentMethodId: string | null;\n paymentMethodLast4: string | null;\n paymentMethodBrand: string | null;\n suspendedReason: string | null;\n pendingAttemptId: string | null;\n quoteAmountMinor: number | null;\n quoteCurrency: string | null;\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import type { Decimal } from "decimal.js";
2
2
  import type { ProviderRef } from "./common.js";
3
+ import type { JsonObject } from "../../shared/json.js";
3
4
  export interface BillingCustomerInfo {
4
5
  providerCustomerId?: string | null;
5
6
  email?: string | null;
@@ -39,7 +40,7 @@ export interface BillingPaymentRecord {
39
40
  purpose: "subscription" | "credit_topup";
40
41
  status: "pending" | "succeeded" | "failed" | "canceled";
41
42
  providerUpdatedAt: string;
42
- metadata: Record<string, unknown>;
43
+ metadata: JsonObject;
43
44
  }
44
45
  /** Result of posting a billing grant or refund to the credit ledger. */
45
46
  export interface BillingCreditPostingResult {