@zonastery/bursar 1.0.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (366) hide show
  1. package/README.md +86 -3
  2. package/dist/billing/auto-recharge-port.d.ts +3 -3
  3. package/dist/billing/auto-recharge-port.d.ts.map +1 -1
  4. package/dist/billing/auto-recharge-port.js.map +1 -1
  5. package/dist/billing/auto-recharge-service.d.ts +5 -4
  6. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  7. package/dist/billing/auto-recharge-service.js +64 -34
  8. package/dist/billing/auto-recharge-service.js.map +1 -1
  9. package/dist/billing/billing-service.d.ts +5 -5
  10. package/dist/billing/billing-service.d.ts.map +1 -1
  11. package/dist/billing/billing-service.js +2 -2
  12. package/dist/billing/billing-service.js.map +1 -1
  13. package/dist/billing/billing-store.d.ts +8 -7
  14. package/dist/billing/billing-store.d.ts.map +1 -1
  15. package/dist/billing/billing-store.js.map +1 -1
  16. package/dist/billing/contracts.d.ts +31 -31
  17. package/dist/billing/contracts.d.ts.map +1 -1
  18. package/dist/billing/contracts.js.map +1 -1
  19. package/dist/billing/event-handlers.d.ts.map +1 -1
  20. package/dist/billing/event-handlers.js +31 -9
  21. package/dist/billing/event-handlers.js.map +1 -1
  22. package/dist/billing/event-processor.d.ts.map +1 -1
  23. package/dist/billing/event-processor.js +2 -1
  24. package/dist/billing/event-processor.js.map +1 -1
  25. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  26. package/dist/billing/financial-event-handlers.js +69 -72
  27. package/dist/billing/financial-event-handlers.js.map +1 -1
  28. package/dist/billing/index.d.ts +1 -1
  29. package/dist/billing/index.d.ts.map +1 -1
  30. package/dist/billing/index.js.map +1 -1
  31. package/dist/billing/management.d.ts +5 -5
  32. package/dist/billing/management.d.ts.map +1 -1
  33. package/dist/billing/management.js +2 -2
  34. package/dist/billing/management.js.map +1 -1
  35. package/dist/billing/postgres/repositories/auto-recharge.d.ts +3 -3
  36. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  37. package/dist/billing/postgres/repositories/auto-recharge.js +202 -59
  38. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  39. package/dist/billing/postgres/repositories/customer.d.ts.map +1 -1
  40. package/dist/billing/postgres/repositories/customer.js +19 -11
  41. package/dist/billing/postgres/repositories/customer.js.map +1 -1
  42. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
  43. package/dist/billing/postgres/repositories/dispute.js +3 -1
  44. package/dist/billing/postgres/repositories/dispute.js.map +1 -1
  45. package/dist/billing/postgres/repositories/event.d.ts +12 -5
  46. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  47. package/dist/billing/postgres/repositories/event.js +18 -15
  48. package/dist/billing/postgres/repositories/event.js.map +1 -1
  49. package/dist/billing/postgres/repositories/invoice.d.ts +3 -3
  50. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  51. package/dist/billing/postgres/repositories/invoice.js +53 -11
  52. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  53. package/dist/billing/postgres/repositories/offer.d.ts +20 -17
  54. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  55. package/dist/billing/postgres/repositories/offer.js +123 -57
  56. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  57. package/dist/billing/postgres/repositories/payment.d.ts +23 -20
  58. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  59. package/dist/billing/postgres/repositories/payment.js +43 -37
  60. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  61. package/dist/billing/postgres/repositories/preferences.d.ts +3 -9
  62. package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -1
  63. package/dist/billing/postgres/repositories/preferences.js +45 -7
  64. package/dist/billing/postgres/repositories/preferences.js.map +1 -1
  65. package/dist/billing/postgres/repositories/refund.d.ts +1 -1
  66. package/dist/billing/postgres/repositories/refund.d.ts.map +1 -1
  67. package/dist/billing/postgres/repositories/refund.js +13 -9
  68. package/dist/billing/postgres/repositories/refund.js.map +1 -1
  69. package/dist/billing/postgres/repositories/subscription-change.d.ts +15 -0
  70. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -0
  71. package/dist/billing/postgres/repositories/subscription-change.js +234 -0
  72. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -0
  73. package/dist/billing/postgres/repositories/subscription.d.ts +38 -17
  74. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  75. package/dist/billing/postgres/repositories/subscription.js +199 -91
  76. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  77. package/dist/billing/postgres/repositories/topup.d.ts +13 -15
  78. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  79. package/dist/billing/postgres/repositories/topup.js +65 -34
  80. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  81. package/dist/billing/postgres/store.d.ts +18 -11
  82. package/dist/billing/postgres/store.d.ts.map +1 -1
  83. package/dist/billing/postgres/store.js +260 -238
  84. package/dist/billing/postgres/store.js.map +1 -1
  85. package/dist/billing/service-types.d.ts +6 -5
  86. package/dist/billing/service-types.d.ts.map +1 -1
  87. package/dist/billing/service-types.js.map +1 -1
  88. package/dist/billing/types/auto-recharge.d.ts +6 -4
  89. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  90. package/dist/billing/types/auto-recharge.js.map +1 -1
  91. package/dist/billing/types/catalog.d.ts +18 -35
  92. package/dist/billing/types/catalog.d.ts.map +1 -1
  93. package/dist/billing/types/catalog.js.map +1 -1
  94. package/dist/billing/types/common.d.ts +0 -1
  95. package/dist/billing/types/common.d.ts.map +1 -1
  96. package/dist/billing/types/common.js.map +1 -1
  97. package/dist/billing/types/documents.d.ts +38 -12
  98. package/dist/billing/types/documents.d.ts.map +1 -1
  99. package/dist/billing/types/documents.js.map +1 -1
  100. package/dist/billing/types/events.d.ts +2 -0
  101. package/dist/billing/types/events.d.ts.map +1 -1
  102. package/dist/billing/types/events.js +238 -0
  103. package/dist/billing/types/events.js.map +1 -1
  104. package/dist/billing/types/subscriptions.d.ts +8 -8
  105. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  106. package/dist/billing/types/subscriptions.js.map +1 -1
  107. package/dist/bursar.d.ts +27 -9
  108. package/dist/bursar.d.ts.map +1 -1
  109. package/dist/bursar.js +48 -20
  110. package/dist/bursar.js.map +1 -1
  111. package/dist/catalog.d.ts +1 -1
  112. package/dist/catalog.d.ts.map +1 -1
  113. package/dist/catalog.js +1 -1
  114. package/dist/catalog.js.map +1 -1
  115. package/dist/commerce/errors.d.ts +1 -10
  116. package/dist/commerce/errors.d.ts.map +1 -1
  117. package/dist/commerce/errors.js +1 -16
  118. package/dist/commerce/errors.js.map +1 -1
  119. package/dist/commerce/index.d.ts +1 -0
  120. package/dist/commerce/index.d.ts.map +1 -1
  121. package/dist/commerce/index.js.map +1 -1
  122. package/dist/commerce/provider-registry.d.ts.map +1 -1
  123. package/dist/commerce/provider-registry.js +27 -2
  124. package/dist/commerce/provider-registry.js.map +1 -1
  125. package/dist/commerce/service.d.ts +15 -7
  126. package/dist/commerce/service.d.ts.map +1 -1
  127. package/dist/commerce/service.js +85 -67
  128. package/dist/commerce/service.js.map +1 -1
  129. package/dist/commerce/types.d.ts +27 -15
  130. package/dist/commerce/types.d.ts.map +1 -1
  131. package/dist/commerce/types.js.map +1 -1
  132. package/dist/config/parse-plans.d.ts.map +1 -1
  133. package/dist/config/parse-plans.js +16 -15
  134. package/dist/config/parse-plans.js.map +1 -1
  135. package/dist/config/parse-pricing.d.ts.map +1 -1
  136. package/dist/config/parse-pricing.js +16 -5
  137. package/dist/config/parse-pricing.js.map +1 -1
  138. package/dist/config/types.d.ts +2 -2
  139. package/dist/config/types.d.ts.map +1 -1
  140. package/dist/config/types.js.map +1 -1
  141. package/dist/credits/{pricing-runtime.d.ts → catalog-runtime.d.ts} +8 -8
  142. package/dist/credits/catalog-runtime.d.ts.map +1 -0
  143. package/dist/credits/{pricing-runtime.js → catalog-runtime.js} +58 -38
  144. package/dist/credits/catalog-runtime.js.map +1 -0
  145. package/dist/credits/events.d.ts +4 -4
  146. package/dist/credits/events.d.ts.map +1 -1
  147. package/dist/credits/events.js +1 -1
  148. package/dist/credits/events.js.map +1 -1
  149. package/dist/credits/lease-workflow.d.ts +14 -14
  150. package/dist/credits/lease-workflow.d.ts.map +1 -1
  151. package/dist/credits/lease-workflow.js +18 -17
  152. package/dist/credits/lease-workflow.js.map +1 -1
  153. package/dist/credits/low-balance-monitor.d.ts +2 -2
  154. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  155. package/dist/credits/low-balance-monitor.js.map +1 -1
  156. package/dist/credits/postgres/repositories/analytics.d.ts +34 -34
  157. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  158. package/dist/credits/postgres/repositories/analytics.js +52 -52
  159. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  160. package/dist/credits/postgres/repositories/balance.d.ts +28 -30
  161. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  162. package/dist/credits/postgres/repositories/balance.js +100 -59
  163. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  164. package/dist/credits/postgres/repositories/bucket.d.ts +14 -8
  165. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
  166. package/dist/credits/postgres/repositories/bucket.js +22 -21
  167. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  168. package/dist/credits/postgres/repositories/catalog.d.ts +31 -0
  169. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -0
  170. package/dist/credits/postgres/repositories/catalog.js +90 -0
  171. package/dist/credits/postgres/repositories/catalog.js.map +1 -0
  172. package/dist/credits/postgres/repositories/deduction.d.ts +28 -26
  173. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  174. package/dist/credits/postgres/repositories/deduction.js +153 -68
  175. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  176. package/dist/credits/postgres/repositories/lease.d.ts +21 -18
  177. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  178. package/dist/credits/postgres/repositories/lease.js +157 -65
  179. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  180. package/dist/credits/postgres/repositories/plan.d.ts +90 -43
  181. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
  182. package/dist/credits/postgres/repositories/plan.js +126 -108
  183. package/dist/credits/postgres/repositories/plan.js.map +1 -1
  184. package/dist/credits/postgres/repositories/team.d.ts +36 -27
  185. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  186. package/dist/credits/postgres/repositories/team.js +96 -52
  187. package/dist/credits/postgres/repositories/team.js.map +1 -1
  188. package/dist/credits/postgres/store.d.ts +23 -18
  189. package/dist/credits/postgres/store.d.ts.map +1 -1
  190. package/dist/credits/postgres/store.js +282 -265
  191. package/dist/credits/postgres/store.js.map +1 -1
  192. package/dist/credits/postgres/value-mappers.d.ts +7 -9
  193. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  194. package/dist/credits/postgres/value-mappers.js +36 -61
  195. package/dist/credits/postgres/value-mappers.js.map +1 -1
  196. package/dist/credits/queries.d.ts +5 -5
  197. package/dist/credits/queries.d.ts.map +1 -1
  198. package/dist/credits/queries.js +4 -4
  199. package/dist/credits/queries.js.map +1 -1
  200. package/dist/credits/service-types.d.ts +42 -7
  201. package/dist/credits/service-types.d.ts.map +1 -1
  202. package/dist/credits/service-types.js.map +1 -1
  203. package/dist/credits/service.d.ts +42 -62
  204. package/dist/credits/service.d.ts.map +1 -1
  205. package/dist/credits/service.js +140 -121
  206. package/dist/credits/service.js.map +1 -1
  207. package/dist/credits/store.d.ts +20 -22
  208. package/dist/credits/store.d.ts.map +1 -1
  209. package/dist/credits/store.js +5 -5
  210. package/dist/credits/store.js.map +1 -1
  211. package/dist/credits/types/account.d.ts +49 -11
  212. package/dist/credits/types/account.d.ts.map +1 -1
  213. package/dist/credits/types/account.js.map +1 -1
  214. package/dist/credits/types/admission.d.ts +17 -6
  215. package/dist/credits/types/admission.d.ts.map +1 -1
  216. package/dist/credits/types/admission.js.map +1 -1
  217. package/dist/credits/types/analytics.d.ts +2 -2
  218. package/dist/credits/types/analytics.d.ts.map +1 -1
  219. package/dist/credits/types/analytics.js.map +1 -1
  220. package/dist/credits/types/catalog.d.ts +20 -15
  221. package/dist/credits/types/catalog.d.ts.map +1 -1
  222. package/dist/credits/types/catalog.js.map +1 -1
  223. package/dist/credits/types/grants.d.ts +22 -8
  224. package/dist/credits/types/grants.d.ts.map +1 -1
  225. package/dist/credits/types/grants.js.map +1 -1
  226. package/dist/credits/types/ledger.d.ts +12 -3
  227. package/dist/credits/types/ledger.d.ts.map +1 -1
  228. package/dist/credits/types/ledger.js.map +1 -1
  229. package/dist/credits/types/teams.d.ts +18 -6
  230. package/dist/credits/types/teams.d.ts.map +1 -1
  231. package/dist/credits/types/teams.js.map +1 -1
  232. package/dist/engine.d.ts.map +1 -1
  233. package/dist/engine.js +24 -10
  234. package/dist/engine.js.map +1 -1
  235. package/dist/errors.d.ts +52 -4
  236. package/dist/errors.d.ts.map +1 -1
  237. package/dist/errors.js +76 -4
  238. package/dist/errors.js.map +1 -1
  239. package/dist/expr/ast.d.ts.map +1 -1
  240. package/dist/expr/ast.js.map +1 -1
  241. package/dist/expr/evaluator.d.ts.map +1 -1
  242. package/dist/expr/evaluator.js +29 -17
  243. package/dist/expr/evaluator.js.map +1 -1
  244. package/dist/expr/parser.d.ts.map +1 -1
  245. package/dist/expr/parser.js +11 -4
  246. package/dist/expr/parser.js.map +1 -1
  247. package/dist/expr/tokenizer.d.ts.map +1 -1
  248. package/dist/expr/tokenizer.js +17 -13
  249. package/dist/expr/tokenizer.js.map +1 -1
  250. package/dist/expr.d.ts +2 -2
  251. package/dist/expr.d.ts.map +1 -1
  252. package/dist/expr.js +5 -7
  253. package/dist/expr.js.map +1 -1
  254. package/dist/generated/pricing-config.schema.json +5 -12
  255. package/dist/generated/pricing-config.types.d.ts +3 -3
  256. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  257. package/dist/generated/pricing-config.types.js.map +1 -1
  258. package/dist/index.d.ts +6 -4
  259. package/dist/index.d.ts.map +1 -1
  260. package/dist/index.js +1 -1
  261. package/dist/index.js.map +1 -1
  262. package/dist/integrations/better-auth.d.ts +23 -0
  263. package/dist/integrations/better-auth.d.ts.map +1 -0
  264. package/dist/integrations/better-auth.js +54 -0
  265. package/dist/integrations/better-auth.js.map +1 -0
  266. package/dist/{load-pricing-file.d.ts → load-config-file.d.ts} +4 -4
  267. package/dist/load-config-file.d.ts.map +1 -0
  268. package/dist/{load-pricing-file.js → load-config-file.js} +15 -10
  269. package/dist/load-config-file.js.map +1 -0
  270. package/dist/node.d.ts +3 -3
  271. package/dist/node.d.ts.map +1 -1
  272. package/dist/node.js +2 -2
  273. package/dist/node.js.map +1 -1
  274. package/dist/providers/_shared.d.ts +5 -0
  275. package/dist/providers/_shared.d.ts.map +1 -1
  276. package/dist/providers/_shared.js +36 -0
  277. package/dist/providers/_shared.js.map +1 -1
  278. package/dist/providers/dodo/better-auth.d.ts +29 -0
  279. package/dist/providers/dodo/better-auth.d.ts.map +1 -0
  280. package/dist/providers/dodo/better-auth.js +23 -0
  281. package/dist/providers/dodo/better-auth.js.map +1 -0
  282. package/dist/providers/dodo/client-contract.d.ts +32 -70
  283. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  284. package/dist/providers/dodo/client-contract.js.map +1 -1
  285. package/dist/providers/dodo/event-mapper.d.ts +3 -1
  286. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  287. package/dist/providers/dodo/event-mapper.js +219 -148
  288. package/dist/providers/dodo/event-mapper.js.map +1 -1
  289. package/dist/providers/dodo/index.d.ts +5 -2
  290. package/dist/providers/dodo/index.d.ts.map +1 -1
  291. package/dist/providers/dodo/index.js +2 -1
  292. package/dist/providers/dodo/index.js.map +1 -1
  293. package/dist/providers/dodo/nextjs.d.ts +16 -0
  294. package/dist/providers/dodo/nextjs.d.ts.map +1 -0
  295. package/dist/providers/dodo/nextjs.js +16 -0
  296. package/dist/providers/dodo/nextjs.js.map +1 -0
  297. package/dist/providers/dodo/provider.d.ts +30 -11
  298. package/dist/providers/dodo/provider.d.ts.map +1 -1
  299. package/dist/providers/dodo/provider.js +192 -122
  300. package/dist/providers/dodo/provider.js.map +1 -1
  301. package/dist/providers/dodo/react-native.d.ts +56 -0
  302. package/dist/providers/dodo/react-native.d.ts.map +1 -0
  303. package/dist/providers/dodo/react-native.js +57 -0
  304. package/dist/providers/dodo/react-native.js.map +1 -0
  305. package/dist/providers/dodo/webhook-bridge.d.ts +17 -0
  306. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -0
  307. package/dist/providers/dodo/webhook-bridge.js +21 -0
  308. package/dist/providers/dodo/webhook-bridge.js.map +1 -0
  309. package/dist/providers/index.d.ts +1 -1
  310. package/dist/providers/index.d.ts.map +1 -1
  311. package/dist/providers/index.js.map +1 -1
  312. package/dist/providers/mock/index.d.ts +1 -0
  313. package/dist/providers/mock/index.d.ts.map +1 -1
  314. package/dist/providers/mock/index.js.map +1 -1
  315. package/dist/providers/mock/provider.d.ts +8 -8
  316. package/dist/providers/mock/provider.d.ts.map +1 -1
  317. package/dist/providers/mock/provider.js +26 -19
  318. package/dist/providers/mock/provider.js.map +1 -1
  319. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  320. package/dist/providers/stripe/event-mapper.js +214 -173
  321. package/dist/providers/stripe/event-mapper.js.map +1 -1
  322. package/dist/providers/stripe/index.d.ts +1 -0
  323. package/dist/providers/stripe/index.d.ts.map +1 -1
  324. package/dist/providers/stripe/index.js.map +1 -1
  325. package/dist/providers/stripe/provider.d.ts +13 -11
  326. package/dist/providers/stripe/provider.d.ts.map +1 -1
  327. package/dist/providers/stripe/provider.js +287 -107
  328. package/dist/providers/stripe/provider.js.map +1 -1
  329. package/dist/providers/types.d.ts +1 -2
  330. package/dist/providers/types.d.ts.map +1 -1
  331. package/dist/providers/types.js.map +1 -1
  332. package/dist/shared/postgres-client.d.ts +5 -0
  333. package/dist/shared/postgres-client.d.ts.map +1 -1
  334. package/dist/shared/postgres-client.js +23 -7
  335. package/dist/shared/postgres-client.js.map +1 -1
  336. package/dist/shared/postgres-validation.d.ts +15 -3
  337. package/dist/shared/postgres-validation.d.ts.map +1 -1
  338. package/dist/shared/postgres-validation.js +58 -14
  339. package/dist/shared/postgres-validation.js.map +1 -1
  340. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  341. package/dist/storage/adapters/clickhouse.js +2 -5
  342. package/dist/storage/adapters/clickhouse.js.map +1 -1
  343. package/dist/storage/adapters/s3.d.ts +0 -6
  344. package/dist/storage/adapters/s3.d.ts.map +1 -1
  345. package/dist/storage/adapters/s3.js +0 -2
  346. package/dist/storage/adapters/s3.js.map +1 -1
  347. package/dist/storage/ports.d.ts +0 -1
  348. package/dist/storage/ports.d.ts.map +1 -1
  349. package/dist/storage/ports.js.map +1 -1
  350. package/dist/storage/postgres-repository.d.ts +1 -1
  351. package/dist/storage/postgres-repository.d.ts.map +1 -1
  352. package/dist/storage/postgres-repository.js +2 -2
  353. package/dist/storage/postgres-repository.js.map +1 -1
  354. package/dist/storage/runtime.d.ts +24 -6
  355. package/dist/storage/runtime.d.ts.map +1 -1
  356. package/dist/storage/runtime.js +87 -30
  357. package/dist/storage/runtime.js.map +1 -1
  358. package/package.json +56 -7
  359. package/dist/credits/postgres/repositories/pricing.d.ts +0 -28
  360. package/dist/credits/postgres/repositories/pricing.d.ts.map +0 -1
  361. package/dist/credits/postgres/repositories/pricing.js +0 -76
  362. package/dist/credits/postgres/repositories/pricing.js.map +0 -1
  363. package/dist/credits/pricing-runtime.d.ts.map +0 -1
  364. package/dist/credits/pricing-runtime.js.map +0 -1
  365. package/dist/load-pricing-file.d.ts.map +0 -1
  366. package/dist/load-pricing-file.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subscription-change.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription-change.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE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AAC;QACxF,CAAC,CAAC,CAAC;QACH,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC,SAAS,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;QAC/E,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAChC,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC5B,IAAI,MAAM,CAAC,IAAI,KAAK,CAAC,IAAI,IAAI,KAAK,SAAS,IAAI,EAAE,KAAK,SAAS,EAAE,CAAC;YAChE,MAAM,IAAI,UAAU,CAAC,GAAG,OAAO,0DAA0D,EAAE;gBACzF,OAAO,EAAE,EAAE,oBAAoB,EAAE,GAAG,CAAC,EAAE,EAAE;aAC1C,CAAC,CAAC;QACL,CAAC;QACD,IAAI,IAAI,CAAC,QAAQ,KAAK,GAAG,CAAC,aAAa,IAAI,EAAE,CAAC,QAAQ,KAAK,GAAG,CAAC,WAAW,EAAE,CAAC;YAC3E,MAAM,IAAI,UAAU,CAAC,GAAG,OAAO,oDAAoD,EAAE;gBACnF,OAAO,EAAE,EAAE,oBAAoB,EAAE,GAAG,CAAC,EAAE,EAAE;aAC1C,CAAC,CAAC;QACL,CAAC;QACD,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC;IACtB,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { BillingSubscriptionChangeUpdate } from \"../../contracts.js\";\nimport type {\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionOfferContext,\n} from \"../../types/index.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport { optionalBoundedDiagnosticMessage } from \"../../../shared/diagnostics.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireRecordRow,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst timestamp = z\n .union([\n z.string().datetime({ offset: true }),\n z.date().refine((value) => !Number.isNaN(value.getTime())),\n ])\n .transform((value) => (value instanceof Date ? value.toISOString() : value));\nconst positiveBigint = z\n .union([z.string().regex(/^[1-9]\\d*$/), z.number().int().positive().safe()])\n .transform(String);\nconst changeState = z.enum([\"awaiting_payment\", \"scheduled\", \"applied\", \"failed\", \"canceled\"]);\nconst effectiveBehavior = z.enum([\"immediate\", \"renewal\"]);\nconst prorationBehavior = z.enum([\"provider_default\", \"invoice_immediately\", \"none\"]);\n\nconst OpenChangeResultSchema = z\n .object({\n change_id: positiveBigint.nullable(),\n state: changeState.nullable(),\n error_code: z\n .enum([\n \"invalid_request\",\n \"missing_subscription\",\n \"invalid_target_offer\",\n \"idempotency_conflict\",\n \"open_change_exists\",\n ])\n .nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n const succeeded = row.error_code === null;\n if (succeeded !== (row.change_id !== null && row.state !== null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"subscription-change result has inconsistent success fields\",\n });\n }\n });\n\nconst ChangeRowSchema = z\n .object({\n id: positiveBigint,\n subscription_id: postgresUuid,\n from_offer_id: postgresUuid,\n from_catalog_revision_id: postgresUuid,\n to_offer_id: postgresUuid,\n to_catalog_revision_id: postgresUuid,\n effective_at: timestamp.nullable(),\n effective_behavior: effectiveBehavior,\n state: changeState,\n proration_behavior: prorationBehavior,\n idempotency_key: z.string().min(1),\n provider_operation_id: z.string().min(1).nullable(),\n error_message: z.string().min(1).max(8192).nullable(),\n })\n .strict();\n\ntype ChangeRow = z.infer<typeof ChangeRowSchema>;\n\nconst OfferContextRowSchema = z\n .object({\n side: z.enum([\"from\", \"to\"]),\n offer_id: postgresUuid,\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\ntype OfferContextRow = z.infer<typeof OfferContextRowSchema>;\n\nfunction projectChange(row: Record<string, unknown>): Record<string, unknown> {\n return {\n id: row.id,\n subscription_id: row.subscription_id,\n from_offer_id: row.from_offer_id,\n from_catalog_revision_id: row.from_catalog_revision_id,\n to_offer_id: row.to_offer_id,\n to_catalog_revision_id: row.to_catalog_revision_id,\n effective_at: row.effective_at,\n effective_behavior: row.effective_behavior,\n state: row.state,\n proration_behavior: row.proration_behavior,\n idempotency_key: row.idempotency_key,\n provider_operation_id: row.provider_operation_id,\n error_message: row.error_message,\n };\n}\n\nfunction projectContext(row: Record<string, unknown>): Record<string, unknown> {\n return {\n side: row.side,\n offer_id: row.offer_id,\n offer_key: row.offer_key,\n plan_id: row.plan_id,\n plan_key: row.plan_key,\n billing_unit: row.billing_unit,\n billing_count: row.billing_count,\n };\n}\n\nfunction publicContext(row: OfferContextRow): BillingSubscriptionOfferContext {\n return {\n offerId: row.offer_id,\n offerKey: row.offer_key,\n planId: row.plan_id,\n plan: row.plan_key,\n interval: row.billing_unit,\n intervalCount: row.billing_count,\n };\n}\n\n/** Persistence boundary for durable subscription offer transitions. */\nexport class BillingSubscriptionChangeRepository {\n constructor(private readonly query: QueryFn) {}\n\n async create(\n subscriptionId: string,\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n const rows = await this.query(\n `SELECT * FROM bursar.open_subscription_change(\n $1::uuid, $2::uuid, $3::timestamptz, $4, $5, $6\n )`,\n [\n subscriptionId,\n input.toOfferId,\n input.effectiveAt,\n input.effective,\n input.idempotencyKey,\n input.prorationBehavior ?? \"provider_default\",\n ],\n );\n const raw = requireRecordRow(rows, \"BillingSubscriptionChangeRepository.create\");\n const result = safeParse(\n OpenChangeResultSchema,\n { change_id: raw.change_id, state: raw.state, error_code: raw.error_code },\n \"BillingSubscriptionChangeRepository.create\",\n { indeterminate: true },\n );\n if (result.error_code !== null) {\n throw new StoreError(`subscription change rejected: ${result.error_code}`, {\n details: { errorCode: result.error_code },\n });\n }\n if (result.change_id === null) {\n throw new StoreError(\"subscription change returned no identifier\", { indeterminate: true });\n }\n const change = await this.getById(result.change_id);\n if (change === null) {\n throw new StoreError(\"subscription change could not be read after creation\", {\n indeterminate: true,\n details: { subscriptionChangeId: result.change_id },\n });\n }\n return change;\n }\n\n async getById(id: string): Promise<BillingSubscriptionChange | null> {\n const rows = await this.query(\n \"SELECT * FROM bursar.get_billing_subscription_change($1::bigint)\",\n [id],\n );\n return this.parseOptional(rows, \"BillingSubscriptionChangeRepository.getById\");\n }\n\n async getOpen(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n const rows = await this.query(\n \"SELECT * FROM bursar.get_open_billing_subscription_change($1, $2)\",\n [provider, providerSubscriptionId],\n );\n return this.parseOptional(rows, \"BillingSubscriptionChangeRepository.getOpen\");\n }\n\n async update(id: string, update: BillingSubscriptionChangeUpdate): Promise<void> {\n if (update.state === undefined) return;\n const rows = await this.query(\n \"SELECT bursar.advance_subscription_change($1::bigint, $2, $3, $4) AS advanced\",\n [\n id,\n update.state,\n update.providerOperationId ?? null,\n optionalBoundedDiagnosticMessage(update.errorMessage),\n ],\n );\n if (\n !requireResultField(rows, \"advanced\", pgBoolean, \"BillingSubscriptionChangeRepository.update\")\n ) {\n throw new StoreError(`subscription change transition rejected: ${id}`, {\n details: { subscriptionChangeId: id },\n });\n }\n }\n\n private async parseOptional(\n rows: readonly unknown[],\n context: string,\n ): Promise<BillingSubscriptionChange | null> {\n const raw = optionalRecordRow(rows, context);\n if (raw === null) return null;\n const row = safeParse(ChangeRowSchema, projectChange(raw), context);\n const contexts = await this.getOfferContexts(row, context);\n return {\n id: row.id,\n subscriptionId: row.subscription_id,\n fromOfferId: row.from_offer_id,\n toOfferId: row.to_offer_id,\n fromOffer: publicContext(contexts.from),\n toOffer: publicContext(contexts.to),\n effectiveAt: row.effective_at,\n effective: row.effective_behavior,\n state: row.state,\n prorationBehavior: row.proration_behavior,\n idempotencyKey: row.idempotency_key,\n providerOperationId: row.provider_operation_id,\n errorMessage: row.error_message,\n };\n }\n\n private async getOfferContexts(\n row: ChangeRow,\n context: string,\n ): Promise<{ from: OfferContextRow; to: OfferContextRow }> {\n const rows = await this.query(\n `SELECT requested.side, requested.offer_id, offer_context.*\n FROM (\n VALUES\n ('from', $1::uuid, $2::uuid),\n ('to', $3::uuid, $4::uuid)\n ) AS requested(side, offer_id, catalog_revision_id)\n CROSS JOIN LATERAL bursar.get_catalog_offer_context(\n requested.offer_id,\n requested.catalog_revision_id\n ) AS offer_context`,\n [\n row.from_offer_id,\n row.from_catalog_revision_id,\n row.to_offer_id,\n row.to_catalog_revision_id,\n ],\n );\n if (rows.length !== 2) {\n throw new StoreError(`${context}: expected both subscription-change offer contexts`, {\n details: { subscriptionChangeId: row.id, rowCount: rows.length },\n });\n }\n const parsed = rows.map((candidate, index) => {\n if (typeof candidate !== \"object\" || candidate === null || Array.isArray(candidate)) {\n throw new StoreError(`${context}: malformed subscription-change offer context`, {\n details: { subscriptionChangeId: row.id, index },\n });\n }\n const record = candidate as Record<string, unknown>;\n return safeParse(OfferContextRowSchema, projectContext(record), `${context}.context`);\n });\n const bySide = new Map(parsed.map((candidate) => [candidate.side, candidate]));\n const from = bySide.get(\"from\");\n const to = bySide.get(\"to\");\n if (bySide.size !== 2 || from === undefined || to === undefined) {\n throw new StoreError(`${context}: duplicate or missing subscription-change offer context`, {\n details: { subscriptionChangeId: row.id },\n });\n }\n if (from.offer_id !== row.from_offer_id || to.offer_id !== row.to_offer_id) {\n throw new StoreError(`${context}: subscription-change offer context does not match`, {\n details: { subscriptionChangeId: row.id },\n });\n }\n return { from, to };\n }\n}\n"]}
