Skip to content

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

Add per-product subscription management to the billing v2 surface

Tre Dubrava7a84a3b6b238
diff --git a/backend/src/ee/routes/v1/license-v2-router.ts b/backend/src/ee/routes/v1/license-v2-router.ts
index 17ac9df237..2eda6882ea 100644
--- a/backend/src/ee/routes/v1/license-v2-router.ts
+++ b/backend/src/ee/routes/v1/license-v2-router.ts
@@ -90,6 +90,25 @@ const BillingV2OverviewSchema = z.object({
entitlements: z.record(BillingV2EntitlementSchema)
});
+const BillingV2PreviewLineSchema = z.object({
+ description: z.string(),
+ amount: z.number(),
+ proration: z.boolean()
+});
+
+const BillingV2PreviewSchema = z.object({
+ currency: z.string(),
+ prorationAmount: z.number(),
+ nextInvoiceTotal: z.number(),
+ nextRecurringTotal: z.number(),
+ prorationDate: z.number(),
+ lines: BillingV2PreviewLineSchema.array()
+});
+
+// Subscription mutations mirror the checkout result: the change applies in place and the affected
+// subscription id comes back (the DB mirror catches up via webhook, so the UI refetches overview).
+const BillingV2MutationResultSchema = z.object({ subscriptionId: z.string().optional() });
+
export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
// Every route is gated on LICENSE_SERVER_V2_MODE="on"; the billing surface is invisible until full v2 cutover.
server.addHook("onRequest", async () => {
@@ -229,4 +248,130 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
});
}
});
+
+ server.route({
+ method: "POST",
+ url: "/:organizationId/billing/v2/subscription/preview",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ params: z.object({ organizationId: z.string().trim() }),
+ body: z
+ .object({
+ addProductId: z.string().trim().optional(),
+ cadence: z.enum(["monthly", "annual"]).optional(),
+ removeProductId: z.string().trim().optional()
+ })
+ .refine((b) => Boolean(b.addProductId) || Boolean(b.removeProductId), {
+ message: "provide a product to add or remove"
+ }),
+ response: {
+ 200: z.object({ preview: BillingV2PreviewSchema })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ return server.services.licenseV2.previewChange({
+ orgId: req.params.organizationId,
+ actor: buildActor(req.permission),
+ addProductId: req.body.addProductId,
+ cadence: req.body.cadence,
+ removeProductId: req.body.removeProductId
+ });
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:organizationId/billing/v2/subscription/items",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ params: z.object({ organizationId: z.string().trim() }),
+ body: z.object({
+ productId: z.string().trim(),
+ cadence: z.enum(["monthly", "annual"]).optional()
+ }),
+ response: {
+ 200: BillingV2MutationResultSchema
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ return server.services.licenseV2.addProduct({
+ orgId: req.params.organizationId,
+ actor: buildActor(req.permission),
+ productId: req.body.productId,
+ cadence: req.body.cadence
+ });
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:organizationId/billing/v2/subscription/items/:productId",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ params: z.object({ organizationId: z.string().trim(), productId: z.string().trim() }),
+ querystring: z.object({ prorationDate: z.coerce.number().optional() }),
+ response: {
+ 200: BillingV2MutationResultSchema
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ return server.services.licenseV2.removeProduct({
+ orgId: req.params.organizationId,
+ actor: buildActor(req.permission),
+ productId: req.params.productId,
+ prorationDate: req.query.prorationDate
+ });
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:organizationId/billing/v2/subscription/cancel",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ params: z.object({ organizationId: z.string().trim() }),
+ response: {
+ 200: BillingV2MutationResultSchema
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ return server.services.licenseV2.cancelSubscription({
+ orgId: req.params.organizationId,
+ actor: buildActor(req.permission)
+ });
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:organizationId/billing/v2/subscription/resume",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ params: z.object({ organizationId: z.string().trim() }),
+ response: {
+ 200: BillingV2MutationResultSchema
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ return server.services.licenseV2.resumeSubscription({
+ orgId: req.params.organizationId,
+ actor: buildActor(req.permission)
+ });
+ }
+ });
};
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 8e478c4280..ae62e77897 100644
--- a/backend/src/ee/services/license-v2/license-v2-service.ts
+++ b/backend/src/ee/services/license-v2/license-v2-service.ts
@@ -10,6 +10,7 @@ import {
TCatalogProduct,
TCheckoutLineItem,
TEntitlementOrg,
+ TSubscriptionPreviewPayload,
TSubscriptionResponse
} from "@app/services/license-client/license-client-types";
import { TOrgDALFactory } from "@app/services/org/org-dal";
@@ -23,12 +24,17 @@ import {
BillingV2Entitlement,
BillingV2Model,
BillingV2Overview,
+ BillingV2Preview,
BillingV2SubState,
TAddBillingV2PaymentMethodDTO,
+ TAddBillingV2ProductDTO,
+ TBillingV2SubscriptionLifecycleDTO,
TCreateBillingV2CheckoutSessionDTO,
TCreateBillingV2PortalSessionDTO,
TGetBillingV2CatalogDTO,
- TGetBillingV2OverviewDTO
+ TGetBillingV2OverviewDTO,
+ TPreviewBillingV2ChangeDTO,
+ TRemoveBillingV2ProductDTO
} from "./license-v2-types";
type TLicenseV2ServiceFactoryDep = {
@@ -45,6 +51,11 @@ type TLicenseV2ServiceFactoryDep = {
| "getBillingProfile"
| "createCheckout"
| "createPortal"
+ | "previewSubscriptionChange"
+ | "addSubscriptionItems"
+ | "removeSubscriptionItem"
+ | "cancelSubscription"
+ | "resumeSubscription"
>;
};
@@ -475,6 +486,89 @@ 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"): 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));
+ 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,
+ cadence,
+ removeProductId
+ }: TPreviewBillingV2ChangeDTO): Promise<{ preview: BillingV2Preview }> => {
+ await ensureManageBilling(orgId, actor);
+ if (!addProductId && !removeProductId) {
+ throw new BadRequestError({ message: "Provide a product to add or remove" });
+ }
+
+ const payload: TSubscriptionPreviewPayload = {};
+ if (addProductId) {
+ payload.add = await resolveAddItems(addProductId, cadence);
+ }
+ if (removeProductId) {
+ payload.remove = [removeProductId];
+ }
+
+ const preview = await licenseClient.previewSubscriptionChange(orgId, payload);
+ return {
+ preview: {
+ currency: preview.currency,
+ prorationAmount: centsToDollars(preview.prorationAmount),
+ nextInvoiceTotal: centsToDollars(preview.nextInvoiceTotal),
+ nextRecurringTotal: centsToDollars(preview.nextRecurringTotal),
+ prorationDate: preview.prorationDate,
+ lines: preview.lines.map((line) => ({
+ description: line.description,
+ amount: centsToDollars(line.amount),
+ proration: line.proration
+ }))
+ }
+ };
+ };
+
+ // 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, cadence }: TAddBillingV2ProductDTO) => {
+ await ensureManageBilling(orgId, actor);
+ const items = await resolveAddItems(productId, cadence);
+ const result = await licenseClient.addSubscriptionItems(orgId, { items });
+ return { subscriptionId: result.subscriptionId };
+ };
+
+ // Remove a single product from a multi-product subscription, the operation the Stripe Customer
+ // Portal cannot do. prorationDate pins the proration to the previewed value when provided.
+ const removeProduct = async ({ orgId, actor, productId, prorationDate }: TRemoveBillingV2ProductDTO) => {
+ await ensureManageBilling(orgId, actor);
+ const result = await licenseClient.removeSubscriptionItem(orgId, productId, prorationDate);
+ return { subscriptionId: result.subscriptionId };
+ };
+
+ const cancelSubscription = async ({ orgId, actor }: TBillingV2SubscriptionLifecycleDTO) => {
+ await ensureManageBilling(orgId, actor);
+ const result = await licenseClient.cancelSubscription(orgId);
+ return { subscriptionId: result.subscriptionId };
+ };
+
+ const resumeSubscription = async ({ orgId, actor }: TBillingV2SubscriptionLifecycleDTO) => {
+ await ensureManageBilling(orgId, actor);
+ const result = await licenseClient.resumeSubscription(orgId);
+ return { subscriptionId: result.subscriptionId };
+ };
+
return {
// Billing surface (portal, checkout, overview) goes live only at full v2 cutover, not during read-compare.
isEnabled: () => envConfig.LICENSE_SERVER_V2_MODE === "on",
@@ -482,6 +576,11 @@ export const licenseV2ServiceFactory = ({
getCatalog,
portalSession,
checkoutSession,
- addPaymentMethod
+ addPaymentMethod,
+ previewChange,
+ addProduct,
+ removeProduct,
+ cancelSubscription,
+ resumeSubscription
};
};
diff --git a/backend/src/ee/services/license-v2/license-v2-types.ts b/backend/src/ee/services/license-v2/license-v2-types.ts
index 9adf688fdd..04482ed479 100644
--- a/backend/src/ee/services/license-v2/license-v2-types.ts
+++ b/backend/src/ee/services/license-v2/license-v2-types.ts
@@ -117,3 +117,45 @@ export type TAddBillingV2PaymentMethodDTO = {
actor: OrgServiceActor;
returnPath?: string;
};
+
+export type BillingV2PreviewLine = {
+ description: string;
+ amount: number;
+ proration: boolean;
+};
+
+export type BillingV2Preview = {
+ currency: string;
+ prorationAmount: number;
+ nextInvoiceTotal: number;
+ nextRecurringTotal: number;
+ prorationDate: number;
+ lines: BillingV2PreviewLine[];
+};
+
+export type TPreviewBillingV2ChangeDTO = {
+ orgId: string;
+ actor: OrgServiceActor;
+ addProductId?: string;
+ cadence?: "monthly" | "annual";
+ removeProductId?: string;
+};
+
+export type TAddBillingV2ProductDTO = {
+ orgId: string;
+ actor: OrgServiceActor;
+ productId: string;
+ cadence?: "monthly" | "annual";
+};
+
+export type TRemoveBillingV2ProductDTO = {
+ orgId: string;
+ actor: OrgServiceActor;
+ productId: string;
+ prorationDate?: number;
+};
+
+export type TBillingV2SubscriptionLifecycleDTO = {
+ orgId: string;
+ actor: OrgServiceActor;
+};
diff --git a/backend/src/services/license-client/license-client-backends.ts b/backend/src/services/license-client/license-client-backends.ts
index 62e76fa91a..87577e86fe 100644
--- a/backend/src/services/license-client/license-client-backends.ts
+++ b/backend/src/services/license-client/license-client-backends.ts
@@ -7,7 +7,9 @@ import {
cloudPlanResponseSchema,
entitlementsResponseSchema,
sessionResponseSchema,
+ subscriptionPreviewResponseSchema,
subscriptionResponseSchema,
+ TAddSubscriptionItemsPayload,
TBillingProfileResponse,
TCatalogResponse,
TCheckoutResult,
@@ -18,6 +20,8 @@ import {
TEntitlementsResponse,
TLicenseClientBackend,
TSessionResponse,
+ TSubscriptionPreview,
+ TSubscriptionPreviewPayload,
TSubscriptionResponse
} from "./license-client-types";
@@ -28,6 +32,10 @@ const CLOUD_PLAN_PATH = "/v1/cloud-plan";
const BILLING_PROFILE_PATH = "/v1/billing/profile";
const CHECKOUT_SESSION_PATH = "/v1/billing/checkout-session";
const PORTAL_SESSION_PATH = "/v1/billing/portal-session";
+const SUBSCRIPTION_PREVIEW_PATH = "/v1/billing/subscription/preview";
+const SUBSCRIPTION_ITEMS_PATH = "/v1/billing/subscription/items";
+const SUBSCRIPTION_CANCEL_PATH = "/v1/billing/subscription/cancel";
+const SUBSCRIPTION_RESUME_PATH = "/v1/billing/subscription/resume";
// Issuer/audience/subject match the license server's in-code constants (it validates iss/aud against
// them). They are public claims, not per-deployment config, so they live here rather than in env.
@@ -188,5 +196,92 @@ export const licenseServerBackend = (
}
const body: unknown = await res.json();
return sessionResponseSchema.parse(body);
+ },
+
+ previewSubscriptionChange: async (
+ orgId: string,
+ payload: TSubscriptionPreviewPayload
+ ): Promise<TSubscriptionPreview> => {
+ const url = new URL(SUBSCRIPTION_PREVIEW_PATH, serverUrl);
+ url.searchParams.set("org_id", orgId);
+ const res = await fetch(url, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}`, "Content-Type": "application/json" },
+ body: JSON.stringify(payload),
+ redirect: "manual"
+ });
+ if (!res.ok) {
+ throw new Error(`license server responded with ${res.status}`);
+ }
+ const body: unknown = await res.json();
+ return subscriptionPreviewResponseSchema.parse(body);
+ },
+
+ addSubscriptionItems: async (orgId: string, payload: TAddSubscriptionItemsPayload): Promise<TCheckoutResult> => {
+ const url = new URL(SUBSCRIPTION_ITEMS_PATH, serverUrl);
+ url.searchParams.set("org_id", orgId);
+ const res = await fetch(url, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}`, "Content-Type": "application/json" },
+ body: JSON.stringify(payload),
+ redirect: "manual"
+ });
+ if (!res.ok) {
+ throw new Error(`license server responded with ${res.status}`);
+ }
+ const body: unknown = await res.json();
+ return checkoutResultSchema.parse(body);
+ },
+
+ removeSubscriptionItem: async (
+ orgId: string,
+ productId: string,
+ prorationDate?: number
+ ): Promise<TCheckoutResult> => {
+ const url = new URL(`${SUBSCRIPTION_ITEMS_PATH}/${encodeURIComponent(productId)}`, serverUrl);
+ url.searchParams.set("org_id", orgId);
+ if (prorationDate !== undefined) {
+ url.searchParams.set("prorationDate", String(prorationDate));
+ }
+ const res = await fetch(url, {
+ method: "DELETE",
+ headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}` },
+ redirect: "manual"
+ });
+ if (!res.ok) {
+ throw new Error(`license server responded with ${res.status}`);
+ }
+ const body: unknown = await res.json();
+ return checkoutResultSchema.parse(body);
+ },
+
+ cancelSubscription: async (orgId: string): Promise<TCheckoutResult> => {
+ const url = new URL(SUBSCRIPTION_CANCEL_PATH, serverUrl);
+ url.searchParams.set("org_id", orgId);
+ const res = await fetch(url, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}` },
+ redirect: "manual"
+ });
+ if (!res.ok) {
+ throw new Error(`license server responded with ${res.status}`);
+ }
+ const body: unknown = await res.json();
+ return checkoutResultSchema.parse(body);
+ },
+
+ resumeSubscription: async (orgId: string): Promise<TCheckoutResult> => {
+ const url = new URL(SUBSCRIPTION_RESUME_PATH, serverUrl);
+ url.searchParams.set("org_id", orgId);
+ const res = await fetch(url, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}` },
+ redirect: "manual"
+ });
+ if (!res.ok) {
+ throw new Error(`license server responded with ${res.status}`);
+ }
+ const body: unknown = await res.json();
+ return checkoutResultSchema.parse(body);
}
});
diff --git a/backend/src/services/license-client/license-client-types.ts b/backend/src/services/license-client/license-client-types.ts
index 2fdba36e8e..becd27831b 100644
--- a/backend/src/services/license-client/license-client-types.ts
+++ b/backend/src/services/license-client/license-client-types.ts
@@ -119,6 +119,28 @@ 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).
+// prorationDate is echoed so the follow-up change can reproduce the same numbers.
+const subscriptionPreviewLineSchema = z
+ .object({
+ description: z.string(),
+ amount: z.number(),
+ proration: z.boolean()
+ })
+ .passthrough();
+
+export const subscriptionPreviewResponseSchema = z
+ .object({
+ currency: z.string(),
+ prorationAmount: z.number(),
+ nextInvoiceTotal: z.number(),
+ nextRecurringTotal: z.number(),
+ prorationDate: z.number(),
+ lines: z.array(subscriptionPreviewLineSchema).default([])
+ })
+ .passthrough();
+
// The cloud-plan FeatureSet carries plan caps; the server nulls a limit when it is effectively
// unlimited. Used counts come back zeroed and are overlaid by this app, so we ignore them.
export const cloudPlanResponseSchema = z
@@ -182,6 +204,7 @@ export type TSessionResponse = z.infer<typeof sessionResponseSchema>;
export type TCheckoutResult = z.infer<typeof checkoutResultSchema>;
export type TCloudPlanResponse = z.infer<typeof cloudPlanResponseSchema>;
export type TBillingProfileResponse = z.infer<typeof billingProfileResponseSchema>;
+export type TSubscriptionPreview = z.infer<typeof subscriptionPreviewResponseSchema>;
export type TCheckoutLineItem = {
productId: string;
@@ -190,6 +213,15 @@ export type TCheckoutLineItem = {
quantities: Record<string, number>;
};
+export type TSubscriptionPreviewPayload = {
+ add?: TCheckoutLineItem[];
+ remove?: string[];
+};
+
+export type TAddSubscriptionItemsPayload = {
+ items: TCheckoutLineItem[];
+};
+
export type TCreateCheckoutPayload = {
items: TCheckoutLineItem[];
email?: string;
@@ -208,4 +240,9 @@ export type TLicenseClientBackend = {
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, prorationDate?: number) => Promise<TCheckoutResult>;
+ cancelSubscription: (orgId: string) => Promise<TCheckoutResult>;
+ resumeSubscription: (orgId: string) => Promise<TCheckoutResult>;
};
diff --git a/backend/src/services/license-client/license-client.ts b/backend/src/services/license-client/license-client.ts
index 10a5fc5ec1..147751322c 100644
--- a/backend/src/services/license-client/license-client.ts
+++ b/backend/src/services/license-client/license-client.ts
@@ -6,10 +6,12 @@ import { featureReaderFactory } from "./feature-reader";
import { licenseServerBackend } from "./license-client-backends";
import { entitlementResolverFactory } from "./license-client-cache";
import {
+ TAddSubscriptionItemsPayload,
TCreateCheckoutPayload,
TCreatePortalPayload,
TEntitlementOrg,
- TLicenseClientBackend
+ TLicenseClientBackend,
+ TSubscriptionPreviewPayload
} from "./license-client-types";
type TLicenseClientFactoryDep = {
@@ -108,6 +110,41 @@ export const licenseClientFactory = ({ envConfig, keyStore }: TLicenseClientFact
return backend.createPortalSession(orgId, payload);
};
+ const previewSubscriptionChange = async (orgId: string, payload: TSubscriptionPreviewPayload) => {
+ if (!backend) {
+ throw new Error("license client backend is not configured");
+ }
+ return backend.previewSubscriptionChange(orgId, payload);
+ };
+
+ const addSubscriptionItems = async (orgId: string, payload: TAddSubscriptionItemsPayload) => {
+ if (!backend) {
+ throw new Error("license client backend is not configured");
+ }
+ return backend.addSubscriptionItems(orgId, payload);
+ };
+
+ const removeSubscriptionItem = async (orgId: string, productId: string, prorationDate?: number) => {
+ if (!backend) {
+ throw new Error("license client backend is not configured");
+ }
+ return backend.removeSubscriptionItem(orgId, productId, prorationDate);
+ };
+
+ const cancelSubscription = async (orgId: string) => {
+ if (!backend) {
+ throw new Error("license client backend is not configured");
+ }
+ return backend.cancelSubscription(orgId);
+ };
+
+ const resumeSubscription = async (orgId: string) => {
+ if (!backend) {
+ throw new Error("license client backend is not configured");
+ }
+ return backend.resumeSubscription(orgId);
+ };
+
return {
...featureReaderFactory({ getEntitlements }),
getEntitlements,
@@ -116,6 +153,11 @@ export const licenseClientFactory = ({ envConfig, keyStore }: TLicenseClientFact
getCloudPlan,
getBillingProfile,
createCheckout,
- createPortal
+ createPortal,
+ previewSubscriptionChange,
+ addSubscriptionItems,
+ removeSubscriptionItem,
+ cancelSubscription,
+ resumeSubscription
};
};
diff --git a/frontend/src/hooks/api/billingV2/index.tsx b/frontend/src/hooks/api/billingV2/index.tsx
index 4bf9e95164..5f7f4d603f 100644
--- a/frontend/src/hooks/api/billingV2/index.tsx
+++ b/frontend/src/hooks/api/billingV2/index.tsx
@@ -1,7 +1,12 @@
export {
useAddBillingV2PaymentMethod,
+ useAddBillingV2Product,
+ useCancelBillingV2Subscription,
useCreateBillingV2CheckoutSession,
- useCreateBillingV2PortalSession
+ useCreateBillingV2PortalSession,
+ usePreviewBillingV2Change,
+ useRemoveBillingV2Product,
+ useResumeBillingV2Subscription
} from "./mutations";
export { billingV2Keys, useGetBillingV2Catalog, useGetBillingV2Overview } from "./queries";
export type {
@@ -14,5 +19,7 @@ export type {
BillingV2Model,
BillingV2Overview,
BillingV2PaymentMethod,
+ BillingV2Preview,
+ BillingV2PreviewLine,
BillingV2SubState
} from "./types";
diff --git a/frontend/src/hooks/api/billingV2/mutations.tsx b/frontend/src/hooks/api/billingV2/mutations.tsx
index 1ae5c8e024..42d54c8fa5 100644
--- a/frontend/src/hooks/api/billingV2/mutations.tsx
+++ b/frontend/src/hooks/api/billingV2/mutations.tsx
@@ -1,12 +1,19 @@
-import { useMutation } from "@tanstack/react-query";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
+import { billingV2Keys } from "./queries";
import {
BillingV2CheckoutResult,
+ BillingV2MutationResult,
+ BillingV2Preview,
TAddBillingV2PaymentMethodDTO,
+ TAddBillingV2ProductDTO,
+ TBillingV2LifecycleDTO,
TCreateBillingV2CheckoutSessionDTO,
- TCreateBillingV2PortalSessionDTO
+ TCreateBillingV2PortalSessionDTO,
+ TPreviewBillingV2ChangeDTO,
+ TRemoveBillingV2ProductDTO
} from "./types";
export const useCreateBillingV2PortalSession = () => {
@@ -57,3 +64,86 @@ export const useAddBillingV2PaymentMethod = () => {
}
});
};
+
+// Preview-only: never mutates, so it does not invalidate the overview. The caller shows the result
+// in a confirmation dialog before committing the add/remove.
+export const usePreviewBillingV2Change = () => {
+ return useMutation({
+ mutationFn: async ({ orgId, addProductId, cadence, removeProductId }: TPreviewBillingV2ChangeDTO) => {
+ const {
+ data: { preview }
+ } = await apiRequest.post<{ preview: BillingV2Preview }>(
+ `/api/v1/organizations/${orgId}/billing/v2/subscription/preview`,
+ { addProductId, cadence, removeProductId }
+ );
+
+ return preview;
+ }
+ });
+};
+
+export const useAddBillingV2Product = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ orgId, productId, cadence }: TAddBillingV2ProductDTO) => {
+ const { data } = await apiRequest.post<BillingV2MutationResult>(
+ `/api/v1/organizations/${orgId}/billing/v2/subscription/items`,
+ { productId, cadence }
+ );
+
+ return data;
+ },
+ onSuccess: (_data, { orgId }) => {
+ void queryClient.invalidateQueries({ queryKey: billingV2Keys.overview(orgId) });
+ }
+ });
+};
+
+export const useRemoveBillingV2Product = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ orgId, productId, prorationDate }: TRemoveBillingV2ProductDTO) => {
+ const params = prorationDate === undefined ? "" : `?prorationDate=${prorationDate}`;
+ const { data } = await apiRequest.delete<BillingV2MutationResult>(
+ `/api/v1/organizations/${orgId}/billing/v2/subscription/items/${encodeURIComponent(productId)}${params}`
+ );
+
+ return data;
+ },
+ onSuccess: (_data, { orgId }) => {
+ void queryClient.invalidateQueries({ queryKey: billingV2Keys.overview(orgId) });
+ }
+ });
+};
+
+export const useCancelBillingV2Subscription = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ orgId }: TBillingV2LifecycleDTO) => {
+ const { data } = await apiRequest.post<BillingV2MutationResult>(
+ `/api/v1/organizations/${orgId}/billing/v2/subscription/cancel`
+ );
+
+ return data;
+ },
+ onSuccess: (_data, { orgId }) => {
+ void queryClient.invalidateQueries({ queryKey: billingV2Keys.overview(orgId) });
+ }
+ });
+};
+
+export const useResumeBillingV2Subscription = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ orgId }: TBillingV2LifecycleDTO) => {
+ const { data } = await apiRequest.post<BillingV2MutationResult>(
+ `/api/v1/organizations/${orgId}/billing/v2/subscription/resume`
+ );
+
+ return data;
+ },
+ onSuccess: (_data, { orgId }) => {
+ void queryClient.invalidateQueries({ queryKey: billingV2Keys.overview(orgId) });
+ }
+ });
+};
diff --git a/frontend/src/hooks/api/billingV2/types.ts b/frontend/src/hooks/api/billingV2/types.ts
index 7c40376d3e..a05c9c10cc 100644
--- a/frontend/src/hooks/api/billingV2/types.ts
+++ b/frontend/src/hooks/api/billingV2/types.ts
@@ -110,3 +110,47 @@ export type TAddBillingV2PaymentMethodDTO = {
orgId: string;
returnPath?: string;
};
+
+export type BillingV2PreviewLine = {
+ description: string;
+ amount: number;
+ proration: boolean;
+};
+
+// prorationAmount is signed: positive is charged now (an add), negative is a credit toward the next
+// invoice (a removal). prorationDate is echoed so the follow-up change reproduces the same numbers.
+export type BillingV2Preview = {
+ currency: string;
+ prorationAmount: number;
+ nextInvoiceTotal: number;
+ nextRecurringTotal: number;
+ prorationDate: number;
+ lines: BillingV2PreviewLine[];
+};
+
+export type BillingV2MutationResult = {
+ subscriptionId?: string;
+};
+
+export type TPreviewBillingV2ChangeDTO = {
+ orgId: string;
+ addProductId?: string;
+ cadence?: BillingV2Cadence;
+ removeProductId?: string;
+};
+
+export type TAddBillingV2ProductDTO = {
+ orgId: string;
+ productId: string;
+ cadence?: BillingV2Cadence;
+};
+
+export type TRemoveBillingV2ProductDTO = {
+ orgId: string;
+ productId: string;
+ prorationDate?: number;
+};
+
+export type TBillingV2LifecycleDTO = {
+ orgId: string;
+};
diff --git a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
index 9e067ba958..47e1e7338d 100644
--- a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
@@ -22,6 +22,7 @@ import {
import { BillingV2RenderState, Overview } from "./components/Overview";
import { ProductSheet } from "./components/ProductSheet";
+import { RemoveProductModal } from "./components/RemoveProductModal";
import { catalogById, intervalToCadence } from "./billing-v2-data";
const CONTACT_SALES_URL = "https://infisical.com/talk-to-us";
@@ -47,6 +48,7 @@ export const BillingV2Page = () => {
const addPaymentMethod = useAddBillingV2PaymentMethod();
const [flow, setFlow] = useState<BillingV2Flow | null>(null);
+ const [removeProdId, setRemoveProdId] = useState<string | null>(null);
// Stripe redirects back with ?checkout=success|canceled; surface the outcome and refresh state.
useEffect(() => {
@@ -77,6 +79,7 @@ export const BillingV2Page = () => {
}
const cadence = intervalToCadence(overview?.interval ?? null);
+ const removeProd = removeProdId ? catalogById(catalog, removeProdId) : undefined;
const close = () => setFlow(null);
@@ -195,6 +198,7 @@ export const BillingV2Page = () => {
subState={subState}
onManageSubscription={onManageSubscription}
onUpgrade={onUpgrade}
+ onRemove={setRemoveProdId}
onUpdatePayment={onUpdatePayment}
onEditDetails={onEditDetails}
onContact={onContact}
@@ -220,6 +224,14 @@ export const BillingV2Page = () => {
}}
/>
)}
+
+ {removeProd && (
+ <RemoveProductModal
+ orgId={orgId}
+ product={removeProd}
+ onClose={() => setRemoveProdId(null)}
+ />
+ )}
</div>
);
};
diff --git a/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx b/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
index 885f94fb65..4349b96866 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
@@ -276,10 +276,11 @@ type ProductRowProps = {
entitlement?: BillingV2Entitlement;
readOnly?: boolean;
onManage: (id: string) => void;
+ onRemove: (id: string) => void;
onContact: (prod: BillingV2CatalogProduct) => void;
};
-const ProductRow = ({ prod, entitlement, readOnly, onManage, onContact }: ProductRowProps) => {
+const ProductRow = ({ prod, entitlement, readOnly, onManage, onRemove, onContact }: ProductRowProps) => {
const entitled = Boolean(entitlement?.entitled);
let limitNote: string | null = null;
if (entitled && entitlement && entitlement.limit !== null && entitlement.limit !== undefined) {
@@ -293,9 +294,16 @@ const ProductRow = ({ prod, entitlement, readOnly, onManage, onContact }: Produc
if (!readOnly) {
if (entitled) {
action = (
- <Button variant="outline" size="sm" onClick={() => onManage(prod.id)}>
- Manage
- </Button>
+ <>
+ {selfServe && (
+ <Button variant="outline" size="sm" onClick={() => onRemove(prod.id)}>
+ Remove
+ </Button>
+ )}
+ <Button variant="outline" size="sm" onClick={() => onManage(prod.id)}>
+ Manage
+ </Button>
+ </>
);
} else if (selfServe) {
action = (
@@ -339,10 +347,18 @@ type ProductsCardProps = {
catalog: BillingV2CatalogProduct[];
readOnly?: boolean;
onManage: (id: string) => void;
+ onRemove: (id: string) => void;
onContact: (prod: BillingV2CatalogProduct) => void;
};
-const ProductsCard = ({ overview, catalog, readOnly, onManage, onContact }: ProductsCardProps) => (
+const ProductsCard = ({
+ overview,
+ catalog,
+ readOnly,
+ onManage,
+ onRemove,
+ onContact
+}: ProductsCardProps) => (
<Card>
<CardHeader>
<CardTitle>Products</CardTitle>
@@ -360,6 +376,7 @@ const ProductsCard = ({ overview, catalog, readOnly, onManage, onContact }: Prod
entitlement={overview.entitlements[prod.id]}
readOnly={readOnly}
onManage={onManage}
+ onRemove={onRemove}
onContact={onContact}
/>
))}
@@ -519,6 +536,7 @@ export type OverviewProps = {
subState: BillingV2RenderState;
onManageSubscription: () => void;
onUpgrade: (productId: string) => void;
+ onRemove: (productId: string) => void;
onUpdatePayment: () => void;
onEditDetails: () => void;
onContact: (prod: BillingV2CatalogProduct) => void;
@@ -532,6 +550,7 @@ export const Overview = ({
subState,
onManageSubscription,
onUpgrade,
+ onRemove,
onUpdatePayment,
onEditDetails,
onContact,
@@ -571,6 +590,7 @@ export const Overview = ({
catalog={catalog}
readOnly={productsReadOnly}
onManage={onUpgrade}
+ onRemove={onRemove}
onContact={onContact}
/>
</div>
@@ -595,6 +615,7 @@ export const Overview = ({
catalog={catalog}
readOnly={productsReadOnly}
onManage={onUpgrade}
+ onRemove={onRemove}
onContact={onContact}
/>
{showPayment && (
diff --git a/frontend/src/pages/organization/BillingV2Page/components/RemoveProductModal.tsx b/frontend/src/pages/organization/BillingV2Page/components/RemoveProductModal.tsx
new file mode 100644
index 0000000000..ae9dcd1ae4
--- /dev/null
+++ b/frontend/src/pages/organization/BillingV2Page/components/RemoveProductModal.tsx
@@ -0,0 +1,114 @@
+import { useEffect } from "react";
+import { Trash2Icon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogMedia,
+ AlertDialogTitle
+} from "@app/components/v3";
+import {
+ BillingV2CatalogProduct,
+ usePreviewBillingV2Change,
+ useRemoveBillingV2Product
+} from "@app/hooks/api";
+
+import { fmtMoney } from "../billing-v2-data";
+
+type Props = {
+ orgId: string;
+ product: BillingV2CatalogProduct;
+ onClose: () => void;
+};
+
+export const RemoveProductModal = ({ orgId, product, onClose }: Props) => {
+ const preview = usePreviewBillingV2Change();
+ const removeProduct = useRemoveBillingV2Product();
+
+ // Preview the prorated credit once when the dialog opens, so the user confirms against real numbers.
+ useEffect(() => {
+ preview.mutate({ orgId, removeProductId: product.id });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [orgId, product.id]);
+
+ const handleRemove = async () => {
+ try {
+ await removeProduct.mutateAsync({
+ orgId,
+ productId: product.id,
+ prorationDate: preview.data?.prorationDate
+ });
+ createNotification({
+ type: "success",
+ text: `${product.name} will be removed. It may take a moment to update here.`
+ });
+ onClose();
+ } catch {
+ createNotification({ type: "error", text: `Failed to remove ${product.name}.` });
+ }
+ };
+
+ const credit = preview.data ? Math.abs(preview.data.prorationAmount) : 0;
+
+ return (
+ <AlertDialog
+ open
+ onOpenChange={(isOpen) => {
+ if (!isOpen) {
+ onClose();
+ }
+ }}
+ >
+ <AlertDialogContent className="sm:max-w-xl!">
+ <AlertDialogHeader>
+ <AlertDialogMedia>
+ <Trash2Icon />
+ </AlertDialogMedia>
+ <AlertDialogTitle>Remove {product.name}?</AlertDialogTitle>
+ <AlertDialogDescription>
+ {product.name} is removed right away. The unused time you already paid for is credited to
+ your next invoice, and your other products are unaffected.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <div className="rounded-md border border-border bg-mineshaft-700/40 px-4 py-3 text-sm">
+ {preview.isPending && (
+ <span className="text-mineshaft-300">Calculating your prorated credit...</span>
+ )}
+ {preview.isError && (
+ <span className="text-mineshaft-300">
+ We couldn&apos;t calculate the credit, but you can still remove this product.
+ </span>
+ )}
+ {preview.data && (
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center justify-between">
+ <span className="text-mineshaft-300">Prorated credit to next invoice</span>
+ <span className="font-semibold text-foreground tabular-nums">
+ {fmtMoney(credit, 2)}
+ </span>
+ </div>
+ <div className="flex items-center justify-between">
+ <span className="text-mineshaft-300">New recurring total</span>
+ <span className="font-semibold text-foreground tabular-nums">
+ {fmtMoney(preview.data.nextRecurringTotal, 2)}
+ </span>
+ </div>
+ </div>
+ )}
+ </div>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Keep product</AlertDialogCancel>
+ <AlertDialogAction variant="danger" isDisabled={removeProduct.isPending} onClick={handleRemove}>
+ Remove {product.name}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+};