@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,170 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import { fireSubscriptionSyncNurturing } from "./subscriptionSync";
3
+
4
+ vi.mock("../../../../src/utils/logger/server", () => ({
5
+ createLogger: () => ({
6
+ info: vi.fn(),
7
+ warn: vi.fn(),
8
+ error: vi.fn(),
9
+ debug: vi.fn(),
10
+ }),
11
+ }));
12
+ vi.mock("../../../../src/utils/posthogErrorCapture", () => ({
13
+ captureException: vi.fn(),
14
+ }));
15
+
16
+ const mockNurturing = {
17
+ identifyUser: vi.fn().mockResolvedValue(undefined),
18
+ trackEvent: vi.fn().mockResolvedValue(undefined),
19
+ groupUser: vi.fn().mockResolvedValue(undefined),
20
+ batch: vi.fn().mockResolvedValue(undefined),
21
+ };
22
+
23
+ let currentNurturing: typeof mockNurturing | undefined = mockNurturing;
24
+
25
+ vi.mock("../../../../src/server/app-layer/app", () => ({
26
+ getApp: () => ({
27
+ get nurturing() {
28
+ return currentNurturing;
29
+ },
30
+ }),
31
+ }));
32
+
33
+ const mockFindMany = vi.fn();
34
+
35
+ vi.mock("../../../../src/server/db", () => ({
36
+ prisma: {
37
+ organizationUser: {
38
+ findMany: (...args: unknown[]) => mockFindMany(...args),
39
+ },
40
+ },
41
+ }));
42
+
43
+ describe("Subscription sync hook", () => {
44
+ beforeEach(() => {
45
+ vi.clearAllMocks();
46
+ currentNurturing = mockNurturing;
47
+ });
48
+
49
+ describe("when a subscription is activated", () => {
50
+ it("identifies all org members with has_subscription true", async () => {
51
+ mockFindMany.mockResolvedValue([
52
+ { userId: "user-1" },
53
+ { userId: "user-2" },
54
+ ]);
55
+
56
+ fireSubscriptionSyncNurturing({
57
+ organizationId: "org-123",
58
+ hasSubscription: true,
59
+ });
60
+
61
+ await vi.waitFor(() => {
62
+ expect(mockNurturing.identifyUser).toHaveBeenCalledTimes(2);
63
+ });
64
+
65
+ expect(mockNurturing.identifyUser).toHaveBeenCalledWith({
66
+ userId: "user-1",
67
+ traits: { has_subscription: true },
68
+ });
69
+ expect(mockNurturing.identifyUser).toHaveBeenCalledWith({
70
+ userId: "user-2",
71
+ traits: { has_subscription: true },
72
+ });
73
+ });
74
+
75
+ it("queries org members by organizationId", async () => {
76
+ mockFindMany.mockResolvedValue([{ userId: "user-1" }]);
77
+
78
+ fireSubscriptionSyncNurturing({
79
+ organizationId: "org-456",
80
+ hasSubscription: true,
81
+ });
82
+
83
+ await vi.waitFor(() => {
84
+ expect(mockFindMany).toHaveBeenCalledWith({
85
+ where: { organizationId: "org-456" },
86
+ select: { userId: true },
87
+ });
88
+ });
89
+ });
90
+ });
91
+
92
+ describe("when a subscription is cancelled", () => {
93
+ it("identifies all org members with has_subscription false", async () => {
94
+ mockFindMany.mockResolvedValue([
95
+ { userId: "user-1" },
96
+ { userId: "user-2" },
97
+ { userId: "user-3" },
98
+ ]);
99
+
100
+ fireSubscriptionSyncNurturing({
101
+ organizationId: "org-123",
102
+ hasSubscription: false,
103
+ });
104
+
105
+ await vi.waitFor(() => {
106
+ expect(mockNurturing.identifyUser).toHaveBeenCalledTimes(3);
107
+ });
108
+
109
+ expect(mockNurturing.identifyUser).toHaveBeenCalledWith({
110
+ userId: "user-1",
111
+ traits: { has_subscription: false },
112
+ });
113
+ });
114
+ });
115
+
116
+ describe("when the org has no members", () => {
117
+ it("does not call identifyUser", async () => {
118
+ mockFindMany.mockResolvedValue([]);
119
+
120
+ fireSubscriptionSyncNurturing({
121
+ organizationId: "org-empty",
122
+ hasSubscription: true,
123
+ });
124
+
125
+ // Give the async work a chance to complete
126
+ await vi.waitFor(() => {
127
+ expect(mockFindMany).toHaveBeenCalled();
128
+ });
129
+
130
+ expect(mockNurturing.identifyUser).not.toHaveBeenCalled();
131
+ });
132
+ });
133
+
134
+ describe("when Customer.io API is unavailable", () => {
135
+ it("does not throw (fire-and-forget)", async () => {
136
+ const { captureException } = await import(
137
+ "../../../../src/utils/posthogErrorCapture"
138
+ );
139
+ mockFindMany.mockResolvedValue([{ userId: "user-1" }]);
140
+ mockNurturing.identifyUser.mockRejectedValueOnce(
141
+ new Error("Customer.io error"),
142
+ );
143
+
144
+ expect(() =>
145
+ fireSubscriptionSyncNurturing({
146
+ organizationId: "org-123",
147
+ hasSubscription: true,
148
+ }),
149
+ ).not.toThrow();
150
+
151
+ await vi.waitFor(() => {
152
+ expect(captureException).toHaveBeenCalled();
153
+ });
154
+ });
155
+ });
156
+
157
+ describe("when nurturing is undefined (no Customer.io key)", () => {
158
+ it("silently skips without querying org members", () => {
159
+ currentNurturing = undefined;
160
+
161
+ fireSubscriptionSyncNurturing({
162
+ organizationId: "org-123",
163
+ hasSubscription: true,
164
+ });
165
+
166
+ expect(mockFindMany).not.toHaveBeenCalled();
167
+ expect(mockNurturing.identifyUser).not.toHaveBeenCalled();
168
+ });
169
+ });
170
+ });
@@ -0,0 +1,143 @@
1
+ import { getApp } from "../../../../src/server/app-layer/app";
2
+ import { prisma } from "../../../../src/server/db";
3
+ import { captureException } from "../../../../src/utils/posthogErrorCapture";
4
+ import type { CioPersonTraits, CioOrgTraits } from "../types";
5
+
6
+ /**
7
+ * Tracks which users have had a full CIO profile sync this process lifetime.
8
+ *
9
+ * On first login after server restart, we send the complete profile so that
10
+ * existing users (who signed up before nurturing was deployed) get backfilled.
11
+ * Since CIO identify is idempotent, re-syncing after restart is harmless.
12
+ *
13
+ * NOTE: process-local. In multi-instance deployments each pod syncs
14
+ * independently on first login — acceptable because identify is idempotent.
15
+ */
16
+ const syncedUserIds = new Set<string>();
17
+
18
+ /**
19
+ * Ensures a user's full profile is synced to Customer.io at least once
20
+ * per process lifetime.
21
+ *
22
+ * On first login after server restart: queries Prisma for user + org + project
23
+ * data, then calls identifyUser with full traits and groupUser for org
24
+ * association. Subsequent logins skip entirely.
25
+ *
26
+ * Fire-and-forget: never throws, never blocks the session callback.
27
+ */
28
+ export function ensureUserSyncedToCio({
29
+ userId,
30
+ hasOrganization,
31
+ }: {
32
+ userId: string;
33
+ hasOrganization: boolean;
34
+ }): void {
35
+ const nurturing = getApp().nurturing;
36
+ if (!nurturing) return;
37
+ if (!hasOrganization) return;
38
+ if (syncedUserIds.has(userId)) return;
39
+
40
+ // Optimistic: mark as synced BEFORE async work to prevent concurrent
41
+ // logins from both triggering a full sync. Removed on failure so the
42
+ // next login can retry.
43
+ syncedUserIds.add(userId);
44
+
45
+ void performFullSync({ userId }).catch((error) => {
46
+ syncedUserIds.delete(userId);
47
+ captureException(error);
48
+ });
49
+ }
50
+
51
+ /**
52
+ * Queries the database for the user's full profile and sends it to Customer.io.
53
+ * Only called on first login per process lifetime.
54
+ */
55
+ async function performFullSync({ userId }: { userId: string }): Promise<void> {
56
+ const nurturing = getApp().nurturing;
57
+ if (!nurturing) return;
58
+
59
+ const [user, orgUser] = await Promise.all([
60
+ prisma.user.findUnique({
61
+ where: { id: userId },
62
+ select: { id: true, email: true, name: true, createdAt: true },
63
+ }),
64
+ prisma.organizationUser.findFirst({
65
+ where: { userId },
66
+ select: { organizationId: true, role: true },
67
+ }),
68
+ ]);
69
+
70
+ if (!user || !orgUser) return;
71
+
72
+ const [org, projects, activeSubscription] = await Promise.all([
73
+ prisma.organization.findUnique({
74
+ where: { id: orgUser.organizationId },
75
+ select: { id: true, name: true, signupData: true },
76
+ }),
77
+ prisma.project.findMany({
78
+ where: {
79
+ team: {
80
+ organization: { id: orgUser.organizationId },
81
+ },
82
+ },
83
+ select: { firstMessage: true, integrated: true },
84
+ }),
85
+ prisma.subscription.findFirst({
86
+ where: {
87
+ organizationId: orgUser.organizationId,
88
+ status: "ACTIVE",
89
+ },
90
+ select: { id: true },
91
+ }),
92
+ ]);
93
+
94
+ if (!org) return;
95
+
96
+ const signupData = (org.signupData ?? {}) as Record<string, unknown>;
97
+ const hasTraces = projects.some((p) => p.firstMessage);
98
+
99
+ const traits: Partial<CioPersonTraits> = {
100
+ ...(user.email ? { email: user.email } : {}),
101
+ ...(user.name ? { name: user.name } : {}),
102
+ ...(signupData.yourRole ? { role: signupData.yourRole as string } : {}),
103
+ ...(signupData.companySize
104
+ ? { company_size: signupData.companySize as string }
105
+ : {}),
106
+ has_traces: hasTraces,
107
+ has_subscription: !!activeSubscription,
108
+ createdAt: user.createdAt.toISOString(),
109
+ last_active_at: new Date().toISOString(),
110
+ };
111
+
112
+ const orgTraits: Partial<CioOrgTraits> = {
113
+ name: org.name,
114
+ ...(signupData.companySize
115
+ ? { company_size: signupData.companySize as string }
116
+ : {}),
117
+ };
118
+
119
+ await Promise.all([
120
+ nurturing.identifyUser({ userId, traits }),
121
+ nurturing.groupUser({
122
+ userId,
123
+ groupId: org.id,
124
+ traits: orgTraits,
125
+ }),
126
+ ]);
127
+ }
128
+
129
+ /**
130
+ * Resets the sync cache. Only exposed for testing.
131
+ * @internal
132
+ */
133
+ export function resetUserSyncCache(): void {
134
+ syncedUserIds.clear();
135
+ }
136
+
137
+ /**
138
+ * Returns the size of the sync cache for testing.
139
+ * @internal
140
+ */
141
+ export function getUserSyncCacheSize(): number {
142
+ return syncedUserIds.size;
143
+ }
@@ -0,0 +1,307 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import {
3
+ ensureUserSyncedToCio,
4
+ resetUserSyncCache,
5
+ getUserSyncCacheSize,
6
+ } from "./userSync";
7
+
8
+ // Suppress logger output
9
+ vi.mock("../../../../src/utils/logger/server", () => ({
10
+ createLogger: () => ({
11
+ info: vi.fn(),
12
+ warn: vi.fn(),
13
+ error: vi.fn(),
14
+ debug: vi.fn(),
15
+ }),
16
+ }));
17
+ vi.mock("../../../../src/utils/posthogErrorCapture", () => ({
18
+ captureException: vi.fn(),
19
+ }));
20
+
21
+ const { mockNurturing, mockPrisma } = vi.hoisted(() => {
22
+ const fn = vi.fn;
23
+ return {
24
+ mockNurturing: {
25
+ identifyUser: fn().mockResolvedValue(undefined),
26
+ trackEvent: fn().mockResolvedValue(undefined),
27
+ groupUser: fn().mockResolvedValue(undefined),
28
+ batch: fn().mockResolvedValue(undefined),
29
+ },
30
+ mockPrisma: {
31
+ user: { findUnique: fn() },
32
+ organizationUser: { findFirst: fn() },
33
+ organization: { findUnique: fn() },
34
+ project: { findMany: fn() },
35
+ subscription: { findFirst: fn() },
36
+ },
37
+ };
38
+ });
39
+
40
+ let currentNurturing: typeof mockNurturing | undefined = mockNurturing;
41
+
42
+ vi.mock("../../../../src/server/app-layer/app", () => ({
43
+ getApp: () => ({
44
+ get nurturing() {
45
+ return currentNurturing;
46
+ },
47
+ }),
48
+ }));
49
+
50
+ vi.mock("../../../../src/server/db", () => ({
51
+ prisma: mockPrisma,
52
+ }));
53
+
54
+ describe("ensureUserSyncedToCio()", () => {
55
+ beforeEach(() => {
56
+ vi.clearAllMocks();
57
+ currentNurturing = mockNurturing;
58
+ resetUserSyncCache();
59
+ });
60
+
61
+ const setupPrismaForFullSync = () => {
62
+ mockPrisma.user.findUnique.mockResolvedValue({
63
+ id: "user-1",
64
+ email: "jane@example.com",
65
+ name: "Jane Doe",
66
+ createdAt: new Date("2025-01-15T10:00:00.000Z"),
67
+ });
68
+ mockPrisma.organizationUser.findFirst.mockResolvedValue({
69
+ userId: "user-1",
70
+ organizationId: "org-1",
71
+ role: "ADMIN",
72
+ });
73
+ mockPrisma.organization.findUnique.mockResolvedValue({
74
+ id: "org-1",
75
+ name: "Acme Corp",
76
+ signupData: {
77
+ yourRole: "engineer",
78
+ companySize: "11-50",
79
+ },
80
+ });
81
+ mockPrisma.project.findMany.mockResolvedValue([
82
+ { id: "proj-1", firstMessage: true, integrated: true },
83
+ ]);
84
+ mockPrisma.subscription.findFirst.mockResolvedValue(null);
85
+ };
86
+
87
+ describe("given a user who has not been synced this process lifetime", () => {
88
+ describe("when the auth session callback fires", () => {
89
+ it("sends full identify call with email, name, and adoption traits", async () => {
90
+ setupPrismaForFullSync();
91
+
92
+ ensureUserSyncedToCio({ userId: "user-1", hasOrganization: true });
93
+
94
+ // Wait for the async fire-and-forget to complete
95
+ await vi.waitFor(() => {
96
+ expect(mockNurturing.identifyUser).toHaveBeenCalledWith({
97
+ userId: "user-1",
98
+ traits: expect.objectContaining({
99
+ email: "jane@example.com",
100
+ name: "Jane Doe",
101
+ role: "engineer",
102
+ company_size: "11-50",
103
+ has_traces: true,
104
+ createdAt: "2025-01-15T10:00:00.000Z",
105
+ }),
106
+ });
107
+ });
108
+ });
109
+
110
+ it("sends groupUser call to associate user with organization", async () => {
111
+ setupPrismaForFullSync();
112
+
113
+ ensureUserSyncedToCio({ userId: "user-1", hasOrganization: true });
114
+
115
+ await vi.waitFor(() => {
116
+ expect(mockNurturing.groupUser).toHaveBeenCalledWith({
117
+ userId: "user-1",
118
+ groupId: "org-1",
119
+ traits: expect.objectContaining({
120
+ name: "Acme Corp",
121
+ company_size: "11-50",
122
+ }),
123
+ });
124
+ });
125
+ });
126
+
127
+ it("adds userId to the sync cache", async () => {
128
+ setupPrismaForFullSync();
129
+
130
+ ensureUserSyncedToCio({ userId: "user-1", hasOrganization: true });
131
+
132
+ await vi.waitFor(() => {
133
+ expect(getUserSyncCacheSize()).toBe(1);
134
+ });
135
+ });
136
+ });
137
+ });
138
+
139
+ describe("given a user who has already been synced this process lifetime", () => {
140
+ describe("when the auth session callback fires again", () => {
141
+ it("skips the Prisma queries and CIO calls entirely", async () => {
142
+ setupPrismaForFullSync();
143
+
144
+ // First call: triggers full sync
145
+ ensureUserSyncedToCio({ userId: "user-1", hasOrganization: true });
146
+
147
+ await vi.waitFor(() => {
148
+ expect(mockNurturing.identifyUser).toHaveBeenCalledTimes(1);
149
+ });
150
+
151
+ vi.clearAllMocks();
152
+
153
+ // Second call: should skip
154
+ ensureUserSyncedToCio({ userId: "user-1", hasOrganization: true });
155
+
156
+ // Give a tick for any async work
157
+ await new Promise((resolve) => setTimeout(resolve, 10));
158
+
159
+ expect(mockPrisma.user.findUnique).not.toHaveBeenCalled();
160
+ expect(mockNurturing.identifyUser).not.toHaveBeenCalled();
161
+ expect(mockNurturing.groupUser).not.toHaveBeenCalled();
162
+ });
163
+ });
164
+ });
165
+
166
+ describe("given a user without an organization", () => {
167
+ describe("when the auth session callback fires", () => {
168
+ it("skips entirely to avoid creating ghost CIO profiles", () => {
169
+ ensureUserSyncedToCio({ userId: "user-1", hasOrganization: false });
170
+
171
+ expect(mockPrisma.user.findUnique).not.toHaveBeenCalled();
172
+ expect(mockNurturing.identifyUser).not.toHaveBeenCalled();
173
+ expect(mockNurturing.groupUser).not.toHaveBeenCalled();
174
+ });
175
+
176
+ it("does not add user to the sync cache", () => {
177
+ ensureUserSyncedToCio({ userId: "user-1", hasOrganization: false });
178
+
179
+ expect(getUserSyncCacheSize()).toBe(0);
180
+ });
181
+ });
182
+ });
183
+
184
+ describe("given nurturing is undefined", () => {
185
+ describe("when the auth session callback fires", () => {
186
+ it("silently skips without querying Prisma", () => {
187
+ currentNurturing = undefined;
188
+
189
+ ensureUserSyncedToCio({ userId: "user-1", hasOrganization: true });
190
+
191
+ expect(mockPrisma.user.findUnique).not.toHaveBeenCalled();
192
+ expect(mockNurturing.identifyUser).not.toHaveBeenCalled();
193
+ });
194
+ });
195
+ });
196
+
197
+ describe("given a Prisma query fails", () => {
198
+ describe("when the user lookup throws", () => {
199
+ it("does not throw (fire-and-forget)", async () => {
200
+ const { captureException } = await import(
201
+ "../../../../src/utils/posthogErrorCapture"
202
+ );
203
+ mockPrisma.user.findUnique.mockRejectedValueOnce(
204
+ new Error("DB connection lost"),
205
+ );
206
+
207
+ expect(() =>
208
+ ensureUserSyncedToCio({ userId: "user-1", hasOrganization: true }),
209
+ ).not.toThrow();
210
+
211
+ await vi.waitFor(() => {
212
+ expect(captureException).toHaveBeenCalled();
213
+ });
214
+ });
215
+
216
+ it("does not add user to the sync cache so next login can retry", async () => {
217
+ mockPrisma.user.findUnique.mockRejectedValueOnce(
218
+ new Error("DB connection lost"),
219
+ );
220
+
221
+ ensureUserSyncedToCio({ userId: "user-1", hasOrganization: true });
222
+
223
+ await vi.waitFor(() => {
224
+ expect(getUserSyncCacheSize()).toBe(0);
225
+ });
226
+ });
227
+ });
228
+ });
229
+
230
+ describe("given the user has no organization membership in DB", () => {
231
+ describe("when orgUser lookup returns null", () => {
232
+ it("skips identify and group calls", async () => {
233
+ mockPrisma.user.findUnique.mockResolvedValue({
234
+ id: "user-1",
235
+ email: "jane@example.com",
236
+ name: "Jane Doe",
237
+ createdAt: new Date("2025-01-15T10:00:00.000Z"),
238
+ });
239
+ mockPrisma.organizationUser.findFirst.mockResolvedValue(null);
240
+
241
+ ensureUserSyncedToCio({ userId: "user-1", hasOrganization: true });
242
+
243
+ // Wait a tick for the async to resolve
244
+ await new Promise((resolve) => setTimeout(resolve, 10));
245
+
246
+ expect(mockNurturing.identifyUser).not.toHaveBeenCalled();
247
+ expect(mockNurturing.groupUser).not.toHaveBeenCalled();
248
+ });
249
+
250
+ it("keeps user in the sync cache (optimistic lock, cleared on restart)", async () => {
251
+ mockPrisma.user.findUnique.mockResolvedValue({
252
+ id: "user-1",
253
+ email: "jane@example.com",
254
+ name: "Jane Doe",
255
+ createdAt: new Date("2025-01-15T10:00:00.000Z"),
256
+ });
257
+ mockPrisma.organizationUser.findFirst.mockResolvedValue(null);
258
+
259
+ ensureUserSyncedToCio({ userId: "user-1", hasOrganization: true });
260
+
261
+ await new Promise((resolve) => setTimeout(resolve, 10));
262
+
263
+ // Optimistic add keeps user cached even on no-op early return.
264
+ // Cache is process-local, so next server restart re-syncs.
265
+ expect(getUserSyncCacheSize()).toBe(1);
266
+ });
267
+ });
268
+ });
269
+
270
+ describe("given a user with no traces (projects without firstMessage)", () => {
271
+ describe("when the auth session callback fires", () => {
272
+ it("sends has_traces as false", async () => {
273
+ mockPrisma.user.findUnique.mockResolvedValue({
274
+ id: "user-1",
275
+ email: "jane@example.com",
276
+ name: "Jane Doe",
277
+ createdAt: new Date("2025-01-15T10:00:00.000Z"),
278
+ });
279
+ mockPrisma.organizationUser.findFirst.mockResolvedValue({
280
+ userId: "user-1",
281
+ organizationId: "org-1",
282
+ role: "MEMBER",
283
+ });
284
+ mockPrisma.organization.findUnique.mockResolvedValue({
285
+ id: "org-1",
286
+ name: "Acme Corp",
287
+ signupData: null,
288
+ });
289
+ mockPrisma.project.findMany.mockResolvedValue([
290
+ { id: "proj-1", firstMessage: false, integrated: false },
291
+ ]);
292
+ mockPrisma.subscription.findFirst.mockResolvedValue(null);
293
+
294
+ ensureUserSyncedToCio({ userId: "user-1", hasOrganization: true });
295
+
296
+ await vi.waitFor(() => {
297
+ expect(mockNurturing.identifyUser).toHaveBeenCalledWith({
298
+ userId: "user-1",
299
+ traits: expect.objectContaining({
300
+ has_traces: false,
301
+ }),
302
+ });
303
+ });
304
+ });
305
+ });
306
+ });
307
+ });