@zonastery/bursar 2.0.3 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (341) hide show
  1. package/dist/billing/auto-recharge-port.d.ts +3 -2
  2. package/dist/billing/auto-recharge-port.d.ts.map +1 -1
  3. package/dist/billing/auto-recharge-port.js.map +1 -1
  4. package/dist/billing/auto-recharge-service.js +3 -3
  5. package/dist/billing/auto-recharge-service.js.map +1 -1
  6. package/dist/billing/billing-service.d.ts +3 -2
  7. package/dist/billing/billing-service.d.ts.map +1 -1
  8. package/dist/billing/billing-service.js +2 -10
  9. package/dist/billing/billing-service.js.map +1 -1
  10. package/dist/billing/billing-store.d.ts +6 -6
  11. package/dist/billing/billing-store.d.ts.map +1 -1
  12. package/dist/billing/billing-store.js.map +1 -1
  13. package/dist/billing/contracts.d.ts +8 -7
  14. package/dist/billing/contracts.d.ts.map +1 -1
  15. package/dist/billing/contracts.js.map +1 -1
  16. package/dist/billing/event-handlers.d.ts +5 -9
  17. package/dist/billing/event-handlers.d.ts.map +1 -1
  18. package/dist/billing/event-handlers.js +191 -285
  19. package/dist/billing/event-handlers.js.map +1 -1
  20. package/dist/billing/event-processor.d.ts +1 -1
  21. package/dist/billing/event-processor.d.ts.map +1 -1
  22. package/dist/billing/event-processor.js +32 -23
  23. package/dist/billing/event-processor.js.map +1 -1
  24. package/dist/billing/financial-event-handlers.d.ts +3 -9
  25. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  26. package/dist/billing/financial-event-handlers.js +10 -12
  27. package/dist/billing/financial-event-handlers.js.map +1 -1
  28. package/dist/billing/index.d.ts +1 -1
  29. package/dist/billing/index.d.ts.map +1 -1
  30. package/dist/billing/index.js.map +1 -1
  31. package/dist/billing/management.d.ts +3 -2
  32. package/dist/billing/management.d.ts.map +1 -1
  33. package/dist/billing/management.js.map +1 -1
  34. package/dist/billing/postgres/repositories/auto-recharge.d.ts +2 -1
  35. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  36. package/dist/billing/postgres/repositories/auto-recharge.js +58 -40
  37. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  38. package/dist/billing/postgres/repositories/dispute.d.ts +2 -1
  39. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
  40. package/dist/billing/postgres/repositories/dispute.js.map +1 -1
  41. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  42. package/dist/billing/postgres/repositories/event.js.map +1 -1
  43. package/dist/billing/postgres/repositories/invoice.d.ts +2 -1
  44. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  45. package/dist/billing/postgres/repositories/invoice.js +8 -12
  46. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  47. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  48. package/dist/billing/postgres/repositories/offer.js +5 -0
  49. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  50. package/dist/billing/postgres/repositories/payment.d.ts +1 -1
  51. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  52. package/dist/billing/postgres/repositories/payment.js +1 -1
  53. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  54. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -1
  55. package/dist/billing/postgres/repositories/subscription-change.js +1 -9
  56. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
  57. package/dist/billing/postgres/repositories/subscription.d.ts +6 -6
  58. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  59. package/dist/billing/postgres/repositories/subscription.js +29 -30
  60. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  61. package/dist/billing/postgres/store.d.ts +6 -5
  62. package/dist/billing/postgres/store.d.ts.map +1 -1
  63. package/dist/billing/postgres/store.js +15 -13
  64. package/dist/billing/postgres/store.js.map +1 -1
  65. package/dist/billing/types/auto-recharge.d.ts +2 -1
  66. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  67. package/dist/billing/types/auto-recharge.js.map +1 -1
  68. package/dist/billing/types/documents.d.ts +2 -1
  69. package/dist/billing/types/documents.d.ts.map +1 -1
  70. package/dist/billing/types/documents.js.map +1 -1
  71. package/dist/billing/types/events.d.ts +3 -2
  72. package/dist/billing/types/events.d.ts.map +1 -1
  73. package/dist/billing/types/events.js +73 -39
  74. package/dist/billing/types/events.js.map +1 -1
  75. package/dist/billing/types/subscriptions.d.ts +4 -1
  76. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  77. package/dist/billing/types/subscriptions.js.map +1 -1
  78. package/dist/breakdown.d.ts +3 -2
  79. package/dist/breakdown.d.ts.map +1 -1
  80. package/dist/breakdown.js.map +1 -1
  81. package/dist/bursar.d.ts.map +1 -1
  82. package/dist/bursar.js +4 -3
  83. package/dist/bursar.js.map +1 -1
  84. package/dist/catalog.d.ts.map +1 -1
  85. package/dist/catalog.js +45 -42
  86. package/dist/catalog.js.map +1 -1
  87. package/dist/commerce/provider-registry.d.ts.map +1 -1
  88. package/dist/commerce/provider-registry.js +11 -6
  89. package/dist/commerce/provider-registry.js.map +1 -1
  90. package/dist/commerce/service.d.ts.map +1 -1
  91. package/dist/commerce/service.js +16 -22
  92. package/dist/commerce/service.js.map +1 -1
  93. package/dist/commerce/types.d.ts.map +1 -1
  94. package/dist/commerce/types.js.map +1 -1
  95. package/dist/config/parse-access.d.ts +5 -2
  96. package/dist/config/parse-access.d.ts.map +1 -1
  97. package/dist/config/parse-access.js +60 -41
  98. package/dist/config/parse-access.js.map +1 -1
  99. package/dist/config/parse-commerce.d.ts +2 -1
  100. package/dist/config/parse-commerce.d.ts.map +1 -1
  101. package/dist/config/parse-commerce.js +49 -29
  102. package/dist/config/parse-commerce.js.map +1 -1
  103. package/dist/config/parse-credits.d.ts +2 -1
  104. package/dist/config/parse-credits.d.ts.map +1 -1
  105. package/dist/config/parse-credits.js +39 -23
  106. package/dist/config/parse-credits.js.map +1 -1
  107. package/dist/config/parse-plans.d.ts +7 -2
  108. package/dist/config/parse-plans.d.ts.map +1 -1
  109. package/dist/config/parse-plans.js +49 -22
  110. package/dist/config/parse-plans.js.map +1 -1
  111. package/dist/config/parse-pricing.d.ts +2 -1
  112. package/dist/config/parse-pricing.d.ts.map +1 -1
  113. package/dist/config/parse-pricing.js +41 -31
  114. package/dist/config/parse-pricing.js.map +1 -1
  115. package/dist/config/parse-utils.d.ts +15 -11
  116. package/dist/config/parse-utils.d.ts.map +1 -1
  117. package/dist/config/parse-utils.js +90 -27
  118. package/dist/config/parse-utils.js.map +1 -1
  119. package/dist/config/types.d.ts.map +1 -1
  120. package/dist/config/types.js.map +1 -1
  121. package/dist/config.d.ts +6 -5
  122. package/dist/config.d.ts.map +1 -1
  123. package/dist/config.js +65 -35
  124. package/dist/config.js.map +1 -1
  125. package/dist/credits/amount.d.ts +1 -1
  126. package/dist/credits/amount.d.ts.map +1 -1
  127. package/dist/credits/amount.js +5 -4
  128. package/dist/credits/amount.js.map +1 -1
  129. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  130. package/dist/credits/catalog-runtime.js +2 -3
  131. package/dist/credits/catalog-runtime.js.map +1 -1
  132. package/dist/credits/events.d.ts +12 -1
  133. package/dist/credits/events.d.ts.map +1 -1
  134. package/dist/credits/events.js +35 -21
  135. package/dist/credits/events.js.map +1 -1
  136. package/dist/credits/lease-workflow.d.ts +2 -1
  137. package/dist/credits/lease-workflow.d.ts.map +1 -1
  138. package/dist/credits/lease-workflow.js +3 -2
  139. package/dist/credits/lease-workflow.js.map +1 -1
  140. package/dist/credits/low-balance-monitor.d.ts +2 -1
  141. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  142. package/dist/credits/low-balance-monitor.js.map +1 -1
  143. package/dist/credits/postgres/repositories/analytics.d.ts +2 -2
  144. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  145. package/dist/credits/postgres/repositories/analytics.js +14 -6
  146. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  147. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  148. package/dist/credits/postgres/repositories/balance.js +6 -6
  149. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  150. package/dist/credits/postgres/repositories/catalog.d.ts +4 -3
  151. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
  152. package/dist/credits/postgres/repositories/catalog.js +4 -3
  153. package/dist/credits/postgres/repositories/catalog.js.map +1 -1
  154. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  155. package/dist/credits/postgres/repositories/deduction.js +2 -2
  156. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  157. package/dist/credits/postgres/repositories/plan.d.ts +1 -1
  158. package/dist/credits/postgres/store.d.ts +3 -2
  159. package/dist/credits/postgres/store.d.ts.map +1 -1
  160. package/dist/credits/postgres/store.js +17 -10
  161. package/dist/credits/postgres/store.js.map +1 -1
  162. package/dist/credits/postgres/value-mappers.d.ts +4 -3
  163. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  164. package/dist/credits/postgres/value-mappers.js +10 -11
  165. package/dist/credits/postgres/value-mappers.js.map +1 -1
  166. package/dist/credits/service.d.ts.map +1 -1
  167. package/dist/credits/service.js +10 -5
  168. package/dist/credits/service.js.map +1 -1
  169. package/dist/credits/store.d.ts +5 -4
  170. package/dist/credits/store.d.ts.map +1 -1
  171. package/dist/credits/store.js.map +1 -1
  172. package/dist/credits/types/account.d.ts +5 -4
  173. package/dist/credits/types/account.d.ts.map +1 -1
  174. package/dist/credits/types/account.js.map +1 -1
  175. package/dist/credits/types/catalog.d.ts +2 -1
  176. package/dist/credits/types/catalog.d.ts.map +1 -1
  177. package/dist/credits/types/catalog.js.map +1 -1
  178. package/dist/credits/types/grants.d.ts.map +1 -1
  179. package/dist/credits/types/grants.js.map +1 -1
  180. package/dist/credits/types/ledger.d.ts +3 -2
  181. package/dist/credits/types/ledger.d.ts.map +1 -1
  182. package/dist/credits/types/ledger.js.map +1 -1
  183. package/dist/engine.d.ts +2 -2
  184. package/dist/engine.d.ts.map +1 -1
  185. package/dist/engine.js +39 -10
  186. package/dist/engine.js.map +1 -1
  187. package/dist/errors.d.ts +7 -4
  188. package/dist/errors.d.ts.map +1 -1
  189. package/dist/errors.js +18 -11
  190. package/dist/errors.js.map +1 -1
  191. package/dist/expr/ast.d.ts.map +1 -1
  192. package/dist/expr/ast.js.map +1 -1
  193. package/dist/expr/parser.d.ts.map +1 -1
  194. package/dist/expr/parser.js.map +1 -1
  195. package/dist/expr/tokenizer.d.ts.map +1 -1
  196. package/dist/expr/tokenizer.js +34 -12
  197. package/dist/expr/tokenizer.js.map +1 -1
  198. package/dist/expr.d.ts.map +1 -1
  199. package/dist/expr.js +12 -6
  200. package/dist/expr.js.map +1 -1
  201. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  202. package/dist/generated/pricing-config.types.js.map +1 -1
  203. package/dist/integrations/better-auth.d.ts +4 -1
  204. package/dist/integrations/better-auth.d.ts.map +1 -1
  205. package/dist/integrations/better-auth.js +7 -4
  206. package/dist/integrations/better-auth.js.map +1 -1
  207. package/dist/load-config-file.d.ts +2 -1
  208. package/dist/load-config-file.d.ts.map +1 -1
  209. package/dist/load-config-file.js +19 -13
  210. package/dist/load-config-file.js.map +1 -1
  211. package/dist/metrics.d.ts +2 -1
  212. package/dist/metrics.d.ts.map +1 -1
  213. package/dist/metrics.js.map +1 -1
  214. package/dist/node.d.ts +1 -1
  215. package/dist/node.d.ts.map +1 -1
  216. package/dist/node.js.map +1 -1
  217. package/dist/providers/_shared.d.ts +8 -5
  218. package/dist/providers/_shared.d.ts.map +1 -1
  219. package/dist/providers/_shared.js +15 -11
  220. package/dist/providers/_shared.js.map +1 -1
  221. package/dist/providers/dodo/better-auth-core.d.ts +32 -0
  222. package/dist/providers/dodo/better-auth-core.d.ts.map +1 -0
  223. package/dist/providers/dodo/better-auth-core.js +14 -0
  224. package/dist/providers/dodo/better-auth-core.js.map +1 -0
  225. package/dist/providers/dodo/better-auth.d.ts +5 -7
  226. package/dist/providers/dodo/better-auth.d.ts.map +1 -1
  227. package/dist/providers/dodo/better-auth.js +16 -13
  228. package/dist/providers/dodo/better-auth.js.map +1 -1
  229. package/dist/providers/dodo/client-contract.d.ts +11 -10
  230. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  231. package/dist/providers/dodo/client-contract.js.map +1 -1
  232. package/dist/providers/dodo/event-mapper.d.ts +7 -4
  233. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  234. package/dist/providers/dodo/event-mapper.js +121 -113
  235. package/dist/providers/dodo/event-mapper.js.map +1 -1
  236. package/dist/providers/dodo/nextjs-core.d.ts +22 -0
  237. package/dist/providers/dodo/nextjs-core.d.ts.map +1 -0
  238. package/dist/providers/dodo/nextjs-core.js +14 -0
  239. package/dist/providers/dodo/nextjs-core.js.map +1 -0
  240. package/dist/providers/dodo/nextjs.d.ts +5 -7
  241. package/dist/providers/dodo/nextjs.d.ts.map +1 -1
  242. package/dist/providers/dodo/nextjs.js +11 -10
  243. package/dist/providers/dodo/nextjs.js.map +1 -1
  244. package/dist/providers/dodo/provider.d.ts +3 -3
  245. package/dist/providers/dodo/provider.d.ts.map +1 -1
  246. package/dist/providers/dodo/provider.js +42 -35
  247. package/dist/providers/dodo/provider.js.map +1 -1
  248. package/dist/providers/dodo/react-native-core.d.ts +56 -0
  249. package/dist/providers/dodo/react-native-core.d.ts.map +1 -0
  250. package/dist/providers/dodo/react-native-core.js +56 -0
  251. package/dist/providers/dodo/react-native-core.js.map +1 -0
  252. package/dist/providers/dodo/react-native.d.ts +6 -50
  253. package/dist/providers/dodo/react-native.d.ts.map +1 -1
  254. package/dist/providers/dodo/react-native.js +5 -49
  255. package/dist/providers/dodo/react-native.js.map +1 -1
  256. package/dist/providers/dodo/webhook-bridge.d.ts +4 -2
  257. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
  258. package/dist/providers/dodo/webhook-bridge.js.map +1 -1
  259. package/dist/providers/environment.d.ts +1 -1
  260. package/dist/providers/environment.d.ts.map +1 -1
  261. package/dist/providers/environment.js +4 -2
  262. package/dist/providers/environment.js.map +1 -1
  263. package/dist/providers/mock/provider.d.ts.map +1 -1
  264. package/dist/providers/mock/provider.js +5 -10
  265. package/dist/providers/mock/provider.js.map +1 -1
  266. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  267. package/dist/providers/stripe/event-mapper.js +33 -9
  268. package/dist/providers/stripe/event-mapper.js.map +1 -1
  269. package/dist/providers/stripe/provider.d.ts.map +1 -1
  270. package/dist/providers/stripe/provider.js +100 -60
  271. package/dist/providers/stripe/provider.js.map +1 -1
  272. package/dist/providers/types.d.ts.map +1 -1
  273. package/dist/providers/types.js.map +1 -1
  274. package/dist/retry.d.ts.map +1 -1
  275. package/dist/retry.js +16 -9
  276. package/dist/retry.js.map +1 -1
  277. package/dist/shared/diagnostics.d.ts +5 -5
  278. package/dist/shared/diagnostics.d.ts.map +1 -1
  279. package/dist/shared/diagnostics.js +32 -22
  280. package/dist/shared/diagnostics.js.map +1 -1
  281. package/dist/shared/idempotency.d.ts +4 -3
  282. package/dist/shared/idempotency.d.ts.map +1 -1
  283. package/dist/shared/idempotency.js +21 -10
  284. package/dist/shared/idempotency.js.map +1 -1
  285. package/dist/shared/json.d.ts +28 -0
  286. package/dist/shared/json.d.ts.map +1 -0
  287. package/dist/shared/json.js +41 -0
  288. package/dist/shared/json.js.map +1 -0
  289. package/dist/shared/logger.d.ts +10 -4
  290. package/dist/shared/logger.d.ts.map +1 -1
  291. package/dist/shared/logger.js.map +1 -1
  292. package/dist/shared/postgres-client.d.ts +8 -6
  293. package/dist/shared/postgres-client.d.ts.map +1 -1
  294. package/dist/shared/postgres-client.js +69 -47
  295. package/dist/shared/postgres-client.js.map +1 -1
  296. package/dist/shared/postgres-errors.d.ts +1 -1
  297. package/dist/shared/postgres-errors.d.ts.map +1 -1
  298. package/dist/shared/postgres-errors.js +32 -31
  299. package/dist/shared/postgres-errors.js.map +1 -1
  300. package/dist/shared/postgres-types.d.ts +3 -2
  301. package/dist/shared/postgres-types.d.ts.map +1 -1
  302. package/dist/shared/postgres-types.js.map +1 -1
  303. package/dist/shared/postgres-validation.d.ts +7 -6
  304. package/dist/shared/postgres-validation.d.ts.map +1 -1
  305. package/dist/shared/postgres-validation.js +17 -10
  306. package/dist/shared/postgres-validation.js.map +1 -1
  307. package/dist/storage/adapters/clickhouse.d.ts +11 -4
  308. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  309. package/dist/storage/adapters/clickhouse.js +8 -6
  310. package/dist/storage/adapters/clickhouse.js.map +1 -1
  311. package/dist/storage/adapters/s3.d.ts +28 -5
  312. package/dist/storage/adapters/s3.d.ts.map +1 -1
  313. package/dist/storage/adapters/s3.js +48 -33
  314. package/dist/storage/adapters/s3.js.map +1 -1
  315. package/dist/storage/diagnostics.d.ts +1 -1
  316. package/dist/storage/diagnostics.js +13 -12
  317. package/dist/storage/diagnostics.js.map +1 -1
  318. package/dist/storage/maintenance.d.ts.map +1 -1
  319. package/dist/storage/maintenance.js +31 -25
  320. package/dist/storage/maintenance.js.map +1 -1
  321. package/dist/storage/outbox-worker.d.ts +1 -1
  322. package/dist/storage/outbox-worker.js +18 -18
  323. package/dist/storage/outbox-worker.js.map +1 -1
  324. package/dist/storage/ports.d.ts +10 -7
  325. package/dist/storage/ports.d.ts.map +1 -1
  326. package/dist/storage/ports.js.map +1 -1
  327. package/dist/storage/postgres-repository.d.ts +3 -1
  328. package/dist/storage/postgres-repository.d.ts.map +1 -1
  329. package/dist/storage/postgres-repository.js +10 -4
  330. package/dist/storage/postgres-repository.js.map +1 -1
  331. package/dist/storage/runtime.d.ts +1 -1
  332. package/dist/storage/runtime.d.ts.map +1 -1
  333. package/dist/storage/runtime.js +165 -182
  334. package/dist/storage/runtime.js.map +1 -1
  335. package/dist/telemetry/index.d.ts +10 -6
  336. package/dist/telemetry/index.d.ts.map +1 -1
  337. package/dist/telemetry/index.js +26 -23
  338. package/dist/telemetry/index.js.map +1 -1
  339. package/dist/telemetry/opentelemetry.js +3 -3
  340. package/dist/telemetry/opentelemetry.js.map +1 -1
  341. package/package.json +14 -14
