@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
@@ -31,19 +31,15 @@ export class BillingInvoiceRepository {
31
31
  async listForUser(userId) {
32
32
  const rows = await this.query(`SELECT * FROM bursar.list_billing_invoices($1::uuid)`, [userId]);
33
33
  return rows.map((row) => {
34
- if (typeof row !== "object" || row === null || Array.isArray(row)) {
35
- throw new TypeError("BillingInvoiceRepository.listForUser expected an object row");
36
- }
37
- const raw = row;
38
34
  const parsed = safeParse(InvoiceRowSchema, {
39
- provider: raw.provider,
40
- provider_invoice_id: raw.provider_invoice_id,
41
- status: raw.status,
42
- amount_paid_minor: raw.amount_paid_minor,
43
- amount_due_minor: raw.amount_due_minor,
44
- currency: raw.currency,
45
- period_start: raw.period_start,
46
- period_end: raw.period_end,
35
+ provider: row.provider,
36
+ provider_invoice_id: row.provider_invoice_id,
37
+ status: row.status,
38
+ amount_paid_minor: row.amount_paid_minor,
39
+ amount_due_minor: row.amount_due_minor,
40
+ currency: row.currency,
41
+ period_start: row.period_start,
42
+ period_end: row.period_end,
47
43
  }, "BillingInvoiceRepository.listForUser");
48
44
  return {
49
45
  provider: parsed.provider,
@@ -1 +1 @@
1
- {"version":3,"file":"invoice.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/invoice.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EACL,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,cAAc,GAAG,CAAC;KACrB,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;KACzE,SAAS,CAAC,MAAM,CAAC;KACjB,MAAM,CAAC,MAAM,CAAC,aAAa,EAAE,2DAA2D,CAAC,CAAC;AAC7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B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,kHAAkH,EAClH;YACE,SAAS;YACT,QAAQ;YACR,iBAAiB;YACjB,cAAc;YACd,MAAM;YACN,cAAc;YACd,eAAe;YACf,QAAQ;YACR,WAAW;YACX,SAAS;YACT,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC;YACxB,iBAAiB;SAClB,CACF,CAAC;QACF,kBAAkB,CAAC,IAAI,EAAE,IAAI,EAAE,YAAY,EAAE,iCAAiC,CAAC,CAAC;IAClF,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { BillingInvoiceRecord } from \"../../types/index.js\";\nimport {\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst safeMinorUnits = z\n .union([z.number().int().nonnegative().safe(), z.string().regex(/^\\d+$/)])\n .transform(Number)\n .refine(Number.isSafeInteger, \"minor-unit amount exceeds JavaScript's safe integer range\");\nconst optionalTimestamp = z\n .union([\n z.date().refine((value) => !Number.isNaN(value.getTime())),\n z.string().datetime({ offset: true }),\n ])\n .transform((value) => (value instanceof Date ? value.toISOString() : value))\n .nullable();\n\nconst InvoiceRowSchema = z\n .object({\n provider: z.string().min(1),\n provider_invoice_id: z.string().min(1),\n status: z.enum([\"draft\", \"open\", \"paid\", \"void\", \"uncollectible\"]),\n amount_paid_minor: safeMinorUnits,\n amount_due_minor: safeMinorUnits,\n currency: z.string().regex(/^[A-Z]{3}$/),\n period_start: optionalTimestamp,\n period_end: optionalTimestamp,\n })\n .strict();\n\nexport class BillingInvoiceRepository {\n constructor(private query: QueryFn) {}\n\n async listForUser(userId: string): Promise<BillingInvoiceRecord[]> {\n const rows = await this.query(`SELECT * FROM bursar.list_billing_invoices($1::uuid)`, [userId]);\n return rows.map((row) => {\n if (typeof row !== \"object\" || row === null || Array.isArray(row)) {\n throw new TypeError(\"BillingInvoiceRepository.listForUser expected an object row\");\n }\n const raw = row as Record<string, unknown>;\n const parsed = safeParse(\n InvoiceRowSchema,\n {\n provider: raw.provider,\n provider_invoice_id: raw.provider_invoice_id,\n status: raw.status,\n amount_paid_minor: raw.amount_paid_minor,\n amount_due_minor: raw.amount_due_minor,\n currency: raw.currency,\n period_start: raw.period_start,\n period_end: raw.period_end,\n },\n \"BillingInvoiceRepository.listForUser\",\n );\n return {\n provider: parsed.provider,\n providerInvoiceId: parsed.provider_invoice_id,\n status: parsed.status,\n amountPaidMinor: parsed.amount_paid_minor,\n amountDueMinor: parsed.amount_due_minor,\n currency: parsed.currency,\n periodStart: parsed.period_start,\n periodEnd: parsed.period_end,\n } satisfies BillingInvoiceRecord;\n });\n }\n\n async upsert(\n subjectId: string,\n provider: string,\n providerInvoiceId: string,\n subscriptionId: string | null,\n status: \"draft\" | \"open\" | \"paid\" | \"void\" | \"uncollectible\",\n amountPaidMinor: number,\n amountDueMinor: number,\n currency: string,\n periodStart: string | null,\n periodEnd: string | null,\n metadata: Record<string, unknown>,\n providerUpdatedAt: string,\n ): Promise<void> {\n const rows = await this.query(\n `SELECT bursar.upsert_billing_invoice($1::uuid, $2, $3, $4::uuid, $5, $6, $7, $8, $9, $10, $11::jsonb, $12) AS id`,\n [\n subjectId,\n provider,\n providerInvoiceId,\n subscriptionId,\n status,\n amountDueMinor,\n amountPaidMinor,\n currency,\n periodStart,\n periodEnd,\n JSON.stringify(metadata),\n providerUpdatedAt,\n ],\n );\n requireResultField(rows, \"id\", postgresUuid, \"BillingInvoiceRepository.upsert\");\n }\n}\n"]}
1
+ {"version":3,"file":"invoice.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/invoice.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB,OAAO,EACL,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,cAAc,GAAG,CAAC;KACrB,KAAK,CAAC,CAAC,CAA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,QAAoB,EACpB,iBAAyB;QAEzB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,kHAAkH,EAClH;YACE,SAAS;YACT,QAAQ;YACR,iBAAiB;YACjB,cAAc;YACd,MAAM;YACN,cAAc;YACd,eAAe;YACf,QAAQ;YACR,WAAW;YACX,SAAS;YACT,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC;YACxB,iBAAiB;SAClB,CACF,CAAC;QACF,kBAAkB,CAAC,IAAI,EAAE,IAAI,EAAE,YAAY,EAAE,iCAAiC,CAAC,CAAC;IAClF,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { JsonObject } from \"../../../shared/json.js\";\nimport type { BillingInvoiceRecord } from \"../../types/index.js\";\nimport {\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst safeMinorUnits = z\n .union([z.number().int().nonnegative().safe(), z.string().regex(/^\\d+$/)])\n .transform(Number)\n .refine(Number.isSafeInteger, \"minor-unit amount exceeds JavaScript's safe integer range\");\nconst optionalTimestamp = z\n .union([\n z.date().refine((value) => !Number.isNaN(value.getTime())),\n z.string().datetime({ offset: true }),\n ])\n .transform((value) => (value instanceof Date ? value.toISOString() : value))\n .nullable();\n\nconst InvoiceRowSchema = z\n .object({\n provider: z.string().min(1),\n provider_invoice_id: z.string().min(1),\n status: z.enum([\"draft\", \"open\", \"paid\", \"void\", \"uncollectible\"]),\n amount_paid_minor: safeMinorUnits,\n amount_due_minor: safeMinorUnits,\n currency: z.string().regex(/^[A-Z]{3}$/),\n period_start: optionalTimestamp,\n period_end: optionalTimestamp,\n })\n .strict();\n\nexport class BillingInvoiceRepository {\n constructor(private query: QueryFn) {}\n\n async listForUser(userId: string): Promise<BillingInvoiceRecord[]> {\n const rows = await this.query(`SELECT * FROM bursar.list_billing_invoices($1::uuid)`, [userId]);\n return rows.map((row) => {\n const parsed = safeParse(\n InvoiceRowSchema,\n {\n provider: row.provider,\n provider_invoice_id: row.provider_invoice_id,\n status: row.status,\n amount_paid_minor: row.amount_paid_minor,\n amount_due_minor: row.amount_due_minor,\n currency: row.currency,\n period_start: row.period_start,\n period_end: row.period_end,\n },\n \"BillingInvoiceRepository.listForUser\",\n );\n return {\n provider: parsed.provider,\n providerInvoiceId: parsed.provider_invoice_id,\n status: parsed.status,\n amountPaidMinor: parsed.amount_paid_minor,\n amountDueMinor: parsed.amount_due_minor,\n currency: parsed.currency,\n periodStart: parsed.period_start,\n periodEnd: parsed.period_end,\n } satisfies BillingInvoiceRecord;\n });\n }\n\n async upsert(\n subjectId: string,\n provider: string,\n providerInvoiceId: string,\n subscriptionId: string | null,\n status: \"draft\" | \"open\" | \"paid\" | \"void\" | \"uncollectible\",\n amountPaidMinor: number,\n amountDueMinor: number,\n currency: string,\n periodStart: string | null,\n periodEnd: string | null,\n metadata: JsonObject,\n providerUpdatedAt: string,\n ): Promise<void> {\n const rows = await this.query(\n `SELECT bursar.upsert_billing_invoice($1::uuid, $2, $3, $4::uuid, $5, $6, $7, $8, $9, $10, $11::jsonb, $12) AS id`,\n [\n subjectId,\n provider,\n providerInvoiceId,\n subscriptionId,\n status,\n amountDueMinor,\n amountPaidMinor,\n currency,\n periodStart,\n periodEnd,\n JSON.stringify(metadata),\n providerUpdatedAt,\n ],\n );\n requireResultField(rows, \"id\", postgresUuid, \"BillingInvoiceRepository.upsert\");\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"offer.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/offer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAGrC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAgDjE,UAAU,mBAAmB;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,IAA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G,mBAAmB,GAC/C,CACI;IACE,YAAY,EAAE,IAAI,CAAC;IACnB,WAAW,EAAE,IAAI,CAAC;IAClB,iBAAiB,EAAE,KAAK,CAAC;CAC1B,GACD;IACE,YAAY,EAAE,OAAO,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,EAAE,OAAO,CAAC;CAC5B,CACJ,CAAC;AAEJ,+CAA+C;AAC/C,qBAAa,sBAAsB;IACrB,OAAO,CAAC,QAAQ,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAErC,cAAc,CAClB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,GAAG,IAAI,EACtB,SAAS,EAAE,MAAM,GAAG,IAAI,GACvB,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;IAK5B,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;YAI7E,OAAO;CAuGtB"}
@@ -92,6 +92,11 @@ export class BillingOfferRepository {
92
92
  });
93
93
  }
94
94
  const rawContext = contextRows[0];
95
+ if (rawContext === undefined) {
96
+ throw new StoreError("BillingOfferRepository: catalog plan context is missing", {
97
+ details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },
98
+ });
99
+ }
95
100
  const offerContext = safeParse(OfferContextRowSchema, {
96
101
  offer_key: rawContext.offer_key,
97
102
  plan_id: rawContext.plan_id,
@@ -1 +1 @@
1
- {"version":3,"file":"offer.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/offer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,wCAAwC,CAAC;AAE9F,MAAM,qB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MAAM,EAAE,YAAY,CAAC,OAAO;YAC5B,QAAQ,EAAE,KAAK,CAAC,SAAS;YACzB,IAAI,EAAE,KAAK,CAAC,QAAQ;YACpB,QAAQ,EAAE,KAAK,CAAC,YAAY;YAC5B,aAAa,EAAE,KAAK,CAAC,aAAa;SACnC,CAAC;QACF,IAAI,KAAK,CAAC,kBAAkB,KAAK,IAAI,EAAE,CAAC;YACtC,OAAO;gBACL,GAAG,aAAa;gBAChB,YAAY,EAAE,IAAI;gBAClB,WAAW,EAAE,IAAI;gBACjB,iBAAiB,EAAE,KAAK;aACzB,CAAC;QACJ,CAAC;QACD,IAAI,KAAK,CAAC,sBAAsB,KAAK,IAAI,IAAI,KAAK,CAAC,mBAAmB,KAAK,IAAI,EAAE,CAAC;YAChF,MAAM,IAAI,UAAU,CAAC,GAAG,OAAO,gDAAgD,EAAE;gBAC/E,OAAO,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,EAAE,iBAAiB,EAAE,KAAK,CAAC,mBAAmB,EAAE;aAC7E,CAAC,CAAC;QACL,CAAC;QACD,OAAO;YACL,GAAG,aAAa;YAChB,YAAY,EAAE,KAAK,CAAC,kBAAkB;YACtC,WAAW,EAAE,KAAK,CAAC,sBAAsB;YACzC,iBAAiB,EAAE,KAAK,CAAC,mBAAmB,KAAK,kBAAkB;SACpE,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { z } from \"zod\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport { postgresUuid, safeParse, unwrapJsonb } from \"../../../shared/postgres-validation.js\";\n\nconst PositiveDecimalSchema = z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .transform((value) => new Decimal(value))\n .refine((value) => value.isFinite() && value.gt(0), \"expected a finite positive decimal\");\n\nconst CatalogOfferRowSchema = z\n .object({\n id: postgresUuid,\n catalog_revision_id: postgresUuid,\n offer_key: z.string().min(1),\n plan_key: z.string().min(1),\n billing_unit: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n billing_count: z.number().int().positive(),\n cycle_grant_amount: PositiveDecimalSchema.nullable(),\n cycle_grant_bucket_key: z.string().min(1).nullable(),\n cycle_grant_renewal: z.enum([\"replace_previous\", \"accumulate\"]).nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n const grantFields = [\n row.cycle_grant_amount,\n row.cycle_grant_bucket_key,\n row.cycle_grant_renewal,\n ];\n if (\n grantFields.some((value) => value !== null) &&\n grantFields.some((value) => value === null)\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"cycle grant fields must either all be set or all be null\",\n });\n }\n });\n\nconst OfferContextRowSchema = z\n .object({\n offer_key: z.string().min(1),\n plan_id: postgresUuid,\n plan_key: z.string().min(1),\n billing_unit: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n billing_count: z.number().int().positive(),\n })\n .strict();\n\ninterface BillingOfferRowBase {\n id: string;\n planId: string;\n offerKey: string;\n plan: string;\n interval: \"day\" | \"week\" | \"month\" | \"year\";\n intervalCount: number;\n}\n\nexport type BillingOfferRow = BillingOfferRowBase &\n (\n | {\n grantCredits: null;\n grantBucket: null;\n grantReplacePrior: false;\n }\n | {\n grantCredits: Decimal;\n grantBucket: string;\n grantReplacePrior: boolean;\n }\n );\n\n/** Repository for billing offer resolution. */\nexport class BillingOfferRepository {\n constructor(private readonly query: QueryFn) {}\n\n async resolveByPrice(\n provider: string,\n priceId: string | null,\n productId: string | null,\n ): Promise<BillingOfferRow | null> {\n const lookupType = priceId !== null ? \"price_id\" : \"product_id\";\n return this.resolve(provider, lookupType, priceId ?? productId, \"resolveByPrice\");\n }\n\n async resolveByLookup(provider: string, lookupKey: string): Promise<BillingOfferRow | null> {\n return this.resolve(provider, \"external_id\", lookupKey, \"resolveByLookup\");\n }\n\n private async resolve(\n provider: string,\n lookupType: \"price_id\" | \"product_id\" | \"external_id\",\n lookupValue: string | null,\n operation: string,\n ): Promise<BillingOfferRow | null> {\n if (!provider.trim()) throw new TypeError(\"provider must not be empty\");\n if (!lookupValue?.trim()) return null;\n\n const context = `BillingOfferRepository.${operation}`;\n const rows = await this.query(\"SELECT * FROM bursar.resolve_catalog_offer($1, $2, $3)\", [\n provider,\n lookupType,\n lookupValue,\n ]);\n if (rows.length > 1) {\n throw new StoreError(`${context}: expected at most one offer`, {\n details: { rowCount: rows.length },\n });\n }\n const raw = unwrapJsonb(rows);\n if (raw?.id == null) return null;\n const offer = safeParse(\n CatalogOfferRowSchema,\n {\n id: raw.id,\n catalog_revision_id: raw.catalog_revision_id,\n offer_key: raw.offer_key,\n plan_key: raw.plan_key,\n billing_unit: raw.billing_unit,\n billing_count: raw.billing_count,\n cycle_grant_amount: raw.cycle_grant_amount,\n cycle_grant_bucket_key: raw.cycle_grant_bucket_key,\n cycle_grant_renewal: raw.cycle_grant_renewal,\n },\n context,\n );\n\n const contextRows = await this.query(\n \"SELECT * FROM bursar.get_catalog_offer_context($1::uuid, $2::uuid)\",\n [offer.id, offer.catalog_revision_id],\n );\n if (contextRows.length !== 1) {\n throw new StoreError(`${context}: catalog plan context is missing`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n const rawContext = contextRows[0] as Record<string, unknown>;\n const offerContext = safeParse(\n OfferContextRowSchema,\n {\n offer_key: rawContext.offer_key,\n plan_id: rawContext.plan_id,\n plan_key: rawContext.plan_key,\n billing_unit: rawContext.billing_unit,\n billing_count: rawContext.billing_count,\n },\n `${context}.context`,\n );\n if (\n offerContext.offer_key !== offer.offer_key ||\n offerContext.plan_key !== offer.plan_key ||\n offerContext.billing_unit !== offer.billing_unit ||\n offerContext.billing_count !== offer.billing_count\n ) {\n throw new StoreError(`${context}: catalog plan context does not match the resolved offer`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n\n const resolvedOffer: BillingOfferRowBase = {\n id: offer.id,\n planId: offerContext.plan_id,\n offerKey: offer.offer_key,\n plan: offer.plan_key,\n interval: offer.billing_unit,\n intervalCount: offer.billing_count,\n };\n if (offer.cycle_grant_amount === null) {\n return {\n ...resolvedOffer,\n grantCredits: null,\n grantBucket: null,\n grantReplacePrior: false,\n };\n }\n if (offer.cycle_grant_bucket_key === null || offer.cycle_grant_renewal === null) {\n throw new StoreError(`${context}: resolved offer has an incomplete cycle grant`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n return {\n ...resolvedOffer,\n grantCredits: offer.cycle_grant_amount,\n grantBucket: offer.cycle_grant_bucket_key,\n grantReplacePrior: offer.cycle_grant_renewal === \"replace_previous\",\n };\n }\n}\n"]}
1
+ {"version":3,"file":"offer.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/offer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,wCAAwC,CAAC;AAE9F,MAAM,qBAAqB,GAAG,CAAC;KAC5B,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC;KACtD,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC;KACxC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,EAAE,IAAI,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,oCAAoC,CAAC,CAAC;AAE5F,MAAM,qBAAqB,GAAG,CAAC;KAC5B,MAAM,CAAC;IACN,EAAE,EAAE,YAAY;IAChB,mBAAmB,EAAE,YAAY;IACjC,SAAS,EAAE,CAAC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YAAY,EAAE,IAAI;gBAClB,WAAW,EAAE,IAAI;gBACjB,iBAAiB,EAAE,KAAK;aACzB,CAAC;QACJ,CAAC;QACD,IAAI,KAAK,CAAC,sBAAsB,KAAK,IAAI,IAAI,KAAK,CAAC,mBAAmB,KAAK,IAAI,EAAE,CAAC;YAChF,MAAM,IAAI,UAAU,CAAC,GAAG,OAAO,gDAAgD,EAAE;gBAC/E,OAAO,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,EAAE,iBAAiB,EAAE,KAAK,CAAC,mBAAmB,EAAE;aAC7E,CAAC,CAAC;QACL,CAAC;QACD,OAAO;YACL,GAAG,aAAa;YAChB,YAAY,EAAE,KAAK,CAAC,kBAAkB;YACtC,WAAW,EAAE,KAAK,CAAC,sBAAsB;YACzC,iBAAiB,EAAE,KAAK,CAAC,mBAAmB,KAAK,kBAAkB;SACpE,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { z } from \"zod\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport { postgresUuid, safeParse, unwrapJsonb } from \"../../../shared/postgres-validation.js\";\n\nconst PositiveDecimalSchema = z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .transform((value) => new Decimal(value))\n .refine((value) => value.isFinite() && value.gt(0), \"expected a finite positive decimal\");\n\nconst CatalogOfferRowSchema = z\n .object({\n id: postgresUuid,\n catalog_revision_id: postgresUuid,\n offer_key: z.string().min(1),\n plan_key: z.string().min(1),\n billing_unit: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n billing_count: z.number().int().positive(),\n cycle_grant_amount: PositiveDecimalSchema.nullable(),\n cycle_grant_bucket_key: z.string().min(1).nullable(),\n cycle_grant_renewal: z.enum([\"replace_previous\", \"accumulate\"]).nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n const grantFields = [\n row.cycle_grant_amount,\n row.cycle_grant_bucket_key,\n row.cycle_grant_renewal,\n ];\n if (\n grantFields.some((value) => value !== null) &&\n grantFields.some((value) => value === null)\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"cycle grant fields must either all be set or all be null\",\n });\n }\n });\n\nconst OfferContextRowSchema = z\n .object({\n offer_key: z.string().min(1),\n plan_id: postgresUuid,\n plan_key: z.string().min(1),\n billing_unit: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n billing_count: z.number().int().positive(),\n })\n .strict();\n\ninterface BillingOfferRowBase {\n id: string;\n planId: string;\n offerKey: string;\n plan: string;\n interval: \"day\" | \"week\" | \"month\" | \"year\";\n intervalCount: number;\n}\n\nexport type BillingOfferRow = BillingOfferRowBase &\n (\n | {\n grantCredits: null;\n grantBucket: null;\n grantReplacePrior: false;\n }\n | {\n grantCredits: Decimal;\n grantBucket: string;\n grantReplacePrior: boolean;\n }\n );\n\n/** Repository for billing offer resolution. */\nexport class BillingOfferRepository {\n constructor(private readonly query: QueryFn) {}\n\n async resolveByPrice(\n provider: string,\n priceId: string | null,\n productId: string | null,\n ): Promise<BillingOfferRow | null> {\n const lookupType = priceId !== null ? \"price_id\" : \"product_id\";\n return this.resolve(provider, lookupType, priceId ?? productId, \"resolveByPrice\");\n }\n\n async resolveByLookup(provider: string, lookupKey: string): Promise<BillingOfferRow | null> {\n return this.resolve(provider, \"external_id\", lookupKey, \"resolveByLookup\");\n }\n\n private async resolve(\n provider: string,\n lookupType: \"price_id\" | \"product_id\" | \"external_id\",\n lookupValue: string | null,\n operation: string,\n ): Promise<BillingOfferRow | null> {\n if (!provider.trim()) throw new TypeError(\"provider must not be empty\");\n if (!lookupValue?.trim()) return null;\n\n const context = `BillingOfferRepository.${operation}`;\n const rows = await this.query(\"SELECT * FROM bursar.resolve_catalog_offer($1, $2, $3)\", [\n provider,\n lookupType,\n lookupValue,\n ]);\n if (rows.length > 1) {\n throw new StoreError(`${context}: expected at most one offer`, {\n details: { rowCount: rows.length },\n });\n }\n const raw = unwrapJsonb(rows);\n if (raw?.id == null) return null;\n const offer = safeParse(\n CatalogOfferRowSchema,\n {\n id: raw.id,\n catalog_revision_id: raw.catalog_revision_id,\n offer_key: raw.offer_key,\n plan_key: raw.plan_key,\n billing_unit: raw.billing_unit,\n billing_count: raw.billing_count,\n cycle_grant_amount: raw.cycle_grant_amount,\n cycle_grant_bucket_key: raw.cycle_grant_bucket_key,\n cycle_grant_renewal: raw.cycle_grant_renewal,\n },\n context,\n );\n\n const contextRows = await this.query(\n \"SELECT * FROM bursar.get_catalog_offer_context($1::uuid, $2::uuid)\",\n [offer.id, offer.catalog_revision_id],\n );\n if (contextRows.length !== 1) {\n throw new StoreError(`${context}: catalog plan context is missing`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n const rawContext = contextRows[0];\n if (rawContext === undefined) {\n throw new StoreError(\"BillingOfferRepository: catalog plan context is missing\", {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n const offerContext = safeParse(\n OfferContextRowSchema,\n {\n offer_key: rawContext.offer_key,\n plan_id: rawContext.plan_id,\n plan_key: rawContext.plan_key,\n billing_unit: rawContext.billing_unit,\n billing_count: rawContext.billing_count,\n },\n `${context}.context`,\n );\n if (\n offerContext.offer_key !== offer.offer_key ||\n offerContext.plan_key !== offer.plan_key ||\n offerContext.billing_unit !== offer.billing_unit ||\n offerContext.billing_count !== offer.billing_count\n ) {\n throw new StoreError(`${context}: catalog plan context does not match the resolved offer`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n\n const resolvedOffer: BillingOfferRowBase = {\n id: offer.id,\n planId: offerContext.plan_id,\n offerKey: offer.offer_key,\n plan: offer.plan_key,\n interval: offer.billing_unit,\n intervalCount: offer.billing_count,\n };\n if (offer.cycle_grant_amount === null) {\n return {\n ...resolvedOffer,\n grantCredits: null,\n grantBucket: null,\n grantReplacePrior: false,\n };\n }\n if (offer.cycle_grant_bucket_key === null || offer.cycle_grant_renewal === null) {\n throw new StoreError(`${context}: resolved offer has an incomplete cycle grant`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n return {\n ...resolvedOffer,\n grantCredits: offer.cycle_grant_amount,\n grantBucket: offer.cycle_grant_bucket_key,\n grantReplacePrior: offer.cycle_grant_renewal === \"replace_previous\",\n };\n }\n}\n"]}
@@ -20,7 +20,7 @@ declare const BillingPaymentRowSchema: z.ZodObject<{
20
20
  canceled: "canceled";
21
21
  }>;
22
22
  provider_updated_at: z.ZodUnion<readonly [z.ZodString, z.ZodDate]>;
23
- metadata: z.ZodRecord<z.ZodString, z.ZodUnknown>;
23
+ metadata: z.ZodRecord<z.ZodString, z.ZodJSONSchema>;
24
24
  }, z.core.$strict>;
25
25
  export type BillingPaymentRow = z.infer<typeof BillingPaymentRowSchema>;
26
26
  export type ForRefundRow = BillingPaymentRow;
@@ -1 +1 @@
1
- {"version":3,"file":"payment.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/payment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAajE,QAAA,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;;;kBAelB,CAAC;AACZ,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,uBAAuB,CAAC,CAAC;AACxE,MAAM,MAAM,YAAY,GAAG,iBAAiB,CAAC;AAuB7C,qBAAa,wBAAwB;IACvB,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAC5B,MAAM,CACV,QAAQ,EAAE,MAAM,EAChB,iBAAiB,EAAE,MAAM,EACzB,iBAAiB,EAAE,MAAM,GAAG,IAAI,EAChC,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,cAAc,GA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CAAC;IAyBZ,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IAQvF,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC;CAQhG"}
@@ -17,7 +17,7 @@ const BillingPaymentRowSchema = z
17
17
  purpose: z.enum(["subscription", "credit_topup"]),
18
18
  status: z.enum(["pending", "succeeded", "failed", "canceled"]),
19
19
  provider_updated_at: z.union([z.string().datetime({ offset: true }), z.date()]),
20
- metadata: z.record(z.string(), z.unknown()),
20
+ metadata: z.record(z.string(), z.json()),
21
21
  })