@@ -1,29 +1,50 @@
1
1
  import { z } from "zod";
2
+ import type { BillingSubscriptionState } from "../../types/subscriptions.js";
2
3
  import type { QueryFn } from "../../../shared/postgres-types.js";
3
4
  declare const SubscriptionRowSchema: z.ZodObject<{
4
- user_id: z.ZodOptional<z.ZodString>;
5
- subject_id: z.ZodOptional<z.ZodString>;
5
+ id: z.ZodString;
6
+ user_id: z.ZodString;
6
7
  provider: z.ZodString;
7
8
  provider_subscription_id: z.ZodString;
8
- provider_customer_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
9
- offer_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
10
- status: z.ZodOptional<z.ZodString>;
11
- current_period_start: z.ZodOptional<z.ZodUnknown>;
12
- current_period_end: z.ZodOptional<z.ZodUnknown>;
13
- trial_end: z.ZodOptional<z.ZodUnknown>;
14
- cancel_at: z.ZodOptional<z.ZodUnknown>;
15
- ended_at: z.ZodOptional<z.ZodUnknown>;
16
- grace_ends_at: z.ZodOptional<z.ZodUnknown>;
17
- grace_expired_at: z.ZodOptional<z.ZodUnknown>;
18
- provider_updated_at: z.ZodOptional<z.ZodUnknown>;
19
- cancel_at_period_end: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString, z.ZodNumber]>, z.ZodTransform<boolean, string | number | boolean>>>>;
20
- metadata: z.ZodOptional<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
21
- }, z.core.$loose>;
9
+ provider_customer_id: z.ZodNullable<z.ZodString>;
10
+ offer_id: z.ZodString;
11
+ offer_key: z.ZodString;
12
+ plan_id: z.ZodString;
13
+ plan: z.ZodString;
14
+ status: z.ZodEnum<{
15
+ canceled: "canceled";
16
+ incomplete: "incomplete";
17
+ incomplete_expired: "incomplete_expired";
18
+ trialing: "trialing";
19
+ active: "active";
20
+ past_due: "past_due";
21
+ unpaid: "unpaid";
22
+ paused: "paused";
23
+ expired: "expired";
24
+ }>;
25
+ current_period_start: z.ZodNullable<z.ZodPipe<z.ZodUnion<readonly [z.ZodDate, z.ZodString]>, z.ZodTransform<string, string | Date>>>;
26
+ current_period_end: z.ZodNullable<z.ZodPipe<z.ZodUnion<readonly [z.ZodDate, z.ZodString]>, z.ZodTransform<string, string | Date>>>;
27
+ trial_end: z.ZodNullable<z.ZodPipe<z.ZodUnion<readonly [z.ZodDate, z.ZodString]>, z.ZodTransform<string, string | Date>>>;
28
+ cancel_at: z.ZodNullable<z.ZodPipe<z.ZodUnion<readonly [z.ZodDate, z.ZodString]>, z.ZodTransform<string, string | Date>>>;
29
+ ended_at: z.ZodNullable<z.ZodPipe<z.ZodUnion<readonly [z.ZodDate, z.ZodString]>, z.ZodTransform<string, string | Date>>>;
30
+ grace_ends_at: z.ZodNullable<z.ZodPipe<z.ZodUnion<readonly [z.ZodDate, z.ZodString]>, z.ZodTransform<string, string | Date>>>;
31
+ grace_expired_at: z.ZodNullable<z.ZodPipe<z.ZodUnion<readonly [z.ZodDate, z.ZodString]>, z.ZodTransform<string, string | Date>>>;
32
+ provider_updated_at: z.ZodPipe<z.ZodUnion<readonly [z.ZodDate, z.ZodString]>, z.ZodTransform<string, string | Date>>;
33
+ cancel_at_period_end: z.ZodBoolean;
34
+ interval: z.ZodEnum<{
35
+ day: "day";
36
+ week: "week";
37
+ month: "month";
38
+ year: "year";
39
+ }>;
40
+ interval_count: z.ZodNumber;
41
+ metadata: z.ZodRecord<z.ZodString, z.ZodUnknown>;
42
+ }, z.core.$strict>;
22
43
  export type SubscriptionRow = z.infer<typeof SubscriptionRowSchema>;
