Skip to content

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

feat(api): implement billing v2 usage breakdown and organization listing

Victor Hugo dos Santoscd1a07ece2cb
diff --git a/backend/src/ee/routes/v1/license-v2-router.ts b/backend/src/ee/routes/v1/license-v2-router.ts
index 7a22037e9a..94bfe9b96e 100644
--- a/backend/src/ee/routes/v1/license-v2-router.ts
+++ b/backend/src/ee/routes/v1/license-v2-router.ts
@@ -1,10 +1,12 @@
import { FastifyRequest } from "fastify";
import { z } from "zod";
+import { BillingV2BreakdownDimension } from "@app/ee/services/license-v2/license-v2-types";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { isUserSessionAuth } from "@app/server/plugins/auth/inject-identity";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
+import { isSuperAdmin } from "@app/services/super-admin/super-admin-fns";
// The license server joins this onto its configured portal origin, so it must be a single-rooted
// relative path. Reject protocol-relative ("//host", "/\\host") values that browsers can normalize
@@ -172,6 +174,32 @@ const BillingV2OverviewSchema = z.object({
selfServe: z.boolean()
});
+const BillingV2BreakdownScopeSchema = z.object({
+ orgId: z.string().describe("ID of the organization the units were created in."),
+ name: z.string().describe("Display name of the organization."),
+ isRoot: z.boolean().describe("Whether this is the root organization of the billing tree."),
+ count: z.number().describe("Metered units attributed to this organization."),
+ orgLevelCount: z.number().describe("Units created on the organization itself rather than in a project."),
+ projects: z
+ .object({
+ id: z.string().describe("ID of the project the units were created in."),
+ name: z.string().describe("Display name of the project."),
+ count: z.number().describe("Metered units created in this project.")
+ })
+ .array()
+ .describe("Per-project split of this organization's units; empty when the dimension has no project detail.")
+});
+
+const BillingV2UsageBreakdownSchema = z.object({
+ dimensionKey: z.string().describe("The metered dimension this breakdown explains."),
+ total: z.number().describe("Live total for the dimension, counted the same way the meter counts it."),
+ userCount: z.number().describe("Human seats in the metered set; 0 for dimensions that count no users."),
+ machineCount: z.number().describe("The part of the total the scopes partition."),
+ hasProjectDetail: z.boolean().describe("Whether units can be attributed to individual projects."),
+ unit: z.string().describe("Singular noun for what is counted, e.g. 'machine identity'."),
+ scopes: BillingV2BreakdownScopeSchema.array().describe("Organizations the total is drawn from, largest first.")
+});
+
const BillingV2PreviewLineSchema = z.object({
description: z.string(),
amount: z.number(),
@@ -225,7 +253,69 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
handler: async (req) => {
return server.services.licenseV2.getOverview({
orgId: req.params.organizationId,
- actor: buildActor(req.permission)
+ actor: buildActor(req.permission),
+ isInstanceAdmin: isSuperAdmin(req.auth)
+ });
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:organizationId/billing/v2/organizations",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ operationId: "listBillableOrganizations",
+ description:
+ "List the root organizations whose billing the caller may read. A self-hosted instance admin gets every organization on the instance, because one licence covers them all; everyone else gets only their own.",
+ params: z.object({ organizationId: z.string().trim().uuid() }),
+ response: {
+ 200: z.object({
+ organizations: z
+ .object({
+ id: z.string().describe("ID of the root organization."),
+ name: z.string().describe("Display name of the root organization.")
+ })
+ .array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
+ handler: async (req) => {
+ return server.services.licenseV2.getBillableOrganizations({
+ orgId: req.params.organizationId,
+ actor: buildActor(req.permission),
+ isInstanceAdmin: isSuperAdmin(req.auth)
+ });
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:organizationId/billing/v2/usage/:dimensionKey/breakdown",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ operationId: "getBillingUsageBreakdown",
+ description:
+ "Break one metered usage dimension down by the organizations and projects its units were created in.",
+ params: z.object({
+ organizationId: z.string().trim().uuid(),
+ dimensionKey: z.nativeEnum(BillingV2BreakdownDimension).describe("The metered dimension to break down.")
+ }),
+ response: {
+ 200: z.object({ breakdown: BillingV2UsageBreakdownSchema })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
+ handler: async (req) => {
+ return server.services.licenseV2.getUsageBreakdown({
+ orgId: req.params.organizationId,
+ dimensionKey: req.params.dimensionKey,
+ actor: buildActor(req.permission),
+ isInstanceAdmin: isSuperAdmin(req.auth)
});
}
});
@@ -267,7 +357,8 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
handler: async (req) => {
return server.services.licenseV2.getCatalog({
orgId: req.params.organizationId,
- actor: buildActor(req.permission)
+ actor: buildActor(req.permission),
+ isInstanceAdmin: isSuperAdmin(req.auth)
});
}
});
diff --git a/backend/src/ee/services/license-v2/license-v2-breakdown-dal.ts b/backend/src/ee/services/license-v2/license-v2-breakdown-dal.ts
new file mode 100644
index 0000000000..197cafd83e
--- /dev/null
+++ b/backend/src/ee/services/license-v2/license-v2-breakdown-dal.ts
@@ -0,0 +1,71 @@
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { orgTreeIds } from "@app/lib/knex";
+
+export type TLicenseV2BreakdownDALFactory = ReturnType<typeof licenseV2BreakdownDALFactory>;
+
+export type TScopeOrgRow = { id: string; name: string; isRoot: boolean };
+export type TRootOrgRow = { id: string; name: string };
+
+// An instance admin picks from this list, and a self-hosted instance is not a multi-tenant estate, so
+// the count is in the tens. Capped anyway so a pathological instance cannot return an unbounded list;
+// the picker filters client-side, so a cap that hides orgs would be invisible, hence the log.
+const ROOT_ORG_LIMIT = 500;
+export type TScopeProjectRow = { id: string; name: string; orgId: string };
+
+// Scope names for the usage breakdown. Billing is answered at the root org, so a billing admin reading
+// it is shown every sub-org and project the metered total was drawn from, including ones they are not a
+// member of: a total the customer is billed on that cannot be explained is worse than naming a project
+// they already pay for. Names only, deliberately, and the UI does not link them — nothing here exposes
+// a project's contents, and this DAL must not grow fields that would.
+export const licenseV2BreakdownDALFactory = (db: TDbClient) => {
+ const findOrgTreeNames = async (orgId: string): Promise<TScopeOrgRow[]> => {
+ try {
+ const rows = (await db
+ .replicaNode()(TableName.Organization)
+ .whereIn("id", orgTreeIds(db.replicaNode(), orgId))
+ .select("id", "name", "rootOrgId")) as { id: string; name: string; rootOrgId: string | null }[];
+
+ // A root org is the one carrying no rootOrgId; every sub-org points back at it.
+ return rows.map((row) => ({ id: row.id, name: row.name, isRoot: !row.rootOrgId }));
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find org tree names for usage breakdown" });
+ }
+ };
+
+ const findProjectNames = async (projectIds: string[]): Promise<TScopeProjectRow[]> => {
+ if (!projectIds.length) {
+ return [];
+ }
+
+ try {
+ // Soft-deleted projects are excluded from every meter, so one reaching here would be a bug in the
+ // count rather than a project to name; leaving it unnamed keeps the two consistent.
+ return (await db
+ .replicaNode()(TableName.Project)
+ .whereIn("id", projectIds)
+ .whereNull("deleteAfter")
+ .select("id", "name", "orgId")) as TScopeProjectRow[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find project names for usage breakdown" });
+ }
+ };
+
+ // Every root organization on the instance. Only ever reached for an instance admin on self-hosted,
+ // where one licence covers them all; the service is what enforces that.
+ const findAllRootOrgs = async (): Promise<TRootOrgRow[]> => {
+ try {
+ return (await db
+ .replicaNode()(TableName.Organization)
+ .whereNull("rootOrgId")
+ .orderBy("name", "asc")
+ .limit(ROOT_ORG_LIMIT)
+ .select("id", "name")) as TRootOrgRow[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find all root organizations for billing" });
+ }
+ };
+
+ return { findOrgTreeNames, findProjectNames, findAllRootOrgs };
+};
diff --git a/backend/src/ee/services/license-v2/license-v2-breakdown.test.ts b/backend/src/ee/services/license-v2/license-v2-breakdown.test.ts
new file mode 100644
index 0000000000..b21ffb41d6
--- /dev/null
+++ b/backend/src/ee/services/license-v2/license-v2-breakdown.test.ts
@@ -0,0 +1,15 @@
+import { METERED_DIMENSION_KEYS } from "@app/services/license-client/usage/usage-counters";
+
+import { BillingV2BreakdownDimension } from "./license-v2-types";
+
+describe("billing v2 usage breakdown dimensions", () => {
+ // The breakdown reads its counts from the meters, so a dimension it offers must be one the license
+ // server actually meters. Renaming a key in features.ts without updating the enum would otherwise ship
+ // a route that 400s on a dimension the billing page links to.
+ test("every breakdown dimension is a metered dimension", () => {
+ const metered = new Set(METERED_DIMENSION_KEYS);
+ const unknown = Object.values(BillingV2BreakdownDimension).filter((key) => !metered.has(key));
+
+ expect(unknown).toEqual([]);
+ });
+});
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 0e455c3121..1c3b0961e9 100644
--- a/backend/src/ee/services/license-v2/license-v2-service.ts
+++ b/backend/src/ee/services/license-v2/license-v2-service.ts
@@ -1,6 +1,6 @@
import { ForbiddenError } from "@casl/ability";
-import { OrganizationActionScope } from "@app/db/schemas";
+import { OrganizationActionScope, ProjectType } from "@app/db/schemas";
import { TEnvConfig } from "@app/lib/config/env";
import { BadRequestError, InternalServerError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
@@ -12,12 +12,18 @@ import {
TSubscriptionPreviewPayload,
TSubscriptionResponse
} from "@app/services/license-client/license-client-types";
+import { TUsageCounterDALFactory } from "@app/services/license-client/usage/usage-counter-dal";
import { TMeteredFeature } from "@app/services/license-client/usage/usage-counters";
import { TOrgDALFactory } from "@app/services/org/org-dal";
+import { TLicenseDALFactory } from "../license/license-dal";
import { OrgPermissionBillingActions, OrgPermissionSubjects } from "../permission/org-permission";
import { TPermissionServiceFactory } from "../permission/permission-service-types";
+import { TLicenseV2BreakdownDALFactory, TScopeOrgRow, TScopeProjectRow } from "./license-v2-breakdown-dal";
import {
+ BillingV2BreakdownDimension,
+ BillingV2BreakdownProject,
+ BillingV2BreakdownScope,
BillingV2CatalogProduct,
BillingV2CompareRow,
BillingV2Deprecation,
@@ -28,6 +34,7 @@ import {
BillingV2Plan,
BillingV2Preview,
BillingV2SubState,
+ BillingV2UsageBreakdown,
TAddBillingV2PaymentMethodDTO,
TBillingV2SubscriptionLifecycleDTO,
TBuyBillingV2ProductDTO,
@@ -36,6 +43,7 @@ import {
TCreateBillingV2PortalSessionDTO,
TGetBillingV2CatalogDTO,
TGetBillingV2OverviewDTO,
+ TGetBillingV2UsageBreakdownDTO,
TPreviewBillingV2ChangeDTO,
TRemoveBillingV2ProductDTO,
TStartBillingV2TrialDTO
@@ -45,6 +53,18 @@ type TLicenseV2ServiceFactoryDep = {
envConfig: Pick<TEnvConfig, "isCloud" | "SITE_URL">;
orgDAL: Pick<TOrgDALFactory, "findById">;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
+ // The usage breakdown reads its counts through the same DALs the meters report from, so it explains
+ // the billed figure rather than recomputing it a second way.
+ licenseDAL: Pick<TLicenseDALFactory, "countBillableOrgActors" | "getBillableIdentityOwnershipBreakdown">;
+ usageCounterDAL: Pick<
+ TUsageCounterDALFactory,
+ | "resolveRootOrgId"
+ | "countProjectIdentitiesByKindFor"
+ | "getProjectIdentityBreakdown"
+ | "getInternalCaOrgBreakdown"
+ | "getActiveCertificateOrgBreakdown"
+ >;
+ breakdownDAL: TLicenseV2BreakdownDALFactory;
// 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, ...).
@@ -325,7 +345,10 @@ export const licenseV2ServiceFactory = ({
orgDAL,
permissionService,
meteredFeatures,
- licenseClient
+ licenseClient,
+ licenseDAL,
+ usageCounterDAL,
+ breakdownDAL
}: TLicenseV2ServiceFactoryDep) => {
const countByDimensionKey = new Map(meteredFeatures.map(({ feature, count }) => [feature.key, count]));
@@ -394,7 +417,20 @@ export const licenseV2ServiceFactory = ({
// cloud has per-org self-serve subscriptions.
const isSelfHostedLicense = !envConfig.isCloud;
- const ensureBillingRead = async (orgId: string, actor: TGetBillingV2OverviewDTO["actor"]) => {
+ // A self-hosted licence covers every organization on the instance, so an instance admin is
+ // accountable for usage that spans all of them and may read any org's billing. Cloud bills per root
+ // org, so the exception never applies there. Everyone else is held to their own org by
+ // getOrgPermission, which refuses a token scoped elsewhere before any ability is evaluated.
+ const canReadAcrossOrgs = (isInstanceAdmin?: boolean) => Boolean(isInstanceAdmin) && !envConfig.isCloud;
+
+ const ensureBillingRead = async (
+ orgId: string,
+ actor: TGetBillingV2OverviewDTO["actor"],
+ isInstanceAdmin?: boolean
+ ) => {
+ if (orgId !== actor.orgId && canReadAcrossOrgs(isInstanceAdmin)) {
+ return;
+ }
const { permission } = await permissionService.getOrgPermission({
actorId: actor.id,
actor: actor.type,
@@ -651,8 +687,8 @@ export const licenseV2ServiceFactory = ({
return entitlements;
};
- const getOverview = async ({ orgId, actor }: TGetBillingV2OverviewDTO) => {
- await ensureBillingRead(orgId, actor);
+ const getOverview = async ({ orgId, actor, isInstanceAdmin }: TGetBillingV2OverviewDTO) => {
+ await ensureBillingRead(orgId, actor, isInstanceAdmin);
const organization = await orgDAL.findById(orgId);
if (!organization) {
@@ -786,6 +822,198 @@ export const licenseV2ServiceFactory = ({
return { overview };
};
+ // Assembles the org/project rows a breakdown query returned into the scope tree the UI renders. The
+ // root org is always present, even at zero, so the customer can see it holds nothing; a sub-org is
+ // listed only once it contributes, since an org tree can carry far more sub-orgs than a product uses.
+ const $buildScopes = (
+ orgs: TScopeOrgRow[],
+ projectsById: Map<string, TScopeProjectRow>,
+ rows: { orgId: string; projectId: string | null; count: number }[]
+ ): BillingV2BreakdownScope[] => {
+ const byOrg = new Map<string, { orgLevelCount: number; projects: BillingV2BreakdownProject[] }>();
+ orgs.forEach((org) => byOrg.set(org.id, { orgLevelCount: 0, projects: [] }));
+
+ rows.forEach((row) => {
+ const scope = byOrg.get(row.orgId);
+ // An identity whose org left the tree between the count and this read has nowhere to be shown.
+ // Dropping it would make the parts stop summing to the total, so attribute it to the root.
+ const target = scope ?? byOrg.get(orgs.find((org) => org.isRoot)?.id ?? "");
+ if (!target) {
+ return;
+ }
+ if (!row.projectId) {
+ target.orgLevelCount += row.count;
+ return;
+ }
+ const project = projectsById.get(row.projectId);
+ target.projects.push({
+ id: row.projectId,
+ // A project deleted between the count and this read still holds metered units, so it keeps its
+ // row rather than vanishing and leaving the parts short of the total.
+ name: project?.name ?? "Deleted project",
+ count: row.count
+ });
+ });
+
+ return orgs
+ .map((org) => {
+ const scope = byOrg.get(org.id) ?? { orgLevelCount: 0, projects: [] };
+ const projects = scope.projects.sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
+ const count = scope.orgLevelCount + projects.reduce((sum, project) => sum + project.count, 0);
+ return {
+ orgId: org.id,
+ name: org.name,
+ isRoot: org.isRoot,
+ count,
+ orgLevelCount: scope.orgLevelCount,
+ projects
+ };
+ })
+ .filter((scope) => scope.isRoot || scope.count > 0)
+ .sort((a, b) => Number(b.isRoot) - Number(a.isRoot) || b.count - a.count || a.name.localeCompare(b.name));
+ };
+
+ // Where one metered dimension's usage comes from. Every count here is read through the same DAL the
+ // usage meter reports from, so the breakdown explains the billed figure instead of offering a second
+ // opinion on it. It is a read: it never consults the plan, so a downgrade cannot change the answer.
+ const getUsageBreakdown = async ({ orgId, actor, dimensionKey, isInstanceAdmin }: TGetBillingV2UsageBreakdownDTO) => {
+ await ensureBillingRead(orgId, actor, isInstanceAdmin);
+
+ const organization = await orgDAL.findById(orgId);
+ if (!organization) {
+ throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
+ }
+
+ // ensureBillingRead already refuses a child org, so this normally resolves to orgId itself. It stays
+ // because every meter counts and reports at the root: reading the tree from anywhere else would
+ // answer with a subset of the figure the customer is billed on.
+ const rootOrgId = await usageCounterDAL.resolveRootOrgId(orgId);
+
+ const orgs = await breakdownDAL.findOrgTreeNames(rootOrgId);
+
+ // withProjectDetail false collapses each organization's rows into a single org total, so the scope
+ // list stops at the organization and no project is named. PAM is reported that way: the project a
+ // PAM identity happens to be created in is not a distinction the product draws.
+ const buildIdentityBreakdown = async (
+ counts: { users: number; identities: number },
+ rows: { orgId: string; projectId: string | null; count: number }[],
+ withProjectDetail: boolean
+ ): Promise<BillingV2UsageBreakdown> => {
+ const attributed = withProjectDetail
+ ? rows
+ : rows.map((row) => ({ orgId: row.orgId, projectId: null, count: row.count }));
+ const projectIds = withProjectDetail
+ ? [...new Set(rows.map((row) => row.projectId).filter((id): id is string => Boolean(id)))]
+ : [];
+ const projects = await breakdownDAL.findProjectNames(projectIds);
+ const projectsById = new Map(projects.map((project) => [project.id, project]));
+
+ return {
+ dimensionKey,
+ total: counts.users + counts.identities,
+ userCount: counts.users,
+ machineCount: counts.identities,
+ hasProjectDetail: withProjectDetail,
+ unit: "machine identity",
+ scopes: $buildScopes(orgs, projectsById, attributed)
+ };
+ };
+
+ const buildOrgOnlyBreakdown = (rows: { orgId: string; count: number }[], unit: string): BillingV2UsageBreakdown => {
+ const scopes = $buildScopes(
+ orgs,
+ new Map(),
+ rows.map((row) => ({ orgId: row.orgId, projectId: null, count: row.count }))
+ );
+ const total = scopes.reduce((sum, scope) => sum + scope.count, 0);
+ return { dimensionKey, total, userCount: 0, machineCount: total, hasProjectDetail: false, unit, scopes };
+ };
+
+ switch (dimensionKey) {
+ case BillingV2BreakdownDimension.Identities: {
+ const [counts, rows] = await Promise.all([
+ licenseDAL.countBillableOrgActors(rootOrgId),
+ licenseDAL.getBillableIdentityOwnershipBreakdown(rootOrgId)
+ ]);
+ return { breakdown: await buildIdentityBreakdown(counts, rows, true) };
+ }
+ case BillingV2BreakdownDimension.SecretIdentities:
+ case BillingV2BreakdownDimension.PamIdentities: {
+ const projectType =
+ dimensionKey === BillingV2BreakdownDimension.SecretIdentities ? ProjectType.SecretManager : ProjectType.PAM;
+ const [counts, rows] = await Promise.all([
+ usageCounterDAL.countProjectIdentitiesByKindFor(projectType, rootOrgId),
+ usageCounterDAL.getProjectIdentityBreakdown(projectType, rootOrgId)
+ ]);
+ return {
+ breakdown: await buildIdentityBreakdown(
+ counts,
+ rows,
+ dimensionKey === BillingV2BreakdownDimension.SecretIdentities
+ )
+ };
+ }
+ case BillingV2BreakdownDimension.UserIdentities: {
+ // Human seats only. Users hold no creation scope the way an identity does (a person can be a
+ // member of many orgs in the tree), so this dimension has a total and no scope tree.
+ const { users } = await licenseDAL.countBillableOrgActors(rootOrgId);
+ return {
+ breakdown: {
+ dimensionKey,
+ total: users,
+ userCount: users,
+ machineCount: 0,
+ hasProjectDetail: false,
+ unit: "user identity",
+ scopes: []
+ }
+ };
+ }
+ case BillingV2BreakdownDimension.InternalCas: {
+ // Deliberately unfiltered by CA status, exactly as the meter counts it: a disabled or
+ // pending-certificate CA is billed, so excluding it here would leave the parts short of the total.
+ const rows = await usageCounterDAL.getInternalCaOrgBreakdown(rootOrgId);
+ return { breakdown: buildOrgOnlyBreakdown(rows, "internal CA") };
+ }
+ case BillingV2BreakdownDimension.ActiveCerts:
+ case BillingV2BreakdownDimension.WildcardCerts: {
+ const rows = await usageCounterDAL.getActiveCertificateOrgBreakdown(rootOrgId);
+ const isWildcard = dimensionKey === BillingV2BreakdownDimension.WildcardCerts;
+ return {
+ breakdown: buildOrgOnlyBreakdown(
+ rows.map((row) => ({ orgId: row.orgId, count: isWildcard ? row.wildcard : row.count })),
+ isWildcard ? "wildcard certificate" : "active certificate"
+ )
+ };
+ }
+ default:
+ throw new BadRequestError({
+ message: `'${dimensionKey}' is not a usage dimension that can be broken down by scope.`
+ });
+ }
+ };
+
+ // Organizations whose billing this caller may read, for the billing page's organization picker. An
+ // instance admin on self-hosted gets every root org, because one licence covers them all; everyone
+ // else gets only their own, so the picker resolves to a single entry and the UI hides it. Returning a
+ // list either way keeps the "may I switch org" decision on the server rather than in the client.
+ const getBillableOrganizations = async ({ orgId, actor, isInstanceAdmin }: TGetBillingV2OverviewDTO) => {
+ await ensureBillingRead(orgId, actor, isInstanceAdmin);
+
+ if (!canReadAcrossOrgs(isInstanceAdmin)) {
+ const organization = await orgDAL.findById(orgId);
+ if (!organization) {
+ throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
+ }
+ const rootOrgId = await usageCounterDAL.resolveRootOrgId(orgId);
+ const self = await breakdownDAL.findOrgTreeNames(rootOrgId);
+ const root = self.find((org) => org.isRoot);
+ return { organizations: root ? [{ id: root.id, name: root.name }] : [] };
+ }
+
+ return { organizations: await breakdownDAL.findAllRootOrgs() };
+ };
+
// Force-refresh entitlements: ask the license server to recompute and drop the local cache, so the
// next overview read pulls the latest and re-populates the cache. Exposed as a manual refresh button.
const refreshEntitlements = async ({ orgId, actor }: TGetBillingV2OverviewDTO) => {
@@ -794,8 +1022,8 @@ export const licenseV2ServiceFactory = ({
return { success: true as const };
};
- const getCatalog = async ({ orgId, actor }: TGetBillingV2CatalogDTO) => {
- await ensureBillingRead(orgId, actor);
+ const getCatalog = async ({ orgId, actor, isInstanceAdmin }: TGetBillingV2CatalogDTO) => {
+ await ensureBillingRead(orgId, actor, isInstanceAdmin);
const catalog = await licenseClient.getCatalog(orgId);
if (!catalog) {
@@ -1030,6 +1258,8 @@ export const licenseV2ServiceFactory = ({
return {
getOverview,
+ getUsageBreakdown,
+ getBillableOrganizations,
refreshEntitlements,
getCatalog,
portalSession,
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 63b5a24ecf..4b9734a1cb 100644
--- a/backend/src/ee/services/license-v2/license-v2-types.ts
+++ b/backend/src/ee/services/license-v2/license-v2-types.ts
@@ -200,11 +200,15 @@ export type BillingV2Overview = {
export type TGetBillingV2OverviewDTO = {
orgId: string;
actor: OrgServiceActor;
+ // Lets a self-hosted instance admin read an organization their token is not scoped to, because one
+ // licence covers every org on the instance. Never honoured on cloud.
+ isInstanceAdmin?: boolean;
};
export type TGetBillingV2CatalogDTO = {
orgId: string;
actor: OrgServiceActor;
+ isInstanceAdmin?: boolean;
};
export type TCreateBillingV2PortalSessionDTO = {
@@ -304,3 +308,63 @@ export type TBillingV2SubscriptionLifecycleDTO = {
orgId: string;
actor: OrgServiceActor;
};
+
+// The metered dimensions the usage breakdown can explain. Values are license-server dimension keys and
+// must match the descriptors in services/license-client/features.ts; license-v2-breakdown.test.ts fails
+// when they drift.
+export enum BillingV2BreakdownDimension {
+ Identities = "identities",
+ UserIdentities = "user_identities",
+ SecretIdentities = "secret_identities",
+ PamIdentities = "pam_identities",
+ InternalCas = "internal_cas",
+ ActiveCerts = "active_certs",
+ WildcardCerts = "wildcard_certs"
+}
+
+// One project a metered dimension's units were created in. Named even when the reader has no access to
+// the project, so a billed total is always explainable; the UI renders the name as plain text.
+export type BillingV2BreakdownProject = {
+ id: string;
+ name: string;
+ count: number;
+};
+
+// One organization in the billing tree (the root org or one of its sub-orgs) and the metered units
+// attributed to it. orgLevelCount plus every project count equals count.
+export type BillingV2BreakdownScope = {
+ orgId: string;
+ name: string;
+ isRoot: boolean;
+ count: number;
+ // Units created on the org itself rather than inside one of its projects. Always 0 for a dimension
+ // with no project attribution (see hasProjectDetail).
+ orgLevelCount: number;
+ projects: BillingV2BreakdownProject[];
+};
+
+// Where one metered dimension's usage comes from, counted live from the same predicates that feed the
+// meter. The overview's `used` is the figure the customer is billed on and is reported to the license
+// server asynchronously, so the two can differ by a reporting cycle.
+export type BillingV2UsageBreakdown = {
+ dimensionKey: string;
+ total: number;
+ // Humans in the metered set. The identity meters bill users and machine identities together; the PKI
+ // meters count neither, so this is 0 for them.
+ userCount: number;
+ // The part of the total the scopes partition.
+ machineCount: number;
+ // false for the PKI dimensions: the meter dedupes certificates by name across the whole tree, so a
+ // certificate cannot be attributed to one project without the parts summing past the billed total.
+ hasProjectDetail: boolean;
+ // Singular noun for what is counted ("machine identity", "internal CA"), for the UI's labels.
+ unit: string;
+ scopes: BillingV2BreakdownScope[];
+};
+
+export type TGetBillingV2UsageBreakdownDTO = {
+ orgId: string;
+ actor: OrgServiceActor;
+ dimensionKey: string;
+ isInstanceAdmin?: boolean;
+};
diff --git a/backend/src/ee/services/license/license-dal.ts b/backend/src/ee/services/license/license-dal.ts
index 33d273332e..ee407eecf0 100644
--- a/backend/src/ee/services/license/license-dal.ts
+++ b/backend/src/ee/services/license/license-dal.ts
@@ -12,6 +12,154 @@ export type TLicenseDALFactory = ReturnType<typeof licenseDALFactory>;
// direct or inherited through a group.
const COUNTED_PROJECT_TYPES = [ProjectType.SecretManager, ProjectType.KMS];
+// One machine identity's billable seat, resolved to where the identity was created: the project that
+// owns it, or the org itself when it is org-owned (identities.projectId is null).
+export type TBillableIdentityOwnershipRow = { orgId: string; projectId: string | null; count: number };
+
+// The scope CTEs every billable-actor query starts from. Extracted so the seat counter and the usage
+// breakdown resolve "which actors are in scope" from one definition — a breakdown that disagreed with
+// the meter would show the customer a total that isn't the one they are billed on.
+// Attaches: orgs, counted_projects, all_projects, org_users, org_identities.
+const $withBillableScopes = (knex: Knex, orgId: string | null) => {
+ const orgIds = orgId
+ ? knex
+ .select("id")
+ .from(TableName.Organization)
+ .where("id", orgId)
+ .union((qb) => void qb.select("id").from(TableName.Organization).where("rootOrgId", orgId), true)
+ : knex.select("id").from(TableName.Organization);
+
+ return (
+ knex
+ .with("orgs", orgIds)
+ // Projects whose members count toward a seat (Secret Manager + KMS), excluding soft-deleted ones.
+ .with("counted_projects", (qb) => {
+ void qb
+ .from(TableName.Project)
+ .whereNull("deleteAfter")
+ .whereIn("type", COUNTED_PROJECT_TYPES)
+ .whereIn("orgId", knex.select("id").from("orgs"))
+ .select("id");
+ })
+ // Every live project in scope, used to decide whether an actor is projectless.
+ .with("all_projects", (qb) => {
+ void qb
+ .from(TableName.Project)
+ .whereNull("deleteAfter")
+ .whereIn("orgId", knex.select("id").from("orgs"))
+ .select("id");
+ })
+ // Real (accepted, non-ghost) org-member users in scope, deduped across orgs.
+ .with("org_users", (qb) => {
+ void qb
+ .from({ m: TableName.Membership })
+ .join({ u: TableName.Users }, "u.id", "m.actorUserId")
+ .where("m.scope", AccessScope.Organization)
+ .whereIn("m.scopeOrgId", knex.select("id").from("orgs"))
+ .whereNotNull("m.actorUserId")
+ .where("u.isGhost", false)
+ .where("u.isAccepted", true)
+ .distinct({ id: "m.actorUserId" });
+ })
+ // Identities that belong to an org in scope, deduped.
+ .with("org_identities", (qb) => {
+ void qb.from(TableName.Identity).whereIn("orgId", knex.select("id").from("orgs")).distinct("id");
+ })
+ );
+};
+
+// Actors present in at least one counted (SM/KMS) project, direct or via a group. UNION dedupes
+// across the four sources, and kind ('u'/'i') lets the caller split by actor type.
+const $countedMembersCte = (knex: Knex) => (qb: Knex.QueryBuilder) => {
+ void qb.distinct("kind", "entityId").from(
+ knex
+ .from({ m: TableName.Membership })
+ .where("m.scope", AccessScope.Project)
+ .whereNotNull("m.actorUserId")
+ .whereIn("m.scopeProjectId", knex.select("id").from("counted_projects"))
+ .whereIn("m.actorUserId", knex.select("id").from("org_users"))
+ .select(knex.raw("'u' as kind"), { entityId: "m.actorUserId" })
+ .union(
+ [
+ (u) => {
+ void u
+ .from({ m: TableName.Membership })
+ .where("m.scope", AccessScope.Project)
+ .whereNotNull("m.actorIdentityId")
+ .whereIn("m.scopeProjectId", knex.select("id").from("counted_projects"))
+ .whereIn("m.actorIdentityId", knex.select("id").from("org_identities"))
+ .select(knex.raw("'i' as kind"), { entityId: "m.actorIdentityId" });
+ },
+ (u) => {
+ void u
+ .from({ ugm: TableName.UserGroupMembership })
+ .join({ mg: TableName.Membership }, "mg.actorGroupId", "ugm.groupId")
+ .where("mg.scope", AccessScope.Project)
+ .where("ugm.isPending", false)
+ .whereIn("mg.scopeProjectId", knex.select("id").from("counted_projects"))
+ .whereIn("ugm.userId", knex.select("id").from("org_users"))
+ .select(knex.raw("'u' as kind"), { entityId: "ugm.userId" });
+ },
+ (u) => {
+ void u
+ .from({ igm: TableName.IdentityGroupMembership })
+ .join({ mg: TableName.Membership }, "mg.actorGroupId", "igm.groupId")
+ .where("mg.scope", AccessScope.Project)
+ .whereIn("mg.scopeProjectId", knex.select("id").from("counted_projects"))
+ .whereIn("igm.identityId", knex.select("id").from("org_identities"))
+ .select(knex.raw("'i' as kind"), { entityId: "igm.identityId" });
+ }
+ ],
+ true
+ )
+ .as("cm")
+ );
+};
+
+// Org users with no project membership at all (direct or via a group) count as present in the org.
+const $projectlessUsersCte = (knex: Knex) => (qb: Knex.QueryBuilder) => {
+ void qb
+ .from({ ou: "org_users" })
+ .whereNotExists((w) => {
+ void w
+ .from({ m: TableName.Membership })
+ .where("m.scope", AccessScope.Project)
+ .whereRaw('m."actorUserId" = ou.id')
+ .whereIn("m.scopeProjectId", knex.select("id").from("all_projects"));
+ })
+ .whereNotExists((w) => {
+ void w
+ .from({ ugm: TableName.UserGroupMembership })
+ .join({ mg: TableName.Membership }, "mg.actorGroupId", "ugm.groupId")
+ .where("mg.scope", AccessScope.Project)
+ .where("ugm.isPending", false)
+ .whereRaw('ugm."userId" = ou.id')
+ .whereIn("mg.scopeProjectId", knex.select("id").from("all_projects"));
+ })
+ .select("ou.id");
+};
+
+const $projectlessIdentitiesCte = (knex: Knex) => (qb: Knex.QueryBuilder) => {
+ void qb
+ .from({ oi: "org_identities" })
+ .whereNotExists((w) => {
+ void w
+ .from({ m: TableName.Membership })
+ .where("m.scope", AccessScope.Project)
+ .whereRaw('m."actorIdentityId" = oi.id')
+ .whereIn("m.scopeProjectId", knex.select("id").from("all_projects"));
+ })
+ .whereNotExists((w) => {
+ void w
+ .from({ igm: TableName.IdentityGroupMembership })
+ .join({ mg: TableName.Membership }, "mg.actorGroupId", "igm.groupId")
+ .where("mg.scope", AccessScope.Project)
+ .whereRaw('igm."identityId" = oi.id')
+ .whereIn("mg.scopeProjectId", knex.select("id").from("all_projects"));
+ })
+ .select("oi.id");
+};
+
export const licenseDALFactory = (db: TDbClient) => {
const countBillableOrgActors = async (
orgId: string | null,
@@ -20,138 +168,10 @@ export const licenseDALFactory = (db: TDbClient) => {
try {
const knex = tx || db.replicaNode();
- const orgIds = orgId
- ? knex
- .select("id")
- .from(TableName.Organization)
- .where("id", orgId)
- .union((qb) => void qb.select("id").from(TableName.Organization).where("rootOrgId", orgId), true)
- : knex.select("id").from(TableName.Organization);
-
- const row = (await knex
- .with("orgs", orgIds)
- // Projects whose members count toward a seat (Secret Manager + KMS), excluding soft-deleted ones.
- .with("counted_projects", (qb) => {
- void qb
- .from(TableName.Project)
- .whereNull("deleteAfter")
- .whereIn("type", COUNTED_PROJECT_TYPES)
- .whereIn("orgId", knex.select("id").from("orgs"))
- .select("id");
- })
- // Every live project in scope, used to decide whether an actor is projectless.
- .with("all_projects", (qb) => {
- void qb
- .from(TableName.Project)
- .whereNull("deleteAfter")
- .whereIn("orgId", knex.select("id").from("orgs"))
- .select("id");
- })
- // Real (accepted, non-ghost) org-member users in scope, deduped across orgs.
- .with("org_users", (qb) => {
- void qb
- .from({ m: TableName.Membership })
- .join({ u: TableName.Users }, "u.id", "m.actorUserId")
- .where("m.scope", AccessScope.Organization)
- .whereIn("m.scopeOrgId", knex.select("id").from("orgs"))
- .whereNotNull("m.actorUserId")
- .where("u.isGhost", false)
- .where("u.isAccepted", true)
- .distinct({ id: "m.actorUserId" });
- })
- // Identities that belong to an org in scope, deduped.
- .with("org_identities", (qb) => {
- void qb.from(TableName.Identity).whereIn("orgId", knex.select("id").from("orgs")).distinct("id");
- })
- // Actors present in at least one counted (SM/KMS) project, direct or via a group. UNION dedupes
- // across the four sources, and kind ('u'/'i') lets the final select split by actor type.
- .with("counted_members", (qb) => {
- void qb.distinct("kind", "entityId").from(
- knex
- .from({ m: TableName.Membership })
- .where("m.scope", AccessScope.Project)
- .whereNotNull("m.actorUserId")
- .whereIn("m.scopeProjectId", knex.select("id").from("counted_projects"))
- .whereIn("m.actorUserId", knex.select("id").from("org_users"))
- .select(knex.raw("'u' as kind"), { entityId: "m.actorUserId" })
- .union(
- [
- (u) => {
- void u
- .from({ m: TableName.Membership })
- .where("m.scope", AccessScope.Project)
- .whereNotNull("m.actorIdentityId")
- .whereIn("m.scopeProjectId", knex.select("id").from("counted_projects"))
- .whereIn("m.actorIdentityId", knex.select("id").from("org_identities"))
- .select(knex.raw("'i' as kind"), { entityId: "m.actorIdentityId" });
- },
- (u) => {
- void u
- .from({ ugm: TableName.UserGroupMembership })
- .join({ mg: TableName.Membership }, "mg.actorGroupId", "ugm.groupId")
- .where("mg.scope", AccessScope.Project)
- .where("ugm.isPending", false)
- .whereIn("mg.scopeProjectId", knex.select("id").from("counted_projects"))
- .whereIn("ugm.userId", knex.select("id").from("org_users"))
- .select(knex.raw("'u' as kind"), { entityId: "ugm.userId" });
- },
- (u) => {
- void u
- .from({ igm: TableName.IdentityGroupMembership })
- .join({ mg: TableName.Membership }, "mg.actorGroupId", "igm.groupId")
- .where("mg.scope", AccessScope.Project)
- .whereIn("mg.scopeProjectId", knex.select("id").from("counted_projects"))
- .whereIn("igm.identityId", knex.select("id").from("org_identities"))
- .select(knex.raw("'i' as kind"), { entityId: "igm.identityId" });
- }
- ],
- true
- )
- .as("cm")
- );
- })
- // Org users with no project membership at all (direct or via a group) count as present in the org.
- .with("projectless_users", (qb) => {
- void qb
- .from({ ou: "org_users" })
- .whereNotExists((w) => {
- void w
- .from({ m: TableName.Membership })
- .where("m.scope", AccessScope.Project)
- .whereRaw('m."actorUserId" = ou.id')
- .whereIn("m.scopeProjectId", knex.select("id").from("all_projects"));
- })
- .whereNotExists((w) => {
- void w
- .from({ ugm: TableName.UserGroupMembership })
- .join({ mg: TableName.Membership }, "mg.actorGroupId", "ugm.groupId")
- .where("mg.scope", AccessScope.Project)
- .where("ugm.isPending", false)
- .whereRaw('ugm."userId" = ou.id')
- .whereIn("mg.scopeProjectId", knex.select("id").from("all_projects"));
- })
- .select("ou.id");
- })
- .with("projectless_identities", (qb) => {
- void qb
- .from({ oi: "org_identities" })
- .whereNotExists((w) => {
- void w
- .from({ m: TableName.Membership })
- .where("m.scope", AccessScope.Project)
- .whereRaw('m."actorIdentityId" = oi.id')
- .whereIn("m.scopeProjectId", knex.select("id").from("all_projects"));
- })
- .whereNotExists((w) => {
- void w
- .from({ igm: TableName.IdentityGroupMembership })
- .join({ mg: TableName.Membership }, "mg.actorGroupId", "igm.groupId")
- .where("mg.scope", AccessScope.Project)
- .whereRaw('igm."identityId" = oi.id')
- .whereIn("mg.scopeProjectId", knex.select("id").from("all_projects"));
- })
- .select("oi.id");
- })
+ const row = (await $withBillableScopes(knex, orgId)
+ .with("counted_members", $countedMembersCte(knex))
+ .with("projectless_users", $projectlessUsersCte(knex))
+ .with("projectless_identities", $projectlessIdentitiesCte(knex))
.select(
knex.raw("(select count(*) from counted_members where kind = 'u') as counted_users"),
knex.raw("(select count(*) from counted_members where kind = 'i') as counted_identities"),
@@ -176,6 +196,39 @@ export const licenseDALFactory = (db: TDbClient) => {
}
};
+ // The same seats countBillableOrgActors bills for, attributed to where each machine identity was
+ // created. Seats are held by membership (an identity can sit in many projects), so grouping on
+ // membership would count one identity several times; identities.projectId is a single column, so
+ // grouping on ownership partitions the billed total exactly once across the tree.
+ const getBillableIdentityOwnershipBreakdown = async (
+ orgId: string,
+ tx?: Knex
+ ): Promise<TBillableIdentityOwnershipRow[]> => {
+ try {
+ const knex = tx || db.replicaNode();
+
+ const rows = (await $withBillableScopes(knex, orgId)
+ .with("counted_members", $countedMembersCte(knex))
+ .with("projectless_identities", $projectlessIdentitiesCte(knex))
+ .with("billable_identities", (qb) => {
+ void qb
+ .select("entityId as id")
+ .from("counted_members")
+ .where("kind", "i")
+ .union((u) => void u.select("id").from("projectless_identities"), true);
+ })
+ .from({ i: TableName.Identity })
+ .whereIn("i.id", knex.select("id").from("billable_identities"))
+ .groupBy("i.orgId", "i.projectId")
+ .select({ orgId: "i.orgId", projectId: "i.projectId" })
+ .count("i.id as count")) as { orgId: string; projectId: string | null; count: string | number }[];
+
+ return rows.map((row) => ({ orgId: row.orgId, projectId: row.projectId, count: Number(row.count) }));
+ } catch (error) {
+ throw new DatabaseError({ error, name: "GetBillableIdentityOwnershipBreakdown" });
+ }
+ };
+
const countOfOrgMembers = async (orgId: string | null, tx?: Knex) => {
const { users } = await countBillableOrgActors(orgId, tx);
return users;
@@ -186,5 +239,10 @@ export const licenseDALFactory = (db: TDbClient) => {
return users + identities;
};
- return { countBillableOrgActors, countOfOrgMembers, countOrgUsersAndIdentities };
+ return {
+ countBillableOrgActors,
+ getBillableIdentityOwnershipBreakdown,
+ countOfOrgMembers,
+ countOrgUsersAndIdentities
+ };
};
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 39a2e89949..f08353278e 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -93,6 +93,7 @@ import { licenseDALFactory } from "@app/ee/services/license/license-dal";
import { getLicenseKeyConfig } from "@app/ee/services/license/license-fns";
import { licenseServiceFactory } from "@app/ee/services/license/license-service";
import { LicenseType } from "@app/ee/services/license/license-types";
+import { licenseV2BreakdownDALFactory } from "@app/ee/services/license-v2/license-v2-breakdown-dal";
import { licenseV2ServiceFactory } from "@app/ee/services/license-v2/license-v2-service";
import { oidcConfigDALFactory } from "@app/ee/services/oidc/oidc-config-dal";
import { oidcConfigServiceFactory } from "@app/ee/services/oidc/oidc-config-service";
@@ -843,6 +844,7 @@ export const registerRoutes = async (
// Usage metering: counts the metered features and reports them to the License Server. Inert when no
// license server is configured (emitter no-ops / worker no-ops without a reporter).
const usageCounterDAL = usageCounterDALFactory(db);
+ const licenseV2BreakdownDAL = licenseV2BreakdownDALFactory(db);
const meteredFeatures = buildMeteredFeatures({ licenseDAL, usageCounterDAL, isCloud: envConfig.isCloud });
meteredFeatures.forEach(({ feature, count }) => licenseClient.registerCounter(feature, count));
const usageReporter = isOfflineLicense ? null : buildUsageReporter(envConfig);
@@ -870,7 +872,10 @@ export const registerRoutes = async (
orgDAL,
permissionService,
meteredFeatures,
- licenseClient
+ licenseClient,
+ licenseDAL,
+ usageCounterDAL,
+ breakdownDAL: licenseV2BreakdownDAL
});
// Project events SSE service (for clients to subscribe to secret mutation events)
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 64a23caa24..602acc3aa2 100644
--- a/backend/src/services/license-client/usage/usage-counter-dal.ts
+++ b/backend/src/services/license-client/usage/usage-counter-dal.ts
@@ -8,6 +8,18 @@ import { CertStatus } from "@app/services/certificate/certificate-types";
export type TUsageCounterDALFactory = ReturnType<typeof usageCounterDALFactory>;
+// One metered machine identity resolved to where it was created: the project that owns it, or the org
+// itself (projectId null) when it is org-owned.
+export type TIdentityOwnershipRow = { orgId: string; projectId: string | null; count: number };
+
+// A metered PKI unit count for one org in the tree. Certificates carry no per-project attribution here
+// because the meter dedupes by quotaKey across the whole tree (see getActiveCertificateOrgBreakdown).
+export type TOrgUnitCountRow = { orgId: string; count: number };
+
+// Active certificates for one org, with the wildcard subset that active_certs and wildcard_certs both
+// read, so the two meters can never disagree about which certificates are live.
+export type TCertificateOrgUnitRow = TOrgUnitCountRow & { wildcard: number };
+
const toCount = (row: unknown): number => Number((row as { count?: string | number } | undefined)?.count ?? 0);
// Live counts for the project-scoped metered features, summed across the whole org tree and excluding
@@ -134,7 +146,10 @@ export const usageCounterDALFactory = (db: TDbClient) => {
}
};
- const countProjectIdentities = async (projectType: ProjectType, orgId?: string): Promise<number> => {
+ // The distinct actor set behind the project-scoped identity meters, as ('u' | 'i', entityId) rows.
+ // Shared by the meter and the usage breakdown so a breakdown can never disagree with the number the
+ // customer is billed on.
+ const $projectIdentityEntities = (projectType: ProjectType, orgId?: string) => {
const scopedOrgIds = () => {
const qb = db.replicaNode()(TableName.Organization).select(`${TableName.Organization}.id`);
if (orgId) {
@@ -229,13 +244,61 @@ export const usageCounterDALFactory = (db: TDbClient) => {
],
true
);
+ return distinctEntities;
+ };
+
+ const countProjectIdentities = async (projectType: ProjectType, orgId?: string): Promise<number> => {
// .as() on a union builder is typed as any, so cast the awaited row before counting.
- const row = (await db.replicaNode().count("* as count").from(distinctEntities.as("project_identities")).first()) as
- | { count?: string | number }
- | undefined;
+ const row = (await db
+ .replicaNode()
+ .count("* as count")
+ .from($projectIdentityEntities(projectType, orgId).as("project_identities"))
+ .first()) as { count?: string | number } | undefined;
return toCount(row);
};
+ // The same actors countProjectIdentities meters, split by actor type. The meter bills one number for
+ // both; the breakdown sheet shows the human/machine split behind it.
+ const countProjectIdentitiesByKind = async (
+ projectType: ProjectType,
+ orgId?: string
+ ): Promise<{ users: number; identities: number }> => {
+ const rows = (await db
+ .replicaNode()
+ .select("kind")
+ .count("* as count")
+ .from($projectIdentityEntities(projectType, orgId).as("project_identities"))
+ .groupBy("kind")) as { kind: string; count: string | number }[];
+
+ const byKind = (kind: string) => Number(rows.find((row) => row.kind === kind)?.count ?? 0);
+ return { users: byKind("u"), identities: byKind("i") };
+ };
+
+ // Machine identities from the same metered set, attributed to where each was created: the project
+ // that owns it, or the org itself when org-owned. Seats are held by membership, which is
+ // many-to-many, so grouping on membership would count one identity once per project it sits in;
+ // identities.projectId is a single column and partitions the metered total exactly once.
+ const getProjectIdentityOwnershipBreakdown = async (
+ projectType: ProjectType,
+ orgId: string
+ ): Promise<TIdentityOwnershipRow[]> => {
+ const rows = (await db
+ .replicaNode()({ i: TableName.Identity })
+ .whereIn(
+ "i.id",
+ db
+ .replicaNode()
+ .select("entityId")
+ .from($projectIdentityEntities(projectType, orgId).as("project_identities"))
+ .where("kind", "i")
+ )
+ .groupBy("i.orgId", "i.projectId")
+ .select({ orgId: "i.orgId", projectId: "i.projectId" })
+ .count("i.id as count")) as { orgId: string; projectId: string | null; count: string | number }[];
+
+ return rows.map((row) => ({ orgId: row.orgId, projectId: row.projectId, count: Number(row.count) }));
+ };
+
const countSecretManagementIdentities = async (orgId?: string): Promise<number> => {
try {
return await countProjectIdentities(ProjectType.SecretManager, orgId);
@@ -252,6 +315,92 @@ export const usageCounterDALFactory = (db: TDbClient) => {
}
};
+ const countProjectIdentitiesByKindFor = async (projectType: ProjectType, orgId: string) => {
+ try {
+ return await countProjectIdentitiesByKind(projectType, orgId);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Count project identities by kind for usage breakdown" });
+ }
+ };
+
+ const getProjectIdentityBreakdown = async (projectType: ProjectType, orgId: string) => {
+ try {
+ return await getProjectIdentityOwnershipBreakdown(projectType, orgId);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Get project identity breakdown for usage" });
+ }
+ };
+
+ // Mirrors countInternalCas exactly, including its lack of a status filter: a disabled or
+ // pending-certificate CA is metered, so the breakdown counts it too or it would not add up to the
+ // number the customer is billed on.
+ const getInternalCaOrgBreakdown = async (orgId: string): Promise<TOrgUnitCountRow[]> => {
+ try {
+ const rows = (await db
+ .replicaNode()(TableName.CertificateAuthority)
+ .join(
+ TableName.InternalCertificateAuthority,
+ `${TableName.CertificateAuthority}.id`,
+ `${TableName.InternalCertificateAuthority}.caId`
+ )
+ .join(TableName.Project, `${TableName.CertificateAuthority}.projectId`, `${TableName.Project}.id`)
+ .whereNull(`${TableName.Project}.deleteAfter`)
+ .whereIn(`${TableName.Project}.orgId`, orgTreeIds(db.replicaNode(), orgId))
+ .groupBy(`${TableName.Project}.orgId`)
+ .select({ orgId: `${TableName.Project}.orgId` })
+ .count(`${TableName.CertificateAuthority}.id as count`)) as {
+ orgId: string;
+ count: string | number;
+ }[];
+
+ return rows.map((row) => ({ orgId: row.orgId, count: Number(row.count) }));
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Get internal CA breakdown for usage" });
+ }
+ };
+
+ // The meter counts DISTINCT quotaKey across the whole org tree, so one certificate name issued in two
+ // orgs is a single billable unit. Splitting that by org therefore needs each quotaKey attributed to
+ // exactly one of them, else the parts sum past the billed total. The earliest issuance wins (org id
+ // breaks a tie) so the attribution is stable between reads rather than shifting with row order.
+ const getActiveCertificateOrgBreakdown = async (orgId: string): Promise<TCertificateOrgUnitRow[]> => {
+ try {
+ const attributed = $activeQuotaCertificates(orgId)
+ .whereNotNull(`${TableName.Certificate}.quotaKey`)
+ .distinctOn(`${TableName.Certificate}.quotaKey`)
+ .orderBy([
+ { column: `${TableName.Certificate}.quotaKey` },
+ { column: `${TableName.Certificate}.notBefore`, order: "asc" },
+ { column: `${TableName.Project}.orgId`, order: "asc" }
+ ])
+ .select({
+ quotaKey: `${TableName.Certificate}.quotaKey`,
+ orgId: `${TableName.Project}.orgId`,
+ hasWildcard: `${TableName.Certificate}.hasWildcard`
+ });
+
+ const rows = (await db
+ .replicaNode()
+ .from(attributed.as("attributed"))
+ .groupBy("attributed.orgId")
+ .select({ orgId: "attributed.orgId" })
+ .count("* as total")
+ .select(db.raw(`COUNT(*) FILTER (WHERE attributed."hasWildcard") as "wildcard"`))) as {
+ orgId: string;
+ total: string | number;
+ wildcard: string | number;
+ }[];
+
+ return rows.map((row) => ({
+ orgId: row.orgId,
+ count: Number(row.total),
+ wildcard: Number(row.wildcard)
+ }));
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Get active certificate breakdown for usage" });
+ }
+ };
+
return {
countInternalCas,
resolveRootOrgId,
@@ -259,6 +408,10 @@ export const usageCounterDALFactory = (db: TDbClient) => {
isCertificateQuotaKeyActiveInOrg,
countPamResources,
countSecretManagementIdentities,
- countPamIdentities
+ countPamIdentities,
+ countProjectIdentitiesByKindFor,
+ getProjectIdentityBreakdown,
+ getInternalCaOrgBreakdown,
+ getActiveCertificateOrgBreakdown
};
};
diff --git a/backend/src/services/license-client/usage/usage-counters.ts b/backend/src/services/license-client/usage/usage-counters.ts
index 4043041b34..5049f0c671 100644
--- a/backend/src/services/license-client/usage/usage-counters.ts
+++ b/backend/src/services/license-client/usage/usage-counters.ts
@@ -35,7 +35,14 @@ export const METERED_DIMENSION_KEYS: string[] = [
type TBuildMeteredFeaturesDep = {
licenseDAL: Pick<TLicenseDALFactory, "countOrgUsersAndIdentities" | "countOfOrgMembers">;
- usageCounterDAL: TUsageCounterDALFactory;
+ usageCounterDAL: Pick<
+ TUsageCounterDALFactory,
+ | "countInternalCas"
+ | "resolveRootOrgId"
+ | "countActiveCertificateQuotaKeysByOrg"
+ | "countSecretManagementIdentities"
+ | "countPamIdentities"
+ >;
// Cloud meters per org; self-hosted meters the whole instance (a single license covers the DB).
isCloud: boolean;
};
diff --git a/frontend/src/hooks/api/billingV2/index.tsx b/frontend/src/hooks/api/billingV2/index.tsx
index 001eac6fc7..3f68b2808d 100644
--- a/frontend/src/hooks/api/billingV2/index.tsx
+++ b/frontend/src/hooks/api/billingV2/index.tsx
@@ -11,8 +11,16 @@ export {
useResumeBillingV2Subscription,
useStartBillingV2Trial
} from "./mutations";
-export { billingV2Keys, useGetBillingV2Catalog, useGetBillingV2Overview } from "./queries";
+export {
+ billingV2Keys,
+ useGetBillingV2Catalog,
+ useGetBillingV2Organizations,
+ useGetBillingV2Overview,
+ useGetBillingV2UsageBreakdown
+} from "./queries";
export type {
+ BillingV2BreakdownProject,
+ BillingV2BreakdownScope,
BillingV2Cadence,
BillingV2CatalogProduct,
BillingV2CommitmentChange,
@@ -22,11 +30,14 @@ export type {
BillingV2Entitlement,
BillingV2EntitlementDim,
BillingV2Invoice,
+ BillingV2Organization,
BillingV2Overview,
BillingV2PaymentMethod,
BillingV2Plan,
BillingV2Preview,
BillingV2PreviewLine,
BillingV2SubState,
- BillingV2TrialResult
+ BillingV2TrialResult,
+ BillingV2UsageBreakdown
} from "./types";
+export { BillingV2BreakdownDimension } from "./types";
diff --git a/frontend/src/hooks/api/billingV2/queries.tsx b/frontend/src/hooks/api/billingV2/queries.tsx
index 9f54cfe5eb..834a9bb4f8 100644
--- a/frontend/src/hooks/api/billingV2/queries.tsx
+++ b/frontend/src/hooks/api/billingV2/queries.tsx
@@ -2,11 +2,19 @@ import { useQuery } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
-import { BillingV2CatalogProduct, BillingV2Overview } from "./types";
+import {
+ BillingV2CatalogProduct,
+ BillingV2Organization,
+ BillingV2Overview,
+ BillingV2UsageBreakdown
+} from "./types";
export const billingV2Keys = {
overview: (orgId: string) => [{ orgId }, "billing-v2-overview"] as const,
- catalog: (orgId: string) => [{ orgId }, "billing-v2-catalog"] as const
+ catalog: (orgId: string) => [{ orgId }, "billing-v2-catalog"] as const,
+ usageBreakdown: (orgId: string, dimensionKey: string) =>
+ [{ orgId, dimensionKey }, "billing-v2-usage-breakdown"] as const,
+ organizations: (orgId: string) => [{ orgId }, "billing-v2-organizations"] as const
};
export const useGetBillingV2Overview = (orgId: string) => {
@@ -40,3 +48,40 @@ export const useGetBillingV2Catalog = (orgId: string) => {
enabled: Boolean(orgId)
});
};
+
+// Counted live rather than served from the billing snapshot, so it stays behind the sheet that opens it
+// rather than loading with the page: the identity dimensions count over the whole org tree.
+export const useGetBillingV2UsageBreakdown = (orgId: string, dimensionKey: string | null) => {
+ return useQuery({
+ queryKey: billingV2Keys.usageBreakdown(orgId, dimensionKey ?? ""),
+ queryFn: async () => {
+ const {
+ data: { breakdown }
+ } = await apiRequest.get<{ breakdown: BillingV2UsageBreakdown }>(
+ `/api/v1/organizations/${orgId}/billing/v2/usage/${dimensionKey}/breakdown`
+ );
+
+ return breakdown;
+ },
+ enabled: Boolean(orgId) && Boolean(dimensionKey)
+ });
+};
+
+// Which organizations the billing page may be pointed at. The server decides: an instance admin on
+// self-hosted gets every root org, everyone else gets only their own. Keeping that decision server-side
+// means the client never has to know who is an instance admin.
+export const useGetBillingV2Organizations = (orgId: string) => {
+ return useQuery({
+ queryKey: billingV2Keys.organizations(orgId),
+ queryFn: async () => {
+ const {
+ data: { organizations }
+ } = await apiRequest.get<{ organizations: BillingV2Organization[] }>(
+ `/api/v1/organizations/${orgId}/billing/v2/organizations`
+ );
+
+ return organizations;
+ },
+ enabled: Boolean(orgId)
+ });
+};
diff --git a/frontend/src/hooks/api/billingV2/types.ts b/frontend/src/hooks/api/billingV2/types.ts
index 5437021bf7..3b5faae893 100644
--- a/frontend/src/hooks/api/billingV2/types.ts
+++ b/frontend/src/hooks/api/billingV2/types.ts
@@ -310,3 +310,53 @@ export type BillingV2TrialCancelResult = {
export type TBillingV2LifecycleDTO = {
orgId: string;
};
+
+// The metered dimensions the usage breakdown can explain. Values are the license-server dimension keys.
+export enum BillingV2BreakdownDimension {
+ Identities = "identities",
+ UserIdentities = "user_identities",
+ SecretIdentities = "secret_identities",
+ PamIdentities = "pam_identities",
+ InternalCas = "internal_cas",
+ ActiveCerts = "active_certs",
+ WildcardCerts = "wildcard_certs"
+}
+
+export type BillingV2BreakdownProject = {
+ id: string;
+ name: string;
+ count: number;
+};
+
+// One organization in the billing tree and the metered units attributed to it. orgLevelCount plus every
+// project count equals count. Names are shown for organizations and projects the reader may not have
+// access to, so they render as plain text and never as links.
+export type BillingV2BreakdownScope = {
+ orgId: string;
+ name: string;
+ isRoot: boolean;
+ count: number;
+ orgLevelCount: number;
+ projects: BillingV2BreakdownProject[];
+};
+
+// Where one metered dimension's usage comes from. total is counted live from the same predicates that
+// feed the meter, so it can differ from the overview's billed `used` by a reporting cycle.
+export type BillingV2UsageBreakdown = {
+ dimensionKey: string;
+ total: number;
+ userCount: number;
+ machineCount: number;
+ // false for the PKI dimensions, whose units cannot be attributed to a single project.
+ hasProjectDetail: boolean;
+ unit: string;
+ scopes: BillingV2BreakdownScope[];
+};
+
+// A root organization the signed-in caller may read billing for. A self-hosted instance admin gets
+// every organization on the instance, because one licence covers them all; everyone else gets only
+// their own, so the picker collapses to a single entry and the UI hides it.
+export type BillingV2Organization = {
+ id: string;
+ name: string;
+};
diff --git a/frontend/src/index.css b/frontend/src/index.css
index fd3703351b..afb13baac1 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -368,6 +368,17 @@ html[data-platform="ios"] {
}
/* Keyframes */
+ /* Proportional bars grow from their left edge when they first paint. scaleX rather than width keeps
+ the work on the compositor, which matters because a scope breakdown can hold dozens of bars. */
+ @keyframes barGrow {
+ from {
+ transform: scaleX(0);
+ }
+ to {
+ transform: scaleX(1);
+ }
+ }
+
@keyframes fadeIn {
0% {
opacity: 0;
@@ -479,6 +490,11 @@ html[data-platform="ios"] {
animation: fadeIn 100ms cubic-bezier(0.16, 1, 0.3, 1);
}
+ .animate-bar-grow {
+ transform-origin: left;
+ animation: barGrow 420ms ease-out both;
+ }
+
.popIn {
animation: popIn 150ms cubic-bezier(0.16, 1, 0.3, 1);
}
diff --git a/frontend/src/pages/organization/BillingPage/BillingPage.tsx b/frontend/src/pages/organization/BillingPage/BillingPage.tsx
index 276afc2269..733fa70904 100644
--- a/frontend/src/pages/organization/BillingPage/BillingPage.tsx
+++ b/frontend/src/pages/organization/BillingPage/BillingPage.tsx
@@ -1,6 +1,7 @@
import { useSubscription } from "@app/context";
import { BillingV2Page } from "../BillingV2Page";
+import { PREVIEW_MODE } from "../BillingV2Page/billing-v2-local-preview";
import { OfflineBillingPage } from "./OfflineBillingPage";
export const BillingPage = () => {
@@ -8,7 +9,8 @@ export const BillingPage = () => {
// Offline (air-gapped) licenses can't reach the license server, so the billing surface can't load;
// short-circuit to the offline page (no API calls) before mounting it.
- if (subscription?.isOffline) {
+ // LAYOUT PREVIEW — REMOVE BEFORE MERGE: lets the offline page be reviewed without an offline licence.
+ if (PREVIEW_MODE === "offline" || subscription?.isOffline) {
return <OfflineBillingPage />;
}
diff --git a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
index 765ead1d3a..5021daf0ce 100644
--- a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
@@ -15,20 +15,32 @@ import {
useAddBillingV2PaymentMethod,
useCreateBillingV2PortalSession,
useGetBillingV2Catalog,
+ useGetBillingV2Organizations,
useGetBillingV2Overview
} from "@app/hooks/api";
import { Overview } from "./components/Overview";
import { ProductSheet } from "./components/ProductSheet";
import { RemoveProductModal } from "./components/RemoveProductModal";
+import { UsageBreakdownSheet } from "./components/UsageBreakdownSheet";
import { catalogById } from "./billing-v2-format";
+// LOCAL PREVIEW ONLY — DO NOT COMMIT (see billing-v2-local-preview.ts).
+import {
+ asCloudOverview,
+ asManagedCloudOverview,
+ PREVIEW_CATALOG,
+ PREVIEW_ENTITLEMENTS,
+ PREVIEW_MODE
+} from "./billing-v2-local-preview";
import { BillingV2RenderState } from "./billing-v2-view-types";
const CONTACT_SALES_URL = "https://infisical.com/talk-to-us";
// `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" };
+type BillingV2Flow =
+ | { type: "sheet"; prodId: string; view?: "commitment" }
+ | { type: "breakdown"; prodId: string };
export const BillingV2Page = () => {
const { t } = useTranslation();
@@ -40,11 +52,70 @@ export const BillingV2Page = () => {
OrgPermissionSubjects.Billing
);
- const { data: overview, isPending, isError, refetch } = useGetBillingV2Overview(orgId);
- const { data: catalog = [] } = useGetBillingV2Catalog(orgId);
+ // Which organization the page is pointed at. Defaults to the signed-in one; an instance admin on
+ // self-hosted can switch it, and the overview, catalog and breakdown all follow.
+ const [selectedOrgId, setSelectedOrgId] = useState(orgId);
+ // The org switcher changes currentOrg without unmounting this page, and useState only reads its
+ // initial value, so the selection has to be reset explicitly or every query keeps asking about the
+ // org the user just left. Adjusted during render rather than in an effect so no pass renders the
+ // previous org's figures under the new org's name.
+ const [lastOrgId, setLastOrgId] = useState(orgId);
+ if (orgId !== lastOrgId) {
+ setLastOrgId(orgId);
+ setSelectedOrgId(orgId);
+ }
+ const { data: rootOrgs = [] } = useGetBillingV2Organizations(orgId);
+
+ const {
+ data: serverOverview,
+ isPending,
+ isError,
+ refetch
+ } = useGetBillingV2Overview(selectedOrgId);
+ const { data: realCatalog = [] } = useGetBillingV2Catalog(selectedOrgId);
const createPortalSession = useCreateBillingV2PortalSession();
const addPaymentMethod = useAddBillingV2PaymentMethod();
+ // ===== LAYOUT PREVIEW — REMOVE BEFORE MERGE (see billing-v2-local-preview.ts) =====
+ // A dev stack has no licence server, so the catalog is empty and no product cards render. This
+ // substitutes the licence server's half of the data so the layout is reviewable. Switch views with
+ // PREVIEW_MODE in billing-v2-local-preview.ts.
+ const usePreview = PREVIEW_MODE !== "off" && realCatalog.length === 0;
+ const catalog = usePreview ? PREVIEW_CATALOG : realCatalog;
+ // Shadows the real overview for the whole component, so every branch keyed off it (subState, the
+ // managed/self-serve copy, the payment and invoice cards) sees the faked shape too. Restore to
+ // `const { data: overview, ... } = useGetBillingV2Overview(selectedOrgId)` when removing the preview.
+ let overview = serverOverview;
+ if (usePreview && serverOverview) {
+ if (PREVIEW_MODE === "cloud") {
+ overview = asCloudOverview(serverOverview);
+ } else if (PREVIEW_MODE === "cloud-managed") {
+ overview = asManagedCloudOverview(serverOverview);
+ } else {
+ overview = { ...serverOverview, entitlements: PREVIEW_ENTITLEMENTS };
+ }
+ }
+ // The preview fakes the deployment, so it has to fake this endpoint's answer too. A dev stack is
+ // self-hosted and the signed-in user is often an instance admin, so the server legitimately returns
+ // every root org on the box; left alone, the picker would appear while the page pretends to be cloud.
+ // Real cloud returns exactly one org, which is what makes the production rule (more than one entry
+ // means you may switch) correct without testing isCloud anywhere.
+ const pickerOrgs =
+ usePreview && PREVIEW_MODE !== "self-hosted" ? rootOrgs.slice(0, 1) : rootOrgs;
+ // ===== END LAYOUT PREVIEW =====
+
+ // Root organizations the signed-in user belongs to. A self-hosted licence spans every org on the
+ // instance, so the breakdown needs to say which one it is explaining; cloud bills per root org and
+ // stays bounded to the logged-in one.
+ // The server already decided what this caller may see: more than one entry means an instance admin
+ // on self-hosted, so the picker is theirs alone without the client testing for that. Cloud is bounded
+ // to the logged-in root org, so it never has one.
+ // LOCAL PREVIEW: drop `pickerOrgs` and use `rootOrgs` directly when removing the preview block.
+ // More than one entry means the server decided this caller may switch: an instance admin on
+ // self-hosted. Cloud always returns a single org, so this needs no isCloud test, and not reading the
+ // overview keeps the picker on screen while that request is loading or failing.
+ const showOrgFilter = pickerOrgs.length > 1;
+
const [flow, setFlow] = useState<BillingV2Flow | null>(null);
const [removeProdId, setRemoveProdId] = useState<string | null>(null);
@@ -107,6 +178,11 @@ export const BillingV2Page = () => {
setFlow({ type: "sheet", prodId: productId, view: "commitment" });
};
+ // Explains where a product's metered usage was created, across the org tree.
+ const onViewBreakdown = (productId: string) => {
+ setFlow({ type: "breakdown", prodId: productId });
+ };
+
const hasActiveSubscription = overview?.subState === "active";
const onUpdatePayment = async () => {
@@ -162,6 +238,11 @@ export const BillingV2Page = () => {
onManageSubscription={onManageSubscription}
onUpgrade={onUpgrade}
onSetCommitment={onSetCommitment}
+ onViewBreakdown={onViewBreakdown}
+ rootOrgs={pickerOrgs}
+ selectedOrgId={selectedOrgId}
+ onSelectOrg={setSelectedOrgId}
+ showOrgFilter={showOrgFilter}
onUpdatePayment={onUpdatePayment}
onEditDetails={onEditDetails}
onContact={onContact}
@@ -192,6 +273,15 @@ export const BillingV2Page = () => {
/>
)}
+ {flow?.type === "breakdown" && catalogById(catalog, flow.prodId) && (
+ <UsageBreakdownSheet
+ orgId={selectedOrgId}
+ prod={catalogById(catalog, flow.prodId)!}
+ entitlement={overview?.entitlements[flow.prodId]}
+ onClose={close}
+ />
+ )}
+
{removeProd && (
<RemoveProductModal
orgId={orgId}
diff --git a/frontend/src/pages/organization/BillingV2Page/billing-v2-local-preview.ts b/frontend/src/pages/organization/BillingV2Page/billing-v2-local-preview.ts
new file mode 100644
index 0000000000..ca36503881
--- /dev/null
+++ b/frontend/src/pages/organization/BillingV2Page/billing-v2-local-preview.ts
@@ -0,0 +1,206 @@
+/* eslint-disable */
+// ---------------------------------------------------------------------------------------------
+//
+// To remove: delete this file and the LOCAL_PREVIEW block in BillingV2Page.tsx.
+// ---------------------------------------------------------------------------------------------
+// ONE SWITCH for reviewing the layout. Flip this, save, and the page re-renders:
+//
+// "cloud" paying cloud customer: header tiles, payment card, invoices, no org picker
+// "cloud-managed" enterprise-managed cloud: Managed Billing notice, no Stripe sections
+// "self-hosted" licensed instance: managed copy, instance-admin org picker, no Stripe cards
+// "offline" air-gapped licence: the standalone OfflineBillingPage (nothing from this feature)
+// "off" no faking at all; on a dev stack this shows "No products available"
+// The usage
+export type PreviewMode = "cloud" | "cloud-managed" | "self-hosted" | "offline" | "off";
+export const PREVIEW_MODE: PreviewMode = "cloud";
+
+import {
+ BillingV2CatalogProduct,
+ BillingV2Entitlement,
+ BillingV2EntitlementDim,
+ BillingV2Overview
+} from "@app/hooks/api";
+
+const dim = (
+ key: string,
+ label: string,
+ noun: string,
+ used: number
+): BillingV2EntitlementDim => ({
+ key,
+ label,
+ noun,
+ unit: noun,
+ metered: true,
+ cadence: "monthly",
+ used,
+ limit: null,
+ committed: null,
+ commitAvailable: false,
+ onDemandAmount: 0
+});
+
+const product = (
+ id: string,
+ name: string,
+ icon: string,
+ color: string,
+ tagline: string
+): BillingV2CatalogProduct => ({
+ id,
+ name,
+ icon,
+ color,
+ tagline,
+ // Sales-led, so an unentitled product renders "Contact sales" rather than an Activate button, which
+ // is what production shows for these.
+ plans: [
+ {
+ tier: "enterprise",
+ name: "Enterprise",
+ selfServe: false,
+ salesLed: true,
+ trialable: false,
+ dims: []
+ }
+ ]
+});
+
+// Icon tokens and colours are approximations taken from a production screenshot, not the real catalog:
+// a dev stack has no licence server to read it from. Expect these to differ from production in detail.
+export const PREVIEW_CATALOG: BillingV2CatalogProduct[] = [
+ product(
+ "legacy_secrets",
+ "Legacy Secret Management",
+ "key_round",
+ "#7d7f80",
+ "The original per-identity secret management plan."
+ ),
+ product(
+ "secrets",
+ "Secrets Management",
+ "key_round",
+ "#e0ed34",
+ "Store, manage, and sync secrets across your stack."
+ ),
+ product(
+ "pki",
+ "Certificate Management",
+ "file_check",
+ "#ed8c34",
+ "Issue and manage X.509 certificates and private CAs."
+ ),
+ product(
+ "pam",
+ "Privileged Access Management",
+ "user_round_plus",
+ "#ff3568",
+ "Secure, broker, and audit privileged access."
+ )
+];
+
+export const PREVIEW_ENTITLEMENTS: Record<string, BillingV2Entitlement> = {
+ // Two dimensions, as production shows: the combined identity meter plus the human-seat one.
+ legacy_secrets: {
+ entitled: true,
+ planTier: "enterprise",
+ cadence: "annual",
+ renewsOn: "November 3, 2026",
+ dimensions: [
+ dim("identities", "Identities", "identity", 25),
+ dim("user_identities", "User Identities", "user identity", 10)
+ ]
+ },
+ secrets: {
+ entitled: true,
+ planTier: "enterprise",
+ cadence: "monthly",
+ dimensions: [dim("secret_identities", "Secret Identities", "secret identity", 15)]
+ },
+ // Several breakdownable dimensions, so the sheet renders its unit tabs.
+ pki: {
+ entitled: true,
+ planTier: "enterprise",
+ cadence: "monthly",
+ dimensions: [
+ dim("internal_cas", "Internal CAs", "internal CA", 23),
+ dim("active_certs", "Active Certificates", "active certificate", 134),
+ dim("wildcard_certs", "Wildcard Certificates", "wildcard certificate", 23)
+ ]
+ },
+ pam: {
+ entitled: true,
+ planTier: "enterprise",
+ cadence: "monthly",
+ dimensions: [dim("pam_identities", "PAM Identities", "PAM identity", 54)]
+ }
+};
+
+// Two real cloud shapes, because they render very differently and both are worth reviewing.
+//
+// "cloud" is a paying self-serve customer: an active Stripe subscription, so the page shows the header
+// stat tiles, the payment method card, the billing details card and the invoice list.
+const CLOUD_BASE = {
+ isCloud: true as const,
+ mode: "self-serve" as const,
+ checkoutFrozen: false,
+ planName: "Enterprise",
+ entitlements: PREVIEW_ENTITLEMENTS
+};
+
+export const asCloudOverview = (overview: BillingV2Overview): BillingV2Overview => ({
+ ...overview,
+ ...CLOUD_BASE,
+ subState: "active",
+ selfServe: true,
+ billing: {
+ monthlyRecurring: 1240,
+ annualCommitted: 18000,
+ activeProductCount: PREVIEW_CATALOG.length,
+ nextCharge: {
+ amount: 1240,
+ at: "October 1, 2026",
+ productKeys: ["secrets"],
+ cadence: "monthly",
+ hasUsage: true
+ }
+ },
+ onDemandAmount: 84,
+ payment: { brand: "visa", last4: "4242", expMonth: 11, expYear: 2028 },
+ billingDetails: {
+ name: "Admin Org",
+ email: "[email protected]",
+ address: {
+ line1: "1 Example Street",
+ city: "San Francisco",
+ state: "CA",
+ postalCode: "94105",
+ country: "US"
+ },
+ taxIds: []
+ },
+ invoices: [
+ { id: "in_3", number: "INV-0003", date: "September 1, 2026", amount: 1240, paid: true, pdfUrl: null },
+ { id: "in_2", number: "INV-0002", date: "August 1, 2026", amount: 1240, paid: true, pdfUrl: null },
+ { id: "in_1", number: "INV-0001", date: "July 1, 2026", amount: 1156, paid: true, pdfUrl: null }
+ ]
+});
+
+// "cloud-managed" is an enterprise-managed cloud org, which is what a real production account looked
+// like: contract-billed, so there is no Stripe subscription and none of those sections render. selfServe
+// false is what raises the Managed Billing notice.
+//
+// One thing this cannot reproduce: production also shows a Manage button on the active product. On this
+// branch that needs overview.selfServe true, the same flag the Managed Billing notice needs false, so
+// the two cannot both render. Production is on an older build where they could.
+export const asManagedCloudOverview = (overview: BillingV2Overview): BillingV2Overview => ({
+ ...overview,
+ ...CLOUD_BASE,
+ subState: "no-subscription",
+ selfServe: false,
+ billing: { monthlyRecurring: 0, annualCommitted: 0, activeProductCount: 1, nextCharge: null },
+ onDemandAmount: 0,
+ payment: null,
+ billingDetails: null,
+ invoices: []
+});
diff --git a/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx b/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
index fbf6b285c9..118f7ce2e8 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
@@ -2,7 +2,7 @@ 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";
+import { BillingV2CatalogProduct, BillingV2Organization, BillingV2Overview } from "@app/hooks/api";
import { BillingV2RenderState } from "../billing-v2-view-types";
import { BillingHeaderCard } from "./cards/BillingHeaderCard";
@@ -13,6 +13,7 @@ import { ProductsCard } from "./cards/ProductsCard";
import { ErrorPanel } from "./states/ErrorPanel";
import { OverviewSkeleton } from "./states/OverviewSkeleton";
import { Banner } from "./Banner";
+import { RootOrgFilter } from "./RootOrgFilter";
export type OverviewProps = {
overview?: BillingV2Overview;
@@ -21,6 +22,13 @@ export type OverviewProps = {
onManageSubscription: () => void;
onUpgrade: (productId: string) => void;
onSetCommitment: (productId: string) => void;
+ onViewBreakdown: (productId: string) => void;
+ // Root-org picker for the usage breakdown. Only rendered on self-hosted, where one licence spans
+ // every organization on the instance; on cloud the breakdown is bounded to the logged-in root org.
+ rootOrgs: BillingV2Organization[];
+ selectedOrgId: string;
+ onSelectOrg: (orgId: string) => void;
+ showOrgFilter: boolean;
onUpdatePayment: () => void;
onEditDetails: () => void;
onContact: (prod: BillingV2CatalogProduct) => void;
@@ -38,19 +46,36 @@ export const Overview = ({
onManageSubscription,
onUpgrade,
onSetCommitment,
+ onViewBreakdown,
+ rootOrgs,
+ selectedOrgId,
+ onSelectOrg,
+ showOrgFilter,
onUpdatePayment,
onEditDetails,
onContact,
onRetry,
canManageBilling
}: OverviewProps) => {
+ // Rendered before the early returns: a failing organization must not take the control that chose it
+ // off the screen, or the only way back is a page reload.
+ const orgFilter = showOrgFilter ? (
+ <RootOrgFilter orgs={rootOrgs} value={selectedOrgId} onChange={onSelectOrg} />
+ ) : null;
+
if (subState === "loading") {
- return <OverviewSkeleton />;
+ return (
+ <div className="flex flex-col gap-4">
+ {orgFilter}
+ <OverviewSkeleton />
+ </div>
+ );
}
if (subState === "error" || !overview) {
return (
<div className="flex flex-col gap-4">
+ {orgFilter}
<ErrorPanel onRetry={onRetry} />
</div>
);
@@ -101,12 +126,14 @@ export const Overview = ({
onUpdatePayment={onUpdatePayment}
onManageSubscription={onManageSubscription}
/>
+ {orgFilter}
<ProductsCard
overview={overview}
catalog={catalog}
readOnly={productsReadOnly}
onManage={onUpgrade}
onSetCommitment={onSetCommitment}
+ onViewBreakdown={onViewBreakdown}
onContact={onContact}
/>
</div>
@@ -133,12 +160,14 @@ export const Overview = ({
onContact={onContact}
/> */}
<BillingHeaderCard overview={overview} catalog={catalog} />
+ {orgFilter}
<ProductsCard
overview={overview}
catalog={catalog}
readOnly={productsReadOnly}
onManage={onUpgrade}
onSetCommitment={onSetCommitment}
+ onViewBreakdown={onViewBreakdown}
onContact={onContact}
/>
{!isManaged && (
diff --git a/frontend/src/pages/organization/BillingV2Page/components/RootOrgFilter.tsx b/frontend/src/pages/organization/BillingV2Page/components/RootOrgFilter.tsx
new file mode 100644
index 0000000000..e94f89c252
--- /dev/null
+++ b/frontend/src/pages/organization/BillingV2Page/components/RootOrgFilter.tsx
@@ -0,0 +1,44 @@
+import { Building2 } from "lucide-react";
+
+import { Combobox } from "@app/components/v3";
+import { BillingV2Organization } from "@app/hooks/api";
+
+type RootOrgFilterProps = {
+ orgs: BillingV2Organization[];
+ value: string;
+ onChange: (orgId: string) => void;
+ isLoading?: boolean;
+};
+
+// Picks which root organization's usage the breakdown explains. A self-hosted licence covers every org
+// in the instance, so the billed figure spans all of them and one org's page cannot account for it on
+// its own. Cloud bills per root org, so this is not rendered there.
+export const RootOrgFilter = ({ orgs, value, onChange, isLoading }: RootOrgFilterProps) => (
+ <div className="flex flex-col gap-2 rounded-lg border border-border bg-card p-4">
+ <div className="flex items-center gap-2">
+ <Building2 className="size-4 text-org" />
+ <span className="text-sm font-medium text-foreground">Organization</span>
+ </div>
+ <p className="text-xs text-muted">
+ This instance&apos;s licence covers every organization on it. Pick one to see the usage it
+ contributes.
+ </p>
+ {/* The width goes on a wrapper: Combobox forwards className to its input, while the chevron is
+ positioned against the full-width container, so narrowing the input alone strands it. */}
+ <div className="w-full max-w-sm">
+ <Combobox<BillingV2Organization>
+ id="billing-root-org-filter"
+ placeholder="Select an organization..."
+ searchPlaceholder="Search organizations..."
+ searchAriaLabel="Search root organizations"
+ isLoading={isLoading}
+ options={orgs}
+ value={orgs.find((org) => org.id === value) ?? null}
+ onValueChange={(option) => onChange(option.id)}
+ getOptionValue={(option) => option.id}
+ getOptionLabel={(option) => option.name}
+ emptyMessage="No organizations found"
+ />
+ </div>
+ </div>
+);
diff --git a/frontend/src/pages/organization/BillingV2Page/components/UsageBreakdownSheet.tsx b/frontend/src/pages/organization/BillingV2Page/components/UsageBreakdownSheet.tsx
new file mode 100644
index 0000000000..85aa0c2b8b
--- /dev/null
+++ b/frontend/src/pages/organization/BillingV2Page/components/UsageBreakdownSheet.tsx
@@ -0,0 +1,466 @@
+import { useMemo, useState } from "react";
+import { ArrowDownAZ, ArrowDownWideNarrow, Box, Building2, Search } from "lucide-react";
+
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+ Badge,
+ Button,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+ Skeleton,
+ Tabs,
+ TabsList,
+ TabsTrigger
+} from "@app/components/v3";
+import { cn } from "@app/components/v3/utils";
+import {
+ BillingV2BreakdownDimension,
+ BillingV2BreakdownScope,
+ BillingV2CatalogProduct,
+ BillingV2Entitlement,
+ BillingV2UsageBreakdown,
+ useGetBillingV2UsageBreakdown
+} from "@app/hooks/api";
+
+import { pluralizeUnit } from "../billing-v2-format";
+import { ProductIcon } from "./shared";
+
+// user_identities is deliberately absent: it is already the user half of the summary split, and it
+// carries no scope tree, so a tab for it would show a number the reader has just seen and nothing else.
+const BREAKDOWN_DIMENSIONS = new Set<string>(
+ Object.values(BillingV2BreakdownDimension).filter(
+ (key) => key !== BillingV2BreakdownDimension.UserIdentities
+ )
+);
+
+// A product's dimensions that can be explained by scope, in the order the entitlement lists them. More
+// than one turns the sheet's body into tabs, the way Certificate Management carries CAs and both
+// certificate meters.
+export const breakdownableDimensions = (entitlement?: BillingV2Entitlement) =>
+ (entitlement?.dimensions ?? []).filter((dim) => BREAKDOWN_DIMENSIONS.has(dim.key));
+
+type SortOrder = "count" | "name";
+
+const pct = (part: number, whole: number) => (whole > 0 ? `${(part / whole) * 100}%` : "0%");
+const share = (part: number, whole: number) =>
+ whole > 0 ? `${Math.round((part / whole) * 100)}%` : "0%";
+const sentenceCase = (value: string) => value.charAt(0).toUpperCase() + value.slice(1);
+
+type CountShareProps = {
+ count: number;
+ total: number;
+ // Named on the top-level scope rows so the percentage says what it is a percentage of; omitted on
+ // the nested rows, where the parent row has just established it.
+ unitLabel?: string;
+};
+
+const CountShare = ({ count, total, unitLabel }: CountShareProps) => (
+ <span className="shrink-0 text-xs whitespace-nowrap text-muted tabular-nums">
+ <span className="font-semibold text-foreground">{count.toLocaleString()}</span> ·{" "}
+ {share(count, total)}
+ {unitLabel ? ` of ${unitLabel}` : ""}
+ </span>
+);
+
+type MeterProps = { className: string; width: string; height?: string };
+
+const Meter = ({ className, width, height = "h-1.5" }: MeterProps) => (
+ <div className={cn("w-full overflow-hidden rounded-xs bg-background", height)}>
+ <div className={cn("animate-bar-grow h-full rounded-xs", className)} style={{ width }} />
+ </div>
+);
+
+type ScopeRowProps = {
+ scope: BillingV2BreakdownScope;
+ // Total across every scope, so each row's bar is drawn to the same scale.
+ machineCount: number;
+ unitLabel: string;
+ hasProjectDetail: boolean;
+};
+
+// One organization's contribution. Expanding it says where inside that org the units were created: on
+// the org itself, or in one of its projects. Built on the shared Accordion so it opens with the same
+// motion and hover colours as every other expandable row in the product.
+const ScopeRow = ({ scope, machineCount, unitLabel, hasProjectDetail }: ScopeRowProps) => {
+ // 85% is the strength DimensionMeter already uses for a filled meter, so a bar reads as a bar rather
+ // than as a solid scope-coloured block next to it.
+ const scopeTint = scope.isRoot ? "bg-org/85" : "bg-sub-org/85";
+ // The org's own share sits directly under the org's bar at a different length. In the scope colour the
+ // two read as the same measurement drawn twice, so it takes the neutral tint and leaves the scope
+ // colour to mean "this is the whole organization".
+ const orgLevelTint = "bg-neutral/85";
+ const canExpand = hasProjectDetail && scope.count > 0;
+ const projectLabel = `${scope.projects.length} ${scope.projects.length === 1 ? "project" : "projects"}`;
+
+ const header = (
+ <div className="flex min-w-0 flex-1 flex-col gap-2">
+ <div className="flex items-center justify-between gap-3">
+ <span className="flex min-w-0 items-center gap-2 text-sm font-medium text-foreground">
+ <Building2
+ className={cn("size-3.5 shrink-0", scope.isRoot ? "text-org" : "text-sub-org")}
+ />
+ <span className="truncate">{scope.name}</span>
+ {scope.isRoot && <Badge variant="org">Root org</Badge>}
+ </span>
+ <CountShare count={scope.count} total={machineCount} unitLabel={unitLabel} />
+ </div>
+ <Meter className={scopeTint} width={pct(scope.count, machineCount)} />
+ </div>
+ );
+
+ if (!canExpand) {
+ return (
+ <div className="rounded-md border border-border bg-container p-3">
+ <div className="flex">{header}</div>
+ </div>
+ );
+ }
+
+ return (
+ <Accordion type="single" collapsible>
+ <AccordionItem value={scope.orgId}>
+ <AccordionTrigger className="px-3 py-3">{header}</AccordionTrigger>
+ <AccordionContent className="border-t border-border px-3 pt-3 pb-3.5">
+ <div className="flex flex-col gap-2.5">
+ <span className="text-[11px] tracking-wide text-muted uppercase">
+ Where these {unitLabel} were created
+ </span>
+ {scope.orgLevelCount > 0 && (
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center justify-between gap-3">
+ <span className="flex min-w-0 items-center gap-2 text-xs text-accent">
+ {/* A swatch rather than an icon: this row is the parent org itself, not a resource. */}
+ <span className={cn("size-2.5 shrink-0 rounded-xs", orgLevelTint)} />
+ <span className="truncate">{scope.isRoot ? "Org" : "Sub-Org"}</span>
+ </span>
+ <CountShare count={scope.orgLevelCount} total={scope.count} />
+ </div>
+ <Meter
+ className={orgLevelTint}
+ width={pct(scope.orgLevelCount, scope.count)}
+ height="h-1"
+ />
+ </div>
+ )}
+ {scope.projects.length > 0 && (
+ <div className="flex items-center gap-2 border-t border-border pt-2.5">
+ <span className="text-[11px] tracking-wide text-muted uppercase">Projects</span>
+ <span className="text-[11px] text-muted">{projectLabel}</span>
+ </div>
+ )}
+ {scope.projects.map((project) => (
+ <div key={project.id} className="flex flex-col gap-1.5">
+ <div className="flex items-center justify-between gap-3">
+ {/* Plain text, never a link: the breakdown names projects the reader may not open. */}
+ <span className="flex min-w-0 items-center gap-2 text-xs text-accent">
+ <Box className="size-3 shrink-0 text-project" />
+ <span className="truncate">{project.name}</span>
+ </span>
+ <CountShare count={project.count} total={scope.count} />
+ </div>
+ <Meter
+ className="bg-project/85"
+ width={pct(project.count, scope.count)}
+ height="h-1"
+ />
+ </div>
+ ))}
+ </div>
+ </AccordionContent>
+ </AccordionItem>
+ </Accordion>
+ );
+};
+
+const BreakdownSkeleton = () => (
+ <div className="flex flex-col gap-4">
+ <Skeleton className="h-24 w-full" />
+ <Skeleton className="h-28 w-full" />
+ <Skeleton className="h-14 w-full" />
+ <Skeleton className="h-14 w-full" />
+ </div>
+);
+
+const BreakdownBody = ({ breakdown }: { breakdown: BillingV2UsageBreakdown }) => {
+ const [query, setQuery] = useState("");
+ const [sort, setSort] = useState<SortOrder>("count");
+
+ const { total, userCount, machineCount, unit, hasProjectDetail, scopes } = breakdown;
+ const unitLabel = pluralizeUnit(unit);
+ // The identity meters bill people and machines as one figure, so the headline counts both and cannot
+ // borrow the scope label, which names machines only. A dimension that counts a single kind keeps its
+ // own noun.
+ const totalLabel = userCount > 0 ? "unique identities" : unitLabel;
+ const rootScope = scopes.find((scope) => scope.isRoot);
+ const subOrgScopes = useMemo(() => scopes.filter((scope) => !scope.isRoot), [scopes]);
+ const subOrgCount = subOrgScopes.reduce((sum, scope) => sum + scope.count, 0);
+
+ // Counts only the orgs and projects that actually hold units of this dimension, which is what the
+ // scope list already contains. Truthful here and free, because the breakdown is loaded.
+ const projectCount = scopes.reduce((sum, scope) => sum + scope.projects.length, 0);
+ const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`;
+ const spanSummary = [
+ "Created across the root org",
+ subOrgScopes.length > 0 ? plural(subOrgScopes.length, "sub-org") : null,
+ hasProjectDetail && projectCount > 0 ? plural(projectCount, "project") : null
+ ]
+ .filter(Boolean)
+ .join(subOrgScopes.length > 0 && hasProjectDetail && projectCount > 0 ? ", " : " and ")
+ .replace(/, ([^,]*)$/, " and $1");
+
+ const visibleSubOrgs = useMemo(() => {
+ const term = query.trim().toLowerCase();
+ const matched = term
+ ? subOrgScopes.filter((scope) => scope.name.toLowerCase().includes(term))
+ : subOrgScopes;
+ return [...matched].sort((a, b) =>
+ sort === "name" ? a.name.localeCompare(b.name) : b.count - a.count
+ );
+ }, [subOrgScopes, query, sort]);
+
+ return (
+ <div className="flex flex-col gap-4">
+ <div className="flex flex-col gap-3 rounded-lg border border-border bg-card p-4">
+ <div className="flex items-baseline gap-2">
+ <span className="text-2xl font-semibold text-foreground tabular-nums">
+ {total.toLocaleString()}
+ </span>
+ <span className="text-xs text-muted">{totalLabel}</span>
+ </div>
+ {userCount > 0 && (
+ // The identity meters bill people and machines together, so the split is what makes the
+ // headline figure legible. No colour keys: nothing on this sheet is keyed to them yet.
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-accent">
+ <span>
+ <span className="font-semibold text-foreground">{userCount.toLocaleString()}</span>{" "}
+ user identities
+ </span>
+ <span className="text-border">·</span>
+ <span>
+ <span className="font-semibold text-foreground">{machineCount.toLocaleString()}</span>{" "}
+ {unitLabel}
+ </span>
+ </div>
+ )}
+ </div>
+
+ {machineCount === 0 ? (
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>Nothing counted yet</EmptyTitle>
+ <EmptyDescription>
+ No {unitLabel} have been created in this organization or its sub-organizations.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <>
+ <div className="flex flex-col gap-1 pt-1">
+ <span className="text-base font-semibold text-foreground">
+ {sentenceCase(unitLabel)} by scope
+ </span>
+ <span className="text-xs text-muted">{spanSummary}</span>
+ </div>
+
+ {subOrgScopes.length > 0 && rootScope && (
+ <div className="flex flex-col gap-3 rounded-lg border border-border bg-card p-4">
+ <div className="flex items-baseline gap-2">
+ <span className="text-2xl font-semibold text-foreground tabular-nums">
+ {machineCount.toLocaleString()}
+ </span>
+ <span className="text-xs text-muted">{unitLabel}</span>
+ </div>
+ <div className="flex h-2.5 w-full gap-0.5 overflow-hidden rounded-xs bg-background">
+ <div
+ className="animate-bar-grow h-full rounded-xs bg-org/85"
+ style={{ width: pct(rootScope.count, machineCount) }}
+ />
+ {/* Staggered so the two segments read as one bar filling left to right, not two racing. */}
+ <div
+ className="animate-bar-grow h-full rounded-xs bg-sub-org/85"
+ style={{ width: pct(subOrgCount, machineCount), animationDelay: "60ms" }}
+ />
+ </div>
+ <div className="flex flex-wrap items-center gap-x-5 gap-y-1 text-xs text-accent">
+ <span className="flex items-center gap-1.5">
+ <span className="h-1.5 w-3 rounded-xs bg-org/85" />
+ <span className="font-semibold text-foreground">
+ {rootScope.count.toLocaleString()}
+ </span>{" "}
+ created in the root org
+ </span>
+ <span className="flex items-center gap-1.5">
+ <span className="h-1.5 w-3 rounded-xs bg-sub-org/85" />
+ <span className="font-semibold text-foreground">
+ {subOrgCount.toLocaleString()}
+ </span>{" "}
+ created in sub-orgs
+ </span>
+ </div>
+ </div>
+ )}
+
+ {rootScope && (
+ <ScopeRow
+ scope={rootScope}
+ machineCount={machineCount}
+ unitLabel={unitLabel}
+ hasProjectDetail={hasProjectDetail}
+ />
+ )}
+
+ {subOrgScopes.length > 0 && (
+ <div className="flex flex-col gap-2.5">
+ <div className="flex items-center gap-2">
+ <InputGroup className="flex-1">
+ <InputGroupAddon align="inline-start">
+ <Search className="size-3.5" />
+ </InputGroupAddon>
+ <InputGroupInput
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Search sub-organizations..."
+ aria-label="Search sub-organizations"
+ />
+ </InputGroup>
+ {/* md matches the search field's height; the fixed width keeps the control from
+ resizing as the label changes between the two sort orders. */}
+ <Button
+ variant="outline"
+ size="md"
+ className="w-36 shrink-0 justify-start"
+ onClick={() => setSort((current) => (current === "count" ? "name" : "count"))}
+ >
+ {sort === "count" ? <ArrowDownWideNarrow /> : <ArrowDownAZ />}
+ {sort === "count" ? "Most identities" : "Alphabetical"}
+ </Button>
+ </div>
+
+ <div className="flex items-center justify-between gap-3 px-0.5">
+ <span className="text-[11px] tracking-wide text-muted uppercase">
+ Sub-organizations
+ </span>
+ <span className="text-[11px] text-muted">
+ {visibleSubOrgs.length}{" "}
+ {visibleSubOrgs.length === 1 ? "sub-organization" : "sub-organizations"}
+ </span>
+ </div>
+
+ {visibleSubOrgs.length === 0 ? (
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>No matching sub-organizations</EmptyTitle>
+ <EmptyDescription>Clear the search to see all of them.</EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <div className="flex flex-col gap-2">
+ {visibleSubOrgs.map((scope) => (
+ <ScopeRow
+ key={scope.orgId}
+ scope={scope}
+ machineCount={machineCount}
+ unitLabel={unitLabel}
+ hasProjectDetail={hasProjectDetail}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ );
+};
+
+type UsageBreakdownSheetProps = {
+ orgId: string;
+ prod: BillingV2CatalogProduct;
+ entitlement?: BillingV2Entitlement;
+ onClose: () => void;
+};
+
+// Explains where one product's metered usage comes from: which organization in the billing tree, and
+// which project inside it, each unit was created in. Counted live from the same predicates that feed the
+// meter, so it explains the billed figure rather than offering a second opinion on it.
+export const UsageBreakdownSheet = ({
+ orgId,
+ prod,
+ entitlement,
+ onClose
+}: UsageBreakdownSheetProps) => {
+ const dimensions = breakdownableDimensions(entitlement);
+ const [activeKey, setActiveKey] = useState(dimensions[0]?.key ?? "");
+ const activeDim = dimensions.find((dim) => dim.key === activeKey) ?? dimensions[0];
+
+ const {
+ data: breakdown,
+ isPending,
+ isError
+ } = useGetBillingV2UsageBreakdown(orgId, activeDim?.key ?? null);
+
+ return (
+ <Sheet open onOpenChange={(open) => !open && onClose()}>
+ <SheetContent side="right" className="flex w-full flex-col p-0 sm:max-w-2xl">
+ <SheetHeader className="flex-row items-center gap-3 pr-12">
+ <ProductIcon product={prod} />
+ <div className="min-w-0">
+ <SheetTitle className="text-base">Usage breakdown</SheetTitle>
+ <SheetDescription className="mt-0.5">{prod.name}</SheetDescription>
+ </div>
+ </SheetHeader>
+
+ <div className="flex thin-scrollbar flex-1 flex-col gap-4 overflow-y-auto p-4">
+ {dimensions.length > 1 && (
+ <Tabs value={activeDim?.key} onValueChange={setActiveKey}>
+ <TabsList variant="org">
+ {dimensions.map((dim) => (
+ <TabsTrigger key={dim.key} value={dim.key}>
+ {dim.label}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ </Tabs>
+ )}
+
+ {isPending && <BreakdownSkeleton />}
+
+ {isError && (
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>Couldn&apos;t load the breakdown</EmptyTitle>
+ <EmptyDescription>
+ We couldn&apos;t work out where this usage comes from. Close this and try again in
+ a moment.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ )}
+
+ {breakdown && !isError && <BreakdownBody breakdown={breakdown} />}
+ </div>
+
+ <SheetFooter className="flex-row items-center justify-end border-t">
+ <Button variant="org" size="sm" onClick={onClose}>
+ Done
+ </Button>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ );
+};
diff --git a/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx b/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx
index 292f486926..e6a6f4f194 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx
@@ -1,5 +1,5 @@
import { CSSProperties, ReactNode } from "react";
-import { DollarSign, Package, RefreshCw } from "lucide-react";
+import { ChevronRight, DollarSign, Package, RefreshCw } from "lucide-react";
import { createNotification } from "@app/components/notifications";
import {
@@ -34,6 +34,7 @@ import {
} from "../../billing-v2-format";
import { asPlanDeprecation, deprecationSubline } from "../deprecation/deprecation-data";
import { ActiveBadge, CardEmpty, DimensionMeter, ProductIcon } from "../shared";
+import { breakdownableDimensions } from "../UsageBreakdownSheet";
type ActiveProductCardProps = {
prod: BillingV2CatalogProduct;
@@ -42,6 +43,7 @@ type ActiveProductCardProps = {
selfServe: boolean;
onManage: (id: string) => void;
onSetCommitment: (id: string) => void;
+ onViewBreakdown: (id: string) => void;
};
// Full-width card for an active product: identity and status, price, Manage action, usage meters.
@@ -51,7 +53,8 @@ const ActiveProductCard = ({
readOnly,
selfServe,
onManage,
- onSetCommitment
+ onSetCommitment,
+ onViewBreakdown
}: 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. Hidden for enterprise-managed orgs.
@@ -82,6 +85,9 @@ const ActiveProductCard = ({
// Bar-bearing dims first so the block reads bars, then bare cost lines, then the shared legend.
const sortedDims = [...dims].sort((a, b) => Number(dimHasCeiling(b)) - Number(dimHasCeiling(a)));
+ // Only offer the breakdown for dimensions we can attribute to an org and project.
+ const hasBreakdown = breakdownableDimensions(entitlement).length > 0;
+
// Cadence and renewal (or trial / deprecation) as one muted subline under the product name.
let subline: ReactNode = null;
if (deprecation) {
@@ -163,6 +169,27 @@ const ActiveProductCard = ({
))}
</div>
)}
+ {hasBreakdown && (
+ // Full-bleed strip on the card's bottom edge. Sits above the commit nudge so the card ends on
+ // the action that costs money rather than on a read.
+ <button
+ type="button"
+ onClick={() => onViewBreakdown(prod.id)}
+ className={cn(
+ "group -mx-4 -mb-4 flex cursor-pointer items-center justify-between gap-3 border-t border-border px-4 py-2.5 text-left transition-colors hover:bg-container-hover",
+ commitNudge && "mb-0"
+ )}
+ >
+ {/* No counts here. A truthful "across N sub-orgs" means counting which orgs actually
+ contribute to this dimension, which costs a full usage breakdown per product on every page
+ load. The sheet says it instead, where that data is already loaded. */}
+ <span className="text-xs text-muted">Break this down by organization usage</span>
+ <span className="flex shrink-0 items-center gap-1 text-xs text-accent transition-colors group-hover:text-foreground">
+ View breakdown
+ <ChevronRight className="size-3.5" />
+ </span>
+ </button>
+ )}
{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">
@@ -255,6 +282,7 @@ type ProductsCardProps = {
readOnly?: boolean;
onManage: (id: string) => void;
onSetCommitment: (id: string) => void;
+ onViewBreakdown: (id: string) => void;
onContact: (prod: BillingV2CatalogProduct) => void;
};
@@ -264,6 +292,7 @@ export const ProductsCard = ({
readOnly,
onManage,
onSetCommitment,
+ onViewBreakdown,
onContact
}: ProductsCardProps) => {
// A deprecated product stays visible to existing subscribers but is closed to new ones, so hide it
@@ -339,6 +368,7 @@ export const ProductsCard = ({
selfServe={overview.selfServe}
onManage={onManage}
onSetCommitment={onSetCommitment}
+ onViewBreakdown={onViewBreakdown}
/>
))}
{available.length > 0 && (