@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,706 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // Mocks
5
+ // ---------------------------------------------------------------------------
6
+
7
+ vi.mock("../../../src/env.mjs", () => ({
8
+ env: {
9
+ IS_SAAS: true,
10
+ BASE_HOST: "https://app.langwatch.ai",
11
+ },
12
+ }));
13
+
14
+ vi.mock("../../../src/utils/logger/server", () => ({
15
+ createLogger: () => ({
16
+ error: vi.fn(),
17
+ warn: vi.fn(),
18
+ info: vi.fn(),
19
+ debug: vi.fn(),
20
+ }),
21
+ }));
22
+
23
+ vi.mock("../../../src/utils/posthogErrorCapture", () => ({
24
+ captureException: vi.fn(),
25
+ }));
26
+
27
+ vi.mock("../../../src/server/app-layer/app", () => ({
28
+ getApp: vi.fn(),
29
+ }));
30
+
31
+ vi.mock("../../../src/server/utils/dateUtils", () => ({
32
+ getCurrentMonthStart: vi.fn(() => new Date("2025-01-01T00:00:00.000Z")),
33
+ }));
34
+
35
+ import { env } from "../../../src/env.mjs";
36
+ import {
37
+ UsageLimitService,
38
+ resourceLimitCooldown,
39
+ planLimitCooldown,
40
+ planLimitInFlight,
41
+ } from "../notifications/usage-limit.service";
42
+ import type { NotificationService } from "../notifications/notification.service";
43
+ import type { NotificationRepository } from "../notifications/repositories/notification.repository";
44
+ import type { OrganizationService } from "../../../src/server/app-layer/organizations/organization.service";
45
+ import type { UsageService } from "../../../src/server/app-layer/usage/usage.service";
46
+ import type { PlanProvider } from "../../../src/server/app-layer/subscription/plan-provider";
47
+
48
+ // ---------------------------------------------------------------------------
49
+ // Helpers
50
+ // ---------------------------------------------------------------------------
51
+
52
+ function createMockNotificationService(): NotificationService {
53
+ return {
54
+ sendUsageLimitEmail: vi.fn().mockResolvedValue(undefined),
55
+ sendSlackPlanLimitAlert: vi.fn().mockResolvedValue(undefined),
56
+ sendSlackResourceLimitAlert: vi.fn().mockResolvedValue(undefined),
57
+ sendSlackSubscriptionEvent: vi.fn().mockResolvedValue(undefined),
58
+ sendSlackSignupEvent: vi.fn().mockResolvedValue(undefined),
59
+ sendSlackLicensePurchase: vi.fn().mockResolvedValue(undefined),
60
+ sendHubspotPlanLimitForm: vi.fn().mockResolvedValue(undefined),
61
+ } as unknown as NotificationService;
62
+ }
63
+
64
+ function createMockNotificationRepository(): NotificationRepository {
65
+ return {
66
+ findRecentByOrganization: vi.fn().mockResolvedValue([]),
67
+ create: vi.fn().mockImplementation((params: Record<string, unknown>) => ({
68
+ id: "notif_1",
69
+ ...params,
70
+ createdAt: new Date(),
71
+ updatedAt: new Date(),
72
+ })),
73
+ findById: vi.fn().mockResolvedValue(null),
74
+ } as unknown as NotificationRepository;
75
+ }
76
+
77
+ function createMockOrganizationService(): OrganizationService {
78
+ return {
79
+ findWithAdmins: vi.fn().mockResolvedValue(null),
80
+ updateSentPlanLimitAlert: vi.fn().mockResolvedValue(undefined),
81
+ findProjectsWithName: vi.fn().mockResolvedValue([]),
82
+ getOrganizationIdByTeamId: vi.fn().mockResolvedValue(null),
83
+ getProjectIds: vi.fn().mockResolvedValue([]),
84
+ isFeatureEnabled: vi.fn().mockResolvedValue(false),
85
+ } as unknown as OrganizationService;
86
+ }
87
+
88
+ function createMockUsageService(): UsageService {
89
+ return {
90
+ getCountByProjects: vi.fn().mockResolvedValue([]),
91
+ checkLimit: vi.fn(),
92
+ } as unknown as UsageService;
93
+ }
94
+
95
+ function createMockPlanProvider(): PlanProvider {
96
+ return {
97
+ getActivePlan: vi.fn().mockResolvedValue({ name: "Launch" }),
98
+ } as unknown as PlanProvider;
99
+ }
100
+
101
+ function createService({
102
+ notificationRepository = createMockNotificationRepository(),
103
+ organizationService = createMockOrganizationService(),
104
+ usageService = createMockUsageService(),
105
+ notificationService = createMockNotificationService(),
106
+ planProvider = createMockPlanProvider(),
107
+ } = {}) {
108
+ return {
109
+ service: UsageLimitService.create({
110
+ notificationRepository,
111
+ organizationService,
112
+ usageService,
113
+ notificationService,
114
+ planProvider,
115
+ }),
116
+ notificationRepository,
117
+ organizationService,
118
+ usageService,
119
+ notificationService,
120
+ planProvider,
121
+ };
122
+ }
123
+
124
+ const ORG_WITH_ADMIN = {
125
+ id: "org_1",
126
+ name: "Acme Corp",
127
+ sentPlanLimitAlert: null,
128
+ members: [
129
+ {
130
+ role: "ADMIN",
131
+ user: {
132
+ id: "user_1",
133
+ name: "Jane Admin",
134
+ email: "jane@example.com",
135
+ },
136
+ },
137
+ ],
138
+ };
139
+
140
+ // ---------------------------------------------------------------------------
141
+ // Tests
142
+ // ---------------------------------------------------------------------------
143
+
144
+ describe("UsageLimitService", () => {
145
+ describe("create()", () => {
146
+ it("returns a UsageLimitService instance", () => {
147
+ const { service } = createService();
148
+ expect(service).toBeInstanceOf(UsageLimitService);
149
+ });
150
+ });
151
+
152
+ // -------------------------------------------------------------------------
153
+ // notifyPlanLimitReached
154
+ // -------------------------------------------------------------------------
155
+
156
+ describe("notifyPlanLimitReached()", () => {
157
+ afterEach(async () => {
158
+ planLimitInFlight.delete("org_1");
159
+ planLimitInFlight.delete("org_missing");
160
+ await planLimitCooldown.delete("org_1");
161
+ await planLimitCooldown.delete("org_missing");
162
+ });
163
+
164
+ describe("when IS_SAAS is false", () => {
165
+ beforeEach(() => {
166
+ vi.mocked(env).IS_SAAS = false;
167
+ });
168
+
169
+ afterEach(() => {
170
+ vi.mocked(env).IS_SAAS = true;
171
+ });
172
+
173
+ it("returns early without querying the database", async () => {
174
+ const { service, organizationService } = createService();
175
+
176
+ await service.notifyPlanLimitReached({
177
+ organizationId: "org_1",
178
+ planName: "free",
179
+ });
180
+
181
+ expect(organizationService.findWithAdmins).not.toHaveBeenCalled();
182
+ });
183
+ });
184
+
185
+ describe("when organization is not found", () => {
186
+ it("returns without sending notifications", async () => {
187
+ const { service, organizationService, notificationService } = createService();
188
+ (organizationService.findWithAdmins as ReturnType<typeof vi.fn>).mockResolvedValue(null);
189
+
190
+ await service.notifyPlanLimitReached({
191
+ organizationId: "org_missing",
192
+ planName: "free",
193
+ });
194
+
195
+ expect(notificationService.sendSlackPlanLimitAlert).not.toHaveBeenCalled();
196
+ expect(notificationService.sendHubspotPlanLimitForm).not.toHaveBeenCalled();
197
+ });
198
+ });
199
+
200
+ describe("when alert was sent recently (within 30 days)", () => {
201
+ it("returns without sending notifications", async () => {
202
+ const { service, organizationService, notificationService } = createService();
203
+ (organizationService.findWithAdmins as ReturnType<typeof vi.fn>).mockResolvedValue({
204
+ ...ORG_WITH_ADMIN,
205
+ sentPlanLimitAlert: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000), // 10 days ago
206
+ });
207
+
208
+ await service.notifyPlanLimitReached({
209
+ organizationId: "org_1",
210
+ planName: "free",
211
+ });
212
+
213
+ expect(notificationService.sendSlackPlanLimitAlert).not.toHaveBeenCalled();
214
+ });
215
+ });
216
+
217
+ describe("when no recent alert exists", () => {
218
+ it("sends Slack and Hubspot notifications and updates the timestamp", async () => {
219
+ const { service, organizationService, notificationService } = createService();
220
+ (organizationService.findWithAdmins as ReturnType<typeof vi.fn>).mockResolvedValue(ORG_WITH_ADMIN);
221
+
222
+ await service.notifyPlanLimitReached({
223
+ organizationId: "org_1",
224
+ planName: "free",
225
+ });
226
+
227
+ expect(notificationService.sendSlackPlanLimitAlert).toHaveBeenCalledWith(
228
+ expect.objectContaining({
229
+ organizationId: "org_1",
230
+ organizationName: "Acme Corp",
231
+ adminName: "Jane Admin",
232
+ adminEmail: "jane@example.com",
233
+ planName: "free",
234
+ }),
235
+ );
236
+ expect(notificationService.sendHubspotPlanLimitForm).toHaveBeenCalledWith(
237
+ expect.objectContaining({
238
+ organizationId: "org_1",
239
+ }),
240
+ );
241
+ expect(organizationService.updateSentPlanLimitAlert).toHaveBeenCalledWith(
242
+ "org_1",
243
+ expect.any(Date),
244
+ );
245
+ });
246
+ });
247
+
248
+ describe("when alert was sent more than 30 days ago", () => {
249
+ it("sends notifications again", async () => {
250
+ const { service, organizationService, notificationService } = createService();
251
+ (organizationService.findWithAdmins as ReturnType<typeof vi.fn>).mockResolvedValue({
252
+ ...ORG_WITH_ADMIN,
253
+ sentPlanLimitAlert: new Date(Date.now() - 31 * 24 * 60 * 60 * 1000), // 31 days ago
254
+ });
255
+
256
+ await service.notifyPlanLimitReached({
257
+ organizationId: "org_1",
258
+ planName: "free",
259
+ });
260
+
261
+ expect(notificationService.sendSlackPlanLimitAlert).toHaveBeenCalled();
262
+ });
263
+ });
264
+
265
+ describe("when called concurrently for the same organization", () => {
266
+ it("sends only one notification", async () => {
267
+ const { service, organizationService, notificationService } = createService();
268
+ (organizationService.findWithAdmins as ReturnType<typeof vi.fn>).mockResolvedValue(ORG_WITH_ADMIN);
269
+
270
+ await Promise.all([
271
+ service.notifyPlanLimitReached({ organizationId: "org_1", planName: "free" }),
272
+ service.notifyPlanLimitReached({ organizationId: "org_1", planName: "free" }),
273
+ service.notifyPlanLimitReached({ organizationId: "org_1", planName: "free" }),
274
+ service.notifyPlanLimitReached({ organizationId: "org_1", planName: "free" }),
275
+ service.notifyPlanLimitReached({ organizationId: "org_1", planName: "free" }),
276
+ ]);
277
+
278
+ expect(notificationService.sendSlackPlanLimitAlert).toHaveBeenCalledTimes(1);
279
+ });
280
+ });
281
+
282
+ describe("when called again after cooldown expires", () => {
283
+ it("sends notification again", async () => {
284
+ const { service, organizationService, notificationService } = createService();
285
+ (organizationService.findWithAdmins as ReturnType<typeof vi.fn>).mockResolvedValue(ORG_WITH_ADMIN);
286
+
287
+ await service.notifyPlanLimitReached({ organizationId: "org_1", planName: "free" });
288
+ expect(notificationService.sendSlackPlanLimitAlert).toHaveBeenCalledTimes(1);
289
+
290
+ // Simulate cooldown expiry
291
+ planLimitInFlight.delete("org_1");
292
+ await planLimitCooldown.delete("org_1");
293
+ vi.mocked(notificationService.sendSlackPlanLimitAlert as ReturnType<typeof vi.fn>).mockClear();
294
+
295
+ await service.notifyPlanLimitReached({ organizationId: "org_1", planName: "free" });
296
+ expect(notificationService.sendSlackPlanLimitAlert).toHaveBeenCalledTimes(1);
297
+ });
298
+ });
299
+
300
+ describe("when one notification channel fails", () => {
301
+ it("completes without throwing (fire-and-forget sends)", async () => {
302
+ const { service, organizationService, notificationService } = createService();
303
+ (organizationService.findWithAdmins as ReturnType<typeof vi.fn>).mockResolvedValue(ORG_WITH_ADMIN);
304
+ (notificationService.sendSlackPlanLimitAlert as ReturnType<typeof vi.fn>)
305
+ .mockRejectedValueOnce(new Error("Slack down"));
306
+
307
+ // Should not throw — allSettled absorbs the rejection
308
+ await service.notifyPlanLimitReached({ organizationId: "org_1", planName: "free" });
309
+
310
+ expect(notificationService.sendSlackPlanLimitAlert).toHaveBeenCalledTimes(1);
311
+ expect(notificationService.sendHubspotPlanLimitForm).toHaveBeenCalledTimes(1);
312
+ });
313
+ });
314
+ });
315
+
316
+ // -------------------------------------------------------------------------
317
+ // notifyResourceLimitReached
318
+ // -------------------------------------------------------------------------
319
+
320
+ describe("notifyResourceLimitReached()", () => {
321
+ // Clear all known cooldown keys between tests so cache state doesn't bleed across test cases
322
+ beforeEach(async () => {
323
+ await resourceLimitCooldown.delete("org_1:workflows");
324
+ await resourceLimitCooldown.delete("org_1:agents");
325
+ await resourceLimitCooldown.delete("org_missing:workflows");
326
+ });
327
+
328
+ describe("when IS_SAAS is false", () => {
329
+ beforeEach(() => {
330
+ vi.mocked(env).IS_SAAS = false;
331
+ });
332
+
333
+ afterEach(() => {
334
+ vi.mocked(env).IS_SAAS = true;
335
+ });
336
+
337
+ it("returns without sending", async () => {
338
+ const { service, notificationService } = createService();
339
+
340
+ await service.notifyResourceLimitReached({
341
+ organizationId: "org_1",
342
+ limitType: "workflows",
343
+ current: 5,
344
+ max: 5,
345
+ });
346
+
347
+ expect(
348
+ notificationService.sendSlackResourceLimitAlert,
349
+ ).not.toHaveBeenCalled();
350
+ });
351
+ });
352
+
353
+ describe("when cooldown is active for the organization and limit type", () => {
354
+ it("suppresses the notification", async () => {
355
+ const { service, notificationService } = createService();
356
+
357
+ await resourceLimitCooldown.set("org_1:workflows", true);
358
+
359
+ await service.notifyResourceLimitReached({
360
+ organizationId: "org_1",
361
+ limitType: "workflows",
362
+ current: 5,
363
+ max: 5,
364
+ });
365
+
366
+ expect(
367
+ notificationService.sendSlackResourceLimitAlert,
368
+ ).not.toHaveBeenCalled();
369
+ });
370
+ });
371
+
372
+ describe("when cooldown is active for a different limit type", () => {
373
+ it("sends the notification (cooldown is per-org+type)", async () => {
374
+ const { service, organizationService, notificationService } = createService();
375
+ (organizationService.findWithAdmins as ReturnType<typeof vi.fn>).mockResolvedValue(ORG_WITH_ADMIN);
376
+
377
+ // First call sets the cooldown for workflows
378
+ await service.notifyResourceLimitReached({
379
+ organizationId: "org_1",
380
+ limitType: "workflows",
381
+ current: 5,
382
+ max: 5,
383
+ });
384
+
385
+ vi.mocked(
386
+ notificationService.sendSlackResourceLimitAlert as ReturnType<
387
+ typeof vi.fn
388
+ >,
389
+ ).mockClear();
390
+
391
+ // Second call with different type is NOT suppressed
392
+ await service.notifyResourceLimitReached({
393
+ organizationId: "org_1",
394
+ limitType: "agents",
395
+ current: 3,
396
+ max: 3,
397
+ });
398
+
399
+ expect(
400
+ notificationService.sendSlackResourceLimitAlert,
401
+ ).toHaveBeenCalled();
402
+ });
403
+ });
404
+
405
+ describe("when notification conditions are met", () => {
406
+ it("sends correct payload with org name, admin, plan, display label, and counts", async () => {
407
+ const { service, organizationService, notificationService } = createService();
408
+ (organizationService.findWithAdmins as ReturnType<typeof vi.fn>).mockResolvedValue(ORG_WITH_ADMIN);
409
+
410
+ await service.notifyResourceLimitReached({
411
+ organizationId: "org_1",
412
+ limitType: "workflows",
413
+ current: 5,
414
+ max: 5,
415
+ });
416
+
417
+ expect(
418
+ notificationService.sendSlackResourceLimitAlert,
419
+ ).toHaveBeenCalledWith({
420
+ organizationId: "org_1",
421
+ organizationName: "Acme Corp",
422
+ adminName: "Jane Admin",
423
+ adminEmail: "jane@example.com",
424
+ planName: "Launch",
425
+ limitType: "Workflows",
426
+ current: 5,
427
+ max: 5,
428
+ });
429
+ });
430
+ });
431
+
432
+ describe("when called concurrently for the same organization", () => {
433
+ it("sends at most one notification per concurrent batch (in-memory cooldown has a race window)", async () => {
434
+ const { service, organizationService, notificationService } = createService();
435
+ (organizationService.findWithAdmins as ReturnType<typeof vi.fn>).mockResolvedValue(ORG_WITH_ADMIN);
436
+
437
+ await Promise.all([
438
+ service.notifyResourceLimitReached({
439
+ organizationId: "org_1",
440
+ limitType: "workflows",
441
+ current: 5,
442
+ max: 5,
443
+ }),
444
+ service.notifyResourceLimitReached({
445
+ organizationId: "org_1",
446
+ limitType: "workflows",
447
+ current: 5,
448
+ max: 5,
449
+ }),
450
+ ]);
451
+
452
+ // The in-memory cooldown has a documented race window: two concurrent calls both see
453
+ // a cache miss before either writes the cooldown entry. The worst case is a duplicate
454
+ // alert (see NOTE in usage-limit.service.ts). Both calls proceed when concurrent.
455
+ expect(
456
+ notificationService.sendSlackResourceLimitAlert,
457
+ ).toHaveBeenCalledTimes(2);
458
+ });
459
+ });
460
+
461
+ describe("when organization is not found", () => {
462
+ it("releases the cooldown", async () => {
463
+ const { service, organizationService } = createService();
464
+ (organizationService.findWithAdmins as ReturnType<typeof vi.fn>).mockResolvedValue(null);
465
+
466
+ await service.notifyResourceLimitReached({
467
+ organizationId: "org_missing",
468
+ limitType: "workflows",
469
+ current: 5,
470
+ max: 5,
471
+ });
472
+
473
+ expect(await resourceLimitCooldown.get("org_missing:workflows")).toBeUndefined();
474
+ });
475
+ });
476
+
477
+ describe("when notification dispatch fails", () => {
478
+ it("releases the cooldown", async () => {
479
+ const { service, organizationService, notificationService } = createService();
480
+ (organizationService.findWithAdmins as ReturnType<typeof vi.fn>).mockResolvedValue(ORG_WITH_ADMIN);
481
+ (
482
+ notificationService.sendSlackResourceLimitAlert as ReturnType<
483
+ typeof vi.fn
484
+ >
485
+ ).mockRejectedValue(new Error("Slack down"));
486
+
487
+ await service.notifyResourceLimitReached({
488
+ organizationId: "org_1",
489
+ limitType: "workflows",
490
+ current: 5,
491
+ max: 5,
492
+ });
493
+
494
+ expect(await resourceLimitCooldown.get("org_1:workflows")).toBeUndefined();
495
+ });
496
+ });
497
+
498
+ describe("when plan provider fails", () => {
499
+ it("sends notification with 'unknown' plan name", async () => {
500
+ const failingPlanProvider: PlanProvider = {
501
+ getActivePlan: vi.fn().mockRejectedValue(new Error("plan error")),
502
+ } as unknown as PlanProvider;
503
+ const organizationService = createMockOrganizationService();
504
+ (organizationService.findWithAdmins as ReturnType<typeof vi.fn>).mockResolvedValue(ORG_WITH_ADMIN);
505
+ const { service, notificationService } = createService({
506
+ organizationService,
507
+ planProvider: failingPlanProvider,
508
+ });
509
+
510
+ await service.notifyResourceLimitReached({
511
+ organizationId: "org_1",
512
+ limitType: "workflows",
513
+ current: 5,
514
+ max: 5,
515
+ });
516
+
517
+ expect(
518
+ notificationService.sendSlackResourceLimitAlert,
519
+ ).toHaveBeenCalledWith(
520
+ expect.objectContaining({
521
+ planName: "unknown",
522
+ }),
523
+ );
524
+ });
525
+ });
526
+ });
527
+
528
+ // -------------------------------------------------------------------------
529
+ // checkAndSendWarning
530
+ // -------------------------------------------------------------------------
531
+
532
+ describe("checkAndSendWarning()", () => {
533
+ describe("when usage is below all thresholds", () => {
534
+ it("returns null without sending emails", async () => {
535
+ const { service, notificationService } = createService();
536
+
537
+ const result = await service.checkAndSendWarning({
538
+ organizationId: "org_1",
539
+ currentMonthMessagesCount: 100,
540
+ maxMonthlyUsageLimit: 10000,
541
+ });
542
+
543
+ expect(result).toBeNull();
544
+ expect(notificationService.sendUsageLimitEmail).not.toHaveBeenCalled();
545
+ });
546
+ });
547
+
548
+ describe("when usage exceeds 50% threshold", () => {
549
+ beforeEach(() => {
550
+ vi.clearAllMocks();
551
+ });
552
+
553
+ it("sends email to admin members and creates notification record", async () => {
554
+ const { service, organizationService, usageService, notificationService } = createService();
555
+ (organizationService.findWithAdmins as ReturnType<typeof vi.fn>).mockResolvedValue(ORG_WITH_ADMIN);
556
+ (organizationService.findProjectsWithName as ReturnType<typeof vi.fn>).mockResolvedValue([
557
+ { id: "p1", name: "My Project" },
558
+ ]);
559
+ (usageService.getCountByProjects as ReturnType<typeof vi.fn>).mockResolvedValue([
560
+ { projectId: "p1", count: 5500 },
561
+ ]);
562
+
563
+ const result = await service.checkAndSendWarning({
564
+ organizationId: "org_1",
565
+ currentMonthMessagesCount: 5500,
566
+ maxMonthlyUsageLimit: 10000,
567
+ });
568
+
569
+ expect(notificationService.sendUsageLimitEmail).toHaveBeenCalledWith(
570
+ expect.objectContaining({
571
+ to: "jane@example.com",
572
+ orgName: "Acme Corp",
573
+ usageData: expect.objectContaining({
574
+ crossedThreshold: 50,
575
+ currentMonthMessagesCount: 5500,
576
+ maxMonthlyUsageLimit: 10000,
577
+ }),
578
+ }),
579
+ );
580
+ expect(result).toMatchObject({
581
+ id: "notif_1",
582
+ organizationId: "org_1",
583
+ });
584
+ });
585
+ });
586
+
587
+ describe("when organization is not found", () => {
588
+ it("returns null", async () => {
589
+ const { service, organizationService } = createService();
590
+ (organizationService.findWithAdmins as ReturnType<typeof vi.fn>).mockResolvedValue(null);
591
+
592
+ const result = await service.checkAndSendWarning({
593
+ organizationId: "org_missing",
594
+ currentMonthMessagesCount: 9500,
595
+ maxMonthlyUsageLimit: 10000,
596
+ });
597
+
598
+ expect(result).toBeNull();
599
+ });
600
+ });
601
+
602
+ describe("when organization has no admin members", () => {
603
+ it("returns null", async () => {
604
+ const { service, organizationService } = createService();
605
+ (organizationService.findWithAdmins as ReturnType<typeof vi.fn>).mockResolvedValue({
606
+ ...ORG_WITH_ADMIN,
607
+ members: [],
608
+ });
609
+
610
+ const result = await service.checkAndSendWarning({
611
+ organizationId: "org_1",
612
+ currentMonthMessagesCount: 9500,
613
+ maxMonthlyUsageLimit: 10000,
614
+ });
615
+
616
+ expect(result).toBeNull();
617
+ });
618
+ });
619
+
620
+ describe("when notification was already sent for this threshold this month", () => {
621
+ it("returns null without sending duplicate", async () => {
622
+ const { service, organizationService, notificationRepository, notificationService } = createService();
623
+ (organizationService.findWithAdmins as ReturnType<typeof vi.fn>).mockResolvedValue(ORG_WITH_ADMIN);
624
+ (notificationRepository.findRecentByOrganization as ReturnType<typeof vi.fn>).mockResolvedValue([
625
+ {
626
+ id: "existing_notif",
627
+ sentAt: new Date(),
628
+ metadata: {
629
+ type: "USAGE_LIMIT_WARNING",
630
+ threshold: 90,
631
+ },
632
+ },
633
+ ]);
634
+
635
+ const result = await service.checkAndSendWarning({
636
+ organizationId: "org_1",
637
+ currentMonthMessagesCount: 9200,
638
+ maxMonthlyUsageLimit: 10000,
639
+ });
640
+
641
+ expect(result).toBeNull();
642
+ expect(notificationService.sendUsageLimitEmail).not.toHaveBeenCalled();
643
+ });
644
+ });
645
+
646
+ describe("when all email sends fail", () => {
647
+ it("throws an error without creating a notification record", async () => {
648
+ const { service, organizationService, notificationRepository, usageService, notificationService } = createService();
649
+ (organizationService.findWithAdmins as ReturnType<typeof vi.fn>).mockResolvedValue(ORG_WITH_ADMIN);
650
+ (organizationService.findProjectsWithName as ReturnType<typeof vi.fn>).mockResolvedValue([]);
651
+ (usageService.getCountByProjects as ReturnType<typeof vi.fn>).mockResolvedValue([]);
652
+ (notificationService.sendUsageLimitEmail as ReturnType<typeof vi.fn>)
653
+ .mockRejectedValue(new Error("SMTP failure"));
654
+
655
+ await expect(
656
+ service.checkAndSendWarning({
657
+ organizationId: "org_1",
658
+ currentMonthMessagesCount: 9500,
659
+ maxMonthlyUsageLimit: 10000,
660
+ }),
661
+ ).rejects.toThrow("All 1 usage limit warning emails failed to send");
662
+
663
+ expect(notificationRepository.create).not.toHaveBeenCalled();
664
+ });
665
+ });
666
+
667
+ describe("when maxMonthlyUsageLimit is 0", () => {
668
+ it("returns null (no threshold crossed)", async () => {
669
+ const { service } = createService();
670
+
671
+ const result = await service.checkAndSendWarning({
672
+ organizationId: "org_1",
673
+ currentMonthMessagesCount: 100,
674
+ maxMonthlyUsageLimit: 0,
675
+ });
676
+
677
+ expect(result).toBeNull();
678
+ });
679
+ });
680
+
681
+ describe("when admins have no email addresses", () => {
682
+ it("returns null without sending emails", async () => {
683
+ const { service, organizationService, notificationService } = createService();
684
+ (organizationService.findWithAdmins as ReturnType<typeof vi.fn>).mockResolvedValue({
685
+ ...ORG_WITH_ADMIN,
686
+ members: [
687
+ {
688
+ role: "ADMIN",
689
+ user: { id: "user_no_email", name: "No Email Admin", email: null },
690
+ },
691
+ ],
692
+ });
693
+ (organizationService.findProjectsWithName as ReturnType<typeof vi.fn>).mockResolvedValue([]);
694
+
695
+ const result = await service.checkAndSendWarning({
696
+ organizationId: "org_1",
697
+ currentMonthMessagesCount: 9500,
698
+ maxMonthlyUsageLimit: 10000,
699
+ });
700
+
701
+ expect(result).toBeNull();
702
+ expect(notificationService.sendUsageLimitEmail).not.toHaveBeenCalled();
703
+ });
704
+ });
705
+ });
706
+ });