🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(billing): auto-create default spend alerts on new subscriptions (#12694)
Steffen Schmitzc13712779966
diff --git a/web/src/__tests__/server/createDefaultSpendAlerts.servertest.ts b/web/src/__tests__/server/createDefaultSpendAlerts.servertest.tsnew file mode 100644index 0000000000..90d3d89ab9--- /dev/null+++ b/web/src/__tests__/server/createDefaultSpendAlerts.servertest.ts@@ -0,0 +1,111 @@+/** @jest-environment node */+import { prisma } from "@langfuse/shared/src/db";+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";+import { createDefaultSpendAlerts } from "@/src/ee/features/billing/server/stripeWebhookHandler";+import { stripeProducts } from "@/src/ee/features/billing/utils/stripeCatalogue";++describe("createDefaultSpendAlerts", () => {+ it("creates alerts with correct thresholds for core plan", async () => {+ const { orgId } = await createOrgProjectAndApiKey();+ const coreProduct = stripeProducts.find(+ (p) => p.mappedPlan === "cloud:core",+ )!;++ await createDefaultSpendAlerts({+ orgId,+ productId: coreProduct.stripeProductId,+ });++ const alerts = await prisma.cloudSpendAlert.findMany({+ where: { orgId },+ });++ expect(alerts).toHaveLength(1);+ expect(alerts[0].threshold.toNumber()).toBe(200);+ expect(alerts[0].title).toBe("Default Spend alert ($200)");+ });++ it("creates alerts with correct thresholds for pro plan", async () => {+ const { orgId } = await createOrgProjectAndApiKey();+ const proProduct = stripeProducts.find(+ (p) => p.mappedPlan === "cloud:pro",+ )!;++ await createDefaultSpendAlerts({+ orgId,+ productId: proProduct.stripeProductId,+ });++ const alerts = await prisma.cloudSpendAlert.findMany({+ where: { orgId },+ });++ expect(alerts).toHaveLength(1);+ expect(alerts[0].threshold.toNumber()).toBe(1000);+ });++ it("creates alerts with correct thresholds for enterprise plan", async () => {+ const { orgId } = await createOrgProjectAndApiKey();+ const enterpriseProduct = stripeProducts.find(+ (p) => p.mappedPlan === "cloud:enterprise",+ )!;++ await createDefaultSpendAlerts({+ orgId,+ productId: enterpriseProduct.stripeProductId,+ });++ const alerts = await prisma.cloudSpendAlert.findMany({+ where: { orgId },+ });++ expect(alerts).toHaveLength(1);+ expect(alerts[0].threshold.toNumber()).toBe(2000);+ });++ it("skips creation if org already has alerts", async () => {+ const { orgId } = await createOrgProjectAndApiKey();++ // Create an existing alert+ await prisma.cloudSpendAlert.create({+ data: {+ orgId,+ title: "Existing alert",+ threshold: 500,+ },+ });++ const coreProduct = stripeProducts.find(+ (p) => p.mappedPlan === "cloud:core",+ )!;++ await createDefaultSpendAlerts({+ orgId,+ productId: coreProduct.stripeProductId,+ });++ const alerts = await prisma.cloudSpendAlert.findMany({+ where: { orgId },+ });++ // Should still have only the original alert+ expect(alerts).toHaveLength(1);+ expect(alerts[0].title).toBe("Existing alert");+ });++ it("handles unknown product IDs gracefully", async () => {+ const { orgId } = await createOrgProjectAndApiKey();++ // Should not throw+ await createDefaultSpendAlerts({+ orgId,+ productId: "prod_unknown_id",+ });++ const alerts = await prisma.cloudSpendAlert.findMany({+ where: { orgId },+ });++ expect(alerts).toHaveLength(0);+ });+});diff --git a/web/src/ee/features/billing/server/stripeWebhookHandler.ts b/web/src/ee/features/billing/server/stripeWebhookHandler.tsindex 6524cc8b71..0773314f41 100644--- a/web/src/ee/features/billing/server/stripeWebhookHandler.ts+++ b/web/src/ee/features/billing/server/stripeWebhookHandler.ts@@ -11,6 +11,7 @@ import {CloudConfigSchema,InternalServerError,type Organization,+ type Plan,parseDbOrg,} from "@langfuse/shared";import {@@ -21,6 +22,7 @@ import {} from "@langfuse/shared/src/server";import { auditLog } from "@/src/features/audit-logs/auditLog";import { type StripeSubscriptionMetadata } from "@/src/ee/features/billing/utils/stripeSubscriptionMetadata";+import { mapStripeProductIdToPlan } from "@/src/ee/features/billing/utils/stripeCatalogue";/*** Stripe webhook handler for managing subscription events, billing alerts, and invoice notifications.@@ -373,6 +375,85 @@ export async function updateOrgBillingCycleAnchor(});}+type PlanWithoutSpendAlerts =+ | "oss"+ | "cloud:hobby"+ | "self-hosted:pro"+ | "self-hosted:enterprise";++const DEFAULT_SPEND_ALERT_THRESHOLDS: Record<+ Exclude<Plan, PlanWithoutSpendAlerts>,+ number+> = {+ "cloud:core": 200,+ "cloud:pro": 1000,+ "cloud:team": 1000,+ "cloud:enterprise": 2000,+};++export async function createDefaultSpendAlerts({+ orgId,+ productId,+}: {+ orgId: string;+ productId: string;+}) {+ const plan = mapStripeProductIdToPlan(productId) as Exclude<+ Plan,+ PlanWithoutSpendAlerts+ >;+ if (!plan) {+ logger.error(+ `[Stripe Webhook] createDefaultSpendAlerts: Unknown product ID ${productId}, skipping`,+ );+ return;+ }++ const threshold = DEFAULT_SPEND_ALERT_THRESHOLDS[plan];+ if (!threshold) {+ logger.error(+ `[Stripe Webhook] createDefaultSpendAlerts: No spend alerts configured for plan ${plan}, skipping`,+ );+ return;+ }++ // Skip if org already has spend alerts (idempotency / don't overwrite user-configured alerts)+ const existingAlerts = await prisma.cloudSpendAlert.findFirst({+ where: { orgId },+ select: { id: true },+ });+ if (existingAlerts) {+ logger.info(+ `[Stripe Webhook] createDefaultSpendAlerts: Org ${orgId} already has spend alerts, skipping`,+ );+ return;+ }++ const alert = await prisma.cloudSpendAlert.create({+ data: {+ orgId,+ title: `Default Spend alert ($${threshold})`,+ threshold,+ },+ });++ await auditLog({+ session: {+ user: { id: "stripe-webhook" },+ orgId,+ },+ orgId,+ resourceType: "cloudSpendAlert",+ resourceId: alert.id,+ action: "create",+ after: alert,+ });++ logger.info(+ `[Stripe Webhook] createDefaultSpendAlerts: Created default alert over $${threshold} for org ${orgId} on plan ${plan}`,+ );+}+async function handleSubscriptionChanged(subscription: Stripe.Subscription,action: "created" | "deleted" | "updated",@@ -557,6 +638,22 @@ async function handleSubscriptionChanged(await updateOrgBillingCycleAnchor(parsedOrg.id, anchorDate);}+ // Auto-create default spend alerts for new subscriptions (best-effort)+ if (action === "created") {+ try {+ await createDefaultSpendAlerts({+ orgId: parsedOrg.id,+ productId: productId,+ });+ } catch (err) {+ logger.error(+ "[Stripe Webhook] Failed to create default spend alerts",+ err,+ );+ traceException(err);+ }+ }+// Invalidate API keys in Redis for it to be updatedawait invalidateCachedOrgApiKeys(parsedOrg.id);