Skip to content

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

feat(billing): Add option to add discount code to active subscriptions from settings menu (#9235)

Michael Fröhlich700921f69f5e
diff --git a/web/src/ee/features/billing/components/BillingDiscountCodeButton.tsx b/web/src/ee/features/billing/components/BillingDiscountCodeButton.tsx
new file mode 100644
index 0000000000..1fffec5627
--- /dev/null
+++ b/web/src/ee/features/billing/components/BillingDiscountCodeButton.tsx
@@ -0,0 +1,95 @@
+import { useState } from "react";
+import { Button } from "@/src/components/ui/button";
+import {
+ Dialog,
+ DialogBody,
+ DialogClose,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/src/components/ui/dialog";
+import { Input } from "@/src/components/ui/input";
+import { api } from "@/src/utils/api";
+import { toast } from "sonner";
+import { nanoid } from "nanoid";
+
+export const BillingDiscountCodeButton = ({
+ orgId,
+}: {
+ orgId: string | undefined;
+}) => {
+ const [code, setCode] = useState("");
+ const [open, setOpen] = useState(false);
+ const [processing, setProcessing] = useState(false);
+ const [opId, setOpId] = useState<string | null>(null);
+
+ const utils = api.useUtils();
+
+ const mutation = api.cloudBilling.applyPromotionCode.useMutation({
+ onSuccess: async () => {
+ toast.success("Promotion code applied");
+ setProcessing(false);
+ setOpen(false);
+ setCode("");
+ setOpId(null);
+ await Promise.all([
+ utils.cloudBilling.getSubscriptionInfo.invalidate(),
+ utils.cloudBilling.getInvoices.invalidate(),
+ ]);
+ },
+ onError: (err) => {
+ setProcessing(false);
+ toast.error(err.message || "Failed to apply promotion code");
+ },
+ });
+
+ if (!orgId) return null;
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogTrigger asChild>
+ <Button variant="ghost" size="sm">
+ Add Promotion Code
+ </Button>
+ </DialogTrigger>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle className="text-lg">Add Promotion Code</DialogTitle>
+ </DialogHeader>
+ <DialogBody className="space-y-3 text-sm">
+ <p>Enter a valid promotion code to apply it to your subscription.</p>
+ <Input
+ value={code}
+ onChange={(e) => setCode(e.target.value)}
+ placeholder="PROMO2025"
+ disabled={processing}
+ />
+ </DialogBody>
+ <DialogFooter>
+ <DialogClose asChild>
+ <Button variant="secondary" disabled={processing}>
+ Cancel
+ </Button>
+ </DialogClose>
+ <Button
+ variant="default"
+ disabled={processing || !code.trim()}
+ onClick={() => {
+ setProcessing(true);
+ let id = opId;
+ if (!id) {
+ id = nanoid();
+ setOpId(id);
+ }
+ mutation.mutate({ orgId, code: code.trim(), opId: id });
+ }}
+ >
+ {processing ? "Applying…" : "Apply"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/web/src/ee/features/billing/components/BillingDiscountView.tsx b/web/src/ee/features/billing/components/BillingDiscountView.tsx
index 958bd212b9..9acbef308a 100644
--- a/web/src/ee/features/billing/components/BillingDiscountView.tsx
+++ b/web/src/ee/features/billing/components/BillingDiscountView.tsx
@@ -1,6 +1,7 @@
import { api } from "@/src/utils/api";
import { Badge } from "@/src/components/ui/badge";
import { useBillingInformation } from "@/src/ee/features/billing/components/useBillingInformation";
+import { BillingDiscountCodeButton } from "@/src/ee/features/billing/components/BillingDiscountCodeButton";
export const BillingDiscountView = () => {
const { organization } = useBillingInformation();
@@ -14,7 +15,6 @@ export const BillingDiscountView = () => {
);
const discounts = data?.discounts ?? [];
- if (!discounts.length) return null;
const formatAmount = (value: number, currency: string | null) => {
const cur = (currency || "USD").toUpperCase();
@@ -30,29 +30,33 @@ export const BillingDiscountView = () => {
}
};
- if (!shouldRenderComponent) return null;
-
- if (!discounts.length) return null;
+ if (!shouldRenderComponent)
+ return (
+ <div className="flex items-center">
+ <BillingDiscountCodeButton orgId={organization?.id} />
+ </div>
+ );
return (
- <div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
- <span className="mr-1">Active discounts:</span>
- {discounts.map((d) => {
- const labelParts: string[] = [];
- if (d.code) labelParts.push(d.code);
- else if (d.name) labelParts.push(d.name);
-
- if (d.kind === "percent") labelParts.push(`${d.value}% off`);
- else labelParts.push(`${formatAmount(d.value, d.currency)} off`);
-
- return (
- <Badge key={d.id} variant="secondary" className="font-normal">
- {labelParts.join(" · ")}
- </Badge>
- );
- })}
+ <div className="flex flex-col gap-2">
+ <div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
+ <span className="mr-1">Discounts:</span>
+ {discounts.map((d) => {
+ const labelParts: string[] = [];
+ if (d.code) labelParts.push(d.code);
+ else if (d.name) labelParts.push(d.name);
+
+ if (d.kind === "percent") labelParts.push(`${d.value}% off`);
+ else labelParts.push(`${formatAmount(d.value, d.currency)} off`);
+
+ return (
+ <Badge key={d.id} variant="secondary" className="font-normal">
+ {labelParts.join(" · ")}
+ </Badge>
+ );
+ })}
+ <BillingDiscountCodeButton orgId={organization?.id} />
+ </div>
</div>
);
};
-
-export default BillingDiscountView;
diff --git a/web/src/ee/features/billing/server/cloudBillingRouter.ts b/web/src/ee/features/billing/server/cloudBillingRouter.ts
index d86a592d22..ab6a6fb1e0 100644
--- a/web/src/ee/features/billing/server/cloudBillingRouter.ts
+++ b/web/src/ee/features/billing/server/cloudBillingRouter.ts
@@ -277,6 +277,36 @@ export const cloudBillingRouter = createTRPCRouter({
return await stripeBillingService.getUsage(input.orgId);
}),
+ applyPromotionCode: protectedOrganizationProcedure
+ .input(
+ z.object({
+ orgId: z.string(),
+ code: z.string().min(1),
+ opId: z.string().optional(),
+ }),
+ )
+ .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 stripeBillingService = createBillingServiceFromContext(ctx);
+
+ const result = await stripeBillingService.applyPromotionCode(
+ input.orgId,
+ input.code,
+ input.opId,
+ );
+
+ return result;
+ }),
getUsageAlerts: protectedOrganizationProcedure
.input(z.object({ orgId: z.string(), opId: z.string().optional() }))
.query(async ({ input, ctx }) => {
diff --git a/web/src/ee/features/billing/server/stripeBillingService.ts b/web/src/ee/features/billing/server/stripeBillingService.ts
index 7c79721b6b..642422f556 100644
--- a/web/src/ee/features/billing/server/stripeBillingService.ts
+++ b/web/src/ee/features/billing/server/stripeBillingService.ts
@@ -1516,6 +1516,129 @@ class BillingService {
// [B] End ----------------------------------------------------------------------------------------
}
+ /**
+ * Apply a promotion code to the organization's active Stripe subscription.
+ * Preserves existing discounts and adds the new promotion code if valid and not already applied.
+ */
+ async applyPromotionCode(orgId: string, code: string, opId?: string) {
+ const client = this.stripe;
+
+ const { parsedOrg } = await this.getParsedOrg(orgId);
+
+ const subscriptionId = parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;
+ if (!subscriptionId)
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Organization does not have an active subscription",
+ });
+
+ // Validate the promotion code exists and is active
+ const promoList = await client.promotionCodes.list({
+ code,
+ active: true,
+ limit: 1,
+ });
+
+ const promo = promoList.data[0];
+ if (!promo) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Invalid or expired promotion code",
+ });
+ }
+
+ const subscription =
+ await this.retrieveSubscriptionWithScheduleAndDiscounts(
+ client,
+ subscriptionId,
+ );
+
+ // Avoid adding duplicate promotion codes
+ const alreadyApplied = (subscription.discounts || []).some((d) => {
+ if (!isExpandedOrNullable(d)) return false;
+ const pc = d.promotion_code;
+ if (!isExpandedOrNullable(pc) || pc === null) return false;
+ // match by id or code
+ return (
+ (typeof pc === "string" && pc === promo.id) ||
+ (typeof pc !== "string" && (pc.id === promo.id || pc.code === code))
+ );
+ });
+
+ if (alreadyApplied) {
+ return { ok: true as const };
+ }
+
+ // Preserve existing discounts similar to schedule update logic
+ const existingDiscounts = (subscription.discounts || [])
+ .map((discount) => {
+ if (!isExpandedOrNullable(discount)) return undefined;
+
+ const coupon = discount.coupon;
+ const promotionCode = discount.promotion_code;
+
+ if (isExpandedOrNullable(coupon) && coupon) {
+ const couponId = typeof coupon === "string" ? coupon : coupon.id;
+ return {
+ coupon: couponId,
+ } as Stripe.SubscriptionUpdateParams.Discount;
+ }
+
+ if (isExpandedOrNullable(promotionCode) && promotionCode) {
+ const promoId =
+ typeof promotionCode === "string"
+ ? promotionCode
+ : promotionCode.id;
+ return {
+ promotion_code: promoId,
+ } as Stripe.SubscriptionUpdateParams.Discount;
+ }
+
+ return undefined;
+ })
+ .filter(
+ (d): d is Stripe.SubscriptionUpdateParams.Discount => d !== undefined,
+ );
+
+ const idempotencyKey = makeIdempotencyKey({
+ kind: IdempotencyKind.enum["subscription.update.discounts.add"],
+ fields: { subscriptionId, promotionCodeId: promo.id },
+ opId,
+ });
+
+ logger.info("stripeBillingService.subscription.update.discounts.add", {
+ subscriptionId,
+ customerId: subscription.customer,
+ orgId: parsedOrg.id,
+ promotionCodeId: promo.id,
+ idempotencyKey,
+ opId,
+ userId: this.ctx.session.user?.id,
+ userEmail: this.ctx.session.user?.email,
+ });
+
+ await client.subscriptions.update(
+ subscriptionId,
+ {
+ discounts: [...existingDiscounts, { promotion_code: promo.id }],
+ proration_behavior: "none",
+ },
+ { idempotencyKey },
+ );
+
+ void auditLog({
+ session: this.ctx.session,
+ orgId: parsedOrg.id,
+ resourceType: "organization",
+ resourceId: parsedOrg.id,
+ action: "BillingService.applyPromotionCode",
+ before: parsedOrg.cloudConfig,
+ after: "webhook",
+ });
+
+ return { ok: true as const };
+ }
+
// TODO: Currently not working as expected, need to fix
/**
* Create/update/deactivate Stripe usage alerts for an organization.
diff --git a/web/src/ee/features/billing/utils/stripeIdempotencyKey.ts b/web/src/ee/features/billing/utils/stripeIdempotencyKey.ts
index 3a70a2d878..48416c8d8b 100644
--- a/web/src/ee/features/billing/utils/stripeIdempotencyKey.ts
+++ b/web/src/ee/features/billing/utils/stripeIdempotencyKey.ts
@@ -30,6 +30,7 @@ export const IdempotencyKind = z.enum([
"subscription.reactivate",
"subscription.migrate.flexible",
"subscription.schedule.clear",
+ "subscription.update.discounts.add",
]);
export type IdempotencyKind = z.infer<typeof IdempotencyKind>;