@langwatch/server 3.1.0-beta.3 → 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 (119) 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/langwatch_nlp/uv.lock +179 -5
  118. package/package.json +1 -1
  119. package/packages/server/dist/cli.cjs +192 -142
@@ -0,0 +1,717 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+
3
+ vi.mock("../utils/growthSeatEvent", () => ({
4
+ createCheckoutLineItems: vi.fn().mockReturnValue([
5
+ { price: "price_seat_usd_monthly", quantity: 3 },
6
+ { price: "price_events_usd_monthly" },
7
+ ]),
8
+ GROWTH_SEAT_PLAN_TYPES: [
9
+ "GROWTH_SEAT_EUR_MONTHLY",
10
+ "GROWTH_SEAT_EUR_ANNUAL",
11
+ "GROWTH_SEAT_USD_MONTHLY",
12
+ "GROWTH_SEAT_USD_ANNUAL",
13
+ ],
14
+ isGrowthSeatPrice: vi.fn((id: string) => id.startsWith("price_seat_")),
15
+ resolveGrowthSeatPlanType: vi
16
+ .fn()
17
+ .mockReturnValue("GROWTH_SEAT_USD_MONTHLY"),
18
+ }));
19
+
20
+ import { createSeatEventSubscriptionFns } from "../services/seatEventSubscription";
21
+ import { SubscriptionStatus } from "../planTypes";
22
+ import {
23
+ NoActiveSubscriptionError,
24
+ SubscriptionItemNotFoundError,
25
+ } from "../errors";
26
+
27
+ // ── Mock factories ──────────────────────────────────────────────────────────
28
+
29
+ const createMockStripe = () => ({
30
+ subscriptions: {
31
+ retrieve: vi.fn(),
32
+ update: vi.fn(),
33
+ },
34
+ checkout: {
35
+ sessions: {
36
+ create: vi.fn(),
37
+ },
38
+ },
39
+ invoices: {
40
+ retrieveUpcoming: vi.fn(),
41
+ },
42
+ billingPortal: {
43
+ sessions: {
44
+ create: vi.fn(),
45
+ },
46
+ },
47
+ });
48
+
49
+ const createMockDb = () => ({
50
+ subscription: {
51
+ findMany: vi.fn().mockResolvedValue([]),
52
+ findFirst: vi.fn(),
53
+ create: vi.fn(),
54
+ update: vi.fn(),
55
+ updateMany: vi.fn(),
56
+ },
57
+ organizationInvite: {
58
+ findFirst: vi.fn(),
59
+ create: vi.fn(),
60
+ deleteMany: vi.fn(),
61
+ },
62
+ $transaction: vi.fn((fn: (tx: any) => Promise<any>) =>
63
+ fn({
64
+ subscription: {
65
+ create: vi.fn().mockResolvedValue({ id: "sub_new_1" }),
66
+ },
67
+ organizationInvite: {
68
+ findFirst: vi.fn().mockResolvedValue(null),
69
+ create: vi.fn(),
70
+ },
71
+ }),
72
+ ),
73
+ });
74
+
75
+ // ── Tests ───────────────────────────────────────────────────────────────────
76
+
77
+ describe("seatEventSubscription", () => {
78
+ let stripe: ReturnType<typeof createMockStripe>;
79
+ let db: ReturnType<typeof createMockDb>;
80
+ let service: ReturnType<typeof createSeatEventSubscriptionFns>;
81
+
82
+ beforeEach(() => {
83
+ vi.clearAllMocks();
84
+ stripe = createMockStripe();
85
+ db = createMockDb();
86
+ service = createSeatEventSubscriptionFns({
87
+ stripe: stripe as any,
88
+ db: db as any,
89
+ });
90
+ });
91
+
92
+ // ── previewProration ────────────────────────────────────────────────────
93
+
94
+ describe("previewProration()", () => {
95
+ describe("when active subscription exists with a seat item", () => {
96
+ beforeEach(() => {
97
+ db.subscription.findFirst.mockResolvedValue({
98
+ id: "sub_db_1",
99
+ stripeSubscriptionId: "sub_stripe_1",
100
+ status: SubscriptionStatus.ACTIVE,
101
+ });
102
+
103
+ stripe.subscriptions.retrieve.mockResolvedValue({
104
+ status: "active",
105
+ items: {
106
+ data: [
107
+ {
108
+ id: "si_seat",
109
+ price: {
110
+ id: "price_seat_usd_monthly",
111
+ unit_amount: 2500,
112
+ recurring: { interval: "month" },
113
+ },
114
+ },
115
+ ],
116
+ },
117
+ });
118
+ });
119
+
120
+ it("returns formatted proration amount and recurring total for USD", async () => {
121
+ // "with change" invoice has $15 proration, "current" has $5 existing proration
122
+ stripe.invoices.retrieveUpcoming
123
+ .mockResolvedValueOnce({
124
+ currency: "usd",
125
+ lines: {
126
+ data: [
127
+ { proration: true, amount: 1500 },
128
+ { proration: false, amount: 5000 },
129
+ ],
130
+ },
131
+ })
132
+ .mockResolvedValueOnce({
133
+ currency: "usd",
134
+ lines: {
135
+ data: [{ proration: true, amount: 500 }],
136
+ },
137
+ });
138
+
139
+ const result = await service.previewProration({
140
+ organizationId: "org_1",
141
+ newTotalSeats: 4,
142
+ });
143
+
144
+ // 1000 cents = $10 (whole number, no decimals)
145
+ expect(result.formattedAmountDue).toBe("$10");
146
+ // 4 seats * $25 = $100 (whole number, no decimals)
147
+ expect(result.formattedRecurringTotal).toBe("$100");
148
+ expect(result.billingInterval).toBe("month");
149
+ });
150
+
151
+ it("returns formatted proration amount and recurring total for EUR", async () => {
152
+ stripe.subscriptions.retrieve.mockResolvedValue({
153
+ status: "active",
154
+ items: {
155
+ data: [
156
+ {
157
+ id: "si_seat",
158
+ price: {
159
+ id: "price_seat_eur_monthly",
160
+ unit_amount: 2000,
161
+ recurring: { interval: "month" },
162
+ },
163
+ },
164
+ ],
165
+ },
166
+ });
167
+
168
+ stripe.invoices.retrieveUpcoming
169
+ .mockResolvedValueOnce({
170
+ currency: "eur",
171
+ lines: { data: [{ proration: true, amount: 2000 }] },
172
+ })
173
+ .mockResolvedValueOnce({
174
+ currency: "eur",
175
+ lines: { data: [] },
176
+ });
177
+
178
+ const result = await service.previewProration({
179
+ organizationId: "org_1",
180
+ newTotalSeats: 5,
181
+ });
182
+
183
+ // EUR uses en-IE locale
184
+ expect(result.formattedAmountDue).toBe("\u20AC20");
185
+ expect(result.formattedRecurringTotal).toBe("\u20AC100");
186
+ });
187
+
188
+ it("formats whole-dollar amounts without decimals", async () => {
189
+ stripe.invoices.retrieveUpcoming
190
+ .mockResolvedValueOnce({
191
+ currency: "usd",
192
+ lines: { data: [{ proration: true, amount: 5000 }] },
193
+ })
194
+ .mockResolvedValueOnce({
195
+ currency: "usd",
196
+ lines: { data: [] },
197
+ });
198
+
199
+ const result = await service.previewProration({
200
+ organizationId: "org_1",
201
+ newTotalSeats: 2,
202
+ });
203
+
204
+ // 5000 cents = $50, whole number => no decimals
205
+ expect(result.formattedAmountDue).toBe("$50");
206
+ // 2 * 2500 = 5000 cents = $50
207
+ expect(result.formattedRecurringTotal).toBe("$50");
208
+ });
209
+
210
+ it("formats fractional amounts with two decimal places", async () => {
211
+ stripe.invoices.retrieveUpcoming
212
+ .mockResolvedValueOnce({
213
+ currency: "usd",
214
+ lines: { data: [{ proration: true, amount: 1550 }] },
215
+ })
216
+ .mockResolvedValueOnce({
217
+ currency: "usd",
218
+ lines: { data: [{ proration: true, amount: 100 }] },
219
+ });
220
+
221
+ const result = await service.previewProration({
222
+ organizationId: "org_1",
223
+ newTotalSeats: 1,
224
+ });
225
+
226
+ // (1550 - 100) = 1450 cents = $14.50
227
+ expect(result.formattedAmountDue).toBe("$14.50");
228
+ });
229
+
230
+ it("subtracts existing prorations to isolate incremental cost", async () => {
231
+ stripe.invoices.retrieveUpcoming
232
+ .mockResolvedValueOnce({
233
+ currency: "usd",
234
+ lines: {
235
+ data: [
236
+ { proration: true, amount: 3000 },
237
+ { proration: true, amount: 1000 },
238
+ ],
239
+ },
240
+ })
241
+ .mockResolvedValueOnce({
242
+ currency: "usd",
243
+ lines: {
244
+ data: [{ proration: true, amount: 2000 }],
245
+ },
246
+ });
247
+
248
+ const result = await service.previewProration({
249
+ organizationId: "org_1",
250
+ newTotalSeats: 3,
251
+ });
252
+
253
+ // (3000 + 1000) - 2000 = 2000 cents = $20
254
+ expect(result.formattedAmountDue).toBe("$20");
255
+ });
256
+
257
+ it("passes correct subscription_items to Stripe upstream invoice", async () => {
258
+ stripe.invoices.retrieveUpcoming
259
+ .mockResolvedValueOnce({
260
+ currency: "usd",
261
+ lines: { data: [] },
262
+ })
263
+ .mockResolvedValueOnce({
264
+ currency: "usd",
265
+ lines: { data: [] },
266
+ });
267
+
268
+ await service.previewProration({
269
+ organizationId: "org_1",
270
+ newTotalSeats: 7,
271
+ });
272
+
273
+ expect(stripe.invoices.retrieveUpcoming).toHaveBeenCalledWith({
274
+ subscription: "sub_stripe_1",
275
+ subscription_items: [{ id: "si_seat", quantity: 7 }],
276
+ subscription_proration_behavior: "create_prorations",
277
+ });
278
+ });
279
+ });
280
+
281
+ describe("when no active subscription exists", () => {
282
+ it("throws NoActiveSubscriptionError", async () => {
283
+ db.subscription.findFirst.mockResolvedValue(null);
284
+
285
+ await expect(
286
+ service.previewProration({
287
+ organizationId: "org_1",
288
+ newTotalSeats: 3,
289
+ }),
290
+ ).rejects.toThrow(NoActiveSubscriptionError);
291
+ });
292
+ });
293
+
294
+ describe("when Stripe subscription is not active", () => {
295
+ it("throws NoActiveSubscriptionError", async () => {
296
+ db.subscription.findFirst.mockResolvedValue({
297
+ id: "sub_db_1",
298
+ stripeSubscriptionId: "sub_stripe_1",
299
+ });
300
+
301
+ stripe.subscriptions.retrieve.mockResolvedValue({
302
+ status: "canceled",
303
+ items: { data: [] },
304
+ });
305
+
306
+ await expect(
307
+ service.previewProration({
308
+ organizationId: "org_1",
309
+ newTotalSeats: 3,
310
+ }),
311
+ ).rejects.toThrow(NoActiveSubscriptionError);
312
+ });
313
+ });
314
+
315
+ describe("when no seat item found on subscription", () => {
316
+ it("throws SubscriptionItemNotFoundError", async () => {
317
+ db.subscription.findFirst.mockResolvedValue({
318
+ id: "sub_db_1",
319
+ stripeSubscriptionId: "sub_stripe_1",
320
+ });
321
+
322
+ stripe.subscriptions.retrieve.mockResolvedValue({
323
+ status: "active",
324
+ items: {
325
+ data: [
326
+ {
327
+ id: "si_events",
328
+ price: { id: "price_events_usd_monthly" },
329
+ },
330
+ ],
331
+ },
332
+ });
333
+
334
+ await expect(
335
+ service.previewProration({
336
+ organizationId: "org_1",
337
+ newTotalSeats: 3,
338
+ }),
339
+ ).rejects.toThrow(SubscriptionItemNotFoundError);
340
+ });
341
+ });
342
+ });
343
+
344
+ // ── updateSeatEventItems ──────────────────────────────────────────────────
345
+
346
+ describe("updateSeatEventItems()", () => {
347
+ describe("when active subscription exists with a seat item", () => {
348
+ beforeEach(() => {
349
+ db.subscription.findFirst.mockResolvedValue({
350
+ id: "sub_db_1",
351
+ stripeSubscriptionId: "sub_stripe_1",
352
+ status: SubscriptionStatus.ACTIVE,
353
+ });
354
+
355
+ stripe.subscriptions.retrieve.mockResolvedValue({
356
+ status: "active",
357
+ canceled_at: null,
358
+ items: {
359
+ data: [
360
+ { id: "si_seat", price: { id: "price_seat_usd_monthly" } },
361
+ ],
362
+ },
363
+ });
364
+
365
+ stripe.subscriptions.update.mockResolvedValue({});
366
+ });
367
+
368
+ it("updates Stripe subscription seat quantity", async () => {
369
+ const result = await service.updateSeatEventItems({
370
+ organizationId: "org_1",
371
+ totalMembers: 10,
372
+ });
373
+
374
+ expect(result).toEqual({ success: true });
375
+ expect(stripe.subscriptions.update).toHaveBeenCalledWith(
376
+ "sub_stripe_1",
377
+ {
378
+ items: [{ id: "si_seat", quantity: 10 }],
379
+ proration_behavior: "always_invoice",
380
+ },
381
+ );
382
+ });
383
+
384
+ it("updates DB subscription to ACTIVE with new seat count", async () => {
385
+ await service.updateSeatEventItems({
386
+ organizationId: "org_1",
387
+ totalMembers: 8,
388
+ });
389
+
390
+ expect(db.subscription.update).toHaveBeenCalledWith({
391
+ where: { id: "sub_db_1" },
392
+ data: {
393
+ status: SubscriptionStatus.ACTIVE,
394
+ maxMembers: 8,
395
+ endDate: null,
396
+ },
397
+ });
398
+ });
399
+ });
400
+
401
+ describe("when subscription is scheduled for cancellation", () => {
402
+ it("reactivates by setting cancel_at_period_end to false", async () => {
403
+ db.subscription.findFirst.mockResolvedValue({
404
+ id: "sub_db_1",
405
+ stripeSubscriptionId: "sub_stripe_1",
406
+ status: SubscriptionStatus.ACTIVE,
407
+ });
408
+
409
+ stripe.subscriptions.retrieve.mockResolvedValue({
410
+ status: "active",
411
+ canceled_at: 1700000000,
412
+ items: {
413
+ data: [
414
+ { id: "si_seat", price: { id: "price_seat_usd_monthly" } },
415
+ ],
416
+ },
417
+ });
418
+
419
+ stripe.subscriptions.update.mockResolvedValue({});
420
+
421
+ await service.updateSeatEventItems({
422
+ organizationId: "org_1",
423
+ totalMembers: 5,
424
+ });
425
+
426
+ expect(stripe.subscriptions.update).toHaveBeenCalledWith(
427
+ "sub_stripe_1",
428
+ {
429
+ cancel_at_period_end: false,
430
+ items: [{ id: "si_seat", quantity: 5 }],
431
+ proration_behavior: "always_invoice",
432
+ },
433
+ );
434
+ });
435
+ });
436
+
437
+ describe("when no DB subscription has a stripe ID", () => {
438
+ it("returns success false", async () => {
439
+ db.subscription.findFirst.mockResolvedValue(null);
440
+
441
+ const result = await service.updateSeatEventItems({
442
+ organizationId: "org_1",
443
+ totalMembers: 5,
444
+ });
445
+
446
+ expect(result).toEqual({ success: false });
447
+ expect(stripe.subscriptions.retrieve).not.toHaveBeenCalled();
448
+ });
449
+ });
450
+
451
+ describe("when Stripe subscription status is not active", () => {
452
+ it("returns success false", async () => {
453
+ db.subscription.findFirst.mockResolvedValue({
454
+ id: "sub_db_1",
455
+ stripeSubscriptionId: "sub_stripe_1",
456
+ });
457
+
458
+ stripe.subscriptions.retrieve.mockResolvedValue({
459
+ status: "canceled",
460
+ items: { data: [] },
461
+ });
462
+
463
+ const result = await service.updateSeatEventItems({
464
+ organizationId: "org_1",
465
+ totalMembers: 5,
466
+ });
467
+
468
+ expect(result).toEqual({ success: false });
469
+ expect(stripe.subscriptions.update).not.toHaveBeenCalled();
470
+ });
471
+ });
472
+
473
+ describe("when no seat item found on Stripe subscription", () => {
474
+ it("returns success false", async () => {
475
+ db.subscription.findFirst.mockResolvedValue({
476
+ id: "sub_db_1",
477
+ stripeSubscriptionId: "sub_stripe_1",
478
+ });
479
+
480
+ stripe.subscriptions.retrieve.mockResolvedValue({
481
+ status: "active",
482
+ items: {
483
+ data: [
484
+ {
485
+ id: "si_events",
486
+ price: { id: "price_events_usd_monthly" },
487
+ },
488
+ ],
489
+ },
490
+ });
491
+
492
+ const result = await service.updateSeatEventItems({
493
+ organizationId: "org_1",
494
+ totalMembers: 5,
495
+ });
496
+
497
+ expect(result).toEqual({ success: false });
498
+ expect(stripe.subscriptions.update).not.toHaveBeenCalled();
499
+ });
500
+ });
501
+ });
502
+
503
+ // ── createSeatEventCheckout ───────────────────────────────────────────────
504
+
505
+ describe("createSeatEventCheckout()", () => {
506
+ describe("when stale PENDING subscriptions exist", () => {
507
+ beforeEach(() => {
508
+ db.subscription.findMany.mockResolvedValue([
509
+ { id: "stale_sub_1" },
510
+ { id: "stale_sub_2" },
511
+ ]);
512
+
513
+ stripe.checkout.sessions.create.mockResolvedValue({
514
+ url: "https://checkout.stripe.com/session",
515
+ });
516
+ });
517
+
518
+ it("cancels stale PENDING subscriptions", async () => {
519
+ await service.createSeatEventCheckout({
520
+ organizationId: "org_1",
521
+ customerId: "cus_1",
522
+ baseUrl: "https://app.test",
523
+ currency: "USD" as any,
524
+ billingInterval: "monthly",
525
+ membersToAdd: 3,
526
+ });
527
+
528
+ expect(db.subscription.updateMany).toHaveBeenCalledWith({
529
+ where: {
530
+ organizationId: "org_1",
531
+ plan: {
532
+ in: [
533
+ "GROWTH_SEAT_EUR_MONTHLY",
534
+ "GROWTH_SEAT_EUR_ANNUAL",
535
+ "GROWTH_SEAT_USD_MONTHLY",
536
+ "GROWTH_SEAT_USD_ANNUAL",
537
+ ],
538
+ },
539
+ status: SubscriptionStatus.PENDING,
540
+ },
541
+ data: {
542
+ status: SubscriptionStatus.CANCELLED,
543
+ endDate: expect.any(Date),
544
+ },
545
+ });
546
+ });
547
+
548
+ it("deletes orphaned PAYMENT_PENDING invites from stale subs", async () => {
549
+ await service.createSeatEventCheckout({
550
+ organizationId: "org_1",
551
+ customerId: "cus_1",
552
+ baseUrl: "https://app.test",
553
+ currency: "USD" as any,
554
+ billingInterval: "monthly",
555
+ membersToAdd: 3,
556
+ });
557
+
558
+ expect(db.organizationInvite.deleteMany).toHaveBeenCalledWith({
559
+ where: {
560
+ organizationId: "org_1",
561
+ status: "PAYMENT_PENDING",
562
+ subscriptionId: { in: ["stale_sub_1", "stale_sub_2"] },
563
+ },
564
+ });
565
+ });
566
+ });
567
+
568
+ describe("when no stale subscriptions exist", () => {
569
+ beforeEach(() => {
570
+ db.subscription.findMany.mockResolvedValue([]);
571
+
572
+ stripe.checkout.sessions.create.mockResolvedValue({
573
+ url: "https://checkout.stripe.com/session",
574
+ });
575
+ });
576
+
577
+ it("skips invite cleanup", async () => {
578
+ await service.createSeatEventCheckout({
579
+ organizationId: "org_1",
580
+ customerId: "cus_1",
581
+ baseUrl: "https://app.test",
582
+ currency: "USD" as any,
583
+ billingInterval: "monthly",
584
+ membersToAdd: 2,
585
+ });
586
+
587
+ expect(db.organizationInvite.deleteMany).not.toHaveBeenCalled();
588
+ });
589
+ });
590
+
591
+ describe("when creating checkout session", () => {
592
+ beforeEach(() => {
593
+ db.subscription.findMany.mockResolvedValue([]);
594
+
595
+ stripe.checkout.sessions.create.mockResolvedValue({
596
+ url: "https://checkout.stripe.com/session_abc",
597
+ });
598
+ });
599
+
600
+ it("returns the checkout session URL", async () => {
601
+ const result = await service.createSeatEventCheckout({
602
+ organizationId: "org_1",
603
+ customerId: "cus_1",
604
+ baseUrl: "https://app.test",
605
+ currency: "USD" as any,
606
+ billingInterval: "monthly",
607
+ membersToAdd: 3,
608
+ });
609
+
610
+ expect(result).toEqual({
611
+ url: "https://checkout.stripe.com/session_abc",
612
+ });
613
+ });
614
+
615
+ it("creates Stripe checkout with correct line items and metadata", async () => {
616
+ await service.createSeatEventCheckout({
617
+ organizationId: "org_1",
618
+ customerId: "cus_1",
619
+ baseUrl: "https://app.test",
620
+ currency: "USD" as any,
621
+ billingInterval: "monthly",
622
+ membersToAdd: 3,
623
+ });
624
+
625
+ expect(stripe.checkout.sessions.create).toHaveBeenCalledWith(
626
+ expect.objectContaining({
627
+ mode: "subscription",
628
+ customer: "cus_1",
629
+ line_items: [
630
+ { price: "price_seat_usd_monthly", quantity: 3 },
631
+ { price: "price_events_usd_monthly" },
632
+ ],
633
+ metadata: {
634
+ selectedCurrency: "USD",
635
+ selectedBillingInterval: "monthly",
636
+ },
637
+ client_reference_id: "subscription_setup_sub_new_1",
638
+ allow_promotion_codes: true,
639
+ }),
640
+ );
641
+ });
642
+
643
+ it("sets success URL without upgrade param by default", async () => {
644
+ await service.createSeatEventCheckout({
645
+ organizationId: "org_1",
646
+ customerId: "cus_1",
647
+ baseUrl: "https://app.test",
648
+ currency: "USD" as any,
649
+ billingInterval: "monthly",
650
+ membersToAdd: 3,
651
+ });
652
+
653
+ const callArgs = stripe.checkout.sessions.create.mock.calls[0]![0];
654
+ expect(callArgs.success_url).toBe(
655
+ "https://app.test/settings/subscription?success",
656
+ );
657
+ });
658
+
659
+ it("appends upgraded_from param when isUpgradeFromTiered is true", async () => {
660
+ await service.createSeatEventCheckout({
661
+ organizationId: "org_1",
662
+ customerId: "cus_1",
663
+ baseUrl: "https://app.test",
664
+ currency: "USD" as any,
665
+ billingInterval: "monthly",
666
+ membersToAdd: 3,
667
+ isUpgradeFromTiered: true,
668
+ });
669
+
670
+ const callArgs = stripe.checkout.sessions.create.mock.calls[0]![0];
671
+ expect(callArgs.success_url).toBe(
672
+ "https://app.test/settings/subscription?success&upgraded_from=tiered",
673
+ );
674
+ });
675
+
676
+ it("sets billing_cycle_anchor to the 1st of next month", async () => {
677
+ await service.createSeatEventCheckout({
678
+ organizationId: "org_1",
679
+ customerId: "cus_1",
680
+ baseUrl: "https://app.test",
681
+ currency: "USD" as any,
682
+ billingInterval: "monthly",
683
+ membersToAdd: 3,
684
+ });
685
+
686
+ const callArgs = stripe.checkout.sessions.create.mock.calls[0]![0];
687
+ const anchor =
688
+ callArgs.subscription_data.billing_cycle_anchor as number;
689
+
690
+ // Anchor should be a Unix timestamp for the 1st of next month
691
+ const anchorDate = new Date(anchor * 1000);
692
+ expect(anchorDate.getUTCDate()).toBe(1);
693
+ });
694
+ });
695
+ });
696
+
697
+ // ── seatEventBillingPortalUrl ─────────────────────────────────────────────
698
+
699
+ describe("seatEventBillingPortalUrl()", () => {
700
+ it("creates portal session and returns URL", async () => {
701
+ stripe.billingPortal.sessions.create.mockResolvedValue({
702
+ url: "https://billing.stripe.com/portal",
703
+ });
704
+
705
+ const result = await service.seatEventBillingPortalUrl({
706
+ customerId: "cus_1",
707
+ baseUrl: "https://app.test",
708
+ });
709
+
710
+ expect(result).toEqual({ url: "https://billing.stripe.com/portal" });
711
+ expect(stripe.billingPortal.sessions.create).toHaveBeenCalledWith({
712
+ customer: "cus_1",
713
+ return_url: "https://app.test/settings/subscription",
714
+ });
715
+ });
716
+ });
717
+ });