@@ -1,4 +1,5 @@
1
1
  import { LRUCache } from "lru-cache";
2
+ import { z } from "zod";
2
3
  import { normalizeLogger } from "../shared/logger.js";
3
4
  import { BillingEventType } from "./types/index.js";
4
5
  import { BillingFinancialEventHandlers } from "./financial-event-handlers.js";
@@ -16,6 +17,9 @@ export class BillingEventHandlers {
16
17
  get hasProvisioning() {
17
18
  return this.provisioning !== null;
18
19
  }
20
+ get terminalPlan() {
21
+ return this.terminalPlanKey;
22
+ }
19
23
  constructor(store, options) {
20
24
  this.store = store;
21
25
  this.provisioning = options?.provisioning ?? null;
@@ -35,7 +39,12 @@ export class BillingEventHandlers {
35
39
  return { offer };
36
40
  },
37
41
  });
38
- this.financial = new BillingFinancialEventHandlers(store, this.logger, this.pastDueGracePeriodMs, (event) => this.resolveAccountId(event), (event) => this.handleSubscriptionRenewed(event), (event, status) => this.updateCheckoutIntentFromEvent(event, status), (event) => this.getExistingSubscription(event), (event, userId, existing, overrides) => this.buildSubscriptionState(event, userId, existing, overrides));
42
+ this.financial = new BillingFinancialEventHandlers(store, this.logger, this.pastDueGracePeriodMs, (event) => this.resolveAccountId(event), (event) => this.handleSubscriptionRenewed(event), (event, status) => this.updateCheckoutIntentFromEvent(event, status), (event, graceEndsAt) => this.applySubscriptionEvent(event, {
43
+ action: "payment_failed_recorded",
44
+ status: "past_due",
45
+ graceEndsAt,
46
+ graceExpiredAt: null,
47
+ }));
39
48
  this.handlerMap = {
40
49
  [BillingEventType.CUSTOMER_CREATED]: this.handleCustomerCreated.bind(this),
41
50
  [BillingEventType.CUSTOMER_UPDATED]: this.handleCustomerCreated.bind(this),
@@ -70,8 +79,8 @@ export class BillingEventHandlers {
70
79
  this.offerCache.clear();
71
80
  }
72
81
  async updateCheckoutIntentFromEvent(event, status) {
73
- const intentId = event.metadata?.checkout_intent_id;
74
- if (typeof intentId !== "string" || !intentId)
82
+ const intentId = z.string().safeParse(event.metadata?.checkout_intent_id).data;
83
+ if (!intentId)
75
84
  return;
76
85
  await this.store.updateCheckoutIntent(intentId, { status });
77
86
  }
@@ -103,7 +112,7 @@ export class BillingEventHandlers {
103
112
  null;
104
113
  if (providerPaymentId) {
105
114
  const payment = await this.store.getBillingPayment(event.provider, providerPaymentId);
106
- if (typeof payment?.userId === "string") {
115
+ if (payment?.userId) {
107
116
  event.accountId = payment.userId;
108
117
  return payment.userId;
109
118
  }
@@ -138,7 +147,7 @@ export class BillingEventHandlers {
138
147
  if (event.customer?.providerCustomerId) {
139
148
  const uid = await this.resolveAccountId(event);
140
149
  if (uid && this.provisioning) {
141
- await this.revokeSubscription(uid);
150
+ await this.revokeCustomerAccess(uid);
142
151
  }
143
152
  }
144
153
  return { handled: true, action: "customer_deleted" };
@@ -185,10 +194,18 @@ export class BillingEventHandlers {
185
194
  currentPeriodEnd: sub.periodEnd ?? existing?.currentPeriodEnd ?? null,
186
195
  trialEnd: sub.trialEnd ?? existing?.trialEnd ?? null,
187
196
  cancelAt: sub.cancelAt ?? existing?.cancelAt ?? null,
188
- endedAt: sub.endedAt ?? existing?.endedAt ?? null,
189
- graceEndsAt: status === "past_due" ? (overrides?.graceEndsAt ?? existing?.graceEndsAt ?? null) : null,
197
+ endedAt: ["incomplete_expired", "canceled", "expired"].includes(status)
198
+ ? (sub.endedAt ?? existing?.endedAt ?? null)
199
+ : null,
200
+ graceEndsAt: status === "past_due"
201
+ ? overrides && "graceEndsAt" in overrides
202
+ ? (overrides.graceEndsAt ?? null)
203
+ : (existing?.graceEndsAt ?? null)
204
+ : null,
190
205
  graceExpiredAt: status === "past_due"
191
- ? (overrides?.graceExpiredAt ?? existing?.graceExpiredAt ?? null)
206
+ ? overrides && "graceExpiredAt" in overrides
207
+ ? (overrides.graceExpiredAt ?? null)
208
+ : (existing?.graceExpiredAt ?? null)
192
209
  : null,
193
210
  providerUpdatedAt: event.occurredAt,
194
211
  cancelAtPeriodEnd: overrides?.cancelAtPeriodEnd ??
@@ -197,7 +214,7 @@ export class BillingEventHandlers {
197
214
  false,
198
215
  interval: overrides?.interval ??
199
216
  sub.interval ??
200
- event.metadata?.billing_interval ??
217
+ z.string().safeParse(event.metadata?.billing_interval).data ??
201
218
  existing?.interval ??
202
219
  null,
203
220
  intervalCount: overrides?.intervalCount ?? sub.intervalCount ?? existing?.intervalCount ?? null,
@@ -217,8 +234,8 @@ export class BillingEventHandlers {
217
234
  return {
218
235
  offer,
219
236
  offerId: offer.offerId,
220
- offerKey: offer?.offerKey ?? null,
221
- plan: offer?.plan ?? null,
237
+ offerKey: offer.offerKey ?? null,
238
+ plan: offer.plan ?? null,
222
239
  };
223
240
  }
224
241
  // Tier 2: Resolve by lookup_key
@@ -228,14 +245,118 @@ export class BillingEventHandlers {
228
245
  return {
229
246
  offer: lookupOffer,
230
247
  offerId: lookupOffer.offerId,
231
- offerKey: lookupOffer?.offerKey ?? null,
232
- plan: lookupOffer?.plan ?? null,
248
+ offerKey: lookupOffer.offerKey ?? null,
249
+ plan: lookupOffer.plan ?? null,
233
250
  };
234
251
  }
235
252
  this.logger.error(`[BillingService] resolveOfferAndKeys: no offer found for ${event.provider}/${refs.lookupKey}`);
236
253
  }
237
254
  return { offer: null, offerId: null, offerKey: null, plan: null };
238
255
  }
256
+ subscriptionPlanAnchor(event, preserveAllowanceAnchor, preservedAllowanceAnchor) {
257
+ if (preserveAllowanceAnchor) {
258
+ if (preservedAllowanceAnchor === null)
259
+ return null;
260
+ const anchor = new Date(preservedAllowanceAnchor);
261
+ if (Number.isNaN(anchor.getTime()))
262
+ return null;
263
+ return anchor.getTime() > Date.now() ? new Date() : anchor;
264
+ }
265
+ const periodStart = event.subscription?.periodStart;
266
+ if (!periodStart)
267
+ return null;
268
+ const anchor = new Date(periodStart);
269
+ if (Number.isNaN(anchor.getTime())) {
270
+ this.logger.warn("[BillingService] invalid periodStart; using database assignment time", {
271
+ periodStart,
272
+ userId: event.accountId ?? null,
273
+ });
274
+ return null;
275
+ }
276
+ return anchor;
277
+ }
278
+ async reconcileSubscriptionEvent(uid, event, expected, options) {
279
+ if (!event.subscription || !event.billingEventId) {
280
+ throw new StoreError("subscription reconciliation requires a claimed billing event", {
281
+ indeterminate: true,
282
+ details: { provider: event.provider, providerEventId: event.eventId },
283
+ });
284
+ }
285
+ const persisted = await this.store.getBillingSubscription(event.provider, event.subscription.providerSubscriptionId);
286
+ if (!persisted?.subscriptionId) {
287
+ throw new StoreError("subscription reconciliation requires persisted subscription identity", {
288
+ indeterminate: true,
289
+ details: {
290
+ provider: event.provider,
291
+ providerSubscriptionId: event.subscription.providerSubscriptionId,
292
+ },
293
+ });
294
+ }
295
+ const applyEntitlement = this.provisioning !== null && this.autoSelectEntitlementSource;
296
+ const planAssignedAt = this.subscriptionPlanAnchor(event, options?.preserveAllowanceAnchor ?? false, options?.preservedAllowanceAnchor ?? null);
297
+ const outcome = await this.store.reconcileSubscriptionEntitlement(uid, persisted.subscriptionId, event.billingEventId, expected.status, expected.providerUpdatedAt, planAssignedAt, applyEntitlement, this.terminalPlanKey, `subscription_${expected.status}`);
298
+ this.logger.info("[BillingService] reconciled subscription entitlement", {
299
+ applyEntitlement,
300
+ outcome,
301
+ provider: event.provider,
302
+ providerSubscriptionId: event.subscription.providerSubscriptionId,
303
+ userId: uid,
304
+ });
305
+ return outcome;
306
+ }
307
+ async applySubscriptionEvent(event, options) {
308
+ const uid = await this.resolveAccountId(event);
309
+ if (!uid)
310
+ return { handled: false, error: "account_not_found" };
311
+ if (!event.subscription?.providerSubscriptionId) {
312
+ return { handled: false, error: "no_subscription_data" };
313
+ }
314
+ const existing = await this.getExistingSubscription(event);
315
+ const resolved = options.resolveOffers === false
316
+ ? { offer: null, offerId: null, offerKey: null, plan: null }
317
+ : await this.resolveOfferAndKeys(event);
318
+ const isPlanChange = options.action === "subscription_plan_changed";
319
+ const preservedAllowanceAnchor = isPlanChange && this.provisioning !== null
320
+ ? ((await this.provisioning.getUserPlan(uid))?.planAssignedAt ?? null)
321
+ : null;
322
+ const pending = isPlanChange
323
+ ? await this.store.getOpenBillingSubscriptionChange(event.provider, event.subscription.providerSubscriptionId)
324
+ : null;
325
+ const metadata = isPlanChange
326
+ ? {
327
+ ...(existing?.metadata ?? {}),
328
+ ...(event.metadata ?? {}),
329
+ pendingPlanChange: null,
330
+ }
331
+ : undefined;
332
+ const stateOverrides = {
333
+ status: options.status,
334
+ cancelAtPeriodEnd: options.cancelAtPeriodEnd,
335
+ offerKey: resolved.offerKey ?? existing?.offerKey ?? null,
336
+ offerId: resolved.offerId ?? existing?.offerId ?? null,
337
+ plan: resolved.plan ?? existing?.plan ?? null,
338
+ interval: resolved.offer?.interval,
339
+ intervalCount: resolved.offer?.intervalCount,
340
+ metadata,
341
+ };
342
+ if (options.graceEndsAt !== undefined)
343
+ stateOverrides.graceEndsAt = options.graceEndsAt;
344
+ if (options.graceExpiredAt !== undefined) {
345
+ stateOverrides.graceExpiredAt = options.graceExpiredAt;
346
+ }
347
+ const subscriptionState = this.buildSubscriptionState(event, uid, existing, stateOverrides);
348
+ await this.store.upsertBillingSubscription(subscriptionState);
349
+ const outcome = await this.reconcileSubscriptionEvent(uid, event, subscriptionState, {
350
+ preserveAllowanceAnchor: isPlanChange,
351
+ preservedAllowanceAnchor,
352
+ });
353
+ if (outcome === "stale")
354
+ return { handled: true, action: "stale_subscription_event" };
355
+ if (pending) {
356
+ await this.store.updateBillingSubscriptionChange(pending.id, { state: "applied" });
357
+ }
358
+ return { handled: true, action: options.action };
359
+ }
239
360
  async handleSubscriptionCreated(event) {
240
361
  const uid = await this.resolveAccountId(event);
241
362
  this.logger.info("[BillingService] handleSubscriptionCreated", {
@@ -293,7 +414,7 @@ export class BillingEventHandlers {
293
414
  // The partial unique index is the final arbiter under concurrent
294
415
  // webhooks. Convert its race loser into the same manual-review path as
295
416
  // the preflight check instead of retrying a permanently invalid event.
296
- const code = error.code;
417
+ const code = z.object({ code: z.string().optional() }).safeParse(error).data?.code;
297
418
  if (code !== "23505")
298
419
  throw error;
299
420
  const concurrent = (await this.store.getUserSubscriptions(uid)).find((candidate) => candidate.provider === event.provider &&
@@ -311,15 +432,19 @@ export class BillingEventHandlers {
311
432
  });
312
433
  return { handled: false, error: "subscription_conflict" };
313
434
  }
314
- if (this.provisioning &&
315
- event.subscription.status &&
316
- ["active", "trialing"].includes(event.subscription.status)) {
317
- await this.provisionSubscription(uid, offer, event);
435
+ const outcome = await this.reconcileSubscriptionEvent(uid, event, subscriptionState);
436
+ if (outcome === "stale") {
437
+ return {
438
+ handled: true,
439
+ action: "stale_subscription_event",
440
+ subscriptionId,
441
+ };
318
442
  }
319
- if (["active", "trialing"].includes(event.subscription.status ?? "")) {
443
+ const status = event.subscription.status;
444
+ if (["active", "trialing"].includes(status ?? "")) {
320
445
  await this.updateCheckoutIntentFromEvent(event, "completed");
321
446
  }
322
- return { handled: true, action: "subscription_created" };
447
+ return { handled: true, action: "subscription_created", subscriptionId };
323
448
  }
324
449
  async handleSubscriptionUpdated(event) {
325
450
  this.logger.info("[BillingService] handleSubscriptionUpdated", {
@@ -327,140 +452,52 @@ export class BillingEventHandlers {
327
452
  eventId: event.eventId,
328
453
  subId: event.subscription?.providerSubscriptionId,
329
454
  });
330
- const uid = await this.resolveAccountId(event);
331
- if (!uid)
332
- return { handled: false, error: "account_not_found" };
333
- if (!event.subscription?.providerSubscriptionId)
334
- return { handled: false, error: "no_subscription_data" };
335
- const existing = await this.getExistingSubscription(event);
336
- const { offer, offerId, offerKey, plan } = await this.resolveOfferAndKeys(event);
337
- await this.store.upsertBillingSubscription(this.buildSubscriptionState(event, uid, existing, {
338
- status: event.subscription.status ?? existing?.status ?? "incomplete",
339
- cancelAtPeriodEnd: event.subscription.cancelAtPeriodEnd ?? existing?.cancelAtPeriodEnd ?? false,
340
- offerKey: offerKey ?? existing?.offerKey ?? null,
341
- offerId: offerId ?? existing?.offerId ?? null,
342
- plan: plan ?? existing?.plan ?? null,
343
- interval: offer?.interval,
344
- intervalCount: offer?.intervalCount,
345
- }));
346
- if (this.provisioning) {
347
- await this.reEvaluateAccess(uid, event);
348
- }
349
- return { handled: true, action: "subscription_updated" };
455
+ return this.applySubscriptionEvent(event, {
456
+ action: "subscription_updated",
457
+ status: event.subscription?.status,
458
+ cancelAtPeriodEnd: event.subscription?.cancelAtPeriodEnd,
459
+ });
350
460
  }
351
461
  async handleSubscriptionActivated(event) {
352
462
  this.logger.info("[BillingService] handleSubscriptionActivated", {
353
463
  provider: event.provider,
354
464
  eventId: event.eventId,
355
465
  });
356
- const uid = await this.resolveAccountId(event);
357
- if (!uid)
358
- return { handled: false, error: "account_not_found" };
359
- if (!event.subscription?.providerSubscriptionId)
360
- return { handled: false, error: "no_subscription_data" };
361
- const existing = await this.getExistingSubscription(event);
362
- const { offer, offerId, offerKey, plan } = await this.resolveOfferAndKeys(event);
363
- await this.store.upsertBillingSubscription(this.buildSubscriptionState(event, uid, existing, {
466
+ return this.applySubscriptionEvent(event, {
467
+ action: "subscription_activated",
364
468
  status: "active",
365
- offerKey: offerKey ?? existing?.offerKey ?? null,
366
- offerId: offerId ?? existing?.offerId ?? null,
367
- plan: plan ?? existing?.plan ?? null,
368
- interval: offer?.interval,
369
- intervalCount: offer?.intervalCount,
370
- }));
371
- if (this.provisioning) {
372
- await this.provisionSubscription(uid, offer, event);
373
- }
374
- return { handled: true, action: "subscription_activated" };
469
+ });
375
470
  }
376
471
  async handleSubscriptionRenewed(event) {
377
- const uid = await this.resolveAccountId(event);
378
- if (!uid)
379
- return { handled: false, error: "account_not_found" };
380
- if (!event.subscription?.providerSubscriptionId)
381
- return { handled: false, error: "no_subscription_data" };
382
- const existing = await this.getExistingSubscription(event);
383
- const { offer, offerId, offerKey, plan } = await this.resolveOfferAndKeys(event);
384
- const resolvedPlanKey = plan ?? existing?.plan ?? null;
385
- await this.store.upsertBillingSubscription(this.buildSubscriptionState(event, uid, existing, {
472
+ const result = await this.applySubscriptionEvent(event, {
473
+ action: "subscription_renewed",
386
474
  status: "active",
387
- offerKey: offerKey ?? existing?.offerKey ?? null,
388
- offerId: offerId ?? existing?.offerId ?? null,
389
- plan: resolvedPlanKey,
390
- interval: offer?.interval,
391
- intervalCount: offer?.intervalCount,
392
- }));
393
- if (this.provisioning && resolvedPlanKey) {
394
- await this.provisionSubscription(uid, offer, event);
475
+ });
476
+ if (result.handled && result.action !== "stale_subscription_event") {
477
+ const { offer } = await this.resolveOfferAndKeys(event);
478
+ await this.grantSubscriptionCycle(event, offer);
395
479
  }
396
- await this.grantSubscriptionCycle(event, offer);
397
- return { handled: true, action: "subscription_renewed" };
480
+ return result;
398
481
  }
399
482
  async handleSubscriptionPlanChanged(event) {
400
- const uid = await this.resolveAccountId(event);
401
- if (!uid)
402
- return { handled: false, error: "account_not_found" };
403
- if (!event.subscription?.providerSubscriptionId)
404
- return { handled: false, error: "no_subscription_data" };
405
- const existing = await this.getExistingSubscription(event);
406
- const { offer, offerId, offerKey, plan } = await this.resolveOfferAndKeys(event);
407
- // Capture the current allowance anchor before advancing the durable
408
- // change. The Postgres transition updates the assignment atomically, so
409
- // reading it afterwards would return the new assignment's timestamp and
410
- // silently reset the learner's current allowance window.
411
- const preservedAllowanceAnchor = this.provisioning
412
- ? ((await this.provisioning.getUserPlan(uid))?.planAssignedAt ?? null)
413
- : undefined;
414
- const pending = await this.store.getOpenBillingSubscriptionChange(event.provider, event.subscription.providerSubscriptionId);
415
- if (pending) {
416
- await this.store.updateBillingSubscriptionChange(pending.id, {
417
- state: "applied",
418
- });
419
- }
420
- await this.store.upsertBillingSubscription(this.buildSubscriptionState(event, uid, existing, {
421
- status: event.subscription.status ?? "active",
422
- offerKey: offerKey ?? existing?.offerKey ?? null,
423
- offerId: offerId ?? existing?.offerId ?? null,
424
- plan: plan ?? existing?.plan ?? null,
425
- interval: offer?.interval,
426
- intervalCount: offer?.intervalCount,
427
- metadata: {
428
- ...(existing?.metadata ?? {}),
429
- ...(event.metadata ?? {}),
430
- pendingPlanChange: null,
431
- },
432
- }));
433
- if (this.provisioning && (plan ?? existing?.plan)) {
434
- // Plan-change: prefer new plan over existing (renewal at L422 correctly keeps existing).
435
- await this.provisionSubscription(uid, offer, event, plan ?? existing?.plan ?? undefined, true, preservedAllowanceAnchor);
436
- }
437
- return { handled: true, action: "subscription_plan_changed" };
483
+ return this.applySubscriptionEvent(event, {
484
+ action: "subscription_plan_changed",
485
+ status: event.subscription?.status ?? "active",
486
+ });
438
487
  }
439
488
  async handleCancellationScheduled(event) {
440
- const uid = await this.resolveAccountId(event);
441
- if (!uid)
442
- return { handled: false, error: "account_not_found" };
443
- if (!event.subscription?.providerSubscriptionId)
444
- return { handled: false, error: "no_subscription_data" };
445
- const existing = await this.getExistingSubscription(event);
446
- await this.store.upsertBillingSubscription(this.buildSubscriptionState(event, uid, existing, {
447
- status: existing?.status ?? event.subscription.status ?? "active",
489
+ return this.applySubscriptionEvent(event, {
490
+ action: "cancellation_scheduled",
448
491
  cancelAtPeriodEnd: true,
449
- }));
450
- return { handled: true, action: "cancellation_scheduled" };
492
+ resolveOffers: false,
493
+ });
451
494
  }
452
495
  async handleCancellationUnscheduled(event) {
453
- const uid = await this.resolveAccountId(event);
454
- if (!uid)
455
- return { handled: false, error: "account_not_found" };
456
- if (!event.subscription?.providerSubscriptionId)
457
- return { handled: false, error: "no_subscription_data" };
458
- const existing = await this.getExistingSubscription(event);
459
- await this.store.upsertBillingSubscription(this.buildSubscriptionState(event, uid, existing, {
460
- status: existing?.status ?? event.subscription.status ?? "active",
496
+ return this.applySubscriptionEvent(event, {
497
+ action: "cancellation_unscheduled",
461
498
  cancelAtPeriodEnd: false,
462
- }));
463
- return { handled: true, action: "cancellation_unscheduled" };
499
+ resolveOffers: false,
500
+ });
464
501
  }
465
502
  async handleSubscriptionCanceled(event) {
466
503
  this.logger.info("[BillingService] handleSubscriptionCanceled", {
@@ -483,7 +520,7 @@ export class BillingEventHandlers {
483
520
  },
484
521
  });
485
522
  }
486
- await this.store.upsertBillingSubscription(this.buildSubscriptionState(event, uid, existing, {
523
+ const subscriptionState = this.buildSubscriptionState(event, uid, existing, {
487
524
  status: "canceled",
488
525
  cancelAtPeriodEnd: event.subscription.cancelAtPeriodEnd ?? true,
489
526
  offerKey: resolved?.offerKey ?? existing?.offerKey ?? null,
@@ -491,113 +528,40 @@ export class BillingEventHandlers {
491
528
  plan: resolved?.plan ?? existing?.plan ?? null,
492
529
  interval: resolved?.offer?.interval,
493
530
  intervalCount: resolved?.offer?.intervalCount,
494
- }));
495
- if (this.provisioning) {
496
- await this.revokeIfCurrentSubscription(uid, event.subscription.providerSubscriptionId);
497
- }
531
+ });
532
+ await this.store.upsertBillingSubscription(subscriptionState);
533
+ const outcome = await this.reconcileSubscriptionEvent(uid, event, subscriptionState);
534
+ if (outcome === "stale")
535
+ return { handled: true, action: "stale_subscription_event" };
498
536
  return { handled: true, action: "subscription_canceled" };
499
537
  }
500
538
  async handleSubscriptionExpired(event) {
501
- const uid = await this.resolveAccountId(event);
502
- if (!uid)
503
- return { handled: false, error: "account_not_found" };
504
- if (!event.subscription?.providerSubscriptionId)
505
- return { handled: false, error: "no_subscription_data" };
506
- const existing = await this.getExistingSubscription(event);
507
- await this.store.upsertBillingSubscription(this.buildSubscriptionState(event, uid, existing, {
539
+ return this.applySubscriptionEvent(event, {
540
+ action: "subscription_expired",
508
541
  status: "expired",
509
- cancelAtPeriodEnd: event.subscription.cancelAtPeriodEnd ?? true,
510
- }));
511
- if (this.provisioning) {
512
- await this.revokeIfCurrentSubscription(uid, event.subscription.providerSubscriptionId);
513
- }
514
- return { handled: true, action: "subscription_expired" };
542
+ cancelAtPeriodEnd: event.subscription?.cancelAtPeriodEnd ?? true,
543
+ resolveOffers: false,
544
+ });
515
545
  }
516
546
  async handleSubscriptionPaused(event) {
517
- const uid = await this.resolveAccountId(event);
518
- if (!uid)
519
- return { handled: false, error: "account_not_found" };
520
- if (!event.subscription?.providerSubscriptionId)
521
- return { handled: false, error: "no_subscription_data" };
522
- const existing = await this.getExistingSubscription(event);
523
- await this.store.upsertBillingSubscription(this.buildSubscriptionState(event, uid, existing, {
547
+ return this.applySubscriptionEvent(event, {
548
+ action: "subscription_paused",
524
549
  status: "paused",
525
- cancelAtPeriodEnd: existing?.cancelAtPeriodEnd ?? false,
526
- }));
527
- if (this.provisioning) {
528
- await this.revokeIfCurrentSubscription(uid, event.subscription.providerSubscriptionId);
529
- }
530
- return { handled: true, action: "subscription_paused" };
550
+ resolveOffers: false,
551
+ });
531
552
  }
532
553
  async handleSubscriptionResumed(event) {
533
- const uid = await this.resolveAccountId(event);
534
- if (!uid)
535
- return { handled: false, error: "account_not_found" };
536
- if (!event.subscription?.providerSubscriptionId)
537
- return { handled: false, error: "no_subscription_data" };
538
- const existing = await this.getExistingSubscription(event);
539
- const { offer, offerKey, plan } = await this.resolveOfferAndKeys(event);
540
- await this.store.upsertBillingSubscription(this.buildSubscriptionState(event, uid, existing, {
554
+ return this.applySubscriptionEvent(event, {
555
+ action: "subscription_resumed",
541
556
  status: "active",
542
557
  cancelAtPeriodEnd: false,
543
- offerKey: offerKey ?? existing?.offerKey ?? null,
544
- plan: plan ?? existing?.plan ?? null,
545
- }));
546
- if (this.provisioning) {
547
- await this.provisionSubscription(uid, offer, event);
548
- }
549
- return { handled: true, action: "subscription_resumed" };
558
+ });
550
559
  }
551
560
  async handleTrialWillEnd(event) {
552
561
  // Resolve userId so routeEvent's blanket fireEventCallback has a useful value.
553
562
  await this.resolveAccountId(event);
554
563
  return { handled: true, action: "trial_will_end_notified" };
555
564
  }
556
- async provisionSubscription(uid, offer, event, planKeyOverride, preserveAllowanceAnchor = false, preservedAllowanceAnchor) {
557
- if (!this.provisioning) {
558
- this.logger.debug(`[BillingService] provisionSubscription: no provisioning capability for user ${uid}`);
559
- return;
560
- }
561
- const plan = planKeyOverride ?? offer?.plan;
562
- if (!plan) {
563
- this.logger.debug("[BillingService] provisionSubscription skipped (no plan)", { uid });
564
- return;
565
- }
566
- this.logger.debug("[BillingService] provisionSubscription setting plan", { uid, plan });
567
- let periodStart;
568
- if (preserveAllowanceAnchor) {
569
- const existingAnchor = preservedAllowanceAnchor !== undefined
570
- ? preservedAllowanceAnchor
571
- : (await this.provisioning.getUserPlan(uid))?.planAssignedAt;
572
- if (existingAnchor) {
573
- const anchor = new Date(existingAnchor);
574
- // A provider's subscription period start may actually be its next
575
- // renewal date. Never let a future anchor hide an already-active
576
- // entitlement after a plan change.
577
- if (!Number.isNaN(anchor.getTime()) && anchor.getTime() <= Date.now()) {
578
- periodStart = anchor;
579
- }
580
- }
581
- }
582
- else {
583
- periodStart = event.subscription?.periodStart;
584
- }
585
- const planAssignedAt = periodStart
586
- ? (() => {
587
- const d = new Date(periodStart);
588
- return Number.isNaN(d.getTime()) ? undefined : d;
589
- })()
590
- : preserveAllowanceAnchor
591
- ? new Date()
592
- : undefined;
593
- await this.provisioning.setUserPlan(uid, plan, planAssignedAt);
594
- if (this.autoSelectEntitlementSource && event.provider) {
595
- const selected = await this.store.selectSubscriptionEntitlementSource(uid, event.provider, event.subscription?.providerSubscriptionId);
596
- if (selected) {
597
- this.logger.debug(`[BillingService] selected ${event.provider} subscription as entitlement source for user ${uid}`);
598
- }
599
- }
600
- }
601
565
  async grantSubscriptionCycle(event, offer) {
602
566
  const credits = offer?.grant?.mode === "cycle_grant" ? offer.grant.credits : null;
603
567
  if (!credits || credits.lte(0) || !event.billingEventId || !event.subscription)
@@ -624,7 +588,7 @@ export class BillingEventHandlers {
624
588
  });
625
589
  await this.store.grantBillingCredit(grantId, `billing:${event.eventId}:subscription-cycle`);
626
590
  }
627
- async revokeSubscription(uid) {
591
+ async revokeCustomerAccess(uid) {
628
592
  if (!this.provisioning)
629
593
  return;
630
594
  if (this.terminalPlanKey) {
@@ -633,63 +597,5 @@ export class BillingEventHandlers {
633
597
  }
634
598
  await this.provisioning.unsetUserPlan(uid);
635
599
  }
636
- /**
637
- * Do not revoke access because a stale subscription record ended while a
638
- * newer subscription for the same user is still active.
639
- */
640
- async revokeIfCurrentSubscription(uid, subscriptionId) {
641
- const current = await this.store.getUserSubscription(uid, ["active", "trialing", "past_due"]);
642
- if (!current || current.providerSubscriptionId === subscriptionId) {
643
- await this.revokeSubscription(uid);
644
- }
645
- }
646
- async reEvaluateAccess(uid, event) {
647
- if (!this.provisioning || !event.subscription)
648
- return;
649
- const status = event.subscription.status;
650
- // Provider retries (Stripe past_due, Dodo on_hold mapped to past_due)
651
- // are a grace period. Keep the last paid entitlements until the provider
652
- // reaches a terminal state instead of revoking access on the first miss.
653
- if (status && ["active", "trialing"].includes(status)) {
654
- const offer = await this.resolveOfferFromEvent(event);
655
- if (offer) {
656
- await this.provisionSubscription(uid, offer, event);
657
- }
658
- else {
659
- const existing = await this.store.getBillingSubscription(event.provider, event.subscription.providerSubscriptionId);
660
- if (existing?.plan) {
661
- await this.provisionSubscription(uid, null, event, existing.plan);
662
- }
663
- }
664
- }
665
- else if (status === "past_due") {
666
- const existing = await this.store.getBillingSubscription(event.provider, event.subscription.providerSubscriptionId);
667
- const graceHasExpired = Boolean(existing?.graceExpiredAt) ||
668
- (Boolean(existing?.graceEndsAt) &&
669
- new Date(existing.graceEndsAt).getTime() <= Date.now());
670
- if (graceHasExpired) {
671
- await this.revokeIfCurrentSubscription(uid, event.subscription.providerSubscriptionId);
672
- }
673
- else {
674
- const offer = await this.resolveOfferFromEvent(event);
675
- if (offer) {
676
- await this.provisionSubscription(uid, offer, event);
677
- }
678
- else if (existing?.plan) {
679
- await this.provisionSubscription(uid, null, event, existing.plan);
680
- }
681
- }
682
- }
683
- else if (status &&
684
- ["canceled", "expired", "unpaid", "paused", "incomplete_expired"].includes(status)) {
685
- await this.revokeIfCurrentSubscription(uid, event.subscription.providerSubscriptionId);
686
- }
687
- }
688
- async resolveOfferFromEvent(event) {
689
- const refs = event.subscription?.refs;
690
- if (!refs)
691
- return null;
692
- return this.resolveBillingOfferCached(event.provider, refs.productId ?? null, refs.priceId ?? null);
693
- }
694
600
  }
695
601
  //# sourceMappingURL=event-handlers.js.map