@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
@@ -6,7 +6,6 @@ import { StoreError } from "../errors.js";
6
6
  export class BillingEventHandlers {
7
7
  store;
8
8
  provisioning;
9
- resolveUser;
10
9
  autoSelectEntitlementSource;
11
10
  pastDueGracePeriodMs;
12
11
  terminalPlanKey;
@@ -20,7 +19,6 @@ export class BillingEventHandlers {
20
19
  constructor(store, options) {
21
20
  this.store = store;
22
21
  this.provisioning = options?.provisioning ?? null;
23
- this.resolveUser = options?.resolveUser ?? null;
24
22
  this.autoSelectEntitlementSource = options?.autoSelectEntitlementSource ?? true;
25
23
  this.pastDueGracePeriodMs = options?.pastDueGracePeriodMs ?? 7 * 24 * 60 * 60 * 1000;
26
24
  if (!Number.isFinite(this.pastDueGracePeriodMs) || this.pastDueGracePeriodMs < 0) {
@@ -37,7 +35,7 @@ export class BillingEventHandlers {
37
35
  return { offer };
38
36
  },
39
37
  });
40
- this.financial = new BillingFinancialEventHandlers(store, this.logger, this.pastDueGracePeriodMs, (event) => this.resolveUserId(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));
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));
41
39
  this.handlerMap = {
42
40
  [BillingEventType.CUSTOMER_CREATED]: this.handleCustomerCreated.bind(this),
43
41
  [BillingEventType.CUSTOMER_UPDATED]: this.handleCustomerCreated.bind(this),
@@ -78,31 +76,24 @@ export class BillingEventHandlers {
78
76
  await this.store.updateCheckoutIntent(intentId, { status });
79
77
  }
80
78
  /**
81
- * Resolve userId from the event, mutating event.userId so that
79
+ * Resolve accountId from the event, mutating event.accountId so that
82
80
  * routeEvent's blanket fireEventCallback can read it. Each ingestBillingEvent
83
81
  * call creates a fresh event object, so mutation is safe.
84
82
  */
85
- async resolveUserId(event) {
86
- if (event.userId)
87
- return event.userId;
83
+ async resolveAccountId(event) {
84
+ if (event.accountId)
85
+ return event.accountId;
88
86
  if (event.customer?.providerCustomerId) {
89
87
  const uid = await this.store.getBillingCustomer(event.provider, event.customer.providerCustomerId);
90
88
  if (uid) {
91
- event.userId = uid;
92
- return uid;
93
- }
94
- }
95
- if (this.resolveUser && event.customer?.providerCustomerId) {
96
- const uid = this.resolveUser(event.provider, event.customer.providerCustomerId, event.customer.email ?? null);
97
- if (uid) {
98
- event.userId = uid;
89
+ event.accountId = uid;
99
90
  return uid;
100
91
  }
101
92
  }
102
93
  if (event.subscription?.providerSubscriptionId) {
103
94
  const existing = await this.store.getBillingSubscription(event.provider, event.subscription.providerSubscriptionId);
104
95
  if (existing?.userId) {
105
- event.userId = existing.userId;
96
+ event.accountId = existing.userId;
106
97
  return existing.userId;
107
98
  }
108
99
  }
@@ -113,7 +104,7 @@ export class BillingEventHandlers {
113
104
  if (providerPaymentId) {
114
105
  const payment = await this.store.getBillingPayment(event.provider, providerPaymentId);
115
106
  if (typeof payment?.userId === "string") {
116
- event.userId = payment.userId;
107
+ event.accountId = payment.userId;
117
108
  return payment.userId;
118
109
  }
119
110
  }
@@ -132,7 +123,7 @@ export class BillingEventHandlers {
132
123
  customerId: event.customer?.providerCustomerId,
133
124
  });
134
125
  if (event.customer?.providerCustomerId) {
135
- const uid = await this.resolveUserId(event);
126
+ const uid = await this.resolveAccountId(event);
136
127
  if (uid) {
137
128
  await this.store.upsertBillingCustomer(event.provider, event.customer.providerCustomerId, uid, event.customer.email ?? null);
138
129
  }
@@ -145,7 +136,7 @@ export class BillingEventHandlers {
145
136
  customerId: event.customer?.providerCustomerId,
146
137
  });
147
138
  if (event.customer?.providerCustomerId) {
148
- const uid = await this.resolveUserId(event);
139
+ const uid = await this.resolveAccountId(event);
149
140
  if (uid && this.provisioning) {
150
141
  await this.revokeSubscription(uid);
151
142
  }
@@ -156,10 +147,10 @@ export class BillingEventHandlers {
156
147
  this.logger.info("[BillingService] handleCheckoutCompleted", {
157
148
  provider: event.provider,
158
149
  eventId: event.eventId,
159
- hasUserId: Boolean(event.userId),
150
+ hasAccountId: Boolean(event.accountId),
160
151
  });
161
152
  if (event.customer?.providerCustomerId) {
162
- const uid = await this.resolveUserId(event);
153
+ const uid = await this.resolveAccountId(event);
163
154
  if (uid) {
164
155
  await this.store.upsertBillingCustomer(event.provider, event.customer.providerCustomerId, uid, event.customer.email ?? null);
165
156
  }
@@ -246,14 +237,14 @@ export class BillingEventHandlers {
246
237
  return { offer: null, offerId: null, offerKey: null, plan: null };
247
238
  }
248
239
  async handleSubscriptionCreated(event) {
249
- const uid = await this.resolveUserId(event);
240
+ const uid = await this.resolveAccountId(event);
250
241
  this.logger.info("[BillingService] handleSubscriptionCreated", {
251
242
  eventId: event.eventId,
252
243
  provider: event.provider,
253
- hasUserId: Boolean(uid),
244
+ hasAccountId: Boolean(uid),
254
245
  });
255
246
  if (!uid)
256
- return { handled: false, error: "user_not_found" };
247
+ return { handled: false, error: "account_not_found" };
257
248
  if (event.customer?.providerCustomerId) {
258
249
  await this.store.upsertBillingCustomer(event.provider, event.customer.providerCustomerId, uid, event.customer.email ?? null);
259
250
  }
@@ -336,9 +327,9 @@ export class BillingEventHandlers {
336
327
  eventId: event.eventId,
337
328
  subId: event.subscription?.providerSubscriptionId,
338
329
  });
339
- const uid = await this.resolveUserId(event);
330
+ const uid = await this.resolveAccountId(event);
340
331
  if (!uid)
341
- return { handled: false, error: "user_not_found" };
332
+ return { handled: false, error: "account_not_found" };
342
333
  if (!event.subscription?.providerSubscriptionId)
343
334
  return { handled: false, error: "no_subscription_data" };
344
335
  const existing = await this.getExistingSubscription(event);
@@ -362,9 +353,9 @@ export class BillingEventHandlers {
362
353
  provider: event.provider,
363
354
  eventId: event.eventId,
364
355
  });
365
- const uid = await this.resolveUserId(event);
356
+ const uid = await this.resolveAccountId(event);
366
357
  if (!uid)
367
- return { handled: false, error: "user_not_found" };
358
+ return { handled: false, error: "account_not_found" };
368
359
  if (!event.subscription?.providerSubscriptionId)
369
360
  return { handled: false, error: "no_subscription_data" };
370
361
  const existing = await this.getExistingSubscription(event);
@@ -383,9 +374,9 @@ export class BillingEventHandlers {
383
374
  return { handled: true, action: "subscription_activated" };
384
375
  }
385
376
  async handleSubscriptionRenewed(event) {
386
- const uid = await this.resolveUserId(event);
377
+ const uid = await this.resolveAccountId(event);
387
378
  if (!uid)
388
- return { handled: false, error: "user_not_found" };
379
+ return { handled: false, error: "account_not_found" };
389
380
  if (!event.subscription?.providerSubscriptionId)
390
381
  return { handled: false, error: "no_subscription_data" };
391
382
  const existing = await this.getExistingSubscription(event);
@@ -406,9 +397,9 @@ export class BillingEventHandlers {
406
397
  return { handled: true, action: "subscription_renewed" };
407
398
  }
408
399
  async handleSubscriptionPlanChanged(event) {
409
- const uid = await this.resolveUserId(event);
400
+ const uid = await this.resolveAccountId(event);
410
401
  if (!uid)
411
- return { handled: false, error: "user_not_found" };
402
+ return { handled: false, error: "account_not_found" };
412
403
  if (!event.subscription?.providerSubscriptionId)
413
404
  return { handled: false, error: "no_subscription_data" };
414
405
  const existing = await this.getExistingSubscription(event);
@@ -417,7 +408,7 @@ export class BillingEventHandlers {
417
408
  // change. The Postgres transition updates the assignment atomically, so
418
409
  // reading it afterwards would return the new assignment's timestamp and
419
410
  // silently reset the learner's current allowance window.
420
- const preservedAllowanceAnchor = this.provisioning?.getUserPlan
411
+ const preservedAllowanceAnchor = this.provisioning
421
412
  ? ((await this.provisioning.getUserPlan(uid))?.planAssignedAt ?? null)
422
413
  : undefined;
423
414
  const pending = await this.store.getOpenBillingSubscriptionChange(event.provider, event.subscription.providerSubscriptionId);
@@ -446,9 +437,9 @@ export class BillingEventHandlers {
446
437
  return { handled: true, action: "subscription_plan_changed" };
447
438
  }
448
439
  async handleCancellationScheduled(event) {
449
- const uid = await this.resolveUserId(event);
440
+ const uid = await this.resolveAccountId(event);
450
441
  if (!uid)
451
- return { handled: false, error: "user_not_found" };
442
+ return { handled: false, error: "account_not_found" };
452
443
  if (!event.subscription?.providerSubscriptionId)
453
444
  return { handled: false, error: "no_subscription_data" };
454
445
  const existing = await this.getExistingSubscription(event);
@@ -459,9 +450,9 @@ export class BillingEventHandlers {
459
450
  return { handled: true, action: "cancellation_scheduled" };
460
451
  }
461
452
  async handleCancellationUnscheduled(event) {
462
- const uid = await this.resolveUserId(event);
453
+ const uid = await this.resolveAccountId(event);
463
454
  if (!uid)
464
- return { handled: false, error: "user_not_found" };
455
+ return { handled: false, error: "account_not_found" };
465
456
  if (!event.subscription?.providerSubscriptionId)
466
457
  return { handled: false, error: "no_subscription_data" };
467
458
  const existing = await this.getExistingSubscription(event);
@@ -476,9 +467,9 @@ export class BillingEventHandlers {
476
467
  provider: event.provider,
477
468
  eventId: event.eventId,
478
469
  });
479
- const uid = await this.resolveUserId(event);
470
+ const uid = await this.resolveAccountId(event);
480
471
  if (!uid)
481
- return { handled: false, error: "user_not_found" };
472
+ return { handled: false, error: "account_not_found" };
482
473
  if (!event.subscription?.providerSubscriptionId)
483
474
  return { handled: false, error: "no_subscription_data" };
484
475
  const existing = await this.getExistingSubscription(event);
@@ -507,9 +498,9 @@ export class BillingEventHandlers {
507
498
  return { handled: true, action: "subscription_canceled" };
508
499
  }
509
500
  async handleSubscriptionExpired(event) {
510
- const uid = await this.resolveUserId(event);
501
+ const uid = await this.resolveAccountId(event);
511
502
  if (!uid)
512
- return { handled: false, error: "user_not_found" };
503
+ return { handled: false, error: "account_not_found" };
513
504
  if (!event.subscription?.providerSubscriptionId)
514
505
  return { handled: false, error: "no_subscription_data" };
515
506
  const existing = await this.getExistingSubscription(event);
@@ -523,9 +514,9 @@ export class BillingEventHandlers {
523
514
  return { handled: true, action: "subscription_expired" };
524
515
  }
525
516
  async handleSubscriptionPaused(event) {
526
- const uid = await this.resolveUserId(event);
517
+ const uid = await this.resolveAccountId(event);
527
518
  if (!uid)
528
- return { handled: false, error: "user_not_found" };
519
+ return { handled: false, error: "account_not_found" };
529
520
  if (!event.subscription?.providerSubscriptionId)
530
521
  return { handled: false, error: "no_subscription_data" };
531
522
  const existing = await this.getExistingSubscription(event);
@@ -539,9 +530,9 @@ export class BillingEventHandlers {
539
530
  return { handled: true, action: "subscription_paused" };
540
531
  }
541
532
  async handleSubscriptionResumed(event) {
542
- const uid = await this.resolveUserId(event);
533
+ const uid = await this.resolveAccountId(event);
543
534
  if (!uid)
544
- return { handled: false, error: "user_not_found" };
535
+ return { handled: false, error: "account_not_found" };
545
536
  if (!event.subscription?.providerSubscriptionId)
546
537
  return { handled: false, error: "no_subscription_data" };
547
538
  const existing = await this.getExistingSubscription(event);
@@ -559,7 +550,7 @@ export class BillingEventHandlers {
559
550
  }
560
551
  async handleTrialWillEnd(event) {
561
552
  // Resolve userId so routeEvent's blanket fireEventCallback has a useful value.
562
- await this.resolveUserId(event);
553
+ await this.resolveAccountId(event);
563
554
  return { handled: true, action: "trial_will_end_notified" };
564
555
  }
565
556
  async provisionSubscription(uid, offer, event, planKeyOverride, preserveAllowanceAnchor = false, preservedAllowanceAnchor) {
@@ -577,9 +568,7 @@ export class BillingEventHandlers {
577
568
  if (preserveAllowanceAnchor) {
578
569
  const existingAnchor = preservedAllowanceAnchor !== undefined
579
570
  ? preservedAllowanceAnchor
580
- : this.provisioning.getUserPlan
581
- ? (await this.provisioning.getUserPlan(uid))?.planAssignedAt
582
- : undefined;
571
+ : (await this.provisioning.getUserPlan(uid))?.planAssignedAt;
583
572
  if (existingAnchor) {
584
573
  const anchor = new Date(existingAnchor);
585
574
  // A provider's subscription period start may actually be its next
@@ -1 +1 @@
1
- {"version":3,"file":"event-handlers.js","sourceRoot":"","sources":["../../src/billing/event-handlers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAStD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,6BAA6B,EAAE,MAAM,+BAA+B,CAAC;AAC9E,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAiB1C,MAAM,OAAO,oBAAoB;IAgBZ;IAfF,YAAY,CAAiC;IAC7C,WAAW,CAAqB;IAChC,2BAA2B,CAAU;IACrC,oBAAoB,CAAS;IAC7B,eAAe,CAAgB;IAC/B,MAAM,CAAmB;IACzB,UAAU,CAAkD;IAC5D,SAAS,CAAgC;IACzC,UAAU,CAAuE;IAElG,IAAI,eAAe;QACjB,OAAO,IAAI,CAAC,YAAY,KAAK,IAAI,CAAC;IACpC,CAAC;IAED,YACmB,KAAmB,EACpC,OAA+B;QADd,UAAK,GAAL,KAAK,CAAc;QAGpC,IAAI,CAAC,YAAY,GAAG,OAAO,EAAE,YAAY,IAAI,IAAI,CAAC;QAClD,IAAI,CAAC,WAAW,GAAG,OAAO,EAAE,WAAW,IAAI,IAAI,CAAC;QAChD,IAAI,CAAC,2BAA2B,GAAG,OAAO,EAAE,2BAA2B,IAAI,IAAI,CAAC;QAChF,IAAI,CAAC,oBAAoB,GAAG,OAAO,EAAE,oBAAoB,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE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nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport { normalizeLogger } from \"../shared/logger.js\";\nimport type { BillingStore } from \"./billing-store.js\";\nimport type {\n BillingEvent,\n BillingEventResult,\n BillingOfferResult,\n BillingSubscriptionState,\n BillingSubscriptionStatus,\n} from \"./types/index.js\";\nimport { BillingEventType } from \"./types/index.js\";\nimport { BillingFinancialEventHandlers } from \"./financial-event-handlers.js\";\nimport { StoreError } from \"../errors.js\";\nimport type {\n BillingProvisioningPort,\n BillingServiceOptions,\n ResolveUser,\n} from \"./service-types.js\";\n\ninterface OfferCacheValue {\n offer: BillingOfferResult | null;\n}\n\ninterface OfferContext {\n provider: string;\n productId: string | null;\n priceId: string | null;\n}\n\nexport class BillingEventHandlers {\n private readonly provisioning: BillingProvisioningPort | null;\n private readonly resolveUser: ResolveUser | null;\n private readonly autoSelectEntitlementSource: boolean;\n private readonly pastDueGracePeriodMs: number;\n private readonly terminalPlanKey: string | null;\n private readonly logger: NormalizedLogger;\n private readonly offerCache: LRUCache<string, OfferCacheValue, OfferContext>;\n private readonly financial: BillingFinancialEventHandlers;\n private readonly handlerMap: Record<string, (event: BillingEvent) => Promise<BillingEventResult>>;\n\n get hasProvisioning(): boolean {\n return this.provisioning !== null;\n }\n\n constructor(\n private readonly store: BillingStore,\n options?: BillingServiceOptions,\n ) {\n this.provisioning = options?.provisioning ?? null;\n this.resolveUser = options?.resolveUser ?? null;\n this.autoSelectEntitlementSource = options?.autoSelectEntitlementSource ?? true;\n this.pastDueGracePeriodMs = options?.pastDueGracePeriodMs ?? 7 * 24 * 60 * 60 * 1000;\n if (!Number.isFinite(this.pastDueGracePeriodMs) || this.pastDueGracePeriodMs < 0) {\n throw new RangeError(\"pastDueGracePeriodMs must be a finite non-negative number\");\n }\n this.terminalPlanKey = options?.terminalPlanKey ?? null;\n this.logger = normalizeLogger(options?.logger);\n this.offerCache = new LRUCache<string, OfferCacheValue, OfferContext>({\n max: 100,\n ttl: 60_000,\n allowStale: false,\n fetchMethod: async (_, __, { context }) => {\n const offer = await this.store.resolveBillingOffer(\n context.provider,\n context.productId,\n context.priceId,\n );\n return { offer };\n },\n });\n this.financial = new BillingFinancialEventHandlers(\n store,\n this.logger,\n this.pastDueGracePeriodMs,\n (event) => this.resolveUserId(event),\n (event) => this.handleSubscriptionRenewed(event),\n (event, status) => this.updateCheckoutIntentFromEvent(event, status),\n (event) => this.getExistingSubscription(event),\n (event, userId, existing, overrides) =>\n this.buildSubscriptionState(event, userId, existing, overrides),\n );\n this.handlerMap = {\n [BillingEventType.CUSTOMER_CREATED]: this.handleCustomerCreated.bind(this),\n [BillingEventType.CUSTOMER_UPDATED]: this.handleCustomerCreated.bind(this),\n [BillingEventType.CUSTOMER_DELETED]: this.handleCustomerDeleted.bind(this),\n [BillingEventType.CHECKOUT_COMPLETED]: this.handleCheckoutCompleted.bind(this),\n [BillingEventType.SUBSCRIPTION_CREATED]: this.handleSubscriptionCreated.bind(this),\n [BillingEventType.SUBSCRIPTION_UPDATED]: this.handleSubscriptionUpdated.bind(this),\n [BillingEventType.SUBSCRIPTION_ACTIVATED]: this.handleSubscriptionActivated.bind(this),\n [BillingEventType.SUBSCRIPTION_RENEWED]: this.handleSubscriptionRenewed.bind(this),\n [BillingEventType.SUBSCRIPTION_PLAN_CHANGED]: this.handleSubscriptionPlanChanged.bind(this),\n [BillingEventType.SUBSCRIPTION_CANCELLATION_SCHEDULED]:\n this.handleCancellationScheduled.bind(this),\n [BillingEventType.SUBSCRIPTION_CANCELLATION_UNSCHEDULED]:\n this.handleCancellationUnscheduled.bind(this),\n [BillingEventType.SUBSCRIPTION_CANCELED]: this.handleSubscriptionCanceled.bind(this),\n [BillingEventType.SUBSCRIPTION_EXPIRED]: this.handleSubscriptionExpired.bind(this),\n [BillingEventType.SUBSCRIPTION_PAUSED]: this.handleSubscriptionPaused.bind(this),\n [BillingEventType.SUBSCRIPTION_RESUMED]: this.handleSubscriptionResumed.bind(this),\n [BillingEventType.SUBSCRIPTION_TRIAL_WILL_END]: this.handleTrialWillEnd.bind(this),\n [BillingEventType.INVOICE_PAID]: this.financial.handleInvoicePaid.bind(this.financial),\n [BillingEventType.PAYMENT_SUCCEEDED]: this.financial.handlePaymentSucceeded.bind(\n this.financial,\n ),\n [BillingEventType.PAYMENT_FAILED]: this.financial.handlePaymentFailed.bind(this.financial),\n [BillingEventType.REFUND_CREATED]: this.financial.handleRefundCreated.bind(this.financial),\n [BillingEventType.REFUND_UPDATED]: this.financial.handleRefundCreated.bind(this.financial),\n [BillingEventType.REFUND_FAILED]: this.financial.handleRefundCreated.bind(this.financial),\n [BillingEventType.DISPUTE_CREATED]: this.financial.handleDisputeCreated.bind(this.financial),\n [BillingEventType.DISPUTE_CLOSED]: this.financial.handleDisputeClosed.bind(this.financial),\n };\n }\n\n getHandler(\n eventType: BillingEventType,\n ): ((event: BillingEvent) => Promise<BillingEventResult>) | undefined {\n return this.handlerMap[eventType];\n }\n\n invalidateOfferCache(): void {\n this.offerCache.clear();\n }\n\n async updateCheckoutIntentFromEvent(\n event: BillingEvent,\n status: \"completed\" | \"failed\" | \"expired\",\n ): Promise<void> {\n const intentId = event.metadata?.checkout_intent_id;\n if (typeof intentId !== \"string\" || !intentId) return;\n await this.store.updateCheckoutIntent(intentId, { status });\n }\n\n /**\n * Resolve userId from the event, mutating event.userId so that\n * routeEvent's blanket fireEventCallback can read it. Each ingestBillingEvent\n * call creates a fresh event object, so mutation is safe.\n */\n private async resolveUserId(event: BillingEvent): Promise<string | null> {\n if (event.userId) return event.userId;\n if (event.customer?.providerCustomerId) {\n const uid = await this.store.getBillingCustomer(\n event.provider,\n event.customer.providerCustomerId,\n );\n if (uid) {\n event.userId = uid;\n return uid;\n }\n }\n if (this.resolveUser && event.customer?.providerCustomerId) {\n const uid = this.resolveUser(\n event.provider,\n event.customer.providerCustomerId,\n event.customer.email ?? null,\n );\n if (uid) {\n event.userId = uid;\n return uid;\n }\n }\n if (event.subscription?.providerSubscriptionId) {\n const existing = await this.store.getBillingSubscription(\n event.provider,\n event.subscription.providerSubscriptionId,\n );\n if (existing?.userId) {\n event.userId = existing.userId;\n return existing.userId;\n }\n }\n const providerPaymentId =\n event.payment?.providerPaymentId ??\n event.refund?.providerPaymentId ??\n event.dispute?.providerPaymentId ??\n null;\n if (providerPaymentId) {\n const payment = await this.store.getBillingPayment(event.provider, providerPaymentId);\n if (typeof payment?.userId === \"string\") {\n event.userId = payment.userId;\n return payment.userId;\n }\n }\n return null;\n }\n\n private async resolveBillingOfferCached(\n provider: string,\n productId: string | null,\n priceId: string | null,\n ): Promise<BillingOfferResult | null> {\n const cacheKey = `${provider}:${productId ?? \"\"}:${priceId ?? \"\"}`;\n const result = await this.offerCache.fetch(cacheKey, {\n context: { provider, productId, priceId },\n });\n return result?.offer ?? null;\n }\n\n private async handleCustomerCreated(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handleCustomerCreated\", {\n provider: event.provider,\n customerId: event.customer?.providerCustomerId,\n });\n if (event.customer?.providerCustomerId) {\n const uid = await this.resolveUserId(event);\n if (uid) {\n await this.store.upsertBillingCustomer(\n event.provider,\n event.customer.providerCustomerId,\n uid,\n event.customer.email ?? null,\n );\n }\n }\n return { handled: true, action: \"customer_created\" };\n }\n\n private async handleCustomerDeleted(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handleCustomerDeleted\", {\n provider: event.provider,\n customerId: event.customer?.providerCustomerId,\n });\n if (event.customer?.providerCustomerId) {\n const uid = await this.resolveUserId(event);\n if (uid && this.provisioning) {\n await this.revokeSubscription(uid);\n }\n }\n return { handled: true, action: \"customer_deleted\" };\n }\n\n private async handleCheckoutCompleted(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handleCheckoutCompleted\", {\n provider: event.provider,\n eventId: event.eventId,\n hasUserId: Boolean(event.userId),\n });\n if (event.customer?.providerCustomerId) {\n const uid = await this.resolveUserId(event);\n if (uid) {\n await this.store.upsertBillingCustomer(\n event.provider,\n event.customer.providerCustomerId,\n uid,\n event.customer.email ?? null,\n );\n }\n }\n if (event.subscription?.providerSubscriptionId) {\n return this.handleSubscriptionCreated(event);\n }\n await this.updateCheckoutIntentFromEvent(event, \"completed\");\n return { handled: true, action: \"checkout_completed\" };\n }\n\n private async getExistingSubscription(\n event: BillingEvent,\n ): Promise<BillingSubscriptionState | null> {\n if (!event.subscription?.providerSubscriptionId) return null;\n return this.store.getBillingSubscription(\n event.provider,\n event.subscription.providerSubscriptionId,\n );\n }\n\n private buildSubscriptionState(\n event: BillingEvent,\n userId: string,\n existing: BillingSubscriptionState | null,\n overrides?: {\n status?: BillingSubscriptionStatus | null;\n cancelAtPeriodEnd?: boolean | null;\n offerKey?: string | null;\n offerId?: string | null;\n plan?: string | null;\n interval?: string | null;\n intervalCount?: number | null;\n metadata?: Record<string, unknown> | null;\n graceEndsAt?: string | null;\n graceExpiredAt?: string | null;\n },\n ): BillingSubscriptionState {\n if (!event.subscription) {\n throw new TypeError(\"billing subscription event requires subscription data\");\n }\n const sub = event.subscription;\n const status = overrides?.status ?? sub.status ?? existing?.status ?? \"incomplete\";\n return {\n userId,\n provider: event.provider,\n providerSubscriptionId: sub.providerSubscriptionId,\n providerCustomerId:\n event.customer?.providerCustomerId ?? existing?.providerCustomerId ?? null,\n offerId: overrides?.offerId ?? existing?.offerId ?? null,\n offerKey: overrides?.offerKey ?? existing?.offerKey ?? null,\n plan: overrides?.plan ?? existing?.plan ?? null,\n status,\n currentPeriodStart: sub.periodStart ?? existing?.currentPeriodStart ?? null,\n currentPeriodEnd: sub.periodEnd ?? existing?.currentPeriodEnd ?? null,\n trialEnd: sub.trialEnd ?? existing?.trialEnd ?? null,\n cancelAt: sub.cancelAt ?? existing?.cancelAt ?? null,\n endedAt: sub.endedAt ?? existing?.endedAt ?? null,\n graceEndsAt:\n status === \"past_due\" ? (overrides?.graceEndsAt ?? existing?.graceEndsAt ?? null) : null,\n graceExpiredAt:\n status === \"past_due\"\n ? (overrides?.graceExpiredAt ?? existing?.graceExpiredAt ?? null)\n : null,\n providerUpdatedAt: event.occurredAt,\n cancelAtPeriodEnd:\n overrides?.cancelAtPeriodEnd ??\n sub.cancelAtPeriodEnd ??\n existing?.cancelAtPeriodEnd ??\n false,\n interval:\n overrides?.interval ??\n sub.interval ??\n (event.metadata?.billing_interval as string | undefined) ??\n existing?.interval ??\n null,\n intervalCount:\n overrides?.intervalCount ?? sub.intervalCount ?? existing?.intervalCount ?? null,\n metadata:\n overrides?.metadata ??\n (event.metadata || existing?.metadata\n ? { ...(existing?.metadata ?? {}), ...(event.metadata ?? {}) }\n : null),\n };\n }\n\n private async resolveOfferAndKeys(event: BillingEvent): Promise<{\n offer: BillingOfferResult | null;\n offerId: string | null;\n offerKey: string | null;\n plan: string | null;\n }> {\n const refs = event.subscription?.refs;\n if (!refs) return { offer: null, offerId: null, offerKey: null, plan: null };\n\n // Tier 1: Resolve by price/product ID\n const offer = await this.resolveBillingOfferCached(\n event.provider,\n refs.productId ?? null,\n refs.priceId ?? null,\n );\n if (offer) {\n return {\n offer,\n offerId: offer.offerId,\n offerKey: (offer?.offerKey as string | null) ?? null,\n plan: (offer?.plan as string | null) ?? null,\n };\n }\n\n // Tier 2: Resolve by lookup_key\n if (refs.lookupKey) {\n const lookupOffer = await this.store.resolveBillingOfferByLookup(\n event.provider,\n refs.lookupKey,\n );\n if (lookupOffer) {\n return {\n offer: lookupOffer,\n offerId: lookupOffer.offerId,\n offerKey: (lookupOffer?.offerKey as string | null) ?? null,\n plan: (lookupOffer?.plan as string | null) ?? null,\n };\n }\n\n this.logger.error(\n `[BillingService] resolveOfferAndKeys: no offer found for ${event.provider}/${refs.lookupKey}`,\n );\n }\n\n return { offer: null, offerId: null, offerKey: null, plan: null };\n }\n\n private async handleSubscriptionCreated(event: BillingEvent): Promise<BillingEventResult> {\n const uid = await this.resolveUserId(event);\n this.logger.info(\"[BillingService] handleSubscriptionCreated\", {\n eventId: event.eventId,\n provider: event.provider,\n hasUserId: Boolean(uid),\n });\n if (!uid) return { handled: false, error: \"user_not_found\" };\n if (event.customer?.providerCustomerId) {\n await this.store.upsertBillingCustomer(\n event.provider,\n event.customer.providerCustomerId,\n uid,\n event.customer.email ?? null,\n );\n }\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const subscriptionId = event.subscription.providerSubscriptionId;\n const existing = await this.getExistingSubscription(event);\n const blockingStatuses = new Set([\"active\", \"trialing\", \"past_due\", \"incomplete\"]);\n const existingForProvider = (await this.store.getUserSubscriptions(uid)).find(\n (candidate) =>\n candidate.provider === event.provider &&\n candidate.providerSubscriptionId !== subscriptionId &&\n blockingStatuses.has(candidate.status ?? \"\"),\n );\n if (existingForProvider) {\n await this.store.recordSubscriptionConflict({\n userId: uid,\n provider: event.provider,\n duplicateSubscriptionId: subscriptionId,\n existingSubscriptionId: existingForProvider.providerSubscriptionId,\n eventId: event.eventId,\n metadata: event.metadata ?? {},\n });\n return { handled: false, error: \"subscription_conflict\" };\n }\n const { offer, offerId, offerKey, plan } = await this.resolveOfferAndKeys(event);\n this.logger.debug(\"[BillingService] resolveOfferAndKeys\", {\n offerKey,\n plan,\n eventId: event.eventId,\n });\n const subscriptionState = this.buildSubscriptionState(event, uid, existing, {\n status: event.subscription.status ?? \"incomplete\",\n cancelAtPeriodEnd: event.subscription.cancelAtPeriodEnd ?? false,\n offerKey: offerKey ?? existing?.offerKey ?? null,\n offerId: offerId ?? existing?.offerId ?? null,\n plan: plan ?? existing?.plan ?? null,\n interval: offer?.interval,\n intervalCount: offer?.intervalCount,\n });\n try {\n this.logger.debug(\"[BillingService] upserting subscription\", {\n plan: subscriptionState.plan,\n eventId: event.eventId,\n });\n await this.store.upsertBillingSubscription(subscriptionState);\n } catch (error) {\n // The partial unique index is the final arbiter under concurrent\n // webhooks. Convert its race loser into the same manual-review path as\n // the preflight check instead of retrying a permanently invalid event.\n const code = (error as { code?: string }).code;\n if (code !== \"23505\") throw error;\n const concurrent = (await this.store.getUserSubscriptions(uid)).find(\n (candidate) =>\n candidate.provider === event.provider &&\n candidate.providerSubscriptionId !== subscriptionId &&\n blockingStatuses.has(candidate.status ?? \"\"),\n );\n if (!concurrent) throw error;\n await this.store.recordSubscriptionConflict({\n userId: uid,\n provider: event.provider,\n duplicateSubscriptionId: subscriptionId,\n existingSubscriptionId: concurrent.providerSubscriptionId,\n eventId: event.eventId,\n metadata: event.metadata ?? {},\n });\n return { handled: false, error: \"subscription_conflict\" };\n }\n if (\n this.provisioning &&\n event.subscription.status &&\n [\"active\", \"trialing\"].includes(event.subscription.status)\n ) {\n await this.provisionSubscription(uid, offer, event);\n }\n if ([\"active\", \"trialing\"].includes(event.subscription.status ?? \"\")) {\n await this.updateCheckoutIntentFromEvent(event, \"completed\");\n }\n return { handled: true, action: \"subscription_created\" };\n }\n\n private async handleSubscriptionUpdated(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handleSubscriptionUpdated\", {\n provider: event.provider,\n eventId: event.eventId,\n subId: event.subscription?.providerSubscriptionId,\n });\n const uid = await this.resolveUserId(event);\n if (!uid) return { handled: false, error: \"user_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n const { offer, offerId, offerKey, plan } = await this.resolveOfferAndKeys(event);\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: event.subscription.status ?? existing?.status ?? \"incomplete\",\n cancelAtPeriodEnd:\n event.subscription.cancelAtPeriodEnd ?? existing?.cancelAtPeriodEnd ?? false,\n offerKey: offerKey ?? existing?.offerKey ?? null,\n offerId: offerId ?? existing?.offerId ?? null,\n plan: plan ?? existing?.plan ?? null,\n interval: offer?.interval,\n intervalCount: offer?.intervalCount,\n }),\n );\n if (this.provisioning) {\n await this.reEvaluateAccess(uid, event);\n }\n return { handled: true, action: \"subscription_updated\" };\n }\n\n private async handleSubscriptionActivated(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handleSubscriptionActivated\", {\n provider: event.provider,\n eventId: event.eventId,\n });\n const uid = await this.resolveUserId(event);\n if (!uid) return { handled: false, error: \"user_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n const { offer, offerId, offerKey, plan } = await this.resolveOfferAndKeys(event);\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: \"active\",\n offerKey: offerKey ?? existing?.offerKey ?? null,\n offerId: offerId ?? existing?.offerId ?? null,\n plan: plan ?? existing?.plan ?? null,\n interval: offer?.interval,\n intervalCount: offer?.intervalCount,\n }),\n );\n if (this.provisioning) {\n await this.provisionSubscription(uid, offer, event);\n }\n return { handled: true, action: \"subscription_activated\" };\n }\n\n private async handleSubscriptionRenewed(event: BillingEvent): Promise<BillingEventResult> {\n const uid = await this.resolveUserId(event);\n if (!uid) return { handled: false, error: \"user_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n const { offer, offerId, offerKey, plan } = await this.resolveOfferAndKeys(event);\n const resolvedPlanKey = plan ?? existing?.plan ?? null;\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: \"active\",\n offerKey: offerKey ?? existing?.offerKey ?? null,\n offerId: offerId ?? existing?.offerId ?? null,\n plan: resolvedPlanKey,\n interval: offer?.interval,\n intervalCount: offer?.intervalCount,\n }),\n );\n if (this.provisioning && resolvedPlanKey) {\n await this.provisionSubscription(uid, offer, event);\n }\n await this.grantSubscriptionCycle(event, offer);\n return { handled: true, action: \"subscription_renewed\" };\n }\n\n private async handleSubscriptionPlanChanged(event: BillingEvent): Promise<BillingEventResult> {\n const uid = await this.resolveUserId(event);\n if (!uid) return { handled: false, error: \"user_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n const { offer, offerId, offerKey, plan } = await this.resolveOfferAndKeys(event);\n // Capture the current allowance anchor before advancing the durable\n // change. The Postgres transition updates the assignment atomically, so\n // reading it afterwards would return the new assignment's timestamp and\n // silently reset the learner's current allowance window.\n const preservedAllowanceAnchor = this.provisioning?.getUserPlan\n ? ((await this.provisioning.getUserPlan(uid))?.planAssignedAt ?? null)\n : undefined;\n const pending = await this.store.getOpenBillingSubscriptionChange(\n event.provider,\n event.subscription.providerSubscriptionId,\n );\n if (pending) {\n await this.store.updateBillingSubscriptionChange(pending.id, {\n state: \"applied\",\n });\n }\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: event.subscription.status ?? \"active\",\n offerKey: offerKey ?? existing?.offerKey ?? null,\n offerId: offerId ?? existing?.offerId ?? null,\n plan: plan ?? existing?.plan ?? null,\n interval: offer?.interval,\n intervalCount: offer?.intervalCount,\n metadata: {\n ...(existing?.metadata ?? {}),\n ...(event.metadata ?? {}),\n pendingPlanChange: null,\n },\n }),\n );\n if (this.provisioning && (plan ?? existing?.plan)) {\n // Plan-change: prefer new plan over existing (renewal at L422 correctly keeps existing).\n await this.provisionSubscription(\n uid,\n offer,\n event,\n plan ?? existing?.plan ?? undefined,\n true,\n preservedAllowanceAnchor,\n );\n }\n return { handled: true, action: \"subscription_plan_changed\" };\n }\n\n private async handleCancellationScheduled(event: BillingEvent): Promise<BillingEventResult> {\n const uid = await this.resolveUserId(event);\n if (!uid) return { handled: false, error: \"user_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: existing?.status ?? event.subscription.status ?? \"active\",\n cancelAtPeriodEnd: true,\n }),\n );\n return { handled: true, action: \"cancellation_scheduled\" };\n }\n\n private async handleCancellationUnscheduled(event: BillingEvent): Promise<BillingEventResult> {\n const uid = await this.resolveUserId(event);\n if (!uid) return { handled: false, error: \"user_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: existing?.status ?? event.subscription.status ?? \"active\",\n cancelAtPeriodEnd: false,\n }),\n );\n return { handled: true, action: \"cancellation_unscheduled\" };\n }\n\n private async handleSubscriptionCanceled(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handleSubscriptionCanceled\", {\n provider: event.provider,\n eventId: event.eventId,\n });\n const uid = await this.resolveUserId(event);\n if (!uid) return { handled: false, error: \"user_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n const resolved = existing ? null : await this.resolveOfferAndKeys(event);\n if (!existing && !resolved?.offerId) {\n throw new StoreError(\n `cannot persist cancellation for unknown subscription ${event.provider}/${event.subscription.providerSubscriptionId}: offer could not be resolved`,\n {\n retryable: true,\n details: {\n provider: event.provider,\n providerSubscriptionId: event.subscription.providerSubscriptionId,\n },\n },\n );\n }\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: \"canceled\",\n cancelAtPeriodEnd: event.subscription.cancelAtPeriodEnd ?? true,\n offerKey: resolved?.offerKey ?? existing?.offerKey ?? null,\n offerId: resolved?.offerId ?? existing?.offerId ?? null,\n plan: resolved?.plan ?? existing?.plan ?? null,\n interval: resolved?.offer?.interval,\n intervalCount: resolved?.offer?.intervalCount,\n }),\n );\n if (this.provisioning) {\n await this.revokeIfCurrentSubscription(uid, event.subscription.providerSubscriptionId);\n }\n return { handled: true, action: \"subscription_canceled\" };\n }\n\n private async handleSubscriptionExpired(event: BillingEvent): Promise<BillingEventResult> {\n const uid = await this.resolveUserId(event);\n if (!uid) return { handled: false, error: \"user_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: \"expired\",\n cancelAtPeriodEnd: event.subscription.cancelAtPeriodEnd ?? true,\n }),\n );\n if (this.provisioning) {\n await this.revokeIfCurrentSubscription(uid, event.subscription.providerSubscriptionId);\n }\n return { handled: true, action: \"subscription_expired\" };\n }\n\n private async handleSubscriptionPaused(event: BillingEvent): Promise<BillingEventResult> {\n const uid = await this.resolveUserId(event);\n if (!uid) return { handled: false, error: \"user_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: \"paused\",\n cancelAtPeriodEnd: existing?.cancelAtPeriodEnd ?? false,\n }),\n );\n if (this.provisioning) {\n await this.revokeIfCurrentSubscription(uid, event.subscription.providerSubscriptionId);\n }\n return { handled: true, action: \"subscription_paused\" };\n }\n\n private async handleSubscriptionResumed(event: BillingEvent): Promise<BillingEventResult> {\n const uid = await this.resolveUserId(event);\n if (!uid) return { handled: false, error: \"user_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n const { offer, offerKey, plan } = await this.resolveOfferAndKeys(event);\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: \"active\",\n cancelAtPeriodEnd: false,\n offerKey: offerKey ?? existing?.offerKey ?? null,\n plan: plan ?? existing?.plan ?? null,\n }),\n );\n if (this.provisioning) {\n await this.provisionSubscription(uid, offer, event);\n }\n return { handled: true, action: \"subscription_resumed\" };\n }\n\n private async handleTrialWillEnd(event: BillingEvent): Promise<BillingEventResult> {\n // Resolve userId so routeEvent's blanket fireEventCallback has a useful value.\n await this.resolveUserId(event);\n return { handled: true, action: \"trial_will_end_notified\" };\n }\n\n private async provisionSubscription(\n uid: string,\n offer: BillingOfferResult | null,\n event: BillingEvent,\n planKeyOverride?: string,\n preserveAllowanceAnchor = false,\n preservedAllowanceAnchor?: Date | string | null,\n ): Promise<void> {\n if (!this.provisioning) {\n this.logger.debug(\n `[BillingService] provisionSubscription: no provisioning capability for user ${uid}`,\n );\n return;\n }\n const plan = planKeyOverride ?? offer?.plan;\n if (!plan) {\n this.logger.debug(\"[BillingService] provisionSubscription skipped (no plan)\", { uid });\n return;\n }\n this.logger.debug(\"[BillingService] provisionSubscription setting plan\", { uid, plan });\n let periodStart: Date | string | null | undefined;\n if (preserveAllowanceAnchor) {\n const existingAnchor =\n preservedAllowanceAnchor !== undefined\n ? preservedAllowanceAnchor\n : this.provisioning.getUserPlan\n ? (await this.provisioning.getUserPlan(uid))?.planAssignedAt\n : undefined;\n if (existingAnchor) {\n const anchor = new Date(existingAnchor);\n // A provider's subscription period start may actually be its next\n // renewal date. Never let a future anchor hide an already-active\n // entitlement after a plan change.\n if (!Number.isNaN(anchor.getTime()) && anchor.getTime() <= Date.now()) {\n periodStart = anchor;\n }\n }\n } else {\n periodStart = event.subscription?.periodStart;\n }\n const planAssignedAt = periodStart\n ? (() => {\n const d = new Date(periodStart);\n return Number.isNaN(d.getTime()) ? undefined : d;\n })()\n : preserveAllowanceAnchor\n ? new Date()\n : undefined;\n await this.provisioning.setUserPlan(uid, plan, planAssignedAt);\n\n if (this.autoSelectEntitlementSource && event.provider) {\n const selected = await this.store.selectSubscriptionEntitlementSource(\n uid,\n event.provider,\n event.subscription?.providerSubscriptionId,\n );\n if (selected) {\n this.logger.debug(\n `[BillingService] selected ${event.provider} subscription as entitlement source for user ${uid}`,\n );\n }\n }\n }\n\n private async grantSubscriptionCycle(\n event: BillingEvent,\n offer: BillingOfferResult | null,\n ): Promise<void> {\n const credits = offer?.grant?.mode === \"cycle_grant\" ? offer.grant.credits : null;\n if (!credits || credits.lte(0) || !event.billingEventId || !event.subscription) return;\n\n const subscription = await this.store.getBillingSubscription(\n event.provider,\n event.subscription.providerSubscriptionId,\n );\n if (!subscription?.subscriptionId) {\n throw new StoreError(\"subscription cycle grant requires a persisted subscription\", {\n indeterminate: true,\n details: {\n provider: event.provider,\n providerSubscriptionId: event.subscription.providerSubscriptionId,\n },\n });\n }\n const payment =\n event.payment?.providerPaymentId != null\n ? await this.store.getBillingPayment(event.provider, event.payment.providerPaymentId)\n : null;\n const grantId = await this.store.createBillingCreditGrant({\n paymentId: payment?.id == null ? null : String(payment.id),\n subscriptionId: subscription.subscriptionId,\n configuredCredits: credits,\n quantity: 1,\n billingEventId: event.billingEventId,\n });\n await this.store.grantBillingCredit(grantId, `billing:${event.eventId}:subscription-cycle`);\n }\n\n private async revokeSubscription(uid: string): Promise<void> {\n if (!this.provisioning) return;\n if (this.terminalPlanKey) {\n await this.provisioning.setUserPlan(uid, this.terminalPlanKey);\n return;\n }\n await this.provisioning.unsetUserPlan(uid);\n }\n\n /**\n * Do not revoke access because a stale subscription record ended while a\n * newer subscription for the same user is still active.\n */\n async revokeIfCurrentSubscription(uid: string, subscriptionId: string): Promise<void> {\n const current = await this.store.getUserSubscription(uid, [\"active\", \"trialing\", \"past_due\"]);\n if (!current || current.providerSubscriptionId === subscriptionId) {\n await this.revokeSubscription(uid);\n }\n }\n\n private async reEvaluateAccess(uid: string, event: BillingEvent): Promise<void> {\n if (!this.provisioning || !event.subscription) return;\n const status = event.subscription.status;\n // Provider retries (Stripe past_due, Dodo on_hold mapped to past_due)\n // are a grace period. Keep the last paid entitlements until the provider\n // reaches a terminal state instead of revoking access on the first miss.\n if (status && [\"active\", \"trialing\"].includes(status)) {\n const offer = await this.resolveOfferFromEvent(event);\n if (offer) {\n await this.provisionSubscription(uid, offer, event);\n } else {\n const existing = await this.store.getBillingSubscription(\n event.provider,\n event.subscription.providerSubscriptionId,\n );\n if (existing?.plan) {\n await this.provisionSubscription(uid, null, event, existing.plan);\n }\n }\n } else if (status === \"past_due\") {\n const existing = await this.store.getBillingSubscription(\n event.provider,\n event.subscription.providerSubscriptionId,\n );\n const graceHasExpired =\n Boolean(existing?.graceExpiredAt) ||\n (Boolean(existing?.graceEndsAt) &&\n new Date(existing!.graceEndsAt!).getTime() <= Date.now());\n if (graceHasExpired) {\n await this.revokeIfCurrentSubscription(uid, event.subscription.providerSubscriptionId);\n } else {\n const offer = await this.resolveOfferFromEvent(event);\n if (offer) {\n await this.provisionSubscription(uid, offer, event);\n } else if (existing?.plan) {\n await this.provisionSubscription(uid, null, event, existing.plan);\n }\n }\n } else if (\n status &&\n [\"canceled\", \"expired\", \"unpaid\", \"paused\", \"incomplete_expired\"].includes(status)\n ) {\n await this.revokeIfCurrentSubscription(uid, event.subscription.providerSubscriptionId);\n }\n }\n\n private async resolveOfferFromEvent(event: BillingEvent): Promise<BillingOfferResult | null> {\n const refs = event.subscription?.refs;\n if (!refs) return null;\n return this.resolveBillingOfferCached(\n event.provider,\n refs.productId ?? null,\n refs.priceId ?? null,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"event-handlers.js","sourceRoot":"","sources":["../../src/billing/event-handlers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAStD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,6BAA6B,EAAE,MAAM,+BAA+B,CAAC;AAC9E,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAa1C,MAAM,OAAO,oBAAoB;IAeZ;IAdF,YAAY,CAAiC;IAC7C,2BAA2B,CAAU;IACrC,oBAAoB,CAAS;IAC7B,eAAe,CAAgB;IAC/B,MAAM,CAAmB;IACzB,UAAU,CAAkD;IAC5D,SAAS,CAAgC;IACzC,UAAU,CAAuE;IAElG,IAAI,eAAe;QACjB,OAAO,IAAI,CAAC,YAAY,KAAK,IAAI,CAAC;IACpC,CAAC;IAED,YACmB,KAAmB,EACpC,OAA+B;Q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AAE,KAAK,CAAC,YAAY,CAAC,sBAAsB,CAAC,CAAC;YACzF,CAAC;iBAAM,CAAC;gBACN,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,qBAAqB,CAAC,KAAK,CAAC,CAAC;gBACtD,IAAI,KAAK,EAAE,CAAC;oBACV,MAAM,IAAI,CAAC,qBAAqB,CAAC,GAAG,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;gBACtD,CAAC;qBAAM,IAAI,QAAQ,EAAE,IAAI,EAAE,CAAC;oBAC1B,MAAM,IAAI,CAAC,qBAAqB,CAAC,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC;gBACpE,CAAC;YACH,CAAC;QACH,CAAC;aAAM,IACL,MAAM;YACN,CAAC,UAAU,EAAE,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,oBAAoB,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,EAClF,CAAC;YACD,MAAM,IAAI,CAAC,2BAA2B,CAAC,GAAG,EAAE,KAAK,CAAC,YAAY,CAAC,sBAAsB,CAAC,CAAC;QACzF,CAAC;IACH,CAAC;IAEO,KAAK,CAAC,qBAAqB,CAAC,KAAmB;QACrD,MAAM,IAAI,GAAG,KAAK,CAAC,YAAY,EAAE,IAAI,CAAC;QACtC,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QACvB,OAAO,IAAI,CAAC,yBAAyB,CACnC,KAAK,CAAC,QAAQ,EACd,IAAI,CAAC,SAAS,IAAI,IAAI,EACtB,IAAI,CAAC,OAAO,IAAI,IAAI,CACrB,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { LRUCache } from \"lru-cache\";\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport { normalizeLogger } from \"../shared/logger.js\";\nimport type { BillingStore } from \"./billing-store.js\";\nimport type {\n BillingEvent,\n BillingEventResult,\n BillingOfferResult,\n BillingSubscriptionState,\n BillingSubscriptionStatus,\n} from \"./types/index.js\";\nimport { BillingEventType } from \"./types/index.js\";\nimport { BillingFinancialEventHandlers } from \"./financial-event-handlers.js\";\nimport { StoreError } from \"../errors.js\";\nimport type { BillingProvisioningPort, BillingServiceOptions } from \"./service-types.js\";\n\ninterface OfferCacheValue {\n offer: BillingOfferResult | null;\n}\n\ninterface OfferContext {\n provider: string;\n productId: string | null;\n priceId: string | null;\n}\n\nexport class BillingEventHandlers {\n private readonly provisioning: BillingProvisioningPort | null;\n private readonly autoSelectEntitlementSource: boolean;\n private readonly pastDueGracePeriodMs: number;\n private readonly terminalPlanKey: string | null;\n private readonly logger: NormalizedLogger;\n private readonly offerCache: LRUCache<string, OfferCacheValue, OfferContext>;\n private readonly financial: BillingFinancialEventHandlers;\n private readonly handlerMap: Record<string, (event: BillingEvent) => Promise<BillingEventResult>>;\n\n get hasProvisioning(): boolean {\n return this.provisioning !== null;\n }\n\n constructor(\n private readonly store: BillingStore,\n options?: BillingServiceOptions,\n ) {\n this.provisioning = options?.provisioning ?? null;\n this.autoSelectEntitlementSource = options?.autoSelectEntitlementSource ?? true;\n this.pastDueGracePeriodMs = options?.pastDueGracePeriodMs ?? 7 * 24 * 60 * 60 * 1000;\n if (!Number.isFinite(this.pastDueGracePeriodMs) || this.pastDueGracePeriodMs < 0) {\n throw new RangeError(\"pastDueGracePeriodMs must be a finite non-negative number\");\n }\n this.terminalPlanKey = options?.terminalPlanKey ?? null;\n this.logger = normalizeLogger(options?.logger);\n this.offerCache = new LRUCache<string, OfferCacheValue, OfferContext>({\n max: 100,\n ttl: 60_000,\n allowStale: false,\n fetchMethod: async (_, __, { context }) => {\n const offer = await this.store.resolveBillingOffer(\n context.provider,\n context.productId,\n context.priceId,\n );\n return { offer };\n },\n });\n this.financial = new BillingFinancialEventHandlers(\n store,\n this.logger,\n this.pastDueGracePeriodMs,\n (event) => this.resolveAccountId(event),\n (event) => this.handleSubscriptionRenewed(event),\n (event, status) => this.updateCheckoutIntentFromEvent(event, status),\n (event) => this.getExistingSubscription(event),\n (event, userId, existing, overrides) =>\n this.buildSubscriptionState(event, userId, existing, overrides),\n );\n this.handlerMap = {\n [BillingEventType.CUSTOMER_CREATED]: this.handleCustomerCreated.bind(this),\n [BillingEventType.CUSTOMER_UPDATED]: this.handleCustomerCreated.bind(this),\n [BillingEventType.CUSTOMER_DELETED]: this.handleCustomerDeleted.bind(this),\n [BillingEventType.CHECKOUT_COMPLETED]: this.handleCheckoutCompleted.bind(this),\n [BillingEventType.SUBSCRIPTION_CREATED]: this.handleSubscriptionCreated.bind(this),\n [BillingEventType.SUBSCRIPTION_UPDATED]: this.handleSubscriptionUpdated.bind(this),\n [BillingEventType.SUBSCRIPTION_ACTIVATED]: this.handleSubscriptionActivated.bind(this),\n [BillingEventType.SUBSCRIPTION_RENEWED]: this.handleSubscriptionRenewed.bind(this),\n [BillingEventType.SUBSCRIPTION_PLAN_CHANGED]: this.handleSubscriptionPlanChanged.bind(this),\n [BillingEventType.SUBSCRIPTION_CANCELLATION_SCHEDULED]:\n this.handleCancellationScheduled.bind(this),\n [BillingEventType.SUBSCRIPTION_CANCELLATION_UNSCHEDULED]:\n this.handleCancellationUnscheduled.bind(this),\n [BillingEventType.SUBSCRIPTION_CANCELED]: this.handleSubscriptionCanceled.bind(this),\n [BillingEventType.SUBSCRIPTION_EXPIRED]: this.handleSubscriptionExpired.bind(this),\n [BillingEventType.SUBSCRIPTION_PAUSED]: this.handleSubscriptionPaused.bind(this),\n [BillingEventType.SUBSCRIPTION_RESUMED]: this.handleSubscriptionResumed.bind(this),\n [BillingEventType.SUBSCRIPTION_TRIAL_WILL_END]: this.handleTrialWillEnd.bind(this),\n [BillingEventType.INVOICE_PAID]: this.financial.handleInvoicePaid.bind(this.financial),\n [BillingEventType.PAYMENT_SUCCEEDED]: this.financial.handlePaymentSucceeded.bind(\n this.financial,\n ),\n [BillingEventType.PAYMENT_FAILED]: this.financial.handlePaymentFailed.bind(this.financial),\n [BillingEventType.REFUND_CREATED]: this.financial.handleRefundCreated.bind(this.financial),\n [BillingEventType.REFUND_UPDATED]: this.financial.handleRefundCreated.bind(this.financial),\n [BillingEventType.REFUND_FAILED]: this.financial.handleRefundCreated.bind(this.financial),\n [BillingEventType.DISPUTE_CREATED]: this.financial.handleDisputeCreated.bind(this.financial),\n [BillingEventType.DISPUTE_CLOSED]: this.financial.handleDisputeClosed.bind(this.financial),\n };\n }\n\n getHandler(\n eventType: BillingEventType,\n ): ((event: BillingEvent) => Promise<BillingEventResult>) | undefined {\n return this.handlerMap[eventType];\n }\n\n invalidateOfferCache(): void {\n this.offerCache.clear();\n }\n\n async updateCheckoutIntentFromEvent(\n event: BillingEvent,\n status: \"completed\" | \"failed\" | \"expired\",\n ): Promise<void> {\n const intentId = event.metadata?.checkout_intent_id;\n if (typeof intentId !== \"string\" || !intentId) return;\n await this.store.updateCheckoutIntent(intentId, { status });\n }\n\n /**\n * Resolve accountId from the event, mutating event.accountId so that\n * routeEvent's blanket fireEventCallback can read it. Each ingestBillingEvent\n * call creates a fresh event object, so mutation is safe.\n */\n private async resolveAccountId(event: BillingEvent): Promise<string | null> {\n if (event.accountId) return event.accountId;\n if (event.customer?.providerCustomerId) {\n const uid = await this.store.getBillingCustomer(\n event.provider,\n event.customer.providerCustomerId,\n );\n if (uid) {\n event.accountId = uid;\n return uid;\n }\n }\n if (event.subscription?.providerSubscriptionId) {\n const existing = await this.store.getBillingSubscription(\n event.provider,\n event.subscription.providerSubscriptionId,\n );\n if (existing?.userId) {\n event.accountId = existing.userId;\n return existing.userId;\n }\n }\n const providerPaymentId =\n event.payment?.providerPaymentId ??\n event.refund?.providerPaymentId ??\n event.dispute?.providerPaymentId ??\n null;\n if (providerPaymentId) {\n const payment = await this.store.getBillingPayment(event.provider, providerPaymentId);\n if (typeof payment?.userId === \"string\") {\n event.accountId = payment.userId;\n return payment.userId;\n }\n }\n return null;\n }\n\n private async resolveBillingOfferCached(\n provider: string,\n productId: string | null,\n priceId: string | null,\n ): Promise<BillingOfferResult | null> {\n const cacheKey = `${provider}:${productId ?? \"\"}:${priceId ?? \"\"}`;\n const result = await this.offerCache.fetch(cacheKey, {\n context: { provider, productId, priceId },\n });\n return result?.offer ?? null;\n }\n\n private async handleCustomerCreated(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handleCustomerCreated\", {\n provider: event.provider,\n customerId: event.customer?.providerCustomerId,\n });\n if (event.customer?.providerCustomerId) {\n const uid = await this.resolveAccountId(event);\n if (uid) {\n await this.store.upsertBillingCustomer(\n event.provider,\n event.customer.providerCustomerId,\n uid,\n event.customer.email ?? null,\n );\n }\n }\n return { handled: true, action: \"customer_created\" };\n }\n\n private async handleCustomerDeleted(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handleCustomerDeleted\", {\n provider: event.provider,\n customerId: event.customer?.providerCustomerId,\n });\n if (event.customer?.providerCustomerId) {\n const uid = await this.resolveAccountId(event);\n if (uid && this.provisioning) {\n await this.revokeSubscription(uid);\n }\n }\n return { handled: true, action: \"customer_deleted\" };\n }\n\n private async handleCheckoutCompleted(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handleCheckoutCompleted\", {\n provider: event.provider,\n eventId: event.eventId,\n hasAccountId: Boolean(event.accountId),\n });\n if (event.customer?.providerCustomerId) {\n const uid = await this.resolveAccountId(event);\n if (uid) {\n await this.store.upsertBillingCustomer(\n event.provider,\n event.customer.providerCustomerId,\n uid,\n event.customer.email ?? null,\n );\n }\n }\n if (event.subscription?.providerSubscriptionId) {\n return this.handleSubscriptionCreated(event);\n }\n await this.updateCheckoutIntentFromEvent(event, \"completed\");\n return { handled: true, action: \"checkout_completed\" };\n }\n\n private async getExistingSubscription(\n event: BillingEvent,\n ): Promise<BillingSubscriptionState | null> {\n if (!event.subscription?.providerSubscriptionId) return null;\n return this.store.getBillingSubscription(\n event.provider,\n event.subscription.providerSubscriptionId,\n );\n }\n\n private buildSubscriptionState(\n event: BillingEvent,\n userId: string,\n existing: BillingSubscriptionState | null,\n overrides?: {\n status?: BillingSubscriptionStatus | null;\n cancelAtPeriodEnd?: boolean | null;\n offerKey?: string | null;\n offerId?: string | null;\n plan?: string | null;\n interval?: string | null;\n intervalCount?: number | null;\n metadata?: Record<string, unknown> | null;\n graceEndsAt?: string | null;\n graceExpiredAt?: string | null;\n },\n ): BillingSubscriptionState {\n if (!event.subscription) {\n throw new TypeError(\"billing subscription event requires subscription data\");\n }\n const sub = event.subscription;\n const status = overrides?.status ?? sub.status ?? existing?.status ?? \"incomplete\";\n return {\n userId,\n provider: event.provider,\n providerSubscriptionId: sub.providerSubscriptionId,\n providerCustomerId:\n event.customer?.providerCustomerId ?? existing?.providerCustomerId ?? null,\n offerId: overrides?.offerId ?? existing?.offerId ?? null,\n offerKey: overrides?.offerKey ?? existing?.offerKey ?? null,\n plan: overrides?.plan ?? existing?.plan ?? null,\n status,\n currentPeriodStart: sub.periodStart ?? existing?.currentPeriodStart ?? null,\n currentPeriodEnd: sub.periodEnd ?? existing?.currentPeriodEnd ?? null,\n trialEnd: sub.trialEnd ?? existing?.trialEnd ?? null,\n cancelAt: sub.cancelAt ?? existing?.cancelAt ?? null,\n endedAt: sub.endedAt ?? existing?.endedAt ?? null,\n graceEndsAt:\n status === \"past_due\" ? (overrides?.graceEndsAt ?? existing?.graceEndsAt ?? null) : null,\n graceExpiredAt:\n status === \"past_due\"\n ? (overrides?.graceExpiredAt ?? existing?.graceExpiredAt ?? null)\n : null,\n providerUpdatedAt: event.occurredAt,\n cancelAtPeriodEnd:\n overrides?.cancelAtPeriodEnd ??\n sub.cancelAtPeriodEnd ??\n existing?.cancelAtPeriodEnd ??\n false,\n interval:\n overrides?.interval ??\n sub.interval ??\n (event.metadata?.billing_interval as string | undefined) ??\n existing?.interval ??\n null,\n intervalCount:\n overrides?.intervalCount ?? sub.intervalCount ?? existing?.intervalCount ?? null,\n metadata:\n overrides?.metadata ??\n (event.metadata || existing?.metadata\n ? { ...(existing?.metadata ?? {}), ...(event.metadata ?? {}) }\n : null),\n };\n }\n\n private async resolveOfferAndKeys(event: BillingEvent): Promise<{\n offer: BillingOfferResult | null;\n offerId: string | null;\n offerKey: string | null;\n plan: string | null;\n }> {\n const refs = event.subscription?.refs;\n if (!refs) return { offer: null, offerId: null, offerKey: null, plan: null };\n\n // Tier 1: Resolve by price/product ID\n const offer = await this.resolveBillingOfferCached(\n event.provider,\n refs.productId ?? null,\n refs.priceId ?? null,\n );\n if (offer) {\n return {\n offer,\n offerId: offer.offerId,\n offerKey: (offer?.offerKey as string | null) ?? null,\n plan: (offer?.plan as string | null) ?? null,\n };\n }\n\n // Tier 2: Resolve by lookup_key\n if (refs.lookupKey) {\n const lookupOffer = await this.store.resolveBillingOfferByLookup(\n event.provider,\n refs.lookupKey,\n );\n if (lookupOffer) {\n return {\n offer: lookupOffer,\n offerId: lookupOffer.offerId,\n offerKey: (lookupOffer?.offerKey as string | null) ?? null,\n plan: (lookupOffer?.plan as string | null) ?? null,\n };\n }\n\n this.logger.error(\n `[BillingService] resolveOfferAndKeys: no offer found for ${event.provider}/${refs.lookupKey}`,\n );\n }\n\n return { offer: null, offerId: null, offerKey: null, plan: null };\n }\n\n private async handleSubscriptionCreated(event: BillingEvent): Promise<BillingEventResult> {\n const uid = await this.resolveAccountId(event);\n this.logger.info(\"[BillingService] handleSubscriptionCreated\", {\n eventId: event.eventId,\n provider: event.provider,\n hasAccountId: Boolean(uid),\n });\n if (!uid) return { handled: false, error: \"account_not_found\" };\n if (event.customer?.providerCustomerId) {\n await this.store.upsertBillingCustomer(\n event.provider,\n event.customer.providerCustomerId,\n uid,\n event.customer.email ?? null,\n );\n }\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const subscriptionId = event.subscription.providerSubscriptionId;\n const existing = await this.getExistingSubscription(event);\n const blockingStatuses = new Set([\"active\", \"trialing\", \"past_due\", \"incomplete\"]);\n const existingForProvider = (await this.store.getUserSubscriptions(uid)).find(\n (candidate) =>\n candidate.provider === event.provider &&\n candidate.providerSubscriptionId !== subscriptionId &&\n blockingStatuses.has(candidate.status ?? \"\"),\n );\n if (existingForProvider) {\n await this.store.recordSubscriptionConflict({\n userId: uid,\n provider: event.provider,\n duplicateSubscriptionId: subscriptionId,\n existingSubscriptionId: existingForProvider.providerSubscriptionId,\n eventId: event.eventId,\n metadata: event.metadata ?? {},\n });\n return { handled: false, error: \"subscription_conflict\" };\n }\n const { offer, offerId, offerKey, plan } = await this.resolveOfferAndKeys(event);\n this.logger.debug(\"[BillingService] resolveOfferAndKeys\", {\n offerKey,\n plan,\n eventId: event.eventId,\n });\n const subscriptionState = this.buildSubscriptionState(event, uid, existing, {\n status: event.subscription.status ?? \"incomplete\",\n cancelAtPeriodEnd: event.subscription.cancelAtPeriodEnd ?? false,\n offerKey: offerKey ?? existing?.offerKey ?? null,\n offerId: offerId ?? existing?.offerId ?? null,\n plan: plan ?? existing?.plan ?? null,\n interval: offer?.interval,\n intervalCount: offer?.intervalCount,\n });\n try {\n this.logger.debug(\"[BillingService] upserting subscription\", {\n plan: subscriptionState.plan,\n eventId: event.eventId,\n });\n await this.store.upsertBillingSubscription(subscriptionState);\n } catch (error) {\n // The partial unique index is the final arbiter under concurrent\n // webhooks. Convert its race loser into the same manual-review path as\n // the preflight check instead of retrying a permanently invalid event.\n const code = (error as { code?: string }).code;\n if (code !== \"23505\") throw error;\n const concurrent = (await this.store.getUserSubscriptions(uid)).find(\n (candidate) =>\n candidate.provider === event.provider &&\n candidate.providerSubscriptionId !== subscriptionId &&\n blockingStatuses.has(candidate.status ?? \"\"),\n );\n if (!concurrent) throw error;\n await this.store.recordSubscriptionConflict({\n userId: uid,\n provider: event.provider,\n duplicateSubscriptionId: subscriptionId,\n existingSubscriptionId: concurrent.providerSubscriptionId,\n eventId: event.eventId,\n metadata: event.metadata ?? {},\n });\n return { handled: false, error: \"subscription_conflict\" };\n }\n if (\n this.provisioning &&\n event.subscription.status &&\n [\"active\", \"trialing\"].includes(event.subscription.status)\n ) {\n await this.provisionSubscription(uid, offer, event);\n }\n if ([\"active\", \"trialing\"].includes(event.subscription.status ?? \"\")) {\n await this.updateCheckoutIntentFromEvent(event, \"completed\");\n }\n return { handled: true, action: \"subscription_created\" };\n }\n\n private async handleSubscriptionUpdated(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handleSubscriptionUpdated\", {\n provider: event.provider,\n eventId: event.eventId,\n subId: event.subscription?.providerSubscriptionId,\n });\n const uid = await this.resolveAccountId(event);\n if (!uid) return { handled: false, error: \"account_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n const { offer, offerId, offerKey, plan } = await this.resolveOfferAndKeys(event);\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: event.subscription.status ?? existing?.status ?? \"incomplete\",\n cancelAtPeriodEnd:\n event.subscription.cancelAtPeriodEnd ?? existing?.cancelAtPeriodEnd ?? false,\n offerKey: offerKey ?? existing?.offerKey ?? null,\n offerId: offerId ?? existing?.offerId ?? null,\n plan: plan ?? existing?.plan ?? null,\n interval: offer?.interval,\n intervalCount: offer?.intervalCount,\n }),\n );\n if (this.provisioning) {\n await this.reEvaluateAccess(uid, event);\n }\n return { handled: true, action: \"subscription_updated\" };\n }\n\n private async handleSubscriptionActivated(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handleSubscriptionActivated\", {\n provider: event.provider,\n eventId: event.eventId,\n });\n const uid = await this.resolveAccountId(event);\n if (!uid) return { handled: false, error: \"account_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n const { offer, offerId, offerKey, plan } = await this.resolveOfferAndKeys(event);\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: \"active\",\n offerKey: offerKey ?? existing?.offerKey ?? null,\n offerId: offerId ?? existing?.offerId ?? null,\n plan: plan ?? existing?.plan ?? null,\n interval: offer?.interval,\n intervalCount: offer?.intervalCount,\n }),\n );\n if (this.provisioning) {\n await this.provisionSubscription(uid, offer, event);\n }\n return { handled: true, action: \"subscription_activated\" };\n }\n\n private async handleSubscriptionRenewed(event: BillingEvent): Promise<BillingEventResult> {\n const uid = await this.resolveAccountId(event);\n if (!uid) return { handled: false, error: \"account_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n const { offer, offerId, offerKey, plan } = await this.resolveOfferAndKeys(event);\n const resolvedPlanKey = plan ?? existing?.plan ?? null;\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: \"active\",\n offerKey: offerKey ?? existing?.offerKey ?? null,\n offerId: offerId ?? existing?.offerId ?? null,\n plan: resolvedPlanKey,\n interval: offer?.interval,\n intervalCount: offer?.intervalCount,\n }),\n );\n if (this.provisioning && resolvedPlanKey) {\n await this.provisionSubscription(uid, offer, event);\n }\n await this.grantSubscriptionCycle(event, offer);\n return { handled: true, action: \"subscription_renewed\" };\n }\n\n private async handleSubscriptionPlanChanged(event: BillingEvent): Promise<BillingEventResult> {\n const uid = await this.resolveAccountId(event);\n if (!uid) return { handled: false, error: \"account_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n const { offer, offerId, offerKey, plan } = await this.resolveOfferAndKeys(event);\n // Capture the current allowance anchor before advancing the durable\n // change. The Postgres transition updates the assignment atomically, so\n // reading it afterwards would return the new assignment's timestamp and\n // silently reset the learner's current allowance window.\n const preservedAllowanceAnchor = this.provisioning\n ? ((await this.provisioning.getUserPlan(uid))?.planAssignedAt ?? null)\n : undefined;\n const pending = await this.store.getOpenBillingSubscriptionChange(\n event.provider,\n event.subscription.providerSubscriptionId,\n );\n if (pending) {\n await this.store.updateBillingSubscriptionChange(pending.id, {\n state: \"applied\",\n });\n }\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: event.subscription.status ?? \"active\",\n offerKey: offerKey ?? existing?.offerKey ?? null,\n offerId: offerId ?? existing?.offerId ?? null,\n plan: plan ?? existing?.plan ?? null,\n interval: offer?.interval,\n intervalCount: offer?.intervalCount,\n metadata: {\n ...(existing?.metadata ?? {}),\n ...(event.metadata ?? {}),\n pendingPlanChange: null,\n },\n }),\n );\n if (this.provisioning && (plan ?? existing?.plan)) {\n // Plan-change: prefer new plan over existing (renewal at L422 correctly keeps existing).\n await this.provisionSubscription(\n uid,\n offer,\n event,\n plan ?? existing?.plan ?? undefined,\n true,\n preservedAllowanceAnchor,\n );\n }\n return { handled: true, action: \"subscription_plan_changed\" };\n }\n\n private async handleCancellationScheduled(event: BillingEvent): Promise<BillingEventResult> {\n const uid = await this.resolveAccountId(event);\n if (!uid) return { handled: false, error: \"account_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: existing?.status ?? event.subscription.status ?? \"active\",\n cancelAtPeriodEnd: true,\n }),\n );\n return { handled: true, action: \"cancellation_scheduled\" };\n }\n\n private async handleCancellationUnscheduled(event: BillingEvent): Promise<BillingEventResult> {\n const uid = await this.resolveAccountId(event);\n if (!uid) return { handled: false, error: \"account_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: existing?.status ?? event.subscription.status ?? \"active\",\n cancelAtPeriodEnd: false,\n }),\n );\n return { handled: true, action: \"cancellation_unscheduled\" };\n }\n\n private async handleSubscriptionCanceled(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handleSubscriptionCanceled\", {\n provider: event.provider,\n eventId: event.eventId,\n });\n const uid = await this.resolveAccountId(event);\n if (!uid) return { handled: false, error: \"account_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n const resolved = existing ? null : await this.resolveOfferAndKeys(event);\n if (!existing && !resolved?.offerId) {\n throw new StoreError(\n `cannot persist cancellation for unknown subscription ${event.provider}/${event.subscription.providerSubscriptionId}: offer could not be resolved`,\n {\n retryable: true,\n details: {\n provider: event.provider,\n providerSubscriptionId: event.subscription.providerSubscriptionId,\n },\n },\n );\n }\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: \"canceled\",\n cancelAtPeriodEnd: event.subscription.cancelAtPeriodEnd ?? true,\n offerKey: resolved?.offerKey ?? existing?.offerKey ?? null,\n offerId: resolved?.offerId ?? existing?.offerId ?? null,\n plan: resolved?.plan ?? existing?.plan ?? null,\n interval: resolved?.offer?.interval,\n intervalCount: resolved?.offer?.intervalCount,\n }),\n );\n if (this.provisioning) {\n await this.revokeIfCurrentSubscription(uid, event.subscription.providerSubscriptionId);\n }\n return { handled: true, action: \"subscription_canceled\" };\n }\n\n private async handleSubscriptionExpired(event: BillingEvent): Promise<BillingEventResult> {\n const uid = await this.resolveAccountId(event);\n if (!uid) return { handled: false, error: \"account_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: \"expired\",\n cancelAtPeriodEnd: event.subscription.cancelAtPeriodEnd ?? true,\n }),\n );\n if (this.provisioning) {\n await this.revokeIfCurrentSubscription(uid, event.subscription.providerSubscriptionId);\n }\n return { handled: true, action: \"subscription_expired\" };\n }\n\n private async handleSubscriptionPaused(event: BillingEvent): Promise<BillingEventResult> {\n const uid = await this.resolveAccountId(event);\n if (!uid) return { handled: false, error: \"account_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: \"paused\",\n cancelAtPeriodEnd: existing?.cancelAtPeriodEnd ?? false,\n }),\n );\n if (this.provisioning) {\n await this.revokeIfCurrentSubscription(uid, event.subscription.providerSubscriptionId);\n }\n return { handled: true, action: \"subscription_paused\" };\n }\n\n private async handleSubscriptionResumed(event: BillingEvent): Promise<BillingEventResult> {\n const uid = await this.resolveAccountId(event);\n if (!uid) return { handled: false, error: \"account_not_found\" };\n if (!event.subscription?.providerSubscriptionId)\n return { handled: false, error: \"no_subscription_data\" };\n const existing = await this.getExistingSubscription(event);\n const { offer, offerKey, plan } = await this.resolveOfferAndKeys(event);\n await this.store.upsertBillingSubscription(\n this.buildSubscriptionState(event, uid, existing, {\n status: \"active\",\n cancelAtPeriodEnd: false,\n offerKey: offerKey ?? existing?.offerKey ?? null,\n plan: plan ?? existing?.plan ?? null,\n }),\n );\n if (this.provisioning) {\n await this.provisionSubscription(uid, offer, event);\n }\n return { handled: true, action: \"subscription_resumed\" };\n }\n\n private async handleTrialWillEnd(event: BillingEvent): Promise<BillingEventResult> {\n // Resolve userId so routeEvent's blanket fireEventCallback has a useful value.\n await this.resolveAccountId(event);\n return { handled: true, action: \"trial_will_end_notified\" };\n }\n\n private async provisionSubscription(\n uid: string,\n offer: BillingOfferResult | null,\n event: BillingEvent,\n planKeyOverride?: string,\n preserveAllowanceAnchor = false,\n preservedAllowanceAnchor?: Date | string | null,\n ): Promise<void> {\n if (!this.provisioning) {\n this.logger.debug(\n `[BillingService] provisionSubscription: no provisioning capability for user ${uid}`,\n );\n return;\n }\n const plan = planKeyOverride ?? offer?.plan;\n if (!plan) {\n this.logger.debug(\"[BillingService] provisionSubscription skipped (no plan)\", { uid });\n return;\n }\n this.logger.debug(\"[BillingService] provisionSubscription setting plan\", { uid, plan });\n let periodStart: Date | string | null | undefined;\n if (preserveAllowanceAnchor) {\n const existingAnchor =\n preservedAllowanceAnchor !== undefined\n ? preservedAllowanceAnchor\n : (await this.provisioning.getUserPlan(uid))?.planAssignedAt;\n if (existingAnchor) {\n const anchor = new Date(existingAnchor);\n // A provider's subscription period start may actually be its next\n // renewal date. Never let a future anchor hide an already-active\n // entitlement after a plan change.\n if (!Number.isNaN(anchor.getTime()) && anchor.getTime() <= Date.now()) {\n periodStart = anchor;\n }\n }\n } else {\n periodStart = event.subscription?.periodStart;\n }\n const planAssignedAt = periodStart\n ? (() => {\n const d = new Date(periodStart);\n return Number.isNaN(d.getTime()) ? undefined : d;\n })()\n : preserveAllowanceAnchor\n ? new Date()\n : undefined;\n await this.provisioning.setUserPlan(uid, plan, planAssignedAt);\n\n if (this.autoSelectEntitlementSource && event.provider) {\n const selected = await this.store.selectSubscriptionEntitlementSource(\n uid,\n event.provider,\n event.subscription?.providerSubscriptionId,\n );\n if (selected) {\n this.logger.debug(\n `[BillingService] selected ${event.provider} subscription as entitlement source for user ${uid}`,\n );\n }\n }\n }\n\n private async grantSubscriptionCycle(\n event: BillingEvent,\n offer: BillingOfferResult | null,\n ): Promise<void> {\n const credits = offer?.grant?.mode === \"cycle_grant\" ? offer.grant.credits : null;\n if (!credits || credits.lte(0) || !event.billingEventId || !event.subscription) return;\n\n const subscription = await this.store.getBillingSubscription(\n event.provider,\n event.subscription.providerSubscriptionId,\n );\n if (!subscription?.subscriptionId) {\n throw new StoreError(\"subscription cycle grant requires a persisted subscription\", {\n indeterminate: true,\n details: {\n provider: event.provider,\n providerSubscriptionId: event.subscription.providerSubscriptionId,\n },\n });\n }\n const payment =\n event.payment?.providerPaymentId != null\n ? await this.store.getBillingPayment(event.provider, event.payment.providerPaymentId)\n : null;\n const grantId = await this.store.createBillingCreditGrant({\n paymentId: payment?.id == null ? null : String(payment.id),\n subscriptionId: subscription.subscriptionId,\n configuredCredits: credits,\n quantity: 1,\n billingEventId: event.billingEventId,\n });\n await this.store.grantBillingCredit(grantId, `billing:${event.eventId}:subscription-cycle`);\n }\n\n private async revokeSubscription(uid: string): Promise<void> {\n if (!this.provisioning) return;\n if (this.terminalPlanKey) {\n await this.provisioning.setUserPlan(uid, this.terminalPlanKey);\n return;\n }\n await this.provisioning.unsetUserPlan(uid);\n }\n\n /**\n * Do not revoke access because a stale subscription record ended while a\n * newer subscription for the same user is still active.\n */\n async revokeIfCurrentSubscription(uid: string, subscriptionId: string): Promise<void> {\n const current = await this.store.getUserSubscription(uid, [\"active\", \"trialing\", \"past_due\"]);\n if (!current || current.providerSubscriptionId === subscriptionId) {\n await this.revokeSubscription(uid);\n }\n }\n\n private async reEvaluateAccess(uid: string, event: BillingEvent): Promise<void> {\n if (!this.provisioning || !event.subscription) return;\n const status = event.subscription.status;\n // Provider retries (Stripe past_due, Dodo on_hold mapped to past_due)\n // are a grace period. Keep the last paid entitlements until the provider\n // reaches a terminal state instead of revoking access on the first miss.\n if (status && [\"active\", \"trialing\"].includes(status)) {\n const offer = await this.resolveOfferFromEvent(event);\n if (offer) {\n await this.provisionSubscription(uid, offer, event);\n } else {\n const existing = await this.store.getBillingSubscription(\n event.provider,\n event.subscription.providerSubscriptionId,\n );\n if (existing?.plan) {\n await this.provisionSubscription(uid, null, event, existing.plan);\n }\n }\n } else if (status === \"past_due\") {\n const existing = await this.store.getBillingSubscription(\n event.provider,\n event.subscription.providerSubscriptionId,\n );\n const graceHasExpired =\n Boolean(existing?.graceExpiredAt) ||\n (Boolean(existing?.graceEndsAt) &&\n new Date(existing!.graceEndsAt!).getTime() <= Date.now());\n if (graceHasExpired) {\n await this.revokeIfCurrentSubscription(uid, event.subscription.providerSubscriptionId);\n } else {\n const offer = await this.resolveOfferFromEvent(event);\n if (offer) {\n await this.provisionSubscription(uid, offer, event);\n } else if (existing?.plan) {\n await this.provisionSubscription(uid, null, event, existing.plan);\n }\n }\n } else if (\n status &&\n [\"canceled\", \"expired\", \"unpaid\", \"paused\", \"incomplete_expired\"].includes(status)\n ) {\n await this.revokeIfCurrentSubscription(uid, event.subscription.providerSubscriptionId);\n }\n }\n\n private async resolveOfferFromEvent(event: BillingEvent): Promise<BillingOfferResult | null> {\n const refs = event.subscription?.refs;\n if (!refs) return null;\n return this.resolveBillingOfferCached(\n event.provider,\n refs.productId ?? null,\n refs.priceId ?? null,\n );\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"event-processor.d.ts","sourceRoot":"","sources":["../../src/billing/event-processor.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EAAE,YAAY,EAAuB,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAG9F,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAGhE,qBAAa,qBAAqB;IAc9B,OAAO,CAAC,QAAQ,CAAC,KAAK;IAbxB,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAyD;IACvF,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAmB;IAC1C,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAuB;IAChD,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAGjC;IAEH,IAAI,eAAe,IAAI,OAAO,CAE7B;gBAGkB,KAAK,EAAE,YAAY,EACpC,OAAO,CAAC,EAAE,qBAAqB;IAOjC,oFAAoF;IACpF,oBAAoB,IAAI,IAAI;IAItB,kBAAkB,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,kBAAkB,CAAC;YAyE5D,yBAAyB;YA0BzB,UAAU;YAkBV,iBAAiB;IAczB,2BAA2B,CAAC,MAAM,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAGzF"}
1
+ {"version":3,"file":"event-processor.d.ts","sourceRoot":"","sources":["../../src/billing/event-processor.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OA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