🪢 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): show active promotion codes in billing settings #9210 (#9221)
Michael Fröhlich16f41f809ab9
diff --git a/web/src/ee/features/billing/components/BillingDiscountView.tsx b/web/src/ee/features/billing/components/BillingDiscountView.tsxnew file mode 100644index 0000000000..474db658c2--- /dev/null+++ b/web/src/ee/features/billing/components/BillingDiscountView.tsx@@ -0,0 +1,54 @@+import { useRouter } from "next/router";+import { api } from "@/src/utils/api";+import { Badge } from "@/src/components/ui/badge";++export const BillingDiscountView = () => {+ const router = useRouter();+ const orgId = router.query.organizationId as string | undefined;++ const { data } = api.cloudBilling.getSubscriptionInfo.useQuery(+ { orgId: orgId ?? "" },+ { enabled: Boolean(orgId) },+ );++ const discounts = data?.discounts ?? [];+ if (!discounts.length) return null;++ const formatAmount = (value: number, currency: string | null) => {+ const cur = (currency || "USD").toUpperCase();+ try {+ return new Intl.NumberFormat(undefined, {+ style: "currency",+ currency: cur,+ currencyDisplay: "narrowSymbol",+ }).format(value / 100);+ } catch {+ // Fallback simple formatting+ return `${(value / 100).toFixed(2)} ${cur}`;+ }+ };++ if (!discounts.length) return null;++ 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>+ );+};++export default BillingDiscountView;diff --git a/web/src/ee/features/billing/components/BillingPlanPeriodView.tsx b/web/src/ee/features/billing/components/BillingPlanPeriodView.tsxnew file mode 100644index 0000000000..35ff744e2f--- /dev/null+++ b/web/src/ee/features/billing/components/BillingPlanPeriodView.tsx@@ -0,0 +1,30 @@+import { useRouter } from "next/router";+import { api } from "@/src/utils/api";+import { formatLocalIsoDate } from "@/src/components/LocalIsoDate";+import { BillingCurrentPlanLabel } from "./BillingCurrentPlanLabel";++export const BillingPlanPeriodView = () => {+ const router = useRouter();+ const orgId = router.query.organizationId as string | undefined;++ const { data, isLoading } = api.cloudBilling.getSubscriptionInfo.useQuery(+ { orgId: orgId ?? "" },+ { enabled: Boolean(orgId) },+ );++ return (+ <div className="flex flex-col gap-1 text-sm text-muted-foreground">+ <BillingCurrentPlanLabel />+ <p>+ Billing period:{" "}+ {!isLoading && data?.billingPeriod && (+ <>+ {`${formatLocalIsoDate(data.billingPeriod.start, false, "day")} - ${formatLocalIsoDate(data.billingPeriod.end, false, "day")}`}+ </>+ )}+ </p>+ </div>+ );+};++export default BillingPlanPeriodView;diff --git a/web/src/ee/features/billing/components/BillingSettings.tsx b/web/src/ee/features/billing/components/BillingSettings.tsxindex 07019e17ec..651a784df4 100644--- a/web/src/ee/features/billing/components/BillingSettings.tsx+++ b/web/src/ee/features/billing/components/BillingSettings.tsx@@ -12,6 +12,7 @@ import { BillingActionButtons } from "./BillingActionButtons";import { BillingScheduleNotification } from "./BillingScheduleNotification";import { BillingInvoiceTable } from "./BillingInvoiceTable";import { useBillingInformation } from "./useBillingInformation";+import { BillingDiscountView } from "./BillingDiscountView";export const BillingSettings = () => {const router = useRouter();@@ -44,6 +45,7 @@ export const BillingSettings = () => {<Header title="Usage & Billing" /><div className="space-y-6"><BillingUsageChart />+ {orgId && billingInfo.hasActiveSubscription && <BillingDiscountView />}<BillingActionButtons />{isUsageAlertEntitled && orgId && <UsageAlerts orgId={orgId} />}{orgId && billingInfo.hasActiveSubscription && (diff --git a/web/src/ee/features/billing/components/BillingUsageChart.tsx b/web/src/ee/features/billing/components/BillingUsageChart.tsxindex e7446d40bd..ae3e89d6ef 100644--- a/web/src/ee/features/billing/components/BillingUsageChart.tsx+++ b/web/src/ee/features/billing/components/BillingUsageChart.tsx@@ -7,8 +7,7 @@ import { Card } from "@/src/components/ui/card";import { numberFormatter, compactNumberFormatter } from "@/src/utils/numbers";import { type Plan } from "@langfuse/shared";import { MAX_EVENTS_FREE_PLAN } from "@/src/ee/features/billing/constants";-import { formatLocalIsoDate } from "@/src/components/LocalIsoDate";-import { BillingCurrentPlanLabel } from "./BillingCurrentPlanLabel";+import { BillingPlanPeriodView } from "@/src/ee/features/billing/components/BillingPlanPeriodView";export const BillingUsageChart = () => {const organization = useQueryOrganization();@@ -72,13 +71,8 @@ export const BillingUsageChart = () => {</span>)}</Card>- <div className="mt-2 flex flex-col gap-1 text-sm text-muted-foreground">- <BillingCurrentPlanLabel />- {usage.data?.billingPeriod && (- <p>- {`Billing period: ${formatLocalIsoDate(usage.data.billingPeriod.start, false, "day")} - ${formatLocalIsoDate(usage.data.billingPeriod.end, false, "day")}`}- </p>- )}+ <div className="mt-2">+ <BillingPlanPeriodView /></div></div>);diff --git a/web/src/ee/features/billing/server/stripeBillingService.ts b/web/src/ee/features/billing/server/stripeBillingService.tsindex b14892f1ba..eff30da891 100644--- a/web/src/ee/features/billing/server/stripeBillingService.ts+++ b/web/src/ee/features/billing/server/stripeBillingService.ts@@ -46,6 +46,20 @@ export type BillingSubscriptionInfo = {newProductId?: string;message?: string | null;} | null;+ billingPeriod?: {+ start: Date;+ end: Date;+ } | null;+ discounts?: Array<{+ id: string;+ code: string | null;+ name: string | null;+ kind: "percent" | "amount";+ value: number; // percent value or amount in currency minor units (e.g. cents)+ currency: string | null;+ duration: "forever" | "once" | "repeating" | null;+ durationInMonths: number | null;+ }>;};class BillingService {@@ -92,12 +106,18 @@ class BillingService {return { org, parsedOrg: parseDbOrg(org) };}- private async retrieveSubscriptionWithSchedule(+ private async retrieveSubscriptionWithScheduleAndDiscounts(client: Stripe,subscriptionId: string,): Promise<SubscriptionWithSchedule> {const subscription = await client.subscriptions.retrieve(subscriptionId, {- expand: ["schedule"],+ expand: [+ "schedule",+ // Expand discounts for promotion code display+ "discounts",+ "discounts.coupon",+ "discounts.promotion_code",+ ],});const schedule = subscription.schedule;@@ -109,6 +129,8 @@ class BillingService {});}+ // Note: Discounts - We cannot easily type arrays here, so we leave it to the calling component to type it+return { ...subscription, schedule: schedule };}@@ -242,13 +264,14 @@ class BillingService {if (!subscriptionId) {// No active subscription → nothing scheduled- return { cancellation: null, scheduledChange: null };+ return { cancellation: null, scheduledChange: null, billingPeriod: null };}- const subscription = await this.retrieveSubscriptionWithSchedule(- client,- subscriptionId,- );+ const subscription =+ await this.retrieveSubscriptionWithScheduleAndDiscounts(+ client,+ subscriptionId,+ );// Cancellation info (supports classic and flexible billing)const nowSec = Math.floor(Date.now() / 1000);@@ -271,6 +294,18 @@ class BillingService {}}+ // Current billing period (based on first subscription item)+ const firstItem = subscription.items?.data?.[0];+ const billingPeriod =+ firstItem &&+ typeof firstItem.current_period_start === "number" &&+ typeof firstItem.current_period_end === "number"+ ? {+ start: new Date(firstItem.current_period_start * 1000),+ end: new Date(firstItem.current_period_end * 1000),+ }+ : null;+// Next scheduled change from subscription schedule phaseslet scheduledChange: {scheduleId: string;@@ -350,7 +385,45 @@ class BillingService {}}- return { cancellation, scheduledChange };+ // Active discounts / promotion codes+ const discounts = subscription.discounts+ .map((discount) => {+ if (!isExpandedOrNullable(discount)) {+ return null;+ }++ const coupon = discount.coupon;+ const promotion_code = discount.promotion_code;++ if (!isExpandedOrNullable(coupon)) {+ return null;+ }++ if (!isExpandedOrNullable(promotion_code)) {+ return null;+ }++ const amountOff = coupon?.amount_off;+ const percentOff = coupon?.percent_off;+ const kind: "percent" | "amount" =+ percentOff !== null ? "percent" : "amount";++ const value = kind === "percent" ? (percentOff ?? 0) : (amountOff ?? 0);++ return {+ id: discount.id,+ code: promotion_code?.code ?? null,+ name: coupon?.name,+ kind,+ value,+ currency: coupon?.currency,+ duration: coupon?.duration,+ durationInMonths: coupon?.duration_in_months,+ };+ })+ .filter((d) => d !== null);++ return { cancellation, scheduledChange, billingPeriod, discounts };}/**@@ -539,10 +612,11 @@ class BillingService {message: "Organization does not have an active subscription",});- const subscription = await this.retrieveSubscriptionWithSchedule(- client,- stripeSubscriptionId,- );+ const subscription =+ await this.retrieveSubscriptionWithScheduleAndDiscounts(+ client,+ stripeSubscriptionId,+ );if (["canceled", "paused", "incomplete", "incomplete_expired"].includes(@@ -897,10 +971,11 @@ class BillingService {message: "No active subscription to cancel",});- const subscription = await this.retrieveSubscriptionWithSchedule(- client,- subscriptionId,- );+ const subscription =+ await this.retrieveSubscriptionWithScheduleAndDiscounts(+ client,+ subscriptionId,+ );// If the user cancels the subscription, we want to release the existing scheduleawait this.releaseExistingSubscriptionScheduleIfAny(subscription, opId);@@ -958,10 +1033,11 @@ class BillingService {message: "No active subscription to reactivate",});- const subscription = await this.retrieveSubscriptionWithSchedule(- client,- subscriptionId,- );+ const subscription =+ await this.retrieveSubscriptionWithScheduleAndDiscounts(+ client,+ subscriptionId,+ );// If the user reactivates the subscription, we want to remove the cancellationconst cancellationPayload = subscription.cancel_at@@ -1023,10 +1099,11 @@ class BillingService {message: "No active subscription found",});- const subscription = await this.retrieveSubscriptionWithSchedule(- client,- subscriptionId,- );+ const subscription =+ await this.retrieveSubscriptionWithScheduleAndDiscounts(+ client,+ subscriptionId,+ );await this.releaseExistingSubscriptionScheduleIfAny(subscription, opId);@@ -1250,10 +1327,11 @@ class BillingService {// ------------------------------------------------------------------------------------------------if (stripeCustomerId && stripeSubscriptionId) {try {- const subscription = await this.retrieveSubscriptionWithSchedule(- client,- stripeSubscriptionId,- );+ const subscription =+ await this.retrieveSubscriptionWithScheduleAndDiscounts(+ client,+ stripeSubscriptionId,+ );const usageItem = subscription.items.data.find((item) =>this.isMetered(item.price),