Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(billing): add configurable spend alerts for paid cloud plans (#9551)

Michael Fröhlich8cb3d26e54a3
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index c764f9646c..64ebd5a798 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -332,6 +332,15 @@ export type BlobStorageIntegration = {
created_at: Generated<Timestamp>;
updated_at: Generated<Timestamp>;
};
+export type CloudSpendAlert = {
+ id: string;
+ org_id: string;
+ title: string;
+ threshold: string;
+ triggered_at: Timestamp | null;
+ created_at: Generated<Timestamp>;
+ updated_at: Generated<Timestamp>;
+};
export type Comment = {
id: string;
project_id: string;
@@ -851,6 +860,7 @@ export type DB = {
batch_exports: BatchExport;
billing_meter_backups: BillingMeterBackup;
blob_storage_integrations: BlobStorageIntegration;
+ cloud_spend_alerts: CloudSpendAlert;
comments: Comment;
cron_jobs: CronJobs;
dashboard_widgets: DashboardWidget;
diff --git a/packages/shared/prisma/migrations/20251006173445_add_cloud_spend_alerts/migration.sql b/packages/shared/prisma/migrations/20251006173445_add_cloud_spend_alerts/migration.sql
new file mode 100644
index 0000000000..d592188047
--- /dev/null
+++ b/packages/shared/prisma/migrations/20251006173445_add_cloud_spend_alerts/migration.sql
@@ -0,0 +1,15 @@
+-- CreateTable
+CREATE TABLE "cloud_spend_alerts" (
+ "id" TEXT NOT NULL,
+ "org_id" TEXT NOT NULL,
+ "title" TEXT NOT NULL,
+ "threshold" DECIMAL(65,30) NOT NULL,
+ "triggered_at" TIMESTAMP(3),
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "cloud_spend_alerts_pkey" PRIMARY KEY ("id")
+);
+
+-- AddForeignKey
+ALTER TABLE "cloud_spend_alerts" ADD CONSTRAINT "cloud_spend_alerts_org_id_fkey" FOREIGN KEY ("org_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
\ No newline at end of file
diff --git a/packages/shared/prisma/migrations/20251006173446_optimize_cloud_spend_alerts_add_index/migration.sql b/packages/shared/prisma/migrations/20251006173446_optimize_cloud_spend_alerts_add_index/migration.sql
new file mode 100644
index 0000000000..168068f16f
--- /dev/null
+++ b/packages/shared/prisma/migrations/20251006173446_optimize_cloud_spend_alerts_add_index/migration.sql
@@ -0,0 +1,3 @@
+-- CreateIndex
+CREATE INDEX CONCURRENTLY "cloud_spend_alerts_org_id_idx" ON "cloud_spend_alerts"("org_id");
+
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 9f9cfd6fcf..cb54f5459e 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -120,6 +120,7 @@ model Organization {
MembershipInvitation MembershipInvitation[]
ApiKey ApiKey[]
surveys Survey[]
+ cloudSpendAlerts CloudSpendAlert[]
@@map("organizations")
}
@@ -1433,3 +1434,20 @@ enum SurveyName {
@@map("SurveyName")
}
+
+model CloudSpendAlert {
+ id String @id @default(cuid())
+ orgId String @map("org_id")
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
+
+ title String // e.g., "Production Alert"
+ threshold Decimal @map("threshold") // USD amount
+
+ triggeredAt DateTime? @map("triggered_at") // Last trigger timestamp
+
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+
+ @@index([orgId])
+ @@map("cloud_spend_alerts")
+}
diff --git a/packages/shared/src/interfaces/cloudConfigSchema.ts b/packages/shared/src/interfaces/cloudConfigSchema.ts
index 49ab1a6c06..673845b093 100644
--- a/packages/shared/src/interfaces/cloudConfigSchema.ts
+++ b/packages/shared/src/interfaces/cloudConfigSchema.ts
@@ -25,21 +25,6 @@ export const CloudConfigSchema = z.object({
// custom rate limits for an organization
rateLimitOverrides: CloudConfigRateLimit.optional(),
-
- // billing alert configuration
- usageAlerts: z
- .object({
- enabled: z.boolean().default(true),
- type: z.enum(["STRIPE"]).default("STRIPE"),
- threshold: z.number().int().positive(),
- alertId: z.string(), // Alert ID for tracking
- meterId: z.string(), // Meter ID for usage tracking
- notifications: z.object({
- email: z.boolean().default(true),
- recipients: z.array(z.string().email()).default([]),
- }),
- })
- .optional(),
});
export type CloudConfigSchema = z.infer<typeof CloudConfigSchema>;
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 06039028e6..a096e088a7 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -2,7 +2,7 @@ export * from "./services/StorageService";
export * from "./services/email/organizationInvitation/sendMembershipInvitationEmail";
export * from "./services/email/batchExportSuccess/sendBatchExportSuccessEmail";
export * from "./services/email/passwordReset/sendResetPasswordVerificationRequest";
-export * from "./services/email/billingAlert/sendBillingAlertEmail";
+export * from "./services/email/cloudSpendAlert/sendCloudSpendAlertEmail";
export * from "./services/email/usageThresholdWarning/sendUsageThresholdWarningEmail";
export * from "./services/email/usageThresholdSuspension/sendUsageThresholdSuspensionEmail";
export * from "./services/PromptService";
@@ -34,6 +34,7 @@ export * from "./redis/redis";
export * from "./redis/traceUpsert";
export * from "./redis/createEvalQueue";
export * from "./redis/cloudUsageMeteringQueue";
+export * from "./redis/cloudSpendAlertQueue";
export * from "./redis/cloudFreeTierUsageThresholdQueue";
export * from "./redis/getQueue";
export * from "./redis/webhookQueue";
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index 5e6749727b..1e311160fe 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -42,6 +42,9 @@ export const BatchExportJobSchema = z.object({
projectId: z.string(),
batchExportId: z.string(),
});
+export const CloudSpendAlertJobSchema = z.object({
+ orgId: z.string(),
+});
export const TraceQueueEventSchema = z.object({
projectId: z.string(),
traceId: z.string(),
@@ -209,6 +212,7 @@ export type CreateEvalQueueEventType = z.infer<
typeof CreateEvalQueueEventSchema
>;
export type BatchExportJobType = z.infer<typeof BatchExportJobSchema>;
+export type CloudSpendAlertJobType = z.infer<typeof CloudSpendAlertJobSchema>;
export type TraceQueueEventType = z.infer<typeof TraceQueueEventSchema>;
export type TracesQueueEventType = z.infer<typeof TracesQueueEventSchema>;
export type ScoresQueueEventType = z.infer<typeof ScoresQueueEventSchema>;
@@ -259,6 +263,7 @@ export enum QueueName {
IngestionQueue = "ingestion-queue", // Process single events with S3-merge
IngestionSecondaryQueue = "secondary-ingestion-queue", // Separates high priority + high throughput projects from other projects.
CloudUsageMeteringQueue = "cloud-usage-metering-queue",
+ CloudSpendAlertQueue = "cloud-spend-alert-queue",
CloudFreeTierUsageThresholdQueue = "cloud-free-tier-usage-threshold-queue",
ExperimentCreate = "experiment-create-queue",
PostHogIntegrationQueue = "posthog-integration-queue",
@@ -286,6 +291,7 @@ export enum QueueJobs {
EvaluationExecution = "evaluation-execution-job",
BatchExportJob = "batch-export-job",
CloudUsageMeteringJob = "cloud-usage-metering-job",
+ CloudSpendAlertJob = "cloud-spend-alert-job",
CloudFreeTierUsageThresholdJob = "cloud-free-tier-usage-threshold-job",
OtelIngestionJob = "otel-ingestion-job",
IngestionJob = "ingestion-job",
@@ -431,6 +437,12 @@ export type TQueueJobTypes = {
payload: EntityChangeEventType;
name: QueueJobs.EntityChangeJob;
};
+ [QueueName.CloudSpendAlertQueue]: {
+ timestamp: Date;
+ id: string;
+ payload: CloudSpendAlertJobType;
+ name: QueueJobs.CloudSpendAlertJob;
+ };
[QueueName.CloudFreeTierUsageThresholdQueue]: {
timestamp: Date;
id: string;
diff --git a/packages/shared/src/server/redis/cloudSpendAlertQueue.ts b/packages/shared/src/server/redis/cloudSpendAlertQueue.ts
new file mode 100644
index 0000000000..64a9dcc46f
--- /dev/null
+++ b/packages/shared/src/server/redis/cloudSpendAlertQueue.ts
@@ -0,0 +1,53 @@
+import { Queue } from "bullmq";
+import { env } from "../../env";
+import { QueueName } from "../queues";
+import {
+ createNewRedisInstance,
+ redisQueueRetryOptions,
+ getQueuePrefix,
+} from "./redis";
+import { logger } from "../logger";
+
+export class CloudSpendAlertQueue {
+ private static instance: Queue | null = null;
+
+ public static getInstance(): Queue | null {
+ if (!env.STRIPE_SECRET_KEY) {
+ return null;
+ }
+
+ if (CloudSpendAlertQueue.instance) {
+ return CloudSpendAlertQueue.instance;
+ }
+
+ const newRedis = createNewRedisInstance({
+ enableOfflineQueue: false,
+ ...redisQueueRetryOptions,
+ });
+
+ CloudSpendAlertQueue.instance = newRedis
+ ? new Queue(QueueName.CloudSpendAlertQueue, {
+ connection: newRedis,
+ prefix: getQueuePrefix(QueueName.CloudSpendAlertQueue),
+ defaultJobOptions: {
+ removeOnComplete: true,
+ removeOnFail: 100,
+ attempts: 5,
+ backoff: {
+ type: "exponential",
+ delay: 5000,
+ },
+ },
+ })
+ : null;
+
+ CloudSpendAlertQueue.instance?.on("error", (err) => {
+ logger.error("CloudSpendAlertQueue error", err);
+ });
+
+ // Note: Jobs are triggered by the metering job with 5-minute delays
+ // No automatic scheduling needed
+
+ return CloudSpendAlertQueue.instance;
+ }
+}
diff --git a/packages/shared/src/server/redis/getQueue.ts b/packages/shared/src/server/redis/getQueue.ts
index b866793ee0..dd2a5a3c8e 100644
--- a/packages/shared/src/server/redis/getQueue.ts
+++ b/packages/shared/src/server/redis/getQueue.ts
@@ -2,6 +2,7 @@ import { Queue } from "bullmq";
import { QueueName } from "../queues";
import { BatchExportQueue } from "./batchExport";
import { CloudUsageMeteringQueue } from "./cloudUsageMeteringQueue";
+import { CloudSpendAlertQueue } from "./cloudSpendAlertQueue";
import { CloudFreeTierUsageThresholdQueue } from "./cloudFreeTierUsageThresholdQueue";
import { DatasetRunItemUpsertQueue } from "./datasetRunItemUpsert";
import { EvalExecutionQueue } from "./evalExecutionQueue";
@@ -40,6 +41,8 @@ export function getQueue(
return BatchExportQueue.getInstance();
case QueueName.CloudUsageMeteringQueue:
return CloudUsageMeteringQueue.getInstance();
+ case QueueName.CloudSpendAlertQueue:
+ return CloudSpendAlertQueue.getInstance();
case QueueName.CloudFreeTierUsageThresholdQueue:
return CloudFreeTierUsageThresholdQueue.getInstance();
case QueueName.DatasetRunItemUpsert:
diff --git a/packages/shared/src/server/services/email/billingAlert/sendBillingAlertEmail.ts b/packages/shared/src/server/services/email/billingAlert/sendBillingAlertEmail.ts
deleted file mode 100644
index 14cd9fbe93..0000000000
--- a/packages/shared/src/server/services/email/billingAlert/sendBillingAlertEmail.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { createTransport } from "nodemailer";
-import { parseConnectionUrl } from "nodemailer/lib/shared/index.js";
-import { render } from "@react-email/render";
-import { BillingAlertEmailTemplate } from "./BillingAlertEmailTemplate";
-import { logger } from "../../../logger";
-
-export interface BillingAlertEmailProps {
- env: Partial<
- Record<"EMAIL_FROM_ADDRESS" | "SMTP_CONNECTION_URL", string | undefined>
- >;
- organizationName: string;
- currentUsage: number;
- threshold: number;
- billingUrl: string;
- receiverEmail: string;
-}
-
-export const sendBillingAlertEmail = async ({
- env,
- organizationName,
- currentUsage,
- threshold,
- billingUrl,
- receiverEmail,
-}: BillingAlertEmailProps) => {
- if (!env.EMAIL_FROM_ADDRESS || !env.SMTP_CONNECTION_URL) {
- logger.error(
- "Missing environment variables for sending billing alert email.",
- );
- return;
- }
-
- try {
- const mailer = createTransport(parseConnectionUrl(env.SMTP_CONNECTION_URL));
-
- const emailSubject = `Langfuse Cloud Billing Alert: ${organizationName} usage exceeded ${threshold} events`;
- const emailHtml = await render(
- BillingAlertEmailTemplate({
- organizationName,
- currentUsage,
- threshold,
- billingUrl,
- receiverEmail,
- }),
- );
-
- await mailer.sendMail({
- to: receiverEmail,
- from: {
- address: env.EMAIL_FROM_ADDRESS,
- name: "Langfuse",
- },
- subject: emailSubject,
- html: emailHtml,
- });
- } catch (error) {
- logger.error(`Failed to send billing alert email`, error);
- }
-};
diff --git a/packages/shared/src/server/services/email/billingAlert/BillingAlertEmailTemplate.tsx b/packages/shared/src/server/services/email/cloudSpendAlert/CloudSpendAlertEmailTemplate.tsx
similarity index 62%
rename from packages/shared/src/server/services/email/billingAlert/BillingAlertEmailTemplate.tsx
rename to packages/shared/src/server/services/email/cloudSpendAlert/CloudSpendAlertEmailTemplate.tsx
index 237fa174c1..c8d073c0d3 100644
--- a/packages/shared/src/server/services/email/billingAlert/BillingAlertEmailTemplate.tsx
+++ b/packages/shared/src/server/services/email/cloudSpendAlert/CloudSpendAlertEmailTemplate.tsx
@@ -16,27 +16,30 @@ import {
Column,
} from "@react-email/components";
-interface BillingAlertEmailProps {
+interface CloudSpendAlertEmailProps {
organizationName: string;
- currentUsage: number;
+ alertTitle: string;
+ currentSpend: number;
threshold: number;
billingUrl: string;
+ detectedAtUtc?: string;
receiverEmail: string;
}
-export const BillingAlertEmailTemplate = ({
+export const CloudSpendAlertEmailTemplate = ({
organizationName,
- currentUsage,
+ alertTitle,
+ currentSpend,
threshold,
billingUrl,
+ detectedAtUtc,
receiverEmail,
-}: BillingAlertEmailProps) => {
+}: CloudSpendAlertEmailProps) => {
return (
<Html>
<Head />
<Preview>
- Your Langfuse Cloud usage is {`${currentUsage}`} events for the current
- billing period
+ {`Spend alert · ${organizationName} reached $${threshold.toFixed(2)}`}
</Preview>
<Tailwind>
<Body className="bg-background my-auto mx-auto font-sans">
@@ -53,11 +56,13 @@ export const BillingAlertEmailTemplate = ({
<Section>
<Heading className="mx-0 my-[30px] p-0 text-center text-2xl font-normal text-black">
- Usage Threshold Exceeded
+ Spend alert: {alertTitle}
</Heading>
<Text className="text-gray-700 text-sm leading-6">
- Your organization &quot;{organizationName}&quot; has exceeded
- the configured billing threshold
+ This is a notification you configured for &quot;
+ {organizationName}&quot;. It indicates your current billing
+ cycle spend has reached the limit you set. There are no service
+ interruptions or immediate billing actions.
</Text>
</Section>
@@ -66,21 +71,33 @@ export const BillingAlertEmailTemplate = ({
<Row>
<Column className="text-center">
<Text className="text-gray-600 text-sm font-medium m-0 mb-1">
- Current Usage (# Events)
+ Current Spend (USD)
</Text>
<Text className="text-2xl font-bold text-gray-900 m-0">
- {currentUsage}
+ {`$${currentSpend.toFixed(2)}`}
</Text>
</Column>
<Column className="text-center">
<Text className="text-gray-600 text-sm font-medium m-0 mb-1">
- Alert Threshold (# Events)
+ Alert Threshold (USD)
</Text>
<Text className="text-2xl font-bold text-gray-900 m-0">
- {threshold}
+ {`$${threshold.toFixed(2)}`}
</Text>
</Column>
</Row>
+ {detectedAtUtc ? (
+ <Row>
+ <Column className="text-center">
+ <Text className="text-gray-600 text-xs font-medium mt-3 mb-0">
+ Detected at (UTC)
+ </Text>
+ <Text className="text-sm text-gray-900 m-0">
+ {detectedAtUtc}
+ </Text>
+ </Column>
+ </Row>
+ ) : null}
</div>
</Section>
@@ -89,21 +106,23 @@ export const BillingAlertEmailTemplate = ({
className="rounded bg-black px-5 py-3 text-center text-xs font-semibold text-white no-underline"
href={billingUrl}
>
- View Billing Page and Manage Alerts
+ View Billing & Manage Spend Alerts
</Button>
</Section>
<Section className="mt-8">
<Heading className="text-black text-[18px] font-semibold">
- What happens next?
+ No immediate action required
</Heading>
<Text className="text-gray-700 text-sm leading-6">
- • Your current billing cycle continues normally
+ • Ingestions and billing continue as normal
<br />
- • Charges will appear on your next invoice
+ • This email is informational; it reflects a threshold you
+ configured
<br />
- • You can adjust usage or modify alert thresholds
- <br />• Contact support if you have questions about your bill
+ • Manage thresholds or review usage in your billing settings
+ <br />• This alert won’t trigger again until the next billing
+ cycle
</Text>
</Section>
@@ -111,18 +130,9 @@ export const BillingAlertEmailTemplate = ({
<Section>
<Text className="text-[#666666] text-[12px] leading-[24px]">
- This email was sent to {receiverEmail} regarding billing alerts
+ This email was sent to {receiverEmail} regarding spend alerts
for &quot;{organizationName}&quot;.
</Text>
- <Text className="text-[#666666] text-[12px] leading-[24px]">
- Questions? Contact us at{" "}
- <a
- href="mailto:[email protected]"
- className="text-blue-600 no-underline"
- >
- </a>
- </Text>
</Section>
</Container>
</Body>
@@ -131,4 +141,4 @@ export const BillingAlertEmailTemplate = ({
);
};
-export default BillingAlertEmailTemplate;
+export default CloudSpendAlertEmailTemplate;
diff --git a/packages/shared/src/server/services/email/cloudSpendAlert/sendCloudSpendAlertEmail.ts b/packages/shared/src/server/services/email/cloudSpendAlert/sendCloudSpendAlertEmail.ts
new file mode 100644
index 0000000000..b7d697f4f3
--- /dev/null
+++ b/packages/shared/src/server/services/email/cloudSpendAlert/sendCloudSpendAlertEmail.ts
@@ -0,0 +1,90 @@
+import { createTransport } from "nodemailer";
+import { parseConnectionUrl } from "nodemailer/lib/shared/index.js";
+import { render } from "@react-email/render";
+import { CloudSpendAlertEmailTemplate } from "./CloudSpendAlertEmailTemplate";
+import { logger } from "../../../logger";
+
+export interface CloudSpendAlertEmailProps {
+ env: Partial<
+ Record<
+ "EMAIL_FROM_ADDRESS" | "SMTP_CONNECTION_URL" | "NEXTAUTH_URL",
+ string | undefined
+ >
+ >;
+ orgId: string;
+ orgName: string;
+ alertTitle: string;
+ currentSpend: number;
+ threshold: number;
+ detectedAtUtc?: string;
+ recipients: string[];
+}
+
+export const sendCloudSpendAlertEmail = async ({
+ env,
+ orgId,
+ orgName,
+ alertTitle,
+ currentSpend,
+ threshold,
+ detectedAtUtc,
+ recipients,
+}: CloudSpendAlertEmailProps) => {
+ if (!env.EMAIL_FROM_ADDRESS || !env.SMTP_CONNECTION_URL) {
+ logger.error(
+ "Missing environment variables for sending cloud spend alert email.",
+ );
+ return;
+ }
+
+ if (recipients.length === 0) {
+ logger.warn(`No recipients found for cloud spend alert for org ${orgId}`);
+ return;
+ }
+
+ try {
+ const mailer = createTransport(parseConnectionUrl(env.SMTP_CONNECTION_URL));
+
+ const billingUrl = `${env.NEXTAUTH_URL}/organization/${orgId}/settings/billing`;
+ const emailSubject = `Langfuse Spend Alert · ${orgName} reached $${threshold.toFixed(2)}`;
+
+ // Send email to each recipient
+ for (const recipient of recipients) {
+ const emailHtml = await render(
+ CloudSpendAlertEmailTemplate({
+ organizationName: orgName,
+ alertTitle,
+ currentSpend,
+ threshold,
+ billingUrl,
+ detectedAtUtc,
+ receiverEmail: recipient,
+ }),
+ );
+
+ await mailer.sendMail({
+ to: recipient,
+ from: {
+ address: env.EMAIL_FROM_ADDRESS,
+ name: "Langfuse",
+ },
+ subject: emailSubject,
+ html: emailHtml,
+ });
+
+ logger.info(
+ `Sent cloud spend alert email to ${recipient} for org ${orgId}`,
+ );
+ }
+
+ logger.info(
+ `Successfully sent cloud spend alert emails to ${recipients.length} recipients for org ${orgId}`,
+ );
+ } catch (error) {
+ logger.error(
+ `Failed to send cloud spend alert email for org ${orgId}`,
+ error,
+ );
+ throw error;
+ }
+};
diff --git a/web/src/ee/features/billing/README.md b/web/src/ee/features/billing/README.md
index 406d750032..3c1bfeabe0 100644
--- a/web/src/ee/features/billing/README.md
+++ b/web/src/ee/features/billing/README.md
@@ -23,8 +23,6 @@ See `web/src/ee/features/billing/server/cloudBillingRouter.ts`.
- `clearPlanSwitchSchedule` — releases any active/not-started schedule.
- `getStripeCustomerPortalUrl` — portal for payment methods, tax IDs, invoices (not for plan switches).
- `getInvoices` — paginated invoice list with subscription/usage/tax breakdown and preview row.
-- `getUsage` — usage for current period from Stripe preview; falls back to ClickHouse aggregate.
-- `getUsageAlerts` / `upsertUsageAlerts` — toggle and configure Stripe usage alerts. (don't work correctly atm)
### Checkout and Subscription Management
diff --git a/web/src/ee/features/billing/components/BillingSettings.tsx b/web/src/ee/features/billing/components/BillingSettings.tsx
index 6eebca60c9..28ff023a2b 100644
--- a/web/src/ee/features/billing/components/BillingSettings.tsx
+++ b/web/src/ee/features/billing/components/BillingSettings.tsx
@@ -6,13 +6,13 @@ import { useRouter } from "next/router";
import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";
-import { UsageAlerts } from "./UsageAlerts";
import { BillingUsageChart } from "./BillingUsageChart";
import { BillingActionButtons } from "./BillingActionButtons";
import { BillingScheduleNotification } from "./BillingScheduleNotification";
import { BillingInvoiceTable } from "./BillingInvoiceTable";
import { BillingDiscountView } from "./BillingDiscountView";
import { BillingPlanPeriodView } from "@/src/ee/features/billing/components/BillingPlanPeriodView";
+import { SpendAlertsSection } from "./SpendAlerts/SpendAlertsSection";
export const BillingSettings = () => {
const router = useRouter();
@@ -23,7 +23,7 @@ export const BillingSettings = () => {
});
const entitled = useHasEntitlement("cloud-billing");
- const isUsageAlertEntitled = useHasEntitlement("cloud-usage-alerts");
+ const isSpendAlertEntitled = useHasEntitlement("cloud-spend-alerts");
// Handle conditional rendering without early returns
if (!entitled) {
@@ -52,8 +52,8 @@ export const BillingSettings = () => {
<BillingPlanPeriodView />
<BillingDiscountView />
<BillingActionButtons />
- {isUsageAlertEntitled && orgId && <UsageAlerts orgId={orgId} />}
<BillingInvoiceTable />
+ {isSpendAlertEntitled && orgId && <SpendAlertsSection orgId={orgId} />}
</div>
</div>
);
diff --git a/web/src/ee/features/billing/components/SpendAlerts/DeleteSpendAlertDialog.tsx b/web/src/ee/features/billing/components/SpendAlerts/DeleteSpendAlertDialog.tsx
new file mode 100644
index 0000000000..f51c68e0ea
--- /dev/null
+++ b/web/src/ee/features/billing/components/SpendAlerts/DeleteSpendAlertDialog.tsx
@@ -0,0 +1,86 @@
+import { useState } from "react";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/src/components/ui/dialog";
+import { Button } from "@/src/components/ui/button";
+import { api } from "@/src/utils/api";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { toast } from "sonner";
+
+interface DeleteSpendAlertDialogProps {
+ orgId: string;
+ alertId: string;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onSuccess: () => void;
+}
+
+export function DeleteSpendAlertDialog({
+ orgId,
+ alertId,
+ open,
+ onOpenChange,
+ onSuccess,
+}: DeleteSpendAlertDialogProps) {
+ const [isDeleting, setIsDeleting] = useState(false);
+ const capture = usePostHogClientCapture();
+
+ const deleteMutation = api.spendAlerts.deleteSpendAlert.useMutation();
+
+ const handleDelete = async () => {
+ setIsDeleting(true);
+ try {
+ await deleteMutation.mutateAsync({
+ orgId,
+ id: alertId,
+ });
+ capture("spend_alert:deleted", {
+ orgId,
+ alertId,
+ });
+ toast.success("Spend alert deleted successfully");
+ onSuccess();
+ } catch (error) {
+ console.error("Failed to delete spend alert:", error);
+ toast.error("Failed to delete spend alert. Please try again.");
+ } finally {
+ setIsDeleting(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Delete Spend Alert</DialogTitle>
+ <DialogDescription>
+ Are you sure you want to delete this spend alert? This action cannot
+ be undone and you will no longer receive notifications for this
+ threshold.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button
+ variant="outline"
+ disabled={isDeleting}
+ onClick={() => onOpenChange(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={handleDelete}
+ disabled={isDeleting}
+ >
+ {isDeleting ? "Deleting..." : "Delete Alert"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/web/src/ee/features/billing/components/SpendAlerts/SpendAlertDialog.tsx b/web/src/ee/features/billing/components/SpendAlerts/SpendAlertDialog.tsx
new file mode 100644
index 0000000000..3f1400002b
--- /dev/null
+++ b/web/src/ee/features/billing/components/SpendAlerts/SpendAlertDialog.tsx
@@ -0,0 +1,206 @@
+import { useState } from "react";
+import { useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import * as z from "zod/v4";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogTitle,
+} from "@/src/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/src/components/ui/form";
+import { Input } from "@/src/components/ui/input";
+import { Button } from "@/src/components/ui/button";
+import { api } from "@/src/utils/api";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { toast } from "sonner";
+import { Info } from "lucide-react";
+
+const spendAlertSchema = z.object({
+ title: z
+ .string()
+ .min(1, "Title is required")
+ .max(100, "Title must be less than 100 characters"),
+ limit: z.coerce
+ .number()
+ .positive("Limit must be positive")
+ .max(1000000, "Limit must be less than $1,000,000"),
+});
+
+type SpendAlertFormInput = z.input<typeof spendAlertSchema>;
+type SpendAlertFormOutput = z.output<typeof spendAlertSchema>;
+
+interface SpendAlertDialogProps {
+ orgId: string;
+ alert?: {
+ id: string;
+ title: string;
+ threshold: { toString(): string };
+ };
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onSuccess: () => void;
+}
+
+export function SpendAlertDialog({
+ orgId,
+ alert,
+ open,
+ onOpenChange,
+ onSuccess,
+}: SpendAlertDialogProps) {
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const capture = usePostHogClientCapture();
+
+ const form = useForm<SpendAlertFormInput, undefined, SpendAlertFormOutput>({
+ resolver: zodResolver(spendAlertSchema),
+ defaultValues: {
+ title: alert?.title ?? "",
+ limit: alert ? parseFloat(alert.threshold.toString()) : undefined,
+ },
+ });
+
+ const createMutation = api.spendAlerts.createSpendAlert.useMutation();
+ const updateMutation = api.spendAlerts.updateSpendAlert.useMutation();
+
+ const onSubmit = async (data: SpendAlertFormOutput) => {
+ setIsSubmitting(true);
+ try {
+ if (alert) {
+ // Update existing alert
+ await updateMutation.mutateAsync({
+ orgId,
+ id: alert.id,
+ title: data.title,
+ threshold: data.limit,
+ });
+ capture("spend_alert:updated", {
+ orgId,
+ alertId: alert.id,
+ limit: data.limit,
+ });
+ toast.success("Spend alert updated successfully");
+ } else {
+ // Create new alert
+ await createMutation.mutateAsync({
+ orgId,
+ title: data.title,
+ threshold: data.limit,
+ });
+ capture("spend_alert:created", {
+ orgId,
+ limit: data.limit,
+ });
+ toast.success("Spend alert created successfully");
+ }
+ onSuccess();
+ } catch (error) {
+ console.error("Failed to save spend alert:", error);
+ toast.error(
+ `Failed to ${alert ? "update" : "create"} spend alert. Please try again.`,
+ );
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="p-4 sm:max-w-[425px]">
+ <DialogTitle>
+ {alert ? "Edit Spend Alert" : "Create Spend Alert"}
+ </DialogTitle>
+ <DialogDescription className="pb-2 pt-1 text-sm text-muted-foreground">
+ Get notified when your organization&apos;s spending exceeds a limit.
+ </DialogDescription>
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
+ <FormField
+ control={form.control}
+ name="title"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Alert Title</FormLabel>
+ <FormControl>
+ <Input placeholder="e.g., Production Alert" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="limit"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Limit (USD)</FormLabel>
+ <FormControl>
+ <Input
+ type="number"
+ min="0.01"
+ step="0.01"
+ max="1000000"
+ placeholder="100.00"
+ name={field.name}
+ onBlur={field.onBlur}
+ ref={field.ref}
+ onChange={field.onChange}
+ value={
+ typeof field.value === "number" ||
+ typeof field.value === "string"
+ ? field.value
+ : ""
+ }
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <div className="text-xs text-muted-foreground">
+ <div className="flex flex-row items-center">
+ <Info className="mr-2 h-3 w-3" />
+ <span className="font-medium">How it works</span>
+ </div>
+ <ul className="list-disc pl-5">
+ <li>
+ The limit is evaluated against your upcoming invoice total,
+ including base fee, running usage fees, discounts, and taxes.
+ </li>
+ <li>Alerts trigger once per billing cycle.</li>
+ <li>You will receive an email when the alert is triggered.</li>
+ <li>Alerts are evaluated with a 90 minute delay.</li>
+ </ul>
+ </div>
+ <div className="flex flex-row items-center justify-end gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={isSubmitting}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" disabled={isSubmitting}>
+ {isSubmitting
+ ? alert
+ ? "Updating..."
+ : "Creating..."
+ : alert
+ ? "Update Alert"
+ : "Create Alert"}
+ </Button>
+ </div>
+ </form>
+ </Form>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/web/src/ee/features/billing/components/SpendAlerts/SpendAlertsSection.tsx b/web/src/ee/features/billing/components/SpendAlerts/SpendAlertsSection.tsx
new file mode 100644
index 0000000000..4b4ee0a749
--- /dev/null
+++ b/web/src/ee/features/billing/components/SpendAlerts/SpendAlertsSection.tsx
@@ -0,0 +1,65 @@
+import { useState } from "react";
+import { Button } from "@/src/components/ui/button";
+import { Plus } from "lucide-react";
+import { SpendAlertsTable } from "./SpendAlertsTable";
+import { SpendAlertDialog } from "./SpendAlertDialog";
+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
+import { useHasEntitlement } from "@/src/features/entitlements/hooks";
+
+interface SpendAlertsSectionProps {
+ orgId: string;
+}
+
+export function SpendAlertsSection({ orgId }: SpendAlertsSectionProps) {
+ const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
+ const [refetchTrigger, setRefetchTrigger] = useState(0);
+
+ const hasAccess = useHasOrganizationAccess({
+ organizationId: orgId,
+ scope: "langfuseCloudBilling:CRUD",
+ });
+
+ const hasEntitlement = useHasEntitlement("cloud-spend-alerts");
+
+ if (!hasEntitlement) {
+ return null;
+ }
+
+ if (!hasAccess) {
+ return null;
+ }
+
+ return (
+ <>
+ <div className="space-y-2">
+ <div className="flex items-center justify-between pt-4">
+ <div>
+ <h3 className="text-large font-medium">Spend Alerts</h3>
+ <p className="max-w-prose text-sm text-muted-foreground">
+ Get notified when your organization&apos;s spending exceeds
+ configured thresholds. Alerts may be delayed by up to 90 minutes.
+ </p>
+ <p className="max-w-prose text-sm text-muted-foreground"></p>
+ </div>
+
+ <Button onClick={() => setIsCreateDialogOpen(true)}>
+ <Plus className="mr-2 h-4 w-4" />
+ Create Alert
+ </Button>
+ </div>
+
+ <SpendAlertsTable orgId={orgId} key={refetchTrigger} />
+ </div>
+
+ <SpendAlertDialog
+ orgId={orgId}
+ open={isCreateDialogOpen}
+ onOpenChange={setIsCreateDialogOpen}
+ onSuccess={() => {
+ setIsCreateDialogOpen(false);
+ setRefetchTrigger((prev) => prev + 1); // Trigger refetch
+ }}
+ />
+ </>
+ );
+}
diff --git a/web/src/ee/features/billing/components/SpendAlerts/SpendAlertsTable.tsx b/web/src/ee/features/billing/components/SpendAlerts/SpendAlertsTable.tsx
new file mode 100644
index 0000000000..f77171a83e
--- /dev/null
+++ b/web/src/ee/features/billing/components/SpendAlerts/SpendAlertsTable.tsx
@@ -0,0 +1,175 @@
+import { useMemo, useState } from "react";
+import { Button } from "@/src/components/ui/button";
+import { Badge } from "@/src/components/ui/badge";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/src/components/ui/dropdown-menu";
+import { MoreHorizontal, Edit, Trash2 } from "lucide-react";
+import { api } from "@/src/utils/api";
+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
+import { formatDistanceToNow } from "date-fns";
+import { SpendAlertDialog } from "./SpendAlertDialog";
+import { DeleteSpendAlertDialog } from "./DeleteSpendAlertDialog";
+import { DataTable } from "@/src/components/table/data-table";
+import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
+import { type LangfuseColumnDef } from "@/src/components/table/types";
+import { usdFormatter } from "@/src/utils/numbers";
+
+interface SpendAlertsTableProps {
+ orgId: string;
+}
+
+type AlertRow = {
+ id: string;
+ title: string;
+ threshold: number; // USD
+ triggeredAt: Date | null;
+ createdAt: Date;
+};
+
+export function SpendAlertsTable({ orgId }: SpendAlertsTableProps) {
+ const [editingAlert, setEditingAlert] = useState<string | null>(null);
+ const [deletingAlert, setDeletingAlert] = useState<string | null>(null);
+
+ const hasAccess = useHasOrganizationAccess({
+ organizationId: orgId,
+ scope: "langfuseCloudBilling:CRUD",
+ });
+
+ const {
+ data: spendAlerts,
+ isLoading,
+ isError,
+ refetch,
+ } = api.spendAlerts.getSpendAlerts.useQuery(
+ { orgId },
+ { enabled: hasAccess },
+ );
+
+ const rows = useMemo<AlertRow[]>(() => {
+ return (spendAlerts ?? []).map((a: any) => ({
+ id: a.id,
+ title: a.title,
+ threshold: parseFloat(a.threshold?.toString?.() ?? "0"),
+ triggeredAt: a.triggeredAt ? new Date(a.triggeredAt) : null,
+ createdAt: new Date(a.createdAt),
+ }));
+ }, [spendAlerts]);
+
+ const data = useMemo(() => {
+ if (isLoading) return { isLoading: true, isError: false } as const;
+ if (isError)
+ return {
+ isLoading: false,
+ isError: false,
+ data: [] as AlertRow[],
+ } as const;
+ return { isLoading: false, isError: false, data: rows } as const;
+ }, [isLoading, isError, rows]);
+
+ const columns: LangfuseColumnDef<AlertRow>[] = [
+ {
+ accessorKey: "title",
+ id: "title",
+ header: "Title",
+ cell: ({ row }) => row.original.title,
+ size: 160,
+ },
+ {
+ accessorKey: "Limit",
+ id: "limit",
+ header: "Limit (USD)",
+ size: 140,
+ cell: ({ row }) => usdFormatter(row.original.threshold, 2, 2),
+ },
+ {
+ accessorKey: "status",
+ id: "status",
+ header: "Status",
+ size: 110,
+ cell: ({ row }) => (
+ <Badge variant={row.original.triggeredAt ? "destructive" : "secondary"}>
+ {row.original.triggeredAt ? "Triggered" : "Active"}
+ </Badge>
+ ),
+ },
+ {
+ accessorKey: "lastTriggered",
+ id: "lastTriggered",
+ header: "Last Triggered",
+ size: 160,
+ cell: ({ row }) =>
+ row.original.triggeredAt
+ ? formatDistanceToNow(new Date(row.original.triggeredAt), {
+ addSuffix: true,
+ })
+ : "Never",
+ },
+ {
+ accessorKey: "actions",
+ id: "actions",
+ header: "Actions",
+ size: 120,
+ cell: ({ row }) => (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" className="h-8 w-8 p-0">
+ <MoreHorizontal className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => setEditingAlert(row.original.id)}>
+ <Edit className="mr-2 h-4 w-4" />
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => setDeletingAlert(row.original.id)}
+ className="text-destructive"
+ >
+ <Trash2 className="mr-2 h-4 w-4" />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ),
+ },
+ ];
+
+ const editingAlertData = spendAlerts?.find((a) => a.id === editingAlert);
+
+ return (
+ <>
+ <DataTableToolbar columns={columns} />
+ <DataTable tableName={"spend-alerts"} columns={columns} data={data} />
+
+ {editingAlert && editingAlertData && (
+ <SpendAlertDialog
+ orgId={orgId}
+ alert={editingAlertData}
+ open={!!editingAlert}
+ onOpenChange={(open) => !open && setEditingAlert(null)}
+ onSuccess={() => {
+ setEditingAlert(null);
+ void refetch();
+ }}
+ />
+ )}
+
+ {deletingAlert && (
+ <DeleteSpendAlertDialog
+ orgId={orgId}
+ alertId={deletingAlert}
+ open={!!deletingAlert}
+ onOpenChange={(open) => !open && setDeletingAlert(null)}
+ onSuccess={() => {
+ setDeletingAlert(null);
+ void refetch();
+ }}
+ />
+ )}
+ </>
+ );
+}
diff --git a/web/src/ee/features/billing/components/UsageAlerts.tsx b/web/src/ee/features/billing/components/UsageAlerts.tsx
deleted file mode 100644
index 8b2397e1f3..0000000000
--- a/web/src/ee/features/billing/components/UsageAlerts.tsx
+++ /dev/null
@@ -1,321 +0,0 @@
-import React, { useEffect, useState } from "react";
-import { useForm } from "react-hook-form";
-import Link from "next/link";
-import { zodResolver } from "@hookform/resolvers/zod";
-import { z } from "zod/v4";
-import { api } from "@/src/utils/api";
-import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
-} from "@/src/components/ui/card";
-import { Button } from "@/src/components/ui/button";
-import { Input } from "@/src/components/ui/input";
-import { Switch } from "@/src/components/ui/switch";
-import {
- Form,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from "@/src/components/ui/form";
-import { toast } from "sonner";
-import { Bell, Plus, X } from "lucide-react";
-
-const usageAlertsSchema = z.object({
- enabled: z.boolean(),
- threshold: z.number().int().positive(),
- notifications: z.object({
- email: z.boolean(),
- recipients: z.array(z.string().email()),
- }),
-});
-
-type UsageAlertsFormData = z.infer<typeof usageAlertsSchema>;
-
-export function UsageAlerts({ orgId }: { orgId: string }) {
- const [newRecipient, setNewRecipient] = useState("");
- const [isAddingRecipient, setIsAddingRecipient] = useState(false);
-
- const {
- data: usageAlerts,
- isLoading,
- refetch,
- } = api.cloudBilling.getUsageAlerts.useQuery(
- { orgId },
- { enabled: Boolean(orgId) },
- );
-
- const upsertUsageAlerts = api.cloudBilling.upsertUsageAlerts.useMutation({
- onSuccess: () => {
- toast.success("Usage alerts updated", {
- description: "Your usage alert settings have been saved successfully.",
- });
- refetch();
- },
- onError: (error) => {
- toast.error("Failed to update usage alerts", {
- description: error.message,
- });
- },
- });
-
- const form = useForm<UsageAlertsFormData>({
- resolver: zodResolver(usageAlertsSchema),
- defaultValues: {
- enabled: false,
- threshold: 100000,
- notifications: {
- email: true,
- recipients: [],
- },
- },
- });
-
- useEffect(() => {
- // Overwrite from with existing usage alerts if available
- if (usageAlerts) {
- form.reset({
- enabled: usageAlerts.enabled,
- threshold: usageAlerts.threshold,
- notifications: {
- email: usageAlerts.notifications.email,
- recipients: usageAlerts.notifications.recipients || [],
- },
- });
- }
- }, [usageAlerts, form]);
-
- const onSubmit = (data: UsageAlertsFormData) => {
- upsertUsageAlerts.mutate({
- orgId,
- usageAlerts: data,
- });
- };
-
- const addRecipient = () => {
- if (!newRecipient.trim()) return;
-
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
- if (!emailRegex.test(newRecipient)) {
- toast.error("Invalid email address", {
- description: "Please enter a valid email address.",
- });
- return;
- }
-
- const currentRecipients = form.getValues("notifications.recipients");
- if (currentRecipients.includes(newRecipient)) {
- toast.error("Email already added", {
- description: "This email address is already in the recipient list.",
- });
- return;
- }
-
- form.setValue("notifications.recipients", [
- ...currentRecipients,
- newRecipient,
- ]);
- setNewRecipient("");
- setIsAddingRecipient(false);
- };
-
- const removeRecipient = (emailToRemove: string) => {
- const currentRecipients = form.getValues("notifications.recipients");
- form.setValue(
- "notifications.recipients",
- currentRecipients.filter((email) => email !== emailToRemove),
- );
- };
-
- const recipients = form.watch("notifications.recipients");
- const isEnabled = form.watch("enabled");
-
- if (isLoading) {
- return (
- <Card>
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <Bell className="h-5 w-5" />
- Usage Alerts
- </CardTitle>
- <CardDescription>Loading usage alert settings...</CardDescription>
- </CardHeader>
- </Card>
- );
- }
-
- return (
- <Card>
- <CardHeader>
- <div className="flex items-start justify-between">
- <div className="pr-8">
- <CardTitle className="flex items-center gap-2">
- <Bell className="h-5 w-5" />
- Usage Alerts
- </CardTitle>
- <CardDescription className="mt-2">
- Get notified when your usage exceeds a specified threshold to
- avoid billing surprises. The alert triggers at most once per
- billing cycle and will only consider &quot;future&quot; usage from
- the time of creation or last update.
- </CardDescription>
- </div>
- <Form {...form}>
- <FormField
- control={form.control}
- name="enabled"
- render={({ field }) => (
- <FormItem>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
- </Form>
- </div>
- </CardHeader>
- <CardContent>
- <Form {...form}>
- <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
- {isEnabled && (
- <>
- <FormField
- control={form.control}
- name="threshold"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Threshold Amount</FormLabel>
- <FormControl>
- <div className="flex items-center space-x-2">
- <Input
- type="number"
- placeholder="100000"
- {...field}
- onChange={(e) =>
- field.onChange(Number(e.target.value))
- }
- className="flex-1"
- />
- <span className="text-sm text-muted-foreground">
- Events
- </span>
- </div>
- </FormControl>
- <FormDescription>
- You&apos;ll receive an alert when your usage exceeds
- this number of events in your billing period. Go to our{" "}
- <Link
- href={
- "https://langfuse.com/pricing?calculatorOpen=true"
- }
- target="_blank"
- className="underline"
- >
- pricing calculator
- </Link>{" "}
- to translate events into cost.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <div className="space-y-4">
- <div>
- <h4 className="mb-2 text-sm font-medium">
- Email Recipients
- </h4>
- <p className="mb-3 text-sm text-muted-foreground">
- Organization admins will automatically receive alerts. Add
- additional recipients below.
- </p>
-
- <div className="space-y-2">
- {recipients.map((email, index) => (
- <div
- key={index}
- className="flex items-center justify-between rounded-md border p-2"
- >
- <span className="text-sm">{email}</span>
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={() => removeRecipient(email)}
- >
- <X className="h-4 w-4" />
- </Button>
- </div>
- ))}
-
- {isAddingRecipient ? (
- <div className="flex items-center space-x-2">
- <Input
- type="email"
- placeholder="Enter email address"
- value={newRecipient}
- onChange={(e) => setNewRecipient(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter") {
- e.preventDefault();
- addRecipient();
- }
- }}
- className="flex-1"
- />
- <Button
- type="button"
- size="sm"
- onClick={addRecipient}
- >
- Add
- </Button>
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => {
- setIsAddingRecipient(false);
- setNewRecipient("");
- }}
- >
- Cancel
- </Button>
- </div>
- ) : (
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => setIsAddingRecipient(true)}
- className="w-full"
- >
- <Plus className="mr-2 h-4 w-4" />
- Add Recipient
- </Button>
- )}
- </div>
- </div>
- </div>
- </>
- )}
-
- <div className="flex justify-end">
- <Button type="submit" disabled={upsertUsageAlerts.isPending}>
- {upsertUsageAlerts.isPending ? "Saving..." : "Save Changes"}
- </Button>
- </div>
- </form>
- </Form>
- </CardContent>
- </Card>
- );
-}
diff --git a/web/src/ee/features/billing/server/cloudBillingRouter.ts b/web/src/ee/features/billing/server/cloudBillingRouter.ts
index 834cfe7307..c1e435fc18 100644
--- a/web/src/ee/features/billing/server/cloudBillingRouter.ts
+++ b/web/src/ee/features/billing/server/cloudBillingRouter.ts
@@ -2,7 +2,6 @@ import * as z from "zod/v4";
import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
-import { parseDbOrg } from "@langfuse/shared";
import {
createTRPCRouter,
protectedOrganizationProcedure,
@@ -316,90 +315,4 @@ export const cloudBillingRouter = createTRPCRouter({
return result;
}),
- getUsageAlerts: protectedOrganizationProcedure
- .input(z.object({ orgId: z.string(), opId: z.string().optional() }))
- .query(async ({ input, ctx }) => {
- throwIfNoEntitlement({
- entitlement: "cloud-billing",
- sessionUser: ctx.session.user,
- orgId: input.orgId,
- });
- throwIfNoOrganizationAccess({
- organizationId: input.orgId,
- scope: "langfuseCloudBilling:CRUD",
- session: ctx.session,
- });
-
- const org = await ctx.prisma.organization.findUnique({
- where: {
- id: input.orgId,
- },
- });
- if (!org) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Organization not found",
- });
- }
-
- const parsedOrg = parseDbOrg(org);
- return parsedOrg.cloudConfig?.usageAlerts || null;
- }),
- upsertUsageAlerts: protectedOrganizationProcedure
- .input(
- z.object({
- orgId: z.string(),
- usageAlerts: z.object({
- enabled: z.boolean(),
- threshold: z.number().int().positive(),
- notifications: z.object({
- email: z.boolean().default(true),
- recipients: z.array(z.string().email()),
- }),
- }),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- throwIfNoEntitlement({
- entitlement: "cloud-billing",
- sessionUser: ctx.session.user,
- orgId: input.orgId,
- });
- throwIfNoOrganizationAccess({
- organizationId: input.orgId,
- scope: "langfuseCloudBilling:CRUD",
- session: ctx.session,
- });
-
- try {
- const orgBefore = await ctx.prisma.organization.findUnique({
- where: { id: input.orgId },
- });
- const updatedAlerts = await createBillingServiceFromContext(
- ctx,
- ).upsertUsageAlerts(input.orgId, input.usageAlerts);
- const orgAfter = await ctx.prisma.organization.findUnique({
- where: { id: input.orgId },
- });
- void auditLog({
- session: ctx.session,
- orgId: input.orgId,
- resourceType: "organization",
- resourceId: input.orgId,
- action: "updateUsageAlerts",
- before: orgBefore!,
- after: orgAfter!,
- });
- return updatedAlerts;
- } catch (error) {
- logger.error("Failed to update usage alerts", {
- error,
- orgId: input.orgId,
- });
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Failed to update usage alerts",
- });
- }
- }),
});
diff --git a/web/src/ee/features/billing/server/spendAlertRouter.ts b/web/src/ee/features/billing/server/spendAlertRouter.ts
new file mode 100644
index 0000000000..e40e48017a
--- /dev/null
+++ b/web/src/ee/features/billing/server/spendAlertRouter.ts
@@ -0,0 +1,187 @@
+import * as z from "zod/v4";
+
+import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
+
+import {
+ createTRPCRouter,
+ protectedOrganizationProcedure,
+} from "@/src/server/api/trpc";
+import { TRPCError } from "@trpc/server";
+import { throwIfNoOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+
+export const spendAlertRouter = createTRPCRouter({
+ getSpendAlerts: protectedOrganizationProcedure
+ .input(z.object({ orgId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ throwIfNoEntitlement({
+ entitlement: "cloud-billing",
+ sessionUser: ctx.session.user,
+ orgId: input.orgId,
+ });
+ throwIfNoOrganizationAccess({
+ organizationId: input.orgId,
+ scope: "langfuseCloudBilling:CRUD",
+ session: ctx.session,
+ });
+
+ const spendAlerts = await ctx.prisma.cloudSpendAlert.findMany({
+ where: {
+ orgId: input.orgId,
+ },
+ orderBy: {
+ createdAt: "desc",
+ },
+ });
+
+ return spendAlerts;
+ }),
+
+ createSpendAlert: protectedOrganizationProcedure
+ .input(
+ z.object({
+ orgId: z.string(),
+ title: z.string().min(1).max(100),
+ threshold: z.number().positive().max(1000000), // Max $1M USD
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoEntitlement({
+ entitlement: "cloud-billing",
+ sessionUser: ctx.session.user,
+ orgId: input.orgId,
+ });
+ throwIfNoOrganizationAccess({
+ organizationId: input.orgId,
+ scope: "langfuseCloudBilling:CRUD",
+ session: ctx.session,
+ });
+
+ const spendAlert = await ctx.prisma.cloudSpendAlert.create({
+ data: {
+ orgId: input.orgId,
+ title: input.title,
+ threshold: input.threshold,
+ },
+ });
+
+ await auditLog({
+ session: ctx.session,
+ orgId: input.orgId,
+ resourceType: "cloudSpendAlert",
+ resourceId: spendAlert.id,
+ action: "create",
+ after: spendAlert,
+ });
+
+ return spendAlert;
+ }),
+
+ updateSpendAlert: protectedOrganizationProcedure
+ .input(
+ z.object({
+ orgId: z.string(),
+ id: z.string(),
+ title: z.string().min(1).max(100).optional(),
+ threshold: z.number().positive().max(1000000).optional(), // Max $1M USD
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoEntitlement({
+ entitlement: "cloud-billing",
+ sessionUser: ctx.session.user,
+ orgId: input.orgId,
+ });
+ throwIfNoOrganizationAccess({
+ organizationId: input.orgId,
+ scope: "langfuseCloudBilling:CRUD",
+ session: ctx.session,
+ });
+
+ // Check if spend alert exists and belongs to the organization
+ const existingAlert = await ctx.prisma.cloudSpendAlert.findFirst({
+ where: {
+ id: input.id,
+ orgId: input.orgId,
+ },
+ });
+
+ if (!existingAlert) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Spend alert not found",
+ });
+ }
+
+ const updateData: { title?: string; threshold?: number } = {};
+ if (input.title !== undefined) updateData.title = input.title;
+ if (input.threshold !== undefined) updateData.threshold = input.threshold;
+
+ const updatedAlert = await ctx.prisma.cloudSpendAlert.update({
+ where: { id: input.id },
+ data: updateData,
+ });
+
+ await auditLog({
+ session: ctx.session,
+ orgId: input.orgId,
+ resourceType: "cloudSpendAlert",
+ resourceId: updatedAlert.id,
+ action: "update",
+ before: existingAlert,
+ after: updatedAlert,
+ });
+
+ return updatedAlert;
+ }),
+
+ deleteSpendAlert: protectedOrganizationProcedure
+ .input(
+ z.object({
+ orgId: z.string(),
+ id: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoEntitlement({
+ entitlement: "cloud-billing",
+ sessionUser: ctx.session.user,
+ orgId: input.orgId,
+ });
+ throwIfNoOrganizationAccess({
+ organizationId: input.orgId,
+ scope: "langfuseCloudBilling:CRUD",
+ session: ctx.session,
+ });
+
+ // Check if spend alert exists and belongs to the organization
+ const existingAlert = await ctx.prisma.cloudSpendAlert.findFirst({
+ where: {
+ id: input.id,
+ orgId: input.orgId,
+ },
+ });
+
+ if (!existingAlert) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Spend alert not found",
+ });
+ }
+
+ await ctx.prisma.cloudSpendAlert.delete({
+ where: { id: input.id },
+ });
+
+ await auditLog({
+ session: ctx.session,
+ orgId: input.orgId,
+ resourceType: "cloudSpendAlert",
+ resourceId: input.id,
+ action: "delete",
+ before: existingAlert,
+ });
+
+ return { success: true };
+ }),
+});
diff --git a/web/src/ee/features/billing/server/stripeBillingService.ts b/web/src/ee/features/billing/server/stripeBillingService.ts
index 63a9d7c238..60efaaa642 100644
--- a/web/src/ee/features/billing/server/stripeBillingService.ts
+++ b/web/src/ee/features/billing/server/stripeBillingService.ts
@@ -28,7 +28,6 @@ import {
IdempotencyKind,
} from "@/src/ee/features/billing/utils/stripeIdempotencyKey";
-import { UsageAlertService } from "./usageAlertService";
import { type StripeSubscriptionMetadata } from "@/src/ee/features/billing/utils/stripeSubscriptionMetadata";
type ProductWithDefaultPrice = Expanded<Stripe.Product, "default_price">;
@@ -1742,117 +1741,6 @@ class BillingService {
return { ok: true as const };
}
-
- // TODO: Currently not working as expected, need to fix
- /**
- * Create/update/deactivate Stripe usage alerts for an organization.
- *
- * Preconditions: Org must have a Stripe customer and active subscription.
- *
- * @param orgId Organization id
- * @param payload Usage alert configuration
- */
- async upsertUsageAlerts(
- orgId: string,
- payload: {
- enabled: boolean;
- threshold: number;
- notifications: { email: boolean; recipients: string[] };
- },
- ) {
- const { parsedOrg } = await this.getParsedOrg(orgId);
- const stripeCustomerId = parsedOrg.cloudConfig?.stripe?.customerId;
- const subscriptionId = parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;
- const currentAlerts = parsedOrg.cloudConfig?.usageAlerts;
- if (!stripeCustomerId || !subscriptionId)
- throw new TRPCError({
- code: "PRECONDITION_FAILED",
- message:
- "Organization must have a Stripe customer with active subscription to configure usage alerts",
- });
- const client = this.stripe;
- let updatedAlerts = payload;
-
- const subscription = await client.subscriptions.retrieve(subscriptionId);
- if (!subscription)
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Stripe subscription not found",
- });
- const meterId = subscription.items.data.filter((subItem) =>
- Boolean((subItem as any).plan.meter),
- )[0]?.plan.meter as string | undefined;
-
- const updatedUsageAlertConfig: any = {
- enabled: updatedAlerts.enabled,
- type: "STRIPE",
- threshold: updatedAlerts.threshold,
- alertId: currentAlerts?.alertId ?? null,
- meterId: meterId ?? null,
- notifications: {
- email: updatedAlerts.notifications.email,
- recipients: updatedAlerts.notifications.recipients,
- },
- };
-
- if (
- !updatedAlerts.enabled &&
- currentAlerts?.alertId &&
- currentAlerts?.enabled
- ) {
- await UsageAlertService.getInstance({ stripeClient: client }).deactivate({
- id: currentAlerts?.alertId,
- });
- }
- if (!currentAlerts?.alertId) {
- const alert = await UsageAlertService.getInstance({
- stripeClient: client,
- }).create({
- orgId,
- customerId: stripeCustomerId,
- meterId,
- amount: updatedAlerts.threshold,
- });
- updatedUsageAlertConfig.alertId = alert.id;
- }
- if (
- updatedAlerts.enabled &&
- currentAlerts?.alertId &&
- (currentAlerts?.threshold !== updatedAlerts.threshold ||
- currentAlerts.meterId !== meterId)
- ) {
- const alert = await UsageAlertService.getInstance({
- stripeClient: client,
- }).recreate({
- orgId,
- customerId: stripeCustomerId,
- meterId,
- existingAlertId: currentAlerts.alertId,
- amount: updatedAlerts.threshold,
- });
- updatedUsageAlertConfig.alertId = alert.id;
- }
- if (
- updatedAlerts.enabled &&
- currentAlerts?.alertId &&
- !currentAlerts.enabled
- ) {
- await UsageAlertService.getInstance({ stripeClient: client }).activate({
- id: currentAlerts.alertId,
- });
- }
-
- const newCloudConfig = {
- ...parsedOrg.cloudConfig,
- usageAlerts: updatedUsageAlertConfig,
- };
- await this.ctx.prisma.organization.update({
- where: { id: orgId },
- data: { cloudConfig: newCloudConfig },
- });
-
- return updatedAlerts;
- }
}
/**
diff --git a/web/src/ee/features/billing/server/stripeWebhookHandler.ts b/web/src/ee/features/billing/server/stripeWebhookHandler.ts
index 5d971b3b65..b5deb93323 100644
--- a/web/src/ee/features/billing/server/stripeWebhookHandler.ts
+++ b/web/src/ee/features/billing/server/stripeWebhookHandler.ts
@@ -20,9 +20,6 @@ import {
startOfDayUTC,
} from "@langfuse/shared/src/server";
import { auditLog } from "@/src/features/audit-logs/auditLog";
-import { sendBillingAlertEmail } from "@langfuse/shared/src/server";
-import { Role } from "@langfuse/shared";
-import { UsageAlertService } from "@/src/ee/features/billing/server/usageAlertService";
import { type StripeSubscriptionMetadata } from "@/src/ee/features/billing/utils/stripeSubscriptionMetadata";
/**
@@ -113,20 +110,6 @@ export async function stripeWebhookHandler(req: NextRequest) {
});
await handleSubscriptionChanged(deletedSubscription, "deleted");
break;
- case "invoice.created":
- const invoiceData = event.data.object;
- logger.info("[Stripe Webhook] Start invoice.created", {
- payload: invoiceData,
- });
- await handleInvoiceCreated(invoiceData);
- break;
- case "billing.alert.triggered":
- const alertData = event.data.object;
- logger.info("[Stripe Webhook] Start billing.alert.triggered", {
- payload: alertData,
- });
- await handleBillingAlertTriggered(alertData);
- break;
default:
logger.warn(`Unhandled event type ${event.type}`);
}
@@ -618,274 +601,3 @@ async function handleSubscriptionChanged(
return;
}
-
-async function handleBillingAlertTriggered(
- alertData: Stripe.Billing.AlertTriggered,
-) {
- try {
- // Find organization by Stripe customer ID
- const customerId = alertData.customer;
- if (!customerId) {
- logger.error("[Stripe Webhook] No customer ID found in usage alert");
- return;
- }
-
- const organization = await prisma.organization.findFirst({
- where: {
- cloudConfig: {
- path: ["stripe", "customerId"],
- equals: customerId,
- },
- },
- });
-
- if (!organization) {
- logger.warn(
- "[Stripe Webhook] Organization not found for customer ID - Potentially received the webhook on wrong environment",
- {
- customerId,
- },
- );
- return;
- }
-
- const parsedOrg = parseDbOrg(organization);
- const usageAlerts = parsedOrg.cloudConfig?.usageAlerts;
-
- if (!usageAlerts || !usageAlerts.enabled) {
- logger.info(
- "[Stripe Webhook] Usage alerts not enabled for organization",
- {
- orgId: organization.id,
- },
- );
- return;
- }
-
- // Extract usage information from alert data
- const usageAmount = alertData.value;
- const threshold = usageAlerts.threshold;
-
- // Send email notifications if enabled
- if (usageAlerts.notifications.email) {
- await sendBillingAlertNotifications({
- organization,
- usageAlerts,
- usageAmount,
- threshold,
- alertId: alertData.alert.id,
- });
- }
-
- logger.info("[Stripe Webhook] Usage alert triggered successfully", {
- organizationId: organization.id,
- organizationName: organization.name,
- usageAmount,
- threshold,
- alertId: alertData.alert.id,
- });
- } catch (error) {
- logger.error("[Stripe Webhook] Error processing usage alert", {
- error,
- alertId: alertData.alert.id,
- });
- traceException("[Stripe Webhook] Error processing usage alert");
- }
-}
-
-async function sendBillingAlertNotifications({
- organization,
- usageAlerts,
- usageAmount,
- threshold,
- alertId,
-}: {
- organization: Organization;
- usageAlerts: NonNullable<
- ReturnType<typeof parseDbOrg>["cloudConfig"]
- >["usageAlerts"];
- usageAmount: number;
- threshold: number;
- alertId: string;
-}) {
- try {
- // Get organization admins and owners
- const adminMembers = await prisma.organizationMembership.findMany({
- where: {
- orgId: organization.id,
- role: {
- in: [Role.ADMIN, Role.OWNER],
- },
- },
- include: {
- user: {
- select: {
- email: true,
- },
- },
- },
- });
-
- // Collect all recipients
- const recipients = new Set<string>();
-
- // Add admin/owner emails
- adminMembers.forEach((member) => {
- if (member.user.email) {
- recipients.add(member.user.email);
- }
- });
-
- // Add additional recipients from settings
- if (usageAlerts?.notifications.recipients) {
- usageAlerts.notifications.recipients.forEach((email) => {
- recipients.add(email);
- });
- }
-
- // Generate URLs
- const billingUrl = `${env.NEXTAUTH_URL}/organization/${organization.id}/settings/billing`;
-
- // Send email to all recipients
- const emailPromises = Array.from(recipients).map(async (email) => {
- try {
- await sendBillingAlertEmail({
- env,
- organizationName: organization.name,
- currentUsage: usageAmount,
- threshold,
- billingUrl,
- receiverEmail: email,
- });
-
- logger.info("[Stripe Webhook] Usage alert email sent", {
- organizationId: organization.id,
- recipientEmail: email,
- alertId,
- });
- } catch (error) {
- logger.error("[Stripe Webhook] Failed to send usage alert email", {
- organizationId: organization.id,
- recipientEmail: email,
- alertId,
- error,
- });
- }
- });
-
- await Promise.all(emailPromises);
-
- logger.info("[Stripe Webhook] Billing alert notifications sent", {
- organizationId: organization.id,
- recipientCount: recipients.size,
- alertId,
- });
- } catch (error) {
- logger.error("[Stripe Webhook] Error sending usage alert notifications", {
- organizationId: organization.id,
- alertId,
- error,
- });
- }
-}
-
-/**
- * Whenever a stripe invoice is created, we recreate the usage alert.
- * This is necessary, because usage alerts trigger only once globally and with this setup,
- * we can ensure that they trigger once per billing period.
- * @param invoice
- */
-async function handleInvoiceCreated(invoice: Stripe.Invoice): Promise<void> {
- try {
- // Find organization by Stripe customer ID
- const customerId =
- typeof invoice.customer === "string"
- ? invoice.customer
- : invoice.customer?.id;
- if (!customerId) {
- logger.error(
- "[Stripe Webhook] No customer ID found in invoice created event",
- );
- return;
- }
-
- const organization = await prisma.organization.findFirst({
- where: {
- cloudConfig: {
- path: ["stripe", "customerId"],
- equals: customerId,
- },
- },
- });
-
- if (!organization) {
- logger.warn(
- "[Stripe Webhook] Organization not found for customer ID - Potentially received the webhook on wrong environment",
- {
- customerId,
- },
- );
- return;
- }
-
- const parsedOrg = parseDbOrg(organization);
- const usageAlerts = parsedOrg.cloudConfig?.usageAlerts;
-
- if (!usageAlerts || !usageAlerts.enabled) {
- logger.info(
- "[Stripe Webhook] Usage alerts not enabled for organization - skipping recreation",
- {
- orgId: organization.id,
- },
- );
- return;
- }
-
- const updatedAlert = await UsageAlertService.getInstance({
- stripeClient,
- }).recreate({
- orgId: parsedOrg.id,
- customerId: customerId,
- meterId: usageAlerts.meterId,
- existingAlertId: usageAlerts.alertId,
- amount: usageAlerts.threshold,
- });
- // We can use ! here as we'd never reach this point if the fields are undefined
- parsedOrg.cloudConfig!.usageAlerts!.alertId = updatedAlert.id;
-
- await prisma.organization.update({
- where: {
- id: parsedOrg.id,
- },
- data: {
- cloudConfig: parsedOrg.cloudConfig!,
- },
- });
-
- void auditLog({
- session: {
- user: { id: "stripe-webhook" },
- orgId: parsedOrg.id,
- },
- orgId: parsedOrg.id,
- resourceType: "organization",
- resourceId: parsedOrg.id,
- action: "BillingService.usageAlerts.recreate",
- before: parsedOrg.cloudConfig,
- after: parsedOrg.cloudConfig!,
- });
- logger.info(
- `[Stripe Webhook] Recreated usage alert for ${parsedOrg.id} after invoice creation`,
- {
- orgId: parsedOrg.id,
- alertId: updatedAlert.id,
- },
- );
- } catch (error) {
- logger.error("[Stripe Webhook] Error handling invoice created", {
- error,
- invoiceId: invoice.id,
- });
- traceException("[Stripe Webhook] Error handling invoice created");
- }
-}
diff --git a/web/src/ee/features/billing/server/usageAlertService.ts b/web/src/ee/features/billing/server/usageAlertService.ts
deleted file mode 100644
index 142aa11d38..0000000000
--- a/web/src/ee/features/billing/server/usageAlertService.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-import type Stripe from "stripe";
-import { TRPCError } from "@trpc/server";
-
-export interface UsageAlertServiceConfig {
- stripeClient?: Stripe;
-}
-
-class UsageAlertService {
- private stripeClient: Stripe;
-
- private static instance: UsageAlertService;
-
- public static getInstance(
- config: UsageAlertServiceConfig,
- ): UsageAlertService {
- if (!config || !config.stripeClient) {
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Stripe client is required and cannot be empty",
- });
- }
- if (!UsageAlertService.instance) {
- UsageAlertService.instance = new UsageAlertService(config);
- }
- return UsageAlertService.instance;
- }
-
- constructor(config: UsageAlertServiceConfig) {
- if (!config.stripeClient) {
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Stripe client is required and cannot be empty",
- });
- }
- this.stripeClient = config.stripeClient;
- }
-
- public async create({
- orgId,
- customerId,
- meterId,
- amount,
- }: {
- orgId: string;
- customerId: string;
- meterId: string | null | undefined;
- amount: number;
- }) {
- if (!meterId) {
- throw new TRPCError({
- code: "PRECONDITION_FAILED",
- message: "Meter ID is required to create a usage alert",
- });
- }
-
- return this.stripeClient.billing.alerts.create({
- title: `Usage Alert ${orgId}`,
- alert_type: "usage_threshold",
- usage_threshold: {
- filters: [
- {
- type: "customer",
- customer: customerId,
- },
- ],
- gte: amount,
- meter: meterId,
- recurrence: "one_time",
- },
- });
- }
-
- public async recreate({
- orgId,
- customerId,
- meterId,
- existingAlertId,
- amount,
- }: {
- orgId: string;
- customerId: string;
- meterId: string | null | undefined;
- existingAlertId: string;
- amount: number;
- }) {
- if (!meterId) {
- throw new TRPCError({
- code: "PRECONDITION_FAILED",
- message: "Meter ID is required to recreate a usage alert",
- });
- }
- if (!existingAlertId) {
- throw new TRPCError({
- code: "PRECONDITION_FAILED",
- message: "Existing alert ID is required to recreate a usage alert",
- });
- }
-
- // Deactivate the existing alert
- await this.stripeClient.billing.alerts.archive(existingAlertId);
-
- // Create a new alert with the same meter ID and updated amount
- return this.create({ orgId, customerId, meterId, amount });
- }
-
- public async activate({ id }: { id: string }) {
- return this.stripeClient.billing.alerts.activate(id);
- }
-
- public async deactivate({ id }: { id: string }) {
- return this.stripeClient.billing.alerts.deactivate(id);
- }
-}
-
-// Export the service class for testing purposes
-export { UsageAlertService };
diff --git a/web/src/features/audit-logs/auditLog.ts b/web/src/features/audit-logs/auditLog.ts
index a1626d88c2..56f3110d39 100644
--- a/web/src/features/audit-logs/auditLog.ts
+++ b/web/src/features/audit-logs/auditLog.ts
@@ -39,6 +39,7 @@ export type AuditableResource =
| "automation"
| "action"
| "slackIntegration"
+ | "cloudSpendAlert"
// legacy resources
| "membership";
diff --git a/web/src/features/entitlements/constants/entitlements.ts b/web/src/features/entitlements/constants/entitlements.ts
index e43407c23f..c0aa9c7f73 100644
--- a/web/src/features/entitlements/constants/entitlements.ts
+++ b/web/src/features/entitlements/constants/entitlements.ts
@@ -5,7 +5,7 @@ const entitlements = [
// features
"rbac-project-roles",
"cloud-billing",
- "cloud-usage-alerts",
+ "cloud-spend-alerts",
"cloud-multi-tenant-sso",
"self-host-ui-customization",
"self-host-allowed-organization-creators",
@@ -62,8 +62,7 @@ export const entitlementAccess: Record<
},
},
"cloud:core": {
- // TODO: Update Stripe Webhooks when enabling this again.
- entitlements: [...cloudAllPlansEntitlements], // , "cloud-usage-alerts"],
+ entitlements: [...cloudAllPlansEntitlements, "cloud-spend-alerts"],
entitlementLimits: {
"organization-member-count": false,
"data-access-days": 90,
@@ -73,7 +72,7 @@ export const entitlementAccess: Record<
},
},
"cloud:pro": {
- entitlements: [...cloudAllPlansEntitlements], // "cloud-usage-alerts"],
+ entitlements: [...cloudAllPlansEntitlements, "cloud-spend-alerts"],
entitlementLimits: {
"annotation-queue-count": false,
"organization-member-count": false,
@@ -92,7 +91,7 @@ export const entitlementAccess: Record<
"prompt-protected-labels",
"admin-api",
"scheduled-blob-exports",
- // "cloud-usage-alerts",
+ "cloud-spend-alerts",
],
entitlementLimits: {
"annotation-queue-count": false,
@@ -112,7 +111,7 @@ export const entitlementAccess: Record<
"prompt-protected-labels",
"admin-api",
"scheduled-blob-exports",
- // "cloud-usage-alerts",
+ "cloud-spend-alerts",
],
entitlementLimits: {
"annotation-queue-count": false,
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index 9a32488ada..ca5d868d1f 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -191,6 +191,7 @@ const events = {
navigate_detail_pages: ["button_click_prev_or_next"],
support_chat: ["initiated", "opened", "message_sent"], // also used on landing page for consistency
cmd_k_menu: ["opened", "search_entered", "navigated"],
+ spend_alert: ["created", "updated", "deleted"],
} as const;
// type that represents all possible event names, e.g. "traces:bookmark"
diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.ts
index b806703539..0abbd5432e 100644
--- a/web/src/server/api/root.ts
+++ b/web/src/server/api/root.ts
@@ -9,6 +9,7 @@ import { membersRouter } from "@/src/features/rbac/server/membersRouter";
import { userRouter } from "@/src/server/api/routers/users";
import { datasetRouter } from "@/src/features/datasets/server/dataset-router";
import { cloudBillingRouter } from "@/src/ee/features/billing/server/cloudBillingRouter";
+import { spendAlertRouter } from "@/src/ee/features/billing/server/spendAlertRouter";
import { observationsRouter } from "@/src/server/api/routers/observations";
import { sessionRouter } from "@/src/server/api/routers/sessions";
import { promptRouter } from "@/src/features/prompts/server/routers/promptRouter";
@@ -70,6 +71,7 @@ export const appRouter = createTRPCRouter({
members: membersRouter,
datasets: datasetRouter,
cloudBilling: cloudBillingRouter,
+ spendAlerts: spendAlertRouter,
observations: observationsRouter,
prompts: promptRouter,
models: modelRouter,
diff --git a/worker/src/app.ts b/worker/src/app.ts
index 305e2e84f5..a5619fd011 100644
--- a/worker/src/app.ts
+++ b/worker/src/app.ts
@@ -18,6 +18,7 @@ import { batchExportQueueProcessor } from "./queues/batchExportQueue";
import { onShutdown } from "./utils/shutdown";
import helmet from "helmet";
import { cloudUsageMeteringQueueProcessor } from "./queues/cloudUsageMeteringQueue";
+import { cloudSpendAlertQueueProcessor } from "./queues/cloudSpendAlertQueue";
import { cloudFreeTierUsageThresholdQueueProcessor } from "./queues/cloudFreeTierUsageThresholdQueue";
import { WorkerManager } from "./queues/workerManager";
import {
@@ -302,6 +303,27 @@ if (
);
}
+// Cloud Spend Alert Queue: Only enable in cloud environment with Stripe
+if (
+ env.QUEUE_CONSUMER_CLOUD_SPEND_ALERT_QUEUE_IS_ENABLED === "true" &&
+ env.STRIPE_SECRET_KEY
+) {
+ WorkerManager.register(
+ QueueName.CloudSpendAlertQueue,
+ cloudSpendAlertQueueProcessor,
+ {
+ concurrency: 20,
+ limiter: {
+ // Process at most 600 jobs per minute / 10 jobs per second for Stripe API rate limits
+ // - stripe allows 100 ops / sec but we want to use a lower limit to account for 3 environments and other calls
+ // - See: https://docs.stripe.com/rate-limits
+ max: 900,
+ duration: 60_000,
+ },
+ },
+ );
+}
+
// Free Tier Usage Threshold Queue: Only enable in cloud environment
if (
env.QUEUE_CONSUMER_FREE_TIER_USAGE_THRESHOLD_QUEUE_IS_ENABLED === "true" &&
diff --git a/worker/src/ee/cloudSpendAlerts/handleCloudSpendAlertJob.ts b/worker/src/ee/cloudSpendAlerts/handleCloudSpendAlertJob.ts
new file mode 100644
index 0000000000..e3b4c40087
--- /dev/null
+++ b/worker/src/ee/cloudSpendAlerts/handleCloudSpendAlertJob.ts
@@ -0,0 +1,257 @@
+import { parseDbOrg, Role } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import Stripe from "stripe";
+import { env } from "../../env";
+import { logger } from "@langfuse/shared/src/server";
+import { recordIncrement, traceException } from "@langfuse/shared/src/server";
+import { Job } from "bullmq";
+import { backOff } from "exponential-backoff";
+import { sendCloudSpendAlertEmail } from "@langfuse/shared/src/server";
+
+export const handleCloudSpendAlertJob = async (job: Job<{ orgId: string }>) => {
+ const { orgId } = job.data;
+
+ logger.info(`[CLOUD SPEND ALERTS] Processing org ${orgId}`);
+
+ if (!env.STRIPE_SECRET_KEY) {
+ logger.warn("[CLOUD SPEND ALERTS] Stripe secret key not found");
+ throw new Error("Stripe secret key not found");
+ }
+
+ // Fetch organization with spend alerts
+ const orgData = await prisma.organization.findFirst({
+ where: {
+ id: orgId,
+ },
+ include: {
+ cloudSpendAlerts: true,
+ },
+ });
+
+ if (!orgData) {
+ logger.error(`[CLOUD SPEND ALERTS] Organization ${orgId} not found`);
+ return;
+ }
+
+ const org = {
+ ...parseDbOrg(orgData),
+ spendAlerts: orgData.cloudSpendAlerts,
+ };
+
+ // Check if org has spend alerts configured
+ if (org.spendAlerts.length === 0) {
+ logger.info(`[CLOUD SPEND ALERTS] No spend alerts for org ${orgId}`);
+ return;
+ }
+
+ if (org.cloudConfig?.plan === "Hobby") {
+ // handle case where user has downgraded to hobby
+ logger.info(
+ `[CLOUD SPEND ALERTS] Org ${orgId} not entitled to spend alerts (plan: Hobby"})`,
+ );
+ return;
+ }
+
+ // Get Stripe customer ID
+ const stripeCustomerId = org.cloudConfig?.stripe?.customerId;
+ if (!stripeCustomerId) {
+ logger.error(
+ `[CLOUD SPEND ALERTS] Stripe customer id not found for org ${orgId}`,
+ );
+ traceException(
+ `[CLOUD SPEND ALERTS] Stripe customer id not found for org ${orgId}`,
+ );
+ return;
+ }
+ // Get Stripe subscription ID
+ const stripeSubscriptionId = org.cloudConfig?.stripe?.activeSubscriptionId;
+ if (!stripeSubscriptionId) {
+ logger.error(
+ `[CLOUD SPEND ALERTS] Stripe subscription id not found for org ${orgId}`,
+ );
+ traceException(
+ `[CLOUD SPEND ALERTS] Stripe subscription id not found for org ${orgId}`,
+ );
+ return;
+ }
+
+ // Setup stripe client
+ const stripe = new Stripe(env.STRIPE_SECRET_KEY);
+
+ try {
+ // Get subscription to check billing cycle
+ const subscription =
+ await stripe.subscriptions.retrieve(stripeSubscriptionId);
+
+ const currentPeriodStart = new Date(
+ subscription.current_period_start * 1000,
+ );
+
+ // Create preview invoice to calculate current spend
+ const canCreateInvoicePreview = [
+ "active",
+ "past_due",
+ "trialing",
+ "unpaid",
+ ].includes(subscription.status);
+
+ if (!canCreateInvoicePreview) {
+ logger.warn(
+ `[CLOUD SPEND ALERTS] Cannot create invoice preview for org ${orgId} - subscription status: ${subscription.status}`,
+ );
+ return;
+ }
+
+ const previewInvoice = await backOff(
+ async () =>
+ await stripe.invoices.createPreview({
+ customer:
+ typeof subscription.customer === "string"
+ ? subscription.customer
+ : subscription.customer?.id,
+ subscription: stripeSubscriptionId,
+ }),
+ {
+ numOfAttempts: 3,
+ },
+ );
+
+ // Calculate current spend in USD
+ const currentSpendCents = previewInvoice.total ?? 0;
+ const currentSpendUSD = currentSpendCents / 100;
+
+ logger.info(
+ `[CLOUD SPEND ALERTS] Org ${orgId} current spend: $${currentSpendUSD.toFixed(2)}`,
+ );
+
+ // Get org admins and owners for email notifications (fetch once for all alerts)
+ const adminMemberships = await prisma.organizationMembership.findMany({
+ where: {
+ orgId: orgId,
+ role: { in: [Role.OWNER, Role.ADMIN] },
+ },
+ include: {
+ user: {
+ select: { email: true },
+ },
+ },
+ });
+
+ const adminEmails = adminMemberships
+ .map((m) => m.user?.email)
+ .filter((email): email is string => Boolean(email));
+
+ // Check each spend alert for this org
+ for (const alert of org.spendAlerts) {
+ const thresholdUSD = parseFloat(alert.threshold.toString());
+
+ // Check if threshold is breached
+ if (currentSpendUSD >= thresholdUSD) {
+ // Check if already triggered this billing cycle
+ const alreadyTriggered =
+ alert.triggeredAt && alert.triggeredAt >= currentPeriodStart;
+
+ if (!alreadyTriggered) {
+ logger.info(
+ `[CLOUD SPEND ALERTS] Triggering alert ${alert.id} for org ${orgId} - spend $${currentSpendUSD.toFixed(2)} >= threshold $${thresholdUSD.toFixed(2)}`,
+ );
+
+ const detectedAt = new Date();
+ const detectedAtUtc = detectedAt.toISOString().replace(".000Z", "Z");
+ if (adminEmails.length > 0) {
+ try {
+ // Send email notifications
+ await sendCloudSpendAlertEmail({
+ env,
+ orgId: orgId,
+ orgName: org.name,
+ alertTitle: alert.title,
+ currentSpend: currentSpendUSD,
+ threshold: thresholdUSD,
+ // casting due to cross-package type lag; property is supported in implementation
+ detectedAtUtc,
+ recipients: adminEmails,
+ } as any);
+
+ recordIncrement(
+ "langfuse.queue.cloud_spend_alert_queue.emails_sent",
+ 1,
+ { unit: "emails" },
+ );
+
+ logger.info(
+ `[CLOUD SPEND ALERTS] Sent alert emails to ${adminEmails.length} recipients for org ${orgId}`,
+ );
+ } catch (e) {
+ recordIncrement(
+ "langfuse.queue.cloud_spend_alert_queue.email_failures",
+ 1,
+ { unit: "emails" },
+ );
+ throw e;
+ }
+ }
+
+ // Update triggeredAt timestamp (reuse detection time)
+ await prisma.cloudSpendAlert.update({
+ where: { id: alert.id },
+ data: { triggeredAt: detectedAt },
+ });
+
+ recordIncrement(
+ "langfuse.queue.cloud_spend_alert_queue.triggered_alerts",
+ 1,
+ {
+ unit: "alerts",
+ },
+ );
+ } else {
+ logger.debug(
+ `[CLOUD SPEND ALERTS] Alert ${alert.id} for org ${orgId} already triggered this billing cycle`,
+ );
+ }
+ }
+
+ // Reset triggeredAt if we're in a new billing cycle and threshold is not breached
+ if (
+ currentSpendUSD < thresholdUSD &&
+ alert.triggeredAt &&
+ alert.triggeredAt < currentPeriodStart
+ ) {
+ await prisma.cloudSpendAlert.update({
+ where: { id: alert.id },
+ data: { triggeredAt: null },
+ });
+ logger.debug(
+ `[CLOUD SPEND ALERTS] Reset alert ${alert.id} for org ${orgId} - new billing cycle`,
+ );
+ }
+ }
+
+ recordIncrement(
+ "langfuse.queue.cloud_spend_alert_queue.processed_orgs",
+ 1,
+ {
+ unit: "organizations",
+ },
+ );
+
+ logger.info(`[CLOUD SPEND ALERTS] Completed job for org ${orgId}`);
+ } catch (error) {
+ logger.error(`[CLOUD SPEND ALERTS] Error processing org ${orgId}`, {
+ error,
+ orgId,
+ });
+ traceException(
+ `[CLOUD SPEND ALERTS] Error processing org ${orgId}: ${error}`,
+ );
+ recordIncrement(
+ "langfuse.queue.cloud_spend_alert_queue.skipped_orgs_with_errors",
+ 1,
+ {
+ unit: "organizations",
+ },
+ );
+ throw error; // Let BullMQ handle retry
+ }
+};
diff --git a/worker/src/ee/cloudUsageMetering/handleCloudUsageMeteringJob.ts b/worker/src/ee/cloudUsageMetering/handleCloudUsageMeteringJob.ts
index 1180e93bf8..d7edbac697 100644
--- a/worker/src/ee/cloudUsageMetering/handleCloudUsageMeteringJob.ts
+++ b/worker/src/ee/cloudUsageMetering/handleCloudUsageMeteringJob.ts
@@ -4,6 +4,7 @@ import Stripe from "stripe";
import { env } from "../../env";
import {
CloudUsageMeteringQueue,
+ CloudSpendAlertQueue,
getObservationCountsByProjectInCreationInterval,
getScoreCountsByProjectInCreationInterval,
getTraceCountsByProjectInCreationInterval,
@@ -117,11 +118,17 @@ export const handleCloudUsageMeteringJob = async (job: Job) => {
deletedAt: null,
},
},
+ cloudSpendAlerts: {
+ select: {
+ id: true,
+ },
+ },
},
})
- ).map(({ projects, ...org }) => ({
+ ).map(({ projects, cloudSpendAlerts, ...org }) => ({
...parseDbOrg(org),
projectIds: projects.map((p) => p.id),
+ cloudSpendAlertIds: cloudSpendAlerts.map((a) => a.id),
}));
logger.info(
`[CLOUD USAGE METERING] Job for ${organizations.length} organizations`,
@@ -266,6 +273,28 @@ export const handleCloudUsageMeteringJob = async (job: Job) => {
countProcessedOrgs++;
countProcessedObservations += countObservations;
countProcessedEvents += countEvents;
+
+ // Trigger spend alert job for orgs with activity and spend alerts configured
+ if (org.cloudSpendAlertIds.length > 0) {
+ if (countEvents > 0 || countObservations > 0) {
+ try {
+ await CloudSpendAlertQueue.getInstance()?.add(
+ QueueJobs.CloudSpendAlertJob,
+ { orgId: org.id },
+ { delay: 5 * 60 * 1000 }, // 5 minutes delay
+ );
+ logger.info(
+ `[CLOUD USAGE METERING] Enqueued spend alert job for org ${org.id} with 5min delay`,
+ );
+ } catch (error) {
+ logger.error(
+ `[CLOUD USAGE METERING] Failed to enqueue spend alert job for org ${org.id}`,
+ { error },
+ );
+ // Don't fail the metering job if spend alert enqueueing fails
+ }
+ }
+ }
}
// update cron job
diff --git a/worker/src/env.ts b/worker/src/env.ts
index 96a2e7aac2..6697c32a9a 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -154,6 +154,9 @@ const EnvSchema = z.object({
QUEUE_CONSUMER_CLOUD_USAGE_METERING_QUEUE_IS_ENABLED: z
.enum(["true", "false"])
.default("true"),
+ QUEUE_CONSUMER_CLOUD_SPEND_ALERT_QUEUE_IS_ENABLED: z
+ .enum(["true", "false"])
+ .default("true"),
QUEUE_CONSUMER_FREE_TIER_USAGE_THRESHOLD_QUEUE_IS_ENABLED: z
.enum(["true", "false"])
.default("true"),
diff --git a/worker/src/queues/cloudSpendAlertQueue.ts b/worker/src/queues/cloudSpendAlertQueue.ts
new file mode 100644
index 0000000000..7971144d0f
--- /dev/null
+++ b/worker/src/queues/cloudSpendAlertQueue.ts
@@ -0,0 +1,10 @@
+import { Processor } from "bullmq";
+import { logger, QueueJobs } from "@langfuse/shared/src/server";
+import { handleCloudSpendAlertJob } from "../ee/cloudSpendAlerts/handleCloudSpendAlertJob";
+
+export const cloudSpendAlertQueueProcessor: Processor = async (job) => {
+ if (job.name === QueueJobs.CloudSpendAlertJob) {
+ logger.info("Executing Cloud Spend Alert Job", job.data);
+ return await handleCloudSpendAlertJob(job);
+ }
+};
diff --git a/worker/src/scripts/send-test-spend-alert-emails.ts b/worker/src/scripts/send-test-spend-alert-emails.ts
new file mode 100644
index 0000000000..b8b7185e8e
--- /dev/null
+++ b/worker/src/scripts/send-test-spend-alert-emails.ts
@@ -0,0 +1,112 @@
+// This script sends test spend alert emails for visual testing.
+// Execute with: pnpm tsx src/scripts/send-test-spend-alert-emails.ts
+// WARNING: This sends real emails! Comment out before pushing to production.
+
+/*
+ * Run the script with:
+ *
+ * pnpm dotenv -e ../.env -- tsx src/scripts/send-test-spend-alert-emails.ts
+ *
+ */
+
+import { sendCloudSpendAlertEmail, logger } from "@langfuse/shared/src/server";
+import { env } from "../env";
+
+const TEST_EMAILS: string[] = [
+ // TODO ADD EMAILS HERE – these accounts will receive test emails
+];
+const TEST_ORG_ID = "test-org-id";
+const TEST_ORG_NAME = "Test Organization";
+
+const main = async () => {
+ // Check if TEST_EMAILS is empty
+ if (TEST_EMAILS.length === 0) {
+ console.error("\n❌ Error: TEST_EMAILS list is empty!");
+ console.error(
+ "\nPlease add email addresses to the TEST_EMAILS array in this script before running it.",
+ );
+ console.error(
+ "Edit the file at: worker/src/scripts/send-test-spend-alert-emails.ts\n",
+ );
+ process.exit(1);
+ }
+
+ console.log(
+ `Sending test spend alert emails to ${TEST_EMAILS.length} recipients`,
+ );
+
+ // Test scenario 1: Production Alert - $100 threshold exceeded
+ console.log("\nđź“§ Sending Production Alert emails...");
+ await sendCloudSpendAlertEmail({
+ env: {
+ EMAIL_FROM_ADDRESS: env.EMAIL_FROM_ADDRESS,
+ SMTP_CONNECTION_URL: env.SMTP_CONNECTION_URL,
+ NEXTAUTH_URL: env.NEXTAUTH_URL,
+ },
+ orgId: TEST_ORG_ID,
+ orgName: TEST_ORG_NAME,
+ alertTitle: "Production Alert",
+ currentSpend: 127.45,
+ threshold: 100.0,
+ detectedAtUtc: new Date().toISOString(),
+ recipients: TEST_EMAILS,
+ });
+ console.log(" âś“ Production Alert emails sent");
+
+ // Test scenario 2: Development Alert - $50 threshold exceeded
+ console.log("\nđź“§ Sending Development Alert emails...");
+ await sendCloudSpendAlertEmail({
+ env: {
+ EMAIL_FROM_ADDRESS: env.EMAIL_FROM_ADDRESS,
+ SMTP_CONNECTION_URL: env.SMTP_CONNECTION_URL,
+ NEXTAUTH_URL: env.NEXTAUTH_URL,
+ },
+ orgId: TEST_ORG_ID,
+ orgName: TEST_ORG_NAME,
+ alertTitle: "Development Environment Alert",
+ currentSpend: 67.89,
+ threshold: 50.0,
+ detectedAtUtc: new Date().toISOString(),
+ recipients: TEST_EMAILS,
+ });
+ console.log(" âś“ Development Alert emails sent");
+
+ // Test scenario 3: High-value alert - $1000 threshold exceeded
+ console.log("\nđź“§ Sending High-Value Alert emails...");
+ await sendCloudSpendAlertEmail({
+ env: {
+ EMAIL_FROM_ADDRESS: env.EMAIL_FROM_ADDRESS,
+ SMTP_CONNECTION_URL: env.SMTP_CONNECTION_URL,
+ NEXTAUTH_URL: env.NEXTAUTH_URL,
+ },
+ orgId: TEST_ORG_ID,
+ orgName: TEST_ORG_NAME,
+ alertTitle: "Enterprise Budget Alert",
+ currentSpend: 1234.56,
+ threshold: 1000.0,
+ detectedAtUtc: new Date().toISOString(),
+ recipients: TEST_EMAILS,
+ });
+ console.log(" âś“ High-Value Alert emails sent");
+
+ console.log(
+ `\nâś… All test spend alert emails sent successfully to ${TEST_EMAILS.length} recipients`,
+ );
+ console.log("Recipients:", TEST_EMAILS.join(", "));
+ console.log("\nTest scenarios sent:");
+ console.log(" 1. Production Alert: $127.45 / $100.00 threshold");
+ console.log(" 2. Development Alert: $67.89 / $50.00 threshold");
+ console.log(" 3. Enterprise Budget Alert: $1,234.56 / $1,000.00 threshold");
+};
+
+if (require.main === module) {
+ main()
+ .catch((err) => {
+ logger.error("Error sending test spend alert emails:", err);
+ process.exit(1);
+ })
+ .finally(() => {
+ process.exit(0);
+ });
+}