22
22
  .strict();
23
23
  function parsePaymentRow(row, context) {
@@ -1 +1 @@
1
- {"version":3,"file":"payment.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/payment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,sBAAsB,GAAG,CAAC,CAAC,KAAK,CAAC;IACrC,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC;IACzB,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE;CACtC,CAAC,CAAC;AAEH,MAAM,uBAAuB,GAAG,CAAC;KAC9B,MAAM,CAAC;IACN,EAAE,EAAE,YAAY;IAChB,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3B,mBAAmB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IACtC,mBAAmB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IA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AI,CAAC,KAAK,CAAC,6DAA6D,EAAE;YAC3F,QAAQ;YACR,iBAAiB;SAClB,CAAC,CAAC;QACH,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,oCAAoC,CAAC,CAAC;QAC1E,OAAO,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,GAAG,EAAE,oCAAoC,CAAC,CAAC;IAC1F,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst PgSafeMinorUnitsSchema = z.union([\n z.string().regex(/^\\d+$/),\n z.number().int().nonnegative().safe(),\n]);\n\nconst BillingPaymentRowSchema = z\n .object({\n id: postgresUuid,\n provider: z.string().min(1),\n provider_payment_id: z.string().min(1),\n provider_invoice_id: z.string().nullable(),\n subject_id: postgresUuid,\n amount_minor: PgSafeMinorUnitsSchema,\n tax_minor: PgSafeMinorUnitsSchema,\n currency: z.string().regex(/^[A-Z]{3}$/),\n purpose: z.enum([\"subscription\", \"credit_topup\"]),\n status: z.enum([\"pending\", \"succeeded\", \"failed\", \"canceled\"]),\n provider_updated_at: z.union([z.string().datetime({ offset: true }), z.date()]),\n metadata: z.record(z.string(), z.unknown()),\n })\n .strict();\nexport type BillingPaymentRow = z.infer<typeof BillingPaymentRowSchema>;\nexport type ForRefundRow = BillingPaymentRow;\n\nfunction parsePaymentRow(row: Record<string, unknown>, context: string): BillingPaymentRow {\n return safeParse(\n BillingPaymentRowSchema,\n {\n id: row.id,\n provider: row.provider,\n provider_payment_id: row.provider_payment_id,\n provider_invoice_id: row.provider_invoice_id,\n subject_id: row.subject_id,\n amount_minor: row.amount_minor,\n tax_minor: row.tax_minor,\n currency: row.currency,\n purpose: row.purpose,\n status: row.status,\n provider_updated_at: row.provider_updated_at,\n metadata: row.metadata,\n },\n context,\n );\n}\n\nexport class BillingPaymentRepository {\n constructor(private query: QueryFn) {}\n async upsert(\n provider: string,\n providerPaymentId: string,\n providerInvoiceId: string | null,\n userId: string,\n amountMinor: number,\n taxMinor: number,\n currency: string,\n purpose: \"subscription\" | \"credit_topup\",\n metadata: string | null,\n status: \"pending\" | \"succeeded\" | \"failed\" | \"canceled\",\n providerUpdatedAt: string,\n ): Promise<string> {\n if (!userId) throw new TypeError(\"billing payment requires a subject\");\n if (purpose !== \"subscription\" && purpose !== \"credit_topup\") {\n throw new TypeError(\"billing payment requires a known purpose\");\n }\n const rows = await this.query(\n `SELECT bursar.upsert_billing_payment(\n $1::uuid,$2,$3,$4,$5,$6,$7,$8::bursar.billing_payment_status,$9,$10,$11::jsonb\n ) AS id`,\n [\n userId,\n provider,\n providerPaymentId,\n amountMinor,\n taxMinor,\n currency,\n purpose,\n status,\n providerUpdatedAt,\n providerInvoiceId,\n metadata ?? \"{}\",\n ],\n );\n return requireResultField(rows, \"id\", postgresUuid, \"BillingPaymentRepository.upsert\");\n }\n async getForRefund(provider: string, providerPaymentId: string): Promise<ForRefundRow | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_payment_by_provider($1,$2)\", [\n provider,\n providerPaymentId,\n ]);\n const row = optionalRecordRow(rows, \"BillingPaymentRepository.getForRefund\");\n return row === null ? null : parsePaymentRow(row, \"BillingPaymentRepository.getForRefund\");\n }\n async getDirect(provider: string, providerPaymentId: string): Promise<BillingPaymentRow | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_payment_by_provider($1,$2)\", [\n provider,\n providerPaymentId,\n ]);\n const row = optionalRecordRow(rows, \"BillingPaymentRepository.getDirect\");\n return row === null ? null : parsePaymentRow(row, \"BillingPaymentRepository.getDirect\");\n }\n}\n"]}
1
+ {"version":3,"file":"payment.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/payment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAA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,iBAAiB;YACjB,QAAQ,IAAI,IAAI;SACjB,CACF,CAAC;QACF,OAAO,kBAAkB,CAAC,IAAI,EAAE,IAAI,EAAE,YAAY,EAAE,iCAAiC,CAAC,CAAC;IACzF,CAAC;IACD,KAAK,CAAC,YAAY,CAAC,QAAgB,EAAE,iBAAyB;QAC5D,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,6DAA6D,EAAE;YAC3F,QAAQ;YACR,iBAAiB;SAClB,CAAC,CAAC;QACH,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,uCAAuC,CAAC,CAAC;QAC7E,OAAO,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,GAAG,EAAE,uCAAuC,CAAC,CAAC;IAC7F,CAAC;IACD,KAAK,CAAC,SAAS,CAAC,QAAgB,EAAE,iBAAyB;QACzD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,6DAA6D,EAAE;YAC3F,QAAQ;YACR,iBAAiB;SAClB,CAAC,CAAC;QACH,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,oCAAoC,CAAC,CAAC;QAC1E,OAAO,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,GAAG,EAAE,oCAAoC,CAAC,CAAC;IAC1F,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { PostgresRow } from \"../../../shared/json.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst PgSafeMinorUnitsSchema = z.union([\n z.string().regex(/^\\d+$/),\n z.number().int().nonnegative().safe(),\n]);\n\nconst BillingPaymentRowSchema = z\n .object({\n id: postgresUuid,\n provider: z.string().min(1),\n provider_payment_id: z.string().min(1),\n provider_invoice_id: z.string().nullable(),\n subject_id: postgresUuid,\n amount_minor: PgSafeMinorUnitsSchema,\n tax_minor: PgSafeMinorUnitsSchema,\n currency: z.string().regex(/^[A-Z]{3}$/),\n purpose: z.enum([\"subscription\", \"credit_topup\"]),\n status: z.enum([\"pending\", \"succeeded\", \"failed\", \"canceled\"]),\n provider_updated_at: z.union([z.string().datetime({ offset: true }), z.date()]),\n metadata: z.record(z.string(), z.json()),\n })\n .strict();\nexport type BillingPaymentRow = z.infer<typeof BillingPaymentRowSchema>;\nexport type ForRefundRow = BillingPaymentRow;\n\nfunction parsePaymentRow(row: PostgresRow, context: string): BillingPaymentRow {\n return safeParse(\n BillingPaymentRowSchema,\n {\n id: row.id,\n provider: row.provider,\n provider_payment_id: row.provider_payment_id,\n provider_invoice_id: row.provider_invoice_id,\n subject_id: row.subject_id,\n amount_minor: row.amount_minor,\n tax_minor: row.tax_minor,\n currency: row.currency,\n purpose: row.purpose,\n status: row.status,\n provider_updated_at: row.provider_updated_at,\n metadata: row.metadata,\n },\n context,\n );\n}\n\nexport class BillingPaymentRepository {\n constructor(private query: QueryFn) {}\n async upsert(\n provider: string,\n providerPaymentId: string,\n providerInvoiceId: string | null,\n userId: string,\n amountMinor: number,\n taxMinor: number,\n currency: string,\n purpose: \"subscription\" | \"credit_topup\",\n metadata: string | null,\n status: \"pending\" | \"succeeded\" | \"failed\" | \"canceled\",\n providerUpdatedAt: string,\n ): Promise<string> {\n if (!userId) throw new TypeError(\"billing payment requires a subject\");\n if (purpose !== \"subscription\" && purpose !== \"credit_topup\") {\n throw new TypeError(\"billing payment requires a known purpose\");\n }\n const rows = await this.query(\n `SELECT bursar.upsert_billing_payment(\n $1::uuid,$2,$3,$4,$5,$6,$7,$8::bursar.billing_payment_status,$9,$10,$11::jsonb\n ) AS id`,\n [\n userId,\n provider,\n providerPaymentId,\n amountMinor,\n taxMinor,\n currency,\n purpose,\n status,\n providerUpdatedAt,\n providerInvoiceId,\n metadata ?? \"{}\",\n ],\n );\n return requireResultField(rows, \"id\", postgresUuid, \"BillingPaymentRepository.upsert\");\n }\n async getForRefund(provider: string, providerPaymentId: string): Promise<ForRefundRow | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_payment_by_provider($1,$2)\", [\n provider,\n providerPaymentId,\n ]);\n const row = optionalRecordRow(rows, \"BillingPaymentRepository.getForRefund\");\n return row === null ? null : parsePaymentRow(row, \"BillingPaymentRepository.getForRefund\");\n }\n async getDirect(provider: string, providerPaymentId: string): Promise<BillingPaymentRow | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_payment_by_provider($1,$2)\", [\n provider,\n providerPaymentId,\n ]);\n const row = optionalRecordRow(rows, \"BillingPaymentRepository.getDirect\");\n return row === null ? null : parsePaymentRow(row, \"BillingPaymentRepository.getDirect\");\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"subscription-change.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription-change.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAO,KAAK,EACV,yBAAyB,EACzB,8BAA8B,EAE/B,MAAM,sBAAsB,CAAC;AAG9B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AA2HjE,uEAAuE;AACvE,qBAAa,mCAAmC;IAClC,OAAO,CAAC,QAAQ,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAErC,MAAM,CACV,cAAc,EAAE,MAAM,EACtB,KAAK,EAAE,8BAA8B,GACpC,OAAO,CAAC,yBAAyB,CAAC;IAuC/B,OAAO,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC;IAQ9D,OAAO,CACX,QAAQ,EAAE,MAAM,EAChB,sBAAsB,EAAE,MAAM,GAC7B,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC;IAQtC,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,+BAA+B,GAAG,OAAO,CAAC,IAAI,CAAC;YAoBlE,aAAa;YAyBb,gBAAgB;CAmD/B"}
1
+ {"version":3,"file":"subscription-change.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription-change.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAO,KAAK,EACV,yBAAyB,EACzB,8BAA8B,EAE/B,MAAM,sBAAsB,CAAC;AAG9B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AA4HjE,uEAAuE;AACvE,qBAAa,mCAAmC;IAClC,OAAO,CAAC,QAAQ,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAErC,MAAM,CACV,cAAc,EAAE,MAAM,EACtB,KAAK,EAAE,8BAA8B,GACpC,OAAO,CAAC,yBAAyB,CAAC;IAuC/B,OAAO,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC;IAQ9D,OAAO,CACX,QAAQ,EAAE,MAAM,EAChB,sBAAsB,EAAE,MAAM,GAC7B,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC;IAQtC,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,+BAA+B,GAAG,OAAO,CAAC,IAAI,CAAC;YAoBlE,aAAa;YAyBb,gBAAgB;CA6C/B"}
@@ -206,15 +206,7 @@ export class BillingSubscriptionChangeRepository {
206
206
  details: { subscriptionChangeId: row.id, rowCount: rows.length },
207
207
  });
