@langwatch/server 3.1.0-beta.4 → 3.1.0-beta.5

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 (118) hide show
  1. package/langwatch/ee/admin/ImpersonationBanner.tsx +61 -0
  2. package/langwatch/ee/admin/ImpersonationSwitchBackMenuItem.tsx +30 -0
  3. package/langwatch/ee/admin/__tests__/ImpersonationBanner.integration.test.tsx +82 -0
  4. package/langwatch/ee/admin/__tests__/impersonation.service.unit.test.ts +231 -0
  5. package/langwatch/ee/admin/backoffice/BackofficeTable.tsx +200 -0
  6. package/langwatch/ee/admin/backoffice/__tests__/adminClient.unit.test.ts +147 -0
  7. package/langwatch/ee/admin/backoffice/__tests__/dateInputToISO.unit.test.ts +42 -0
  8. package/langwatch/ee/admin/backoffice/__tests__/userVisibility.unit.test.ts +174 -0
  9. package/langwatch/ee/admin/backoffice/adminClient.ts +114 -0
  10. package/langwatch/ee/admin/backoffice/resources/OrganizationFeaturesView.tsx +373 -0
  11. package/langwatch/ee/admin/backoffice/resources/OrganizationsView.tsx +677 -0
  12. package/langwatch/ee/admin/backoffice/resources/ProjectsView.tsx +647 -0
  13. package/langwatch/ee/admin/backoffice/resources/SubscriptionsView.tsx +628 -0
  14. package/langwatch/ee/admin/backoffice/resources/UsersView.tsx +556 -0
  15. package/langwatch/ee/admin/backoffice/useAdminResource.ts +104 -0
  16. package/langwatch/ee/admin/backoffice/userVisibility.ts +105 -0
  17. package/langwatch/ee/admin/impersonation.service.ts +170 -0
  18. package/langwatch/ee/admin/isAdmin.ts +9 -0
  19. package/langwatch/ee/admin/routes/admin.ts +531 -0
  20. package/langwatch/ee/admin/safeSelects.ts +64 -0
  21. package/langwatch/ee/billing/__tests__/customerService.unit.test.ts +183 -0
  22. package/langwatch/ee/billing/__tests__/growthSeatEvent.unit.test.ts +213 -0
  23. package/langwatch/ee/billing/__tests__/licensePurchaseHandler.unit.test.ts +250 -0
  24. package/langwatch/ee/billing/__tests__/notification.service.unit.test.ts +768 -0
  25. package/langwatch/ee/billing/__tests__/planLimits.unit.test.ts +19 -0
  26. package/langwatch/ee/billing/__tests__/planProvider.unit.test.ts +440 -0
  27. package/langwatch/ee/billing/__tests__/planTypes.unit.test.ts +32 -0
  28. package/langwatch/ee/billing/__tests__/pricing.unit.test.ts +54 -0
  29. package/langwatch/ee/billing/__tests__/seatEventSubscription.unit.test.ts +717 -0
  30. package/langwatch/ee/billing/__tests__/stripe.integration.test.ts +344 -0
  31. package/langwatch/ee/billing/__tests__/stripePrices.types.unit.test.ts +27 -0
  32. package/langwatch/ee/billing/__tests__/stripePricesLoader.unit.test.ts +72 -0
  33. package/langwatch/ee/billing/__tests__/subscription.service.unit.test.ts +730 -0
  34. package/langwatch/ee/billing/__tests__/subscriptionItemCalculator.unit.test.ts +176 -0
  35. package/langwatch/ee/billing/__tests__/usage-limit.service.unit.test.ts +706 -0
  36. package/langwatch/ee/billing/__tests__/usageReportingService.integration.test.ts +421 -0
  37. package/langwatch/ee/billing/__tests__/usageReportingService.unit.test.ts +515 -0
  38. package/langwatch/ee/billing/__tests__/webhookService.unit.test.ts +958 -0
  39. package/langwatch/ee/billing/currencyRouter.ts +18 -0
  40. package/langwatch/ee/billing/errors.ts +129 -0
  41. package/langwatch/ee/billing/index.ts +67 -0
  42. package/langwatch/ee/billing/middleware.ts +17 -0
  43. package/langwatch/ee/billing/notifications/notification.service.ts +651 -0
  44. package/langwatch/ee/billing/notifications/repositories/notification.repository.ts +51 -0
  45. package/langwatch/ee/billing/notifications/types.ts +9 -0
  46. package/langwatch/ee/billing/notifications/usage-limit.service.ts +622 -0
  47. package/langwatch/ee/billing/nurturing/hooks/activityTracking.ts +90 -0
  48. package/langwatch/ee/billing/nurturing/hooks/activityTracking.unit.test.ts +237 -0
  49. package/langwatch/ee/billing/nurturing/hooks/featureAdoption.ts +120 -0
  50. package/langwatch/ee/billing/nurturing/hooks/featureAdoption.unit.test.ts +324 -0
  51. package/langwatch/ee/billing/nurturing/hooks/index.ts +17 -0
  52. package/langwatch/ee/billing/nurturing/hooks/productInterest.ts +68 -0
  53. package/langwatch/ee/billing/nurturing/hooks/productInterest.unit.test.ts +138 -0
  54. package/langwatch/ee/billing/nurturing/hooks/promptCreation.integration.test.ts +288 -0
  55. package/langwatch/ee/billing/nurturing/hooks/promptCreation.ts +131 -0
  56. package/langwatch/ee/billing/nurturing/hooks/promptCreation.unit.test.ts +134 -0
  57. package/langwatch/ee/billing/nurturing/hooks/signupIdentification.ts +101 -0
  58. package/langwatch/ee/billing/nurturing/hooks/signupIdentification.unit.test.ts +317 -0
  59. package/langwatch/ee/billing/nurturing/hooks/subscriptionSync.ts +49 -0
  60. package/langwatch/ee/billing/nurturing/hooks/subscriptionSync.unit.test.ts +170 -0
  61. package/langwatch/ee/billing/nurturing/hooks/userSync.ts +143 -0
  62. package/langwatch/ee/billing/nurturing/hooks/userSync.unit.test.ts +307 -0
  63. package/langwatch/ee/billing/nurturing/nurturing.service.ts +179 -0
  64. package/langwatch/ee/billing/nurturing/nurturing.service.unit.test.ts +266 -0
  65. package/langwatch/ee/billing/nurturing/nurturing.service.wiring.unit.test.ts +109 -0
  66. package/langwatch/ee/billing/nurturing/types.ts +125 -0
  67. package/langwatch/ee/billing/planLimits.ts +190 -0
  68. package/langwatch/ee/billing/planProvider.ts +119 -0
  69. package/langwatch/ee/billing/planTypes.ts +53 -0
  70. package/langwatch/ee/billing/pricing.ts +57 -0
  71. package/langwatch/ee/billing/services/billableEventsQuery.ts +248 -0
  72. package/langwatch/ee/billing/services/customerService.ts +90 -0
  73. package/langwatch/ee/billing/services/licensePurchaseHandler.ts +73 -0
  74. package/langwatch/ee/billing/services/seatEventSubscription.ts +351 -0
  75. package/langwatch/ee/billing/services/seatSyncService.ts +34 -0
  76. package/langwatch/ee/billing/services/subscription.repository.ts +203 -0
  77. package/langwatch/ee/billing/services/subscription.service.ts +549 -0
  78. package/langwatch/ee/billing/services/subscriptionItemCalculator.ts +249 -0
  79. package/langwatch/ee/billing/services/usageReportingService.ts +301 -0
  80. package/langwatch/ee/billing/services/webhookService.ts +858 -0
  81. package/langwatch/ee/billing/stripe/stripeCatalog.json +1781 -0
  82. package/langwatch/ee/billing/stripe/stripeClient.ts +13 -0
  83. package/langwatch/ee/billing/stripe/stripePriceCatalog.ts +70 -0
  84. package/langwatch/ee/billing/stripe/stripePrices.types.ts +118 -0
  85. package/langwatch/ee/billing/subscriptionRouter.ts +202 -0
  86. package/langwatch/ee/billing/types.ts +102 -0
  87. package/langwatch/ee/billing/utils/currency.ts +99 -0
  88. package/langwatch/ee/billing/utils/growthSeatEvent.ts +137 -0
  89. package/langwatch/ee/licensing/__tests__/constants.unit.test.ts +56 -0
  90. package/langwatch/ee/licensing/__tests__/defaults.unit.test.ts +192 -0
  91. package/langwatch/ee/licensing/__tests__/fixtures/testKeys.ts +86 -0
  92. package/langwatch/ee/licensing/__tests__/fixtures/testLicenses.ts +92 -0
  93. package/langwatch/ee/licensing/__tests__/licenseGenerationService.unit.test.ts +232 -0
  94. package/langwatch/ee/licensing/__tests__/licenseHandler.integration.test.ts +419 -0
  95. package/langwatch/ee/licensing/__tests__/planMapping.unit.test.ts +195 -0
  96. package/langwatch/ee/licensing/__tests__/planTemplates.unit.test.ts +193 -0
  97. package/langwatch/ee/licensing/__tests__/signing.unit.test.ts +164 -0
  98. package/langwatch/ee/licensing/__tests__/validation.unit.test.ts +281 -0
  99. package/langwatch/ee/licensing/client.ts +29 -0
  100. package/langwatch/ee/licensing/constants.ts +195 -0
  101. package/langwatch/ee/licensing/defaults.ts +55 -0
  102. package/langwatch/ee/licensing/errors.ts +11 -0
  103. package/langwatch/ee/licensing/index.ts +52 -0
  104. package/langwatch/ee/licensing/licenseGenerationService.ts +87 -0
  105. package/langwatch/ee/licensing/licenseHandler.ts +308 -0
  106. package/langwatch/ee/licensing/planInfo.ts +46 -0
  107. package/langwatch/ee/licensing/planMapping.ts +37 -0
  108. package/langwatch/ee/licensing/planTemplates.ts +109 -0
  109. package/langwatch/ee/licensing/server.ts +43 -0
  110. package/langwatch/ee/licensing/signing.ts +43 -0
  111. package/langwatch/ee/licensing/types.ts +156 -0
  112. package/langwatch/ee/licensing/validation.ts +107 -0
  113. package/langwatch/ee/managed-providers/ManagedModelProviderAlert.tsx +29 -0
  114. package/langwatch/ee/managed-providers/managedBedrockConfig.ts +226 -0
  115. package/langwatch/ee/saas/ExtraFooterComponents.tsx +169 -0
  116. package/langwatch/package.json +1 -1
  117. package/package.json +1 -1
  118. package/packages/server/dist/cli.cjs +1 -1
