Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat: updated the billing ui for commitment setup

=7685bc46f575
diff --git a/backend/src/ee/routes/v1/license-v2-router.ts b/backend/src/ee/routes/v1/license-v2-router.ts
index 28aaa598fa..f26a5a0753 100644
--- a/backend/src/ee/routes/v1/license-v2-router.ts
+++ b/backend/src/ee/routes/v1/license-v2-router.ts
@@ -40,6 +40,7 @@ const BillingV2PlanSchema = z.object({
name: z.string(),
selfServe: z.boolean(),
salesLed: z.boolean(),
+ trialable: z.boolean(),
feature: z.string().optional(),
base: z.object({ monthly: z.number(), annual: z.number() }).optional(),
dims: BillingV2DimSchema.array()
@@ -50,9 +51,7 @@ const BillingV2CatalogProductSchema = z.object({
name: z.string(),
icon: z.string(),
color: z.string(),
- model: z.enum(["seat", "usage", "limit", "flat"]),
addon: z.boolean().optional(),
- desc: z.string(),
tagline: z.string().optional(),
plans: BillingV2PlanSchema.array(),
includes: z.string().array().optional(),
@@ -74,21 +73,32 @@ const BillingV2EntitlementDimSchema = z.object({
noun: z.string(),
unit: z.string(),
metered: z.boolean(),
+ cadence: z.enum(["monthly", "annual"]).nullable(),
used: z.number(),
limit: z.number().nullable(),
- // Present for metered dimensions: the included allowance and per-unit overage rate (dollars).
+ committed: z.number().nullable(),
+ // Rates in dollars. per_resource dims: committedRate (annual) + onDemandRate (monthly overage);
+ // metered dims: rate (per-unit) + freeBand (included). onDemandAmount is the computed monthly
+ // overage cost.
+ committedRate: z.number().optional(),
+ onDemandRate: z.number().optional(),
+ rate: z.number().optional(),
freeBand: z.number().optional(),
- rate: z.number().optional()
+ onDemandAmount: z.number()
});
const BillingV2EntitlementSchema = z.object({
entitled: z.boolean(),
planTier: z.string().optional(),
- // Fixed recurring charge and estimated metered usage for the product (dollars); the headline is
- // their sum. dimensions drives the per-dimension usage bars.
+ // Product cadence + recurring amount + monthly on-demand overage; dimensions drives the usage bars.
+ cadence: z.enum(["monthly", "annual"]).nullable().optional(),
amount: z.number().optional(),
- estimatedUsageAmount: z.number().optional(),
+ onDemandAmount: z.number().optional(),
dimensions: BillingV2EntitlementDimSchema.array().optional(),
+ // Trial state; trialEndsAt is a formatted date string.
+ status: z.string().optional(),
+ isTrialing: z.boolean().optional(),
+ trialEndsAt: z.string().nullable().optional(),
limit: z.number().nullable().optional(),
used: z.number().optional(),
unit: z.string().nullable().optional()
@@ -129,7 +139,7 @@ const BillingV2OverviewSchema = z.object({
.nullable(),
invoices: BillingV2InvoiceSchema.array(),
entitlements: z.record(BillingV2EntitlementSchema),
- estimatedUsageAmount: z.number()
+ onDemandAmount: z.number()
});
const BillingV2PreviewLineSchema = z.object({
@@ -138,32 +148,26 @@ const BillingV2PreviewLineSchema = z.object({
proration: z.boolean()
});
-const BillingV2EstimatedUsageLineSchema = z.object({
- dimension: z.string(),
- unit: z.string(),
- peak: z.number(),
- freeBand: z.number(),
- rate: z.number(),
- amount: z.number()
-});
-
const BillingV2PreviewSchema = z.object({
currency: z.string(),
prorationAmount: z.number(),
nextInvoiceTotal: z.number(),
nextRecurringTotal: z.number(),
prorationDate: z.number(),
- lines: BillingV2PreviewLineSchema.array(),
- // Projected metered usage (dollars) and its breakdown; estimatedTotal = nextRecurringTotal + usage.
- estimatedUsage: z.number(),
- estimatedUsageLines: BillingV2EstimatedUsageLineSchema.array(),
- estimatedTotal: z.number()
+ lines: BillingV2PreviewLineSchema.array()
});
// Subscription mutations mirror the checkout result: the change applies in place and the affected
// subscription id comes back (the DB mirror catches up via webhook, so the UI refetches overview).
const BillingV2MutationResultSchema = z.object({ subscriptionId: z.string().optional() });
+// Per-dimension committed quantities (annual per_resource) and a single commitment quantity change.
+const BillingV2CommitmentsSchema = z.record(z.string().trim(), z.number().int().min(0));
+const BillingV2CommitmentChangeSchema = z.object({
+ dimensionKey: z.string().trim(),
+ quantity: z.number().int().min(1)
+});
+
export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
// Every route is gated on LICENSE_SERVER_V2_MODE="on"; the billing surface is invisible until full v2 cutover.
server.addHook("onRequest", async () => {
@@ -258,6 +262,7 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
productId: z.string().trim(),
plan: z.string().trim().optional(),
cadence: z.enum(["monthly", "annual"]).optional(),
+ commitments: BillingV2CommitmentsSchema.optional(),
email: z.string().trim().email().optional(),
returnPath: ReturnPathSchema
}),
@@ -277,6 +282,7 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
productId: req.body.productId,
plan: req.body.plan,
cadence: req.body.cadence,
+ commitments: req.body.commitments,
email: req.body.email,
returnPath: req.body.returnPath
});
@@ -319,11 +325,16 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
addProductId: z.string().trim().optional(),
plan: z.string().trim().optional(),
cadence: z.enum(["monthly", "annual"]).optional(),
- removeProductId: z.string().trim().optional()
+ commitments: BillingV2CommitmentsSchema.optional(),
+ removeProductId: z.string().trim().optional(),
+ commitmentChanges: BillingV2CommitmentChangeSchema.array().optional()
})
- .refine((b) => Boolean(b.addProductId) || Boolean(b.removeProductId), {
- message: "provide a product to add or remove"
- }),
+ .refine(
+ (b) => Boolean(b.addProductId) || Boolean(b.removeProductId) || Boolean(b.commitmentChanges?.length),
+ {
+ message: "provide a product to add or remove, or a commitment change"
+ }
+ ),
response: {
200: z.object({ preview: BillingV2PreviewSchema })
}
@@ -336,7 +347,9 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
addProductId: req.body.addProductId,
plan: req.body.plan,
cadence: req.body.cadence,
- removeProductId: req.body.removeProductId
+ commitments: req.body.commitments,
+ removeProductId: req.body.removeProductId,
+ commitmentChanges: req.body.commitmentChanges
});
}
});
@@ -352,7 +365,8 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
body: z.object({
productId: z.string().trim(),
plan: z.string().trim().optional(),
- cadence: z.enum(["monthly", "annual"]).optional()
+ cadence: z.enum(["monthly", "annual"]).optional(),
+ commitments: BillingV2CommitmentsSchema.optional()
}),
response: {
200: BillingV2MutationResultSchema
@@ -365,7 +379,8 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
actor: buildActor(req.permission),
productId: req.body.productId,
plan: req.body.plan,
- cadence: req.body.cadence
+ cadence: req.body.cadence,
+ commitments: req.body.commitments
});
}
});
@@ -392,6 +407,65 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "POST",
+ url: "/:organizationId/billing/v2/subscription/commitments",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ params: z.object({ organizationId: z.string().trim() }),
+ body: z.object({
+ // One or more per_resource commitment changes; the service applies them per dimension.
+ changes: BillingV2CommitmentChangeSchema.array().min(1),
+ // Echo the prorationDate from a preview so the billed total matches the confirmation.
+ prorationDate: z.number().optional()
+ }),
+ response: {
+ 200: BillingV2MutationResultSchema
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ return server.services.licenseV2.changeCommitment({
+ orgId: req.params.organizationId,
+ actor: buildActor(req.permission),
+ changes: req.body.changes,
+ prorationDate: req.body.prorationDate
+ });
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:organizationId/billing/v2/trial",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ params: z.object({ organizationId: z.string().trim() }),
+ body: z.object({
+ productId: z.string().trim(),
+ plan: z.string().trim()
+ }),
+ response: {
+ 200: z.object({
+ outcome: z.enum(["trial_started", "collect_payment_method"]),
+ checkoutUrl: z.string().optional()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ return server.services.licenseV2.startTrial({
+ orgId: req.params.organizationId,
+ actor: buildActor(req.permission),
+ productId: req.body.productId,
+ plan: req.body.plan
+ });
+ }
+ });
+
server.route({
method: "POST",
url: "/:organizationId/billing/v2/subscription/cancel",
diff --git a/backend/src/ee/services/license-v2/license-v2-service.ts b/backend/src/ee/services/license-v2/license-v2-service.ts
index d402a287e2..2005c0928c 100644
--- a/backend/src/ee/services/license-v2/license-v2-service.ts
+++ b/backend/src/ee/services/license-v2/license-v2-service.ts
@@ -25,7 +25,6 @@ import {
BillingV2Dim,
BillingV2Entitlement,
BillingV2EntitlementDim,
- BillingV2Model,
BillingV2Overview,
BillingV2Plan,
BillingV2Preview,
@@ -33,12 +32,14 @@ import {
TAddBillingV2PaymentMethodDTO,
TAddBillingV2ProductDTO,
TBillingV2SubscriptionLifecycleDTO,
+ TChangeBillingV2CommitmentDTO,
TCreateBillingV2CheckoutSessionDTO,
TCreateBillingV2PortalSessionDTO,
TGetBillingV2CatalogDTO,
TGetBillingV2OverviewDTO,
TPreviewBillingV2ChangeDTO,
- TRemoveBillingV2ProductDTO
+ TRemoveBillingV2ProductDTO,
+ TStartBillingV2TrialDTO
} from "./license-v2-types";
type TLicenseV2ServiceFactoryDep = {
@@ -62,6 +63,8 @@ type TLicenseV2ServiceFactoryDep = {
| "previewSubscriptionChange"
| "addSubscriptionItems"
| "removeSubscriptionItem"
+ | "changeCommitment"
+ | "startTrial"
| "cancelSubscription"
| "resumeSubscription"
>;
@@ -79,15 +82,6 @@ const FALLBACK_COLOR = "#6b7280";
const IDENTITY_LIMIT_FEATURE_KEY = "max_identities";
const MEMBER_LIMIT_FEATURE_KEY = "member_limit";
-const CATALOG_MODELS: BillingV2Model[] = ["seat", "usage", "limit", "flat"];
-
-const toModel = (model: string): BillingV2Model => {
- if (CATALOG_MODELS.includes(model as BillingV2Model)) {
- return model as BillingV2Model;
- }
- return "usage";
-};
-
// Price kinds we understand; an unknown kind is treated as non-purchasable, never sold as per_unit.
const PER_UNIT_KIND = "per_unit";
const METERED_KIND = "metered";
@@ -214,6 +208,7 @@ const toPlan = (product: TCatalogProduct, plan: TCatalogProduct["plans"][number]
name: plan.name,
selfServe: plan.selfServe,
salesLed: plan.salesLed,
+ trialable: plan.trialable ?? false,
feature: plan.feature,
dims
};
@@ -250,9 +245,7 @@ const toCatalogProduct = (product: TCatalogProduct): BillingV2CatalogProduct =>
name: product.name,
icon: product.icon || FALLBACK_ICON,
color: product.color || FALLBACK_COLOR,
- model: toModel(product.model),
addon: product.addon,
- desc: product.description ?? "",
tagline: product.tagline,
plans,
includes: product.includes,
@@ -260,13 +253,15 @@ const toCatalogProduct = (product: TCatalogProduct): BillingV2CatalogProduct =>
};
};
-// Translates a catalog product into the line items the checkout endpoint expects: the chosen plan's
-// per_unit dimensions at quantity 1. Metered and base lines are added server-side, so a metered-only
-// or base-only plan (e.g. the NHI add-on) checks out with no quantities.
+// Translates a catalog product into the line item the checkout endpoint expects. Monthly is
+// usage-based (no commitment); an annual per_resource line carries the caller-chosen per-dimension
+// commitments. Metered and base lines are added server-side. Returns null when the plan is not
+// purchasable for the cadence (no priced line and no base fee).
const buildCheckoutItems = (
product: TCatalogProduct,
cadence: "monthly" | "annual",
- planTier?: string
+ planTier?: string,
+ commitments?: Record<string, number>
): TCheckoutLineItem[] | null => {
// A requested tier must resolve to a self-serve plan; with none requested, fall back to the first
// paid self-serve plan (the legacy single-"pro" behaviour).
@@ -277,29 +272,20 @@ const buildCheckoutItems = (
return null;
}
- const quantities: Record<string, number> = {};
- const perUnitPrice = plan.prices.find(
- (candidate) => candidate.cadence === cadence && candidate.kind === PER_UNIT_KIND && candidate.unitAmountCents > 0
+ const hasPriceForCadence = plan.prices.some(
+ (candidate) => candidate.cadence === cadence && isKnownPriceKind(candidate.kind)
);
- if (perUnitPrice) {
- quantities[perUnitPrice.dimensionKey] = 1;
- }
-
- const hasMetered = plan.prices.some((candidate) => candidate.cadence === cadence && candidate.kind === METERED_KIND);
const baseForCadence = cadence === "annual" ? plan.basePriceAnnualCents : plan.basePriceMonthlyCents;
const hasBase = baseForCadence !== null && baseForCadence !== undefined;
- if (!perUnitPrice && !hasMetered && !hasBase) {
+ if (!hasPriceForCadence && !hasBase) {
return null;
}
- return [
- {
- productId: product.id,
- plan: plan.tier,
- cadence,
- quantities
- }
- ];
+ const item: TCheckoutLineItem = { productId: product.id, plan: plan.tier, cadence };
+ if (commitments && Object.keys(commitments).length > 0) {
+ item.commitments = commitments;
+ }
+ return [item];
};
export const licenseV2ServiceFactory = ({
@@ -361,13 +347,11 @@ export const licenseV2ServiceFactory = ({
const featureKeys = new Set<string>();
subscription.items.forEach((item) => {
item.dimensions.forEach((dimension) => {
- if (
- !dimension.metered &&
- dimension.featureKey &&
- !usage.has(dimension.featureKey) &&
- counterByFeatureKey.has(dimension.featureKey)
- ) {
- featureKeys.add(dimension.featureKey);
+ // The stable key the dimension caps against is limitKey (contract); older servers send it as
+ // featureKey. Overlay live counts for non-metered dims we have a counter for.
+ const overlayKey = dimension.limitKey ?? dimension.featureKey;
+ if (!dimension.metered && overlayKey && !usage.has(overlayKey) && counterByFeatureKey.has(overlayKey)) {
+ featureKeys.add(overlayKey);
}
});
});
@@ -427,41 +411,53 @@ export const licenseV2ServiceFactory = ({
if (subscription) {
subscription.items.forEach((item) => {
// Resolve the pinned per-dimension contract into a display-ready list: label/noun from the
- // catalog, metered/used/limit/rate/freeBand from the org's pinned subscription version. Money
- // is converted to dollars here so *Cents fields never reach the client. rate/freeBand are set
- // only for metered dimensions; per-unit dimensions get their rate from the catalog client-side.
+ // catalog, everything else from the org's version-pinned subscription. Money is converted to
+ // dollars here so *Cents fields never reach the client. per_resource dims carry committedRate
+ // (annual) + onDemandRate (monthly overage); metered dims carry rate + freeBand.
const dimensions: BillingV2EntitlementDim[] = item.dimensions.map((dimension) => {
const catalogKey = `${item.productId}:${dimension.key}`;
const metered = dimension.metered ?? false;
+ // eslint-disable-next-line no-nested-ternary
+ const cadence = dimension.cadence === "annual" ? "annual" : dimension.cadence === "monthly" ? "monthly" : null;
+ const committed = dimension.committed ?? null;
+ const hasCommittedRate =
+ dimension.committedRateCents !== null && dimension.committedRateCents !== undefined;
+ const hasOnDemandRate = dimension.onDemandRateCents !== null && dimension.onDemandRateCents !== undefined;
const hasRate = dimension.rateCents !== null && dimension.rateCents !== undefined;
const hasFreeBand = dimension.freeBand !== null && dimension.freeBand !== undefined;
+
+ // Overlay live per-org usage for non-metered dims (the server reports 0 for them); metered
+ // dims keep the server's period reading. Matched on the stable limit/feature key.
let used = dimension.used ?? 0;
- const liveUsed = dimension.featureKey ? liveUsageByFeatureKey.get(dimension.featureKey) : undefined;
+ const overlayKey = dimension.limitKey ?? dimension.featureKey;
+ const liveUsed = overlayKey ? liveUsageByFeatureKey.get(overlayKey) : undefined;
if (!metered && liveUsed !== undefined) {
used = liveUsed;
}
+
+ const onDemandRate = hasOnDemandRate ? centsToDollars(dimension.onDemandRateCents) : undefined;
+ // Monthly overage cost: usage above the prepaid commitment at the on-demand rate.
+ const onDemandAmount =
+ committed !== null && onDemandRate !== undefined ? Math.max(0, used - committed) * onDemandRate : 0;
+
return {
key: dimension.key,
label: labelByDimension.get(catalogKey) ?? dimension.key,
noun: nounByDimension.get(catalogKey) ?? dimension.unit ?? dimension.key,
unit: dimension.unit ?? nounByDimension.get(catalogKey) ?? dimension.key,
metered,
+ cadence,
used,
limit: dimension.limit ?? null,
- ...(metered && hasFreeBand ? { freeBand: dimension.freeBand as number } : {}),
- ...(metered && hasRate ? { rate: centsToDollars(dimension.rateCents) } : {})
+ committed,
+ onDemandAmount,
+ ...(hasCommittedRate ? { committedRate: centsToDollars(dimension.committedRateCents) } : {}),
+ ...(onDemandRate !== undefined ? { onDemandRate } : {}),
+ ...(metered && hasRate ? { rate: centsToDollars(dimension.rateCents) } : {}),
+ ...(metered && hasFreeBand ? { freeBand: dimension.freeBand as number } : {})
};
});
- // Estimated metered usage cost for the period: sum of max(0, used - freeBand) * rate over the
- // metered dimensions. Fixed recurring (item.amount) excludes this per the contract.
- const estimatedUsageAmount = dimensions.reduce((sum, dimension) => {
- if (!dimension.metered || dimension.rate === undefined) {
- return sum;
- }
- return sum + Math.max(0, dimension.used - (dimension.freeBand ?? 0)) * dimension.rate;
- }, 0);
-
// Collapsed "most constraining" summary retained for callers that render a single limit line
// (the product sheet). Derived from the resolved dimensions when present, else from the legacy
// limits/quantities maps for older license servers. "Most constraining" = the highest
@@ -501,12 +497,26 @@ export const licenseV2ServiceFactory = ({
const unit = limitKey ? (nounByDimension.get(`${item.productId}:${limitKey}`) ?? null) : null;
+ // Product cadence is annual when any dimension is annually committed, else monthly; drives the
+ // YEARLY/MONTHLY badge and the headline period.
+ // eslint-disable-next-line no-nested-ternary
+ const cadence = dimensions.some((dimension) => dimension.cadence === "annual")
+ ? "annual"
+ : dimensions.length > 0
+ ? "monthly"
+ : null;
+ const onDemandAmount = dimensions.reduce((sum, dimension) => sum + dimension.onDemandAmount, 0);
+
entitlements[item.productId] = {
entitled: true,
planTier: item.plan,
+ cadence,
amount: item.amount !== undefined ? centsToDollars(item.amount) : undefined,
- estimatedUsageAmount,
+ onDemandAmount,
dimensions: dimensions.length > 0 ? dimensions : undefined,
+ status: item.status,
+ isTrialing: item.isTrialing ?? false,
+ trialEndsAt: item.trialEndsAt ? formatDate(item.trialEndsAt) : null,
used,
limit,
unit
@@ -649,10 +659,9 @@ export const licenseV2ServiceFactory = ({
subscription,
new Map([[IDENTITY_LIMIT_FEATURE_KEY, members + identities]])
);
- // Org-wide projected metered usage (dollars): the summary adds this to recurringAmount for the
- // next-month total, so every product's estimate is summed once here.
- const estimatedUsageAmount = Object.values(entitlements).reduce(
- (sum, entitlement) => sum + (entitlement.estimatedUsageAmount ?? 0),
+ // Org-wide monthly on-demand overage (dollars), summed once for the summary's on-demand note.
+ const onDemandAmount = Object.values(entitlements).reduce(
+ (sum, entitlement) => sum + (entitlement.onDemandAmount ?? 0),
0
);
@@ -676,7 +685,7 @@ export const licenseV2ServiceFactory = ({
billingDetails,
invoices,
entitlements,
- estimatedUsageAmount
+ onDemandAmount
};
return { overview };
@@ -711,6 +720,7 @@ export const licenseV2ServiceFactory = ({
productId,
plan,
cadence,
+ commitments,
email,
returnPath
}: TCreateBillingV2CheckoutSessionDTO) => {
@@ -722,7 +732,7 @@ export const licenseV2ServiceFactory = ({
throw new NotFoundError({ message: `Product with ID '${productId}' not found` });
}
- const items = buildCheckoutItems(product, normalizeCadence(cadence), plan);
+ const items = buildCheckoutItems(product, normalizeCadence(cadence), plan, commitments);
if (!items) {
throw new BadRequestError({ message: "This product is not available for self-serve checkout" });
}
@@ -749,14 +759,15 @@ export const licenseV2ServiceFactory = ({
const resolveAddItems = async (
productId: string,
cadence?: "monthly" | "annual",
- plan?: string
+ plan?: string,
+ commitments?: Record<string, number>
): Promise<TCheckoutLineItem[]> => {
const catalog = await licenseClient.getCatalog();
const product = catalog?.products.find((candidate) => candidate.id === productId);
if (!product) {
throw new NotFoundError({ message: `Product with ID '${productId}' not found` });
}
- const items = buildCheckoutItems(product, normalizeCadence(cadence), plan);
+ const items = buildCheckoutItems(product, normalizeCadence(cadence), plan, commitments);
if (!items) {
throw new BadRequestError({ message: "This product is not available for self-serve checkout" });
}
@@ -771,23 +782,27 @@ export const licenseV2ServiceFactory = ({
addProductId,
plan,
cadence,
- removeProductId
+ commitments,
+ removeProductId,
+ commitmentChanges
}: TPreviewBillingV2ChangeDTO): Promise<{ preview: BillingV2Preview }> => {
await ensureManageBilling(orgId, actor);
- if (!addProductId && !removeProductId) {
- throw new BadRequestError({ message: "Provide a product to add or remove" });
+ if (!addProductId && !removeProductId && !(commitmentChanges && commitmentChanges.length > 0)) {
+ throw new BadRequestError({ message: "Provide a product to add or remove, or a commitment change" });
}
const payload: TSubscriptionPreviewPayload = {};
if (addProductId) {
- payload.add = await resolveAddItems(addProductId, cadence, plan);
+ payload.add = await resolveAddItems(addProductId, cadence, plan, commitments);
}
if (removeProductId) {
payload.remove = [removeProductId];
}
+ if (commitmentChanges && commitmentChanges.length > 0) {
+ payload.commitmentChanges = commitmentChanges;
+ }
const preview = await licenseClient.previewSubscriptionChange(orgId, payload);
- const estimatedUsage = centsToDollars(preview.estimatedUsageCents);
return {
preview: {
currency: preview.currency,
@@ -799,35 +814,54 @@ export const licenseV2ServiceFactory = ({
description: line.description,
amount: centsToDollars(line.amount),
proration: line.proration
- })),
- estimatedUsage,
- estimatedUsageLines: preview.estimatedUsageLines.map((line) => ({
- dimension: line.dimension,
- unit: line.unit ?? line.dimension,
- peak: line.peak,
- freeBand: line.freeBand,
- rate: centsToDollars(line.rateCents),
- amount: centsToDollars(line.amountCents)
- })),
- // Fall back to nextRecurringTotal + estimatedUsage when an older server omits estimatedTotal.
- estimatedTotal:
- preview.estimatedTotal !== null && preview.estimatedTotal !== undefined
- ? centsToDollars(preview.estimatedTotal)
- : centsToDollars(preview.nextRecurringTotal) + estimatedUsage
+ }))
}
};
};
// Add a product to an existing active subscription (clears any scheduled cancel server-side). The
// first-purchase / no-subscription path stays on checkoutSession, which opens Stripe Checkout.
- const addProduct = async ({ orgId, actor, productId, plan, cadence }: TAddBillingV2ProductDTO) => {
+ const addProduct = async ({ orgId, actor, productId, plan, cadence, commitments }: TAddBillingV2ProductDTO) => {
await ensureManageBilling(orgId, actor);
- const items = await resolveAddItems(productId, cadence, plan);
+ const items = await resolveAddItems(productId, cadence, plan, commitments);
const result = await licenseClient.addSubscriptionItems(orgId, { items });
await licenseClient.invalidateEntitlements(orgId);
return { subscriptionId: result.subscriptionId };
};
+ // Apply one or more previewed per_resource commitment changes. The License Server's apply endpoint
+ // is single-dimension, so loop per change reusing the previewed prorationDate (assumption C): the
+ // per-dimension prorations, pinned to the same instant, sum to the "charged today" the user saw. A
+ // mid-loop failure leaves earlier changes applied and surfaces the error to retry the rest.
+ const changeCommitment = async ({ orgId, actor, changes, prorationDate }: TChangeBillingV2CommitmentDTO) => {
+ await ensureManageBilling(orgId, actor);
+ if (!changes.length) {
+ throw new BadRequestError({ message: "Provide at least one commitment change" });
+ }
+
+ let subscriptionId: string | undefined;
+ for (const change of changes) {
+ // eslint-disable-next-line no-await-in-loop
+ const result = await licenseClient.changeCommitment(orgId, {
+ dimensionKey: change.dimensionKey,
+ quantity: change.quantity,
+ prorationDate
+ });
+ subscriptionId = result.subscriptionId ?? subscriptionId;
+ }
+ await licenseClient.invalidateEntitlements(orgId);
+ return { subscriptionId };
+ };
+
+ // Start a plan-scoped self-serve trial. trial_started attaches directly; collect_payment_method
+ // returns a setup-mode checkout URL to add a card (the trial then auto-starts via webhook).
+ const startTrial = async ({ orgId, actor, productId, plan }: TStartBillingV2TrialDTO) => {
+ await ensureManageBilling(orgId, actor);
+ const result = await licenseClient.startTrial(orgId, { productKey: productId, planKey: plan });
+ await licenseClient.invalidateEntitlements(orgId);
+ return { outcome: result.outcome, checkoutUrl: result.checkoutUrl };
+ };
+
// Remove a single product from a multi-product subscription, the operation the Stripe Customer
// Portal cannot do. The license server prorates at commit time (Stripe default = now).
const removeProduct = async ({ orgId, actor, productId }: TRemoveBillingV2ProductDTO) => {
@@ -862,6 +896,8 @@ export const licenseV2ServiceFactory = ({
previewChange,
addProduct,
removeProduct,
+ changeCommitment,
+ startTrial,
cancelSubscription,
resumeSubscription
};
diff --git a/backend/src/ee/services/license-v2/license-v2-types.ts b/backend/src/ee/services/license-v2/license-v2-types.ts
index cd7569e042..714082d34e 100644
--- a/backend/src/ee/services/license-v2/license-v2-types.ts
+++ b/backend/src/ee/services/license-v2/license-v2-types.ts
@@ -1,7 +1,5 @@
import { OrgServiceActor } from "@app/lib/types";
-export type BillingV2Model = "seat" | "usage" | "limit" | "flat";
-
export type BillingV2SubState = "active" | "trialing" | "past-due" | "suspended" | "no-subscription";
export type BillingV2Mode = "self-serve" | "managed";
@@ -32,6 +30,8 @@ export type BillingV2Plan = {
name: string;
selfServe: boolean;
salesLed: boolean;
+ // Offers a self-serve trial; the UI shows a trial CTA only when selfServe && trialable.
+ trialable: boolean;
feature?: string;
base?: { monthly: number; annual: number };
dims: BillingV2Dim[];
@@ -42,9 +42,7 @@ export type BillingV2CatalogProduct = {
name: string;
icon: string;
color: string;
- model: BillingV2Model;
addon?: boolean;
- desc: string;
tagline?: string;
plans: BillingV2Plan[];
includes?: string[];
@@ -67,19 +65,26 @@ export type BillingV2Invoice = {
pdfUrl: string;
};
-// One metered/priced dimension of an active product, resolved for display: label/noun come from the
-// catalog, the rest from the org's pinned subscription version. rate/freeBand (dollars/allowance) are
-// present only for metered dimensions; per-unit dimensions get their rate from the catalog client-side.
+// One dimension of an active product, resolved for display from the org's version-pinned subscription
+// (label/noun from the catalog). Rates are in dollars. An annual per_resource dimension carries
+// committed + committedRate (annual) + onDemandRate (monthly overage); a metered dimension carries
+// rate + freeBand. onDemandAmount is the computed monthly overage cost, max(0, used - committed) *
+// onDemandRate (0 unless annually committed with overflow).
export type BillingV2EntitlementDim = {
key: string;
label: string;
noun: string;
unit: string;
metered: boolean;
+ cadence: "monthly" | "annual" | null;
used: number;
limit: number | null;
- freeBand?: number;
+ committed: number | null;
+ committedRate?: number;
+ onDemandRate?: number;
rate?: number;
+ freeBand?: number;
+ onDemandAmount: number;
};
export type BillingV2Entitlement = {
@@ -87,13 +92,21 @@ export type BillingV2Entitlement = {
// Tier the org is currently subscribed to for this product (from the subscription item), so the UI
// can mark the matching plan card as the active one. Absent for feature-only entitlements.
planTier?: string;
- // Fixed recurring charge for this product (dollars); excludes metered usage per the contract.
+ // Product-level cadence: "annual" when any dimension is annually committed, else "monthly". Drives
+ // the YEARLY/MONTHLY badge and the "/ year" vs "/ month" headline period.
+ cadence?: "monthly" | "annual" | null;
+ // Recurring charge for this product (dollars): the annual committed total for a yearly product, the
+ // monthly total for a monthly product (item.amount).
amount?: number;
- // Estimated metered usage cost for the current period (dollars); 0 when the product has no metered
- // usage. The product headline is amount + estimatedUsageAmount.
- estimatedUsageAmount?: number;
+ // Monthly on-demand overage cost across the product's annually-committed dimensions (dollars), for
+ // the "+ $X / mo on-demand" line. 0 when there is no overflow.
+ onDemandAmount?: number;
// Every priced/metered dimension of the product, for the per-dimension usage bars.
dimensions?: BillingV2EntitlementDim[];
+ // Trial state for the product line. trialEndsAt is a formatted date (null when not trialing).
+ status?: string;
+ isTrialing?: boolean;
+ trialEndsAt?: string | null;
limit?: number | null;
used?: number;
// Singular noun for the limited dimension (e.g. "certificate"), resolved from the catalog so the
@@ -133,9 +146,8 @@ export type BillingV2Overview = {
} | null;
invoices: BillingV2Invoice[];
entitlements: Record<string, BillingV2Entitlement>;
- // Estimated metered usage cost for the current period across all products (dollars). Added to
- // recurringAmount for the projected next-month total shown in the summary.
- estimatedUsageAmount: number;
+ // Total monthly on-demand overage across all products (dollars), for the summary's on-demand note.
+ onDemandAmount: number;
};
export type TGetBillingV2OverviewDTO = {
@@ -161,6 +173,8 @@ export type TCreateBillingV2CheckoutSessionDTO = {
// Which plan tier of the product to purchase; defaults to the first paid self-serve plan.
plan?: string;
cadence?: "monthly" | "annual";
+ // Per-dimension committed quantities; required for an annual per_resource line.
+ commitments?: Record<string, number>;
email?: string;
returnPath?: string;
};
@@ -177,17 +191,6 @@ export type BillingV2PreviewLine = {
proration: boolean;
};
-// A projected metered usage line for a change preview. rate/amount are dollars; peak is the projected
-// period usage (peak for a max-aggregated dimension) and freeBand the included allowance.
-export type BillingV2EstimatedUsageLine = {
- dimension: string;
- unit: string;
- peak: number;
- freeBand: number;
- rate: number;
- amount: number;
-};
-
export type BillingV2Preview = {
currency: string;
prorationAmount: number;
@@ -195,11 +198,12 @@ export type BillingV2Preview = {
nextRecurringTotal: number;
prorationDate: number;
lines: BillingV2PreviewLine[];
- // Projected metered usage for the period (dollars) and its per-dimension breakdown. estimatedTotal
- // is nextRecurringTotal + estimatedUsage.
- estimatedUsage: number;
- estimatedUsageLines: BillingV2EstimatedUsageLine[];
- estimatedTotal: number;
+};
+
+// A single per_resource commitment quantity change, shared by preview and apply.
+export type BillingV2CommitmentChange = {
+ dimensionKey: string;
+ quantity: number;
};
export type TPreviewBillingV2ChangeDTO = {
@@ -209,7 +213,11 @@ export type TPreviewBillingV2ChangeDTO = {
// Plan tier of the product being added; defaults to the first paid self-serve plan.
plan?: string;
cadence?: "monthly" | "annual";
+ // Initial per-dimension commitments for an annual add.
+ commitments?: Record<string, number>;
removeProductId?: string;
+ // Per_resource commitment quantity changes to preview against the existing subscription.
+ commitmentChanges?: BillingV2CommitmentChange[];
};
export type TAddBillingV2ProductDTO = {
@@ -219,6 +227,8 @@ export type TAddBillingV2ProductDTO = {
// Plan tier to add; defaults to the first paid self-serve plan.
plan?: string;
cadence?: "monthly" | "annual";
+ // Per-dimension committed quantities; required for an annual per_resource line.
+ commitments?: Record<string, number>;
};
export type TRemoveBillingV2ProductDTO = {
@@ -227,6 +237,22 @@ export type TRemoveBillingV2ProductDTO = {
productId: string;
};
+// Apply one or more previewed per_resource commitment changes. The service loops the single-dimension
+// apply per change, reusing prorationDate so the billed total matches the preview.
+export type TChangeBillingV2CommitmentDTO = {
+ orgId: string;
+ actor: OrgServiceActor;
+ changes: BillingV2CommitmentChange[];
+ prorationDate?: number;
+};
+
+export type TStartBillingV2TrialDTO = {
+ orgId: string;
+ actor: OrgServiceActor;
+ productId: string;
+ plan: string;
+};
+
export type TBillingV2SubscriptionLifecycleDTO = {
orgId: string;
actor: OrgServiceActor;
diff --git a/backend/src/services/license-client/license-client-backends.ts b/backend/src/services/license-client/license-client-backends.ts
index dded387472..3d5483e89c 100644
--- a/backend/src/services/license-client/license-client-backends.ts
+++ b/backend/src/services/license-client/license-client-backends.ts
@@ -14,6 +14,7 @@ import {
TAddSubscriptionItemsPayload,
TBillingProfileResponse,
TCatalogResponse,
+ TChangeCommitmentPayload,
TCheckoutResult,
TCloudPlanResponse,
TCreateCheckoutPayload,
@@ -21,10 +22,13 @@ import {
TEntitlementOrg,
TEntitlementsResponse,
TLicenseClientBackend,
+ trialResultSchema,
TSessionResponse,
+ TStartTrialPayload,
TSubscriptionPreview,
TSubscriptionPreviewPayload,
- TSubscriptionResponse
+ TSubscriptionResponse,
+ TTrialResult
} from "./license-client-types";
// Token-scoped paths for the self-hosted (license-key) backend: the key identifies the license, so
@@ -233,8 +237,15 @@ export const licenseServerBackend = (
return checkoutResultSchema.parse(body);
},
- removeSubscriptionItem: async (orgId: string, productId: string): Promise<TCheckoutResult> => {
+ removeSubscriptionItem: async (
+ orgId: string,
+ productId: string,
+ prorationDate?: number
+ ): Promise<TCheckoutResult> => {
const url = new URL(orgScoped(orgId, `/subscription/items/${encodeURIComponent(productId)}`), serverUrl);
+ if (prorationDate !== undefined) {
+ url.searchParams.set("prorationDate", String(prorationDate));
+ }
const res = await fetch(url, {
method: "DELETE",
headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}` },
@@ -245,6 +256,36 @@ export const licenseServerBackend = (
return checkoutResultSchema.parse(body);
},
+ // Apply a previewed per_resource commitment change; echoes the preview's prorationDate so the
+ // billed amount matches the confirmation the customer saw.
+ changeCommitment: async (orgId: string, payload: TChangeCommitmentPayload): Promise<TCheckoutResult> => {
+ const url = new URL(orgScoped(orgId, "/subscription/commitments"), 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 checkoutResultSchema.parse(body);
+ },
+
+ // Start a plan-scoped self-serve trial. The wire request/response use snake_case; map to camelCase.
+ startTrial: async (orgId: string, payload: TStartTrialPayload): Promise<TTrialResult> => {
+ const url = new URL(orgScoped(orgId, "/billing/trial"), serverUrl);
+ const res = await fetch(url, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}`, "Content-Type": "application/json" },
+ body: JSON.stringify({ product_key: payload.productKey, plan_key: payload.planKey }),
+ redirect: "manual"
+ });
+ await throwIfResponseError(res);
+ const body: unknown = await res.json();
+ const parsed = trialResultSchema.parse(body);
+ return { outcome: parsed.outcome, checkoutUrl: parsed.checkout_url };
+ },
+
cancelSubscription: async (orgId: string): Promise<TCheckoutResult> => {
const url = new URL(orgScoped(orgId, "/subscription/cancel"), serverUrl);
const res = await fetch(url, {
@@ -349,6 +390,8 @@ export const licenseServerSelfHostedBackend = (
previewSubscriptionChange: notSupportedOnSelfHosted("previewSubscriptionChange"),
addSubscriptionItems: notSupportedOnSelfHosted("addSubscriptionItems"),
removeSubscriptionItem: notSupportedOnSelfHosted("removeSubscriptionItem"),
+ changeCommitment: notSupportedOnSelfHosted("changeCommitment"),
+ startTrial: notSupportedOnSelfHosted("startTrial"),
cancelSubscription: notSupportedOnSelfHosted("cancelSubscription"),
resumeSubscription: notSupportedOnSelfHosted("resumeSubscription")
});
diff --git a/backend/src/services/license-client/license-client-types.ts b/backend/src/services/license-client/license-client-types.ts
index 2910bb25a7..921cecc233 100644
--- a/backend/src/services/license-client/license-client-types.ts
+++ b/backend/src/services/license-client/license-client-types.ts
@@ -41,6 +41,8 @@ const catalogPlanSchema = z
name: z.string(),
selfServe: z.boolean(),
salesLed: z.boolean(),
+ // Offers a self-serve trial; a plan is trialable only when selfServe && trialable.
+ trialable: z.boolean().default(false),
feature: z.string().optional(),
basePriceMonthlyCents: z.number().nullish(),
basePriceAnnualCents: z.number().nullish(),
@@ -66,11 +68,9 @@ const catalogProductSchema = z
.object({
id: z.string(),
name: z.string(),
- description: z.string().optional(),
tagline: z.string().optional(),
icon: z.string().optional(),
color: z.string().optional(),
- model: z.string(),
addon: z.boolean(),
dimensions: z.array(catalogDimensionSchema),
plans: z.array(catalogPlanSchema),
@@ -85,20 +85,32 @@ export const catalogResponseSchema = z
})
.passthrough();
-// Per-dimension metered usage on a subscription item. metered/aggregation/freeBand/rateCents come
-// from the org's pinned plan version (not the global feature flag); freeBand/rateCents are only
-// meaningful for metered dimensions. Additive + permissive so an older server (no dimensions) parses.
+// A dimension descriptor on a subscription item (the org's version-pinned billing view). Rates are
+// grandfathered, so they reflect what the customer is billed, not the current catalog price.
+// - cadence is per dimension ("annual" | "monthly" | ""); do NOT infer it from the top-level cadence
+// or from committed != null.
+// - per_resource: committed (prepaid floor) + committedRateCents (annual) + onDemandRateCents (monthly
+// overage). Overflow is max(0, used - committed), costed client-side at onDemandRateCents.
+// - metered: freeBand (included) + rateCents (per-unit). committed/*RateCents are null for metered;
+// rateCents/freeBand are null for per_resource.
+// - limitKey is the stable feature key the dimension caps against; live per-org usage is overlaid on
+// it (dimension keys drift). limit is the optional hard feature cap, independent of committed.
+// Additive + permissive so an older server (no dimensions) parses.
const subscriptionItemDimensionSchema = z
.object({
key: z.string(),
- // Stable feature key the dimension caps against; used to overlay live per-org usage. Dimension
- // keys drift (e.g. a display rename), so usage is matched on this, not on key.
+ limitKey: z.string().nullish(),
+ // Legacy alias for limitKey emitted by pre-contract servers; the service prefers limitKey.
featureKey: z.string().nullish(),
unit: z.string().optional(),
metered: z.boolean().default(false),
aggregation: z.string().optional(),
+ cadence: z.string().nullish(),
used: z.number().default(0),
limit: z.number().nullish(),
+ committed: z.number().nullish(),
+ committedRateCents: z.number().nullish(),
+ onDemandRateCents: z.number().nullish(),
freeBand: z.number().nullish(),
rateCents: z.number().nullish()
})
@@ -111,6 +123,10 @@ const subscriptionItemSchema = z
quantities: z.record(z.string(), z.number()),
limits: z.record(z.string(), z.number()),
amount: z.number().optional(),
+ // Trial state for the product line (from the self-serve trial work).
+ status: z.string().optional(),
+ isTrialing: z.boolean().default(false),
+ trialEndsAt: z.number().nullish(),
dimensions: z.array(subscriptionItemDimensionSchema).default([])
})
.passthrough();
@@ -118,9 +134,11 @@ const subscriptionItemSchema = z
export const subscriptionResponseSchema = z
.object({
status: z.string(),
+ // Top-level cadence is a summary only; per-product cadence lives on each dimension.
cadence: z.string(),
currentPeriodEnd: z.number().nullable(),
recurringTotal: z.number().nullable(),
+ tier: z.string().optional(),
items: z.array(subscriptionItemSchema)
})
.passthrough();
@@ -152,20 +170,6 @@ const subscriptionPreviewLineSchema = z
})
.passthrough();
-// Projected metered cost for the change, computed by the server. estimatedUsageCents is the summed
-// projection; estimatedTotal = nextRecurringTotal + estimatedUsageCents. All additive/nullish so an
-// older server that omits them still parses (the service falls back to nextRecurringTotal).
-const subscriptionPreviewUsageLineSchema = z
- .object({
- dimension: z.string(),
- unit: z.string().optional(),
- peak: z.number().default(0),
- freeBand: z.number().default(0),
- rateCents: z.number().default(0),
- amountCents: z.number().default(0)
- })
- .passthrough();
-
export const subscriptionPreviewResponseSchema = z
.object({
currency: z.string(),
@@ -173,10 +177,7 @@ export const subscriptionPreviewResponseSchema = z
nextInvoiceTotal: z.number(),
nextRecurringTotal: z.number(),
prorationDate: z.number(),
- lines: z.array(subscriptionPreviewLineSchema).default([]),
- estimatedUsageCents: z.number().default(0),
- estimatedUsageLines: z.array(subscriptionPreviewUsageLineSchema).default([]),
- estimatedTotal: z.number().nullish()
+ lines: z.array(subscriptionPreviewLineSchema).default([])
})
.passthrough();
@@ -270,12 +271,23 @@ export type TCheckoutLineItem = {
productId: string;
plan: string;
cadence: string;
- quantities: Record<string, number>;
+ // Legacy per-unit quantities (pre-commitment). Superseded by commitments for an annual per_resource
+ // line; kept optional so the server tolerates either during rollout.
+ quantities?: Record<string, number>;
+ // Per-dimension committed quantity; REQUIRED for an annual per_resource line, omitted for monthly.
+ commitments?: Record<string, number>;
+};
+
+// A single per_resource commitment quantity change (preview) applied post-purchase.
+export type TCommitmentChange = {
+ dimensionKey: string;
+ quantity: number;
};
export type TSubscriptionPreviewPayload = {
add?: TCheckoutLineItem[];
remove?: string[];
+ commitmentChanges?: TCommitmentChange[];
};
export type TAddSubscriptionItemsPayload = {
@@ -292,6 +304,30 @@ export type TCreatePortalPayload = {
returnPath?: string;
};
+// Self-serve apply of a previewed commitment change. prorationDate echoes the preview's value so the
+// billed amount matches; omit to prorate at now.
+export type TChangeCommitmentPayload = {
+ dimensionKey: string;
+ quantity: number;
+ prorationDate?: number;
+};
+
+export type TStartTrialPayload = {
+ productKey: string;
+ planKey: string;
+};
+
+// trial_started: attached directly (card on file). collect_payment_method: caller must complete the
+// setup-mode Checkout at checkoutUrl to add a card; the trial then auto-starts via webhook.
+const trialResultSchema = z
+ .object({
+ outcome: z.enum(["trial_started", "collect_payment_method"]),
+ checkout_url: z.string().optional()
+ })
+ .passthrough();
+export type TTrialResult = { outcome: "trial_started" | "collect_payment_method"; checkoutUrl?: string };
+export { trialResultSchema };
+
export type TLicenseClientBackend = {
fetchEntitlements: (org: TEntitlementOrg) => Promise<TEntitlementsResponse>;
// Ask the license server to recompute/bust its cached entitlements after a license change.
@@ -304,7 +340,11 @@ export type TLicenseClientBackend = {
createPortalSession: (orgId: string, payload: TCreatePortalPayload) => Promise<TSessionResponse>;
previewSubscriptionChange: (orgId: string, payload: TSubscriptionPreviewPayload) => Promise<TSubscriptionPreview>;
addSubscriptionItems: (orgId: string, payload: TAddSubscriptionItemsPayload) => Promise<TCheckoutResult>;
- removeSubscriptionItem: (orgId: string, productId: string) => Promise<TCheckoutResult>;
+ removeSubscriptionItem: (orgId: string, productId: string, prorationDate?: number) => Promise<TCheckoutResult>;
+ // Apply a previewed per_resource commitment change (self-serve).
+ changeCommitment: (orgId: string, payload: TChangeCommitmentPayload) => Promise<TCheckoutResult>;
+ // Start a plan-scoped self-serve trial.
+ startTrial: (orgId: string, payload: TStartTrialPayload) => Promise<TTrialResult>;
cancelSubscription: (orgId: string) => Promise<TCheckoutResult>;
resumeSubscription: (orgId: string) => Promise<TCheckoutResult>;
};
diff --git a/backend/src/services/license-client/license-client.ts b/backend/src/services/license-client/license-client.ts
index 475895459f..cb5cc39ba0 100644
--- a/backend/src/services/license-client/license-client.ts
+++ b/backend/src/services/license-client/license-client.ts
@@ -7,10 +7,12 @@ import { licenseServerBackend, licenseServerSelfHostedBackend } from "./license-
import { entitlementResolverFactory } from "./license-client-cache";
import {
TAddSubscriptionItemsPayload,
+ TChangeCommitmentPayload,
TCreateCheckoutPayload,
TCreatePortalPayload,
TEntitlementOrg,
TLicenseClientBackend,
+ TStartTrialPayload,
TSubscriptionPreviewPayload
} from "./license-client-types";
@@ -159,11 +161,25 @@ export const licenseClientFactory = ({ envConfig, keyStore }: TLicenseClientFact
return backend.addSubscriptionItems(orgId, payload);
};
- const removeSubscriptionItem = async (orgId: string, productId: string) => {
+ const removeSubscriptionItem = async (orgId: string, productId: string, prorationDate?: number) => {
if (!backend) {
throw new Error("license client backend is not configured");
}
- return backend.removeSubscriptionItem(orgId, productId);
+ return backend.removeSubscriptionItem(orgId, productId, prorationDate);
+ };
+
+ const changeCommitment = async (orgId: string, payload: TChangeCommitmentPayload) => {
+ if (!backend) {
+ throw new Error("license client backend is not configured");
+ }
+ return backend.changeCommitment(orgId, payload);
+ };
+
+ const startTrial = async (orgId: string, payload: TStartTrialPayload) => {
+ if (!backend) {
+ throw new Error("license client backend is not configured");
+ }
+ return backend.startTrial(orgId, payload);
};
const cancelSubscription = async (orgId: string) => {
@@ -194,6 +210,8 @@ export const licenseClientFactory = ({ envConfig, keyStore }: TLicenseClientFact
previewSubscriptionChange,
addSubscriptionItems,
removeSubscriptionItem,
+ changeCommitment,
+ startTrial,
cancelSubscription,
resumeSubscription
};
diff --git a/frontend/src/hooks/api/billingV2/index.tsx b/frontend/src/hooks/api/billingV2/index.tsx
index d2428a57f9..8f3518af0a 100644
--- a/frontend/src/hooks/api/billingV2/index.tsx
+++ b/frontend/src/hooks/api/billingV2/index.tsx
@@ -2,27 +2,29 @@ export {
useAddBillingV2PaymentMethod,
useAddBillingV2Product,
useCancelBillingV2Subscription,
+ useChangeBillingV2Commitment,
useCreateBillingV2CheckoutSession,
useCreateBillingV2PortalSession,
usePreviewBillingV2Change,
useRemoveBillingV2Product,
- useResumeBillingV2Subscription
+ useResumeBillingV2Subscription,
+ useStartBillingV2Trial
} from "./mutations";
export { billingV2Keys, useGetBillingV2Catalog, useGetBillingV2Overview } from "./queries";
export type {
BillingV2Cadence,
BillingV2CatalogProduct,
+ BillingV2CommitmentChange,
BillingV2CompareRow,
BillingV2Dim,
BillingV2Entitlement,
BillingV2EntitlementDim,
- BillingV2EstimatedUsageLine,
BillingV2Invoice,
- BillingV2Model,
BillingV2Overview,
BillingV2PaymentMethod,
BillingV2Plan,
BillingV2Preview,
BillingV2PreviewLine,
- BillingV2SubState
+ BillingV2SubState,
+ BillingV2TrialResult
} from "./types";
diff --git a/frontend/src/hooks/api/billingV2/mutations.tsx b/frontend/src/hooks/api/billingV2/mutations.tsx
index 4f1a5d48de..01b6547c0f 100644
--- a/frontend/src/hooks/api/billingV2/mutations.tsx
+++ b/frontend/src/hooks/api/billingV2/mutations.tsx
@@ -7,13 +7,16 @@ import {
BillingV2CheckoutResult,
BillingV2MutationResult,
BillingV2Preview,
+ BillingV2TrialResult,
TAddBillingV2PaymentMethodDTO,
TAddBillingV2ProductDTO,
TBillingV2LifecycleDTO,
+ TChangeBillingV2CommitmentDTO,
TCreateBillingV2CheckoutSessionDTO,
TCreateBillingV2PortalSessionDTO,
TPreviewBillingV2ChangeDTO,
- TRemoveBillingV2ProductDTO
+ TRemoveBillingV2ProductDTO,
+ TStartBillingV2TrialDTO
} from "./types";
export const useCreateBillingV2PortalSession = () => {
@@ -38,12 +41,13 @@ export const useCreateBillingV2CheckoutSession = () => {
productId,
plan,
cadence,
+ commitments,
email,
returnPath
}: TCreateBillingV2CheckoutSessionDTO) => {
const { data } = await apiRequest.post<BillingV2CheckoutResult>(
`/api/v1/organizations/${orgId}/billing/v2/checkout-session`,
- { productId, plan, cadence, email, returnPath }
+ { productId, plan, cadence, commitments, email, returnPath }
);
return data;
@@ -75,13 +79,15 @@ export const usePreviewBillingV2Change = () => {
addProductId,
plan,
cadence,
- removeProductId
+ commitments,
+ removeProductId,
+ commitmentChanges
}: TPreviewBillingV2ChangeDTO) => {
const {
data: { preview }
} = await apiRequest.post<{ preview: BillingV2Preview }>(
`/api/v1/organizations/${orgId}/billing/v2/subscription/preview`,
- { addProductId, plan, cadence, removeProductId }
+ { addProductId, plan, cadence, commitments, removeProductId, commitmentChanges }
);
return preview;
@@ -92,10 +98,52 @@ export const usePreviewBillingV2Change = () => {
export const useAddBillingV2Product = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ orgId, productId, plan, cadence }: TAddBillingV2ProductDTO) => {
+ mutationFn: async ({
+ orgId,
+ productId,
+ plan,
+ cadence,
+ commitments
+ }: TAddBillingV2ProductDTO) => {
const { data } = await apiRequest.post<BillingV2MutationResult>(
`/api/v1/organizations/${orgId}/billing/v2/subscription/items`,
- { productId, plan, cadence }
+ { productId, plan, cadence, commitments }
+ );
+
+ return data;
+ },
+ onSuccess: (_data, { orgId }) => {
+ queryClient.invalidateQueries({ queryKey: billingV2Keys.overview(orgId) });
+ }
+ });
+};
+
+// Apply one or more previewed per_resource commitment changes (the backend loops per dimension).
+export const useChangeBillingV2Commitment = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ orgId, changes, prorationDate }: TChangeBillingV2CommitmentDTO) => {
+ const { data } = await apiRequest.post<BillingV2MutationResult>(
+ `/api/v1/organizations/${orgId}/billing/v2/subscription/commitments`,
+ { changes, prorationDate }
+ );
+
+ return data;
+ },
+ onSuccess: (_data, { orgId }) => {
+ queryClient.invalidateQueries({ queryKey: billingV2Keys.overview(orgId) });
+ }
+ });
+};
+
+// Start a plan-scoped self-serve trial. collect_payment_method returns a Stripe setup checkout URL.
+export const useStartBillingV2Trial = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ orgId, productId, plan }: TStartBillingV2TrialDTO) => {
+ const { data } = await apiRequest.post<BillingV2TrialResult>(
+ `/api/v1/organizations/${orgId}/billing/v2/trial`,
+ { productId, plan }
);
return data;
diff --git a/frontend/src/hooks/api/billingV2/types.ts b/frontend/src/hooks/api/billingV2/types.ts
index dd37c8551c..b7bc9deb76 100644
--- a/frontend/src/hooks/api/billingV2/types.ts
+++ b/frontend/src/hooks/api/billingV2/types.ts
@@ -1,5 +1,3 @@
-export type BillingV2Model = "seat" | "usage" | "limit" | "flat";
-
export type BillingV2Cadence = "monthly" | "annual";
export type BillingV2Dim = {
@@ -27,6 +25,8 @@ export type BillingV2Plan = {
name: string;
selfServe: boolean;
salesLed: boolean;
+ // Offers a self-serve trial; the trial CTA shows only when selfServe && trialable.
+ trialable: boolean;
feature?: string;
base?: { monthly: number; annual: number };
dims: BillingV2Dim[];
@@ -37,9 +37,7 @@ export type BillingV2CatalogProduct = {
name: string;
icon: string;
color: string;
- model: BillingV2Model;
addon?: boolean;
- desc: string;
tagline?: string;
plans: BillingV2Plan[];
includes?: string[];
@@ -69,32 +67,45 @@ export type BillingV2Invoice = {
pdfUrl: string | null;
};
-// One priced/metered dimension of an active product, resolved for display by the backend. rate and
-// freeBand (dollars/allowance) are present only for metered dimensions; per-unit dimensions get their
-// rate from the catalog on the client.
+// One dimension of an active product, resolved for display by the backend (rates in dollars). An
+// annual per_resource dimension carries committed + committedRate (annual) + onDemandRate (monthly
+// overage); a metered dimension carries rate + freeBand. onDemandAmount is the computed monthly
+// overage cost (max(0, used - committed) * onDemandRate).
export type BillingV2EntitlementDim = {
key: string;
label: string;
noun: string;
unit: string;
metered: boolean;
+ cadence: BillingV2Cadence | null;
used: number;
limit: number | null;
- freeBand?: number;
+ committed: number | null;
+ committedRate?: number;
+ onDemandRate?: number;
rate?: number;
+ freeBand?: number;
+ onDemandAmount: number;
};
export type BillingV2Entitlement = {
entitled: boolean;
// Tier the org is currently subscribed to for this product; lets the UI mark the active plan card.
planTier?: string;
- // Fixed recurring charge for this product (dollars); excludes metered usage.
+ // Product cadence: "annual" when any dimension is annually committed, else "monthly". Drives the
+ // YEARLY/MONTHLY badge and the "/ year" vs "/ month" headline period.
+ cadence?: BillingV2Cadence | null;
+ // Recurring charge for the product (dollars): annual committed total for yearly, monthly for monthly.
amount?: number;
- // Estimated metered usage cost for the current period (dollars). The product headline is
- // amount + estimatedUsageAmount.
- estimatedUsageAmount?: number;
+ // Monthly on-demand overage across the product's committed dimensions (dollars), for the
+ // "+ $X / mo on-demand" line.
+ onDemandAmount?: number;
// Every priced/metered dimension of the product, for the per-dimension usage bars.
dimensions?: BillingV2EntitlementDim[];
+ // Trial state; trialEndsAt is a formatted date string (null when not trialing).
+ status?: string;
+ isTrialing?: boolean;
+ trialEndsAt?: string | null;
limit?: number | null;
used?: number;
// Singular noun for the limited dimension (e.g. "certificate"); rendered, pluralized, beside the count.
@@ -115,9 +126,8 @@ export type BillingV2Overview = {
identities: number;
identityLimit: number | null;
};
- // Projected metered usage across all products (dollars); added to recurringAmount for the summary's
- // next-month total.
- estimatedUsageAmount: number;
+ // Total monthly on-demand overage across all products (dollars).
+ onDemandAmount: number;
payment: BillingV2PaymentMethod;
billingDetails: {
name: string;
@@ -152,6 +162,8 @@ export type TCreateBillingV2CheckoutSessionDTO = {
productId: string;
plan?: string;
cadence?: BillingV2Cadence;
+ // Per-dimension committed quantities; required for an annual per_resource line.
+ commitments?: Record<string, number>;
email?: string;
returnPath?: string;
};
@@ -167,17 +179,6 @@ export type BillingV2PreviewLine = {
proration: boolean;
};
-// A projected metered usage line for a change preview. rate/amount are dollars; peak is the projected
-// period usage and freeBand the included allowance.
-export type BillingV2EstimatedUsageLine = {
- dimension: string;
- unit: string;
- peak: number;
- freeBand: number;
- rate: number;
- amount: number;
-};
-
// prorationAmount is signed: positive is charged now (an add), negative is a credit toward the next
// invoice (a removal). prorationDate is the timestamp the preview was computed at, for display only.
export type BillingV2Preview = {
@@ -187,23 +188,28 @@ export type BillingV2Preview = {
nextRecurringTotal: number;
prorationDate: number;
lines: BillingV2PreviewLine[];
- // Projected metered usage for the period (dollars) and its breakdown; estimatedTotal is
- // nextRecurringTotal + estimatedUsage.
- estimatedUsage: number;
- estimatedUsageLines: BillingV2EstimatedUsageLine[];
- estimatedTotal: number;
};
export type BillingV2MutationResult = {
subscriptionId?: string;
};
+// A single per_resource commitment quantity change, shared by preview and apply.
+export type BillingV2CommitmentChange = {
+ dimensionKey: string;
+ quantity: number;
+};
+
export type TPreviewBillingV2ChangeDTO = {
orgId: string;
addProductId?: string;
plan?: string;
cadence?: BillingV2Cadence;
+ // Initial per-dimension commitments for an annual add.
+ commitments?: Record<string, number>;
removeProductId?: string;
+ // Per_resource commitment quantity changes to preview against the existing subscription.
+ commitmentChanges?: BillingV2CommitmentChange[];
};
export type TAddBillingV2ProductDTO = {
@@ -211,6 +217,8 @@ export type TAddBillingV2ProductDTO = {
productId: string;
plan?: string;
cadence?: BillingV2Cadence;
+ // Per-dimension committed quantities; required for an annual per_resource line.
+ commitments?: Record<string, number>;
};
export type TRemoveBillingV2ProductDTO = {
@@ -218,6 +226,27 @@ export type TRemoveBillingV2ProductDTO = {
productId: string;
};
+// Apply one or more previewed per_resource commitment changes; the backend loops the per-dimension
+// apply, reusing prorationDate so the billed total matches the preview.
+export type TChangeBillingV2CommitmentDTO = {
+ orgId: string;
+ changes: BillingV2CommitmentChange[];
+ prorationDate?: number;
+};
+
+export type TStartBillingV2TrialDTO = {
+ orgId: string;
+ productId: string;
+ plan: string;
+};
+
+// trial_started: attached directly. collect_payment_method: complete the setup Checkout at checkoutUrl
+// to add a card (the trial then auto-starts via webhook).
+export type BillingV2TrialResult = {
+ outcome: "trial_started" | "collect_payment_method";
+ checkoutUrl?: string;
+};
+
export type TBillingV2LifecycleDTO = {
orgId: string;
};
diff --git a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
index 793fb0f064..01fa2b5c54 100644
--- a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
@@ -14,17 +14,15 @@ import {
} from "@app/context";
import {
useAddBillingV2PaymentMethod,
- useCreateBillingV2CheckoutSession,
useCreateBillingV2PortalSession,
useGetBillingV2Catalog,
useGetBillingV2Overview
} from "@app/hooks/api";
-import { AddProductModal } from "./components/AddProductModal";
import { BillingV2RenderState, Overview } from "./components/Overview";
import { ProductSheet } from "./components/ProductSheet";
import { RemoveProductModal } from "./components/RemoveProductModal";
-import { catalogById, intervalToCadence } from "./billing-v2-data";
+import { catalogById } from "./billing-v2-data";
const CONTACT_SALES_URL = "https://infisical.com/talk-to-us";
@@ -45,13 +43,10 @@ export const BillingV2Page = () => {
const { data: overview, isPending, isError, refetch } = useGetBillingV2Overview(orgId);
const { data: catalog = [] } = useGetBillingV2Catalog(orgId);
const createPortalSession = useCreateBillingV2PortalSession();
- const createCheckoutSession = useCreateBillingV2CheckoutSession();
const addPaymentMethod = useAddBillingV2PaymentMethod();
const [flow, setFlow] = useState<BillingV2Flow | null>(null);
const [removeProdId, setRemoveProdId] = useState<string | null>(null);
- // The product to add in place plus the chosen plan tier (an existing-subscription upgrade path).
- const [addProd, setAddProd] = useState<{ id: string; plan: string } | null>(null);
// Stripe redirects back with ?checkout=success|canceled; surface the outcome and refresh state.
useEffect(() => {
@@ -81,9 +76,7 @@ export const BillingV2Page = () => {
subState = "loading";
}
- const cadence = intervalToCadence(overview?.interval ?? null);
const removeProd = removeProdId ? catalogById(catalog, removeProdId) : undefined;
- const addProdProduct = addProd ? catalogById(catalog, addProd.id) : undefined;
const close = () => setFlow(null);
@@ -99,64 +92,23 @@ export const BillingV2Page = () => {
}
};
- const redirectToCheckout = async (productId: string, plan: string) => {
- const result = await createCheckoutSession.mutateAsync({
- orgId,
- productId,
- plan,
- cadence,
- email: billingEmail,
- returnPath: window.location.pathname
- });
-
- // The product was added straight to the existing subscription; no Stripe redirect needed.
- if (result.outcome === "subscription_updated") {
- close();
- createNotification({
- type: "success",
- text: "Product added to your subscription. It may take a moment to appear here."
- });
- refetch();
- return;
- }
-
- if (result.checkoutUrl) {
- window.location.href = result.checkoutUrl;
- return;
- }
-
- createNotification({ type: "error", text: "Failed to start checkout." });
- };
-
const onManageSubscription = () => {
redirectToPortal();
};
+ // Opening a product (Manage or Activate) shows its sheet; activation, commitment changes, and trials
+ // are all handled inside the sheet against its own mutations.
const onUpgrade = (productId: string) => {
setFlow({ type: "sheet", prodId: productId });
};
- // Owned products are managed in the Stripe portal. A new product is added in place with a proration
- // confirmation when a subscription already exists; a first-time customer goes through Stripe Checkout.
+ // A first-time customer checks out through Stripe; an org with a live subscription has products
+ // added / changed in place. Trialing and past-due orgs still have a usable subscription.
const hasActiveSubscription =
overview?.subState === "active" ||
overview?.subState === "trialing" ||
overview?.subState === "past-due";
- const onSheetManage = async (productId: string, plan: string) => {
- const isEntitled = Boolean(overview?.entitlements[productId]?.entitled);
- if (isEntitled) {
- await redirectToPortal();
- return;
- }
- if (hasActiveSubscription) {
- close();
- setAddProd({ id: productId, plan });
- return;
- }
- await redirectToCheckout(productId, plan);
- };
-
const onUpdatePayment = async () => {
try {
const url = await addPaymentMethod.mutateAsync({
@@ -182,8 +134,6 @@ export const BillingV2Page = () => {
refetch();
};
- const sheetRedirecting = createPortalSession.isPending || createCheckoutSession.isPending;
-
// A managed (self-hosted licensed) org can't self-serve through Stripe; its plan is set by the license.
const isManaged = overview?.mode === "managed";
const pageDescription = isManaged
@@ -223,13 +173,14 @@ export const BillingV2Page = () => {
{flow?.type === "sheet" && (
<ProductSheet
- prodId={flow.prodId}
+ orgId={orgId}
prod={catalogById(catalog, flow.prodId)}
entitlement={overview?.entitlements[flow.prodId]}
- cadence={cadence}
- redirecting={sheetRedirecting}
+ hasActiveSubscription={hasActiveSubscription}
+ billingEmail={billingEmail}
+ returnPath={window.location.pathname}
+ renewsOn={overview?.nextBillingDate ?? null}
onClose={close}
- onManage={onSheetManage}
onRemove={setRemoveProdId}
onContact={() => {
close();
@@ -249,16 +200,6 @@ export const BillingV2Page = () => {
}}
/>
)}
-
- {addProdProduct && addProd && (
- <AddProductModal
- orgId={orgId}
- product={addProdProduct}
- plan={addProd.plan}
- cadence={cadence}
- onClose={() => setAddProd(null)}
- />
- )}
</div>
);
};
diff --git a/frontend/src/pages/organization/BillingV2Page/billing-v2-data.ts b/frontend/src/pages/organization/BillingV2Page/billing-v2-data.ts
index 6e56d02c73..971cd148d6 100644
--- a/frontend/src/pages/organization/BillingV2Page/billing-v2-data.ts
+++ b/frontend/src/pages/organization/BillingV2Page/billing-v2-data.ts
@@ -78,41 +78,28 @@ export const isMeteredCadence = (dim: BillingV2Dim, cad: BillingV2Cadence): bool
return dim.meteredMonthly ?? false;
};
-// Fixed recurring + estimated metered usage for a product (dollars). This is the product card
-// headline; the metered portion is a projection, so callers show an "est." qualifier when it's > 0.
-export const productTotal = (entitlement?: BillingV2Entitlement): number =>
- (entitlement?.amount ?? 0) + (entitlement?.estimatedUsageAmount ?? 0);
-
-// The per-unit rate to display for a dimension (dollars): the pinned metered rate when the backend
-// sent one, otherwise the catalog's per-unit price for the active cadence. null when neither exists.
-export const dimRate = (
- dim: BillingV2EntitlementDim,
- product: BillingV2CatalogProduct | undefined,
- planTier: string | undefined,
- cadence: BillingV2Cadence
-): number | null => {
- if (dim.rate !== undefined && dim.rate !== null) {
- return dim.rate;
- }
- const plan = product?.plans.find((candidate) => candidate.tier === planTier) ?? product?.plans[0];
- const catalogDim = plan?.dims.find((candidate) => candidate.key === dim.key);
- if (!catalogDim) {
- return null;
- }
- return unitPrice(catalogDim, cadence);
-};
+// "/ year" or "/ month" for a product's cadence.
+export const cadencePeriod = (cadence: BillingV2Cadence | null | undefined): string =>
+ cadence === "annual" ? "year" : "month";
+
+// An annually-committed per_resource dimension: usage above `committed` is billed monthly on-demand.
+export const dimAnnualCommitted = (dim: BillingV2EntitlementDim): boolean =>
+ dim.cadence === "annual" && dim.committed !== null;
-// The billed quantity for a dimension: for a metered dimension it's the overage above the included
-// free band; for a per-unit dimension it's the used count.
-export const dimBilledQuantity = (dim: BillingV2EntitlementDim): number => {
+// Per-unit monthly rate for a dimension (dollars): metered uses its per-unit rate; a monthly
+// per_resource (and an annual dimension's overage) uses the on-demand rate.
+export const dimMonthlyRate = (dim: BillingV2EntitlementDim): number => {
if (dim.metered) {
- return Math.max(0, dim.used - (dim.freeBand ?? 0));
+ return dim.rate ?? 0;
}
- return dim.used;
+ return dim.onDemandRate ?? dim.rate ?? 0;
};
-// Fill percentage (0-100) for a dimension's usage bar, or null when there's no finite cap to fill
-// against (unlimited or usage-based). Mirrors the utilization semantics used server-side.
+// On-demand overflow quantity for an annually-committed dimension (0 otherwise).
+export const dimOnDemandQuantity = (dim: BillingV2EntitlementDim): number =>
+ dimAnnualCommitted(dim) ? Math.max(0, dim.used - (dim.committed ?? 0)) : 0;
+
+// Fill percentage (0-100) for a simple usage bar, or null when there's no finite cap to fill against.
export const usagePct = (used: number, limit: number | null): number | null => {
if (limit === null || limit <= 0) {
return null;
@@ -120,15 +107,28 @@ export const usagePct = (used: number, limit: number | null): number | null => {
return Math.min(100, (used / limit) * 100);
};
-// Human-readable price breakdown for a product card, e.g. "1 CA × $500 + 84 certificates × $3" or
-// "Flat · up to 10 resources". Priced/metered dimensions read as "{qty} {units} × ${rate}"; flat
-// dimensions (a cap with no per-unit rate) read as "up to {limit} {units}". Returns null when nothing
-// is priced. Illustrative only: the authoritative total is the product headline (amount + usage).
-export const productBreakdown = (
- entitlement: BillingV2Entitlement | undefined,
- product: BillingV2CatalogProduct | undefined,
- cadence: BillingV2Cadence
-): string | null => {
+// Segments for a dimension's usage bar. Annual committed: the bar spans the greater of committed and
+// used; the committed portion is blue and any overflow orange. Monthly: a single blue used/limit fill.
+export const dimBarSegments = (
+ dim: BillingV2EntitlementDim
+): { committedPct: number; onDemandPct: number } => {
+ if (dimAnnualCommitted(dim)) {
+ const committed = dim.committed ?? 0;
+ const denominator = Math.max(committed, dim.used, 1);
+ const committedFill = Math.min(committed, dim.used);
+ return {
+ committedPct: (committedFill / denominator) * 100,
+ onDemandPct: (Math.max(0, dim.used - committed) / denominator) * 100
+ };
+ }
+ return { committedPct: usagePct(dim.used, dim.limit) ?? 0, onDemandPct: 0 };
+};
+
+// Headline price breakdown for a product card, e.g. "55 seats committed × $20",
+// "1 CA committed × $435 + 100 certificates committed × $3", "140 active contributors × $7", or
+// "Flat · up to 10 resources". Annual committed dims read as "{committed} {units} committed × $rate";
+// monthly priced dims as "{used} {units} × $rate"; a capped flat dim as "up to {limit} {units}".
+export const productBreakdown = (entitlement?: BillingV2Entitlement): string | null => {
const dims = entitlement?.dimensions ?? [];
if (dims.length === 0) {
return null;
@@ -137,11 +137,20 @@ export const productBreakdown = (
const pricedTerms: string[] = [];
const flatTerms: string[] = [];
dims.forEach((dim) => {
- const rate = dimRate(dim, product, entitlement?.planTier, cadence);
- if (rate !== null && rate > 0) {
- const qty = dimBilledQuantity(dim);
+ if (dimAnnualCommitted(dim) && dim.committedRate) {
+ const committed = dim.committed ?? 0;
+ pricedTerms.push(
+ `${committed.toLocaleString()} ${pluralizeUnit(dim.noun)} committed × ${fmtMoney(dim.committedRate)}`
+ );
+ return;
+ }
+ const rate = dimMonthlyRate(dim);
+ if (rate > 0) {
+ const qty = dim.metered ? Math.max(0, dim.used - (dim.freeBand ?? 0)) : dim.used;
pricedTerms.push(`${qty.toLocaleString()} ${pluralizeUnit(dim.noun)} × ${fmtMoney(rate)}`);
- } else if (dim.limit !== null) {
+ return;
+ }
+ if (dim.limit !== null) {
flatTerms.push(`up to ${dim.limit.toLocaleString()} ${pluralizeUnit(dim.noun)}`);
}
});
diff --git a/frontend/src/pages/organization/BillingV2Page/components/ActivateView.tsx b/frontend/src/pages/organization/BillingV2Page/components/ActivateView.tsx
new file mode 100644
index 0000000000..7320dda53f
--- /dev/null
+++ b/frontend/src/pages/organization/BillingV2Page/components/ActivateView.tsx
@@ -0,0 +1,291 @@
+import { useEffect, useMemo, useState } from "react";
+import { ChevronLeftIcon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import { Badge, Button, SheetFooter, SheetHeader, SheetTitle } from "@app/components/v3";
+import { cn } from "@app/components/v3/utils";
+import {
+ BillingV2Cadence,
+ BillingV2CatalogProduct,
+ BillingV2Dim,
+ BillingV2Plan,
+ useAddBillingV2Product,
+ useCreateBillingV2CheckoutSession,
+ usePreviewBillingV2Change
+} from "@app/hooks/api";
+
+import { fmtMoney } from "../billing-v2-data";
+import { ProductIcon, Stepper } from "./shared";
+
+type Props = {
+ orgId: string;
+ prod: BillingV2CatalogProduct;
+ plan: BillingV2Plan;
+ hasActiveSubscription: boolean;
+ billingEmail?: string;
+ returnPath: string;
+ renewsOn: string | null;
+ onBack: () => void;
+ onDone: () => void;
+};
+
+// A per_resource dimension that can be committed annually (has an annual per-unit price).
+const isCommittable = (dim: BillingV2Dim): boolean => dim.annual > 0 && !dim.meteredAnnual;
+
+// The plan's monthly headline price (base fee, else the first priced dimension's monthly rate).
+const monthlyHeadline = (plan: BillingV2Plan): number => {
+ if (plan.base) {
+ return plan.base.monthly;
+ }
+ const dim = plan.dims.find((d) => d.monthly > 0);
+ return dim ? dim.monthly : 0;
+};
+
+type CadenceOptionProps = {
+ active: boolean;
+ title: string;
+ subtitle: string;
+ badge?: string;
+ onClick: () => void;
+};
+
+const CadenceOption = ({ active, title, subtitle, badge, onClick }: CadenceOptionProps) => (
+ <button
+ type="button"
+ onClick={onClick}
+ className={cn(
+ "flex flex-1 flex-col gap-1 rounded-lg border p-4 text-left transition-colors",
+ active ? "border-org bg-org/5" : "border-border hover:border-foreground/20"
+ )}
+ >
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium text-foreground">{title}</span>
+ {badge && <Badge variant="success">{badge}</Badge>}
+ </div>
+ <span className="text-xs text-muted">{subtitle}</span>
+ </button>
+);
+
+// Activate a product on the chosen plan. Monthly is usage-based (rate only, no commitment); yearly
+// asks for a committed quantity per per_resource dimension. The cost is previewed before confirming;
+// an existing subscription is updated in place, a brand-new customer goes through Stripe Checkout.
+export const ActivateView = ({
+ orgId,
+ prod,
+ plan,
+ hasActiveSubscription,
+ billingEmail,
+ returnPath,
+ renewsOn,
+ onBack,
+ onDone
+}: Props) => {
+ const committable = useMemo(() => plan.dims.filter(isCommittable), [plan.dims]);
+ const supportsAnnual = committable.length > 0 || Boolean(plan.base && plan.base.annual > 0);
+ const supportsMonthly = plan.dims.some((d) => d.monthly > 0) || Boolean(plan.base);
+
+ const [cadence, setCadence] = useState<BillingV2Cadence>(supportsMonthly ? "monthly" : "annual");
+ const [commitments, setCommitments] = useState<Record<string, number>>(() =>
+ Object.fromEntries(committable.map((dim) => [dim.key, Math.max(dim.included, 1)]))
+ );
+
+ const preview = usePreviewBillingV2Change();
+ const addProduct = useAddBillingV2Product();
+ const checkout = useCreateBillingV2CheckoutSession();
+
+ const commitmentsForCadence = cadence === "annual" ? commitments : undefined;
+ const commitmentsKey = JSON.stringify(commitmentsForCadence ?? {});
+
+ // Re-price when the cadence or a committed quantity changes.
+ useEffect(() => {
+ preview.mutate({
+ orgId,
+ addProductId: prod.id,
+ plan: plan.tier,
+ cadence,
+ commitments: commitmentsForCadence
+ });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [orgId, prod.id, plan.tier, cadence, commitmentsKey]);
+
+ const dueToday = preview.data ? Math.max(preview.data.prorationAmount, 0) : 0;
+ const recurring = preview.data?.nextRecurringTotal ?? 0;
+ const period = cadence === "annual" ? "year" : "month";
+ const pending = addProduct.isPending || checkout.isPending;
+
+ // Savings badge on the yearly option: how much cheaper the annual rate is vs paying monthly.
+ const savingsPct = useMemo(() => {
+ const monthly = monthlyHeadline(plan);
+ const annual = plan.base
+ ? plan.base.annual
+ : (plan.dims.find((d) => d.annual > 0)?.annual ?? 0);
+ if (monthly <= 0 || annual <= 0) {
+ return null;
+ }
+ const pct = Math.round((1 - annual / (monthly * 12)) * 100);
+ return pct > 0 ? pct : null;
+ }, [plan]);
+
+ const handleActivate = async () => {
+ try {
+ if (hasActiveSubscription) {
+ await addProduct.mutateAsync({
+ orgId,
+ productId: prod.id,
+ plan: plan.tier,
+ cadence,
+ commitments: commitmentsForCadence
+ });
+ createNotification({
+ type: "success",
+ text: `${prod.name} activated. It may take a moment to update here.`
+ });
+ onDone();
+ return;
+ }
+ const result = await checkout.mutateAsync({
+ orgId,
+ productId: prod.id,
+ plan: plan.tier,
+ cadence,
+ commitments: commitmentsForCadence,
+ email: billingEmail,
+ returnPath
+ });
+ if (result.outcome === "subscription_updated") {
+ createNotification({ type: "success", text: `${prod.name} activated.` });
+ onDone();
+ return;
+ }
+ if (result.checkoutUrl) {
+ window.location.href = result.checkoutUrl;
+ return;
+ }
+ createNotification({ type: "error", text: "Failed to start checkout." });
+ } catch {
+ createNotification({ type: "error", text: `Failed to activate ${prod.name}.` });
+ }
+ };
+
+ 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">Activate {prod.name}</SheetTitle>
+ <p className="mt-1 text-sm text-muted">
+ Choose monthly or yearly billing, set your units, and see the cost before you confirm.
+ </p>
+ </div>
+ </SheetHeader>
+
+ <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-5">
+ {supportsMonthly && supportsAnnual && (
+ <div className="flex flex-col gap-2">
+ <span className="text-sm font-medium text-foreground">Billing cadence</span>
+ <div className="flex gap-3">
+ <CadenceOption
+ active={cadence === "monthly"}
+ title="Monthly"
+ subtitle="Usage-based"
+ onClick={() => setCadence("monthly")}
+ />
+ <CadenceOption
+ active={cadence === "annual"}
+ title="Yearly"
+ subtitle="Commit & save"
+ badge={savingsPct ? `SAVE ~${savingsPct}%` : undefined}
+ onClick={() => setCadence("annual")}
+ />
+ </div>
+ <span className="text-xs text-muted">
+ {cadence === "monthly"
+ ? "Pay for what you provision each month. No commitment, scale up or down freely."
+ : "Pre-buy units for the year at the annual rate. Usage above your commitment is billed monthly on-demand."}
+ </span>
+ </div>
+ )}
+
+ {cadence === "annual" && committable.length > 0
+ ? committable.map((dim) => (
+ <div
+ key={dim.key}
+ className="flex items-center justify-between gap-4 rounded-lg border border-border bg-card p-4"
+ >
+ <div className="min-w-0">
+ <div className="text-sm font-medium text-foreground">
+ {dim.label} · committed for the year
+ </div>
+ <div className="mt-0.5 text-xs text-muted">
+ {fmtMoney(dim.annual)} / {dim.noun} / yr committed
+ </div>
+ </div>
+ <Stepper
+ value={commitments[dim.key] ?? 0}
+ min={0}
+ onChange={(value) => setCommitments((prev) => ({ ...prev, [dim.key]: value }))}
+ />
+ </div>
+ ))
+ : null}
+
+ {cadence === "monthly" && (
+ <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} · {plan.name}
+ </div>
+ {plan.feature && <div className="mt-0.5 text-xs text-muted">{plan.feature}</div>}
+ </div>
+ </div>
+ <span className="shrink-0 text-sm font-semibold text-foreground tabular-nums">
+ {fmtMoney(monthlyHeadline(plan))} / month
+ </span>
+ </div>
+ )}
+
+ <div className="flex flex-col rounded-lg border border-border">
+ <div className="flex items-center justify-between border-b border-border bg-mineshaft-700/40 p-4">
+ <div>
+ <div className="text-sm text-foreground">Charged today</div>
+ <div className="text-xs text-muted">
+ {preview.isPending ? "Calculating…" : "Prorated onto your shared billing date"}
+ </div>
+ </div>
+ <span className="text-lg font-semibold text-info tabular-nums">
+ {fmtMoney(dueToday, dueToday ? 2 : 0)}
+ </span>
+ </div>
+ <div className="flex items-center justify-between p-4">
+ <div>
+ <div className="text-sm text-foreground">
+ {cadence === "annual" ? "Annual commitment" : "Monthly total"}
+ </div>
+ {renewsOn && <div className="text-xs text-muted">Billed on {renewsOn}</div>}
+ </div>
+ <span className="text-sm font-semibold text-foreground tabular-nums">
+ {fmtMoney(recurring)} / {period}
+ </span>
+ </div>
+ </div>
+ </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={handleActivate}
+ isDisabled={pending || !preview.data}
+ isPending={pending}
+ >
+ Activate · pay {fmtMoney(dueToday, dueToday ? 2 : 0)} today
+ </Button>
+ </SheetFooter>
+ </>
+ );
+};
diff --git a/frontend/src/pages/organization/BillingV2Page/components/AddProductModal.tsx b/frontend/src/pages/organization/BillingV2Page/components/AddProductModal.tsx
deleted file mode 100644
index 0bf74b3b95..0000000000
--- a/frontend/src/pages/organization/BillingV2Page/components/AddProductModal.tsx
+++ /dev/null
@@ -1,134 +0,0 @@
-import { useEffect } from "react";
-import { PlusIcon } from "lucide-react";
-
-import { createNotification } from "@app/components/notifications";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogMedia,
- AlertDialogTitle
-} from "@app/components/v3";
-import {
- BillingV2Cadence,
- BillingV2CatalogProduct,
- useAddBillingV2Product,
- usePreviewBillingV2Change
-} from "@app/hooks/api";
-
-import { fmtMoney } from "../billing-v2-data";
-
-type Props = {
- orgId: string;
- product: BillingV2CatalogProduct;
- plan: string;
- cadence: BillingV2Cadence;
- onClose: () => void;
-};
-
-export const AddProductModal = ({ orgId, product, plan, cadence, onClose }: Props) => {
- const preview = usePreviewBillingV2Change();
- const addProduct = useAddBillingV2Product();
-
- // Preview the prorated charge once when the dialog opens, so the user confirms against real numbers.
- useEffect(() => {
- preview.mutate({ orgId, addProductId: product.id, plan, cadence });
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [orgId, product.id, plan, cadence]);
-
- const handleAdd = async (e: React.MouseEvent<HTMLButtonElement>) => {
- e.preventDefault();
- try {
- await addProduct.mutateAsync({ orgId, productId: product.id, plan, cadence });
- createNotification({
- type: "success",
- text: `${product.name} was added. It may take a moment to update here.`
- });
- onClose();
- } catch {
- createNotification({ type: "error", text: `Failed to add ${product.name}.` });
- }
- };
-
- const dueToday = preview.data ? Math.max(preview.data.prorationAmount, 0) : 0;
-
- // Only let the user commit a charge once the prorated cost has rendered; a still-loading or
- // failed preview keeps the confirm disabled so nobody pays without seeing the amount.
- const canConfirm = Boolean(preview.data);
-
- return (
- <AlertDialog
- open
- onOpenChange={(isOpen) => {
- if (!isOpen) {
- onClose();
- }
- }}
- >
- <AlertDialogContent className="sm:max-w-xl!">
- <AlertDialogHeader>
- <AlertDialogMedia>
- <PlusIcon />
- </AlertDialogMedia>
- <AlertDialogTitle>Add {product.name}?</AlertDialogTitle>
- <AlertDialogDescription>
- {product.name} is added to your subscription right away. You are charged an estimated
- prorated amount for the rest of this billing period, then the new recurring total going
- forward.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <div className="rounded-md border border-border bg-mineshaft-700/40 px-4 py-3 text-sm">
- {preview.isPending && (
- <span className="text-mineshaft-300">Calculating your prorated charge...</span>
- )}
- {preview.isError && (
- <span className="text-mineshaft-300">
- We couldn&apos;t calculate the charge, but you can still add this product.
- </span>
- )}
- {preview.data && (
- <div className="flex flex-col gap-1.5">
- <div className="flex items-center justify-between">
- <span className="text-mineshaft-300">Estimated due today</span>
- <span className="font-semibold text-foreground tabular-nums">
- {fmtMoney(dueToday, 2)}
- </span>
- </div>
- {preview.data.estimatedUsage > 0 && (
- <>
- <div className="flex items-center justify-between">
- <span className="text-mineshaft-300">Estimated usage this period</span>
- <span className="font-semibold text-foreground tabular-nums">
- ~{fmtMoney(preview.data.estimatedUsage, 2)}
- </span>
- </div>
- <div className="flex items-center justify-between border-t border-border pt-1.5">
- <span className="text-mineshaft-300">New Recurring total</span>
- <span className="font-semibold text-foreground tabular-nums">
- ~{fmtMoney(preview.data.estimatedTotal, 2)}
- </span>
- </div>
- </>
- )}
- </div>
- )}
- </div>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- variant="org"
- isDisabled={addProduct.isPending || !canConfirm}
- onClick={handleAdd}
- isPending={addProduct.isPending}
- >
- Add {product.name}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- );
-};
diff --git a/frontend/src/pages/organization/BillingV2Page/components/CommitmentView.tsx b/frontend/src/pages/organization/BillingV2Page/components/CommitmentView.tsx
new file mode 100644
index 0000000000..8a03bafb17
--- /dev/null
+++ b/frontend/src/pages/organization/BillingV2Page/components/CommitmentView.tsx
@@ -0,0 +1,237 @@
+import { useEffect, useMemo, useState } from "react";
+import { ArrowUpIcon, ChevronLeftIcon, Info } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import { Button, SheetFooter, SheetHeader, SheetTitle } from "@app/components/v3";
+import {
+ BillingV2CatalogProduct,
+ BillingV2CommitmentChange,
+ BillingV2Entitlement,
+ useChangeBillingV2Commitment,
+ usePreviewBillingV2Change
+} from "@app/hooks/api";
+
+import { dimAnnualCommitted, fmtMoney } from "../billing-v2-data";
+import { ProductIcon, Stepper } from "./shared";
+
+type Props = {
+ orgId: string;
+ prod: BillingV2CatalogProduct;
+ entitlement: BillingV2Entitlement;
+ renewsOn: string | null;
+ onBack: () => void;
+ onDone: () => void;
+};
+
+// Change the prepaid annual commitment for a product's per_resource dimensions. Steppers set the new
+// committed quantity per dimension; the preview endpoint (commitmentChanges) prices the change and the
+// apply endpoint commits it. Usage above the commitment is billed monthly on-demand.
+export const CommitmentView = ({ orgId, prod, entitlement, renewsOn, onBack, onDone }: Props) => {
+ const committable = useMemo(
+ () => (entitlement.dimensions ?? []).filter(dimAnnualCommitted),
+ [entitlement.dimensions]
+ );
+
+ const [quantities, setQuantities] = useState<Record<string, number>>(() =>
+ Object.fromEntries(committable.map((dim) => [dim.key, dim.committed ?? 0]))
+ );
+
+ const preview = usePreviewBillingV2Change();
+ const applyCommitment = useChangeBillingV2Commitment();
+
+ // Only the dimensions whose committed quantity actually changed are sent to preview/apply.
+ const changes: BillingV2CommitmentChange[] = useMemo(
+ () =>
+ committable
+ .filter((dim) => quantities[dim.key] !== (dim.committed ?? 0))
+ .map((dim) => ({ dimensionKey: dim.key, quantity: quantities[dim.key] })),
+ [committable, quantities]
+ );
+ const changesKey = JSON.stringify(changes);
+
+ // Re-price whenever the set of changes changes; with nothing changed, there is no charge to preview.
+ useEffect(() => {
+ if (changes.length > 0) {
+ preview.mutate({ orgId, commitmentChanges: changes });
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [orgId, changesKey]);
+
+ const hasChanges = changes.length > 0;
+
+ // Current annual commitment total (committed × annual rate) and the current monthly on-demand spend,
+ // both computed client-side so the summary can show the before/after delta.
+ const currentAnnual = committable.reduce(
+ (sum, dim) => sum + (dim.committed ?? 0) * (dim.committedRate ?? 0),
+ 0
+ );
+ const newAnnual = hasChanges && preview.data ? preview.data.nextRecurringTotal : currentAnnual;
+ const currentOnDemand =
+ entitlement.onDemandAmount ??
+ committable.reduce(
+ (sum, dim) => sum + Math.max(0, dim.used - (dim.committed ?? 0)) * (dim.onDemandRate ?? 0),
+ 0
+ );
+ const newOnDemand = committable.reduce(
+ (sum, dim) => sum + Math.max(0, dim.used - quantities[dim.key]) * (dim.onDemandRate ?? 0),
+ 0
+ );
+ const chargedToday = hasChanges ? Math.max(preview.data?.prorationAmount ?? 0, 0) : 0;
+
+ let chargedNote = "No change yet";
+ if (hasChanges) {
+ chargedNote = preview.isPending ? "Calculating…" : "Prorated for the rest of your annual term";
+ }
+
+ const raiseToCoverUsage = () => {
+ setQuantities((prev) => {
+ const next = { ...prev };
+ committable.forEach((dim) => {
+ next[dim.key] = Math.max(dim.committed ?? 0, dim.used);
+ });
+ return next;
+ });
+ };
+ const coversUsage = committable.every((dim) => quantities[dim.key] >= dim.used);
+
+ const canConfirm = hasChanges && Boolean(preview.data) && !preview.isPending;
+
+ const handleConfirm = async () => {
+ try {
+ await applyCommitment.mutateAsync({
+ orgId,
+ changes,
+ prorationDate: preview.data?.prorationDate
+ });
+ createNotification({
+ type: "success",
+ text: `${prod.name} commitment updated. It may take a moment to update here.`
+ });
+ onDone();
+ } catch {
+ createNotification({ type: "error", text: `Failed to update ${prod.name} commitment.` });
+ }
+ };
+
+ const onDemandDelta =
+ // eslint-disable-next-line no-nested-ternary
+ newOnDemand === currentOnDemand
+ ? null
+ : newOnDemand < currentOnDemand
+ ? `Down from ${fmtMoney(currentOnDemand)} / mo`
+ : `Up from ${fmtMoney(currentOnDemand)} / mo`;
+
+ 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">Change {prod.name} commitment</SheetTitle>
+ <p className="mt-1 text-sm text-muted">
+ Adjust the units you pre-buy for the year. Usage above your commitment is billed monthly
+ on-demand.
+ </p>
+ </div>
+ </SheetHeader>
+
+ <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-5">
+ {committable.map((dim) => {
+ const onDemandQty = Math.max(0, dim.used - quantities[dim.key]);
+ return (
+ <div
+ key={dim.key}
+ className="flex items-center justify-between gap-4 rounded-lg border border-border bg-card p-4"
+ >
+ <div className="min-w-0">
+ <div className="text-sm font-medium text-foreground">
+ {dim.label} · committed for the year
+ </div>
+ <div className="mt-0.5 text-xs text-muted">
+ {fmtMoney(dim.committedRate ?? 0)} / {dim.noun} / yr committed · using{" "}
+ {dim.used.toLocaleString()} now
+ {onDemandQty > 0 && (
+ <span className="text-warning">
+ {" "}
+ · {onDemandQty.toLocaleString()} on-demand
+ </span>
+ )}
+ </div>
+ </div>
+ <Stepper
+ value={quantities[dim.key]}
+ min={0}
+ onChange={(value) => setQuantities((prev) => ({ ...prev, [dim.key]: value }))}
+ />
+ </div>
+ );
+ })}
+
+ {!coversUsage && (
+ <Button variant="info" size="sm" className="self-start" onClick={raiseToCoverUsage}>
+ <ArrowUpIcon />
+ Raise commitment to cover current usage
+ </Button>
+ )}
+
+ <div className="flex gap-3 rounded-lg border border-info/20 bg-info/5 p-4 text-xs text-accent">
+ <Info className="mt-0.5 size-4 shrink-0 text-info" />
+ <span>
+ Committed units are pre-bought for the year at the annual rate. Usage above your
+ commitment is billed monthly at the on-demand rate until your renewal. Raising your
+ commitment is prorated for the rest of the term; lowering it takes effect at renewal.
+ </span>
+ </div>
+
+ <div className="flex flex-col rounded-lg border border-border">
+ <div className="flex items-center justify-between border-b border-border bg-mineshaft-700/40 p-4">
+ <div>
+ <div className="text-sm text-foreground">Charged today</div>
+ <div className="text-xs text-muted">{chargedNote}</div>
+ </div>
+ <span className="text-lg font-semibold text-info tabular-nums">
+ {fmtMoney(chargedToday, chargedToday ? 2 : 0)}
+ </span>
+ </div>
+ <div className="flex items-center justify-between border-b border-border p-4">
+ <div>
+ <div className="text-sm text-foreground">New annual commitment</div>
+ <div className="text-xs text-muted">
+ For {prod.name}
+ {renewsOn ? `, billed on ${renewsOn}` : ""}
+ </div>
+ </div>
+ <span className="text-sm font-semibold text-foreground tabular-nums">
+ {fmtMoney(newAnnual)} / year
+ </span>
+ </div>
+ <div className="flex items-center justify-between p-4">
+ <div>
+ <div className="text-sm text-foreground">On-demand after change</div>
+ <div className="text-xs text-muted">
+ {onDemandDelta ?? "Billed monthly for usage above your commitment"}
+ </div>
+ </div>
+ <span className="text-sm font-semibold text-warning tabular-nums">
+ {fmtMoney(newOnDemand)} / mo
+ </span>
+ </div>
+ </div>
+ </div>
+
+ <SheetFooter className="flex-row justify-between border-t">
+ <Button variant="ghost" onClick={onBack} isDisabled={applyCommitment.isPending}>
+ <ChevronLeftIcon />
+ Back to plans
+ </Button>
+ <Button
+ variant="org"
+ onClick={handleConfirm}
+ isDisabled={!canConfirm || applyCommitment.isPending}
+ isPending={applyCommitment.isPending}
+ >
+ Confirm &amp; pay
+ </Button>
+ </SheetFooter>
+ </>
+ );
+};
diff --git a/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx b/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
index 0f6a13adbb..21e6dfced0 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
@@ -43,26 +43,14 @@ import {
} from "@app/components/v3";
import { cn } from "@app/components/v3/utils";
import {
- BillingV2Cadence,
BillingV2CatalogProduct,
BillingV2Entitlement,
- BillingV2EntitlementDim,
BillingV2Invoice,
BillingV2Overview
} from "@app/hooks/api";
-import {
- cadenceWordShort,
- dimRate,
- fmtMoney,
- intervalToCadence,
- intervalWord,
- pluralizeUnit,
- productBreakdown,
- productTotal,
- usagePct
-} from "../billing-v2-data";
-import { ActiveBadge, ProductIcon } from "./shared";
+import { cadencePeriod, fmtMoney, intervalWord, productBreakdown } from "../billing-v2-data";
+import { ActiveBadge, CadenceBadge, DimensionMeter, ProductIcon } from "./shared";
export type BillingV2Mode = "self-serve" | "managed";
export type BillingV2RenderState =
@@ -250,16 +238,11 @@ const StatusBadge = ({ subState }: { subState: BillingV2RenderState }) => {
return <ActiveBadge />;
};
-// Projected next-month cost: fixed recurring plus estimated metered usage across all products.
-const nextMonthTotal = (overview: BillingV2Overview): number =>
- (overview.recurringAmount ?? 0) + (overview.estimatedUsageAmount ?? 0);
-
const recurringLabel = (overview: BillingV2Overview): string => {
- const total = nextMonthTotal(overview);
- if (!total) {
+ if (!overview.recurringAmount) {
return "Free";
}
- return `${fmtMoney(total)} / ${intervalWord(overview.interval)}`;
+ return `${fmtMoney(overview.recurringAmount)} / ${intervalWord(overview.interval)}`;
};
type StatTone = "success" | "info" | "warning" | "danger" | "org";
@@ -314,13 +297,12 @@ const StatTile = ({ title, tone, icon, value, footer }: StatTileProps) => (
const SummaryCard = ({ overview }: SummaryCardProps) => {
const status = STATUS_VISUAL[overview.subState];
- const total = nextMonthTotal(overview);
- const usage = overview.estimatedUsageAmount ?? 0;
- const hasUsage = usage > 0;
+ const onDemand = overview.onDemandAmount ?? 0;
+ const hasOnDemand = onDemand > 0;
let recurringNote = "No recurring charges";
- if (total) {
- recurringNote = hasUsage
- ? `Includes ~${fmtMoney(usage)} est. usage`
+ if (overview.recurringAmount) {
+ recurringNote = hasOnDemand
+ ? `+ ${fmtMoney(onDemand)} / mo on-demand`
: `Billed ${intervalWord(overview.interval)}ly`;
}
@@ -341,16 +323,15 @@ const SummaryCard = ({ overview }: SummaryCardProps) => {
footer={<span className="text-xs text-muted">All products renew together</span>}
/>
<StatTile
- title="Next month"
+ title="Recurring total"
tone="org"
icon={<CreditCard />}
- value={
- <span className="flex items-baseline gap-1.5">
- {recurringLabel(overview)}
- {hasUsage && <span className="text-xs font-normal text-muted">est.</span>}
+ value={recurringLabel(overview)}
+ footer={
+ <span className={cn("text-xs", hasOnDemand ? "text-warning" : "text-muted")}>
+ {recurringNote}
</span>
}
- footer={<span className="text-xs text-muted">{recurringNote}</span>}
/>
</div>
);
@@ -441,45 +422,9 @@ const UsageCard = ({ overview }: UsageCardProps) => {
// Capitalize a plan tier ("pro" -> "Pro") for the badge beside an active product's name.
const tierLabel = (tier: string): string => tier.charAt(0).toUpperCase() + tier.slice(1);
-type DimensionMeterProps = {
- dim: BillingV2EntitlementDim;
- product: BillingV2CatalogProduct;
- planTier?: string;
- cadence: BillingV2Cadence;
-};
-
-// One usage bar for a product dimension: "{used} / {limit} · $rate/unit/mo" with a fill bar. A
-// dimension with no finite cap (unlimited or usage-based) shows a running count and no bar.
-const DimensionMeter = ({ dim, product, planTier, cadence }: DimensionMeterProps) => {
- const rate = dimRate(dim, product, planTier, cadence);
- const pct = usagePct(dim.used, dim.limit);
- const rateNote =
- rate !== null && rate > 0 ? `${fmtMoney(rate)}/${dim.noun}/${cadenceWordShort(cadence)}` : null;
-
- return (
- <div className="flex flex-col gap-1.5">
- <div className="flex items-baseline justify-between gap-2.5 text-xs">
- <span className="text-muted">{dim.label}</span>
- <span className="text-muted tabular-nums">
- <span className="font-medium text-foreground">{dim.used.toLocaleString()}</span>
- {dim.limit !== null ? ` / ${dim.limit.toLocaleString()}` : ` ${pluralizeUnit(dim.noun)}`}
- {rateNote && <span> · {rateNote}</span>}
- </span>
- </div>
- {pct !== null && (
- <div className="h-1.5 w-full overflow-hidden rounded-full bg-border">
- <div className="h-full rounded-full bg-org transition-all" style={{ width: `${pct}%` }} />
- </div>
- )}
- </div>
- );
-};
-
type ProductRowProps = {
prod: BillingV2CatalogProduct;
entitlement?: BillingV2Entitlement;
- cadence: BillingV2Cadence;
- interval: "month" | "year" | null;
renewsOn: string | null;
readOnly?: boolean;
onManage: (id: string) => void;
@@ -489,8 +434,6 @@ type ProductRowProps = {
const ProductRow = ({
prod,
entitlement,
- cadence,
- interval,
renewsOn,
readOnly,
onManage,
@@ -512,7 +455,7 @@ const ProductRow = ({
action = (
<Button variant="org" size="sm" onClick={() => onManage(prod.id)}>
<ArrowBigUpDashIcon />
- Upgrade
+ Activate
</Button>
);
} else if (salesLed) {
@@ -524,7 +467,7 @@ const ProductRow = ({
}
}
- // Inactive product: compact row with the tagline and an upgrade / contact action.
+ // Inactive product: compact row with the tagline and an activate / contact action.
if (!entitled) {
return (
<div className="flex items-center gap-4 border-t border-border py-4 first:border-t-0">
@@ -535,57 +478,63 @@ const ProductRow = ({
{prod.addon && <Badge variant="neutral">Add-on</Badge>}
<Badge variant="neutral">Inactive</Badge>
</div>
- <div className="text-xs text-muted">{prod.tagline || prod.desc}</div>
+ <div className="text-xs text-muted">{prod.tagline}</div>
</div>
{action && <div className="flex shrink-0 items-center gap-1.5">{action}</div>}
</div>
);
}
- // Active product: headline all-in total (fixed recurring + estimated metered usage), the renewal
- // date, a price breakdown line, and one usage bar per dimension.
+ // Active product: cadence badge, renewal (or trial) line, headline recurring + on-demand, price
+ // breakdown, and one usage bar per dimension.
const dims = entitlement?.dimensions ?? [];
- const total = productTotal(entitlement);
- const hasUsage = (entitlement?.estimatedUsageAmount ?? 0) > 0;
- const breakdown = productBreakdown(entitlement, prod, cadence);
+ const amount = entitlement?.amount ?? 0;
+ const onDemand = entitlement?.onDemandAmount ?? 0;
+ const breakdown = productBreakdown(entitlement);
+ const isTrialing = Boolean(entitlement?.isTrialing);
return (
<div className="flex flex-col gap-3 border-t border-border py-4 first:border-t-0">
<div className="flex items-center gap-4">
<ProductIcon product={prod} />
- <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">
<div className="flex flex-wrap items-center gap-2">
<span className="text-sm font-semibold text-foreground">{prod.name}</span>
{entitlement?.planTier && (
<Badge variant="neutral">{tierLabel(entitlement.planTier)}</Badge>
)}
{prod.addon && <Badge variant="neutral">Add-on</Badge>}
- <ActiveBadge />
+ {isTrialing ? <Badge variant="info">Trial</Badge> : <ActiveBadge />}
+ </div>
+ <div className="flex flex-wrap items-center gap-2 text-xs text-muted">
+ {!isTrialing && <CadenceBadge cadence={entitlement?.cadence} />}
+ {isTrialing && entitlement?.trialEndsAt ? (
+ <span>Trial ends {entitlement.trialEndsAt}</span>
+ ) : (
+ renewsOn && <span>Renews {renewsOn}</span>
+ )}
</div>
- {renewsOn && <div className="text-xs text-muted">Renews {renewsOn}</div>}
</div>
<div className="flex shrink-0 flex-col items-end gap-0.5">
<div className="flex items-baseline gap-1">
<span className="text-sm font-semibold text-foreground tabular-nums">
- {fmtMoney(total)}
+ {fmtMoney(amount)}
</span>
- <span className="text-xs text-muted">/ {intervalWord(interval)}</span>
- {hasUsage && <span className="text-[10px] text-muted">est.</span>}
+ <span className="text-xs text-muted">/ {cadencePeriod(entitlement?.cadence)}</span>
</div>
{breakdown && <span className="text-xs text-muted">{breakdown}</span>}
+ {onDemand > 0 && (
+ <span className="text-xs font-medium text-warning">
+ + {fmtMoney(onDemand)} / mo on-demand
+ </span>
+ )}
</div>
{action && <div className="flex shrink-0 items-center gap-1.5">{action}</div>}
</div>
{dims.length > 0 && (
<div className="flex flex-col gap-3 pl-[52px]">
{dims.map((dim) => (
- <DimensionMeter
- key={dim.key}
- dim={dim}
- product={prod}
- planTier={entitlement?.planTier}
- cadence={cadence}
- />
+ <DimensionMeter key={dim.key} dim={dim} />
))}
</div>
)}
@@ -602,7 +551,6 @@ type ProductsCardProps = {
};
const ProductsCard = ({ overview, catalog, readOnly, onManage, onContact }: ProductsCardProps) => {
- const cadence = intervalToCadence(overview.interval);
return (
<Card>
<CardHeader>
@@ -625,8 +573,6 @@ const ProductsCard = ({ overview, catalog, readOnly, onManage, onContact }: Prod
key={prod.id}
prod={prod}
entitlement={overview.entitlements[prod.id]}
- cadence={cadence}
- interval={overview.interval}
renewsOn={overview.nextBillingDate}
readOnly={readOnly}
onManage={onManage}
diff --git a/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsx b/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsx
index 119e1e22b6..4101552066 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsx
@@ -1,7 +1,17 @@
import { useState } from "react";
-import { ArrowRight, Check, ExternalLink, ShoppingCart } from "lucide-react";
+import { ArrowRight, Check, PlusIcon, Sparkles } from "lucide-react";
+import { createNotification } from "@app/components/notifications";
import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogMedia,
+ AlertDialogTitle,
Badge,
Button,
Sheet,
@@ -23,24 +33,27 @@ import {
BillingV2CompareRow,
BillingV2Dim,
BillingV2Entitlement,
- BillingV2Plan
+ BillingV2Plan,
+ useStartBillingV2Trial
} from "@app/hooks/api";
import {
+ cadencePeriod,
cadenceWord,
cadenceWordShort,
+ dimAnnualCommitted,
fmtMoney,
isMeteredCadence,
pluralizeUnit,
unitPrice
} from "../billing-v2-data";
-import { ActiveBadge, ProductIcon } from "./shared";
+import { ActivateView } from "./ActivateView";
+import { CommitmentView } from "./CommitmentView";
+import { ActiveBadge, DimensionMeter, ProductIcon } from "./shared";
// 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 };
-// A priced dimension as a display line. A metered dimension reads as usage-based: an optional "First
-// N included, then" prefix and a flag to badge the line, instead of a fixed per-unit charge.
const dimPriceLine = (dim: BillingV2Dim, cadence: BillingV2Cadence, unit: string): PriceLine => {
const metered = isMeteredCadence(dim, cadence);
const line: PriceLine = { amount: fmtMoney(unitPrice(dim, cadence), 2), unit, metered };
@@ -63,11 +76,8 @@ const PriceLineView = ({ line, headline }: { line: PriceLine; headline?: boolean
</div>
);
-// A plan's price is a base fee plus any number of priced dimensions, and any combination is valid:
-// base only, meter only, or both. The base fee leads as the headline; every priced dimension is then
-// listed below (e.g. "$5 per MCP / mo", "$3 per Agent / mo"). When there's no base fee the first
-// dimension is promoted to the headline so the card always opens with a price. A metered dimension
-// renders with its usage-based framing (included allowance + "Usage-based" badge).
+// A plan's price: a base fee leads as the headline, else the first priced dimension is promoted; the
+// remaining priced dimensions list below. A metered dimension renders with its usage-based framing.
const PlanPricing = ({ plan, cadence }: { plan: BillingV2Plan; cadence: BillingV2Cadence }) => {
const dims = plan.dims ?? [];
@@ -116,46 +126,46 @@ const renderCompareCell = (value: string | boolean | number | undefined) => {
return value;
};
-type PlanBadgeProps = { plan: BillingV2Plan; isCurrent: boolean };
-
-const PlanBadge = ({ plan, isCurrent }: PlanBadgeProps) => {
+const PlanBadge = ({ plan, isCurrent }: { plan: BillingV2Plan; isCurrent: boolean }) => {
if (isCurrent) {
return (
<Badge variant="success">
<Check className="text-success" />
- Current Plan
+ Current plan
</Badge>
);
}
if (plan.salesLed) {
- return <Badge variant="neutral">Talk to Us</Badge>;
+ return <Badge variant="info">Sales-led</Badge>;
}
- return <Badge variant="neutral">Self-Checkout</Badge>;
+ return <Badge variant="info">Self-serve</Badge>;
};
type PlanCardProps = {
- prodId: string;
plan: BillingV2Plan;
cadence: BillingV2Cadence;
isCurrent: boolean;
entitled: boolean;
- redirecting?: boolean;
- onSelect: (prodId: string, planTier: string) => void;
+ canChangeCommitment: boolean;
+ onActivate: (planTier: string) => void;
+ onStartTrial: (planTier: string) => void;
+ onChangeCommitment: () => void;
onContact: () => void;
};
const PlanCard = ({
- prodId,
plan,
cadence,
isCurrent,
entitled,
- redirecting,
- onSelect,
+ canChangeCommitment,
+ onActivate,
+ onStartTrial,
+ onChangeCommitment,
onContact
}: PlanCardProps) => {
- // A sales-led plan with no published price shows "Custom"; everything else renders its pricing.
const isCustom = plan.salesLed && !plan.base && plan.dims.length === 0;
+ const offersTrial = plan.selfServe && plan.trialable && !entitled;
let cta = null;
if (plan.salesLed && !isCurrent) {
@@ -165,18 +175,36 @@ const PlanCard = ({
<ArrowRight />
</Button>
);
- } else if (plan.selfServe && !entitled) {
- // Picking a self-serve plan starts checkout (or an in-place add for an existing subscription).
+ } else if (isCurrent && canChangeCommitment) {
cta = (
+ <Button
+ variant="outline"
+ size="sm"
+ className="mt-auto self-start"
+ onClick={onChangeCommitment}
+ >
+ Change commitment
+ </Button>
+ );
+ } else if (plan.selfServe && !entitled) {
+ cta = offersTrial ? (
+ <Button
+ variant="org"
+ size="sm"
+ className="mt-auto self-start"
+ onClick={() => onStartTrial(plan.tier)}
+ >
+ Start free trial
+ </Button>
+ ) : (
<Button
variant="org"
size="sm"
className="mt-auto self-start"
- isPending={redirecting}
- onClick={() => onSelect(prodId, plan.tier)}
+ onClick={() => onActivate(plan.tier)}
>
- <ShoppingCart />
- Continue to checkout
+ <PlusIcon />
+ Activate on {plan.name}
</Button>
);
}
@@ -198,45 +226,53 @@ const PlanCard = ({
) : (
<PlanPricing plan={plan} cadence={cadence} />
)}
+ {offersTrial && (
+ <div className="flex items-center gap-1.5 text-xs text-success">
+ <Check className="size-3.5" />
+ Free trial · no charge for your first cycle
+ </div>
+ )}
{plan.feature && <div className="text-xs text-accent">{plan.feature}</div>}
{cta}
+ {offersTrial && (
+ <div className="text-xs text-muted">No charge for your first cycle · cancel anytime</div>
+ )}
</div>
);
};
-type EntitlementSummaryProps = {
- entitlement?: BillingV2Entitlement;
-};
-
-const EntitlementSummary = ({ entitlement }: EntitlementSummaryProps) => {
- const entitled = Boolean(entitlement?.entitled);
- let detail = "This product isn't part of your current plan.";
- if (entitled) {
- detail = "This product is active on your subscription.";
- if (entitlement && entitlement.limit !== null && entitlement.limit !== undefined) {
- const used = entitlement.used ?? 0;
- detail = `Active on your subscription. ${used.toLocaleString()} of ${entitlement.limit.toLocaleString()} in use.`;
- }
- }
+// "Your current usage" panel for an active product: the recurring headline plus a bar per dimension.
+const CurrentUsageCard = ({ entitlement }: { entitlement: BillingV2Entitlement }) => {
+ const dims = entitlement.dimensions ?? [];
return (
- <div className="rounded-lg border border-border bg-card p-4">
- <div className="mb-3 flex items-center justify-between gap-3">
- <span className="text-xs font-medium text-foreground">Your Plan</span>
- {entitled ? <ActiveBadge /> : <Badge variant="neutral">Inactive</Badge>}
+ <div className="flex flex-col gap-3.5 rounded-xl border border-border bg-card p-[18px]">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-sm font-medium text-foreground">Your current usage</span>
+ <span className="text-sm text-muted">
+ <span className="font-semibold text-foreground">{fmtMoney(entitlement.amount ?? 0)}</span>{" "}
+ / {cadencePeriod(entitlement.cadence)}
+ </span>
</div>
- <div className="text-xs text-accent">{detail}</div>
+ {dims.length > 0 && (
+ <div className="flex flex-col gap-3">
+ {dims.map((dim) => (
+ <DimensionMeter key={dim.key} dim={dim} />
+ ))}
+ </div>
+ )}
</div>
);
};
-type CompareTableProps = {
+const CompareTable = ({
+ plans,
+ compare
+}: {
plans: BillingV2Plan[];
compare: BillingV2CompareRow[];
-};
-
-const CompareTable = ({ plans, compare }: CompareTableProps) => (
+}) => (
<div>
- <div className="mb-3 text-xs font-medium text-muted">Compare Plans</div>
+ <div className="mb-3 text-xs font-medium tracking-wide text-muted uppercase">Compare plans</div>
<Table>
<TableHeader>
<TableRow>
@@ -280,191 +316,259 @@ const IncludesList = ({ includes }: { includes: string[] }) => (
</div>
);
-// Static column classes (Tailwind can't see computed ones); cap at three before wrapping.
const GRID_COLS: Record<number, string> = {
1: "grid-cols-1",
2: "sm:grid-cols-2",
3: "sm:grid-cols-2 lg:grid-cols-3"
};
-type PlansViewProps = {
- prod: BillingV2CatalogProduct;
- entitlement?: BillingV2Entitlement;
- cadence: BillingV2Cadence;
- redirecting?: boolean;
- pendingTier: string | null;
- onSelect: (prodId: string, planTier: string) => void;
- onContact: (prod: BillingV2CatalogProduct) => void;
-};
-
-const PlansView = ({
- prod,
- entitlement,
- cadence,
- redirecting,
- pendingTier,
- onSelect,
- onContact
-}: PlansViewProps) => {
- // Sales-led ("Contact sales") plans sort last; alphabetical by name within each group breaks ties.
- const plans = [...(prod.plans ?? [])].sort((a, b) => {
- if (a.salesLed !== b.salesLed) {
- return a.salesLed ? 1 : -1;
- }
- return a.name.localeCompare(b.name);
- });
- const entitled = Boolean(entitlement?.entitled);
- // When entitled but the server didn't say which tier, fall back to the first self-serve plan so a
- // card is still marked active (mirrors the previous single-"pro" behaviour).
- const currentTier =
- entitlement?.planTier ?? (entitled ? plans.find((plan) => plan.selfServe)?.tier : undefined);
-
- const gridCols = GRID_COLS[Math.min(plans.length, 3)] ?? GRID_COLS[3];
- const showCompare = Boolean(prod.compare && prod.compare.length > 0 && plans.length > 1);
-
- return (
- <>
- <EntitlementSummary entitlement={entitlement} />
-
- <div className={`grid gap-3.5 ${gridCols}`}>
- {plans.map((plan) => (
- <PlanCard
- key={plan.tier}
- prodId={prod.id}
- plan={plan}
- cadence={cadence}
- entitled={entitled}
- isCurrent={entitled && plan.tier === currentTier}
- redirecting={Boolean(redirecting) && pendingTier === plan.tier}
- onSelect={onSelect}
- onContact={() => onContact(prod)}
- />
- ))}
- </div>
-
- {showCompare && prod.compare ? (
- <CompareTable plans={plans} compare={prod.compare} />
- ) : (
- prod.includes && prod.includes.length > 0 && <IncludesList includes={prod.includes} />
- )}
- </>
- );
-};
-
type ProductSheetProps = {
- prodId: string;
+ orgId: string;
prod?: BillingV2CatalogProduct;
entitlement?: BillingV2Entitlement;
- cadence: BillingV2Cadence;
- redirecting?: boolean;
+ hasActiveSubscription: boolean;
+ billingEmail?: string;
+ returnPath: string;
+ renewsOn: string | null;
onClose: () => void;
- onManage: (prodId: string, planTier: string) => void;
onRemove: (prodId: string) => void;
onContact: (prod: BillingV2CatalogProduct) => void;
};
+type SheetView = "plans" | "activate" | "commitment";
+
export const ProductSheet = ({
- prodId,
+ orgId,
prod,
entitlement,
- cadence,
- redirecting,
+ hasActiveSubscription,
+ billingEmail,
+ returnPath,
+ renewsOn,
onClose,
- onManage,
onRemove,
onContact
}: ProductSheetProps) => {
- // Track which plan's button was clicked so only that card spins while the request is in flight,
- // rather than every card sharing the single `redirecting` flag.
- const [pendingTier, setPendingTier] = useState<string | null>(null);
+ const [view, setView] = useState<SheetView>("plans");
+ // The plan tier chosen for the activate view.
+ const [activatePlan, setActivatePlan] = useState<string | null>(null);
+ // The plan tier awaiting trial confirmation (drives the confirm dialog).
+ const [trialConfirmTier, setTrialConfirmTier] = useState<string | null>(null);
+
+ const startTrial = useStartBillingV2Trial();
if (!prod) {
return null;
}
const entitled = Boolean(entitlement?.entitled);
- const selfServe = prod.plans.some((plan) => plan.selfServe);
+ const selfServePlan = prod.plans.find((plan) => plan.selfServe && !plan.salesLed);
+ // The active product's plan-card price renders in its billing cadence; a new one defaults to monthly.
+ const displayCadence: BillingV2Cadence = entitlement?.cadence === "annual" ? "annual" : "monthly";
+ const canChangeCommitment = (entitlement?.dimensions ?? []).some(dimAnnualCommitted);
- const handleSelect = (id: string, planTier: string) => {
- setPendingTier(planTier);
- onManage(id, planTier);
+ // Sales-led plans sort last; alphabetical by name breaks ties within each group.
+ const plans = [...(prod.plans ?? [])].sort((a, b) => {
+ if (a.salesLed !== b.salesLed) {
+ return a.salesLed ? 1 : -1;
+ }
+ return a.name.localeCompare(b.name);
+ });
+ const currentTier =
+ entitlement?.planTier ?? (entitled ? plans.find((plan) => plan.selfServe)?.tier : undefined);
+ const gridCols = GRID_COLS[Math.min(plans.length, 3)] ?? GRID_COLS[3];
+ const showCompare = Boolean(prod.compare && prod.compare.length > 0 && plans.length > 1);
+
+ const openActivate = (planTier: string) => {
+ setActivatePlan(planTier);
+ setView("activate");
};
- // An entitled product is managed in the Stripe portal; selecting a plan is handled per-card.
- const primaryCta = entitled ? (
- <Button
- variant="org"
- onClick={() => onManage(prodId, entitlement?.planTier ?? "")}
- isPending={redirecting}
- >
- Manage in Stripe
- <ExternalLink />
- </Button>
- ) : null;
+ const handleConfirmTrial = async () => {
+ if (!trialConfirmTier) {
+ return;
+ }
+ try {
+ const result = await startTrial.mutateAsync({
+ orgId,
+ productId: prod.id,
+ plan: trialConfirmTier
+ });
+ // No card on file: finish the Stripe setup checkout, which auto-starts the trial via webhook.
+ if (result.outcome === "collect_payment_method" && result.checkoutUrl) {
+ window.location.href = result.checkoutUrl;
+ return;
+ }
+ createNotification({
+ type: "success",
+ text: `Your ${prod.name} trial has started. It may take a moment to update here.`
+ });
+ onClose();
+ } catch {
+ createNotification({ type: "error", text: `Failed to start the ${prod.name} trial.` });
+ setTrialConfirmTier(null);
+ }
+ };
+
+ const activatePlanObj = activatePlan
+ ? plans.find((plan) => plan.tier === activatePlan)
+ : (selfServePlan ?? undefined);
+ const trialPlanObj = trialConfirmTier
+ ? plans.find((plan) => plan.tier === trialConfirmTier)
+ : undefined;
return (
- <Sheet
- open
- onOpenChange={(open) => {
- if (!open && !redirecting) {
- onClose();
- }
- }}
- >
- <SheetContent
- side="right"
- className={`w-full p-0 sm:max-w-3xl ${redirecting ? "[&>button]:hidden" : ""}`}
- onEscapeKeyDown={(e) => {
- if (redirecting) {
- e.preventDefault();
+ <>
+ <Sheet
+ open
+ onOpenChange={(open) => {
+ if (!open) {
+ onClose();
}
}}
- onPointerDownOutside={(e) => {
- if (redirecting) {
- e.preventDefault();
+ >
+ <SheetContent side="right" className="flex w-full flex-col p-0 sm:max-w-3xl">
+ {view === "activate" && activatePlanObj && (
+ <ActivateView
+ orgId={orgId}
+ prod={prod}
+ plan={activatePlanObj}
+ hasActiveSubscription={hasActiveSubscription}
+ billingEmail={billingEmail}
+ returnPath={returnPath}
+ renewsOn={renewsOn}
+ onBack={() => setView("plans")}
+ onDone={onClose}
+ />
+ )}
+
+ {view === "commitment" && entitlement && (
+ <CommitmentView
+ orgId={orgId}
+ prod={prod}
+ entitlement={entitlement}
+ renewsOn={renewsOn}
+ onBack={() => setView("plans")}
+ onDone={onClose}
+ />
+ )}
+
+ {view === "plans" && (
+ <>
+ <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="flex flex-wrap items-center gap-2 text-base">
+ {prod.name}
+ {prod.addon && <Badge variant="neutral">Add-on</Badge>}
+ {entitled && <ActiveBadge />}
+ </SheetTitle>
+ <SheetDescription className="mt-1">{prod.tagline}</SheetDescription>
+ </div>
+ </SheetHeader>
+
+ <div className="flex flex-1 flex-col gap-6 overflow-y-auto p-5">
+ {entitled && entitlement && <CurrentUsageCard entitlement={entitlement} />}
+
+ <div className={`grid gap-3.5 ${gridCols}`}>
+ {plans.map((plan) => (
+ <PlanCard
+ key={plan.tier}
+ plan={plan}
+ cadence={displayCadence}
+ entitled={entitled}
+ isCurrent={entitled && plan.tier === currentTier}
+ canChangeCommitment={canChangeCommitment}
+ onActivate={openActivate}
+ onStartTrial={setTrialConfirmTier}
+ onChangeCommitment={() => setView("commitment")}
+ onContact={() => onContact(prod)}
+ />
+ ))}
+ </div>
+
+ {showCompare && prod.compare ? (
+ <CompareTable plans={plans} compare={prod.compare} />
+ ) : (
+ prod.includes &&
+ prod.includes.length > 0 && <IncludesList includes={prod.includes} />
+ )}
+ </div>
+
+ <SheetFooter className="flex-row items-center justify-between border-t">
+ {entitled ? (
+ <>
+ <Button
+ variant="ghost"
+ className="text-danger"
+ onClick={() => onRemove(prod.id)}
+ >
+ Remove product
+ </Button>
+ <Button variant="outline" onClick={onClose}>
+ Close
+ </Button>
+ </>
+ ) : (
+ <>
+ <span className="text-xs text-muted">
+ Choose monthly or yearly at checkout · cancel any time
+ </span>
+ <div className="flex items-center gap-2">
+ <Button variant="outline" onClick={onClose}>
+ Close
+ </Button>
+ {selfServePlan && (
+ <Button variant="org" onClick={() => openActivate(selfServePlan.tier)}>
+ <PlusIcon />
+ Activate on {selfServePlan.name}
+ </Button>
+ )}
+ </div>
+ </>
+ )}
+ </SheetFooter>
+ </>
+ )}
+ </SheetContent>
+ </Sheet>
+
+ <AlertDialog
+ open={Boolean(trialConfirmTier)}
+ onOpenChange={(open) => {
+ if (!open && !startTrial.isPending) {
+ setTrialConfirmTier(null);
}
}}
>
- <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="flex flex-wrap items-center gap-2 text-base">
- {prod.name}
- {prod.addon && <Badge variant="neutral">Add-on</Badge>}
- </SheetTitle>
- <SheetDescription className="mt-1">{prod.tagline || prod.desc}</SheetDescription>
- </div>
- </SheetHeader>
-
- <div className="flex flex-1 flex-col gap-6 overflow-y-auto p-5">
- <PlansView
- prod={prod}
- entitlement={entitlement}
- cadence={cadence}
- redirecting={redirecting}
- pendingTier={pendingTier}
- onSelect={handleSelect}
- onContact={onContact}
- />
- </div>
-
- <SheetFooter className="flex-row justify-start border-t">
- {primaryCta}
- <Button variant="outline" onClick={onClose} isDisabled={redirecting}>
- Close
- </Button>
- {entitled && selfServe && (
- <Button
- variant="danger"
- className="ml-auto"
- onClick={() => onRemove(prodId)}
- isDisabled={redirecting}
+ <AlertDialogContent className="sm:max-w-lg!">
+ <AlertDialogHeader>
+ <AlertDialogMedia>
+ <Sparkles />
+ </AlertDialogMedia>
+ <AlertDialogTitle>Start your {prod.name} trial?</AlertDialogTitle>
+ <AlertDialogDescription>
+ Your free trial starts now with no charge. When it ends, {prod.name} continues on the
+ monthly {trialPlanObj?.name ?? "Pro"} plan and you&apos;ll be billed for what you use.
+ Cancel anytime before then to avoid charges.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="org"
+ isDisabled={startTrial.isPending}
+ isPending={startTrial.isPending}
+ onClick={(e) => {
+ e.preventDefault();
+ handleConfirmTrial();
+ }}
>
- Remove
- </Button>
- )}
- </SheetFooter>
- </SheetContent>
- </Sheet>
+ Start free trial
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
);
};
diff --git a/frontend/src/pages/organization/BillingV2Page/components/RemoveProductModal.tsx b/frontend/src/pages/organization/BillingV2Page/components/RemoveProductModal.tsx
index ff87cb458b..b84b8712f4 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/RemoveProductModal.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/RemoveProductModal.tsx
@@ -184,7 +184,7 @@ export const RemoveProductModal = ({ orgId, product, onClose, onRemoved }: Props
<div className="flex items-center justify-between">
<span className="text-mineshaft-300">New recurring total</span>
<span className="font-semibold text-foreground tabular-nums">
- {fmtMoney(preview.data.estimatedTotal, 2)}
+ {fmtMoney(preview.data.nextRecurringTotal, 2)}
</span>
</div>
</div>
diff --git a/frontend/src/pages/organization/BillingV2Page/components/shared.tsx b/frontend/src/pages/organization/BillingV2Page/components/shared.tsx
index 4fa194de96..12d78d622c 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/shared.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/shared.tsx
@@ -1,8 +1,22 @@
-import { Box } from "lucide-react";
+import { ReactNode } from "react";
+import { Box, MinusIcon, PlusIcon } from "lucide-react";
import { DynamicIcon, type IconName } from "lucide-react/dynamic";
-import { Badge } from "@app/components/v3";
-import { BillingV2CatalogProduct } from "@app/hooks/api";
+import { Badge, Button } from "@app/components/v3";
+import {
+ BillingV2CatalogProduct,
+ BillingV2Entitlement,
+ BillingV2EntitlementDim
+} from "@app/hooks/api";
+
+import {
+ dimAnnualCommitted,
+ dimBarSegments,
+ dimMonthlyRate,
+ dimOnDemandQuantity,
+ fmtMoney,
+ pluralizeUnit
+} from "../billing-v2-data";
type ProductIconProps = {
product: BillingV2CatalogProduct;
@@ -40,3 +54,122 @@ export const ProductIcon = ({ product, size = 36 }: ProductIconProps) => {
};
export const ActiveBadge = () => <Badge variant="success">Active</Badge>;
+
+// A YEARLY / MONTHLY cadence pill matching a product's billing cadence.
+export const CadenceBadge = ({ cadence }: { cadence: BillingV2Entitlement["cadence"] }) => {
+ if (cadence === "annual") {
+ return <Badge variant="info">Yearly</Badge>;
+ }
+ return <Badge variant="neutral">Monthly</Badge>;
+};
+
+// One usage bar for a product dimension. An annual committed dimension shows the committed portion
+// (blue) plus any on-demand overflow (amber) with a rate legend; a monthly/metered dimension shows a
+// single "{used} / {limit} · $rate/unit/mo" fill.
+export const DimensionMeter = ({ dim }: { dim: BillingV2EntitlementDim }) => {
+ const committed = dimAnnualCommitted(dim);
+ const { committedPct, onDemandPct } = dimBarSegments(dim);
+ const onDemandQty = dimOnDemandQuantity(dim);
+ const monthlyRate = dimMonthlyRate(dim);
+
+ let right: ReactNode;
+ if (committed) {
+ right = (
+ <>
+ <span className="font-medium text-foreground">{(dim.committed ?? 0).toLocaleString()}</span>{" "}
+ committed
+ {onDemandQty > 0 ? (
+ <>
+ {" · "}
+ <span className="font-medium text-warning">
+ {onDemandQty.toLocaleString()} on-demand
+ </span>
+ </>
+ ) : (
+ <> · {dim.used.toLocaleString()} used</>
+ )}
+ </>
+ );
+ } else {
+ right = (
+ <>
+ <span className="font-medium text-foreground">{dim.used.toLocaleString()}</span>
+ {dim.limit !== null ? ` / ${dim.limit.toLocaleString()}` : ` ${pluralizeUnit(dim.noun)}`}
+ {monthlyRate > 0 && <span> · {`${fmtMoney(monthlyRate)}/${dim.noun}/mo`}</span>}
+ </>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-baseline justify-between gap-2.5 text-xs">
+ <span className="text-muted">{dim.label}</span>
+ <span className="text-muted tabular-nums">{right}</span>
+ </div>
+ <div className="flex h-1.5 w-full gap-0.5 overflow-hidden rounded-full bg-border">
+ <div
+ className="h-full rounded-full bg-primary transition-all"
+ style={{ width: `${committedPct}%` }}
+ />
+ {onDemandPct > 0 && (
+ <div
+ className="h-full rounded-full bg-warning transition-all"
+ style={{ width: `${onDemandPct}%` }}
+ />
+ )}
+ </div>
+ {committed && (
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted">
+ {dim.committedRate !== undefined && (
+ <span className="flex items-center gap-1.5">
+ <span className="size-2.5 rounded-sm bg-primary" />
+ Committed {`${fmtMoney(dim.committedRate)} / ${dim.noun} /yr`}
+ </span>
+ )}
+ {dim.onDemandRate !== undefined && (
+ <span className="flex items-center gap-1.5">
+ <span className="size-2.5 rounded-sm bg-warning" />
+ On-demand {`${fmtMoney(dim.onDemandRate)} / ${dim.noun} /mo`}
+ </span>
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
+
+type StepperProps = {
+ value: number;
+ min?: number;
+ onChange: (value: number) => void;
+ isDisabled?: boolean;
+};
+
+// A small [-] [value] [+] quantity control for setting a commitment count.
+export const Stepper = ({ value, min = 0, onChange, isDisabled }: StepperProps) => (
+ <div className="flex items-center overflow-hidden rounded-md border border-border">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="rounded-none px-3"
+ isDisabled={isDisabled || value <= min}
+ onClick={() => onChange(Math.max(min, value - 1))}
+ aria-label="Decrease"
+ >
+ <MinusIcon className="size-4" />
+ </Button>
+ <span className="min-w-12 border-x border-border py-1.5 text-center text-sm font-medium text-foreground tabular-nums">
+ {value.toLocaleString()}
+ </span>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="rounded-none px-3"
+ isDisabled={isDisabled}
+ onClick={() => onChange(value + 1)}
+ aria-label="Increase"
+ >
+ <PlusIcon className="size-4" />
+ </Button>
+ </div>
+);