🪢 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(cloud): switch between available plans (#5153)
Marc Klingen6c84c54a4af7
diff --git a/web/src/ee/features/billing/components/BillingSettings.tsx b/web/src/ee/features/billing/components/BillingSettings.tsxindex f5013d72c8..c3656321c7 100644--- a/web/src/ee/features/billing/components/BillingSettings.tsx+++ b/web/src/ee/features/billing/components/BillingSettings.tsx@@ -21,12 +21,18 @@ import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";import { MAX_EVENTS_FREE_PLAN } from "@/src/ee/features/billing/constants";import {Dialog,+ DialogClose,DialogContent,+ DialogFooter,+ DialogDescription,DialogHeader,+ DialogTitle,DialogTrigger,} from "@/src/components/ui/dialog";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { stripeProducts } from "@/src/ee/features/billing/utils/stripeProducts";+import { toast } from "sonner";+import { ActionButton } from "@/src/components/ActionButton";export const BillingSettings = () => {const router = useRouter();@@ -163,18 +169,19 @@ const BillingPortalOrPricingPageButton = () => {router.push(url);},});-- if (!organization) return null;- if (billingPortalUrl.isLoading) return null;- if (billingPortalUrl.data)- return (- <Button asChild>- <Link href={billingPortalUrl.data}>Billing portal</Link>- </Button>- );+ const mutChangePlan =+ api.cloudBilling.changeStripeSubscriptionProduct.useMutation({+ onSuccess: () => {+ toast.success("Plan changed successfully");+ // wait 1 second before reloading+ setTimeout(() => {+ window.location.reload();+ }, 500);+ },+ });// Do not show checkout or customer portal if manual plan is set in cloud config- if (organization.cloudConfig?.plan) {+ if (organization?.cloudConfig?.plan) {if (chatAvailable)return (<Button@@ -191,8 +198,7 @@ const BillingPortalOrPricingPageButton = () => {else return null;}- // Show pricing page button- return (+ const switchPlan = (<DialogonOpenChange={(open) => {if (open) {@@ -230,22 +236,89 @@ const BillingPortalOrPricingPageButton = () => {</div><div>{product.checkout?.description}</div><div className="mb-6 mt-2">{product.checkout?.price}</div>- <Button- onClick={() => {- if (organization)- mutCreateCheckoutSession.mutate({- orgId: organization.id,- stripeProductId: product.stripeProductId,- });- }}- className="mt-auto"- >- Select plan- </Button>+ {organization?.cloudConfig?.stripe?.activeProductId ? (+ // Change plan+ <Dialog>+ <DialogTrigger asChild>+ <Button+ disabled={+ organization?.cloudConfig?.stripe?.activeProductId ===+ product.stripeProductId+ }+ className="mt-auto"+ >+ {organization?.cloudConfig?.stripe?.activeProductId ===+ product.stripeProductId+ ? "Current plan"+ : "Change plan"}+ </Button>+ </DialogTrigger>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Confirm Plan Change</DialogTitle>+ <DialogDescription>+ Changing your plan will immediately generate an+ invoice for any usage on your current plan. Your new+ plan and billing period will start today. Are you sure+ you want to continue?+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <DialogClose asChild>+ <Button variant="secondary">Cancel</Button>+ </DialogClose>+ <ActionButton+ onClick={() => {+ if (organization) {+ mutChangePlan.mutate({+ orgId: organization.id,+ stripeProductId: product.stripeProductId,+ });+ }+ }}+ loading={mutChangePlan.isLoading}+ >+ Confirm+ </ActionButton>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ ) : (+ // Upgrade, no plan yet+ <ActionButton+ onClick={() => {+ if (organization)+ mutCreateCheckoutSession.mutate({+ orgId: organization.id,+ stripeProductId: product.stripeProductId,+ });+ }}+ disabled={+ organization?.cloudConfig?.stripe?.activeProductId ===+ product.stripeProductId+ }+ className="mt-auto"+ loading={mutCreateCheckoutSession.isLoading}+ >+ Select plan+ </ActionButton>+ )}</div>))}</div></DialogContent></Dialog>);++ // Show pricing page button+ return (+ <>+ {switchPlan}+ {billingPortalUrl.data && (+ <Button asChild>+ <Link href={billingPortalUrl.data}>Billing portal</Link>+ </Button>+ )}+ </>+ );};diff --git a/web/src/ee/features/billing/server/cloudBillingRouter.ts b/web/src/ee/features/billing/server/cloudBillingRouter.tsindex 1242388dcd..88c0910153 100644--- a/web/src/ee/features/billing/server/cloudBillingRouter.ts+++ b/web/src/ee/features/billing/server/cloudBillingRouter.ts@@ -147,6 +147,130 @@ export const cloudBillingRouter = createTRPCRouter({return session.url;}),+ changeStripeSubscriptionProduct: protectedOrganizationProcedure+ .input(+ z.object({+ orgId: z.string(),+ stripeProductId: z.string(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ throwIfNoOrganizationAccess({+ organizationId: input.orgId,+ scope: "langfuseCloudBilling:CRUD",+ session: ctx.session,+ });+ throwIfNoEntitlement({+ entitlement: "cloud-billing",+ sessionUser: ctx.session.user,+ orgId: input.orgId,+ });++ // check that product is valid+ if (+ !stripeProducts+ .filter((i) => Boolean(i.checkout))+ .map((i) => i.stripeProductId)+ .includes(input.stripeProductId)+ )+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Invalid stripe product id, product not available",+ });++ const org = await ctx.prisma.organization.findUnique({+ where: {+ id: input.orgId,+ },+ });+ if (!org) {+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Organization not found",+ });+ }++ const parsedOrg = parseDbOrg(org);+ if (parsedOrg.cloudConfig?.plan)+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Cannot change plan for orgs that have a manual/legacy plan",+ });++ const stripeSubscriptionId =+ parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;++ if (!stripeSubscriptionId)+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Organization does not have an active subscription",+ });++ if (!stripeClient)+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Stripe client not initialized",+ });++ const subscription =+ await stripeClient.subscriptions.retrieve(stripeSubscriptionId);++ if (+ ["canceled", "paused", "incomplete", "incomplete_expired"].includes(+ subscription.status,+ )+ )+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message:+ "Subscription is not active, current status: " ++ subscription.status,+ });++ if (subscription.items.data.length !== 1)+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Subscription has multiple items",+ });++ const item = subscription.items.data[0];++ if (+ !stripeProducts+ .map((i) => i.stripeProductId)+ .includes(item.price.product as string)+ )+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Current subscription product is not a valid product",+ });++ const newProduct = await stripeClient.products.retrieve(+ input.stripeProductId,+ );+ if (!newProduct.default_price)+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "New product does not have a default price in Stripe",+ });++ await stripeClient.subscriptions.update(stripeSubscriptionId, {+ items: [+ // remove current product from subscription+ {+ id: item.id,+ deleted: true,+ },+ // add new product to subscription+ {+ price: newProduct.default_price as string,+ },+ ],+ // reset billing cycle which causes immediate invoice for existing plan+ billing_cycle_anchor: "now",+ proration_behavior: "none",+ });+ }),getStripeCustomerPortalUrl: protectedOrganizationProcedure.input(z.object({diff --git a/web/src/ee/features/evals/components/evaluator-form.tsx b/web/src/ee/features/evals/components/evaluator-form.tsxindex bd7f5dd24f..1e3fd85ce9 100644--- a/web/src/ee/features/evals/components/evaluator-form.tsx+++ b/web/src/ee/features/evals/components/evaluator-form.tsx@@ -69,7 +69,7 @@ import { showSuccessToast } from "@/src/features/notifications/showSuccessToast"const formSchema = z.object({scoreName: z.string(),target: z.string(),- filter: z.array(singleFilter).nullable(), // re-using the filter type from the tables+ filter: z.array(singleFilter).nullable(), // reusing the filter type from the tablesmapping: z.array(wipVariableMapping),sampling: z.coerce.number().gt(0).lte(1),delay: z.coerce.number().optional().default(10),diff --git a/web/src/ee/features/evals/server/router.ts b/web/src/ee/features/evals/server/router.tsindex 0d561b90de..aeaea73b97 100644--- a/web/src/ee/features/evals/server/router.ts+++ b/web/src/ee/features/evals/server/router.ts@@ -37,7 +37,7 @@ const APIEvaluatorSchema = z.object({evalTemplateId: z.string(),scoreName: z.string(),targetObject: z.string(),- filter: z.array(singleFilter).nullable(), // re-using the filter type from the tables+ filter: z.array(singleFilter).nullable(), // reusing the filter type from the tablesvariableMapping: z.array(variableMapping),sampling: z.instanceof(Prisma.Decimal),delay: z.number(),@@ -93,7 +93,7 @@ const CreateEvalJobSchema = z.object({evalTemplateId: z.string(),scoreName: z.string().min(1),target: z.string(),- filter: z.array(singleFilter).nullable(), // re-using the filter type from the tables+ filter: z.array(singleFilter).nullable(), // reusing the filter type from the tablesmapping: z.array(variableMapping),sampling: z.number().gt(0).lte(1),delay: z.number().gte(0).default(DEFAULT_TRACE_JOB_DELAY), // 10 seconds default