Skip to content

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

feat: added license dal change

=506cc53b5414
diff --git a/backend/e2e-test/license-dal.spec.ts b/backend/e2e-test/license-dal.spec.ts
new file mode 100644
index 0000000000..dbd744e794
--- /dev/null
+++ b/backend/e2e-test/license-dal.spec.ts
@@ -0,0 +1,225 @@
+import { randomUUID } from "node:crypto";
+
+import { Knex } from "knex";
+import { afterAll, beforeAll, describe, expect, test } from "vitest";
+
+import {
+ AccessScope,
+ ProjectType,
+ TableName,
+ TGroupsInsert,
+ TIdentitiesInsert,
+ TIdentityGroupMembershipInsert,
+ TOrganizationsInsert,
+ TProjectsInsert,
+ TUserGroupMembershipInsert,
+ TUsersInsert
+} from "@app/db/schemas";
+import { licenseDALFactory } from "@app/ee/services/license/license-dal";
+
+declare const testDb: Knex;
+
+const licenseDAL = licenseDALFactory(testDb);
+
+// Fixed ids for the two orgs under test so cleanup is trivial.
+const ROOT_ORG_ID = randomUUID();
+const SUB_ORG_ID = randomUUID();
+const suffix = randomUUID().slice(0, 8);
+
+const ids = {
+ // users
+ u1: randomUUID(), // SM project (direct) -> counted
+ u2: randomUUID(), // PAM project only -> not counted
+ u3: randomUUID(), // projectless -> counted
+ u4: randomUUID(), // KMS project via group -> counted
+ u5: randomUUID(), // ghost, projectless -> not counted
+ u6: randomUUID(), // not accepted, projectless -> not counted
+ u7: randomUUID(), // SM + PAM -> counted once
+ u8: randomUUID(), // only a PENDING group into SM -> not a counted member, falls through to projectless (counted)
+ u9: randomUUID(), // PKI (cert-manager) project only -> not counted
+ u10: randomUUID(), // soft-deleted SM project + live PAM -> not counted (deleted project ignored, PAM doesn't count)
+ // identities
+ i1: randomUUID(), // SM project (direct) -> counted
+ i2: randomUUID(), // PAM project only -> not counted
+ i3: randomUUID(), // projectless (root org) -> counted
+ i4: randomUUID(), // KMS project via group -> counted
+ i5: randomUUID(), // projectless, in the SUB-ORG -> counted (proves sub-org rollup)
+ // projects
+ pSm: randomUUID(),
+ pKms: randomUUID(),
+ pPam: randomUUID(),
+ pCert: randomUUID(),
+ pSmDeleted: randomUUID(),
+ // groups
+ gLive: randomUUID(), // assigned to the KMS project, non-pending members
+ gPending: randomUUID() // assigned to the SM project, pending member
+};
+
+const orgMembership = (userId: string, orgId = ROOT_ORG_ID) => ({
+ id: randomUUID(),
+ scope: AccessScope.Organization,
+ scopeOrgId: orgId,
+ actorUserId: userId
+});
+
+const projectMembership = (
+ actor: { userId?: string; identityId?: string; groupId?: string },
+ projectId: string,
+ orgId = ROOT_ORG_ID
+) => ({
+ id: randomUUID(),
+ scope: AccessScope.Project,
+ scopeOrgId: orgId,
+ scopeProjectId: projectId,
+ actorUserId: actor.userId ?? null,
+ actorIdentityId: actor.identityId ?? null,
+ actorGroupId: actor.groupId ?? null
+});
+
+describe("license-dal billable org-actor count", () => {
+ beforeAll(async () => {
+ // Rows are held in typed consts rather than inline literals: the generated *Insert types omit the
+ // immutable `id` key, and TS's excess-property check only fires on fresh object literals, so a
+ // const lets the fixtures set explicit ids to wire relationships up front.
+ const orgRows: (TOrganizationsInsert & { id: string })[] = [
+ { id: ROOT_ORG_ID, name: `root-${suffix}`, slug: `root-${suffix}` },
+ { id: SUB_ORG_ID, name: `sub-${suffix}`, slug: `sub-${suffix}`, rootOrgId: ROOT_ORG_ID }
+ ];
+ await testDb(TableName.Organization).insert(orgRows);
+
+ const userRows: (TUsersInsert & { id: string })[] = [
+ { id: ids.u1, username: `u1-${suffix}`, isAccepted: true, isGhost: false },
+ { id: ids.u2, username: `u2-${suffix}`, isAccepted: true, isGhost: false },
+ { id: ids.u3, username: `u3-${suffix}`, isAccepted: true, isGhost: false },
+ { id: ids.u4, username: `u4-${suffix}`, isAccepted: true, isGhost: false },
+ { id: ids.u5, username: `u5-${suffix}`, isAccepted: true, isGhost: true },
+ { id: ids.u6, username: `u6-${suffix}`, isAccepted: false, isGhost: false },
+ { id: ids.u7, username: `u7-${suffix}`, isAccepted: true, isGhost: false },
+ { id: ids.u8, username: `u8-${suffix}`, isAccepted: true, isGhost: false },
+ { id: ids.u9, username: `u9-${suffix}`, isAccepted: true, isGhost: false },
+ { id: ids.u10, username: `u10-${suffix}`, isAccepted: true, isGhost: false }
+ ];
+ await testDb(TableName.Users).insert(userRows);
+
+ const identityRows: (TIdentitiesInsert & { id: string })[] = [
+ { id: ids.i1, name: `i1-${suffix}`, orgId: ROOT_ORG_ID },
+ { id: ids.i2, name: `i2-${suffix}`, orgId: ROOT_ORG_ID },
+ { id: ids.i3, name: `i3-${suffix}`, orgId: ROOT_ORG_ID },
+ { id: ids.i4, name: `i4-${suffix}`, orgId: ROOT_ORG_ID },
+ { id: ids.i5, name: `i5-${suffix}`, orgId: SUB_ORG_ID }
+ ];
+ await testDb(TableName.Identity).insert(identityRows);
+
+ const projectRows: (TProjectsInsert & { id: string })[] = [
+ { id: ids.pSm, name: `sm-${suffix}`, slug: `sm-${suffix}`, orgId: ROOT_ORG_ID, type: ProjectType.SecretManager },
+ { id: ids.pKms, name: `kms-${suffix}`, slug: `kms-${suffix}`, orgId: ROOT_ORG_ID, type: ProjectType.KMS },
+ { id: ids.pPam, name: `pam-${suffix}`, slug: `pam-${suffix}`, orgId: ROOT_ORG_ID, type: ProjectType.PAM },
+ {
+ id: ids.pCert,
+ name: `cert-${suffix}`,
+ slug: `cert-${suffix}`,
+ orgId: ROOT_ORG_ID,
+ type: ProjectType.CertificateManager
+ },
+ {
+ id: ids.pSmDeleted,
+ name: `sm-del-${suffix}`,
+ slug: `sm-del-${suffix}`,
+ orgId: ROOT_ORG_ID,
+ type: ProjectType.SecretManager,
+ deleteAfter: new Date()
+ }
+ ];
+ await testDb(TableName.Project).insert(projectRows);
+
+ const groupRows: (TGroupsInsert & { id: string })[] = [
+ { id: ids.gLive, orgId: ROOT_ORG_ID, name: `g-live-${suffix}`, slug: `g-live-${suffix}` },
+ { id: ids.gPending, orgId: ROOT_ORG_ID, name: `g-pending-${suffix}`, slug: `g-pending-${suffix}` }
+ ];
+ await testDb(TableName.Groups).insert(groupRows);
+
+ // Org memberships (every real actor belongs to the org). u5/u6 belong too but are filtered as
+ // ghost / unaccepted.
+ await testDb(TableName.Membership).insert([
+ orgMembership(ids.u1),
+ orgMembership(ids.u2),
+ orgMembership(ids.u3),
+ orgMembership(ids.u4),
+ orgMembership(ids.u5),
+ orgMembership(ids.u6),
+ orgMembership(ids.u7),
+ orgMembership(ids.u8),
+ orgMembership(ids.u9),
+ orgMembership(ids.u10)
+ ]);
+
+ // Project memberships (direct).
+ await testDb(TableName.Membership).insert([
+ projectMembership({ userId: ids.u1 }, ids.pSm),
+ projectMembership({ userId: ids.u2 }, ids.pPam),
+ projectMembership({ userId: ids.u7 }, ids.pSm),
+ projectMembership({ userId: ids.u7 }, ids.pPam),
+ projectMembership({ userId: ids.u9 }, ids.pCert),
+ projectMembership({ userId: ids.u10 }, ids.pSmDeleted),
+ projectMembership({ userId: ids.u10 }, ids.pPam),
+ projectMembership({ identityId: ids.i1 }, ids.pSm),
+ projectMembership({ identityId: ids.i2 }, ids.pPam),
+ // Group -> project assignments.
+ projectMembership({ groupId: ids.gLive }, ids.pKms),
+ projectMembership({ groupId: ids.gPending }, ids.pSm)
+ ]);
+
+ // Group memberships: gLive (KMS) has a non-pending user + identity; gPending (SM) has a pending user.
+ const userGroupRows: (TUserGroupMembershipInsert & { id: string })[] = [
+ { id: randomUUID(), userId: ids.u4, groupId: ids.gLive, isPending: false },
+ { id: randomUUID(), userId: ids.u8, groupId: ids.gPending, isPending: true }
+ ];
+ await testDb(TableName.UserGroupMembership).insert(userGroupRows);
+
+ const identityGroupRows: (TIdentityGroupMembershipInsert & { id: string })[] = [
+ { id: randomUUID(), identityId: ids.i4, groupId: ids.gLive }
+ ];
+ await testDb(TableName.IdentityGroupMembership).insert(identityGroupRows);
+ });
+
+ afterAll(async () => {
+ const orgIds = [ROOT_ORG_ID, SUB_ORG_ID];
+ const groupIds = [ids.gLive, ids.gPending];
+ await testDb(TableName.UserGroupMembership).whereIn("groupId", groupIds).delete();
+ await testDb(TableName.IdentityGroupMembership).whereIn("groupId", groupIds).delete();
+ await testDb(TableName.Membership).whereIn("scopeOrgId", orgIds).delete();
+ await testDb(TableName.Groups).whereIn("orgId", orgIds).delete();
+ await testDb(TableName.Identity).whereIn("orgId", orgIds).delete();
+ await testDb(TableName.Project).whereIn("orgId", orgIds).delete();
+ // Sub-org first: rootOrgId FK on the root org.
+ await testDb(TableName.Organization).where("id", SUB_ORG_ID).delete();
+ await testDb(TableName.Organization).where("id", ROOT_ORG_ID).delete();
+ });
+
+ // Billable users: u1 (SM), u4 (KMS via group), u7 (SM+PAM, once), u3 (projectless),
+ // u8 (only a pending group -> projectless). Excluded: u2/u10 (PAM/PKI or deleted-SM), u5 (ghost),
+ // u6 (unaccepted), u9 (PKI).
+ test("countOfOrgMembers counts only billable users", async () => {
+ const count = await licenseDAL.countOfOrgMembers(ROOT_ORG_ID, testDb);
+ expect(count).toBe(5);
+ });
+
+ // Billable identities: i1 (SM), i4 (KMS via group), i3 (projectless root), i5 (projectless sub-org).
+ // Excluded: i2 (PAM only).
+ test("countOfOrgIdentities counts only billable identities, including sub-orgs", async () => {
+ const count = await licenseDAL.countOfOrgIdentities(ROOT_ORG_ID, testDb);
+ expect(count).toBe(4);
+ });
+
+ test("countOrgUsersAndIdentities returns the combined billable total", async () => {
+ const count = await licenseDAL.countOrgUsersAndIdentities(ROOT_ORG_ID, testDb);
+ expect(count).toBe(9);
+ });
+
+ test("scoping to an unrelated org yields zero", async () => {
+ const users = await licenseDAL.countOfOrgMembers(randomUUID(), testDb);
+ const identities = await licenseDAL.countOfOrgIdentities(randomUUID(), testDb);
+ expect(users).toBe(0);
+ expect(identities).toBe(0);
+ });
+});
diff --git a/backend/src/db/migrations/20260723090000_add-org-actor-count-indexes.ts b/backend/src/db/migrations/20260723090000_add-org-actor-count-indexes.ts
new file mode 100644
index 0000000000..d538e4c6b5
--- /dev/null
+++ b/backend/src/db/migrations/20260723090000_add-org-actor-count-indexes.ts
@@ -0,0 +1,53 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+// Two unindexed foreign keys that the billable org-actor count leans on:
+// - organizations.rootOrgId: the count resolves an org plus its sub-orgs via
+// "id = :orgId OR rootOrgId = :orgId"; without this index the OR branch seq-scans
+// every organization.
+// - identities.orgId: the count enumerates an org's identities; without this index it
+// seq-scans the whole identities table.
+// Both feed the identity-creation quota gate on the hot path, so index them.
+const ROOT_ORG_ID_INDEX = "idx_organizations_root_org_id";
+const IDENTITY_ORG_ID_INDEX = "idx_identities_org_id";
+const MIGRATION_TIMEOUT = 60 * 60 * 1000; // 60 minutes
+const MIGRATION_LOCK_TIMEOUT = 30 * 1000; // 30 seconds
+
+export async function up(knex: Knex): Promise<void> {
+ const stmtResult = await knex.raw("SHOW statement_timeout");
+ const originalStatementTimeout = stmtResult.rows[0].statement_timeout;
+ const lockResult = await knex.raw("SHOW lock_timeout");
+ const originalLockTimeout = lockResult.rows[0].lock_timeout;
+
+ try {
+ await knex.raw(`SET statement_timeout = ${MIGRATION_TIMEOUT}`);
+ await knex.raw(`SET lock_timeout = ${MIGRATION_LOCK_TIMEOUT}`);
+
+ if (await knex.schema.hasColumn(TableName.Organization, "rootOrgId")) {
+ await knex.raw(`
+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "${ROOT_ORG_ID_INDEX}"
+ ON ${TableName.Organization} ("rootOrgId")
+ WHERE "rootOrgId" IS NOT NULL
+ `);
+ }
+
+ if (await knex.schema.hasColumn(TableName.Identity, "orgId")) {
+ await knex.raw(`
+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "${IDENTITY_ORG_ID_INDEX}"
+ ON ${TableName.Identity} ("orgId")
+ `);
+ }
+ } finally {
+ await knex.raw(`SET statement_timeout = '${originalStatementTimeout}'`);
+ await knex.raw(`SET lock_timeout = '${originalLockTimeout}'`);
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await knex.raw(`DROP INDEX CONCURRENTLY IF EXISTS "${ROOT_ORG_ID_INDEX}"`);
+ await knex.raw(`DROP INDEX CONCURRENTLY IF EXISTS "${IDENTITY_ORG_ID_INDEX}"`);
+}
+
+const config = { transaction: false };
+export { config };
diff --git a/backend/src/ee/services/license/license-dal.ts b/backend/src/ee/services/license/license-dal.ts
index 66895401b5..c4a5c12548 100644
--- a/backend/src/ee/services/license/license-dal.ts
+++ b/backend/src/ee/services/license/license-dal.ts
@@ -1,28 +1,184 @@
import { Knex } from "knex";
import { TDbClient } from "@app/db";
-import { AccessScope, TableName } from "@app/db/schemas";
+import { AccessScope, ProjectType, TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
export type TLicenseDALFactory = ReturnType<typeof licenseDALFactory>;
+// A user/identity occupies a billable seat only when it is (a) an org member, and (b) either a member
+// of a Secret-Management-flavoured project (Secret Manager or KMS) or not a member of any project at
+// all. Actors that only live in other project types (PAM, PKI, ...) do not count. Membership can be
+// direct or inherited through a group.
+const COUNTED_PROJECT_TYPES = [ProjectType.SecretManager, ProjectType.KMS];
+
export const licenseDALFactory = (db: TDbClient) => {
+ // Counts billable org actors split by kind. orgId null counts across every org (self-hosted seat
+ // enforcement); a non-null orgId scopes to that root org and its sub-orgs. Both counts fold the
+ // "in a Secret-Management project OR projectless" rule described on COUNTED_PROJECT_TYPES.
+ const countBillableOrgActors = async (
+ orgId: string | null,
+ tx?: Knex
+ ): Promise<{ users: number; identities: number }> => {
+ 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");
+ })
+ .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"),
+ knex.raw("(select count(*) from projectless_users) as projectless_users"),
+ knex.raw("(select count(*) from projectless_identities) as projectless_identities")
+ )
+ .first()) as
+ | {
+ counted_users?: string | number;
+ counted_identities?: string | number;
+ projectless_users?: string | number;
+ projectless_identities?: string | number;
+ }
+ | undefined;
+
+ return {
+ users: Number(row?.counted_users ?? 0) + Number(row?.projectless_users ?? 0),
+ identities: Number(row?.counted_identities ?? 0) + Number(row?.projectless_identities ?? 0)
+ };
+ };
+
const countOfOrgMembers = async (orgId: string | null, tx?: Knex) => {
try {
- const doc = await (tx || db.replicaNode())(TableName.Membership)
- .join(TableName.Organization, `${TableName.Organization}.id`, `${TableName.Membership}.scopeOrgId`)
- .where({ scope: AccessScope.Organization })
- .andWhere((bd) => {
- if (orgId) {
- void bd.where(`${TableName.Membership}.scopeOrgId`, orgId);
- }
- })
- .join(TableName.Users, `${TableName.Membership}.actorUserId`, `${TableName.Users}.id`)
- .where(`${TableName.Users}.isGhost`, false)
- .where(`${TableName.Users}.isAccepted`, true)
- .whereNull(`${TableName.Organization}.rootOrgId`)
- .count();
- return Number(doc?.[0]?.count ?? 0);
+ const { users } = await countBillableOrgActors(orgId, tx);
+ return users;
} catch (error) {
throw new DatabaseError({ error, name: "Count of Org Members" });
}
@@ -30,57 +186,17 @@ export const licenseDALFactory = (db: TDbClient) => {
const countOfOrgIdentities = async (orgId: string | null, tx?: Knex) => {
try {
- // count org identities
- const identityDoc = await (tx || db.replicaNode())(TableName.Identity)
- .join(TableName.Organization, `${TableName.Identity}.orgId`, `${TableName.Organization}.id`)
- .where((bd) => {
- if (orgId) {
- void bd.where(`${TableName.Organization}.rootOrgId`, orgId).orWhere(`${TableName.Organization}.id`, orgId);
- }
- })
- .count();
-
- const identityCount = Number(identityDoc?.[0].count);
-
- return identityCount;
+ const { identities } = await countBillableOrgActors(orgId, tx);
+ return identities;
} catch (error) {
- throw new DatabaseError({ error, name: "Count of Org Users + Identities" });
+ throw new DatabaseError({ error, name: "Count of Org Identities" });
}
};
const countOrgUsersAndIdentities = async (orgId: string | null, tx?: Knex) => {
try {
- // count org users
- const userDoc = await (tx || db.replicaNode())(TableName.Membership)
- .join(TableName.Organization, `${TableName.Organization}.id`, `${TableName.Membership}.scopeOrgId`)
- .where({ scope: AccessScope.Organization })
- .whereNotNull(`${TableName.Membership}.actorUserId`)
- .andWhere((bd) => {
- if (orgId) {
- void bd.where(`${TableName.Membership}.scopeOrgId`, orgId);
- }
- })
- .join(TableName.Users, `${TableName.Membership}.actorUserId`, `${TableName.Users}.id`)
- .where(`${TableName.Users}.isGhost`, false)
- .where(`${TableName.Users}.isAccepted`, true)
- .whereNull(`${TableName.Organization}.rootOrgId`)
- .count();
-
- const userCount = Number(userDoc?.[0].count);
-
- // count org identities
- const identityDoc = await (tx || db.replicaNode())(TableName.Identity)
- .join(TableName.Organization, `${TableName.Identity}.orgId`, `${TableName.Organization}.id`)
- .where((bd) => {
- if (orgId) {
- void bd.where(`${TableName.Organization}.rootOrgId`, orgId).orWhere(`${TableName.Organization}.id`, orgId);
- }
- })
- .count();
-
- const identityCount = Number(identityDoc?.[0].count);
-
- return userCount + identityCount;
+ const { users, identities } = await countBillableOrgActors(orgId, tx);
+ return users + identities;
} catch (error) {
throw new DatabaseError({ error, name: "Count of Org Users + Identities" });
}