@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,68 @@
1
+ import { getApp } from "../../../../src/server/app-layer/app";
2
+ import { captureException } from "../../../../src/utils/posthogErrorCapture";
3
+ import type { CioPersonTraits } from "../types";
4
+
5
+ /**
6
+ * Valid integration method trait values sent to Customer.io.
7
+ *
8
+ * These are the canonical CIO trait values. The onboarding product-selection
9
+ * screen ("Pick your flavour") uses different UI keys; the mapping below
10
+ * translates from those UI keys to these trait values.
11
+ */
12
+ export type IntegrationMethodValue =
13
+ | "coding_agent"
14
+ | "platform"
15
+ | "mcp"
16
+ | "manual_sdk";
17
+
18
+ /**
19
+ * Maps the UI product selection key to the Customer.io integration_method trait value.
20
+ *
21
+ * The onboarding "Pick your flavour" screen asks HOW the user wants to
22
+ * integrate. We map the integration method UI key to the CIO trait:
23
+ *
24
+ * - "via-claude-code" -> "coding_agent"
25
+ * - "via-platform" -> "platform"
26
+ * - "via-claude-desktop" -> "mcp"
27
+ * - "manually" -> "manual_sdk"
28
+ */
29
+ export function mapProductSelectionToIntegrationMethod(
30
+ selection: string
31
+ ): IntegrationMethodValue {
32
+ const mapping: Record<string, IntegrationMethodValue> = {
33
+ "via-claude-code": "coding_agent",
34
+ "via-platform": "platform",
35
+ "via-claude-desktop": "mcp",
36
+ "manually": "manual_sdk",
37
+ };
38
+
39
+ if (!Object.hasOwn(mapping, selection)) {
40
+ throw new Error(`Unknown product selection: ${selection}`);
41
+ }
42
+ return mapping[selection]!;
43
+ }
44
+
45
+ /**
46
+ * Fires a separate identifyUser call to set the integration_method trait.
47
+ *
48
+ * Called from the "Pick your flavour" onboarding screen AFTER the initial
49
+ * signup identification (initializeOrganization fires before flavour selection).
50
+ * Fire-and-forget -- does not block navigation.
51
+ */
52
+ export function fireIntegrationMethodNurturing({
53
+ userId,
54
+ integrationMethod,
55
+ }: {
56
+ userId: string;
57
+ integrationMethod: IntegrationMethodValue;
58
+ }): void {
59
+ const nurturing = getApp().nurturing;
60
+ if (!nurturing) return;
61
+
62
+ void nurturing
63
+ .identifyUser({
64
+ userId,
65
+ traits: { integration_method: integrationMethod } as Partial<CioPersonTraits>,
66
+ })
67
+ .catch(captureException);
68
+ }
@@ -0,0 +1,138 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import {
3
+ fireIntegrationMethodNurturing,
4
+ mapProductSelectionToIntegrationMethod,
5
+ } from "./productInterest";
6
+
7
+ vi.mock("../../../../src/utils/logger/server", () => ({
8
+ createLogger: () => ({
9
+ info: vi.fn(),
10
+ warn: vi.fn(),
11
+ error: vi.fn(),
12
+ debug: vi.fn(),
13
+ }),
14
+ }));
15
+ vi.mock("../../../../src/utils/posthogErrorCapture", () => ({
16
+ captureException: vi.fn(),
17
+ }));
18
+
19
+ const mockNurturing = {
20
+ identifyUser: vi.fn().mockResolvedValue(undefined),
21
+ trackEvent: vi.fn().mockResolvedValue(undefined),
22
+ groupUser: vi.fn().mockResolvedValue(undefined),
23
+ batch: vi.fn().mockResolvedValue(undefined),
24
+ };
25
+
26
+ let currentNurturing: typeof mockNurturing | undefined = mockNurturing;
27
+
28
+ vi.mock("../../../../src/server/app-layer/app", () => ({
29
+ getApp: () => ({
30
+ get nurturing() {
31
+ return currentNurturing;
32
+ },
33
+ }),
34
+ }));
35
+
36
+ describe("mapProductSelectionToIntegrationMethod()", () => {
37
+ describe("when given a valid product selection", () => {
38
+ it("maps 'via-claude-code' to 'coding_agent'", () => {
39
+ expect(mapProductSelectionToIntegrationMethod("via-claude-code")).toBe("coding_agent");
40
+ });
41
+
42
+ it("maps 'via-platform' to 'platform'", () => {
43
+ expect(mapProductSelectionToIntegrationMethod("via-platform")).toBe("platform");
44
+ });
45
+
46
+ it("maps 'via-claude-desktop' to 'mcp'", () => {
47
+ expect(mapProductSelectionToIntegrationMethod("via-claude-desktop")).toBe("mcp");
48
+ });
49
+
50
+ it("maps 'manually' to 'manual_sdk'", () => {
51
+ expect(mapProductSelectionToIntegrationMethod("manually")).toBe("manual_sdk");
52
+ });
53
+ });
54
+
55
+ describe("when given an unknown selection", () => {
56
+ it("throws an error", () => {
57
+ expect(() => mapProductSelectionToIntegrationMethod("unknown")).toThrow(
58
+ "Unknown product selection: unknown"
59
+ );
60
+ });
61
+ });
62
+ });
63
+
64
+ describe("fireIntegrationMethodNurturing()", () => {
65
+ beforeEach(() => {
66
+ vi.clearAllMocks();
67
+ currentNurturing = mockNurturing;
68
+ });
69
+
70
+ describe("when the user selects an integration method", () => {
71
+ it("sends only integration_method trait via identifyUser", () => {
72
+ fireIntegrationMethodNurturing({
73
+ userId: "user-123",
74
+ integrationMethod: "coding_agent",
75
+ });
76
+
77
+ expect(mockNurturing.identifyUser).toHaveBeenCalledWith({
78
+ userId: "user-123",
79
+ traits: { integration_method: "coding_agent" },
80
+ });
81
+ });
82
+
83
+ it("does not re-send other signup traits", () => {
84
+ fireIntegrationMethodNurturing({
85
+ userId: "user-123",
86
+ integrationMethod: "platform",
87
+ });
88
+
89
+ const call = mockNurturing.identifyUser.mock.calls[0]![0];
90
+ expect(Object.keys(call.traits)).toEqual(["integration_method"]);
91
+ });
92
+
93
+ it("does not call trackEvent or groupUser", () => {
94
+ fireIntegrationMethodNurturing({
95
+ userId: "user-123",
96
+ integrationMethod: "mcp",
97
+ });
98
+
99
+ expect(mockNurturing.trackEvent).not.toHaveBeenCalled();
100
+ expect(mockNurturing.groupUser).not.toHaveBeenCalled();
101
+ });
102
+ });
103
+
104
+ describe("when Customer.io API is unavailable", () => {
105
+ it("does not throw (fire-and-forget)", async () => {
106
+ const { captureException } = await import(
107
+ "../../../../src/utils/posthogErrorCapture"
108
+ );
109
+ mockNurturing.identifyUser.mockRejectedValueOnce(
110
+ new Error("CIO unavailable")
111
+ );
112
+
113
+ expect(() =>
114
+ fireIntegrationMethodNurturing({
115
+ userId: "user-123",
116
+ integrationMethod: "coding_agent",
117
+ })
118
+ ).not.toThrow();
119
+
120
+ await vi.waitFor(() => {
121
+ expect(captureException).toHaveBeenCalled();
122
+ });
123
+ });
124
+ });
125
+
126
+ describe("when nurturing is undefined (no Customer.io key)", () => {
127
+ it("silently skips without calling any nurturing methods", () => {
128
+ currentNurturing = undefined;
129
+
130
+ fireIntegrationMethodNurturing({
131
+ userId: "user-123",
132
+ integrationMethod: "manual_sdk",
133
+ });
134
+
135
+ expect(mockNurturing.identifyUser).not.toHaveBeenCalled();
136
+ });
137
+ });
138
+ });
@@ -0,0 +1,288 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import { afterPromptCreated } from "./promptCreation";
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
+ const mockProjects = {
26
+ resolveOrgAdmin: vi.fn().mockResolvedValue({
27
+ userId: "admin-1",
28
+ organizationId: "org-1",
29
+ firstMessage: false,
30
+ }),
31
+ };
32
+
33
+ vi.mock("../../../../src/server/app-layer/app", () => ({
34
+ getApp: () => ({
35
+ get nurturing() {
36
+ return currentNurturing;
37
+ },
38
+ projects: mockProjects,
39
+ }),
40
+ }));
41
+
42
+ function createMockPrisma({
43
+ organizationId = "org-1",
44
+ promptCount = 1,
45
+ }: {
46
+ organizationId?: string;
47
+ promptCount?: number;
48
+ } = {}) {
49
+ return {
50
+ project: {
51
+ findUnique: vi.fn().mockResolvedValue({
52
+ team: { organizationId },
53
+ }),
54
+ },
55
+ llmPromptConfig: {
56
+ count: vi.fn().mockResolvedValue(promptCount),
57
+ },
58
+ } as any;
59
+ }
60
+
61
+ describe("afterPromptCreated()", () => {
62
+ beforeEach(() => {
63
+ vi.clearAllMocks();
64
+ currentNurturing = mockNurturing;
65
+ });
66
+
67
+ describe("given an organization with no prior prompts", () => {
68
+ describe("when a user creates their first prompt via tRPC (userId provided)", () => {
69
+ it("identifies user with has_prompts true and prompt_count 1", async () => {
70
+ const prisma = createMockPrisma({ promptCount: 1 });
71
+
72
+ afterPromptCreated({
73
+ prisma,
74
+ projectId: "proj-1",
75
+ userId: "user-1",
76
+ });
77
+
78
+ await vi.waitFor(() => {
79
+ expect(mockNurturing.identifyUser).toHaveBeenCalledWith({
80
+ userId: "user-1",
81
+ traits: { has_prompts: true, prompt_count: 1 },
82
+ });
83
+ });
84
+ });
85
+
86
+ it("tracks first_prompt_created event with project_id", async () => {
87
+ const prisma = createMockPrisma({ promptCount: 1 });
88
+
89
+ afterPromptCreated({
90
+ prisma,
91
+ projectId: "proj-1",
92
+ userId: "user-1",
93
+ });
94
+
95
+ await vi.waitFor(() => {
96
+ expect(mockNurturing.trackEvent).toHaveBeenCalledWith({
97
+ userId: "user-1",
98
+ event: "first_prompt_created",
99
+ properties: { project_id: "proj-1" },
100
+ });
101
+ });
102
+ });
103
+ });
104
+ });
105
+
106
+ describe("given an organization that already has prompts", () => {
107
+ describe("when a user creates another prompt", () => {
108
+ it("identifies user with updated org-wide prompt_count", async () => {
109
+ const prisma = createMockPrisma({ promptCount: 5 });
110
+
111
+ afterPromptCreated({
112
+ prisma,
113
+ projectId: "proj-1",
114
+ userId: "user-1",
115
+ });
116
+
117
+ await vi.waitFor(() => {
118
+ expect(mockNurturing.identifyUser).toHaveBeenCalledWith({
119
+ userId: "user-1",
120
+ traits: { has_prompts: true, prompt_count: 5 },
121
+ });
122
+ });
123
+ });
124
+
125
+ // Skipped: source only fires trackEvent when orgPromptCount === 1 (see firePromptCreatedNurturing).
126
+ // Test intent is for CIO-side deduplication (always fire, CIO deduplicates per person) — not yet implemented.
127
+ it.skip("sends first_prompt_created event (CIO Journey deduplicates per person)", async () => {
128
+ const prisma = createMockPrisma({ promptCount: 5 });
129
+
130
+ afterPromptCreated({
131
+ prisma,
132
+ projectId: "proj-1",
133
+ userId: "user-1",
134
+ });
135
+
136
+ await vi.waitFor(() => {
137
+ expect(mockNurturing.trackEvent).toHaveBeenCalledWith({
138
+ userId: "user-1",
139
+ event: "first_prompt_created",
140
+ properties: { project_id: "proj-1" },
141
+ });
142
+ });
143
+ });
144
+ });
145
+ });
146
+
147
+ describe("when created via REST API (no userId)", () => {
148
+ it("resolves userId via resolveOrgAdmin", async () => {
149
+ const prisma = createMockPrisma({ promptCount: 1 });
150
+ mockProjects.resolveOrgAdmin.mockResolvedValueOnce({
151
+ userId: "admin-1",
152
+ organizationId: "org-1",
153
+ firstMessage: false,
154
+ });
155
+
156
+ afterPromptCreated({
157
+ prisma,
158
+ projectId: "proj-1",
159
+ // no userId provided
160
+ });
161
+
162
+ await vi.waitFor(() => {
163
+ expect(mockProjects.resolveOrgAdmin).toHaveBeenCalledWith("proj-1");
164
+ });
165
+
166
+ await vi.waitFor(() => {
167
+ expect(mockNurturing.identifyUser).toHaveBeenCalledWith({
168
+ userId: "admin-1",
169
+ traits: { has_prompts: true, prompt_count: 1 },
170
+ });
171
+ });
172
+ });
173
+
174
+ it("uses organizationId from resolveOrgAdmin for counting", async () => {
175
+ const prisma = createMockPrisma({ promptCount: 3 });
176
+ mockProjects.resolveOrgAdmin.mockResolvedValueOnce({
177
+ userId: "admin-1",
178
+ organizationId: "org-resolved",
179
+ firstMessage: false,
180
+ });
181
+
182
+ afterPromptCreated({
183
+ prisma,
184
+ projectId: "proj-1",
185
+ });
186
+
187
+ await vi.waitFor(() => {
188
+ expect(prisma.llmPromptConfig.count).toHaveBeenCalledWith({
189
+ where: {
190
+ organizationId: "org-resolved",
191
+ deletedAt: null,
192
+ versions: { some: {} },
193
+ },
194
+ });
195
+ });
196
+ });
197
+ });
198
+
199
+ describe("when Customer.io API is unavailable", () => {
200
+ it("does not throw (fire-and-forget)", async () => {
201
+ const { captureException } = await import(
202
+ "../../../../src/utils/posthogErrorCapture"
203
+ );
204
+ const prisma = createMockPrisma({ promptCount: 1 });
205
+ mockNurturing.identifyUser.mockRejectedValueOnce(
206
+ new Error("CIO unavailable"),
207
+ );
208
+
209
+ expect(() =>
210
+ afterPromptCreated({
211
+ prisma,
212
+ projectId: "proj-1",
213
+ userId: "user-1",
214
+ }),
215
+ ).not.toThrow();
216
+
217
+ await vi.waitFor(() => {
218
+ expect(captureException).toHaveBeenCalled();
219
+ });
220
+ });
221
+ });
222
+
223
+ describe("when Prisma query fails", () => {
224
+ it("captures the error and does not throw", async () => {
225
+ const { captureException } = await import(
226
+ "../../../../src/utils/posthogErrorCapture"
227
+ );
228
+ const prisma = createMockPrisma();
229
+ prisma.project.findUnique.mockRejectedValueOnce(
230
+ new Error("DB unavailable"),
231
+ );
232
+
233
+ expect(() =>
234
+ afterPromptCreated({
235
+ prisma,
236
+ projectId: "proj-1",
237
+ userId: "user-1",
238
+ }),
239
+ ).not.toThrow();
240
+
241
+ await vi.waitFor(() => {
242
+ expect(captureException).toHaveBeenCalled();
243
+ });
244
+ });
245
+ });
246
+
247
+ describe("when no admin user can be resolved", () => {
248
+ it("skips nurturing calls without throwing", async () => {
249
+ const prisma = createMockPrisma();
250
+ mockProjects.resolveOrgAdmin.mockResolvedValueOnce({
251
+ userId: null,
252
+ organizationId: null,
253
+ firstMessage: false,
254
+ });
255
+
256
+ afterPromptCreated({
257
+ prisma,
258
+ projectId: "proj-1",
259
+ // no userId
260
+ });
261
+
262
+ // Give async code time to complete
263
+ await new Promise((r) => setTimeout(r, 50));
264
+
265
+ expect(mockNurturing.identifyUser).not.toHaveBeenCalled();
266
+ expect(mockNurturing.trackEvent).not.toHaveBeenCalled();
267
+ });
268
+ });
269
+
270
+ describe("when nurturing is undefined (no Customer.io key)", () => {
271
+ it("silently skips without calling any nurturing methods", async () => {
272
+ currentNurturing = undefined;
273
+ const prisma = createMockPrisma({ promptCount: 1 });
274
+
275
+ afterPromptCreated({
276
+ prisma,
277
+ projectId: "proj-1",
278
+ userId: "user-1",
279
+ });
280
+
281
+ // Give async code time to complete
282
+ await new Promise((r) => setTimeout(r, 50));
283
+
284
+ expect(mockNurturing.identifyUser).not.toHaveBeenCalled();
285
+ expect(mockNurturing.trackEvent).not.toHaveBeenCalled();
286
+ });
287
+ });
288
+ });
@@ -0,0 +1,131 @@
1
+ import type { PrismaClient } from "@prisma/client";
2
+ import { getApp } from "../../../../src/server/app-layer/app";
3
+ import { createLogger } from "../../../../src/utils/logger/server";
4
+ import { captureException } from "../../../../src/utils/posthogErrorCapture";
5
+
6
+ const logger = createLogger("ee:nurturing:prompt-creation");
7
+
8
+ /**
9
+ * Fires nurturing calls when a prompt is created.
10
+ *
11
+ * Always sends has_prompts: true + prompt_count on every call (idempotent).
12
+ * Only sends first_prompt_created event when orgPromptCount === 1.
13
+ *
14
+ * All calls are fire-and-forget.
15
+ *
16
+ * @param userId - The org admin user ID
17
+ * @param projectId - The project where the prompt was created
18
+ * @param orgPromptCount - The org-wide prompt count AFTER the prompt was created
19
+ */
20
+ export function firePromptCreatedNurturing({
21
+ userId,
22
+ projectId,
23
+ orgPromptCount,
24
+ }: {
25
+ userId: string;
26
+ projectId: string;
27
+ orgPromptCount: number;
28
+ }): void {
29
+ const nurturing = getApp().nurturing;
30
+ if (!nurturing) return;
31
+
32
+ void nurturing
33
+ .identifyUser({
34
+ userId,
35
+ traits: { has_prompts: true, prompt_count: orgPromptCount },
36
+ })
37
+ .catch(captureException);
38
+
39
+ if (orgPromptCount === 1) {
40
+ void nurturing
41
+ .trackEvent({
42
+ userId,
43
+ event: "first_prompt_created",
44
+ properties: { project_id: projectId },
45
+ })
46
+ .catch(captureException);
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Counts org-wide non-deleted prompts that have at least one version,
52
+ * resolves the org admin userId, and fires the prompt creation nurturing hook.
53
+ *
54
+ * Used at prompt creation call sites (tRPC and REST API) to avoid
55
+ * duplicating the counting and userId resolution logic.
56
+ *
57
+ * Entirely fire-and-forget: errors are captured but never thrown.
58
+ *
59
+ * @param prisma - PrismaClient for database queries
60
+ * @param projectId - The project where the prompt was created
61
+ * @param userId - The user who created the prompt (optional; resolved via resolveOrgAdmin if missing)
62
+ */
63
+ export function afterPromptCreated({
64
+ prisma,
65
+ projectId,
66
+ userId,
67
+ }: {
68
+ prisma: PrismaClient;
69
+ projectId: string;
70
+ userId?: string | null;
71
+ }): void {
72
+ void (async () => {
73
+ try {
74
+ // Resolve userId if not provided (REST API path)
75
+ let resolvedUserId = userId;
76
+ let organizationId: string | undefined;
77
+
78
+ if (!resolvedUserId) {
79
+ const resolution = await getApp().projects.resolveOrgAdmin(projectId);
80
+ resolvedUserId = resolution.userId;
81
+ organizationId = resolution.organizationId ?? undefined;
82
+ }
83
+
84
+ if (!resolvedUserId) {
85
+ logger.warn(
86
+ { projectId },
87
+ "No user ID available for prompt creation nurturing — skipping",
88
+ );
89
+ return;
90
+ }
91
+
92
+ // Get organizationId if we don't have it yet
93
+ if (!organizationId) {
94
+ const project = await prisma.project.findUnique({
95
+ where: { id: projectId },
96
+ select: { team: { select: { organizationId: true } } },
97
+ });
98
+ organizationId = project?.team?.organizationId ?? undefined;
99
+ }
100
+
101
+ if (!organizationId) {
102
+ logger.warn(
103
+ { projectId },
104
+ "Could not resolve organizationId for prompt count — skipping",
105
+ );
106
+ return;
107
+ }
108
+
109
+ // Count org-wide non-deleted prompts with at least one version
110
+ const orgPromptCount = await prisma.llmPromptConfig.count({
111
+ where: {
112
+ organizationId,
113
+ deletedAt: null,
114
+ versions: { some: {} },
115
+ },
116
+ });
117
+
118
+ firePromptCreatedNurturing({
119
+ userId: resolvedUserId,
120
+ projectId,
121
+ orgPromptCount,
122
+ });
123
+ } catch (error) {
124
+ logger.error(
125
+ { projectId, error },
126
+ "Failed to fire prompt creation nurturing — non-fatal",
127
+ );
128
+ captureException(error);
129
+ }
130
+ })();
131
+ }