Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: added support for self serve upgrade
=fe6606b9db20
diff --git a/backend/src/ee/routes/v1/license-v2-router.ts b/backend/src/ee/routes/v1/license-v2-router.tsindex 7a22037e9a..642dc14cd0 100644--- a/backend/src/ee/routes/v1/license-v2-router.ts+++ b/backend/src/ee/routes/v1/license-v2-router.ts@@ -49,6 +49,8 @@ const BillingV2PlanSchema = z.object({selfServe: z.boolean(),salesLed: z.boolean(),trialable: z.boolean(),+ upgradeable: z.boolean(),+ trialDays: z.number(),deprecated: z.boolean().optional(),deprecation: BillingV2DeprecationSchema.optional(),displayOrder: z.number().optional(),@@ -117,6 +119,10 @@ const BillingV2EntitlementSchema = z.object({status: z.string().optional(),isTrialing: z.boolean().optional(),trialEndsAt: z.string().nullable().optional(),+ trialPlan: z.string().optional(),+ trialPlanName: z.string().optional(),+ trialPlanEndsAt: z.string().nullable().optional(),+ trialPlanDaysLeft: z.number().nullable().optional(),renewsOn: z.string().nullable().optional(),deprecation: BillingV2DeprecationSchema.extend({kind: z.enum(["product", "plan"])@@ -126,6 +132,16 @@ const BillingV2EntitlementSchema = z.object({unit: z.string().nullable().optional()});+const BillingV2TrialSchema = z.object({+ productKey: z.string(),+ planTier: z.string().nullable(),+ basePlanTier: z.string().nullable(),+ outcome: z.string(),+ endedDetail: z.string().nullable(),+ endedAt: z.string().nullable(),+ endedDaysAgo: z.number().nullable()+});+const BillingV2OverviewSchema = z.object({isCloud: z.boolean(),mode: z.enum(["self-serve", "managed"]),@@ -166,7 +182,7 @@ const BillingV2OverviewSchema = z.object({.nullable(),invoices: BillingV2InvoiceSchema.array(),entitlements: z.record(BillingV2EntitlementSchema),- trialedProductKeys: z.string().array(),+ trials: BillingV2TrialSchema.array(),onDemandAmount: z.number(),checkoutFrozen: z.boolean(),selfServe: z.boolean()@@ -186,6 +202,7 @@ const BillingV2PreviewSchema = z.object({nextInvoiceTotal: z.number(),nextRecurringTotal: z.number(),prorationDate: z.number().nullish(),+ toPlanVersionId: z.string().nullish(),lines: BillingV2PreviewLineSchema.array()});@@ -193,6 +210,9 @@ const BillingV2PreviewSchema = z.object({// subscription id comes back (the DB mirror catches up via webhook, so the UI refetches overview).const BillingV2MutationResultSchema = z.object({ subscriptionId: z.string().optional() });+// Product and plan keys are short catalog identifiers (e.g. "secrets_management", "advanced").+const BillingV2KeySchema = z.string().trim().min(1).max(64);+const BillingV2QuantitiesSchema = z.record(z.string().trim(), z.number().int().min(0));const BillingV2CommitmentChangeSchema = z.object({dimensionKey: z.string().trim(),@@ -333,10 +353,20 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {cadence: z.enum(["monthly", "annual"]).optional(),quantities: BillingV2QuantitiesSchema.optional(),removeProductId: z.string().trim().optional(),- commitmentChanges: BillingV2CommitmentChangeSchema.array().optional()+ commitmentChanges: BillingV2CommitmentChangeSchema.array().optional(),+ upgradeProductId: BillingV2KeySchema.optional(),+ upgradePlan: BillingV2KeySchema.optional()})- .refine((b) => Boolean(b.addProductId) || Boolean(b.removeProductId) || Boolean(b.commitmentChanges?.length), {- message: "provide a product to add or remove, or a commitment change"+ .refine(+ (b) =>+ Boolean(b.addProductId) ||+ Boolean(b.removeProductId) ||+ Boolean(b.upgradeProductId) ||+ Boolean(b.commitmentChanges?.length),+ { message: "provide a product to add, remove or upgrade, or a commitment change" }+ )+ .refine((b) => !b.upgradeProductId || Boolean(b.upgradePlan), {+ message: "upgradePlan is required when upgradeProductId is set"}),response: {200: z.object({ preview: BillingV2PreviewSchema })@@ -352,7 +382,9 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {cadence: req.body.cadence,quantities: req.body.quantities,removeProductId: req.body.removeProductId,- commitmentChanges: req.body.commitmentChanges+ commitmentChanges: req.body.commitmentChanges,+ upgradeProductId: req.body.upgradeProductId,+ upgradePlan: req.body.upgradePlan});}});@@ -398,6 +430,42 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {}});+ server.route({+ method: "POST",+ url: "/:organizationId/billing/v2/subscription/upgrade",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ params: z.object({ organizationId: z.string().trim() }),+ body: z.object({+ productId: BillingV2KeySchema,+ plan: BillingV2KeySchema,+ expectedPlanVersionId: z.string().trim().uuid(),+ prorationDate: z.number().int().positive().optional()+ }),+ response: {+ 200: z.object({+ outcome: z.literal("upgraded"),+ subscriptionId: z.string().optional(),+ fromPlanKey: z.string().optional(),+ toPlanKey: z.string().optional()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ return server.services.licenseV2.upgradeProduct({+ orgId: req.params.organizationId,+ actor: buildActor(req.permission),+ productId: req.body.productId,+ plan: req.body.plan,+ expectedPlanVersionId: req.body.expectedPlanVersionId,+ prorationDate: req.body.prorationDate+ });+ }+ });+server.route({method: "DELETE",url: "/:organizationId/billing/v2/subscription/products/:productId",diff --git a/backend/src/ee/services/license-v2/license-v2-service.ts b/backend/src/ee/services/license-v2/license-v2-service.tsindex 0e455c3121..5c0855880d 100644--- a/backend/src/ee/services/license-v2/license-v2-service.ts+++ b/backend/src/ee/services/license-v2/license-v2-service.ts@@ -28,6 +28,7 @@ import {BillingV2Plan,BillingV2Preview,BillingV2SubState,+ BillingV2Trial,TAddBillingV2PaymentMethodDTO,TBillingV2SubscriptionLifecycleDTO,TBuyBillingV2ProductDTO,@@ -38,7 +39,8 @@ import {TGetBillingV2OverviewDTO,TPreviewBillingV2ChangeDTO,TRemoveBillingV2ProductDTO,- TStartBillingV2TrialDTO+ TStartBillingV2TrialDTO,+ TUpgradeBillingV2ProductDTO} from "./license-v2-types";type TLicenseV2ServiceFactoryDep = {@@ -62,6 +64,7 @@ type TLicenseV2ServiceFactoryDep = {| "previewSubscriptionChange"| "buyProduct"| "removeProduct"+ | "upgradeProduct"| "changeCommitments"| "startTrial"| "cancelTrial"@@ -114,6 +117,22 @@ const formatIsoDate = (iso: string | null | undefined): string | null => {return date.toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" });};+const DAY_IN_MS = 24 * 60 * 60 * 1000;++const daysUntil = (unixSeconds: number | null | undefined): number | null => {+ if (!unixSeconds) {+ return null;+ }+ return Math.max(0, Math.ceil((unixSeconds * 1000 - Date.now()) / DAY_IN_MS));+};++const daysSince = (unixSeconds: number | null | undefined): number | null => {+ if (!unixSeconds) {+ return null;+ }+ return Math.max(0, Math.floor((Date.now() - unixSeconds * 1000) / DAY_IN_MS));+};+// Compact date ("Aug 16") for the header's next-charge line, where the year is noise.const formatShortDate = (unixSeconds: number | null | undefined): string | null => {if (!unixSeconds) {@@ -162,10 +181,10 @@ const resolveSubState = (subscription: TSubscriptionResponse | null): BillingV2Sif (status === "past_due") {return "past-due";}- if (status === "unpaid" || status === "canceled" || status === "incomplete") {+ if (status === "unpaid" || status === "incomplete") {return "suspended";}- if (status === "none" || status === "") {+ if (status === "canceled" || status === "incomplete_expired" || status === "none" || status === "") {return "no-subscription";}return "active";@@ -264,6 +283,8 @@ const toPlan = (product: TCatalogProduct, plan: TCatalogProduct["plans"][number]selfServe: plan.selfServe,salesLed: plan.salesLed,trialable: plan.trialable ?? false,+ upgradeable: plan.upgradeable ?? false,+ trialDays: plan.trialDays ?? 0,deprecated: plan.deprecated ?? false,...(deprecation ? { deprecation } : {}),displayOrder: plan.displayOrder ?? undefined,@@ -596,6 +617,15 @@ export const licenseV2ServiceFactory = ({status: item.status,isTrialing: item.isTrialing ?? false,trialEndsAt: item.trialEndsAt ? formatDate(item.trialEndsAt) : null,+ ...(item.trialPlan+ ? {+ trialPlan: item.trialPlan,+ trialPlanName:+ catalogProduct?.plans.find((candidate) => candidate.tier === item.trialPlan)?.name ?? item.trialPlan,+ trialPlanEndsAt: formatDate(item.trialPlanEndsAt),+ trialPlanDaysLeft: daysUntil(item.trialPlanEndsAt)+ }+ : {}),renewsOn,...(deprecation ? { deprecation } : {}),used,@@ -625,12 +655,14 @@ export const licenseV2ServiceFactory = ({if (existing) {existing.planTier = existing.planTier ?? product.plan_key ?? undefined;existing.status = existing.status ?? product.status ?? undefined;+ existing.trialPlan = existing.trialPlan ?? product.trial_plan_key ?? undefined;return;}entitlements[product.product_key] = {entitled: true,planTier: product.plan_key ?? undefined,status: product.status ?? undefined,+ ...(product.trial_plan_key ? { trialPlan: product.trial_plan_key } : {}),isTrialing,trialEndsAt: formatIsoDate(product.trial_ends_at)};@@ -721,14 +753,19 @@ export const licenseV2ServiceFactory = ({0);- // Products whose one-per-product trial is used up (any outcome — trialing/converted/expired/- // canceled/completed). The UI gates the trial CTA on this so a canceled trial isn't re-offered.- // A failed lookup degrades to empty: the server still blocks a repeat trial with a 409 on start.- let trialedProductKeys: string[] = [];+ let trialHistory: BillingV2Trial[] = [];if (!isSelfHostedLicense) {try {const trials = await licenseClient.getTrials(orgId);- trialedProductKeys = [...new Set(trials.trials.map((trial) => trial.product_key))];+ trialHistory = trials.trials.map((trial) => ({+ productKey: trial.product_key,+ planTier: trial.plan_key ?? null,+ basePlanTier: trial.base_plan_key ?? null,+ outcome: trial.outcome,+ endedDetail: trial.ended_detail ?? null,+ endedAt: formatDate(trial.trial_ends_at),+ endedDaysAgo: daysSince(trial.trial_ends_at)+ }));} catch (error) {logger.error(error, `billing-v2: failed to read trial history [orgId=${orgId}]`);}@@ -775,7 +812,7 @@ export const licenseV2ServiceFactory = ({billingDetails,invoices,entitlements,- trialedProductKeys,+ trials: trialHistory,onDemandAmount,checkoutFrozen: subscription?.capabilities?.checkoutFrozen ?? false,// false for an enterprise-managed org (self-serve mutations 403); default true keeps paygo and@@ -891,14 +928,36 @@ export const licenseV2ServiceFactory = ({cadence,quantities,removeProductId,- commitmentChanges+ commitmentChanges,+ upgradeProductId,+ upgradePlan}: TPreviewBillingV2ChangeDTO): Promise<{ preview: BillingV2Preview }> => {await ensureManageBilling(orgId, actor);- if (!addProductId && !removeProductId && !(commitmentChanges && commitmentChanges.length > 0)) {- throw new BadRequestError({ message: "Provide a product to add or remove, or a commitment change" });+ if (+ !addProductId &&+ !removeProductId &&+ !upgradeProductId &&+ !(commitmentChanges && commitmentChanges.length > 0)+ ) {+ throw new BadRequestError({+ message: "Provide a product to add, remove or upgrade, or a commitment change"+ });+ }+ if (upgradeProductId && !upgradePlan) {+ throw new BadRequestError({ message: "Provide the plan to upgrade to" });+ }+ // A plan change already is a remove plus an add, so pairing it with either double-counts. The+ // license server rejects the combination too; failing here keeps the round trip off the wire.+ if (upgradeProductId && (addProductId === upgradeProductId || removeProductId === upgradeProductId)) {+ throw new BadRequestError({+ message: "A plan change cannot be combined with adding or removing the same product"+ });}const payload: TSubscriptionPreviewPayload = {};+ if (upgradeProductId && upgradePlan) {+ payload.upgrade = { productId: upgradeProductId, plan: upgradePlan };+ }if (addProductId) {const catalog = await licenseClient.getCatalog(orgId);const product = catalog?.products.find((candidate) => candidate.id === addProductId);@@ -936,6 +995,7 @@ export const licenseV2ServiceFactory = ({nextInvoiceTotal: centsToDollars(preview.nextInvoiceTotal),nextRecurringTotal: centsToDollars(preview.nextRecurringTotal),prorationDate: preview.prorationDate ?? null,+ toPlanVersionId: preview.toPlanVersionId ?? null,lines: preview.lines.map((line) => ({description: line.description,amount: centsToDollars(line.amount),@@ -945,6 +1005,33 @@ export const licenseV2ServiceFactory = ({};};+ // Move a held product onto a higher plan. No quantities, cadence or declaredUsage: the license+ // server carries every existing line forward with its live quantity, so the only thing charged is+ // the prorated difference and the renewal date does not move.+ const upgradeProduct = async ({+ orgId,+ actor,+ productId,+ plan,+ expectedPlanVersionId,+ prorationDate+ }: TUpgradeBillingV2ProductDTO) => {+ await ensureManageBilling(orgId, actor);+ const result = await licenseClient.upgradeProduct(orgId, {+ productId,+ plan,+ expectedPlanVersionId,+ prorationDate+ });+ await licenseClient.markEntitlementsStale(orgId);+ return {+ outcome: result.outcome,+ subscriptionId: result.subscriptionId,+ fromPlanKey: result.fromPlanKey,+ toPlanKey: result.toPlanKey+ };+ };+const changeCommitments = async ({ orgId, actor, changes, productId }: TChangeBillingV2CommitmentDTO) => {await ensureManageBilling(orgId, actor);if (!changes.length) {@@ -1037,6 +1124,7 @@ export const licenseV2ServiceFactory = ({addPaymentMethod,previewChange,removeProduct,+ upgradeProduct,changeCommitments,startTrial,cancelTrial,diff --git a/backend/src/ee/services/license-v2/license-v2-types.ts b/backend/src/ee/services/license-v2/license-v2-types.tsindex 63b5a24ecf..81cb35d72e 100644--- a/backend/src/ee/services/license-v2/license-v2-types.ts+++ b/backend/src/ee/services/license-v2/license-v2-types.ts@@ -39,8 +39,12 @@ export type BillingV2Plan = {name: string;selfServe: boolean;salesLed: boolean;- // Offers a self-serve trial; the UI shows a trial CTA only when selfServe && trialable.+ // Org-aware: whether this org may trial / upgrade to this plan. Computed from the same rules the+ // mutating endpoints enforce, so a CTA gated on these can never offer an action that then 409s.trialable: boolean;+ upgradeable: boolean;+ // Trial length in days for this plan; 0 when it offers no trial.+ trialDays: number;// Kept for existing customers, closed to new ones. deprecation carries the reason/nextSteps/date.deprecated?: boolean;deprecation?: BillingV2Deprecation;@@ -135,6 +139,10 @@ export type BillingV2Entitlement = {status?: string;isTrialing?: boolean;trialEndsAt?: string | null;+ trialPlan?: string;+ trialPlanName?: string;+ trialPlanEndsAt?: string | null;+ trialPlanDaysLeft?: number | null;// Formatted date this product's soonest line renews (each product bills on its own cycle); null when// the product has no dated line (e.g. feature-only entitlements).renewsOn?: string | null;@@ -167,6 +175,16 @@ export type BillingV2Billing = {nextCharge: BillingV2NextCharge | null;};+export type BillingV2Trial = {+ productKey: string;+ planTier: string | null;+ basePlanTier: string | null;+ outcome: string;+ endedDetail: string | null;+ endedAt: string | null;+ endedDaysAgo: number | null;+};+export type BillingV2Overview = {isCloud: boolean;mode: BillingV2Mode;@@ -189,8 +207,7 @@ export type BillingV2Overview = {} | null;invoices: BillingV2Invoice[];entitlements: Record<string, BillingV2Entitlement>;- // Product keys whose one-per-product trial is used up (any outcome); the UI gates the trial CTA on it.- trialedProductKeys: string[];+ trials: BillingV2Trial[];// Total monthly on-demand overage across all products (dollars), for the summary's on-demand note.onDemandAmount: number;checkoutFrozen: boolean;@@ -245,6 +262,7 @@ export type BillingV2Preview = {nextInvoiceTotal: number;nextRecurringTotal: number;prorationDate?: number | null;+ toPlanVersionId?: string | null;lines: BillingV2PreviewLine[];};@@ -265,6 +283,17 @@ export type TPreviewBillingV2ChangeDTO = {removeProductId?: string;// Per_resource commitment quantity changes to preview against the existing subscription.commitmentChanges?: BillingV2CommitmentChange[];+ upgradeProductId?: string;+ upgradePlan?: string;+};++export type TUpgradeBillingV2ProductDTO = {+ orgId: string;+ actor: OrgServiceActor;+ productId: string;+ plan: string;+ expectedPlanVersionId: string;+ prorationDate?: number;};export type TRemoveBillingV2ProductDTO = {diff --git a/backend/src/services/license-client/license-client-backends.ts b/backend/src/services/license-client/license-client-backends.tsindex 42a3fff423..626ed8a85b 100644--- a/backend/src/services/license-client/license-client-backends.ts+++ b/backend/src/services/license-client/license-client-backends.ts@@ -34,7 +34,10 @@ import {TSubscriptionResponse,TTrialCancelResult,TTrialResult,- TTrialsResponse+ TTrialsResponse,+ TUpgradePayload,+ TUpgradeResult,+ upgradeResultSchema} from "./license-client-types";import { TLicenseTokenProvider } from "./license-token-provider";@@ -80,7 +83,20 @@ const BILLING_ERROR_MESSAGES: Record<string, string> = {past_due: "There's an unpaid invoice on your account. Resolve payment before making changes.",resubscribe_cooldown: "This product was removed recently. Please wait a bit before resubscribing.",not_self_serve: "Billing for this organization is managed by our team. Contact sales to make changes.",- product_not_trialing: "Start this product's trial or activate it before setting an annual commitment."+ product_not_trialing: "Start this product's trial or activate it before setting an annual commitment.",+ not_an_upgrade: "This plan isn't an upgrade from your current one. Contact support to switch to it.",+ product_not_held: "You don't have this product yet. Add it before changing its plan.",+ product_trialing: "You're on a trial of this product. You can change plans once the trial converts.",+ product_churned: "This product was canceled. Add it again before changing its plan.",+ trial_already_used: "You've already trialed this plan.",+ trial_already_open: "A trial for this product is already running.",+ trial_not_eligible: "You're already on this plan.",+ version_moved: "Prices changed while you were reviewing. Check the new total and try again.",+ commitment_not_portable: "Your annual commitment can't move to that plan. Contact sales to switch.",+ dimension_not_priced: "That plan doesn't price something you're billed for today. Contact support to switch.",+ no_payment_method: "Add a payment method before making this change.",+ subscription_syncing: "Your billing details are still syncing. Please try again in a moment.",+ plan_deprecated: "This plan is being retired and is no longer available."};const throwIfResponseError = async (res: Response): Promise<void> => {@@ -274,6 +290,21 @@ export const licenseServerBackend = (return checkoutResultSchema.parse(body);},+ // Move a held product onto a higher plan in place. expectedPlanVersionId is the version the preview+ // priced; prorationDate is a staleness check the server rejects when older than 15 minutes.+ upgradeProduct: async (orgId: string, payload: TUpgradePayload): Promise<TUpgradeResult> => {+ const url = new URL(orgScoped(orgId, "/subscription/upgrade"), serverUrl);+ const res = await fetch(url, {+ method: "POST",+ headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}`, "Content-Type": "application/json" },+ body: JSON.stringify(payload),+ redirect: "manual"+ });+ await throwIfResponseError(res);+ const body: unknown = await res.json();+ return upgradeResultSchema.parse(body);+ },+// Start / change annual commitments across dimensions, all-or-nothing. The license server prices at// its current time; no client-supplied proration instant is forwarded.changeCommitments: async (orgId: string, payload: TChangeCommitmentsPayload): Promise<TCheckoutResult> => {@@ -448,6 +479,7 @@ export const licenseServerSelfHostedBackend = (previewSubscriptionChange: notSupportedOnSelfHosted("previewSubscriptionChange"),buyProduct: notSupportedOnSelfHosted("buyProduct"),removeProduct: notSupportedOnSelfHosted("removeProduct"),+ upgradeProduct: notSupportedOnSelfHosted("upgradeProduct"),changeCommitments: notSupportedOnSelfHosted("changeCommitments"),startTrial: notSupportedOnSelfHosted("startTrial"),cancelTrial: notSupportedOnSelfHosted("cancelTrial"),diff --git a/backend/src/services/license-client/license-client-types.ts b/backend/src/services/license-client/license-client-types.tsindex d84aacd02c..2dd18bb63b 100644--- a/backend/src/services/license-client/license-client-types.ts+++ b/backend/src/services/license-client/license-client-types.ts@@ -15,6 +15,7 @@ const entitlementProductSchema = zproduct_key: z.string(),plan_key: z.string().nullish(),status: z.string().nullish(), // active | trialing | grace | churned+ trial_plan_key: z.string().nullish(),trial_ends_at: z.string().nullish(),current_period_end: z.string().nullish()})@@ -56,8 +57,11 @@ const catalogPlanSchema = zname: z.string(),selfServe: z.boolean(),salesLed: z.boolean(),- // Offers a self-serve trial; a plan is trialable only when selfServe && trialable.+ // Org-aware: whether THIS org may trial / upgrade to this plan, not a static property of the plan.trialable: z.boolean().default(false),+ upgradeable: z.boolean().default(false),+ // Server-configured trial length for this plan; 0 when the plan offers no trial.+ trialDays: z.number().nullish(),// true = kept for existing customers, closed to new ones. reason/nextSteps/date shown when true.deprecated: z.boolean().default(false),deprecationReason: z.string().nullish(),@@ -163,6 +167,8 @@ const subscriptionItemSchema = zstatus: z.string().optional(),isTrialing: z.boolean().default(false),trialEndsAt: z.number().nullish(),+ trialPlan: z.string().nullish(),+ trialPlanEndsAt: z.number().nullish(),// Present only when this item's product OR plan is deprecated (product supersedes plan). The item// keeps working; this carries the contract-specific message (the sunset date comes from the catalog).deprecation: z.object({ reason: z.string().nullish(), nextSteps: z.string().nullish() }).nullish(),@@ -261,10 +267,23 @@ export const subscriptionPreviewResponseSchema = znextInvoiceTotal: z.number(),nextRecurringTotal: z.number(),prorationDate: z.number().nullish(),+ // Upgrade previews only. Echoed back on apply so a price published between the two calls fails as+ // version_moved instead of silently charging a different number.+ toPlanVersionId: z.string().nullish(),lines: z.array(subscriptionPreviewLineSchema).default([])}).passthrough();+export const upgradeResultSchema = z+ .object({+ outcome: z.literal("upgraded"),+ subscriptionId: z.string().optional(),+ fromPlanKey: z.string().optional(),+ toPlanKey: z.string().optional(),+ toPlanVersionId: z.string().optional()+ })+ .passthrough();+// The cloud-plan FeatureSet carries plan caps; the server nulls a limit when it is effectively// unlimited. Used counts come back zeroed and are overlaid by this app, so we ignore them.export const cloudPlanResponseSchema = z@@ -366,12 +385,27 @@ export type TCommitmentChange = {quantity: number;};+// An upgrade carries no quantities or declaredUsage: the server moves the lines the org already has,+// each keeping its live quantity and cadence. Mutually exclusive with add/remove of the same product.+export type TUpgradeItem = {+ productId: string;+ plan: string;+};+export type TSubscriptionPreviewPayload = {add?: TProductLineItem[];remove?: string[];commitmentChanges?: TCommitmentChange[];+ upgrade?: TUpgradeItem;};+export type TUpgradePayload = TUpgradeItem & {+ expectedPlanVersionId: string;+ prorationDate?: number;+};++export type TUpgradeResult = z.infer<typeof upgradeResultSchema>;+export type TBuyProductPayload = {productId: string;plan: string;@@ -447,8 +481,10 @@ const trialHistoryItemSchema = z.object({product_key: z.string(),plan_key: z.string().nullish(),- // trialing | converted | expired | canceled | completed+ base_plan_key: z.string().nullish(),+ // trialing | converted | expired | canceled | completed | revertedoutcome: z.string(),+ ended_detail: z.string().nullish(),started_at: z.number().nullish(),trial_ends_at: z.number().nullish()})@@ -471,6 +507,8 @@ export type TLicenseClientBackend = {buyProduct: (orgId: string, payload: TBuyProductPayload) => Promise<TCheckoutResult>;// Remove one product; removing the last product cancels the subscription.removeProduct: (orgId: string, productId: string) => Promise<TCheckoutResult>;+ // Move a held product onto a higher plan in place, invoicing only the prorated difference.+ upgradeProduct: (orgId: string, payload: TUpgradePayload) => Promise<TUpgradeResult>;// Start / change annual commitments across dimensions (all-or-nothing).changeCommitments: (orgId: string, payload: TChangeCommitmentsPayload) => Promise<TCheckoutResult>;// Start a plan-scoped self-serve trial.diff --git a/backend/src/services/license-client/license-client.ts b/backend/src/services/license-client/license-client.tsindex 06fb6c7743..6f1adbe1fb 100644--- a/backend/src/services/license-client/license-client.ts+++ b/backend/src/services/license-client/license-client.ts@@ -13,7 +13,8 @@ import {TEntitlementOrg,TLicenseClientBackend,TStartTrialPayload,- TSubscriptionPreviewPayload+ TSubscriptionPreviewPayload,+ TUpgradePayload} from "./license-client-types";import { createSelfHostedTokenProvider } from "./license-token-provider";@@ -176,6 +177,13 @@ export const licenseClientFactory = ({ envConfig, keyStore, isOffline = false }:return backend.removeProduct(orgId, productId);};+ const upgradeProduct = async (orgId: string, payload: TUpgradePayload) => {+ if (!backend) {+ throw new Error("license client backend is not configured");+ }+ return backend.upgradeProduct(orgId, payload);+ };+const changeCommitments = async (orgId: string, payload: TChangeCommitmentsPayload) => {if (!backend) {throw new Error("license client backend is not configured");@@ -236,6 +244,7 @@ export const licenseClientFactory = ({ envConfig, keyStore, isOffline = false }:previewSubscriptionChange,buyProduct,removeProduct,+ upgradeProduct,changeCommitments,startTrial,cancelTrial,diff --git a/frontend/src/hooks/api/billingV2/index.tsx b/frontend/src/hooks/api/billingV2/index.tsxindex 001eac6fc7..c13c5d283a 100644--- a/frontend/src/hooks/api/billingV2/index.tsx+++ b/frontend/src/hooks/api/billingV2/index.tsx@@ -9,7 +9,8 @@ export {useRefreshBillingV2Entitlements,useRemoveBillingV2Product,useResumeBillingV2Subscription,- useStartBillingV2Trial+ useStartBillingV2Trial,+ useUpgradeBillingV2Product} from "./mutations";export { billingV2Keys, useGetBillingV2Catalog, useGetBillingV2Overview } from "./queries";export type {@@ -28,5 +29,8 @@ export type {BillingV2Preview,BillingV2PreviewLine,BillingV2SubState,- BillingV2TrialResult+ BillingV2Trial,+ BillingV2TrialOutcome,+ BillingV2TrialResult,+ BillingV2UpgradeResult} from "./types";diff --git a/frontend/src/hooks/api/billingV2/mutations.tsx b/frontend/src/hooks/api/billingV2/mutations.tsxindex a193be4e22..94b7fb7fa5 100644--- a/frontend/src/hooks/api/billingV2/mutations.tsx+++ b/frontend/src/hooks/api/billingV2/mutations.tsx@@ -1,4 +1,4 @@-import { useMutation, useQueryClient } from "@tanstack/react-query";+import { QueryClient, useMutation, useQueryClient } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";@@ -10,6 +10,7 @@ import {BillingV2Preview,BillingV2TrialCancelResult,BillingV2TrialResult,+ BillingV2UpgradeResult,TAddBillingV2PaymentMethodDTO,TBillingV2LifecycleDTO,TBuyBillingV2ProductDTO,@@ -18,9 +19,18 @@ import {TCreateBillingV2PortalSessionDTO,TPreviewBillingV2ChangeDTO,TRemoveBillingV2ProductDTO,- TStartBillingV2TrialDTO+ TStartBillingV2TrialDTO,+ TUpgradeBillingV2ProductDTO} from "./types";+// The catalog's trialable/upgradeable flags are org-aware, so any mutation that changes what the org+// holds invalidates it alongside the overview; otherwise both CTAs stay stale after the action that+// changed them.+const invalidateBillingV2 = (queryClient: QueryClient, orgId: string) => {+ queryClient.invalidateQueries({ queryKey: billingV2Keys.overview(orgId) });+ queryClient.invalidateQueries({ queryKey: billingV2Keys.catalog(orgId) });+};+export const useCreateBillingV2PortalSession = () => {return useMutation({mutationFn: async ({ orgId, returnPath }: TCreateBillingV2PortalSessionDTO) => {@@ -57,7 +67,7 @@ export const useBuyBillingV2Product = () => {return data;},onSuccess: (_data, { orgId }) => {- queryClient.invalidateQueries({ queryKey: billingV2Keys.overview(orgId) });+ invalidateBillingV2(queryClient, orgId);}});};@@ -88,13 +98,24 @@ export const usePreviewBillingV2Change = () => {cadence,quantities,removeProductId,- commitmentChanges+ commitmentChanges,+ upgradeProductId,+ upgradePlan}: TPreviewBillingV2ChangeDTO) => {const {data: { preview }} = await apiRequest.post<{ preview: BillingV2Preview }>(`/api/v1/organizations/${orgId}/billing/v2/subscription/preview`,- { addProductId, plan, cadence, quantities, removeProductId, commitmentChanges }+ {+ addProductId,+ plan,+ cadence,+ quantities,+ removeProductId,+ commitmentChanges,+ upgradeProductId,+ upgradePlan+ });return preview;@@ -102,6 +123,31 @@ export const usePreviewBillingV2Change = () => {});};+// Move a held product onto a higher plan. expectedPlanVersionId comes from the preview and is what+// turns a price published in between into a clean conflict instead of an unexpected charge.+export const useUpgradeBillingV2Product = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({+ orgId,+ productId,+ plan,+ expectedPlanVersionId,+ prorationDate+ }: TUpgradeBillingV2ProductDTO) => {+ const { data } = await apiRequest.post<BillingV2UpgradeResult>(+ `/api/v1/organizations/${orgId}/billing/v2/subscription/upgrade`,+ { productId, plan, expectedPlanVersionId, prorationDate }+ );++ return data;+ },+ onSuccess: (_data, { orgId }) => {+ invalidateBillingV2(queryClient, orgId);+ }+ });+};+// Start / change annual commitments across dimensions in one atomic call.export const useChangeBillingV2Commitment = () => {const queryClient = useQueryClient();@@ -115,7 +161,7 @@ export const useChangeBillingV2Commitment = () => {return data;},onSuccess: (_data, { orgId }) => {- queryClient.invalidateQueries({ queryKey: billingV2Keys.overview(orgId) });+ invalidateBillingV2(queryClient, orgId);}});};@@ -134,7 +180,7 @@ export const useStartBillingV2Trial = () => {return data;},onSuccess: (_data, { orgId }) => {- queryClient.invalidateQueries({ queryKey: billingV2Keys.overview(orgId) });+ invalidateBillingV2(queryClient, orgId);}});};@@ -152,7 +198,7 @@ export const useCancelBillingV2Trial = () => {return data;},onSuccess: (_data, { orgId }) => {- queryClient.invalidateQueries({ queryKey: billingV2Keys.overview(orgId) });+ invalidateBillingV2(queryClient, orgId);}});};@@ -168,7 +214,7 @@ export const useRemoveBillingV2Product = () => {return data;},onSuccess: (_data, { orgId }) => {- queryClient.invalidateQueries({ queryKey: billingV2Keys.overview(orgId) });+ invalidateBillingV2(queryClient, orgId);}});};@@ -184,7 +230,7 @@ export const useCancelBillingV2Subscription = () => {return data;},onSuccess: (_data, { orgId }) => {- queryClient.invalidateQueries({ queryKey: billingV2Keys.overview(orgId) });+ invalidateBillingV2(queryClient, orgId);}});};@@ -200,7 +246,7 @@ export const useResumeBillingV2Subscription = () => {return data;},onSuccess: (_data, { orgId }) => {- queryClient.invalidateQueries({ queryKey: billingV2Keys.overview(orgId) });+ invalidateBillingV2(queryClient, orgId);}});};diff --git a/frontend/src/hooks/api/billingV2/types.ts b/frontend/src/hooks/api/billingV2/types.tsindex 5437021bf7..a30b6d2e5d 100644--- a/frontend/src/hooks/api/billingV2/types.ts+++ b/frontend/src/hooks/api/billingV2/types.ts@@ -34,8 +34,12 @@ export type BillingV2Plan = {name: string;selfServe: boolean;salesLed: boolean;- // Offers a self-serve trial; the trial CTA shows only when selfServe && trialable.+ // Org-aware: whether this org may trial / upgrade to this plan. The server computes both from the+ // same rules the mutating endpoints enforce, so gating a CTA on them can never offer a 409.trialable: boolean;+ upgradeable: boolean;+ // Trial length in days; 0 when the plan offers no trial.+ trialDays: number;// Kept for existing customers, closed to new ones; deprecation carries the reason/nextSteps/date.deprecated?: boolean;deprecation?: BillingV2Deprecation;@@ -135,6 +139,10 @@ export type BillingV2Entitlement = {status?: string;isTrialing?: boolean;trialEndsAt?: string | null;+ trialPlan?: string;+ trialPlanName?: string;+ trialPlanEndsAt?: string | null;+ trialPlanDaysLeft?: number | null;// Formatted date this product's soonest line renews (each product bills on its own cycle); null when// the product has no dated line.renewsOn?: string | null;@@ -147,6 +155,24 @@ export type BillingV2Entitlement = {unit?: string | null;};+export type BillingV2TrialOutcome =+ | "trialing"+ | "converted"+ | "expired"+ | "canceled"+ | "completed"+ | "reverted";++export type BillingV2Trial = {+ productKey: string;+ planTier: string | null;+ basePlanTier: string | null;+ outcome: BillingV2TrialOutcome | string;+ endedDetail: string | null;+ endedAt: string | null;+ endedDaysAgo: number | null;+};+export type BillingV2Overview = {isCloud: boolean;mode: "self-serve" | "managed";@@ -185,8 +211,7 @@ export type BillingV2Overview = {} | null;invoices: BillingV2Invoice[];entitlements: Record<string, BillingV2Entitlement>;- // Product keys whose one-per-product trial is used up (any outcome); gates the trial CTA.- trialedProductKeys: string[];+ trials: BillingV2Trial[];// Mutating billing actions are frozen server-side; the UI disables purchase/commit/remove controls.checkoutFrozen: boolean;// false for an enterprise-managed org: render the self-serve billing UI but disable its controls@@ -239,6 +264,9 @@ export type BillingV2Preview = {totalDueNow: number;nextInvoiceTotal: number;nextRecurringTotal: number;+ prorationDate?: number | null;+ // Upgrade previews only; must be echoed back on apply.+ toPlanVersionId?: string | null;lines: BillingV2PreviewLine[];};@@ -267,6 +295,25 @@ export type TPreviewBillingV2ChangeDTO = {removeProductId?: string;// Per_resource commitment quantity changes to preview against the existing subscription.commitmentChanges?: BillingV2CommitmentChange[];+ // Plan change for a product already held. Carries no quantities or cadence: the server moves the+ // existing lines as they are.+ upgradeProductId?: string;+ upgradePlan?: string;+};++export type TUpgradeBillingV2ProductDTO = {+ orgId: string;+ productId: string;+ plan: string;+ expectedPlanVersionId: string;+ prorationDate?: number;+};++export type BillingV2UpgradeResult = {+ outcome: "upgraded";+ subscriptionId?: string;+ fromPlanKey?: string;+ toPlanKey?: string;};export type TRemoveBillingV2ProductDTO = {diff --git a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsxindex 765ead1d3a..88c1923fb4 100644--- a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx+++ b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx@@ -181,7 +181,6 @@ export const BillingV2Page = () => {initialView={flow.view}returnPath={window.location.pathname}renewsOn={overview?.entitlements[flow.prodId]?.renewsOn ?? null}- trialUsed={overview?.trialedProductKeys.includes(flow.prodId) ?? false}selfServe={overview?.selfServe ?? true}onClose={close}onRemove={setRemoveProdId}diff --git a/frontend/src/pages/organization/BillingV2Page/components/ChargeBreakdown.tsx b/frontend/src/pages/organization/BillingV2Page/components/ChargeBreakdown.tsxindex 5154f4ae5b..fb3ca239bc 100644--- a/frontend/src/pages/organization/BillingV2Page/components/ChargeBreakdown.tsx+++ b/frontend/src/pages/organization/BillingV2Page/components/ChargeBreakdown.tsx@@ -28,29 +28,29 @@ export const ChargeBreakdown = ({ prorationAmount, additionalCharges, totalDueNoif (totalDueNow < 0) {// Net credit: nothing is charged now and the remaining credit rolls to future invoices.body = (- <>+ <div>You'll be charged <span className="font-medium">$0</span> now. This change costs{" "}{fmtMoney(prorationAmount, 2)}, and a{" "}<span className="font-medium">{fmtMoney(Math.abs(totalDueNow), 2)} credit</span> will beapplied to your future invoices.- </>+ </div>);} else if (additionalCharges < 0) {// Still due now, but earlier changes contribute a credit that reduces the charge.body = (- <>+ <div>You'll be charged <span className="font-medium">{fmtMoney(totalDueNow, 2)}</span> now:{" "}{fmtMoney(prorationAmount, 2)} for this change, and a credit of{" "}{fmtMoney(Math.abs(additionalCharges), 2)} from earlier changes will be applied.- </>+ </div>);} else {body = (- <>+ <div>You'll be charged <span className="font-medium">{fmtMoney(totalDueNow, 2)}</span> now:{" "}{fmtMoney(prorationAmount, 2)} for this change, plus {fmtMoney(additionalCharges, 2)} inpending charges from earlier changes that haven't been billed yet.- </>+ </div>);}diff --git a/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx b/frontend/src/pages/organization/BillingV2Page/components/Overview.tsxindex fbf6b285c9..6f5b1dbd7f 100644--- a/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx+++ b/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx@@ -13,6 +13,7 @@ import { ProductsCard } from "./cards/ProductsCard";import { ErrorPanel } from "./states/ErrorPanel";import { OverviewSkeleton } from "./states/OverviewSkeleton";import { Banner } from "./Banner";+import { TrialBanners } from "./TrialBanners";export type OverviewProps = {overview?: BillingV2Overview;@@ -132,6 +133,13 @@ export const Overview = ({onManage={onUpgrade}onContact={onContact}/> */}+ <TrialBanners+ overview={overview}+ catalog={catalog}+ onManage={onUpgrade}+ onUpdatePayment={onUpdatePayment}+ onContact={onContact}+ /><BillingHeaderCard overview={overview} catalog={catalog} /><ProductsCardoverview={overview}diff --git a/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsx b/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsxindex 4bf5befea3..e641686873 100644--- a/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsx+++ b/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsx@@ -57,6 +57,7 @@ import {import { ActivateView } from "./ActivateView";import { CommitmentView } from "./CommitmentView";import { ActiveBadge, DimensionMeter, ProductIcon } from "./shared";+import { UpgradeView } from "./UpgradeView";// prefix/metered carry the usage-based framing for metered dims; absent for per_unit and base prices.type PriceLine = { amount: string; unit: string; prefix?: string; metered?: boolean };@@ -187,8 +188,6 @@ type PlanCardProps = {cadence: BillingV2Cadence;isCurrent: boolean;entitled: boolean;- // This product's one-per-product trial is already used up (any outcome), so no trial CTA.- trialUsed: boolean;canChangeCommitment: boolean;// Whether a commitment already exists, so the CTA reads "Change" vs "Set" commitment.hasCommitment: boolean;@@ -196,6 +195,8 @@ type PlanCardProps = {// sales-led "Contact sales" CTA stays enabled.selfServe: boolean;onActivate: (planTier: string) => void;+ onStartTrial: (planTier: string) => void;+ onUpgrade: (planTier: string) => void;onChangeCommitment: () => void;onContact: () => void;};@@ -205,18 +206,19 @@ const PlanCard = ({cadence,isCurrent,entitled,- trialUsed,canChangeCommitment,hasCommitment,selfServe,onActivate,+ onStartTrial,+ onUpgrade,onChangeCommitment,onContact}: PlanCardProps) => {const isCustom = plan.salesLed && !plan.base && plan.dims.length === 0;- // A trial is offered only when the plan supports it, the org isn't already on the product, and it- // hasn't used its one-time trial for this product yet.- const offersTrial = plan.selfServe && plan.trialable && !entitled && !trialUsed;+ const offersTrial = plan.selfServe && plan.trialable;+ const trialLabel =+ plan.trialDays > 0 ? `Try free for ${plan.trialDays} days` : "Start a free trial";// Each card carries its own billing-cadence toggle. It defaults to the passed cadence (annual for a// new product, so the discounted per-month rate leads), clamped to what the plan actually prices.@@ -264,7 +266,7 @@ const PlanCard = ({isDisabled={!selfServe}onClick={() => onActivate(plan.tier)}>- Start a free trial+ {trialLabel}</Button>) : (<Button@@ -277,6 +279,30 @@ const PlanCard = ({Activate</Button>);+ } else if (entitled && !isCurrent && plan.selfServe && (offersTrial || plan.upgradeable)) {+ // A plan above the one held. Trial wins when offered: it charges nothing, and once it starts+ // trialable goes false while upgradeable stays true, so the card falls through to Upgrade.+ cta = offersTrial ? (+ <Button+ variant="org"+ size="sm"+ className="w-full justify-center"+ isDisabled={!selfServe}+ onClick={() => onStartTrial(plan.tier)}+ >+ {trialLabel}+ </Button>+ ) : (+ <Button+ variant="org"+ size="sm"+ className="w-full justify-center"+ isDisabled={!selfServe}+ onClick={() => onUpgrade(plan.tier)}+ >+ Upgrade now+ </Button>+ );}return (@@ -432,8 +458,6 @@ type ProductSheetProps = {initialView?: SheetView;returnPath: string;renewsOn: string | null;- // This product's one-per-product trial is already used up (backend-computed from trial history).- trialUsed: boolean;// capabilities.selfServe: false for an enterprise-managed org. Self-serve CTAs render disabled and a// notice points to sales; the sales-led "Contact sales" path stays available.selfServe: boolean;@@ -442,7 +466,7 @@ type ProductSheetProps = {onContact: (prod: BillingV2CatalogProduct) => void;};-type SheetView = "plans" | "activate" | "commitment";+type SheetView = "plans" | "activate" | "commitment" | "upgrade";export const ProductSheet = ({orgId,@@ -452,7 +476,6 @@ export const ProductSheet = ({initialView,returnPath,renewsOn,- trialUsed,selfServe,onClose,onRemove,@@ -461,6 +484,8 @@ export const ProductSheet = ({const [view, setView] = useState<SheetView>(initialView ?? "plans");// The plan tier chosen for the activate view.const [activatePlan, setActivatePlan] = useState<string | null>(null);+ // The plan tier chosen for the upgrade view.+ const [upgradePlan, setUpgradePlan] = useState<string | null>(null);// The plan tier awaiting trial confirmation (drives the confirm dialog).const [trialConfirmTier, setTrialConfirmTier] = useState<string | null>(null);// Whether the cancel-trial confirm dialog is open.@@ -476,9 +501,17 @@ export const ProductSheet = ({const entitled = Boolean(entitlement?.entitled);// A trialing product is canceled (trial → free), not removed like a paid product line.const isTrialing = Boolean(entitlement?.isTrialing);+ // An upgrade trial sits on top of a paid plan: ending it reverts to that plan rather than to free.+ const upgradeTrialPlan = entitlement?.trialPlan+ ? (entitlement.trialPlanName ??+ prod.plans.find((plan) => plan.tier === entitlement.trialPlan)?.name ??+ entitlement.trialPlan)+ : null;+ const basePlanName = entitlement?.planTier+ ? (prod.plans.find((plan) => plan.tier === entitlement.planTier)?.name ?? entitlement.planTier)+ : "your current plan";const selfServePlan = prod.plans.find((plan) => plan.selfServe && !plan.salesLed);- const trialAvailable =- !entitled && !trialUsed && prod.plans.some((plan) => plan.selfServe && plan.trialable);+ const trialAvailable = !entitled && prod.plans.some((plan) => plan.selfServe && plan.trialable);// The plan-card price always leads with the best (annual) rate shown as a per-month figure (÷12, see// PlanPricing) with a "billed annually" note, even for a trialable plan. An entitled product shows// its own cadence. PlanPricing falls back to monthly for a monthly-only plan. The trial's@@ -506,6 +539,11 @@ export const ProductSheet = ({setView("activate");};+ const openUpgrade = (planTier: string) => {+ setUpgradePlan(planTier);+ setView("upgrade");+ };+const handleConfirmTrial = async () => {if (!trialConfirmTier) {return;@@ -546,7 +584,9 @@ export const ProductSheet = ({await cancelTrial.mutateAsync({ orgId, productId: prod.id });createNotification({type: "success",- text: `Your ${prod.name} trial has been canceled.`+ text: upgradeTrialPlan+ ? `Your ${upgradeTrialPlan} trial has ended. You're still on ${basePlanName}.`+ : `Your ${prod.name} trial has been canceled.`});onClose();} catch {@@ -559,6 +599,17 @@ export const ProductSheet = ({? plans.find((plan) => plan.tier === activatePlan): (selfServePlan ?? undefined);+ const upgradePlanObj = upgradePlan ? plans.find((plan) => plan.tier === upgradePlan) : undefined;++ const trialConfirmPlan = trialConfirmTier+ ? plans.find((plan) => plan.tier === trialConfirmTier)+ : undefined;+ // Trialing a plan above one the org already pays for: it converts to that plan rather than starting+ // a paid subscription from free, so the confirmation has to promise something different.+ const trialIsUpgrade = entitled && Boolean(trialConfirmTier) && trialConfirmTier !== currentTier;+ const trialLengthLabel =+ trialConfirmPlan && trialConfirmPlan.trialDays > 0 ? `${trialConfirmPlan.trialDays}-day ` : "";+return (<><Sheet@@ -590,6 +641,20 @@ export const ProductSheet = ({/>)}+ {view === "upgrade" && upgradePlanObj && (+ <UpgradeView+ orgId={orgId}+ prod={prod}+ plan={upgradePlanObj}+ fromPlanName={basePlanName}+ renewsOn={renewsOn}+ selfServe={selfServe}+ isTrialConversion={entitlement?.trialPlan === upgradePlanObj.tier}+ onBack={() => setView("plans")}+ onDone={onClose}+ />+ )}+{view === "commitment" && entitlement && (<CommitmentVieworgId={orgId}@@ -639,12 +704,13 @@ export const ProductSheet = ({plan={plan}cadence={displayCadence}entitled={entitled}- trialUsed={trialUsed}isCurrent={entitled && plan.tier === currentTier}canChangeCommitment={showChangeCommitment}hasCommitment={hasCommitment}selfServe={selfServe}onActivate={openActivate}+ onStartTrial={setTrialConfirmTier}+ onUpgrade={openUpgrade}onChangeCommitment={() => setView("commitment")}onContact={() => onContact(prod)}/>@@ -662,13 +728,13 @@ export const ProductSheet = ({<SheetFooter className="flex-row items-center justify-between border-t">{entitled ? (<>- {isTrialing ? (+ {isTrialing || upgradeTrialPlan ? (<Buttonvariant="danger"isDisabled={!selfServe}onClick={() => setShowCancelTrial(true)}>- Cancel trial+ {upgradeTrialPlan ? "End trial" : "Cancel trial"}</Button>) : (<Button@@ -712,11 +778,13 @@ export const ProductSheet = ({<AlertDialogMedia><Sparkles /></AlertDialogMedia>- <AlertDialogTitle>Start your {prod.name} trial</AlertDialogTitle>+ <AlertDialogTitle>+ Start your {trialConfirmPlan?.name ?? prod.name} trial+ </AlertDialogTitle><AlertDialogDescription>- Your 14-day trial is free. After it ends, your subscription continues automatically- and you'll be billed monthly based on usage. Cancel before the trial ends to- avoid charges.+ {trialIsUpgrade+ ? `Your ${trialLengthLabel}trial is free and nothing changes about your bill. You'll keep paying for ${basePlanName} until it ends, then move to ${trialConfirmPlan?.name} and be charged the difference. End the trial before then to stay on ${basePlanName}.`+ : `Your ${trialLengthLabel}trial is free. After it ends, your subscription continues automatically and you'll be billed monthly based on usage. Cancel before the trial ends to avoid charges.`}</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter>@@ -749,10 +817,15 @@ export const ProductSheet = ({<AlertDialogMedia><CalendarX2Icon /></AlertDialogMedia>- <AlertDialogTitle>Cancel your {prod.name} trial</AlertDialogTitle>+ <AlertDialogTitle>+ {upgradeTrialPlan+ ? `End your ${upgradeTrialPlan} trial`+ : `Cancel your ${prod.name} trial`}+ </AlertDialogTitle><AlertDialogDescription>- Canceling returns you to the free tier immediately and stops the trial from converting- to a paid plan. This trial can't be restarted later.+ {upgradeTrialPlan+ ? `You'll go back to ${basePlanName} right away and won't be charged anything. This trial can't be restarted later.`+ : "Canceling returns you to the free tier immediately and stops the trial from converting to a paid plan. This trial can't be restarted later."}</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter>@@ -766,7 +839,7 @@ export const ProductSheet = ({handleCancelTrial();}}>- Cancel trial+ {upgradeTrialPlan ? "End trial" : "Cancel trial"}</AlertDialogAction></AlertDialogFooter></AlertDialogContent>diff --git a/frontend/src/pages/organization/BillingV2Page/components/TrialBanners.tsx b/frontend/src/pages/organization/BillingV2Page/components/TrialBanners.tsxnew file mode 100644index 0000000000..a7325b13cb--- /dev/null+++ b/frontend/src/pages/organization/BillingV2Page/components/TrialBanners.tsx@@ -0,0 +1,107 @@+import { CircleAlert } from "lucide-react";++import { Alert, AlertDescription, AlertTitle, Button } from "@app/components/v3";+import { BillingV2CatalogProduct, BillingV2Overview, BillingV2Trial } from "@app/hooks/api";++import { tierLabel } from "../billing-v2-format";++// A reverted trial stays in the history forever, so only surface it while it is still actionable.+const REVERTED_NOTICE_DAYS = 14;++const REVERTED_REASON: Record<string, { body: string; action?: "payment" | "contact" }> = {+ no_payment_method: {+ body: "We couldn't charge a card when the trial ended, so nothing changed.",+ action: "payment"+ },+ commitment_not_portable: {+ body: "Your annual commitment couldn't carry over to the new plan, so nothing changed.",+ action: "contact"+ },+ dimension_not_priced: {+ body: "The new plan doesn't price something you're billed for today, so nothing changed.",+ action: "contact"+ }+};++const planName = (+ catalog: BillingV2CatalogProduct[],+ productKey: string,+ tier: string | null+): string => {+ if (!tier) {+ return "a higher plan";+ }+ const prod = catalog.find((candidate) => candidate.id === productKey);+ return prod?.plans.find((plan) => plan.tier === tier)?.name ?? tierLabel(tier);+};++const isRecentRevert = (trial: BillingV2Trial): boolean =>+ trial.outcome === "reverted" &&+ Boolean(trial.basePlanTier) &&+ (trial.endedDaysAgo === null || trial.endedDaysAgo <= REVERTED_NOTICE_DAYS);++type Props = {+ overview: BillingV2Overview;+ catalog: BillingV2CatalogProduct[];+ onManage: (productId: string) => void;+ onUpdatePayment: () => void;+ onContact: (prod: BillingV2CatalogProduct) => void;+};++// A running upgrade trial is rendered on the product's own card, not here. This is only the+// after-the-fact notice that one ended without converting, which has no card of its own.+export const TrialBanners = ({+ overview,+ catalog,+ onManage,+ onUpdatePayment,+ onContact+}: Props) => {+ // A revert that has since been superseded by a running trial of the same product is stale news.+ const reverted = overview.trials+ .filter(isRecentRevert)+ .filter((trial) => !overview.entitlements[trial.productKey]?.trialPlan);++ if (reverted.length === 0) {+ return null;+ }++ return (+ <>+ {reverted.map((trial) => {+ const reason = trial.endedDetail ? REVERTED_REASON[trial.endedDetail] : undefined;+ const catalogProduct = catalog.find((prod) => prod.id === trial.productKey);+ const basePlan = planName(catalog, trial.productKey, trial.basePlanTier);++ return (+ <Alert key={`reverted-${trial.productKey}-${trial.planTier ?? ""}`} variant="warning">+ <CircleAlert />+ <AlertTitle>+ Your {planName(catalog, trial.productKey, trial.planTier)} trial ended+ </AlertTitle>+ <AlertDescription>+ {reason?.body ?? "Your trial ended."} You're still on {basePlan}.+ {overview.selfServe && (+ <div className="mt-3 flex flex-wrap gap-2">+ {reason?.action === "payment" && (+ <Button variant="outline" size="xs" onClick={onUpdatePayment}>+ Add a payment method+ </Button>+ )}+ {reason?.action === "contact" && catalogProduct && (+ <Button variant="outline" size="xs" onClick={() => onContact(catalogProduct)}>+ Contact support+ </Button>+ )}+ <Button variant="ghost" size="xs" onClick={() => onManage(trial.productKey)}>+ View plans+ </Button>+ </div>+ )}+ </AlertDescription>+ </Alert>+ );+ })}+ </>+ );+};diff --git a/frontend/src/pages/organization/BillingV2Page/components/UpgradeView.tsx b/frontend/src/pages/organization/BillingV2Page/components/UpgradeView.tsxnew file mode 100644index 0000000000..05ebdd64a4--- /dev/null+++ b/frontend/src/pages/organization/BillingV2Page/components/UpgradeView.tsx@@ -0,0 +1,218 @@+import { useEffect, useState } from "react";+import { ArrowRight, ChevronLeftIcon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import {+ Alert,+ AlertDescription,+ AlertTitle,+ Button,+ SheetFooter,+ SheetHeader,+ SheetTitle+} from "@app/components/v3";+import {+ BillingV2CatalogProduct,+ BillingV2Plan,+ usePreviewBillingV2Change,+ useUpgradeBillingV2Product+} from "@app/hooks/api";++import { fmtMoney } from "../billing-v2-format";+import { ChargeBreakdown } from "./ChargeBreakdown";+import { CostSummary, CostSummaryRow, ProductIcon } from "./shared";++// The server rejects a proration date older than 15 minutes. Re-price before that so a sheet left+// open fails by refreshing the number rather than by throwing at the customer.+const PREVIEW_MAX_AGE_MS = 12 * 60 * 1000;++type Props = {+ orgId: string;+ prod: BillingV2CatalogProduct;+ plan: BillingV2Plan;+ fromPlanName: string;+ renewsOn: string | null;+ selfServe: boolean;+ // The org is mid upgrade-trial of this plan, so upgrading pulls the conversion forward rather than+ // starting something new.+ isTrialConversion: boolean;+ onBack: () => void;+ onDone: () => void;+};++export const UpgradeView = ({+ orgId,+ prod,+ plan,+ fromPlanName,+ renewsOn,+ selfServe,+ isTrialConversion,+ onBack,+ onDone+}: Props) => {+ const preview = usePreviewBillingV2Change();+ const upgrade = useUpgradeBillingV2Product();+ const [pricedAt, setPricedAt] = useState(0);++ const { mutate: runPreview } = preview;+ useEffect(() => {+ runPreview(+ { orgId, upgradeProductId: prod.id, upgradePlan: plan.tier },+ { onSuccess: () => setPricedAt(Date.now()) }+ );+ }, [orgId, prod.id, plan.tier, runPreview]);++ const isCalculating = preview.isPending || !preview.data;+ const dueToday = Math.max(preview.data?.totalDueNow ?? 0, 0);+ const recurring = preview.data?.nextRecurringTotal ?? 0;+ const additionalCharges = preview.data?.additionalCharges ?? 0;+ const versionId = preview.data?.toPlanVersionId ?? null;++ const rePreview = () =>+ new Promise<typeof preview.data>((resolve) => {+ runPreview(+ { orgId, upgradeProductId: prod.id, upgradePlan: plan.tier },+ {+ onSuccess: (fresh) => {+ setPricedAt(Date.now());+ resolve(fresh);+ },+ onError: () => resolve(undefined)+ }+ );+ });++ const handleUpgrade = async () => {+ let priced = preview.data;+ // A stale preview would be rejected on apply, and a version published in between would charge a+ // number the customer never saw, so re-price first and confirm the total is unchanged.+ if (Date.now() - pricedAt > PREVIEW_MAX_AGE_MS) {+ const fresh = await rePreview();+ if (!fresh) {+ return;+ }+ if (fresh.totalDueNow !== priced?.totalDueNow) {+ createNotification({+ type: "info",+ text: "Prices changed while you were reviewing. Check the new total and confirm again."+ });+ return;+ }+ priced = fresh;+ }++ if (!priced?.toPlanVersionId) {+ createNotification({ type: "error", text: "Couldn't price this change. Please try again." });+ return;+ }++ try {+ await upgrade.mutateAsync({+ orgId,+ productId: prod.id,+ plan: plan.tier,+ expectedPlanVersionId: priced.toPlanVersionId,+ prorationDate: priced.prorationDate ?? undefined+ });+ createNotification({+ type: "success",+ text: `You're on ${plan.name}. It may take a moment to update here.`+ });+ onDone();+ } catch {+ // The backend's message is surfaced by the global mutation error handler (reactQuery.tsx).+ await rePreview();+ }+ };++ const pending = upgrade.isPending;++ return (+ <>+ <SheetHeader className="flex-row items-center gap-3.5 border-b pr-12">+ <ProductIcon product={prod} size={40} />+ <div className="min-w-0 flex-1">+ <SheetTitle className="text-base">Upgrade to {plan.name}</SheetTitle>+ <p className="mt-1 text-sm text-muted">+ You'll only pay the difference for the rest of this billing period. Your renewal+ date doesn't change.+ </p>+ </div>+ </SheetHeader>++ <div className="flex flex-col gap-4 overflow-y-auto p-5">+ {isTrialConversion && (+ <Alert variant="info">+ <AlertTitle>This ends your trial early</AlertTitle>+ <AlertDescription>+ You're already using {plan.name} on trial. Upgrading now moves you onto it for+ good and charges the difference from today.+ </AlertDescription>+ </Alert>+ )}++ <div className="flex items-center justify-between gap-4 rounded-lg border border-border bg-card p-4">+ <div className="flex min-w-0 items-center gap-3">+ <ProductIcon product={prod} size={36} />+ <div className="min-w-0">+ <div className="text-sm font-medium text-foreground">{prod.name}</div>+ <div className="mt-0.5 flex items-center gap-1.5 text-xs text-muted">+ <span>{fromPlanName}</span>+ <ArrowRight className="size-3" />+ <span className="font-medium text-foreground">{plan.name}</span>+ </div>+ </div>+ </div>+ </div>++ {plan.feature && (+ <div className="rounded-lg border border-border bg-card p-4 text-xs text-accent">+ {plan.feature}+ </div>+ )}++ <CostSummary>+ <CostSummaryRow+ label="Charged today"+ note="Prorated for the rest of this billing period"+ value={fmtMoney(dueToday, dueToday ? 2 : 0)}+ isCalculating={isCalculating}+ valueClassName="text-base"+ />+ <CostSummaryRow+ label="New recurring total"+ note={renewsOn ? `Billed on ${renewsOn}` : undefined}+ value={fmtMoney(recurring)}+ isCalculating={isCalculating}+ />+ </CostSummary>++ {!isCalculating && additionalCharges !== 0 && (+ <ChargeBreakdown+ prorationAmount={preview.data?.prorationAmount ?? 0}+ additionalCharges={additionalCharges}+ totalDueNow={preview.data?.totalDueNow ?? 0}+ />+ )}+ </div>++ <SheetFooter className="flex-row justify-between border-t">+ <Button variant="ghost" onClick={onBack} isDisabled={pending}>+ <ChevronLeftIcon />+ Back to plans+ </Button>+ <Button+ variant="org"+ onClick={handleUpgrade}+ isDisabled={!selfServe || pending || isCalculating || !versionId}+ isPending={pending}+ >+ {isCalculating+ ? `Upgrade to ${plan.name}`+ : `Upgrade · pay ${fmtMoney(dueToday, dueToday ? 2 : 0)} today`}+ </Button>+ </SheetFooter>+ </>+ );+};diff --git a/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx b/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsxindex 292f486926..8986f6761d 100644--- a/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx+++ b/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx@@ -1,5 +1,5 @@import { CSSProperties, ReactNode } from "react";-import { DollarSign, Package, RefreshCw } from "lucide-react";+import { Clock, DollarSign, Package, RefreshCw } from "lucide-react";import { createNotification } from "@app/components/notifications";import {@@ -69,6 +69,13 @@ const ActiveProductCard = ({const monthlyRecurring = entitlement?.cadence === "annual" ? 0 : (entitlement?.amount ?? 0);const hasPrice = annualCommitted > 0 || monthlyRecurring > 0 || onDemand > 0;const isTrialing = Boolean(entitlement?.isTrialing);+ const trialedPlan = entitlement?.trialPlan+ ? prod.plans.find((plan) => plan.tier === entitlement.trialPlan)+ : undefined;+ const trialPlanName = entitlement?.trialPlan+ ? (entitlement.trialPlanName ?? trialedPlan?.name ?? tierLabel(entitlement.trialPlan))+ : null;+ const trialDaysLeft = entitlement?.trialPlanDaysLeft;// The headline figure steps down a size when a second amount line shares the block.const priceLines = [annualCommitted > 0, monthlyRecurring > 0, onDemand > 0].filter(@@ -156,6 +163,27 @@ const ActiveProductCard = ({</Button>)}</div>+ {trialPlanName && (+ <div className="-mx-4 flex flex-col gap-1.5 border-y border-border bg-warning/5 px-4 py-2.5">+ <div className="flex items-center justify-between gap-3">+ <span className="flex items-center gap-2 text-xs text-foreground">+ <Clock className="size-3.5 shrink-0 text-warning" />+ Trialing {trialPlanName}+ </span>+ {trialDaysLeft !== null && trialDaysLeft !== undefined && (+ <span className="shrink-0 text-xs font-medium text-warning tabular-nums">+ {trialDaysLeft === 0+ ? "Ends today"+ : `${trialDaysLeft} day${trialDaysLeft === 1 ? "" : "s"} left`}+ </span>+ )}+ </div>+ <span className="text-[11px] text-muted">+ {entitlement?.trialPlanEndsAt ? `Trial ends ${entitlement.trialPlanEndsAt} · ` : ""}+ upgrades to {trialPlanName} automatically when it ends+ </span>+ </div>+ )}{sortedDims.length > 0 && (<div className="flex flex-col gap-3.5">{sortedDims.map((dim) => (@@ -196,8 +224,6 @@ const ActiveProductCard = ({type AvailableProductTileProps = {prod: BillingV2CatalogProduct;readOnly?: boolean;- // This product's one-per-product trial is already used up, so it can only be activated, not trialed.- trialUsed?: boolean;onManage: (id: string) => void;onContact: (prod: BillingV2CatalogProduct) => void;};@@ -206,13 +232,12 @@ type AvailableProductTileProps = {const AvailableProductTile = ({prod,readOnly,- trialUsed,onManage,onContact}: AvailableProductTileProps) => {const selfServe = prod.plans.some((plan) => plan.selfServe);const salesLed = prod.plans.some((plan) => plan.salesLed);- const offersTrial = !trialUsed && prod.plans.some((plan) => plan.selfServe && plan.trialable);+ const trialPlan = prod.plans.find((plan) => plan.selfServe && plan.trialable);let action = null;if (!readOnly) {@@ -224,7 +249,9 @@ const AvailableProductTile = ({style={{ "--product-color": prod.color } as CSSProperties}onClick={() => onManage(prod.id)}>- {offersTrial ? "Start a free trial" : "Activate"}+ {trialPlan+ ? `Try free${trialPlan.trialDays > 0 ? ` for ${trialPlan.trialDays} days` : ""}`+ : "Activate"}</Button>);} else if (salesLed) {@@ -355,7 +382,6 @@ export const ProductsCard = ({key={prod.id}prod={prod}readOnly={readOnly}- trialUsed={overview.trialedProductKeys.includes(prod.id)}onManage={onManage}onContact={onContact}/>