Skip to content

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

feat(api): enhance billing v2 organization management and usage breakdown

Victor Hugo dos Santoseedfc12ee0a3
diff --git a/backend/src/ee/routes/v1/license-v2-router.ts b/backend/src/ee/routes/v1/license-v2-router.ts
index 94bfe9b96e..b76da713e8 100644
--- a/backend/src/ee/routes/v1/license-v2-router.ts
+++ b/backend/src/ee/routes/v1/license-v2-router.ts
@@ -194,7 +194,9 @@ 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."),
+ scopedCount: z
+ .number()
+ .describe("The part of the total the scope tree accounts for; equals total for dimensions with no users."),
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.")
@@ -270,6 +272,11 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
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() }),
+ querystring: z.object({
+ search: z.string().trim().optional().describe("Match root organizations whose name contains this."),
+ limit: z.coerce.number().min(1).max(1000).default(100).describe("Maximum organizations to return."),
+ offset: z.coerce.number().min(0).default(0).describe("Number of organizations to skip.")
+ }),
response: {
200: z.object({
organizations: z
@@ -277,7 +284,8 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
id: z.string().describe("ID of the root organization."),
name: z.string().describe("Display name of the root organization.")
})
- .array()
+ .array(),
+ totalCount: z.number().describe("Root organizations matching the search, across every page.")
})
}
},
@@ -286,14 +294,17 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
return server.services.licenseV2.getBillableOrganizations({
orgId: req.params.organizationId,
actor: buildActor(req.permission),
- isInstanceAdmin: isSuperAdmin(req.auth)
+ isInstanceAdmin: isSuperAdmin(req.auth),
+ search: req.query.search,
+ limit: req.query.limit,
+ offset: req.query.offset
});
}
});
server.route({
method: "GET",
- url: "/:organizationId/billing/v2/usage/:dimensionKey/breakdown",
+ url: "/:organizationId/billing/v2/breakdowns/:dimensionKey",
config: {
rateLimit: readLimit
},
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
index 197cafd83e..594bf26620 100644
--- a/backend/src/ee/services/license-v2/license-v2-breakdown-dal.ts
+++ b/backend/src/ee/services/license-v2/license-v2-breakdown-dal.ts
@@ -1,6 +1,7 @@
import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
+import { sanitizeSqlLikeString } from "@app/lib/fn";
import { orgTreeIds } from "@app/lib/knex";
export type TLicenseV2BreakdownDALFactory = ReturnType<typeof licenseV2BreakdownDALFactory>;
@@ -8,17 +9,8 @@ export type TLicenseV2BreakdownDALFactory = ReturnType<typeof licenseV2Breakdown
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 {
@@ -40,8 +32,6 @@ export const licenseV2BreakdownDALFactory = (db: TDbClient) => {
}
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)
@@ -52,16 +42,23 @@ export const licenseV2BreakdownDALFactory = (db: TDbClient) => {
}
};
- // 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[]> => {
+ const findAllRootOrgs = async (dto: {
+ search?: string;
+ limit: number;
+ offset: number;
+ }): Promise<{ orgs: TRootOrgRow[]; totalCount: number }> => {
try {
- return (await db
- .replicaNode()(TableName.Organization)
- .whereNull("rootOrgId")
- .orderBy("name", "asc")
- .limit(ROOT_ORG_LIMIT)
- .select("id", "name")) as TRootOrgRow[];
+ const baseQuery = db.replicaNode()(TableName.Organization).whereNull("rootOrgId");
+ if (dto.search) {
+ void baseQuery.whereILike("name", `%${sanitizeSqlLikeString(dto.search)}%`);
+ }
+
+ const [totalResult, orgs] = await Promise.all([
+ baseQuery.clone().count({ count: "*" }).first(),
+ baseQuery.clone().orderBy("name", "asc").limit(dto.limit).offset(dto.offset).select("id", "name")
+ ]);
+
+ return { orgs: orgs as TRootOrgRow[], totalCount: Number(totalResult?.count ?? 0) };
} catch (error) {
throw new DatabaseError({ error, name: "Find all root organizations for billing" });
}
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
deleted file mode 100644
index b21ffb41d6..0000000000
--- a/backend/src/ee/services/license-v2/license-v2-breakdown.test.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-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 1c3b0961e9..9cd32383fe 100644
--- a/backend/src/ee/services/license-v2/license-v2-service.ts
+++ b/backend/src/ee/services/license-v2/license-v2-service.ts
@@ -44,6 +44,7 @@ import {
TGetBillingV2CatalogDTO,
TGetBillingV2OverviewDTO,
TGetBillingV2UsageBreakdownDTO,
+ TListBillableOrganizationsDTO,
TPreviewBillingV2ChangeDTO,
TRemoveBillingV2ProductDTO,
TStartBillingV2TrialDTO
@@ -53,8 +54,6 @@ 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,
@@ -417,10 +416,6 @@ export const licenseV2ServiceFactory = ({
// cloud has per-org self-serve subscriptions.
const isSelfHostedLicense = !envConfig.isCloud;
- // 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 (
@@ -822,24 +817,31 @@ 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
+ // Assembles the org/project rows a breakdown query returned into the scope tree. The
+ // root org is always present, even at zero, so the user 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: [] }));
+ type TScopeAccumulator = {
+ name: string;
+ isRoot: boolean;
+ orgLevelCount: number;
+ projects: BillingV2BreakdownProject[];
+ };
+ const byOrg = new Map<string, TScopeAccumulator>();
+ orgs.forEach((org) => byOrg.set(org.id, { name: org.name, isRoot: org.isRoot, 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 ?? "");
+ let target = byOrg.get(row.orgId);
if (!target) {
- return;
+ // An organization that left the tree between the count and this read still holds metered
+ // units. Folding them into the root would inflate the figure the root org's own usage view
+ // shows, so the scope keeps its own row
+ target = { name: "Deleted organization", isRoot: false, orgLevelCount: 0, projects: [] };
+ byOrg.set(row.orgId, target);
}
if (!row.projectId) {
target.orgLevelCount += row.count;
@@ -855,15 +857,14 @@ export const licenseV2ServiceFactory = ({
});
});
- return orgs
- .map((org) => {
- const scope = byOrg.get(org.id) ?? { orgLevelCount: 0, projects: [] };
+ return [...byOrg.entries()]
+ .map(([orgId, scope]) => {
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,
+ orgId,
+ name: scope.name,
+ isRoot: scope.isRoot,
count,
orgLevelCount: scope.orgLevelCount,
projects
@@ -873,9 +874,6 @@ export const licenseV2ServiceFactory = ({
.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);
@@ -884,16 +882,9 @@ export const licenseV2ServiceFactory = ({
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 }[],
@@ -912,7 +903,7 @@ export const licenseV2ServiceFactory = ({
dimensionKey,
total: counts.users + counts.identities,
userCount: counts.users,
- machineCount: counts.identities,
+ scopedCount: counts.identities,
hasProjectDetail: withProjectDetail,
unit: "machine identity",
scopes: $buildScopes(orgs, projectsById, attributed)
@@ -926,7 +917,7 @@ export const licenseV2ServiceFactory = ({
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 };
+ return { dimensionKey, total, userCount: 0, scopedCount: total, hasProjectDetail: false, unit, scopes };
};
switch (dimensionKey) {
@@ -954,15 +945,13 @@ export const licenseV2ServiceFactory = ({
};
}
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,
+ scopedCount: 0,
hasProjectDetail: false,
unit: "user identity",
scopes: []
@@ -970,8 +959,6 @@ export const licenseV2ServiceFactory = ({
};
}
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") };
}
@@ -986,32 +973,43 @@ export const licenseV2ServiceFactory = ({
)
};
}
- default:
+ default: {
+ const unhandled: never = dimensionKey;
throw new BadRequestError({
- message: `'${dimensionKey}' is not a usage dimension that can be broken down by scope.`
+ message: `'${String(unhandled)}' 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) => {
+ const getBillableOrganizations = async ({
+ orgId,
+ actor,
+ isInstanceAdmin,
+ search,
+ limit,
+ offset
+ }: TListBillableOrganizationsDTO) => {
await ensureBillingRead(orgId, actor, isInstanceAdmin);
+ // ensureBillingRead checks with ParentOrganization scope, which refuses a child org, so orgId is
+ // already the root and the list collapses to that single entry.
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 }] : [] };
+
+ const matches = search ? organization.name.toLowerCase().includes(search.toLowerCase()) : true;
+ const organizations = matches ? [{ id: organization.id, name: organization.name }] : [];
+ return {
+ organizations: organizations.slice(offset, offset + limit),
+ totalCount: organizations.length
+ };
}
- return { organizations: await breakdownDAL.findAllRootOrgs() };
+ const { orgs, totalCount } = await breakdownDAL.findAllRootOrgs({ search, limit, offset });
+ return { organizations: orgs, totalCount };
};
// Force-refresh entitlements: ask the license server to recompute and drop the local cache, so the
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 4b9734a1cb..a896e29134 100644
--- a/backend/src/ee/services/license-v2/license-v2-types.ts
+++ b/backend/src/ee/services/license-v2/license-v2-types.ts
@@ -1,4 +1,5 @@
import { OrgServiceActor } from "@app/lib/types";
+import type { TMeteredDimensionKey } from "@app/services/license-client/usage/usage-counters";
export type BillingV2SubState = "active" | "trialing" | "past-due" | "suspended" | "no-subscription";
@@ -205,6 +206,12 @@ export type TGetBillingV2OverviewDTO = {
isInstanceAdmin?: boolean;
};
+export type TListBillableOrganizationsDTO = TGetBillingV2OverviewDTO & {
+ search?: string;
+ limit: number;
+ offset: number;
+};
+
export type TGetBillingV2CatalogDTO = {
orgId: string;
actor: OrgServiceActor;
@@ -310,28 +317,26 @@ export type TBillingV2SubscriptionLifecycleDTO = {
};
// 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.
+// must match the descriptors in services/license-client/features.ts
+export const BillingV2BreakdownDimension = {
+ Identities: "identities",
+ UserIdentities: "user_identities",
+ SecretIdentities: "secret_identities",
+ PamIdentities: "pam_identities",
+ InternalCas: "internal_cas",
+ ActiveCerts: "active_certs",
+ WildcardCerts: "wildcard_certs"
+} as const satisfies Record<string, TMeteredDimensionKey>;
+
+export type TBillingV2BreakdownDimension =
+ (typeof BillingV2BreakdownDimension)[keyof typeof BillingV2BreakdownDimension];
+
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;
@@ -343,19 +348,13 @@ export type BillingV2BreakdownScope = {
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.
+ // Humans in the metered set. The identity meters bill users and machine identities together
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.
+ // The part of the total the scope tree accounts for: total minus userCount for the identity meters.
+ scopedCount: number;
hasProjectDetail: boolean;
// Singular noun for what is counted ("machine identity", "internal CA"), for the UI's labels.
unit: string;
@@ -365,6 +364,6 @@ export type BillingV2UsageBreakdown = {
export type TGetBillingV2UsageBreakdownDTO = {
orgId: string;
actor: OrgServiceActor;
- dimensionKey: string;
+ dimensionKey: TBillingV2BreakdownDimension;
isInstanceAdmin?: boolean;
};
diff --git a/backend/src/ee/services/license/license-dal.ts b/backend/src/ee/services/license/license-dal.ts
index ee407eecf0..4e0bea6d62 100644
--- a/backend/src/ee/services/license/license-dal.ts
+++ b/backend/src/ee/services/license/license-dal.ts
@@ -12,14 +12,8 @@ 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
@@ -32,7 +26,6 @@ const $withBillableScopes = (knex: Knex, orgId: string | null) => {
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)
@@ -41,7 +34,6 @@ const $withBillableScopes = (knex: Knex, orgId: string | null) => {
.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)
@@ -49,7 +41,6 @@ const $withBillableScopes = (knex: Knex, orgId: string | null) => {
.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 })
diff --git a/backend/src/services/license-client/feature.ts b/backend/src/services/license-client/feature.ts
index 0c3cae77ed..8bc94387b5 100644
--- a/backend/src/services/license-client/feature.ts
+++ b/backend/src/services/license-client/feature.ts
@@ -30,7 +30,10 @@ export const defineFeature = <T extends TFeatureValue>(key: string, fallback: T)
fallback
});
-export const defineLimitFeature = (key: string, fallback: number): TLimitFeatureDescriptor => ({
+export const defineLimitFeature = <K extends string>(
+ key: K,
+ fallback: number
+): TLimitFeatureDescriptor & { readonly key: K } => ({
key,
fallback,
limit: true
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 602acc3aa2..fb0b4e612f 100644
--- a/backend/src/services/license-client/usage/usage-counter-dal.ts
+++ b/backend/src/services/license-client/usage/usage-counter-dal.ts
@@ -28,21 +28,25 @@ export const usageCounterDALFactory = (db: TDbClient) => {
// orgId omitted means instance-wide: self-hosted is one licence over the whole database and reports
// under an identity that is not an org id, so the org filter has to come off rather than be handed a
// non-uuid.
- const countInternalCas = async (orgId?: string): Promise<number> => {
- try {
- const qb = 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`);
+ const $internalCas = (orgId?: string) => {
+ const qb = 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`);
+
+ if (orgId) void qb.whereIn(`${TableName.Project}.orgId`, orgTreeIds(db.replicaNode(), orgId));
- if (orgId) void qb.whereIn(`${TableName.Project}.orgId`, orgTreeIds(db.replicaNode(), orgId));
+ return qb;
+ };
- const row = await qb.count(`${TableName.CertificateAuthority}.id as count`).first();
+ const countInternalCas = async (orgId?: string): Promise<number> => {
+ try {
+ const row = await $internalCas(orgId).count(`${TableName.CertificateAuthority}.id as count`).first();
return toCount(row);
} catch (error) {
throw new DatabaseError({ error, name: "Count internal CAs for usage" });
@@ -257,8 +261,6 @@ export const usageCounterDALFactory = (db: TDbClient) => {
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
@@ -331,21 +333,9 @@ export const usageCounterDALFactory = (db: TDbClient) => {
}
};
- // 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))
+ const rows = (await $internalCas(orgId)
.groupBy(`${TableName.Project}.orgId`)
.select({ orgId: `${TableName.Project}.orgId` })
.count(`${TableName.CertificateAuthority}.id as count`)) as {
diff --git a/backend/src/services/license-client/usage/usage-counters.ts b/backend/src/services/license-client/usage/usage-counters.ts
index 5049f0c671..baa60cb145 100644
--- a/backend/src/services/license-client/usage/usage-counters.ts
+++ b/backend/src/services/license-client/usage/usage-counters.ts
@@ -21,9 +21,7 @@ export type TMeteredFeature = {
resolveReportOrgId?: (orgId: string) => Promise<string>;
};
-// Static list of every metered dimension key (no DAL needed). For callers that only need the keys, not
-// the count fns — e.g. background reconciliation emitting one event per dimension for an org.
-export const METERED_DIMENSION_KEYS: string[] = [
+const METERED_FEATURES = [
IdentitiesMeter,
InternalCas,
ActiveCerts,
@@ -31,7 +29,11 @@ export const METERED_DIMENSION_KEYS: string[] = [
SecretIdentities,
PamIdentities,
UserIdentities
-].map((feature) => feature.key);
+] as const;
+
+export type TMeteredDimensionKey = (typeof METERED_FEATURES)[number]["key"];
+
+export const METERED_DIMENSION_KEYS: TMeteredDimensionKey[] = METERED_FEATURES.map((feature) => feature.key);
type TBuildMeteredFeaturesDep = {
licenseDAL: Pick<TLicenseDALFactory, "countOrgUsersAndIdentities" | "countOfOrgMembers">;
diff --git a/frontend/src/components/v3/generic/Combobox/Combobox.stories.tsx b/frontend/src/components/v3/generic/Combobox/Combobox.stories.tsx
index 185fd13b72..978c648991 100644
--- a/frontend/src/components/v3/generic/Combobox/Combobox.stories.tsx
+++ b/frontend/src/components/v3/generic/Combobox/Combobox.stories.tsx
@@ -1,6 +1,8 @@
-import { createContext, type ReactNode, useContext, useState } from "react";
+import { createContext, type ReactNode, useContext, useEffect, useState } from "react";
import type { Meta, StoryObj } from "@storybook/react-vite";
+import { useDebounce } from "@app/hooks";
+
import { Button } from "../Button";
import {
Dialog,
@@ -140,6 +142,91 @@ export const Default: Story = {
render: () => <DefaultRender />
};
+const ALL_ORGANIZATIONS = Array.from({ length: 2_000 }, (_, index) => ({
+ id: `org-${index + 1}`,
+ name: `Organization ${index + 1}`
+}));
+
+const PAGE_SIZE = 25;
+
+// Stands in for a paginated list endpoint: matches server-side and returns only the first page.
+const fetchOrganizations = (search: string) =>
+ new Promise<{ organizations: typeof ALL_ORGANIZATIONS; totalCount: number }>((resolve) => {
+ setTimeout(() => {
+ const query = search.trim().toLocaleLowerCase();
+ const matches = ALL_ORGANIZATIONS.filter((org) =>
+ org.name.toLocaleLowerCase().includes(query)
+ );
+ resolve({ organizations: matches.slice(0, PAGE_SIZE), totalCount: matches.length });
+ }, 400);
+ });
+
+const ServerSearchRender = () => {
+ const [value, setValue] = useState<(typeof ALL_ORGANIZATIONS)[number] | null>(null);
+ const [search, setSearch] = useState("");
+ const [debouncedSearch] = useDebounce(search);
+ const [organizations, setOrganizations] = useState<typeof ALL_ORGANIZATIONS>([]);
+ const [totalCount, setTotalCount] = useState(0);
+ const [isLoading, setIsLoading] = useState(true);
+
+ useEffect(() => {
+ let isCurrent = true;
+ setIsLoading(true);
+ fetchOrganizations(debouncedSearch).then((page) => {
+ if (!isCurrent) return;
+ setOrganizations(page.organizations);
+ setTotalCount(page.totalCount);
+ setIsLoading(false);
+ });
+ return () => {
+ isCurrent = false;
+ };
+ }, [debouncedSearch]);
+
+ return (
+ <Field>
+ <FieldLabel htmlFor="combobox-server-search">Organization</FieldLabel>
+ <StoryCombobox
+ id="combobox-server-search"
+ options={organizations}
+ value={value}
+ onValueChange={setValue}
+ onClear={() => setValue(null)}
+ onSearchChange={setSearch}
+ isLoading={isLoading}
+ getOptionValue={(option) => option.id}
+ getOptionLabel={(option) => option.name}
+ placeholder="Select organization..."
+ searchPlaceholder="Search organizations..."
+ searchAriaLabel="Search organizations"
+ emptyMessage="No organizations match that search."
+ listFooter={
+ totalCount > organizations.length
+ ? `Showing ${organizations.length} of ${totalCount.toLocaleString()} — type to search the rest`
+ : null
+ }
+ />
+ </Field>
+ );
+};
+
+/**
+ * Passing `onSearchChange` hands filtering to the caller: the internal matcher is switched off
+ * and `options` renders exactly as given. Use it when the option set is too large to send in
+ * full, so the popup shows one page of server results and typing fetches the next one. Debounce
+ * the query on your side, and pair it with `isLoading` so the popup says it is still working.
+ *
+ * It also turns off the auto-highlight that local filtering uses: the list arrives after a debounce
+ * and a round trip, so highlighting the top match would put it on a row the user has not seen yet and
+ * Enter would commit it. Pair the prop with `listFooter` to say that the list is only one page.
+ *
+ * This story searches 2,000 organizations through a fake endpoint that returns 25 at a time.
+ * Without `onSearchChange` the component would only ever match within those 25.
+ */
+export const ServerSearch: Story = {
+ render: () => <ServerSearchRender />
+};
+
const RichOptionsRender = () => {
const [value, setValue] = useState<(typeof ORGANIZATION_ROLES)[number] | null>(
ORGANIZATION_ROLES[1]
diff --git a/frontend/src/components/v3/generic/Combobox/Combobox.tsx b/frontend/src/components/v3/generic/Combobox/Combobox.tsx
index 0466ee1492..e3bd1a0d8a 100644
--- a/frontend/src/components/v3/generic/Combobox/Combobox.tsx
+++ b/frontend/src/components/v3/generic/Combobox/Combobox.tsx
@@ -17,6 +17,8 @@ type ComboboxSharedProps<TOption> = {
getOptionLabel: (option: TOption) => string;
getOptionKeywords?: (option: TOption) => readonly string[];
isOptionDisabled?: (option: TOption) => boolean;
+ onSearchChange?: (search: string) => void;
+ listFooter?: React.ReactNode;
renderOption?: (option: TOption, state: ComboboxRenderOptionState) => React.ReactNode;
renderValue?: (option: TOption) => React.ReactNode;
clearAriaLabel?: string;
@@ -80,7 +82,8 @@ const preventComboboxFormSubmit = (event: React.KeyboardEvent<HTMLInputElement>)
const useComboboxItems = <TOption,>(
options: readonly TOption[],
selectedOptions: readonly TOption[],
- getOptionValue: (option: TOption) => string
+ getOptionValue: (option: TOption) => string,
+ keepUnlistedSelection: boolean
) =>
React.useMemo(() => {
const selectedByValue = new Map(
@@ -93,12 +96,14 @@ const useComboboxItems = <TOption,>(
return selectedByValue.get(optionValue) ?? option;
});
- selectedOptions.forEach((option) => {
- if (!optionValues.has(getOptionValue(option))) stableOptions.push(option);
- });
+ if (keepUnlistedSelection) {
+ selectedOptions.forEach((option) => {
+ if (!optionValues.has(getOptionValue(option))) stableOptions.push(option);
+ });
+ }
return stableOptions;
- }, [getOptionValue, options, selectedOptions]);
+ }, [getOptionValue, keepUnlistedSelection, options, selectedOptions]);
type ComboboxListProps<TOption> = Pick<
ComboboxSharedProps<TOption>,
@@ -169,6 +174,10 @@ const ComboboxList = <TOption,>({
</>
);
+const ComboboxListFooter = ({ children }: { children: React.ReactNode }) => (
+ <div className="border-t border-border px-3 py-2 text-xs text-muted">{children}</div>
+);
+
type ComboboxSelectAllProps = {
areAllSelected: boolean;
optionCount: number;
@@ -268,6 +277,8 @@ const SingleCombobox = <TOption,>({
getOptionLabel,
getOptionKeywords,
isOptionDisabled,
+ onSearchChange,
+ listFooter,
renderOption,
renderValue,
onClear,
@@ -291,17 +302,30 @@ const SingleCombobox = <TOption,>({
const inputRef = React.useRef<HTMLInputElement | null>(null);
const [open, setOpen] = React.useState(false);
const selectedOptions = React.useMemo(() => (value == null ? [] : [value]), [value]);
- const items = useComboboxItems(options, selectedOptions, getOptionValue);
- const filter = useComboboxFilter({ getOptionKeywords, getOptionLabel });
+ const items = useComboboxItems(options, selectedOptions, getOptionValue, !onSearchChange);
+ const localFilter = useComboboxFilter({ getOptionKeywords, getOptionLabel });
+
+ const filter = onSearchChange ? null : localFilter;
const selectedValues = React.useMemo(
() => new Set(value == null ? [] : [getOptionValue(value)]),
[getOptionValue, value]
);
+ const stableValueRef = React.useRef<TOption | null>(null);
+ if (value == null) {
+ stableValueRef.current = null;
+ } else if (
+ stableValueRef.current == null ||
+ getOptionValue(stableValueRef.current) !== getOptionValue(value)
+ ) {
+ stableValueRef.current = value;
+ }
+ const selectedValue = onSearchChange ? stableValueRef.current : (value ?? null);
+
return (
<ComboboxPrimitive.Root<TOption, false>
items={items}
- value={value ?? null}
+ value={selectedValue}
onValueChange={(nextValue, eventDetails) => {
if (nextValue == null) {
if (eventDetails.reason === "clear-press") onClear?.();
@@ -311,6 +335,11 @@ const SingleCombobox = <TOption,>({
}}
open={open}
onOpenChange={setOpen}
+ onInputValueChange={(nextSearch, eventDetails) => {
+ if (eventDetails.reason === "input-change" || eventDetails.reason === "input-clear") {
+ onSearchChange?.(nextSearch);
+ }
+ }}
itemToStringLabel={getOptionLabel}
itemToStringValue={getOptionValue}
isItemEqualToValue={(option, selectedOption) =>
@@ -319,7 +348,7 @@ const SingleCombobox = <TOption,>({
filter={filter}
disabled={isDisabled}
modal={modal}
- autoHighlight
+ autoHighlight={!onSearchChange}
>
<div className="relative w-full">
<ComboboxPrimitive.Input
@@ -400,6 +429,7 @@ const SingleCombobox = <TOption,>({
selectedValues={selectedValues}
maxHeight={SINGLE_LIST_MAX_HEIGHT}
/>
+ {listFooter && <ComboboxListFooter>{listFooter}</ComboboxListFooter>}
</ComboboxPopup>
</ComboboxPrimitive.Root>
);
@@ -413,6 +443,8 @@ const MultipleCombobox = <TOption,>({
getOptionLabel,
getOptionKeywords,
isOptionDisabled,
+ onSearchChange,
+ listFooter,
renderOption,
renderValue,
onClear,
@@ -443,18 +475,26 @@ const MultipleCombobox = <TOption,>({
const [open, setOpen] = React.useState(false);
const [search, setSearch] = React.useState("");
const selectedOptions = React.useMemo(() => [...value], [value]);
- const items = useComboboxItems(options, selectedOptions, getOptionValue);
- const filter = useComboboxFilter({ getOptionKeywords, getOptionLabel });
+ const items = useComboboxItems(options, selectedOptions, getOptionValue, !onSearchChange);
+ const localFilter = useComboboxFilter({ getOptionKeywords, getOptionLabel });
+ const filter = onSearchChange ? null : localFilter;
+ const updateSearch = (nextSearch: string) => {
+ setSearch(nextSearch);
+ onSearchChange?.(nextSearch);
+ };
const selectedValues = React.useMemo(
() => new Set(value.map(getOptionValue)),
[getOptionValue, value]
);
// Select all only covers the options matching the current search, so a filtered
- // list toggles what is on screen instead of the entire option set.
+ // list toggles what is on screen instead of the entire option set. Under a caller-owned
+ // search the fetched options are already that set.
const selectAllOptions = React.useMemo(
() =>
isSelectAll
- ? items.filter((option) => !isOptionDisabled?.(option) && filter(option, search))
+ ? items.filter(
+ (option) => !isOptionDisabled?.(option) && (filter == null || filter(option, search))
+ )
: [],
[filter, isOptionDisabled, isSelectAll, items, search]
);
@@ -483,7 +523,7 @@ const MultipleCombobox = <TOption,>({
onValueChange={(nextValue, eventDetails) => {
if (eventDetails.reason === "item-press") {
eventDetails.cancel();
- setSearch("");
+ updateSearch("");
setOpen(true);
window.requestAnimationFrame(() => inputRef.current?.focus());
}
@@ -498,10 +538,10 @@ const MultipleCombobox = <TOption,>({
open={open}
onOpenChange={(nextOpen) => {
setOpen(nextOpen);
- if (!nextOpen) setSearch("");
+ if (!nextOpen) updateSearch("");
}}
inputValue={search}
- onInputValueChange={setSearch}
+ onInputValueChange={updateSearch}
itemToStringLabel={getOptionLabel}
itemToStringValue={getOptionValue}
isItemEqualToValue={(option, selectedOption) =>
@@ -510,7 +550,7 @@ const MultipleCombobox = <TOption,>({
filter={filter}
disabled={isDisabled}
modal={modal}
- autoHighlight
+ autoHighlight={!onSearchChange}
>
<ComboboxPrimitive.Chips
ref={chipsRef}
@@ -626,6 +666,7 @@ const MultipleCombobox = <TOption,>({
selectedValues={selectedValues}
maxHeight={MULTIPLE_LIST_MAX_HEIGHT}
/>
+ {listFooter && <ComboboxListFooter>{listFooter}</ComboboxListFooter>}
</ComboboxPopup>
</ComboboxPrimitive.Root>
);
@@ -634,6 +675,8 @@ const MultipleCombobox = <TOption,>({
/**
* Searchable object select built on Base UI. Use `multiple` for the chips-based
* multi-select contract while legacy `FilterableSelect` consumers migrate incrementally.
+ * Options are filtered in the browser unless `onSearchChange` is passed, which hands
+ * filtering to the caller so the list can be fetched a page at a time.
*/
function Combobox<TOption>(props: ComboboxProps<TOption>) {
const { multiple } = props;
diff --git a/frontend/src/hooks/api/billingV2/queries.tsx b/frontend/src/hooks/api/billingV2/queries.tsx
index 834a9bb4f8..b3d5b76725 100644
--- a/frontend/src/hooks/api/billingV2/queries.tsx
+++ b/frontend/src/hooks/api/billingV2/queries.tsx
@@ -1,20 +1,23 @@
-import { useQuery } from "@tanstack/react-query";
+import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import {
BillingV2CatalogProduct,
- BillingV2Organization,
+ BillingV2OrganizationsPage,
BillingV2Overview,
BillingV2UsageBreakdown
} from "./types";
+type BillingV2OrganizationsParams = { search?: string; limit?: number; offset?: number };
+
export const billingV2Keys = {
overview: (orgId: string) => [{ orgId }, "billing-v2-overview"] 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
+ organizations: (orgId: string, params: BillingV2OrganizationsParams) =>
+ [{ orgId, ...params }, "billing-v2-organizations"] as const
};
export const useGetBillingV2Overview = (orgId: string) => {
@@ -49,8 +52,6 @@ export const useGetBillingV2Catalog = (orgId: string) => {
});
};
-// 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 ?? ""),
@@ -58,7 +59,7 @@ export const useGetBillingV2UsageBreakdown = (orgId: string, dimensionKey: strin
const {
data: { breakdown }
} = await apiRequest.get<{ breakdown: BillingV2UsageBreakdown }>(
- `/api/v1/organizations/${orgId}/billing/v2/usage/${dimensionKey}/breakdown`
+ `/api/v1/organizations/${orgId}/billing/v2/breakdowns/${dimensionKey}`
);
return breakdown;
@@ -70,18 +71,23 @@ export const useGetBillingV2UsageBreakdown = (orgId: string, dimensionKey: strin
// 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) => {
+export const useGetBillingV2Organizations = (
+ orgId: string,
+ { search, limit = 100, offset = 0 }: BillingV2OrganizationsParams = {}
+) => {
return useQuery({
- queryKey: billingV2Keys.organizations(orgId),
+ queryKey: billingV2Keys.organizations(orgId, { search, limit, offset }),
queryFn: async () => {
- const {
- data: { organizations }
- } = await apiRequest.get<{ organizations: BillingV2Organization[] }>(
- `/api/v1/organizations/${orgId}/billing/v2/organizations`
+ const { data } = await apiRequest.get<BillingV2OrganizationsPage>(
+ `/api/v1/organizations/${orgId}/billing/v2/organizations`,
+ { params: { search: search || undefined, limit, offset } }
);
- return organizations;
+ return data;
},
- enabled: Boolean(orgId)
+ enabled: Boolean(orgId),
+ // Searching replaces the query key, so without this the popup empties on every keystroke and the
+ // list jumps. Holding the previous page keeps it readable while the next one loads.
+ placeholderData: keepPreviousData
});
};
diff --git a/frontend/src/hooks/api/billingV2/types.ts b/frontend/src/hooks/api/billingV2/types.ts
index 3b5faae893..bde73de69f 100644
--- a/frontend/src/hooks/api/billingV2/types.ts
+++ b/frontend/src/hooks/api/billingV2/types.ts
@@ -311,7 +311,6 @@ 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",
@@ -328,9 +327,6 @@ export type BillingV2BreakdownProject = {
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;
@@ -340,23 +336,22 @@ export type BillingV2BreakdownScope = {
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.
+ scopedCount: number;
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;
};
+
+export type BillingV2OrganizationsPage = {
+ organizations: BillingV2Organization[];
+ totalCount: number;
+};
diff --git a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
index 5021daf0ce..2473f47371 100644
--- a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
@@ -11,6 +11,7 @@ import {
useOrganization,
useOrgPermission
} from "@app/context";
+import { useDebounce } from "@app/hooks";
import {
useAddBillingV2PaymentMethod,
useCreateBillingV2PortalSession,
@@ -36,6 +37,9 @@ import { BillingV2RenderState } from "./billing-v2-view-types";
const CONTACT_SALES_URL = "https://infisical.com/talk-to-us";
+// One popup's worth of organizations. The rest are reached by searching, which the picker's footer says.
+const ORG_PAGE_SIZE = 10;
+
// `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 =
@@ -52,19 +56,23 @@ export const BillingV2Page = () => {
OrgPermissionSubjects.Billing
);
- // 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);
+ // The picker searches server-side: the instance's root organizations are listed a page at a time,
+ // so an organization past the page is reachable only by name. Short enough that the popup does not
+ // scroll, since the answer to a long list here is to search it, not to wade through it.
+ const [orgSearch, setOrgSearch] = useState("");
+ const [debouncedOrgSearch] = useDebounce(orgSearch);
+ const { data: orgPage, isFetching: isRootOrgsFetching } = useGetBillingV2Organizations(orgId, {
+ search: debouncedOrgSearch,
+ limit: ORG_PAGE_SIZE
+ });
+ const rootOrgs = orgPage?.organizations ?? [];
+ const { data: unsearchedOrgPage } = useGetBillingV2Organizations(orgId, { limit: ORG_PAGE_SIZE });
const {
data: serverOverview,
@@ -100,21 +108,17 @@ export const BillingV2Page = () => {
// 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;
+ 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;
+ // More than one organization means the server decided this caller may switch: an instance admin on
+ // self-hosted, where one licence spans every org on the box. Cloud is bounded to the logged-in root
+ // org and always counts one, so this needs no isCloud test, and not reading the overview keeps the
+ // picker on screen while that request is loading or failing.
+ // LOCAL PREVIEW: drop the preview branch and use `unsearchedOrgPage?.totalCount` directly.
+ const rootOrgCount =
+ usePreview && PREVIEW_MODE !== "self-hosted" ? 1 : (unsearchedOrgPage?.totalCount ?? 0);
+ const showOrgFilter = rootOrgCount > 1;
const [flow, setFlow] = useState<BillingV2Flow | null>(null);
const [removeProdId, setRemoveProdId] = useState<string | null>(null);
@@ -178,7 +182,6 @@ 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 });
};
@@ -240,8 +243,11 @@ export const BillingV2Page = () => {
onSetCommitment={onSetCommitment}
onViewBreakdown={onViewBreakdown}
rootOrgs={pickerOrgs}
+ rootOrgCount={rootOrgCount}
+ isRootOrgsLoading={isRootOrgsFetching}
selectedOrgId={selectedOrgId}
onSelectOrg={setSelectedOrgId}
+ onSearchOrgs={setOrgSearch}
showOrgFilter={showOrgFilter}
onUpdatePayment={onUpdatePayment}
onEditDetails={onEditDetails}
diff --git a/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx b/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
index 118f7ce2e8..6db770881a 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
@@ -23,11 +23,12 @@ export type OverviewProps = {
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[];
+ rootOrgCount: number;
+ isRootOrgsLoading: boolean;
selectedOrgId: string;
onSelectOrg: (orgId: string) => void;
+ onSearchOrgs: (search: string) => void;
showOrgFilter: boolean;
onUpdatePayment: () => void;
onEditDetails: () => void;
@@ -48,8 +49,11 @@ export const Overview = ({
onSetCommitment,
onViewBreakdown,
rootOrgs,
+ rootOrgCount,
+ isRootOrgsLoading,
selectedOrgId,
onSelectOrg,
+ onSearchOrgs,
showOrgFilter,
onUpdatePayment,
onEditDetails,
@@ -57,10 +61,15 @@ export const Overview = ({
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} />
+ <RootOrgFilter
+ orgs={rootOrgs}
+ totalCount={rootOrgCount}
+ isLoading={isRootOrgsLoading}
+ value={selectedOrgId}
+ onChange={onSelectOrg}
+ onSearchChange={onSearchOrgs}
+ />
) : null;
if (subState === "loading") {
diff --git a/frontend/src/pages/organization/BillingV2Page/components/RootOrgFilter.tsx b/frontend/src/pages/organization/BillingV2Page/components/RootOrgFilter.tsx
index e94f89c252..579aa6b463 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/RootOrgFilter.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/RootOrgFilter.tsx
@@ -1,44 +1,76 @@
+import { useState } from "react";
import { Building2 } from "lucide-react";
-import { Combobox } from "@app/components/v3";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ Combobox
+} from "@app/components/v3";
import { BillingV2Organization } from "@app/hooks/api";
type RootOrgFilterProps = {
orgs: BillingV2Organization[];
value: string;
onChange: (orgId: string) => void;
+ onSearchChange: (search: string) => void;
+ totalCount: number;
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>
-);
+export const RootOrgFilter = ({
+ orgs,
+ value,
+ onChange,
+ onSearchChange,
+ totalCount,
+ isLoading
+}: RootOrgFilterProps) => {
+ const [lastSelected, setLastSelected] = useState<BillingV2Organization | null>(null);
+ const orgInPage = orgs.find((org) => org.id === value) ?? null;
+ if (orgInPage && orgInPage.id !== lastSelected?.id) {
+ setLastSelected(orgInPage);
+ }
+ const selectedOrg = orgInPage ?? (lastSelected?.id === value ? lastSelected : null);
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ <Building2 className="size-4 text-org" />
+ Organization
+ </CardTitle>
+ <CardDescription>
+ This instance&apos;s licence covers every organization on it. Pick one to see the usage it
+ contributes.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <Combobox<BillingV2Organization>
+ id="billing-root-org-filter"
+ placeholder="Select an organization..."
+ searchPlaceholder="Search organizations..."
+ searchAriaLabel="Search root organizations"
+ isLoading={isLoading}
+ options={orgs}
+ value={selectedOrg}
+ onValueChange={(option) => onChange(option.id)}
+ onSearchChange={onSearchChange}
+ getOptionValue={(option) => option.id}
+ getOptionLabel={(option) => option.name}
+ emptyMessage="No organizations found"
+ listFooter={
+ totalCount > orgs.length
+ ? `Showing ${orgs.length.toLocaleString()} of ${totalCount.toLocaleString()}. Type in the input to search.`
+ : null
+ }
+ />
+ </CardContent>
+ </Card>
+ );
+};
diff --git a/frontend/src/pages/organization/BillingV2Page/components/UsageBreakdownSheet.tsx b/frontend/src/pages/organization/BillingV2Page/components/UsageBreakdownSheet.tsx
index 85aa0c2b8b..e153d7df69 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/UsageBreakdownSheet.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/UsageBreakdownSheet.tsx
@@ -63,8 +63,6 @@ const sentenceCase = (value: string) => value.charAt(0).toUpperCase() + value.sl
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;
};
@@ -86,22 +84,13 @@ const Meter = ({ className, width, height = "h-1.5" }: MeterProps) => (
type ScopeRowProps = {
scope: BillingV2BreakdownScope;
- // Total across every scope, so each row's bar is drawn to the same scale.
- machineCount: number;
+ scopedCount: 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 ScopeRow = ({ scope, scopedCount, unitLabel, hasProjectDetail }: ScopeRowProps) => {
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"}`;
@@ -116,9 +105,9 @@ const ScopeRow = ({ scope, machineCount, unitLabel, hasProjectDetail }: ScopeRow
<span className="truncate">{scope.name}</span>
{scope.isRoot && <Badge variant="org">Root org</Badge>}
</span>
- <CountShare count={scope.count} total={machineCount} unitLabel={unitLabel} />
+ <CountShare count={scope.count} total={scopedCount} unitLabel={unitLabel} />
</div>
- <Meter className={scopeTint} width={pct(scope.count, machineCount)} />
+ <Meter className={scopeTint} width={pct(scope.count, scopedCount)} />
</div>
);
@@ -143,7 +132,6 @@ const ScopeRow = ({ scope, machineCount, unitLabel, hasProjectDetail }: ScopeRow
<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>
@@ -165,7 +153,6 @@ const ScopeRow = ({ scope, machineCount, unitLabel, hasProjectDetail }: ScopeRow
{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>
@@ -199,18 +186,13 @@ const BreakdownBody = ({ breakdown }: { breakdown: BillingV2UsageBreakdown }) =>
const [query, setQuery] = useState("");
const [sort, setSort] = useState<SortOrder>("count");
- const { total, userCount, machineCount, unit, hasProjectDetail, scopes } = breakdown;
+ const { total, userCount, scopedCount, 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 = [
@@ -242,8 +224,6 @@ const BreakdownBody = ({ breakdown }: { breakdown: BillingV2UsageBreakdown }) =>
<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>{" "}
@@ -251,14 +231,14 @@ const BreakdownBody = ({ breakdown }: { breakdown: BillingV2UsageBreakdown }) =>
</span>
<span className="text-border">·</span>
<span>
- <span className="font-semibold text-foreground">{machineCount.toLocaleString()}</span>{" "}
+ <span className="font-semibold text-foreground">{scopedCount.toLocaleString()}</span>{" "}
{unitLabel}
</span>
</div>
)}
</div>
- {machineCount === 0 ? (
+ {scopedCount === 0 ? (
<Empty className="border">
<EmptyHeader>
<EmptyTitle>Nothing counted yet</EmptyTitle>
@@ -280,19 +260,18 @@ const BreakdownBody = ({ breakdown }: { breakdown: BillingV2UsageBreakdown }) =>
<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()}
+ {scopedCount.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) }}
+ style={{ width: pct(rootScope.count, scopedCount) }}
/>
- {/* 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" }}
+ style={{ width: pct(subOrgCount, scopedCount), animationDelay: "60ms" }}
/>
</div>
<div className="flex flex-wrap items-center gap-x-5 gap-y-1 text-xs text-accent">
@@ -317,7 +296,7 @@ const BreakdownBody = ({ breakdown }: { breakdown: BillingV2UsageBreakdown }) =>
{rootScope && (
<ScopeRow
scope={rootScope}
- machineCount={machineCount}
+ scopedCount={scopedCount}
unitLabel={unitLabel}
hasProjectDetail={hasProjectDetail}
/>
@@ -337,8 +316,6 @@ const BreakdownBody = ({ breakdown }: { breakdown: BillingV2UsageBreakdown }) =>
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"
@@ -373,7 +350,7 @@ const BreakdownBody = ({ breakdown }: { breakdown: BillingV2UsageBreakdown }) =>
<ScopeRow
key={scope.orgId}
scope={scope}
- machineCount={machineCount}
+ scopedCount={scopedCount}
unitLabel={unitLabel}
hasProjectDetail={hasProjectDetail}
/>
@@ -395,9 +372,6 @@ type UsageBreakdownSheetProps = {
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,
diff --git a/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx b/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx
index e6a6f4f194..2aa459b728 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx
@@ -85,7 +85,6 @@ 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.
@@ -170,8 +169,6 @@ 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)}
@@ -180,9 +177,6 @@ const ActiveProductCard = ({
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
@@ -192,7 +186,14 @@ const ActiveProductCard = ({
)}
{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">
+ <div
+ className={cn(
+ "-mx-4 -mb-4 flex items-center justify-between gap-3 border-t border-border bg-warning/5 px-4 py-2.5",
+ // Sitting under the breakdown strip, -mt-3 cancels the card's gap-3 so the two full-bleed
+ // strips meet on one divider and read as a single footer instead of two floating bars.
+ hasBreakdown ? "-mt-3" : "mt-1"
+ )}
+ >
<span className="flex items-center gap-2.5 text-xs text-muted">
<span className="flex size-6 shrink-0 items-center justify-center rounded-md border border-warning/40 text-warning">
<DollarSign className="size-3.5" />