23
44
  export declare class BillingSubscriptionRepository {
24
45
  private query;
25
46
  constructor(query: QueryFn);
26
- upsert(state: Record<string, unknown>): Promise<void>;
47
+ upsert(state: BillingSubscriptionState): Promise<void>;
27
48
  private map;
28
49
  private withOfferContext;
29
50
  get(provider: string, providerSubscriptionId: string): Promise<SubscriptionRow | null>;
@@ -1 +1 @@
1
- {"version":3,"file":"subscription.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAGjE,QAAA,MAAM,qBAAqB;;;;;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CAAC,OAAO,CAAC;IAab,cAAc,CAAC,KAAK,EAAE;QAC1B,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QACvB,QAAQ,EAAE,MAAM,CAAC;QACjB,uBAAuB,EAAE,MAAM,CAAC;QAChC,sBAAsB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QACvC,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QACxB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACpC,GAAG,OAAO,CAAC,MAAM,CAAC;IAsBnB,gFAAgF;IAC1E,uBAAuB,CAC3B,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,sBAAsB,CAAC,EAAE,MAAM,GAAG,IAAI,GACrC,OAAO,CAAC,OAAO,CAAC;CAuCpB"}
@@ -1,42 +1,111 @@
1
1
  import { z } from "zod";
2
- import { pgBoolean, safeParse } from "../../../shared/postgres-validation.js";
2
+ import { StoreError } from "../../../errors.js";
3
+ import { optionalRecordRow, pgBoolean, postgresUuid, requireResultField, safeParse, } from "../../../shared/postgres-validation.js";
4
+ const timestamp = z
5
+ .union([
6
+ z.date().refine((value) => !Number.isNaN(value.getTime())),
7
+ z.string().datetime({ offset: true }),
8
+ ])
9
+ .transform((value) => (value instanceof Date ? value : new Date(value)).toISOString());
10
+ const SubscriptionStatusSchema = z.enum([
11
+ "incomplete",
12
+ "incomplete_expired",
13
+ "trialing",
14
+ "active",
15
+ "past_due",
16
+ "canceled",
17
+ "unpaid",
18
+ "paused",
19
+ "expired",
20
+ ]);
21
+ const PersistedSubscriptionRowSchema = z
22
+ .object({
23
+ id: postgresUuid,
24
+ subject_id: postgresUuid,
25
+ provider: z.string().min(1),
26
+ provider_subscription_id: z.string().min(1),
27
+ provider_customer_id: z.string().min(1).nullable(),
28
+ offer_id: postgresUuid,
29
+ catalog_revision_id: postgresUuid,
30
+ status: SubscriptionStatusSchema,
31
+ current_period_start: timestamp.nullable(),
32
+ current_period_end: timestamp.nullable(),
33
+ trial_end: timestamp.nullable(),
34
+ cancel_at: timestamp.nullable(),
35
+ ended_at: timestamp.nullable(),
36
+ grace_ends_at: timestamp.nullable(),
37
+ grace_expired_at: timestamp.nullable(),
38
+ provider_updated_at: timestamp,
39
+ cancel_at_period_end: pgBoolean,
40
+ metadata: z.record(z.string(), z.unknown()),
41
+ })
42
+ .strict();
43
+ const CatalogReferenceSchema = z
44
+ .object({
45
+ offer_id: postgresUuid,
46
+ catalog_revision_id: postgresUuid,
47
+ })
48
+ .strict();
49
+ const OfferContextSchema = z
50
+ .object({
51
+ offer_key: z.string().min(1),
52
+ plan_id: postgresUuid,
53
+ plan_key: z.string().min(1),
54
+ billing_unit: z.enum(["day", "week", "month", "year"]),
55
+ billing_count: z.number().int().positive(),
56
+ })
57
+ .strict();
3
58
  const SubscriptionRowSchema = z
4
59
  .object({
5
- user_id: z.string().optional(),
6
- subject_id: z.string().optional(),
7
- provider: z.string(),
8
- provider_subscription_id: z.string(),
9
- provider_customer_id: z.string().nullable().optional(),
10
- offer_id: z.string().nullable().optional(),
11
- status: z.string().optional(),
12
- current_period_start: z.unknown().optional(),
13
- current_period_end: z.unknown().optional(),
14
- trial_end: z.unknown().optional(),
15
- cancel_at: z.unknown().optional(),
16
- ended_at: z.unknown().optional(),
17
- grace_ends_at: z.unknown().optional(),
18
- grace_expired_at: z.unknown().optional(),
19
- provider_updated_at: z.unknown().optional(),
20
- cancel_at_period_end: pgBoolean.nullable().optional(),
21
- metadata: z.record(z.string(), z.unknown()).nullable().optional(),
60
+ id: postgresUuid,
61
+ user_id: postgresUuid,
62
+ provider: z.string().min(1),
63
+ provider_subscription_id: z.string().min(1),
64
+ provider_customer_id: z.string().min(1).nullable(),
65
+ offer_id: postgresUuid,
66
+ offer_key: z.string().min(1),
67
+ plan_id: postgresUuid,
68
+ plan: z.string().min(1),
69
+ status: SubscriptionStatusSchema,
70
+ current_period_start: timestamp.nullable(),
71
+ current_period_end: timestamp.nullable(),
72
+ trial_end: timestamp.nullable(),
73
+ cancel_at: timestamp.nullable(),
74
+ ended_at: timestamp.nullable(),
75
+ grace_ends_at: timestamp.nullable(),
76
+ grace_expired_at: timestamp.nullable(),
77
+ provider_updated_at: timestamp,
78
+ cancel_at_period_end: pgBoolean,
79
+ interval: z.enum(["day", "week", "month", "year"]),
80
+ interval_count: z.number().int().positive(),
81
+ metadata: z.record(z.string(), z.unknown()),
22
82
  })
23
- .passthrough();
24
- function timestampValue(value) {
25
- if (value instanceof Date) {
26
- const timestamp = value.getTime();
27
- return Number.isNaN(timestamp) ? null : timestamp;
28
- }
29
- const timestamp = Date.parse(String(value ?? ""));
30
- return Number.isNaN(timestamp) ? null : timestamp;
83
+ .strict();
84
+ function record(value, context) {
85
+ return safeParse(z.record(z.string(), z.unknown()), value, context);
31
86
  }
32
- function compareProviderTimestampsDescending(left, right) {
33
- const leftTimestamp = timestampValue(left.provider_updated_at);
34
- const rightTimestamp = timestampValue(right.provider_updated_at);
35
- if (leftTimestamp === null)
36
- return rightTimestamp === null ? 0 : 1;
37
- if (rightTimestamp === null)
38
- return -1;
39
- return rightTimestamp - leftTimestamp;
87
+ function persistedSubscription(row, context) {
88
+ const value = record(row, context);
89
+ return safeParse(PersistedSubscriptionRowSchema, {
90
+ id: value.id,
91
+ subject_id: value.subject_id,
92
+ provider: value.provider,
93
+ provider_subscription_id: value.provider_subscription_id,
94
+ provider_customer_id: value.provider_customer_id,
95
+ offer_id: value.offer_id,
96
+ catalog_revision_id: value.catalog_revision_id,
97
+ status: value.status,
98
+ current_period_start: value.current_period_start,
99
+ current_period_end: value.current_period_end,
100
+ trial_end: value.trial_end,
101
+ cancel_at: value.cancel_at,
102
+ ended_at: value.ended_at,
103
+ grace_ends_at: value.grace_ends_at,
104
+ grace_expired_at: value.grace_expired_at,
105
+ provider_updated_at: value.provider_updated_at,
106
+ cancel_at_period_end: value.cancel_at_period_end,
107
+ metadata: value.metadata,
108
+ }, context);
40
109
  }
41
110
  export class BillingSubscriptionRepository {
42
111
  query;
@@ -44,65 +113,103 @@ export class BillingSubscriptionRepository {
44
113
  this.query = query;
45
114
  }
46
115
  async upsert(state) {
47
- const provider = String(state.provider ?? "");
48
- const providerSubscriptionId = String(state.providerSubscriptionId ?? "");
49
- let userId = String(state.userId ?? state.subjectId ?? "");
116
+ const provider = state.provider;
117
+ const providerSubscriptionId = state.providerSubscriptionId;
118
+ const userId = state.userId;
50
119
  let providerCustomerId = state.providerCustomerId ?? null;
51
- let offerId = String(state.offerId ?? state.offer_id ?? "");
120
+ let offerId = state.offerId ?? null;
52
121
  if (!provider || !providerSubscriptionId) {
53
- throw new Error("subscription.upsert: subject, provider, subscription, and offer are required");
122
+ throw new TypeError("subscription.upsert: subject, provider, subscription, and offer are required");
54
123
  }
55
124
  const existing = await this.query(`SELECT * FROM bursar.get_billing_subscription_by_provider($1, $2)`, [provider, providerSubscriptionId]);
56
- const existingRow = existing[0];
57
- if (!userId && existingRow?.subject_id != null)
58
- userId = String(existingRow.subject_id);
59
- if (providerCustomerId == null && existingRow?.provider_customer_id != null) {
60
- providerCustomerId = String(existingRow.provider_customer_id);
125
+ const rawExisting = optionalRecordRow(existing, "BillingSubscriptionRepository.upsert.existing");
126
+ const existingRow = rawExisting === null
127
+ ? null
128
+ : persistedSubscription(rawExisting, "BillingSubscriptionRepository.upsert.existing");
129
+ if (providerCustomerId === null && existingRow !== null) {
130
+ providerCustomerId = existingRow.provider_customer_id;
61
131
  }
62
- if (!offerId && existingRow?.offer_id != null)
63
- offerId = String(existingRow.offer_id);
64
- const offerKey = String(state.offerKey ?? state.offer_key ?? "");
65
- if (!offerId && offerKey) {
132
+ if (offerId === null && existingRow !== null)
133
+ offerId = existingRow.offer_id;
134
+ const offerKey = state.offerKey ?? null;
135
+ if (offerId === null && offerKey !== null) {
66
136
  const offerRows = await this.query(`SELECT * FROM bursar.resolve_active_catalog_offer($1)`, [
67
137
  offerKey,
68
138
  ]);
69
- const offerRow = offerRows[0];
70
- if (offerRow?.id != null)
71
- offerId = String(offerRow.id);
139
+ const offerRow = optionalRecordRow(offerRows, "BillingSubscriptionRepository.upsert.offer");
140
+ if (offerRow !== null) {
141
+ offerId = safeParse(postgresUuid, offerRow.id, "BillingSubscriptionRepository.upsert.offer.id");
142
+ }
72
143
  }
73
144
  if (!userId || !offerId) {
74
- throw new Error("subscription.upsert: subject, provider, subscription, and offer are required");
145
+ throw new TypeError("subscription.upsert: subject, provider, subscription, and offer are required");
75
146
  }
76
- await this.query("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)", [
147
+ const providerUpdatedAt = safeParse(timestamp, state.providerUpdatedAt, "BillingSubscriptionRepository.upsert.providerUpdatedAt");
148
+ const rows = await this.query("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", [
77
149
  userId,
78
150
  provider,
79
151
  providerSubscriptionId,
80
152
  providerCustomerId,
81
153
  offerId,
82
- state.status ?? "incomplete",
154
+ state.status,
83
155
  state.currentPeriodStart ?? null,
84
156
  state.currentPeriodEnd ?? null,
85
- state.cancelAtPeriodEnd ?? false,
157
+ state.cancelAtPeriodEnd,
86
158
  JSON.stringify(state.metadata ?? {}),
87
159
  state.trialEnd ?? null,
88
160
  state.cancelAt ?? null,
89
161
  state.endedAt ?? null,
90
- state.providerUpdatedAt ?? new Date().toISOString(),
162
+ providerUpdatedAt,
91
163
  state.graceEndsAt ?? null,
92
164
  ]);
165
+ requireResultField(rows, "id", postgresUuid, "BillingSubscriptionRepository.upsert");
93
166
  }
94
167
  map(row) {
95
- const r = row;
96
- if (r.subject_id == null && r.provider == null)
97
- return null;
98
- return safeParse(SubscriptionRowSchema, { ...r, user_id: r.subject_id }, "BillingSubscriptionRepository");
168
+ const r = record(row, "BillingSubscriptionRepository.map");
169
+ return safeParse(SubscriptionRowSchema, {
170
+ id: r.id,
171
+ user_id: r.subject_id,
172
+ provider: r.provider,
173
+ provider_subscription_id: r.provider_subscription_id,
174
+ provider_customer_id: r.provider_customer_id,
175
+ offer_id: r.offer_id,
176
+ offer_key: r.offer_key,
177
+ plan_id: r.plan_id,
178
+ plan: r.plan,
179
+ status: r.status,
180
+ current_period_start: r.current_period_start,
181
+ current_period_end: r.current_period_end,
182
+ trial_end: r.trial_end,
183
+ cancel_at: r.cancel_at,
184
+ ended_at: r.ended_at,
185
+ grace_ends_at: r.grace_ends_at,
186
+ grace_expired_at: r.grace_expired_at,
187
+ provider_updated_at: r.provider_updated_at,
188
+ cancel_at_period_end: r.cancel_at_period_end,
189
+ interval: r.interval,
190
+ interval_count: r.interval_count,
191
+ metadata: r.metadata,
192
+ }, "BillingSubscriptionRepository");
99
193
  }
100
- async withOfferContext(row) {
101
- const value = row;
102
- if (value.offer_id == null || value.catalog_revision_id == null)
103
- return value;
104
- const contextRows = await this.query(`SELECT * FROM bursar.get_catalog_offer_context($1::uuid, $2::uuid)`, [value.offer_id, value.catalog_revision_id]);
105
- const context = contextRows[0] ?? {};
194
+ async withOfferContext(value) {
195
+ const reference = safeParse(CatalogReferenceSchema, { offer_id: value.offer_id, catalog_revision_id: value.catalog_revision_id }, "BillingSubscriptionRepository.withOfferContext.reference");
196
+ const contextRows = await this.query(`SELECT * FROM bursar.get_catalog_offer_context($1::uuid, $2::uuid)`, [reference.offer_id, reference.catalog_revision_id]);
197
+ const rawContext = optionalRecordRow(contextRows, "BillingSubscriptionRepository.withOfferContext");
198
+ if (rawContext === null) {
199
+ throw new StoreError("Billing subscription offer context is missing", {
200
+ details: {
201
+ offerId: reference.offer_id,
202
+ catalogRevisionId: reference.catalog_revision_id,
203
+ },
204
+ });
205
+ }
206
+ const context = safeParse(OfferContextSchema, {
207
+ offer_key: rawContext.offer_key,
208
+ plan_id: rawContext.plan_id,
209
+ plan_key: rawContext.plan_key,
210
+ billing_unit: rawContext.billing_unit,
211
+ billing_count: rawContext.billing_count,
212
+ }, "BillingSubscriptionRepository.withOfferContext.context");
106
213
  return {
107
214
  ...value,
108
215
  ...context,
@@ -113,40 +220,43 @@ export class BillingSubscriptionRepository {
113
220
  }
114
221
  async get(provider, providerSubscriptionId) {
115
222
  const rows = await this.query(`SELECT * FROM bursar.get_billing_subscription_by_provider($1, $2)`, [provider, providerSubscriptionId]);
116
- return rows[0] ? this.map(await this.withOfferContext(rows[0])) : null;
223
+ const row = optionalRecordRow(rows, "BillingSubscriptionRepository.get");
224
+ return row === null
225
+ ? null
226
+ : this.map(await this.withOfferContext(persistedSubscription(row, "BillingSubscriptionRepository.get")));
117
227
  }
118
228
  async getUserSubscription(userId, statuses) {
229
+ const allowed = new Set(safeParse(z.array(SubscriptionStatusSchema), statuses ?? ["active", "trialing"], "BillingSubscriptionRepository.getUserSubscription.statuses"));
119
230
  const rows = await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [
120
231
  userId,
121
232
  ]);
122
- const allowed = statuses ?? ["active", "trialing"];
123
233
  const candidates = rows
124
- .filter((row) => allowed.includes(String(row.status)))
125
- .sort(compareProviderTimestampsDescending);
126
- return candidates[0] ? this.map(await this.withOfferContext(candidates[0])) : null;
234
+ .map((row) => persistedSubscription(row, "BillingSubscriptionRepository.getUserSubscription"))
235
+ .filter((row) => allowed.has(row.status))
236
+ .sort((left, right) => Date.parse(right.provider_updated_at) - Date.parse(left.provider_updated_at));
237
+ const selected = candidates[0];
238
+ return selected === undefined ? null : this.map(await this.withOfferContext(selected));
127
239
  }
128
240
  async getUserSubscriptions(userId) {
129
241
  const rows = await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [
130
242
  userId,
131
243
  ]);
132
- const enriched = await Promise.all(rows.map((row) => this.withOfferContext(row)));
133
- return enriched
134
- .map((row) => this.map(row))
135
- .filter((row) => row !== null);
244
+ const persisted = rows.map((row) => persistedSubscription(row, "BillingSubscriptionRepository.getUserSubscriptions"));
245
+ const enriched = await Promise.all(persisted.map((row) => this.withOfferContext(row)));
246
+ return enriched.map((row) => this.map(row));
136
247
  }
137
248
  async listExpiredGraceSubscriptions(now, limit = 100) {
138
249
  const rows = await this.query(`SELECT * FROM bursar.list_expired_grace_subscriptions($1, $2)`, [
139
250
  now,
140
251
  limit,
141
252
  ]);
142
- const enriched = await Promise.all(rows.map((row) => this.withOfferContext(row)));
143
- return enriched
144
- .map((row) => this.map(row))
145
- .filter((row) => row !== null);
253
+ const persisted = rows.map((row) => persistedSubscription(row, "BillingSubscriptionRepository.listExpiredGraceSubscriptions"));
254
+ const enriched = await Promise.all(persisted.map((row) => this.withOfferContext(row)));
255
+ return enriched.map((row) => this.map(row));
146
256
  }
147
257
  async markGraceExpired(subscriptionId, expectedGraceEndsAt, expiredAt) {
148
258
  const rows = await this.query(`SELECT bursar.mark_subscription_grace_expired($1::uuid, $2, $3) AS marked`, [subscriptionId, expectedGraceEndsAt, expiredAt]);
149
- return rows[0]?.marked === true;
259
+ return requireResultField(rows, "marked", pgBoolean, "BillingSubscriptionRepository.markGraceExpired");
150
260
  }
151
261
  async recordConflict(input) {
152
262
  const rows = await this.query(`SELECT bursar.record_subscription_conflict(
@@ -159,27 +269,25 @@ export class BillingSubscriptionRepository {
159
269
  input.eventId ?? null,
160
270
  JSON.stringify(input.metadata ?? {}),
161
271
  ]);
162
- const id = rows[0]?.id;
163
- if (id == null)
164
- throw new Error("subscription conflict audit returned no ID");
165
- return String(id);
272
+ return requireResultField(rows, "id", z.union([z.string().min(1), z.number().int()]).transform(String), "BillingSubscriptionRepository.recordConflict");
166
273
  }
167
274
  /** Select a provider subscription without modifying provider-reported state. */
168
275
  async selectEntitlementSource(userId, provider, providerSubscriptionId) {
169
- const rows = (await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [
170
- userId,
171
- ]));
172
276
  const eligibleStatuses = new Set(["trialing", "active", "past_due", "paused"]);
277
+ const rows = await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [
278
+ userId,
279
+ ]);
173
280
  const replacement = rows
281
+ .map((row) => persistedSubscription(row, "BillingSubscriptionRepository.selectEntitlementSource"))
174
282
  .filter((row) => row.provider === provider &&
175
- eligibleStatuses.has(String(row.status)) &&
283
+ eligibleStatuses.has(row.status) &&
176
284
  (!providerSubscriptionId || row.provider_subscription_id === providerSubscriptionId))
177
- .sort(compareProviderTimestampsDescending)[0];
285
+ .sort((left, right) => Date.parse(right.provider_updated_at) - Date.parse(left.provider_updated_at))[0];
178
286
  if (replacement?.id == null)
179
287
  return false;
180
288
  const selectedRows = await this.query(`SELECT bursar.select_entitlement_source($1::uuid, $2::uuid) AS selected`, [userId, replacement.id]);
181
- if (selectedRows[0]?.selected !== true) {
182
- throw new Error("subscription entitlement source selection was rejected");
289
+ if (!requireResultField(selectedRows, "selected", pgBoolean, "BillingSubscriptionRepository.selectEntitlementSource")) {
290
+ throw new StoreError("subscription entitlement source selection was rejected");
183
291
  }
184
292
  return true;
185
293
  }
@@ -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;AAExB,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,wCAAwC,CAAC;AAE9E,MAAM,qBAAqB,GAAG,CAAC;KAC5B,MAAM,CAAC;IACN,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC9B,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IACjC,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE;IACpB,wBAAwB,EAAE,CAAC,CAAC,MAAM,EAAE;IACpC,oBAAoB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE;IACtD,QAAQ,EAAE,CAAC,CAAC,MAAM,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C;QACF,IAAK,YAAY,CAAC,CAAC,CAAyC,EAAE,QAAQ,KAAK,IAAI,EAAE,CAAC;YAChF,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;QAC5E,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport { pgBoolean, safeParse } from \"../../../shared/postgres-validation.js\";\n\nconst SubscriptionRowSchema = z\n .object({\n user_id: z.string().optional(),\n subject_id: z.string().optional(),\n provider: z.string(),\n provider_subscription_id: z.string(),\n provider_customer_id: z.string().nullable().optional(),\n offer_id: z.string().nullable().optional(),\n status: z.string().optional(),\n current_period_start: z.unknown().optional(),\n current_period_end: z.unknown().optional(),\n trial_end: z.unknown().optional(),\n cancel_at: z.unknown().optional(),\n ended_at: z.unknown().optional(),\n grace_ends_at: z.unknown().optional(),\n grace_expired_at: z.unknown().optional(),\n provider_updated_at: z.unknown().optional(),\n cancel_at_period_end: pgBoolean.nullable().optional(),\n metadata: z.record(z.string(), z.unknown()).nullable().optional(),\n })\n .passthrough();\n\nfunction timestampValue(value: unknown): number | null {\n if (value instanceof Date) {\n const timestamp = value.getTime();\n return Number.isNaN(timestamp) ? null : timestamp;\n }\n const timestamp = Date.parse(String(value ?? \"\"));\n return Number.isNaN(timestamp) ? null : timestamp;\n}\n\nfunction compareProviderTimestampsDescending(\n left: Record<string, unknown>,\n right: Record<string, unknown>,\n): number {\n const leftTimestamp = timestampValue(left.provider_updated_at);\n const rightTimestamp = timestampValue(right.provider_updated_at);\n if (leftTimestamp === null) return rightTimestamp === null ? 0 : 1;\n if (rightTimestamp === null) return -1;\n return rightTimestamp - leftTimestamp;\n}\nexport type SubscriptionRow = z.infer<typeof SubscriptionRowSchema>;\n\nexport class BillingSubscriptionRepository {\n constructor(private query: QueryFn) {}\n\n async upsert(state: Record<string, unknown>): Promise<void> {\n const provider = String(state.provider ?? \"\");\n const providerSubscriptionId = String(state.providerSubscriptionId ?? \"\");\n let userId = String(state.userId ?? state.subjectId ?? \"\");\n let providerCustomerId = state.providerCustomerId ?? null;\n let offerId = String(state.offerId ?? state.offer_id ?? \"\");\n\n if (!provider || !providerSubscriptionId) {\n throw new Error(\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 existingRow = existing[0] as Record<string, unknown> | undefined;\n if (!userId && existingRow?.subject_id != null) userId = String(existingRow.subject_id);\n if (providerCustomerId == null && existingRow?.provider_customer_id != null) {\n providerCustomerId = String(existingRow.provider_customer_id);\n }\n if (!offerId && existingRow?.offer_id != null) offerId = String(existingRow.offer_id);\n\n const offerKey = String(state.offerKey ?? state.offer_key ?? \"\");\n if (!offerId && offerKey) {\n const offerRows = await this.query(`SELECT * FROM bursar.resolve_active_catalog_offer($1)`, [\n offerKey,\n ]);\n const offerRow = offerRows[0] as Record<string, unknown> | undefined;\n if (offerRow?.id != null) offerId = String(offerRow.id);\n }\n\n if (!userId || !offerId) {\n throw new Error(\n \"subscription.upsert: subject, provider, subscription, and offer are required\",\n );\n }\n\n 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)\",\n [\n userId,\n provider,\n providerSubscriptionId,\n providerCustomerId,\n offerId,\n state.status ?? \"incomplete\",\n state.currentPeriodStart ?? null,\n state.currentPeriodEnd ?? null,\n state.cancelAtPeriodEnd ?? false,\n JSON.stringify(state.metadata ?? {}),\n state.trialEnd ?? null,\n state.cancelAt ?? null,\n state.endedAt ?? null,\n state.providerUpdatedAt ?? new Date().toISOString(),\n state.graceEndsAt ?? null,\n ],\n );\n }\n\n private map(row: unknown): SubscriptionRow | null {\n const r = row as Record<string, unknown>;\n if (r.subject_id == null && r.provider == null) return null;\n return safeParse(\n SubscriptionRowSchema,\n { ...r, user_id: r.subject_id },\n \"BillingSubscriptionRepository\",\n );\n }\n\n private async withOfferContext(row: unknown): Promise<Record<string, unknown>> {\n const value = row as Record<string, unknown>;\n if (value.offer_id == null || value.catalog_revision_id == null) return value;\n const contextRows = await this.query(\n `SELECT * FROM bursar.get_catalog_offer_context($1::uuid, $2::uuid)`,\n [value.offer_id, value.catalog_revision_id],\n );\n const context = (contextRows[0] as Record<string, unknown> | undefined) ?? {};\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 return rows[0] ? this.map(await this.withOfferContext(rows[0])) : null;\n }\n async getUserSubscription(userId: string, statuses?: string[]): Promise<SubscriptionRow | null> {\n const rows = await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [\n userId,\n ]);\n const allowed = statuses ?? [\"active\", \"trialing\"];\n const candidates = (rows as Array<Record<string, unknown>>)\n .filter((row) => allowed.includes(String(row.status)))\n .sort(compareProviderTimestampsDescending);\n return candidates[0] ? this.map(await this.withOfferContext(candidates[0])) : null;\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 enriched = await Promise.all(rows.map((row) => this.withOfferContext(row)));\n return enriched\n .map((row) => this.map(row))\n .filter((row): row is SubscriptionRow => row !== null);\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 enriched = await Promise.all(rows.map((row) => this.withOfferContext(row)));\n return enriched\n .map((row) => this.map(row))\n .filter((row): row is SubscriptionRow => row !== null);\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 (rows[0] as Record<string, unknown> | undefined)?.marked === true;\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 const id = (rows[0] as Record<string, unknown> | undefined)?.id;\n if (id == null) throw new Error(\"subscription conflict audit returned no ID\");\n return String(id);\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 rows = (await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [\n userId,\n ])) as Array<Record<string, unknown>>;\n const eligibleStatuses = new Set([\"trialing\", \"active\", \"past_due\", \"paused\"]);\n const replacement = rows\n .filter(\n (row) =>\n row.provider === provider &&\n eligibleStatuses.has(String(row.status)) &&\n (!providerSubscriptionId || row.provider_subscription_id === providerSubscriptionId),\n )\n .sort(compareProviderTimestampsDescending)[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 ((selectedRows[0] as Record<string, unknown> | undefined)?.selected !== true) {\n throw new Error(\"subscription entitlement source selection was rejected\");\n }\n\n return true;\n }\n}\n"]}
1
+ {"version":3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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"]}