208
208
  }
209
- const parsed = rows.map((candidate, index) => {
210
- if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate)) {
211
- throw new StoreError(`${context}: malformed subscription-change offer context`, {
212
- details: { subscriptionChangeId: row.id, index },
213
- });
214
- }
215
- const record = candidate;
216
- return safeParse(OfferContextRowSchema, projectContext(record), `${context}.context`);
217
- });
209
+ const parsed = rows.map((candidate) => safeParse(OfferContextRowSchema, projectContext(candidate), `${context}.context`));
218
210
  const bySide = new Map(parsed.map((candidate) => [candidate.side, candidate]));
219
211
  const from = bySide.get("from");
220
212
  const to = bySide.get("to");
@@ -1 +1 @@
1
- {"version":3,"file":"subscription-change.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription-change.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAOxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAElF,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,SAAS,GAAG,CAAC;KAChB,KAAK,CAAC;IACL,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IACrC,CAAC,CAAC,IAAI,EAAE,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;CAC3D,CAAC;KACD,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;AAC/E,MAAM,cAAc,GAAG,CAAC;KACrB,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;KAC3E,SAAS,CAAC,MAAM,CAAC,CAAC;AACrB,MAAM,WAAW,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,kBAA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9E,OAAO,EAAE,EAAE,oBAAoB,EAAE,GAAG,CAAC,EAAE,EAAE,KAAK,EAAE;iBACjD,CAAC,CAAC;YACL,CAAC;YACD,MAAM,MAAM,GAAG,SAAoC,CAAC;YACpD,OAAO,SAAS,CAAC,qBAAqB,EAAE,cAAc,CAAC,MAAM,CAAC,EAAE,GAAG,OAAO,UAAU,CAAC,CAAC;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
+ {"version":3,"file":"subscription-change.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription-change.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAOxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAGlF,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,SAAS,GAAG,CAAC;KAChB,KAAK,CAAC;IACL,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IACrC,CAAC,CAAC,IAAI,EAAE,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;CAC3D,CAAC;KACD,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;AAC/E,MAAM,cAAc,GAAG,CAAC;KACrB,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;KAC3E,SAAS,CAAC,MAAM,CAAC,CAAC;AACrB,MAAM,WAAW,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,kBAAkB,EAAE,WAAW,EAAE,SAAS,EAAE,QAAQ,EAAE,UAAU,CAAC,CAAC,CAAC;AAC/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,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 type { PostgresRow } from \"../../../shared/json.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: PostgresRow) {\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: PostgresRow) {\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 PostgresRow[],\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) =>\n safeParse(OfferContextRowSchema, projectContext(candidate), `${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,6 +1,7 @@
1
1
  import { z } from "zod";
2
- import type { BillingSubscriptionState } from "../../types/subscriptions.js";
2
+ import type { BillingSubscriptionState, BillingSubscriptionStatus, SubscriptionEntitlementOutcome } from "../../types/subscriptions.js";
3
3
  import type { QueryFn } from "../../../shared/postgres-types.js";
4
+ import type { JsonObject } from "../../../shared/json.js";
4
5
  declare const SubscriptionRowSchema: z.ZodObject<{
5
6
  id: z.ZodString;
6
7
  user_id: z.ZodString;
@@ -38,7 +39,7 @@ declare const SubscriptionRowSchema: z.ZodObject<{
38
39
  year: "year";
39
40
  }>;
40
41
  interval_count: z.ZodNumber;
41
- metadata: z.ZodRecord<z.ZodString, z.ZodUnknown>;
42
+ metadata: z.ZodRecord<z.ZodString, z.ZodJSONSchema>;
42
43
  }, z.core.$strict>;
43
44
  export type SubscriptionRow = z.infer<typeof SubscriptionRowSchema>;
44
45
  export declare class BillingSubscriptionRepository {
@@ -51,17 +52,16 @@ export declare class BillingSubscriptionRepository {
51
52
  getUserSubscription(userId: string, statuses?: string[]): Promise<SubscriptionRow | null>;
52
53
  getUserSubscriptions(userId: string): Promise<SubscriptionRow[]>;
53
54
  listExpiredGraceSubscriptions(now: string, limit?: number): Promise<SubscriptionRow[]>;
54
- markGraceExpired(subscriptionId: string, expectedGraceEndsAt: string, expiredAt: string): Promise<boolean>;
55
+ reconcileEntitlement(subjectId: string, subscriptionId: string, billingEventId: string, expectedStatus: BillingSubscriptionStatus, expectedProviderUpdatedAt: string, planAssignedAt: Date | string | null, applyEntitlement: boolean, terminalPlanKey: string | null, reason: string): Promise<SubscriptionEntitlementOutcome>;
56
+ expireGracePeriod(subjectId: string, subscriptionId: string, expectedGraceEndsAt: string, expiredAt: string, terminalPlanKey: string | null): Promise<boolean>;
55
57
  recordConflict(input: {
56
58
  userId?: string | null;
57
59
  provider: string;
58
60
  duplicateSubscriptionId: string;
59
61
  existingSubscriptionId?: string | null;
60
62
  eventId?: string | null;
61
- metadata?: Record<string, unknown>;
63
+ metadata?: JsonObject;
62
64
  }): Promise<string>;
63
- /** Select a provider subscription without modifying provider-reported state. */
64
- selectEntitlementSource(userId: string, provider: string, providerSubscriptionId?: string | null): Promise<boolean>;
65
65
  }
66
66
  export {};
67
67
  //# sourceMappingURL=subscription.d.ts.map
@@ -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,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AAC7E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAiEjE,QAAA,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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MAAM,EACtB,cAAc,EAAE,MAAM,EACtB,cAAc,EAAE,yBAAyB,EACzC,yBAAyB,EAAE,MAAM,EACjC,cAAc,EAAE,IAAI,GAAG,MAAM,GAAG,IAAI,EACpC,gBAAgB,EAAE,OAAO,EACzB,eAAe,EAAE,MAAM,GAAG,IAAI,EAC9B,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,8BAA8B,CAAC;IAuCpC,iBAAiB,CACrB,SAAS,EAAE,MAAM,EACjB,cAAc,EAAE,MAAM,EACtB,mBAAmB,EAAE,MAAM,EAC3B,SAAS,EAAE,MAAM,EACjB,eAAe,EAAE,MAAM,GAAG,IAAI,GAC7B,OAAO,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,UAAU,CAAC;KACvB,GAAG,OAAO,CAAC,MAAM,CAAC;CAqBpB"}
@@ -18,6 +18,7 @@ const SubscriptionStatusSchema = z.enum([
18
18
  "paused",
19
19
  "expired",
20
20
  ]);
21
+ const SubscriptionEntitlementOutcomeSchema = z.enum(["applied", "revoked", "preserved", "stale"]);
21
22
  const PersistedSubscriptionRowSchema = z
22
23
  .object({
23
24
  id: postgresUuid,
@@ -37,7 +38,7 @@ const PersistedSubscriptionRowSchema = z
37
38
  grace_expired_at: timestamp.nullable(),
38
39
  provider_updated_at: timestamp,
39
40
  cancel_at_period_end: pgBoolean,
40
- metadata: z.record(z.string(), z.unknown()),
41
+ metadata: z.record(z.string(), z.json()),
41
42
  })
42
43
  .strict();
43
44
  const CatalogReferenceSchema = z
@@ -78,14 +79,11 @@ const SubscriptionRowSchema = z
78
79
  cancel_at_period_end: pgBoolean,
79
80
  interval: z.enum(["day", "week", "month", "year"]),
80
81
  interval_count: z.number().int().positive(),
81
- metadata: z.record(z.string(), z.unknown()),
82
+ metadata: z.record(z.string(), z.json()),
82
83
  })
83
84
  .strict();
84
- function record(value, context) {
85
- return safeParse(z.record(z.string(), z.unknown()), value, context);
86
- }
87
85
  function persistedSubscription(row, context) {
88
- const value = record(row, context);
86
+ const value = row;
89
87
  return safeParse(PersistedSubscriptionRowSchema, {
90
88
  id: value.id,
91
89
  subject_id: value.subject_id,
@@ -165,7 +163,7 @@ export class BillingSubscriptionRepository {
165
163
  requireResultField(rows, "id", postgresUuid, "BillingSubscriptionRepository.upsert");
166
164
  }
167
165
  map(row) {
168
- const r = record(row, "BillingSubscriptionRepository.map");
166
+ const r = row;
169
167
  return safeParse(SubscriptionRowSchema, {
170
168
  id: r.id,
171
169
  user_id: r.subject_id,
@@ -254,9 +252,30 @@ export class BillingSubscriptionRepository {
254
252
  const enriched = await Promise.all(persisted.map((row) => this.withOfferContext(row)));
255
253
  return enriched.map((row) => this.map(row));
256
254
  }
257
- async markGraceExpired(subscriptionId, expectedGraceEndsAt, expiredAt) {
258
- const rows = await this.query(`SELECT bursar.mark_subscription_grace_expired($1::uuid, $2, $3) AS marked`, [subscriptionId, expectedGraceEndsAt, expiredAt]);
259
- return requireResultField(rows, "marked", pgBoolean, "BillingSubscriptionRepository.markGraceExpired");
255
+ async reconcileEntitlement(subjectId, subscriptionId, billingEventId, expectedStatus, expectedProviderUpdatedAt, planAssignedAt, applyEntitlement, terminalPlanKey, reason) {
256
+ const expectedTimestamp = safeParse(timestamp, expectedProviderUpdatedAt, "BillingSubscriptionRepository.reconcileEntitlement.expectedProviderUpdatedAt");
257
+ const assignmentTimestamp = planAssignedAt === null
258
+ ? null
259
+ : safeParse(timestamp, planAssignedAt, "BillingSubscriptionRepository.reconcileEntitlement.planAssignedAt");
260
+ const rows = await this.query(`SELECT bursar.reconcile_subscription_entitlement(
261
+ $1::uuid, $2::uuid, $3::uuid, $4::bursar.billing_subscription_status,
262
+ $5::timestamptz, $6::timestamptz, $7, $8, $9
263
+ ) AS outcome`, [
264
+ subjectId,
265
+ subscriptionId,
266
+ billingEventId,
267
+ expectedStatus,
268
+ expectedTimestamp,
269
+ assignmentTimestamp,
270
+ applyEntitlement,
271
+ terminalPlanKey,
272
+ reason,
273
+ ]);
274
+ return requireResultField(rows, "outcome", SubscriptionEntitlementOutcomeSchema, "BillingSubscriptionRepository.reconcileEntitlement");
275
+ }
276
+ async expireGracePeriod(subjectId, subscriptionId, expectedGraceEndsAt, expiredAt, terminalPlanKey) {
277
+ const rows = await this.query(`SELECT bursar.expire_subscription_grace_period($1::uuid, $2::uuid, $3, $4, $5) AS expired`, [subjectId, subscriptionId, expectedGraceEndsAt, expiredAt, terminalPlanKey]);
278
+ return requireResultField(rows, "expired", pgBoolean, "BillingSubscriptionRepository.expireGracePeriod");
260
279
  }
261
280
  async recordConflict(input) {
262
281
  const rows = await this.query(`SELECT bursar.record_subscription_conflict(
@@ -271,25 +290,5 @@ export class BillingSubscriptionRepository {
271
290
  ]);
272
291
  return requireResultField(rows, "id", z.union([z.string().min(1), z.number().int()]).transform(String), "BillingSubscriptionRepository.recordConflict");
273
292
  }
274
- /** Select a provider subscription without modifying provider-reported state. */
275
- async selectEntitlementSource(userId, provider, providerSubscriptionId) {
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
- ]);
280
- const replacement = rows
281
- .map((row) => persistedSubscription(row, "BillingSubscriptionRepository.selectEntitlementSource"))
282
- .filter((row) => row.provider === provider &&
283
- eligibleStatuses.has(row.status) &&
284
- (!providerSubscriptionId || row.provider_subscription_id === providerSubscriptionId))
285
- .sort((left, right) => Date.parse(right.provider_updated_at) - Date.parse(left.provider_updated_at))[0];
286
- if (replacement?.id == null)
287
- return false;
288
- const selectedRows = await this.query(`SELECT bursar.select_entitlement_source($1::uuid, $2::uuid) AS selected`, [userId, replacement.id]);
289
- if (!requireResultField(selectedRows, "selected", pgBoolean, "BillingSubscriptionRepository.selectEntitlementSource")) {
290
- throw new StoreError("subscription entitlement source selection was rejected");
291
- }
292
- return true;
293
- }
294
293
  }
295
294
  //# sourceMappingURL=subscription.js.map