Skip to content

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

feat: updated based on feedback

=b2b6748b4714
diff --git a/backend/src/ee/routes/v1/license-v2-router.ts b/backend/src/ee/routes/v1/license-v2-router.ts
index ceee64bb92..099a03489d 100644
--- a/backend/src/ee/routes/v1/license-v2-router.ts
+++ b/backend/src/ee/routes/v1/license-v2-router.ts
@@ -91,6 +91,7 @@ const BillingV2EntitlementDimSchema = z.object({
used: z.number(),
limit: z.number().nullable(),
committed: z.number().nullable(),
+ commitAvailable: z.boolean(),
// 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.
@@ -98,7 +99,10 @@ const BillingV2EntitlementDimSchema = z.object({
onDemandRate: z.number().optional(),
rate: z.number().optional(),
freeBand: z.number().optional(),
- onDemandAmount: z.number()
+ onDemandAmount: z.number(),
+ canDecreaseNow: z.boolean().optional(),
+ renewalDate: z.string().nullable().optional(),
+ decreaseAllowedFrom: z.string().nullable().optional()
});
const BillingV2EntitlementSchema = z.object({
@@ -163,7 +167,8 @@ const BillingV2OverviewSchema = z.object({
invoices: BillingV2InvoiceSchema.array(),
entitlements: z.record(BillingV2EntitlementSchema),
trialedProductKeys: z.string().array(),
- onDemandAmount: z.number()
+ onDemandAmount: z.number(),
+ checkoutFrozen: z.boolean()
});
const BillingV2PreviewLineSchema = z.object({
@@ -175,8 +180,11 @@ const BillingV2PreviewLineSchema = z.object({
const BillingV2PreviewSchema = z.object({
currency: z.string(),
prorationAmount: z.number(),
+ additionalCharges: z.number(),
+ totalDueNow: z.number(),
nextInvoiceTotal: z.number(),
nextRecurringTotal: z.number(),
+ prorationDate: z.number().nullish(),
lines: BillingV2PreviewLineSchema.array()
});
@@ -184,11 +192,10 @@ const BillingV2PreviewSchema = z.object({
// subscription id comes back (the DB mirror catches up via webhook, so the UI refetches overview).
const BillingV2MutationResultSchema = z.object({ subscriptionId: z.string().optional() });
-// 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 BillingV2QuantitiesSchema = z.record(z.string().trim(), z.number().int().min(0));
const BillingV2CommitmentChangeSchema = z.object({
dimensionKey: z.string().trim(),
- quantity: z.number().int().min(1)
+ quantity: z.number().int().min(0)
});
export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
@@ -294,45 +301,6 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
}
});
- server.route({
- method: "POST",
- url: "/:organizationId/billing/v2/checkout-session",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- params: z.object({ organizationId: z.string().trim() }),
- body: z.object({
- 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
- }),
- response: {
- 200: z.object({
- outcome: z.enum(["checkout_created", "subscription_updated"]),
- checkoutUrl: z.string().optional(),
- subscriptionId: z.string().optional()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- return server.services.licenseV2.checkoutSession({
- orgId: req.params.organizationId,
- actor: buildActor(req.permission),
- productId: req.body.productId,
- plan: req.body.plan,
- cadence: req.body.cadence,
- commitments: req.body.commitments,
- email: req.body.email,
- returnPath: req.body.returnPath
- });
- }
- });
-
server.route({
method: "POST",
url: "/:organizationId/billing/v2/payment-method",
@@ -369,7 +337,7 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
addProductId: z.string().trim().optional(),
plan: z.string().trim().optional(),
cadence: z.enum(["monthly", "annual"]).optional(),
- commitments: BillingV2CommitmentsSchema.optional(),
+ quantities: BillingV2QuantitiesSchema.optional(),
removeProductId: z.string().trim().optional(),
commitmentChanges: BillingV2CommitmentChangeSchema.array().optional()
})
@@ -388,7 +356,7 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
addProductId: req.body.addProductId,
plan: req.body.plan,
cadence: req.body.cadence,
- commitments: req.body.commitments,
+ quantities: req.body.quantities,
removeProductId: req.body.removeProductId,
commitmentChanges: req.body.commitmentChanges
});
@@ -397,7 +365,7 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
server.route({
method: "POST",
- url: "/:organizationId/billing/v2/subscription/items",
+ url: "/:organizationId/billing/v2/subscription/products",
config: {
rateLimit: writeLimit
},
@@ -407,28 +375,40 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
productId: z.string().trim(),
plan: z.string().trim().optional(),
cadence: z.enum(["monthly", "annual"]).optional(),
- commitments: BillingV2CommitmentsSchema.optional()
+ quantities: BillingV2QuantitiesSchema.optional(),
+ returnPath: ReturnPathSchema,
+ prorationDate: z.number().optional()
}),
response: {
- 200: BillingV2MutationResultSchema
+ 200: z.object({
+ outcome: z.enum(["checkout_created", "subscription_updated"]),
+ checkoutUrl: z.string().optional(),
+ subscriptionId: z.string().optional()
+ })
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
- return server.services.licenseV2.addProduct({
+ // A first-touch org has no Stripe customer yet, so the server needs an email. Take it from the
+ // authenticated user (JWT-only route) rather than trusting a client-supplied value.
+ const email = req.auth.authMode === AuthMode.JWT ? (req.auth.user.email ?? undefined) : undefined;
+ return server.services.licenseV2.buyProduct({
orgId: req.params.organizationId,
actor: buildActor(req.permission),
productId: req.body.productId,
plan: req.body.plan,
cadence: req.body.cadence,
- commitments: req.body.commitments
+ quantities: req.body.quantities,
+ email,
+ returnPath: req.body.returnPath,
+ prorationDate: req.body.prorationDate
});
}
});
server.route({
method: "DELETE",
- url: "/:organizationId/billing/v2/subscription/items/:productId",
+ url: "/:organizationId/billing/v2/subscription/products/:productId",
config: {
rateLimit: writeLimit
},
@@ -448,8 +428,10 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
}
});
+ // Start / change annual commitments across dimensions in one atomic call. Increase is charged now; a
+ // decrease is rejected unless the dimension's window is open (server-enforced).
server.route({
- method: "POST",
+ method: "PUT",
url: "/:organizationId/billing/v2/subscription/commitments",
config: {
rateLimit: writeLimit
@@ -457,8 +439,8 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
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).max(20)
+ changes: BillingV2CommitmentChangeSchema.array().min(1).max(20),
+ prorationDate: z.number().optional()
}),
response: {
200: BillingV2MutationResultSchema
@@ -466,10 +448,11 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
- return server.services.licenseV2.changeCommitment({
+ return server.services.licenseV2.changeCommitments({
orgId: req.params.organizationId,
actor: buildActor(req.permission),
- changes: req.body.changes
+ changes: req.body.changes,
+ prorationDate: req.body.prorationDate
});
}
});
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 e488572efb..0f0b6257e3 100644
--- a/backend/src/ee/services/license-v2/license-v2-service.ts
+++ b/backend/src/ee/services/license-v2/license-v2-service.ts
@@ -7,11 +7,12 @@ import { logger } from "@app/lib/logger";
import { TLicenseClientFactory } from "@app/services/license-client";
import {
TCatalogProduct,
- TCheckoutLineItem,
TEntitlementOrg,
+ TProductLineItem,
TSubscriptionPreviewPayload,
TSubscriptionResponse
} from "@app/services/license-client/license-client-types";
+import { TMeteredFeature } from "@app/services/license-client/usage/usage-counters";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { isV2SelfHostedLicenseKey } from "../license/license-fns";
@@ -29,11 +30,10 @@ import {
BillingV2Preview,
BillingV2SubState,
TAddBillingV2PaymentMethodDTO,
- TAddBillingV2ProductDTO,
TBillingV2SubscriptionLifecycleDTO,
+ TBuyBillingV2ProductDTO,
TCancelBillingV2TrialDTO,
TChangeBillingV2CommitmentDTO,
- TCreateBillingV2CheckoutSessionDTO,
TCreateBillingV2PortalSessionDTO,
TGetBillingV2CatalogDTO,
TGetBillingV2OverviewDTO,
@@ -46,6 +46,10 @@ type TLicenseV2ServiceFactoryDep = {
envConfig: Pick<TEnvConfig, "LICENSE_SERVER_V2_MODE" | "LICENSE_KEY" | "SITE_URL">;
orgDAL: Pick<TOrgDALFactory, "findById">;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
+ // Same metered-feature/count-fn pairs the usage pipeline registers; used to seed a purchase's initial
+ // per_resource quantities with the org's present provisioned count so the previewed/charged figure is
+ // truthful (identities, active certs, ...).
+ meteredFeatures: TMeteredFeature[];
licenseClient: Pick<
TLicenseClientFactory,
| "getEntitlements"
@@ -55,12 +59,11 @@ type TLicenseV2ServiceFactoryDep = {
| "getSubscription"
| "getCloudPlan"
| "getBillingProfile"
- | "createCheckout"
| "createPortal"
| "previewSubscriptionChange"
- | "addSubscriptionItems"
- | "removeSubscriptionItem"
- | "changeCommitment"
+ | "buyProduct"
+ | "removeProduct"
+ | "changeCommitments"
| "startTrial"
| "cancelTrial"
| "getTrials"
@@ -318,60 +321,75 @@ const toCatalogProduct = (product: TCatalogProduct): BillingV2CatalogProduct =>
};
};
-// 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,
- 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).
- const plan = planTier
- ? product.plans.find((candidate) => candidate.tier === planTier && candidate.selfServe === true)
- : findPaidSelfServePlan(product);
- if (!plan) {
- return null;
- }
-
- const hasPriceForCadence = plan.prices.some(
- (candidate) => candidate.cadence === cadence && isKnownPriceKind(candidate.kind)
- );
- const baseForCadence = cadence === "annual" ? plan.basePriceAnnualCents : plan.basePriceMonthlyCents;
- const hasBase = baseForCadence !== null && baseForCadence !== undefined;
- if (!hasPriceForCadence && !hasBase) {
- return null;
- }
-
- const item: TCheckoutLineItem = { productId: product.id, plan: plan.tier, cadence };
- if (commitments && Object.keys(commitments).length > 0) {
- // Commitment mode (prepaid annual units with monthly on-demand overage) only makes sense when the
- // committed dimension is priced on BOTH cadences: annual for the commitment, monthly for the
- // overage. Reject it for a single-cadence plan (annual-only or monthly-only).
- const dimensionHasBothCadences = (dimensionKey: string): boolean => {
- const prices = plan.prices.filter((price) => price.dimensionKey === dimensionKey && isKnownPriceKind(price.kind));
- return prices.some((price) => price.cadence === "annual") && prices.some((price) => price.cadence === "monthly");
- };
- const unsupported = Object.keys(commitments).filter((dimensionKey) => !dimensionHasBothCadences(dimensionKey));
- if (cadence !== "annual" || unsupported.length > 0) {
- throw new BadRequestError({
- message: "Commitment mode is only available when the plan has both monthly and annual pricing."
- });
- }
- item.commitments = commitments;
- }
- return [item];
-};
-
export const licenseV2ServiceFactory = ({
envConfig,
orgDAL,
permissionService,
+ meteredFeatures,
licenseClient
}: TLicenseV2ServiceFactoryDep) => {
+ const countByDimensionKey = new Map(meteredFeatures.map(({ feature, count }) => [feature.key, count]));
+
+ const buildProductLineItem = async (
+ product: TCatalogProduct,
+ cadence: "monthly" | "annual",
+ orgId: string,
+ planTier?: string,
+ committed?: Record<string, number>
+ ): Promise<{
+ planTier: string;
+ quantities?: Record<string, number>;
+ declaredUsage: Record<string, number>;
+ } | null> => {
+ const plan = planTier
+ ? product.plans.find((candidate) => candidate.tier === planTier && candidate.selfServe === true)
+ : findPaidSelfServePlan(product);
+ if (!plan) {
+ return null;
+ }
+
+ const hasPriceForCadence = plan.prices.some(
+ (candidate) => candidate.cadence === cadence && isKnownPriceKind(candidate.kind)
+ );
+ const baseForCadence = cadence === "annual" ? plan.basePriceAnnualCents : plan.basePriceMonthlyCents;
+ const hasBase = baseForCadence !== null && baseForCadence !== undefined;
+ if (!hasPriceForCadence && !hasBase) {
+ return null;
+ }
+
+ const perUnitPrices = plan.prices.filter((price) => price.cadence === cadence && price.kind === PER_UNIT_KIND);
+ // The org's present provisioned count per priced per_resource dimension (null when we can't meter it).
+ const counted = await Promise.all(
+ perUnitPrices.map(async (price) => {
+ const countFn = countByDimensionKey.get(price.dimensionKey);
+ const present = countFn ? await countFn(orgId) : null;
+ return { dimensionKey: price.dimensionKey, present, included: price.includedQuantity ?? 0 };
+ })
+ );
+
+ // declaredUsage: actual current usage; only dimensions we can meter (the server floors omitted ones).
+ const declaredUsage: Record<string, number> = {};
+ counted.forEach(({ dimensionKey, present }) => {
+ if (present !== null) {
+ declaredUsage[dimensionKey] = present;
+ }
+ });
+
+ // quantities: committed units, only for an annual commitment (ignored by the server on monthly). The
+ // buyer's entered commitment wins; otherwise commit the present count (or the included floor) so an
+ // annual line still prices. Never sourced into declaredUsage.
+ const quantities =
+ cadence === "annual"
+ ? Object.fromEntries(
+ counted.map(({ dimensionKey, present, included }) => [
+ dimensionKey,
+ committed?.[dimensionKey] ?? present ?? included
+ ])
+ )
+ : undefined;
+
+ return { planTier: plan.tier, quantities, declaredUsage };
+ };
// A self-hosted v2 license is managed out-of-band: the billing surface is read-only. Self-serve
// mutations don't need an explicit guard here, the self-hosted license client rejects them itself.
const isSelfHostedLicense = isV2SelfHostedLicenseKey(envConfig.LICENSE_KEY ?? "");
@@ -466,11 +484,21 @@ export const licenseV2ServiceFactory = ({
used,
limit: dimension.limit ?? null,
committed,
+ // Whether this customer can commit this dimension, per their pinned plan version (NOT the
+ // catalog). The UI gates the commit action on this for owned products.
+ commitAvailable: dimension.commitAvailable ?? false,
onDemandAmount,
...(hasCommittedRate ? { committedRate: centsToDollars(dimension.committedRateCents) } : {}),
...(onDemandRate !== undefined ? { onDemandRate } : {}),
...(metered && hasRate ? { rate: centsToDollars(dimension.rateCents) } : {}),
- ...(metered && hasFreeBand ? { freeBand: dimension.freeBand as number } : {})
+ ...(metered && hasFreeBand ? { freeBand: dimension.freeBand as number } : {}),
+ // Commitment-decrease window: the UI locks the stepper's floor to the current committed
+ // quantity unless canDecreaseNow, and shows when a decrease opens (decreaseAllowedFrom).
+ ...(dimension.canDecreaseNow !== null && dimension.canDecreaseNow !== undefined
+ ? { canDecreaseNow: dimension.canDecreaseNow }
+ : {}),
+ ...(dimension.renewalDate ? { renewalDate: formatDate(dimension.renewalDate) } : {}),
+ ...(dimension.decreaseAllowedFrom ? { decreaseAllowedFrom: formatDate(dimension.decreaseAllowedFrom) } : {})
};
});
@@ -748,7 +776,8 @@ export const licenseV2ServiceFactory = ({
invoices,
entitlements,
trialedProductKeys,
- onDemandAmount
+ onDemandAmount,
+ checkoutFrozen: subscription?.capabilities?.checkoutFrozen ?? false
};
return { overview };
@@ -799,16 +828,17 @@ export const licenseV2ServiceFactory = ({
return openPortal(orgId, returnPath);
};
- const checkoutSession = async ({
+ const buyProduct = async ({
orgId,
actor,
productId,
plan,
cadence,
- commitments,
+ quantities,
email,
- returnPath
- }: TCreateBillingV2CheckoutSessionDTO) => {
+ returnPath,
+ prorationDate
+ }: TBuyBillingV2ProductDTO) => {
await ensureManageBilling(orgId, actor);
const catalog = await licenseClient.getCatalog();
@@ -817,22 +847,29 @@ export const licenseV2ServiceFactory = ({
throw new NotFoundError({ message: `Product with ID '${productId}' not found` });
}
- const items = buildCheckoutItems(product, normalizeCadence(cadence), plan, commitments);
- if (!items) {
+ // `quantities` from the client is the buyer's committed choice; the service derives declaredUsage.
+ const resolved = await buildProductLineItem(product, normalizeCadence(cadence), orgId, plan, quantities);
+ if (!resolved) {
throw new BadRequestError({ message: "This product is not available for self-serve checkout" });
}
- const result = await licenseClient.createCheckout(orgId, {
- items,
+ const result = await licenseClient.buyProduct(orgId, {
+ productId,
+ plan: resolved.planTier,
+ cadence: normalizeCadence(cadence),
+ quantities: resolved.quantities,
+ declaredUsage: resolved.declaredUsage,
email,
- returnPath,
- returnUrl: buildReturnUrl(orgId, returnPath)
+ returnUrl: buildReturnUrl(orgId, returnPath),
+ prorationDate
});
+
if (result.outcome === "subscription_updated") {
+ await licenseClient.invalidateEntitlements(orgId);
return { outcome: "subscription_updated" as const, subscriptionId: result.subscriptionId };
}
- // checkout_created: the customer must finish in Stripe Checkout.
+ // checkout_created: the customer must finish in Stripe Checkout; entitlements change via webhook.
if (!result.checkoutUrl) {
throw new InternalServerError({ message: "Checkout session did not return a URL" });
}
@@ -844,35 +881,13 @@ export const licenseV2ServiceFactory = ({
return openPortal(orgId, returnPath);
};
- // Resolve a catalog product id + cadence into the license-server line items, shared by the
- // preview and add paths so both price the same way checkout does.
- const resolveAddItems = async (
- productId: string,
- cadence?: "monthly" | "annual",
- 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, commitments);
- if (!items) {
- throw new BadRequestError({ message: "This product is not available for self-serve checkout" });
- }
- return items;
- };
-
- // Preview the proration impact of adding or removing a product before it is committed, so the UI
- // can show an explicit confirmation. Amounts come back as dollars (cents / 100) to match overview.
const previewChange = async ({
orgId,
actor,
addProductId,
plan,
cadence,
- commitments,
+ quantities,
removeProductId,
commitmentChanges
}: TPreviewBillingV2ChangeDTO): Promise<{ preview: BillingV2Preview }> => {
@@ -883,7 +898,23 @@ export const licenseV2ServiceFactory = ({
const payload: TSubscriptionPreviewPayload = {};
if (addProductId) {
- payload.add = await resolveAddItems(addProductId, cadence, plan, commitments);
+ const catalog = await licenseClient.getCatalog();
+ const product = catalog?.products.find((candidate) => candidate.id === addProductId);
+ if (!product) {
+ throw new NotFoundError({ message: `Product with ID '${addProductId}' not found` });
+ }
+ const resolved = await buildProductLineItem(product, normalizeCadence(cadence), orgId, plan, quantities);
+ if (!resolved) {
+ throw new BadRequestError({ message: "This product is not available for self-serve checkout" });
+ }
+ const addItem: TProductLineItem = {
+ productId: addProductId,
+ plan: resolved.planTier,
+ cadence: normalizeCadence(cadence),
+ quantities: resolved.quantities,
+ declaredUsage: resolved.declaredUsage
+ };
+ payload.add = [addItem];
}
if (removeProductId) {
payload.remove = [removeProductId];
@@ -893,12 +924,16 @@ export const licenseV2ServiceFactory = ({
}
const preview = await licenseClient.previewSubscriptionChange(orgId, payload);
+ const totalDueNowCents = preview.totalDueNow ?? preview.prorationAmount + preview.additionalCharges;
return {
preview: {
currency: preview.currency,
prorationAmount: centsToDollars(preview.prorationAmount),
+ additionalCharges: centsToDollars(preview.additionalCharges),
+ totalDueNow: centsToDollars(totalDueNowCents),
nextInvoiceTotal: centsToDollars(preview.nextInvoiceTotal),
nextRecurringTotal: centsToDollars(preview.nextRecurringTotal),
+ prorationDate: preview.prorationDate ?? null,
lines: preview.lines.map((line) => ({
description: line.description,
amount: centsToDollars(line.amount),
@@ -908,37 +943,17 @@ export const licenseV2ServiceFactory = ({
};
};
- // 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, commitments }: TAddBillingV2ProductDTO) => {
- await ensureManageBilling(orgId, actor);
- 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; the server prorates each at commit time, so the preview
- // total may drift slightly if the user waits before confirming. A mid-loop failure leaves earlier
- // changes applied and surfaces the error to retry the rest.
- const changeCommitment = async ({ orgId, actor, changes }: TChangeBillingV2CommitmentDTO) => {
+ const changeCommitments = 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
- });
- subscriptionId = result.subscriptionId ?? subscriptionId;
- }
+ const result = await licenseClient.changeCommitments(orgId, {
+ dimensions: changes.map((change) => ({ dimensionKey: change.dimensionKey, quantity: change.quantity })),
+ prorationDate
+ });
await licenseClient.invalidateEntitlements(orgId);
- return { subscriptionId };
+ return { subscriptionId: result.subscriptionId };
};
// Start a plan-scoped self-serve trial. The trial is granted immediately (no upfront charge);
@@ -973,7 +988,7 @@ export const licenseV2ServiceFactory = ({
// Portal cannot do. The license server prorates at commit time (Stripe default = now).
const removeProduct = async ({ orgId, actor, productId }: TRemoveBillingV2ProductDTO) => {
await ensureManageBilling(orgId, actor);
- const result = await licenseClient.removeSubscriptionItem(orgId, productId);
+ const result = await licenseClient.removeProduct(orgId, productId);
await licenseClient.invalidateEntitlements(orgId);
return { subscriptionId: result.subscriptionId };
};
@@ -999,12 +1014,11 @@ export const licenseV2ServiceFactory = ({
refreshEntitlements,
getCatalog,
portalSession,
- checkoutSession,
+ buyProduct,
addPaymentMethod,
previewChange,
- addProduct,
removeProduct,
- changeCommitment,
+ changeCommitments,
startTrial,
cancelTrial,
cancelSubscription,
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 188c5567f3..f1a3d46abe 100644
--- a/backend/src/ee/services/license-v2/license-v2-types.ts
+++ b/backend/src/ee/services/license-v2/license-v2-types.ts
@@ -99,11 +99,20 @@ export type BillingV2EntitlementDim = {
used: number;
limit: number | null;
committed: number | null;
+ // Whether this customer can commit this dimension annually, per their pinned plan version (from the
+ // subscription read, NOT the catalog). Grandfather-safe; the UI gates the commit action on this.
+ commitAvailable: boolean;
committedRate?: number;
onDemandRate?: number;
rate?: number;
freeBand?: number;
onDemandAmount: number;
+ // Annual-commitment lifecycle, present only for a real per_resource commitment. canDecreaseNow is
+ // false until the final window before renewal (a decrease is rejected until then); renewalDate and
+ // decreaseAllowedFrom are formatted display dates.
+ canDecreaseNow?: boolean;
+ renewalDate?: string | null;
+ decreaseAllowedFrom?: string | null;
};
export type BillingV2Entitlement = {
@@ -184,6 +193,7 @@ export type BillingV2Overview = {
trialedProductKeys: string[];
// Total monthly on-demand overage across all products (dollars), for the summary's on-demand note.
onDemandAmount: number;
+ checkoutFrozen: boolean;
};
export type TGetBillingV2OverviewDTO = {
@@ -202,17 +212,18 @@ export type TCreateBillingV2PortalSessionDTO = {
returnPath?: string;
};
-export type TCreateBillingV2CheckoutSessionDTO = {
+export type TBuyBillingV2ProductDTO = {
orgId: string;
actor: OrgServiceActor;
productId: string;
// 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>;
+ quantities?: Record<string, number>;
email?: string;
returnPath?: string;
+ // Echoed from a prior preview so the applied charge matches the previewed one.
+ prorationDate?: number;
};
export type TAddBillingV2PaymentMethodDTO = {
@@ -230,8 +241,11 @@ export type BillingV2PreviewLine = {
export type BillingV2Preview = {
currency: string;
prorationAmount: number;
+ additionalCharges: number;
+ totalDueNow: number;
nextInvoiceTotal: number;
nextRecurringTotal: number;
+ prorationDate?: number | null;
lines: BillingV2PreviewLine[];
};
@@ -248,36 +262,26 @@ 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>;
+ quantities?: Record<string, number>;
removeProductId?: string;
// Per_resource commitment quantity changes to preview against the existing subscription.
commitmentChanges?: BillingV2CommitmentChange[];
};
-export type TAddBillingV2ProductDTO = {
- orgId: string;
- actor: OrgServiceActor;
- productId: string;
- // 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 = {
orgId: string;
actor: OrgServiceActor;
productId: string;
};
-// Apply one or more previewed per_resource commitment changes. The service loops the single-dimension
-// apply per change; each prorates at commit time on the server (no client-supplied timestamp).
+// Start / change annual commitments across dimensions in one atomic call. Increase is charged now; a
+// decrease is rejected by the server unless the dimension's decrease window is open. prorationDate is
+// echoed from a prior preview for dimensions that already have a commit item.
export type TChangeBillingV2CommitmentDTO = {
orgId: string;
actor: OrgServiceActor;
changes: BillingV2CommitmentChange[];
+ prorationDate?: number;
};
export type TStartBillingV2TrialDTO = {
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index eb0a90ddf2..81f1b6e8a4 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -855,6 +855,7 @@ export const registerRoutes = async (
envConfig,
orgDAL,
permissionService,
+ meteredFeatures,
licenseClient
});
diff --git a/backend/src/services/license-client/license-client-backends.ts b/backend/src/services/license-client/license-client-backends.ts
index be88b41d5e..098c64cac3 100644
--- a/backend/src/services/license-client/license-client-backends.ts
+++ b/backend/src/services/license-client/license-client-backends.ts
@@ -12,14 +12,13 @@ import {
sessionResponseSchema,
subscriptionPreviewResponseSchema,
subscriptionResponseSchema,
- TAddSubscriptionItemsPayload,
TBillingProfileResponse,
+ TBuyProductPayload,
TCancelTrialPayload,
TCatalogResponse,
- TChangeCommitmentPayload,
+ TChangeCommitmentsPayload,
TCheckoutResult,
TCloudPlanResponse,
- TCreateCheckoutPayload,
TCreatePortalPayload,
TEntitlementOrg,
TEntitlementsResponse,
@@ -69,13 +68,37 @@ export const mintServiceToken = (signingKey: string): string =>
// product; cancel the subscription instead"); when it has none, fall back to the generic error
// default rather than a status code the customer can't act on. 5xx bodies may carry internal detail,
// so those stay generic.
+// Friendly, action-oriented copy for the license server's machine error codes (details.code). Resolved
+// here so the whole billing surface throws a user-facing message the frontend just renders (no per-code
+// branching in the UI). Falls back to the server's own message when the code is unknown/absent.
+const BILLING_ERROR_MESSAGES: Record<string, string> = {
+ commitment_decrease_locked: "Commitments can't be reduced until the final window before your renewal.",
+ cap_exceeded: "That amount is above the limit available on your plan.",
+ plan_cadence_not_offered: "Your current plan version doesn't offer this billing option.",
+ product_already_held: "You already have this product. Remove it before adding it again.",
+ past_due: "There's an unpaid invoice on your account. Resolve payment before making changes.",
+ resubscribe_cooldown: "This product was removed recently. Please wait a bit before resubscribing."
+};
+
const throwIfResponseError = async (res: Response): Promise<void> => {
if (res.ok) {
return;
}
if (res.status >= 400 && res.status < 500) {
- const body = (await res.json().catch(() => null)) as { message?: string } | null;
- throw new BadRequestError({ message: body?.message });
+ const body = (await res.json().catch(() => null)) as {
+ error?: string;
+ message?: string;
+ details?: { code?: string };
+ } | null;
+ // Resolve the contract's machine code (details.code) to friendly copy so the message thrown here is
+ // user-facing; keep the code in details for any caller that still branches on it. The envelope uses
+ // `error`; older servers used `message`, so read both as the fallback.
+ const code = body?.details?.code;
+ const message = (code && BILLING_ERROR_MESSAGES[code]) || body?.error || body?.message;
+ throw new BadRequestError({
+ message,
+ details: code ? { code } : undefined
+ });
}
throw new InternalServerError({ message: "Billing service error" });
};
@@ -191,8 +214,10 @@ export const licenseServerBackend = (
return billingProfileResponseSchema.parse(body);
},
- createCheckoutSession: async (orgId: string, payload: TCreateCheckoutPayload): Promise<TCheckoutResult> => {
- const url = new URL(orgScoped(orgId, "/billing/checkout-session"), serverUrl);
+ // Buy/add one product. Self-selects append-to-live-subscription vs open a hosted Checkout server
+ // side, so the caller never branches on subscription state.
+ buyProduct: async (orgId: string, payload: TBuyProductPayload): Promise<TCheckoutResult> => {
+ const url = new URL(orgScoped(orgId, "/subscription/products"), serverUrl);
const res = await fetch(url, {
method: "POST",
headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}`, "Content-Type": "application/json" },
@@ -233,21 +258,9 @@ export const licenseServerBackend = (
return subscriptionPreviewResponseSchema.parse(body);
},
- addSubscriptionItems: async (orgId: string, payload: TAddSubscriptionItemsPayload): Promise<TCheckoutResult> => {
- const url = new URL(orgScoped(orgId, "/subscription/items"), 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);
- },
-
- removeSubscriptionItem: async (orgId: string, productId: string): Promise<TCheckoutResult> => {
- const url = new URL(orgScoped(orgId, `/subscription/items/${encodeURIComponent(productId)}`), serverUrl);
+ // Remove one product. Removing the last product cancels the subscription; idempotent when absent.
+ removeProduct: async (orgId: string, productId: string): Promise<TCheckoutResult> => {
+ const url = new URL(orgScoped(orgId, `/subscription/products/${encodeURIComponent(productId)}`), serverUrl);
const res = await fetch(url, {
method: "DELETE",
headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}` },
@@ -258,12 +271,12 @@ export const licenseServerBackend = (
return checkoutResultSchema.parse(body);
},
- // Apply a previewed per_resource commitment change. The server prorates at commit time; the payload
- // carries no proration timestamp, so the caller can't influence the charged amount.
- changeCommitment: async (orgId: string, payload: TChangeCommitmentPayload): Promise<TCheckoutResult> => {
+ // Start / change annual commitments across dimensions, all-or-nothing. prorationDate (echoed from a
+ // prior preview) applies to dimensions that already have a commit item.
+ changeCommitments: async (orgId: string, payload: TChangeCommitmentsPayload): Promise<TCheckoutResult> => {
const url = new URL(orgScoped(orgId, "/subscription/commitments"), serverUrl);
const res = await fetch(url, {
- method: "POST",
+ method: "PUT",
headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}`, "Content-Type": "application/json" },
body: JSON.stringify(payload),
redirect: "manual"
@@ -428,12 +441,11 @@ export const licenseServerSelfHostedBackend = (
fetchCloudPlan: notSupportedOnSelfHosted("fetchCloudPlan"),
fetchBillingProfile: notSupportedOnSelfHosted("fetchBillingProfile"),
- createCheckoutSession: notSupportedOnSelfHosted("createCheckoutSession"),
createPortalSession: notSupportedOnSelfHosted("createPortalSession"),
previewSubscriptionChange: notSupportedOnSelfHosted("previewSubscriptionChange"),
- addSubscriptionItems: notSupportedOnSelfHosted("addSubscriptionItems"),
- removeSubscriptionItem: notSupportedOnSelfHosted("removeSubscriptionItem"),
- changeCommitment: notSupportedOnSelfHosted("changeCommitment"),
+ buyProduct: notSupportedOnSelfHosted("buyProduct"),
+ removeProduct: notSupportedOnSelfHosted("removeProduct"),
+ changeCommitments: notSupportedOnSelfHosted("changeCommitments"),
startTrial: notSupportedOnSelfHosted("startTrial"),
cancelTrial: notSupportedOnSelfHosted("cancelTrial"),
fetchTrials: notSupportedOnSelfHosted("fetchTrials"),
diff --git a/backend/src/services/license-client/license-client-types.ts b/backend/src/services/license-client/license-client-types.ts
index 89ad83fe3e..d930d8a526 100644
--- a/backend/src/services/license-client/license-client-types.ts
+++ b/backend/src/services/license-client/license-client-types.ts
@@ -141,7 +141,11 @@ const subscriptionItemDimensionSchema = z
committedRateCents: z.number().nullish(),
onDemandRateCents: z.number().nullish(),
freeBand: z.number().nullish(),
- rateCents: z.number().nullish()
+ rateCents: z.number().nullish(),
+ commitAvailable: z.boolean().default(false),
+ renewalDate: z.number().nullish(),
+ canDecreaseNow: z.boolean().nullish(),
+ decreaseAllowedFrom: z.number().nullish()
})
.passthrough();
@@ -199,6 +203,12 @@ const subscriptionBillingSchema = z
export const subscriptionResponseSchema = z
.object({
status: z.string(),
+ // Mutating billing actions are frozen server-side (DISABLE_CHECKOUT); the client disables controls
+ // ahead of a 503 rather than discovering it on submit.
+ capabilities: z
+ .object({ checkoutFrozen: z.boolean().default(false) })
+ .passthrough()
+ .nullish(),
// Per-line billing: there is no subscription-level cadence/period/total (a subscription can mix
// monthly and annual lines). These top-level fields are legacy summaries kept nullish for
// back-compat with older servers; read `billing` for the authoritative per-line view.
@@ -229,10 +239,9 @@ export const checkoutResultSchema = z
})
.passthrough();
-// Proration preview for an add/remove against an existing subscription. prorationAmount is signed:
-// positive is charged now (an add), negative is a credit toward the next invoice (a removal). The
-// server prorates at request time; no client-supplied timestamp is accepted (it would let a caller
-// pick a cheaper proration instant), so the preview carries an amount but not a timestamp to echo.
+// Proration preview for an add/remove/commitment change. prorationAmount is signed: positive is
+// charged now (an add/increase), negative is a credit toward the next invoice (a removal). prorationDate
+// is the instant the server priced at; echo it back into the apply so it reproduces the exact charge.
const subscriptionPreviewLineSchema = z
.object({
description: z.string(),
@@ -245,8 +254,11 @@ export const subscriptionPreviewResponseSchema = z
.object({
currency: z.string(),
prorationAmount: z.number(),
+ additionalCharges: z.number().default(0),
+ totalDueNow: z.number().nullish(),
nextInvoiceTotal: z.number(),
nextRecurringTotal: z.number(),
+ prorationDate: z.number().nullish(),
lines: z.array(subscriptionPreviewLineSchema).default([])
})
.passthrough();
@@ -337,40 +349,40 @@ export type TCloudPlanResponse = z.infer<typeof cloudPlanResponseSchema>;
export type TBillingProfileResponse = z.infer<typeof billingProfileResponseSchema>;
export type TSubscriptionPreview = z.infer<typeof subscriptionPreviewResponseSchema>;
-export type TCheckoutLineItem = {
+export type TProductLineItem = {
productId: string;
plan: string;
- cadence: string;
- // Legacy per-unit quantities (pre-commitment). Superseded by commitments for an annual per_resource
- // line; kept optional so the server tolerates either during rollout.
+ cadence?: string;
quantities?: Record<string, number>;
- // Per-dimension committed quantity; REQUIRED for an annual per_resource line, omitted for monthly.
- commitments?: Record<string, number>;
+ declaredUsage?: Record<string, number>;
};
-// A single per_resource commitment quantity change (preview) applied post-purchase.
+// A single per_resource commitment quantity change (shared by preview commitmentChanges and the
+// multi-dimension commitment apply).
export type TCommitmentChange = {
dimensionKey: string;
quantity: number;
};
export type TSubscriptionPreviewPayload = {
- add?: TCheckoutLineItem[];
+ add?: TProductLineItem[];
remove?: string[];
commitmentChanges?: TCommitmentChange[];
};
-export type TAddSubscriptionItemsPayload = {
- items: TCheckoutLineItem[];
-};
-
-export type TCreateCheckoutPayload = {
- items: TCheckoutLineItem[];
+export type TBuyProductPayload = {
+ productId: string;
+ plan: string;
+ cadence?: string;
+ // Committed units (annual commitment lines only; ignored on monthly).
+ quantities?: Record<string, number>;
+ // Present actual usage per per_resource dimension (sizes a monthly line, seeds the usage reading).
+ declaredUsage?: Record<string, number>;
email?: string;
// Absolute return URL; its origin must be in the license server's CUSTOMER_PORTAL_ORIGINS allowlist
- // (the multi-region fix). returnPath is the relative back-compat fallback.
+ // (the multi-region fix).
returnUrl?: string;
- returnPath?: string;
+ prorationDate?: number;
};
export type TCreatePortalPayload = {
@@ -378,11 +390,11 @@ export type TCreatePortalPayload = {
returnPath?: string;
};
-// Self-serve apply of a previewed commitment change. The server prorates at commit time; the caller
-// cannot supply a proration timestamp (that would let a billing user pick a cheaper instant).
-export type TChangeCommitmentPayload = {
- dimensionKey: string;
- quantity: number;
+// Start / change annual commitments across dimensions (PUT /subscription/commitments), all-or-nothing.
+// prorationDate is echoed from a prior preview for dimensions that already have a commit item.
+export type TChangeCommitmentsPayload = {
+ dimensions: TCommitmentChange[];
+ prorationDate?: number;
};
export type TStartTrialPayload = {
@@ -447,13 +459,14 @@ export type TLicenseClientBackend = {
fetchSubscription: (orgId: string) => Promise<TSubscriptionResponse | null>;
fetchCloudPlan: (orgId: string) => Promise<TCloudPlanResponse | null>;
fetchBillingProfile: (orgId: string) => Promise<TBillingProfileResponse | null>;
- createCheckoutSession: (orgId: string, payload: TCreateCheckoutPayload) => Promise<TCheckoutResult>;
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>;
- // Apply a previewed per_resource commitment change (self-serve).
- changeCommitment: (orgId: string, payload: TChangeCommitmentPayload) => Promise<TCheckoutResult>;
+ // Buy/add one product; self-selects append vs hosted Checkout server side.
+ buyProduct: (orgId: string, payload: TBuyProductPayload) => Promise<TCheckoutResult>;
+ // Remove one product; removing the last product cancels the subscription.
+ removeProduct: (orgId: string, productId: string) => Promise<TCheckoutResult>;
+ // Start / change annual commitments across dimensions (all-or-nothing).
+ changeCommitments: (orgId: string, payload: TChangeCommitmentsPayload) => Promise<TCheckoutResult>;
// Start a plan-scoped self-serve trial.
startTrial: (orgId: string, payload: TStartTrialPayload) => Promise<TTrialResult>;
// Cancel an in-progress trial for a product (product → free; the trial never converts).
diff --git a/backend/src/services/license-client/license-client.ts b/backend/src/services/license-client/license-client.ts
index ed970d41e5..83b1f5a9f9 100644
--- a/backend/src/services/license-client/license-client.ts
+++ b/backend/src/services/license-client/license-client.ts
@@ -6,10 +6,9 @@ import { featureReaderFactory } from "./feature-reader";
import { licenseServerBackend, licenseServerSelfHostedBackend } from "./license-client-backends";
import { entitlementResolverFactory } from "./license-client-cache";
import {
- TAddSubscriptionItemsPayload,
+ TBuyProductPayload,
TCancelTrialPayload,
- TChangeCommitmentPayload,
- TCreateCheckoutPayload,
+ TChangeCommitmentsPayload,
TCreatePortalPayload,
TEntitlementOrg,
TLicenseClientBackend,
@@ -134,13 +133,6 @@ export const licenseClientFactory = ({ envConfig, keyStore }: TLicenseClientFact
return backend.fetchBillingProfile(orgId);
};
- const createCheckout = async (orgId: string, payload: TCreateCheckoutPayload) => {
- if (!backend) {
- throw new Error("license client backend is not configured");
- }
- return backend.createCheckoutSession(orgId, payload);
- };
-
const createPortal = async (orgId: string, payload: TCreatePortalPayload) => {
if (!backend) {
throw new Error("license client backend is not configured");
@@ -155,25 +147,25 @@ export const licenseClientFactory = ({ envConfig, keyStore }: TLicenseClientFact
return backend.previewSubscriptionChange(orgId, payload);
};
- const addSubscriptionItems = async (orgId: string, payload: TAddSubscriptionItemsPayload) => {
+ const buyProduct = async (orgId: string, payload: TBuyProductPayload) => {
if (!backend) {
throw new Error("license client backend is not configured");
}
- return backend.addSubscriptionItems(orgId, payload);
+ return backend.buyProduct(orgId, payload);
};
- const removeSubscriptionItem = async (orgId: string, productId: string) => {
+ const removeProduct = async (orgId: string, productId: string) => {
if (!backend) {
throw new Error("license client backend is not configured");
}
- return backend.removeSubscriptionItem(orgId, productId);
+ return backend.removeProduct(orgId, productId);
};
- const changeCommitment = async (orgId: string, payload: TChangeCommitmentPayload) => {
+ const changeCommitments = async (orgId: string, payload: TChangeCommitmentsPayload) => {
if (!backend) {
throw new Error("license client backend is not configured");
}
- return backend.changeCommitment(orgId, payload);
+ return backend.changeCommitments(orgId, payload);
};
const startTrial = async (orgId: string, payload: TStartTrialPayload) => {
@@ -221,12 +213,11 @@ export const licenseClientFactory = ({ envConfig, keyStore }: TLicenseClientFact
getSubscription,
getCloudPlan,
getBillingProfile,
- createCheckout,
createPortal,
previewSubscriptionChange,
- addSubscriptionItems,
- removeSubscriptionItem,
- changeCommitment,
+ buyProduct,
+ removeProduct,
+ changeCommitments,
startTrial,
cancelTrial,
getTrials,
diff --git a/backend/src/services/license-client/usage/usage-counter-dal.ts b/backend/src/services/license-client/usage/usage-counter-dal.ts
index 8b82ce589c..efbfb4fe38 100644
--- a/backend/src/services/license-client/usage/usage-counter-dal.ts
+++ b/backend/src/services/license-client/usage/usage-counter-dal.ts
@@ -65,28 +65,44 @@ export const usageCounterDALFactory = (db: TDbClient) => {
}
};
- // Distinct users + machine identities that belong to a project of the given type, either through a
- // direct membership or through a group assigned to the project. Project memberships (user, identity,
- // and group actors) all live in the unified `memberships` table with scope = project; the group's
- // members are then resolved through the user/identity group-membership tables. When orgId is given
- // the count is scoped to that org (cloud); when omitted it spans the whole instance (self-hosted).
- // The four sources are UNION-ed (not UNION ALL) with a per-kind prefix so an identity in several
- // projects, or reachable via both a direct and a group membership, is only counted once.
const countProjectIdentities = async (projectType: ProjectType, orgId?: string): Promise<number> => {
- // The live project ids for this type, resolved once per source. Scoping happens here on
- // projects.orgId (indexed via projects_orgid_type_idx) rather than on memberships.scopeOrgId:
- // leading with the org's handful of typed projects lets each source drive off the small project set
- // and probe memberships through the partial (scopeProjectId, actor*) unique indexes as an
- // index-only scan, instead of scanning every project-scope membership row in the org. Self-hosted
- // passes no orgId and counts the whole instance. A fresh builder per call keeps knex from
- // mutating a shared subquery.
+ const scopedOrgIds = () => {
+ const qb = db.replicaNode()(TableName.Organization).select(`${TableName.Organization}.id`);
+ if (orgId) {
+ void qb.where((bd) => {
+ void bd.where(`${TableName.Organization}.id`, orgId).orWhere(`${TableName.Organization}.rootOrgId`, orgId);
+ });
+ }
+ return qb;
+ };
+
const typedProjectIds = () => {
const qb = db
.replicaNode()(TableName.Project)
.where(`${TableName.Project}.type`, projectType)
.whereNull(`${TableName.Project}.deleteAfter`)
.select(`${TableName.Project}.id`);
- if (orgId) void qb.where(`${TableName.Project}.orgId`, orgId);
+ if (orgId) void qb.whereIn(`${TableName.Project}.orgId`, scopedOrgIds());
+ return qb;
+ };
+
+ const orgMemberUserIds = () => {
+ const qb = db
+ .replicaNode()(TableName.Membership)
+ .join(TableName.Users, `${TableName.Membership}.actorUserId`, `${TableName.Users}.id`)
+ .where(`${TableName.Membership}.scope`, AccessScope.Organization)
+ .whereNotNull(`${TableName.Membership}.actorUserId`)
+ .where(`${TableName.Users}.isGhost`, false)
+ .where(`${TableName.Users}.isAccepted`, true)
+ .select(`${TableName.Membership}.actorUserId`);
+ if (orgId) void qb.whereIn(`${TableName.Membership}.scopeOrgId`, scopedOrgIds());
+ return qb;
+ };
+
+ // Identities that actually belong to the org / child orgs (licenseDAL identity scope).
+ const orgIdentityIds = () => {
+ const qb = db.replicaNode()(TableName.Identity).select(`${TableName.Identity}.id`);
+ if (orgId) void qb.whereIn(`${TableName.Identity}.orgId`, scopedOrgIds());
return qb;
};
@@ -97,6 +113,7 @@ export const usageCounterDALFactory = (db: TDbClient) => {
.where(`${TableName.Membership}.scope`, AccessScope.Project)
.whereNotNull(`${TableName.Membership}.actorUserId`)
.whereIn(`${TableName.Membership}.scopeProjectId`, typedProjectIds())
+ .whereIn(`${TableName.Membership}.actorUserId`, orgMemberUserIds())
.select(db.raw("'u' as kind"))
.select(`${TableName.Membership}.actorUserId as entityId`);
@@ -108,6 +125,7 @@ export const usageCounterDALFactory = (db: TDbClient) => {
.where(`${TableName.Membership}.scope`, AccessScope.Project)
.whereNotNull(`${TableName.Membership}.actorIdentityId`)
.whereIn(`${TableName.Membership}.scopeProjectId`, typedProjectIds())
+ .whereIn(`${TableName.Membership}.actorIdentityId`, orgIdentityIds())
.select(db.raw("'i' as kind"))
.select(`${TableName.Membership}.actorIdentityId as entityId`),
// A group assigned to a project (membership with actorGroupId) brings its members into it. A
@@ -123,6 +141,7 @@ export const usageCounterDALFactory = (db: TDbClient) => {
.where(`${TableName.Membership}.scope`, AccessScope.Project)
.where(`${TableName.UserGroupMembership}.isPending`, false)
.whereIn(`${TableName.Membership}.scopeProjectId`, typedProjectIds())
+ .whereIn(`${TableName.UserGroupMembership}.userId`, orgMemberUserIds())
.select(db.raw("'u' as kind"))
.select(`${TableName.UserGroupMembership}.userId as entityId`),
(qb) =>
@@ -135,6 +154,7 @@ export const usageCounterDALFactory = (db: TDbClient) => {
)
.where(`${TableName.Membership}.scope`, AccessScope.Project)
.whereIn(`${TableName.Membership}.scopeProjectId`, typedProjectIds())
+ .whereIn(`${TableName.IdentityGroupMembership}.identityId`, orgIdentityIds())
.select(db.raw("'i' as kind"))
.select(`${TableName.IdentityGroupMembership}.identityId as entityId`)
],
diff --git a/backend/src/services/license-client/usage/usage-event-queue.ts b/backend/src/services/license-client/usage/usage-event-queue.ts
index 1a9657a3d0..9e75c61828 100644
--- a/backend/src/services/license-client/usage/usage-event-queue.ts
+++ b/backend/src/services/license-client/usage/usage-event-queue.ts
@@ -68,15 +68,22 @@ export const usageEventQueueFactory = ({
}
]);
} catch (error) {
- if (
- error instanceof UsageReportError &&
- error.status === 422 &&
- error.serverMessage.includes("not priced by any active product on this license")
- ) {
- logger.info(
- `usage-event-queue: dimension not priced on this license, skipping [orgId=${orgId}] [dimensionKey=${dimensionKey}]`
- );
- return;
+ if (error instanceof UsageReportError) {
+ if (error.status === 404) {
+ logger.info(
+ `usage-event-queue: dimension not found, skipping [orgId=${orgId}] [dimensionKey=${dimensionKey}]`
+ );
+ return;
+ }
+ if (
+ error.status === 422 &&
+ error.serverMessage.includes("not priced by any active product on this license")
+ ) {
+ logger.info(
+ `usage-event-queue: dimension not priced on this license, skipping [orgId=${orgId}] [dimensionKey=${dimensionKey}]`
+ );
+ return;
+ }
}
throw error;
}
diff --git a/frontend/src/hooks/api/billingV2/index.tsx b/frontend/src/hooks/api/billingV2/index.tsx
index 38a360226b..001eac6fc7 100644
--- a/frontend/src/hooks/api/billingV2/index.tsx
+++ b/frontend/src/hooks/api/billingV2/index.tsx
@@ -1,10 +1,9 @@
export {
useAddBillingV2PaymentMethod,
- useAddBillingV2Product,
+ useBuyBillingV2Product,
useCancelBillingV2Subscription,
useCancelBillingV2Trial,
useChangeBillingV2Commitment,
- useCreateBillingV2CheckoutSession,
useCreateBillingV2PortalSession,
usePreviewBillingV2Change,
useRefreshBillingV2Entitlements,
diff --git a/frontend/src/hooks/api/billingV2/mutations.tsx b/frontend/src/hooks/api/billingV2/mutations.tsx
index 0a9777e903..b6cc1585d2 100644
--- a/frontend/src/hooks/api/billingV2/mutations.tsx
+++ b/frontend/src/hooks/api/billingV2/mutations.tsx
@@ -11,11 +11,10 @@ import {
BillingV2TrialCancelResult,
BillingV2TrialResult,
TAddBillingV2PaymentMethodDTO,
- TAddBillingV2ProductDTO,
TBillingV2LifecycleDTO,
+ TBuyBillingV2ProductDTO,
TCancelBillingV2TrialDTO,
TChangeBillingV2CommitmentDTO,
- TCreateBillingV2CheckoutSessionDTO,
TCreateBillingV2PortalSessionDTO,
TPreviewBillingV2ChangeDTO,
TRemoveBillingV2ProductDTO,
@@ -37,23 +36,29 @@ export const useCreateBillingV2PortalSession = () => {
});
};
-export const useCreateBillingV2CheckoutSession = () => {
+// Buy/add one product. The server self-selects appending to a live subscription vs opening a hosted
+// Checkout, so the caller never branches on subscription state. Commitment is a separate step.
+export const useBuyBillingV2Product = () => {
+ const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({
orgId,
productId,
plan,
cadence,
- commitments,
- email,
- returnPath
- }: TCreateBillingV2CheckoutSessionDTO) => {
+ quantities,
+ returnPath,
+ prorationDate
+ }: TBuyBillingV2ProductDTO) => {
const { data } = await apiRequest.post<BillingV2CheckoutResult>(
- `/api/v1/organizations/${orgId}/billing/v2/checkout-session`,
- { productId, plan, cadence, commitments, email, returnPath }
+ `/api/v1/organizations/${orgId}/billing/v2/subscription/products`,
+ { productId, plan, cadence, quantities, returnPath, prorationDate }
);
return data;
+ },
+ onSuccess: (_data, { orgId }) => {
+ queryClient.invalidateQueries({ queryKey: billingV2Keys.overview(orgId) });
}
});
};
@@ -82,7 +87,7 @@ export const usePreviewBillingV2Change = () => {
addProductId,
plan,
cadence,
- commitments,
+ quantities,
removeProductId,
commitmentChanges
}: TPreviewBillingV2ChangeDTO) => {
@@ -90,7 +95,7 @@ export const usePreviewBillingV2Change = () => {
data: { preview }
} = await apiRequest.post<{ preview: BillingV2Preview }>(
`/api/v1/organizations/${orgId}/billing/v2/subscription/preview`,
- { addProductId, plan, cadence, commitments, removeProductId, commitmentChanges }
+ { addProductId, plan, cadence, quantities, removeProductId, commitmentChanges }
);
return preview;
@@ -98,37 +103,14 @@ export const usePreviewBillingV2Change = () => {
});
};
-export const useAddBillingV2Product = () => {
- const queryClient = useQueryClient();
- return useMutation({
- 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, 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).
+// Start / change annual commitments across dimensions in one atomic call.
export const useChangeBillingV2Commitment = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ orgId, changes }: TChangeBillingV2CommitmentDTO) => {
- const { data } = await apiRequest.post<BillingV2MutationResult>(
+ mutationFn: async ({ orgId, changes, prorationDate }: TChangeBillingV2CommitmentDTO) => {
+ const { data } = await apiRequest.put<BillingV2MutationResult>(
`/api/v1/organizations/${orgId}/billing/v2/subscription/commitments`,
- { changes }
+ { changes, prorationDate }
);
return data;
@@ -181,7 +163,7 @@ export const useRemoveBillingV2Product = () => {
return useMutation({
mutationFn: async ({ orgId, productId }: TRemoveBillingV2ProductDTO) => {
const { data } = await apiRequest.delete<BillingV2MutationResult>(
- `/api/v1/organizations/${orgId}/billing/v2/subscription/items/${encodeURIComponent(productId)}`
+ `/api/v1/organizations/${orgId}/billing/v2/subscription/products/${encodeURIComponent(productId)}`
);
return data;
diff --git a/frontend/src/hooks/api/billingV2/types.ts b/frontend/src/hooks/api/billingV2/types.ts
index 79da61eeff..f80814b219 100644
--- a/frontend/src/hooks/api/billingV2/types.ts
+++ b/frontend/src/hooks/api/billingV2/types.ts
@@ -100,11 +100,21 @@ export type BillingV2EntitlementDim = {
used: number;
limit: number | null;
committed: number | null;
+ // Whether this customer can commit this dimension annually, per their pinned plan version (from the
+ // subscription read, NOT the catalog). Grandfather-safe: a later catalog price won't flip it on for a
+ // customer on an older version. Gate the commit action on this for products the customer owns.
+ commitAvailable: boolean;
committedRate?: number;
onDemandRate?: number;
rate?: number;
freeBand?: number;
onDemandAmount: number;
+ // Annual-commitment lifecycle. canDecreaseNow is false until the final window before renewal, so the
+ // UI locks the commitment stepper's floor to the current committed quantity until then. renewalDate
+ // and decreaseAllowedFrom are formatted display dates.
+ canDecreaseNow?: boolean;
+ renewalDate?: string | null;
+ decreaseAllowedFrom?: string | null;
};
export type BillingV2Entitlement = {
@@ -177,6 +187,8 @@ export type BillingV2Overview = {
entitlements: Record<string, BillingV2Entitlement>;
// Product keys whose one-per-product trial is used up (any outcome); gates the trial CTA.
trialedProductKeys: string[];
+ // Mutating billing actions are frozen server-side; the UI disables purchase/commit/remove controls.
+ checkoutFrozen: boolean;
};
export type BillingV2CheckoutResult = {
@@ -190,15 +202,17 @@ export type TCreateBillingV2PortalSessionDTO = {
returnPath?: string;
};
-export type TCreateBillingV2CheckoutSessionDTO = {
+// Buy/add one product. The server self-selects append vs Checkout. quantities are buyer-entered
+// per-dimension values; the server fills any non-entered per_resource dim. Commitment is a separate
+// step (useChangeBillingV2Commitment). prorationDate is echoed from a prior preview.
+export type TBuyBillingV2ProductDTO = {
orgId: string;
productId: string;
plan?: string;
cadence?: BillingV2Cadence;
- // Per-dimension committed quantities; required for an annual per_resource line.
- commitments?: Record<string, number>;
- email?: string;
+ quantities?: Record<string, number>;
returnPath?: string;
+ prorationDate?: number;
};
export type TAddBillingV2PaymentMethodDTO = {
@@ -212,13 +226,19 @@ export type BillingV2PreviewLine = {
proration: boolean;
};
-// prorationAmount is signed: positive is charged now (an add), negative is a credit toward the next
-// invoice (a removal). The server prorates at commit time, so no proration timestamp is echoed back.
+// prorationAmount is this change's cost (signed: positive is charged now, negative a credit).
+// additionalCharges are earlier mid-cycle changes still unbilled that an invoice-now apply settles in
+// the same charge; totalDueNow (= prorationAmount + additionalCharges) is what actually hits the card
+// and is the figure to show as "charged now". prorationDate is echoed into the apply so the applied
+// charge matches the preview.
export type BillingV2Preview = {
currency: string;
prorationAmount: number;
+ additionalCharges: number;
+ totalDueNow: number;
nextInvoiceTotal: number;
nextRecurringTotal: number;
+ prorationDate?: number | null;
lines: BillingV2PreviewLine[];
};
@@ -237,32 +257,26 @@ export type TPreviewBillingV2ChangeDTO = {
addProductId?: string;
plan?: string;
cadence?: BillingV2Cadence;
- // Initial per-dimension commitments for an annual add.
- commitments?: Record<string, number>;
+ // Buyer-entered per-dimension quantities for the add (e.g. annual commitment amounts); the server
+ // fills any non-entered per_resource dim, so the previewed charge matches the buy.
+ quantities?: Record<string, number>;
removeProductId?: string;
// Per_resource commitment quantity changes to preview against the existing subscription.
commitmentChanges?: BillingV2CommitmentChange[];
};
-export type TAddBillingV2ProductDTO = {
- orgId: string;
- productId: string;
- plan?: string;
- cadence?: BillingV2Cadence;
- // Per-dimension committed quantities; required for an annual per_resource line.
- commitments?: Record<string, number>;
-};
-
export type TRemoveBillingV2ProductDTO = {
orgId: string;
productId: string;
};
-// Apply one or more previewed per_resource commitment changes; the backend loops the per-dimension
-// apply and the server prorates at commit time (no client-supplied proration timestamp).
+// Start / change annual commitments across dimensions in one atomic call. An increase is charged now;
+// a decrease is rejected server-side unless the dimension's window is open. prorationDate is echoed
+// from a prior preview.
export type TChangeBillingV2CommitmentDTO = {
orgId: string;
changes: BillingV2CommitmentChange[];
+ prorationDate?: number;
};
export type TStartBillingV2TrialDTO = {
diff --git a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
index 1b2910e6c3..e1f6259819 100644
--- a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
@@ -9,8 +9,7 @@ import {
OrgPermissionBillingActions,
OrgPermissionSubjects,
useOrganization,
- useOrgPermission,
- useUser
+ useOrgPermission
} from "@app/context";
import {
useAddBillingV2PaymentMethod,
@@ -27,15 +26,15 @@ import { BillingV2RenderState } from "./billing-v2-view-types";
const CONTACT_SALES_URL = "https://infisical.com/talk-to-us";
-type BillingV2Flow = { type: "sheet"; prodId: string };
+// `view` optionally opens the product sheet straight into a sub-view (e.g. the set-commitment flow
+// from the "commit and save" nudge) instead of the default plans view.
+type BillingV2Flow = { type: "sheet"; prodId: string; view?: "commitment" };
export const BillingV2Page = () => {
const { t } = useTranslation();
const { currentOrg } = useOrganization();
- const { user } = useUser();
const { permission } = useOrgPermission();
const orgId = currentOrg?.id ?? "";
- const billingEmail = user?.email ?? user?.username;
const canManageBilling = permission.can(
OrgPermissionBillingActions.ManageBilling,
OrgPermissionSubjects.Billing
@@ -103,6 +102,11 @@ export const BillingV2Page = () => {
setFlow({ type: "sheet", prodId: productId });
};
+ // Open the sheet directly into the set-commitment flow (from the "commit and save" nudge).
+ const onSetCommitment = (productId: string) => {
+ setFlow({ type: "sheet", prodId: productId, view: "commitment" });
+ };
+
const hasActiveSubscription = overview?.subState === "active";
const onUpdatePayment = async () => {
@@ -137,13 +141,13 @@ export const BillingV2Page = () => {
: "Manage your subscription, products, and payment. Payment is handled securely through Stripe.";
return (
- <div className="h-full bg-bunker-800">
+ <>
<Helmet>
<title>{t("common.head-title", { title: t("billing.title") })}</title>
<link rel="icon" href="/infisical.ico" />
<meta property="og:image" content="/images/message.png" />
</Helmet>
- <div className="flex h-full w-full justify-center bg-bunker-800 text-white">
+ <div className="mb-8 flex w-full justify-center bg-bunker-800 text-white">
<div className="w-full max-w-8xl">
<PageHeader scope="org" title={t("billing.title")} description={pageDescription} />
<OrgPermissionCan
@@ -157,6 +161,7 @@ export const BillingV2Page = () => {
subState={subState}
onManageSubscription={onManageSubscription}
onUpgrade={onUpgrade}
+ onSetCommitment={onSetCommitment}
onUpdatePayment={onUpdatePayment}
onEditDetails={onEditDetails}
onContact={onContact}
@@ -173,7 +178,7 @@ export const BillingV2Page = () => {
prod={catalogById(catalog, flow.prodId)}
entitlement={overview?.entitlements[flow.prodId]}
hasActiveSubscription={hasActiveSubscription}
- billingEmail={billingEmail}
+ initialView={flow.view}
returnPath={window.location.pathname}
renewsOn={overview?.entitlements[flow.prodId]?.renewsOn ?? null}
trialUsed={overview?.trialedProductKeys.includes(flow.prodId) ?? false}
@@ -197,6 +202,6 @@ export const BillingV2Page = () => {
}}
/>
)}
- </div>
+ </>
);
};
diff --git a/frontend/src/pages/organization/BillingV2Page/billing-v2-format.ts b/frontend/src/pages/organization/BillingV2Page/billing-v2-format.ts
index bf518c9aa3..689c94f121 100644
--- a/frontend/src/pages/organization/BillingV2Page/billing-v2-format.ts
+++ b/frontend/src/pages/organization/BillingV2Page/billing-v2-format.ts
@@ -81,15 +81,17 @@ export const isMeteredCadence = (dim: BillingV2Dim, cad: BillingV2Cadence): bool
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.
-// Metered dimensions are usage-based (no buyer-selected quantity), so they are never "committed" even
-// if the server reports a committed value for them — this keeps commitment UI off usage-based pricing.
-export const dimAnnualCommitted = (dim: BillingV2EntitlementDim): boolean =>
- dim.cadence === "annual" && !dim.metered && dim.committed !== null;
+// A per_resource dimension carrying a prepaid annual commitment: usage above `committed` is billed
+// monthly on-demand. A commitment is identified by a non-null committed quantity, NOT by the product's
+// cadence — a monthly-cadence product can still prepay an annual commitment on a dimension. Metered
+// dimensions are usage-based (no buyer-selected quantity), so they are never "committed" even if the
+// server reports a committed value, which keeps the commitment UI off usage-based pricing.
+export const dimCommitted = (dim: BillingV2EntitlementDim): boolean =>
+ !dim.metered && dim.committed !== null;
// A ceiling to fill a usage bar against: an annual commitment or a finite limit.
export const dimHasCeiling = (dim: BillingV2EntitlementDim): boolean =>
- dimAnnualCommitted(dim) || (dim.limit !== null && dim.limit > 0);
+ dimCommitted(dim) || (dim.limit !== null && dim.limit > 0);
// 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.
@@ -102,7 +104,7 @@ export const dimMonthlyRate = (dim: BillingV2EntitlementDim): number => {
// 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;
+ dimCommitted(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 => {
@@ -117,7 +119,7 @@ export const usagePct = (used: number, limit: number | null): number | null => {
export const dimBarSegments = (
dim: BillingV2EntitlementDim
): { committedPct: number; onDemandPct: number } => {
- if (dimAnnualCommitted(dim)) {
+ if (dimCommitted(dim)) {
const committed = dim.committed ?? 0;
const denominator = Math.max(committed, dim.used, 1);
const committedFill = Math.min(committed, dim.used);
@@ -135,13 +137,53 @@ export const dimBarSegments = (
export const productAnnualCommitted = (entitlement?: BillingV2Entitlement): number => {
const dims = entitlement?.dimensions ?? [];
return dims.reduce((sum, dim) => {
- if (dimAnnualCommitted(dim) && dim.committedRate) {
+ if (dimCommitted(dim) && dim.committedRate) {
return sum + (dim.committed ?? 0) * dim.committedRate;
}
return sum;
}, 0);
};
+export const dimCommittable = (dim: BillingV2EntitlementDim): boolean =>
+ dim.commitAvailable && !dim.metered;
+
+export const canStartCommitment = (entitlement?: BillingV2Entitlement): boolean =>
+ (entitlement?.dimensions ?? []).some((dim) => dimCommittable(dim) && dim.committed === null);
+
+export type BillingV2CommitNudge = {
+ label: string;
+ qty: number;
+ annualCommitted: number;
+ monthlyAnnualized: number;
+ savingsPct: number;
+};
+
+export const commitSavingsNudge = (
+ entitlement?: BillingV2Entitlement
+): BillingV2CommitNudge | null => {
+ if (!entitlement?.entitled) {
+ return null;
+ }
+ const dim = (entitlement.dimensions ?? []).find(
+ (d) =>
+ dimCommittable(d) &&
+ d.committed === null &&
+ d.used > 0 &&
+ (d.committedRate ?? 0) > 0 &&
+ (d.onDemandRate ?? 0) > 0
+ );
+ if (!dim) {
+ return null;
+ }
+ const annualCommitted = dim.used * (dim.committedRate ?? 0);
+ const monthlyAnnualized = dim.used * (dim.onDemandRate ?? 0) * 12;
+ const savingsPct = Math.round((1 - annualCommitted / monthlyAnnualized) * 100);
+ if (savingsPct <= 0) {
+ return null;
+ }
+ return { label: dim.label, qty: dim.used, annualCommitted, monthlyAnnualized, savingsPct };
+};
+
// Capitalize a plan tier ("pro" -> "Pro") for the badge beside a product's name.
export const tierLabel = (tier: string): string => tier.charAt(0).toUpperCase() + tier.slice(1);
diff --git a/frontend/src/pages/organization/BillingV2Page/components/ActivateView.tsx b/frontend/src/pages/organization/BillingV2Page/components/ActivateView.tsx
index fffb66d25c..a5cc781b56 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/ActivateView.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/ActivateView.tsx
@@ -9,12 +9,13 @@ import {
BillingV2CatalogProduct,
BillingV2Dim,
BillingV2Plan,
- useAddBillingV2Product,
- useCreateBillingV2CheckoutSession,
+ useBuyBillingV2Product,
usePreviewBillingV2Change
} from "@app/hooks/api";
import { fmtMoney } from "../billing-v2-format";
+import { ChargeBreakdown } from "./ChargeBreakdown";
+import { CommitmentTerms } from "./CommitmentTerms";
import { CostSummary, CostSummaryRow, ProductIcon, Stepper } from "./shared";
type Props = {
@@ -22,16 +23,12 @@ type Props = {
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. Commitment mode is prepaid annual units
-// with monthly on-demand overage, so it requires BOTH cadences priced: the annual per-unit rate for
-// the commitment and a monthly rate for the overage. A single-cadence dimension is not committable.
const isCommittable = (dim: BillingV2Dim): boolean =>
dim.annual > 0 && dim.monthly > 0 && !dim.meteredAnnual;
@@ -44,6 +41,15 @@ const monthlyHeadline = (plan: BillingV2Plan): number => {
return dim ? dim.monthly : 0;
};
+// The plan's annual headline price (base fee, else the first priced dimension's annual rate).
+const annualHeadline = (plan: BillingV2Plan): number => {
+ if (plan.base) {
+ return plan.base.annual;
+ }
+ const dim = plan.dims.find((d) => d.annual > 0);
+ return dim ? dim.annual : 0;
+};
+
type CadenceOptionProps = {
active: boolean;
title: string;
@@ -69,59 +75,59 @@ const CadenceOption = ({ active, title, subtitle, badge, onClick }: CadenceOptio
</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 supportsAnnual =
+ plan.dims.some((d) => d.annual > 0) || Boolean(plan.base && plan.base.annual > 0);
const supportsMonthly =
plan.dims.some((d) => d.monthly > 0) || Boolean(plan.base && plan.base.monthly > 0);
- const [cadence, setCadence] = useState<BillingV2Cadence>(supportsMonthly ? "monthly" : "annual");
+ const [cadence, setCadence] = useState<BillingV2Cadence>(() => {
+ if (plan.trialable && supportsMonthly) {
+ return "monthly";
+ }
+ return supportsAnnual ? "annual" : "monthly";
+ });
const [commitments, setCommitments] = useState<Record<string, number>>(() =>
Object.fromEntries(committable.map((dim) => [dim.key, Math.max(dim.included, 1)]))
);
+ const [acknowledged, setAcknowledged] = useState(false);
+ const needsCommitmentAck = cadence === "annual" && committable.length > 0;
const preview = usePreviewBillingV2Change();
- const addProduct = useAddBillingV2Product();
- const checkout = useCreateBillingV2CheckoutSession();
+ const buyProduct = useBuyBillingV2Product();
- const commitmentsForCadence = cadence === "annual" ? commitments : undefined;
- const commitmentsKey = JSON.stringify(commitmentsForCadence ?? {});
+ // Yearly sends the buyer-chosen commitment quantities; monthly sends nothing (the server seeds the
+ // recurring quantities from present usage).
+ const quantitiesForCadence = cadence === "annual" ? commitments : undefined;
+ const quantitiesKey = JSON.stringify(quantitiesForCadence ?? {});
- // A brand-new customer has no subscription yet, so the preview endpoint (which prorates against a
- // live subscription) would fail. Compute the figures locally in that case and let Stripe Checkout
- // confirm the exact amount; an existing subscription re-prices via the debounced preview below.
- const localRecurring =
- cadence === "annual"
- ? (plan.base?.annual ?? 0) +
- committable.reduce((sum, dim) => sum + (commitments[dim.key] ?? 0) * dim.annual, 0)
- : monthlyHeadline(plan);
+ // The plan's headline price for the chosen cadence, shown on the static product row.
+ const localRecurring = cadence === "annual" ? annualHeadline(plan) : monthlyHeadline(plan);
- // A preview is fresh only once priced for the current cadence + commitments; until then the cost
- // rows show skeletons. A new customer prices locally, so never calculates.
+ // The preview prices the purchase for the current cadence + quantities whether or not a live
+ // subscription exists (it prices a first purchase too), so every activation waits on it. Until it is
+ // fresh for the current selection the cost rows render as skeletons.
const previewFresh =
!preview.isPending &&
Boolean(preview.data) &&
preview.variables?.cadence === cadence &&
- JSON.stringify(preview.variables?.commitments ?? {}) === commitmentsKey;
- const isCalculating = hasActiveSubscription && !previewFresh;
+ JSON.stringify(preview.variables?.quantities ?? {}) === quantitiesKey;
+ const isCalculating = !previewFresh;
- // Debounced re-price on cadence/commitment changes so a burst of stepper clicks makes one request.
- // Skipped without a live subscription or when the current combo is already priced.
+ // Debounced re-price on cadence/quantity changes so a burst of stepper clicks makes one request;
+ // skipped when the current selection is already priced.
useEffect(() => {
- if (!hasActiveSubscription || previewFresh) {
+ if (previewFresh) {
return undefined;
}
const timeout = setTimeout(() => {
@@ -130,38 +136,46 @@ export const ActivateView = ({
addProductId: prod.id,
plan: plan.tier,
cadence,
- commitments: commitmentsForCadence
+ quantities: quantitiesForCadence
});
}, 400);
return () => clearTimeout(timeout);
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [orgId, prod.id, plan.tier, cadence, commitmentsKey, hasActiveSubscription]);
+ }, [orgId, prod.id, plan.tier, cadence, quantitiesKey]);
- // With a live subscription the change is prorated onto the shared billing date; a new customer pays
- // the first period in full at checkout.
- let dueToday = localRecurring;
- if (hasActiveSubscription) {
- dueToday = preview.data ? Math.max(preview.data.prorationAmount, 0) : 0;
+ // Both figures come from the preview. "Charged today" differs by path: adding to a live subscription
+ // is invoice-now, so the card is charged totalDueNow (this change plus any earlier unbilled mid-cycle
+ // changes it settles); a first purchase goes through Stripe Checkout, which collects the whole first
+ // invoice up front (nextInvoiceTotal) — for a yearly commitment that is the full annual amount, not
+ // the $0 prorationAmount a first purchase reports.
+ let dueToday = 0;
+ if (preview.data) {
+ dueToday = hasActiveSubscription
+ ? Math.max(preview.data.totalDueNow, 0)
+ : preview.data.nextInvoiceTotal;
}
- const recurring = hasActiveSubscription
- ? (preview.data?.nextRecurringTotal ?? 0)
- : localRecurring;
+ const recurring = preview.data?.nextRecurringTotal ?? 0;
+ // Only the invoice-now (existing-subscription) path settles earlier pending charges; disclose the
+ // split when there are any. A first purchase via Checkout has none.
+ const additionalCharges = preview.data?.additionalCharges ?? 0;
+ const showChargeBreakdown = hasActiveSubscription && !isCalculating && additionalCharges !== 0;
const period = cadence === "annual" ? "year" : "month";
- const pending = addProduct.isPending || checkout.isPending;
+ const pending = buyProduct.isPending;
- let chargedNote = "Billed at checkout";
- if (hasActiveSubscription) {
- chargedNote = isCalculating ? "Calculating…" : "Prorated onto your shared billing date";
+ let chargedNote = "Calculating…";
+ if (!isCalculating) {
+ chargedNote = hasActiveSubscription
+ ? "Prorated onto your shared billing date"
+ : "Due today at checkout";
}
- // Without a live subscription there is no preview to wait on, so the CTA is enabled immediately.
- const activateDisabled = pending || isCalculating;
+ // The CTA waits until the preview has priced the current selection, and an annual commitment also
+ // requires the customer to acknowledge the commitment terms.
+ const activateDisabled = pending || isCalculating || (needsCommitmentAck && !acknowledged);
// 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);
+ const annual = annualHeadline(plan);
if (monthly <= 0 || annual <= 0) {
return null;
}
@@ -171,32 +185,21 @@ export const ActivateView = ({
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({
+ const result = await buyProduct.mutateAsync({
orgId,
productId: prod.id,
plan: plan.tier,
cadence,
- commitments: commitmentsForCadence,
- email: billingEmail,
+ quantities: quantitiesForCadence,
+ // The preview echoes the proration instant so the applied charge matches what was shown.
+ prorationDate: preview.data?.prorationDate ?? undefined,
returnPath
});
if (result.outcome === "subscription_updated") {
- createNotification({ type: "success", text: `${prod.name} activated.` });
+ createNotification({
+ type: "success",
+ text: `${prod.name} activated. It may take a moment to update here.`
+ });
onDone();
return;
}
@@ -206,7 +209,7 @@ export const ActivateView = ({
}
createNotification({ type: "error", text: "Failed to start checkout." });
} catch {
- createNotification({ type: "error", text: `Failed to activate ${prod.name}.` });
+ // The backend's message is surfaced by the global mutation error handler (reactQuery.tsx).
}
};
@@ -272,7 +275,7 @@ export const ActivateView = ({
))
: null}
- {cadence === "monthly" && (
+ {(cadence === "monthly" || committable.length === 0) && (
<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} />
@@ -284,11 +287,15 @@ export const ActivateView = ({
</div>
</div>
<span className="shrink-0 text-sm font-semibold text-foreground tabular-nums">
- {fmtMoney(monthlyHeadline(plan))} / month
+ {fmtMoney(localRecurring)} / {period}
</span>
</div>
)}
+ {needsCommitmentAck && (
+ <CommitmentTerms acknowledged={acknowledged} onAcknowledgedChange={setAcknowledged} />
+ )}
+
<CostSummary>
<CostSummaryRow
label="Charged today"
@@ -304,6 +311,14 @@ export const ActivateView = ({
isCalculating={isCalculating}
/>
</CostSummary>
+
+ {showChargeBreakdown && (
+ <ChargeBreakdown
+ prorationAmount={preview.data?.prorationAmount ?? 0}
+ additionalCharges={additionalCharges}
+ totalDueNow={preview.data?.totalDueNow ?? 0}
+ />
+ )}
</div>
<SheetFooter className="flex-row justify-between border-t">
diff --git a/frontend/src/pages/organization/BillingV2Page/components/ChargeBreakdown.tsx b/frontend/src/pages/organization/BillingV2Page/components/ChargeBreakdown.tsx
new file mode 100644
index 0000000000..5154f4ae5b
--- /dev/null
+++ b/frontend/src/pages/organization/BillingV2Page/components/ChargeBreakdown.tsx
@@ -0,0 +1,63 @@
+import { ReactNode } from "react";
+import { InfoIcon } from "lucide-react";
+
+import { Alert, AlertDescription } from "@app/components/v3";
+
+import { fmtMoney } from "../billing-v2-format";
+
+type Props = {
+ // This change's own cost (dollars).
+ prorationAmount: number;
+ // Earlier unbilled mid-cycle changes an invoice-now apply settles now (signed: positive = pending
+ // charges, negative = a credit).
+ additionalCharges: number;
+ // What actually hits the card = prorationAmount + additionalCharges (signed).
+ totalDueNow: number;
+};
+
+// Sign-aware disclosure of what settles on top of this change when applying invoice-now. The earlier
+// changes can be pending charges (positive) or a credit (negative), and the net can even be a credit
+// (nothing charged now, the balance carried to future invoices). Renders nothing when there's nothing
+// extra to settle.
+export const ChargeBreakdown = ({ prorationAmount, additionalCharges, totalDueNow }: Props) => {
+ if (additionalCharges === 0) {
+ return null;
+ }
+
+ let body: ReactNode;
+ if (totalDueNow < 0) {
+ // Net credit: nothing is charged now and the remaining credit rolls to future invoices.
+ body = (
+ <>
+ You&apos;ll be charged <span className="font-medium">$0</span> now. This change costs{" "}
+ {fmtMoney(prorationAmount, 2)}, and a{" "}
+ <span className="font-medium">{fmtMoney(Math.abs(totalDueNow), 2)} credit</span> will be
+ applied to your future invoices.
+ </>
+ );
+ } else if (additionalCharges < 0) {
+ // Still due now, but earlier changes contribute a credit that reduces the charge.
+ body = (
+ <>
+ You&apos;ll be charged <span className="font-medium">{fmtMoney(totalDueNow, 2)}</span> now:{" "}
+ {fmtMoney(prorationAmount, 2)} for this change, and a credit of{" "}
+ {fmtMoney(Math.abs(additionalCharges), 2)} from earlier changes will be applied.
+ </>
+ );
+ } else {
+ body = (
+ <>
+ You&apos;ll be charged <span className="font-medium">{fmtMoney(totalDueNow, 2)}</span> now:{" "}
+ {fmtMoney(prorationAmount, 2)} for this change, plus {fmtMoney(additionalCharges, 2)} in
+ pending charges from earlier changes that haven&apos;t been billed yet.
+ </>
+ );
+ }
+
+ return (
+ <Alert variant="info">
+ <InfoIcon />
+ <AlertDescription className="text-foreground">{body}</AlertDescription>
+ </Alert>
+ );
+};
diff --git a/frontend/src/pages/organization/BillingV2Page/components/CommitmentTerms.tsx b/frontend/src/pages/organization/BillingV2Page/components/CommitmentTerms.tsx
new file mode 100644
index 0000000000..4b08fde0df
--- /dev/null
+++ b/frontend/src/pages/organization/BillingV2Page/components/CommitmentTerms.tsx
@@ -0,0 +1,57 @@
+import { TriangleAlert } from "lucide-react";
+
+import { Alert, AlertDescription, AlertTitle, Checkbox } from "@app/components/v3";
+
+type Props = {
+ acknowledged: boolean;
+ onAcknowledgedChange: (value: boolean) => void;
+};
+
+// Consequence-forward confirmation shown before an annual commitment is purchased or increased. An
+// annual commitment is paid upfront for the whole cycle, is non-cancellable, and cannot be reduced
+// until renewal, so the customer must explicitly acknowledge the terms before Confirm unlocks. The
+// copy is deliberately plain so the commitment they are making is unambiguous.
+export const CommitmentTerms = ({ acknowledged, onAcknowledgedChange }: Props) => (
+ <Alert variant="warning">
+ <TriangleAlert />
+ <AlertTitle>Review your annual commitment</AlertTitle>
+ <AlertDescription className="flex flex-col gap-2 text-foreground">
+ <span>
+ An annual commitment locks in your rate for the full billing year. Please read this before
+ you confirm:
+ </span>
+ <ul className="flex list-disc flex-col gap-1 pl-4 text-muted">
+ <li>
+ <span className="font-medium text-foreground">Paid upfront.</span> You are billed today
+ for the entire year&apos;s committed units, not month by month.
+ </li>
+ <li>
+ <span className="font-medium text-foreground">Increase any time.</span> You can raise your
+ commitment mid cycle; the added units are prorated and charged immediately.
+ </li>
+ <li>
+ <span className="font-medium text-foreground">No reductions mid cycle.</span> Committed
+ units cannot be lowered until the final window before your renewal.
+ </li>
+ <li>
+ <span className="font-medium text-foreground">Not cancellable.</span> The commitment runs
+ to the end of the billing cycle and cannot be cancelled early.
+ </li>
+ </ul>
+ <span>Usage above your commitment is billed monthly at the on-demand rate.</span>
+ <div className="mt-1 flex items-start gap-2.5">
+ <Checkbox
+ id="commitment-ack"
+ variant="warning"
+ isChecked={acknowledged}
+ onCheckedChange={(value) => onAcknowledgedChange(value === true)}
+ className="mt-0.5"
+ />
+ <span className="text-xs">
+ I understand this annual commitment is paid upfront, is not cancellable, and cannot be
+ reduced until my renewal.
+ </span>
+ </div>
+ </AlertDescription>
+ </Alert>
+);
diff --git a/frontend/src/pages/organization/BillingV2Page/components/CommitmentView.tsx b/frontend/src/pages/organization/BillingV2Page/components/CommitmentView.tsx
index dfe0b3c38c..70d1226782 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/CommitmentView.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/CommitmentView.tsx
@@ -18,7 +18,9 @@ import {
usePreviewBillingV2Change
} from "@app/hooks/api";
-import { dimAnnualCommitted, fmtMoney } from "../billing-v2-format";
+import { dimCommittable, fmtMoney } from "../billing-v2-format";
+import { ChargeBreakdown } from "./ChargeBreakdown";
+import { CommitmentTerms } from "./CommitmentTerms";
import { CostSummary, CostSummaryRow, ProductIcon, Stepper } from "./shared";
type Props = {
@@ -34,10 +36,28 @@ type Props = {
// 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) => {
+ // Commit-eligible dimensions come from the subscription read's per-dimension commitAvailable (this
+ // customer's pinned plan version), NOT the catalog, so a later catalog price never lights up commit
+ // for a grandfathered customer. An eligible dimension with committed === null starts from zero (e.g.
+ // a monthly subscriber committing annually). committed is normalized to a number so the stepper and
+ // cost math handle the not-yet-committed case.
const committable = useMemo(
- () => (entitlement.dimensions ?? []).filter(dimAnnualCommitted),
+ () =>
+ (entitlement.dimensions ?? []).filter(dimCommittable).map((dim) => ({
+ key: dim.key,
+ label: dim.label,
+ noun: dim.noun,
+ used: dim.used,
+ committed: dim.committed ?? 0,
+ committedRate: dim.committedRate ?? 0,
+ onDemandRate: dim.onDemandRate ?? 0,
+ canDecreaseNow: dim.canDecreaseNow ?? false,
+ decreaseAllowedFrom: dim.decreaseAllowedFrom ?? null
+ })),
[entitlement.dimensions]
);
+ // "Set up" a first commitment reads differently from "Change" an existing one.
+ const hasExistingCommitment = committable.some((dim) => dim.committed > 0);
const [quantities, setQuantities] = useState<Record<string, number>>(() =>
Object.fromEntries(committable.map((dim) => [dim.key, dim.committed ?? 0]))
@@ -46,6 +66,11 @@ export const CommitmentView = ({ orgId, prod, entitlement, renewsOn, onBack, onD
const preview = usePreviewBillingV2Change();
const applyCommitment = useChangeBillingV2Commitment();
+ // An increase (or a brand-new commitment) charges upfront and locks in the annual terms, so it
+ // requires the customer to acknowledge the commitment terms before confirming. A pure decrease
+ // (only possible inside the renewal window) does not.
+ const [acknowledged, setAcknowledged] = useState(false);
+
// Only the dimensions whose committed quantity actually changed are sent to preview/apply.
const changes: BillingV2CommitmentChange[] = useMemo(
() =>
@@ -101,20 +126,29 @@ export const CommitmentView = ({ orgId, prod, entitlement, renewsOn, onBack, onD
(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;
+ // Applying is invoice-now, so the card is charged totalDueNow (this change + any earlier unbilled
+ // mid-cycle changes), not just this change's proration. Disclose the split when there are extras.
+ const chargedToday = hasChanges ? Math.max(preview.data?.totalDueNow ?? 0, 0) : 0;
+ const additionalCharges = preview.data?.additionalCharges ?? 0;
+ const showChargeBreakdown = hasChanges && previewFresh && additionalCharges !== 0;
let chargedNote = "No change yet";
if (hasChanges) {
chargedNote = isCalculating ? "Calculating…" : "Prorated for the rest of your annual term";
}
- const canConfirm = hasChanges && previewFresh;
+ // An increase raises the prepaid annual total; that (and starting a commitment from zero) is what
+ // needs the upfront-commitment acknowledgment.
+ const isIncreasing = newAnnual > currentAnnual;
+ const canConfirm = hasChanges && previewFresh && (!isIncreasing || acknowledged);
const handleConfirm = async () => {
try {
await applyCommitment.mutateAsync({
orgId,
- changes
+ changes,
+ // Echo the previewed proration instant so the applied charge matches what was shown.
+ prorationDate: preview.data?.prorationDate ?? undefined
});
createNotification({
type: "success",
@@ -122,7 +156,7 @@ export const CommitmentView = ({ orgId, prod, entitlement, renewsOn, onBack, onD
});
onDone();
} catch {
- createNotification({ type: "error", text: `Failed to update ${prod.name} commitment.` });
+ // The backend's message is surfaced by the global mutation error handler (reactQuery.tsx).
}
};
@@ -134,6 +168,14 @@ export const CommitmentView = ({ orgId, prod, entitlement, renewsOn, onBack, onD
? `Down from ${fmtMoney(currentOnDemand)} / mo`
: `Up from ${fmtMoney(currentOnDemand)} / mo`;
+ // When decreases are locked, name the date the window opens (first dimension that reports it).
+ const lockedDim = committable.find(
+ (dim) => dim.canDecreaseNow === false && dim.decreaseAllowedFrom
+ );
+ const decreaseLockNote = lockedDim?.decreaseAllowedFrom
+ ? ` (from ${lockedDim.decreaseAllowedFrom})`
+ : "";
+
const annualNote = `For ${prod.name}${renewsOn ? `, billed on ${renewsOn}` : ""}`;
const annualDelta =
// eslint-disable-next-line no-nested-ternary
@@ -148,10 +190,12 @@ export const CommitmentView = ({ orgId, prod, entitlement, renewsOn, onBack, onD
<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>
+ <SheetTitle className="text-base">
+ {hasExistingCommitment ? "Change" : "Set up"} {prod.name} commitment
+ </SheetTitle>
<p className="text-xs text-muted">
- Adjust the units you pre-buy for the year. Usage above your commitment is billed monthly
- on-demand.
+ {hasExistingCommitment ? "Adjust the" : "Pre-buy"} units you commit for the year. Usage
+ above your commitment is billed monthly on-demand.
</p>
</div>
</SheetHeader>
@@ -159,6 +203,11 @@ export const CommitmentView = ({ orgId, prod, entitlement, renewsOn, onBack, onD
<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]);
+ // Increase-only: the stepper cannot go below the current committed quantity unless the
+ // decrease window is open (canDecreaseNow). A decrease outside the window is rejected server
+ // side (commitment_decrease_locked), so the floor is locked to committed until renewal.
+ const committedFloor = dim.committed ?? 0;
+ const stepperMin = dim.canDecreaseNow ? 0 : committedFloor;
return (
<div
key={dim.key}
@@ -191,21 +240,26 @@ export const CommitmentView = ({ orgId, prod, entitlement, renewsOn, onBack, onD
</div>
<Stepper
value={quantities[dim.key]}
- min={1}
+ min={stepperMin}
onChange={(value) => setQuantities((prev) => ({ ...prev, [dim.key]: value }))}
/>
</div>
);
})}
- <Alert variant="info">
- <InfoIcon />
- <AlertDescription className="text-foreground">
- 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. Adjusting your
- commitment takes effect immediately for the rest of the term and is invoiced right away.
- </AlertDescription>
- </Alert>
+ {isIncreasing ? (
+ <CommitmentTerms acknowledged={acknowledged} onAcknowledgedChange={setAcknowledged} />
+ ) : (
+ <Alert variant="info">
+ <InfoIcon />
+ <AlertDescription className="text-foreground">
+ 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. You can raise a
+ commitment any time (charged now); lowering it is only allowed in the final window
+ before renewal{decreaseLockNote}.
+ </AlertDescription>
+ </Alert>
+ )}
<CostSummary>
<CostSummaryRow
@@ -227,6 +281,14 @@ export const CommitmentView = ({ orgId, prod, entitlement, renewsOn, onBack, onD
valueClassName={newOnDemand > 0 ? "text-warning/90" : "text-muted"}
/>
</CostSummary>
+
+ {showChargeBreakdown && (
+ <ChargeBreakdown
+ prorationAmount={preview.data?.prorationAmount ?? 0}
+ additionalCharges={additionalCharges}
+ totalDueNow={preview.data?.totalDueNow ?? 0}
+ />
+ )}
</div>
<SheetFooter className="flex-row justify-between border-t">
diff --git a/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx b/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
index 8273cd1330..dfa32565d4 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
@@ -1,3 +1,6 @@
+import { TriangleAlert } from "lucide-react";
+
+import { Alert, AlertDescription, AlertTitle } from "@app/components/v3";
import { cn } from "@app/components/v3/utils";
import { BillingV2CatalogProduct, BillingV2Overview } from "@app/hooks/api";
@@ -17,6 +20,7 @@ export type OverviewProps = {
subState: BillingV2RenderState;
onManageSubscription: () => void;
onUpgrade: (productId: string) => void;
+ onSetCommitment: (productId: string) => void;
onUpdatePayment: () => void;
onEditDetails: () => void;
onContact: (prod: BillingV2CatalogProduct) => void;
@@ -33,6 +37,7 @@ export const Overview = ({
subState,
onManageSubscription,
onUpgrade,
+ onSetCommitment,
onUpdatePayment,
onEditDetails,
onContact,
@@ -51,14 +56,29 @@ export const Overview = ({
);
}
- const { mode } = overview;
+ const { mode, checkoutFrozen } = overview;
const isManaged = mode === "managed";
- // Managed plans and read-only billing roles cannot mutate the subscription.
- const productsReadOnly = isManaged || !canManageBilling;
+ // Managed plans and read-only billing roles cannot mutate the subscription. A frozen checkout
+ // (server DISABLE_CHECKOUT) disables every mutation path too, so treat it as read-only for the
+ // products area and show a notice — the customer never reaches a control that would 503.
+ const productsReadOnly = isManaged || !canManageBilling || checkoutFrozen;
+
+ const frozenNotice =
+ checkoutFrozen && !isManaged ? (
+ <Alert variant="warning">
+ <TriangleAlert />
+ <AlertTitle>Billing changes are temporarily paused</AlertTitle>
+ <AlertDescription>
+ Purchases and plan changes are unavailable right now. Your current subscription is
+ unaffected; please check back shortly.
+ </AlertDescription>
+ </Alert>
+ ) : null;
if (subState === "no-subscription") {
return (
<div className="flex flex-col gap-4">
+ {frozenNotice}
<Banner
mode={mode}
subState={subState}
@@ -71,6 +91,7 @@ export const Overview = ({
catalog={catalog}
readOnly={productsReadOnly}
onManage={onUpgrade}
+ onSetCommitment={onSetCommitment}
onContact={onContact}
/>
</div>
@@ -81,6 +102,7 @@ export const Overview = ({
return (
<div className="flex flex-col gap-4">
+ {frozenNotice}
<Banner
mode={mode}
subState={subState}
@@ -100,6 +122,7 @@ export const Overview = ({
catalog={catalog}
readOnly={productsReadOnly}
onManage={onUpgrade}
+ onSetCommitment={onSetCommitment}
onContact={onContact}
/>
{!isManaged && (
diff --git a/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsx b/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsx
index c8a9b33224..64fe7bde21 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsx
@@ -43,7 +43,8 @@ import {
cadencePeriod,
cadenceWord,
cadenceWordShort,
- dimAnnualCommitted,
+ canStartCommitment,
+ dimCommitted,
fmtMoney,
isMeteredCadence,
pluralizeUnit,
@@ -161,6 +162,8 @@ type PlanCardProps = {
// This product's one-per-product trial is already used up (any outcome), so no trial CTA.
trialUsed: boolean;
canChangeCommitment: boolean;
+ // Whether a commitment already exists, so the CTA reads "Change" vs "Set" commitment.
+ hasCommitment: boolean;
onActivate: (planTier: string) => void;
onStartTrial: (planTier: string) => void;
onChangeCommitment: () => void;
@@ -174,6 +177,7 @@ const PlanCard = ({
entitled,
trialUsed,
canChangeCommitment,
+ hasCommitment,
onActivate,
onStartTrial,
onChangeCommitment,
@@ -200,7 +204,7 @@ const PlanCard = ({
className="mt-auto self-start"
onClick={onChangeCommitment}
>
- Change commitment
+ {hasCommitment ? "Change commitment" : "Set commitment"}
<EditIcon />
</Button>
);
@@ -343,7 +347,9 @@ type ProductSheetProps = {
prod?: BillingV2CatalogProduct;
entitlement?: BillingV2Entitlement;
hasActiveSubscription: boolean;
- billingEmail?: string;
+ // Optionally open the sheet straight into a sub-view (e.g. "commitment" from the commit-and-save
+ // nudge) instead of the default plans view.
+ initialView?: SheetView;
returnPath: string;
renewsOn: string | null;
// This product's one-per-product trial is already used up (backend-computed from trial history).
@@ -360,7 +366,7 @@ export const ProductSheet = ({
prod,
entitlement,
hasActiveSubscription,
- billingEmail,
+ initialView,
returnPath,
renewsOn,
trialUsed,
@@ -368,7 +374,7 @@ export const ProductSheet = ({
onRemove,
onContact
}: ProductSheetProps) => {
- const [view, setView] = useState<SheetView>("plans");
+ const [view, setView] = useState<SheetView>(initialView ?? "plans");
// The plan tier chosen for the activate view.
const [activatePlan, setActivatePlan] = useState<string | null>(null);
// The plan tier awaiting trial confirmation (drives the confirm dialog).
@@ -387,9 +393,18 @@ export const ProductSheet = ({
// A trialing product is canceled (trial → free), not removed like a paid product line.
const isTrialing = Boolean(entitlement?.isTrialing);
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);
+ // The active product's plan-card price renders in its billing cadence. A new product defaults to
+ // yearly, EXCEPT when a self-serve trial is on offer: a trial is monthly/usage-based, so show monthly
+ // there. PlanPricing still falls back to monthly for a monthly-only plan.
+ const trialAvailable =
+ !entitled && !trialUsed && prod.plans.some((plan) => plan.selfServe && plan.trialable);
+ const displayCadence: BillingV2Cadence =
+ entitlement?.cadence ?? (trialAvailable ? "monthly" : "annual");
+ // Offer the commitment flow when the org already has a commitment (to change it) OR its pinned plan
+ // version lets it commit a dimension it hasn't set yet (start from zero, e.g. a monthly subscriber
+ // committing annually). Eligibility is the subscription read's per-dimension commitAvailable.
+ const hasCommitment = (entitlement?.dimensions ?? []).some(dimCommitted);
+ const canChangeCommitment = hasCommitment || canStartCommitment(entitlement);
// Render plan cards in the catalog's displayOrder (already sorted server-side). A deprecated plan is
// closed to new customers, so hide it unless the org is already entitled (e.g. currently on it).
@@ -468,7 +483,6 @@ export const ProductSheet = ({
prod={prod}
plan={activatePlanObj}
hasActiveSubscription={hasActiveSubscription}
- billingEmail={billingEmail}
returnPath={returnPath}
renewsOn={renewsOn}
onBack={() => setView("plans")}
@@ -516,6 +530,7 @@ export const ProductSheet = ({
trialUsed={trialUsed}
isCurrent={entitled && plan.tier === currentTier}
canChangeCommitment={canChangeCommitment}
+ hasCommitment={hasCommitment}
onActivate={openActivate}
onStartTrial={setTrialConfirmTier}
onChangeCommitment={() => setView("commitment")}
diff --git a/frontend/src/pages/organization/BillingV2Page/components/RemoveProductModal.tsx b/frontend/src/pages/organization/BillingV2Page/components/RemoveProductModal.tsx
index 58adab277a..142f5fc6b9 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/RemoveProductModal.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/RemoveProductModal.tsx
@@ -20,7 +20,7 @@ import {
useRemoveBillingV2Product
} from "@app/hooks/api";
-import { dimAnnualCommitted, fmtMoney } from "../billing-v2-format";
+import { dimCommitted, fmtMoney } from "../billing-v2-format";
// Removing the last product cancels the whole subscription (handled by the remove endpoint). The
// unused-time wording depends on whether the plan carries a minimum (annual) commitment.
@@ -38,9 +38,6 @@ type Props = {
onRemoved: () => void;
};
-const getServerMessage = (err: unknown): string | undefined =>
- (err as { response?: { data?: { message?: string } } })?.response?.data?.message;
-
export const RemoveProductModal = ({ orgId, product, onClose, onRemoved }: Props) => {
// Overview is already cached by the page (same orgId key), so this reuses it without refetching.
// Count every entitled product (the backend marks every subscription item entitled, including
@@ -53,9 +50,7 @@ export const RemoveProductModal = ({ orgId, product, onClose, onRemoved }: Props
).length;
const isOnlyProduct = overviewReady && entitledProductCount === 1;
// A minimum (annual) commitment means unused time is not credited/refunded on removal.
- const hasCommitment = (overview?.entitlements[product.id]?.dimensions ?? []).some(
- dimAnnualCommitted
- );
+ const hasCommitment = (overview?.entitlements[product.id]?.dimensions ?? []).some(dimCommitted);
const preview = usePreviewBillingV2Change();
const removeProduct = useRemoveBillingV2Product();
@@ -82,11 +77,8 @@ export const RemoveProductModal = ({ orgId, product, onClose, onRemoved }: Props
: `${product.name} will be removed. It may take a moment to update here.`
});
onRemoved();
- } catch (err) {
- createNotification({
- type: "error",
- text: getServerMessage(err) ?? `Failed to remove ${product.name}.`
- });
+ } catch {
+ // The backend's message is surfaced by the global mutation error handler (reactQuery.tsx).
}
};
diff --git a/frontend/src/pages/organization/BillingV2Page/components/cards/BillingHeaderCard.tsx b/frontend/src/pages/organization/BillingV2Page/components/cards/BillingHeaderCard.tsx
index 7476018627..807b0406d4 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/cards/BillingHeaderCard.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/cards/BillingHeaderCard.tsx
@@ -138,7 +138,7 @@ export const BillingHeaderCard = ({ overview, catalog }: BillingHeaderCardProps)
icon={<CreditCard />}
value={
hasRecurring ? (
- <div className="flex flex-col gap-0.5">
+ <div className="flex items-center justify-between gap-0.5">
{billing.monthlyRecurring > 0 && (
<div>
{fmtMoney(billing.monthlyRecurring)}{" "}
@@ -158,7 +158,7 @@ export const BillingHeaderCard = ({ overview, catalog }: BillingHeaderCardProps)
}
footer={
hasRecurring ? (
- <div className="flex items-center gap-1.5">
+ <div className="flex w-full items-center justify-between gap-1.5">
{billing.monthlyRecurring > 0 && <Badge variant="info">Monthly</Badge>}
{billing.annualCommitted > 0 && <Badge variant="warning">Annual</Badge>}
</div>
diff --git a/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx b/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx
index b0a5b2c231..81ef40eac4 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx
@@ -1,5 +1,5 @@
import { ReactNode } from "react";
-import { Package, RefreshCw } from "lucide-react";
+import { DollarSign, Package, RefreshCw } from "lucide-react";
import { createNotification } from "@app/components/notifications";
import {
@@ -26,29 +26,34 @@ import {
import {
byDisplayOrder,
+ commitSavingsNudge,
dimHasCeiling,
fmtMoney,
productAnnualCommitted,
tierLabel
} from "../../billing-v2-format";
import { asPlanDeprecation, deprecationSubline } from "../deprecation/deprecation-data";
-import {
- ActiveBadge,
- CardEmpty,
- DimensionMeter,
- DimensionRateLegend,
- ProductIcon
-} from "../shared";
+import { ActiveBadge, CardEmpty, DimensionMeter, ProductIcon } from "../shared";
type ActiveProductCardProps = {
prod: BillingV2CatalogProduct;
entitlement?: BillingV2Entitlement;
readOnly?: boolean;
onManage: (id: string) => void;
+ onSetCommitment: (id: string) => void;
};
// Full-width card for an active product: identity and status, price, Manage action, usage meters.
-const ActiveProductCard = ({ prod, entitlement, readOnly, onManage }: ActiveProductCardProps) => {
+const ActiveProductCard = ({
+ prod,
+ entitlement,
+ readOnly,
+ onManage,
+ onSetCommitment
+}: ActiveProductCardProps) => {
+ // "Commit annually and save" nudge: shown when the org holds this product monthly but hasn't set the
+ // available commitment. Clicking opens the set-commitment flow.
+ const commitNudge = readOnly ? null : commitSavingsNudge(entitlement);
// Every deprecation is presented as a retiring plan for now (see asPlanDeprecation).
const deprecation = asPlanDeprecation(entitlement?.deprecation);
const isProductDeprecated = deprecation?.kind === "product";
@@ -158,11 +163,37 @@ const ActiveProductCard = ({ prod, entitlement, readOnly, onManage }: ActiveProd
)}
</div>
{sortedDims.length > 0 && (
- <div className="flex flex-col gap-2.5">
+ <div className="flex flex-col gap-3.5">
{sortedDims.map((dim) => (
- <DimensionMeter key={dim.key} dim={dim} color={prod.color} hideLegend />
+ <DimensionMeter key={dim.key} dim={dim} color={prod.color} />
))}
- <DimensionRateLegend dims={sortedDims} color={prod.color} />
+ </div>
+ )}
+ {commitNudge && (
+ // Full-bleed strip at the card's bottom edge nudging the monthly subscriber to commit annually.
+ <div className="-mx-4 mt-1 -mb-4 flex items-center justify-between gap-3 border-t border-border bg-warning/5 px-4 py-2.5">
+ <span className="flex items-center gap-2.5 text-xs text-muted">
+ <span className="flex size-6 shrink-0 items-center justify-center rounded-md border border-warning/40 text-warning">
+ <DollarSign className="size-3.5" />
+ </span>
+ <span>
+ Commit annually and save{" "}
+ <span className="font-medium text-foreground">~{commitNudge.savingsPct}%</span> —{" "}
+ {commitNudge.qty.toLocaleString()} {commitNudge.label} would be{" "}
+ <span className="font-medium text-foreground">
+ {fmtMoney(commitNudge.annualCommitted)} / yr
+ </span>{" "}
+ instead of {fmtMoney(commitNudge.monthlyAnnualized)}.
+ </span>
+ </span>
+ <Button
+ variant="outline"
+ size="sm"
+ className="shrink-0"
+ onClick={() => onSetCommitment(prod.id)}
+ >
+ Switch to annual
+ </Button>
</div>
)}
</div>
@@ -221,6 +252,7 @@ type ProductsCardProps = {
catalog: BillingV2CatalogProduct[];
readOnly?: boolean;
onManage: (id: string) => void;
+ onSetCommitment: (id: string) => void;
onContact: (prod: BillingV2CatalogProduct) => void;
};
@@ -229,6 +261,7 @@ export const ProductsCard = ({
catalog,
readOnly,
onManage,
+ onSetCommitment,
onContact
}: ProductsCardProps) => {
// A deprecated product stays visible to existing subscribers but is closed to new ones, so hide it
@@ -302,6 +335,7 @@ export const ProductsCard = ({
entitlement={overview.entitlements[prod.id]}
readOnly={readOnly}
onManage={onManage}
+ onSetCommitment={onSetCommitment}
/>
))}
{available.length > 0 && (
diff --git a/frontend/src/pages/organization/BillingV2Page/components/shared.tsx b/frontend/src/pages/organization/BillingV2Page/components/shared.tsx
index f22104ac26..97604998d7 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/shared.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/shared.tsx
@@ -20,8 +20,8 @@ import { cn } from "@app/components/v3/utils";
import { BillingV2CatalogProduct, BillingV2EntitlementDim } from "@app/hooks/api";
import {
- dimAnnualCommitted,
dimBarSegments,
+ dimCommitted,
dimHasCeiling,
dimMonthlyRate,
dimOnDemandQuantity,
@@ -133,7 +133,7 @@ export const DimensionRateLegend = ({
}) => {
const entries = dims.filter(
(dim) =>
- dimAnnualCommitted(dim) && (dim.committedRate !== undefined || dim.onDemandRate !== undefined)
+ dimCommitted(dim) && (dim.committedRate !== undefined || dim.onDemandRate !== undefined)
);
if (entries.length === 0) {
return null;
@@ -172,7 +172,7 @@ type DimensionMeterProps = {
// on-demand overflow with a rate legend; a capped dimension a single used/limit fill; an uncapped
// one just its cost line, no bar.
export const DimensionMeter = ({ dim, color, hideLegend }: DimensionMeterProps) => {
- const committed = dimAnnualCommitted(dim);
+ const committed = dimCommitted(dim);
const { committedPct, onDemandPct } = dimBarSegments(dim);
const onDemandQty = dimOnDemandQuantity(dim);
const monthlyRate = dimMonthlyRate(dim);