@zonastery/bursar 2.0.1 → 2.0.3

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 (285) hide show
  1. package/README.md +22 -14
  2. package/dist/billing/auto-recharge-service.d.ts +1 -1
  3. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  4. package/dist/billing/auto-recharge-service.js +9 -6
  5. package/dist/billing/auto-recharge-service.js.map +1 -1
  6. package/dist/billing/billing-store.d.ts +4 -1
  7. package/dist/billing/billing-store.d.ts.map +1 -1
  8. package/dist/billing/billing-store.js +2 -0
  9. package/dist/billing/billing-store.js.map +1 -1
  10. package/dist/billing/contracts.d.ts +2 -1
  11. package/dist/billing/contracts.d.ts.map +1 -1
  12. package/dist/billing/contracts.js.map +1 -1
  13. package/dist/billing/event-handlers.d.ts +2 -3
  14. package/dist/billing/event-handlers.d.ts.map +1 -1
  15. package/dist/billing/event-handlers.js +38 -49
  16. package/dist/billing/event-handlers.js.map +1 -1
  17. package/dist/billing/event-processor.d.ts.map +1 -1
  18. package/dist/billing/event-processor.js +22 -10
  19. package/dist/billing/event-processor.js.map +1 -1
  20. package/dist/billing/financial-event-handlers.d.ts +2 -2
  21. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  22. package/dist/billing/financial-event-handlers.js +7 -7
  23. package/dist/billing/financial-event-handlers.js.map +1 -1
  24. package/dist/billing/postgres/repositories/auto-recharge.js +1 -1
  25. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  26. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  27. package/dist/billing/postgres/repositories/event.js +33 -1
  28. package/dist/billing/postgres/repositories/event.js.map +1 -1
  29. package/dist/billing/postgres/repositories/offer.d.ts +1 -1
  30. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  31. package/dist/billing/postgres/repositories/offer.js +1 -1
  32. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  33. package/dist/billing/postgres/repositories/topup.d.ts +1 -1
  34. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  35. package/dist/billing/postgres/repositories/topup.js +1 -1
  36. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  37. package/dist/billing/postgres/store.d.ts +6 -2
  38. package/dist/billing/postgres/store.d.ts.map +1 -1
  39. package/dist/billing/postgres/store.js +21 -6
  40. package/dist/billing/postgres/store.js.map +1 -1
  41. package/dist/billing/service-types.d.ts +2 -15
  42. package/dist/billing/service-types.d.ts.map +1 -1
  43. package/dist/billing/service-types.js.map +1 -1
  44. package/dist/billing/types/auto-recharge.d.ts +1 -1
  45. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  46. package/dist/billing/types/auto-recharge.js.map +1 -1
  47. package/dist/billing/types/catalog.d.ts +1 -1
  48. package/dist/billing/types/catalog.d.ts.map +1 -1
  49. package/dist/billing/types/catalog.js.map +1 -1
  50. package/dist/billing/types/documents.d.ts +1 -1
  51. package/dist/billing/types/documents.d.ts.map +1 -1
  52. package/dist/billing/types/documents.js.map +1 -1
  53. package/dist/billing/types/events.d.ts +11 -2
  54. package/dist/billing/types/events.d.ts.map +1 -1
  55. package/dist/billing/types/events.js +2 -2
  56. package/dist/billing/types/events.js.map +1 -1
  57. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  58. package/dist/billing/types/subscriptions.js.map +1 -1
  59. package/dist/breakdown.d.ts +1 -1
  60. package/dist/breakdown.d.ts.map +1 -1
  61. package/dist/breakdown.js +1 -1
  62. package/dist/breakdown.js.map +1 -1
  63. package/dist/bursar.d.ts +21 -11
  64. package/dist/bursar.d.ts.map +1 -1
  65. package/dist/bursar.js +40 -4
  66. package/dist/bursar.js.map +1 -1
  67. package/dist/catalog.d.ts.map +1 -1
  68. package/dist/catalog.js +1 -1
  69. package/dist/catalog.js.map +1 -1
  70. package/dist/commerce/index.d.ts +0 -1
  71. package/dist/commerce/index.d.ts.map +1 -1
  72. package/dist/commerce/index.js +0 -1
  73. package/dist/commerce/index.js.map +1 -1
  74. package/dist/commerce/service.d.ts.map +1 -1
  75. package/dist/commerce/service.js +154 -106
  76. package/dist/commerce/service.js.map +1 -1
  77. package/dist/commerce/types.d.ts +9 -5
  78. package/dist/commerce/types.d.ts.map +1 -1
  79. package/dist/commerce/types.js.map +1 -1
  80. package/dist/config/parse-credits.d.ts.map +1 -1
  81. package/dist/config/parse-credits.js +0 -6
  82. package/dist/config/parse-credits.js.map +1 -1
  83. package/dist/config/parse-utils.d.ts +1 -1
  84. package/dist/config/parse-utils.d.ts.map +1 -1
  85. package/dist/config/parse-utils.js +1 -1
  86. package/dist/config/parse-utils.js.map +1 -1
  87. package/dist/config/types.d.ts +1 -6
  88. package/dist/config/types.d.ts.map +1 -1
  89. package/dist/config/types.js.map +1 -1
  90. package/dist/config.d.ts.map +1 -1
  91. package/dist/config.js +8 -1
  92. package/dist/config.js.map +1 -1
  93. package/dist/credits/amount.d.ts +8 -0
  94. package/dist/credits/amount.d.ts.map +1 -0
  95. package/dist/credits/amount.js +32 -0
  96. package/dist/credits/amount.js.map +1 -0
  97. package/dist/credits/catalog-runtime.d.ts +5 -7
  98. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  99. package/dist/credits/catalog-runtime.js +4 -13
  100. package/dist/credits/catalog-runtime.js.map +1 -1
  101. package/dist/credits/lease-workflow.d.ts +2 -2
  102. package/dist/credits/lease-workflow.d.ts.map +1 -1
  103. package/dist/credits/lease-workflow.js +24 -21
  104. package/dist/credits/lease-workflow.js.map +1 -1
  105. package/dist/credits/low-balance-monitor.d.ts +1 -1
  106. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  107. package/dist/credits/low-balance-monitor.js +3 -4
  108. package/dist/credits/low-balance-monitor.js.map +1 -1
  109. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  110. package/dist/credits/postgres/repositories/balance.js +1 -1
  111. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  112. package/dist/credits/postgres/repositories/bucket.js +1 -1
  113. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  114. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  115. package/dist/credits/postgres/repositories/lease.js +4 -2
  116. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  117. package/dist/credits/postgres/repositories/team.d.ts +2 -1
  118. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  119. package/dist/credits/postgres/repositories/team.js +19 -5
  120. package/dist/credits/postgres/repositories/team.js.map +1 -1
  121. package/dist/credits/postgres/store.d.ts +18 -14
  122. package/dist/credits/postgres/store.d.ts.map +1 -1
  123. package/dist/credits/postgres/store.js +30 -18
  124. package/dist/credits/postgres/store.js.map +1 -1
  125. package/dist/credits/postgres/value-mappers.d.ts +1 -1
  126. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  127. package/dist/credits/postgres/value-mappers.js +1 -1
  128. package/dist/credits/postgres/value-mappers.js.map +1 -1
  129. package/dist/credits/service-errors.d.ts +1 -1
  130. package/dist/credits/service-errors.d.ts.map +1 -1
  131. package/dist/credits/service-errors.js +1 -1
  132. package/dist/credits/service-errors.js.map +1 -1
  133. package/dist/credits/service-types.d.ts +21 -16
  134. package/dist/credits/service-types.d.ts.map +1 -1
  135. package/dist/credits/service-types.js.map +1 -1
  136. package/dist/credits/service.d.ts +21 -17
  137. package/dist/credits/service.d.ts.map +1 -1
  138. package/dist/credits/service.js +81 -38
  139. package/dist/credits/service.js.map +1 -1
  140. package/dist/credits/store.d.ts +26 -23
  141. package/dist/credits/store.d.ts.map +1 -1
  142. package/dist/credits/store.js +4 -2
  143. package/dist/credits/store.js.map +1 -1
  144. package/dist/credits/types/account.d.ts +1 -1
  145. package/dist/credits/types/account.d.ts.map +1 -1
  146. package/dist/credits/types/account.js.map +1 -1
  147. package/dist/credits/types/grants.d.ts.map +1 -1
  148. package/dist/credits/types/grants.js.map +1 -1
  149. package/dist/credits/types/teams.d.ts +1 -0
  150. package/dist/credits/types/teams.d.ts.map +1 -1
  151. package/dist/credits/types/teams.js.map +1 -1
  152. package/dist/engine.js +1 -1
  153. package/dist/engine.js.map +1 -1
  154. package/dist/errors.d.ts +4 -0
  155. package/dist/errors.d.ts.map +1 -1
  156. package/dist/errors.js +34 -0
  157. package/dist/errors.js.map +1 -1
  158. package/dist/expr/ast.d.ts.map +1 -1
  159. package/dist/expr/ast.js.map +1 -1
  160. package/dist/expr/evaluator.d.ts +1 -1
  161. package/dist/expr/evaluator.d.ts.map +1 -1
  162. package/dist/expr/evaluator.js +1 -1
  163. package/dist/expr/evaluator.js.map +1 -1
  164. package/dist/expr/parser.d.ts +1 -0
  165. package/dist/expr/parser.d.ts.map +1 -1
  166. package/dist/expr/parser.js +15 -3
  167. package/dist/expr/parser.js.map +1 -1
  168. package/dist/expr.d.ts +1 -1
  169. package/dist/expr.d.ts.map +1 -1
  170. package/dist/expr.js +1 -1
  171. package/dist/expr.js.map +1 -1
  172. package/dist/generated/pricing-config.schema.json +31 -29
  173. package/dist/generated/pricing-config.types.d.ts +6 -18
  174. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  175. package/dist/generated/pricing-config.types.js.map +1 -1
  176. package/dist/index.d.ts +7 -3
  177. package/dist/index.d.ts.map +1 -1
  178. package/dist/index.js +2 -0
  179. package/dist/index.js.map +1 -1
  180. package/dist/load-config-file.d.ts +2 -3
  181. package/dist/load-config-file.d.ts.map +1 -1
  182. package/dist/load-config-file.js +14 -29
  183. package/dist/load-config-file.js.map +1 -1
  184. package/dist/metrics.d.ts +1 -1
  185. package/dist/metrics.d.ts.map +1 -1
  186. package/dist/metrics.js.map +1 -1
  187. package/dist/node.d.ts +6 -3
  188. package/dist/node.d.ts.map +1 -1
  189. package/dist/node.js +1 -0
  190. package/dist/node.js.map +1 -1
  191. package/dist/providers/_shared.d.ts +3 -3
  192. package/dist/providers/_shared.d.ts.map +1 -1
  193. package/dist/providers/_shared.js +11 -6
  194. package/dist/providers/_shared.js.map +1 -1
  195. package/dist/providers/dodo/client-contract.d.ts +8 -13
  196. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  197. package/dist/providers/dodo/client-contract.js.map +1 -1
  198. package/dist/providers/dodo/event-mapper.d.ts +1 -1
  199. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  200. package/dist/providers/dodo/event-mapper.js +23 -15
  201. package/dist/providers/dodo/event-mapper.js.map +1 -1
  202. package/dist/providers/dodo/provider.d.ts +4 -6
  203. package/dist/providers/dodo/provider.d.ts.map +1 -1
  204. package/dist/providers/dodo/provider.js +44 -82
  205. package/dist/providers/dodo/provider.js.map +1 -1
  206. package/dist/providers/dodo/webhook-bridge.d.ts +1 -2
  207. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
  208. package/dist/providers/dodo/webhook-bridge.js +0 -1
  209. package/dist/providers/dodo/webhook-bridge.js.map +1 -1
  210. package/dist/providers/environment.d.ts +6 -0
  211. package/dist/providers/environment.d.ts.map +1 -0
  212. package/dist/providers/environment.js +10 -0
  213. package/dist/providers/environment.js.map +1 -0
  214. package/dist/providers/index.d.ts +3 -7
  215. package/dist/providers/index.d.ts.map +1 -1
  216. package/dist/providers/index.js +1 -5
  217. package/dist/providers/index.js.map +1 -1
  218. package/dist/providers/mock/provider.d.ts +6 -8
  219. package/dist/providers/mock/provider.d.ts.map +1 -1
  220. package/dist/providers/mock/provider.js +18 -50
  221. package/dist/providers/mock/provider.js.map +1 -1
  222. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  223. package/dist/providers/stripe/event-mapper.js +82 -14
  224. package/dist/providers/stripe/event-mapper.js.map +1 -1
  225. package/dist/providers/stripe/provider.d.ts +3 -3
  226. package/dist/providers/stripe/provider.d.ts.map +1 -1
  227. package/dist/providers/stripe/provider.js +37 -24
  228. package/dist/providers/stripe/provider.js.map +1 -1
  229. package/dist/providers/types.d.ts +9 -20
  230. package/dist/providers/types.d.ts.map +1 -1
  231. package/dist/providers/types.js.map +1 -1
  232. package/dist/shared/diagnostics.d.ts +8 -0
  233. package/dist/shared/diagnostics.d.ts.map +1 -1
  234. package/dist/shared/diagnostics.js +49 -0
  235. package/dist/shared/diagnostics.js.map +1 -1
  236. package/dist/shared/idempotency.d.ts +9 -0
  237. package/dist/shared/idempotency.d.ts.map +1 -0
  238. package/dist/shared/idempotency.js +34 -0
  239. package/dist/shared/idempotency.js.map +1 -0
  240. package/dist/shared/postgres-client.d.ts +7 -0
  241. package/dist/shared/postgres-client.d.ts.map +1 -1
  242. package/dist/shared/postgres-client.js +21 -4
  243. package/dist/shared/postgres-client.js.map +1 -1
  244. package/dist/shared/postgres-errors.d.ts.map +1 -1
  245. package/dist/shared/postgres-errors.js.map +1 -1
  246. package/dist/storage/adapters/clickhouse.d.ts +9 -2
  247. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  248. package/dist/storage/adapters/clickhouse.js +142 -36
  249. package/dist/storage/adapters/clickhouse.js.map +1 -1
  250. package/dist/storage/adapters/s3.d.ts +44 -6
  251. package/dist/storage/adapters/s3.d.ts.map +1 -1
  252. package/dist/storage/adapters/s3.js +59 -21
  253. package/dist/storage/adapters/s3.js.map +1 -1
  254. package/dist/storage/diagnostics.d.ts +105 -0
  255. package/dist/storage/diagnostics.d.ts.map +1 -0
  256. package/dist/storage/diagnostics.js +227 -0
  257. package/dist/storage/diagnostics.js.map +1 -0
  258. package/dist/storage/maintenance.d.ts +88 -0
  259. package/dist/storage/maintenance.d.ts.map +1 -0
  260. package/dist/storage/maintenance.js +266 -0
  261. package/dist/storage/maintenance.js.map +1 -0
  262. package/dist/storage/outbox-worker.d.ts +20 -0
  263. package/dist/storage/outbox-worker.d.ts.map +1 -1
  264. package/dist/storage/outbox-worker.js +172 -42
  265. package/dist/storage/outbox-worker.js.map +1 -1
  266. package/dist/storage/ports.d.ts +43 -1
  267. package/dist/storage/ports.d.ts.map +1 -1
  268. package/dist/storage/ports.js.map +1 -1
  269. package/dist/storage/postgres-repository.d.ts +7 -2
  270. package/dist/storage/postgres-repository.d.ts.map +1 -1
  271. package/dist/storage/postgres-repository.js +155 -54
  272. package/dist/storage/postgres-repository.js.map +1 -1
  273. package/dist/storage/runtime.d.ts +30 -9
  274. package/dist/storage/runtime.d.ts.map +1 -1
  275. package/dist/storage/runtime.js +268 -37
  276. package/dist/storage/runtime.js.map +1 -1
  277. package/dist/telemetry/index.d.ts +37 -0
  278. package/dist/telemetry/index.d.ts.map +1 -0
  279. package/dist/telemetry/index.js +115 -0
  280. package/dist/telemetry/index.js.map +1 -0
  281. package/dist/telemetry/opentelemetry.d.ts +25 -0
  282. package/dist/telemetry/opentelemetry.d.ts.map +1 -0
  283. package/dist/telemetry/opentelemetry.js +74 -0
  284. package/dist/telemetry/opentelemetry.js.map +1 -0
  285. package/package.json +62 -36