@@ -0,0 +1,958 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+
3
+ const mockSendSlackSubscriptionEvent = vi.fn().mockResolvedValue(undefined);
4
+
5
+ vi.mock("../../../src/server/app-layer/app", () => ({
6
+ getApp: () => ({
7
+ notifications: {
8
+ sendSlackSubscriptionEvent: mockSendSlackSubscriptionEvent,
9
+ },
10
+ }),
11
+ }));
12
+
13
+ import { SubscriptionStatus } from "../planTypes";
14
+ import { EEWebhookService } from "../services/webhookService";
15
+ import type { SubscriptionRepository, SubscriptionWithOrg } from "../../../src/server/app-layer/subscription/subscription.repository";
16
+ import type { OrganizationRepository } from "../../../src/server/app-layer/organizations/repositories/organization.repository";
17
+
18
+ const createMockSubscriptionRepository = () => ({
19
+ findLastNonCancelled: vi.fn(),
20
+ createPending: vi.fn(),
21
+ updateStatus: vi.fn(),
22
+ updatePlan: vi.fn(),
23
+ findByStripeId: vi.fn(),
24
+ linkStripeId: vi.fn(),
25
+ activate: vi.fn(),
26
+ recordPaymentFailure: vi.fn(),
27
+ cancel: vi.fn(),
28
+ cancelTrialSubscriptions: vi.fn(),
29
+ migrateToSeatEvent: vi.fn(),
30
+ updateQuantities: vi.fn(),
31
+ });
32
+
33
+ const createMockOrganizationRepository = () => ({
34
+ getOrganizationIdByTeamId: vi.fn(),
35
+ getProjectIds: vi.fn(),
36
+ getFeature: vi.fn(),
37
+ findWithAdmins: vi.fn(),
38
+ updateSentPlanLimitAlert: vi.fn(),
39
+ findProjectsWithName: vi.fn(),
40
+ clearTrialLicense: vi.fn(),
41
+ updateCurrency: vi.fn(),
42
+ getPricingModel: vi.fn(),
43
+ getStripeCustomerId: vi.fn(),
44
+ findNameById: vi.fn(),
45
+ });
46
+
47
+ const createMockItemCalculator = () => ({
48
+ calculateQuantityForPrice: vi.fn().mockReturnValue(0),
49
+ prices: {
50
+ PRO: "price_pro",
51
+ GROWTH: "price_growth",
52
+ LAUNCH: "price_launch",
53
+ LAUNCH_ANNUAL: "price_launch_annual",
54
+ ACCELERATE: "price_accelerate",
55
+ ACCELERATE_ANNUAL: "price_acc_annual",
56
+ LAUNCH_USERS: "price_launch_users",
57
+ ACCELERATE_USERS: "price_acc_users",
58
+ LAUNCH_ANNUAL_USERS: "price_launch_annual_users",
59
+ ACCELERATE_ANNUAL_USERS: "price_acc_annual_users",
60
+ LAUNCH_TRACES_10K: "price_launch_traces",
61
+ ACCELERATE_TRACES_100K: "price_acc_traces",
62
+ LAUNCH_ANNUAL_TRACES_10K: "price_launch_annual_traces",
63
+ ACCELERATE_ANNUAL_TRACES_100K: "price_acc_annual_traces",
64
+ GROWTH_SEAT_EUR_MONTHLY: "price_growth_seat_eur_monthly",
65
+ GROWTH_SEAT_EUR_ANNUAL: "price_growth_seat_eur_annual",
66
+ GROWTH_SEAT_USD_MONTHLY: "price_growth_seat_usd_monthly",
67
+ GROWTH_SEAT_USD_ANNUAL: "price_growth_seat_usd_annual",
68
+ GROWTH_EVENTS_EUR_MONTHLY: "price_growth_events_eur_monthly",
69
+ GROWTH_EVENTS_EUR_ANNUAL: "price_growth_events_eur_annual",
70
+ GROWTH_EVENTS_USD_MONTHLY: "price_growth_events_usd_monthly",
71
+ GROWTH_EVENTS_USD_ANNUAL: "price_growth_events_usd_annual",
72
+ GROWTH_EVENTS_EUR_MONTHLY_UNTIL_MAR_2026: "price_growth_events_eur_monthly_until_mar_2026",
73
+ GROWTH_EVENTS_EUR_ANNUAL_UNTIL_MAR_2026: "price_growth_events_eur_annual_until_mar_2026",
74
+ GROWTH_EVENTS_USD_MONTHLY_UNTIL_MAR_2026: "price_growth_events_usd_monthly_until_mar_2026",
75
+ GROWTH_EVENTS_USD_ANNUAL_UNTIL_MAR_2026: "price_growth_events_usd_annual_until_mar_2026",
76
+ },
77
+ });
78
+
79
+ const makeSubscription = (overrides: Record<string, unknown> = {}) => ({
80
+ id: "sub_db_1",
81
+ organizationId: "org_123",
82
+ status: SubscriptionStatus.PENDING,
83
+ plan: "LAUNCH",
84
+ stripeSubscriptionId: "sub_stripe_1",
85
+ startDate: new Date(),
86
+ endDate: null,
87
+ lastPaymentFailedDate: null,
88
+ maxMembers: null,
89
+ maxMessagesPerMonth: null,
90
+ ...overrides,
91
+ });
92
+
93
+ const makeSubscriptionWithOrg = (overrides: Record<string, unknown> = {}): SubscriptionWithOrg => {
94
+ const { organization, ...subscriptionOverrides } = overrides;
95
+ return {
96
+ ...makeSubscription(subscriptionOverrides),
97
+ organization: { name: "Acme", license: null, ...(organization as Record<string, unknown>) },
98
+ } as unknown as SubscriptionWithOrg;
99
+ };
100
+
101
+ const createMockStripe = (overrides: Record<string, unknown> = {}) => ({
102
+ subscriptions: {
103
+ retrieve: vi.fn().mockResolvedValue({ id: "sub_stripe_1", status: "active" }),
104
+ cancel: vi.fn().mockResolvedValue({}),
105
+ },
106
+ ...overrides,
107
+ });
108
+
109
+ describe("webhookService", () => {
110
+ let subRepo: ReturnType<typeof createMockSubscriptionRepository>;
111
+ let orgRepo: ReturnType<typeof createMockOrganizationRepository>;
112
+ let itemCalculator: ReturnType<typeof createMockItemCalculator>;
113
+ let mockStripeInstance: ReturnType<typeof createMockStripe>;
114
+ let service: EEWebhookService;
115
+
116
+ beforeEach(() => {
117
+ vi.clearAllMocks();
118
+ vi.useFakeTimers();
119
+ subRepo = createMockSubscriptionRepository();
120
+ orgRepo = createMockOrganizationRepository();
121
+ itemCalculator = createMockItemCalculator();
122
+ mockStripeInstance = createMockStripe();
123
+ service = new EEWebhookService({
124
+ subscriptionRepository: subRepo as unknown as SubscriptionRepository,
125
+ organizationRepository: orgRepo as unknown as OrganizationRepository,
126
+ stripe: mockStripeInstance as any,
127
+ itemCalculator,
128
+ });
129
+ });
130
+
131
+ afterEach(() => {
132
+ vi.useRealTimers();
133
+ });
134
+
135
+ describe("handleCheckoutCompleted()", () => {
136
+ describe("when client reference ID is missing", () => {
137
+ it("returns early", async () => {
138
+ const result = await service.handleCheckoutCompleted({
139
+ subscriptionId: "sub_1",
140
+ clientReferenceId: null,
141
+ });
142
+
143
+ expect(result.earlyReturn).toBe(true);
144
+ expect(subRepo.linkStripeId).not.toHaveBeenCalled();
145
+ });
146
+ });
147
+
148
+ describe("when client reference ID exists", () => {
149
+ it("strips subscription_setup_ prefix and links Stripe subscription", async () => {
150
+ subRepo.linkStripeId.mockResolvedValue({ count: 1 });
151
+ subRepo.findByStripeId.mockResolvedValue(
152
+ makeSubscription({ status: SubscriptionStatus.PENDING }),
153
+ );
154
+ subRepo.activate.mockResolvedValue(
155
+ makeSubscriptionWithOrg({ status: SubscriptionStatus.ACTIVE }),
156
+ );
157
+
158
+ const promise = service.handleCheckoutCompleted({
159
+ subscriptionId: "sub_stripe_1",
160
+ clientReferenceId: "subscription_setup_sub_db_1",
161
+ });
162
+
163
+ await vi.advanceTimersByTimeAsync(2000);
164
+ const result = await promise;
165
+
166
+ expect(result.earlyReturn).toBe(false);
167
+ expect(subRepo.linkStripeId).toHaveBeenCalledWith({
168
+ id: "sub_db_1",
169
+ stripeSubscriptionId: "sub_stripe_1",
170
+ });
171
+ });
172
+
173
+ it("activates subscription and cancels trial subscriptions", async () => {
174
+ subRepo.linkStripeId.mockResolvedValue({ count: 1 });
175
+ subRepo.findByStripeId.mockResolvedValue(
176
+ makeSubscription({ status: SubscriptionStatus.PENDING }),
177
+ );
178
+ subRepo.activate.mockResolvedValue(
179
+ makeSubscriptionWithOrg({ status: SubscriptionStatus.ACTIVE }),
180
+ );
181
+
182
+ const promise = service.handleCheckoutCompleted({
183
+ subscriptionId: "sub_stripe_1",
184
+ clientReferenceId: "subscription_setup_sub_db_1",
185
+ });
186
+
187
+ await vi.advanceTimersByTimeAsync(2000);
188
+ await promise;
189
+
190
+ expect(subRepo.activate).toHaveBeenCalledWith({
191
+ id: "sub_db_1",
192
+ previousStatus: SubscriptionStatus.PENDING,
193
+ });
194
+ expect(subRepo.cancelTrialSubscriptions).toHaveBeenCalledWith("org_123");
195
+ });
196
+
197
+ it("throws SubscriptionRecordNotFoundError when no subscription matches", async () => {
198
+ subRepo.linkStripeId.mockResolvedValue({ count: 0 });
199
+
200
+ await expect(
201
+ service.handleCheckoutCompleted({
202
+ subscriptionId: "sub_stripe_1",
203
+ clientReferenceId: "subscription_setup_sub_db_1",
204
+ }),
205
+ ).rejects.toThrow("No subscription record found");
206
+ });
207
+
208
+ it("continues when currency update fails", async () => {
209
+ subRepo.linkStripeId.mockResolvedValue({ count: 1 });
210
+ subRepo.findByStripeId.mockResolvedValue(
211
+ makeSubscription({ status: SubscriptionStatus.PENDING }),
212
+ );
213
+ subRepo.activate.mockResolvedValue(
214
+ makeSubscriptionWithOrg({ status: SubscriptionStatus.ACTIVE }),
215
+ );
216
+ orgRepo.updateCurrency.mockRejectedValue(new Error("DB error"));
217
+
218
+ const promise = service.handleCheckoutCompleted({
219
+ subscriptionId: "sub_stripe_1",
220
+ clientReferenceId: "subscription_setup_sub_db_1",
221
+ selectedCurrency: "EUR",
222
+ });
223
+
224
+ await vi.advanceTimersByTimeAsync(2000);
225
+ await promise;
226
+
227
+ expect(subRepo.activate).toHaveBeenCalled();
228
+ expect(subRepo.cancelTrialSubscriptions).toHaveBeenCalledWith("org_123");
229
+ });
230
+
231
+ it("continues when invite approval fails", async () => {
232
+ const mockInviteApprover = {
233
+ approvePaymentPendingInvites: vi.fn().mockRejectedValue(new Error("invite error")),
234
+ };
235
+ service = new EEWebhookService({
236
+ subscriptionRepository: subRepo as unknown as SubscriptionRepository,
237
+ organizationRepository: orgRepo as unknown as OrganizationRepository,
238
+ stripe: mockStripeInstance as any,
239
+ itemCalculator,
240
+ inviteApprover: mockInviteApprover,
241
+ });
242
+
243
+ subRepo.linkStripeId.mockResolvedValue({ count: 1 });
244
+ subRepo.findByStripeId.mockResolvedValue(
245
+ makeSubscription({ status: SubscriptionStatus.PENDING }),
246
+ );
247
+ subRepo.activate.mockResolvedValue(
248
+ makeSubscriptionWithOrg({ status: SubscriptionStatus.ACTIVE }),
249
+ );
250
+
251
+ const promise = service.handleCheckoutCompleted({
252
+ subscriptionId: "sub_stripe_1",
253
+ clientReferenceId: "subscription_setup_sub_db_1",
254
+ });
255
+
256
+ await vi.advanceTimersByTimeAsync(2000);
257
+ await promise;
258
+
259
+ expect(subRepo.activate).toHaveBeenCalled();
260
+ expect(subRepo.cancelTrialSubscriptions).toHaveBeenCalledWith("org_123");
261
+ });
262
+
263
+ it("completes without invite approver", async () => {
264
+ subRepo.linkStripeId.mockResolvedValue({ count: 1 });
265
+ subRepo.findByStripeId.mockResolvedValue(
266
+ makeSubscription({ status: SubscriptionStatus.PENDING }),
267
+ );
268
+ subRepo.activate.mockResolvedValue(
269
+ makeSubscriptionWithOrg({ status: SubscriptionStatus.ACTIVE }),
270
+ );
271
+
272
+ const promise = service.handleCheckoutCompleted({
273
+ subscriptionId: "sub_stripe_1",
274
+ clientReferenceId: "subscription_setup_sub_db_1",
275
+ });
276
+
277
+ await vi.advanceTimersByTimeAsync(2000);
278
+ await promise;
279
+
280
+ // No invite approver configured — should not throw
281
+ expect(subRepo.activate).toHaveBeenCalled();
282
+ });
283
+ });
284
+ });
285
+
286
+ describe("handleInvoicePaymentSucceeded()", () => {
287
+ describe("when no subscription found", () => {
288
+ it("skips without error", async () => {
289
+ subRepo.findByStripeId.mockResolvedValue(null);
290
+
291
+ const promise = service.handleInvoicePaymentSucceeded({
292
+ subscriptionId: "sub_missing",
293
+ });
294
+
295
+ await vi.advanceTimersByTimeAsync(2000);
296
+ await promise;
297
+
298
+ expect(subRepo.activate).not.toHaveBeenCalled();
299
+ });
300
+ });
301
+
302
+ describe("when subscription is not previously active", () => {
303
+ it("activates and clears trial license", async () => {
304
+ subRepo.findByStripeId.mockResolvedValue(
305
+ makeSubscription({ status: SubscriptionStatus.PENDING }),
306
+ );
307
+ subRepo.activate.mockResolvedValue(
308
+ makeSubscriptionWithOrg({
309
+ status: SubscriptionStatus.ACTIVE,
310
+ organization: { name: "Acme", license: "trial-license-key" },
311
+ }),
312
+ );
313
+
314
+ const promise = service.handleInvoicePaymentSucceeded({
315
+ subscriptionId: "sub_stripe_1",
316
+ });
317
+
318
+ await vi.advanceTimersByTimeAsync(2000);
319
+ await promise;
320
+
321
+ expect(subRepo.activate).toHaveBeenCalledWith({
322
+ id: "sub_db_1",
323
+ previousStatus: SubscriptionStatus.PENDING,
324
+ });
325
+ expect(orgRepo.clearTrialLicense).toHaveBeenCalledWith("org_123");
326
+ expect(mockSendSlackSubscriptionEvent).toHaveBeenCalledWith(
327
+ expect.objectContaining({
328
+ type: "confirmed",
329
+ organizationId: "org_123",
330
+ }),
331
+ );
332
+ });
333
+ });
334
+
335
+ describe("when subscription is already active", () => {
336
+ it("does not set startDate and does not notify", async () => {
337
+ subRepo.findByStripeId.mockResolvedValue(
338
+ makeSubscription({ status: SubscriptionStatus.ACTIVE }),
339
+ );
340
+ subRepo.activate.mockResolvedValue(
341
+ makeSubscriptionWithOrg({ status: SubscriptionStatus.ACTIVE }),
342
+ );
343
+
344
+ const promise = service.handleInvoicePaymentSucceeded({
345
+ subscriptionId: "sub_stripe_1",
346
+ });
347
+
348
+ await vi.advanceTimersByTimeAsync(2000);
349
+ await promise;
350
+
351
+ expect(subRepo.activate).toHaveBeenCalledWith({
352
+ id: "sub_db_1",
353
+ previousStatus: SubscriptionStatus.ACTIVE,
354
+ });
355
+ expect(mockSendSlackSubscriptionEvent).not.toHaveBeenCalled();
356
+ });
357
+ });
358
+
359
+ describe("when subscription is a growth seat-event plan", () => {
360
+ it("migrates tiered subscriptions and cancels old Stripe subs", async () => {
361
+ const localStripe = createMockStripe();
362
+ service = new EEWebhookService({
363
+ subscriptionRepository: subRepo as unknown as SubscriptionRepository,
364
+ organizationRepository: orgRepo as unknown as OrganizationRepository,
365
+ stripe: localStripe as any,
366
+ itemCalculator,
367
+ });
368
+
369
+ subRepo.findByStripeId.mockResolvedValue(
370
+ makeSubscription({ status: SubscriptionStatus.PENDING, plan: "GROWTH_SEAT_EUR_MONTHLY" }),
371
+ );
372
+ subRepo.activate.mockResolvedValue(
373
+ makeSubscriptionWithOrg({ status: SubscriptionStatus.ACTIVE, plan: "GROWTH_SEAT_EUR_MONTHLY" }),
374
+ );
375
+ subRepo.migrateToSeatEvent.mockResolvedValue([
376
+ { stripeSubscriptionId: "sub_old_1" },
377
+ { stripeSubscriptionId: "sub_old_2" },
378
+ ]);
379
+
380
+ const promise = service.handleInvoicePaymentSucceeded({
381
+ subscriptionId: "sub_stripe_1",
382
+ });
383
+
384
+ await vi.advanceTimersByTimeAsync(2000);
385
+ await promise;
386
+
387
+ expect(subRepo.migrateToSeatEvent).toHaveBeenCalledWith({
388
+ organizationId: "org_123",
389
+ excludeSubscriptionId: "sub_db_1",
390
+ });
391
+ expect(localStripe.subscriptions.cancel).toHaveBeenCalledWith("sub_old_1", { prorate: true });
392
+ expect(localStripe.subscriptions.cancel).toHaveBeenCalledWith("sub_old_2", { prorate: true });
393
+ });
394
+
395
+ it("logs but does not fail when Stripe cancellation fails", async () => {
396
+ const localStripe = createMockStripe();
397
+ localStripe.subscriptions.cancel.mockRejectedValue(new Error("Stripe error"));
398
+ service = new EEWebhookService({
399
+ subscriptionRepository: subRepo as unknown as SubscriptionRepository,
400
+ organizationRepository: orgRepo as unknown as OrganizationRepository,
401
+ stripe: localStripe as any,
402
+ itemCalculator,
403
+ });
404
+
405
+ subRepo.findByStripeId.mockResolvedValue(
406
+ makeSubscription({ status: SubscriptionStatus.PENDING, plan: "GROWTH_SEAT_EUR_MONTHLY" }),
407
+ );
408
+ subRepo.activate.mockResolvedValue(
409
+ makeSubscriptionWithOrg({ status: SubscriptionStatus.ACTIVE, plan: "GROWTH_SEAT_EUR_MONTHLY" }),
410
+ );
411
+ subRepo.migrateToSeatEvent.mockResolvedValue([
412
+ { stripeSubscriptionId: "sub_old_1" },
413
+ ]);
414
+
415
+ const promise = service.handleInvoicePaymentSucceeded({
416
+ subscriptionId: "sub_stripe_1",
417
+ });
418
+
419
+ await vi.advanceTimersByTimeAsync(2000);
420
+ // Should not throw
421
+ await promise;
422
+
423
+ expect(mockSendSlackSubscriptionEvent).toHaveBeenCalled();
424
+ });
425
+ });
426
+
427
+ describe("when subscription is already CANCELLED in DB and Stripe subscription is canceled", () => {
428
+ it("does not reactivate a cancelled subscription", async () => {
429
+ mockStripeInstance.subscriptions.retrieve.mockResolvedValue({
430
+ id: "sub_stripe_1",
431
+ status: "canceled",
432
+ });
433
+
434
+ subRepo.findByStripeId.mockResolvedValue(
435
+ makeSubscription({
436
+ status: SubscriptionStatus.CANCELLED,
437
+ plan: "GROWTH_SEAT_EUR_MONTHLY",
438
+ }),
439
+ );
440
+
441
+ const promise = service.handleInvoicePaymentSucceeded({
442
+ subscriptionId: "sub_stripe_1",
443
+ });
444
+
445
+ await vi.advanceTimersByTimeAsync(2000);
446
+ await promise;
447
+
448
+ expect(subRepo.activate).not.toHaveBeenCalled();
449
+ expect(mockSendSlackSubscriptionEvent).not.toHaveBeenCalled();
450
+ });
451
+ });
452
+
453
+ describe("when subscription is ACTIVE in DB but Stripe subscription is canceled", () => {
454
+ it("does not reactivate when Stripe status is canceled", async () => {
455
+ mockStripeInstance.subscriptions.retrieve.mockResolvedValue({
456
+ id: "sub_stripe_1",
457
+ status: "canceled",
458
+ });
459
+
460
+ subRepo.findByStripeId.mockResolvedValue(
461
+ makeSubscription({
462
+ status: SubscriptionStatus.ACTIVE,
463
+ plan: "GROWTH_SEAT_EUR_MONTHLY",
464
+ }),
465
+ );
466
+
467
+ const promise = service.handleInvoicePaymentSucceeded({
468
+ subscriptionId: "sub_stripe_1",
469
+ });
470
+
471
+ await vi.advanceTimersByTimeAsync(2000);
472
+ await promise;
473
+
474
+ expect(subRepo.activate).not.toHaveBeenCalled();
475
+ expect(mockSendSlackSubscriptionEvent).not.toHaveBeenCalled();
476
+ });
477
+ });
478
+
479
+ describe("when Stripe subscription status check fails", () => {
480
+ it("proceeds with activation (fail-open)", async () => {
481
+ mockStripeInstance.subscriptions.retrieve.mockRejectedValue(
482
+ new Error("Stripe API unreachable"),
483
+ );
484
+
485
+ subRepo.findByStripeId.mockResolvedValue(
486
+ makeSubscription({ status: SubscriptionStatus.PENDING }),
487
+ );
488
+ subRepo.activate.mockResolvedValue(
489
+ makeSubscriptionWithOrg({ status: SubscriptionStatus.ACTIVE }),
490
+ );
491
+
492
+ const promise = service.handleInvoicePaymentSucceeded({
493
+ subscriptionId: "sub_stripe_1",
494
+ });
495
+
496
+ await vi.advanceTimersByTimeAsync(2000);
497
+ await promise;
498
+
499
+ expect(subRepo.activate).toHaveBeenCalledWith({
500
+ id: "sub_db_1",
501
+ previousStatus: SubscriptionStatus.PENDING,
502
+ });
503
+ expect(mockSendSlackSubscriptionEvent).toHaveBeenCalledWith(
504
+ expect.objectContaining({
505
+ type: "confirmed",
506
+ organizationId: "org_123",
507
+ }),
508
+ );
509
+ });
510
+
511
+ it("skips activation when DB status is CANCELLED", async () => {
512
+ mockStripeInstance.subscriptions.retrieve.mockRejectedValue(
513
+ new Error("Stripe API unreachable"),
514
+ );
515
+
516
+ subRepo.findByStripeId.mockResolvedValue(
517
+ makeSubscription({
518
+ status: SubscriptionStatus.CANCELLED,
519
+ plan: "GROWTH_SEAT_EUR_MONTHLY",
520
+ }),
521
+ );
522
+
523
+ const promise = service.handleInvoicePaymentSucceeded({
524
+ subscriptionId: "sub_stripe_1",
525
+ });
526
+
527
+ await vi.advanceTimersByTimeAsync(2000);
528
+ await promise;
529
+
530
+ expect(subRepo.activate).not.toHaveBeenCalled();
531
+ expect(mockSendSlackSubscriptionEvent).not.toHaveBeenCalled();
532
+ });
533
+ });
534
+
535
+ describe("when Stripe subscription is active (normal renewal)", () => {
536
+ it("activates the subscription as usual", async () => {
537
+ subRepo.findByStripeId.mockResolvedValue(
538
+ makeSubscription({ status: SubscriptionStatus.PENDING }),
539
+ );
540
+ subRepo.activate.mockResolvedValue(
541
+ makeSubscriptionWithOrg({ status: SubscriptionStatus.ACTIVE }),
542
+ );
543
+
544
+ const promise = service.handleInvoicePaymentSucceeded({
545
+ subscriptionId: "sub_stripe_1",
546
+ });
547
+
548
+ await vi.advanceTimersByTimeAsync(2000);
549
+ await promise;
550
+
551
+ expect(subRepo.activate).toHaveBeenCalledWith({
552
+ id: "sub_db_1",
553
+ previousStatus: SubscriptionStatus.PENDING,
554
+ });
555
+ expect(mockSendSlackSubscriptionEvent).toHaveBeenCalledWith(
556
+ expect.objectContaining({
557
+ type: "confirmed",
558
+ organizationId: "org_123",
559
+ }),
560
+ );
561
+ });
562
+ });
563
+ });
564
+
565
+ describe("handleInvoicePaymentFailed()", () => {
566
+ describe("when no subscription found", () => {
567
+ it("skips without error", async () => {
568
+ subRepo.findByStripeId.mockResolvedValue(null);
569
+
570
+ const promise = service.handleInvoicePaymentFailed({
571
+ subscriptionId: "sub_missing",
572
+ });
573
+
574
+ await vi.advanceTimersByTimeAsync(2000);
575
+ await promise;
576
+
577
+ expect(subRepo.recordPaymentFailure).not.toHaveBeenCalled();
578
+ });
579
+ });
580
+
581
+ describe("when subscription is ACTIVE", () => {
582
+ it("keeps status as ACTIVE with failed payment date", async () => {
583
+ subRepo.findByStripeId.mockResolvedValue(
584
+ makeSubscription({ status: SubscriptionStatus.ACTIVE }),
585
+ );
586
+
587
+ const promise = service.handleInvoicePaymentFailed({
588
+ subscriptionId: "sub_1",
589
+ });
590
+
591
+ await vi.advanceTimersByTimeAsync(2000);
592
+ await promise;
593
+
594
+ expect(subRepo.recordPaymentFailure).toHaveBeenCalledWith({
595
+ id: "sub_db_1",
596
+ currentStatus: SubscriptionStatus.ACTIVE,
597
+ });
598
+ });
599
+ });
600
+
601
+ describe("when subscription is PENDING", () => {
602
+ it("sets status to FAILED", async () => {
603
+ subRepo.findByStripeId.mockResolvedValue(
604
+ makeSubscription({ status: SubscriptionStatus.PENDING }),
605
+ );
606
+
607
+ const promise = service.handleInvoicePaymentFailed({
608
+ subscriptionId: "sub_1",
609
+ });
610
+
611
+ await vi.advanceTimersByTimeAsync(2000);
612
+ await promise;
613
+
614
+ expect(subRepo.recordPaymentFailure).toHaveBeenCalledWith({
615
+ id: "sub_db_1",
616
+ currentStatus: SubscriptionStatus.PENDING,
617
+ });
618
+ });
619
+ });
620
+ });
621
+
622
+ describe("handleSubscriptionDeleted()", () => {
623
+ it("waits for Stripe eventual consistency before looking up the subscription", async () => {
624
+ subRepo.findByStripeId.mockResolvedValue(null);
625
+
626
+ const promise = service.handleSubscriptionDeleted({
627
+ stripeSubscriptionId: "sub_stripe_1",
628
+ });
629
+
630
+ // Repository should not have been called yet — still waiting
631
+ expect(subRepo.findByStripeId).not.toHaveBeenCalled();
632
+
633
+ await vi.advanceTimersByTimeAsync(2000);
634
+ await promise;
635
+
636
+ expect(subRepo.findByStripeId).toHaveBeenCalledWith("sub_stripe_1");
637
+ });
638
+
639
+ describe("when no subscription found", () => {
640
+ it("skips without error", async () => {
641
+ subRepo.findByStripeId.mockResolvedValue(null);
642
+
643
+ const promise = service.handleSubscriptionDeleted({
644
+ stripeSubscriptionId: "sub_missing",
645
+ });
646
+
647
+ await vi.advanceTimersByTimeAsync(2000);
648
+ await promise;
649
+
650
+ expect(subRepo.cancel).not.toHaveBeenCalled();
651
+ });
652
+ });
653
+
654
+ describe("when subscription exists", () => {
655
+ it("cancels and nullifies overrides", async () => {
656
+ subRepo.findByStripeId.mockResolvedValue(
657
+ makeSubscription({ status: SubscriptionStatus.ACTIVE }),
658
+ );
659
+
660
+ const promise = service.handleSubscriptionDeleted({
661
+ stripeSubscriptionId: "sub_stripe_1",
662
+ });
663
+
664
+ await vi.advanceTimersByTimeAsync(2000);
665
+ await promise;
666
+
667
+ expect(subRepo.cancel).toHaveBeenCalledWith({ id: "sub_db_1" });
668
+ });
669
+ });
670
+
671
+ describe("when subscription is already cancelled", () => {
672
+ it("is idempotent — skips redundant update", async () => {
673
+ subRepo.findByStripeId.mockResolvedValue(
674
+ makeSubscription({ status: SubscriptionStatus.CANCELLED }),
675
+ );
676
+
677
+ const promise = service.handleSubscriptionDeleted({
678
+ stripeSubscriptionId: "sub_stripe_1",
679
+ });
680
+
681
+ await vi.advanceTimersByTimeAsync(2000);
682
+ await promise;
683
+
684
+ expect(subRepo.cancel).not.toHaveBeenCalled();
685
+ });
686
+ });
687
+
688
+ describe("when subscription is active and gets cancelled", () => {
689
+ it("sends a cancelled Slack notification", async () => {
690
+ subRepo.findByStripeId.mockResolvedValue(
691
+ makeSubscription({ status: SubscriptionStatus.ACTIVE, plan: "GROWTH_SEAT_EUR_MONTHLY" }),
692
+ );
693
+ orgRepo.findNameById.mockResolvedValue({ id: "org_123", name: "Acme" });
694
+
695
+ const promise = service.handleSubscriptionDeleted({
696
+ stripeSubscriptionId: "sub_stripe_1",
697
+ });
698
+
699
+ await vi.advanceTimersByTimeAsync(2000);
700
+ await promise;
701
+
702
+ expect(mockSendSlackSubscriptionEvent).toHaveBeenCalledWith(
703
+ expect.objectContaining({
704
+ type: "cancelled",
705
+ organizationId: "org_123",
706
+ organizationName: "Acme",
707
+ plan: "GROWTH_SEAT_EUR_MONTHLY",
708
+ subscriptionId: "sub_db_1",
709
+ }),
710
+ );
711
+ });
712
+
713
+ it("sends notification with cancellation date", async () => {
714
+ subRepo.findByStripeId.mockResolvedValue(
715
+ makeSubscription({ status: SubscriptionStatus.ACTIVE, plan: "GROWTH_SEAT_EUR_MONTHLY" }),
716
+ );
717
+ orgRepo.findNameById.mockResolvedValue({ id: "org_123", name: "Acme" });
718
+
719
+ const promise = service.handleSubscriptionDeleted({
720
+ stripeSubscriptionId: "sub_stripe_1",
721
+ });
722
+
723
+ await vi.advanceTimersByTimeAsync(2000);
724
+ await promise;
725
+
726
+ expect(mockSendSlackSubscriptionEvent).toHaveBeenCalledWith(
727
+ expect.objectContaining({
728
+ type: "cancelled",
729
+ cancellationDate: expect.any(Date),
730
+ }),
731
+ );
732
+ });
733
+
734
+ it("still cancels and notifies even when org name lookup fails", async () => {
735
+ subRepo.findByStripeId.mockResolvedValue(
736
+ makeSubscription({ status: SubscriptionStatus.ACTIVE, plan: "GROWTH_SEAT_EUR_MONTHLY" }),
737
+ );
738
+ orgRepo.findNameById.mockResolvedValue(null);
739
+
740
+ const promise = service.handleSubscriptionDeleted({
741
+ stripeSubscriptionId: "sub_stripe_1",
742
+ });
743
+
744
+ await vi.advanceTimersByTimeAsync(2000);
745
+ await promise;
746
+
747
+ expect(subRepo.cancel).toHaveBeenCalledWith({ id: "sub_db_1" });
748
+ expect(mockSendSlackSubscriptionEvent).toHaveBeenCalledWith(
749
+ expect.objectContaining({
750
+ type: "cancelled",
751
+ organizationName: "Unknown",
752
+ }),
753
+ );
754
+ });
755
+
756
+ it("completes cancellation even when notification throws", async () => {
757
+ subRepo.findByStripeId.mockResolvedValue(
758
+ makeSubscription({ status: SubscriptionStatus.ACTIVE, plan: "GROWTH_SEAT_EUR_MONTHLY" }),
759
+ );
760
+ orgRepo.findNameById.mockRejectedValue(new Error("DB connection lost"));
761
+
762
+ const promise = service.handleSubscriptionDeleted({
763
+ stripeSubscriptionId: "sub_stripe_1",
764
+ });
765
+
766
+ await vi.advanceTimersByTimeAsync(2000);
767
+ // Should not throw — notification error is caught
768
+ await promise;
769
+
770
+ expect(subRepo.cancel).toHaveBeenCalledWith({ id: "sub_db_1" });
771
+ });
772
+ });
773
+ });
774
+
775
+ describe("handleSubscriptionUpdated()", () => {
776
+ describe("when no subscription found", () => {
777
+ it("skips without error", async () => {
778
+ subRepo.findByStripeId.mockResolvedValue(null);
779
+
780
+ const promise = service.handleSubscriptionUpdated({
781
+ subscription: { id: "sub_missing", items: { data: [] } } as any,
782
+ });
783
+
784
+ await vi.advanceTimersByTimeAsync(2000);
785
+ await promise;
786
+
787
+ expect(subRepo.cancel).not.toHaveBeenCalled();
788
+ expect(subRepo.updateQuantities).not.toHaveBeenCalled();
789
+ });
790
+ });
791
+
792
+ describe("when Stripe status is not active", () => {
793
+ it("cancels with nullified overrides", async () => {
794
+ subRepo.findByStripeId.mockResolvedValue(
795
+ makeSubscription({ status: SubscriptionStatus.ACTIVE }),
796
+ );
797
+
798
+ const promise = service.handleSubscriptionUpdated({
799
+ subscription: {
800
+ id: "sub_stripe_1",
801
+ status: "canceled",
802
+ canceled_at: 1234567890,
803
+ items: { data: [] },
804
+ } as any,
805
+ });
806
+
807
+ await vi.advanceTimersByTimeAsync(2000);
808
+ await promise;
809
+
810
+ expect(subRepo.cancel).toHaveBeenCalledWith({ id: "sub_db_1" });
811
+ });
812
+ });
813
+
814
+ describe("when Stripe reports ended", () => {
815
+ it("cancels with nullified overrides", async () => {
816
+ subRepo.findByStripeId.mockResolvedValue(
817
+ makeSubscription({ status: SubscriptionStatus.ACTIVE }),
818
+ );
819
+
820
+ const promise = service.handleSubscriptionUpdated({
821
+ subscription: {
822
+ id: "sub_stripe_1",
823
+ status: "active",
824
+ ended_at: 1234567890,
825
+ items: { data: [] },
826
+ } as any,
827
+ });
828
+
829
+ await vi.advanceTimersByTimeAsync(2000);
830
+ await promise;
831
+
832
+ expect(subRepo.cancel).toHaveBeenCalledWith({ id: "sub_db_1" });
833
+ });
834
+ });
835
+
836
+ describe("when only canceled_at is set (scheduled cancellation)", () => {
837
+ it("does NOT cancel — updates quantities as normal", async () => {
838
+ subRepo.findByStripeId.mockResolvedValue(
839
+ makeSubscription({ status: SubscriptionStatus.ACTIVE }),
840
+ );
841
+ subRepo.updateQuantities.mockResolvedValue(
842
+ makeSubscriptionWithOrg({ status: SubscriptionStatus.ACTIVE }),
843
+ );
844
+
845
+ const promise = service.handleSubscriptionUpdated({
846
+ subscription: {
847
+ id: "sub_stripe_1",
848
+ status: "active",
849
+ canceled_at: 1234567890,
850
+ ended_at: null,
851
+ items: { data: [] },
852
+ } as any,
853
+ });
854
+
855
+ await vi.advanceTimersByTimeAsync(2000);
856
+ await promise;
857
+
858
+ expect(subRepo.cancel).not.toHaveBeenCalled();
859
+ expect(subRepo.updateQuantities).toHaveBeenCalled();
860
+ });
861
+ });
862
+
863
+ describe("when subscription is active", () => {
864
+ it("recalculates quantities and updates", async () => {
865
+ subRepo.findByStripeId.mockResolvedValue(
866
+ makeSubscription({ status: SubscriptionStatus.ACTIVE, plan: "LAUNCH" }),
867
+ );
868
+ itemCalculator.calculateQuantityForPrice
869
+ .mockReturnValueOnce(5) // users
870
+ .mockReturnValueOnce(30_000); // traces
871
+ subRepo.updateQuantities.mockResolvedValue(
872
+ makeSubscriptionWithOrg({
873
+ status: SubscriptionStatus.ACTIVE,
874
+ maxMembers: 5,
875
+ maxMessagesPerMonth: 30_000,
876
+ }),
877
+ );
878
+
879
+ const promise = service.handleSubscriptionUpdated({
880
+ subscription: {
881
+ id: "sub_stripe_1",
882
+ status: "active",
883
+ canceled_at: null,
884
+ ended_at: null,
885
+ items: {
886
+ data: [
887
+ { price: { id: "price_launch_users" }, quantity: 2 },
888
+ { price: { id: "price_launch_traces" }, quantity: 1 },
889
+ ],
890
+ },
891
+ } as any,
892
+ });
893
+
894
+ await vi.advanceTimersByTimeAsync(2000);
895
+ await promise;
896
+
897
+ expect(subRepo.updateQuantities).toHaveBeenCalledWith({
898
+ id: "sub_db_1",
899
+ maxMembers: 5,
900
+ maxMessagesPerMonth: 30_000,
901
+ });
902
+ });
903
+
904
+ it("notifies when transitioning from non-active to active", async () => {
905
+ subRepo.findByStripeId.mockResolvedValue(
906
+ makeSubscription({ status: SubscriptionStatus.PENDING, plan: "LAUNCH" }),
907
+ );
908
+ subRepo.updateQuantities.mockResolvedValue(
909
+ makeSubscriptionWithOrg({ status: SubscriptionStatus.ACTIVE }),
910
+ );
911
+
912
+ const promise = service.handleSubscriptionUpdated({
913
+ subscription: {
914
+ id: "sub_stripe_1",
915
+ status: "active",
916
+ canceled_at: null,
917
+ ended_at: null,
918
+ items: { data: [] },
919
+ } as any,
920
+ });
921
+
922
+ await vi.advanceTimersByTimeAsync(2000);
923
+ await promise;
924
+
925
+ expect(mockSendSlackSubscriptionEvent).toHaveBeenCalledWith(
926
+ expect.objectContaining({
927
+ type: "confirmed",
928
+ organizationId: "org_123",
929
+ }),
930
+ );
931
+ });
932
+
933
+ it("skips notification when already active", async () => {
934
+ subRepo.findByStripeId.mockResolvedValue(
935
+ makeSubscription({ status: SubscriptionStatus.ACTIVE, plan: "LAUNCH" }),
936
+ );
937
+ subRepo.updateQuantities.mockResolvedValue(
938
+ makeSubscriptionWithOrg({ status: SubscriptionStatus.ACTIVE }),
939
+ );
940
+
941
+ const promise = service.handleSubscriptionUpdated({
942
+ subscription: {
943
+ id: "sub_stripe_1",
944
+ status: "active",
945
+ canceled_at: null,
946
+ ended_at: null,
947
+ items: { data: [] },
948
+ } as any,
949
+ });
950
+
951
+ await vi.advanceTimersByTimeAsync(2000);
952
+ await promise;
953
+
954
+ expect(mockSendSlackSubscriptionEvent).not.toHaveBeenCalled();
955
+ });
956
+ });
957
+ });
958
+ });