Reorganize repo structure and standards references
This commit is contained in:
1 parent
3cb93a81be
commit
be2054274d
5885 files changed
+2588
-195
No files matched your search
+145
@@ -0,0 +1,145 @@
|
||||
// @vitest-environment node
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import pg from "pg";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
// Resolve the repo root from this file's location so the SQL artifacts load
|
||||
// regardless of the cwd vitest runs under (root vs the @toolctrl/web package dir).
|
||||
// This file lives at apps/web/app/utils/db/.server/ → six segments below root.
|
||||
const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../../../..");
|
||||
|
||||
// AK-P4a — FILE RLS GATE PROOF. Companion to R-P2b's rls-tenant-isolation
|
||||
// integration test: proves that once the File RLS block
|
||||
// (local/AK-P4a-merge-migration.sql) is applied, the restricted hivegrid_app role
|
||||
// (NOSUPERUSER, NOBYPASSRLS) is confined to its own tenant's File / FileEntityLink
|
||||
// rows, sees nothing without a tenant context, and is blocked by WITH CHECK from
|
||||
// writing cross-tenant rows. This is what makes the P5 activation a pure switch:
|
||||
// the wrapped fileService.server.ts / worker write-backs already set the GUC, so
|
||||
// flipping RLS on cannot break Files.
|
||||
//
|
||||
// Runs ONLY when RLS_TEST_DATABASE_URL is set (a SUPERUSER connection to a
|
||||
// throwaway DB with the schema pushed). Without it the block is skipped so the
|
||||
// normal unit suite stays green without a DB.
|
||||
//
|
||||
// Setup:
|
||||
// docker run -d --name hg-rls-pg -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=hivegrid -p 5433:5432 pgvector/pgvector:pg16
|
||||
// DIRECT_URL=postgresql://postgres:postgres@localhost:5433/hivegrid pnpm exec prisma db push
|
||||
// RLS_TEST_DATABASE_URL=postgresql://postgres:postgres@localhost:5433/hivegrid pnpm vitest run rls-file-isolation
|
||||
|
||||
const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL;
|
||||
const APP_ROLE = "hivegrid_app";
|
||||
const APP_PASSWORD = "hivegrid_app_pw";
|
||||
|
||||
function appUrlFrom(adminUrl: string): string {
|
||||
const url = new URL(adminUrl);
|
||||
url.username = APP_ROLE;
|
||||
url.password = APP_PASSWORD;
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
const describeIfDb = ADMIN_URL ? describe : describe.skip;
|
||||
|
||||
describeIfDb("File RLS tenant isolation gate proof (File, FileEntityLink)", () => {
|
||||
let admin: pg.Client;
|
||||
let app: pg.Client;
|
||||
|
||||
beforeAll(async () => {
|
||||
admin = new pg.Client({ connectionString: ADMIN_URL });
|
||||
await admin.connect();
|
||||
|
||||
// 1) Base RLS mechanic + restricted role (creates hivegrid_app, NOBYPASSRLS).
|
||||
const baseSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/tenant-isolation.sql"), "utf8");
|
||||
await admin.query(baseSql);
|
||||
// 2) File RLS block: ENABLE/FORCE + tenant_isolation policy + GRANTs on the
|
||||
// four Files tables (the deferred P5 activation artifact, applied here).
|
||||
const fileRlsSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/file-isolation.sql"), "utf8");
|
||||
await admin.query(fileRlsSql);
|
||||
await admin.query(`GRANT CONNECT ON DATABASE ${new URL(ADMIN_URL!).pathname.slice(1)} TO ${APP_ROLE}`);
|
||||
|
||||
// 3) Seed two tenants' files + links as superuser (bypasses RLS). File has no
|
||||
// FK on tenantId/createdByUserId, so no User/Tenant rows are required.
|
||||
await admin.query(`INSERT INTO "File"(id,"updatedAt","tenantId","createdByUserId","displayName","mimeType","sizeBytes","storageKey") VALUES
|
||||
('rls_fileA',now(),'rls_tenantA','rls_userA','a.txt','text/plain',1,'tenants/rls_tenantA/files/rls_fileA/original'),
|
||||
('rls_fileB',now(),'rls_tenantB','rls_userB','b.txt','text/plain',1,'tenants/rls_tenantB/files/rls_fileB/original')
|
||||
ON CONFLICT (id) DO NOTHING`);
|
||||
await admin.query(`INSERT INTO "FileEntityLink"(id,"tenantId","createdByUserId","fileId","entityType","entityId") VALUES
|
||||
('rls_linkA','rls_tenantA','rls_userA','rls_fileA','contact','rls_c1'),
|
||||
('rls_linkB','rls_tenantB','rls_userB','rls_fileB','contact','rls_c2')
|
||||
ON CONFLICT (id) DO NOTHING`);
|
||||
|
||||
app = new pg.Client({ connectionString: appUrlFrom(ADMIN_URL!) });
|
||||
await app.connect();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app?.end();
|
||||
await admin?.end();
|
||||
});
|
||||
|
||||
async function underTenant<T>(tenantId: string, run: () => Promise<T>): Promise<T> {
|
||||
await app.query("BEGIN");
|
||||
try {
|
||||
await app.query("SELECT set_config('app.tenant_id', $1, true)", [tenantId]);
|
||||
const result = await run();
|
||||
await app.query("COMMIT");
|
||||
return result;
|
||||
} catch (error) {
|
||||
await app.query("ROLLBACK");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
it("confirms the app role is neither superuser nor BYPASSRLS", async () => {
|
||||
const { rows } = await admin.query(`SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = $1`, [APP_ROLE]);
|
||||
expect(rows[0]).toMatchObject({ rolsuper: false, rolbypassrls: false });
|
||||
});
|
||||
|
||||
it("under tenant A context, only tenant A files are visible", async () => {
|
||||
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "File" ORDER BY id`)).rows.map((r) => r.id));
|
||||
expect(ids).toEqual(["rls_fileA"]);
|
||||
});
|
||||
|
||||
it("cannot read another tenant's file even with an explicit WHERE filter", async () => {
|
||||
const count = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "File" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c);
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it("sees no files at all when no tenant context is set", async () => {
|
||||
const count = (await app.query(`SELECT count(*)::int AS c FROM "File"`)).rows[0].c;
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it("WITH CHECK blocks inserting a file for a foreign tenant", async () => {
|
||||
await expect(
|
||||
underTenant("rls_tenantA", async () =>
|
||||
app.query(
|
||||
`INSERT INTO "File"(id,"updatedAt","tenantId","createdByUserId","displayName","mimeType","sizeBytes","storageKey")
|
||||
VALUES ('rls_fileX',now(),'rls_tenantB','rls_userB','x.txt','text/plain',1,'tenants/rls_tenantB/files/rls_fileX/original')`,
|
||||
),
|
||||
),
|
||||
).rejects.toThrow(/row-level security/i);
|
||||
});
|
||||
|
||||
it("allows inserting and reading a file for the active tenant", async () => {
|
||||
await underTenant("rls_tenantA", async () => {
|
||||
await app.query(
|
||||
`INSERT INTO "File"(id,"updatedAt","tenantId","createdByUserId","displayName","mimeType","sizeBytes","storageKey")
|
||||
VALUES ('rls_fileA2',now(),'rls_tenantA','rls_userA','a2.txt','text/plain',1,'tenants/rls_tenantA/files/rls_fileA2/original')
|
||||
ON CONFLICT (id) DO NOTHING`,
|
||||
);
|
||||
const ids = (await app.query(`SELECT id FROM "File" ORDER BY id`)).rows.map((r) => r.id);
|
||||
expect(ids).toContain("rls_fileA2");
|
||||
expect(ids).not.toContain("rls_fileB");
|
||||
});
|
||||
});
|
||||
|
||||
it("isolates FileEntityLink rows by tenant as well", async () => {
|
||||
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "FileEntityLink" ORDER BY id`)).rows.map((r) => r.id));
|
||||
expect(ids).toEqual(["rls_linkA"]);
|
||||
const crossCount = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "FileEntityLink" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c);
|
||||
expect(crossCount).toBe(0);
|
||||
});
|
||||
});
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
// @vitest-environment node
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import pg from "pg";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
// Resolve the repo root from this file's location so the SQL artifacts load
|
||||
// regardless of the cwd vitest runs under (root vs the @toolctrl/web package dir).
|
||||
// This file lives at apps/web/app/utils/db/.server/ → six segments below root.
|
||||
const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../../../..");
|
||||
|
||||
// AK-P4b — TASK RLS GATE PROOF. Companion to R-P2b's rls-tenant-isolation and
|
||||
// AK-P4a's rls-file-isolation integration tests: proves that once the Task RLS
|
||||
// block (prisma/rls/task-isolation.sql) is applied, the restricted hivegrid_app
|
||||
// role (NOSUPERUSER, NOBYPASSRLS) is confined to its own tenant's Task /
|
||||
// TaskWatcher / EntityLink rows, sees nothing without a tenant context, and is
|
||||
// blocked by WITH CHECK from writing cross-tenant rows. This is what makes the P5
|
||||
// activation a pure switch: the wrapped taskService/entityLinkService and worker
|
||||
// crons already set the GUC, so flipping RLS on cannot break Tasks.
|
||||
//
|
||||
// Runs ONLY when RLS_TEST_DATABASE_URL is set (a SUPERUSER connection to a
|
||||
// throwaway DB with the schema pushed). Without it the block is skipped so the
|
||||
// normal unit suite stays green without a DB.
|
||||
//
|
||||
// Setup:
|
||||
// docker run -d --name hg-rls-pg -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=hivegrid -p 5433:5432 pgvector/pgvector:pg16
|
||||
// DIRECT_URL=postgresql://postgres:postgres@localhost:5433/hivegrid pnpm exec prisma db push
|
||||
// RLS_TEST_DATABASE_URL=postgresql://postgres:postgres@localhost:5433/hivegrid pnpm vitest run rls-task-isolation
|
||||
|
||||
const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL;
|
||||
const APP_ROLE = "hivegrid_app";
|
||||
const APP_PASSWORD = "hivegrid_app_pw";
|
||||
|
||||
function appUrlFrom(adminUrl: string): string {
|
||||
const url = new URL(adminUrl);
|
||||
url.username = APP_ROLE;
|
||||
url.password = APP_PASSWORD;
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
const describeIfDb = ADMIN_URL ? describe : describe.skip;
|
||||
|
||||
describeIfDb("Task RLS tenant isolation gate proof (Task, TaskWatcher, EntityLink)", () => {
|
||||
let admin: pg.Client;
|
||||
let app: pg.Client;
|
||||
|
||||
beforeAll(async () => {
|
||||
admin = new pg.Client({ connectionString: ADMIN_URL });
|
||||
await admin.connect();
|
||||
|
||||
// 1) Base RLS mechanic + restricted role (creates hivegrid_app, NOBYPASSRLS).
|
||||
const baseSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/tenant-isolation.sql"), "utf8");
|
||||
await admin.query(baseSql);
|
||||
// 2) Task RLS block: ENABLE/FORCE + tenant_isolation policy + GRANTs on the
|
||||
// three Task tables (the deferred P5 activation artifact, applied here).
|
||||
const taskRlsSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/task-isolation.sql"), "utf8");
|
||||
await admin.query(taskRlsSql);
|
||||
await admin.query(`GRANT CONNECT ON DATABASE ${new URL(ADMIN_URL!).pathname.slice(1)} TO ${APP_ROLE}`);
|
||||
|
||||
// 3) Seed two tenants' tasks + watchers + links as superuser (bypasses RLS).
|
||||
// Task/TaskWatcher/EntityLink have no FK on tenantId/createdByUserId
|
||||
// (bare scalars, AD-21), so no User/Tenant/Group rows are required. Each
|
||||
// task carries exactly one assignee (single-assignee rule).
|
||||
await admin.query(`INSERT INTO "Task"(id,"updatedAt","tenantId","createdByUserId","title","assignedToUserId") VALUES
|
||||
('rls_taskA',now(),'rls_tenantA','rls_userA','task A','rls_userA'),
|
||||
('rls_taskB',now(),'rls_tenantB','rls_userB','task B','rls_userB')
|
||||
ON CONFLICT (id) DO NOTHING`);
|
||||
await admin.query(`INSERT INTO "TaskWatcher"(id,"tenantId","taskId","userId") VALUES
|
||||
('rls_watchA','rls_tenantA','rls_taskA','rls_userA'),
|
||||
('rls_watchB','rls_tenantB','rls_taskB','rls_userB')
|
||||
ON CONFLICT (id) DO NOTHING`);
|
||||
await admin.query(`INSERT INTO "EntityLink"(id,"tenantId","createdByUserId","sourceType","sourceId","targetType","targetId") VALUES
|
||||
('rls_linkA','rls_tenantA','rls_userA','task','rls_taskA','contact','rls_c1'),
|
||||
('rls_linkB','rls_tenantB','rls_userB','task','rls_taskB','contact','rls_c2')
|
||||
ON CONFLICT (id) DO NOTHING`);
|
||||
|
||||
app = new pg.Client({ connectionString: appUrlFrom(ADMIN_URL!) });
|
||||
await app.connect();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app?.end();
|
||||
await admin?.end();
|
||||
});
|
||||
|
||||
async function underTenant<T>(tenantId: string, run: () => Promise<T>): Promise<T> {
|
||||
await app.query("BEGIN");
|
||||
try {
|
||||
await app.query("SELECT set_config('app.tenant_id', $1, true)", [tenantId]);
|
||||
const result = await run();
|
||||
await app.query("COMMIT");
|
||||
return result;
|
||||
} catch (error) {
|
||||
await app.query("ROLLBACK");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
it("confirms the app role is neither superuser nor BYPASSRLS", async () => {
|
||||
const { rows } = await admin.query(`SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = $1`, [APP_ROLE]);
|
||||
expect(rows[0]).toMatchObject({ rolsuper: false, rolbypassrls: false });
|
||||
});
|
||||
|
||||
it("under tenant A context, only tenant A tasks are visible", async () => {
|
||||
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "Task" ORDER BY id`)).rows.map((r) => r.id));
|
||||
expect(ids).toEqual(["rls_taskA"]);
|
||||
});
|
||||
|
||||
it("cannot read another tenant's task even with an explicit WHERE filter", async () => {
|
||||
const count = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "Task" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c);
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it("sees no tasks at all when no tenant context is set", async () => {
|
||||
const count = (await app.query(`SELECT count(*)::int AS c FROM "Task"`)).rows[0].c;
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it("WITH CHECK blocks inserting a task for a foreign tenant", async () => {
|
||||
await expect(
|
||||
underTenant("rls_tenantA", async () =>
|
||||
app.query(
|
||||
`INSERT INTO "Task"(id,"updatedAt","tenantId","createdByUserId","title","assignedToUserId")
|
||||
VALUES ('rls_taskX',now(),'rls_tenantB','rls_userB','x','rls_userB')`,
|
||||
),
|
||||
),
|
||||
).rejects.toThrow(/row-level security/i);
|
||||
});
|
||||
|
||||
it("allows inserting and reading a task for the active tenant", async () => {
|
||||
await underTenant("rls_tenantA", async () => {
|
||||
await app.query(
|
||||
`INSERT INTO "Task"(id,"updatedAt","tenantId","createdByUserId","title","assignedToUserId")
|
||||
VALUES ('rls_taskA2',now(),'rls_tenantA','rls_userA','a2','rls_userA')
|
||||
ON CONFLICT (id) DO NOTHING`,
|
||||
);
|
||||
const ids = (await app.query(`SELECT id FROM "Task" ORDER BY id`)).rows.map((r) => r.id);
|
||||
expect(ids).toContain("rls_taskA2");
|
||||
expect(ids).not.toContain("rls_taskB");
|
||||
});
|
||||
});
|
||||
|
||||
it("isolates TaskWatcher rows by tenant as well", async () => {
|
||||
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "TaskWatcher" ORDER BY id`)).rows.map((r) => r.id));
|
||||
expect(ids).toEqual(["rls_watchA"]);
|
||||
const crossCount = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "TaskWatcher" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c);
|
||||
expect(crossCount).toBe(0);
|
||||
});
|
||||
|
||||
it("isolates EntityLink rows by tenant as well", async () => {
|
||||
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "EntityLink" ORDER BY id`)).rows.map((r) => r.id));
|
||||
expect(ids).toEqual(["rls_linkA"]);
|
||||
const crossCount = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "EntityLink" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c);
|
||||
expect(crossCount).toBe(0);
|
||||
});
|
||||
});
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
// @vitest-environment node
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import pg from "pg";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
// R-P2b — RLS-GATE-BEWEIS (AD-1): belegt gegen eine echte Postgres, dass mandantenuebergreifender
|
||||
// Zugriff DB-seitig verhindert ist. Laeuft NUR, wenn RLS_TEST_DATABASE_URL gesetzt ist (Superuser-
|
||||
// Verbindung zu einer Wegwerf-DB mit dem gepushten Schema). Ohne die Variable wird der Block
|
||||
// uebersprungen, damit die normale Unit-Suite ohne DB gruen bleibt.
|
||||
//
|
||||
// Setup:
|
||||
// docker run -d --name hg-rls-pg -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=hivegrid -p 5433:5432 pgvector/pgvector:pg16
|
||||
// DIRECT_URL=postgresql://postgres:postgres@localhost:5433/hivegrid pnpm exec prisma db push
|
||||
// RLS_TEST_DATABASE_URL=postgresql://postgres:postgres@localhost:5433/hivegrid pnpm vitest run rls-tenant-isolation
|
||||
|
||||
const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL;
|
||||
const APP_ROLE = "hivegrid_app";
|
||||
const APP_PASSWORD = "hivegrid_app_pw";
|
||||
|
||||
function appUrlFrom(adminUrl: string): string {
|
||||
const url = new URL(adminUrl);
|
||||
url.username = APP_ROLE;
|
||||
url.password = APP_PASSWORD;
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
const describeIfDb = ADMIN_URL ? describe : describe.skip;
|
||||
|
||||
describeIfDb("RLS tenant isolation gate proof (TenantUser)", () => {
|
||||
let admin: pg.Client;
|
||||
let app: pg.Client;
|
||||
|
||||
beforeAll(async () => {
|
||||
admin = new pg.Client({ connectionString: ADMIN_URL });
|
||||
await admin.connect();
|
||||
|
||||
// 1) RLS-Mechanik + restricted Rolle + Policy aus dem committeten SQL anwenden (idempotent).
|
||||
const rlsSql = fs.readFileSync(path.resolve(process.cwd(), "prisma/rls/tenant-isolation.sql"), "utf8");
|
||||
await admin.query(rlsSql);
|
||||
await admin.query(`GRANT CONNECT ON DATABASE ${new URL(ADMIN_URL!).pathname.slice(1)} TO ${APP_ROLE}`);
|
||||
|
||||
// 2) Zwei Tenants + User + Memberships seeden (als Superuser -> bypasst RLS).
|
||||
await admin.query(`INSERT INTO "Tenant"(id,"updatedAt",slug,name) VALUES
|
||||
('rls_tenantA',now(),'rls-a','A'),('rls_tenantB',now(),'rls-b','B') ON CONFLICT (id) DO NOTHING`);
|
||||
await admin.query(`INSERT INTO "User"(id,"updatedAt",email,"firstName","lastName") VALUES
|
||||
('rls_userA',now(),'rls-a@example.test','A','A'),('rls_userB',now(),'rls-b@example.test','B','B') ON CONFLICT (id) DO NOTHING`);
|
||||
await admin.query(`INSERT INTO "TenantUser"(id,"tenantId","userId",type,joined,status) VALUES
|
||||
('rls_tuA','rls_tenantA','rls_userA',0,0,0),('rls_tuB','rls_tenantB','rls_userB',0,0,0) ON CONFLICT (id) DO NOTHING`);
|
||||
|
||||
app = new pg.Client({ connectionString: appUrlFrom(ADMIN_URL!) });
|
||||
await app.connect();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app?.end();
|
||||
await admin?.end();
|
||||
});
|
||||
|
||||
async function underTenant<T>(tenantId: string, run: () => Promise<T>): Promise<T> {
|
||||
await app.query("BEGIN");
|
||||
try {
|
||||
await app.query("SELECT set_config('app.tenant_id', $1, true)", [tenantId]);
|
||||
const result = await run();
|
||||
await app.query("COMMIT");
|
||||
return result;
|
||||
} catch (error) {
|
||||
await app.query("ROLLBACK");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
it("confirms the app role is neither superuser nor BYPASSRLS", async () => {
|
||||
const { rows } = await admin.query(`SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = $1`, [APP_ROLE]);
|
||||
expect(rows[0]).toMatchObject({ rolsuper: false, rolbypassrls: false });
|
||||
});
|
||||
|
||||
it("under tenant A context, only tenant A rows are visible", async () => {
|
||||
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "TenantUser" ORDER BY id`)).rows.map((r) => r.id));
|
||||
expect(ids).toEqual(["rls_tuA"]);
|
||||
});
|
||||
|
||||
it("cannot read another tenant's rows even with an explicit WHERE filter", async () => {
|
||||
const count = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "TenantUser" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c);
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it("sees no rows at all when no tenant context is set", async () => {
|
||||
const count = (await app.query(`SELECT count(*)::int AS c FROM "TenantUser"`)).rows[0].c;
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it("WITH CHECK blocks inserting a row for a foreign tenant", async () => {
|
||||
await expect(
|
||||
underTenant("rls_tenantA", async () =>
|
||||
app.query(`INSERT INTO "TenantUser"(id,"tenantId","userId",type,joined,status) VALUES ('rls_tuX','rls_tenantB','rls_userB',0,0,0)`)
|
||||
)
|
||||
).rejects.toThrow(/row-level security/i);
|
||||
});
|
||||
|
||||
it("allows inserting and reading a row for the active tenant", async () => {
|
||||
await underTenant("rls_tenantA", async () => {
|
||||
await app.query(`INSERT INTO "TenantUser"(id,"tenantId","userId",type,joined,status) VALUES ('rls_tuA2','rls_tenantA','rls_userA',0,0,0) ON CONFLICT (id) DO NOTHING`);
|
||||
const ids = (await app.query(`SELECT id FROM "TenantUser" ORDER BY id`)).rows.map((r) => r.id);
|
||||
expect(ids).toContain("rls_tuA2");
|
||||
expect(ids).not.toContain("rls_tuB");
|
||||
});
|
||||
});
|
||||
});
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const dbMock = vi.hoisted(() => ({ $transaction: vi.fn() }));
|
||||
vi.mock("~/utils/db.server", () => ({ db: dbMock, dbRead: dbMock }));
|
||||
|
||||
import { withTenantRLS } from "./tenantRls.server";
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("withTenantRLS", () => {
|
||||
it("sets app.tenant_id transaction-locally and runs the callback in the same transaction", async () => {
|
||||
const tx = { $executeRaw: vi.fn().mockResolvedValue(1) };
|
||||
dbMock.$transaction.mockImplementation(async (fn: (tx: unknown) => Promise<unknown>) => fn(tx));
|
||||
|
||||
const result = await withTenantRLS("tenantA", async (handed) => {
|
||||
expect(handed).toBe(tx);
|
||||
return "ok";
|
||||
});
|
||||
|
||||
expect(result).toBe("ok");
|
||||
// Tagged-Template: strings-Array an [0], interpolierter tenantId an [1].
|
||||
const [strings, value] = tx.$executeRaw.mock.calls[0];
|
||||
expect(value).toBe("tenantA");
|
||||
const sql = (strings as string[]).join("?");
|
||||
expect(sql).toContain("set_config");
|
||||
expect(sql).toContain("app.tenant_id");
|
||||
// 3. Argument von set_config ist 'true' (transaktions-lokal) und steht als Literal im SQL.
|
||||
expect(sql).toContain("true");
|
||||
});
|
||||
|
||||
it("rejects an empty tenantId before opening a transaction", async () => {
|
||||
await expect(withTenantRLS("", async () => "x")).rejects.toThrow(/tenantId/);
|
||||
expect(dbMock.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
import type { Prisma } from "@toolctrl/db/prisma-browser";
|
||||
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
// R-P2b — App-seitiger RLS-Adoptions-Mechanismus (AD-1). Setzt den Tenant-Kontext
|
||||
// TRANSAKTIONS-LOKAL (set_config(..., true) entspricht SET LOCAL und ist damit PgBouncer-
|
||||
// Transaction-Pooling-kompatibel: der Wert lebt nur bis COMMIT/ROLLBACK auf genau dieser
|
||||
// Verbindung) und fuehrt die Queries innerhalb derselben Transaktion aus, sodass die
|
||||
// RLS-Policies (USING/WITH CHECK auf current_setting('app.tenant_id')) greifen.
|
||||
//
|
||||
// Tenant-bezogene Datenzugriffe eines Moduls laufen ueber diesen Wrapper, sobald die jeweilige
|
||||
// Tabelle RLS-aktiviert ist (siehe prisma/rls/tenant-isolation.sql). Ohne gesetzten Kontext
|
||||
// liefert eine RLS-Tabelle der App-Rolle KEINE Zeile.
|
||||
|
||||
export type TenantRlsClient = Prisma.TransactionClient;
|
||||
|
||||
export async function withTenantRLS<T>(tenantId: string, callback: (tx: TenantRlsClient) => Promise<T>): Promise<T> {
|
||||
if (!tenantId) {
|
||||
throw new Error("withTenantRLS requires a non-empty tenantId");
|
||||
}
|
||||
return db.$transaction(async (tx: TenantRlsClient) => {
|
||||
await tx.$executeRaw`SELECT set_config('app.tenant_id', ${tenantId}, true)`;
|
||||
return callback(tx);
|
||||
});
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, test } from "vitest";
|
||||
import type { ApiKeyWithDetails } from "./apiKeys.db.server";
|
||||
import { getApiKeyLookupCacheKey, serializeApiLogSearchParams } from "../api/apiKeySecurity.server";
|
||||
import { redactApiKeyForDisplay, redactApiKeysForDisplay } from "./apiKeys.db.server";
|
||||
|
||||
const RAW_SECRET = "raw-secret-value-that-must-not-leak";
|
||||
|
||||
function createApiKeyRow(overrides: Partial<ApiKeyWithDetails> = {}): ApiKeyWithDetails {
|
||||
const now = new Date("2026-01-02T03:04:05.000Z");
|
||||
|
||||
return {
|
||||
id: "api-key-1",
|
||||
tenantId: "tenant-1",
|
||||
createdByUserId: "user-1",
|
||||
alias: "Primary integration",
|
||||
key: RAW_SECRET,
|
||||
keyHash: "hash-value",
|
||||
keyPrefix: "raw-secr",
|
||||
keyLastFour: "leak",
|
||||
hashedAt: now,
|
||||
keyVersion: 1,
|
||||
expires: null,
|
||||
active: true,
|
||||
createdAt: now,
|
||||
tenant: { id: "tenant-1", name: "Tenant", slug: "tenant", deactivatedReason: null },
|
||||
createdByUser: {
|
||||
id: "user-1",
|
||||
email: "user@example.com",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
phone: null,
|
||||
locale: "en",
|
||||
createdAt: now,
|
||||
},
|
||||
entities: [
|
||||
{
|
||||
id: "permission-1",
|
||||
apiKeyId: "api-key-1",
|
||||
entityId: "entity-1",
|
||||
create: true,
|
||||
read: true,
|
||||
update: false,
|
||||
delete: false,
|
||||
entity: { id: "entity-1", title: "Contact", titlePlural: "Contacts", slug: "contacts" },
|
||||
},
|
||||
],
|
||||
_count: { apiKeyLogs: 7 },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("API key display redaction", () => {
|
||||
test("omits raw key while preserving display metadata for detail payloads", () => {
|
||||
const source = createApiKeyRow();
|
||||
|
||||
const redacted = redactApiKeyForDisplay(source);
|
||||
|
||||
expect(redacted).not.toHaveProperty("key");
|
||||
expect(redacted).toMatchObject({
|
||||
id: source.id,
|
||||
alias: source.alias,
|
||||
active: source.active,
|
||||
expires: source.expires,
|
||||
keyPrefix: source.keyPrefix,
|
||||
keyLastFour: source.keyLastFour,
|
||||
hashedAt: source.hashedAt,
|
||||
keyVersion: source.keyVersion,
|
||||
entities: source.entities,
|
||||
createdByUser: source.createdByUser,
|
||||
tenant: source.tenant,
|
||||
_count: source._count,
|
||||
});
|
||||
expect(JSON.stringify(redacted)).not.toContain(RAW_SECRET);
|
||||
});
|
||||
|
||||
test("redacts list payloads without mutating source rows", () => {
|
||||
const source = createApiKeyRow();
|
||||
|
||||
const redacted = redactApiKeysForDisplay([source]);
|
||||
|
||||
expect(redacted).toHaveLength(1);
|
||||
expect(redacted[0]).not.toHaveProperty("key");
|
||||
expect(JSON.stringify(redacted)).not.toContain(RAW_SECRET);
|
||||
expect(source.key).toBe(RAW_SECRET);
|
||||
expect(source).toHaveProperty("key", RAW_SECRET);
|
||||
});
|
||||
|
||||
test("builds API-key cache keys without embedding raw secrets", () => {
|
||||
const cacheKey = getApiKeyLookupCacheKey(RAW_SECRET);
|
||||
|
||||
expect(cacheKey).toMatch(/^apiKeyHash:[a-f0-9]{64}$/);
|
||||
expect(cacheKey).not.toContain(RAW_SECRET);
|
||||
});
|
||||
|
||||
test("redacts query params for API-key log writers", () => {
|
||||
const request = new Request("https://example.com/api/site?token=raw-token&email=person@example.test&page=2&apiKey=sk_live_secret");
|
||||
|
||||
expect(serializeApiLogSearchParams(request)).toBe(
|
||||
JSON.stringify({
|
||||
token: "[REDACTED]",
|
||||
email: "[REDACTED]",
|
||||
page: "2",
|
||||
apiKey: "[REDACTED]",
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,273 @@
|
||||
import {
|
||||
createLegacyApiKeyLog,
|
||||
createLegacyApiKey,
|
||||
countLegacyApiKeyLogsForKey,
|
||||
deleteLegacyApiKey,
|
||||
adminFindLegacyApiKeyById,
|
||||
findFirstLegacyActiveApiKey,
|
||||
findLegacyApiKeyByAlias,
|
||||
findLegacyApiKeyById,
|
||||
findLegacyApiKeyByKey,
|
||||
getAllLegacyApiKeys,
|
||||
rotateLegacyApiKey,
|
||||
getLegacyApiKeyLogsForKey,
|
||||
getLegacyApiKeysForTenant,
|
||||
type LegacyApiKeyLogWithDetails,
|
||||
type LegacyApiKeySimple,
|
||||
type LegacyApiKeyWithDetails,
|
||||
updateLegacyApiKey,
|
||||
} from "@toolctrl/db/api-keys.server";
|
||||
import { db } from "../db.server";
|
||||
import { getClientIPAddress } from "~/utils/server/IpUtils";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
|
||||
import RowFiltersHelper from "../helpers/RowFiltersHelper";
|
||||
import { cachified, clearCacheKey } from "../cache.server";
|
||||
import { loadRequiredWebConfig } from "@toolctrl/config";
|
||||
import { getApiKeyLookupCacheKey, serializeApiLogSearchParams } from "../api/apiKeySecurity.server";
|
||||
|
||||
export type ApiKeyWithDetails = LegacyApiKeyWithDetails;
|
||||
export type RedactedApiKeyWithDetails = Omit<LegacyApiKeyWithDetails, "key">;
|
||||
|
||||
export function redactApiKeyForDisplay(apiKey: LegacyApiKeyWithDetails): RedactedApiKeyWithDetails {
|
||||
const redactedApiKey = { ...apiKey };
|
||||
delete (redactedApiKey as Partial<LegacyApiKeyWithDetails>).key;
|
||||
return redactedApiKey;
|
||||
}
|
||||
|
||||
export function redactApiKeysForDisplay(apiKeys: LegacyApiKeyWithDetails[]): RedactedApiKeyWithDetails[] {
|
||||
return apiKeys.map(redactApiKeyForDisplay);
|
||||
}
|
||||
|
||||
export type ApiKeyLogWithDetails = LegacyApiKeyLogWithDetails;
|
||||
export type ApiKeyLogSimple = { apiKeyId: string | null; status: number | null };
|
||||
|
||||
export type ApiKeySimple = LegacyApiKeySimple;
|
||||
|
||||
export async function getAllApiKeys(): Promise<RedactedApiKeyWithDetails[]> {
|
||||
const apiKeys = await getAllLegacyApiKeys();
|
||||
return redactApiKeysForDisplay(apiKeys);
|
||||
}
|
||||
|
||||
export async function getAllApiKeyLogs(
|
||||
pagination: { page: number; pageSize: number },
|
||||
filters: FiltersDto
|
||||
): Promise<{ items: ApiKeyLogWithDetails[]; pagination: PaginationDto }> {
|
||||
const where = RowFiltersHelper.getFiltersCondition(filters);
|
||||
const items = await db.apiKeyLog.findMany({
|
||||
take: pagination.pageSize,
|
||||
skip: pagination.pageSize * (pagination.page - 1),
|
||||
where,
|
||||
include: {
|
||||
apiKey: {
|
||||
include: { tenant: true },
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
});
|
||||
const totalItems = await db.apiKeyLog.count({
|
||||
where,
|
||||
});
|
||||
|
||||
return {
|
||||
items,
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / pagination.pageSize),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function getAllApiKeyLogsSimple(tenantId?: string): Promise<ApiKeyLogSimple[]> {
|
||||
let where: any = {};
|
||||
if (tenantId) {
|
||||
where = {
|
||||
apiKey: {
|
||||
tenantId,
|
||||
},
|
||||
};
|
||||
}
|
||||
return await db.apiKeyLog.findMany({
|
||||
where,
|
||||
select: {
|
||||
apiKeyId: true,
|
||||
status: true,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantApiKeyLogs(
|
||||
tenantId: string,
|
||||
pagination: { page: number; pageSize: number },
|
||||
filters: FiltersDto
|
||||
): Promise<{ items: ApiKeyLogWithDetails[]; pagination: PaginationDto }> {
|
||||
const where = {
|
||||
AND: [RowFiltersHelper.getFiltersCondition(filters), { apiKey: { tenantId } }],
|
||||
};
|
||||
const items = await db.apiKeyLog.findMany({
|
||||
take: pagination.pageSize,
|
||||
skip: pagination.pageSize * (pagination.page - 1),
|
||||
where,
|
||||
include: { apiKey: { include: { tenant: true } } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
const totalItems = await db.apiKeyLog.count({ where });
|
||||
return {
|
||||
items,
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / pagination.pageSize),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function getApiKeys(tenantId: string): Promise<RedactedApiKeyWithDetails[]> {
|
||||
const apiKeys = await getLegacyApiKeysForTenant(tenantId);
|
||||
return redactApiKeysForDisplay(apiKeys);
|
||||
}
|
||||
|
||||
export async function adminGetApiKeyById(id: string): Promise<RedactedApiKeyWithDetails | null> {
|
||||
const apiKey = await adminFindLegacyApiKeyById(id);
|
||||
return apiKey ? redactApiKeyForDisplay(apiKey) : null;
|
||||
}
|
||||
|
||||
export async function getTenantApiKeyById(id: string, tenantId: string): Promise<RedactedApiKeyWithDetails | null> {
|
||||
const apiKey = await findLegacyApiKeyById({ id, tenantId });
|
||||
return apiKey ? redactApiKeyForDisplay(apiKey) : null;
|
||||
}
|
||||
|
||||
export async function adminGetApiKeyByIdWithSecret(id: string): Promise<ApiKeyWithDetails | null> {
|
||||
return adminFindLegacyApiKeyById(id);
|
||||
}
|
||||
|
||||
export async function getTenantApiKeyByIdWithSecret(id: string, tenantId: string): Promise<ApiKeyWithDetails | null> {
|
||||
return findLegacyApiKeyById({ id, tenantId });
|
||||
}
|
||||
|
||||
export async function getApiKey(key: string): Promise<ApiKeySimple | null> {
|
||||
return await cachified({
|
||||
key: getApiKeyLookupCacheKey(key),
|
||||
ttl: 1000 * 60 * 60,
|
||||
getFreshValue: () => findLegacyApiKeyByKey(key),
|
||||
});
|
||||
}
|
||||
|
||||
export async function getApiKeyByAlias(tenantId: string, alias: string): Promise<ApiKeyWithDetails | null> {
|
||||
return findLegacyApiKeyByAlias(tenantId, alias);
|
||||
}
|
||||
|
||||
export async function getApiKeyLogs(id: string, tenantId: string): Promise<ApiKeyLogWithDetails[]> {
|
||||
return getLegacyApiKeyLogsForKey({ id, tenantId });
|
||||
}
|
||||
|
||||
export async function countApiKeyLogsForKey(id: string, tenantId: string): Promise<number> {
|
||||
return countLegacyApiKeyLogsForKey({ id, tenantId });
|
||||
}
|
||||
|
||||
export async function getFirstApiKey(tenantId: string | null) {
|
||||
return findFirstLegacyActiveApiKey(tenantId);
|
||||
}
|
||||
|
||||
export async function createApiKey(
|
||||
data: {
|
||||
tenantId: string;
|
||||
createdByUserId: string;
|
||||
alias: string;
|
||||
expires: Date | null;
|
||||
active: boolean;
|
||||
},
|
||||
entities: {
|
||||
entityId: string;
|
||||
create: boolean;
|
||||
read: boolean;
|
||||
update: boolean;
|
||||
delete: boolean;
|
||||
}[]
|
||||
) {
|
||||
return createLegacyApiKey(data, entities, undefined, getApiKeyHashSecret());
|
||||
}
|
||||
|
||||
export async function createApiKeyLog(
|
||||
request: Request,
|
||||
data: {
|
||||
tenantId: string | null;
|
||||
apiKeyId: string | null;
|
||||
endpoint: string;
|
||||
error?: string;
|
||||
status?: number;
|
||||
alias?: string;
|
||||
tenantName?: string;
|
||||
}
|
||||
) {
|
||||
return await createLegacyApiKeyLog({
|
||||
tenantId: data.tenantId,
|
||||
apiKeyId: data.apiKeyId,
|
||||
endpoint: data.endpoint,
|
||||
error: data.error,
|
||||
status: data.status,
|
||||
alias: data.alias,
|
||||
tenantName: data.tenantName,
|
||||
ip: getClientIPAddress(request.headers)?.toString() ?? "",
|
||||
method: request.method,
|
||||
params: serializeApiLogSearchParams(request),
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateApiKey(
|
||||
id: string,
|
||||
data: {
|
||||
tenantId: string;
|
||||
alias: string;
|
||||
expires: Date | null;
|
||||
active: boolean;
|
||||
},
|
||||
entities: {
|
||||
entityId: string;
|
||||
create: boolean;
|
||||
read: boolean;
|
||||
update: boolean;
|
||||
delete: boolean;
|
||||
}[]
|
||||
) {
|
||||
const apiKey = await updateLegacyApiKey(id, data, entities);
|
||||
clearCacheKey(getApiKeyLookupCacheKey(apiKey.key));
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
export async function rotateApiKey(id: string, tenantId: string) {
|
||||
const previousApiKey = await findLegacyApiKeyById({ id, tenantId });
|
||||
if (!previousApiKey) {
|
||||
throw new Error(`API key ${id} not found`);
|
||||
}
|
||||
const apiKey = await rotateLegacyApiKey({ id, tenantId: previousApiKey.tenantId }, undefined, getApiKeyHashSecret());
|
||||
|
||||
if (previousApiKey?.key) {
|
||||
clearCacheKey(getApiKeyLookupCacheKey(previousApiKey.key));
|
||||
}
|
||||
clearCacheKey(getApiKeyLookupCacheKey(apiKey.key));
|
||||
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
export async function deleteApiKey(id: string, tenantId: string) {
|
||||
const previousApiKey = await findLegacyApiKeyById({ id, tenantId });
|
||||
if (!previousApiKey) {
|
||||
throw new Error(`API key ${id} not found`);
|
||||
}
|
||||
const apiKey = await deleteLegacyApiKey({ id, tenantId: previousApiKey.tenantId });
|
||||
clearCacheKey(getApiKeyLookupCacheKey(apiKey.key));
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
function getApiKeyHashSecret() {
|
||||
return loadRequiredWebConfig().jwtSecret;
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import path from "node:path";
|
||||
|
||||
const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "appConfiguration.db.server.ts"), "utf8");
|
||||
|
||||
describe("appConfiguration web config adoption", () => {
|
||||
test("uses loadRequiredWebConfig instead of direct web env reads for public config fields", () => {
|
||||
expect(source).toContain('import { loadRequiredWebConfig } from "@toolctrl/config"');
|
||||
expect(source).toContain("const webConfig = loadRequiredWebConfig()");
|
||||
expect(source).toContain("instanceUrl: webConfig.captcha.instanceUrl ?? \"\"");
|
||||
expect(source).toContain("const authProviders = getPublicAuthProviders({ request, webConfig })");
|
||||
expect(source).toContain("enabled: authProviders.magicLink.enabled");
|
||||
expect(source).not.toContain("authProviders.github");
|
||||
expect(source).not.toContain('new URL("https://github.com/login/oauth/authorize")');
|
||||
expect(source).not.toContain("loadWebConfig().config");
|
||||
expect(source).not.toContain("process.env.AUTH_RECAPTCHA_SITE_KEY");
|
||||
expect(source).not.toContain("process?.env.GITHUB_OAUTH_CLIENT_ID");
|
||||
});
|
||||
|
||||
test("does not keep removed Forms or Surveys as feature flags", () => {
|
||||
expect(source).not.toContain("surveys:");
|
||||
});
|
||||
|
||||
test("defaults optional analytics tracking to disabled", () => {
|
||||
expect(source).toContain("analytics: {\n enabled: false,");
|
||||
expect(source).toContain("simpleAnalytics: false");
|
||||
expect(source).toContain("ipLookup: false");
|
||||
});
|
||||
});
|
||||
+320
@@ -0,0 +1,320 @@
|
||||
import { defaultBrandTokens } from "@toolctrl/brand";
|
||||
import { loadRequiredWebConfig } from "@toolctrl/config";
|
||||
import { Prisma } from "@toolctrl/db/prisma-browser";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getPublicAuthProviders } from "../auth/authProviders.server";
|
||||
import { cachified, clearCacheKey } from "../cache.server";
|
||||
import { db } from "../db.server";
|
||||
import { defaultTheme } from "../theme/defaultThemes";
|
||||
import { getBaseURL, getDomainName } from "../url.server";
|
||||
import { PortalConfiguration, getAppPortalConfiguration } from "./appPortalConfiguration.db.server";
|
||||
import { getWidgetsConfiguration, WidgetsConfiguration } from "./appWidgetsConfiguration.db.server";
|
||||
|
||||
export type AppConfiguration = {
|
||||
app: {
|
||||
name: string;
|
||||
url: string;
|
||||
domain: string;
|
||||
theme: string;
|
||||
company?: { name: string; address: string };
|
||||
features: {
|
||||
tenantHome: "/:tenant/" | "/";
|
||||
tenantTypes: boolean;
|
||||
tenantApiKeys?: boolean;
|
||||
tenantEntityCustomization?: boolean;
|
||||
crm: boolean;
|
||||
tenantWorkflows: boolean;
|
||||
tenantEmailMarketing: boolean;
|
||||
tenantFeedback: boolean;
|
||||
};
|
||||
};
|
||||
email: {
|
||||
provider: "mailjet";
|
||||
fromEmail: string;
|
||||
fromName: string;
|
||||
supportEmail: string;
|
||||
};
|
||||
auth: {
|
||||
requireEmailVerification: boolean;
|
||||
requireOrganization: boolean;
|
||||
requireName: boolean;
|
||||
slug: { require: boolean; type: "tenant" | "username" } | null;
|
||||
captcha: {
|
||||
enabled: boolean;
|
||||
instanceUrl: string;
|
||||
loginSiteKey: string;
|
||||
};
|
||||
authMethods: {
|
||||
emailPassword: {
|
||||
enabled: boolean;
|
||||
};
|
||||
magicLink: {
|
||||
enabled: boolean;
|
||||
};
|
||||
};
|
||||
};
|
||||
analytics: {
|
||||
enabled: boolean;
|
||||
simpleAnalytics: boolean;
|
||||
plausibleAnalytics: boolean;
|
||||
// EU-Sterilisation (R-P1a): googleAnalyticsTrackingId entfernt. DB-Spalte bleibt vorerst
|
||||
// verwaist (Drop per Merge-Migration, AD-21), wird aber nicht mehr gelesen/geschrieben.
|
||||
ipLookup?: boolean;
|
||||
};
|
||||
subscription: {
|
||||
required: boolean;
|
||||
allowSubscribeBeforeSignUp: boolean;
|
||||
allowSignUpBeforeSubscribe: boolean;
|
||||
multiple: boolean;
|
||||
};
|
||||
cookies: {
|
||||
enabled: boolean;
|
||||
};
|
||||
notifications: {
|
||||
enabled: boolean;
|
||||
};
|
||||
onboarding: {
|
||||
enabled: boolean;
|
||||
};
|
||||
featureFlags: {
|
||||
enabled: boolean; // load all flags
|
||||
};
|
||||
metrics: {
|
||||
enabled: boolean;
|
||||
logToConsole: boolean;
|
||||
saveToDatabase: boolean;
|
||||
ignoreUrls: string[];
|
||||
};
|
||||
branding: {
|
||||
logo?: string;
|
||||
logoDarkMode?: string;
|
||||
icon?: string;
|
||||
iconDarkMode?: string;
|
||||
favicon?: string;
|
||||
};
|
||||
reviews?: {
|
||||
trustpilot?: { href: string; templateId: string; businessUnitId: string };
|
||||
};
|
||||
launches?: {
|
||||
producthunt?: { title: string; url: string; postId: string };
|
||||
};
|
||||
portals: PortalConfiguration;
|
||||
widgets: WidgetsConfiguration;
|
||||
scripts: { head: string | null; body: string | null };
|
||||
};
|
||||
|
||||
export async function getAppConfiguration({ request }: { request: Request }): Promise<AppConfiguration> {
|
||||
const { t } = await getTranslations(request);
|
||||
const webConfig = loadRequiredWebConfig();
|
||||
const authProviders = getPublicAuthProviders({ request, webConfig });
|
||||
const defaultEmailConfig: AppConfiguration["email"] = {
|
||||
provider: "mailjet",
|
||||
fromEmail: defaultBrandTokens.support.email,
|
||||
fromName: defaultBrandTokens.support.fromName,
|
||||
supportEmail: defaultBrandTokens.support.email,
|
||||
};
|
||||
const conf: AppConfiguration = {
|
||||
app: {
|
||||
name: webConfig.appName,
|
||||
url: getBaseURL(request),
|
||||
domain: getDomainName(request),
|
||||
theme: defaultTheme,
|
||||
company: undefined,
|
||||
features: {
|
||||
tenantHome: "/:tenant/",
|
||||
tenantApiKeys: true,
|
||||
tenantEntityCustomization: false,
|
||||
crm: false,
|
||||
tenantTypes: false,
|
||||
tenantWorkflows: false,
|
||||
tenantEmailMarketing: false,
|
||||
tenantFeedback: true,
|
||||
},
|
||||
},
|
||||
email: defaultEmailConfig,
|
||||
auth: {
|
||||
requireEmailVerification: false,
|
||||
requireOrganization: false,
|
||||
requireName: false,
|
||||
slug: { require: false, type: "username" },
|
||||
captcha: {
|
||||
enabled: Boolean(webConfig.captcha.instanceUrl && webConfig.captcha.loginSiteKey),
|
||||
instanceUrl: webConfig.captcha.instanceUrl ?? "",
|
||||
loginSiteKey: webConfig.captcha.loginSiteKey ?? "",
|
||||
},
|
||||
authMethods: {
|
||||
emailPassword: {
|
||||
enabled: true,
|
||||
},
|
||||
magicLink: {
|
||||
enabled: authProviders.magicLink.enabled,
|
||||
},
|
||||
},
|
||||
},
|
||||
analytics: {
|
||||
enabled: false,
|
||||
simpleAnalytics: false,
|
||||
plausibleAnalytics: false,
|
||||
ipLookup: false,
|
||||
},
|
||||
subscription: {
|
||||
required: false,
|
||||
allowSubscribeBeforeSignUp: true,
|
||||
allowSignUpBeforeSubscribe: true,
|
||||
// `multiple: false` = single-plan-per-tenant. When a user subscribes to a
|
||||
// new plan while an old one is still active, the old one is auto-cancelled
|
||||
// (see `addTenantProductsFromCheckoutSession` in pricingService). This is
|
||||
// the standard SaaS upgrade/downgrade behaviour. Flip to `true` only if
|
||||
// you want tenants to be able to hold multiple parallel subscriptions
|
||||
// (e.g. add-on / marketplace pattern).
|
||||
multiple: false,
|
||||
},
|
||||
cookies: {
|
||||
enabled: false,
|
||||
},
|
||||
notifications: {
|
||||
enabled: true,
|
||||
},
|
||||
onboarding: {
|
||||
enabled: true,
|
||||
},
|
||||
featureFlags: {
|
||||
enabled: true,
|
||||
},
|
||||
metrics: {
|
||||
enabled: false,
|
||||
logToConsole: false,
|
||||
saveToDatabase: false,
|
||||
ignoreUrls: ["/build", "/metrics"],
|
||||
},
|
||||
branding: {
|
||||
logo: undefined,
|
||||
logoDarkMode: undefined,
|
||||
icon: undefined,
|
||||
iconDarkMode: undefined,
|
||||
favicon: undefined,
|
||||
},
|
||||
launches: undefined,
|
||||
portals: getAppPortalConfiguration({ t }),
|
||||
widgets: getWidgetsConfiguration({ t }),
|
||||
scripts: { head: null, body: null },
|
||||
};
|
||||
|
||||
const appConfiguration = await cachified({
|
||||
key: `appConfiguration`,
|
||||
ttl: 1000 * 60 * 60 * 24, // 1 day
|
||||
getFreshValue: async () => db.appConfiguration.findFirst(),
|
||||
});
|
||||
if (!appConfiguration) {
|
||||
return conf;
|
||||
}
|
||||
conf.app.name = appConfiguration?.name ?? "";
|
||||
// conf.app.url = appConfiguration?.url ?? "";
|
||||
conf.app.theme = appConfiguration?.theme ?? defaultTheme;
|
||||
|
||||
conf.email.provider = getTransactionalEmailProvider(appConfiguration?.emailProvider, defaultEmailConfig.provider);
|
||||
conf.email.fromEmail = appConfiguration?.emailFromEmail ?? defaultEmailConfig.fromEmail;
|
||||
conf.email.fromName = appConfiguration?.emailFromName ?? defaultEmailConfig.fromName;
|
||||
conf.email.supportEmail = appConfiguration?.emailSupportEmail ?? defaultEmailConfig.supportEmail;
|
||||
|
||||
conf.auth.requireEmailVerification = appConfiguration?.authRequireEmailVerification;
|
||||
conf.auth.requireOrganization = appConfiguration?.authRequireOrganization;
|
||||
conf.auth.requireName = appConfiguration?.authRequireName;
|
||||
// Captcha (mCaptcha) is env-driven (MCAPTCHA_*), not stored per-tenant in the DB.
|
||||
// `conf.auth.captcha` is already populated from webConfig in the default builder.
|
||||
|
||||
conf.analytics.enabled = appConfiguration?.analyticsEnabled;
|
||||
conf.analytics.simpleAnalytics = appConfiguration?.analyticsSimpleAnalytics;
|
||||
conf.analytics.plausibleAnalytics = appConfiguration?.analyticsPlausibleAnalytics;
|
||||
|
||||
conf.subscription.required = appConfiguration?.subscriptionRequired;
|
||||
conf.subscription.allowSubscribeBeforeSignUp = appConfiguration?.subscriptionAllowSubscribeBeforeSignUp;
|
||||
conf.subscription.allowSignUpBeforeSubscribe = appConfiguration?.subscriptionAllowSignUpBeforeSubscribe;
|
||||
|
||||
conf.cookies.enabled = appConfiguration?.cookiesEnabled;
|
||||
|
||||
conf.metrics.enabled = appConfiguration?.metricsEnabled;
|
||||
conf.metrics.logToConsole = appConfiguration?.metricsLogToConsole;
|
||||
conf.metrics.saveToDatabase = appConfiguration?.metricsSaveToDatabase;
|
||||
conf.metrics.ignoreUrls = appConfiguration?.metricsIgnoreUrls?.split(",") ?? [];
|
||||
|
||||
conf.branding.logo = appConfiguration?.brandingLogo ?? undefined;
|
||||
conf.branding.logoDarkMode = appConfiguration?.brandingLogoDarkMode ?? undefined;
|
||||
conf.branding.icon = appConfiguration?.brandingIcon ?? undefined;
|
||||
conf.branding.iconDarkMode = appConfiguration?.brandingIconDarkMode ?? undefined;
|
||||
conf.branding.favicon = appConfiguration?.brandingFavicon ?? undefined;
|
||||
|
||||
conf.scripts = {
|
||||
head: appConfiguration?.headScripts || null,
|
||||
body: appConfiguration?.bodyScripts || null,
|
||||
};
|
||||
|
||||
return conf;
|
||||
}
|
||||
|
||||
export async function getOrCreateAppConfiguration({ request }: { request: Request }) {
|
||||
let settings = await db.appConfiguration.findFirst();
|
||||
if (!settings) {
|
||||
const conf = await getAppConfiguration({ request });
|
||||
settings = await db.appConfiguration
|
||||
.create({
|
||||
data: {
|
||||
name: conf.app.name,
|
||||
url: conf.app.url,
|
||||
authRequireEmailVerification: conf.auth.requireEmailVerification,
|
||||
authRequireOrganization: conf.auth.requireOrganization,
|
||||
authRequireName: conf.auth.requireName,
|
||||
analyticsEnabled: conf.analytics.enabled,
|
||||
analyticsSimpleAnalytics: conf.analytics.simpleAnalytics,
|
||||
analyticsPlausibleAnalytics: conf.analytics.plausibleAnalytics,
|
||||
subscriptionRequired: conf.subscription.required,
|
||||
subscriptionAllowSubscribeBeforeSignUp: conf.subscription.allowSubscribeBeforeSignUp,
|
||||
subscriptionAllowSignUpBeforeSubscribe: conf.subscription.allowSignUpBeforeSubscribe,
|
||||
cookiesEnabled: conf.cookies.enabled,
|
||||
metricsEnabled: conf.metrics.enabled,
|
||||
metricsLogToConsole: conf.metrics.logToConsole,
|
||||
metricsSaveToDatabase: conf.metrics.saveToDatabase,
|
||||
metricsIgnoreUrls: conf.metrics.ignoreUrls.join(","),
|
||||
brandingLogo: conf.branding.logo,
|
||||
brandingLogoDarkMode: conf.branding.logoDarkMode,
|
||||
brandingIcon: conf.branding.icon,
|
||||
brandingIconDarkMode: conf.branding.iconDarkMode,
|
||||
brandingFavicon: conf.branding.favicon,
|
||||
},
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`appConfiguration`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
|
||||
function getTransactionalEmailProvider(
|
||||
provider: string | null | undefined,
|
||||
fallback: AppConfiguration["email"]["provider"]
|
||||
): AppConfiguration["email"]["provider"] {
|
||||
if (provider === "mailjet") {
|
||||
return provider;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export async function updateAppConfiguration(data: Prisma.AppConfigurationUpdateInput) {
|
||||
return await db.appConfiguration
|
||||
.updateMany({
|
||||
data,
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`appConfiguration`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteAppConfiguration() {
|
||||
return await db.appConfiguration.deleteMany({ where: {} }).then((item) => {
|
||||
clearCacheKey(`appConfiguration`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
import { JsonPropertyDto } from "~/modules/jsonProperties/dtos/JsonPropertyTypeDto";
|
||||
import { TFunction } from "i18next";
|
||||
import { JsonPropertiesValuesDto } from "~/modules/jsonProperties/dtos/JsonPropertiesValuesDto";
|
||||
import { Portal } from "@toolctrl/db/prisma-browser";
|
||||
|
||||
export type PortalConfiguration = {
|
||||
enabled: boolean;
|
||||
forTenants: boolean;
|
||||
pricing: boolean;
|
||||
analytics: boolean;
|
||||
domains?: {
|
||||
enabled: boolean;
|
||||
provider: "fly";
|
||||
portalAppId: string;
|
||||
records?: { A: string; AAAA: string };
|
||||
};
|
||||
metadata: Array<JsonPropertyDto> | undefined;
|
||||
pages: Array<PortalPageConfigDto>;
|
||||
};
|
||||
|
||||
export type PortalPageConfigDto = {
|
||||
name: string;
|
||||
title: string;
|
||||
slug: string;
|
||||
properties: Array<JsonPropertyDto>;
|
||||
errors?: (params: { portal: Portal; page: { attributes: JsonPropertiesValuesDto } | null }) => string[];
|
||||
};
|
||||
|
||||
export function getAppPortalConfiguration({ t }: { t: TFunction }): PortalConfiguration {
|
||||
const titleProperty: JsonPropertyDto = {
|
||||
name: "title",
|
||||
title: t("models.portal.title"),
|
||||
type: "string",
|
||||
required: true,
|
||||
};
|
||||
const descriptionProperty: JsonPropertyDto = {
|
||||
name: "description",
|
||||
title: t("models.portal.description"),
|
||||
type: "string",
|
||||
required: false,
|
||||
};
|
||||
const htmlProperty: JsonPropertyDto = {
|
||||
name: "html",
|
||||
title: t("shared.content"),
|
||||
type: "wysiwyg",
|
||||
required: true,
|
||||
};
|
||||
|
||||
const seoProperties: JsonPropertyDto[] = [
|
||||
{
|
||||
name: "seoTitle",
|
||||
title: t("shared.title"),
|
||||
type: "string",
|
||||
required: false,
|
||||
group: t("models.portal.seo"),
|
||||
},
|
||||
{
|
||||
name: "seoDescription",
|
||||
title: t("shared.description"),
|
||||
type: "string",
|
||||
required: false,
|
||||
group: t("models.portal.seo"),
|
||||
},
|
||||
{
|
||||
name: "seoImage",
|
||||
title: t("shared.image"),
|
||||
type: "image",
|
||||
required: false,
|
||||
group: t("models.portal.seo"),
|
||||
},
|
||||
];
|
||||
|
||||
const conf: PortalConfiguration = {
|
||||
// Portals ship gated OFF by default so the boilerplate stays lean; a
|
||||
// deployment opts in with PORTALS_ENABLED=true (e.g. the e2e/readiness
|
||||
// target). The route files are always mounted but the loaders fail closed
|
||||
// (400 "disabled") until this flag is set, so flipping the env is the only
|
||||
// switch needed at runtime.
|
||||
enabled: process.env.PORTALS_ENABLED === "true",
|
||||
forTenants: true,
|
||||
pricing: true,
|
||||
analytics: true,
|
||||
domains: {
|
||||
enabled: true,
|
||||
provider: "fly",
|
||||
portalAppId: "app-portal",
|
||||
records: {
|
||||
A: "66.241.125.25",
|
||||
AAAA: "2a09:8280:1::31:5dc2:0",
|
||||
},
|
||||
},
|
||||
metadata: [],
|
||||
pages: [
|
||||
{
|
||||
name: "pricing",
|
||||
title: t("models.portal.pages.pricing"),
|
||||
slug: "/plans",
|
||||
properties: [titleProperty, descriptionProperty, ...seoProperties],
|
||||
errors: (params) => {
|
||||
let errors: string[] = [];
|
||||
if (!params.portal.stripeAccountId) {
|
||||
errors.push(t("models.portal.pages.errors.stripeAccountMissing"));
|
||||
}
|
||||
return errors;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "privacy-policy",
|
||||
title: t("models.portal.pages.privacyPolicy"),
|
||||
slug: "/privacy-policy",
|
||||
properties: [titleProperty, descriptionProperty, htmlProperty, ...seoProperties],
|
||||
errors: (params) => {
|
||||
const errors: string[] = [];
|
||||
if (!params.page?.attributes?.html) {
|
||||
errors.push(t("models.portal.pages.errors.privacyPolicyContentMissing"));
|
||||
}
|
||||
return errors;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "terms-and-conditions",
|
||||
title: t("models.portal.pages.termsAndConditions"),
|
||||
slug: "/terms-and-conditions",
|
||||
properties: [titleProperty, descriptionProperty, htmlProperty, ...seoProperties],
|
||||
errors: (params) => {
|
||||
const errors: string[] = [];
|
||||
if (!params.page?.attributes?.html) {
|
||||
errors.push(t("models.portal.pages.errors.termsContentMissing"));
|
||||
}
|
||||
return errors;
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
return conf;
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import { JsonPropertyDto } from "~/modules/jsonProperties/dtos/JsonPropertyTypeDto";
|
||||
import { TFunction } from "i18next";
|
||||
|
||||
export type WidgetsConfiguration = {
|
||||
enabled: boolean;
|
||||
metadata: Array<JsonPropertyDto> | undefined;
|
||||
};
|
||||
|
||||
export function getWidgetsConfiguration({ t }: { t: TFunction }): WidgetsConfiguration {
|
||||
const conf: WidgetsConfiguration = {
|
||||
enabled: false,
|
||||
metadata: [
|
||||
// {
|
||||
// name: "description",
|
||||
// title: t("shared.description"),
|
||||
// type: "string",
|
||||
// required: true,
|
||||
// },
|
||||
],
|
||||
};
|
||||
|
||||
return conf;
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Blacklist } from "@toolctrl/db/prisma-browser";
|
||||
import Constants from "~/application/Constants";
|
||||
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { db } from "../db.server";
|
||||
import { createScopedLogger } from "../logger.server";
|
||||
|
||||
const blacklistLogger = createScopedLogger("db.blacklist");
|
||||
|
||||
export async function getBlacklist(
|
||||
filters?: FiltersDto,
|
||||
pagination?: { page: number; pageSize: number }
|
||||
): Promise<{ items: Blacklist[]; pagination: PaginationDto }> {
|
||||
const items = await db.blacklist.findMany({
|
||||
skip: pagination ? pagination?.pageSize * (pagination?.page - 1) : undefined,
|
||||
take: pagination ? pagination?.pageSize : undefined,
|
||||
orderBy: [{ registerAttempts: "desc" }, { createdAt: "desc" }],
|
||||
});
|
||||
const totalItems = await db.blacklist.count({});
|
||||
|
||||
return {
|
||||
items,
|
||||
pagination: {
|
||||
page: pagination?.page ?? 1,
|
||||
pageSize: pagination?.pageSize ?? Constants.DEFAULT_PAGE_SIZE,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / (pagination?.pageSize ?? Constants.DEFAULT_PAGE_SIZE)),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function findInBlacklist(type: string, value: string): Promise<Blacklist | null> {
|
||||
return await db.blacklist.findFirst({
|
||||
where: {
|
||||
type,
|
||||
value,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function addBlacklistAttempt(item: Blacklist) {
|
||||
blacklistLogger.info(
|
||||
{ type: item.type, value: item.value, registerAttempts: item.registerAttempts + 1 },
|
||||
`[BLACKLISTED ${item.type.toUpperCase()}]`
|
||||
);
|
||||
return await db.blacklist.updateMany({
|
||||
where: {
|
||||
type: item.type,
|
||||
value: item.value,
|
||||
},
|
||||
data: {
|
||||
registerAttempts: item.registerAttempts + 1,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function addToBlacklist(data: { type: string; value: string }) {
|
||||
return await db.blacklist.create({
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteFromBlacklist(where: { type: string; value: string }) {
|
||||
return await db.blacklist.deleteMany({
|
||||
where,
|
||||
});
|
||||
}
|
||||
+800
@@ -0,0 +1,800 @@
|
||||
import { Entity, EntityRelationship, EntityTag, EntityTemplate, Prisma, Property, PropertyAttribute, PropertyOption } from "@toolctrl/db/prisma-browser";
|
||||
import Constants from "~/application/Constants";
|
||||
import { DefaultLogActions } from "~/application/dtos/shared/DefaultLogActions";
|
||||
import { DefaultVisibility } from "~/application/dtos/shared/DefaultVisibility";
|
||||
import { defaultProperties } from "~/utils/helpers/PropertyHelper";
|
||||
import { db } from "../../db.server";
|
||||
import { EntityRelationshipWithDetails } from "./entityRelationships.db.server";
|
||||
import { EntityViewWithDetails } from "./entityViews.db.server";
|
||||
import { createProperties, CreatePropertyDto } from "./properties.db.server";
|
||||
import EntityModelHelper from "~/utils/helpers/models/EntityModelHelper";
|
||||
import EntityViewModelHelper from "~/utils/helpers/models/EntityViewModelHelper";
|
||||
import EntitiesSingleton from "~/modules/rows/repositories/EntitiesSingleton";
|
||||
|
||||
export type EntitySimple = {
|
||||
id: string;
|
||||
order: number;
|
||||
name: string;
|
||||
title: string;
|
||||
titlePlural: string;
|
||||
active: boolean;
|
||||
slug: string;
|
||||
type: string;
|
||||
hasApi: boolean;
|
||||
showInSidebar: boolean;
|
||||
icon: string;
|
||||
onEdit: string | null;
|
||||
};
|
||||
export type RowsUsage = { entityId: string; _count: number };
|
||||
export type EntityWithProperties = Entity & {
|
||||
properties: PropertyWithDetails[];
|
||||
};
|
||||
export type EntityWithDetails = Entity & {
|
||||
properties: PropertyWithDetails[];
|
||||
views: EntityViewWithDetails[];
|
||||
tags: EntityTag[];
|
||||
parentEntities: EntityRelationshipWithDetails[];
|
||||
childEntities: EntityRelationshipWithDetails[];
|
||||
templates: EntityTemplate[];
|
||||
};
|
||||
export type EntityWithDetailsAndRelationships = EntityWithDetails & {
|
||||
parentEntities: (EntityRelationship & { parent: { id: string; name: string; title: string; titlePlural: string; slug: string; onEdit: string | null } })[];
|
||||
childEntities: (EntityRelationship & { parent: { id: string; name: string; title: string; titlePlural: string; slug: string; onEdit: string | null } })[];
|
||||
};
|
||||
export type EntityWithCount = EntityWithDetails & {
|
||||
_count: { rows: number };
|
||||
};
|
||||
|
||||
export type PropertyWithDetails = Property & {
|
||||
// entity: EntityWithDetails;
|
||||
attributes: PropertyAttribute[];
|
||||
options: PropertyOption[];
|
||||
parent?: PropertyWithDetails;
|
||||
formula: { name: string; resultAs: string; calculationTrigger: string } | null;
|
||||
};
|
||||
|
||||
// const includeEntityWithDetails = {
|
||||
// properties: {
|
||||
// include: {
|
||||
// options: true,
|
||||
// },
|
||||
// },
|
||||
// };
|
||||
|
||||
export async function getEntitiesInIds(ids: string[]) {
|
||||
return await db.entity.findMany({
|
||||
where: { id: { in: ids } },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAllEntities({
|
||||
tenantId,
|
||||
active,
|
||||
types,
|
||||
}: {
|
||||
tenantId: string | null | undefined;
|
||||
active?: boolean;
|
||||
types?: string[];
|
||||
}): Promise<EntityWithDetails[]> {
|
||||
let where: Prisma.EntityWhereInput = {};
|
||||
if (active) {
|
||||
where = { active };
|
||||
}
|
||||
if (types) {
|
||||
where = { ...where, type: { in: types } };
|
||||
}
|
||||
const allEntities = await db.entity.findMany({
|
||||
where,
|
||||
orderBy: [
|
||||
{ type: "asc" },
|
||||
{
|
||||
order: "asc",
|
||||
},
|
||||
],
|
||||
include: {
|
||||
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
|
||||
tags: true,
|
||||
parentEntities: {
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
},
|
||||
orderBy: { order: "asc" },
|
||||
},
|
||||
childEntities: {
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
},
|
||||
orderBy: { order: "asc" },
|
||||
},
|
||||
properties: {
|
||||
where: { ...filterTenantId(tenantId) },
|
||||
orderBy: { order: "asc" },
|
||||
include: {
|
||||
attributes: true,
|
||||
options: {
|
||||
orderBy: {
|
||||
order: "asc",
|
||||
},
|
||||
},
|
||||
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
|
||||
},
|
||||
},
|
||||
templates: {
|
||||
where: { ...filterTenantId(tenantId) },
|
||||
},
|
||||
},
|
||||
});
|
||||
EntitiesSingleton.getInstance().setEntities(allEntities);
|
||||
return allEntities;
|
||||
}
|
||||
|
||||
export async function getAllEntitiesSimple({ active, types }: { active?: boolean; types?: string[] } = {}): Promise<EntitySimple[]> {
|
||||
let where: Prisma.EntityWhereInput = {};
|
||||
if (active) {
|
||||
where = { active };
|
||||
}
|
||||
if (types) {
|
||||
where = { ...where, type: { in: types } };
|
||||
}
|
||||
return await db.entity.findMany({
|
||||
where,
|
||||
orderBy: [
|
||||
{ type: "asc" },
|
||||
{
|
||||
order: "asc",
|
||||
},
|
||||
],
|
||||
select: EntityModelHelper.selectSimpleProperties,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEntitySimple({ id, name }: { id?: string; name?: string }): Promise<EntitySimple | null> {
|
||||
if (!id && !name) {
|
||||
return null;
|
||||
} else if (id) {
|
||||
return await db.entity.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
select: EntityModelHelper.selectSimpleProperties,
|
||||
});
|
||||
} else {
|
||||
return await db.entity.findUnique({
|
||||
where: {
|
||||
name,
|
||||
},
|
||||
select: EntityModelHelper.selectSimpleProperties,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function getEntitiesByName(name: string[]) {
|
||||
return await db.entity.findMany({
|
||||
where: {
|
||||
name: {
|
||||
in: name,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAllEntitiesWithRowCount({ tenantId }: { tenantId: string | null }): Promise<EntityWithCount[]> {
|
||||
return await db.entity.findMany({
|
||||
include: {
|
||||
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
|
||||
tags: true,
|
||||
parentEntities: {
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
},
|
||||
orderBy: { order: "asc" },
|
||||
},
|
||||
childEntities: {
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
},
|
||||
orderBy: { order: "asc" },
|
||||
},
|
||||
templates: {
|
||||
where: { ...filterTenantId(tenantId) },
|
||||
},
|
||||
_count: {
|
||||
select: {
|
||||
rows: true,
|
||||
},
|
||||
},
|
||||
properties: {
|
||||
where: { ...filterTenantId(tenantId) },
|
||||
orderBy: { order: "asc" },
|
||||
include: {
|
||||
attributes: true,
|
||||
options: {
|
||||
orderBy: {
|
||||
order: "asc",
|
||||
},
|
||||
},
|
||||
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: [
|
||||
{ type: "asc" },
|
||||
{
|
||||
order: "asc",
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAllRowsUsage(tenantId: string): Promise<RowsUsage[]> {
|
||||
const countEntities = await db.row.groupBy({
|
||||
by: ["entityId"],
|
||||
_count: true,
|
||||
where: {
|
||||
OR: [
|
||||
{
|
||||
tenantId,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
return countEntities;
|
||||
}
|
||||
|
||||
export async function getEntityById({ id, tenantId }: { id: string; tenantId: string | null | undefined }): Promise<EntityWithDetailsAndRelationships | null> {
|
||||
return await db.entity.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
include: {
|
||||
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
|
||||
tags: true,
|
||||
parentEntities: {
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
},
|
||||
orderBy: { order: "asc" },
|
||||
},
|
||||
childEntities: {
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
},
|
||||
orderBy: { order: "asc" },
|
||||
},
|
||||
properties: {
|
||||
where: { ...filterTenantId(tenantId) },
|
||||
orderBy: { order: "asc" },
|
||||
include: {
|
||||
attributes: true,
|
||||
options: {
|
||||
orderBy: {
|
||||
order: "asc",
|
||||
},
|
||||
},
|
||||
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
|
||||
},
|
||||
},
|
||||
templates: {
|
||||
where: { ...filterTenantId(tenantId) },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEntityBySlug({
|
||||
tenantId,
|
||||
slug,
|
||||
activeOnly,
|
||||
}: {
|
||||
tenantId: string | null;
|
||||
slug: string;
|
||||
activeOnly?: boolean;
|
||||
}): Promise<EntityWithDetails> {
|
||||
const entity = await db.entity.findUnique({
|
||||
where: {
|
||||
slug,
|
||||
},
|
||||
include: {
|
||||
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
|
||||
tags: true,
|
||||
parentEntities: {
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
},
|
||||
orderBy: { order: "asc" },
|
||||
},
|
||||
childEntities: {
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
},
|
||||
orderBy: { order: "asc" },
|
||||
},
|
||||
properties: {
|
||||
where: { ...filterTenantId(tenantId) },
|
||||
orderBy: { order: "asc" },
|
||||
include: {
|
||||
attributes: true,
|
||||
// entity: {
|
||||
// include: {
|
||||
// ...includePropertiesWithDetails,
|
||||
// },
|
||||
// },
|
||||
options: {
|
||||
orderBy: {
|
||||
order: "asc",
|
||||
},
|
||||
},
|
||||
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
|
||||
},
|
||||
},
|
||||
templates: {
|
||||
where: { ...filterTenantId(tenantId) },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!entity) {
|
||||
throw new Error(`Entity '${slug}' not found`);
|
||||
}
|
||||
if (activeOnly && !entity.active) {
|
||||
throw new Error(`Entity '${slug}' is not active`);
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
export async function getSimpleEntityBySlug(slug: string): Promise<EntitySimple | null> {
|
||||
return await db.entity.findUnique({
|
||||
where: {
|
||||
slug,
|
||||
},
|
||||
select: EntityModelHelper.selectSimpleProperties,
|
||||
});
|
||||
}
|
||||
|
||||
export async function findEntityBySlug(slug: string): Promise<Entity | null> {
|
||||
return await db.entity.findUnique({
|
||||
where: { slug },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEntityByName({ tenantId, name }: { tenantId: string | null | undefined; name: string }): Promise<EntityWithDetails> {
|
||||
const entity = await db.entity.findUnique({
|
||||
where: {
|
||||
name,
|
||||
},
|
||||
include: {
|
||||
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
|
||||
tags: true,
|
||||
parentEntities: {
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
},
|
||||
orderBy: { order: "asc" },
|
||||
},
|
||||
childEntities: {
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
},
|
||||
orderBy: { order: "asc" },
|
||||
},
|
||||
properties: {
|
||||
where: { ...filterTenantId(tenantId) },
|
||||
orderBy: { order: "asc" },
|
||||
include: {
|
||||
// entity: {
|
||||
// include: {
|
||||
// ...includePropertiesWithDetails,
|
||||
// },
|
||||
// },
|
||||
attributes: true,
|
||||
options: {
|
||||
orderBy: {
|
||||
order: "asc",
|
||||
},
|
||||
},
|
||||
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
|
||||
},
|
||||
},
|
||||
templates: {
|
||||
where: { ...filterTenantId(tenantId) },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!entity) {
|
||||
throw new Error(`Entity with name ${name} not found`);
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
export async function getEntityByIdOrName({
|
||||
tenantId,
|
||||
id,
|
||||
name,
|
||||
}: {
|
||||
tenantId: string | null | undefined;
|
||||
id?: string;
|
||||
name?: string;
|
||||
}): Promise<EntityWithDetails> {
|
||||
let entity: EntityWithDetails | null = null;
|
||||
if (id) {
|
||||
entity = await getEntityById({ tenantId, id });
|
||||
} else if (name) {
|
||||
entity = await getEntityByName({ tenantId, name });
|
||||
}
|
||||
if (!entity) {
|
||||
throw new Error(`Entity with id ${id} or name ${name} not found`);
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
export async function getEntityByIdNameOrSlug({ tenantId, idNameOrSlug }: { tenantId: string | null; idNameOrSlug: string }): Promise<EntityWithDetails> {
|
||||
return getEntityWithWhere({
|
||||
tenantId,
|
||||
where: {
|
||||
OR: [{ id: idNameOrSlug }, { name: idNameOrSlug }, { slug: idNameOrSlug }],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function getEntityWithWhere({ tenantId, where }: { tenantId: string | null; where: Prisma.EntityWhereInput }) {
|
||||
const entity = await db.entity.findFirst({
|
||||
where,
|
||||
include: {
|
||||
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
|
||||
tags: true,
|
||||
parentEntities: {
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
},
|
||||
orderBy: { order: "asc" },
|
||||
},
|
||||
childEntities: {
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
},
|
||||
orderBy: { order: "asc" },
|
||||
},
|
||||
properties: {
|
||||
where: { ...filterTenantId(tenantId) },
|
||||
orderBy: { order: "asc" },
|
||||
include: {
|
||||
// entity: {
|
||||
// include: {
|
||||
// ...includePropertiesWithDetails,
|
||||
// },
|
||||
// },
|
||||
attributes: true,
|
||||
options: {
|
||||
orderBy: {
|
||||
order: "asc",
|
||||
},
|
||||
},
|
||||
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
|
||||
},
|
||||
},
|
||||
templates: {
|
||||
where: { ...filterTenantId(tenantId) },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!entity) {
|
||||
throw new Error(`Entity not found`);
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
export async function findEntityByName({ tenantId, name }: { tenantId: string | null; name: string }): Promise<EntityWithDetails | null> {
|
||||
return await db.entity.findUnique({
|
||||
where: { name },
|
||||
include: {
|
||||
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
|
||||
tags: true,
|
||||
parentEntities: {
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
},
|
||||
orderBy: { order: "asc" },
|
||||
},
|
||||
childEntities: {
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
|
||||
},
|
||||
orderBy: { order: "asc" },
|
||||
},
|
||||
properties: {
|
||||
where: { ...filterTenantId(tenantId) },
|
||||
orderBy: { order: "asc" },
|
||||
include: {
|
||||
// entity: {
|
||||
// include: {
|
||||
// ...includePropertiesWithDetails,
|
||||
// },
|
||||
// },
|
||||
attributes: true,
|
||||
options: {
|
||||
orderBy: {
|
||||
order: "asc",
|
||||
},
|
||||
},
|
||||
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
|
||||
},
|
||||
},
|
||||
templates: {
|
||||
where: { ...filterTenantId(tenantId) },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function findSimpleEntityByName(name: string): Promise<{ id: string; title: string; titlePlural: string; slug: string } | null> {
|
||||
if (EntitiesSingleton.getInstance().isSet()) {
|
||||
return (
|
||||
EntitiesSingleton.getInstance()
|
||||
.getEntities()
|
||||
.find((f) => f.name === name) ?? null
|
||||
);
|
||||
}
|
||||
return await db.entity.findUnique({
|
||||
where: { name },
|
||||
select: { id: true, title: true, titlePlural: true, slug: true },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEntityByPrefix(prefix: string): Promise<Entity | null> {
|
||||
return await db.entity.findUnique({
|
||||
where: {
|
||||
prefix,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createEntity(
|
||||
data: {
|
||||
name: string;
|
||||
slug: string;
|
||||
prefix: string;
|
||||
title: string;
|
||||
titlePlural: string;
|
||||
isAutogenerated: boolean;
|
||||
type: string;
|
||||
hasApi: boolean;
|
||||
icon: string;
|
||||
active: boolean;
|
||||
showInSidebar: boolean;
|
||||
hasTags: boolean;
|
||||
hasComments: boolean;
|
||||
hasTasks: boolean;
|
||||
hasActivity: boolean;
|
||||
hasBulkDelete: boolean;
|
||||
hasViews: boolean;
|
||||
defaultVisibility: string;
|
||||
onCreated: string | null;
|
||||
onEdit: string | null;
|
||||
},
|
||||
order?: number | null
|
||||
) {
|
||||
if (!order) {
|
||||
order = (await getMaxEntityOrder()) + 1;
|
||||
}
|
||||
const entity = await db.entity.create({
|
||||
data: {
|
||||
...data,
|
||||
order,
|
||||
},
|
||||
});
|
||||
|
||||
const webhooks = [
|
||||
{
|
||||
action: DefaultLogActions.Created,
|
||||
method: "POST",
|
||||
endpoint: "",
|
||||
},
|
||||
{
|
||||
action: DefaultLogActions.Updated,
|
||||
method: "POST",
|
||||
endpoint: "",
|
||||
},
|
||||
{
|
||||
action: DefaultLogActions.Created,
|
||||
method: "POST",
|
||||
endpoint: "",
|
||||
},
|
||||
];
|
||||
|
||||
await Promise.all(
|
||||
webhooks.map(async (webhook) => {
|
||||
return await db.entityWebhook.create({
|
||||
data: {
|
||||
entityId: entity.id,
|
||||
action: webhook.action,
|
||||
method: webhook.method,
|
||||
endpoint: webhook.endpoint,
|
||||
},
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
await Promise.all(
|
||||
defaultProperties.map(async (property) => {
|
||||
return await db.property.create({
|
||||
data: {
|
||||
entityId: entity.id,
|
||||
...property,
|
||||
},
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
return entity;
|
||||
}
|
||||
|
||||
export async function createCoreEntity(
|
||||
data: {
|
||||
name: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
titlePlural: string;
|
||||
prefix: string;
|
||||
type: string;
|
||||
isAutogenerated?: boolean;
|
||||
hasApi?: boolean;
|
||||
icon?: string;
|
||||
active?: boolean;
|
||||
showInSidebar?: boolean;
|
||||
hasTags?: boolean;
|
||||
hasComments?: boolean;
|
||||
hasTasks?: boolean;
|
||||
hasActivity?: boolean;
|
||||
hasBulkDelete?: boolean;
|
||||
hasViews?: boolean;
|
||||
defaultVisibility?: DefaultVisibility;
|
||||
onCreated?: string | null;
|
||||
onEdit?: string | null;
|
||||
},
|
||||
properties?: CreatePropertyDto[]
|
||||
) {
|
||||
const entity = await createEntity({
|
||||
name: data.name,
|
||||
slug: data.slug,
|
||||
prefix: data.prefix,
|
||||
title: data.title,
|
||||
titlePlural: data.titlePlural,
|
||||
type: data.type,
|
||||
isAutogenerated: data.isAutogenerated !== undefined ? data.isAutogenerated : true,
|
||||
hasApi: data.hasApi !== undefined ? data.hasApi : true,
|
||||
icon: data.icon !== undefined ? data.icon : "",
|
||||
active: data.active !== undefined ? data.active : true,
|
||||
showInSidebar: data.showInSidebar !== undefined ? data.showInSidebar : true,
|
||||
hasTags: data.hasTags !== undefined ? data.hasTags : true,
|
||||
hasComments: data.hasComments !== undefined ? data.hasComments : true,
|
||||
hasTasks: data.hasTasks !== undefined ? data.hasTasks : false,
|
||||
hasActivity: data.hasActivity !== undefined ? data.hasActivity : true,
|
||||
hasBulkDelete: data.hasBulkDelete !== undefined ? data.hasBulkDelete : false,
|
||||
hasViews: data.hasViews !== undefined ? data.hasViews : true,
|
||||
defaultVisibility: data.defaultVisibility ?? Constants.DEFAULT_ROW_VISIBILITY,
|
||||
onCreated: data.onCreated ?? "redirectToOverview",
|
||||
onEdit: data.onEdit ?? "editRoute",
|
||||
});
|
||||
if (properties) {
|
||||
await createProperties(entity.id, properties);
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
export async function updateEntity(
|
||||
id: string,
|
||||
data: {
|
||||
name?: string;
|
||||
slug?: string;
|
||||
order?: number;
|
||||
prefix?: string;
|
||||
title?: string;
|
||||
titlePlural?: string;
|
||||
isAutogenerated?: boolean;
|
||||
type?: string;
|
||||
hasApi?: boolean;
|
||||
icon?: string;
|
||||
active?: boolean;
|
||||
showInSidebar?: boolean;
|
||||
hasTags?: boolean;
|
||||
hasComments?: boolean;
|
||||
hasTasks?: boolean;
|
||||
hasActivity?: boolean;
|
||||
hasBulkDelete?: boolean;
|
||||
hasViews?: boolean;
|
||||
defaultVisibility?: string;
|
||||
onCreated?: string | null;
|
||||
onEdit?: string | null;
|
||||
}
|
||||
) {
|
||||
return await db.entity.update({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteEntity(id: string) {
|
||||
return await db.entity.delete({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export default async function getMaxEntityOrder(): Promise<number> {
|
||||
return (
|
||||
(
|
||||
await db.entity.aggregate({
|
||||
_max: {
|
||||
order: true,
|
||||
},
|
||||
})
|
||||
)._max?.order ?? 0
|
||||
);
|
||||
}
|
||||
|
||||
export async function getDefaultEntityVisibility(id: string): Promise<DefaultVisibility> {
|
||||
return ((
|
||||
await db.entity.findUnique({
|
||||
where: { id },
|
||||
select: {
|
||||
defaultVisibility: true,
|
||||
},
|
||||
})
|
||||
)?.defaultVisibility ?? Constants.DEFAULT_ROW_VISIBILITY) as DefaultVisibility;
|
||||
}
|
||||
|
||||
function filterTenantId(tenantId: string | null | undefined) {
|
||||
const filter: { tenantId?: string | null; OR?: { tenantId?: string | null }[] } = {};
|
||||
if (tenantId === undefined) {
|
||||
return filter;
|
||||
} else if (tenantId === null) {
|
||||
filter.tenantId = null;
|
||||
} else {
|
||||
filter.OR = [{ tenantId: null }, { tenantId }];
|
||||
}
|
||||
return filter;
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
import { EntityGroup, EntityGroupEntity, Prisma } from "@toolctrl/db/prisma-browser";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { EntitySimple } from "./entities.db.server";
|
||||
import EntityModelHelper from "~/utils/helpers/models/EntityModelHelper";
|
||||
import { EntityViewWithDetails } from "./entityViews.db.server";
|
||||
|
||||
export type EntityGroupWithDetails = EntityGroup & {
|
||||
entities: EntityGroupEntityWithDetails[];
|
||||
};
|
||||
|
||||
export type EntityGroupEntityWithDetails = EntityGroupEntity & {
|
||||
entity: EntitySimple;
|
||||
allView: EntityViewWithDetails | null;
|
||||
};
|
||||
|
||||
export async function getAllEntityGroups(): Promise<EntityGroupWithDetails[]> {
|
||||
return db.entityGroup.findMany({
|
||||
include: {
|
||||
entities: {
|
||||
include: {
|
||||
entity: { select: EntityModelHelper.selectSimpleProperties },
|
||||
allView: { include: { properties: true, filters: true, sort: true, groupByProperty: true } },
|
||||
},
|
||||
orderBy: { entity: { order: "asc" } },
|
||||
},
|
||||
},
|
||||
orderBy: { order: "asc" },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEntityGroup(id: string): Promise<EntityGroupWithDetails | null> {
|
||||
return db.entityGroup.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
entities: {
|
||||
include: {
|
||||
entity: { select: EntityModelHelper.selectSimpleProperties },
|
||||
allView: { include: { properties: true, filters: true, sort: true, groupByProperty: true } },
|
||||
},
|
||||
orderBy: { entity: { order: "asc" } },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEntityGroupBySlug(slug: string): Promise<EntityGroupWithDetails | null> {
|
||||
return db.entityGroup.findUnique({
|
||||
where: { slug },
|
||||
include: {
|
||||
entities: {
|
||||
include: {
|
||||
entity: { select: EntityModelHelper.selectSimpleProperties },
|
||||
allView: { include: { properties: true, filters: true, sort: true, groupByProperty: true } },
|
||||
},
|
||||
orderBy: { entity: { order: "asc" } },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createEntityGroup(data: {
|
||||
order: number;
|
||||
slug: string;
|
||||
title: string;
|
||||
icon: string;
|
||||
collapsible: boolean;
|
||||
section: string | null;
|
||||
entities: {
|
||||
entityId: string;
|
||||
allViewId: string | null;
|
||||
}[];
|
||||
}): Promise<EntityGroup> {
|
||||
return db.entityGroup.create({
|
||||
data: {
|
||||
order: data.order,
|
||||
slug: data.slug,
|
||||
title: data.title,
|
||||
icon: data.icon,
|
||||
collapsible: data.collapsible,
|
||||
section: data.section,
|
||||
entities: {
|
||||
create: data.entities.map((f) => {
|
||||
return {
|
||||
entityId: f.entityId,
|
||||
allViewId: f.allViewId,
|
||||
};
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateEntityGroup(
|
||||
id: string,
|
||||
data: {
|
||||
order?: number;
|
||||
slug?: string;
|
||||
title?: string;
|
||||
icon?: string;
|
||||
collapsible?: boolean;
|
||||
section?: string | null;
|
||||
entities?: {
|
||||
entityId: string;
|
||||
allViewId: string | null;
|
||||
}[];
|
||||
}
|
||||
): Promise<EntityGroup> {
|
||||
let update: Prisma.EntityGroupUpdateInput = {
|
||||
order: data.order,
|
||||
slug: data.slug,
|
||||
title: data.title,
|
||||
icon: data.icon,
|
||||
collapsible: data.collapsible,
|
||||
section: data.section,
|
||||
};
|
||||
if (data.entities) {
|
||||
update.entities = {
|
||||
deleteMany: {},
|
||||
create: data.entities.map((f) => {
|
||||
return {
|
||||
entityId: f.entityId,
|
||||
allViewId: f.allViewId,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
return db.entityGroup.update({
|
||||
where: { id },
|
||||
data: update,
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteEntityGroup(id: string): Promise<EntityGroup> {
|
||||
return db.entityGroup.delete({
|
||||
where: { id },
|
||||
});
|
||||
}
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
import { EntityRelationship } from "@toolctrl/db/prisma-browser";
|
||||
import { db } from "../../db.server";
|
||||
import { EntityViewWithDetails } from "./entityViews.db.server";
|
||||
import EntityViewModelHelper from "~/utils/helpers/models/EntityViewModelHelper";
|
||||
import EntityModelHelper from "~/utils/helpers/models/EntityModelHelper";
|
||||
|
||||
export type EntityRelationshipWithDetails = EntityRelationship & {
|
||||
parent: { id: string; name: string; title: string; titlePlural: string; slug: string; onEdit: string | null };
|
||||
child: { id: string; name: string; title: string; titlePlural: string; slug: string; onEdit: string | null };
|
||||
childEntityView: EntityViewWithDetails | null;
|
||||
parentEntityView: EntityViewWithDetails | null;
|
||||
};
|
||||
|
||||
export type EntityRelationshipWithCount = EntityRelationshipWithDetails & {
|
||||
_count: { rows: number };
|
||||
};
|
||||
|
||||
export async function getAllEntityRelationships(): Promise<EntityRelationshipWithDetails[]> {
|
||||
return await db.entityRelationship.findMany({
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { include: EntityViewModelHelper.includeDetails },
|
||||
},
|
||||
});
|
||||
}
|
||||
export async function findEntityRelationship({
|
||||
parentId,
|
||||
childId,
|
||||
title,
|
||||
notIn,
|
||||
}: {
|
||||
parentId: string;
|
||||
childId: string;
|
||||
title: string | null;
|
||||
notIn?: string[];
|
||||
}): Promise<EntityRelationshipWithCount | null> {
|
||||
return await db.entityRelationship.findFirst({
|
||||
where: {
|
||||
OR: [
|
||||
{ parentId, childId },
|
||||
{ parentId: childId, childId: parentId },
|
||||
],
|
||||
title,
|
||||
id: {
|
||||
notIn,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { include: EntityViewModelHelper.includeDetails },
|
||||
_count: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEntityRelationships(entityId: string): Promise<EntityRelationshipWithDetails[]> {
|
||||
return await db.entityRelationship.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{
|
||||
parentId: entityId,
|
||||
},
|
||||
{
|
||||
childId: entityId,
|
||||
},
|
||||
],
|
||||
},
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { include: EntityViewModelHelper.includeDetails },
|
||||
},
|
||||
orderBy: [{ order: "asc" }],
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEntityRelationshipsWithCount(entityId: string): Promise<EntityRelationshipWithCount[]> {
|
||||
return await db.entityRelationship.findMany({
|
||||
where: {
|
||||
OR: [{ parentId: entityId }, { childId: entityId }],
|
||||
},
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { include: EntityViewModelHelper.includeDetails },
|
||||
_count: true,
|
||||
},
|
||||
orderBy: [{ order: "asc" }],
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEntitiesRelationship({
|
||||
parentEntityId,
|
||||
childEntityId,
|
||||
}: {
|
||||
parentEntityId: string;
|
||||
childEntityId: string;
|
||||
}): Promise<EntityRelationshipWithDetails | null> {
|
||||
return await db.entityRelationship.findFirst({
|
||||
where: {
|
||||
parentId: parentEntityId,
|
||||
childId: childEntityId,
|
||||
},
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { include: EntityViewModelHelper.includeDetails },
|
||||
},
|
||||
orderBy: [{ order: "asc" }],
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEntityRelationship(id: string): Promise<EntityRelationshipWithCount | null> {
|
||||
return await db.entityRelationship.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { include: EntityViewModelHelper.includeDetails },
|
||||
_count: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
type EntityRelationshipScope = {
|
||||
id: string;
|
||||
entityId: string;
|
||||
};
|
||||
|
||||
function relationshipScopeWhere(scope: EntityRelationshipScope) {
|
||||
return {
|
||||
id: scope.id,
|
||||
OR: [{ parentId: scope.entityId }, { childId: scope.entityId }],
|
||||
};
|
||||
}
|
||||
|
||||
export async function getScopedEntityRelationship(scope: EntityRelationshipScope): Promise<EntityRelationshipWithCount | null> {
|
||||
return await db.entityRelationship.findFirst({
|
||||
where: relationshipScopeWhere(scope),
|
||||
include: {
|
||||
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
child: { select: EntityModelHelper.selectEntityWithoutIcon },
|
||||
childEntityView: { include: EntityViewModelHelper.includeDetails },
|
||||
parentEntityView: { include: EntityViewModelHelper.includeDetails },
|
||||
_count: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createEntityRelationship({
|
||||
parentId,
|
||||
childId,
|
||||
order,
|
||||
title,
|
||||
type,
|
||||
required,
|
||||
cascade,
|
||||
readOnly,
|
||||
hiddenIfEmpty,
|
||||
childEntityViewId,
|
||||
parentEntityViewId,
|
||||
}: {
|
||||
parentId: string;
|
||||
childId: string;
|
||||
order: number;
|
||||
title: string | null;
|
||||
type: string;
|
||||
required: boolean;
|
||||
cascade: boolean;
|
||||
readOnly: boolean;
|
||||
hiddenIfEmpty: boolean;
|
||||
childEntityViewId: string | null;
|
||||
parentEntityViewId: string | null;
|
||||
}) {
|
||||
return await db.entityRelationship.create({
|
||||
data: {
|
||||
parentId,
|
||||
childId,
|
||||
order,
|
||||
title,
|
||||
type,
|
||||
required,
|
||||
cascade,
|
||||
readOnly,
|
||||
hiddenIfEmpty,
|
||||
childEntityViewId,
|
||||
parentEntityViewId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateEntityRelationship(
|
||||
id: string,
|
||||
data: {
|
||||
parentId?: string;
|
||||
childId?: string;
|
||||
order?: number;
|
||||
title?: string | null;
|
||||
type?: string;
|
||||
required?: boolean;
|
||||
cascade?: boolean;
|
||||
readOnly?: boolean;
|
||||
hiddenIfEmpty?: boolean;
|
||||
childEntityViewId?: string | null;
|
||||
parentEntityViewId?: string | null;
|
||||
}
|
||||
) {
|
||||
return await db.entityRelationship.update({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
data: {
|
||||
...data,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
type UpdateEntityRelationshipData = Parameters<typeof updateEntityRelationship>[1];
|
||||
|
||||
export async function updateScopedEntityRelationship(scope: EntityRelationshipScope, data: UpdateEntityRelationshipData) {
|
||||
const result = await db.entityRelationship.updateMany({
|
||||
where: relationshipScopeWhere(scope),
|
||||
data: {
|
||||
...data,
|
||||
},
|
||||
});
|
||||
if (result.count !== 1) {
|
||||
throw Error("Relationship not found");
|
||||
}
|
||||
return await getScopedEntityRelationship(scope);
|
||||
}
|
||||
|
||||
export async function deleteEntityRelationship(id: string) {
|
||||
return await db.entityRelationship.delete({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteScopedEntityRelationship(scope: EntityRelationshipScope) {
|
||||
const result = await db.entityRelationship.deleteMany({
|
||||
where: relationshipScopeWhere(scope),
|
||||
});
|
||||
if (result.count !== 1) {
|
||||
throw Error("Relationship not found");
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: {
|
||||
entityTag: {
|
||||
findFirst: vi.fn(),
|
||||
findUnique: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { db } from "~/utils/db.server";
|
||||
import { deleteEntityTag, getEntityTagById, updateEntityTag } from "./entityTags.db.server";
|
||||
|
||||
const entityTagMock = vi.mocked(db.entityTag, true);
|
||||
|
||||
describe("entity tag tenant boundary helpers", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("can resolve tags by id within an entity scope", async () => {
|
||||
const tag = { id: "tag_1", entityId: "entity_1", value: "Warm", color: 3, createdAt: new Date("2026-01-01T00:00:00.000Z") };
|
||||
entityTagMock.findFirst.mockResolvedValueOnce(tag);
|
||||
|
||||
await expect(getEntityTagById("tag_1", "entity_1")).resolves.toEqual(tag);
|
||||
|
||||
expect(entityTagMock.findFirst).toHaveBeenCalledWith({ where: { id: "tag_1", entityId: "entity_1" } });
|
||||
expect(entityTagMock.findUnique).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("updates and deletes tags with id and entity scope", async () => {
|
||||
entityTagMock.updateMany.mockResolvedValueOnce({ count: 1 });
|
||||
entityTagMock.deleteMany.mockResolvedValueOnce({ count: 1 });
|
||||
|
||||
await updateEntityTag({ id: "tag_1", entityId: "entity_1" }, { value: "Warm", color: 3 });
|
||||
await deleteEntityTag({ id: "tag_1", entityId: "entity_1" });
|
||||
|
||||
expect(entityTagMock.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: "tag_1", entityId: "entity_1" },
|
||||
data: { value: "Warm", color: 3 },
|
||||
});
|
||||
expect(entityTagMock.deleteMany).toHaveBeenCalledWith({ where: { id: "tag_1", entityId: "entity_1" } });
|
||||
});
|
||||
});
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
import { EntityTag } from "@toolctrl/db/prisma-browser";
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
export async function getEntityTags(entityId: string): Promise<EntityTag[]> {
|
||||
return await db.entityTag.findMany({
|
||||
where: {
|
||||
entityId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEntityTagById(id: string, entityId?: string): Promise<EntityTag | null> {
|
||||
if (entityId) {
|
||||
return await db.entityTag.findFirst({
|
||||
where: {
|
||||
id,
|
||||
entityId,
|
||||
},
|
||||
});
|
||||
}
|
||||
return await db.entityTag.findUnique({ where: { id } });
|
||||
}
|
||||
|
||||
export async function getEntityTag(entityId: string, value: string): Promise<EntityTag | null> {
|
||||
return await db.entityTag.findFirst({
|
||||
where: {
|
||||
entityId,
|
||||
value,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEntityTagByEntityName(entityName: string, value: string): Promise<EntityTag | null> {
|
||||
return await db.entityTag.findFirst({
|
||||
where: {
|
||||
entity: { name: entityName },
|
||||
value,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createEntityTag(data: { entityId: string; color: number; value: string }) {
|
||||
return await db.entityTag.create({
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateEntityTag({ id, entityId }: { id: string; entityId: string }, data: { color?: number; value?: string }) {
|
||||
return await db.entityTag.updateMany({
|
||||
where: {
|
||||
id,
|
||||
entityId,
|
||||
},
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteEntityTag({ id, entityId }: { id: string; entityId: string }) {
|
||||
return await db.entityTag.deleteMany({
|
||||
where: {
|
||||
id,
|
||||
entityId,
|
||||
},
|
||||
});
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
export async function getEntityTemplates(entityId: string, { tenantId }: { tenantId: string | null }) {
|
||||
return await db.entityTemplate.findMany({
|
||||
where: { entityId, tenantId },
|
||||
orderBy: { entity: { order: "asc" } },
|
||||
});
|
||||
}
|
||||
|
||||
type EntityTemplateScope = {
|
||||
id: string;
|
||||
tenantId: string | null;
|
||||
entityId: string;
|
||||
};
|
||||
|
||||
export async function getEntityTemplate(id: string, { tenantId, entityId }: { tenantId: string | null; entityId?: string }) {
|
||||
return await db.entityTemplate
|
||||
.findFirstOrThrow({
|
||||
where: { id, tenantId, ...(entityId ? { entityId } : {}) },
|
||||
})
|
||||
.catch(() => {
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
export async function createEntityTemplate(data: { tenantId: string | null; entityId: string; title: string; config: string }) {
|
||||
return await db.entityTemplate.create({
|
||||
data: {
|
||||
tenantId: data.tenantId,
|
||||
entityId: data.entityId,
|
||||
title: data.title,
|
||||
config: data.config,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateEntityTemplate(id: string, data: { title: string; config: string }) {
|
||||
return await db.entityTemplate.update({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateScopedEntityTemplate(scope: EntityTemplateScope, data: { title: string; config: string }) {
|
||||
const result = await db.entityTemplate.updateMany({
|
||||
where: scope,
|
||||
data,
|
||||
});
|
||||
if (result.count !== 1) {
|
||||
throw Error("Entity template not found");
|
||||
}
|
||||
return await getEntityTemplate(scope.id, { tenantId: scope.tenantId, entityId: scope.entityId });
|
||||
}
|
||||
|
||||
export async function deleteEntityTemplate(id: string) {
|
||||
return await db.entityTemplate.delete({
|
||||
where: { id },
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteScopedEntityTemplate(scope: EntityTemplateScope) {
|
||||
const result = await db.entityTemplate.deleteMany({
|
||||
where: scope,
|
||||
});
|
||||
if (result.count !== 1) {
|
||||
throw Error("Entity template not found");
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import path from "node:path";
|
||||
|
||||
const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "entityViews.db.server.ts"), "utf8");
|
||||
|
||||
describe("entity views db wrapper", () => {
|
||||
test("does not include tenant user-private views unless a user id is explicit", () => {
|
||||
expect(source).toContain("const userId = options.userId ?? null");
|
||||
expect(source).toContain("if (userId) {\n scope.unshift({ tenantId: options.tenantId, userId });\n }");
|
||||
});
|
||||
|
||||
test("supports scoped entity-view lookup by id", () => {
|
||||
expect(source).toContain("entityId: options?.entityId");
|
||||
expect(source).toContain("...buildEntityViewScopeWhere({ tenantId: options?.tenantId, userId: options?.userId })");
|
||||
});
|
||||
});
|
||||
+422
@@ -0,0 +1,422 @@
|
||||
import { EntityView, EntityViewFilter, EntityViewProperty, EntityViewSort, Prisma, Property } from "@toolctrl/db/prisma-browser";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { UserSimple } from "../users.db.server";
|
||||
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
|
||||
import TenantModelHelper from "~/utils/helpers/models/TenantModelHelper";
|
||||
import { TenantSimple } from "../tenants.db.server";
|
||||
import EntityModelHelper from "~/utils/helpers/models/EntityModelHelper";
|
||||
import { EntitySimple } from "./entities.db.server";
|
||||
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
|
||||
import EntityViewModelHelper from "~/utils/helpers/models/EntityViewModelHelper";
|
||||
|
||||
export type EntityViewWithDetails = EntityView & {
|
||||
properties: EntityViewProperty[];
|
||||
filters: EntityViewFilter[];
|
||||
sort: EntityViewSort[];
|
||||
groupByProperty: Property | null;
|
||||
};
|
||||
|
||||
export type EntityViewWithTenantAndUser = EntityViewWithDetails & {
|
||||
entity: EntitySimple;
|
||||
createdByUser: UserSimple | null;
|
||||
tenant: TenantSimple | null;
|
||||
user: UserSimple | null;
|
||||
};
|
||||
|
||||
export async function getAllEntityViews({
|
||||
type,
|
||||
entityId,
|
||||
pagination,
|
||||
filters,
|
||||
}: {
|
||||
type?: string;
|
||||
entityId?: string;
|
||||
pagination?: { pageSize: number; page: number };
|
||||
filters?: FiltersDto;
|
||||
}): Promise<{ items: EntityViewWithTenantAndUser[]; total: number }> {
|
||||
let where: Prisma.EntityViewWhereInput = {
|
||||
entityId,
|
||||
};
|
||||
if (type === "default") {
|
||||
where = { tenantId: null, userId: null, isSystem: false };
|
||||
} else if (type === "tenant") {
|
||||
where = { tenantId: { not: null }, userId: null, isSystem: false };
|
||||
} else if (type === "user") {
|
||||
where = { userId: { not: null }, isSystem: false };
|
||||
} else if (type === "system") {
|
||||
where = { isSystem: true };
|
||||
}
|
||||
|
||||
const filterEntityId = filters?.properties.find((filter) => filter.name === "entityId")?.value;
|
||||
const filterTenantId = filters?.properties.find((filter) => filter.name === "tenantId")?.value;
|
||||
const filterUserId = filters?.properties.find((filter) => filter.name === "userId")?.value;
|
||||
if (filterEntityId) {
|
||||
where = { ...where, entityId: filterEntityId };
|
||||
}
|
||||
if (filterTenantId) {
|
||||
where = { ...where, tenantId: filterTenantId };
|
||||
}
|
||||
if (filterUserId) {
|
||||
where = { ...where, userId: filterUserId };
|
||||
}
|
||||
|
||||
const items = await db.entityView.findMany({
|
||||
take: pagination?.pageSize,
|
||||
skip: pagination ? pagination.pageSize * (pagination.page - 1) : undefined,
|
||||
where,
|
||||
include: {
|
||||
...EntityViewModelHelper.includeDetails,
|
||||
entity: { select: EntityModelHelper.selectSimpleProperties },
|
||||
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
|
||||
tenant: { select: TenantModelHelper.selectSimpleTenantProperties },
|
||||
user: { select: UserModelHelper.selectSimpleUserProperties },
|
||||
},
|
||||
orderBy: [{ tenantId: "asc" }, { userId: "asc" }, { order: "asc" }],
|
||||
});
|
||||
const total = await db.entityView.count({ where });
|
||||
return {
|
||||
items,
|
||||
total,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getEntityViews(
|
||||
entityId: string,
|
||||
options?: {
|
||||
tenantId?: string | null;
|
||||
userId?: string | null;
|
||||
}
|
||||
): Promise<EntityViewWithDetails[]> {
|
||||
let where: Prisma.EntityViewWhereInput = {
|
||||
entityId,
|
||||
isSystem: false,
|
||||
};
|
||||
if (options?.tenantId !== undefined) {
|
||||
const userId = options.userId ?? null;
|
||||
const scope: Prisma.EntityViewWhereInput[] = [{ tenantId: options.tenantId, userId: null }, { tenantId: null, userId: null }];
|
||||
if (userId) {
|
||||
scope.unshift({ tenantId: options.tenantId, userId });
|
||||
}
|
||||
where = {
|
||||
...where,
|
||||
OR: scope,
|
||||
};
|
||||
}
|
||||
return await db.entityView.findMany({
|
||||
where,
|
||||
include: EntityViewModelHelper.includeDetails,
|
||||
orderBy: {
|
||||
order: "asc",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function buildEntityViewScopeWhere({
|
||||
tenantId,
|
||||
userId,
|
||||
}: {
|
||||
tenantId?: string | null;
|
||||
userId?: string | null;
|
||||
}): Prisma.EntityViewWhereInput {
|
||||
if (tenantId === undefined) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
OR: [
|
||||
{ tenantId, userId },
|
||||
{ tenantId, userId: null },
|
||||
{ tenantId: null, userId: null },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export async function getEntityView(
|
||||
id: string,
|
||||
options?: {
|
||||
entityId?: string;
|
||||
tenantId?: string | null;
|
||||
userId?: string | null;
|
||||
}
|
||||
): Promise<EntityViewWithDetails | null> {
|
||||
return await db.entityView.findFirst({
|
||||
where: {
|
||||
id,
|
||||
entityId: options?.entityId,
|
||||
...buildEntityViewScopeWhere({ tenantId: options?.tenantId, userId: options?.userId }),
|
||||
},
|
||||
include: EntityViewModelHelper.includeDetails,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEntityViewWithTenantAndUser(id: string): Promise<EntityViewWithTenantAndUser | null> {
|
||||
return await db.entityView.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
include: {
|
||||
...EntityViewModelHelper.includeDetails,
|
||||
entity: { select: EntityModelHelper.selectSimpleProperties },
|
||||
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
|
||||
tenant: { select: TenantModelHelper.selectSimpleTenantProperties },
|
||||
user: { select: UserModelHelper.selectSimpleUserProperties },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEntityViewByName({
|
||||
entityId,
|
||||
name,
|
||||
isSystem,
|
||||
tenantId,
|
||||
userId,
|
||||
}: {
|
||||
entityId: string;
|
||||
name: string;
|
||||
isSystem?: boolean;
|
||||
tenantId?: string | null;
|
||||
userId?: string | null;
|
||||
}): Promise<EntityViewWithDetails | null> {
|
||||
return await db.entityView.findFirst({
|
||||
where: {
|
||||
entityId,
|
||||
name,
|
||||
isSystem,
|
||||
...buildEntityViewScopeWhere({ tenantId, userId }),
|
||||
},
|
||||
include: EntityViewModelHelper.includeDetails,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEntityViewDefault({
|
||||
entityId,
|
||||
isSystem,
|
||||
tenantId,
|
||||
userId,
|
||||
}: {
|
||||
entityId: string;
|
||||
isSystem?: boolean;
|
||||
tenantId?: string | null;
|
||||
userId?: string | null;
|
||||
}): Promise<EntityViewWithDetails | null> {
|
||||
return await db.entityView.findFirst({
|
||||
where: {
|
||||
entityId,
|
||||
isSystem,
|
||||
isDefault: true,
|
||||
...buildEntityViewScopeWhere({ tenantId, userId }),
|
||||
},
|
||||
include: EntityViewModelHelper.includeDetails,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEntityViewByOrder(entityId: string, order: number): Promise<EntityViewWithDetails | null> {
|
||||
return await db.entityView.findFirst({
|
||||
where: {
|
||||
entityId,
|
||||
order,
|
||||
},
|
||||
include: EntityViewModelHelper.includeDetails,
|
||||
});
|
||||
}
|
||||
|
||||
export default async function getMaxEntityViewOrder(entityId: string): Promise<number> {
|
||||
return (
|
||||
(
|
||||
await db.entityView.aggregate({
|
||||
where: { entityId },
|
||||
_max: {
|
||||
order: true,
|
||||
},
|
||||
})
|
||||
)._max?.order ?? 0
|
||||
);
|
||||
}
|
||||
|
||||
export async function createEntityView(data: {
|
||||
entityId: string;
|
||||
tenantId: string | null;
|
||||
userId: string | null;
|
||||
createdByUserId: string;
|
||||
layout: string;
|
||||
name: string;
|
||||
title: string;
|
||||
isDefault: boolean;
|
||||
isSystem: boolean;
|
||||
pageSize: number;
|
||||
groupByPropertyId?: string | null;
|
||||
gridColumns?: number;
|
||||
gridColumnsSm?: number;
|
||||
gridColumnsMd?: number;
|
||||
gridColumnsLg?: number;
|
||||
gridColumnsXl?: number;
|
||||
gridColumns2xl?: number;
|
||||
gridGap?: string;
|
||||
order?: number;
|
||||
}) {
|
||||
if (!data.order) {
|
||||
data.order = (await getMaxEntityViewOrder(data.entityId)) + 1;
|
||||
}
|
||||
return await db.entityView.create({
|
||||
data: {
|
||||
entityId: data.entityId,
|
||||
tenantId: data.tenantId,
|
||||
userId: data.userId,
|
||||
createdByUserId: data.createdByUserId,
|
||||
layout: data.layout,
|
||||
order: data.order,
|
||||
name: data.name,
|
||||
title: data.title,
|
||||
isDefault: data.isDefault,
|
||||
isSystem: data.isSystem,
|
||||
pageSize: data.pageSize,
|
||||
groupByPropertyId: data.groupByPropertyId,
|
||||
gridColumns: data.gridColumns ?? 5,
|
||||
gridColumnsSm: data.gridColumnsSm ?? 2,
|
||||
gridColumnsMd: data.gridColumnsMd ?? 3,
|
||||
gridColumnsLg: data.gridColumnsLg ?? 4,
|
||||
gridColumnsXl: data.gridColumnsXl ?? 5,
|
||||
gridColumns2xl: data.gridColumns2xl ?? 6,
|
||||
gridGap: data.gridGap ?? "sm",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateEntityViewProperties(id: string, items: { propertyId: string | null; name: string; order: number }[]) {
|
||||
await db.entityViewProperty.deleteMany({
|
||||
where: { entityViewId: id },
|
||||
});
|
||||
return await Promise.all(
|
||||
items.map(async (item) => {
|
||||
return await db.entityViewProperty.create({
|
||||
data: {
|
||||
entityViewId: id,
|
||||
propertyId: item.propertyId,
|
||||
name: item.name,
|
||||
order: item.order,
|
||||
},
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
type EntityViewScope = {
|
||||
id: string;
|
||||
entityId: string;
|
||||
tenantId: string | null;
|
||||
userId: string | null;
|
||||
};
|
||||
|
||||
async function assertScopedEntityView(scope: EntityViewScope) {
|
||||
const view = await getEntityView(scope.id, { entityId: scope.entityId, tenantId: scope.tenantId, userId: scope.userId });
|
||||
if (!view || view.tenantId !== scope.tenantId || view.userId !== scope.userId) {
|
||||
throw Error("Entity view not found");
|
||||
}
|
||||
return view;
|
||||
}
|
||||
|
||||
export async function updateScopedEntityViewProperties(scope: EntityViewScope, items: { propertyId: string | null; name: string; order: number }[]) {
|
||||
await assertScopedEntityView(scope);
|
||||
return await updateEntityViewProperties(scope.id, items);
|
||||
}
|
||||
|
||||
export async function updateEntityViewFilters(id: string, items: { name: string; condition: string; value: string; match: string }[]) {
|
||||
await db.entityViewFilter.deleteMany({
|
||||
where: { entityViewId: id },
|
||||
});
|
||||
return await Promise.all(
|
||||
items.map(async (item) => {
|
||||
return await db.entityViewFilter.create({
|
||||
data: {
|
||||
entityViewId: id,
|
||||
name: item.name,
|
||||
condition: item.condition,
|
||||
value: item.value,
|
||||
match: item.match,
|
||||
},
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export async function updateScopedEntityViewFilters(scope: EntityViewScope, items: { name: string; condition: string; value: string; match: string }[]) {
|
||||
await assertScopedEntityView(scope);
|
||||
return await updateEntityViewFilters(scope.id, items);
|
||||
}
|
||||
|
||||
export async function updateEntityViewSort(id: string, items: { name: string; asc: boolean; order: number }[]) {
|
||||
await db.entityViewSort.deleteMany({
|
||||
where: { entityViewId: id },
|
||||
});
|
||||
return await Promise.all(
|
||||
items.map(async (item) => {
|
||||
return await db.entityViewSort.create({
|
||||
data: {
|
||||
entityViewId: id,
|
||||
name: item.name,
|
||||
asc: item.asc,
|
||||
order: item.order,
|
||||
},
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export async function updateScopedEntityViewSort(scope: EntityViewScope, items: { name: string; asc: boolean; order: number }[]) {
|
||||
await assertScopedEntityView(scope);
|
||||
return await updateEntityViewSort(scope.id, items);
|
||||
}
|
||||
|
||||
export async function updateEntityView(
|
||||
id: string,
|
||||
data: {
|
||||
layout?: string;
|
||||
isDefault?: boolean;
|
||||
isSystem?: boolean;
|
||||
pageSize?: number;
|
||||
name?: string;
|
||||
title?: string;
|
||||
order?: number;
|
||||
groupByPropertyId?: string | null;
|
||||
gridColumns?: number;
|
||||
gridColumnsSm?: number;
|
||||
gridColumnsMd?: number;
|
||||
gridColumnsLg?: number;
|
||||
gridColumnsXl?: number;
|
||||
gridColumns2xl?: number;
|
||||
gridGap?: string;
|
||||
}
|
||||
) {
|
||||
return await db.entityView.update({
|
||||
where: { id },
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
type UpdateEntityViewData = Parameters<typeof updateEntityView>[1];
|
||||
|
||||
export async function updateScopedEntityView(scope: EntityViewScope, data: UpdateEntityViewData) {
|
||||
const result = await db.entityView.updateMany({
|
||||
where: scope,
|
||||
data,
|
||||
});
|
||||
if (result.count !== 1) {
|
||||
throw Error("Entity view not found");
|
||||
}
|
||||
return await assertScopedEntityView(scope);
|
||||
}
|
||||
|
||||
export async function deleteEntityView(id: string) {
|
||||
return await db.entityView.delete({
|
||||
where: { id },
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteScopedEntityView(scope: EntityViewScope) {
|
||||
const result = await db.entityView.deleteMany({
|
||||
where: scope,
|
||||
});
|
||||
if (result.count !== 1) {
|
||||
throw Error("Entity view not found");
|
||||
}
|
||||
}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: {
|
||||
entityWebhook: {
|
||||
deleteMany: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
},
|
||||
entityWebhookLog: {
|
||||
create: vi.fn(async (args) => args.data),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/url.server", () => ({
|
||||
getBaseURL: vi.fn((request: Request) => new URL(request.url).origin),
|
||||
}));
|
||||
|
||||
// The shared outbound client resolves DNS and rejects hosts that resolve to
|
||||
// internal addresses. Stub the resolver so public test hosts resolve to a
|
||||
// public IP, while a chosen host simulates DNS rebinding to a metadata address.
|
||||
vi.mock("node:dns/promises", () => ({
|
||||
lookup: vi.fn(async (hostname: string) => {
|
||||
if (hostname === "rebind.attacker.test") {
|
||||
return [{ address: "169.254.169.254", family: 4 }];
|
||||
}
|
||||
return [{ address: "93.184.216.34", family: 4 }];
|
||||
}),
|
||||
}));
|
||||
|
||||
import { db } from "~/utils/db.server";
|
||||
import { callEntityWebhooks, deleteEntityWebhook, getEntityWebhook, updateEntityWebhook } from "./entityWebhooks.db.server";
|
||||
|
||||
const entityWebhookMock = vi.mocked(db.entityWebhook, true);
|
||||
const entityWebhookLogMock = vi.mocked(db.entityWebhookLog, true);
|
||||
|
||||
describe("entity webhook delivery", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 204 })));
|
||||
});
|
||||
|
||||
it("delivers allowed absolute webhook URLs", async () => {
|
||||
entityWebhookMock.findMany.mockResolvedValueOnce([
|
||||
{ id: "webhook_absolute", entityId: "entity_1", action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" },
|
||||
]);
|
||||
|
||||
await callEntityWebhooks({
|
||||
logId: "log_1",
|
||||
entityId: "entity_1",
|
||||
action: "created",
|
||||
body: "payload",
|
||||
request: new Request("https://tenant.example.com/api/rows"),
|
||||
});
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith("https://hooks.example.com/rows", expect.objectContaining({ redirect: "manual", signal: expect.any(AbortSignal) }));
|
||||
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_absolute", logId: "log_1", status: 204 } });
|
||||
});
|
||||
|
||||
it("delivers webhooks at request-relative endpoints resolved against the base URL", async () => {
|
||||
entityWebhookMock.findMany.mockResolvedValueOnce([
|
||||
{ id: "webhook_relative", entityId: "entity_1", action: "created", method: "POST", endpoint: "/webhooks/rows" },
|
||||
]);
|
||||
|
||||
await callEntityWebhooks({
|
||||
logId: "log_1",
|
||||
entityId: "entity_1",
|
||||
action: "created",
|
||||
body: "payload",
|
||||
request: new Request("https://tenant.example.com/api/rows"),
|
||||
});
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith("https://tenant.example.com/webhooks/rows", expect.objectContaining({ redirect: "manual", signal: expect.any(AbortSignal) }));
|
||||
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_relative", logId: "log_1", status: 204 } });
|
||||
});
|
||||
|
||||
it("follows safe redirects after validating the redirect target", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 307, headers: { location: "https://hooks.example.com/rows-next" } }))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 204 }))
|
||||
);
|
||||
entityWebhookMock.findMany.mockResolvedValueOnce([
|
||||
{ id: "webhook_redirect", entityId: "entity_1", action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" },
|
||||
]);
|
||||
|
||||
await callEntityWebhooks({
|
||||
logId: "log_1",
|
||||
entityId: "entity_1",
|
||||
action: "created",
|
||||
body: "payload",
|
||||
request: new Request("https://tenant.example.com/api/rows"),
|
||||
});
|
||||
|
||||
expect(fetch).toHaveBeenNthCalledWith(1, "https://hooks.example.com/rows", expect.objectContaining({ method: "POST", redirect: "manual" }));
|
||||
expect(fetch).toHaveBeenNthCalledWith(2, "https://hooks.example.com/rows-next", expect.objectContaining({ method: "POST", redirect: "manual" }));
|
||||
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_redirect", logId: "log_1", status: 204 } });
|
||||
});
|
||||
|
||||
it("blocks unsafe redirect targets without following them", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 302, headers: { location: "http://127.0.0.1/webhook" } })));
|
||||
entityWebhookMock.findMany.mockResolvedValueOnce([
|
||||
{ id: "webhook_redirect_blocked", entityId: "entity_1", action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" },
|
||||
]);
|
||||
|
||||
await callEntityWebhooks({
|
||||
logId: "log_1",
|
||||
entityId: "entity_1",
|
||||
action: "created",
|
||||
body: "payload",
|
||||
request: new Request("https://tenant.example.com/api/rows"),
|
||||
});
|
||||
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
expect(fetch).toHaveBeenCalledWith("https://hooks.example.com/rows", expect.objectContaining({ redirect: "manual" }));
|
||||
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_redirect_blocked", logId: "log_1", status: 0 } });
|
||||
});
|
||||
|
||||
it("blocks unsafe webhook URLs and records failed delivery status without fetching", async () => {
|
||||
entityWebhookMock.findMany.mockResolvedValueOnce([
|
||||
{ id: "webhook_private", entityId: "entity_1", action: "created", method: "POST", endpoint: "http://10.0.0.1/webhook" },
|
||||
{ id: "webhook_internal", entityId: "entity_1", action: "created", method: "POST", endpoint: "https://worker.internal/webhook" },
|
||||
{ id: "webhook_relative_localhost", entityId: "entity_1", action: "created", method: "POST", endpoint: "/webhooks/rows" },
|
||||
]);
|
||||
|
||||
await callEntityWebhooks({
|
||||
logId: "log_1",
|
||||
entityId: "entity_1",
|
||||
action: "created",
|
||||
body: "payload",
|
||||
request: new Request("https://localhost/api/rows"),
|
||||
});
|
||||
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_private", logId: "log_1", status: 0 } });
|
||||
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_internal", logId: "log_1", status: 0 } });
|
||||
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_relative_localhost", logId: "log_1", status: 0 } });
|
||||
});
|
||||
|
||||
it("blocks public hostnames that resolve to internal addresses (DNS rebinding) without fetching", async () => {
|
||||
entityWebhookMock.findMany.mockResolvedValueOnce([
|
||||
{ id: "webhook_rebind", entityId: "entity_1", action: "created", method: "POST", endpoint: "https://rebind.attacker.test/webhook" },
|
||||
]);
|
||||
|
||||
await callEntityWebhooks({
|
||||
logId: "log_1",
|
||||
entityId: "entity_1",
|
||||
action: "created",
|
||||
body: "payload",
|
||||
request: new Request("https://tenant.example.com/api/rows"),
|
||||
});
|
||||
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_rebind", logId: "log_1", status: 0 } });
|
||||
});
|
||||
});
|
||||
|
||||
describe("entity webhook admin boundaries", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("reads a webhook only inside the current entity scope", async () => {
|
||||
const webhook = { id: "webhook_1", entityId: "entity_1", action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" };
|
||||
entityWebhookMock.findFirst.mockResolvedValueOnce(webhook);
|
||||
|
||||
await expect(getEntityWebhook({ id: "webhook_1", entityId: "entity_1" })).resolves.toEqual(webhook);
|
||||
|
||||
expect(entityWebhookMock.findFirst).toHaveBeenCalledWith({ where: { id: "webhook_1", entityId: "entity_1" } });
|
||||
});
|
||||
|
||||
it("updates and deletes only webhooks inside the current entity scope", async () => {
|
||||
entityWebhookMock.updateMany.mockResolvedValueOnce({ count: 1 });
|
||||
entityWebhookMock.deleteMany.mockResolvedValueOnce({ count: 1 });
|
||||
|
||||
await updateEntityWebhook(
|
||||
{ id: "webhook_1", entityId: "entity_1" },
|
||||
{ action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" }
|
||||
);
|
||||
await deleteEntityWebhook({ id: "webhook_1", entityId: "entity_1" });
|
||||
|
||||
expect(entityWebhookMock.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: "webhook_1", entityId: "entity_1" },
|
||||
data: { action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" },
|
||||
});
|
||||
expect(entityWebhookMock.deleteMany).toHaveBeenCalledWith({ where: { id: "webhook_1", entityId: "entity_1" } });
|
||||
});
|
||||
|
||||
it("rejects scoped update and delete misses", async () => {
|
||||
entityWebhookMock.updateMany.mockResolvedValueOnce({ count: 0 });
|
||||
entityWebhookMock.deleteMany.mockResolvedValueOnce({ count: 0 });
|
||||
|
||||
await expect(
|
||||
updateEntityWebhook({ id: "webhook_foreign", entityId: "entity_1" }, { action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" })
|
||||
).rejects.toThrow("Entity webhook not found.");
|
||||
await expect(deleteEntityWebhook({ id: "webhook_foreign", entityId: "entity_1" })).rejects.toThrow("Entity webhook not found.");
|
||||
});
|
||||
});
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
import { EntityWebhook } from "@toolctrl/db/prisma-browser";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { getBaseURL } from "~/utils/url.server";
|
||||
import { fetchOutboundHttpWithRedirects } from "~/utils/outboundHttp.server";
|
||||
|
||||
const BLOCKED_WEBHOOK_STATUS = 0;
|
||||
|
||||
export type EntityWebhookWithDetails = EntityWebhook & { _count: { logs: number } };
|
||||
export async function getEntityWebhooks(entityId: string) {
|
||||
return await db.entityWebhook.findMany({
|
||||
where: {
|
||||
entityId,
|
||||
},
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
logs: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEntityWebhook(input: { id: string; entityId: string }) {
|
||||
return await db.entityWebhook.findFirst({
|
||||
where: {
|
||||
id: input.id,
|
||||
entityId: input.entityId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEntityWebhooksByAction(entityId: string, action: string) {
|
||||
return await db.entityWebhook.findMany({
|
||||
where: {
|
||||
entityId,
|
||||
action,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createEntityWebhook(data: { entityId: string; action: string; method: string; endpoint: string }) {
|
||||
return await db.entityWebhook.create({
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateEntityWebhook(
|
||||
input: { id: string; entityId: string },
|
||||
data: {
|
||||
action: string;
|
||||
method: string;
|
||||
endpoint: string;
|
||||
}
|
||||
) {
|
||||
const result = await db.entityWebhook.updateMany({
|
||||
where: {
|
||||
id: input.id,
|
||||
entityId: input.entityId,
|
||||
},
|
||||
data,
|
||||
});
|
||||
if (result.count !== 1) {
|
||||
throw new Error("Entity webhook not found.");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function deleteEntityWebhook(input: { id: string; entityId: string }) {
|
||||
const result = await db.entityWebhook.deleteMany({
|
||||
where: {
|
||||
id: input.id,
|
||||
entityId: input.entityId,
|
||||
},
|
||||
});
|
||||
if (result.count !== 1) {
|
||||
throw new Error("Entity webhook not found.");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function callEntityWebhooks({
|
||||
logId,
|
||||
entityId,
|
||||
action,
|
||||
body,
|
||||
request,
|
||||
}: {
|
||||
logId: string;
|
||||
entityId: string;
|
||||
action: string;
|
||||
body: string;
|
||||
request?: Request;
|
||||
}) {
|
||||
const webhooks = await getEntityWebhooksByAction(entityId, action);
|
||||
return await Promise.all(
|
||||
webhooks.map(async (webhook) => {
|
||||
if (webhook.endpoint) {
|
||||
const status = await fetchLegacyWebhookStatus(webhook.endpoint, request, {
|
||||
method: webhook.method,
|
||||
body: JSON.stringify(body),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
return db.entityWebhookLog.create({
|
||||
data: {
|
||||
webhookId: webhook.id,
|
||||
logId,
|
||||
status,
|
||||
},
|
||||
});
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function resolveWebhookEndpoint(endpoint: string, request?: Request): string {
|
||||
return endpoint.startsWith("/") && request ? getBaseURL(request) + endpoint : endpoint;
|
||||
}
|
||||
|
||||
// Delivery goes through the shared SSRF-safe outbound client, which validates
|
||||
// the scheme, blocks literal private/loopback/link-local/metadata hosts, AND
|
||||
// resolves DNS to reject public hostnames that resolve to internal addresses
|
||||
// (DNS rebinding) — the gap in the previous forked, hostname-string-only guard.
|
||||
// Redirect hops are re-validated and resolved the same way. Any rejection or
|
||||
// transport error is recorded as a blocked-delivery status.
|
||||
async function fetchLegacyWebhookStatus(endpoint: string, request: Request | undefined, init: RequestInit): Promise<number> {
|
||||
try {
|
||||
const response = await fetchOutboundHttpWithRedirects(resolveWebhookEndpoint(endpoint, request), init);
|
||||
return response.status;
|
||||
} catch {
|
||||
return BLOCKED_WEBHOOK_STATUS;
|
||||
}
|
||||
}
|
||||
+273
@@ -0,0 +1,273 @@
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import { defaultProperties } from "~/utils/helpers/PropertyHelper";
|
||||
import { db } from "../../db.server";
|
||||
|
||||
export async function getProperty(id: string) {
|
||||
return await db.property.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
include: {
|
||||
attributes: true,
|
||||
options: {
|
||||
orderBy: {
|
||||
order: "asc",
|
||||
},
|
||||
},
|
||||
formula: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getEntityPropertyByName(entityId: string, name: string) {
|
||||
return await db.property.findFirst({
|
||||
where: {
|
||||
entityId,
|
||||
name,
|
||||
},
|
||||
include: {
|
||||
attributes: true,
|
||||
options: {
|
||||
orderBy: {
|
||||
order: "asc",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createProperty(data: {
|
||||
entityId: string;
|
||||
name: string;
|
||||
title: string;
|
||||
type: PropertyType;
|
||||
subtype: string | null;
|
||||
order: number;
|
||||
isDefault: boolean;
|
||||
isRequired: boolean;
|
||||
isHidden: boolean;
|
||||
isDisplay: boolean;
|
||||
isReadOnly: boolean;
|
||||
canUpdate: boolean;
|
||||
showInCreate: boolean;
|
||||
formulaId: string | null;
|
||||
tenantId: string | null;
|
||||
}) {
|
||||
if (data.name.includes(" ")) {
|
||||
throw Error("Property names cannot contain spaces: " + data.name);
|
||||
}
|
||||
if (data.name.includes("-")) {
|
||||
throw Error("Property names cannot contain '-': " + data.name);
|
||||
}
|
||||
return await db.property.create({
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export type CreatePropertyDto = {
|
||||
name: string;
|
||||
title: string;
|
||||
type: PropertyType;
|
||||
subtype: string | null;
|
||||
isRequired?: boolean;
|
||||
isDefault?: boolean;
|
||||
isHidden?: boolean;
|
||||
isDisplay?: boolean;
|
||||
isReadOnly?: boolean;
|
||||
canUpdate?: boolean;
|
||||
showInCreate?: boolean;
|
||||
formulaId?: string | null;
|
||||
tenantId?: string | null;
|
||||
options?: { order: number; value: string; name?: string; color?: Colors }[];
|
||||
attributes?: {
|
||||
name: string;
|
||||
value: string;
|
||||
}[];
|
||||
};
|
||||
export async function createProperties(entityId: string, fields: CreatePropertyDto[]) {
|
||||
return await Promise.all(
|
||||
fields.map(async (field, idx) => {
|
||||
const property = await createProperty({
|
||||
entityId,
|
||||
order: defaultProperties.length + idx + 1,
|
||||
name: field.name,
|
||||
title: field.title,
|
||||
type: field.type,
|
||||
subtype: field.subtype ?? null,
|
||||
isRequired: field.isRequired ?? true,
|
||||
isDefault: field.isDefault ?? false,
|
||||
isHidden: field.isHidden ?? false,
|
||||
isDisplay: field.isDisplay ?? false,
|
||||
isReadOnly: field.isReadOnly ?? false,
|
||||
canUpdate: field.canUpdate ?? true,
|
||||
showInCreate: field.showInCreate ?? true,
|
||||
formulaId: field.formulaId ?? null,
|
||||
tenantId: field.tenantId ?? null,
|
||||
});
|
||||
|
||||
if (field.options) {
|
||||
await updatePropertyOptions(
|
||||
property.id,
|
||||
field.options.map((option) => {
|
||||
return {
|
||||
order: option.order,
|
||||
value: option.value,
|
||||
name: option.name ?? null,
|
||||
color: option.color,
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
if (field.attributes) {
|
||||
await updatePropertyAttributes(property.id, field.attributes);
|
||||
}
|
||||
return property;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export async function updateProperty(
|
||||
id: string,
|
||||
data: {
|
||||
name?: string;
|
||||
title?: string;
|
||||
type?: PropertyType;
|
||||
subtype?: string | null;
|
||||
order?: number;
|
||||
isDefault?: boolean;
|
||||
isRequired?: boolean;
|
||||
isHidden?: boolean;
|
||||
isDisplay?: boolean;
|
||||
isReadOnly?: boolean;
|
||||
canUpdate?: boolean;
|
||||
showInCreate?: boolean;
|
||||
formulaId?: string | null;
|
||||
}
|
||||
) {
|
||||
const property = await db.property.update({
|
||||
where: { id },
|
||||
data,
|
||||
});
|
||||
|
||||
return property;
|
||||
}
|
||||
|
||||
type PropertyScope = {
|
||||
id: string;
|
||||
tenantId: string | null;
|
||||
entityId: string;
|
||||
};
|
||||
|
||||
type UpdatePropertyData = Parameters<typeof updateProperty>[1];
|
||||
|
||||
async function assertScopedProperty(scope: PropertyScope) {
|
||||
const property = await getProperty(scope.id);
|
||||
if (!property || property.tenantId !== scope.tenantId || property.entityId !== scope.entityId) {
|
||||
throw Error("Property not found");
|
||||
}
|
||||
return property;
|
||||
}
|
||||
|
||||
export async function getScopedProperty(scope: PropertyScope) {
|
||||
const property = await getProperty(scope.id);
|
||||
if (!property || property.tenantId !== scope.tenantId || property.entityId !== scope.entityId) {
|
||||
return null;
|
||||
}
|
||||
return property;
|
||||
}
|
||||
|
||||
export async function updateScopedProperty(scope: PropertyScope, data: UpdatePropertyData) {
|
||||
const result = await db.property.updateMany({
|
||||
where: scope,
|
||||
data,
|
||||
});
|
||||
if (result.count !== 1) {
|
||||
throw Error("Property not found");
|
||||
}
|
||||
return await assertScopedProperty(scope);
|
||||
}
|
||||
|
||||
export async function updatePropertyOrder(id: string, order: number) {
|
||||
return await db.property.update({
|
||||
where: { id },
|
||||
data: {
|
||||
order,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateScopedPropertyOrder(scope: PropertyScope, order: number) {
|
||||
const result = await db.property.updateMany({
|
||||
where: scope,
|
||||
data: {
|
||||
order,
|
||||
},
|
||||
});
|
||||
if (result.count !== 1) {
|
||||
throw Error("Property not found");
|
||||
}
|
||||
}
|
||||
|
||||
export async function updatePropertyOptions(id: string, options: { order: number; value: string; name?: string | null; color?: Colors }[]) {
|
||||
await db.propertyOption.deleteMany({
|
||||
where: { propertyId: id },
|
||||
});
|
||||
await Promise.all(
|
||||
options.map(async (option) => {
|
||||
return await db.propertyOption.create({
|
||||
data: {
|
||||
propertyId: id,
|
||||
order: option.order,
|
||||
value: option.value,
|
||||
name: option.name ?? null,
|
||||
color: option.color,
|
||||
},
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export async function updateScopedPropertyOptions(scope: PropertyScope, options: { order: number; value: string; name?: string | null; color?: Colors }[]) {
|
||||
await assertScopedProperty(scope);
|
||||
await updatePropertyOptions(scope.id, options);
|
||||
}
|
||||
|
||||
export async function updatePropertyAttributes(id: string, attributes: { name: string; value: string }[]) {
|
||||
await db.propertyAttribute.deleteMany({
|
||||
where: { propertyId: id },
|
||||
});
|
||||
await Promise.all(
|
||||
attributes
|
||||
.filter((f) => f.value !== undefined)
|
||||
.map(async (attribute) => {
|
||||
return await db.propertyAttribute.create({
|
||||
data: {
|
||||
propertyId: id,
|
||||
name: attribute.name,
|
||||
value: attribute.value,
|
||||
},
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export async function updateScopedPropertyAttributes(scope: PropertyScope, attributes: { name: string; value: string }[]) {
|
||||
await assertScopedProperty(scope);
|
||||
await updatePropertyAttributes(scope.id, attributes);
|
||||
}
|
||||
|
||||
export async function deleteProperty(id: string) {
|
||||
return await db.property.delete({
|
||||
where: { id },
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteScopedProperty(scope: PropertyScope) {
|
||||
const result = await db.property.deleteMany({
|
||||
where: scope,
|
||||
});
|
||||
if (result.count !== 1) {
|
||||
throw Error("Property not found");
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
import { RowCommentReaction } from "@toolctrl/db/prisma-browser";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { UserSimple } from "../users.db.server";
|
||||
|
||||
export type RowCommentReactionWithDetails = RowCommentReaction & {
|
||||
createdByUser: UserSimple;
|
||||
};
|
||||
export async function setRowCommentReaction(data: { createdByUserId: string; rowCommentId: string; reaction: string }) {
|
||||
const existing = await db.rowCommentReaction.findFirst({
|
||||
where: {
|
||||
createdByUserId: data.createdByUserId,
|
||||
rowCommentId: data.rowCommentId,
|
||||
reaction: data.reaction,
|
||||
},
|
||||
});
|
||||
if (!existing) {
|
||||
await db.rowCommentReaction.create({
|
||||
data,
|
||||
});
|
||||
return true;
|
||||
} else {
|
||||
await db.rowCommentReaction.deleteMany({
|
||||
where: {
|
||||
...data,
|
||||
},
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
import { RowComment } from "@toolctrl/db/prisma-browser";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { UserSimple } from "../users.db.server";
|
||||
import { RowCommentReactionWithDetails } from "./rowCommentReaction.db.server";
|
||||
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
|
||||
|
||||
export type RowCommentWithDetails = RowComment & {
|
||||
createdByUser: UserSimple;
|
||||
reactions: RowCommentReactionWithDetails[];
|
||||
// replies: (RowComment & { createdByUser: User })[];
|
||||
};
|
||||
|
||||
export async function getRowComments(rowId: string): Promise<RowCommentWithDetails[]> {
|
||||
return await db.rowComment.findMany({
|
||||
where: {
|
||||
rowId,
|
||||
// parentCommentId: null,
|
||||
},
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleCreatedByUser,
|
||||
reactions: {
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleCreatedByUser,
|
||||
},
|
||||
},
|
||||
// replies: {
|
||||
// include: {
|
||||
// ...UserModelHelper.includeSimpleCreatedByUser,
|
||||
// },
|
||||
// },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRowComment(id: string): Promise<RowCommentWithDetails | null> {
|
||||
return await db.rowComment.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleCreatedByUser,
|
||||
reactions: {
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleCreatedByUser,
|
||||
},
|
||||
},
|
||||
// replies: {
|
||||
// include: {
|
||||
// ...UserModelHelper.includeSimpleCreatedByUser,
|
||||
// },
|
||||
// },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRowCommentInRow({ id, rowId }: { id: string; rowId: string }): Promise<RowCommentWithDetails | null> {
|
||||
return await db.rowComment.findFirst({
|
||||
where: {
|
||||
id,
|
||||
rowId,
|
||||
},
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleCreatedByUser,
|
||||
reactions: {
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleCreatedByUser,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createRowComment(data: { createdByUserId: string; rowId: string; value: string }) {
|
||||
return await db.rowComment.create({
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateRowCommentInRow({ id, rowId }: { id: string; rowId: string }, data: { value?: string; isDeleted?: boolean }) {
|
||||
const updated = await db.rowComment.updateMany({
|
||||
where: {
|
||||
id,
|
||||
rowId,
|
||||
},
|
||||
data,
|
||||
});
|
||||
if (updated.count !== 1) {
|
||||
throw new Error("Row comment not found");
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
import { db } from "~/utils/db.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
|
||||
const rowRelationshipsLogger = createScopedLogger("db.entities.rowRelationships");
|
||||
|
||||
type RowRelationshipTenantScope = {
|
||||
tenantId: string | null;
|
||||
};
|
||||
|
||||
function scopedRowRelationshipWhere(scope: RowRelationshipTenantScope) {
|
||||
return {
|
||||
parent: { deletedAt: null, tenantId: scope.tenantId },
|
||||
child: { deletedAt: null, tenantId: scope.tenantId },
|
||||
};
|
||||
}
|
||||
|
||||
export async function getRowRelationship(id: string, scope: RowRelationshipTenantScope) {
|
||||
return await db.rowRelationship.findFirst({
|
||||
where: { id, ...scopedRowRelationshipWhere(scope) },
|
||||
include: {
|
||||
relationship: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRowsRelationship({ parentId, childId, tenantId }: { parentId: string; childId: string; tenantId: string | null }) {
|
||||
return await db.rowRelationship.findFirst({
|
||||
where: { parentId, childId, ...scopedRowRelationshipWhere({ tenantId }) },
|
||||
});
|
||||
}
|
||||
|
||||
export async function createRowRelationship({
|
||||
parentId,
|
||||
childId,
|
||||
relationshipId,
|
||||
metadata,
|
||||
tenantId,
|
||||
}: {
|
||||
parentId: string;
|
||||
childId: string;
|
||||
relationshipId: string;
|
||||
metadata: string | null;
|
||||
tenantId: string | null;
|
||||
}) {
|
||||
const [parent, child] = await Promise.all([
|
||||
db.row.findFirst({ where: { id: parentId, deletedAt: null, tenantId }, select: { id: true } }),
|
||||
db.row.findFirst({ where: { id: childId, deletedAt: null, tenantId }, select: { id: true } }),
|
||||
]);
|
||||
if (!parent || !child) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return await db.rowRelationship
|
||||
.create({
|
||||
data: {
|
||||
parentId,
|
||||
childId,
|
||||
relationshipId,
|
||||
metadata,
|
||||
},
|
||||
})
|
||||
.catch((e) => {
|
||||
rowRelationshipsLogger.error({ err: e }, "Error creating row relationship");
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteRowRelationship({ parentId, childId, tenantId }: { parentId: string; childId: string; tenantId: string | null }) {
|
||||
return await db.rowRelationship.deleteMany({
|
||||
where: {
|
||||
parentId,
|
||||
childId,
|
||||
...scopedRowRelationshipWhere({ tenantId }),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteRowRelationshipById(id: string, scope: RowRelationshipTenantScope) {
|
||||
const item = await db.rowRelationship.findFirst({
|
||||
where: { id, ...scopedRowRelationshipWhere(scope) },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!item) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return await db.rowRelationship.delete({
|
||||
where: {
|
||||
id: item.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
import { EntityTag, RowTag } from "@toolctrl/db/prisma-browser";
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
export type RowTagWithDetails = RowTag & {
|
||||
tag: EntityTag;
|
||||
};
|
||||
|
||||
export async function getRowTags(rowId: string): Promise<RowTagWithDetails[]> {
|
||||
return await db.rowTag.findMany({
|
||||
where: {
|
||||
rowId,
|
||||
},
|
||||
include: {
|
||||
tag: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRowTagById(id: string): Promise<RowTagWithDetails | null> {
|
||||
return await db.rowTag.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
include: {
|
||||
tag: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRowTag(rowId: string, value: string): Promise<RowTagWithDetails | null> {
|
||||
return await db.rowTag.findFirst({
|
||||
where: {
|
||||
rowId,
|
||||
tag: {
|
||||
value,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
tag: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRowTagByIds(rowId: string, tagId: string): Promise<RowTagWithDetails | null> {
|
||||
return await db.rowTag.findFirst({
|
||||
where: {
|
||||
rowId,
|
||||
tagId,
|
||||
},
|
||||
include: {
|
||||
tag: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createRowTag(data: { rowId: string; tagId: string }) {
|
||||
return await db.rowTag.create({
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteRowTags(rowId: string, tagId: string) {
|
||||
return await db.rowTag.deleteMany({
|
||||
where: {
|
||||
rowId,
|
||||
tagId,
|
||||
},
|
||||
});
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
type RowTaskDbMocks = {
|
||||
findMany: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
function getMocks(): RowTaskDbMocks {
|
||||
const store = globalThis as typeof globalThis & { __rowTaskDbMocks__?: RowTaskDbMocks };
|
||||
store.__rowTaskDbMocks__ ??= {
|
||||
findMany: vi.fn(),
|
||||
};
|
||||
return store.__rowTaskDbMocks__;
|
||||
}
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: {
|
||||
rowTask: {
|
||||
findMany: getMocks().findMany,
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { getAllRowTasks } from "./rowTasks.db.server";
|
||||
|
||||
const mocks = getMocks();
|
||||
|
||||
describe("row task db helpers", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.findMany.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("filters task lists through row tenant scope when provided", async () => {
|
||||
await getAllRowTasks({ tenantId: "tenant_1", assignedOrCreatedUserId: "user_1", completed: false });
|
||||
|
||||
expect(mocks.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({
|
||||
completed: false,
|
||||
row: { tenantId: "tenant_1" },
|
||||
OR: [{ createdByUserId: "user_1" }, { assignedToUserId: "user_1" }],
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
import { Prisma, RowTask } from "@toolctrl/db/prisma-browser";
|
||||
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { UserSimple } from "../users.db.server";
|
||||
import { RowWithValues } from "./rows.db.server";
|
||||
|
||||
export type RowTaskWithDetails = RowTask & {
|
||||
createdByUser: UserSimple;
|
||||
assignedToUser: UserSimple | null;
|
||||
row: RowWithValues;
|
||||
};
|
||||
|
||||
export async function getRowTasks(rowId: string): Promise<RowTaskWithDetails[]> {
|
||||
return await db.rowTask.findMany({
|
||||
where: {
|
||||
rowId,
|
||||
},
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleCreatedByUser,
|
||||
assignedToUser: true,
|
||||
row: {
|
||||
include: {
|
||||
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
|
||||
createdByApiKey: true,
|
||||
values: { include: { media: true, multiple: true, range: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: [
|
||||
{
|
||||
completed: "asc",
|
||||
},
|
||||
{
|
||||
createdAt: "asc",
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRowTask(id: string): Promise<RowTaskWithDetails | null> {
|
||||
return await db.rowTask.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleCreatedByUser,
|
||||
assignedToUser: true,
|
||||
row: {
|
||||
include: {
|
||||
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
|
||||
createdByApiKey: true,
|
||||
values: { include: { media: true, multiple: true, range: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRowTaskInRow({ id, rowId }: { id: string; rowId: string }): Promise<RowTaskWithDetails | null> {
|
||||
return await db.rowTask.findFirst({
|
||||
where: {
|
||||
id,
|
||||
rowId,
|
||||
},
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleCreatedByUser,
|
||||
assignedToUser: true,
|
||||
row: {
|
||||
include: {
|
||||
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
|
||||
createdByApiKey: true,
|
||||
values: { include: { media: true, multiple: true, range: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createRowTask(data: {
|
||||
createdByUserId: string;
|
||||
rowId: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
completed?: boolean;
|
||||
completedAt?: Date | null;
|
||||
completedByUserId?: string | null;
|
||||
assignedToUserId?: string | null;
|
||||
deadline?: Date | null;
|
||||
}) {
|
||||
return await db.rowTask.create({
|
||||
data: {
|
||||
createdByUserId: data.createdByUserId,
|
||||
rowId: data.rowId,
|
||||
title: data.title,
|
||||
description: data.description ?? "",
|
||||
completed: data.completed ?? false,
|
||||
completedAt: data.completedAt ?? null,
|
||||
completedByUserId: data.completedByUserId ?? null,
|
||||
assignedToUserId: data.assignedToUserId ?? null,
|
||||
deadline: data.deadline ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateRowTaskInRow(
|
||||
scope: { id: string; rowId: string },
|
||||
data: {
|
||||
createdByUserId?: string;
|
||||
rowId?: string;
|
||||
title?: string;
|
||||
description?: string;
|
||||
completed?: boolean;
|
||||
completedAt?: Date | null;
|
||||
completedByUserId?: string | null;
|
||||
assignedToUserId?: string | null;
|
||||
deadline?: Date | null;
|
||||
}
|
||||
) {
|
||||
const updated = await db.rowTask.updateMany({
|
||||
where: {
|
||||
id: scope.id,
|
||||
rowId: scope.rowId,
|
||||
},
|
||||
data,
|
||||
});
|
||||
if (updated.count !== 1) {
|
||||
throw new Error("Row task not found");
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
export async function deleteRowTaskInRow(scope: { id: string; rowId: string }) {
|
||||
const deleted = await db.rowTask.deleteMany({
|
||||
where: {
|
||||
id: scope.id,
|
||||
rowId: scope.rowId,
|
||||
},
|
||||
});
|
||||
if (deleted.count !== 1) {
|
||||
throw new Error("Row task not found");
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
|
||||
export async function getAllRowTasks({
|
||||
completed,
|
||||
assignedOrCreatedUserId,
|
||||
tenantId,
|
||||
}: {
|
||||
completed?: boolean;
|
||||
assignedOrCreatedUserId?: string;
|
||||
tenantId?: string | null;
|
||||
}): Promise<RowTaskWithDetails[]> {
|
||||
const userWhere: Prisma.RowTaskWhereInput = {};
|
||||
if (assignedOrCreatedUserId) {
|
||||
userWhere.OR = [
|
||||
{
|
||||
createdByUserId: assignedOrCreatedUserId,
|
||||
},
|
||||
{
|
||||
assignedToUserId: assignedOrCreatedUserId,
|
||||
},
|
||||
];
|
||||
}
|
||||
return await db.rowTask.findMany({
|
||||
where: {
|
||||
completed,
|
||||
...(tenantId !== undefined ? { row: { tenantId } } : {}),
|
||||
...userWhere,
|
||||
},
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleCreatedByUser,
|
||||
assignedToUser: true,
|
||||
row: {
|
||||
include: {
|
||||
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
|
||||
createdByApiKey: true,
|
||||
values: { include: { media: true, multiple: true, range: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: [
|
||||
{
|
||||
createdAt: "desc",
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const rootPath = (...segments: string[]) => resolve(process.cwd(), ...segments);
|
||||
const readProjectFile = (path: string) => readFileSync(rootPath(path), "utf8");
|
||||
|
||||
describe("row tenant-scope guard", () => {
|
||||
it("requires explicit tenant and entity scope for row reloads", () => {
|
||||
const source = readProjectFile("apps/web/app/utils/db/entities/rows.db.server.ts");
|
||||
|
||||
expect(source).toContain("getRowById(id: string, scope: { entityId?: string; tenantId: string | null })");
|
||||
expect(source).not.toContain("getRowById(id: string, scope?:");
|
||||
expect(source).not.toContain("RowModelHelper.includeRowDetailsNested");
|
||||
});
|
||||
|
||||
it("keeps legacy row relationship helpers tenant-scoped", () => {
|
||||
const source = readProjectFile("apps/web/app/utils/db/entities/rowRelationships.db.server.ts");
|
||||
|
||||
expect(source).toContain("type RowRelationshipTenantScope");
|
||||
expect(source).toContain("parent: { deletedAt: null, tenantId: scope.tenantId }");
|
||||
expect(source).toContain("child: { deletedAt: null, tenantId: scope.tenantId }");
|
||||
expect(source).not.toContain("findUnique({");
|
||||
expect(source).not.toContain("where: { id },");
|
||||
});
|
||||
});
|
||||
+505
@@ -0,0 +1,505 @@
|
||||
import {
|
||||
hardDeleteRowById,
|
||||
updateRowWithValues,
|
||||
type LegacyRowWithDetails,
|
||||
type RowMutationData,
|
||||
type RowMutationValueInput,
|
||||
type RowMutationRelationshipChildInput,
|
||||
type RowMutationRelationshipParentInput,
|
||||
} from "@toolctrl/db/rows.server";
|
||||
import {
|
||||
Prisma,
|
||||
Row,
|
||||
Tenant,
|
||||
RowValue,
|
||||
ApiKey,
|
||||
RowMedia,
|
||||
RowRelationship,
|
||||
SampleCustomEntity,
|
||||
RowPermission,
|
||||
RowValueMultiple,
|
||||
RowValueRange,
|
||||
} from "@toolctrl/db/prisma-browser";
|
||||
import { RowFiltersDto } from "~/application/dtos/data/RowFiltersDto";
|
||||
import { MediaDto } from "~/application/dtos/entities/MediaDto";
|
||||
import { deleteRowMediaFromStorageProvider, storeRowMediaInStorageProvider } from "~/utils/helpers/.server/MediaService";
|
||||
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
|
||||
import TenantHelper from "~/utils/helpers/TenantHelper";
|
||||
import { db } from "../../db.server";
|
||||
import { UserSimple } from "../users.db.server";
|
||||
import { EntityWithDetails, getEntityById } from "./entities.db.server";
|
||||
import { RowTagWithDetails } from "./rowTags.db.server";
|
||||
import { getRowPermissionsCondition } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
|
||||
import { RowValueRangeDto } from "~/application/dtos/entities/RowValueRangeDto";
|
||||
import RowModelHelper from "~/utils/helpers/models/RowModelHelper";
|
||||
|
||||
export type RowValueWithDetails = RowValue & {
|
||||
media: RowMedia[];
|
||||
multiple: RowValueMultiple[];
|
||||
range: RowValueRange | null;
|
||||
};
|
||||
export type RowWithValues = Row & {
|
||||
createdByUser: UserSimple | null;
|
||||
createdByApiKey: ApiKey | null;
|
||||
values: RowValueWithDetails[];
|
||||
};
|
||||
export type RowWithCreatedBy = Row & {
|
||||
createdByUser: UserSimple | null;
|
||||
createdByApiKey: ApiKey | null;
|
||||
};
|
||||
export type RowWithDetails = Row & {
|
||||
createdByUser: UserSimple | null;
|
||||
createdByApiKey: ApiKey | null;
|
||||
tenant: Tenant | null;
|
||||
values: RowValueWithDetails[];
|
||||
tags: RowTagWithDetails[];
|
||||
parentRows:
|
||||
| (RowRelationship & { parent: RowWithValues })[]
|
||||
| (RowRelationship & {
|
||||
parent: RowWithValues & {
|
||||
parentRows: (RowRelationship & {
|
||||
parent: { values: RowValueWithDetails[] };
|
||||
})[];
|
||||
childRows: (RowRelationship & {
|
||||
child: { values: RowValueWithDetails[] };
|
||||
})[];
|
||||
};
|
||||
})[];
|
||||
childRows: (RowRelationship & {
|
||||
child: RowWithValues & {
|
||||
parentRows: (RowRelationship & {
|
||||
parent: { values: RowValueWithDetails[] };
|
||||
})[];
|
||||
childRows: (RowRelationship & {
|
||||
child: { values: RowValueWithDetails[] };
|
||||
})[];
|
||||
};
|
||||
})[];
|
||||
permissions: RowPermission[];
|
||||
sampleCustomEntity: SampleCustomEntity | null;
|
||||
};
|
||||
export type RowMutationScope = { id: string; entityId: string; tenantId: string | null };
|
||||
|
||||
export async function getAllRows(entityId: string): Promise<RowWithDetails[]> {
|
||||
return await db.row.findMany({
|
||||
where: {
|
||||
deletedAt: null,
|
||||
entityId,
|
||||
},
|
||||
include: RowModelHelper.includeRowDetails,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRows({
|
||||
entityId,
|
||||
entityName,
|
||||
tenantId,
|
||||
|
||||
userId,
|
||||
take,
|
||||
skip,
|
||||
orderBy,
|
||||
filters,
|
||||
ids,
|
||||
rowWhere,
|
||||
includePublic,
|
||||
}: {
|
||||
entityId?: string;
|
||||
entityName?: string;
|
||||
tenantId?: string | null;
|
||||
|
||||
userId?: string;
|
||||
take?: number;
|
||||
skip?: number;
|
||||
orderBy?: Prisma.RowOrderByWithRelationInput[];
|
||||
filters?: RowFiltersDto;
|
||||
ids?: string[];
|
||||
rowWhere?: Prisma.RowWhereInput;
|
||||
includePublic?: boolean;
|
||||
}): Promise<RowWithDetails[]> {
|
||||
const whereFilters = RowFiltersHelper.getRowFiltersCondition(filters);
|
||||
let filterEntity: Prisma.RowWhereInput | undefined = undefined;
|
||||
if (entityId) {
|
||||
filterEntity = { entityId };
|
||||
} else if (entityName) {
|
||||
filterEntity = { entity: { name: entityName } };
|
||||
}
|
||||
|
||||
const accessFilters = await getAccessFilters({ tenantId });
|
||||
const where: Prisma.RowWhereInput = {
|
||||
AND: [
|
||||
{ deletedAt: null },
|
||||
{ ...rowWhere },
|
||||
whereFilters,
|
||||
{ id: { in: ids } },
|
||||
{ ...filterEntity },
|
||||
{ ...accessFilters },
|
||||
// ...getSearchCondition(filters?.query),
|
||||
],
|
||||
};
|
||||
return await db.row.findMany({
|
||||
take,
|
||||
skip,
|
||||
where,
|
||||
include: RowModelHelper.createScopedIncludeRowDetails(tenantId ?? null),
|
||||
orderBy,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRowsBetween(name: string, tenantId: string | null, startDate: Date, endDate: Date): Promise<RowWithDetails[]> {
|
||||
return await db.row.findMany({
|
||||
where: {
|
||||
AND: [
|
||||
{ deletedAt: null },
|
||||
{
|
||||
entity: { name },
|
||||
...TenantHelper.tenantCondition({ tenantId }),
|
||||
},
|
||||
{
|
||||
createdAt: {
|
||||
lte: endDate,
|
||||
gte: startDate,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
include: RowModelHelper.createScopedIncludeRowDetails(tenantId),
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRowsInIds(ids: string[], tenantId?: string | null): Promise<RowWithDetails[]> {
|
||||
return await db.row.findMany({
|
||||
where: {
|
||||
deletedAt: null,
|
||||
id: {
|
||||
in: ids,
|
||||
},
|
||||
tenantId,
|
||||
},
|
||||
include: tenantId === undefined ? RowModelHelper.includeRowDetails : RowModelHelper.createScopedIncludeRowDetails(tenantId),
|
||||
});
|
||||
}
|
||||
|
||||
export async function countRows({
|
||||
entityId,
|
||||
entityName,
|
||||
tenantId,
|
||||
|
||||
userId,
|
||||
filters,
|
||||
rowWhere,
|
||||
includePublic,
|
||||
}: {
|
||||
entityId?: string;
|
||||
entityName?: string;
|
||||
tenantId?: string | null;
|
||||
|
||||
userId?: string | undefined;
|
||||
filters?: RowFiltersDto;
|
||||
rowWhere?: Prisma.RowWhereInput;
|
||||
includePublic?: boolean;
|
||||
}): Promise<number> {
|
||||
const whereFilters = RowFiltersHelper.getRowFiltersCondition(filters);
|
||||
let filterEntity: { entityId: string } | { entity: { name: string } } | undefined = undefined;
|
||||
if (entityId) {
|
||||
filterEntity = { entityId };
|
||||
} else if (entityName) {
|
||||
filterEntity = { entity: { name: entityName } };
|
||||
}
|
||||
|
||||
const accessFilters = await getAccessFilters({ tenantId });
|
||||
const where: Prisma.RowWhereInput = {
|
||||
AND: [
|
||||
{ deletedAt: null },
|
||||
{ ...rowWhere },
|
||||
whereFilters,
|
||||
// { id: { in: ids } },
|
||||
{ ...filterEntity },
|
||||
{ ...accessFilters },
|
||||
// ...getSearchCondition(filters?.query),
|
||||
],
|
||||
};
|
||||
return await db.row.count({
|
||||
where,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRow({ entityId, id, tenantId }: { entityId: string; id: string; tenantId?: string | null }): Promise<RowWithDetails | null> {
|
||||
const accessFilters = await getAccessFilters({ tenantId });
|
||||
return await db.row.findFirst({
|
||||
where: {
|
||||
deletedAt: null,
|
||||
id,
|
||||
entityId,
|
||||
...accessFilters,
|
||||
},
|
||||
include: {
|
||||
...RowModelHelper.createScopedIncludeRowDetails(tenantId ?? null),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRowById(id: string, scope: { entityId?: string; tenantId: string | null }): Promise<RowWithDetails | null> {
|
||||
return await db.row.findFirst({
|
||||
where: {
|
||||
deletedAt: null,
|
||||
id,
|
||||
...(scope.entityId ? { entityId: scope.entityId } : {}),
|
||||
tenantId: scope.tenantId,
|
||||
},
|
||||
include: {
|
||||
...RowModelHelper.createScopedIncludeRowDetails(scope.tenantId),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getMaxRowFolio({ tenantId, entityId }: { tenantId: string | null; entityId: string }) {
|
||||
let where: any = { tenantId, entityId };
|
||||
return await db.row.aggregate({
|
||||
where,
|
||||
_max: {
|
||||
folio: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getNextRowFolio({ tenantId, entityId }: { tenantId: string | null; entityId: string }) {
|
||||
const maxFolio = await getMaxRowFolio({ tenantId, entityId });
|
||||
let next = 1;
|
||||
if (maxFolio && maxFolio._max.folio !== null) {
|
||||
next = maxFolio._max.folio + 1;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export async function getMaxRowOrder({ tenantId, entityId }: { tenantId: string | null; entityId: string }) {
|
||||
let where: any = { tenantId, entityId };
|
||||
return await db.row.aggregate({
|
||||
where,
|
||||
_max: {
|
||||
order: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getNextRowOrder({ tenantId, entityId }: { tenantId: string | null; entityId: string }) {
|
||||
const maxOrder = await getMaxRowOrder({ tenantId, entityId });
|
||||
let next = 1;
|
||||
if (maxOrder && maxOrder._max.order !== null) {
|
||||
next = maxOrder._max.order + 1;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export async function createRow({
|
||||
entity,
|
||||
data,
|
||||
nextFolio,
|
||||
nextOrder,
|
||||
}: {
|
||||
entity: EntityWithDetails;
|
||||
data: {
|
||||
tenantId: string | null;
|
||||
|
||||
createdByUserId?: string | null;
|
||||
createdByApiKeyId?: string | null;
|
||||
properties: any;
|
||||
dynamicProperties?: {
|
||||
propertyId: string;
|
||||
id?: string | null;
|
||||
textValue?: string | null;
|
||||
numberValue?: number | string | null;
|
||||
dateValue?: Date | string | null;
|
||||
booleanValue?: boolean | null;
|
||||
media?: MediaDto[];
|
||||
multiple?: RowValueMultipleDto[];
|
||||
range?: RowValueRangeDto;
|
||||
}[];
|
||||
parentRows?: { relationshipId: string; parentId: string }[];
|
||||
childRows?: { relationshipId: string; childId: string }[];
|
||||
rowCreateInput?: Partial<Prisma.RowCreateInput>;
|
||||
};
|
||||
nextFolio?: number | undefined;
|
||||
nextOrder?: number | undefined;
|
||||
}) {
|
||||
let folio = nextFolio ?? 1;
|
||||
if (!nextFolio) {
|
||||
const maxFolio = await getMaxRowFolio({ tenantId: data.tenantId, entityId: entity.id });
|
||||
if (maxFolio && maxFolio._max.folio !== null) {
|
||||
folio = maxFolio._max.folio + 1;
|
||||
}
|
||||
}
|
||||
|
||||
let order = nextOrder ?? 1;
|
||||
if (!nextOrder) {
|
||||
const maxOrder = await getMaxRowOrder({ tenantId: data.tenantId, entityId: entity.id });
|
||||
if (maxOrder && maxOrder._max.order !== null) {
|
||||
order = maxOrder._max.order + 1;
|
||||
}
|
||||
}
|
||||
|
||||
const createInput: Prisma.XOR<Prisma.RowCreateInput, Prisma.RowUncheckedCreateInput> = {
|
||||
folio,
|
||||
order,
|
||||
entityId: entity.id,
|
||||
tenantId: data.tenantId,
|
||||
createdByUserId: data.createdByUserId ?? null,
|
||||
createdByApiKeyId: data.createdByApiKeyId ?? null,
|
||||
...data.properties,
|
||||
values: {
|
||||
create: data.dynamicProperties
|
||||
// .filter((f) => !f.id)
|
||||
?.map((value) => {
|
||||
return {
|
||||
propertyId: value.propertyId,
|
||||
textValue: value.textValue,
|
||||
numberValue: value.numberValue,
|
||||
dateValue: value.dateValue,
|
||||
booleanValue: value.booleanValue,
|
||||
media: {
|
||||
create: value.media?.map((m) => {
|
||||
return {
|
||||
name: m.name,
|
||||
title: m.title,
|
||||
type: m.type,
|
||||
file: m.file,
|
||||
publicUrl: m.publicUrl,
|
||||
};
|
||||
}),
|
||||
},
|
||||
multiple: {
|
||||
create: value.multiple?.map((m) => {
|
||||
return {
|
||||
order: m.order,
|
||||
value: m.value,
|
||||
};
|
||||
}),
|
||||
},
|
||||
range: {
|
||||
create: {
|
||||
numberMin: value.range?.numberMin,
|
||||
numberMax: value.range?.numberMax,
|
||||
dateMin: value.range?.dateMin,
|
||||
dateMax: value.range?.dateMax,
|
||||
},
|
||||
},
|
||||
};
|
||||
}),
|
||||
},
|
||||
parentRows: {
|
||||
create: data.parentRows?.map(({ relationshipId, parentId }) => {
|
||||
return {
|
||||
relationshipId,
|
||||
parentId,
|
||||
};
|
||||
}),
|
||||
},
|
||||
childRows: {
|
||||
create: data.childRows?.map(({ relationshipId, childId }) => {
|
||||
return {
|
||||
relationshipId,
|
||||
childId,
|
||||
};
|
||||
}),
|
||||
},
|
||||
...data.rowCreateInput,
|
||||
};
|
||||
const row = await db.row.create({
|
||||
data: createInput,
|
||||
});
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function updateRow(
|
||||
scope: RowMutationScope,
|
||||
data: {
|
||||
properties: any;
|
||||
dynamicProperties: {
|
||||
propertyId: string;
|
||||
id?: string | null;
|
||||
textValue?: string | null;
|
||||
numberValue?: number | string | null;
|
||||
dateValue?: Date | string | null;
|
||||
booleanValue?: boolean | null;
|
||||
media?: MediaDto[];
|
||||
multiple?: RowValueMultipleDto[];
|
||||
range?: RowValueRangeDto | undefined;
|
||||
}[];
|
||||
parentRows?: { relationshipId: string; parentId: string }[];
|
||||
childRows?: { relationshipId: string; childId: string }[];
|
||||
rowUpdateInput?: Prisma.RowUpdateInput;
|
||||
}
|
||||
) {
|
||||
const row = await updateRowWithValues(scope, {
|
||||
properties: data.properties,
|
||||
dynamicProperties: data.dynamicProperties as RowMutationValueInput[],
|
||||
parentRows: data.parentRows as RowMutationRelationshipParentInput[] | undefined,
|
||||
childRows: data.childRows as RowMutationRelationshipChildInput[] | undefined,
|
||||
rowUpdateInput: data.rowUpdateInput,
|
||||
} satisfies Omit<RowMutationData, "tenantId" | "createdByUserId" | "createdByApiKeyId" | "rowCreateInput">) as LegacyRowWithDetails as RowWithDetails;
|
||||
const entity = await getEntityById({ tenantId: row.tenantId, id: row.entityId });
|
||||
if (entity) {
|
||||
await storeRowMediaInStorageProvider(entity, row);
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function deleteRow(scope: RowMutationScope) {
|
||||
const row = await getRowById(scope.id, { entityId: scope.entityId, tenantId: scope.tenantId });
|
||||
await deleteRowMediaFromStorageProvider(row);
|
||||
return await hardDeleteRowById(scope);
|
||||
}
|
||||
|
||||
export async function deleteRows({ entityId, tenantId }: { entityId: string; tenantId: string | null }) {
|
||||
return await db.row.deleteMany({
|
||||
where: { entityId, tenantId },
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteRowsInIds({ ids, entityId, tenantId }: { ids: string[]; entityId: string; tenantId: string | null }) {
|
||||
return await db.row.deleteMany({
|
||||
where: { id: { in: ids }, entityId, tenantId },
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateRowMedia(
|
||||
scope: { id: string; rowId: string; entityId: string; tenantId: string | null },
|
||||
data: {
|
||||
file?: string;
|
||||
publicUrl?: string | null;
|
||||
storageBucket?: string | null;
|
||||
storageProvider?: string | null;
|
||||
}
|
||||
) {
|
||||
const result = await db.rowMedia.updateMany({
|
||||
where: {
|
||||
id: scope.id,
|
||||
rowValue: {
|
||||
rowId: scope.rowId,
|
||||
row: { entityId: scope.entityId, tenantId: scope.tenantId, deletedAt: null },
|
||||
},
|
||||
},
|
||||
data,
|
||||
});
|
||||
if (result.count !== 1) {
|
||||
throw new Error(`Row media ${scope.id} not found`);
|
||||
}
|
||||
}
|
||||
|
||||
async function getAccessFilters({ tenantId, userId }: { tenantId?: string | null; userId?: string }) {
|
||||
let tenantFilters: Prisma.RowWhereInput | undefined = undefined;
|
||||
let userPermissionFilters: Prisma.RowWhereInput | undefined = undefined;
|
||||
if (tenantId !== undefined) {
|
||||
tenantFilters = TenantHelper.tenantCondition({ tenantId });
|
||||
}
|
||||
if (userId) {
|
||||
userPermissionFilters = await getRowPermissionsCondition({ tenantId, userId });
|
||||
}
|
||||
const filters: Prisma.RowWhereInput = {
|
||||
AND: [{ ...tenantFilters }, { ...userPermissionFilters }],
|
||||
};
|
||||
return filters;
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import { IpAddress } from "@toolctrl/db/prisma-browser";
|
||||
import Constants from "~/application/Constants";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
export async function getAllIpAddresses(pagination?: { page: number; pageSize: number }): Promise<{ items: IpAddress[]; pagination: PaginationDto }> {
|
||||
const items = await db.ipAddress.findMany({
|
||||
skip: pagination ? pagination?.pageSize * (pagination?.page - 1) : undefined,
|
||||
take: pagination ? pagination?.pageSize : undefined,
|
||||
orderBy: [{ createdAt: "desc" }],
|
||||
});
|
||||
const totalItems = await db.ipAddress.count({});
|
||||
|
||||
return {
|
||||
items,
|
||||
pagination: {
|
||||
page: pagination?.page ?? 1,
|
||||
pageSize: pagination?.pageSize ?? Constants.DEFAULT_PAGE_SIZE,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / (pagination?.pageSize ?? Constants.DEFAULT_PAGE_SIZE)),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../db.server", () => {
|
||||
return {
|
||||
db: {
|
||||
log: {
|
||||
groupBy: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
import { db } from "../db.server";
|
||||
import { getLastUserLogsByUserIds } from "./logs.db.server";
|
||||
|
||||
const groupBy = db.log.groupBy as unknown as ReturnType<typeof vi.fn>;
|
||||
const findMany = db.log.findMany as unknown as ReturnType<typeof vi.fn>;
|
||||
|
||||
describe("getLastUserLogsByUserIds", () => {
|
||||
beforeEach(() => {
|
||||
groupBy.mockReset();
|
||||
findMany.mockReset();
|
||||
});
|
||||
|
||||
it("issues no queries when given an empty user id list", async () => {
|
||||
const result = await getLastUserLogsByUserIds([]);
|
||||
|
||||
expect(result.size).toBe(0);
|
||||
expect(groupBy).not.toHaveBeenCalled();
|
||||
expect(findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses a single groupBy and a single findMany regardless of user count (no N+1)", async () => {
|
||||
const userIds = ["u1", "u2", "u3", "u4", "u5"];
|
||||
const newest: Record<string, Date> = {
|
||||
u1: new Date("2026-05-01T10:00:00.000Z"),
|
||||
u2: new Date("2026-05-02T10:00:00.000Z"),
|
||||
u3: new Date("2026-05-03T10:00:00.000Z"),
|
||||
};
|
||||
groupBy.mockResolvedValueOnce(
|
||||
Object.entries(newest).map(([userId, createdAt]) => ({ userId, _max: { createdAt } }))
|
||||
);
|
||||
findMany.mockResolvedValueOnce(
|
||||
Object.entries(newest).map(([userId, createdAt]) => ({ id: `log-${userId}`, userId, createdAt }))
|
||||
);
|
||||
|
||||
const result = await getLastUserLogsByUserIds(userIds);
|
||||
|
||||
expect(groupBy).toHaveBeenCalledTimes(1);
|
||||
expect(findMany).toHaveBeenCalledTimes(1);
|
||||
expect(groupBy).toHaveBeenCalledWith({
|
||||
by: ["userId"],
|
||||
where: { userId: { in: userIds } },
|
||||
_max: { createdAt: true },
|
||||
});
|
||||
expect(result.get("u1")).toMatchObject({ id: "log-u1", userId: "u1" });
|
||||
expect(result.get("u3")).toMatchObject({ id: "log-u3" });
|
||||
expect(result.size).toBe(3);
|
||||
});
|
||||
|
||||
it("skips the findMany when no users have logs", async () => {
|
||||
groupBy.mockResolvedValueOnce([{ userId: "u1", _max: { createdAt: null } }]);
|
||||
|
||||
const result = await getLastUserLogsByUserIds(["u1"]);
|
||||
|
||||
expect(groupBy).toHaveBeenCalledTimes(1);
|
||||
expect(findMany).not.toHaveBeenCalled();
|
||||
expect(result.size).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,336 @@
|
||||
import { Tenant, Log, ApiKey, Prisma } from "@toolctrl/db/prisma-browser";
|
||||
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { DefaultLogActions } from "~/application/dtos/shared/DefaultLogActions";
|
||||
import { db } from "../db.server";
|
||||
import ApiHelper from "../helpers/ApiHelper";
|
||||
import RowFiltersHelper from "../helpers/RowFiltersHelper";
|
||||
import { getUserInfo } from "../session.server";
|
||||
import { EntityWithDetails } from "./entities/entities.db.server";
|
||||
import { callEntityWebhooks } from "./entities/entityWebhooks.db.server";
|
||||
import { RowCommentWithDetails } from "./entities/rowComments.db.server";
|
||||
import { RowWithDetails } from "./entities/rows.db.server";
|
||||
import { UserWithoutPassword } from "./users.db.server";
|
||||
import UserModelHelper from "../helpers/models/UserModelHelper";
|
||||
|
||||
export type LogWithDetails = Log & {
|
||||
user: UserWithoutPassword | null;
|
||||
apiKey: ApiKey | null;
|
||||
tenant?: Tenant | null;
|
||||
comment?: RowCommentWithDetails | null;
|
||||
};
|
||||
|
||||
const include = {
|
||||
user: true,
|
||||
tenant: true,
|
||||
apiKey: true,
|
||||
comment: {
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleCreatedByUser,
|
||||
reactions: {
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleCreatedByUser,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export async function getAllLogs(
|
||||
pagination: { page: number; pageSize: number },
|
||||
filters: FiltersDto
|
||||
): Promise<{ items: LogWithDetails[]; pagination: PaginationDto }> {
|
||||
const where = RowFiltersHelper.getFiltersCondition(filters);
|
||||
const items = await db.log.findMany({
|
||||
take: pagination.pageSize,
|
||||
skip: pagination.pageSize * (pagination.page - 1),
|
||||
include,
|
||||
where,
|
||||
});
|
||||
const totalItems = await db.log.count({
|
||||
where,
|
||||
});
|
||||
|
||||
return {
|
||||
items,
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / pagination.pageSize),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function getLogs(
|
||||
tenantId: string,
|
||||
pagination: { page: number; pageSize: number },
|
||||
filters: FiltersDto
|
||||
): Promise<{ items: LogWithDetails[]; pagination: PaginationDto }> {
|
||||
const where = RowFiltersHelper.getFiltersCondition(filters);
|
||||
const items = await db.log.findMany({
|
||||
take: pagination.pageSize,
|
||||
skip: pagination.pageSize * (pagination.page - 1),
|
||||
where: { tenantId, ...where },
|
||||
include,
|
||||
});
|
||||
const totalItems = await db.log.count({
|
||||
where: { tenantId, ...where },
|
||||
});
|
||||
|
||||
return {
|
||||
items,
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / pagination.pageSize),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function getAllRowLogs({
|
||||
entityId,
|
||||
rowId,
|
||||
tenantId,
|
||||
pagination,
|
||||
}: {
|
||||
entityId?: string;
|
||||
rowId?: string;
|
||||
tenantId?: string | null;
|
||||
pagination: { page: number; pageSize: number };
|
||||
}): Promise<{ items: LogWithDetails[]; pagination: PaginationDto }> {
|
||||
let where: Prisma.LogWhereInput = { rowId: { not: null } };
|
||||
if (entityId) {
|
||||
where = { ...where, row: { entityId } };
|
||||
}
|
||||
if (rowId) {
|
||||
where = { ...where, rowId };
|
||||
}
|
||||
if (tenantId !== undefined) {
|
||||
where = { ...where, tenantId };
|
||||
}
|
||||
const items = await db.log.findMany({
|
||||
take: pagination.pageSize,
|
||||
skip: pagination.pageSize * (pagination.page - 1),
|
||||
where,
|
||||
include,
|
||||
});
|
||||
const totalItems = await db.log.count({
|
||||
where,
|
||||
});
|
||||
|
||||
return {
|
||||
items,
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / pagination.pageSize),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function getRowLogs(tenantId: string | null, rowId: string): Promise<LogWithDetails[]> {
|
||||
return await db.log.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
rowId,
|
||||
},
|
||||
include,
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRowLogsById(rowId: string): Promise<LogWithDetails[]> {
|
||||
return await db.log.findMany({
|
||||
where: {
|
||||
rowId,
|
||||
},
|
||||
include,
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createLog(request: Request, tenantId: string | null, action: string, details: string) {
|
||||
const userInfo = await getUserInfo(request);
|
||||
await db.log.create({
|
||||
data: {
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
url: new URL(request.url).pathname,
|
||||
action,
|
||||
details,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createManualLog(userId: string, tenantId: string | null, pathname: string, action: string, details: string) {
|
||||
await db.log.create({
|
||||
data: {
|
||||
tenantId,
|
||||
userId,
|
||||
url: pathname,
|
||||
action,
|
||||
details,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createRowLog(
|
||||
request: Request,
|
||||
data: {
|
||||
tenantId: string | null;
|
||||
createdByUserId?: string | null;
|
||||
createdByApiKey?: string | null;
|
||||
action: string;
|
||||
entity: EntityWithDetails;
|
||||
item: RowWithDetails | null;
|
||||
commentId?: string | null;
|
||||
details?: string;
|
||||
}
|
||||
) {
|
||||
const log = await db.log.create({
|
||||
data: {
|
||||
tenantId: data.tenantId,
|
||||
userId: data.createdByUserId ?? null,
|
||||
apiKeyId: data.createdByApiKey ?? null,
|
||||
url: new URL(request.url).pathname,
|
||||
rowId: data.item?.id ?? null,
|
||||
action: data.action,
|
||||
details: data.details ?? null,
|
||||
commentId: data.commentId ?? null,
|
||||
},
|
||||
});
|
||||
const apiFormat = ApiHelper.getApiFormat(data.entity, data.item);
|
||||
await callEntityWebhooks({
|
||||
logId: log.id,
|
||||
entityId: data.entity.id,
|
||||
action: data.action,
|
||||
body: apiFormat,
|
||||
request,
|
||||
});
|
||||
return log;
|
||||
}
|
||||
|
||||
export async function createManualRowLog(
|
||||
data: {
|
||||
tenantId: string | null;
|
||||
createdByUserId?: string | null;
|
||||
createdByApiKey?: string | null;
|
||||
action: string;
|
||||
entity: EntityWithDetails;
|
||||
item: RowWithDetails | null;
|
||||
commentId?: string | null;
|
||||
},
|
||||
request?: Request
|
||||
) {
|
||||
let details = "";
|
||||
const log = await db.log.create({
|
||||
data: {
|
||||
tenantId: data.tenantId,
|
||||
userId: data.createdByUserId ?? null,
|
||||
apiKeyId: data.createdByApiKey ?? null,
|
||||
url: request ? new URL(request.url).pathname : "",
|
||||
rowId: data.item?.id ?? null,
|
||||
action: data.action,
|
||||
details,
|
||||
commentId: data.commentId ?? null,
|
||||
},
|
||||
});
|
||||
const apiFormat = ApiHelper.getApiFormat(data.entity, data.item);
|
||||
await callEntityWebhooks({
|
||||
logId: log.id,
|
||||
entityId: data.entity.id,
|
||||
action: data.action,
|
||||
body: apiFormat,
|
||||
// request,
|
||||
});
|
||||
return log;
|
||||
}
|
||||
|
||||
export async function createLogLogin(request: Request, user: UserWithoutPassword) {
|
||||
// eslint-disable-next-line no-console
|
||||
// console.log({ clientIpAddress: getClientIPAddress(request.headers) });
|
||||
|
||||
await db.log.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
url: "",
|
||||
action: DefaultLogActions.Login,
|
||||
details: "",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createLogLogout(request: Request, userId: string) {
|
||||
await db.log.create({
|
||||
data: {
|
||||
userId,
|
||||
url: "",
|
||||
action: DefaultLogActions.Logout,
|
||||
details: "",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createAdminLog(request: Request, action: string, details: string) {
|
||||
const userInfo = await getUserInfo(request);
|
||||
await db.log.create({
|
||||
data: {
|
||||
userId: userInfo.userId,
|
||||
url: new URL(request.url).pathname,
|
||||
action,
|
||||
details,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getLastUserLog(userId: string): Promise<Log | null> {
|
||||
return await db.log.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the most recent log entry per user for the given userIds in a
|
||||
* constant number of queries (1 groupBy + 1 findMany), avoiding the N+1
|
||||
* pattern of calling `getLastUserLog` per user.
|
||||
*/
|
||||
export async function getLastUserLogsByUserIds(userIds: string[]): Promise<Map<string, Log>> {
|
||||
if (userIds.length === 0) {
|
||||
return new Map();
|
||||
}
|
||||
const groups = await db.log.groupBy({
|
||||
by: ["userId"],
|
||||
where: { userId: { in: userIds } },
|
||||
_max: { createdAt: true },
|
||||
});
|
||||
const filters = groups
|
||||
.map((group) => (group._max.createdAt ? { userId: group.userId, createdAt: group._max.createdAt } : null))
|
||||
.filter((entry): entry is { userId: string; createdAt: Date } => entry !== null);
|
||||
if (filters.length === 0) {
|
||||
return new Map();
|
||||
}
|
||||
const logs = await db.log.findMany({
|
||||
where: { OR: filters },
|
||||
});
|
||||
const byUserId = new Map<string, Log>();
|
||||
for (const log of logs) {
|
||||
const existing = byUserId.get(log.userId ?? "");
|
||||
if (!log.userId) continue;
|
||||
if (!existing || existing.createdAt < log.createdAt) {
|
||||
byUserId.set(log.userId, log);
|
||||
}
|
||||
}
|
||||
return byUserId;
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../../db.server", () => ({
|
||||
db: {
|
||||
group: {
|
||||
create: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
update: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
},
|
||||
groupUser: {
|
||||
createMany: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { db } from "../../db.server";
|
||||
import { addUsersToGroup, createGroup, deleteGroup, getAllGroups, getGroup, getGroups, getMyGroups, removeUsersFromGroup, updateGroup } from "./groups.db.server";
|
||||
|
||||
const dbMock = vi.mocked(db);
|
||||
|
||||
describe("group persistence", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("lists tenant groups and selected groups with users included", async () => {
|
||||
vi.mocked(dbMock.group.findMany).mockResolvedValue([] as never);
|
||||
|
||||
await getAllGroups("tenant_1");
|
||||
await getGroups("tenant_1", ["group_1", "group_2"]);
|
||||
|
||||
expect(dbMock.group.findMany).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({
|
||||
where: { tenantId: "tenant_1" },
|
||||
include: expect.objectContaining({ users: expect.any(Object) }),
|
||||
orderBy: [{ name: "asc" }],
|
||||
})
|
||||
);
|
||||
expect(dbMock.group.findMany).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
where: { tenantId: "tenant_1", id: { in: ["group_1", "group_2"] } },
|
||||
include: expect.objectContaining({ users: expect.any(Object) }),
|
||||
orderBy: [{ name: "asc" }],
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("limits my-groups lookup to created or joined groups in the tenant", async () => {
|
||||
vi.mocked(dbMock.group.findMany).mockResolvedValueOnce([] as never);
|
||||
|
||||
await getMyGroups("user_1", "tenant_1");
|
||||
|
||||
expect(dbMock.group.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: {
|
||||
tenantId: "tenant_1",
|
||||
OR: [{ createdByUserId: "user_1" }, { users: { some: { userId: "user_1" } } }],
|
||||
},
|
||||
include: expect.objectContaining({ users: expect.any(Object) }),
|
||||
orderBy: [{ name: "asc" }],
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("gets groups with optional tenant scope", async () => {
|
||||
vi.mocked(dbMock.group.findFirst).mockResolvedValue({ id: "group_1" } as never);
|
||||
|
||||
await getGroup("group_1");
|
||||
await getGroup("group_1", "tenant_1");
|
||||
|
||||
expect(dbMock.group.findFirst).toHaveBeenNthCalledWith(1, expect.objectContaining({ where: { id: "group_1" } }));
|
||||
expect(dbMock.group.findFirst).toHaveBeenNthCalledWith(2, expect.objectContaining({ where: { id: "group_1", tenantId: "tenant_1" } }));
|
||||
});
|
||||
|
||||
it("creates and mutates groups with tenant-scoped bulk operations when a tenant is provided", async () => {
|
||||
vi.mocked(dbMock.group.create).mockResolvedValueOnce({ id: "group_1" } as never);
|
||||
vi.mocked(dbMock.group.updateMany).mockResolvedValueOnce({ count: 1 } as never);
|
||||
vi.mocked(dbMock.group.update).mockResolvedValueOnce({ id: "group_1" } as never);
|
||||
vi.mocked(dbMock.group.deleteMany).mockResolvedValueOnce({ count: 1 } as never);
|
||||
vi.mocked(dbMock.group.delete).mockResolvedValueOnce({ id: "group_1" } as never);
|
||||
|
||||
const data = { createdByUserId: "user_1", tenantId: "tenant_1", name: "Team", description: "Core team", color: 1 };
|
||||
await createGroup(data);
|
||||
await updateGroup("group_1", { name: "Ops", description: "Ops team", color: 2 }, "tenant_1");
|
||||
await updateGroup("group_1", { name: "Ops", description: "Ops team", color: 2 });
|
||||
await deleteGroup("group_1", "tenant_1");
|
||||
await deleteGroup("group_1");
|
||||
|
||||
expect(dbMock.group.create).toHaveBeenCalledWith({ data });
|
||||
expect(dbMock.group.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: "group_1", tenantId: "tenant_1" },
|
||||
data: { name: "Ops", description: "Ops team", color: 2 },
|
||||
});
|
||||
expect(dbMock.group.update).toHaveBeenCalledWith({
|
||||
where: { id: "group_1" },
|
||||
data: { name: "Ops", description: "Ops team", color: 2 },
|
||||
});
|
||||
expect(dbMock.group.deleteMany).toHaveBeenCalledWith({ where: { id: "group_1", tenantId: "tenant_1" } });
|
||||
expect(dbMock.group.delete).toHaveBeenCalledWith({ where: { id: "group_1" } });
|
||||
});
|
||||
|
||||
it("adds users to a group idempotently (skipDuplicates) and removes them in bulk", async () => {
|
||||
vi.mocked(dbMock.groupUser.createMany).mockResolvedValueOnce({ count: 2 } as never);
|
||||
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 1 } as never);
|
||||
|
||||
await addUsersToGroup("group_1", ["user_1", "user_2"]);
|
||||
await removeUsersFromGroup("group_1", ["user_1"]);
|
||||
|
||||
expect(dbMock.groupUser.createMany).toHaveBeenCalledWith({
|
||||
data: [
|
||||
{ groupId: "group_1", userId: "user_1" },
|
||||
{ groupId: "group_1", userId: "user_2" },
|
||||
],
|
||||
skipDuplicates: true,
|
||||
});
|
||||
expect(dbMock.groupUser.deleteMany).toHaveBeenCalledWith({ where: { groupId: "group_1", userId: { in: ["user_1"] } } });
|
||||
});
|
||||
|
||||
it("short-circuits bulk membership ops on an empty user list", async () => {
|
||||
expect(await addUsersToGroup("group_1", [])).toEqual({ count: 0 });
|
||||
expect(await removeUsersFromGroup("group_1", [])).toEqual({ count: 0 });
|
||||
expect(dbMock.groupUser.createMany).not.toHaveBeenCalled();
|
||||
expect(dbMock.groupUser.deleteMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
import { Group, GroupUser } from "@toolctrl/db/prisma-browser";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { UserSimple } from "../users.db.server";
|
||||
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
|
||||
|
||||
export type GroupWithDetails = Group & {
|
||||
users: (GroupUser & { user: UserSimple })[];
|
||||
};
|
||||
|
||||
export async function getAllGroups(tenantId: string | null): Promise<GroupWithDetails[]> {
|
||||
return await db.group.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
},
|
||||
include: {
|
||||
users: {
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleUser,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: [
|
||||
{
|
||||
name: "asc",
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
export async function getGroups(tenantId: string | null, ids: string[]): Promise<GroupWithDetails[]> {
|
||||
return await db.group.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
id: {
|
||||
in: ids,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
users: {
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleUser,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: [
|
||||
{
|
||||
name: "asc",
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
export async function getMyGroups(userId: string, tenantId: string | null): Promise<GroupWithDetails[]> {
|
||||
return await db.group.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
OR: [
|
||||
{
|
||||
createdByUserId: userId,
|
||||
},
|
||||
{
|
||||
users: {
|
||||
some: {
|
||||
userId,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
include: {
|
||||
users: {
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleUser,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: [
|
||||
{
|
||||
name: "asc",
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
export async function getGroup(id: string, tenantId?: string | null): Promise<GroupWithDetails | null> {
|
||||
return await db.group.findFirst({
|
||||
where: {
|
||||
id,
|
||||
...(tenantId !== undefined ? { tenantId } : {}),
|
||||
},
|
||||
include: {
|
||||
users: {
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleUser,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createGroup(data: { createdByUserId: string; tenantId: string | null; name: string; description: string; color: number }) {
|
||||
return await db.group.create({
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateGroup(id: string, data: { name: string; description: string; color: number }, tenantId?: string | null) {
|
||||
if (tenantId !== undefined) {
|
||||
return await db.group.updateMany({
|
||||
where: {
|
||||
id,
|
||||
tenantId,
|
||||
},
|
||||
data,
|
||||
});
|
||||
}
|
||||
return await db.group.update({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteGroup(id: string, tenantId?: string | null) {
|
||||
if (tenantId !== undefined) {
|
||||
return await db.group.deleteMany({
|
||||
where: {
|
||||
id,
|
||||
tenantId,
|
||||
},
|
||||
});
|
||||
}
|
||||
return await db.group.delete({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// R-P2b — Gruppen-Bulk-Ops (N:M). Idempotent: createMany skipDuplicates stuetzt sich auf den
|
||||
// Unique-Index [groupId, userId], doppelte Mitgliedschaften werden uebersprungen.
|
||||
export async function addUsersToGroup(groupId: string, userIds: string[]) {
|
||||
if (userIds.length === 0) {
|
||||
return { count: 0 };
|
||||
}
|
||||
return await db.groupUser.createMany({
|
||||
data: userIds.map((userId) => ({ groupId, userId })),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeUsersFromGroup(groupId: string, userIds: string[]) {
|
||||
if (userIds.length === 0) {
|
||||
return { count: 0 };
|
||||
}
|
||||
return await db.groupUser.deleteMany({
|
||||
where: { groupId, userId: { in: userIds } },
|
||||
});
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../../db.server", () => ({
|
||||
db: {
|
||||
permission: {
|
||||
aggregate: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
findUnique: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
vi.mock("./roles.db.server", () => ({ getAllRolesNames: vi.fn(), getRoleByName: vi.fn() }));
|
||||
vi.mock("./rolePermissions.db.server", () => ({ createRolePermission: vi.fn(), getAllRolePermissions: vi.fn() }));
|
||||
vi.mock("~/utils/cache.server", () => ({ cachified: vi.fn(), clearCacheKey: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getEntityPermissions: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/RowFiltersHelper", () => ({ default: { getFiltersCondition: vi.fn() } }));
|
||||
|
||||
import { cachified, clearCacheKey } from "~/utils/cache.server";
|
||||
import { getEntityPermissions } from "~/utils/helpers/PermissionsHelper";
|
||||
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
|
||||
import { db } from "../../db.server";
|
||||
import { createRolePermission, getAllRolePermissions } from "./rolePermissions.db.server";
|
||||
import { getAllRolesNames, getRoleByName } from "./roles.db.server";
|
||||
import {
|
||||
createEntityPermissions,
|
||||
createPermissions,
|
||||
deleteEntityPermissions,
|
||||
deletePermission,
|
||||
getAllPermissions,
|
||||
getAllPermissionsIdsAndNames,
|
||||
getNextPermissionsOrder,
|
||||
getPermission,
|
||||
getPermissionByName,
|
||||
getPermissionByNames,
|
||||
getPermissionName,
|
||||
updatePermission,
|
||||
} from "./permissions.db.server";
|
||||
|
||||
describe("permission persistence", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(cachified).mockImplementation((async (options: { getFreshValue: () => unknown }) =>
|
||||
options.getFreshValue()) as never);
|
||||
});
|
||||
|
||||
it("lists permissions with filters, role filters, and type constraints", async () => {
|
||||
vi.mocked(RowFiltersHelper.getFiltersCondition).mockReturnValue({ name: { contains: "admin" } } as never);
|
||||
vi.mocked(db.permission.findMany).mockResolvedValueOnce([] as never);
|
||||
|
||||
await getAllPermissions("admin", {
|
||||
properties: [{ name: "roleId", value: "role_1" }],
|
||||
} as never);
|
||||
|
||||
expect(db.permission.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
AND: ["admin", { OR: [{ name: { contains: "admin" } }, { inRoles: { some: { roleId: "role_1" } } }] }],
|
||||
},
|
||||
include: { inRoles: { include: { role: true } } },
|
||||
orderBy: [{ type: "asc" }, { name: "asc" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("queries permission lookup variants and cached permission names", async () => {
|
||||
vi.mocked(db.permission.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(db.permission.findUnique).mockResolvedValue({ id: "permission_1" } as never);
|
||||
|
||||
await getAllPermissionsIdsAndNames();
|
||||
await getPermission("permission_1");
|
||||
await getPermissionByName("admin.users.view");
|
||||
await getPermissionName("admin.users.view");
|
||||
await getPermissionByNames(["admin.users.view", "admin.users.edit"]);
|
||||
|
||||
expect(db.permission.findMany).toHaveBeenNthCalledWith(1, {
|
||||
select: { id: true, name: true },
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
expect(db.permission.findUnique).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({ where: { id: "permission_1" } })
|
||||
);
|
||||
expect(db.permission.findUnique).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({ where: { name: "admin.users.view" } })
|
||||
);
|
||||
expect(cachified).toHaveBeenCalledWith(expect.objectContaining({ key: "permission:admin.users.view" }));
|
||||
expect(db.permission.findMany).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({ where: { name: { in: ["admin.users.view", "admin.users.edit"] } } })
|
||||
);
|
||||
});
|
||||
|
||||
it("calculates the next permission order with and without a type filter", async () => {
|
||||
vi.mocked(db.permission.aggregate)
|
||||
.mockResolvedValueOnce({ _max: { order: 4 } } as never)
|
||||
.mockResolvedValueOnce({ _max: { order: null } } as never);
|
||||
|
||||
await expect(getNextPermissionsOrder("admin")).resolves.toBe(5);
|
||||
await expect(getNextPermissionsOrder()).resolves.toBe(1);
|
||||
|
||||
expect(db.permission.aggregate).toHaveBeenNthCalledWith(1, { where: { type: "admin" }, _max: { order: true } });
|
||||
expect(db.permission.aggregate).toHaveBeenNthCalledWith(2, { where: {}, _max: { order: true } });
|
||||
});
|
||||
|
||||
it("repairs role links for existing permissions instead of returning early", async () => {
|
||||
vi.mocked(db.permission.findMany).mockResolvedValue([{ id: "permission_1", name: "admin.users.view" }] as never);
|
||||
vi.mocked(getAllRolePermissions).mockResolvedValue([]);
|
||||
vi.mocked(getRoleByName).mockResolvedValue({ id: "role_1", name: "SuperAdmin" } as never);
|
||||
vi.mocked(createRolePermission).mockResolvedValue({ id: "role_permission_1" } as never);
|
||||
|
||||
await createPermissions([{ name: "admin.users.view", description: "View users", type: "admin", inRoles: ["SuperAdmin"] }]);
|
||||
|
||||
expect(db.permission.create).not.toHaveBeenCalled();
|
||||
expect(createRolePermission).toHaveBeenCalledWith({ permissionId: "permission_1", roleId: "role_1" });
|
||||
});
|
||||
|
||||
it("clears the permission lookup cache after creating a previously missing permission", async () => {
|
||||
vi.mocked(db.permission.findMany).mockResolvedValue([]);
|
||||
vi.mocked(db.permission.create).mockResolvedValue({ id: "permission_1", name: "admin.users.view" } as never);
|
||||
vi.mocked(getAllRolePermissions).mockResolvedValue([]);
|
||||
vi.mocked(getRoleByName).mockResolvedValue({ id: "role_1", name: "SuperAdmin" } as never);
|
||||
vi.mocked(createRolePermission).mockResolvedValue({ id: "role_permission_1" } as never);
|
||||
|
||||
await createPermissions([{ name: "admin.users.view", description: "View users", type: "admin", inRoles: ["SuperAdmin"] }]);
|
||||
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("permission:admin.users.view");
|
||||
expect(createRolePermission).toHaveBeenCalledWith({ permissionId: "permission_1", roleId: "role_1" });
|
||||
});
|
||||
|
||||
it("skips duplicate permission inputs after creating the first instance", async () => {
|
||||
vi.mocked(db.permission.findMany).mockResolvedValue([]);
|
||||
vi.mocked(db.permission.create).mockResolvedValue({ id: "permission_1", name: "admin.users.view" } as never);
|
||||
vi.mocked(getAllRolePermissions).mockResolvedValue([]);
|
||||
vi.mocked(getRoleByName).mockResolvedValue({ id: "role_1", name: "SuperAdmin" } as never);
|
||||
|
||||
await createPermissions([
|
||||
{ name: "admin.users.view", description: "View users", type: "admin", inRoles: ["SuperAdmin"] },
|
||||
{ name: "admin.users.view", description: "View users", type: "admin", inRoles: ["SuperAdmin"] },
|
||||
]);
|
||||
|
||||
expect(db.permission.create).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("throws when a requested role link cannot be resolved", async () => {
|
||||
vi.mocked(db.permission.findMany).mockResolvedValue([]);
|
||||
vi.mocked(db.permission.create).mockResolvedValue({ id: "permission_1", name: "admin.users.view" } as never);
|
||||
vi.mocked(getAllRolePermissions).mockResolvedValue([]);
|
||||
vi.mocked(getRoleByName).mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
createPermissions([{ name: "admin.users.view", description: "View users", type: "admin", inRoles: ["Missing"] }])
|
||||
).rejects.toThrow("Role required: Missing");
|
||||
});
|
||||
|
||||
it("updates and deletes permissions while clearing the permission cache", async () => {
|
||||
vi.mocked(db.permission.update).mockResolvedValueOnce({ id: "permission_1", name: "admin.users.view" } as never);
|
||||
vi.mocked(db.permission.delete).mockResolvedValueOnce({ id: "permission_1", name: "admin.users.delete" } as never);
|
||||
|
||||
await updatePermission("permission_1", { name: "admin.users.view" });
|
||||
await deletePermission("permission_1");
|
||||
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("permission:admin.users.view");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("permission:admin.users.delete");
|
||||
});
|
||||
|
||||
it("deletes entity permissions only when generated permission names exist", async () => {
|
||||
vi.mocked(getEntityPermissions)
|
||||
.mockResolvedValueOnce([{ name: "entity.view" }, { name: "entity.edit" }] as never)
|
||||
.mockResolvedValueOnce([] as never);
|
||||
vi.mocked(db.permission.deleteMany).mockResolvedValueOnce({ count: 2 } as never);
|
||||
|
||||
await expect(deleteEntityPermissions({ id: "entity_1" } as never)).resolves.toEqual({ count: 2 });
|
||||
await expect(deleteEntityPermissions({ id: "entity_1" } as never)).resolves.toBeUndefined();
|
||||
|
||||
expect(db.permission.deleteMany).toHaveBeenCalledTimes(1);
|
||||
expect(db.permission.deleteMany).toHaveBeenCalledWith({
|
||||
where: { name: { in: ["entity.view", "entity.edit"] } },
|
||||
});
|
||||
});
|
||||
|
||||
it("creates entity permissions for every generated permission and all app roles", async () => {
|
||||
vi.mocked(getAllRolesNames).mockResolvedValue([{ id: "role_1", name: "Member" }] as never);
|
||||
vi.mocked(getEntityPermissions).mockResolvedValue([{ name: "entity.view", description: "View entity" }] as never);
|
||||
vi.mocked(getAllRolePermissions).mockResolvedValue([]);
|
||||
vi.mocked(db.permission.findMany).mockResolvedValue([]);
|
||||
vi.mocked(db.permission.create).mockResolvedValue({ id: "permission_1", name: "entity.view" } as never);
|
||||
vi.mocked(getRoleByName).mockResolvedValue({ id: "role_1", name: "Member" } as never);
|
||||
|
||||
await createEntityPermissions({ id: "entity_1" } as never);
|
||||
|
||||
expect(db.permission.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
order: 2,
|
||||
name: "entity.view",
|
||||
description: "View entity",
|
||||
type: "app",
|
||||
isDefault: true,
|
||||
entityId: "entity_1",
|
||||
},
|
||||
});
|
||||
expect(createRolePermission).toHaveBeenCalledWith({ permissionId: "permission_1", roleId: "role_1" });
|
||||
});
|
||||
});
|
||||
+254
@@ -0,0 +1,254 @@
|
||||
import { db } from "../../db.server";
|
||||
import { Entity, Permission, Role, RolePermission } from "@toolctrl/db/prisma-browser";
|
||||
import { getAllRolesNames, getRoleByName } from "./roles.db.server";
|
||||
import { createRolePermission, getAllRolePermissions } from "./rolePermissions.db.server";
|
||||
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
|
||||
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
|
||||
import { getEntityPermissions } from "~/utils/helpers/PermissionsHelper";
|
||||
import { cachified, clearCacheKey } from "~/utils/cache.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
|
||||
const permissionsLogger = createScopedLogger("db.permissions");
|
||||
|
||||
export type PermissionWithRoles = Permission & {
|
||||
inRoles: (RolePermission & { role: Role })[];
|
||||
};
|
||||
|
||||
export async function getAllPermissions(type?: string, filters?: FiltersDto): Promise<PermissionWithRoles[]> {
|
||||
let where: any = {
|
||||
type,
|
||||
};
|
||||
if (filters) {
|
||||
where = RowFiltersHelper.getFiltersCondition(filters);
|
||||
const roleId = filters?.properties.find((f) => f.name === "roleId")?.value;
|
||||
if (roleId) {
|
||||
where = {
|
||||
OR: [where, { inRoles: { some: { roleId } } }],
|
||||
};
|
||||
}
|
||||
if (type !== undefined) {
|
||||
where = {
|
||||
AND: [type, where],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return await db.permission.findMany({
|
||||
where,
|
||||
include: {
|
||||
inRoles: {
|
||||
include: {
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: [{ type: "asc" }, { name: "asc" }],
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAllPermissionsIdsAndNames(): Promise<{ id: string; name: string }[]> {
|
||||
return await db.permission.findMany({
|
||||
select: { id: true, name: true },
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPermission(id: string): Promise<PermissionWithRoles | null> {
|
||||
return await db.permission.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
include: {
|
||||
inRoles: {
|
||||
include: {
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPermissionByName(name: string): Promise<PermissionWithRoles | null> {
|
||||
return await db.permission.findUnique({
|
||||
where: {
|
||||
name,
|
||||
},
|
||||
include: {
|
||||
inRoles: {
|
||||
include: {
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPermissionName(name: string): Promise<{ id: string; name: string; description: string } | null> {
|
||||
return await cachified({
|
||||
key: `permission:${name}`,
|
||||
ttl: 1000 * 60 * 60 * 24,
|
||||
getFreshValue: () =>
|
||||
db.permission.findUnique({
|
||||
where: {
|
||||
name,
|
||||
},
|
||||
select: { id: true, name: true, description: true },
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPermissionByNames(names: string[]): Promise<PermissionWithRoles[]> {
|
||||
return await db.permission.findMany({
|
||||
where: {
|
||||
name: {
|
||||
in: names,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
inRoles: {
|
||||
include: {
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getNextPermissionsOrder(type?: string): Promise<number> {
|
||||
let where = {};
|
||||
if (type !== undefined) {
|
||||
where = {
|
||||
type,
|
||||
};
|
||||
}
|
||||
return (
|
||||
((
|
||||
await db.permission.aggregate({
|
||||
where,
|
||||
_max: {
|
||||
order: true,
|
||||
},
|
||||
})
|
||||
)._max.order ?? 0) + 1
|
||||
);
|
||||
}
|
||||
|
||||
export async function createPermissions(
|
||||
permissions: { inRoles: string[]; name: string; description: string; type: string; entityId?: string | null }[],
|
||||
fromOrder: number = 0
|
||||
) {
|
||||
const allRolePermissions = await getAllRolePermissions();
|
||||
const allPermissions = await getAllPermissions();
|
||||
const permissionByName = new Map<string, { id: string; name: string }>(allPermissions.map((permission) => [permission.name, permission]));
|
||||
const createdPermissionNames = new Set<string>();
|
||||
for (const [idx, data] of permissions.entries()) {
|
||||
const existing = permissionByName.get(data.name);
|
||||
if (createdPermissionNames.has(data.name)) {
|
||||
permissionsLogger.info({ permission: data.name }, "Permission already exists");
|
||||
continue;
|
||||
}
|
||||
const permission =
|
||||
existing ??
|
||||
(await createPermission({
|
||||
order: fromOrder + idx + 1,
|
||||
name: data.name,
|
||||
description: data.description,
|
||||
type: data.type,
|
||||
isDefault: true,
|
||||
entityId: data.entityId ?? null,
|
||||
}));
|
||||
createdPermissionNames.add(permission.name);
|
||||
if (existing) {
|
||||
permissionsLogger.info({ permission: data.name }, "Permission already exists");
|
||||
} else {
|
||||
permissionByName.set(permission.name, permission);
|
||||
clearCacheKey(`permission:${permission.name}`);
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
data.inRoles.map(async (inRole) => {
|
||||
const role = await getRoleByName(inRole);
|
||||
if (!role) {
|
||||
throw new Error("Role required: " + inRole);
|
||||
}
|
||||
const existing = allRolePermissions.find((p) => p.roleId === role.id && p.permission.name === permission.name);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
return await createRolePermission({
|
||||
permissionId: permission.id,
|
||||
roleId: role.id,
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function createPermission(data: { order: number; name: string; description: string; type: string; isDefault: boolean; entityId: string | null }) {
|
||||
return await db.permission.create({
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function updatePermission(
|
||||
id: string,
|
||||
data: {
|
||||
name?: string;
|
||||
description?: string;
|
||||
type?: string;
|
||||
order?: number;
|
||||
}
|
||||
) {
|
||||
return await db.permission
|
||||
.update({
|
||||
where: { id },
|
||||
data,
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`permission:${item.name}`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function deletePermission(id: string) {
|
||||
return await db.permission
|
||||
.delete({
|
||||
where: { id },
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`permission:${item.name}`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteEntityPermissions(entity: Entity) {
|
||||
const entityPermissions = await getEntityPermissions(entity);
|
||||
const names = entityPermissions.map((p) => p.name);
|
||||
if (names.length > 0) {
|
||||
return await db.permission.deleteMany({
|
||||
where: {
|
||||
name: {
|
||||
in: names,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function createEntityPermissions(entity: Entity) {
|
||||
const allUserRoles = await getAllRolesNames();
|
||||
// const assignToAllUserRoles = allUserRoles.filter((f) => f.assignToNewUsers);
|
||||
const entityPermissions = await getEntityPermissions(entity);
|
||||
await Promise.all(
|
||||
entityPermissions.map(async (permission, idx) => {
|
||||
const entityPermission = {
|
||||
inRoles: allUserRoles.map((f) => f.name),
|
||||
name: permission.name,
|
||||
description: permission.description,
|
||||
type: "app",
|
||||
entityId: entity.id,
|
||||
};
|
||||
return await createPermissions([entityPermission], allUserRoles.length + idx);
|
||||
})
|
||||
);
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../../db.server", () => ({
|
||||
db: {
|
||||
role: {
|
||||
findUnique: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
permission: {
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
rolePermission: {
|
||||
create: vi.fn(),
|
||||
createMany: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
$transaction: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock("~/utils/cache.server", () => ({ clearCacheKey: vi.fn() }));
|
||||
vi.mock("../tenants.db.server", () => ({ adminGetAllTenants: vi.fn() }));
|
||||
vi.mock("../users.db.server", () => ({ adminGetAllUsersNames: vi.fn() }));
|
||||
|
||||
import { clearCacheKey } from "~/utils/cache.server";
|
||||
import { adminGetAllTenants } from "../tenants.db.server";
|
||||
import { adminGetAllUsersNames } from "../users.db.server";
|
||||
import { db } from "../../db.server";
|
||||
import {
|
||||
createRolePermission,
|
||||
deleteRolePermission,
|
||||
deleteRolePermissionById,
|
||||
getAllRolePermissions,
|
||||
setPermissionRoles,
|
||||
setRolePermissions,
|
||||
} from "./rolePermissions.db.server";
|
||||
|
||||
describe("role permission persistence", () => {
|
||||
const dbMock = vi.mocked(db);
|
||||
const findRoleByIdMock = vi.mocked(dbMock.role.findUnique);
|
||||
const findPermissionsMock = vi.mocked(dbMock.permission.findMany);
|
||||
const findRolesMock = vi.mocked(dbMock.role.findMany);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
dbMock.$transaction.mockImplementation(async (callback: (tx: typeof dbMock) => Promise<unknown>) => callback(dbMock));
|
||||
vi.mocked(adminGetAllTenants).mockResolvedValue([]);
|
||||
vi.mocked(adminGetAllUsersNames).mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("sets role permissions inside one awaited transaction before clearing caches", async () => {
|
||||
findRoleByIdMock.mockResolvedValue({ id: "role_1", name: "Editor", type: "app" } as never);
|
||||
findPermissionsMock.mockResolvedValue([{ id: "permission_a" }, { id: "permission_b" }] as never);
|
||||
|
||||
await setRolePermissions("role_1", ["settings.update", "settings.update", "members.read"]);
|
||||
|
||||
expect(dbMock.permission.findMany).toHaveBeenCalledWith({
|
||||
where: { name: { in: ["settings.update", "members.read"] } },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(dbMock.$transaction).toHaveBeenCalledTimes(1);
|
||||
expect(dbMock.rolePermission.deleteMany).toHaveBeenCalledWith({ where: { roleId: "role_1" } });
|
||||
expect(dbMock.rolePermission.createMany).toHaveBeenCalledWith({
|
||||
data: [
|
||||
{ roleId: "role_1", permissionId: "permission_a" },
|
||||
{ roleId: "role_1", permissionId: "permission_b" },
|
||||
],
|
||||
});
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("roles:app");
|
||||
});
|
||||
|
||||
it("reads and creates role-permission links without duplicating existing links", async () => {
|
||||
dbMock.rolePermission.findMany.mockResolvedValueOnce([{ id: "rp_1" }] as never);
|
||||
dbMock.rolePermission.findFirst
|
||||
.mockResolvedValueOnce({ id: "rp_existing" } as never)
|
||||
.mockResolvedValueOnce(null);
|
||||
dbMock.rolePermission.create.mockResolvedValueOnce({ id: "rp_created" } as never);
|
||||
|
||||
await expect(getAllRolePermissions()).resolves.toEqual([{ id: "rp_1" }]);
|
||||
await expect(createRolePermission({ roleId: "role_1", permissionId: "permission_1" })).resolves.toEqual({ id: "rp_existing" });
|
||||
await expect(createRolePermission({ roleId: "role_1", permissionId: "permission_2" })).resolves.toEqual({ id: "rp_created" });
|
||||
|
||||
expect(dbMock.rolePermission.create).toHaveBeenCalledTimes(1);
|
||||
expect(dbMock.rolePermission.create).toHaveBeenCalledWith({ data: { roleId: "role_1", permissionId: "permission_2" } });
|
||||
});
|
||||
|
||||
it("returns early when setting permissions for a missing role", async () => {
|
||||
findRoleByIdMock.mockResolvedValueOnce(null);
|
||||
|
||||
await setRolePermissions("role_missing", ["settings.update"]);
|
||||
|
||||
expect(dbMock.permission.findMany).not.toHaveBeenCalled();
|
||||
expect(dbMock.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("clears app role user caches across tenants and user-role lookup caches", async () => {
|
||||
findRoleByIdMock.mockResolvedValue({ id: "role_1", name: "Member", type: "app" } as never);
|
||||
findPermissionsMock.mockResolvedValue([]);
|
||||
vi.mocked(adminGetAllTenants).mockResolvedValue([
|
||||
{ id: "tenant_1", users: [{ userId: "user_1" }, { userId: "user_2" }] },
|
||||
{ id: "tenant_2", users: [{ userId: "user_3" }] },
|
||||
] as never);
|
||||
vi.mocked(adminGetAllUsersNames).mockResolvedValue([{ id: "user_1" }, { id: "user_4" }] as never);
|
||||
|
||||
await setRolePermissions("role_1", []);
|
||||
|
||||
expect(dbMock.rolePermission.createMany).not.toHaveBeenCalled();
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("roles:app");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:tenant_1");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_2:tenant_1");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_3:tenant_2");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRole:user_1:Member");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRole:user_4:Member");
|
||||
});
|
||||
|
||||
it("sets permission roles inside one awaited transaction", async () => {
|
||||
findRolesMock.mockResolvedValue([{ id: "role_a" }, { id: "role_b" }] as never);
|
||||
|
||||
await setPermissionRoles("permission_1", ["Admin", "Admin", "Member"]);
|
||||
|
||||
expect(dbMock.role.findMany).toHaveBeenCalledWith({
|
||||
where: { name: { in: ["Admin", "Member"] } },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(dbMock.$transaction).toHaveBeenCalledTimes(1);
|
||||
expect(dbMock.rolePermission.deleteMany).toHaveBeenCalledWith({ where: { permissionId: "permission_1" } });
|
||||
expect(dbMock.rolePermission.createMany).toHaveBeenCalledWith({
|
||||
data: [
|
||||
{ roleId: "role_a", permissionId: "permission_1" },
|
||||
{ roleId: "role_b", permissionId: "permission_1" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("clears permission role links without creating rows when role list is empty", async () => {
|
||||
await setPermissionRoles("permission_1", []);
|
||||
|
||||
expect(dbMock.role.findMany).not.toHaveBeenCalled();
|
||||
expect(dbMock.$transaction).toHaveBeenCalledTimes(1);
|
||||
expect(dbMock.rolePermission.deleteMany).toHaveBeenCalledWith({ where: { permissionId: "permission_1" } });
|
||||
expect(dbMock.rolePermission.createMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("deletes role-permission links by composite keys or id", async () => {
|
||||
dbMock.rolePermission.deleteMany.mockResolvedValueOnce({ count: 1 } as never);
|
||||
dbMock.rolePermission.delete.mockResolvedValueOnce({ id: "rp_1" } as never);
|
||||
|
||||
await expect(deleteRolePermission("role_1", "permission_1")).resolves.toEqual({ count: 1 });
|
||||
await expect(deleteRolePermissionById("rp_1")).resolves.toEqual({ id: "rp_1" });
|
||||
|
||||
expect(dbMock.rolePermission.deleteMany).toHaveBeenCalledWith({ where: { roleId: "role_1", permissionId: "permission_1" } });
|
||||
expect(dbMock.rolePermission.delete).toHaveBeenCalledWith({ where: { id: "rp_1" } });
|
||||
});
|
||||
});
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
import { clearCacheKey } from "~/utils/cache.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { db } from "../../db.server";
|
||||
import { adminGetAllTenants } from "../tenants.db.server";
|
||||
import { adminGetAllUsersNames } from "../users.db.server";
|
||||
|
||||
const rolePermissionsLogger = createScopedLogger("db.rolePermissions");
|
||||
|
||||
export async function getAllRolePermissions() {
|
||||
return await db.rolePermission.findMany({
|
||||
include: {
|
||||
permission: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createRolePermission(data: { roleId: string; permissionId: string }) {
|
||||
const existing = await db.rolePermission.findFirst({
|
||||
where: {
|
||||
roleId: data.roleId,
|
||||
permissionId: data.permissionId,
|
||||
},
|
||||
});
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
return await db.rolePermission.create({
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function setRolePermissions(roleId: string, permissionNames: string[]) {
|
||||
const role = await db.role.findUnique({ where: { id: roleId } });
|
||||
if (!role) {
|
||||
return;
|
||||
}
|
||||
|
||||
const uniquePermissionNames = [...new Set(permissionNames)];
|
||||
const permissions = uniquePermissionNames.length
|
||||
? await db.permission.findMany({
|
||||
where: { name: { in: uniquePermissionNames } },
|
||||
select: { id: true },
|
||||
})
|
||||
: [];
|
||||
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.rolePermission.deleteMany({
|
||||
where: { roleId },
|
||||
});
|
||||
|
||||
if (permissions.length > 0) {
|
||||
await tx.rolePermission.createMany({
|
||||
data: permissions.map((permission) => ({
|
||||
roleId,
|
||||
permissionId: permission.id,
|
||||
})),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
clearCacheKey(`roles:${role.type}`);
|
||||
if (role.type === "app") {
|
||||
const allTenants = await adminGetAllTenants();
|
||||
rolePermissionsLogger.info({ tenantCount: allTenants.length }, "Clearing user roles cache");
|
||||
for (const tenant of allTenants) {
|
||||
for (const user of tenant.users) {
|
||||
clearCacheKey(`userRoles:${user.userId}:${tenant.id}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const allUsers = await adminGetAllUsersNames();
|
||||
for (const user of allUsers) {
|
||||
clearCacheKey(`userRole:${user.id}:${role.name}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function setPermissionRoles(permissionId: string, roleNames: string[]) {
|
||||
const uniqueRoleNames = [...new Set(roleNames)];
|
||||
const roles = uniqueRoleNames.length
|
||||
? await db.role.findMany({
|
||||
where: { name: { in: uniqueRoleNames } },
|
||||
select: { id: true },
|
||||
})
|
||||
: [];
|
||||
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.rolePermission.deleteMany({
|
||||
where: { permissionId },
|
||||
});
|
||||
|
||||
if (roles.length > 0) {
|
||||
await tx.rolePermission.createMany({
|
||||
data: roles.map((role) => ({
|
||||
roleId: role.id,
|
||||
permissionId,
|
||||
})),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteRolePermission(roleId: string, permissionId: string) {
|
||||
return await db.rolePermission.deleteMany({
|
||||
where: { roleId, permissionId },
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteRolePermissionById(id: string) {
|
||||
return await db.rolePermission.delete({
|
||||
where: { id },
|
||||
});
|
||||
}
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../../db.server", () => ({
|
||||
db: {
|
||||
role: {
|
||||
aggregate: vi.fn(),
|
||||
create: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
findUnique: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
vi.mock("~/utils/cache.server", () => ({ cachified: vi.fn(), clearCacheKey: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/RowFiltersHelper", () => ({ default: { getFiltersCondition: vi.fn() } }));
|
||||
|
||||
import { cachified, clearCacheKey } from "~/utils/cache.server";
|
||||
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
|
||||
import { db } from "../../db.server";
|
||||
import {
|
||||
createRole,
|
||||
deleteRole,
|
||||
getAllRoles,
|
||||
getAllRolesNames,
|
||||
getAllRolesWithoutPermissions,
|
||||
getAllRolesWithUsers,
|
||||
getNextRolesOrder,
|
||||
getRole,
|
||||
getRoleByName,
|
||||
getRoles,
|
||||
getRolesByName,
|
||||
getTenantAppRoleByName,
|
||||
getTenantAssignableAppRole,
|
||||
getTenantMutableAppRole,
|
||||
updateRole,
|
||||
} from "./roles.db.server";
|
||||
|
||||
const dbMock = vi.mocked(db);
|
||||
|
||||
describe("role persistence", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(cachified).mockImplementation((async (options: { getFreshValue: () => unknown }) =>
|
||||
options.getFreshValue()) as never);
|
||||
});
|
||||
|
||||
it("lists global roles with permissions and supports type filtering", async () => {
|
||||
vi.mocked(dbMock.role.findMany).mockResolvedValue([] as never);
|
||||
|
||||
await getAllRoles();
|
||||
await getAllRoles("admin");
|
||||
await getAllRolesNames();
|
||||
|
||||
expect(dbMock.role.findMany).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({
|
||||
where: {},
|
||||
include: { permissions: { include: { permission: true }, orderBy: { permission: { name: "asc" } } } },
|
||||
orderBy: [{ type: "asc" }, { order: "asc" }],
|
||||
})
|
||||
);
|
||||
expect(dbMock.role.findMany).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
where: { type: "admin", tenantId: null },
|
||||
include: { permissions: { include: { permission: true }, orderBy: { permission: { name: "asc" } } } },
|
||||
})
|
||||
);
|
||||
expect(dbMock.role.findMany).toHaveBeenNthCalledWith(3, { select: { id: true, name: true }, orderBy: [{ type: "asc" }, { order: "asc" }] });
|
||||
});
|
||||
|
||||
it("caches role lists without permissions", async () => {
|
||||
vi.mocked(dbMock.role.findMany).mockResolvedValue([{ id: "role_1" }] as never);
|
||||
|
||||
await expect(getAllRolesWithoutPermissions("app")).resolves.toEqual([{ id: "role_1" }]);
|
||||
await expect(getAllRolesWithoutPermissions()).resolves.toEqual([{ id: "role_1" }]);
|
||||
|
||||
expect(cachified).toHaveBeenNthCalledWith(1, expect.objectContaining({ key: "roles:app", ttl: 1000 * 60 * 60 * 24 }));
|
||||
expect(cachified).toHaveBeenNthCalledWith(2, expect.objectContaining({ key: "roles:undefined", ttl: 1000 * 60 * 60 * 24 }));
|
||||
expect(dbMock.role.findMany).toHaveBeenNthCalledWith(1, {
|
||||
where: { type: "app", tenantId: null },
|
||||
orderBy: [{ type: "asc" }, { order: "asc" }],
|
||||
});
|
||||
expect(dbMock.role.findMany).toHaveBeenNthCalledWith(2, {
|
||||
where: {},
|
||||
orderBy: [{ type: "asc" }, { order: "asc" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("lists roles with users using tenant scope and permission filters", async () => {
|
||||
vi.mocked(RowFiltersHelper.getFiltersCondition).mockReturnValue({ name: { contains: "editor" } } as never);
|
||||
vi.mocked(dbMock.role.findMany).mockResolvedValueOnce([] as never);
|
||||
|
||||
await getAllRolesWithUsers(
|
||||
"app",
|
||||
{ properties: [{ name: "permissionId", value: "permission_1" }] } as never,
|
||||
"tenant_1"
|
||||
);
|
||||
|
||||
expect(dbMock.role.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: {
|
||||
AND: [
|
||||
{ type: "app", OR: [{ tenantId: null }, { tenantId: "tenant_1" }] },
|
||||
{ OR: [{ name: { contains: "editor" } }, { permissions: { some: { permissionId: "permission_1" } } }] },
|
||||
],
|
||||
},
|
||||
include: expect.objectContaining({
|
||||
permissions: { include: { permission: true }, orderBy: { permission: { name: "asc" } } },
|
||||
users: expect.objectContaining({ where: { tenantId: "tenant_1" } }),
|
||||
}),
|
||||
orderBy: [{ type: "asc" }, { order: "asc" }],
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("lists global roles with users when filters do not target a permission", async () => {
|
||||
vi.mocked(RowFiltersHelper.getFiltersCondition).mockReturnValue({ name: { contains: "member" } } as never);
|
||||
vi.mocked(dbMock.role.findMany).mockResolvedValueOnce([] as never);
|
||||
|
||||
await getAllRolesWithUsers("app", { properties: [{ name: "name", value: "member" }] } as never);
|
||||
|
||||
expect(dbMock.role.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: {
|
||||
AND: [{ type: "app", tenantId: null }, { name: { contains: "member" } }],
|
||||
},
|
||||
include: expect.objectContaining({
|
||||
users: expect.not.objectContaining({ where: expect.anything() }),
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("queries role lookup variants with permission and user details", async () => {
|
||||
vi.mocked(dbMock.role.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(dbMock.role.findUnique).mockResolvedValue({ id: "role_1" } as never);
|
||||
vi.mocked(dbMock.role.findFirst).mockResolvedValue({ id: "role_1" } as never);
|
||||
|
||||
await getRoles(["role_1"]);
|
||||
await getRolesByName(["Admin", "Member"]);
|
||||
await getRole("role_1");
|
||||
await getTenantAssignableAppRole("role_1", "tenant_1");
|
||||
await getTenantMutableAppRole("role_1", "tenant_1");
|
||||
await getRoleByName("Admin");
|
||||
await getTenantAppRoleByName("Support", "tenant_1");
|
||||
|
||||
expect(dbMock.role.findMany).toHaveBeenNthCalledWith(1, expect.objectContaining({ where: { id: { in: ["role_1"] } } }));
|
||||
expect(dbMock.role.findMany).toHaveBeenNthCalledWith(2, expect.objectContaining({ where: { name: { in: ["Admin", "Member"] } } }));
|
||||
expect(dbMock.role.findUnique).toHaveBeenCalledWith(expect.objectContaining({ where: { id: "role_1" } }));
|
||||
expect(dbMock.role.findFirst).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({ where: { id: "role_1", type: "app", OR: [{ isDefault: true, tenantId: null }, { tenantId: "tenant_1" }] } })
|
||||
);
|
||||
expect(dbMock.role.findFirst).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({ where: { id: "role_1", type: "app", isDefault: false, tenantId: "tenant_1" } })
|
||||
);
|
||||
expect(dbMock.role.findFirst).toHaveBeenNthCalledWith(3, expect.objectContaining({ where: { name: "Admin", tenantId: null } }));
|
||||
expect(dbMock.role.findFirst).toHaveBeenNthCalledWith(4, expect.objectContaining({ where: { name: "Support", tenantId: "tenant_1", type: "app" } }));
|
||||
});
|
||||
|
||||
it("calculates next role order for global and tenant-scoped roles", async () => {
|
||||
vi.mocked(dbMock.role.aggregate)
|
||||
.mockResolvedValueOnce({ _max: { order: 4 } } as never)
|
||||
.mockResolvedValueOnce({ _max: { order: null } } as never);
|
||||
|
||||
await expect(getNextRolesOrder("app", "tenant_1")).resolves.toBe(5);
|
||||
await expect(getNextRolesOrder()).resolves.toBe(1);
|
||||
|
||||
expect(dbMock.role.aggregate).toHaveBeenNthCalledWith(1, { where: { type: "app", tenantId: "tenant_1" }, _max: { order: true } });
|
||||
expect(dbMock.role.aggregate).toHaveBeenNthCalledWith(2, { where: {}, _max: { order: true } });
|
||||
});
|
||||
|
||||
it("clears role-list caches after create, update, and delete mutations", async () => {
|
||||
vi.mocked(dbMock.role.create).mockResolvedValueOnce({ id: "role_1", type: "app" } as never);
|
||||
vi.mocked(dbMock.role.update).mockResolvedValueOnce({ id: "role_1", type: "admin" } as never);
|
||||
vi.mocked(dbMock.role.delete).mockResolvedValueOnce({ id: "role_1", type: "app" } as never);
|
||||
|
||||
await createRole({
|
||||
order: 1,
|
||||
name: "Support",
|
||||
description: "Support role",
|
||||
type: "app",
|
||||
assignToNewUsers: false,
|
||||
isDefault: false,
|
||||
tenantId: "tenant_1",
|
||||
});
|
||||
await updateRole("role_1", { name: "Admin", description: "Admin role", type: "admin", assignToNewUsers: true });
|
||||
await deleteRole("role_1");
|
||||
|
||||
expect(dbMock.role.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
order: 1,
|
||||
name: "Support",
|
||||
description: "Support role",
|
||||
type: "app",
|
||||
assignToNewUsers: false,
|
||||
isDefault: false,
|
||||
tenantId: "tenant_1",
|
||||
},
|
||||
});
|
||||
expect(dbMock.role.update).toHaveBeenCalledWith({
|
||||
where: { id: "role_1" },
|
||||
data: { name: "Admin", description: "Admin role", type: "admin", assignToNewUsers: true },
|
||||
});
|
||||
expect(dbMock.role.delete).toHaveBeenCalledWith({ where: { id: "role_1" } });
|
||||
expect(clearCacheKey).toHaveBeenNthCalledWith(1, "roles:app");
|
||||
expect(clearCacheKey).toHaveBeenNthCalledWith(2, "roles:admin");
|
||||
expect(clearCacheKey).toHaveBeenNthCalledWith(3, "roles:app");
|
||||
});
|
||||
});
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
import { db } from "../../db.server";
|
||||
import { Permission, Role, RolePermission, UserRole } from "@toolctrl/db/prisma-browser";
|
||||
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
|
||||
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
|
||||
import { UserSimple } from "../users.db.server";
|
||||
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
|
||||
import { cachified, clearCacheKey } from "~/utils/cache.server";
|
||||
|
||||
export type RoleWithPermissions = Role & {
|
||||
permissions: (RolePermission & { permission: Permission })[];
|
||||
};
|
||||
|
||||
export type RoleWithPermissionsAndUsers = RoleWithPermissions & {
|
||||
users: (UserRole & { user: UserSimple })[];
|
||||
};
|
||||
|
||||
export async function getAllRoles(type?: "admin" | "app"): Promise<RoleWithPermissions[]> {
|
||||
let where = {};
|
||||
if (type !== undefined) {
|
||||
where = {
|
||||
type,
|
||||
tenantId: null,
|
||||
};
|
||||
}
|
||||
|
||||
return await db.role.findMany({
|
||||
where,
|
||||
include: {
|
||||
permissions: {
|
||||
include: {
|
||||
permission: true,
|
||||
},
|
||||
orderBy: { permission: { name: "asc" } },
|
||||
},
|
||||
},
|
||||
orderBy: [
|
||||
{
|
||||
type: "asc",
|
||||
},
|
||||
{
|
||||
order: "asc",
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAllRolesNames(): Promise<{ id: string; name: string }[]> {
|
||||
return await db.role.findMany({
|
||||
select: { id: true, name: true },
|
||||
orderBy: [{ type: "asc" }, { order: "asc" }],
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAllRolesWithoutPermissions(type?: "admin" | "app"): Promise<Role[]> {
|
||||
let where = {};
|
||||
if (type !== undefined) {
|
||||
where = {
|
||||
type,
|
||||
tenantId: null,
|
||||
};
|
||||
}
|
||||
|
||||
return await cachified({
|
||||
key: `roles:${type}`,
|
||||
ttl: 1000 * 60 * 60 * 24,
|
||||
getFreshValue: () =>
|
||||
db.role.findMany({
|
||||
where,
|
||||
orderBy: [
|
||||
{
|
||||
type: "asc",
|
||||
},
|
||||
{
|
||||
order: "asc",
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAllRolesWithUsers(type?: "admin" | "app", filters?: FiltersDto, tenantId?: string | null): Promise<RoleWithPermissionsAndUsers[]> {
|
||||
const scopeWhere: any = {
|
||||
...(type !== undefined ? { type } : {}),
|
||||
...(tenantId !== undefined ? { OR: [{ tenantId: null }, { tenantId }] } : { tenantId: null }),
|
||||
};
|
||||
let where: any = scopeWhere;
|
||||
if (filters !== undefined) {
|
||||
const filterWhere = RowFiltersHelper.getFiltersCondition(filters);
|
||||
const permissionId = filters?.properties.find((f) => f.name === "permissionId")?.value;
|
||||
const permissionWhere = permissionId ? { OR: [filterWhere, { permissions: { some: { permissionId } } }] } : filterWhere;
|
||||
where = {
|
||||
AND: [scopeWhere, permissionWhere],
|
||||
};
|
||||
}
|
||||
return await db.role.findMany({
|
||||
where,
|
||||
include: {
|
||||
permissions: {
|
||||
include: {
|
||||
permission: true,
|
||||
},
|
||||
orderBy: { permission: { name: "asc" } },
|
||||
},
|
||||
users: {
|
||||
...(tenantId !== undefined ? { where: { tenantId } } : {}),
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleUser,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: [
|
||||
{
|
||||
type: "asc",
|
||||
},
|
||||
{
|
||||
order: "asc",
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRoles(ids: string[]): Promise<RoleWithPermissionsAndUsers[]> {
|
||||
return await db.role.findMany({
|
||||
where: {
|
||||
id: {
|
||||
in: ids,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
permissions: {
|
||||
include: {
|
||||
permission: true,
|
||||
},
|
||||
orderBy: { permission: { name: "asc" } },
|
||||
},
|
||||
users: {
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleUser,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRolesByName(names: string[]): Promise<RoleWithPermissionsAndUsers[]> {
|
||||
return await db.role.findMany({
|
||||
where: {
|
||||
name: {
|
||||
in: names,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
permissions: {
|
||||
include: {
|
||||
permission: true,
|
||||
},
|
||||
orderBy: { permission: { name: "asc" } },
|
||||
},
|
||||
users: {
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleUser,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRole(id: string): Promise<RoleWithPermissions | null> {
|
||||
return await db.role.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
include: {
|
||||
permissions: {
|
||||
include: {
|
||||
permission: true,
|
||||
},
|
||||
orderBy: { permission: { name: "asc" } },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantAssignableAppRole(id: string, tenantId: string): Promise<RoleWithPermissions | null> {
|
||||
return await db.role.findFirst({
|
||||
where: {
|
||||
id,
|
||||
type: "app",
|
||||
OR: [{ isDefault: true, tenantId: null }, { tenantId }],
|
||||
},
|
||||
include: {
|
||||
permissions: {
|
||||
include: {
|
||||
permission: true,
|
||||
},
|
||||
orderBy: { permission: { name: "asc" } },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantMutableAppRole(id: string, tenantId: string): Promise<RoleWithPermissions | null> {
|
||||
return await db.role.findFirst({
|
||||
where: {
|
||||
id,
|
||||
type: "app",
|
||||
isDefault: false,
|
||||
tenantId,
|
||||
},
|
||||
include: {
|
||||
permissions: {
|
||||
include: {
|
||||
permission: true,
|
||||
},
|
||||
orderBy: { permission: { name: "asc" } },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRoleByName(name: string): Promise<RoleWithPermissions | null> {
|
||||
return await db.role.findFirst({
|
||||
where: {
|
||||
name,
|
||||
tenantId: null,
|
||||
},
|
||||
include: {
|
||||
permissions: {
|
||||
include: {
|
||||
permission: true,
|
||||
},
|
||||
orderBy: { permission: { name: "asc" } },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantAppRoleByName(name: string, tenantId: string): Promise<RoleWithPermissions | null> {
|
||||
return await db.role.findFirst({
|
||||
where: {
|
||||
name,
|
||||
tenantId,
|
||||
type: "app",
|
||||
},
|
||||
include: {
|
||||
permissions: {
|
||||
include: {
|
||||
permission: true,
|
||||
},
|
||||
orderBy: { permission: { name: "asc" } },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getNextRolesOrder(type?: "admin" | "app", tenantId?: string | null): Promise<number> {
|
||||
let where = {};
|
||||
if (type !== undefined) {
|
||||
where = {
|
||||
type,
|
||||
tenantId: tenantId ?? null,
|
||||
};
|
||||
}
|
||||
return (
|
||||
((
|
||||
await db.role.aggregate({
|
||||
where,
|
||||
_max: {
|
||||
order: true,
|
||||
},
|
||||
})
|
||||
)._max.order ?? 0) + 1
|
||||
);
|
||||
}
|
||||
|
||||
export async function createRole(data: {
|
||||
order: number;
|
||||
name: string;
|
||||
description: string;
|
||||
type: "admin" | "app";
|
||||
assignToNewUsers: boolean;
|
||||
isDefault: boolean;
|
||||
tenantId?: string | null;
|
||||
}) {
|
||||
return await db.role
|
||||
.create({
|
||||
data,
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`roles:${data.type}`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateRole(id: string, data: { name: string; description: string; type: "admin" | "app"; assignToNewUsers: boolean }) {
|
||||
return await db.role
|
||||
.update({
|
||||
where: { id },
|
||||
data,
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`roles:${item.type}`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteRole(id: string) {
|
||||
return await db.role
|
||||
.delete({
|
||||
where: { id },
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`roles:${item.type}`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../../db.server", () => ({
|
||||
db: {
|
||||
rowPermission: {
|
||||
create: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { db } from "../../db.server";
|
||||
import {
|
||||
createRowPermission,
|
||||
deleteRowPermission,
|
||||
deleteRowPermissionByIdForRow,
|
||||
getRowPermissionByGroups,
|
||||
getRowPermissionByRoles,
|
||||
getRowPermissionByTenant,
|
||||
getRowPermissionByUsers,
|
||||
getRowPermissions,
|
||||
updateRowPermissionForRow,
|
||||
} from "./rowPermissions.db.server";
|
||||
|
||||
const dbMock = vi.mocked(db);
|
||||
|
||||
describe("row permission persistence", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("lists row permissions with tenant, role, group, and user display details", async () => {
|
||||
vi.mocked(dbMock.rowPermission.findMany).mockResolvedValueOnce([{ id: "rp_1" }] as never);
|
||||
|
||||
await expect(getRowPermissions("row_1")).resolves.toEqual([{ id: "rp_1" }]);
|
||||
|
||||
expect(dbMock.rowPermission.findMany).toHaveBeenCalledWith({
|
||||
where: { rowId: "row_1" },
|
||||
include: {
|
||||
tenant: { select: { id: true, name: true } },
|
||||
role: { select: { id: true, name: true } },
|
||||
group: { select: { id: true, name: true } },
|
||||
user: { select: { id: true, email: true } },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("looks up row permissions by scoped principals", async () => {
|
||||
vi.mocked(dbMock.rowPermission.findFirst).mockResolvedValue({ id: "rp_1" } as never);
|
||||
|
||||
await getRowPermissionByTenant("row_1", "tenant_1");
|
||||
await getRowPermissionByGroups("row_1", ["group_1", "group_2"]);
|
||||
await getRowPermissionByRoles("row_1", ["role_1"]);
|
||||
await getRowPermissionByUsers("row_1", ["user_1"]);
|
||||
|
||||
expect(dbMock.rowPermission.findFirst).toHaveBeenNthCalledWith(1, { where: { rowId: "row_1", tenantId: "tenant_1" } });
|
||||
expect(dbMock.rowPermission.findFirst).toHaveBeenNthCalledWith(2, { where: { rowId: "row_1", groupId: { in: ["group_1", "group_2"] } } });
|
||||
expect(dbMock.rowPermission.findFirst).toHaveBeenNthCalledWith(3, { where: { rowId: "row_1", roleId: { in: ["role_1"] } } });
|
||||
expect(dbMock.rowPermission.findFirst).toHaveBeenNthCalledWith(4, { where: { rowId: "row_1", userId: { in: ["user_1"] } } });
|
||||
});
|
||||
|
||||
it("creates, updates, and deletes row permissions through row-scoped predicates", async () => {
|
||||
vi.mocked(dbMock.rowPermission.create).mockResolvedValueOnce({ id: "rp_1" } as never);
|
||||
vi.mocked(dbMock.rowPermission.updateMany).mockResolvedValueOnce({ count: 1 } as never);
|
||||
vi.mocked(dbMock.rowPermission.deleteMany).mockResolvedValue({ count: 1 } as never);
|
||||
|
||||
await expect(createRowPermission({ rowId: "row_1", tenantId: "tenant_1", access: "view" })).resolves.toEqual({ id: "rp_1" });
|
||||
await expect(updateRowPermissionForRow("row_1", "rp_1", { access: "edit" })).resolves.toEqual({ count: 1 });
|
||||
await expect(deleteRowPermission("row_1")).resolves.toEqual({ count: 1 });
|
||||
await expect(deleteRowPermissionByIdForRow("row_1", "rp_1")).resolves.toEqual({ count: 1 });
|
||||
|
||||
expect(dbMock.rowPermission.create).toHaveBeenCalledWith({ data: { rowId: "row_1", tenantId: "tenant_1", access: "view" } });
|
||||
expect(dbMock.rowPermission.updateMany).toHaveBeenCalledWith({ where: { id: "rp_1", rowId: "row_1" }, data: { access: "edit" } });
|
||||
expect(dbMock.rowPermission.deleteMany).toHaveBeenNthCalledWith(1, { where: { rowId: "row_1" } });
|
||||
expect(dbMock.rowPermission.deleteMany).toHaveBeenNthCalledWith(2, { where: { id: "rp_1", rowId: "row_1" } });
|
||||
});
|
||||
});
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
import { RowPermission } from "@toolctrl/db/prisma-browser";
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
export type RowPermissionsWithDetails = RowPermission & {
|
||||
tenant: { id: string; name: string } | null;
|
||||
role?: { id: string; name: string } | null;
|
||||
group?: { id: string; name: string } | null;
|
||||
user?: { id: string; email: string } | null;
|
||||
};
|
||||
export async function getRowPermissions(rowId: string): Promise<RowPermissionsWithDetails[]> {
|
||||
return await db.rowPermission.findMany({
|
||||
where: {
|
||||
rowId,
|
||||
},
|
||||
include: {
|
||||
tenant: { select: { id: true, name: true } },
|
||||
role: { select: { id: true, name: true } },
|
||||
group: { select: { id: true, name: true } },
|
||||
user: { select: { id: true, email: true } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRowPermissionByTenant(rowId: string, tenantId?: string | null) {
|
||||
return await db.rowPermission.findFirst({
|
||||
where: {
|
||||
rowId,
|
||||
tenantId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRowPermissionByGroups(rowId: string, groups: string[]) {
|
||||
return await db.rowPermission.findFirst({
|
||||
where: {
|
||||
rowId,
|
||||
groupId: {
|
||||
in: groups,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRowPermissionByRoles(rowId: string, roles: string[]) {
|
||||
return await db.rowPermission.findFirst({
|
||||
where: {
|
||||
rowId,
|
||||
roleId: {
|
||||
in: roles,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRowPermissionByUsers(rowId: string, users: string[]) {
|
||||
return await db.rowPermission.findFirst({
|
||||
where: {
|
||||
rowId,
|
||||
userId: {
|
||||
in: users,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createRowPermission(data: {
|
||||
rowId: string;
|
||||
tenantId?: string | null;
|
||||
roleId?: string | null;
|
||||
groupId?: string | null;
|
||||
userId?: string | null;
|
||||
public?: boolean | null;
|
||||
access: string;
|
||||
}) {
|
||||
return await db.rowPermission.create({
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateRowPermissionForRow(rowId: string, id: string, data: { access: string }) {
|
||||
return await db.rowPermission.updateMany({
|
||||
where: { id, rowId },
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteRowPermission(rowId: string) {
|
||||
return await db.rowPermission.deleteMany({
|
||||
where: {
|
||||
rowId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteRowPermissionByIdForRow(rowId: string, id: string) {
|
||||
return await db.rowPermission.deleteMany({
|
||||
where: {
|
||||
id,
|
||||
rowId,
|
||||
},
|
||||
});
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../../db.server", () => ({
|
||||
db: {
|
||||
groupUser: {
|
||||
create: vi.fn(),
|
||||
createMany: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
},
|
||||
$transaction: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import { db } from "../../db.server";
|
||||
import { createUserGroup, createUserGroups, deleteGroupUsers, deleteUserGroup, replaceGroupUsers } from "./userGroups.db.server";
|
||||
|
||||
const dbMock = vi.mocked(db);
|
||||
|
||||
describe("user group persistence", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(dbMock.$transaction).mockImplementation((async (callback: (tx: typeof dbMock) => Promise<unknown>) => callback(dbMock)) as never);
|
||||
});
|
||||
|
||||
it("creates and deletes single group memberships", async () => {
|
||||
vi.mocked(dbMock.groupUser.create).mockResolvedValueOnce({ id: "group_user_1" } as never);
|
||||
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 1 } as never);
|
||||
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 2 } as never);
|
||||
|
||||
await expect(createUserGroup("user_1", "group_1")).resolves.toEqual({ id: "group_user_1" });
|
||||
await expect(deleteUserGroup("user_1", "group_1")).resolves.toEqual({ count: 1 });
|
||||
await expect(deleteGroupUsers("group_1", "tenant_1")).resolves.toEqual({ count: 2 });
|
||||
|
||||
expect(dbMock.groupUser.create).toHaveBeenCalledWith({ data: { userId: "user_1", groupId: "group_1" } });
|
||||
expect(dbMock.groupUser.deleteMany).toHaveBeenNthCalledWith(1, { where: { userId: "user_1", groupId: "group_1" } });
|
||||
expect(dbMock.groupUser.deleteMany).toHaveBeenNthCalledWith(2, { where: { groupId: "group_1", group: { tenantId: "tenant_1" } } });
|
||||
});
|
||||
|
||||
it("bulk-creates deduplicated group memberships with database duplicate protection", async () => {
|
||||
vi.mocked(dbMock.groupUser.createMany).mockResolvedValueOnce({ count: 2 } as never);
|
||||
|
||||
await expect(createUserGroups("group_1", ["user_1", "user_2", "user_1"])).resolves.toEqual({ count: 2 });
|
||||
|
||||
expect(dbMock.groupUser.createMany).toHaveBeenCalledWith({
|
||||
data: [
|
||||
{ userId: "user_1", groupId: "group_1" },
|
||||
{ userId: "user_2", groupId: "group_1" },
|
||||
],
|
||||
skipDuplicates: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("skips bulk membership writes when no users are selected", async () => {
|
||||
await expect(createUserGroups("group_1", [])).resolves.toEqual({ count: 0 });
|
||||
|
||||
expect(dbMock.groupUser.createMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("replaces group memberships inside one transaction", async () => {
|
||||
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 3 } as never);
|
||||
vi.mocked(dbMock.groupUser.createMany).mockResolvedValueOnce({ count: 2 } as never);
|
||||
|
||||
await expect(replaceGroupUsers("group_1", "tenant_1", ["user_1", "user_2", "user_1"])).resolves.toEqual({ count: 2 });
|
||||
|
||||
expect(dbMock.$transaction).toHaveBeenCalledTimes(1);
|
||||
expect(dbMock.groupUser.deleteMany).toHaveBeenCalledWith({ where: { groupId: "group_1", group: { tenantId: "tenant_1" } } });
|
||||
expect(dbMock.groupUser.createMany).toHaveBeenCalledWith({
|
||||
data: [
|
||||
{ userId: "user_1", groupId: "group_1" },
|
||||
{ userId: "user_2", groupId: "group_1" },
|
||||
],
|
||||
skipDuplicates: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("replaces group memberships with an empty set without bulk insert", async () => {
|
||||
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 3 } as never);
|
||||
|
||||
await expect(replaceGroupUsers("group_1", "tenant_1", [])).resolves.toEqual({ count: 0 });
|
||||
|
||||
expect(dbMock.$transaction).toHaveBeenCalledTimes(1);
|
||||
expect(dbMock.groupUser.deleteMany).toHaveBeenCalledWith({ where: { groupId: "group_1", group: { tenantId: "tenant_1" } } });
|
||||
expect(dbMock.groupUser.createMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
export async function createUserGroup(userId: string, groupId: string) {
|
||||
return await db.groupUser.create({
|
||||
data: {
|
||||
userId,
|
||||
groupId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createUserGroups(groupId: string, userIds: string[]) {
|
||||
const uniqueUserIds = [...new Set(userIds)];
|
||||
if (uniqueUserIds.length === 0) {
|
||||
return { count: 0 };
|
||||
}
|
||||
return await db.groupUser.createMany({
|
||||
data: uniqueUserIds.map((userId) => ({
|
||||
userId,
|
||||
groupId,
|
||||
})),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteUserGroup(userId: string, groupId: string) {
|
||||
return await db.groupUser.deleteMany({
|
||||
where: {
|
||||
userId,
|
||||
groupId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function replaceGroupUsers(groupId: string, tenantId: string, userIds: string[]) {
|
||||
const uniqueUserIds = [...new Set(userIds)];
|
||||
return await db.$transaction(async (tx) => {
|
||||
await tx.groupUser.deleteMany({
|
||||
where: {
|
||||
groupId,
|
||||
group: { tenantId },
|
||||
},
|
||||
});
|
||||
if (uniqueUserIds.length === 0) {
|
||||
return { count: 0 };
|
||||
}
|
||||
return await tx.groupUser.createMany({
|
||||
data: uniqueUserIds.map((userId) => ({
|
||||
userId,
|
||||
groupId,
|
||||
})),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteGroupUsers(groupId: string, tenantId: string) {
|
||||
return await db.groupUser.deleteMany({
|
||||
where: {
|
||||
groupId,
|
||||
group: { tenantId },
|
||||
},
|
||||
});
|
||||
}
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
|
||||
vi.mock("../../db.server", () => ({
|
||||
db: {
|
||||
permission: {
|
||||
count: vi.fn(),
|
||||
},
|
||||
role: {
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
userRole: {
|
||||
count: vi.fn(),
|
||||
create: vi.fn(),
|
||||
createMany: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
vi.mock("~/utils/cache.server", () => ({
|
||||
cachified: vi.fn((options: { getFreshValue: () => unknown }) => options.getFreshValue()),
|
||||
clearCacheKey: vi.fn(),
|
||||
}));
|
||||
|
||||
import { cachified, clearCacheKey } from "~/utils/cache.server";
|
||||
import { db } from "../../db.server";
|
||||
import {
|
||||
countUserPermission,
|
||||
createUserRole,
|
||||
createUserRoles,
|
||||
deleteAllUserRoles,
|
||||
deleteUserRole,
|
||||
ensureTenantUserAppRoles,
|
||||
findPermissionByUser,
|
||||
findUserRolesByIds,
|
||||
getPermissionsByUser,
|
||||
getUserRole,
|
||||
getUserRoleInAdmin,
|
||||
getUserRoleInTenant,
|
||||
getUserRoles,
|
||||
getUsersRolesInTenant,
|
||||
userHasPermission,
|
||||
} from "./userRoles.db.server";
|
||||
|
||||
const dbMock = vi.mocked(db);
|
||||
|
||||
describe("user role persistence", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(cachified).mockImplementation((async (options: { getFreshValue: () => unknown }) => options.getFreshValue()) as never);
|
||||
});
|
||||
|
||||
it("queries user-role relationships with tenant and admin scope", async () => {
|
||||
vi.mocked(dbMock.userRole.findFirst).mockResolvedValue({ id: "ur_1" } as never);
|
||||
vi.mocked(dbMock.userRole.findMany).mockResolvedValue([] as never);
|
||||
|
||||
await getUserRole("user_1", "role_1", "tenant_1");
|
||||
await getUserRoleInTenant("user_1", "tenant_1", "Admin");
|
||||
await getUserRoleInAdmin("user_1", "SuperAdmin");
|
||||
await getUserRoles("user_1", "tenant_1");
|
||||
|
||||
expect(dbMock.userRole.findFirst).toHaveBeenNthCalledWith(1, {
|
||||
where: { userId: "user_1", roleId: "role_1", tenantId: "tenant_1" },
|
||||
});
|
||||
expect(dbMock.userRole.findFirst).toHaveBeenNthCalledWith(2, {
|
||||
where: { userId: "user_1", role: { name: "Admin" }, tenantId: "tenant_1" },
|
||||
});
|
||||
expect(dbMock.userRole.findFirst).toHaveBeenNthCalledWith(3, {
|
||||
where: { userId: "user_1", role: { name: "SuperAdmin" }, tenantId: null },
|
||||
});
|
||||
expect(dbMock.userRole.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { userId: "user_1", tenantId: "tenant_1" },
|
||||
orderBy: { role: { order: "asc" } },
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("deduplicates permissions returned from cached user-role expansion", async () => {
|
||||
vi.mocked(dbMock.userRole.findMany).mockResolvedValueOnce([
|
||||
{
|
||||
role: {
|
||||
name: "Admin",
|
||||
permissions: [{ permission: { name: "members.read" } }, { permission: { name: "members.read" } }],
|
||||
},
|
||||
},
|
||||
{
|
||||
role: {
|
||||
name: "Member",
|
||||
permissions: [{ permission: { name: "settings.update" } }],
|
||||
},
|
||||
},
|
||||
] as never);
|
||||
|
||||
await expect(getPermissionsByUser("user_1", "tenant_1")).resolves.toEqual(["members.read", "settings.update"]);
|
||||
|
||||
expect(cachified).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
key: "userRoles:user_1:tenant_1",
|
||||
ttl: 1000 * 60 * 60 * 24,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("checks permission membership through the cached user-role expansion", async () => {
|
||||
vi.mocked(dbMock.userRole.findMany)
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
role: {
|
||||
name: "Admin",
|
||||
permissions: [{ permission: { name: "members.read" } }],
|
||||
},
|
||||
},
|
||||
] as never)
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
role: {
|
||||
name: "Admin",
|
||||
permissions: [{ permission: { name: "members.read" } }],
|
||||
},
|
||||
},
|
||||
] as never);
|
||||
|
||||
await expect(userHasPermission("user_1", "tenant_1", "members.read")).resolves.toBe(true);
|
||||
await expect(userHasPermission("user_1", "tenant_1", "settings.update")).resolves.toBe(false);
|
||||
|
||||
expect(cachified).toHaveBeenCalledWith(expect.objectContaining({ key: "userRoles:user_1:tenant_1" }));
|
||||
expect(dbMock.permission.count).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns the first matching permission name or null", async () => {
|
||||
vi.mocked(dbMock.userRole.findMany)
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
role: {
|
||||
name: "Admin",
|
||||
permissions: [{ permission: { name: "members.read" } }],
|
||||
},
|
||||
},
|
||||
] as never)
|
||||
.mockResolvedValueOnce([] as never);
|
||||
|
||||
await expect(findPermissionByUser("members.read", "user_1", "tenant_1")).resolves.toBe("members.read");
|
||||
await expect(findPermissionByUser("members.read", "user_1", "tenant_1")).resolves.toBeNull();
|
||||
|
||||
expect(dbMock.userRole.findMany).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({
|
||||
where: {
|
||||
userId: "user_1",
|
||||
tenantId: "tenant_1",
|
||||
role: { permissions: { some: { permission: { name: "members.read" } } } },
|
||||
},
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("counts direct role permission matches and returns zero when none exist", async () => {
|
||||
vi.mocked(dbMock.permission.count).mockResolvedValueOnce(2).mockResolvedValueOnce(0);
|
||||
|
||||
await expect(countUserPermission("user_1", "tenant_1", "members.read")).resolves.toBe(2);
|
||||
await expect(countUserPermission("user_1", "tenant_1", "members.read")).resolves.toBe(0);
|
||||
|
||||
expect(dbMock.permission.count).toHaveBeenCalledWith({
|
||||
where: {
|
||||
name: "members.read",
|
||||
inRoles: { some: { role: { users: { some: { userId: "user_1", tenantId: "tenant_1" } } } } },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("queries bulk role helpers by ids, tenant, and type", async () => {
|
||||
vi.mocked(dbMock.userRole.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(dbMock.userRole.deleteMany).mockResolvedValue({ count: 2 } as never);
|
||||
|
||||
await findUserRolesByIds("user_1", "tenant_1", ["role_1", "role_2"]);
|
||||
await getUsersRolesInTenant("tenant_1");
|
||||
await deleteAllUserRoles("user_1", "app");
|
||||
|
||||
expect(dbMock.userRole.findMany).toHaveBeenNthCalledWith(1, {
|
||||
where: { userId: "user_1", tenantId: "tenant_1", roleId: { in: ["role_1", "role_2"] } },
|
||||
});
|
||||
expect(dbMock.userRole.findMany).toHaveBeenNthCalledWith(2, {
|
||||
where: { tenantId: "tenant_1" },
|
||||
include: { role: true, user: true },
|
||||
});
|
||||
expect(dbMock.userRole.deleteMany).toHaveBeenCalledWith({
|
||||
where: { userId: "user_1", role: { type: "app" } },
|
||||
});
|
||||
});
|
||||
|
||||
it("returns early from app-role repair when the user already has tenant app roles", async () => {
|
||||
vi.mocked(dbMock.userRole.count).mockResolvedValueOnce(2);
|
||||
|
||||
await expect(ensureTenantUserAppRoles({ userId: "user_1", tenantId: "tenant_1", tenantUserType: TenantUserType.MEMBER })).resolves.toEqual({
|
||||
created: 0,
|
||||
roleCount: 2,
|
||||
});
|
||||
|
||||
expect(dbMock.role.findMany).not.toHaveBeenCalled();
|
||||
expect(clearCacheKey).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("grants all scoped app roles to tenant owners and skips already assigned roles", async () => {
|
||||
vi.mocked(dbMock.userRole.count).mockResolvedValueOnce(0);
|
||||
vi.mocked(dbMock.role.findMany).mockResolvedValueOnce([{ id: "role_1" }, { id: "role_2" }] as never);
|
||||
vi.mocked(dbMock.userRole.findMany)
|
||||
.mockResolvedValueOnce([{ id: "existing_role_2", roleId: "role_2" }] as never)
|
||||
.mockResolvedValueOnce([] as never);
|
||||
vi.mocked(dbMock.userRole.createMany).mockResolvedValueOnce({ count: 1 } as never);
|
||||
|
||||
await expect(ensureTenantUserAppRoles({ userId: "user_1", tenantId: "tenant_1", tenantUserType: TenantUserType.OWNER })).resolves.toEqual({
|
||||
created: 1,
|
||||
roleCount: 2,
|
||||
});
|
||||
|
||||
expect(dbMock.role.findMany).toHaveBeenCalledWith({
|
||||
where: { type: "app", OR: [{ tenantId: null }, { tenantId: "tenant_1" }] },
|
||||
orderBy: { order: "asc" },
|
||||
});
|
||||
expect(dbMock.userRole.findMany).toHaveBeenCalledWith({
|
||||
where: { userId: "user_1", tenantId: "tenant_1", roleId: { in: ["role_1", "role_2"] } },
|
||||
});
|
||||
expect(dbMock.userRole.createMany).toHaveBeenCalledWith({
|
||||
data: [{ userId: "user_1", roleId: "role_1", tenantId: "tenant_1" }],
|
||||
skipDuplicates: true,
|
||||
});
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:tenant_1");
|
||||
});
|
||||
|
||||
it("clears role cache when every scoped app role is already assigned", async () => {
|
||||
vi.mocked(dbMock.userRole.count).mockResolvedValueOnce(0);
|
||||
vi.mocked(dbMock.role.findMany).mockResolvedValueOnce([{ id: "role_1" }] as never);
|
||||
vi.mocked(dbMock.userRole.findMany).mockResolvedValueOnce([{ id: "existing_role_1", roleId: "role_1" }] as never);
|
||||
|
||||
await expect(ensureTenantUserAppRoles({ userId: "user_1", tenantId: "tenant_1", tenantUserType: TenantUserType.ADMIN })).resolves.toEqual({
|
||||
created: 0,
|
||||
roleCount: 1,
|
||||
});
|
||||
|
||||
expect(dbMock.userRole.createMany).not.toHaveBeenCalled();
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:tenant_1");
|
||||
});
|
||||
|
||||
it("grants only assign-to-new-users app roles to regular members", async () => {
|
||||
vi.mocked(dbMock.userRole.count).mockResolvedValueOnce(0);
|
||||
vi.mocked(dbMock.role.findMany).mockResolvedValueOnce([] as never);
|
||||
|
||||
await ensureTenantUserAppRoles({ userId: "user_1", tenantId: "tenant_1", tenantUserType: TenantUserType.MEMBER });
|
||||
|
||||
expect(dbMock.role.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
type: "app",
|
||||
OR: [{ tenantId: null }, { tenantId: "tenant_1" }],
|
||||
assignToNewUsers: true,
|
||||
},
|
||||
orderBy: { order: "asc" },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not duplicate an existing user role", async () => {
|
||||
vi.mocked(dbMock.userRole.findFirst).mockResolvedValueOnce({ id: "ur_existing" } as never);
|
||||
|
||||
await expect(createUserRole("user_1", "role_1", "tenant_1")).resolves.toEqual({ id: "ur_existing" });
|
||||
|
||||
expect(dbMock.userRole.create).not.toHaveBeenCalled();
|
||||
expect(clearCacheKey).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns the concurrently-created user role when the unique assignment index wins the race", async () => {
|
||||
vi.mocked(dbMock.userRole.findFirst).mockResolvedValueOnce(null).mockResolvedValueOnce({ id: "ur_concurrent" } as never);
|
||||
vi.mocked(dbMock.userRole.create).mockRejectedValueOnce(Object.assign(new Error("Unique constraint failed"), { code: "P2002" }) as never);
|
||||
|
||||
await expect(createUserRole("user_1", "role_admin", null)).resolves.toEqual({ id: "ur_concurrent" });
|
||||
|
||||
expect(dbMock.userRole.create).toHaveBeenCalledWith({ data: { userId: "user_1", roleId: "role_admin", tenantId: null } });
|
||||
expect(dbMock.userRole.findFirst).toHaveBeenNthCalledWith(2, {
|
||||
where: { userId: "user_1", roleId: "role_admin", tenantId: null },
|
||||
});
|
||||
expect(clearCacheKey).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rethrows failed user-role creation when the error is not a recoverable unique race", async () => {
|
||||
const error = new Error("database down");
|
||||
vi.mocked(dbMock.userRole.findFirst).mockResolvedValueOnce(null);
|
||||
vi.mocked(dbMock.userRole.create).mockRejectedValueOnce(error as never);
|
||||
|
||||
await expect(createUserRole("user_1", "role_1", "tenant_1")).rejects.toBe(error);
|
||||
});
|
||||
|
||||
it("rethrows unique user-role creation races when the assignment cannot be found afterward", async () => {
|
||||
const error = Object.assign(new Error("Unique constraint failed"), { code: "P2002" });
|
||||
vi.mocked(dbMock.userRole.findFirst).mockResolvedValueOnce(null).mockResolvedValueOnce(null);
|
||||
vi.mocked(dbMock.userRole.create).mockRejectedValueOnce(error as never);
|
||||
|
||||
await expect(createUserRole("user_1", "role_1", null)).rejects.toBe(error);
|
||||
});
|
||||
|
||||
it("creates, bulk-creates, and deletes user roles while clearing tenant-specific caches", async () => {
|
||||
vi.mocked(dbMock.userRole.findFirst).mockResolvedValueOnce(null);
|
||||
vi.mocked(dbMock.userRole.create).mockResolvedValueOnce({ id: "ur_1" } as never);
|
||||
vi.mocked(dbMock.userRole.findMany).mockResolvedValueOnce([] as never);
|
||||
vi.mocked(dbMock.userRole.createMany).mockResolvedValueOnce({ count: 3 } as never);
|
||||
vi.mocked(dbMock.userRole.deleteMany).mockResolvedValueOnce({ count: 1 } as never);
|
||||
|
||||
await createUserRole("user_1", "role_1", "tenant_1");
|
||||
await createUserRoles("user_1", [
|
||||
{ id: "role_1", tenantId: "tenant_1" },
|
||||
{ id: "role_2", tenantId: "tenant_1" },
|
||||
{ id: "role_admin", tenantId: null },
|
||||
]);
|
||||
await deleteUserRole("user_1", "role_1", "tenant_1");
|
||||
|
||||
expect(dbMock.userRole.create).toHaveBeenCalledWith({ data: { userId: "user_1", roleId: "role_1", tenantId: "tenant_1" } });
|
||||
expect(dbMock.userRole.createMany).toHaveBeenCalledWith({
|
||||
data: [
|
||||
{ userId: "user_1", roleId: "role_1", tenantId: "tenant_1" },
|
||||
{ userId: "user_1", roleId: "role_2", tenantId: "tenant_1" },
|
||||
{ userId: "user_1", roleId: "role_admin", tenantId: null },
|
||||
],
|
||||
skipDuplicates: true,
|
||||
});
|
||||
expect(dbMock.userRole.deleteMany).toHaveBeenCalledWith({
|
||||
where: { userId: "user_1", roleId: "role_1", tenantId: "tenant_1" },
|
||||
});
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:tenant_1");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:null");
|
||||
});
|
||||
|
||||
it("handles empty and already-existing bulk role assignments without writes", async () => {
|
||||
await expect(createUserRoles("user_1", [])).resolves.toEqual({ count: 0 });
|
||||
|
||||
vi.mocked(dbMock.userRole.findMany).mockResolvedValueOnce([{ userId: "user_1", roleId: "role_1", tenantId: null }] as never);
|
||||
await expect(createUserRoles("user_1", [{ id: "role_1", tenantId: null }])).resolves.toEqual({ count: 0 });
|
||||
|
||||
expect(dbMock.userRole.createMany).not.toHaveBeenCalled();
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:null");
|
||||
});
|
||||
});
|
||||
+369
@@ -0,0 +1,369 @@
|
||||
import { Permission, Role, RolePermission, UserRole } from "@toolctrl/db/prisma-browser";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import { db } from "../../db.server";
|
||||
import { cachified, clearCacheKey } from "~/utils/cache.server";
|
||||
|
||||
export type UserRoleWithPermission = UserRole & {
|
||||
role: Role & { permissions: (RolePermission & { permission: Permission })[] };
|
||||
};
|
||||
|
||||
export type UserRoleAssignment = {
|
||||
userId: string;
|
||||
roleId: string;
|
||||
tenantId?: string | null;
|
||||
};
|
||||
|
||||
function normalizeTenantId(tenantId: string | null | undefined): string | null {
|
||||
return tenantId ?? null;
|
||||
}
|
||||
|
||||
function getUserRoleAssignmentKey(assignment: UserRoleAssignment): string {
|
||||
return `${assignment.userId}:${assignment.roleId}:${normalizeTenantId(assignment.tenantId)}`;
|
||||
}
|
||||
|
||||
function clearUserRoleCache(userId: string, tenantId: string | null): void {
|
||||
clearCacheKey(`userRoles:${userId}:${tenantId}`);
|
||||
}
|
||||
|
||||
function isUniqueConstraintError(error: unknown): boolean {
|
||||
return Boolean(error && typeof error === "object" && "code" in error && error.code === "P2002");
|
||||
}
|
||||
|
||||
export async function getUserRole(userId: string, roleId: string, tenantId?: string | null) {
|
||||
return await db.userRole.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
roleId,
|
||||
tenantId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getUserRoleInTenant(userId: string, tenantId: string, roleName: string) {
|
||||
return await db.userRole.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
role: {
|
||||
name: roleName,
|
||||
},
|
||||
tenantId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getUserRoleInAdmin(userId: string, roleName: string) {
|
||||
return await db.userRole.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
role: {
|
||||
name: roleName,
|
||||
},
|
||||
tenantId: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getUserRoles(userId: string, tenantId?: string | null): Promise<UserRoleWithPermission[]> {
|
||||
return await db.userRole.findMany({
|
||||
where: {
|
||||
userId,
|
||||
tenantId,
|
||||
},
|
||||
include: {
|
||||
role: {
|
||||
include: {
|
||||
permissions: {
|
||||
include: {
|
||||
permission: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
role: {
|
||||
order: "asc",
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPermissionsByUser(userId: string, tenantId: string | null): Promise<string[]> {
|
||||
const userRoles = await cachified({
|
||||
key: `userRoles:${userId}:${tenantId}`,
|
||||
ttl: 1000 * 60 * 60 * 24,
|
||||
getFreshValue: () =>
|
||||
db.userRole.findMany({
|
||||
where: { userId, tenantId },
|
||||
include: { role: { include: { permissions: { include: { permission: { select: { name: true } } } } } } },
|
||||
}),
|
||||
});
|
||||
const roles: string[] = [];
|
||||
const names: string[] = [];
|
||||
userRoles.forEach((userRoles) => {
|
||||
if (!roles.includes(userRoles.role.name)) {
|
||||
roles.push(userRoles.role.name);
|
||||
}
|
||||
userRoles.role.permissions.forEach((permission) => {
|
||||
if (!names.includes(permission.permission.name)) {
|
||||
names.push(permission.permission.name);
|
||||
}
|
||||
});
|
||||
});
|
||||
// console.log({
|
||||
// userId,
|
||||
// tenantId,
|
||||
// roles,
|
||||
// permissions: names,
|
||||
// });
|
||||
return names;
|
||||
}
|
||||
|
||||
export async function userHasPermission(userId: string, tenantId: string | null, permissionName: string): Promise<boolean> {
|
||||
const permissions = await getPermissionsByUser(userId, tenantId);
|
||||
return permissions.includes(permissionName);
|
||||
}
|
||||
|
||||
export async function findPermissionByUser(persmissionName: string, userId: string, tenantId?: string | null): Promise<string | null> {
|
||||
const userRoles = await db.userRole.findMany({
|
||||
where: { userId, tenantId, role: { permissions: { some: { permission: { name: persmissionName } } } } },
|
||||
include: { role: { include: { permissions: { include: { permission: { select: { name: true } } } } } } },
|
||||
});
|
||||
const roles: string[] = [];
|
||||
const names: string[] = [];
|
||||
userRoles.forEach((userRoles) => {
|
||||
if (!roles.includes(userRoles.role.name)) {
|
||||
roles.push(userRoles.role.name);
|
||||
}
|
||||
userRoles.role.permissions.forEach((permission) => {
|
||||
if (!names.includes(permission.permission.name)) {
|
||||
names.push(permission.permission.name);
|
||||
}
|
||||
});
|
||||
});
|
||||
// console.log({
|
||||
// userId,
|
||||
// tenantId,
|
||||
// roles,
|
||||
// permissions: names,
|
||||
// });
|
||||
return names.length > 0 ? names[0] : null;
|
||||
}
|
||||
|
||||
export async function countUserPermission(userId: string, tenantId: string | null, permissionName: string): Promise<number> {
|
||||
const normal = await db.permission.count({
|
||||
where: {
|
||||
name: permissionName,
|
||||
inRoles: { some: { role: { users: { some: { userId, tenantId } } } } },
|
||||
},
|
||||
});
|
||||
if (normal > 0) {
|
||||
return normal;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
export async function findUserRolesByIds(userId: string, tenantId: string | null, roleIds: string[]): Promise<UserRole[]> {
|
||||
return await db.userRole.findMany({
|
||||
where: {
|
||||
userId,
|
||||
tenantId,
|
||||
roleId: {
|
||||
in: roleIds,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getUsersRolesInTenant(tenantId: string) {
|
||||
return await db.userRole.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
},
|
||||
include: {
|
||||
role: true,
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function ensureTenantUserAppRoles({
|
||||
userId,
|
||||
tenantId,
|
||||
tenantUserType,
|
||||
}: {
|
||||
userId: string;
|
||||
tenantId: string;
|
||||
tenantUserType: number;
|
||||
}): Promise<{ created: number; roleCount: number }> {
|
||||
const existingRoleCount = await db.userRole.count({
|
||||
where: {
|
||||
userId,
|
||||
tenantId,
|
||||
role: {
|
||||
type: "app",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (existingRoleCount > 0) {
|
||||
return { created: 0, roleCount: existingRoleCount };
|
||||
}
|
||||
|
||||
const shouldGrantAllAppRoles = tenantUserType === TenantUserType.OWNER || tenantUserType === TenantUserType.ADMIN;
|
||||
const roles = await db.role.findMany({
|
||||
where: {
|
||||
type: "app",
|
||||
OR: [{ tenantId: null }, { tenantId }],
|
||||
...(shouldGrantAllAppRoles ? {} : { assignToNewUsers: true }),
|
||||
},
|
||||
orderBy: {
|
||||
order: "asc",
|
||||
},
|
||||
});
|
||||
|
||||
const existingRoles = await findUserRolesByIds(
|
||||
userId,
|
||||
tenantId,
|
||||
roles.map((role) => role.id)
|
||||
);
|
||||
const existingRoleIds = new Set(existingRoles.map((role) => role.roleId));
|
||||
const missingRoles = roles.filter((role) => !existingRoleIds.has(role.id));
|
||||
if (missingRoles.length > 0) {
|
||||
await createUserRoles(
|
||||
userId,
|
||||
missingRoles.map((role) => ({ id: role.id, tenantId }))
|
||||
);
|
||||
} else {
|
||||
clearCacheKey(`userRoles:${userId}:${tenantId}`);
|
||||
}
|
||||
|
||||
return { created: missingRoles.length, roleCount: roles.length };
|
||||
}
|
||||
|
||||
export async function createUserRole(userId: string, roleId: string, tenantId: string | null = null) {
|
||||
const existing = await getUserRole(userId, roleId, tenantId);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
try {
|
||||
const item = await db.userRole.create({
|
||||
data: {
|
||||
userId,
|
||||
roleId,
|
||||
tenantId,
|
||||
},
|
||||
});
|
||||
clearCacheKey(`userRoles:${userId}:${tenantId}`);
|
||||
return item;
|
||||
} catch (error) {
|
||||
if (!isUniqueConstraintError(error)) {
|
||||
throw error;
|
||||
}
|
||||
const createdByConcurrentRequest = await getUserRole(userId, roleId, tenantId);
|
||||
if (!createdByConcurrentRequest) {
|
||||
throw error;
|
||||
}
|
||||
return createdByConcurrentRequest;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Grants an admin-scoped RBAC role (e.g. "SuperAdmin") to a user by role name,
|
||||
* idempotently. Used by the Admin-SSO callback to wire the JIT-provisioned
|
||||
* `super_admin` identity to its concrete permission set. `createUserRole`
|
||||
* invalidates the `userRoles:<userId>:null` cache, so the granted permissions
|
||||
* are visible on the very next request — independent of the cache TTL.
|
||||
*/
|
||||
export async function ensureAdminUserRoleByName(userId: string, roleName: string): Promise<void> {
|
||||
const role = await db.role.findFirst({
|
||||
where: { name: roleName, type: "admin" },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!role) {
|
||||
return;
|
||||
}
|
||||
await createUserRole(userId, role.id, null);
|
||||
}
|
||||
|
||||
export async function createUserRoles(userId: string, roles: { id: string; tenantId: string | null }[]) {
|
||||
return await createUserRoleAssignments(roles.map((role) => ({ userId, roleId: role.id, tenantId: role.tenantId })));
|
||||
}
|
||||
|
||||
export async function createUserRoleAssignments(assignments: UserRoleAssignment[]) {
|
||||
const uniqueAssignments = [...new Map(assignments.map((assignment) => [getUserRoleAssignmentKey(assignment), assignment])).values()].map((assignment) => ({
|
||||
userId: assignment.userId,
|
||||
roleId: assignment.roleId,
|
||||
tenantId: normalizeTenantId(assignment.tenantId),
|
||||
}));
|
||||
const cacheScopes = [...new Map(uniqueAssignments.map((assignment) => [`${assignment.userId}:${assignment.tenantId}`, assignment])).values()];
|
||||
|
||||
if (uniqueAssignments.length === 0) {
|
||||
return { count: 0 };
|
||||
}
|
||||
|
||||
const userIds = [...new Set(uniqueAssignments.map((assignment) => assignment.userId))];
|
||||
const roleIds = [...new Set(uniqueAssignments.map((assignment) => assignment.roleId))];
|
||||
const tenantIds = [...new Set(uniqueAssignments.map((assignment) => assignment.tenantId))];
|
||||
const nonNullTenantIds = tenantIds.filter((tenantId): tenantId is string => tenantId !== null);
|
||||
const tenantWhere =
|
||||
tenantIds.includes(null) && nonNullTenantIds.length > 0
|
||||
? { OR: [{ tenantId: null }, { tenantId: { in: nonNullTenantIds } }] }
|
||||
: tenantIds.includes(null)
|
||||
? { tenantId: null }
|
||||
: { tenantId: { in: nonNullTenantIds } };
|
||||
|
||||
const existingAssignments = await db.userRole.findMany({
|
||||
where: {
|
||||
userId: { in: userIds },
|
||||
roleId: { in: roleIds },
|
||||
...tenantWhere,
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
roleId: true,
|
||||
tenantId: true,
|
||||
},
|
||||
});
|
||||
const existingAssignmentKeys = new Set(existingAssignments.map((assignment) => getUserRoleAssignmentKey(assignment)));
|
||||
const missingAssignments = uniqueAssignments.filter((assignment) => !existingAssignmentKeys.has(getUserRoleAssignmentKey(assignment)));
|
||||
|
||||
const result =
|
||||
missingAssignments.length > 0
|
||||
? await db.userRole.createMany({
|
||||
data: missingAssignments,
|
||||
skipDuplicates: true,
|
||||
})
|
||||
: { count: 0 };
|
||||
|
||||
cacheScopes.forEach((scope) => {
|
||||
clearUserRoleCache(scope.userId, scope.tenantId);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function deleteUserRole(userId: string, roleId: string, tenantId: string | null = null) {
|
||||
return await db.userRole
|
||||
.deleteMany({
|
||||
where: {
|
||||
userId,
|
||||
roleId,
|
||||
tenantId,
|
||||
},
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`userRoles:${userId}:${tenantId}`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteAllUserRoles(userId: string, type: string) {
|
||||
return await db.userRole.deleteMany({
|
||||
where: {
|
||||
userId,
|
||||
role: {
|
||||
type,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../db.server", () => ({
|
||||
db: {
|
||||
registration: {
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { db } from "../db.server";
|
||||
import { createRegistration, getRegistrationByEmail, getRegistrationByToken, updateRegistration } from "./registration.db.server";
|
||||
|
||||
const registrationMock = vi.mocked(db.registration, true);
|
||||
|
||||
describe("registration db helpers", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("looks up pending registrations by email and token", async () => {
|
||||
registrationMock.findFirst.mockResolvedValueOnce({ id: "registration_1" } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
|
||||
registrationMock.findUnique.mockResolvedValueOnce({ id: "registration_2" } as Awaited<ReturnType<typeof getRegistrationByToken>>);
|
||||
|
||||
await expect(getRegistrationByEmail("ada@example.test")).resolves.toMatchObject({ id: "registration_1" });
|
||||
await expect(getRegistrationByToken("token_1")).resolves.toMatchObject({ id: "registration_2" });
|
||||
|
||||
expect(registrationMock.findFirst).toHaveBeenCalledWith({ where: { email: "ada@example.test" } });
|
||||
expect(registrationMock.findUnique).toHaveBeenCalledWith({ where: { token: "token_1" } });
|
||||
});
|
||||
|
||||
it("persists lead conversion context on new registrations", async () => {
|
||||
registrationMock.create.mockResolvedValueOnce({ id: "registration_1" } as Awaited<ReturnType<typeof createRegistration>>);
|
||||
|
||||
await createRegistration({
|
||||
email: "ada@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
token: "registration-token",
|
||||
company: "Analytical Engines",
|
||||
selectedSubscriptionPriceId: "price_1",
|
||||
leadConversionLeadId: "lead_1",
|
||||
leadConversionToken: "signed-lead-token",
|
||||
leadConversionPlanId: "plan_pro",
|
||||
ipAddress: "127.0.0.1",
|
||||
slug: "ada",
|
||||
});
|
||||
|
||||
expect(registrationMock.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
email: "ada@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
token: "registration-token",
|
||||
company: "Analytical Engines",
|
||||
selectedSubscriptionPriceId: "price_1",
|
||||
leadConversionLeadId: "lead_1",
|
||||
leadConversionToken: "signed-lead-token",
|
||||
leadConversionPlanId: "plan_pro",
|
||||
ipAddress: "127.0.0.1",
|
||||
slug: "ada",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("clears missing lead conversion fields to null when creating registrations", async () => {
|
||||
registrationMock.create.mockResolvedValueOnce({ id: "registration_1" } as Awaited<ReturnType<typeof createRegistration>>);
|
||||
|
||||
await createRegistration({
|
||||
email: "ada@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
token: "registration-token",
|
||||
company: null,
|
||||
selectedSubscriptionPriceId: null,
|
||||
ipAddress: null,
|
||||
slug: null,
|
||||
});
|
||||
|
||||
expect(registrationMock.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
leadConversionLeadId: null,
|
||||
leadConversionToken: null,
|
||||
leadConversionPlanId: null,
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("updates lead conversion context and created tenant id together", async () => {
|
||||
registrationMock.update.mockResolvedValueOnce({ id: "registration_1" } as Awaited<ReturnType<typeof updateRegistration>>);
|
||||
|
||||
await updateRegistration("registration_1", {
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
company: "Analytical Engines",
|
||||
createdTenantId: "tenant_1",
|
||||
token: "new-token",
|
||||
leadConversionLeadId: "lead_1",
|
||||
leadConversionToken: "signed-lead-token",
|
||||
leadConversionPlanId: "plan_pro",
|
||||
});
|
||||
|
||||
expect(registrationMock.update).toHaveBeenCalledWith({
|
||||
where: { id: "registration_1" },
|
||||
data: {
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
company: "Analytical Engines",
|
||||
createdTenantId: "tenant_1",
|
||||
token: "new-token",
|
||||
leadConversionLeadId: "lead_1",
|
||||
leadConversionToken: "signed-lead-token",
|
||||
leadConversionPlanId: "plan_pro",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
import { db } from "../db.server";
|
||||
|
||||
export async function getRegistrationByEmail(email: string) {
|
||||
return await db.registration.findFirst({
|
||||
where: {
|
||||
email,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRegistrationByToken(token: string) {
|
||||
return await db.registration.findUnique({
|
||||
where: {
|
||||
token,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createRegistration(data: {
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
token: string;
|
||||
company: string | null;
|
||||
selectedSubscriptionPriceId: string | null;
|
||||
leadConversionLeadId?: string | null;
|
||||
leadConversionToken?: string | null;
|
||||
leadConversionPlanId?: string | null;
|
||||
ipAddress: string | null;
|
||||
slug: string | null;
|
||||
}) {
|
||||
return await db.registration.create({
|
||||
data: {
|
||||
email: data.email,
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
token: data.token,
|
||||
company: data.company,
|
||||
selectedSubscriptionPriceId: data.selectedSubscriptionPriceId,
|
||||
leadConversionLeadId: data.leadConversionLeadId ?? null,
|
||||
leadConversionToken: data.leadConversionToken ?? null,
|
||||
leadConversionPlanId: data.leadConversionPlanId ?? null,
|
||||
ipAddress: data.ipAddress,
|
||||
slug: data.slug,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateRegistration(
|
||||
id: string,
|
||||
data: {
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
company?: string | null;
|
||||
createdTenantId?: string | null;
|
||||
token?: string;
|
||||
leadConversionLeadId?: string | null;
|
||||
leadConversionToken?: string | null;
|
||||
leadConversionPlanId?: string | null;
|
||||
}
|
||||
) {
|
||||
return await db.registration.update({
|
||||
where: { id },
|
||||
data: {
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
company: data.company,
|
||||
createdTenantId: data.createdTenantId,
|
||||
token: data.token,
|
||||
leadConversionLeadId: data.leadConversionLeadId,
|
||||
leadConversionToken: data.leadConversionToken,
|
||||
leadConversionPlanId: data.leadConversionPlanId,
|
||||
},
|
||||
});
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
/**
|
||||
* PII / secret regression test for SeedService.
|
||||
*
|
||||
* SeedService creates the bootstrap admin user with a hard-coded
|
||||
* default password. The legacy console.log statements printed raw
|
||||
* email addresses; the bigger risk is the password constant leaking
|
||||
* by accident if a future change passes `password` into a logger arg.
|
||||
*
|
||||
* Policy:
|
||||
* - never log raw `email` — always emailFingerprint(email)
|
||||
* - never log `password`, `passwordHash`, `adminPassword`, or
|
||||
* anything looking like a credential
|
||||
* - no live console.* calls remain
|
||||
*/
|
||||
describe("SeedService PII discipline", () => {
|
||||
const SOURCE = readFileSync(resolve(__dirname, "SeedService.ts"), "utf8");
|
||||
|
||||
it("contains no live console.* call sites", () => {
|
||||
const live = SOURCE.split("\n").filter((line, idx, all) => {
|
||||
if (!/console\.(log|error|warn|info|debug)\s*\(/.test(line)) return false;
|
||||
const trimmed = line.trimStart();
|
||||
if (trimmed.startsWith("//") || trimmed.startsWith("*")) return false;
|
||||
const prev = idx > 0 ? all[idx - 1].trim() : "";
|
||||
if (/eslint-disable-next-line[^\n]*no-console/.test(prev)) return false;
|
||||
return true;
|
||||
});
|
||||
expect(live).toEqual([]);
|
||||
});
|
||||
|
||||
it("never passes raw email / password fields as own seedLogger arg keys", () => {
|
||||
const pattern = /seedLogger\.(info|warn|error|debug)\s*\(\s*\{([\s\S]*?)\}/g;
|
||||
const forbiddenKeys = [
|
||||
"email",
|
||||
"password",
|
||||
"passwordHash",
|
||||
"adminEmail",
|
||||
"adminPassword",
|
||||
"rawPassword",
|
||||
"plainPassword",
|
||||
"secret",
|
||||
"token",
|
||||
];
|
||||
const offenders: string[] = [];
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = pattern.exec(SOURCE)) !== null) {
|
||||
const objContent = match[2];
|
||||
for (const key of forbiddenKeys) {
|
||||
const keyRe = new RegExp(`(^|[\\s,{])${key}\\s*:`, "m");
|
||||
if (keyRe.test(objContent)) offenders.push(`key "${key}" in ${match[0].slice(0, 100)}...`);
|
||||
}
|
||||
}
|
||||
expect(offenders, `seedLogger must not log PII/secret fields: ${offenders.join("; ")}`).toEqual([]);
|
||||
});
|
||||
|
||||
it("defines and uses emailFingerprint() for any email-related diagnostics", () => {
|
||||
expect(SOURCE).toMatch(/function emailFingerprint\(/);
|
||||
expect(SOURCE).toMatch(/createHash\(["']sha256["']\)/);
|
||||
// Anywhere we mention "email" inside a seedLogger call must be via emailFingerprint(...)
|
||||
// (Aliased as emailFingerprint key — never raw email value)
|
||||
expect(SOURCE).toMatch(/emailFingerprint\(email\)/);
|
||||
});
|
||||
|
||||
it("uses createScopedLogger('seed')", () => {
|
||||
expect(SOURCE).toMatch(/createScopedLogger\(\s*["']seed["']\s*\)/);
|
||||
});
|
||||
|
||||
it("does not interpolate DEFAULT_ADMIN_PASSWORD into any log message", () => {
|
||||
// Hard-coded admin password constant exists in source; ensure it never
|
||||
// ends up in a logger arg object or template string.
|
||||
const lines = SOURCE.split("\n");
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
if (/seedLogger\.|`/.test(line) && /DEFAULT_ADMIN_PASSWORD/.test(line)) {
|
||||
// Only legal use of the constant: assignment line like `password: DEFAULT_ADMIN_PASSWORD` in the seed-user record.
|
||||
// It must NOT appear inside a logger arg or template literal.
|
||||
if (/seedLogger\./.test(line)) {
|
||||
throw new Error(`SeedService PII leak: DEFAULT_ADMIN_PASSWORD used in seedLogger call at line ${i + 1}: ${line.trim()}`);
|
||||
}
|
||||
if (/`[^`]*\$\{[^}]*DEFAULT_ADMIN_PASSWORD/.test(line)) {
|
||||
throw new Error(`SeedService PII leak: DEFAULT_ADMIN_PASSWORD interpolated in template at line ${i + 1}: ${line.trim()}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
+451
@@ -0,0 +1,451 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
type SeedService = typeof import("./SeedService").default;
|
||||
|
||||
const dbMock = {
|
||||
user: {
|
||||
findUnique: vi.fn(async ({ where }: { where: { email: string } }) => ({ id: `user-${where.email}` })),
|
||||
create: vi.fn(),
|
||||
},
|
||||
adminUser: {
|
||||
findUnique: vi.fn(async () => ({ userId: "admin-id" })),
|
||||
create: vi.fn(),
|
||||
},
|
||||
tenant: {
|
||||
findUnique: vi.fn(async ({ where, include }: { where: { slug: string }; include?: unknown }) => ({
|
||||
id: `tenant-${where.slug}`,
|
||||
slug: where.slug,
|
||||
name: where.slug,
|
||||
...(include ? { subscription: { id: `subscription-${where.slug}`, products: [] } } : {}),
|
||||
})),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
tenantInboundAddress: {
|
||||
findFirst: vi.fn(),
|
||||
create: vi.fn(),
|
||||
},
|
||||
tenantSubscription: {
|
||||
findUnique: vi.fn(async ({ where }: { where: { tenantId: string } }) => ({ id: `subscription-${where.tenantId}` })),
|
||||
create: vi.fn(),
|
||||
},
|
||||
tenantUser: {
|
||||
findFirst: vi.fn(),
|
||||
create: vi.fn(),
|
||||
},
|
||||
subscriptionProduct: {
|
||||
findFirst: vi.fn(async ({ where }: { where: { stripeId: string } }) => ({ id: `product-${where.stripeId}` })),
|
||||
},
|
||||
tenantSubscriptionProduct: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
tenantProductConfiguration: {
|
||||
upsert: vi.fn(),
|
||||
},
|
||||
tenantFeatureOverride: {
|
||||
upsert: vi.fn(),
|
||||
},
|
||||
entity: {
|
||||
aggregate: vi.fn(async () => ({ _max: { order: 0 } })),
|
||||
findMany: vi.fn(async () => []),
|
||||
create: vi.fn(async ({ data }: { data: { name: string } }) => ({ id: `entity-${data.name}`, ...data })),
|
||||
updateMany: vi.fn(),
|
||||
},
|
||||
entityWebhook: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
property: {
|
||||
create: vi.fn(async ({ data }: { data: { name: string } }) => ({ id: `property-${data.name}`, ...data })),
|
||||
},
|
||||
propertyOption: {
|
||||
deleteMany: vi.fn(),
|
||||
create: vi.fn(),
|
||||
},
|
||||
propertyAttribute: {
|
||||
deleteMany: vi.fn(),
|
||||
create: vi.fn(),
|
||||
},
|
||||
permission: {
|
||||
findMany: vi.fn(async ({ where }: { where: { name: { in: string[] } } }) => where.name.in.map((name) => ({ id: `permission-${name}`, name }))),
|
||||
},
|
||||
role: {
|
||||
findFirst: vi.fn(),
|
||||
create: vi.fn(async ({ data }: { data: { name: string } }) => ({ id: `role-${data.name}` })),
|
||||
},
|
||||
rolePermission: {
|
||||
findFirst: vi.fn(),
|
||||
create: vi.fn(),
|
||||
},
|
||||
userRole: {
|
||||
findFirst: vi.fn(),
|
||||
create: vi.fn(),
|
||||
},
|
||||
knowledgeBase: {
|
||||
upsert: vi.fn(async ({ create }: { create: { slug: string } }) => ({ id: `kb-${create.slug}` })),
|
||||
},
|
||||
knowledgeBaseCategory: {
|
||||
upsert: vi.fn(async ({ create }: { create: { slug: string } }) => ({ id: `category-${create.slug}` })),
|
||||
},
|
||||
knowledgeBaseArticle: {
|
||||
upsert: vi.fn(),
|
||||
},
|
||||
supportTicket: {
|
||||
upsert: vi.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
const hashMock = vi.fn(async () => "hashed-password");
|
||||
const genSaltMock = vi.fn(async () => "generated-salt");
|
||||
const seedRolesAndPermissionsMock = vi.fn();
|
||||
const seedStandardEntitlementsMock = vi.fn();
|
||||
const originalEnv = { ...process.env };
|
||||
|
||||
const loggerInfo = vi.fn();
|
||||
const loggerWarn = vi.fn();
|
||||
const loggerError = vi.fn();
|
||||
const loggerDebug = vi.fn();
|
||||
vi.mock("~/utils/logger.server", () => ({
|
||||
createScopedLogger: () => ({ info: loggerInfo, warn: loggerWarn, error: loggerError, debug: loggerDebug }),
|
||||
}));
|
||||
|
||||
vi.mock("bcryptjs", () => ({ default: { genSalt: genSaltMock, hash: hashMock } }));
|
||||
vi.mock("@toolctrl/db/entitlements-seed.server", () => ({
|
||||
getEntitlementPlanStripeId: ({ id }: { id: string }) => `toolctrl_entitlement_plan_${id}`,
|
||||
seedStandardEntitlements: seedStandardEntitlementsMock,
|
||||
}));
|
||||
vi.mock("@toolctrl/db/seed.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("@toolctrl/db/seed.server")>("@toolctrl/db/seed.server");
|
||||
return actual;
|
||||
});
|
||||
vi.mock("~/utils/services/emailService", () => ({ getAvailableTenantInboundAddress: vi.fn(async () => "seed@example.test") }));
|
||||
vi.mock("~/utils/services/rolesAndPermissionsService", () => ({ seedRolesAndPermissions: seedRolesAndPermissionsMock }));
|
||||
vi.mock("~/utils/db.server", () => ({ db: dbMock }));
|
||||
|
||||
async function loadSeedService(): Promise<SeedService> {
|
||||
vi.resetModules();
|
||||
const module = await import("./SeedService");
|
||||
return module.default;
|
||||
}
|
||||
|
||||
describe("SeedService", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env = { ...originalEnv };
|
||||
delete process.env.SEED_ADMIN_EMAIL;
|
||||
delete process.env.SEED_ADMIN_PASSWORD;
|
||||
delete process.env.SEED_DEMO_DATA;
|
||||
delete process.env.ALLOW_STAGING_DEMO_SEED;
|
||||
process.env.NODE_ENV = "test";
|
||||
});
|
||||
|
||||
it("rejects default admin credentials in production before DB writes", async () => {
|
||||
process.env.NODE_ENV = "production";
|
||||
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
const SeedService = await loadSeedService();
|
||||
|
||||
await expect(SeedService.seed()).rejects.toThrow("default seed credentials");
|
||||
|
||||
expect(dbMock.user.findUnique).not.toHaveBeenCalled();
|
||||
expect(dbMock.user.create).not.toHaveBeenCalled();
|
||||
expect(seedRolesAndPermissionsMock).not.toHaveBeenCalled();
|
||||
expect(seedStandardEntitlementsMock).not.toHaveBeenCalled();
|
||||
expect(JSON.stringify(consoleLog.mock.calls)).not.toContain("password");
|
||||
});
|
||||
|
||||
it("uses safe admin credential overrides in production", async () => {
|
||||
process.env.NODE_ENV = "production";
|
||||
process.env.SEED_ADMIN_EMAIL = "owner@example.com";
|
||||
process.env.SEED_ADMIN_PASSWORD = "safe-production-password";
|
||||
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
const SeedService = await loadSeedService();
|
||||
|
||||
await SeedService.seed();
|
||||
|
||||
expect(dbMock.user.findUnique).toHaveBeenCalledWith({ where: { email: "owner@example.com" } });
|
||||
expect(dbMock.user.findUnique).not.toHaveBeenCalledWith({ where: { email: "john.doe@company.com" } });
|
||||
expect(dbMock.user.findUnique).not.toHaveBeenCalledWith({ where: { email: "luna.davis@company.com" } });
|
||||
expect(dbMock.tenant.findUnique).not.toHaveBeenCalled();
|
||||
expect(genSaltMock).toHaveBeenCalledWith(10);
|
||||
expect(hashMock).toHaveBeenCalledWith("safe-production-password", "generated-salt");
|
||||
expect(seedRolesAndPermissionsMock).toHaveBeenCalledWith({
|
||||
adminEmail: "owner@example.com",
|
||||
diagnostics: expect.any(Function),
|
||||
});
|
||||
expect(loggerInfo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ op: "db-seed", phase: "start", nodeEnv: "production" }),
|
||||
"DB seed event",
|
||||
);
|
||||
expect(loggerInfo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ op: "db-seed", phase: "success", nodeEnv: "production" }),
|
||||
"DB seed event",
|
||||
);
|
||||
// The new logger redacts admin email behind a SHA-256 fingerprint. The
|
||||
// raw email must never appear in any logger arg.
|
||||
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("owner@example.com");
|
||||
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("safe-production-password");
|
||||
expect(JSON.stringify(consoleLog.mock.calls)).not.toContain("safe-production-password");
|
||||
});
|
||||
|
||||
it("rejects blank admin credential overrides in production before DB writes", async () => {
|
||||
process.env.NODE_ENV = "production";
|
||||
process.env.SEED_ADMIN_EMAIL = "";
|
||||
process.env.SEED_ADMIN_PASSWORD = "safe-production-password";
|
||||
const SeedService = await loadSeedService();
|
||||
|
||||
await expect(SeedService.seed()).rejects.toThrow("missing seed credentials");
|
||||
|
||||
expect(dbMock.user.findUnique).not.toHaveBeenCalled();
|
||||
expect(dbMock.user.create).not.toHaveBeenCalled();
|
||||
expect(seedRolesAndPermissionsMock).not.toHaveBeenCalled();
|
||||
expect(seedStandardEntitlementsMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses to promote an existing non-admin user during production seed", async () => {
|
||||
process.env.NODE_ENV = "production";
|
||||
process.env.SEED_ADMIN_EMAIL = "owner@example.com";
|
||||
process.env.SEED_ADMIN_PASSWORD = "safe-production-password";
|
||||
dbMock.user.findUnique.mockResolvedValueOnce({ id: "existing-user", email: "owner@example.com" } as never);
|
||||
dbMock.adminUser.findUnique.mockResolvedValueOnce(null as never);
|
||||
const SeedService = await loadSeedService();
|
||||
|
||||
await expect(SeedService.seed()).rejects.toThrow("Production seed refused to promote an existing non-admin user");
|
||||
|
||||
expect(dbMock.adminUser.create).not.toHaveBeenCalled();
|
||||
expect(seedRolesAndPermissionsMock).not.toHaveBeenCalled();
|
||||
expect(seedStandardEntitlementsMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("skips local demo users and tenants unless explicitly enabled", async () => {
|
||||
const SeedService = await loadSeedService();
|
||||
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
|
||||
await SeedService.seed();
|
||||
|
||||
expect(dbMock.user.findUnique).toHaveBeenCalledWith({ where: { email: "admin@email.com" } });
|
||||
expect(dbMock.user.findUnique).not.toHaveBeenCalledWith({ where: { email: "john.doe@company.com" } });
|
||||
expect(dbMock.user.findUnique).not.toHaveBeenCalledWith({ where: { email: "luna.davis@company.com" } });
|
||||
expect(dbMock.tenant.findUnique).not.toHaveBeenCalled();
|
||||
expect(loggerInfo).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ op: "seed.createDemoUsers" }),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it("seeds local demo users and tenants only when explicitly enabled outside production", async () => {
|
||||
process.env.SEED_DEMO_DATA = "true";
|
||||
const SeedService = await loadSeedService();
|
||||
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
|
||||
await SeedService.seed();
|
||||
|
||||
expect(dbMock.user.findUnique).toHaveBeenCalledWith({ where: { email: "admin@email.com" } });
|
||||
expect(dbMock.user.findUnique).toHaveBeenCalledWith({ where: { email: "john.doe@company.com" } });
|
||||
expect(dbMock.user.findUnique).toHaveBeenCalledWith({ where: { email: "luna.davis@company.com" } });
|
||||
expect(dbMock.tenant.findUnique).toHaveBeenCalledWith({ where: { slug: "demo-starter-crm" } });
|
||||
expect(dbMock.tenant.findUnique).toHaveBeenCalledWith({ where: { slug: "demo-pro-crm" } });
|
||||
expect(dbMock.tenant.findUnique).toHaveBeenCalledWith({ where: { slug: "demo-business-crm" } });
|
||||
expect(dbMock.subscriptionProduct.findFirst).toHaveBeenCalledWith({
|
||||
where: { stripeId: "toolctrl_entitlement_plan_starter" },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(dbMock.subscriptionProduct.findFirst).toHaveBeenCalledWith({
|
||||
where: { stripeId: "toolctrl_entitlement_plan_pro" },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(dbMock.subscriptionProduct.findFirst).toHaveBeenCalledWith({
|
||||
where: { stripeId: "toolctrl_entitlement_plan_business" },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(dbMock.tenantSubscriptionProduct.create).toHaveBeenCalledTimes(3);
|
||||
expect(dbMock.entity.findMany).toHaveBeenCalledWith({
|
||||
where: { name: { in: ["company", "contact", "opportunity"] } },
|
||||
select: { id: true, name: true, type: true },
|
||||
});
|
||||
expect(dbMock.entity.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ name: "company", type: "all" }) }));
|
||||
expect(dbMock.entity.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ name: "contact", type: "all" }) }));
|
||||
expect(dbMock.entity.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ name: "opportunity", type: "all" }) }));
|
||||
expect(dbMock.entity.create).not.toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ name: "submission" }) }));
|
||||
expect(dbMock.tenantProductConfiguration.upsert).toHaveBeenCalledTimes(3);
|
||||
expect(dbMock.knowledgeBase.upsert).toHaveBeenCalledTimes(3);
|
||||
expect(dbMock.supportTicket.upsert).toHaveBeenCalledTimes(6);
|
||||
expect(loggerInfo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ op: "seed.createDemoUsers", count: 2 }),
|
||||
"Creating CRM SaaS demo users with tenants",
|
||||
);
|
||||
});
|
||||
|
||||
it("refuses demo data in production without the explicit staging override", async () => {
|
||||
process.env.NODE_ENV = "production";
|
||||
process.env.SEED_DEMO_DATA = "true";
|
||||
process.env.SEED_ADMIN_EMAIL = "owner@example.com";
|
||||
process.env.SEED_ADMIN_PASSWORD = "safe-production-password";
|
||||
const SeedService = await loadSeedService();
|
||||
|
||||
await expect(SeedService.seed()).rejects.toThrow("ALLOW_STAGING_DEMO_SEED=true");
|
||||
|
||||
expect(dbMock.user.findUnique).not.toHaveBeenCalled();
|
||||
expect(seedRolesAndPermissionsMock).not.toHaveBeenCalled();
|
||||
expect(seedStandardEntitlementsMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("allows explicit staging demo data while production runtime safety stays opt-in", async () => {
|
||||
process.env.NODE_ENV = "production";
|
||||
process.env.SEED_DEMO_DATA = "true";
|
||||
process.env.ALLOW_STAGING_DEMO_SEED = "true";
|
||||
process.env.SEED_ADMIN_EMAIL = "owner@example.com";
|
||||
process.env.SEED_ADMIN_PASSWORD = "safe-production-password";
|
||||
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
const SeedService = await loadSeedService();
|
||||
|
||||
await SeedService.seed();
|
||||
|
||||
expect(dbMock.user.findUnique).toHaveBeenCalledWith({ where: { email: "john.doe@company.com" } });
|
||||
expect(dbMock.tenant.findUnique).toHaveBeenCalledWith({ where: { slug: "demo-starter-crm" } });
|
||||
expect(dbMock.tenantProductConfiguration.upsert).toHaveBeenCalled();
|
||||
expect(loggerInfo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ op: "db-seed", phase: "start", nodeEnv: "staging-demo" }),
|
||||
"DB seed event",
|
||||
);
|
||||
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("owner@example.com");
|
||||
});
|
||||
|
||||
it("seeds standard entitlements once after roles and permissions", async () => {
|
||||
const SeedService = await loadSeedService();
|
||||
const calls: string[] = [];
|
||||
seedRolesAndPermissionsMock.mockImplementation(async () => {
|
||||
calls.push("roles");
|
||||
});
|
||||
seedStandardEntitlementsMock.mockImplementation(async () => {
|
||||
calls.push("entitlements");
|
||||
return {
|
||||
planCount: 3,
|
||||
featureCount: 9,
|
||||
createdProducts: 3,
|
||||
updatedProducts: 0,
|
||||
deletedFeatures: 0,
|
||||
createdFeatures: 9,
|
||||
};
|
||||
});
|
||||
|
||||
await SeedService.seed();
|
||||
|
||||
expect(seedRolesAndPermissionsMock).toHaveBeenCalledWith({
|
||||
adminEmail: "admin@email.com",
|
||||
diagnostics: expect.any(Function),
|
||||
});
|
||||
expect(seedStandardEntitlementsMock).toHaveBeenCalledOnce();
|
||||
expect(seedStandardEntitlementsMock).toHaveBeenCalledWith({
|
||||
client: dbMock,
|
||||
diagnostics: expect.any(Function),
|
||||
});
|
||||
expect(calls).toEqual(["roles", "entitlements"]);
|
||||
});
|
||||
|
||||
it("logs redacted DB seed failure diagnostics without raw secret errors", async () => {
|
||||
process.env.SEED_ADMIN_EMAIL = "owner@example.com";
|
||||
process.env.SEED_ADMIN_PASSWORD = "safe-secret-password";
|
||||
const SeedService = await loadSeedService();
|
||||
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
const originalError = new Error("failed with safe-secret-password token sk_live_secret");
|
||||
seedRolesAndPermissionsMock.mockRejectedValueOnce(originalError);
|
||||
|
||||
await expect(SeedService.seed()).rejects.toBe(originalError);
|
||||
|
||||
expect(loggerInfo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ op: "db-seed", phase: "failure", nodeEnv: "test" }),
|
||||
"DB seed event",
|
||||
);
|
||||
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("owner@example.com");
|
||||
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("safe-secret-password");
|
||||
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("sk_live_secret");
|
||||
expect(JSON.stringify(consoleLog.mock.calls)).not.toContain("safe-secret-password");
|
||||
expect(JSON.stringify(consoleLog.mock.calls)).not.toContain("sk_live_secret");
|
||||
});
|
||||
|
||||
it("logs redacted roles and permissions seed diagnostics from the helper", async () => {
|
||||
const SeedService = await loadSeedService();
|
||||
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
seedRolesAndPermissionsMock.mockImplementation(async ({ diagnostics }) => {
|
||||
await diagnostics?.({
|
||||
phase: "success",
|
||||
adminRoleCount: 1,
|
||||
appRoleCount: 4,
|
||||
defaultPermissionCount: 120,
|
||||
dynamicEntityPermissionCount: 3,
|
||||
adminUserAssignmentCount: 1,
|
||||
tenantUserAssignmentCount: 8,
|
||||
password: "password",
|
||||
token: "sk_live_secret",
|
||||
});
|
||||
});
|
||||
|
||||
await SeedService.seed();
|
||||
|
||||
expect(loggerInfo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
op: "seed.rolesAndPermissions",
|
||||
phase: "success",
|
||||
adminRoleCount: 1,
|
||||
appRoleCount: 4,
|
||||
defaultPermissionCount: 120,
|
||||
dynamicEntityPermissionCount: 3,
|
||||
adminUserAssignmentCount: 1,
|
||||
tenantUserAssignmentCount: 8,
|
||||
}),
|
||||
"Roles and permissions seed event",
|
||||
);
|
||||
// The helper-supplied `password` and `token` fields must be dropped
|
||||
// before they hit the logger.
|
||||
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("password");
|
||||
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("sk_live_secret");
|
||||
});
|
||||
|
||||
it("logs redacted entitlements seed diagnostics from the helper", async () => {
|
||||
const SeedService = await loadSeedService();
|
||||
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
seedStandardEntitlementsMock.mockImplementation(async ({ diagnostics }) => {
|
||||
await diagnostics?.({
|
||||
phase: "failure",
|
||||
planCount: 3,
|
||||
featureCount: 9,
|
||||
createdProducts: 1,
|
||||
updatedProducts: 2,
|
||||
deletedFeatures: 4,
|
||||
createdFeatures: 5,
|
||||
planId: "team",
|
||||
error: {
|
||||
name: "Error",
|
||||
message: "Failed for [redacted]",
|
||||
},
|
||||
});
|
||||
return {
|
||||
planCount: 3,
|
||||
featureCount: 9,
|
||||
createdProducts: 1,
|
||||
updatedProducts: 2,
|
||||
deletedFeatures: 4,
|
||||
createdFeatures: 5,
|
||||
};
|
||||
});
|
||||
|
||||
await SeedService.seed();
|
||||
|
||||
expect(loggerInfo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
op: "seed.entitlements",
|
||||
phase: "failure",
|
||||
planCount: 3,
|
||||
featureCount: 9,
|
||||
createdProducts: 1,
|
||||
updatedProducts: 2,
|
||||
deletedFeatures: 4,
|
||||
createdFeatures: 5,
|
||||
planId: "team",
|
||||
err: expect.objectContaining({ name: "Error", message: "Failed for [redacted]" }),
|
||||
}),
|
||||
"Entitlements seed event",
|
||||
);
|
||||
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("sk_live_");
|
||||
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("cus_secret");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,615 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { TenantUserJoined } from "~/application/enums/tenants/TenantUserJoined";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import { getAvailableTenantInboundAddress } from "~/utils/services/emailService";
|
||||
import { getEntitlementPlanStripeId, seedStandardEntitlements, type EntitlementsSeedDiagnosticEvent } from "@toolctrl/db/entitlements-seed.server";
|
||||
import { runDbSeed, type DbSeedDiagnosticEvent } from "@toolctrl/db/seed.server";
|
||||
import { entitlementPlanIds, featureKeys, productBlueprintIds, type EntitlementPlanId } from "@toolctrl/entitlements";
|
||||
import { seedRolesAndPermissions, type RolesAndPermissionsSeedDiagnosticEvent } from "~/utils/services/rolesAndPermissionsService";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { ensureProductCoreCrmEntities } from "~/modules/crm/services/ProductCoreCrmEntities.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
|
||||
const seedLogger = createScopedLogger("seed");
|
||||
|
||||
/**
|
||||
* Hashes an email (lower-cased + trimmed) so seed logs cannot leak the
|
||||
* actual address but operators can still correlate diagnostics.
|
||||
*/
|
||||
function emailFingerprint(email: string): string {
|
||||
return createHash("sha256").update(email.trim().toLowerCase(), "utf8").digest("hex").slice(0, 12);
|
||||
}
|
||||
|
||||
const DEFAULT_ADMIN_EMAIL = "admin@email.com";
|
||||
const DEFAULT_ADMIN_PASSWORD = "password";
|
||||
const localDemoSeedUsers = [
|
||||
{
|
||||
userType: "app" as const,
|
||||
firstName: "John",
|
||||
lastName: "Doe",
|
||||
email: "john.doe@company.com",
|
||||
password: "password",
|
||||
},
|
||||
{
|
||||
userType: "app" as const,
|
||||
firstName: "Luna",
|
||||
lastName: "Davis",
|
||||
email: "luna.davis@company.com",
|
||||
password: "password",
|
||||
},
|
||||
];
|
||||
const demoCrmTenants = [
|
||||
{ slug: "demo-starter-crm", name: "Demo Starter CRM", planId: entitlementPlanIds.starter },
|
||||
{ slug: "demo-pro-crm", name: "Demo Pro CRM", planId: entitlementPlanIds.pro },
|
||||
{ slug: "demo-business-crm", name: "Demo Business CRM", planId: entitlementPlanIds.business },
|
||||
] as const;
|
||||
const demoTenantRoleSeeds = [
|
||||
{
|
||||
name: "CRM Manager",
|
||||
description: "Owns CRM records, imports, and tenant team coordination in the demo workspace.",
|
||||
permissions: ["app.dashboard.view", "app.settings.members.view", "app.settings.roles.view"],
|
||||
},
|
||||
{
|
||||
name: "Support Agent",
|
||||
description: "Handles tenant support tickets and reads the tenant knowledge base in the demo workspace.",
|
||||
permissions: ["app.dashboard.view"],
|
||||
},
|
||||
] as const;
|
||||
const demoKnowledgeBaseCategoryTitle = "Product Core";
|
||||
const demoKnowledgeBaseCategoryDescription = "Plan gates, tenant roles, support, and CRM SaaS setup.";
|
||||
const demoKnowledgeBaseArticleTitle = "Plan gates overview";
|
||||
const demoSupportTicketSubjects = {
|
||||
welcome: "Welcome to the CRM SaaS demo workspace",
|
||||
planGates: "Verify plan gates and tenant roles",
|
||||
} as const;
|
||||
const demoSupportTicketPlanGatesMessage =
|
||||
"Use this ticket to confirm blueprint, plan, tenant override, and tenant-owned role access in the seeded workspace.";
|
||||
|
||||
function getAdminSeedUser() {
|
||||
return {
|
||||
email: process.env.SEED_ADMIN_EMAIL ?? DEFAULT_ADMIN_EMAIL,
|
||||
password: process.env.SEED_ADMIN_PASSWORD ?? DEFAULT_ADMIN_PASSWORD,
|
||||
firstName: "Admin",
|
||||
lastName: "User",
|
||||
};
|
||||
}
|
||||
|
||||
async function seed() {
|
||||
const adminUser = getAdminSeedUser();
|
||||
const shouldSeedDemoData = shouldSeedCrmDemoData();
|
||||
const seedCredentials = shouldSeedDemoData
|
||||
? [
|
||||
{ label: "admin", email: adminUser.email, password: adminUser.password },
|
||||
...localDemoSeedUsers.map((user) => ({ label: user.email, email: user.email, password: user.password })),
|
||||
]
|
||||
: [{ label: "admin", email: adminUser.email, password: adminUser.password }];
|
||||
|
||||
return runDbSeed({
|
||||
nodeEnv: getSeedSafetyEnvironment(),
|
||||
adminEmail: adminUser.email,
|
||||
adminPassword: adminUser.password,
|
||||
seedCredentials,
|
||||
diagnostics: logDbSeedDiagnostic,
|
||||
seed: async () => {
|
||||
const admin = await createUser({ userType: "admin", ...adminUser });
|
||||
let demoUsers: Awaited<ReturnType<typeof createUser>>[] = [];
|
||||
|
||||
if (shouldSeedDemoData) {
|
||||
seedLogger.info({ op: "seed.createDemoUsers", count: localDemoSeedUsers.length }, "Creating CRM SaaS demo users with tenants");
|
||||
demoUsers = await Promise.all(localDemoSeedUsers.map((user) => createUser(user)));
|
||||
const [user1, user2] = demoUsers;
|
||||
|
||||
await Promise.all(
|
||||
demoCrmTenants.map((tenant, index) =>
|
||||
createTenant(tenant.slug, tenant.name, [
|
||||
{ ...admin, type: TenantUserType.ADMIN },
|
||||
{ ...user1, type: index === 0 ? TenantUserType.ADMIN : TenantUserType.OWNER },
|
||||
{ ...user2, type: TenantUserType.MEMBER },
|
||||
])
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (shouldSeedDemoData) {
|
||||
await ensureProductCoreCrmEntities({ ensurePermissions: false });
|
||||
}
|
||||
|
||||
// Permissions
|
||||
await seedRolesAndPermissions({
|
||||
adminEmail: adminUser.email,
|
||||
diagnostics: logRolesAndPermissionsSeedDiagnostic,
|
||||
});
|
||||
|
||||
await seedStandardEntitlements({
|
||||
client: db,
|
||||
diagnostics: logEntitlementsSeedDiagnostic,
|
||||
});
|
||||
|
||||
if (shouldSeedDemoData) {
|
||||
await Promise.all(demoCrmTenants.map((tenant) => assignTenantPlan(tenant.slug, tenant.planId)));
|
||||
await Promise.all(demoCrmTenants.map((tenant) => seedDemoProductCoreTenant(tenant.slug, tenant.planId, demoUsers)));
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function shouldSeedCrmDemoData() {
|
||||
if (process.env.SEED_DEMO_DATA !== "true") {
|
||||
return false;
|
||||
}
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
return true;
|
||||
}
|
||||
if (process.env.ALLOW_STAGING_DEMO_SEED === "true") {
|
||||
return true;
|
||||
}
|
||||
throw new Error("Refusing to seed demo data in production without ALLOW_STAGING_DEMO_SEED=true.");
|
||||
}
|
||||
|
||||
function getSeedSafetyEnvironment() {
|
||||
if (process.env.NODE_ENV === "production" && process.env.SEED_DEMO_DATA === "true" && process.env.ALLOW_STAGING_DEMO_SEED === "true") {
|
||||
return "staging-demo";
|
||||
}
|
||||
return process.env.NODE_ENV ?? "development";
|
||||
}
|
||||
|
||||
function logDbSeedDiagnostic(event: DbSeedDiagnosticEvent) {
|
||||
const { phase, nodeEnv, adminEmail } = event;
|
||||
// Never log raw adminEmail (PII). Use fingerprint hash for correlation.
|
||||
seedLogger.info(
|
||||
{ op: "db-seed", phase, nodeEnv, adminEmailFingerprint: adminEmail ? emailFingerprint(adminEmail) : null },
|
||||
"DB seed event",
|
||||
);
|
||||
}
|
||||
|
||||
function logRolesAndPermissionsSeedDiagnostic(event: RolesAndPermissionsSeedDiagnosticEvent) {
|
||||
const {
|
||||
phase,
|
||||
adminRoleCount,
|
||||
appRoleCount,
|
||||
defaultPermissionCount,
|
||||
dynamicEntityPermissionCount,
|
||||
adminUserAssignmentCount,
|
||||
tenantUserAssignmentCount,
|
||||
error,
|
||||
} = event;
|
||||
seedLogger.info(
|
||||
{
|
||||
op: "seed.rolesAndPermissions",
|
||||
phase,
|
||||
adminRoleCount,
|
||||
appRoleCount,
|
||||
defaultPermissionCount,
|
||||
dynamicEntityPermissionCount,
|
||||
adminUserAssignmentCount,
|
||||
tenantUserAssignmentCount,
|
||||
...(error ? { err: error } : {}),
|
||||
},
|
||||
"Roles and permissions seed event",
|
||||
);
|
||||
}
|
||||
|
||||
function logEntitlementsSeedDiagnostic(event: EntitlementsSeedDiagnosticEvent) {
|
||||
const { phase, planCount, featureCount, createdProducts, updatedProducts, deletedFeatures, createdFeatures, planId, error } = event;
|
||||
seedLogger.info(
|
||||
{
|
||||
op: "seed.entitlements",
|
||||
phase,
|
||||
planCount,
|
||||
featureCount,
|
||||
createdProducts,
|
||||
updatedProducts,
|
||||
deletedFeatures,
|
||||
createdFeatures,
|
||||
...(planId ? { planId } : {}),
|
||||
...(error ? { err: error } : {}),
|
||||
},
|
||||
"Entitlements seed event",
|
||||
);
|
||||
}
|
||||
|
||||
async function createUser({
|
||||
firstName,
|
||||
lastName,
|
||||
email,
|
||||
password,
|
||||
userType,
|
||||
}: {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
password: string;
|
||||
userType: "admin" | "app";
|
||||
}) {
|
||||
// Never log raw `email` (PII) and never log `password` (secret).
|
||||
// Use email fingerprint hash so operators can still correlate seed events.
|
||||
seedLogger.info(
|
||||
{ op: "seed.createUser", userType, emailFingerprint: emailFingerprint(email) },
|
||||
userType === "admin" ? "Seeding admin user" : "Seeding app user",
|
||||
);
|
||||
const salt = await bcrypt.genSalt(10);
|
||||
const passwordHash = await bcrypt.hash(password, salt);
|
||||
let user = await db.user.findUnique({
|
||||
where: { email },
|
||||
});
|
||||
if (user) {
|
||||
const isAdmin = await db.adminUser.findUnique({ where: { userId: user.id } });
|
||||
if (!isAdmin && userType === "admin") {
|
||||
if (process.env.NODE_ENV === "production") {
|
||||
throw new Error("Production seed refused to promote an existing non-admin user. Choose a new SEED_ADMIN_EMAIL or bootstrap the admin user explicitly.");
|
||||
}
|
||||
seedLogger.info(
|
||||
{ op: "seed.promoteUserToAdmin", emailFingerprint: emailFingerprint(email) },
|
||||
"User already exists; promoting to admin",
|
||||
);
|
||||
await db.adminUser.create({ data: { userId: user.id } });
|
||||
} else {
|
||||
seedLogger.info(
|
||||
{ op: "seed.userExists", userType, emailFingerprint: emailFingerprint(email) },
|
||||
"User already exists",
|
||||
);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
user = await db.user.create({
|
||||
data: {
|
||||
email,
|
||||
passwordHash,
|
||||
avatar: "",
|
||||
firstName,
|
||||
lastName,
|
||||
phone: "",
|
||||
},
|
||||
});
|
||||
if (userType === "admin") {
|
||||
await db.adminUser.create({
|
||||
data: { userId: user.id },
|
||||
});
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
async function createTenant(slug: string, name: string, users: { id: string; type: TenantUserType }[]) {
|
||||
seedLogger.info({ op: "seed.createTenant", tenantSlug: slug, tenantName: name }, "Creating tenant");
|
||||
let tenant = await db.tenant.findUnique({
|
||||
where: { slug },
|
||||
});
|
||||
if (tenant) {
|
||||
seedLogger.info({ op: "seed.tenantExists", tenantSlug: slug }, "Tenant already exists");
|
||||
await db.tenant.update({
|
||||
where: { id: tenant.id },
|
||||
data: { active: true },
|
||||
});
|
||||
await ensureTenantSubscription(tenant.id);
|
||||
await ensureTenantInboundAddress(tenant.id, name);
|
||||
await ensureTenantUsers(tenant.id, users);
|
||||
return tenant;
|
||||
}
|
||||
const address = await getAvailableTenantInboundAddress(name);
|
||||
tenant = await db.tenant.create({
|
||||
data: {
|
||||
name,
|
||||
slug,
|
||||
icon: "",
|
||||
active: true,
|
||||
inboundAddresses: {
|
||||
create: {
|
||||
address,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
let tenantId = tenant.id;
|
||||
|
||||
await ensureTenantSubscription(tenantId);
|
||||
await ensureTenantUsers(tenantId, users);
|
||||
|
||||
return tenant;
|
||||
}
|
||||
|
||||
async function ensureTenantSubscription(tenantId: string) {
|
||||
const existing = await db.tenantSubscription.findUnique({ where: { tenantId } });
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
return db.tenantSubscription.create({
|
||||
data: {
|
||||
tenantId,
|
||||
stripeCustomerId: "",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureTenantInboundAddress(tenantId: string, tenantName: string) {
|
||||
const existing = await db.tenantInboundAddress.findFirst({ where: { tenantId } });
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
const address = await getAvailableTenantInboundAddress(tenantName);
|
||||
return db.tenantInboundAddress.create({
|
||||
data: {
|
||||
tenantId,
|
||||
address,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureTenantUsers(tenantId: string, users: { id: string; type: TenantUserType }[]) {
|
||||
for (const user of users) {
|
||||
const tenantUser = await db.tenantUser.findFirst({
|
||||
where: { tenantId, userId: user.id },
|
||||
});
|
||||
if (tenantUser) {
|
||||
seedLogger.info({ op: "seed.tenantUserExists", userId: user.id, tenantId }, "User already in tenant");
|
||||
continue;
|
||||
}
|
||||
await db.tenantUser.create({
|
||||
data: {
|
||||
tenantId,
|
||||
userId: user.id,
|
||||
type: user.type,
|
||||
joined: TenantUserJoined.CREATOR,
|
||||
status: TenantUserStatus.ACTIVE,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function assignTenantPlan(tenantSlug: string, planId: EntitlementPlanId) {
|
||||
const tenant = await db.tenant.findUnique({
|
||||
where: { slug: tenantSlug },
|
||||
include: { subscription: { include: { products: true } } },
|
||||
});
|
||||
if (!tenant?.subscription) {
|
||||
return;
|
||||
}
|
||||
|
||||
const product = await db.subscriptionProduct.findFirst({
|
||||
where: { stripeId: getEntitlementPlanStripeId({ id: planId }) },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!product) {
|
||||
return;
|
||||
}
|
||||
|
||||
const existingProduct = tenant.subscription.products.find((item) => item.subscriptionProductId === product.id && !item.endsAt);
|
||||
if (existingProduct) {
|
||||
return;
|
||||
}
|
||||
|
||||
await db.tenantSubscriptionProduct.create({
|
||||
data: {
|
||||
tenantSubscriptionId: tenant.subscription.id,
|
||||
subscriptionProductId: product.id,
|
||||
stripeSubscriptionId: null,
|
||||
quantity: 1,
|
||||
fromCheckoutSessionId: null,
|
||||
customEntitlementPlanId: planId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function seedDemoProductCoreTenant(tenantSlug: string, planId: EntitlementPlanId, demoUsers: { id: string }[]) {
|
||||
const tenant = await db.tenant.findUnique({
|
||||
where: { slug: tenantSlug },
|
||||
select: { id: true, name: true, slug: true },
|
||||
});
|
||||
if (!tenant) {
|
||||
return;
|
||||
}
|
||||
|
||||
await Promise.all([
|
||||
seedDemoTenantProductConfiguration(tenant.id, planId),
|
||||
seedDemoTenantRoles(tenant.id, demoUsers),
|
||||
seedDemoTenantKnowledgeBase(tenant.id, tenant.slug, tenant.name, planId),
|
||||
seedDemoSupportTickets(tenant.id, tenant.slug, planId, demoUsers[0]?.id),
|
||||
]);
|
||||
}
|
||||
|
||||
async function seedDemoTenantProductConfiguration(tenantId: string, planId: EntitlementPlanId) {
|
||||
await db.tenantProductConfiguration.upsert({
|
||||
where: { tenantId },
|
||||
create: {
|
||||
tenantId,
|
||||
blueprintId: productBlueprintIds.crmSaas,
|
||||
notes: `Seeded CRM SaaS product-core demo configuration for the ${planId} plan.`,
|
||||
},
|
||||
update: {
|
||||
blueprintId: productBlueprintIds.crmSaas,
|
||||
notes: `Seeded CRM SaaS product-core demo configuration for the ${planId} plan.`,
|
||||
},
|
||||
});
|
||||
|
||||
const overrides =
|
||||
planId === entitlementPlanIds.business
|
||||
? [{ featureKey: featureKeys.mcp, override: "enabled", reason: "Business demo tenant shows blueprint-enabled MCP access." }]
|
||||
: [{ featureKey: featureKeys.workflowEngine, override: "disabled", reason: `${planId} demo tenant keeps workflow automation plan-gated.` }];
|
||||
|
||||
for (const override of overrides) {
|
||||
await db.tenantFeatureOverride.upsert({
|
||||
where: { tenantId_featureKey: { tenantId, featureKey: override.featureKey } },
|
||||
create: { tenantId, ...override },
|
||||
update: { override: override.override, reason: override.reason },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function seedDemoTenantRoles(tenantId: string, demoUsers: { id: string }[]) {
|
||||
const permissions = await db.permission.findMany({
|
||||
where: {
|
||||
name: {
|
||||
in: [...new Set(demoTenantRoleSeeds.flatMap((role) => role.permissions))],
|
||||
},
|
||||
},
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
const permissionIdByName = new Map(permissions.map((permission) => [permission.name, permission.id]));
|
||||
|
||||
for (const [index, roleSeed] of demoTenantRoleSeeds.entries()) {
|
||||
let role = await db.role.findFirst({
|
||||
where: { tenantId, name: roleSeed.name, type: "app" },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!role) {
|
||||
role = await db.role.create({
|
||||
data: {
|
||||
tenantId,
|
||||
name: roleSeed.name,
|
||||
description: roleSeed.description,
|
||||
type: "app",
|
||||
assignToNewUsers: index === 1,
|
||||
isDefault: false,
|
||||
order: 100 + index,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
}
|
||||
|
||||
for (const permissionName of roleSeed.permissions) {
|
||||
const permissionId = permissionIdByName.get(permissionName);
|
||||
if (!permissionId) {
|
||||
continue;
|
||||
}
|
||||
const existing = await db.rolePermission.findFirst({ where: { roleId: role.id, permissionId } });
|
||||
if (!existing) {
|
||||
await db.rolePermission.create({ data: { roleId: role.id, permissionId } });
|
||||
}
|
||||
}
|
||||
|
||||
const user = demoUsers[index];
|
||||
if (user) {
|
||||
const existing = await db.userRole.findFirst({ where: { tenantId, userId: user.id, roleId: role.id } });
|
||||
if (!existing) {
|
||||
await db.userRole.create({ data: { tenantId, userId: user.id, roleId: role.id } });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function seedDemoTenantKnowledgeBase(tenantId: string, tenantSlug: string, tenantName: string, planId: EntitlementPlanId) {
|
||||
const ownerKey = `tenant:${tenantId}`;
|
||||
const slug = `${tenantSlug}-kb`;
|
||||
const knowledgeBase = await db.knowledgeBase.upsert({
|
||||
where: { ownerKey_slug: { ownerKey, slug } },
|
||||
create: {
|
||||
tenantId,
|
||||
ownerKey,
|
||||
basePath: "help",
|
||||
slug,
|
||||
title: `${tenantName} Knowledge Base`,
|
||||
description: `Tenant-owned product-core demo knowledge base for the ${planId} plan.`,
|
||||
defaultLanguage: "en",
|
||||
layout: "articles",
|
||||
color: 500,
|
||||
enabled: true,
|
||||
languages: "en,de",
|
||||
links: "[]",
|
||||
logo: "",
|
||||
seoImage: "",
|
||||
},
|
||||
update: {
|
||||
tenantId,
|
||||
title: `${tenantName} Knowledge Base`,
|
||||
description: `Tenant-owned product-core demo knowledge base for the ${planId} plan.`,
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const category = await db.knowledgeBaseCategory.upsert({
|
||||
where: { knowledgeBaseId_slug: { knowledgeBaseId: knowledgeBase.id, slug: "product-core" } },
|
||||
create: {
|
||||
knowledgeBaseId: knowledgeBase.id,
|
||||
slug: "product-core",
|
||||
order: 1,
|
||||
title: demoKnowledgeBaseCategoryTitle,
|
||||
description: demoKnowledgeBaseCategoryDescription,
|
||||
icon: "book-open",
|
||||
language: "en",
|
||||
seoImage: "",
|
||||
},
|
||||
update: {
|
||||
title: demoKnowledgeBaseCategoryTitle,
|
||||
description: demoKnowledgeBaseCategoryDescription,
|
||||
},
|
||||
});
|
||||
|
||||
const content = `<p>${tenantName} is seeded on the ${planId} plan with CRM SaaS blueprint gates, tenant roles, support tickets, and tenant-owned knowledge base content.</p>`;
|
||||
await db.knowledgeBaseArticle.upsert({
|
||||
where: { knowledgeBaseId_slug: { knowledgeBaseId: knowledgeBase.id, slug: "plan-gates-overview" } },
|
||||
create: {
|
||||
knowledgeBaseId: knowledgeBase.id,
|
||||
categoryId: category.id,
|
||||
slug: "plan-gates-overview",
|
||||
title: demoKnowledgeBaseArticleTitle,
|
||||
description: `What the ${planId} plan enables in this seeded tenant.`,
|
||||
order: 1,
|
||||
contentDraft: content,
|
||||
contentPublished: content,
|
||||
contentPublishedAsText: `${tenantName} is seeded on the ${planId} plan with CRM SaaS blueprint gates, tenant roles, support tickets, and tenant-owned knowledge base content.`,
|
||||
contentType: "html",
|
||||
language: "en",
|
||||
seoImage: "",
|
||||
publishedAt: new Date(),
|
||||
},
|
||||
update: {
|
||||
categoryId: category.id,
|
||||
title: demoKnowledgeBaseArticleTitle,
|
||||
description: `What the ${planId} plan enables in this seeded tenant.`,
|
||||
contentDraft: content,
|
||||
contentPublished: content,
|
||||
contentPublishedAsText: `${tenantName} is seeded on the ${planId} plan with CRM SaaS blueprint gates, tenant roles, support tickets, and tenant-owned knowledge base content.`,
|
||||
publishedAt: new Date(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function seedDemoSupportTickets(tenantId: string, tenantSlug: string, planId: EntitlementPlanId, userId?: string) {
|
||||
const tickets = [
|
||||
{
|
||||
inboundMessageId: `seed:${tenantSlug}:welcome`,
|
||||
subject: demoSupportTicketSubjects.welcome,
|
||||
message: `This ${planId} tenant includes seeded support-ticket data so HelpDesk can be reviewed immediately.`,
|
||||
priority: "normal",
|
||||
status: "open",
|
||||
},
|
||||
{
|
||||
inboundMessageId: `seed:${tenantSlug}:plan-gates`,
|
||||
subject: demoSupportTicketSubjects.planGates,
|
||||
message: demoSupportTicketPlanGatesMessage,
|
||||
priority: planId === entitlementPlanIds.business ? "high" : "normal",
|
||||
status: "open",
|
||||
},
|
||||
];
|
||||
|
||||
for (const ticket of tickets) {
|
||||
await db.supportTicket.upsert({
|
||||
where: { inboundMessageId: ticket.inboundMessageId },
|
||||
create: {
|
||||
tenantId,
|
||||
userId,
|
||||
source: "seed",
|
||||
fromEmail: "support-demo@example.test",
|
||||
fromUrl: `/${tenantSlug}/dashboard`,
|
||||
...ticket,
|
||||
},
|
||||
update: {
|
||||
tenantId,
|
||||
userId,
|
||||
source: "seed",
|
||||
fromEmail: "support-demo@example.test",
|
||||
fromUrl: `/${tenantSlug}/dashboard`,
|
||||
subject: ticket.subject,
|
||||
message: ticket.message,
|
||||
priority: ticket.priority,
|
||||
status: ticket.status,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
seed,
|
||||
};
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
export {
|
||||
createCheckoutSessionStatus,
|
||||
getCheckoutSessionStatus,
|
||||
updateCheckoutSessionStatus,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
export {
|
||||
createSubscriptionFeature,
|
||||
createSubscriptionPrice,
|
||||
createSubscriptionProduct,
|
||||
createSubscriptionUsageBasedPrice,
|
||||
createSubscriptionUsageBasedTier,
|
||||
deleteSubscriptionFeatures,
|
||||
deleteSubscriptionPrice,
|
||||
deleteSubscriptionProduct,
|
||||
deleteSubscriptionUsageBasedPrice,
|
||||
deleteSubscriptionUsageBasedTier,
|
||||
getAllSubscriptionFeatures,
|
||||
getAllSubscriptionProducts,
|
||||
getAllSubscriptionProductsWithTenants,
|
||||
getSubscriptionPrice,
|
||||
getSubscriptionPriceByStripeId,
|
||||
getSubscriptionPrices,
|
||||
getSubscriptionProduct,
|
||||
getSubscriptionProductByStripeId,
|
||||
getSubscriptionProductsInIds,
|
||||
getSubscriptionUsageBasedPriceByStripeId,
|
||||
updateSubscriptionPrice,
|
||||
updateSubscriptionPriceStripeId,
|
||||
updateSubscriptionProduct,
|
||||
updateSubscriptionProductStripeId,
|
||||
type SubscriptionPriceWithProduct,
|
||||
type SubscriptionUsageBasedPriceWithProduct,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
// Subscription-product mutations (the path an in-app plan upgrade runs)
|
||||
// must purge the cache cross-replica. Assert each wrapper routes through the
|
||||
// publishing helper `clearTenantSubscriptionCache` rather than a bare,
|
||||
// local-only `clearCacheKey`.
|
||||
//
|
||||
// The mock fn is parked on `globalThis` so the hoisted `vi.mock` factory can
|
||||
// reach it without a top-level reference (vitest 0.29 has no `vi.hoisted`).
|
||||
type CacheMocks = { clearTenantSubscriptionCache: ReturnType<typeof vi.fn> };
|
||||
|
||||
function getMocks(): CacheMocks {
|
||||
const store = globalThis as typeof globalThis & { __tenantSubProductDbCacheMocks__?: CacheMocks };
|
||||
store.__tenantSubProductDbCacheMocks__ ??= { clearTenantSubscriptionCache: vi.fn() };
|
||||
return store.__tenantSubProductDbCacheMocks__;
|
||||
}
|
||||
|
||||
vi.mock("@toolctrl/db/subscriptions.server", () => ({
|
||||
addTenantSubscriptionProduct: vi.fn(),
|
||||
cancelTenantSubscriptionProduct: vi.fn(),
|
||||
updateTenantSubscriptionProduct: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/services/.server/subscriptionService", () => ({
|
||||
clearTenantSubscriptionCache: getMocks().clearTenantSubscriptionCache,
|
||||
}));
|
||||
|
||||
import {
|
||||
addTenantSubscriptionProduct,
|
||||
cancelTenantSubscriptionProduct,
|
||||
updateTenantSubscriptionProduct,
|
||||
} from "./tenantSubscriptionProducts.db.server";
|
||||
import {
|
||||
addTenantSubscriptionProduct as persistAdd,
|
||||
cancelTenantSubscriptionProduct as persistCancel,
|
||||
updateTenantSubscriptionProduct as persistUpdate,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
|
||||
const mocks = getMocks();
|
||||
|
||||
describe("tenantSubscriptionProducts db wrapper — cross-replica cache invalidation", () => {
|
||||
it("addTenantSubscriptionProduct publishes a cross-replica invalidation for the tenant", async () => {
|
||||
mocks.clearTenantSubscriptionCache.mockClear();
|
||||
vi.mocked(persistAdd).mockResolvedValueOnce({
|
||||
tenantSubscription: { tenantId: "tenant-a" },
|
||||
} as Awaited<ReturnType<typeof persistAdd>>);
|
||||
|
||||
await addTenantSubscriptionProduct({} as Parameters<typeof addTenantSubscriptionProduct>[0]);
|
||||
|
||||
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledWith("tenant-a");
|
||||
});
|
||||
|
||||
it("updateTenantSubscriptionProduct publishes a cross-replica invalidation for the tenant", async () => {
|
||||
mocks.clearTenantSubscriptionCache.mockClear();
|
||||
vi.mocked(persistUpdate).mockResolvedValueOnce({
|
||||
tenantSubscription: { tenantId: "tenant-b" },
|
||||
} as Awaited<ReturnType<typeof persistUpdate>>);
|
||||
|
||||
await updateTenantSubscriptionProduct("p1", "tenant-b", {} as Parameters<typeof updateTenantSubscriptionProduct>[2]);
|
||||
|
||||
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledWith("tenant-b");
|
||||
});
|
||||
|
||||
it("cancelTenantSubscriptionProduct publishes cross-replica before and after the persist", async () => {
|
||||
mocks.clearTenantSubscriptionCache.mockClear();
|
||||
vi.mocked(persistCancel).mockResolvedValueOnce({
|
||||
tenantId: "tenant-c",
|
||||
} as Awaited<ReturnType<typeof persistCancel>>);
|
||||
|
||||
await cancelTenantSubscriptionProduct("p1", "tenant-c", {} as Parameters<typeof cancelTenantSubscriptionProduct>[2]);
|
||||
|
||||
// Pre-invalidate on the passed tenantId + re-invalidate on the persisted
|
||||
// record's tenantId — both publish cross-replica.
|
||||
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.clearTenantSubscriptionCache).toHaveBeenNthCalledWith(1, "tenant-c");
|
||||
expect(mocks.clearTenantSubscriptionCache).toHaveBeenNthCalledWith(2, "tenant-c");
|
||||
});
|
||||
});
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
import {
|
||||
addTenantSubscriptionProduct as persistTenantSubscriptionProduct,
|
||||
cancelTenantSubscriptionProduct as persistTenantSubscriptionProductCancellation,
|
||||
updateTenantSubscriptionProduct as persistTenantSubscriptionProductUpdate,
|
||||
type TenantSubscriptionProductCreateInput,
|
||||
type TenantSubscriptionProductUpdateInput,
|
||||
type TenantSubscriptionProductCancelInput,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
import { clearTenantSubscriptionCache } from "~/utils/services/.server/subscriptionService";
|
||||
|
||||
export {
|
||||
adminGetTenantSubscriptionProductById,
|
||||
getAllTenantSubscriptionProducts,
|
||||
getTenantSubscriptionProduct,
|
||||
getTenantSubscriptionProductById,
|
||||
getTenantSubscriptionProductByStripeSubscriptionId,
|
||||
type TenantSubscriptionProductPage,
|
||||
type TenantSubscriptionProductWithDetails,
|
||||
type TenantSubscriptionProductWithTenant,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
|
||||
export async function addTenantSubscriptionProduct(data: TenantSubscriptionProductCreateInput) {
|
||||
const item = await persistTenantSubscriptionProduct(data);
|
||||
// Cross-replica purge: clearTenantSubscriptionCache publishes on the
|
||||
// subscription pub/sub channel so peer web replicas drop their L1 too.
|
||||
clearTenantSubscriptionCache(item.tenantSubscription.tenantId);
|
||||
return item;
|
||||
}
|
||||
|
||||
export async function updateTenantSubscriptionProduct(id: string, tenantId: string, data: TenantSubscriptionProductUpdateInput) {
|
||||
const item = await persistTenantSubscriptionProductUpdate({ id, tenantId }, data);
|
||||
clearTenantSubscriptionCache(item.tenantSubscription.tenantId);
|
||||
return item;
|
||||
}
|
||||
|
||||
export async function cancelTenantSubscriptionProduct(id: string, tenantId: string, data: TenantSubscriptionProductCancelInput) {
|
||||
// Pre-invalidate the affected tenant only — no need to wipe every tenant's
|
||||
// subscription cache for a single tenant cancellation.
|
||||
clearTenantSubscriptionCache(tenantId);
|
||||
const item = await persistTenantSubscriptionProductCancellation({ id, tenantId }, data);
|
||||
// Re-invalidate against the persisted record's tenantId in case it differs;
|
||||
// publishes cross-replica so no peer keeps a stale entry.
|
||||
clearTenantSubscriptionCache(item.tenantId);
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("~/utils/cache.server", () => {
|
||||
const map = new Map<string, unknown>();
|
||||
return {
|
||||
cache: map,
|
||||
cachified: vi.fn(),
|
||||
clearCacheKey: vi.fn((key: string) => map.delete(key)),
|
||||
clearCacheKeyPrefix: vi.fn((prefix: string) => {
|
||||
for (const k of map.keys()) if (k.startsWith(prefix)) map.delete(k);
|
||||
}),
|
||||
__test_map: map,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/shared-store.server", async () => {
|
||||
const { MemoryAdapter, createSharedStore } = await import("@toolctrl/shared-store");
|
||||
const adapter = new MemoryAdapter();
|
||||
const store = createSharedStore({ namespace: "web-test", adapter });
|
||||
return {
|
||||
getSharedStore: () => store,
|
||||
__setSharedStoreFactoryForTests: vi.fn(),
|
||||
__resetSharedStoreForTests: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
import {
|
||||
publishTenantInvalidation,
|
||||
subscribeTenantCache,
|
||||
__resetTenantCacheForTests,
|
||||
} from "./tenant-cache.server";
|
||||
import * as cacheServer from "~/utils/cache.server";
|
||||
|
||||
beforeEach(() => {
|
||||
__resetTenantCacheForTests();
|
||||
(cacheServer as unknown as { __test_map: Map<string, unknown> }).__test_map.clear();
|
||||
vi.mocked(cacheServer.clearCacheKey).mockClear();
|
||||
vi.mocked(cacheServer.clearCacheKeyPrefix).mockClear();
|
||||
delete process.env.CACHE_INVALIDATION_ENABLED;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
__resetTenantCacheForTests();
|
||||
});
|
||||
|
||||
describe("tenant cache (two-tier)", () => {
|
||||
it("publishTenantInvalidation clears local cachified keys for tenant id", async () => {
|
||||
await publishTenantInvalidation("tenant-7");
|
||||
expect(vi.mocked(cacheServer.clearCacheKey)).toHaveBeenCalledWith("tenant:tenant-7");
|
||||
expect(vi.mocked(cacheServer.clearCacheKey)).toHaveBeenCalledWith("tenantSimple:tenant-7");
|
||||
expect(vi.mocked(cacheServer.clearCacheKey)).toHaveBeenCalledWith("tenantIdOrSlug:tenant-7");
|
||||
});
|
||||
|
||||
it("remote invalidation purges all 3 cachified prefixes for the affected tenant", async () => {
|
||||
await subscribeTenantCache();
|
||||
await publishTenantInvalidation("tenant-9");
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
// local + remote both fire clearCacheKey — assert tenant-9 keys were dropped
|
||||
expect(vi.mocked(cacheServer.clearCacheKey).mock.calls.filter((c) => c[0] === "tenant:tenant-9").length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it("subscribeTenantCache is idempotent", async () => {
|
||||
const a = await subscribeTenantCache();
|
||||
const b = await subscribeTenantCache();
|
||||
expect(a).toBe(b);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { createTwoTierCache, type TwoTierCache } from "@toolctrl/shared-store";
|
||||
import { getSharedStore } from "~/shared-store.server";
|
||||
import { clearCacheKey, clearCacheKeyPrefix } from "~/utils/cache.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
|
||||
/**
|
||||
* Tenant cache (two-tier). The existing in-process `cachified` LRU in
|
||||
* `tenants.db.server.ts` stays the L1 read path; this module owns the
|
||||
* pub/sub channel so peer replicas drop their L1 entries when a
|
||||
* mutation happens on a different replica.
|
||||
*
|
||||
* Keys broadcast over the channel are tenant ids. The subscriber clears
|
||||
* every cachified key derived from a tenant (`tenant:`, `tenantSimple:`,
|
||||
* `tenantIdOrSlug:`).
|
||||
*/
|
||||
const log = createScopedLogger("tenant-cache");
|
||||
|
||||
const TTL_SECONDS_DEFAULT = 5 * 60;
|
||||
|
||||
let cacheSingleton: TwoTierCache<{ id: string } | null> | null = null;
|
||||
let subscribeDisposer: (() => Promise<void>) | null = null;
|
||||
|
||||
function pubsubEnabledFromEnv(): boolean {
|
||||
const raw = process.env.CACHE_INVALIDATION_ENABLED;
|
||||
if (raw === undefined || raw === null || raw === "") return true;
|
||||
return raw.toLowerCase() !== "false" && raw !== "0";
|
||||
}
|
||||
|
||||
function ttlSecondsFromEnv(): number {
|
||||
const raw = process.env.CACHE_L1_TTL_SECONDS;
|
||||
if (!raw) return TTL_SECONDS_DEFAULT;
|
||||
const parsed = Number(raw);
|
||||
if (!Number.isFinite(parsed) || parsed <= 0) return TTL_SECONDS_DEFAULT;
|
||||
return Math.floor(parsed);
|
||||
}
|
||||
|
||||
export function getTenantCache(): TwoTierCache<{ id: string } | null> {
|
||||
if (cacheSingleton) return cacheSingleton;
|
||||
cacheSingleton = createTwoTierCache<{ id: string } | null>({
|
||||
store: getSharedStore(),
|
||||
namespace: "tenant",
|
||||
ttlSeconds: ttlSecondsFromEnv(),
|
||||
pubsubEnabled: pubsubEnabledFromEnv(),
|
||||
logger: { warn: (obj, msg) => log.warn(obj, msg), error: (obj, msg) => log.error(obj, msg) },
|
||||
});
|
||||
return cacheSingleton;
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish a tenant-invalidation. Call after any tenant mutation in the
|
||||
* web app (settings update, logo upload, member add/remove). The local
|
||||
* cachified entries are also cleared as a defence-in-depth in case the
|
||||
* caller forgot to call clearCacheKey().
|
||||
*/
|
||||
export async function publishTenantInvalidation(tenantId: string): Promise<void> {
|
||||
clearCacheKey(`tenant:${tenantId}`);
|
||||
clearCacheKey(`tenantSimple:${tenantId}`);
|
||||
clearCacheKey(`tenantIdOrSlug:${tenantId}`);
|
||||
await getTenantCache().invalidate(tenantId).catch(() => {
|
||||
/* logged inside helper */
|
||||
});
|
||||
}
|
||||
|
||||
export async function subscribeTenantCache(): Promise<() => Promise<void>> {
|
||||
if (subscribeDisposer) return subscribeDisposer;
|
||||
const cache = getTenantCache();
|
||||
subscribeDisposer = await cache.subscribe((key) => {
|
||||
if (!key || key === "*") {
|
||||
clearCacheKeyPrefix("tenant:");
|
||||
clearCacheKeyPrefix("tenantSimple:");
|
||||
clearCacheKeyPrefix("tenantIdOrSlug:");
|
||||
return;
|
||||
}
|
||||
clearCacheKey(`tenant:${key}`);
|
||||
clearCacheKey(`tenantSimple:${key}`);
|
||||
clearCacheKey(`tenantIdOrSlug:${key}`);
|
||||
});
|
||||
log.info({ namespace: "tenant" }, "tenant cache subscriber started");
|
||||
return subscribeDisposer;
|
||||
}
|
||||
|
||||
/** Test seam: drop the singleton + disposer. */
|
||||
export function __resetTenantCacheForTests(): void {
|
||||
cacheSingleton = null;
|
||||
subscribeDisposer = null;
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
// Stripe-driven subscription mutations must purge the cache cross-replica,
|
||||
// not just in-process — assert these wrappers route through the publishing
|
||||
// helper `clearTenantSubscriptionCache` (which fans out on pub/sub).
|
||||
//
|
||||
// The mock fn is parked on `globalThis` so the hoisted `vi.mock` factory can
|
||||
// reach it without a top-level reference (vitest 0.29 has no `vi.hoisted`).
|
||||
type CacheMocks = { clearTenantSubscriptionCache: ReturnType<typeof vi.fn> };
|
||||
|
||||
function getMocks(): CacheMocks {
|
||||
const store = globalThis as typeof globalThis & { __tenantSubsDbCacheMocks__?: CacheMocks };
|
||||
store.__tenantSubsDbCacheMocks__ ??= { clearTenantSubscriptionCache: vi.fn() };
|
||||
return store.__tenantSubsDbCacheMocks__;
|
||||
}
|
||||
|
||||
vi.mock("@toolctrl/db/subscriptions.server", () => ({
|
||||
createTenantSubscription: vi.fn(),
|
||||
getTenantSubscription: vi.fn(),
|
||||
getTenantSubscriptions: vi.fn(),
|
||||
updateTenantSubscriptionCustomerId: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/services/.server/subscriptionService", () => ({
|
||||
clearTenantSubscriptionCache: getMocks().clearTenantSubscriptionCache,
|
||||
}));
|
||||
|
||||
import { createTenantSubscription, updateTenantSubscriptionCustomerId } from "./tenantSubscriptions.db.server";
|
||||
import {
|
||||
createTenantSubscription as persistTenantSubscription,
|
||||
updateTenantSubscriptionCustomerId as persistTenantSubscriptionCustomerId,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
|
||||
const mocks = getMocks();
|
||||
|
||||
describe("tenantSubscriptions db wrapper — cross-replica cache invalidation", () => {
|
||||
it("createTenantSubscription publishes a cross-replica invalidation for the tenant", async () => {
|
||||
mocks.clearTenantSubscriptionCache.mockClear();
|
||||
vi.mocked(persistTenantSubscription).mockResolvedValueOnce({
|
||||
tenantId: "tenant-a",
|
||||
} as Awaited<ReturnType<typeof persistTenantSubscription>>);
|
||||
|
||||
await createTenantSubscription("tenant-a", "cus_x");
|
||||
|
||||
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledWith("tenant-a");
|
||||
});
|
||||
|
||||
it("updateTenantSubscriptionCustomerId publishes a cross-replica invalidation for the tenant", async () => {
|
||||
mocks.clearTenantSubscriptionCache.mockClear();
|
||||
vi.mocked(persistTenantSubscriptionCustomerId).mockResolvedValueOnce(
|
||||
{} as Awaited<ReturnType<typeof persistTenantSubscriptionCustomerId>>,
|
||||
);
|
||||
|
||||
await updateTenantSubscriptionCustomerId("tenant-b", { stripeCustomerId: "cus_y" });
|
||||
|
||||
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledWith("tenant-b");
|
||||
});
|
||||
});
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import {
|
||||
createTenantSubscription as persistTenantSubscription,
|
||||
getTenantSubscription as readTenantSubscription,
|
||||
updateTenantSubscriptionCustomerId as persistTenantSubscriptionCustomerId,
|
||||
type TenantSubscriptionWithDetails,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
import { clearTenantSubscriptionCache } from "~/utils/services/.server/subscriptionService";
|
||||
|
||||
export { getTenantSubscription, getTenantSubscriptions, type TenantSubscriptionWithDetails } from "@toolctrl/db/subscriptions.server";
|
||||
|
||||
export async function getOrPersistTenantSubscription(tenantId: string): Promise<TenantSubscriptionWithDetails> {
|
||||
const subscription = await readTenantSubscription(tenantId);
|
||||
|
||||
if (!subscription) {
|
||||
return await createTenantSubscription(tenantId, "");
|
||||
}
|
||||
return subscription;
|
||||
}
|
||||
|
||||
export async function createTenantSubscription(tenantId: string, stripeCustomerId: string) {
|
||||
const item = await persistTenantSubscription({ tenantId, stripeCustomerId });
|
||||
// Cross-replica purge: clearTenantSubscriptionCache publishes on the
|
||||
// subscription pub/sub channel so peer web replicas drop their L1 too.
|
||||
clearTenantSubscriptionCache(tenantId);
|
||||
return item;
|
||||
}
|
||||
|
||||
export async function updateTenantSubscriptionCustomerId(tenantId: string, data: { stripeCustomerId: string }) {
|
||||
const item = await persistTenantSubscriptionCustomerId(tenantId, data);
|
||||
clearTenantSubscriptionCache(tenantId);
|
||||
return item;
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
export async function getUserInvitation(id: string, tenantId?: string) {
|
||||
return await db.tenantUserInvitation.findFirst({
|
||||
where: {
|
||||
id,
|
||||
...(tenantId ? { tenantId } : {}),
|
||||
pending: true,
|
||||
},
|
||||
include: {
|
||||
tenant: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getUserInvitations(tenantId?: string) {
|
||||
if (!tenantId) {
|
||||
return [];
|
||||
}
|
||||
return await db.tenantUserInvitation.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
pending: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createUserInvitation(
|
||||
tenantId: string,
|
||||
data: {
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
type: TenantUserType;
|
||||
fromUserId: string | null;
|
||||
}
|
||||
) {
|
||||
const invitation = await db.tenantUserInvitation.create({
|
||||
data: {
|
||||
tenantId,
|
||||
...data,
|
||||
pending: true,
|
||||
},
|
||||
});
|
||||
|
||||
return invitation;
|
||||
}
|
||||
|
||||
export async function updateUserInvitationPending(id: string) {
|
||||
return await db.tenantUserInvitation.update({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
data: {
|
||||
pending: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteUserInvitation(id: string, tenantId?: string) {
|
||||
if (tenantId) {
|
||||
return await db.tenantUserInvitation.deleteMany({
|
||||
where: {
|
||||
id,
|
||||
tenantId,
|
||||
},
|
||||
});
|
||||
}
|
||||
return await db.tenantUserInvitation.delete({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
}
|
||||
+582
@@ -0,0 +1,582 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { TenantUserJoined } from "~/application/enums/tenants/TenantUserJoined";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: {
|
||||
tenant: {
|
||||
count: vi.fn(),
|
||||
create: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
findUnique: vi.fn(),
|
||||
update: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
tenantUser: {
|
||||
count: vi.fn(),
|
||||
create: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
findFirstOrThrow: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
userRole: {
|
||||
deleteMany: vi.fn(),
|
||||
},
|
||||
groupUser: {
|
||||
deleteMany: vi.fn(),
|
||||
},
|
||||
$transaction: vi.fn(),
|
||||
},
|
||||
dbRead: {
|
||||
tenant: {
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
vi.mock("../helpers/RowFiltersHelper", () => ({
|
||||
default: {
|
||||
getFiltersCondition: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock("../cache.server", () => ({
|
||||
cachified: vi.fn((options: { getFreshValue: () => unknown }) => options.getFreshValue()),
|
||||
clearCacheKey: vi.fn(),
|
||||
clearCacheKeyPrefix: vi.fn(),
|
||||
}));
|
||||
vi.mock("../services/emailService", () => ({
|
||||
getAvailableTenantInboundAddress: vi.fn(),
|
||||
}));
|
||||
vi.mock("../services/tenantService", () => ({
|
||||
getAvailableTenantSlug: vi.fn(),
|
||||
}));
|
||||
vi.mock("./permissions/userRoles.db.server", () => ({
|
||||
createUserRole: vi.fn(),
|
||||
}));
|
||||
vi.mock("./tenantSubscriptions.db.server", () => ({
|
||||
createTenantSubscription: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/modules/plugins/services/.server/pluginHookPublisher", () => ({
|
||||
emitPluginHookFireAndForget: vi.fn(),
|
||||
}));
|
||||
|
||||
import { db, dbRead } from "~/utils/db.server";
|
||||
import RowFiltersHelper from "../helpers/RowFiltersHelper";
|
||||
import { cachified, clearCacheKey, clearCacheKeyPrefix } from "../cache.server";
|
||||
import { getAvailableTenantInboundAddress } from "../services/emailService";
|
||||
import { getAvailableTenantSlug } from "../services/tenantService";
|
||||
import { createUserRole } from "./permissions/userRoles.db.server";
|
||||
import { createTenantSubscription } from "./tenantSubscriptions.db.server";
|
||||
import { emitPluginHookFireAndForget } from "~/modules/plugins/services/.server/pluginHookPublisher";
|
||||
import {
|
||||
addTenantTypeToTenant,
|
||||
adminGetAllActiveTenantSimple,
|
||||
adminGetAllTenants,
|
||||
adminGetAllTenantsIdsAndNames,
|
||||
adminGetAllTenantsWithUsage,
|
||||
createTenant,
|
||||
createTenantUser,
|
||||
deleteTenant,
|
||||
deleteTenantUser,
|
||||
getAllTenantUsers,
|
||||
getAllTenantsWithoutTypes,
|
||||
getMyTenants,
|
||||
getTenant,
|
||||
getTenantByIdOrSlug,
|
||||
getTenantBySlug,
|
||||
getTenantMember,
|
||||
getTenantSimple,
|
||||
getTenantUser,
|
||||
getTenantUserByIds,
|
||||
getTenantUserSimple,
|
||||
getTenantUserType,
|
||||
getTenantUsers,
|
||||
getTenantUsersCount,
|
||||
getTenantUsersInTenantIds,
|
||||
getTenantWithProfile,
|
||||
getTenantWithUsers,
|
||||
getTenantsInIds,
|
||||
requireTenant,
|
||||
updateTenant,
|
||||
updateTenantDeactivated,
|
||||
updateTenantTheme,
|
||||
} from "./tenants.db.server";
|
||||
|
||||
const dbMock = vi.mocked(db);
|
||||
const dbReadMock = vi.mocked(dbRead);
|
||||
|
||||
describe("tenants db wrapper", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(cachified).mockImplementation((async (options: { getFreshValue: () => unknown }) =>
|
||||
options.getFreshValue()) as never);
|
||||
dbMock.$transaction.mockImplementation((async (operations: Promise<unknown>[] | ((tx: typeof db) => Promise<unknown>)) => {
|
||||
if (Array.isArray(operations)) {
|
||||
return await Promise.all(operations);
|
||||
}
|
||||
return await operations(db);
|
||||
}) as never);
|
||||
vi.mocked(RowFiltersHelper.getFiltersCondition).mockReturnValue(undefined);
|
||||
});
|
||||
|
||||
it("combines admin tenant usage filters for user membership, empty type, and pagination", async () => {
|
||||
const baseWhere = { name: { contains: "acme" } };
|
||||
vi.mocked(RowFiltersHelper.getFiltersCondition).mockReturnValue(baseWhere as never);
|
||||
vi.mocked(dbMock.tenant.findMany).mockResolvedValueOnce([{ id: "tenant_1" }] as never);
|
||||
vi.mocked(dbMock.tenant.count).mockResolvedValueOnce(42);
|
||||
|
||||
const result = await adminGetAllTenantsWithUsage(
|
||||
{
|
||||
query: "",
|
||||
properties: [
|
||||
{ name: "userId", value: "user_1" },
|
||||
{ name: "typeId", value: "null" },
|
||||
],
|
||||
} as never,
|
||||
{ page: 3, pageSize: 10 }
|
||||
);
|
||||
|
||||
const userWhere = { OR: [baseWhere, { users: { some: { userId: "user_1" } } }] };
|
||||
const expectedWhere = { OR: [userWhere, { types: { none: {} } }] };
|
||||
expect(dbMock.tenant.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
skip: 20,
|
||||
take: 10,
|
||||
where: expectedWhere,
|
||||
orderBy: { createdAt: "desc" },
|
||||
})
|
||||
);
|
||||
expect(dbMock.tenant.count).toHaveBeenCalledWith({ where: expectedWhere });
|
||||
expect(result.pagination).toEqual({ page: 3, pageSize: 10, totalItems: 42, totalPages: 5 });
|
||||
});
|
||||
|
||||
it("uses read and write clients for the basic tenant listing helpers", async () => {
|
||||
vi.mocked(dbMock.tenant.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(dbReadMock.tenant.findMany).mockResolvedValue([] as never);
|
||||
|
||||
await getTenantsInIds(["tenant_1", "tenant_2"]);
|
||||
await adminGetAllTenants();
|
||||
await adminGetAllTenantsIdsAndNames();
|
||||
await adminGetAllActiveTenantSimple();
|
||||
|
||||
expect(dbMock.tenant.findMany).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({ where: { id: { in: ["tenant_1", "tenant_2"] } } })
|
||||
);
|
||||
expect(dbMock.tenant.findMany).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({ orderBy: { createdAt: "desc" } })
|
||||
);
|
||||
expect(dbReadMock.tenant.findMany).toHaveBeenNthCalledWith(1, {
|
||||
select: { id: true, name: true, slug: true },
|
||||
});
|
||||
expect(dbReadMock.tenant.findMany).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
where: { active: true },
|
||||
orderBy: { name: "asc" },
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("wraps cached tenant identity lookups with stable cache keys", async () => {
|
||||
vi.mocked(dbMock.tenant.findUnique).mockResolvedValue({ id: "tenant_1" } as never);
|
||||
vi.mocked(dbMock.tenant.findFirst).mockResolvedValue({ id: "tenant_1" } as never);
|
||||
|
||||
await getTenant("tenant_1");
|
||||
await getTenantSimple("tenant_1");
|
||||
await getTenantByIdOrSlug("acme");
|
||||
|
||||
expect(cachified).toHaveBeenCalledWith(expect.objectContaining({ key: "tenant:tenant_1" }));
|
||||
expect(cachified).toHaveBeenCalledWith(expect.objectContaining({ key: "tenantSimple:tenant_1" }));
|
||||
expect(cachified).toHaveBeenCalledWith(expect.objectContaining({ key: "tenantIdOrSlug:acme" }));
|
||||
expect(dbMock.tenant.findFirst).toHaveBeenCalledWith({
|
||||
where: { OR: [{ id: "acme" }, { slug: "acme" }] },
|
||||
include: { subscription: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("queries direct tenant identity variants without cache wrappers", async () => {
|
||||
vi.mocked(dbMock.tenant.findUnique).mockResolvedValue({ id: "tenant_1" } as never);
|
||||
|
||||
await getTenantBySlug("acme");
|
||||
await getTenantWithProfile("tenant_1");
|
||||
await getTenantWithUsers("tenant_1");
|
||||
|
||||
expect(dbMock.tenant.findUnique).toHaveBeenNthCalledWith(1, { where: { slug: "acme" } });
|
||||
expect(dbMock.tenant.findUnique).toHaveBeenNthCalledWith(2, { where: { id: "tenant_1" }, include: { types: true } });
|
||||
expect(dbMock.tenant.findUnique).toHaveBeenNthCalledWith(3, { where: { id: "tenant_1" }, include: { users: true } });
|
||||
});
|
||||
|
||||
it("uses the free-text query as a user filter and concrete tenant type when no base filter exists", async () => {
|
||||
vi.mocked(dbMock.tenant.findMany).mockResolvedValueOnce([] as never);
|
||||
vi.mocked(dbMock.tenant.count).mockResolvedValueOnce(3);
|
||||
|
||||
const result = await adminGetAllTenantsWithUsage({
|
||||
query: "user_query",
|
||||
properties: [{ name: "typeId", value: "type_pro" }],
|
||||
} as never);
|
||||
|
||||
const expectedWhere = {
|
||||
OR: [{ users: { some: { userId: "user_query" } } }, { types: { some: { id: "type_pro" } } }],
|
||||
};
|
||||
expect(dbMock.tenant.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
skip: undefined,
|
||||
take: undefined,
|
||||
where: expectedWhere,
|
||||
})
|
||||
);
|
||||
expect(result.pagination).toEqual({ page: 1, pageSize: 10, totalItems: 3, totalPages: 1 });
|
||||
});
|
||||
|
||||
it("throws a descriptive error when requireTenant cannot resolve a tenant", async () => {
|
||||
vi.mocked(dbMock.tenant.findUnique).mockResolvedValueOnce(null);
|
||||
|
||||
await expect(requireTenant("tenant_missing")).rejects.toThrow("Tenant not found: tenant_missing");
|
||||
});
|
||||
|
||||
it("returns null early for tenant-with-users and tenant-user lookups without ids", async () => {
|
||||
await expect(getTenantWithUsers()).resolves.toBeNull();
|
||||
await expect(getTenantUser()).resolves.toBeNull();
|
||||
|
||||
expect(dbMock.tenant.findUnique).not.toHaveBeenCalled();
|
||||
expect(dbMock.tenantUser.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns active member tenants and active tenant-user counts", async () => {
|
||||
vi.mocked(dbMock.tenant.findMany).mockResolvedValueOnce([{ id: "tenant_1" }] as never);
|
||||
vi.mocked(dbMock.tenantUser.count).mockResolvedValueOnce(7);
|
||||
|
||||
await expect(getMyTenants("user_1")).resolves.toEqual([{ id: "tenant_1" }]);
|
||||
await expect(getTenantUsersCount("tenant_1")).resolves.toBe(7);
|
||||
|
||||
expect(dbMock.tenant.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { active: true, users: { some: { userId: "user_1", status: TenantUserStatus.ACTIVE } } },
|
||||
orderBy: { name: "asc" },
|
||||
})
|
||||
);
|
||||
expect(dbMock.tenantUser.count).toHaveBeenCalledWith({
|
||||
where: { tenantId: "tenant_1", status: TenantUserStatus.ACTIVE },
|
||||
});
|
||||
});
|
||||
|
||||
it("scopes tenant users to active members and tenant-local role includes by default", async () => {
|
||||
vi.mocked(dbMock.tenantUser.findMany).mockResolvedValueOnce([{ id: "tu_1" }] as never);
|
||||
|
||||
await expect(getTenantUsers("tenant_1")).resolves.toEqual([{ id: "tu_1" }]);
|
||||
|
||||
expect(dbMock.tenantUser.findMany).toHaveBeenCalledWith({
|
||||
where: { tenantId: "tenant_1", status: TenantUserStatus.ACTIVE },
|
||||
include: {
|
||||
user: {
|
||||
include: {
|
||||
roles: { where: { tenantId: "tenant_1" }, include: { role: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("skips the active-member status filter when inactive members are requested", async () => {
|
||||
vi.mocked(dbMock.tenantUser.findMany).mockResolvedValueOnce([] as never);
|
||||
|
||||
await getTenantUsers("tenant_1", { includeInactive: true });
|
||||
|
||||
expect(dbMock.tenantUser.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { tenantId: "tenant_1" } }));
|
||||
});
|
||||
|
||||
it("returns an empty member list without touching the database when tenant id is blank", async () => {
|
||||
await expect(getTenantUsers(null)).resolves.toEqual([]);
|
||||
|
||||
expect(dbMock.tenantUser.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("adds tenant scope to tenant-user lookup only when a tenant id is provided", async () => {
|
||||
vi.mocked(dbMock.tenantUser.findFirst).mockResolvedValue({ id: "tu_1" } as never);
|
||||
|
||||
await getTenantUser("tu_1");
|
||||
await getTenantUser("tu_1", "tenant_1");
|
||||
|
||||
expect(dbMock.tenantUser.findFirst).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({ where: { id: "tu_1" } })
|
||||
);
|
||||
expect(dbMock.tenantUser.findFirst).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({ where: { id: "tu_1", tenantId: "tenant_1" } })
|
||||
);
|
||||
});
|
||||
|
||||
it("queries bulk and admin tenant-user projections with tenant-safe includes", async () => {
|
||||
vi.mocked(dbMock.tenantUser.findMany).mockResolvedValue([] as never);
|
||||
|
||||
await getTenantUsersInTenantIds(["tenant_1", "tenant_2"]);
|
||||
await getAllTenantUsers();
|
||||
|
||||
expect(dbMock.tenantUser.findMany).toHaveBeenNthCalledWith(1, {
|
||||
where: { tenantId: { in: ["tenant_1", "tenant_2"] } },
|
||||
include: {
|
||||
tenant: true,
|
||||
user: { select: expect.any(Object) },
|
||||
},
|
||||
});
|
||||
expect(dbMock.tenantUser.findMany).toHaveBeenNthCalledWith(2, {
|
||||
include: {
|
||||
user: {
|
||||
include: {
|
||||
admin: true,
|
||||
roles: { include: { role: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("queries tenant-user membership by composite identity and active member predicates", async () => {
|
||||
vi.mocked(dbMock.tenantUser.findFirst).mockResolvedValue({ id: "tu_1" } as never);
|
||||
|
||||
await getTenantUserByIds("tenant_1", "user_1");
|
||||
await getTenantMember("user_1", "tenant_1");
|
||||
await getTenantUserType("user_1", "tenant_1");
|
||||
|
||||
expect(dbMock.tenantUser.findFirst).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({ where: { tenantId: "tenant_1", userId: "user_1" } })
|
||||
);
|
||||
expect(dbMock.tenantUser.findFirst).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
where: { userId: "user_1", tenantId: "tenant_1", status: TenantUserStatus.ACTIVE, tenant: { active: true } },
|
||||
})
|
||||
);
|
||||
expect(dbMock.tenantUser.findFirst).toHaveBeenNthCalledWith(3, {
|
||||
where: { userId: "user_1", tenantId: "tenant_1", status: TenantUserStatus.ACTIVE, tenant: { active: true } },
|
||||
select: { status: true, type: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("caches tenant-user simple lookups and converts missing rows to null", async () => {
|
||||
vi.mocked(dbMock.tenantUser.findFirstOrThrow).mockRejectedValueOnce(new Error("not found"));
|
||||
|
||||
await expect(getTenantUserSimple({ tenantId: "tenant_1", userId: "user_1" })).resolves.toBeNull();
|
||||
|
||||
expect(cachified).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
key: "tenantUserSimple:tenant_1:user_1",
|
||||
ttl: 1000 * 60 * 60 * 24,
|
||||
})
|
||||
);
|
||||
expect(dbMock.tenantUser.findFirstOrThrow).toHaveBeenCalledWith({
|
||||
where: { tenantId: "tenant_1", userId: "user_1", status: TenantUserStatus.ACTIVE, tenant: { active: true } },
|
||||
select: { id: true, type: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("updates tenant profile data, tenant types, and all slug/id cache keys", async () => {
|
||||
vi.mocked(dbMock.tenant.update).mockResolvedValueOnce({ id: "tenant_1", slug: "new-slug" } as never);
|
||||
|
||||
await updateTenant(
|
||||
{ id: "tenant_1", slug: "old-slug" } as never,
|
||||
{ name: "Acme", icon: "icon", slug: "new-slug", typeIds: ["type_1", "type_2"] }
|
||||
);
|
||||
|
||||
expect(dbMock.tenant.update).toHaveBeenCalledWith({
|
||||
where: { id: "tenant_1" },
|
||||
data: {
|
||||
name: "Acme",
|
||||
icon: "icon",
|
||||
slug: "new-slug",
|
||||
types: { set: [{ id: "type_1" }, { id: "type_2" }] },
|
||||
},
|
||||
});
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("tenant:old-slug");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("tenant:tenant_1");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("tenantIdOrSlug:old-slug");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("tenantSimple:tenant_1");
|
||||
});
|
||||
|
||||
it("updates tenant theme and invalidates API-key tenant cache prefixes", async () => {
|
||||
vi.mocked(dbMock.tenant.update).mockResolvedValueOnce({ id: "tenant_1", slug: "acme" } as never);
|
||||
|
||||
await updateTenantTheme("tenant_1", { theme: "dark", themeConfig: "{\"accent\":\"blue\"}" });
|
||||
|
||||
expect(dbMock.tenant.update).toHaveBeenCalledWith({
|
||||
where: { id: "tenant_1" },
|
||||
data: { theme: "dark", themeConfig: "{\"accent\":\"blue\"}" },
|
||||
});
|
||||
expect(clearCacheKeyPrefix).toHaveBeenCalledWith("apiKeyHash:");
|
||||
});
|
||||
|
||||
it("adds a tenant type and clears tenant cache keys", async () => {
|
||||
vi.mocked(dbMock.tenant.update).mockResolvedValueOnce({ id: "tenant_1", slug: "acme" } as never);
|
||||
|
||||
await addTenantTypeToTenant("tenant_1", { typeId: "type_1" });
|
||||
|
||||
expect(dbMock.tenant.update).toHaveBeenCalledWith({
|
||||
where: { id: "tenant_1" },
|
||||
data: { types: { connect: { id: "type_1" } } },
|
||||
});
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("tenant:acme");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("tenant:tenant_1");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("tenantSimple:tenant_1");
|
||||
});
|
||||
|
||||
it("creates tenants inactive when requested and emits the tenant-created plugin hook", async () => {
|
||||
const createdAt = new Date("2026-05-25T12:00:00.000Z");
|
||||
vi.mocked(getAvailableTenantSlug).mockResolvedValueOnce("acme");
|
||||
vi.mocked(getAvailableTenantInboundAddress).mockResolvedValueOnce("acme@example.test");
|
||||
vi.mocked(dbMock.tenant.create).mockResolvedValueOnce({ id: "tenant_1", slug: "acme", createdAt } as never);
|
||||
|
||||
await createTenant({ name: "Acme", icon: "icon", active: false, slug: "acme" });
|
||||
|
||||
expect(dbMock.tenant.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
name: "Acme",
|
||||
slug: "acme",
|
||||
icon: "icon",
|
||||
active: false,
|
||||
inboundAddresses: { create: [{ address: "acme@example.test" }] },
|
||||
},
|
||||
});
|
||||
expect(createTenantSubscription).not.toHaveBeenCalled();
|
||||
expect(emitPluginHookFireAndForget).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: "tenant.created" }),
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
slug: "acme",
|
||||
ownerEmail: null,
|
||||
plan: null,
|
||||
createdAt: "2026-05-25T12:00:00.000Z",
|
||||
},
|
||||
{ tenantId: "tenant_1", dispatchKey: "tenant:tenant_1:created" }
|
||||
);
|
||||
});
|
||||
|
||||
it("defaults new tenants active and creates a subscription when a customer id is present", async () => {
|
||||
vi.mocked(getAvailableTenantSlug).mockResolvedValueOnce("acme");
|
||||
vi.mocked(getAvailableTenantInboundAddress).mockResolvedValueOnce("acme@example.test");
|
||||
vi.mocked(dbMock.tenant.create).mockResolvedValueOnce({
|
||||
id: "tenant_1",
|
||||
slug: "acme",
|
||||
createdAt: new Date("2026-05-25T12:00:00.000Z"),
|
||||
} as never);
|
||||
|
||||
await createTenant({ name: "Acme", subscriptionCustomerId: "cus_1" });
|
||||
|
||||
expect(dbMock.tenant.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ active: true }) }));
|
||||
expect(createTenantSubscription).toHaveBeenCalledWith("tenant_1", "cus_1");
|
||||
});
|
||||
|
||||
it("creates tenant users as active invited members and assigns each requested role", async () => {
|
||||
vi.mocked(dbMock.tenantUser.create).mockResolvedValueOnce({ id: "tu_1", tenantId: "tenant_1", userId: "user_1" } as never);
|
||||
|
||||
await createTenantUser(
|
||||
{ tenantId: "tenant_1", userId: "user_1", type: 0 },
|
||||
[{ id: "role_admin" }, { id: "role_member" }] as never
|
||||
);
|
||||
|
||||
expect(dbMock.tenantUser.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
type: 0,
|
||||
joined: TenantUserJoined.JOINED_BY_INVITATION,
|
||||
status: TenantUserStatus.ACTIVE,
|
||||
},
|
||||
});
|
||||
expect(createUserRole).toHaveBeenCalledWith("user_1", "role_admin", "tenant_1");
|
||||
expect(createUserRole).toHaveBeenCalledWith("user_1", "role_member", "tenant_1");
|
||||
});
|
||||
|
||||
it("does not delete cross-tenant membership when a tenant-scoped delete misses", async () => {
|
||||
vi.mocked(dbMock.tenantUser.findFirst).mockResolvedValueOnce(null);
|
||||
|
||||
await expect(deleteTenantUser("tu_1", "tenant_1")).resolves.toEqual({ count: 0 });
|
||||
|
||||
expect(dbMock.tenantUser.deleteMany).not.toHaveBeenCalled();
|
||||
expect(dbMock.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("deletes tenant-scoped membership, roles, groups, and user-role cache together", async () => {
|
||||
vi.mocked(dbMock.tenantUser.findFirst).mockResolvedValueOnce({ tenantId: "tenant_1", userId: "user_1" } as never);
|
||||
vi.mocked(dbMock.tenantUser.deleteMany).mockResolvedValueOnce({ count: 1 } as never);
|
||||
vi.mocked(dbMock.userRole.deleteMany).mockResolvedValueOnce({ count: 2 } as never);
|
||||
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 3 } as never);
|
||||
|
||||
await expect(deleteTenantUser("tu_1", "tenant_1")).resolves.toEqual({ count: 1 });
|
||||
|
||||
expect(dbMock.tenantUser.deleteMany).toHaveBeenCalledWith({ where: { id: "tu_1", tenantId: "tenant_1" } });
|
||||
expect(dbMock.userRole.deleteMany).toHaveBeenCalledWith({ where: { tenantId: "tenant_1", userId: "user_1" } });
|
||||
expect(dbMock.groupUser.deleteMany).toHaveBeenCalledWith({
|
||||
where: { userId: "user_1", group: { tenantId: "tenant_1" } },
|
||||
});
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:tenant_1");
|
||||
});
|
||||
|
||||
it("cleans role and group links after an unscoped tenant-user delete when the deleted row has a tenant", async () => {
|
||||
vi.mocked(dbMock.tenantUser.delete).mockResolvedValueOnce({ id: "tu_1", tenantId: "tenant_1", userId: "user_1" } as never);
|
||||
vi.mocked(dbMock.userRole.deleteMany).mockResolvedValueOnce({ count: 2 } as never);
|
||||
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 3 } as never);
|
||||
|
||||
await deleteTenantUser("tu_1");
|
||||
|
||||
expect(dbMock.$transaction).toHaveBeenCalledTimes(1);
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:tenant_1");
|
||||
});
|
||||
|
||||
it("returns an unscoped tenant-user delete without cleanup when the deleted row has no tenant", async () => {
|
||||
vi.mocked(dbMock.tenantUser.delete).mockResolvedValueOnce({ id: "tu_1", tenantId: null, userId: "user_1" } as never);
|
||||
|
||||
await expect(deleteTenantUser("tu_1")).resolves.toEqual({ id: "tu_1", tenantId: null, userId: "user_1" });
|
||||
|
||||
expect(dbMock.$transaction).not.toHaveBeenCalled();
|
||||
expect(clearCacheKey).not.toHaveBeenCalledWith("userRoles:user_1:null");
|
||||
});
|
||||
|
||||
it("deletes tenants with dependent records included", async () => {
|
||||
vi.mocked(dbMock.tenant.delete).mockResolvedValueOnce({ id: "tenant_1" } as never);
|
||||
|
||||
await deleteTenant("tenant_1");
|
||||
|
||||
expect(dbMock.tenant.delete).toHaveBeenCalledWith({
|
||||
where: { id: "tenant_1" },
|
||||
include: {
|
||||
subscription: true,
|
||||
users: true,
|
||||
invitations: true,
|
||||
rows: true,
|
||||
logs: true,
|
||||
apiKeys: true,
|
||||
userRoles: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("updates deactivation state and clears tenant identity cache keys", async () => {
|
||||
vi.mocked(dbMock.tenant.update).mockResolvedValueOnce({ id: "tenant_1", slug: "acme" } as never);
|
||||
|
||||
await updateTenantDeactivated("tenant_1", { active: false, deactivatedReason: "billing" });
|
||||
|
||||
expect(dbMock.tenant.update).toHaveBeenCalledWith({
|
||||
where: { id: "tenant_1" },
|
||||
data: { active: false, deactivatedReason: "billing" },
|
||||
});
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("tenant:acme");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("tenant:tenant_1");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("tenantIdOrSlug:acme");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("tenantSimple:tenant_1");
|
||||
});
|
||||
|
||||
it("lists tenants without assigned types", async () => {
|
||||
vi.mocked(dbMock.tenant.findMany).mockResolvedValueOnce([] as never);
|
||||
|
||||
await getAllTenantsWithoutTypes();
|
||||
|
||||
expect(dbMock.tenant.findMany).toHaveBeenCalledWith({ where: { types: { none: {} } } });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,638 @@
|
||||
import { Prisma, Role, Tenant, TenantInboundAddress, TenantSettingsRow, TenantType, TenantUser } from "@toolctrl/db/prisma-browser";
|
||||
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { TenantUserJoined } from "~/application/enums/tenants/TenantUserJoined";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import { db, dbRead } from "~/utils/db.server";
|
||||
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
|
||||
import RowFiltersHelper from "../helpers/RowFiltersHelper";
|
||||
import { getAvailableTenantInboundAddress } from "../services/emailService";
|
||||
import { createUserRole } from "./permissions/userRoles.db.server";
|
||||
import { TenantSubscriptionWithDetails, createTenantSubscription } from "./tenantSubscriptions.db.server";
|
||||
import { UserSimple, UserWithRoles } from "./users.db.server";
|
||||
import { RowWithDetails } from "./entities/rows.db.server";
|
||||
import { getAvailableTenantSlug } from "../services/tenantService";
|
||||
import RowModelHelper from "../helpers/models/RowModelHelper";
|
||||
import TenantModelHelper from "../helpers/models/TenantModelHelper";
|
||||
import TenantSubscriptionProductModelHelper from "../helpers/models/TenantSubscriptionProductModelHelper";
|
||||
import { cachified, clearCacheKey, clearCacheKeyPrefix } from "../cache.server";
|
||||
import { emitPluginHookFireAndForget } from "~/modules/plugins/services/.server/pluginHookPublisher";
|
||||
import { PLUGIN_HOOK_TENANT_CREATED } from "@toolctrl/plugin-runtime";
|
||||
|
||||
export type TenantSimple = {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
icon: string | null;
|
||||
logo: string | null;
|
||||
deactivatedReason: string | null;
|
||||
types: TenantType[];
|
||||
active: boolean;
|
||||
theme: string | null;
|
||||
themeConfig: string | null;
|
||||
};
|
||||
|
||||
export type TenantWithProfile = Tenant & {
|
||||
types: TenantType[];
|
||||
};
|
||||
|
||||
export type TenantWithDetails = Tenant & {
|
||||
inboundAddresses: TenantInboundAddress[];
|
||||
users: (TenantUser & {
|
||||
user: UserSimple;
|
||||
})[];
|
||||
subscription: TenantSubscriptionWithDetails | null;
|
||||
tenantSettingsRow: (TenantSettingsRow & { row: RowWithDetails }) | null;
|
||||
types: TenantType[];
|
||||
};
|
||||
|
||||
export type TenantWithUsage = TenantWithDetails & {
|
||||
_count: {
|
||||
users?: number;
|
||||
invitations?: number;
|
||||
rows?: number;
|
||||
logs?: number;
|
||||
apiKeys?: number;
|
||||
events?: number;
|
||||
};
|
||||
};
|
||||
|
||||
export type TenantUserWithUser = TenantUser & {
|
||||
user: UserWithRoles;
|
||||
};
|
||||
|
||||
export type TenantUserWithDetails = TenantUser & {
|
||||
tenant: Tenant;
|
||||
user: UserSimple;
|
||||
};
|
||||
|
||||
export async function getTenantsInIds(ids: string[]): Promise<TenantWithDetails[]> {
|
||||
return await db.tenant.findMany({
|
||||
where: { id: { in: ids } },
|
||||
include: {
|
||||
...TenantModelHelper.includeTenantWithDetails,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function adminGetAllTenants(): Promise<TenantWithDetails[]> {
|
||||
return await db.tenant.findMany({
|
||||
include: {
|
||||
...TenantModelHelper.includeTenantWithDetails,
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}
|
||||
|
||||
export async function adminGetAllTenantsIdsAndNames(): Promise<{ id: string; name: string; slug: string }[]> {
|
||||
// Admin-only enumeration used for picklists and audit views — replica-safe.
|
||||
// Called AFTER auth has already resolved the admin user via the write client,
|
||||
// so the replica-lag read-after-write hazard does not apply here.
|
||||
return await dbRead.tenant.findMany({
|
||||
select: { id: true, name: true, slug: true },
|
||||
});
|
||||
}
|
||||
|
||||
export async function adminGetAllActiveTenantSimple(): Promise<TenantSimple[]> {
|
||||
// Admin tenant-switcher listing used post-auth — replica-safe.
|
||||
// The admin user identity itself was loaded on the write client in the
|
||||
// session-resolution path; this enumeration is purely informational.
|
||||
return await dbRead.tenant.findMany({
|
||||
where: { active: true },
|
||||
select: TenantModelHelper.selectSimpleTenantProperties,
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
}
|
||||
|
||||
export async function adminGetAllTenantsWithUsage(
|
||||
filters?: FiltersDto,
|
||||
pagination?: { page: number; pageSize: number }
|
||||
): Promise<{ items: TenantWithUsage[]; pagination: PaginationDto }> {
|
||||
let where: Prisma.TenantWhereInput = RowFiltersHelper.getFiltersCondition(filters);
|
||||
const userId = filters?.properties.find((f) => f.name === "userId")?.value ?? filters?.query ?? "";
|
||||
if (userId) {
|
||||
if (where) {
|
||||
where = {
|
||||
OR: [where, { users: { some: { userId } } }],
|
||||
};
|
||||
} else {
|
||||
where = { users: { some: { userId } } };
|
||||
}
|
||||
}
|
||||
const typeId = filters?.properties.find((f) => f.name === "typeId")?.value;
|
||||
if (typeId) {
|
||||
if (where) {
|
||||
if (typeId === "null") {
|
||||
where = {
|
||||
OR: [where, { types: { none: {} } }],
|
||||
};
|
||||
} else {
|
||||
where = {
|
||||
OR: [where, { types: { some: { id: typeId } } }],
|
||||
};
|
||||
}
|
||||
} else {
|
||||
if (typeId === "null") {
|
||||
where = { types: { none: {} } };
|
||||
} else {
|
||||
where = { types: { some: { id: typeId } } };
|
||||
}
|
||||
}
|
||||
}
|
||||
const items = await db.tenant.findMany({
|
||||
skip: pagination ? pagination?.pageSize * (pagination?.page - 1) : undefined,
|
||||
take: pagination ? pagination?.pageSize : undefined,
|
||||
where,
|
||||
include: {
|
||||
inboundAddresses: true,
|
||||
users: {
|
||||
include: {
|
||||
...UserModelHelper.includeSimpleUser,
|
||||
},
|
||||
},
|
||||
subscription: {
|
||||
include: {
|
||||
products: { include: { ...TenantSubscriptionProductModelHelper.includeTenantSubscriptionProductDetails } },
|
||||
},
|
||||
},
|
||||
tenantSettingsRow: { include: { row: { include: RowModelHelper.includeRowDetails } } },
|
||||
types: true,
|
||||
_count: true,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
});
|
||||
const totalItems = await db.tenant.count({
|
||||
where,
|
||||
});
|
||||
return {
|
||||
items,
|
||||
pagination: {
|
||||
page: pagination?.page ?? 1,
|
||||
pageSize: pagination?.pageSize ?? 10,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / (pagination?.pageSize ?? 10)),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function getTenant(id: string): Promise<TenantWithDetails | null> {
|
||||
return await cachified({
|
||||
key: `tenant:${id}`,
|
||||
ttl: 1000 * 60 * 60 * 24,
|
||||
getFreshValue: () =>
|
||||
db.tenant.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
include: {
|
||||
...TenantModelHelper.includeTenantWithDetails,
|
||||
},
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export async function requireTenant(id: string): Promise<TenantWithDetails> {
|
||||
const tenant = await getTenant(id);
|
||||
if (!tenant) {
|
||||
throw new Error("Tenant not found: " + id);
|
||||
}
|
||||
return tenant;
|
||||
}
|
||||
|
||||
export async function getTenantSimple(id: string): Promise<TenantSimple | null> {
|
||||
return await cachified({
|
||||
key: `tenantSimple:${id}`,
|
||||
ttl: 1000 * 60 * 60 * 24,
|
||||
getFreshValue: () =>
|
||||
db.tenant.findUnique({
|
||||
where: { id },
|
||||
select: TenantModelHelper.selectSimpleTenantProperties,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantByIdOrSlug(id: string) {
|
||||
return await cachified({
|
||||
key: `tenantIdOrSlug:${id}`,
|
||||
ttl: 1000 * 60 * 60 * 24,
|
||||
getFreshValue: () =>
|
||||
db.tenant.findFirst({
|
||||
where: {
|
||||
OR: [{ id }, { slug: id }],
|
||||
},
|
||||
include: {
|
||||
subscription: true,
|
||||
},
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantBySlug(slug: string) {
|
||||
return await db.tenant.findUnique({
|
||||
where: {
|
||||
slug,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantWithProfile(id: string): Promise<TenantWithProfile | null> {
|
||||
return await db.tenant.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
types: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantWithUsers(id?: string) {
|
||||
if (!id) {
|
||||
return null;
|
||||
}
|
||||
return await db.tenant.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
include: {
|
||||
users: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getMyTenants(userId: string): Promise<TenantSimple[]> {
|
||||
const tenantsAsMember = await db.tenant.findMany({
|
||||
where: { active: true, users: { some: { userId, status: TenantUserStatus.ACTIVE } } },
|
||||
select: TenantModelHelper.selectSimpleTenantProperties,
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
|
||||
// await Promise.all(tenantsAsMember.map(async(tenant) => {
|
||||
// const relatedTenants = await db.tenantRelationship.findFirst({
|
||||
// where: { fromTenantId: tenant.id },
|
||||
// include: { toTenant: true },
|
||||
// });
|
||||
// }));
|
||||
|
||||
return [...tenantsAsMember];
|
||||
}
|
||||
|
||||
export async function getTenantUsersCount(tenantId: string) {
|
||||
return await db.tenantUser.count({
|
||||
where: { tenantId, status: TenantUserStatus.ACTIVE },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantUsers(tenantId?: string | null, options: { includeInactive?: boolean } = {}): Promise<TenantUserWithUser[]> {
|
||||
if (!tenantId) {
|
||||
return [];
|
||||
}
|
||||
return await db.tenantUser.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
...(options.includeInactive ? {} : { status: TenantUserStatus.ACTIVE }),
|
||||
},
|
||||
include: {
|
||||
user: {
|
||||
include: {
|
||||
roles: { where: { tenantId }, include: { role: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantUsersInTenantIds(tenantIds: string[]): Promise<TenantUserWithDetails[]> {
|
||||
return await db.tenantUser.findMany({
|
||||
where: {
|
||||
tenantId: { in: tenantIds },
|
||||
},
|
||||
include: {
|
||||
tenant: true,
|
||||
user: { select: UserModelHelper.selectSimpleUserProperties },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAllTenantUsers(): Promise<TenantUserWithUser[]> {
|
||||
return await db.tenantUser.findMany({
|
||||
include: {
|
||||
user: {
|
||||
include: {
|
||||
admin: true,
|
||||
roles: { include: { role: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantUser(id?: string, tenantId?: string) {
|
||||
if (!id) {
|
||||
return null;
|
||||
}
|
||||
return await db.tenantUser.findFirst({
|
||||
where: {
|
||||
id,
|
||||
...(tenantId ? { tenantId } : {}),
|
||||
},
|
||||
include: {
|
||||
tenant: true,
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantUserByIds(tenantId: string, userId: string) {
|
||||
return await db.tenantUser.findFirst({
|
||||
where: {
|
||||
tenantId,
|
||||
userId,
|
||||
},
|
||||
include: {
|
||||
tenant: true,
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantUserSimple({ tenantId, userId }: { tenantId: string; userId: string }) {
|
||||
return await cachified({
|
||||
key: `tenantUserSimple:${tenantId}:${userId}`,
|
||||
ttl: 1000 * 60 * 60 * 24, // 1 day
|
||||
getFreshValue: () =>
|
||||
db.tenantUser
|
||||
.findFirstOrThrow({
|
||||
where: { tenantId, userId, status: TenantUserStatus.ACTIVE, tenant: { active: true } },
|
||||
select: { id: true, type: true },
|
||||
})
|
||||
.catch(() => null),
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantMember(userId?: string, tenantId?: string) {
|
||||
return await db.tenantUser.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
tenantId,
|
||||
status: TenantUserStatus.ACTIVE,
|
||||
tenant: { active: true },
|
||||
},
|
||||
include: {
|
||||
tenant: true,
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantUserType(userId: string, tenantId: string) {
|
||||
return await db.tenantUser.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
tenantId,
|
||||
status: TenantUserStatus.ACTIVE,
|
||||
tenant: {
|
||||
active: true,
|
||||
},
|
||||
},
|
||||
select: { status: true, type: true },
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateTenant(before: Tenant, data: { name?: string; icon?: string; slug?: string; typeIds?: string[] }) {
|
||||
const update: Prisma.TenantUncheckedUpdateInput = {
|
||||
name: data.name,
|
||||
icon: data.icon,
|
||||
slug: data.slug,
|
||||
};
|
||||
if (data.typeIds) {
|
||||
update.types = { set: data.typeIds.map((type) => ({ id: type })) };
|
||||
}
|
||||
return await db.tenant
|
||||
.update({
|
||||
where: {
|
||||
id: before.id,
|
||||
},
|
||||
data: update,
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`tenant:${before.slug}`);
|
||||
clearCacheKey(`tenant:${before.id}`);
|
||||
clearCacheKey(`tenantIdOrSlug:${before.id}`);
|
||||
clearCacheKey(`tenantIdOrSlug:${before.slug}`);
|
||||
clearCacheKey(`tenantSimple:${before.id}`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateTenantTheme(id: string, data: { theme: string | null; themeConfig: string | null }) {
|
||||
return await db.tenant
|
||||
.update({
|
||||
where: { id },
|
||||
data: {
|
||||
theme: data.theme,
|
||||
themeConfig: data.themeConfig,
|
||||
},
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`tenant:${item.slug}`);
|
||||
clearCacheKey(`tenant:${item.id}`);
|
||||
clearCacheKey(`tenantIdOrSlug:${item.id}`);
|
||||
clearCacheKey(`tenantIdOrSlug:${item.slug}`);
|
||||
clearCacheKey(`tenantSimple:${item.id}`);
|
||||
clearCacheKeyPrefix("apiKeyHash:");
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function addTenantTypeToTenant(id: string, data: { typeId: string }) {
|
||||
return await db.tenant
|
||||
.update({
|
||||
where: { id },
|
||||
data: { types: { connect: { id: data.typeId } } },
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`tenant:${item.slug}`);
|
||||
clearCacheKey(`tenant:${item.id}`);
|
||||
clearCacheKey(`tenantSimple:${item.id}`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function createTenant({
|
||||
name,
|
||||
icon,
|
||||
subscriptionCustomerId,
|
||||
active,
|
||||
slug,
|
||||
}: {
|
||||
name: string;
|
||||
icon?: string;
|
||||
subscriptionCustomerId?: string | undefined;
|
||||
active?: boolean;
|
||||
slug?: string;
|
||||
}) {
|
||||
slug = await getAvailableTenantSlug({ name, slug });
|
||||
const inboundAddress = await getAvailableTenantInboundAddress(name);
|
||||
const tenant = await db.tenant.create({
|
||||
data: {
|
||||
name,
|
||||
slug,
|
||||
icon,
|
||||
active: active ?? true,
|
||||
inboundAddresses: {
|
||||
create: [{ address: inboundAddress }],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (subscriptionCustomerId) {
|
||||
await createTenantSubscription(tenant.id, subscriptionCustomerId);
|
||||
}
|
||||
|
||||
// Phase 06 #22 — emit plugin hook `tenant.created` so installed
|
||||
// plugins subscribed to the tenant lifecycle can react. Fire-and-
|
||||
// forget: hook delivery failures never propagate into tenant create.
|
||||
await emitPluginHookFireAndForget(
|
||||
PLUGIN_HOOK_TENANT_CREATED,
|
||||
{
|
||||
tenantId: tenant.id,
|
||||
slug: tenant.slug,
|
||||
ownerEmail: null,
|
||||
plan: null,
|
||||
createdAt: tenant.createdAt.toISOString(),
|
||||
},
|
||||
{ tenantId: tenant.id, dispatchKey: `tenant:${tenant.id}:created` }
|
||||
);
|
||||
|
||||
return tenant;
|
||||
}
|
||||
|
||||
export async function createTenantUser(data: { tenantId: string; userId: string; type: number }, roles: Role[]) {
|
||||
const tenantUser = await db.tenantUser.create({
|
||||
data: {
|
||||
...data,
|
||||
joined: TenantUserJoined.JOINED_BY_INVITATION,
|
||||
status: TenantUserStatus.ACTIVE,
|
||||
},
|
||||
});
|
||||
|
||||
await Promise.all(
|
||||
roles.map(async (role) => {
|
||||
return await createUserRole(tenantUser.userId, role.id, tenantUser.tenantId);
|
||||
})
|
||||
);
|
||||
|
||||
return tenantUser;
|
||||
}
|
||||
|
||||
export async function deleteTenantUser(id: string, tenantId?: string) {
|
||||
if (tenantId) {
|
||||
const tenantUser = await db.tenantUser.findFirst({
|
||||
where: {
|
||||
id,
|
||||
tenantId,
|
||||
},
|
||||
select: {
|
||||
tenantId: true,
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!tenantUser) {
|
||||
return { count: 0 };
|
||||
}
|
||||
|
||||
const [deleted] = await db.$transaction([
|
||||
db.tenantUser.deleteMany({
|
||||
where: {
|
||||
id,
|
||||
tenantId,
|
||||
},
|
||||
}),
|
||||
db.userRole.deleteMany({
|
||||
where: {
|
||||
tenantId: tenantUser.tenantId,
|
||||
userId: tenantUser.userId,
|
||||
},
|
||||
}),
|
||||
db.groupUser.deleteMany({
|
||||
where: {
|
||||
userId: tenantUser.userId,
|
||||
group: {
|
||||
tenantId: tenantUser.tenantId,
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
clearCacheKey(`userRoles:${tenantUser.userId}:${tenantUser.tenantId}`);
|
||||
return deleted;
|
||||
}
|
||||
|
||||
const deleted = await db.tenantUser.delete({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
if (deleted.tenantId) {
|
||||
await db.$transaction([
|
||||
db.userRole.deleteMany({
|
||||
where: {
|
||||
tenantId: deleted.tenantId,
|
||||
userId: deleted.userId,
|
||||
},
|
||||
}),
|
||||
db.groupUser.deleteMany({
|
||||
where: {
|
||||
userId: deleted.userId,
|
||||
group: {
|
||||
tenantId: deleted.tenantId,
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
clearCacheKey(`userRoles:${deleted.userId}:${deleted.tenantId}`);
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
|
||||
export async function deleteTenant(id: string) {
|
||||
return await db.tenant.delete({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
include: {
|
||||
subscription: true,
|
||||
users: true,
|
||||
invitations: true,
|
||||
rows: true,
|
||||
logs: true,
|
||||
apiKeys: true,
|
||||
userRoles: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateTenantDeactivated(id: string, data: { active: boolean; deactivatedReason: string | null }) {
|
||||
return await db.tenant
|
||||
.update({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
data,
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`tenant:${item.slug}`);
|
||||
clearCacheKey(`tenant:${item.id}`);
|
||||
clearCacheKey(`tenantIdOrSlug:${item.id}`);
|
||||
clearCacheKey(`tenantIdOrSlug:${item.slug}`);
|
||||
clearCacheKey(`tenantSimple:${item.id}`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAllTenantsWithoutTypes() {
|
||||
return await db.tenant.findMany({
|
||||
where: { types: { none: {} } },
|
||||
});
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const createUniqueTenantIpAddressRecord = vi.fn();
|
||||
|
||||
vi.mock("@toolctrl/db/auth-boundary.server", () => ({
|
||||
createUniqueTenantIpAddressRecord,
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: {
|
||||
tenantIpAddress: {
|
||||
findMany: vi.fn(),
|
||||
count: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/models/UserModelHelper", () => ({
|
||||
default: { selectSimpleUserProperties: { id: true } },
|
||||
}));
|
||||
|
||||
vi.mock("~/application/Constants", () => ({
|
||||
default: { DEFAULT_PAGE_SIZE: 10 },
|
||||
}));
|
||||
|
||||
describe("createUniqueTenantIpAddress", () => {
|
||||
beforeEach(() => {
|
||||
createUniqueTenantIpAddressRecord.mockReset();
|
||||
});
|
||||
|
||||
it("delegates tenant shell IP writes through the auth boundary", async () => {
|
||||
const data = {
|
||||
ip: "127.0.0.1",
|
||||
fromUrl: "/acme",
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
apiKeyId: null,
|
||||
};
|
||||
createUniqueTenantIpAddressRecord.mockResolvedValue({ id: "ip_1" });
|
||||
|
||||
const { createUniqueTenantIpAddress } = await import("./tenantIpAddress.db.server");
|
||||
|
||||
await expect(createUniqueTenantIpAddress(data)).resolves.toEqual({ id: "ip_1" });
|
||||
expect(createUniqueTenantIpAddressRecord).toHaveBeenCalledWith(data);
|
||||
});
|
||||
});
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
import { createUniqueTenantIpAddressRecord } from "@toolctrl/db/auth-boundary.server";
|
||||
import { ApiKey, Tenant, TenantIpAddress } from "@toolctrl/db/prisma-browser";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { UserSimple } from "../users.db.server";
|
||||
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import Constants from "~/application/Constants";
|
||||
|
||||
export type TenantIpAddressWithDetails = TenantIpAddress & {
|
||||
tenant: Tenant;
|
||||
user: UserSimple | null;
|
||||
apiKey: ApiKey | null;
|
||||
};
|
||||
|
||||
export async function getAllTenantIpAddresses(pagination?: {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}): Promise<{ items: TenantIpAddressWithDetails[]; pagination: PaginationDto }> {
|
||||
const items = await db.tenantIpAddress.findMany({
|
||||
skip: pagination ? pagination?.pageSize * (pagination?.page - 1) : undefined,
|
||||
take: pagination ? pagination?.pageSize : undefined,
|
||||
include: {
|
||||
tenant: true,
|
||||
user: {
|
||||
select: UserModelHelper.selectSimpleUserProperties,
|
||||
},
|
||||
apiKey: true,
|
||||
},
|
||||
orderBy: [
|
||||
{
|
||||
createdAt: "desc",
|
||||
},
|
||||
],
|
||||
});
|
||||
const totalItems = await db.tenantIpAddress.count({});
|
||||
|
||||
return {
|
||||
items,
|
||||
pagination: {
|
||||
page: pagination?.page ?? 1,
|
||||
pageSize: pagination?.pageSize ?? Constants.DEFAULT_PAGE_SIZE,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / (pagination?.pageSize ?? Constants.DEFAULT_PAGE_SIZE)),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function createUniqueTenantIpAddress(data: { ip: string; fromUrl: string; tenantId: string; userId?: string | null; apiKeyId?: string | null }) {
|
||||
return createUniqueTenantIpAddressRecord(data);
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tenantTypeFindMany: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: {
|
||||
tenantType: {
|
||||
findMany: mocks.tenantTypeFindMany,
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { getTenantTypeOptions } from "./tenantTypes.db.server";
|
||||
|
||||
describe("tenant type db helpers", () => {
|
||||
beforeEach(() => {
|
||||
mocks.tenantTypeFindMany.mockReset();
|
||||
mocks.tenantTypeFindMany.mockResolvedValue([
|
||||
{ id: "type_1", title: "Workspace" },
|
||||
{ id: "type_2", title: "Customer" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("loads lightweight tenant type options for account forms", async () => {
|
||||
await expect(getTenantTypeOptions()).resolves.toEqual([
|
||||
{ id: "type_1", title: "Workspace" },
|
||||
{ id: "type_2", title: "Customer" },
|
||||
]);
|
||||
|
||||
expect(mocks.tenantTypeFindMany).toHaveBeenCalledWith({
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "asc",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
import { Prisma, SubscriptionProduct, TenantType } from "@toolctrl/db/prisma-browser";
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
export type TenantTypeWithDetails = TenantType & {
|
||||
subscriptionProducts: SubscriptionProduct[];
|
||||
_count: { tenants: number };
|
||||
};
|
||||
const includeDetails = {
|
||||
subscriptionProducts: true,
|
||||
_count: { select: { tenants: true } },
|
||||
};
|
||||
export async function getAllTenantTypes(): Promise<TenantTypeWithDetails[]> {
|
||||
return await db.tenantType.findMany({
|
||||
include: {
|
||||
subscriptionProducts: true,
|
||||
_count: { select: { tenants: true } },
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "asc",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantTypeOptions(): Promise<Array<Pick<TenantType, "id" | "title">>> {
|
||||
return await db.tenantType.findMany({
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "asc",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getDefaultTenantTypes() {
|
||||
return await db.tenantType.findMany({
|
||||
where: { isDefault: true },
|
||||
orderBy: {
|
||||
createdAt: "asc",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantType(id: string): Promise<TenantTypeWithDetails | null> {
|
||||
return await db.tenantType.findUnique({
|
||||
where: { id: id },
|
||||
include: includeDetails,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantTypeByTitle(title: string): Promise<TenantTypeWithDetails | null> {
|
||||
return await db.tenantType.findUnique({
|
||||
where: { title },
|
||||
include: includeDetails,
|
||||
});
|
||||
}
|
||||
|
||||
export async function createTenantType(data: {
|
||||
title: string;
|
||||
titlePlural: string;
|
||||
description: string | null;
|
||||
isDefault?: boolean;
|
||||
subscriptionProducts: string[];
|
||||
}) {
|
||||
return await db.tenantType.create({
|
||||
data: {
|
||||
title: data.title,
|
||||
titlePlural: data.titlePlural,
|
||||
description: data.description,
|
||||
isDefault: data.isDefault,
|
||||
subscriptionProducts: {
|
||||
connect: data.subscriptionProducts.map((id) => ({ id })),
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateTenantType(
|
||||
id: string,
|
||||
data: {
|
||||
title?: string;
|
||||
titlePlural?: string;
|
||||
description?: string | null;
|
||||
isDefault?: boolean;
|
||||
subscriptionProducts?: string[];
|
||||
}
|
||||
) {
|
||||
const update: Prisma.TenantTypeUncheckedUpdateInput = {
|
||||
title: data.title,
|
||||
titlePlural: data.titlePlural,
|
||||
description: data.description,
|
||||
isDefault: data.isDefault,
|
||||
};
|
||||
if (data.subscriptionProducts) {
|
||||
update.subscriptionProducts = {
|
||||
set: data.subscriptionProducts.map((id) => ({ id })),
|
||||
};
|
||||
}
|
||||
return await db.tenantType.update({
|
||||
where: { id: id },
|
||||
data: update,
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteTenantType(id: string) {
|
||||
return await db.tenantType.delete({
|
||||
where: { id: id },
|
||||
});
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import path from "node:path";
|
||||
|
||||
const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "users.db.server.ts"), "utf8");
|
||||
|
||||
describe("users db wrapper", () => {
|
||||
test("allows user profile updates to persist light or dark mode", () => {
|
||||
expect(source).toContain("lightOrDarkMode?: string");
|
||||
});
|
||||
|
||||
test("provides a tenant-scoped user details helper for app routes", () => {
|
||||
expect(source).toContain("export async function getTenantScopedUsersWithDetails(tenantId: string)");
|
||||
expect(source).toContain("tenants: {\n where: {\n tenantId,\n },");
|
||||
expect(source).toContain("roles: {\n where: {\n tenantId,\n },");
|
||||
});
|
||||
|
||||
test("keeps core user registration free of CRM and marketing side effects", () => {
|
||||
expect(source).not.toContain("~/modules/crm/services/CrmService");
|
||||
expect(source).not.toContain("marketingSubscriber: true");
|
||||
expect(source).not.toContain("Created user contact");
|
||||
});
|
||||
|
||||
test("returns the persisted default tenant after user registration", () => {
|
||||
expect(source).toContain("defaultTenantId: user.defaultTenantId");
|
||||
});
|
||||
|
||||
test("parallelizes admin user pagination queries", () => {
|
||||
expect(source).toContain("const [items, totalItems] = await Promise.all([");
|
||||
expect(source).toContain("db.user.findMany({");
|
||||
expect(source).toContain("db.user.count({\n where,\n }),");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,719 @@
|
||||
import { AdminUser, Role, Tenant, TenantUser, UserRole } from "@toolctrl/db/prisma-browser";
|
||||
import { consumeRecoveryCode, getRecoveryCodeStatus, RecoveryCodeHashEntry } from "~/utils/auth/mfa/recovery-codes.server";
|
||||
import { hashPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import Constants from "~/application/Constants";
|
||||
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { db } from "~/utils/db.server";
|
||||
import RowFiltersHelper from "../helpers/RowFiltersHelper";
|
||||
import { SortedByDto } from "~/application/dtos/data/SortedByDto";
|
||||
import { Prisma } from "@toolctrl/db/prisma-browser";
|
||||
import DateUtils from "../shared/DateUtils";
|
||||
import { DefaultLogActions } from "~/application/dtos/shared/DefaultLogActions";
|
||||
import { cachified, clearCacheKey } from "../cache.server";
|
||||
import { createScopedLogger } from "../logger.server";
|
||||
import { emitPluginHookFireAndForget } from "~/modules/plugins/services/.server/pluginHookPublisher";
|
||||
import { PLUGIN_HOOK_USER_CREATED } from "@toolctrl/plugin-runtime";
|
||||
|
||||
const usersLogger = createScopedLogger("db.users");
|
||||
|
||||
export type UserSimple = {
|
||||
id: string;
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
// avatar: string | null;
|
||||
phone: string | null;
|
||||
locale: string | null;
|
||||
createdAt: Date;
|
||||
};
|
||||
export type UserWithNames = {
|
||||
id: string;
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
};
|
||||
export type UserWithoutPassword = {
|
||||
id: string;
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
avatar: string | null;
|
||||
phone: string | null;
|
||||
admin?: AdminUser | null;
|
||||
defaultTenantId: string | null;
|
||||
createdAt: Date;
|
||||
locale: string | null;
|
||||
lightOrDarkMode?: string | null;
|
||||
};
|
||||
export type UserWithRoles = UserSimple & {
|
||||
admin?: AdminUser | null;
|
||||
roles: (UserRole & { role: Role })[];
|
||||
};
|
||||
|
||||
export type UserTotpStatus = {
|
||||
enabled: boolean;
|
||||
pending: boolean;
|
||||
enabledAt: Date | null;
|
||||
pendingCreatedAt: Date | null;
|
||||
};
|
||||
|
||||
export type UserTotpPendingEnrollment = {
|
||||
totpPendingSecretEncrypted: string | null;
|
||||
totpPendingCreatedAt: Date | null;
|
||||
};
|
||||
|
||||
export type UserMfaRecoveryCodeStatus = {
|
||||
configured: boolean;
|
||||
remainingCount: number;
|
||||
generatedAt: Date | null;
|
||||
lastUsedAt: Date | null;
|
||||
};
|
||||
|
||||
export type UserMfaRecoveryCodeConsumeResult = {
|
||||
consumed: boolean;
|
||||
remainingCount: number;
|
||||
usedAt: Date | null;
|
||||
};
|
||||
|
||||
export type UserWithDetails = UserWithoutPassword & {
|
||||
admin: AdminUser | null;
|
||||
tenants: (TenantUser & { tenant: Tenant })[];
|
||||
roles: (UserRole & { role: Role })[];
|
||||
};
|
||||
|
||||
export const includeCreatedBy = {
|
||||
byUser: {
|
||||
select: { id: true, email: true, firstName: true, lastName: true },
|
||||
},
|
||||
byApiKey: {
|
||||
select: { id: true, alias: true },
|
||||
},
|
||||
byEmail: {
|
||||
select: { id: true, subject: true },
|
||||
},
|
||||
byEventWebhookAttempt: {
|
||||
select: { id: true, endpoint: true, message: true },
|
||||
},
|
||||
};
|
||||
|
||||
export async function adminGetAllTenantUsers(tenantId: string): Promise<UserWithDetails[]> {
|
||||
return db.user.findMany({
|
||||
where: {
|
||||
tenants: {
|
||||
some: {
|
||||
tenantId,
|
||||
},
|
||||
},
|
||||
},
|
||||
include: {
|
||||
admin: true,
|
||||
tenants: {
|
||||
include: {
|
||||
tenant: true,
|
||||
},
|
||||
},
|
||||
roles: {
|
||||
include: {
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantScopedUsersWithDetails(tenantId: string): Promise<UserWithDetails[]> {
|
||||
return db.user.findMany({
|
||||
where: {
|
||||
tenants: {
|
||||
some: {
|
||||
tenantId,
|
||||
},
|
||||
},
|
||||
},
|
||||
include: {
|
||||
admin: true,
|
||||
tenants: {
|
||||
where: {
|
||||
tenantId,
|
||||
},
|
||||
include: {
|
||||
tenant: true,
|
||||
},
|
||||
},
|
||||
roles: {
|
||||
where: {
|
||||
tenantId,
|
||||
},
|
||||
include: {
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function adminGetAllUsers(
|
||||
filters?: FiltersDto,
|
||||
pagination?: { page: number; pageSize: number; sortedBy?: SortedByDto[] }
|
||||
): Promise<{ items: UserWithDetails[]; pagination: PaginationDto }> {
|
||||
let where: Prisma.UserWhereInput = RowFiltersHelper.getFiltersCondition(filters);
|
||||
const tenantId = filters?.properties.find((f) => f.name === "tenantId")?.value ?? filters?.query ?? "";
|
||||
if (tenantId) {
|
||||
where = {
|
||||
OR: [where, { tenants: { some: { tenantId } } }],
|
||||
};
|
||||
}
|
||||
// lastLogin manual filter
|
||||
const lastLoginFilter = filters?.properties.find((f) => f.name === "lastLogin");
|
||||
if (lastLoginFilter?.value) {
|
||||
const gte = DateUtils.gteFromFilter(lastLoginFilter.value);
|
||||
const logs = (
|
||||
await db.log.findMany({
|
||||
where: { userId: { not: null }, createdAt: { gte }, action: DefaultLogActions.Login },
|
||||
select: { userId: true },
|
||||
})
|
||||
).map((l) => l.userId);
|
||||
const usersIn: string[] = logs.filter((f) => f !== null).map((m) => m as string);
|
||||
where = {
|
||||
AND: [where, { id: { in: usersIn } }],
|
||||
};
|
||||
}
|
||||
|
||||
const isAdminFilter = filters?.properties.find((f) => f.name === "isAdmin");
|
||||
if (isAdminFilter?.value) {
|
||||
if (isAdminFilter.value === "true") {
|
||||
where = {
|
||||
AND: [where, { admin: { isNot: null } }],
|
||||
};
|
||||
} else {
|
||||
where = {
|
||||
AND: [where, { admin: null }],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
let orderBy: Prisma.UserOrderByWithRelationInput[] = [{ createdAt: "desc" }];
|
||||
if (pagination?.sortedBy?.length) {
|
||||
pagination.sortedBy = pagination.sortedBy.filter((s) => ["email", "firstName", "lastName", "createdAt"].includes(s.name));
|
||||
orderBy = pagination.sortedBy.map((s) => {
|
||||
return { [s.name]: s.direction };
|
||||
});
|
||||
}
|
||||
const [items, totalItems] = await Promise.all([
|
||||
db.user.findMany({
|
||||
skip: pagination ? pagination?.pageSize * (pagination?.page - 1) : undefined,
|
||||
take: pagination ? pagination?.pageSize : undefined,
|
||||
where,
|
||||
include: {
|
||||
admin: true,
|
||||
tenants: {
|
||||
include: {
|
||||
tenant: true,
|
||||
},
|
||||
},
|
||||
roles: {
|
||||
include: {
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy,
|
||||
}),
|
||||
db.user.count({
|
||||
where,
|
||||
}),
|
||||
]);
|
||||
return {
|
||||
items,
|
||||
pagination: {
|
||||
page: pagination?.page ?? 1,
|
||||
pageSize: pagination?.pageSize ?? Constants.DEFAULT_PAGE_SIZE,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / (pagination?.pageSize ?? Constants.DEFAULT_PAGE_SIZE)),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function adminGetAllUsersNames(): Promise<UserWithNames[]> {
|
||||
return db.user.findMany({
|
||||
select: { id: true, email: true, firstName: true, lastName: true },
|
||||
});
|
||||
}
|
||||
|
||||
export async function adminGetAllUsersNamesInIds(ids: string[]): Promise<UserWithNames[]> {
|
||||
return db.user.findMany({
|
||||
select: { id: true, email: true, firstName: true, lastName: true },
|
||||
where: {
|
||||
id: { in: ids },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getUsersById(ids: string[]): Promise<UserWithDetails[]> {
|
||||
return db.user.findMany({
|
||||
where: {
|
||||
id: {
|
||||
in: ids,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
admin: true,
|
||||
tenants: {
|
||||
include: {
|
||||
tenant: true,
|
||||
},
|
||||
},
|
||||
roles: {
|
||||
include: {
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAdminUsersInRoles(roles: string[]): Promise<UserWithDetails[]> {
|
||||
return db.user.findMany({
|
||||
where: { roles: { some: { role: { id: { in: roles } } } } },
|
||||
include: {
|
||||
admin: true,
|
||||
tenants: {
|
||||
include: {
|
||||
tenant: true,
|
||||
},
|
||||
},
|
||||
roles: {
|
||||
include: {
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getUsersByTenant(tenantId: string | null): Promise<UserWithDetails[]> {
|
||||
let where = {};
|
||||
if (tenantId) {
|
||||
where = {
|
||||
tenants: {
|
||||
some: {
|
||||
tenantId,
|
||||
},
|
||||
},
|
||||
};
|
||||
} else {
|
||||
where = {
|
||||
admin: {
|
||||
isNot: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
return db.user.findMany({
|
||||
where,
|
||||
include: {
|
||||
admin: true,
|
||||
tenants: {
|
||||
include: {
|
||||
tenant: true,
|
||||
},
|
||||
},
|
||||
roles: {
|
||||
include: {
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getUser(userId?: string): Promise<UserWithoutPassword | null> {
|
||||
if (!userId) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return await cachified({
|
||||
key: `user:${userId}`,
|
||||
ttl: 1000 * 60 * 60 * 24,
|
||||
getFreshValue: async () =>
|
||||
db.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
avatar: true,
|
||||
phone: true,
|
||||
admin: true,
|
||||
defaultTenantId: true,
|
||||
createdAt: true,
|
||||
locale: true,
|
||||
lightOrDarkMode: true,
|
||||
},
|
||||
}),
|
||||
});
|
||||
} catch (error: any) {
|
||||
usersLogger.warn({ err: error }, "Could not fetch user with mfa snapshot");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function setUserTotpPendingSecret(userId: string | undefined, encryptedSecret: string, pendingCreatedAt: Date = new Date()) {
|
||||
if (!userId) {
|
||||
return null;
|
||||
}
|
||||
return await db.user
|
||||
.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
totpPendingSecretEncrypted: encryptedSecret,
|
||||
totpPendingCreatedAt: pendingCreatedAt,
|
||||
},
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`user:${userId}`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function activateUserTotpPendingSecret(userId: string | undefined, encryptedSecret: string, enabledAt: Date = new Date()) {
|
||||
if (!userId) {
|
||||
return null;
|
||||
}
|
||||
return await db.user
|
||||
.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
totpSecretEncrypted: encryptedSecret,
|
||||
totpEnabledAt: enabledAt,
|
||||
totpPendingSecretEncrypted: null,
|
||||
totpPendingCreatedAt: null,
|
||||
},
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`user:${userId}`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function disableUserTotp(userId: string | undefined) {
|
||||
if (!userId) {
|
||||
return null;
|
||||
}
|
||||
return await db.user
|
||||
.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
totpSecretEncrypted: null,
|
||||
totpPendingSecretEncrypted: null,
|
||||
totpEnabledAt: null,
|
||||
totpPendingCreatedAt: null,
|
||||
},
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`user:${userId}`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function getUserTotpStatus(userId: string | undefined): Promise<UserTotpStatus | null> {
|
||||
if (!userId) {
|
||||
return null;
|
||||
}
|
||||
const status = await db.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
totpSecretEncrypted: true,
|
||||
totpPendingSecretEncrypted: true,
|
||||
totpEnabledAt: true,
|
||||
totpPendingCreatedAt: true,
|
||||
},
|
||||
});
|
||||
if (!status) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
enabled: Boolean(status.totpSecretEncrypted && status.totpEnabledAt),
|
||||
pending: Boolean(status.totpPendingSecretEncrypted && status.totpPendingCreatedAt),
|
||||
enabledAt: status.totpEnabledAt,
|
||||
pendingCreatedAt: status.totpPendingCreatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* D1 (2FA-Login-Gate) — liefert das VERSCHLUESSELTE TOTP-Secret eines Nutzers, sofern TOTP aktiv
|
||||
* (enabled) ist, sonst null. `verifyTotpCode` erwartet genau dieses verschluesselte Secret und
|
||||
* entschluesselt intern. Wird beim Login-Verify gebraucht, ohne den Klartext zu beruehren.
|
||||
*/
|
||||
export async function getActiveTotpSecretEncrypted(userId: string | undefined): Promise<string | null> {
|
||||
if (!userId) {
|
||||
return null;
|
||||
}
|
||||
const user = await db.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { totpSecretEncrypted: true, totpEnabledAt: true },
|
||||
});
|
||||
if (!user?.totpSecretEncrypted || !user.totpEnabledAt) {
|
||||
return null;
|
||||
}
|
||||
return user.totpSecretEncrypted;
|
||||
}
|
||||
|
||||
export async function getUserTotpPendingEnrollment(userId: string | undefined): Promise<UserTotpPendingEnrollment | null> {
|
||||
if (!userId) {
|
||||
return null;
|
||||
}
|
||||
return await db.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
totpPendingSecretEncrypted: true,
|
||||
totpPendingCreatedAt: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function setUserMfaRecoveryCodes(
|
||||
userId: string | undefined,
|
||||
entries: RecoveryCodeHashEntry[],
|
||||
generatedAt: Date = new Date()
|
||||
) {
|
||||
if (!userId) {
|
||||
return null;
|
||||
}
|
||||
return await db.user
|
||||
.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
mfaRecoveryCodeHashes: entries,
|
||||
mfaRecoveryCodesGeneratedAt: generatedAt,
|
||||
mfaRecoveryCodeLastUsedAt: null,
|
||||
},
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`user:${userId}`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function getUserMfaRecoveryCodeStatus(userId: string | undefined): Promise<UserMfaRecoveryCodeStatus | null> {
|
||||
if (!userId) {
|
||||
return null;
|
||||
}
|
||||
const user = await db.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
mfaRecoveryCodeHashes: true,
|
||||
mfaRecoveryCodesGeneratedAt: true,
|
||||
mfaRecoveryCodeLastUsedAt: true,
|
||||
},
|
||||
});
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
const status = getRecoveryCodeStatus(user.mfaRecoveryCodeHashes as RecoveryCodeHashEntry[] | null, {
|
||||
generatedAt: user.mfaRecoveryCodesGeneratedAt,
|
||||
lastUsedAt: user.mfaRecoveryCodeLastUsedAt,
|
||||
});
|
||||
return {
|
||||
configured: status.configured,
|
||||
remainingCount: status.remainingCount,
|
||||
generatedAt: status.generatedAt,
|
||||
lastUsedAt: status.lastUsedAt,
|
||||
};
|
||||
}
|
||||
|
||||
export async function consumeUserMfaRecoveryCode(
|
||||
userId: string | undefined,
|
||||
code: string,
|
||||
options: { now?: Date } = {}
|
||||
): Promise<UserMfaRecoveryCodeConsumeResult | null> {
|
||||
if (!userId) {
|
||||
return null;
|
||||
}
|
||||
const user = await db.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
mfaRecoveryCodeHashes: true,
|
||||
mfaRecoveryCodesGeneratedAt: true,
|
||||
mfaRecoveryCodeLastUsedAt: true,
|
||||
},
|
||||
});
|
||||
const entries = user?.mfaRecoveryCodeHashes as RecoveryCodeHashEntry[] | null | undefined;
|
||||
if (!user || !entries?.length) {
|
||||
return { consumed: false, remainingCount: 0, usedAt: null };
|
||||
}
|
||||
|
||||
const result = consumeRecoveryCode(entries, code, { now: options.now });
|
||||
if (!result.matched || !result.usedAt) {
|
||||
const status = getRecoveryCodeStatus(entries, {
|
||||
generatedAt: user.mfaRecoveryCodesGeneratedAt,
|
||||
lastUsedAt: user.mfaRecoveryCodeLastUsedAt,
|
||||
});
|
||||
return { consumed: false, remainingCount: status.remainingCount, usedAt: null };
|
||||
}
|
||||
|
||||
const updateResult = await db.user.updateMany({
|
||||
where: { id: userId, mfaRecoveryCodeHashes: { equals: entries as Prisma.InputJsonValue } },
|
||||
data: {
|
||||
mfaRecoveryCodeHashes: result.entries,
|
||||
mfaRecoveryCodeLastUsedAt: result.usedAt,
|
||||
},
|
||||
});
|
||||
if (updateResult.count !== 1) {
|
||||
return { consumed: false, remainingCount: getRecoveryCodeStatus(entries).remainingCount, usedAt: null };
|
||||
}
|
||||
|
||||
clearCacheKey(`user:${userId}`);
|
||||
const status = getRecoveryCodeStatus(result.entries, {
|
||||
generatedAt: user.mfaRecoveryCodesGeneratedAt,
|
||||
lastUsedAt: result.usedAt,
|
||||
});
|
||||
return { consumed: true, remainingCount: status.remainingCount, usedAt: result.usedAt };
|
||||
}
|
||||
|
||||
export async function getUserByEmail(email?: string) {
|
||||
if (!email) {
|
||||
return null;
|
||||
}
|
||||
return await db.user.findUnique({
|
||||
where: { email },
|
||||
include: {
|
||||
tenants: true,
|
||||
admin: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getUserByEmailWithDetails(email: string): Promise<UserWithDetails | null> {
|
||||
return await db.user.findUnique({
|
||||
where: { email },
|
||||
include: {
|
||||
admin: true,
|
||||
tenants: { include: { tenant: true } },
|
||||
roles: { include: { role: true } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function register(data: {
|
||||
email: string;
|
||||
password: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
active?: boolean;
|
||||
avatarURL?: string;
|
||||
locale?: string;
|
||||
defaultTenantId?: string | null;
|
||||
request: Request;
|
||||
}) {
|
||||
const { email, password, firstName, lastName, active, avatarURL, locale, defaultTenantId } = data;
|
||||
const passwordHash = await hashPassword(password);
|
||||
const user = await db.user.create({
|
||||
data: {
|
||||
email,
|
||||
passwordHash,
|
||||
firstName,
|
||||
lastName,
|
||||
avatar: avatarURL ?? "",
|
||||
phone: "",
|
||||
active,
|
||||
locale,
|
||||
defaultTenantId,
|
||||
},
|
||||
});
|
||||
// Phase 06 #22 — emit plugin hook `user.created` so installed plugins
|
||||
// can react (e.g. provisioning external SSO accounts, notifications).
|
||||
// Fire-and-forget: failures never propagate into user registration.
|
||||
await emitPluginHookFireAndForget(
|
||||
PLUGIN_HOOK_USER_CREATED,
|
||||
{
|
||||
userId: user.id,
|
||||
tenantId: defaultTenantId ?? null,
|
||||
email: user.email,
|
||||
locale: user.locale ?? null,
|
||||
createdAt: user.createdAt.toISOString(),
|
||||
},
|
||||
{ tenantId: defaultTenantId ?? null, dispatchKey: `user:${user.id}:created` }
|
||||
);
|
||||
return { id: user.id, email, defaultTenantId: user.defaultTenantId, locale };
|
||||
}
|
||||
|
||||
export async function updateUserProfile(
|
||||
data: { firstName?: string; lastName?: string; avatar?: string; locale?: string; lightOrDarkMode?: string },
|
||||
userId?: string
|
||||
) {
|
||||
if (!userId) {
|
||||
return null;
|
||||
}
|
||||
return await db.user
|
||||
.update({
|
||||
where: { id: userId },
|
||||
data,
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`user:${userId}`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateUserVerifyToken(data: { verifyToken: string; verifyTokenCreatedAt?: Date | null }, userId?: string) {
|
||||
if (!userId) {
|
||||
return null;
|
||||
}
|
||||
return await db.user
|
||||
.update({
|
||||
where: { id: userId },
|
||||
data,
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`user:${userId}`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateUserPassword(data: { passwordHash: string }, userId?: string) {
|
||||
if (!userId) {
|
||||
return null;
|
||||
}
|
||||
return await db.user
|
||||
.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
...data,
|
||||
verifyToken: "",
|
||||
verifyTokenCreatedAt: null,
|
||||
},
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`user:${userId}`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateUserDefaultTenantId(data: { defaultTenantId: string }, userId: string) {
|
||||
if (!userId) {
|
||||
return null;
|
||||
}
|
||||
return await db.user
|
||||
.update({
|
||||
where: { id: userId },
|
||||
data,
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`user:${userId}`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
export async function deleteUser(userId: string) {
|
||||
return await db.user
|
||||
.delete({
|
||||
where: { id: userId },
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`user:${userId}`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, test, vi, beforeEach } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import path from "node:path";
|
||||
|
||||
const mockUpdate = vi.fn();
|
||||
const mockUpdateMany = vi.fn();
|
||||
const mockFindUnique = vi.fn();
|
||||
|
||||
vi.mock("../db.server", () => ({
|
||||
db: {
|
||||
user: {
|
||||
update: mockUpdate,
|
||||
updateMany: mockUpdateMany,
|
||||
findUnique: mockFindUnique,
|
||||
},
|
||||
},
|
||||
}));
|
||||
vi.mock("../cache.server", () => ({ cachified: vi.fn(), clearCacheKey: vi.fn() }));
|
||||
vi.mock("~/modules/crm/services/CrmService", () => ({ default: { createContact: vi.fn() } }));
|
||||
|
||||
const testDir = path.dirname(fileURLToPath(import.meta.url));
|
||||
const usersSource = readFileSync(path.join(testDir, "users.db.server.ts"), "utf8");
|
||||
const schemaSource = readFileSync(path.join(testDir, "../../../../../prisma/schema/accounts.prisma"), "utf8");
|
||||
const migrationSource = readFileSync(path.join(testDir, "../../../../../prisma/migrations/20260508130000_user_totp_mfa/migration.sql"), "utf8");
|
||||
const recoveryCodesMigrationSource = readFileSync(
|
||||
path.join(testDir, "../../../../../prisma/migrations/20260508133000_user_mfa_recovery_codes/migration.sql"),
|
||||
"utf8"
|
||||
);
|
||||
|
||||
describe("user TOTP MFA storage contract", () => {
|
||||
beforeEach(() => {
|
||||
process.env.CRYPTO_SECRET = "test-recovery-secret";
|
||||
mockUpdate.mockReset();
|
||||
mockUpdateMany.mockReset();
|
||||
mockFindUnique.mockReset();
|
||||
});
|
||||
|
||||
test("schema and migration define nullable encrypted TOTP state without defaults", () => {
|
||||
expect(schemaSource).toContain("totpSecretEncrypted String?");
|
||||
expect(schemaSource).toContain("totpPendingSecretEncrypted String?");
|
||||
expect(schemaSource).toContain("totpEnabledAt DateTime?");
|
||||
expect(schemaSource).toContain("totpPendingCreatedAt DateTime?");
|
||||
|
||||
for (const column of ["totpSecretEncrypted", "totpPendingSecretEncrypted", "totpEnabledAt", "totpPendingCreatedAt"]) {
|
||||
expect(migrationSource).toContain(`ADD COLUMN "${column}"`);
|
||||
}
|
||||
expect(migrationSource).not.toMatch(/NOT NULL|DEFAULT|otpauth|secret_fixture|totp-secret/i);
|
||||
});
|
||||
|
||||
test("schema and migration define nullable hashed recovery-code state without plaintext fixtures", () => {
|
||||
expect(schemaSource).toContain("mfaRecoveryCodeHashes Json?");
|
||||
expect(schemaSource).toContain("mfaRecoveryCodesGeneratedAt DateTime?");
|
||||
expect(schemaSource).toContain("mfaRecoveryCodeLastUsedAt DateTime?");
|
||||
expect(schemaSource).not.toMatch(/recoveryCodesPlaintext|recoveryCodePlaintext|mfaRecoveryCodePlain|mfaRecoveryCodesPlain/i);
|
||||
|
||||
for (const column of ["mfaRecoveryCodeHashes", "mfaRecoveryCodesGeneratedAt", "mfaRecoveryCodeLastUsedAt"]) {
|
||||
expect(recoveryCodesMigrationSource).toContain(`ADD COLUMN "${column}"`);
|
||||
}
|
||||
expect(recoveryCodesMigrationSource).not.toMatch(/NOT NULL|DEFAULT|\b[A-Z0-9]{4}-[A-Z0-9]{4}\b|plaintext|plain text|secret_fixture|recovery-code-secret/i);
|
||||
});
|
||||
|
||||
test("generic getUser select omits encrypted TOTP fields and recovery-code hashes", () => {
|
||||
const getUserBlock = usersSource.match(/export async function getUser\(userId\?: string\)[\s\S]*?export async function setUserTotpPendingSecret/);
|
||||
|
||||
expect(getUserBlock?.[0]).toContain("select: {");
|
||||
expect(getUserBlock?.[0]).not.toContain("totpSecretEncrypted");
|
||||
expect(getUserBlock?.[0]).not.toContain("totpPendingSecretEncrypted");
|
||||
expect(getUserBlock?.[0]).not.toContain("mfaRecoveryCodeHashes");
|
||||
});
|
||||
|
||||
test("setUserTotpPendingSecret stores pending secret metadata and clears cache", async () => {
|
||||
const { setUserTotpPendingSecret } = await import("./users.db.server");
|
||||
const { clearCacheKey } = await import("../cache.server");
|
||||
const pendingCreatedAt = new Date("2026-05-08T13:00:00.000Z");
|
||||
mockUpdate.mockResolvedValueOnce({ id: "user_1" });
|
||||
|
||||
await setUserTotpPendingSecret("user_1", "encrypted-pending-secret", pendingCreatedAt);
|
||||
|
||||
expect(mockUpdate).toHaveBeenCalledWith({
|
||||
where: { id: "user_1" },
|
||||
data: {
|
||||
totpPendingSecretEncrypted: "encrypted-pending-secret",
|
||||
totpPendingCreatedAt: pendingCreatedAt,
|
||||
},
|
||||
});
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("user:user_1");
|
||||
});
|
||||
|
||||
test("activateUserTotpPendingSecret promotes pending secret, clears pending fields, and clears cache", async () => {
|
||||
const { activateUserTotpPendingSecret } = await import("./users.db.server");
|
||||
const { clearCacheKey } = await import("../cache.server");
|
||||
const enabledAt = new Date("2026-05-08T13:05:00.000Z");
|
||||
mockUpdate.mockResolvedValueOnce({ id: "user_1" });
|
||||
|
||||
await activateUserTotpPendingSecret("user_1", "encrypted-active-secret", enabledAt);
|
||||
|
||||
expect(mockUpdate).toHaveBeenCalledWith({
|
||||
where: { id: "user_1" },
|
||||
data: {
|
||||
totpSecretEncrypted: "encrypted-active-secret",
|
||||
totpEnabledAt: enabledAt,
|
||||
totpPendingSecretEncrypted: null,
|
||||
totpPendingCreatedAt: null,
|
||||
},
|
||||
});
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("user:user_1");
|
||||
});
|
||||
|
||||
test("disableUserTotp clears active and pending TOTP state and clears cache", async () => {
|
||||
const { disableUserTotp } = await import("./users.db.server");
|
||||
const { clearCacheKey } = await import("../cache.server");
|
||||
mockUpdate.mockResolvedValueOnce({ id: "user_1" });
|
||||
|
||||
await disableUserTotp("user_1");
|
||||
|
||||
expect(mockUpdate).toHaveBeenCalledWith({
|
||||
where: { id: "user_1" },
|
||||
data: {
|
||||
totpSecretEncrypted: null,
|
||||
totpPendingSecretEncrypted: null,
|
||||
totpEnabledAt: null,
|
||||
totpPendingCreatedAt: null,
|
||||
},
|
||||
});
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("user:user_1");
|
||||
});
|
||||
|
||||
test("getUserTotpStatus exposes booleans and timestamps without encrypted secrets", async () => {
|
||||
const { getUserTotpStatus } = await import("./users.db.server");
|
||||
const enabledAt = new Date("2026-05-08T13:05:00.000Z");
|
||||
const pendingCreatedAt = new Date("2026-05-08T13:00:00.000Z");
|
||||
mockFindUnique.mockResolvedValueOnce({
|
||||
totpSecretEncrypted: "encrypted-active-secret",
|
||||
totpPendingSecretEncrypted: "encrypted-pending-secret",
|
||||
totpEnabledAt: enabledAt,
|
||||
totpPendingCreatedAt: pendingCreatedAt,
|
||||
});
|
||||
|
||||
const status = await getUserTotpStatus("user_1");
|
||||
|
||||
expect(mockFindUnique).toHaveBeenCalledWith({
|
||||
where: { id: "user_1" },
|
||||
select: {
|
||||
totpSecretEncrypted: true,
|
||||
totpPendingSecretEncrypted: true,
|
||||
totpEnabledAt: true,
|
||||
totpPendingCreatedAt: true,
|
||||
},
|
||||
});
|
||||
expect(status).toEqual({
|
||||
enabled: true,
|
||||
pending: true,
|
||||
enabledAt,
|
||||
pendingCreatedAt,
|
||||
});
|
||||
expect(status).not.toHaveProperty("totpSecretEncrypted");
|
||||
expect(status).not.toHaveProperty("totpPendingSecretEncrypted");
|
||||
});
|
||||
|
||||
test("setUserMfaRecoveryCodes replaces hashes, resets last-used timestamp, and clears cache", async () => {
|
||||
const { setUserMfaRecoveryCodes } = await import("./users.db.server");
|
||||
const { clearCacheKey } = await import("../cache.server");
|
||||
const generatedAt = new Date("2026-05-08T14:00:00.000Z");
|
||||
const entries = [{ hash: "hash-1", usedAt: null, createdAt: generatedAt }];
|
||||
mockUpdate.mockResolvedValueOnce({ id: "user_1" });
|
||||
|
||||
await setUserMfaRecoveryCodes("user_1", entries, generatedAt);
|
||||
|
||||
expect(mockUpdate).toHaveBeenCalledWith({
|
||||
where: { id: "user_1" },
|
||||
data: {
|
||||
mfaRecoveryCodeHashes: entries,
|
||||
mfaRecoveryCodesGeneratedAt: generatedAt,
|
||||
mfaRecoveryCodeLastUsedAt: null,
|
||||
},
|
||||
});
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("user:user_1");
|
||||
expect(await setUserMfaRecoveryCodes(undefined, entries, generatedAt)).toBeNull();
|
||||
});
|
||||
|
||||
test("getUserMfaRecoveryCodeStatus returns redacted status only", async () => {
|
||||
const { getUserMfaRecoveryCodeStatus } = await import("./users.db.server");
|
||||
const generatedAt = new Date("2026-05-08T14:00:00.000Z");
|
||||
const lastUsedAt = new Date("2026-05-08T14:05:00.000Z");
|
||||
mockFindUnique.mockResolvedValueOnce({
|
||||
mfaRecoveryCodeHashes: [
|
||||
{ hash: "hash-1", usedAt: null, createdAt: generatedAt },
|
||||
{ hash: "hash-2", usedAt: lastUsedAt, createdAt: generatedAt },
|
||||
],
|
||||
mfaRecoveryCodesGeneratedAt: generatedAt,
|
||||
mfaRecoveryCodeLastUsedAt: lastUsedAt,
|
||||
});
|
||||
|
||||
const status = await getUserMfaRecoveryCodeStatus("user_1");
|
||||
|
||||
expect(mockFindUnique).toHaveBeenCalledWith({
|
||||
where: { id: "user_1" },
|
||||
select: {
|
||||
mfaRecoveryCodeHashes: true,
|
||||
mfaRecoveryCodesGeneratedAt: true,
|
||||
mfaRecoveryCodeLastUsedAt: true,
|
||||
},
|
||||
});
|
||||
expect(status).toEqual({ configured: true, remainingCount: 1, generatedAt, lastUsedAt });
|
||||
expect(JSON.stringify(status)).not.toMatch(/hash-1|hash-2|recovery-code/i);
|
||||
expect(await getUserMfaRecoveryCodeStatus(undefined)).toBeNull();
|
||||
});
|
||||
|
||||
test("consumeUserMfaRecoveryCode marks one matching unused code and clears cache", async () => {
|
||||
const { consumeUserMfaRecoveryCode } = await import("./users.db.server");
|
||||
const { hashRecoveryCode } = await import("~/utils/auth/mfa/recovery-codes.server");
|
||||
const { clearCacheKey } = await import("../cache.server");
|
||||
const generatedAt = new Date("2026-05-08T14:00:00.000Z");
|
||||
const usedAt = new Date("2026-05-08T14:10:00.000Z");
|
||||
const entries = [
|
||||
{ hash: hashRecoveryCode("ABCD-EFGH-JKLM")!, usedAt: null, createdAt: generatedAt },
|
||||
{ hash: hashRecoveryCode("NPQR-STUV-WXYZ")!, usedAt: null, createdAt: generatedAt },
|
||||
];
|
||||
mockFindUnique.mockResolvedValueOnce({
|
||||
mfaRecoveryCodeHashes: entries,
|
||||
mfaRecoveryCodesGeneratedAt: generatedAt,
|
||||
mfaRecoveryCodeLastUsedAt: null,
|
||||
});
|
||||
mockUpdateMany.mockResolvedValueOnce({ count: 1 });
|
||||
|
||||
const result = await consumeUserMfaRecoveryCode("user_1", "ABCD-EFGH-JKLM", { now: usedAt });
|
||||
|
||||
expect(mockUpdateMany).toHaveBeenCalledWith({
|
||||
where: { id: "user_1", mfaRecoveryCodeHashes: { equals: entries } },
|
||||
data: {
|
||||
mfaRecoveryCodeHashes: [{ ...entries[0], usedAt }, entries[1]],
|
||||
mfaRecoveryCodeLastUsedAt: usedAt,
|
||||
},
|
||||
});
|
||||
expect(result).toEqual({ consumed: true, remainingCount: 1, usedAt });
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("user:user_1");
|
||||
});
|
||||
|
||||
test("consumeUserMfaRecoveryCode rejects missing state, wrong code, and used-code replay without update", async () => {
|
||||
const { consumeUserMfaRecoveryCode } = await import("./users.db.server");
|
||||
const { hashRecoveryCode } = await import("~/utils/auth/mfa/recovery-codes.server");
|
||||
const generatedAt = new Date("2026-05-08T14:00:00.000Z");
|
||||
const usedAt = new Date("2026-05-08T14:10:00.000Z");
|
||||
const usedEntries = [{ hash: hashRecoveryCode("ABCD-EFGH-JKLM")!, usedAt, createdAt: generatedAt }];
|
||||
|
||||
mockFindUnique.mockResolvedValueOnce(null);
|
||||
await expect(consumeUserMfaRecoveryCode("user_1", "ABCD-EFGH-JKLM")).resolves.toEqual({
|
||||
consumed: false,
|
||||
remainingCount: 0,
|
||||
usedAt: null,
|
||||
});
|
||||
|
||||
mockFindUnique.mockResolvedValueOnce({
|
||||
mfaRecoveryCodeHashes: usedEntries,
|
||||
mfaRecoveryCodesGeneratedAt: generatedAt,
|
||||
mfaRecoveryCodeLastUsedAt: usedAt,
|
||||
});
|
||||
await expect(consumeUserMfaRecoveryCode("user_1", "WRONG-CODE-HERE")).resolves.toEqual({
|
||||
consumed: false,
|
||||
remainingCount: 0,
|
||||
usedAt: null,
|
||||
});
|
||||
|
||||
mockFindUnique.mockResolvedValueOnce({
|
||||
mfaRecoveryCodeHashes: usedEntries,
|
||||
mfaRecoveryCodesGeneratedAt: generatedAt,
|
||||
mfaRecoveryCodeLastUsedAt: usedAt,
|
||||
});
|
||||
await expect(consumeUserMfaRecoveryCode("user_1", "ABCD-EFGH-JKLM")).resolves.toEqual({
|
||||
consumed: false,
|
||||
remainingCount: 0,
|
||||
usedAt: null,
|
||||
});
|
||||
|
||||
await expect(consumeUserMfaRecoveryCode(undefined, "ABCD-EFGH-JKLM")).resolves.toBeNull();
|
||||
expect(mockUpdateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user