@@ -1 +1 @@
1
- {"version":3,"file":"offer.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/offer.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,wCAAwC,CAAC;AAE9F,MAAM,qBAAqB,GAAG,CAAC;KAC5B,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC;KACtD,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC;KACxC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,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,S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AAI,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":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I,UAAU,CAAC,GAAG,OAAO,0DAA0D,EAAE;gBACzF,OAAO,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,EAAE,iBAAiB,EAAE,KAAK,CAAC,mBAAmB,EAAE;aAC7E,CAAC,CAAC;QACL,CAAC;QAED,MAAM,aAAa,GAAwB;YACzC,EAAE,EAAE,KAAK,CAAC,EAAE;YACZ,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,4 +1,4 @@
1
- import Decimal from "decimal.js";
1
+ import { Decimal } from "decimal.js";
2
2
  import { z } from "zod";
3
3
  import type { QueryFn } from "../../../shared/postgres-types.js";
4
4
  declare const BillingTopupRowSchema: z.ZodObject<{
@@ -1 +1 @@
1
- {"version":3,"file":"topup.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/topup.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAajE,QAAA,MAAM,qBAAqB;;;;;;;;;;kBAuBvB,CAAC;AAEL,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAEpE,+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;CAsCtB"}
1
+ {"version":3,"file":"topup.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/topup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAajE,QAAA,MAAM,qBAAqB;;;;;;;;;;kBAuBvB,CAAC;AAEL,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAEpE,+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;CAsCtB"}
@@ -1,4 +1,4 @@
1
- import Decimal from "decimal.js";
1
+ import { Decimal } from "decimal.js";
2
2
  import { z } from "zod";
3
3
  import { StoreError } from "../../../errors.js";
4
4
  import { postgresUuid, safeParse, unwrapJsonb } from "../../../shared/post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AAC,QAAQ;YACtB,YAAY,EAAE,GAAG,CAAC,YAAY;YAC9B,YAAY,EAAE,GAAG,CAAC,YAAY;YAC9B,gBAAgB,EAAE,GAAG,CAAC,gBAAgB;SACvC,EACD,OAAO,CACR,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 SafeMinorUnitsSchema = z\n .union([z.string().regex(/^\\d+$/), z.number().int().nonnegative().safe()])\n .transform(Number)\n .refine(Number.isSafeInteger, \"minor-unit amount exceeds JavaScript's safe integer range\");\n\nconst BillingTopupRowSchema = z\n .object({\n id: postgresUuid,\n topup_key: z.string().min(1),\n credits_per_unit: PositiveDecimalSchema,\n bucket_key: z.string().min(1),\n amount_minor: SafeMinorUnitsSchema,\n currency: z.string().regex(/^[A-Z]{3}$/),\n min_quantity: z.number().int().positive(),\n max_quantity: z.number().int().positive(),\n default_quantity: z.number().int().positive(),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.max_quantity < row.min_quantity) {\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: \"max_quantity is below min_quantity\" });\n }\n if (row.default_quantity < row.min_quantity || row.default_quantity > row.max_quantity) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"default_quantity is outside the configured range\",\n });\n }\n });\n\nexport type BillingTopupRow = z.infer<typeof BillingTopupRowSchema>;\n\n/** Repository for credit top-up resolution. */\nexport class BillingTopupRepository {\n constructor(private readonly query: QueryFn) {}\n\n async resolveByPrice(\n provider: string,\n priceId: string | null,\n productId: string | null,\n ): Promise<BillingTopupRow | 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<BillingTopupRow | 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<BillingTopupRow | null> {\n if (!provider.trim()) throw new TypeError(\"provider must not be empty\");\n if (!lookupValue?.trim()) return null;\n\n const context = `BillingTopupRepository.${operation}`;\n const rows = await this.query(\"SELECT * FROM bursar.resolve_catalog_topup($1, $2, $3)\", [\n provider,\n lookupType,\n lookupValue,\n ]);\n if (rows.length > 1) {\n throw new StoreError(`${context}: expected at most one top-up`, {\n details: { rowCount: rows.length },\n });\n }\n const raw = unwrapJsonb(rows);\n if (raw?.id == null) return null;\n return safeParse(\n BillingTopupRowSchema,\n {\n id: raw.id,\n topup_key: raw.topup_key,\n credits_per_unit: raw.credits_per_unit,\n bucket_key: raw.bucket_key,\n amount_minor: raw.amount_minor,\n currency: raw.currency,\n min_quantity: raw.min_quantity,\n max_quantity: raw.max_quantity,\n default_quantity: raw.default_quantity,\n },\n context,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"topup.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/topup.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,U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AE,IAAI,EAAE;YAAE,OAAO,IAAI,CAAC;QAEtC,MAAM,OAAO,GAAG,0BAA0B,SAAS,EAAE,CAAC;QACtD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,wDAAwD,EAAE;YACtF,QAAQ;YACR,UAAU;YACV,WAAW;SACZ,CAAC,CAAC;QACH,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACpB,MAAM,IAAI,UAAU,CAAC,GAAG,OAAO,+BAA+B,EAAE;gBAC9D,OAAO,EAAE,EAAE,QAAQ,EAAE,IAAI,CAAC,MAAM,EAAE;aACnC,CAAC,CAAC;QACL,CAAC;QACD,MAAM,GAAG,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;QAC9B,IAAI,GAAG,EAAE,EAAE,IAAI,IAAI;YAAE,OAAO,IAAI,CAAC;QACjC,OAAO,SAAS,CACd,qBAAqB,EACrB;YACE,EAAE,EAAE,GAAG,CAAC,EAAE;YACV,SAAS,EAAE,GAAG,CAAC,SAAS;YACxB,gBAAgB,EAAE,GAAG,CAAC,gBAAgB;YACtC,UAAU,EAAE,GAAG,CAAC,UAAU;YAC1B,YAAY,EAAE,GAAG,CAAC,YAAY;YAC9B,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,YAAY,EAAE,GAAG,CAAC,YAAY;YAC9B,YAAY,EAAE,GAAG,CAAC,YAAY;YAC9B,gBAAgB,EAAE,GAAG,CAAC,gBAAgB;SACvC,EACD,OAAO,CACR,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 SafeMinorUnitsSchema = z\n .union([z.string().regex(/^\\d+$/), z.number().int().nonnegative().safe()])\n .transform(Number)\n .refine(Number.isSafeInteger, \"minor-unit amount exceeds JavaScript's safe integer range\");\n\nconst BillingTopupRowSchema = z\n .object({\n id: postgresUuid,\n topup_key: z.string().min(1),\n credits_per_unit: PositiveDecimalSchema,\n bucket_key: z.string().min(1),\n amount_minor: SafeMinorUnitsSchema,\n currency: z.string().regex(/^[A-Z]{3}$/),\n min_quantity: z.number().int().positive(),\n max_quantity: z.number().int().positive(),\n default_quantity: z.number().int().positive(),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.max_quantity < row.min_quantity) {\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: \"max_quantity is below min_quantity\" });\n }\n if (row.default_quantity < row.min_quantity || row.default_quantity > row.max_quantity) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"default_quantity is outside the configured range\",\n });\n }\n });\n\nexport type BillingTopupRow = z.infer<typeof BillingTopupRowSchema>;\n\n/** Repository for credit top-up resolution. */\nexport class BillingTopupRepository {\n constructor(private readonly query: QueryFn) {}\n\n async resolveByPrice(\n provider: string,\n priceId: string | null,\n productId: string | null,\n ): Promise<BillingTopupRow | 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<BillingTopupRow | 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<BillingTopupRow | null> {\n if (!provider.trim()) throw new TypeError(\"provider must not be empty\");\n if (!lookupValue?.trim()) return null;\n\n const context = `BillingTopupRepository.${operation}`;\n const rows = await this.query(\"SELECT * FROM bursar.resolve_catalog_topup($1, $2, $3)\", [\n provider,\n lookupType,\n lookupValue,\n ]);\n if (rows.length > 1) {\n throw new StoreError(`${context}: expected at most one top-up`, {\n details: { rowCount: rows.length },\n });\n }\n const raw = unwrapJsonb(rows);\n if (raw?.id == null) return null;\n return safeParse(\n BillingTopupRowSchema,\n {\n id: raw.id,\n topup_key: raw.topup_key,\n credits_per_unit: raw.credits_per_unit,\n bucket_key: raw.bucket_key,\n amount_minor: raw.amount_minor,\n currency: raw.currency,\n min_quantity: raw.min_quantity,\n max_quantity: raw.max_quantity,\n default_quantity: raw.default_quantity,\n },\n context,\n );\n }\n}\n"]}
@@ -1,19 +1,23 @@
1
- import Decimal from "decimal.js";
1
+ import { Decimal } from "decimal.js";
2
2
  import type { BillingAutoRechargeAttempt, BillingAutoRechargeProfile, BillingCreditPostingResult, BillingCustomerRecord, BillingEventClaim, BillingOfferResult, BillingPaymentRecord, BillingPreferences, BillingSubscriptionChange, BillingSubscriptionChangeInput, BillingSubscriptionState, CheckoutIntent, BillingTopupResult } from "../types/index.js";
3
3
  import { BillingStore } from "../billing-store.js";
4
4
  import type { AutoRechargeAttemptClaim, AutoRechargeAttemptUpdate, AutoRechargeProviderPaymentUpdate, BillingCreditGrantCreate, BillingDisputeUpsert, BillingInvoiceUpsert, BillingPaymentUpsert, BillingRefundUpsert, BillingSubscriptionChangeUpdate, BillingSubscriptionConflictCreate, CheckoutIntentCreate, CheckoutIntentUpdate } from "../contracts.js";
5
5
  import { type PostgresConnectionOptions, type PostgresPool, type PostgresPoolConstructor } from "../../shared/postgres-client.js";
6
- export interface PostgresBillingStoreOptions extends PostgresConnectionOptions {
6
+ import { type ProviderEnvironment } from "../../providers/environment.js";
7
+ export interface PostgresBillingStoreOptions extends Omit<PostgresConnectionOptions, "providerEnvironment"> {
7
8
  /** PostgreSQL connection string or an application-owned pool. */
8
9
  postgres: PostgresPool | string;
9
10
  /** Tenant UUID bound to every store transaction. */
10
11
  tenantId: string;
12
+ /** Explicit financial namespace; billing stores never guess live vs test. */
13
+ providerEnvironment: ProviderEnvironment;
11
14
  /** Injectable `pg.Pool` constructor for custom runtimes and tests. */
12
15
  poolConstructor?: PostgresPoolConstructor;
13
16
  billingPayloadBackend?: "postgres" | "s3";
14
17
  }
15
18
  export declare class PostgresBillingStore extends BillingStore {
16
19
  private readonly postgres;
20
+ readonly providerEnvironment: ProviderEnvironment;
17
21
  private _offer;
18
22
  private _topup;
19
23
  private _customer;
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/billing/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AAEjC,OAAO,KAAK,EACV,0BAA0B,EAC1B,0BAA0B,EAC1B,0BAA0B,EAC1B,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EAClB,oBAAoB,EACpB,kBAAkB,EAClB,yBAAyB,EACzB,8BAA8B,EAC9B,wBAAwB,EACxB,cAAc,EACd,kBAAkB,EACnB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EACV,wBAAwB,EACxB,yBAAyB,EACzB,iCAAiC,EACjC,wBAAwB,EACxB,oBAAoB,EACpB,oBAAoB,EACpB,oBAAoB,EACpB,mBAAmB,EACnB,+BAA+B,EAC/B,iCAAiC,EACjC,oBAAoB,EACpB,oBAAoB,EACrB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAEL,KAAK,yBAAyB,EAC9B,KAAK,YAAY,EACjB,KAAK,uBAAuB,EAC7B,MAAM,iCAAiC,CAAC;AA2FzC,MAAM,WAAW,2BAA4B,SAAQ,yBAAyB;IAC5E,iEAAiE;IACjE,QAAQ,EAAE,YAAY,GAAG,MAAM,CAAC;IAChC,oDAAoD;IACpD,QAAQ,EAAE,MAAM,CAAC;IACjB,sEAAsE;IACtE,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C,qBAAqB,CAAC,EAAE,UAAU,GAAG,IAAI,CAAC;CAC3C;AA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AM,EAAE,MAAM,EACd,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GACvB,OAAO,CAAC,qBAAqB,GAAG,IAAI,CAAC;CAQzC"}
@@ -1,9 +1,11 @@
1
- import Decimal from "decimal.js";
1
+ import { Decimal } from "decimal.js";
2
2
  import { z } from "zod";
3
3
  import { BillingStore } from "../billing-store.js";
4
4
  import { PostgresClient, } from "../../shared/postgres-client.js";
5
+ import { normalizeProviderEnvironment, } from "../../providers/environment.js";
5
6
  import { StoreClosedError, StoreError } from "../../errors.js";
6
7
  import { optionalBoundedDiagnosticMessage } from "../../shared/diagnostics.js";
8
+ import { requireStableKey } from "../../shared/idempotency.js";
7
9
  import { optionalRecordRow, pgBoolean, postgresUuid, requireRecordRow, requireResultField, safeParse, } from "../../shared/postgres-validation.js";
8
10
  import { BillingOfferRepository } from "./repositories/offer.js";
9
11
  import { BillingTopupRepository } from "./repositories/topup.js";
@@ -71,6 +73,7 @@ function billingCreditPostingResult(rows, context) {
71
73
  }
72
74
  export class PostgresBillingStore extends BillingStore {
73
75
  postgres;
76
+ providerEnvironment;
74
77
  _offer = null;
75
78
  _topup = null;
76
79
  _customer = null;
@@ -91,8 +94,11 @@ export class PostgresBillingStore extends BillingStore {
91
94
  if (typeof options.postgres !== "string" && options.poolConstructor !== undefined) {
92
95
  throw new TypeError("poolConstructor cannot be used with an existing PostgreSQL pool");
93
96
  }
97
+ const providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);
98
+ this.providerEnvironment = providerEnvironment;
94
99
  this.postgres = new PostgresClient(options.postgres, {
95
100
  tenantId: options.tenantId,
101
+ providerEnvironment,
96
102
  poolConstructor: options.poolConstructor,
97
103
  billingPayloadBackend: options.billingPayloadBackend,
98
104
  connectionTimeoutMs: options.connectionTimeoutMs,
@@ -173,12 +179,16 @@ export class PostgresBillingStore extends BillingStore {
173
179
  return this._subscriptionChange;
174
180
  }
175
181
  async createOrGetCheckoutIntent(input) {
182
+ const operationKey = requireStableKey(input.operationKey, "operationKey");
176
183
  if (!/^[0-9a-fA-F]{64}$/.test(input.requestDigest)) {
177
184
  throw new TypeError("requestDigest must be a 32-byte hex string");
178
185
  }
179
- const rows = await this.queryFn(`SELECT bursar.create_checkout_intent($1::uuid, $2, $3, $4, decode($5, 'hex'), $6::timestamptz) AS id`, [
186
+ const rows = await this.queryFn(`SELECT bursar.create_checkout_intent(
187
+ $1::uuid, $2, $3, $4, $5, decode($6, 'hex'), $7::timestamptz
188
+ ) AS id`, [
180
189
  input.subjectId,
181
190
  input.provider,
191
+ operationKey,
182
192
  input.checkoutKind,
183
193
  input.productKey,
184
194
  input.requestDigest,
@@ -285,10 +295,15 @@ export class PostgresBillingStore extends BillingStore {
285
295
  return { status: "duplicate" };
286
296
  if (result.status === "busy")
287
297
  return { status: "busy" };
288
- if (result.status === "invalid_request" ||
289
- result.status === "idempotency_conflict" ||
290
- result.status === "max_retries_exceeded") {
291
- return { status: "retry" };
298
+ if (result.status === "invalid_request")
299
+ return { status: "invalid_request" };
300
+ if (result.status === "idempotency_conflict" || result.status === "max_retries_exceeded") {
301
+ if (result.event_id === null) {
302
+ throw new StoreError("Billing event terminal claim returned no event identifier", {
303
+ details: { provider, eventId, status: result.status },
304
+ });
305
+ }
306
+ return { status: result.status, billingEventId: result.event_id };
292
307
  }
293
308
  throw new StoreError("Billing event claim returned an unsupported status", {
294
309
  details: { provider, eventId, status: result.status },
@@ -1 +1 @@
1
- {"version":3,"file":"store.js","sourceRoot":"","sources":["../../../src/billing/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAgBxB,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAgBnD,OAAO,EACL,cAAc,GAIf,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC/D,OAAO,EAAE,gCAAgC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C,CAAC;IAED,KAAK,CAAC,sBAAsB,CAAC,MAAc;QACzC,OAAO,IAAI,CAAC,mBAAmB,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IACrD,CAAC;IAED,KAAK,CAAC,yBAAyB,CAC7B,OAAmC,EACnC,OAAqC;QAErC,OAAO,IAAI,CAAC,mBAAmB,CAAC,aAAa,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;IAED,KAAK,CAAC,wBAAwB,CAC5B,KAA+B;QAE/B,OAAO,IAAI,CAAC,mBAAmB,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;IACtD,CAAC;IAED,KAAK,CAAC,yBAAyB,CAAC,KAAgC;QAC9D,OAAO,IAAI,CAAC,mBAAmB,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;IACvD,CAAC;IAED,KAAK,CAAC,0CAA0C,CAC9C,KAAwC;QAExC,OAAO,IAAI,CAAC,mBAAmB,CAAC,8BAA8B,CAAC,KAAK,CAAC,CAAC;IACxE,CAAC;IAED,KAAK,CAAC,yBAAyB,CAAC,MAAc,EAAE,KAAoB;QAClE,OAAO,IAAI,CAAC,mBAAmB,CAAC,aAAa,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC/D,CAAC;IAED,KAAK,CAAC,0BAA0B,CAC9B,MAAc,EACd,QAAwB;QAExB,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,WAAW,CAAC,MAAM,EAAE,QAAQ,IAAI,IAAI,CAAC,CAAC;QAChF,IAAI,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QACzB,OAAO;YACL,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,kBAAkB,EAAE,MAAM,CAAC,kBAAkB;SAC9C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\nimport { z } from \"zod\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeProfile,\n BillingCreditPostingResult,\n BillingCustomerRecord,\n BillingEventClaim,\n BillingOfferResult,\n BillingPaymentRecord,\n BillingPreferences,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionState,\n CheckoutIntent,\n BillingTopupResult,\n} from \"../types/index.js\";\nimport { BillingStore } from \"../billing-store.js\";\nimport type {\n AutoRechargeAttemptClaim,\n AutoRechargeAttemptUpdate,\n AutoRechargeProviderPaymentUpdate,\n BillingCreditGrantCreate,\n BillingDisputeUpsert,\n BillingInvoiceUpsert,\n BillingPaymentUpsert,\n BillingRefundUpsert,\n BillingSubscriptionChangeUpdate,\n BillingSubscriptionConflictCreate,\n CheckoutIntentCreate,\n CheckoutIntentUpdate,\n} from \"../contracts.js\";\nimport type { QueryFn } from \"../../shared/postgres-types.js\";\nimport {\n PostgresClient,\n type PostgresConnectionOptions,\n type PostgresPool,\n type PostgresPoolConstructor,\n} from \"../../shared/postgres-client.js\";\nimport { StoreClosedError, StoreError } from \"../../errors.js\";\nimport { optionalBoundedDiagnosticMessage } from \"../../shared/diagnostics.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireRecordRow,\n requireResultField,\n safeParse,\n} from \"../../shared/postgres-validation.js\";\nimport { BillingOfferRepository, type BillingOfferRow } from \"./repositories/offer.js\";\nimport { BillingTopupRepository, type BillingTopupRow } from \"./repositories/topup.js\";\nimport { BillingCustomerRepository } from \"./repositories/customer.js\";\nimport {\n BillingSubscriptionRepository,\n type SubscriptionRow,\n} from \"./repositories/subscription.js\";\nimport { BillingEventRepository } from \"./repositories/event.js\";\nimport { BillingPaymentRepository } from \"./repositories/payment.js\";\nimport { BillingRefundRepository } from \"./repositories/refund.js\";\nimport { BillingInvoiceRepository } from \"./repositories/invoice.js\";\nimport { BillingDisputeRepository } from \"./repositories/dispute.js\";\nimport { BillingPreferencesRepository } from \"./repositories/preferences.js\";\nimport { BillingAutoRechargeRepository } from \"./repositories/auto-recharge.js\";\nimport { BillingSubscriptionChangeRepository } from \"./repositories/subscription-change.js\";\n\nconst PgSafeMinorUnitsSchema = z\n .union([z.string().regex(/^\\d+$/), z.number().int().nonnegative().safe()])\n .transform(Number)\n .refine(Number.isSafeInteger, \"minor-unit amount exceeds JavaScript's safe integer range\");\n\nconst BillingCreditPostingRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n balance_after: z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .nullable()\n .transform((value) => (value === null ? null : new Decimal(value))),\n replayed: pgBoolean,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.error_code === null && (row.ledger_entry_id === null || row.balance_after === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"successful posting requires ledger_entry_id and balance_after\",\n });\n }\n });\n\nconst CheckoutIntentRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n checkout_kind: z.enum([\"subscription\", \"credit_topup\"]),\n product_key: z.string().min(1),\n request_digest: z.instanceof(Uint8Array).refine((value) => value.byteLength === 32),\n status: z.enum([\"open\", \"completed\", \"failed\", \"expired\"]),\n provider_session_id: z.string().min(1).nullable(),\n checkout_url: z.string().min(1).nullable(),\n expires_at: z.union([z.string().datetime({ offset: true }), z.date()]),\n })\n .strict();\n\nfunction billingCreditPostingResult(\n rows: readonly unknown[] | null | undefined,\n context: string,\n): BillingCreditPostingResult {\n const raw = requireRecordRow(rows, context);\n const row = safeParse(\n BillingCreditPostingRowSchema,\n {\n ledger_entry_id: raw.ledger_entry_id,\n balance_after: raw.balance_after,\n replayed: raw.replayed,\n error_code: raw.error_code,\n },\n context,\n { indeterminate: true },\n );\n return {\n ledgerEntryId: row.ledger_entry_id,\n balanceAfter: row.balance_after,\n replayed: row.replayed,\n errorCode: row.error_code,\n };\n}\n\nexport interface PostgresBillingStoreOptions extends PostgresConnectionOptions {\n /** PostgreSQL connection string or an application-owned pool. */\n postgres: PostgresPool | string;\n /** Tenant UUID bound to every store transaction. */\n tenantId: string;\n /** Injectable `pg.Pool` constructor for custom runtimes and tests. */\n poolConstructor?: PostgresPoolConstructor;\n billingPayloadBackend?: \"postgres\" | \"s3\";\n}\n\nexport class PostgresBillingStore extends BillingStore {\n private readonly postgres: PostgresClient;\n\n private _offer: BillingOfferRepository | null = null;\n private _topup: BillingTopupRepository | null = null;\n private _customer: BillingCustomerRepository | null = null;\n private _subscription: BillingSubscriptionRepository | null = null;\n private _event: BillingEventRepository | null = null;\n private _payment: BillingPaymentRepository | null = null;\n private _refund: BillingRefundRepository | null = null;\n private _invoice: BillingInvoiceRepository | null = null;\n private _dispute: BillingDisputeRepository | null = null;\n private _preferences: BillingPreferencesRepository | null = null;\n private _autoRecharge: BillingAutoRechargeRepository | null = null;\n private _subscriptionChange: BillingSubscriptionChangeRepository | null = null;\n constructor(options: PostgresBillingStoreOptions) {\n super();\n if (typeof options !== \"object\" || options === null) {\n throw new TypeError(\"PostgresBillingStore options are required\");\n }\n if (typeof options.postgres !== \"string\" && options.poolConstructor !== undefined) {\n throw new TypeError(\"poolConstructor cannot be used with an existing PostgreSQL pool\");\n }\n this.postgres = new PostgresClient(options.postgres, {\n tenantId: options.tenantId,\n poolConstructor: options.poolConstructor,\n billingPayloadBackend: options.billingPayloadBackend,\n connectionTimeoutMs: options.connectionTimeoutMs,\n statementTimeoutMs: options.statementTimeoutMs,\n idleTransactionTimeoutMs: options.idleTransactionTimeoutMs,\n idleTimeoutMs: options.idleTimeoutMs,\n maxConnections: options.maxConnections,\n applicationName: options.applicationName,\n onPoolError: options.onPoolError,\n closedError: () => new StoreClosedError(\"Billing store has been closed\"),\n });\n }\n\n async close(): Promise<void> {\n await this.postgres.close();\n }\n\n private get queryFn(): QueryFn {\n return this.postgres.query;\n }\n\n private get billingOffer(): BillingOfferRepository {\n if (!this._offer) this._offer = new BillingOfferRepository(this.queryFn);\n return this._offer;\n }\n\n private get billingTopup(): BillingTopupRepository {\n if (!this._topup) this._topup = new BillingTopupRepository(this.queryFn);\n return this._topup;\n }\n\n private get billingCustomer(): BillingCustomerRepository {\n if (!this._customer) this._customer = new BillingCustomerRepository(this.queryFn);\n return this._customer;\n }\n\n private get billingSubscription(): BillingSubscriptionRepository {\n if (!this._subscription) this._subscription = new BillingSubscriptionRepository(this.queryFn);\n return this._subscription;\n }\n\n private get billingEvent(): BillingEventRepository {\n if (!this._event) this._event = new BillingEventRepository(this.queryFn);\n return this._event;\n }\n\n private get billingPayment(): BillingPaymentRepository {\n if (!this._payment) this._payment = new BillingPaymentRepository(this.queryFn);\n return this._payment;\n }\n\n private get billingRefund(): BillingRefundRepository {\n if (!this._refund) this._refund = new BillingRefundRepository(this.queryFn);\n return this._refund;\n }\n\n private get billingInvoice(): BillingInvoiceRepository {\n if (!this._invoice) this._invoice = new BillingInvoiceRepository(this.queryFn);\n return this._invoice;\n }\n\n private get billingDispute(): BillingDisputeRepository {\n if (!this._dispute) this._dispute = new BillingDisputeRepository(this.queryFn);\n return this._dispute;\n }\n\n private get billingPreferences(): BillingPreferencesRepository {\n if (!this._preferences) this._preferences = new BillingPreferencesRepository(this.queryFn);\n return this._preferences;\n }\n\n private get billingAutoRecharge(): BillingAutoRechargeRepository {\n if (!this._autoRecharge) this._autoRecharge = new BillingAutoRechargeRepository(this.queryFn);\n return this._autoRecharge;\n }\n\n private get billingSubscriptionChange(): BillingSubscriptionChangeRepository {\n if (!this._subscriptionChange) {\n this._subscriptionChange = new BillingSubscriptionChangeRepository(this.queryFn);\n }\n return this._subscriptionChange;\n }\n\n async createOrGetCheckoutIntent(input: CheckoutIntentCreate): Promise<CheckoutIntent> {\n if (!/^[0-9a-fA-F]{64}$/.test(input.requestDigest)) {\n throw new TypeError(\"requestDigest must be a 32-byte hex string\");\n }\n const rows = await this.queryFn(\n `SELECT bursar.create_checkout_intent($1::uuid, $2, $3, $4, decode($5, 'hex'), $6::timestamptz) AS id`,\n [\n input.subjectId,\n input.provider,\n input.checkoutKind,\n input.productKey,\n input.requestDigest,\n input.expiresAt,\n ],\n );\n const id = requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createOrGetCheckoutIntent\",\n );\n const intent = await this.getCheckoutIntent(id, input.subjectId);\n if (!intent) {\n throw new StoreError(\"checkout intent could not be read after creation\", {\n indeterminate: true,\n details: { checkoutIntentId: id },\n });\n }\n return intent;\n }\n\n async updateCheckoutIntent(id: string, update: CheckoutIntentUpdate): Promise<void> {\n const rows = await this.queryFn(\n `SELECT bursar.advance_checkout_intent($1::uuid, $2, $3, $4) AS advanced`,\n [id, update.status ?? null, update.providerSessionId ?? null, update.checkoutUrl ?? null],\n );\n if (\n !requireResultField(rows, \"advanced\", pgBoolean, \"PostgresBillingStore.updateCheckoutIntent\")\n ) {\n throw new StoreError(`checkout intent transition rejected: ${id}`, {\n details: { checkoutIntentId: id },\n });\n }\n }\n\n async getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_checkout_intent($1::uuid, $2::uuid)`,\n [id, subjectId],\n );\n if (rows.length === 0) return null;\n if (rows.length !== 1) {\n throw new StoreError(\"getCheckoutIntent: expected at most one row\", {\n details: { rowCount: rows.length, checkoutIntentId: id },\n });\n }\n const row = rows[0] as Record<string, unknown>;\n return this.rowToCheckoutIntent(\n safeParse(\n CheckoutIntentRowSchema,\n {\n id: row.id,\n subject_id: row.subject_id,\n provider: row.provider,\n checkout_kind: row.checkout_kind,\n product_key: row.product_key,\n request_digest: row.request_digest,\n status: row.status,\n provider_session_id: row.provider_session_id,\n checkout_url: row.checkout_url,\n expires_at: row.expires_at,\n },\n \"PostgresBillingStore.getCheckoutIntent\",\n ),\n );\n }\n\n private rowToCheckoutIntent(row: z.infer<typeof CheckoutIntentRowSchema>): CheckoutIntent {\n return {\n id: row.id,\n subjectId: row.subject_id,\n provider: row.provider,\n checkoutKind: row.checkout_kind,\n productKey: row.product_key,\n requestDigest: Buffer.from(row.request_digest).toString(\"hex\"),\n status: row.status,\n providerSessionId: row.provider_session_id,\n checkoutUrl: row.checkout_url,\n expiresAt: row.expires_at instanceof Date ? row.expires_at.toISOString() : row.expires_at,\n };\n }\n\n private rowToOffer(row: BillingOfferRow | null): BillingOfferResult | null {\n if (!row) return null;\n return {\n offerId: row.id,\n offerKey: row.offerKey,\n planId: row.planId,\n plan: row.plan,\n interval: row.interval,\n intervalCount: row.intervalCount,\n grant:\n row.grantCredits === null\n ? null\n : {\n mode: \"cycle_grant\",\n credits: row.grantCredits,\n bucket: row.grantBucket,\n replacePrior: row.grantReplacePrior,\n },\n };\n }\n\n async resolveBillingOffer(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByPrice(provider, priceId ?? null, productId ?? null);\n return this.rowToOffer(r);\n }\n\n async resolveBillingOfferByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByLookup(provider, lookupKey);\n return this.rowToOffer(r);\n }\n\n async claimBillingEvent(\n provider: string,\n eventId: string,\n eventType: string,\n envelope?: Record<string, unknown>,\n ): Promise<BillingEventClaim> {\n const result = await this.billingEvent.claim(\n provider,\n eventId,\n eventType,\n JSON.stringify(envelope ?? { eventType }),\n );\n if (result.status === \"claimed\") {\n if (result.claim_token === null || result.event_id === null) {\n throw new StoreError(\"Billing event claim returned no claim identifiers\", {\n details: { provider, eventId },\n });\n }\n return {\n status: \"claimed\" as const,\n claimToken: result.claim_token,\n billingEventId: result.event_id,\n };\n }\n if (result.status === \"duplicate\") return { status: \"duplicate\" as const };\n if (result.status === \"busy\") return { status: \"busy\" as const };\n if (\n result.status === \"invalid_request\" ||\n result.status === \"idempotency_conflict\" ||\n result.status === \"max_retries_exceeded\"\n ) {\n return { status: \"retry\" as const };\n }\n throw new StoreError(\"Billing event claim returned an unsupported status\", {\n details: { provider, eventId, status: result.status },\n });\n }\n\n async completeBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n ): Promise<boolean> {\n return this.billingEvent.complete(provider, eventId, claimToken);\n }\n\n async failBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n error?: string,\n ): Promise<boolean> {\n return this.billingEvent.fail(\n provider,\n eventId,\n claimToken,\n optionalBoundedDiagnosticMessage(error) ?? undefined,\n );\n }\n\n async upsertBillingCustomer(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email?: string | null,\n ): Promise<void> {\n await this.billingCustomer.upsert(provider, providerCustomerId, userId, email ?? null);\n }\n\n async upsertBillingSubscription(state: BillingSubscriptionState): Promise<void> {\n await this.billingSubscription.upsert(state);\n }\n\n async getBillingCustomer(provider: string, providerCustomerId: string): Promise<string | null> {\n return this.billingCustomer.get(provider, providerCustomerId);\n }\n\n async getBillingSubscription(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.get(provider, providerSubscriptionId);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async createBillingSubscriptionChange(\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n const subscription = await this.billingSubscription.get(\n input.provider,\n input.providerSubscriptionId,\n );\n if (!subscription?.id) {\n throw new StoreError(\"subscription change requires a persisted subscription\", {\n retryable: true,\n details: {\n provider: input.provider,\n providerSubscriptionId: input.providerSubscriptionId,\n },\n });\n }\n return this.billingSubscriptionChange.create(subscription.id, input);\n }\n\n async getOpenBillingSubscriptionChange(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.billingSubscriptionChange.getOpen(provider, providerSubscriptionId);\n }\n\n async listExpiredGraceSubscriptions(\n now: string,\n limit = 100,\n ): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.listExpiredGraceSubscriptions(now, limit);\n return rows.map((row) => this.rowToSubscriptionState(row));\n }\n\n async markSubscriptionGraceExpired(\n subscriptionId: string,\n expectedGraceEndsAt: string,\n expiredAt = new Date().toISOString(),\n ): Promise<boolean> {\n return this.billingSubscription.markGraceExpired(\n subscriptionId,\n expectedGraceEndsAt,\n expiredAt,\n );\n }\n\n async updateBillingSubscriptionChange(\n id: string,\n update: BillingSubscriptionChangeUpdate,\n ): Promise<void> {\n await this.billingSubscriptionChange.update(id, update);\n }\n\n async getUserSubscription(\n userId: string,\n statuses?: string[],\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.getUserSubscription(userId, statuses);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async getUserSubscriptions(userId: string): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.getUserSubscriptions(userId);\n return rows.map((r) => this.rowToSubscriptionState(r));\n }\n\n async recordSubscriptionConflict(input: BillingSubscriptionConflictCreate): Promise<void> {\n await this.billingSubscription.recordConflict(input);\n }\n\n async selectSubscriptionEntitlementSource(\n userId: string,\n provider: string,\n providerSubscriptionId?: string | null,\n ): Promise<boolean> {\n return this.billingSubscription.selectEntitlementSource(\n userId,\n provider,\n providerSubscriptionId,\n );\n }\n\n private rowToTopup(r: BillingTopupRow | null): BillingTopupResult | null {\n if (!r) return null;\n const minAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.min_quantity,\n \"PostgresBillingStore.rowToTopup.minAmountMinor\",\n );\n const maxAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.max_quantity,\n \"PostgresBillingStore.rowToTopup.maxAmountMinor\",\n );\n return {\n topupId: r.id,\n topupKey: r.topup_key,\n creditsPerUnit: r.credits_per_unit,\n depositTo: r.bucket_key,\n amountMinor: r.amount_minor,\n currency: r.currency,\n minQuantity: r.min_quantity,\n maxQuantity: r.max_quantity,\n defaultQuantity: r.default_quantity,\n minAmountMinor,\n maxAmountMinor,\n };\n }\n\n async resolveCreditTopup(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByPrice(provider, priceId ?? null, productId ?? null);\n return this.rowToTopup(r);\n }\n\n async resolveCreditTopupByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByLookup(provider, lookupKey);\n return this.rowToTopup(r);\n }\n\n async computeTopupCredits(\n amountMinor: number,\n topupConfig: BillingTopupResult,\n ): Promise<Decimal> {\n if (!Number.isSafeInteger(amountMinor) || amountMinor < 0) {\n throw new TypeError(\"amountMinor must be a non-negative safe integer\");\n }\n const unitAmount = topupConfig.amountMinor;\n if (unitAmount <= 0 || amountMinor % unitAmount !== 0) return new Decimal(0);\n const quantity = amountMinor / unitAmount;\n if (quantity < topupConfig.minQuantity || quantity > topupConfig.maxQuantity) {\n return new Decimal(0);\n }\n return topupConfig.creditsPerUnit.mul(quantity);\n }\n\n async upsertBillingPayment(options: BillingPaymentUpsert): Promise<string> {\n return this.billingPayment.upsert(\n options.provider,\n options.providerPaymentId,\n options.providerInvoiceId ?? null,\n options.userId,\n options.amountMinor,\n options.taxMinor,\n options.currency,\n options.purpose,\n options.metadata ? JSON.stringify(options.metadata) : null,\n options.status,\n options.providerUpdatedAt,\n );\n }\n\n async createBillingCreditGrant(input: BillingCreditGrantCreate): Promise<string> {\n const rows = await this.queryFn(\n \"SELECT bursar.create_billing_credit_grant($1::uuid, $2::uuid, $3::uuid, $4, $5, $6::uuid) AS id\",\n [\n input.paymentId ?? null,\n input.subscriptionId ?? null,\n input.topupId ?? null,\n input.configuredCredits.toString(),\n input.quantity,\n input.billingEventId ?? null,\n ],\n );\n return requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createBillingCreditGrant\",\n );\n }\n\n async grantBillingCredit(\n grantId: string,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.grant_billing_credit($1::uuid, $2)\", [\n grantId,\n idempotencyKey,\n ]);\n return billingCreditPostingResult(rows, \"PostgresBillingStore.grantBillingCredit\");\n }\n\n async getBillingCreditGrantByPayment(paymentId: string): Promise<string | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_billing_credit_grant_by_payment($1::uuid)`,\n [paymentId],\n );\n const row = optionalRecordRow(rows, \"PostgresBillingStore.getBillingCreditGrantByPayment\");\n return row === null\n ? null\n : safeParse(postgresUuid, row.id, \"PostgresBillingStore.getBillingCreditGrantByPayment.id\");\n }\n\n async postBillingRefund(\n refundId: string,\n grantId: string,\n amountMinor: number,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\n \"SELECT * FROM bursar.post_billing_refund($1::uuid, $2::uuid, $3, $4)\",\n [refundId, grantId, amountMinor, idempotencyKey],\n );\n return billingCreditPostingResult(rows, \"PostgresBillingStore.postBillingRefund\");\n }\n\n async upsertBillingRefund(options: BillingRefundUpsert): Promise<string> {\n return this.billingRefund.upsert(\n options.provider,\n options.providerRefundId,\n options.providerPaymentId,\n options.userId,\n options.amountMinor,\n options.currency,\n options.reason ?? null,\n options.metadata ? JSON.stringify(options.metadata) : null,\n options.status,\n options.providerUpdatedAt,\n );\n }\n\n async upsertBillingInvoice(options: BillingInvoiceUpsert): Promise<void> {\n const subscription = options.providerSubscriptionId\n ? await this.billingSubscription.get(options.provider, options.providerSubscriptionId)\n : null;\n if (options.providerSubscriptionId && !subscription) {\n throw new StoreError(\"invoice subscription is not available\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerInvoiceId: options.providerInvoiceId,\n providerSubscriptionId: options.providerSubscriptionId ?? null,\n },\n });\n }\n await this.billingInvoice.upsert(\n options.userId,\n options.provider,\n options.providerInvoiceId,\n subscription?.id ? String(subscription.id) : null,\n options.status,\n options.amountDueMinor,\n options.amountPaidMinor,\n options.currency,\n options.periodStart ?? null,\n options.periodEnd ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async listBillingInvoices(userId: string) {\n return this.billingInvoice.listForUser(userId);\n }\n\n async upsertBillingDispute(options: BillingDisputeUpsert): Promise<void> {\n const payment = await this.billingPayment.getForRefund(\n options.provider,\n options.providerPaymentId,\n );\n if (!payment?.id) {\n throw new StoreError(\"dispute payment is required\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerDisputeId: options.providerDisputeId,\n providerPaymentId: options.providerPaymentId ?? null,\n },\n });\n }\n await this.billingDispute.upsert(\n options.provider,\n options.providerDisputeId,\n String(payment.id),\n options.status,\n options.reason ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async getBillingPayment(\n provider: string,\n providerPaymentId: string,\n ): Promise<BillingPaymentRecord | null> {\n const row = await this.billingPayment.getForRefund(provider, providerPaymentId);\n if (!row) return null;\n return {\n id: row.id,\n provider: row.provider,\n providerPaymentId: row.provider_payment_id,\n providerInvoiceId: row.provider_invoice_id,\n userId: row.subject_id,\n amountMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.amount_minor,\n \"PostgresBillingStore.getBillingPayment.amountMinor\",\n ),\n taxMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.tax_minor,\n \"PostgresBillingStore.getBillingPayment.taxMinor\",\n ),\n currency: row.currency,\n purpose: row.purpose,\n status: row.status,\n providerUpdatedAt:\n row.provider_updated_at instanceof Date\n ? row.provider_updated_at.toISOString()\n : row.provider_updated_at,\n metadata: row.metadata,\n };\n }\n\n private rowToSubscriptionState(r: SubscriptionRow): BillingSubscriptionState {\n return {\n subscriptionId: r.id,\n userId: r.user_id,\n provider: r.provider,\n providerSubscriptionId: r.provider_subscription_id,\n providerCustomerId: r.provider_customer_id,\n offerId: r.offer_id,\n offerKey: r.offer_key,\n planId: r.plan_id,\n plan: r.plan,\n status: r.status,\n currentPeriodStart: r.current_period_start,\n currentPeriodEnd: r.current_period_end,\n trialEnd: r.trial_end,\n cancelAt: r.cancel_at,\n endedAt: r.ended_at,\n graceEndsAt: r.grace_ends_at,\n graceExpiredAt: r.grace_expired_at,\n providerUpdatedAt: r.provider_updated_at,\n cancelAtPeriodEnd: r.cancel_at_period_end,\n interval: r.interval,\n intervalCount: r.interval_count,\n metadata: r.metadata,\n };\n }\n\n async getActiveCatalogDocument(): Promise<Record<string, unknown> | null> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.active_catalog_revision()\", []);\n if (rows.length === 0) return null;\n if (rows.length !== 1 || typeof rows[0] !== \"object\" || rows[0] === null) {\n throw new StoreError(\"active catalog revision returned a malformed row\", {\n details: { rowCount: rows.length },\n });\n }\n return safeParse(\n z.record(z.string(), z.unknown()),\n (rows[0] as Record<string, unknown>).source_document,\n \"PostgresBillingStore.getActiveCatalogDocument\",\n );\n }\n\n async pseudonymizeFinancialSubject(userId: string): Promise<boolean> {\n const rows = await this.queryFn(\n `SELECT bursar.pseudonymize_financial_subject($1::uuid) AS pseudonymized`,\n [userId],\n );\n return requireResultField(\n rows,\n \"pseudonymized\",\n pgBoolean,\n \"PostgresBillingStore.pseudonymizeFinancialSubject\",\n );\n }\n\n async getBillingPreferences(userId: string): Promise<BillingPreferences | null> {\n return this.billingPreferences.get(userId);\n }\n\n async upsertBillingPreferences(prefs: BillingPreferences): Promise<void> {\n await this.billingPreferences.upsert(prefs);\n }\n\n async getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n return this.billingAutoRecharge.getProfile(userId);\n }\n\n async upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void> {\n return this.billingAutoRecharge.upsertProfile(profile, options);\n }\n\n async claimAutoRechargeAttempt(\n input: AutoRechargeAttemptClaim,\n ): Promise<BillingAutoRechargeAttempt | null> {\n return this.billingAutoRecharge.claimAttempt(input);\n }\n\n async updateAutoRechargeAttempt(input: AutoRechargeAttemptUpdate): Promise<void> {\n return this.billingAutoRecharge.updateAttempt(input);\n }\n\n async updateAutoRechargeAttemptByProviderPayment(\n input: AutoRechargeProviderPaymentUpdate,\n ): Promise<void> {\n return this.billingAutoRecharge.updateAttemptByProviderPayment(input);\n }\n\n async countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number> {\n return this.billingAutoRecharge.countAttempts(userId, since);\n }\n\n async getBillingCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null> {\n const result = await this.billingCustomer.getByUserId(userId, provider ?? null);\n if (!result) return null;\n return {\n provider: result.provider,\n providerCustomerId: result.providerCustomerId,\n };\n }\n}\n"]}
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../../src/billing/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAgBxB,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAgBnD,OAAO,EACL,cAAc,GAIf,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,4BAA4B,GAE7B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC/D,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAC/D,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,SAAS,GACV,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,sBAAsB,EAAwB,MAAM,yBAAyB,CAAC;AACvF,OAAO,EAAE,sBAAsB,EAAwB,MAAM,yBAAyB,CAAC;AACvF,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EACL,6BAA6B,GAE9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AACjE,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EAAE,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oRechargeProfile,\n BillingCreditPostingResult,\n BillingCustomerRecord,\n BillingEventClaim,\n BillingOfferResult,\n BillingPaymentRecord,\n BillingPreferences,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionState,\n CheckoutIntent,\n BillingTopupResult,\n} from \"../types/index.js\";\nimport { BillingStore } from \"../billing-store.js\";\nimport type {\n AutoRechargeAttemptClaim,\n AutoRechargeAttemptUpdate,\n AutoRechargeProviderPaymentUpdate,\n BillingCreditGrantCreate,\n BillingDisputeUpsert,\n BillingInvoiceUpsert,\n BillingPaymentUpsert,\n BillingRefundUpsert,\n BillingSubscriptionChangeUpdate,\n BillingSubscriptionConflictCreate,\n CheckoutIntentCreate,\n CheckoutIntentUpdate,\n} from \"../contracts.js\";\nimport type { QueryFn } from \"../../shared/postgres-types.js\";\nimport {\n PostgresClient,\n type PostgresConnectionOptions,\n type PostgresPool,\n type PostgresPoolConstructor,\n} from \"../../shared/postgres-client.js\";\nimport {\n normalizeProviderEnvironment,\n type ProviderEnvironment,\n} from \"../../providers/environment.js\";\nimport { StoreClosedError, StoreError } from \"../../errors.js\";\nimport { optionalBoundedDiagnosticMessage } from \"../../shared/diagnostics.js\";\nimport { requireStableKey } from \"../../shared/idempotency.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireRecordRow,\n requireResultField,\n safeParse,\n} from \"../../shared/postgres-validation.js\";\nimport { BillingOfferRepository, type BillingOfferRow } from \"./repositories/offer.js\";\nimport { BillingTopupRepository, type BillingTopupRow } from \"./repositories/topup.js\";\nimport { BillingCustomerRepository } from \"./repositories/customer.js\";\nimport {\n BillingSubscriptionRepository,\n type SubscriptionRow,\n} from \"./repositories/subscription.js\";\nimport { BillingEventRepository } from \"./repositories/event.js\";\nimport { BillingPaymentRepository } from \"./repositories/payment.js\";\nimport { BillingRefundRepository } from \"./repositories/refund.js\";\nimport { BillingInvoiceRepository } from \"./repositories/invoice.js\";\nimport { BillingDisputeRepository } from \"./repositories/dispute.js\";\nimport { BillingPreferencesRepository } from \"./repositories/preferences.js\";\nimport { BillingAutoRechargeRepository } from \"./repositories/auto-recharge.js\";\nimport { BillingSubscriptionChangeRepository } from \"./repositories/subscription-change.js\";\n\nconst PgSafeMinorUnitsSchema = z\n .union([z.string().regex(/^\\d+$/), z.number().int().nonnegative().safe()])\n .transform(Number)\n .refine(Number.isSafeInteger, \"minor-unit amount exceeds JavaScript's safe integer range\");\n\nconst BillingCreditPostingRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n balance_after: z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .nullable()\n .transform((value) => (value === null ? null : new Decimal(value))),\n replayed: pgBoolean,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.error_code === null && (row.ledger_entry_id === null || row.balance_after === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"successful posting requires ledger_entry_id and balance_after\",\n });\n }\n });\n\nconst CheckoutIntentRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n checkout_kind: z.enum([\"subscription\", \"credit_topup\"]),\n product_key: z.string().min(1),\n request_digest: z.instanceof(Uint8Array).refine((value) => value.byteLength === 32),\n status: z.enum([\"open\", \"completed\", \"failed\", \"expired\"]),\n provider_session_id: z.string().min(1).nullable(),\n checkout_url: z.string().min(1).nullable(),\n expires_at: z.union([z.string().datetime({ offset: true }), z.date()]),\n })\n .strict();\n\nfunction billingCreditPostingResult(\n rows: readonly unknown[] | null | undefined,\n context: string,\n): BillingCreditPostingResult {\n const raw = requireRecordRow(rows, context);\n const row = safeParse(\n BillingCreditPostingRowSchema,\n {\n ledger_entry_id: raw.ledger_entry_id,\n balance_after: raw.balance_after,\n replayed: raw.replayed,\n error_code: raw.error_code,\n },\n context,\n { indeterminate: true },\n );\n return {\n ledgerEntryId: row.ledger_entry_id,\n balanceAfter: row.balance_after,\n replayed: row.replayed,\n errorCode: row.error_code,\n };\n}\n\nexport interface PostgresBillingStoreOptions extends Omit<\n PostgresConnectionOptions,\n \"providerEnvironment\"\n> {\n /** PostgreSQL connection string or an application-owned pool. */\n postgres: PostgresPool | string;\n /** Tenant UUID bound to every store transaction. */\n tenantId: string;\n /** Explicit financial namespace; billing stores never guess live vs test. */\n providerEnvironment: ProviderEnvironment;\n /** Injectable `pg.Pool` constructor for custom runtimes and tests. */\n poolConstructor?: PostgresPoolConstructor;\n billingPayloadBackend?: \"postgres\" | \"s3\";\n}\n\nexport class PostgresBillingStore extends BillingStore {\n private readonly postgres: PostgresClient;\n readonly providerEnvironment: ProviderEnvironment;\n\n private _offer: BillingOfferRepository | null = null;\n private _topup: BillingTopupRepository | null = null;\n private _customer: BillingCustomerRepository | null = null;\n private _subscription: BillingSubscriptionRepository | null = null;\n private _event: BillingEventRepository | null = null;\n private _payment: BillingPaymentRepository | null = null;\n private _refund: BillingRefundRepository | null = null;\n private _invoice: BillingInvoiceRepository | null = null;\n private _dispute: BillingDisputeRepository | null = null;\n private _preferences: BillingPreferencesRepository | null = null;\n private _autoRecharge: BillingAutoRechargeRepository | null = null;\n private _subscriptionChange: BillingSubscriptionChangeRepository | null = null;\n constructor(options: PostgresBillingStoreOptions) {\n super();\n if (typeof options !== \"object\" || options === null) {\n throw new TypeError(\"PostgresBillingStore options are required\");\n }\n if (typeof options.postgres !== \"string\" && options.poolConstructor !== undefined) {\n throw new TypeError(\"poolConstructor cannot be used with an existing PostgreSQL pool\");\n }\n const providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);\n this.providerEnvironment = providerEnvironment;\n this.postgres = new PostgresClient(options.postgres, {\n tenantId: options.tenantId,\n providerEnvironment,\n poolConstructor: options.poolConstructor,\n billingPayloadBackend: options.billingPayloadBackend,\n connectionTimeoutMs: options.connectionTimeoutMs,\n statementTimeoutMs: options.statementTimeoutMs,\n idleTransactionTimeoutMs: options.idleTransactionTimeoutMs,\n idleTimeoutMs: options.idleTimeoutMs,\n maxConnections: options.maxConnections,\n applicationName: options.applicationName,\n onPoolError: options.onPoolError,\n closedError: () => new StoreClosedError(\"Billing store has been closed\"),\n });\n }\n\n async close(): Promise<void> {\n await this.postgres.close();\n }\n\n private get queryFn(): QueryFn {\n return this.postgres.query;\n }\n\n private get billingOffer(): BillingOfferRepository {\n if (!this._offer) this._offer = new BillingOfferRepository(this.queryFn);\n return this._offer;\n }\n\n private get billingTopup(): BillingTopupRepository {\n if (!this._topup) this._topup = new BillingTopupRepository(this.queryFn);\n return this._topup;\n }\n\n private get billingCustomer(): BillingCustomerRepository {\n if (!this._customer) this._customer = new BillingCustomerRepository(this.queryFn);\n return this._customer;\n }\n\n private get billingSubscription(): BillingSubscriptionRepository {\n if (!this._subscription) this._subscription = new BillingSubscriptionRepository(this.queryFn);\n return this._subscription;\n }\n\n private get billingEvent(): BillingEventRepository {\n if (!this._event) this._event = new BillingEventRepository(this.queryFn);\n return this._event;\n }\n\n private get billingPayment(): BillingPaymentRepository {\n if (!this._payment) this._payment = new BillingPaymentRepository(this.queryFn);\n return this._payment;\n }\n\n private get billingRefund(): BillingRefundRepository {\n if (!this._refund) this._refund = new BillingRefundRepository(this.queryFn);\n return this._refund;\n }\n\n private get billingInvoice(): BillingInvoiceRepository {\n if (!this._invoice) this._invoice = new BillingInvoiceRepository(this.queryFn);\n return this._invoice;\n }\n\n private get billingDispute(): BillingDisputeRepository {\n if (!this._dispute) this._dispute = new BillingDisputeRepository(this.queryFn);\n return this._dispute;\n }\n\n private get billingPreferences(): BillingPreferencesRepository {\n if (!this._preferences) this._preferences = new BillingPreferencesRepository(this.queryFn);\n return this._preferences;\n }\n\n private get billingAutoRecharge(): BillingAutoRechargeRepository {\n if (!this._autoRecharge) this._autoRecharge = new BillingAutoRechargeRepository(this.queryFn);\n return this._autoRecharge;\n }\n\n private get billingSubscriptionChange(): BillingSubscriptionChangeRepository {\n if (!this._subscriptionChange) {\n this._subscriptionChange = new BillingSubscriptionChangeRepository(this.queryFn);\n }\n return this._subscriptionChange;\n }\n\n async createOrGetCheckoutIntent(input: CheckoutIntentCreate): Promise<CheckoutIntent> {\n const operationKey = requireStableKey(input.operationKey, \"operationKey\");\n if (!/^[0-9a-fA-F]{64}$/.test(input.requestDigest)) {\n throw new TypeError(\"requestDigest must be a 32-byte hex string\");\n }\n const rows = await this.queryFn(\n `SELECT bursar.create_checkout_intent(\n $1::uuid, $2, $3, $4, $5, decode($6, 'hex'), $7::timestamptz\n ) AS id`,\n [\n input.subjectId,\n input.provider,\n operationKey,\n input.checkoutKind,\n input.productKey,\n input.requestDigest,\n input.expiresAt,\n ],\n );\n const id = requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createOrGetCheckoutIntent\",\n );\n const intent = await this.getCheckoutIntent(id, input.subjectId);\n if (!intent) {\n throw new StoreError(\"checkout intent could not be read after creation\", {\n indeterminate: true,\n details: { checkoutIntentId: id },\n });\n }\n return intent;\n }\n\n async updateCheckoutIntent(id: string, update: CheckoutIntentUpdate): Promise<void> {\n const rows = await this.queryFn(\n `SELECT bursar.advance_checkout_intent($1::uuid, $2, $3, $4) AS advanced`,\n [id, update.status ?? null, update.providerSessionId ?? null, update.checkoutUrl ?? null],\n );\n if (\n !requireResultField(rows, \"advanced\", pgBoolean, \"PostgresBillingStore.updateCheckoutIntent\")\n ) {\n throw new StoreError(`checkout intent transition rejected: ${id}`, {\n details: { checkoutIntentId: id },\n });\n }\n }\n\n async getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_checkout_intent($1::uuid, $2::uuid)`,\n [id, subjectId],\n );\n if (rows.length === 0) return null;\n if (rows.length !== 1) {\n throw new StoreError(\"getCheckoutIntent: expected at most one row\", {\n details: { rowCount: rows.length, checkoutIntentId: id },\n });\n }\n const row = rows[0] as Record<string, unknown>;\n return this.rowToCheckoutIntent(\n safeParse(\n CheckoutIntentRowSchema,\n {\n id: row.id,\n subject_id: row.subject_id,\n provider: row.provider,\n checkout_kind: row.checkout_kind,\n product_key: row.product_key,\n request_digest: row.request_digest,\n status: row.status,\n provider_session_id: row.provider_session_id,\n checkout_url: row.checkout_url,\n expires_at: row.expires_at,\n },\n \"PostgresBillingStore.getCheckoutIntent\",\n ),\n );\n }\n\n private rowToCheckoutIntent(row: z.infer<typeof CheckoutIntentRowSchema>): CheckoutIntent {\n return {\n id: row.id,\n subjectId: row.subject_id,\n provider: row.provider,\n checkoutKind: row.checkout_kind,\n productKey: row.product_key,\n requestDigest: Buffer.from(row.request_digest).toString(\"hex\"),\n status: row.status,\n providerSessionId: row.provider_session_id,\n checkoutUrl: row.checkout_url,\n expiresAt: row.expires_at instanceof Date ? row.expires_at.toISOString() : row.expires_at,\n };\n }\n\n private rowToOffer(row: BillingOfferRow | null): BillingOfferResult | null {\n if (!row) return null;\n return {\n offerId: row.id,\n offerKey: row.offerKey,\n planId: row.planId,\n plan: row.plan,\n interval: row.interval,\n intervalCount: row.intervalCount,\n grant:\n row.grantCredits === null\n ? null\n : {\n mode: \"cycle_grant\",\n credits: row.grantCredits,\n bucket: row.grantBucket,\n replacePrior: row.grantReplacePrior,\n },\n };\n }\n\n async resolveBillingOffer(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByPrice(provider, priceId ?? null, productId ?? null);\n return this.rowToOffer(r);\n }\n\n async resolveBillingOfferByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByLookup(provider, lookupKey);\n return this.rowToOffer(r);\n }\n\n async claimBillingEvent(\n provider: string,\n eventId: string,\n eventType: string,\n envelope?: Record<string, unknown>,\n ): Promise<BillingEventClaim> {\n const result = await this.billingEvent.claim(\n provider,\n eventId,\n eventType,\n JSON.stringify(envelope ?? { eventType }),\n );\n if (result.status === \"claimed\") {\n if (result.claim_token === null || result.event_id === null) {\n throw new StoreError(\"Billing event claim returned no claim identifiers\", {\n details: { provider, eventId },\n });\n }\n return {\n status: \"claimed\" as const,\n claimToken: result.claim_token,\n billingEventId: result.event_id,\n };\n }\n if (result.status === \"duplicate\") return { status: \"duplicate\" as const };\n if (result.status === \"busy\") return { status: \"busy\" as const };\n if (result.status === \"invalid_request\") return { status: \"invalid_request\" as const };\n if (result.status === \"idempotency_conflict\" || result.status === \"max_retries_exceeded\") {\n if (result.event_id === null) {\n throw new StoreError(\"Billing event terminal claim returned no event identifier\", {\n details: { provider, eventId, status: result.status },\n });\n }\n return { status: result.status, billingEventId: result.event_id };\n }\n throw new StoreError(\"Billing event claim returned an unsupported status\", {\n details: { provider, eventId, status: result.status },\n });\n }\n\n async completeBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n ): Promise<boolean> {\n return this.billingEvent.complete(provider, eventId, claimToken);\n }\n\n async failBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n error?: string,\n ): Promise<boolean> {\n return this.billingEvent.fail(\n provider,\n eventId,\n claimToken,\n optionalBoundedDiagnosticMessage(error) ?? undefined,\n );\n }\n\n async upsertBillingCustomer(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email?: string | null,\n ): Promise<void> {\n await this.billingCustomer.upsert(provider, providerCustomerId, userId, email ?? null);\n }\n\n async upsertBillingSubscription(state: BillingSubscriptionState): Promise<void> {\n await this.billingSubscription.upsert(state);\n }\n\n async getBillingCustomer(provider: string, providerCustomerId: string): Promise<string | null> {\n return this.billingCustomer.get(provider, providerCustomerId);\n }\n\n async getBillingSubscription(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.get(provider, providerSubscriptionId);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async createBillingSubscriptionChange(\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n const subscription = await this.billingSubscription.get(\n input.provider,\n input.providerSubscriptionId,\n );\n if (!subscription?.id) {\n throw new StoreError(\"subscription change requires a persisted subscription\", {\n retryable: true,\n details: {\n provider: input.provider,\n providerSubscriptionId: input.providerSubscriptionId,\n },\n });\n }\n return this.billingSubscriptionChange.create(subscription.id, input);\n }\n\n async getOpenBillingSubscriptionChange(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.billingSubscriptionChange.getOpen(provider, providerSubscriptionId);\n }\n\n async listExpiredGraceSubscriptions(\n now: string,\n limit = 100,\n ): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.listExpiredGraceSubscriptions(now, limit);\n return rows.map((row) => this.rowToSubscriptionState(row));\n }\n\n async markSubscriptionGraceExpired(\n subscriptionId: string,\n expectedGraceEndsAt: string,\n expiredAt = new Date().toISOString(),\n ): Promise<boolean> {\n return this.billingSubscription.markGraceExpired(\n subscriptionId,\n expectedGraceEndsAt,\n expiredAt,\n );\n }\n\n async updateBillingSubscriptionChange(\n id: string,\n update: BillingSubscriptionChangeUpdate,\n ): Promise<void> {\n await this.billingSubscriptionChange.update(id, update);\n }\n\n async getUserSubscription(\n userId: string,\n statuses?: string[],\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.getUserSubscription(userId, statuses);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async getUserSubscriptions(userId: string): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.getUserSubscriptions(userId);\n return rows.map((r) => this.rowToSubscriptionState(r));\n }\n\n async recordSubscriptionConflict(input: BillingSubscriptionConflictCreate): Promise<void> {\n await this.billingSubscription.recordConflict(input);\n }\n\n async selectSubscriptionEntitlementSource(\n userId: string,\n provider: string,\n providerSubscriptionId?: string | null,\n ): Promise<boolean> {\n return this.billingSubscription.selectEntitlementSource(\n userId,\n provider,\n providerSubscriptionId,\n );\n }\n\n private rowToTopup(r: BillingTopupRow | null): BillingTopupResult | null {\n if (!r) return null;\n const minAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.min_quantity,\n \"PostgresBillingStore.rowToTopup.minAmountMinor\",\n );\n const maxAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.max_quantity,\n \"PostgresBillingStore.rowToTopup.maxAmountMinor\",\n );\n return {\n topupId: r.id,\n topupKey: r.topup_key,\n creditsPerUnit: r.credits_per_unit,\n depositTo: r.bucket_key,\n amountMinor: r.amount_minor,\n currency: r.currency,\n minQuantity: r.min_quantity,\n maxQuantity: r.max_quantity,\n defaultQuantity: r.default_quantity,\n minAmountMinor,\n maxAmountMinor,\n };\n }\n\n async resolveCreditTopup(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByPrice(provider, priceId ?? null, productId ?? null);\n return this.rowToTopup(r);\n }\n\n async resolveCreditTopupByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByLookup(provider, lookupKey);\n return this.rowToTopup(r);\n }\n\n async computeTopupCredits(\n amountMinor: number,\n topupConfig: BillingTopupResult,\n ): Promise<Decimal> {\n if (!Number.isSafeInteger(amountMinor) || amountMinor < 0) {\n throw new TypeError(\"amountMinor must be a non-negative safe integer\");\n }\n const unitAmount = topupConfig.amountMinor;\n if (unitAmount <= 0 || amountMinor % unitAmount !== 0) return new Decimal(0);\n const quantity = amountMinor / unitAmount;\n if (quantity < topupConfig.minQuantity || quantity > topupConfig.maxQuantity) {\n return new Decimal(0);\n }\n return topupConfig.creditsPerUnit.mul(quantity);\n }\n\n async upsertBillingPayment(options: BillingPaymentUpsert): Promise<string> {\n return this.billingPayment.upsert(\n options.provider,\n options.providerPaymentId,\n options.providerInvoiceId ?? null,\n options.userId,\n options.amountMinor,\n options.taxMinor,\n options.currency,\n options.purpose,\n options.metadata ? JSON.stringify(options.metadata) : null,\n options.status,\n options.providerUpdatedAt,\n );\n }\n\n async createBillingCreditGrant(input: BillingCreditGrantCreate): Promise<string> {\n const rows = await this.queryFn(\n \"SELECT bursar.create_billing_credit_grant($1::uuid, $2::uuid, $3::uuid, $4, $5, $6::uuid) AS id\",\n [\n input.paymentId ?? null,\n input.subscriptionId ?? null,\n input.topupId ?? null,\n input.configuredCredits.toString(),\n input.quantity,\n input.billingEventId ?? null,\n ],\n );\n return requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createBillingCreditGrant\",\n );\n }\n\n async grantBillingCredit(\n grantId: string,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.grant_billing_credit($1::uuid, $2)\", [\n grantId,\n idempotencyKey,\n ]);\n return billingCreditPostingResult(rows, \"PostgresBillingStore.grantBillingCredit\");\n }\n\n async getBillingCreditGrantByPayment(paymentId: string): Promise<string | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_billing_credit_grant_by_payment($1::uuid)`,\n [paymentId],\n );\n const row = optionalRecordRow(rows, \"PostgresBillingStore.getBillingCreditGrantByPayment\");\n return row === null\n ? null\n : safeParse(postgresUuid, row.id, \"PostgresBillingStore.getBillingCreditGrantByPayment.id\");\n }\n\n async postBillingRefund(\n refundId: string,\n grantId: string,\n amountMinor: number,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\n \"SELECT * FROM bursar.post_billing_refund($1::uuid, $2::uuid, $3, $4)\",\n [refundId, grantId, amountMinor, idempotencyKey],\n );\n return billingCreditPostingResult(rows, \"PostgresBillingStore.postBillingRefund\");\n }\n\n async upsertBillingRefund(options: BillingRefundUpsert): Promise<string> {\n return this.billingRefund.upsert(\n options.provider,\n options.providerRefundId,\n options.providerPaymentId,\n options.userId,\n options.amountMinor,\n options.currency,\n options.reason ?? null,\n options.metadata ? JSON.stringify(options.metadata) : null,\n options.status,\n options.providerUpdatedAt,\n );\n }\n\n async upsertBillingInvoice(options: BillingInvoiceUpsert): Promise<void> {\n const subscription = options.providerSubscriptionId\n ? await this.billingSubscription.get(options.provider, options.providerSubscriptionId)\n : null;\n if (options.providerSubscriptionId && !subscription) {\n throw new StoreError(\"invoice subscription is not available\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerInvoiceId: options.providerInvoiceId,\n providerSubscriptionId: options.providerSubscriptionId ?? null,\n },\n });\n }\n await this.billingInvoice.upsert(\n options.userId,\n options.provider,\n options.providerInvoiceId,\n subscription?.id ? String(subscription.id) : null,\n options.status,\n options.amountDueMinor,\n options.amountPaidMinor,\n options.currency,\n options.periodStart ?? null,\n options.periodEnd ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async listBillingInvoices(userId: string) {\n return this.billingInvoice.listForUser(userId);\n }\n\n async upsertBillingDispute(options: BillingDisputeUpsert): Promise<void> {\n const payment = await this.billingPayment.getForRefund(\n options.provider,\n options.providerPaymentId,\n );\n if (!payment?.id) {\n throw new StoreError(\"dispute payment is required\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerDisputeId: options.providerDisputeId,\n providerPaymentId: options.providerPaymentId ?? null,\n },\n });\n }\n await this.billingDispute.upsert(\n options.provider,\n options.providerDisputeId,\n String(payment.id),\n options.status,\n options.reason ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async getBillingPayment(\n provider: string,\n providerPaymentId: string,\n ): Promise<BillingPaymentRecord | null> {\n const row = await this.billingPayment.getForRefund(provider, providerPaymentId);\n if (!row) return null;\n return {\n id: row.id,\n provider: row.provider,\n providerPaymentId: row.provider_payment_id,\n providerInvoiceId: row.provider_invoice_id,\n userId: row.subject_id,\n amountMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.amount_minor,\n \"PostgresBillingStore.getBillingPayment.amountMinor\",\n ),\n taxMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.tax_minor,\n \"PostgresBillingStore.getBillingPayment.taxMinor\",\n ),\n currency: row.currency,\n purpose: row.purpose,\n status: row.status,\n providerUpdatedAt:\n row.provider_updated_at instanceof Date\n ? row.provider_updated_at.toISOString()\n : row.provider_updated_at,\n metadata: row.metadata,\n };\n }\n\n private rowToSubscriptionState(r: SubscriptionRow): BillingSubscriptionState {\n return {\n subscriptionId: r.id,\n userId: r.user_id,\n provider: r.provider,\n providerSubscriptionId: r.provider_subscription_id,\n providerCustomerId: r.provider_customer_id,\n offerId: r.offer_id,\n offerKey: r.offer_key,\n planId: r.plan_id,\n plan: r.plan,\n status: r.status,\n currentPeriodStart: r.current_period_start,\n currentPeriodEnd: r.current_period_end,\n trialEnd: r.trial_end,\n cancelAt: r.cancel_at,\n endedAt: r.ended_at,\n graceEndsAt: r.grace_ends_at,\n graceExpiredAt: r.grace_expired_at,\n providerUpdatedAt: r.provider_updated_at,\n cancelAtPeriodEnd: r.cancel_at_period_end,\n interval: r.interval,\n intervalCount: r.interval_count,\n metadata: r.metadata,\n };\n }\n\n async getActiveCatalogDocument(): Promise<Record<string, unknown> | null> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.active_catalog_revision()\", []);\n if (rows.length === 0) return null;\n if (rows.length !== 1 || typeof rows[0] !== \"object\" || rows[0] === null) {\n throw new StoreError(\"active catalog revision returned a malformed row\", {\n details: { rowCount: rows.length },\n });\n }\n return safeParse(\n z.record(z.string(), z.unknown()),\n (rows[0] as Record<string, unknown>).source_document,\n \"PostgresBillingStore.getActiveCatalogDocument\",\n );\n }\n\n async pseudonymizeFinancialSubject(userId: string): Promise<boolean> {\n const rows = await this.queryFn(\n `SELECT bursar.pseudonymize_financial_subject($1::uuid) AS pseudonymized`,\n [userId],\n );\n return requireResultField(\n rows,\n \"pseudonymized\",\n pgBoolean,\n \"PostgresBillingStore.pseudonymizeFinancialSubject\",\n );\n }\n\n async getBillingPreferences(userId: string): Promise<BillingPreferences | null> {\n return this.billingPreferences.get(userId);\n }\n\n async upsertBillingPreferences(prefs: BillingPreferences): Promise<void> {\n await this.billingPreferences.upsert(prefs);\n }\n\n async getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n return this.billingAutoRecharge.getProfile(userId);\n }\n\n async upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void> {\n return this.billingAutoRecharge.upsertProfile(profile, options);\n }\n\n async claimAutoRechargeAttempt(\n input: AutoRechargeAttemptClaim,\n ): Promise<BillingAutoRechargeAttempt | null> {\n return this.billingAutoRecharge.claimAttempt(input);\n }\n\n async updateAutoRechargeAttempt(input: AutoRechargeAttemptUpdate): Promise<void> {\n return this.billingAutoRecharge.updateAttempt(input);\n }\n\n async updateAutoRechargeAttemptByProviderPayment(\n input: AutoRechargeProviderPaymentUpdate,\n ): Promise<void> {\n return this.billingAutoRecharge.updateAttemptByProviderPayment(input);\n }\n\n async countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number> {\n return this.billingAutoRecharge.countAttempts(userId, since);\n }\n\n async getBillingCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null> {\n const result = await this.billingCustomer.getByUserId(userId, provider ?? null);\n if (!result) return null;\n return {\n provider: result.provider,\n providerCustomerId: result.providerCustomerId,\n };\n }\n}\n"]}
@@ -1,11 +1,8 @@
1
- import type Decimal from "decimal.js";
2
1
  import type { Logger } from "../shared/logger.js";
3
- import type { AddCreditsResult, RevokeCreditsResult, SetUserPlanResult, UnsetUserPlanResult } from "../credits/types/index.js";
2
+ import type { SetUserPlanResult, UnsetUserPlanResult } from "../credits/types/index.js";
4
3
  import type { BillingEventHandler, BillingEventType } from "./types/index.js";
5
- export type ResolveUser = (provider: string, providerCustomerId: string | null, email: string | null) => string | null;
6
4
  export interface BillingServiceOptions {
7
5
  provisioning?: BillingProvisioningPort | null;
8
- resolveUser?: ResolveUser | null;
9
6
  eventHandlers?: Partial<Record<BillingEventType, BillingEventHandler>>;
10
7
  autoSelectEntitlementSource?: boolean;
11
8
  /** Access grace after a failed subscription payment. Defaults to seven days. */
@@ -19,20 +16,10 @@ export interface BillingServiceOptions {
19
16
  * provisioning. Billing does not depend on the full credit service.
20
17
  */
21
18
  export interface BillingProvisioningPort {
22
- getUserPlan?(userId: string): Promise<{
19
+ getUserPlan(userId: string): Promise<{
23
20
  planAssignedAt?: Date | string | null;
24
21
  } | null>;
25
22
  setUserPlan(userId: string, planKey: string, planAssignedAt?: Date | null): Promise<SetUserPlanResult>;
26
23
  unsetUserPlan(userId: string): Promise<UnsetUserPlanResult>;
27
- addCredits(userId: string, amount: Decimal | number, options?: {
28
- type?: string;
29
- bucket?: string | null;
30
- idempotencyKey?: string | null;
31
- }): Promise<AddCreditsResult>;
32
- deductCredits(userId: string, amount: Decimal | number, options?: {
33
- entryType?: string;
34
- bucket?: string | null;
35
- }): Promise<AddCreditsResult>;
36
- revokeCreditsByEntryType(userId: string, entryType: string): Promise<RevokeCreditsResult>;
37
24
  }
38
25
  //# sourceMappingURL=service-types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"service-types.d.ts","sourceRoot":"","sources":["../../src/billing/service-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,YAAY,CAAC;AAEtC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EACV,gBAAgB,EAChB,mBAAmB,EACnB,iBAAiB,EACjB,mBAAmB,EACpB,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAE9E,MAAM,MAAM,WAAW,GAAG,CACxB,QAAQ,EAAE,MAAM,EAChB,kBAAkB,EAAE,MAAM,GAAG,IAAI,EACjC,KAAK,EAAE,MAAM,GAAG,IAAI,KACjB,MAAM,GAAG,IAAI,CAAC;AAEnB,MAAM,WAAW,qBAAqB;IACpC,YAAY,CAAC,EAAE,uBAAuB,GAAG,IAAI,CAAC;IAC9C,WAAW,CAAC,EAAE,WAAW,GAAG,IAAI,CAAC;IACjC,aAAa,CAAC,EAAE,OAAO,CAAC,MAAM,CAA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AAmB,CAAC,CAAC;CAC3F"}
1
+ {"version":3,"file":"service-types.d.ts","sourceRoot":"","sources":["../../src/billing/service-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AACxF,OAAO,KAAK,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAE9E,MAAM,WAAW,qBAAqB;IACpC,YAAY,CAAC,EAAE,uBAAuB,GAAG,IAAI,CAAC;IAC9C,aAAa,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,gBAAgB,EAAE,mBAAmB,CAAC,CAAC,CAAC;IACvE,2BAA2B,CAAC,EAAE,OAAO,CAAC;IACtC,gFAAgF;IAChF,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,qEAAqE;IACrE,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB;AAED;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,cAAc,CAAC,EAAE,IAAI,GAAG,MAAM,GAAG,IAAI,CAAA;KAAE,GAAG,IAAI,CAAC,CAAC;IACvF,WAAW,CACT,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,EACf,cAAc,CAAC,EAAE,IAAI,GAAG,IAAI,GAC3B,OAAO,CAAC,iBAAiB,CAAC,CAAC;IAC9B,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC;CAC7D"}
@@ -1 +1 @@
1
- {"version":3,"file":"service-types.js","sourceRoot":"","sources":["../../src/billing/service-types.ts"],"names":[],"mappings":"","sourcesContent":["import type Decimal from \"decimal.js\";\n\nimport type { Logger } from \"../shared/logger.js\";\nimport type {\n AddCreditsResult,\n RevokeCreditsResult,\n SetUserPlanResult,\n UnsetUserPlanResult,\n} from \"../credits/types/index.js\";\nimport type { BillingEventHandler, BillingEventType } from \"./types/index.js\";\n\nexport type ResolveUser = (\n provider: string,\n providerCustomerId: string | null,\n email: string | null,\n) => string | null;\n\nexport interface BillingServiceOptions {\n provisioning?: BillingProvisioningPort | null;\n resolveUser?: ResolveUser | null;\n eventHandlers?: Partial<Record<BillingEventType, BillingEventHandler>>;\n autoSelectEntitlementSource?: boolean;\n /** Access grace after a failed subscription payment. Defaults to seven days. */\n pastDueGracePeriodMs?: number;\n /** Plan assigned when a paid subscription reaches terminal state. */\n terminalPlanKey?: string | null;\n logger?: Logger | null;\n}\n\n/**\n * The narrow credit capability billing may request during subscription\n * provisioning. Billing does not depend on the full credit service.\n */\nexport interface BillingProvisioningPort {\n getUserPlan?(userId: string): Promise<{ planAssignedAt?: Date | string | null } | null>;\n setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt?: Date | null,\n ): Promise<SetUserPlanResult>;\n unsetUserPlan(userId: string): Promise<UnsetUserPlanResult>;\n addCredits(\n userId: string,\n amount: Decimal | number,\n options?: {\n type?: string;\n bucket?: string | null;\n idempotencyKey?: string | null;\n },\n ): Promise<AddCreditsResult>;\n deductCredits(\n userId: string,\n amount: Decimal | number,\n options?: { entryType?: string; bucket?: string | null },\n ): Promise<AddCreditsResult>;\n revokeCreditsByEntryType(userId: string, entryType: string): Promise<RevokeCreditsResult>;\n}\n"]}
1
+ {"version":3,"file":"service-types.js","sourceRoot":"","sources":["../../src/billing/service-types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Logger } from \"../shared/logger.js\";\nimport type { SetUserPlanResult, UnsetUserPlanResult } from \"../credits/types/index.js\";\nimport type { BillingEventHandler, BillingEventType } from \"./types/index.js\";\n\nexport interface BillingServiceOptions {\n provisioning?: BillingProvisioningPort | null;\n eventHandlers?: Partial<Record<BillingEventType, BillingEventHandler>>;\n autoSelectEntitlementSource?: boolean;\n /** Access grace after a failed subscription payment. Defaults to seven days. */\n pastDueGracePeriodMs?: number;\n /** Plan assigned when a paid subscription reaches terminal state. */\n terminalPlanKey?: string | null;\n logger?: Logger | null;\n}\n\n/**\n * The narrow credit capability billing may request during subscription\n * provisioning. Billing does not depend on the full credit service.\n */\nexport interface BillingProvisioningPort {\n getUserPlan(userId: string): Promise<{ planAssignedAt?: Date | string | null } | null>;\n setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt?: Date | null,\n ): Promise<SetUserPlanResult>;\n unsetUserPlan(userId: string): Promise<UnsetUserPlanResult>;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type Decimal from "decimal.js";
1
+ import type { Decimal } from "decimal.js";
2
2
  export declare const AUTO_RECHARGE_STATES: readonly ["disabled", "active", "paused"];
3
3
  export type BillingAutoRechargeState = (typeof AUTO_RECHARGE_STATES)[number];
4
4
  export type BillingAutoRechargeAttemptState = "claimed" | "submitted" | "processing" | "unknown" | "succeeded" | "failed" | "action_required";
@@ -1 +1 @@
1
- {"version":3,"file":"auto-recharge.d.ts","sourceRoot":"","sources":["../../../src/billing/types/auto-recharge.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,YAAY,CAAC;AAEtC,eAAO,MAAM,oBAAoB,2CAA4C,CAAC;AAC9E,MAAM,MAAM,wBAAwB,GAAG,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,CAAC;AAE7E,MAAM,MAAM,+BAA+B,GACvC,SAAS,GACT,WAAW,GACX,YAAY,GACZ,SAAS,GACT,WAAW,GACX,QAAQ,GACR,iBAAiB,CAAC;AAEtB,MAAM,WAAW,0BAA0B;IACzC,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,EAAE,wBAAwB,CAAC;IAChC,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,OAAO,EAA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