@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.
- package/langwatch/ee/admin/ImpersonationBanner.tsx +61 -0
- package/langwatch/ee/admin/ImpersonationSwitchBackMenuItem.tsx +30 -0
- package/langwatch/ee/admin/__tests__/ImpersonationBanner.integration.test.tsx +82 -0
- package/langwatch/ee/admin/__tests__/impersonation.service.unit.test.ts +231 -0
- package/langwatch/ee/admin/backoffice/BackofficeTable.tsx +200 -0
- package/langwatch/ee/admin/backoffice/__tests__/adminClient.unit.test.ts +147 -0
- package/langwatch/ee/admin/backoffice/__tests__/dateInputToISO.unit.test.ts +42 -0
- package/langwatch/ee/admin/backoffice/__tests__/userVisibility.unit.test.ts +174 -0
- package/langwatch/ee/admin/backoffice/adminClient.ts +114 -0
- package/langwatch/ee/admin/backoffice/resources/OrganizationFeaturesView.tsx +373 -0
- package/langwatch/ee/admin/backoffice/resources/OrganizationsView.tsx +677 -0
- package/langwatch/ee/admin/backoffice/resources/ProjectsView.tsx +647 -0
- package/langwatch/ee/admin/backoffice/resources/SubscriptionsView.tsx +628 -0
- package/langwatch/ee/admin/backoffice/resources/UsersView.tsx +556 -0
- package/langwatch/ee/admin/backoffice/useAdminResource.ts +104 -0
- package/langwatch/ee/admin/backoffice/userVisibility.ts +105 -0
- package/langwatch/ee/admin/impersonation.service.ts +170 -0
- package/langwatch/ee/admin/isAdmin.ts +9 -0
- package/langwatch/ee/admin/routes/admin.ts +531 -0
- package/langwatch/ee/admin/safeSelects.ts +64 -0
- package/langwatch/ee/billing/__tests__/customerService.unit.test.ts +183 -0
- package/langwatch/ee/billing/__tests__/growthSeatEvent.unit.test.ts +213 -0
- package/langwatch/ee/billing/__tests__/licensePurchaseHandler.unit.test.ts +250 -0
- package/langwatch/ee/billing/__tests__/notification.service.unit.test.ts +768 -0
- package/langwatch/ee/billing/__tests__/planLimits.unit.test.ts +19 -0
- package/langwatch/ee/billing/__tests__/planProvider.unit.test.ts +440 -0
- package/langwatch/ee/billing/__tests__/planTypes.unit.test.ts +32 -0
- package/langwatch/ee/billing/__tests__/pricing.unit.test.ts +54 -0
- package/langwatch/ee/billing/__tests__/seatEventSubscription.unit.test.ts +717 -0
- package/langwatch/ee/billing/__tests__/stripe.integration.test.ts +344 -0
- package/langwatch/ee/billing/__tests__/stripePrices.types.unit.test.ts +27 -0
- package/langwatch/ee/billing/__tests__/stripePricesLoader.unit.test.ts +72 -0
- package/langwatch/ee/billing/__tests__/subscription.service.unit.test.ts +730 -0
- package/langwatch/ee/billing/__tests__/subscriptionItemCalculator.unit.test.ts +176 -0
- package/langwatch/ee/billing/__tests__/usage-limit.service.unit.test.ts +706 -0
- package/langwatch/ee/billing/__tests__/usageReportingService.integration.test.ts +421 -0
- package/langwatch/ee/billing/__tests__/usageReportingService.unit.test.ts +515 -0
- package/langwatch/ee/billing/__tests__/webhookService.unit.test.ts +958 -0
- package/langwatch/ee/billing/currencyRouter.ts +18 -0
- package/langwatch/ee/billing/errors.ts +129 -0
- package/langwatch/ee/billing/index.ts +67 -0
- package/langwatch/ee/billing/middleware.ts +17 -0
- package/langwatch/ee/billing/notifications/notification.service.ts +651 -0
- package/langwatch/ee/billing/notifications/repositories/notification.repository.ts +51 -0
- package/langwatch/ee/billing/notifications/types.ts +9 -0
- package/langwatch/ee/billing/notifications/usage-limit.service.ts +622 -0
- package/langwatch/ee/billing/nurturing/hooks/activityTracking.ts +90 -0
- package/langwatch/ee/billing/nurturing/hooks/activityTracking.unit.test.ts +237 -0
- package/langwatch/ee/billing/nurturing/hooks/featureAdoption.ts +120 -0
- package/langwatch/ee/billing/nurturing/hooks/featureAdoption.unit.test.ts +324 -0
- package/langwatch/ee/billing/nurturing/hooks/index.ts +17 -0
- package/langwatch/ee/billing/nurturing/hooks/productInterest.ts +68 -0
- package/langwatch/ee/billing/nurturing/hooks/productInterest.unit.test.ts +138 -0
- package/langwatch/ee/billing/nurturing/hooks/promptCreation.integration.test.ts +288 -0
- package/langwatch/ee/billing/nurturing/hooks/promptCreation.ts +131 -0
- package/langwatch/ee/billing/nurturing/hooks/promptCreation.unit.test.ts +134 -0
- package/langwatch/ee/billing/nurturing/hooks/signupIdentification.ts +101 -0
- package/langwatch/ee/billing/nurturing/hooks/signupIdentification.unit.test.ts +317 -0
- package/langwatch/ee/billing/nurturing/hooks/subscriptionSync.ts +49 -0
- package/langwatch/ee/billing/nurturing/hooks/subscriptionSync.unit.test.ts +170 -0
- package/langwatch/ee/billing/nurturing/hooks/userSync.ts +143 -0
- package/langwatch/ee/billing/nurturing/hooks/userSync.unit.test.ts +307 -0
- package/langwatch/ee/billing/nurturing/nurturing.service.ts +179 -0
- package/langwatch/ee/billing/nurturing/nurturing.service.unit.test.ts +266 -0
- package/langwatch/ee/billing/nurturing/nurturing.service.wiring.unit.test.ts +109 -0
- package/langwatch/ee/billing/nurturing/types.ts +125 -0
- package/langwatch/ee/billing/planLimits.ts +190 -0
- package/langwatch/ee/billing/planProvider.ts +119 -0
- package/langwatch/ee/billing/planTypes.ts +53 -0
- package/langwatch/ee/billing/pricing.ts +57 -0
- package/langwatch/ee/billing/services/billableEventsQuery.ts +248 -0
- package/langwatch/ee/billing/services/customerService.ts +90 -0
- package/langwatch/ee/billing/services/licensePurchaseHandler.ts +73 -0
- package/langwatch/ee/billing/services/seatEventSubscription.ts +351 -0
- package/langwatch/ee/billing/services/seatSyncService.ts +34 -0
- package/langwatch/ee/billing/services/subscription.repository.ts +203 -0
- package/langwatch/ee/billing/services/subscription.service.ts +549 -0
- package/langwatch/ee/billing/services/subscriptionItemCalculator.ts +249 -0
- package/langwatch/ee/billing/services/usageReportingService.ts +301 -0
- package/langwatch/ee/billing/services/webhookService.ts +858 -0
- package/langwatch/ee/billing/stripe/stripeCatalog.json +1781 -0
- package/langwatch/ee/billing/stripe/stripeClient.ts +13 -0
- package/langwatch/ee/billing/stripe/stripePriceCatalog.ts +70 -0
- package/langwatch/ee/billing/stripe/stripePrices.types.ts +118 -0
- package/langwatch/ee/billing/subscriptionRouter.ts +202 -0
- package/langwatch/ee/billing/types.ts +102 -0
- package/langwatch/ee/billing/utils/currency.ts +99 -0
- package/langwatch/ee/billing/utils/growthSeatEvent.ts +137 -0
- package/langwatch/ee/licensing/__tests__/constants.unit.test.ts +56 -0
- package/langwatch/ee/licensing/__tests__/defaults.unit.test.ts +192 -0
- package/langwatch/ee/licensing/__tests__/fixtures/testKeys.ts +86 -0
- package/langwatch/ee/licensing/__tests__/fixtures/testLicenses.ts +92 -0
- package/langwatch/ee/licensing/__tests__/licenseGenerationService.unit.test.ts +232 -0
- package/langwatch/ee/licensing/__tests__/licenseHandler.integration.test.ts +419 -0
- package/langwatch/ee/licensing/__tests__/planMapping.unit.test.ts +195 -0
- package/langwatch/ee/licensing/__tests__/planTemplates.unit.test.ts +193 -0
- package/langwatch/ee/licensing/__tests__/signing.unit.test.ts +164 -0
- package/langwatch/ee/licensing/__tests__/validation.unit.test.ts +281 -0
- package/langwatch/ee/licensing/client.ts +29 -0
- package/langwatch/ee/licensing/constants.ts +195 -0
- package/langwatch/ee/licensing/defaults.ts +55 -0
- package/langwatch/ee/licensing/errors.ts +11 -0
- package/langwatch/ee/licensing/index.ts +52 -0
- package/langwatch/ee/licensing/licenseGenerationService.ts +87 -0
- package/langwatch/ee/licensing/licenseHandler.ts +308 -0
- package/langwatch/ee/licensing/planInfo.ts +46 -0
- package/langwatch/ee/licensing/planMapping.ts +37 -0
- package/langwatch/ee/licensing/planTemplates.ts +109 -0
- package/langwatch/ee/licensing/server.ts +43 -0
- package/langwatch/ee/licensing/signing.ts +43 -0
- package/langwatch/ee/licensing/types.ts +156 -0
- package/langwatch/ee/licensing/validation.ts +107 -0
- package/langwatch/ee/managed-providers/ManagedModelProviderAlert.tsx +29 -0
- package/langwatch/ee/managed-providers/managedBedrockConfig.ts +226 -0
- package/langwatch/ee/saas/ExtraFooterComponents.tsx +169 -0
- package/langwatch/package.json +1 -1
- package/package.json +1 -1
- package/packages/server/dist/cli.cjs +1 -1
|
@@ -0,0 +1,651 @@
|
|
|
1
|
+
import {
|
|
2
|
+
IncomingWebhook,
|
|
3
|
+
type IncomingWebhookSendArguments,
|
|
4
|
+
} from "@slack/webhook";
|
|
5
|
+
import { sendUsageLimitEmail } from "../../../src/server/mailer/usageLimitEmail";
|
|
6
|
+
import { createLogger } from "../../../src/utils/logger/server";
|
|
7
|
+
import { captureException } from "../../../src/utils/posthogErrorCapture";
|
|
8
|
+
import type { AppConfig } from "../../../src/server/app-layer/config";
|
|
9
|
+
import type {
|
|
10
|
+
LicensePurchaseNotificationPayload,
|
|
11
|
+
PlanLimitNotificationContext,
|
|
12
|
+
ResourceLimitNotificationContext,
|
|
13
|
+
SignupNotificationPayload,
|
|
14
|
+
SubscriptionNotificationPayload,
|
|
15
|
+
} from "../types";
|
|
16
|
+
|
|
17
|
+
const logger = createLogger("ee:notification-service");
|
|
18
|
+
|
|
19
|
+
const DEFAULT_APP_URL = "https://app.langwatch.ai";
|
|
20
|
+
const EXTERNAL_SERVICE_TIMEOUT_MS = 10_000;
|
|
21
|
+
|
|
22
|
+
// ---------------------------------------------------------------------------
|
|
23
|
+
// Exported types
|
|
24
|
+
// ---------------------------------------------------------------------------
|
|
25
|
+
|
|
26
|
+
export interface UsageLimitEmailData {
|
|
27
|
+
organizationName: string;
|
|
28
|
+
usagePercentage: number;
|
|
29
|
+
usagePercentageFormatted: string;
|
|
30
|
+
currentMonthMessagesCount: number;
|
|
31
|
+
maxMonthlyUsageLimit: number;
|
|
32
|
+
crossedThreshold: number;
|
|
33
|
+
projectUsageData: Array<{ id: string; name: string; messageCount: number }>;
|
|
34
|
+
actionUrl: string;
|
|
35
|
+
logoUrl: string;
|
|
36
|
+
severity: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// ---------------------------------------------------------------------------
|
|
40
|
+
// Helpers (absorbed from billingNotificationRegistration.ts)
|
|
41
|
+
// ---------------------------------------------------------------------------
|
|
42
|
+
|
|
43
|
+
type ProspectiveNotification = Extract<
|
|
44
|
+
SubscriptionNotificationPayload,
|
|
45
|
+
{ type: "prospective" }
|
|
46
|
+
>;
|
|
47
|
+
|
|
48
|
+
type ConfirmedNotification = Extract<
|
|
49
|
+
SubscriptionNotificationPayload,
|
|
50
|
+
{ type: "confirmed" }
|
|
51
|
+
>;
|
|
52
|
+
|
|
53
|
+
type CancelledNotification = Extract<
|
|
54
|
+
SubscriptionNotificationPayload,
|
|
55
|
+
{ type: "cancelled" }
|
|
56
|
+
>;
|
|
57
|
+
|
|
58
|
+
type NotificationServiceOptions = {
|
|
59
|
+
config: Pick<
|
|
60
|
+
AppConfig,
|
|
61
|
+
| "baseHost"
|
|
62
|
+
| "slackPlanLimitChannel"
|
|
63
|
+
| "slackSignupsChannel"
|
|
64
|
+
| "slackSubscriptionsChannel"
|
|
65
|
+
| "hubspotPortalId"
|
|
66
|
+
| "hubspotReachedLimitFormId"
|
|
67
|
+
| "hubspotFormId"
|
|
68
|
+
>;
|
|
69
|
+
createSlackWebhook?: (url: string) => Pick<IncomingWebhook, "send">;
|
|
70
|
+
fetchFn?: typeof fetch;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const formatNumber = (value?: number | null) =>
|
|
74
|
+
typeof value === "number" ? value.toLocaleString() : "-";
|
|
75
|
+
|
|
76
|
+
const formatDate = (value?: Date | null) =>
|
|
77
|
+
value
|
|
78
|
+
? new Intl.DateTimeFormat("en-US", {
|
|
79
|
+
dateStyle: "medium",
|
|
80
|
+
timeStyle: "short",
|
|
81
|
+
}).format(value)
|
|
82
|
+
: "Now";
|
|
83
|
+
|
|
84
|
+
const buildProspectiveBlocks = (
|
|
85
|
+
payload: ProspectiveNotification,
|
|
86
|
+
adminLink: string,
|
|
87
|
+
): IncomingWebhookSendArguments["blocks"] => {
|
|
88
|
+
const blocks: IncomingWebhookSendArguments["blocks"] = [
|
|
89
|
+
{
|
|
90
|
+
type: "header",
|
|
91
|
+
text: { type: "plain_text", text: "Prospective subscription interest" },
|
|
92
|
+
},
|
|
93
|
+
];
|
|
94
|
+
|
|
95
|
+
const dataBlock = {
|
|
96
|
+
type: "section",
|
|
97
|
+
fields: [
|
|
98
|
+
{ type: "mrkdwn", text: `*Organization:* ${payload.organizationName}` },
|
|
99
|
+
{ type: "mrkdwn", text: `*Plan:* ${payload.plan}` },
|
|
100
|
+
{
|
|
101
|
+
type: "mrkdwn",
|
|
102
|
+
text: `*Customer:* ${payload.customerName ?? "Unknown"}`,
|
|
103
|
+
},
|
|
104
|
+
],
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
if (payload.note) {
|
|
108
|
+
dataBlock.fields.push({
|
|
109
|
+
type: "mrkdwn",
|
|
110
|
+
text: `_${payload.note}_`,
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
blocks.push(dataBlock);
|
|
115
|
+
|
|
116
|
+
blocks.push({
|
|
117
|
+
type: "context",
|
|
118
|
+
elements: [
|
|
119
|
+
{
|
|
120
|
+
type: "mrkdwn",
|
|
121
|
+
text: `Triggered by ${payload.customerName ?? "a team member"}`,
|
|
122
|
+
},
|
|
123
|
+
],
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
blocks.push({
|
|
127
|
+
type: "actions",
|
|
128
|
+
elements: [
|
|
129
|
+
{
|
|
130
|
+
type: "button",
|
|
131
|
+
text: { type: "plain_text", text: "Open org in admin" },
|
|
132
|
+
url: adminLink,
|
|
133
|
+
action_id: "subscription_prospective_admin",
|
|
134
|
+
style: "primary",
|
|
135
|
+
},
|
|
136
|
+
],
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
return blocks;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const buildConfirmedBlocks = (
|
|
143
|
+
payload: ConfirmedNotification,
|
|
144
|
+
adminLink: string,
|
|
145
|
+
): IncomingWebhookSendArguments["blocks"] => {
|
|
146
|
+
const startText = payload.startDate
|
|
147
|
+
? `Activated on ${formatDate(payload.startDate)}`
|
|
148
|
+
: "Activated just now";
|
|
149
|
+
|
|
150
|
+
return [
|
|
151
|
+
{
|
|
152
|
+
type: "header",
|
|
153
|
+
text: { type: "plain_text", text: "Subscription activated" },
|
|
154
|
+
},
|
|
155
|
+
{
|
|
156
|
+
type: "section",
|
|
157
|
+
text: {
|
|
158
|
+
type: "mrkdwn",
|
|
159
|
+
text: `*${payload.organizationName}* is live on *${payload.plan}*.`,
|
|
160
|
+
},
|
|
161
|
+
},
|
|
162
|
+
{
|
|
163
|
+
type: "section",
|
|
164
|
+
fields: [
|
|
165
|
+
{
|
|
166
|
+
type: "mrkdwn",
|
|
167
|
+
text: `*Subscription ID:* ${payload.subscriptionId}`,
|
|
168
|
+
},
|
|
169
|
+
{
|
|
170
|
+
type: "mrkdwn",
|
|
171
|
+
text: `*Start Date:* ${formatDate(payload.startDate)}`,
|
|
172
|
+
},
|
|
173
|
+
{
|
|
174
|
+
type: "mrkdwn",
|
|
175
|
+
text: `*Seats:* ${formatNumber(payload.maxMembers)}`,
|
|
176
|
+
},
|
|
177
|
+
{
|
|
178
|
+
type: "mrkdwn",
|
|
179
|
+
text: `*Traces/month:* ${formatNumber(payload.maxMessagesPerMonth)}`,
|
|
180
|
+
},
|
|
181
|
+
],
|
|
182
|
+
},
|
|
183
|
+
{
|
|
184
|
+
type: "context",
|
|
185
|
+
elements: [
|
|
186
|
+
{
|
|
187
|
+
type: "mrkdwn",
|
|
188
|
+
text: startText,
|
|
189
|
+
},
|
|
190
|
+
],
|
|
191
|
+
},
|
|
192
|
+
{
|
|
193
|
+
type: "actions",
|
|
194
|
+
elements: [
|
|
195
|
+
{
|
|
196
|
+
type: "button",
|
|
197
|
+
text: { type: "plain_text", text: "Open org in admin" },
|
|
198
|
+
url: adminLink,
|
|
199
|
+
action_id: "subscription_confirmed_admin",
|
|
200
|
+
},
|
|
201
|
+
],
|
|
202
|
+
},
|
|
203
|
+
];
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
const buildCancelledBlocks = (
|
|
207
|
+
payload: CancelledNotification,
|
|
208
|
+
adminLink: string,
|
|
209
|
+
): IncomingWebhookSendArguments["blocks"] => {
|
|
210
|
+
const cancelText = payload.cancellationDate
|
|
211
|
+
? `Cancelled on ${formatDate(payload.cancellationDate)}`
|
|
212
|
+
: "Cancelled just now";
|
|
213
|
+
|
|
214
|
+
return [
|
|
215
|
+
{
|
|
216
|
+
type: "header",
|
|
217
|
+
text: { type: "plain_text", text: "Subscription cancelled" },
|
|
218
|
+
},
|
|
219
|
+
{
|
|
220
|
+
type: "section",
|
|
221
|
+
text: {
|
|
222
|
+
type: "mrkdwn",
|
|
223
|
+
text: `*${payload.organizationName}* has cancelled *${payload.plan}*.`,
|
|
224
|
+
},
|
|
225
|
+
},
|
|
226
|
+
{
|
|
227
|
+
type: "section",
|
|
228
|
+
fields: [
|
|
229
|
+
{
|
|
230
|
+
type: "mrkdwn",
|
|
231
|
+
text: `*Subscription ID:* ${payload.subscriptionId}`,
|
|
232
|
+
},
|
|
233
|
+
{
|
|
234
|
+
type: "mrkdwn",
|
|
235
|
+
text: `*Cancellation Date:* ${formatDate(payload.cancellationDate)}`,
|
|
236
|
+
},
|
|
237
|
+
],
|
|
238
|
+
},
|
|
239
|
+
{
|
|
240
|
+
type: "context",
|
|
241
|
+
elements: [
|
|
242
|
+
{
|
|
243
|
+
type: "mrkdwn",
|
|
244
|
+
text: cancelText,
|
|
245
|
+
},
|
|
246
|
+
],
|
|
247
|
+
},
|
|
248
|
+
{
|
|
249
|
+
type: "actions",
|
|
250
|
+
elements: [
|
|
251
|
+
{
|
|
252
|
+
type: "button",
|
|
253
|
+
text: { type: "plain_text", text: "Open org in admin" },
|
|
254
|
+
url: adminLink,
|
|
255
|
+
action_id: "subscription_cancelled_admin",
|
|
256
|
+
},
|
|
257
|
+
],
|
|
258
|
+
},
|
|
259
|
+
];
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
// ---------------------------------------------------------------------------
|
|
263
|
+
// NotificationService - Channel dispatch (HOW to send)
|
|
264
|
+
// ---------------------------------------------------------------------------
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Channel dispatch service: owns all delivery channels (email, Slack, Hubspot).
|
|
268
|
+
* Contains no business logic -- just "send X via channel Y."
|
|
269
|
+
*
|
|
270
|
+
* Absorbed from:
|
|
271
|
+
* - billingNotificationRegistration.ts (Slack/Hubspot implementations)
|
|
272
|
+
* - slackLicenseNotification.ts (Slack license purchase)
|
|
273
|
+
* - notificationHandlers.ts (error safety wrapper)
|
|
274
|
+
*/
|
|
275
|
+
export class NotificationService {
|
|
276
|
+
private readonly config: NotificationServiceOptions["config"];
|
|
277
|
+
private readonly createSlackWebhook: (
|
|
278
|
+
url: string,
|
|
279
|
+
) => Pick<IncomingWebhook, "send">;
|
|
280
|
+
private readonly fetchFn: typeof fetch;
|
|
281
|
+
|
|
282
|
+
private constructor(options: NotificationServiceOptions) {
|
|
283
|
+
this.config = options.config;
|
|
284
|
+
this.createSlackWebhook =
|
|
285
|
+
options?.createSlackWebhook ??
|
|
286
|
+
((url) =>
|
|
287
|
+
new IncomingWebhook(url, {
|
|
288
|
+
timeout: EXTERNAL_SERVICE_TIMEOUT_MS,
|
|
289
|
+
}));
|
|
290
|
+
this.fetchFn =
|
|
291
|
+
options?.fetchFn ??
|
|
292
|
+
((...args) => fetch(...args)) as typeof fetch;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Factory method for creating a NotificationService.
|
|
297
|
+
*/
|
|
298
|
+
static create(options: NotificationServiceOptions): NotificationService {
|
|
299
|
+
return new NotificationService(options);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Null-object factory: every method is a silent noop.
|
|
304
|
+
* Use in tests or non-SaaS deployments where no notifications are needed.
|
|
305
|
+
*/
|
|
306
|
+
static createNull(): NotificationService {
|
|
307
|
+
return NotificationService.create({
|
|
308
|
+
config: {} as NotificationServiceOptions["config"],
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
private getAdminLink(organizationId: string): string {
|
|
313
|
+
return `${this.config.baseHost ?? DEFAULT_APP_URL}/admin#/organizations/${organizationId}`;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
private async sendSlackMessage({
|
|
317
|
+
channelUrl,
|
|
318
|
+
body,
|
|
319
|
+
missingConfigLog,
|
|
320
|
+
errorLog,
|
|
321
|
+
}: {
|
|
322
|
+
channelUrl?: string;
|
|
323
|
+
body: IncomingWebhookSendArguments;
|
|
324
|
+
missingConfigLog?: string;
|
|
325
|
+
errorLog: string;
|
|
326
|
+
}): Promise<void> {
|
|
327
|
+
if (!channelUrl) {
|
|
328
|
+
if (missingConfigLog) {
|
|
329
|
+
logger.warn(missingConfigLog);
|
|
330
|
+
}
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
try {
|
|
335
|
+
const webhook = this.createSlackWebhook(channelUrl);
|
|
336
|
+
await webhook.send(body);
|
|
337
|
+
} catch (error) {
|
|
338
|
+
logger.error({ error }, errorLog);
|
|
339
|
+
captureException(error);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// -------------------------------------------------------------------------
|
|
344
|
+
// Email
|
|
345
|
+
// -------------------------------------------------------------------------
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Sends a usage-limit warning email to the specified recipient.
|
|
349
|
+
*/
|
|
350
|
+
async sendUsageLimitEmail({
|
|
351
|
+
to,
|
|
352
|
+
orgName,
|
|
353
|
+
usageData,
|
|
354
|
+
}: {
|
|
355
|
+
to: string;
|
|
356
|
+
orgName: string;
|
|
357
|
+
usageData: UsageLimitEmailData;
|
|
358
|
+
}): Promise<void> {
|
|
359
|
+
try {
|
|
360
|
+
await sendUsageLimitEmail({
|
|
361
|
+
to,
|
|
362
|
+
organizationName: orgName,
|
|
363
|
+
usagePercentage: usageData.usagePercentage,
|
|
364
|
+
usagePercentageFormatted: usageData.usagePercentageFormatted,
|
|
365
|
+
currentMonthMessagesCount: usageData.currentMonthMessagesCount,
|
|
366
|
+
maxMonthlyUsageLimit: usageData.maxMonthlyUsageLimit,
|
|
367
|
+
crossedThreshold: usageData.crossedThreshold,
|
|
368
|
+
projectUsageData: usageData.projectUsageData,
|
|
369
|
+
actionUrl: usageData.actionUrl,
|
|
370
|
+
logoUrl: usageData.logoUrl,
|
|
371
|
+
severity: usageData.severity,
|
|
372
|
+
});
|
|
373
|
+
} catch (error) {
|
|
374
|
+
logger.error({ error, to }, "Failed to send usage limit email");
|
|
375
|
+
throw error;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// -------------------------------------------------------------------------
|
|
380
|
+
// Slack
|
|
381
|
+
// -------------------------------------------------------------------------
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* Sends a Slack alert when a plan limit is reached.
|
|
385
|
+
*/
|
|
386
|
+
async sendSlackPlanLimitAlert(
|
|
387
|
+
context: PlanLimitNotificationContext,
|
|
388
|
+
): Promise<void> {
|
|
389
|
+
await this.sendSlackMessage({
|
|
390
|
+
channelUrl: this.config.slackPlanLimitChannel,
|
|
391
|
+
body: {
|
|
392
|
+
text: `Plan limit reached: ${context.organizationName}, ${context.adminEmail ?? "unknown"}, Plan: ${context.planName}`,
|
|
393
|
+
},
|
|
394
|
+
errorLog: "Failed to send Slack plan-limit notification",
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Sends a Slack alert when a resource limit is reached.
|
|
400
|
+
*/
|
|
401
|
+
async sendSlackResourceLimitAlert(
|
|
402
|
+
context: ResourceLimitNotificationContext,
|
|
403
|
+
): Promise<void> {
|
|
404
|
+
await this.sendSlackMessage({
|
|
405
|
+
channelUrl: this.config.slackPlanLimitChannel,
|
|
406
|
+
body: {
|
|
407
|
+
text: `Resource limit reached: ${context.organizationName}, ${context.adminEmail ?? "unknown"}, Plan: ${context.planName}, ${context.limitType}: ${context.current}/${context.max}`,
|
|
408
|
+
},
|
|
409
|
+
errorLog: "Failed to send Slack resource-limit notification",
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Sends a Slack notification for subscription events (prospective or confirmed).
|
|
415
|
+
*/
|
|
416
|
+
async sendSlackSubscriptionEvent(
|
|
417
|
+
payload: SubscriptionNotificationPayload,
|
|
418
|
+
): Promise<void> {
|
|
419
|
+
const adminLink = this.getAdminLink(payload.organizationId);
|
|
420
|
+
|
|
421
|
+
let blocks: IncomingWebhookSendArguments["blocks"];
|
|
422
|
+
switch (payload.type) {
|
|
423
|
+
case "prospective":
|
|
424
|
+
blocks = buildProspectiveBlocks(payload, adminLink);
|
|
425
|
+
break;
|
|
426
|
+
case "confirmed":
|
|
427
|
+
blocks = buildConfirmedBlocks(payload, adminLink);
|
|
428
|
+
break;
|
|
429
|
+
case "cancelled":
|
|
430
|
+
blocks = buildCancelledBlocks(payload, adminLink);
|
|
431
|
+
break;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
await this.sendSlackMessage({
|
|
435
|
+
channelUrl: this.config.slackSubscriptionsChannel,
|
|
436
|
+
body: { blocks },
|
|
437
|
+
missingConfigLog:
|
|
438
|
+
"SLACK_CHANNEL_SUBSCRIPTIONS is not configured; skipping subscription notification",
|
|
439
|
+
errorLog: "Failed to send Slack subscription notification",
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* Sends a Slack notification for a new signup.
|
|
445
|
+
*/
|
|
446
|
+
async sendSlackSignupEvent(payload: SignupNotificationPayload): Promise<void> {
|
|
447
|
+
const details = [
|
|
448
|
+
payload.phoneNumber,
|
|
449
|
+
payload.utmCampaign ? `Campaign: ${payload.utmCampaign}` : null,
|
|
450
|
+
].filter(Boolean);
|
|
451
|
+
|
|
452
|
+
const organizationDetails =
|
|
453
|
+
details.length > 0 ? `, ${details.join(", ")}` : "";
|
|
454
|
+
|
|
455
|
+
await this.sendSlackMessage({
|
|
456
|
+
channelUrl: this.config.slackSignupsChannel,
|
|
457
|
+
body: {
|
|
458
|
+
text: `🔔 New user registered: ${payload.userName ?? "Unknown"}, ${payload.userEmail ?? "unknown"}. Organization: ${payload.organizationName ?? "Unknown"}${organizationDetails}`,
|
|
459
|
+
},
|
|
460
|
+
missingConfigLog:
|
|
461
|
+
"SLACK_CHANNEL_SIGNUPS is not configured; skipping signup notification",
|
|
462
|
+
errorLog: "Failed to send Slack signup notification",
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* Sends a Slack notification for a license purchase.
|
|
468
|
+
*/
|
|
469
|
+
async sendSlackLicensePurchase(
|
|
470
|
+
payload: LicensePurchaseNotificationPayload,
|
|
471
|
+
): Promise<void> {
|
|
472
|
+
const amountFormatted = new Intl.NumberFormat("en-US", {
|
|
473
|
+
style: "currency",
|
|
474
|
+
currency: payload.currency,
|
|
475
|
+
}).format(payload.amountPaid / 100);
|
|
476
|
+
|
|
477
|
+
await this.sendSlackMessage({
|
|
478
|
+
channelUrl: this.config.slackSubscriptionsChannel,
|
|
479
|
+
body: {
|
|
480
|
+
text: "New License Purchase",
|
|
481
|
+
blocks: [
|
|
482
|
+
{
|
|
483
|
+
type: "header",
|
|
484
|
+
text: {
|
|
485
|
+
type: "plain_text",
|
|
486
|
+
text: "New License Purchase",
|
|
487
|
+
},
|
|
488
|
+
},
|
|
489
|
+
{
|
|
490
|
+
type: "section",
|
|
491
|
+
fields: [
|
|
492
|
+
{ type: "mrkdwn", text: `*Buyer:*\n${payload.buyerEmail}` },
|
|
493
|
+
{ type: "mrkdwn", text: `*Plan:*\n${payload.planType}` },
|
|
494
|
+
{ type: "mrkdwn", text: `*Seats:*\n${payload.seats}` },
|
|
495
|
+
{ type: "mrkdwn", text: `*Amount:*\n${amountFormatted}` },
|
|
496
|
+
],
|
|
497
|
+
},
|
|
498
|
+
],
|
|
499
|
+
},
|
|
500
|
+
errorLog: "Failed to send Slack license purchase notification",
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// -------------------------------------------------------------------------
|
|
505
|
+
// Hubspot
|
|
506
|
+
// -------------------------------------------------------------------------
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
* Submits a HubSpot signup lead form when a new user registers.
|
|
510
|
+
*/
|
|
511
|
+
async sendHubspotSignupForm(
|
|
512
|
+
payload: SignupNotificationPayload,
|
|
513
|
+
): Promise<void> {
|
|
514
|
+
const { hubspotPortalId, hubspotFormId } = this.config;
|
|
515
|
+
|
|
516
|
+
if (!hubspotPortalId || !hubspotFormId) {
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
const nameParts = (payload.userName ?? "").split(" ").filter(Boolean);
|
|
521
|
+
const firstName = nameParts[0] ?? "";
|
|
522
|
+
const lastName = nameParts.length > 1 ? nameParts[nameParts.length - 1]! : "";
|
|
523
|
+
|
|
524
|
+
const signUpData = payload.signUpData;
|
|
525
|
+
|
|
526
|
+
const formData = {
|
|
527
|
+
submittedAt: Date.now(),
|
|
528
|
+
fields: [
|
|
529
|
+
{ objectTypeId: "0-1", name: "company", value: payload.organizationName ?? "" },
|
|
530
|
+
{ objectTypeId: "0-1", name: "firstname", value: firstName },
|
|
531
|
+
{ objectTypeId: "0-1", name: "lastname", value: lastName },
|
|
532
|
+
{ objectTypeId: "0-1", name: "email", value: payload.userEmail ?? "" },
|
|
533
|
+
{ objectTypeId: "0-1", name: "mobilephone", value: payload.phoneNumber ?? "" },
|
|
534
|
+
{ objectTypeId: "0-1", name: "Features_usage_multiple", value: signUpData?.featureUsage ?? "Other" },
|
|
535
|
+
{ objectTypeId: "0-1", name: "user_role", value: signUpData?.yourRole ?? "Other" },
|
|
536
|
+
{ objectTypeId: "0-1", name: "product_usage", value: signUpData?.usage ?? "" },
|
|
537
|
+
{ objectTypeId: "0-1", name: "product_solution", value: signUpData?.solution ?? "" },
|
|
538
|
+
{ objectTypeId: "0-1", name: "organization_size", value: signUpData?.companySize ?? "1" },
|
|
539
|
+
{ objectTypeId: "0-1", name: "utm_campaign", value: signUpData?.utmCampaign ?? payload.utmCampaign ?? "" },
|
|
540
|
+
],
|
|
541
|
+
context: {
|
|
542
|
+
pageUri: "app.langwatch.ai",
|
|
543
|
+
pageName: "Sign Up",
|
|
544
|
+
},
|
|
545
|
+
};
|
|
546
|
+
|
|
547
|
+
const url = `https://api.hsforms.com/submissions/v3/integration/submit/${hubspotPortalId}/${hubspotFormId}`;
|
|
548
|
+
|
|
549
|
+
const controller = new AbortController();
|
|
550
|
+
const timeoutId = setTimeout(
|
|
551
|
+
() => controller.abort(),
|
|
552
|
+
EXTERNAL_SERVICE_TIMEOUT_MS,
|
|
553
|
+
);
|
|
554
|
+
|
|
555
|
+
try {
|
|
556
|
+
const response = await this.fetchFn(url, {
|
|
557
|
+
method: "POST",
|
|
558
|
+
headers: {
|
|
559
|
+
"Content-Type": "application/json",
|
|
560
|
+
},
|
|
561
|
+
body: JSON.stringify(formData),
|
|
562
|
+
signal: controller.signal,
|
|
563
|
+
});
|
|
564
|
+
|
|
565
|
+
if (!response.ok) {
|
|
566
|
+
captureException(
|
|
567
|
+
new Error(`HubSpot signup form request failed: ${response.status}`),
|
|
568
|
+
);
|
|
569
|
+
}
|
|
570
|
+
} catch (error) {
|
|
571
|
+
logger.error(
|
|
572
|
+
{ error },
|
|
573
|
+
"Failed to send HubSpot signup form notification",
|
|
574
|
+
);
|
|
575
|
+
captureException(error);
|
|
576
|
+
} finally {
|
|
577
|
+
clearTimeout(timeoutId);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* Submits a HubSpot form when a plan limit is reached.
|
|
583
|
+
*/
|
|
584
|
+
async sendHubspotPlanLimitForm(
|
|
585
|
+
context: PlanLimitNotificationContext,
|
|
586
|
+
): Promise<void> {
|
|
587
|
+
const { hubspotPortalId, hubspotReachedLimitFormId } = this.config;
|
|
588
|
+
|
|
589
|
+
if (!hubspotPortalId || !hubspotReachedLimitFormId) {
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
const formData = {
|
|
594
|
+
submittedAt: Date.now(),
|
|
595
|
+
fields: [
|
|
596
|
+
{
|
|
597
|
+
objectTypeId: "0-1",
|
|
598
|
+
name: "firstname",
|
|
599
|
+
value: context.adminName,
|
|
600
|
+
},
|
|
601
|
+
{
|
|
602
|
+
objectTypeId: "0-1",
|
|
603
|
+
name: "company",
|
|
604
|
+
value: context.organizationName,
|
|
605
|
+
},
|
|
606
|
+
{
|
|
607
|
+
objectTypeId: "0-1",
|
|
608
|
+
name: "email",
|
|
609
|
+
value: context.adminEmail,
|
|
610
|
+
},
|
|
611
|
+
],
|
|
612
|
+
context: {
|
|
613
|
+
pageUri: "app.langwatch.ai",
|
|
614
|
+
pageName: "Plan Limit Reached",
|
|
615
|
+
},
|
|
616
|
+
};
|
|
617
|
+
|
|
618
|
+
const url = `https://api.hsforms.com/submissions/v3/integration/submit/${hubspotPortalId}/${hubspotReachedLimitFormId}`;
|
|
619
|
+
|
|
620
|
+
const controller = new AbortController();
|
|
621
|
+
const timeoutId = setTimeout(
|
|
622
|
+
() => controller.abort(),
|
|
623
|
+
EXTERNAL_SERVICE_TIMEOUT_MS,
|
|
624
|
+
);
|
|
625
|
+
|
|
626
|
+
try {
|
|
627
|
+
const response = await this.fetchFn(url, {
|
|
628
|
+
method: "POST",
|
|
629
|
+
headers: {
|
|
630
|
+
"Content-Type": "application/json",
|
|
631
|
+
},
|
|
632
|
+
body: JSON.stringify(formData),
|
|
633
|
+
signal: controller.signal,
|
|
634
|
+
});
|
|
635
|
+
|
|
636
|
+
if (!response.ok) {
|
|
637
|
+
captureException(
|
|
638
|
+
new Error(`HubSpot request failed: ${response.status}`),
|
|
639
|
+
);
|
|
640
|
+
}
|
|
641
|
+
} catch (error) {
|
|
642
|
+
logger.error(
|
|
643
|
+
{ error },
|
|
644
|
+
"Failed to send HubSpot plan-limit notification",
|
|
645
|
+
);
|
|
646
|
+
captureException(error);
|
|
647
|
+
} finally {
|
|
648
|
+
clearTimeout(timeoutId);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { Notification, Prisma, PrismaClient } from "@prisma/client";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Derives create params from Prisma schema, omitting auto-generated fields
|
|
5
|
+
*/
|
|
6
|
+
export type CreateNotificationParams = Omit<
|
|
7
|
+
Prisma.NotificationUncheckedCreateInput,
|
|
8
|
+
"id" | "createdAt" | "updatedAt"
|
|
9
|
+
>;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Repository for notification data access
|
|
13
|
+
* Single Responsibility: Handle all database operations for Notification
|
|
14
|
+
*/
|
|
15
|
+
export class NotificationRepository {
|
|
16
|
+
constructor(private readonly prisma: PrismaClient) {}
|
|
17
|
+
|
|
18
|
+
async findRecentByOrganization(
|
|
19
|
+
organizationId: string,
|
|
20
|
+
since: Date,
|
|
21
|
+
): Promise<Notification[]> {
|
|
22
|
+
return this.prisma.notification.findMany({
|
|
23
|
+
where: {
|
|
24
|
+
organizationId,
|
|
25
|
+
sentAt: {
|
|
26
|
+
gte: since,
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
orderBy: {
|
|
30
|
+
sentAt: "desc",
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async create(params: CreateNotificationParams): Promise<Notification> {
|
|
36
|
+
return this.prisma.notification.create({
|
|
37
|
+
data: {
|
|
38
|
+
organizationId: params.organizationId,
|
|
39
|
+
projectId: params.projectId,
|
|
40
|
+
metadata: params.metadata,
|
|
41
|
+
sentAt: params.sentAt,
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async findById(id: string) {
|
|
47
|
+
return this.prisma.notification.findUnique({
|
|
48
|
+
where: { id },
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
}
|