🪢 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
fix(billing): automatically cancel and invoice stripe subscriptions when an org is deleted (#9228)
Michael Fröhlich540411947390
diff --git a/web/src/ee/features/billing/server/stripeBillingService.ts b/web/src/ee/features/billing/server/stripeBillingService.tsindex eff30da891..18c0884e86 100644--- a/web/src/ee/features/billing/server/stripeBillingService.ts+++ b/web/src/ee/features/billing/server/stripeBillingService.ts@@ -1082,6 +1082,77 @@ class BillingService {};}+ /**+ * Cancel the active subscription immediately and generate a final invoice.+ * - Releases any active/not-started schedules first+ * - Invoices outstanding usage now+ * - No proration is applied+ *+ * Designed for destructive flows (e.g., org deletion). If no active+ * subscription exists, this method is a no-op and returns success.+ */+ async cancelImmediatelyAndInvoice(orgId: string, opId?: string) {+ const client = this.stripe;++ const { parsedOrg } = await this.getParsedOrg(orgId);++ const subscriptionId = parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;+ if (!subscriptionId) {+ logger.info(+ "stripeBillingService.subscription.cancel.now:noop.noActiveSubscription",+ {+ orgId,+ },+ );+ return { status: "noop" as const };+ }++ const subscription = await this.retrieveSubscriptionWithSchedule(+ client,+ subscriptionId,+ );++ // Release any pending schedule before immediate cancel+ await this.releaseExistingSubscriptionScheduleIfAny(subscription, opId);++ const cancelNowKey = makeIdempotencyKey({+ kind: IdempotencyKind.enum["subscription.cancel.now"],+ fields: { subscriptionId },+ opId,+ });++ logger.info("stripeBillingService.subscription.cancel.now", {+ subscriptionId,+ customerId: subscription.customer,+ orgId,+ idempotencyKey: cancelNowKey,+ opId,+ userId: this.ctx.session.user?.id,+ userEmail: this.ctx.session.user?.email,+ });++ await client.subscriptions.cancel(+ subscriptionId,+ {+ invoice_now: true,+ prorate: false,+ } as any,+ { idempotencyKey: cancelNowKey },+ );++ void auditLog({+ session: this.ctx.session,+ orgId: parsedOrg.id,+ resourceType: "organization",+ resourceId: parsedOrg.id,+ action: "BillingService.cancelImmediatelyAndInvoice",+ before: parsedOrg.cloudConfig,+ after: "webhook",+ });++ return { status: "success" as const };+ }+/*** Clear any active or not-started subscription schedule for the org's subscription.*diff --git a/web/src/ee/features/billing/utils/stripeIdempotencyKey.ts b/web/src/ee/features/billing/utils/stripeIdempotencyKey.tsindex c48217669c..3a70a2d878 100644--- a/web/src/ee/features/billing/utils/stripeIdempotencyKey.ts+++ b/web/src/ee/features/billing/utils/stripeIdempotencyKey.ts@@ -26,6 +26,7 @@ export const IdempotencyKind = z.enum(["subscription.schedule.create.fromSub","subscription.schedule.update","subscription.cancelAtPeriodEnd",+ "subscription.cancel.now","subscription.reactivate","subscription.migrate.flexible","subscription.schedule.clear",diff --git a/web/src/features/organizations/server/organizationRouter.ts b/web/src/features/organizations/server/organizationRouter.tsindex 81fb4988e4..883899e2a8 100644--- a/web/src/features/organizations/server/organizationRouter.ts+++ b/web/src/features/organizations/server/organizationRouter.ts@@ -10,6 +10,7 @@ import { throwIfNoOrganizationAccess } from "@/src/features/rbac/utils/checkOrgaimport { TRPCError } from "@trpc/server";import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { redis } from "@langfuse/shared/src/server";+import { createBillingServiceFromContext } from "@/src/ee/features/billing/server/stripeBillingService";export const organizationsRouter = createTRPCRouter({create: authenticatedProcedure@@ -104,6 +105,7 @@ export const organizationsRouter = createTRPCRouter({orgId: input.orgId,},});+if (countProjects > 0) {throw new TRPCError({code: "FORBIDDEN",@@ -112,6 +114,20 @@ export const organizationsRouter = createTRPCRouter({});}+ // Attempt to cancel Stripe subscription immediately (Cloud only) before deleting org+ try {+ const stripeBillingService = createBillingServiceFromContext(ctx);+ await stripeBillingService.cancelImmediatelyAndInvoice(input.orgId);+ } catch (e) {+ // If billing cancellation fails for reasons other than no subscription, abort deletion+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message:+ "Failed to cancel Stripe subscription prior to organization deletion",+ cause: e as Error,+ });+ }+const organization = await ctx.prisma.organization.delete({where: {id: input.orgId,