Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+112
@@ -0,0 +1,112 @@
|
||||
// @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";
|
||||
|
||||
const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../../../..");
|
||||
|
||||
// R-P5 — APPS-ENGINE RLS GATE PROOF. Proves that once apps-engine-isolation.sql is
|
||||
// applied, the restricted hivegrid_app role (NOSUPERUSER, NOBYPASSRLS) is confined
|
||||
// to its own tenant's DataConnection / AppSyncRun rows, sees nothing without a
|
||||
// tenant context, and is blocked by WITH CHECK from writing cross-tenant. The
|
||||
// global `App` catalog stays readable (no RLS).
|
||||
//
|
||||
// Runs ONLY when RLS_TEST_DATABASE_URL is set; otherwise skipped.
|
||||
//
|
||||
// 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-apps-engine
|
||||
|
||||
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("Apps-Engine RLS tenant isolation gate proof (DataConnection, AppSyncRun)", () => {
|
||||
let admin: pg.Client;
|
||||
let app: pg.Client;
|
||||
|
||||
beforeAll(async () => {
|
||||
admin = new pg.Client({ connectionString: ADMIN_URL });
|
||||
await admin.connect();
|
||||
|
||||
await admin.query(fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/tenant-isolation.sql"), "utf8"));
|
||||
await admin.query(fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/apps-engine-isolation.sql"), "utf8"));
|
||||
await admin.query(`GRANT CONNECT ON DATABASE ${new URL(ADMIN_URL!).pathname.slice(1)} TO ${APP_ROLE}`);
|
||||
|
||||
// Global App catalog (no tenant) + two tenants' connections + sync runs.
|
||||
await admin.query(`INSERT INTO "App"(id,"updatedAt","key","title","category","connectionType") VALUES
|
||||
('rls_app1',now(),'sample-data-sync','Sample','erp','rest_api') ON CONFLICT (id) DO NOTHING`);
|
||||
await admin.query(`INSERT INTO "DataConnection"(id,"updatedAt","tenantId","appId","label") VALUES
|
||||
('rls_dcA',now(),'rls_tenantA','rls_app1','A'),
|
||||
('rls_dcB',now(),'rls_tenantB','rls_app1','B') ON CONFLICT (id) DO NOTHING`);
|
||||
await admin.query(`INSERT INTO "AppSyncRun"(id,"updatedAt","tenantId","dataConnectionId") VALUES
|
||||
('rls_runA',now(),'rls_tenantA','rls_dcA'),
|
||||
('rls_runB',now(),'rls_tenantB','rls_dcB') 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, only tenant A connections are visible", async () => {
|
||||
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "DataConnection" ORDER BY id`)).rows.map((r) => r.id));
|
||||
expect(ids).toEqual(["rls_dcA"]);
|
||||
});
|
||||
|
||||
it("sees no connections without a tenant context", async () => {
|
||||
expect((await app.query(`SELECT count(*)::int AS c FROM "DataConnection"`)).rows[0].c).toBe(0);
|
||||
});
|
||||
|
||||
it("WITH CHECK blocks inserting a connection for a foreign tenant", async () => {
|
||||
await expect(
|
||||
underTenant("rls_tenantA", async () =>
|
||||
app.query(`INSERT INTO "DataConnection"(id,"updatedAt","tenantId","appId","label") VALUES ('rls_dcX',now(),'rls_tenantB','rls_app1','x')`),
|
||||
),
|
||||
).rejects.toThrow(/row-level security/i);
|
||||
});
|
||||
|
||||
it("isolates AppSyncRun rows by tenant", async () => {
|
||||
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "AppSyncRun" ORDER BY id`)).rows.map((r) => r.id));
|
||||
expect(ids).toEqual(["rls_runA"]);
|
||||
});
|
||||
|
||||
it("keeps the global App catalog readable under any tenant context", async () => {
|
||||
const count = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "App"`)).rows[0].c);
|
||||
expect(count).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
// @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 @hivegrid/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)), "../../../../../..");
|
||||
|
||||
// VA-P23 — EMAIL-INBOX RLS GATE PROOF. Companion to rls-file-isolation: proves
|
||||
// that once the email-inbox RLS block (prisma/rls/email-inbox-isolation.sql) is
|
||||
// applied, the restricted hivegrid_app role (NOSUPERUSER, NOBYPASSRLS) is
|
||||
// confined to its own tenant's EmailIntegrationMailbox / -Message rows, sees
|
||||
// nothing without a tenant context, and is blocked by WITH CHECK from writing
|
||||
// cross-tenant rows. This makes the P5 activation a pure switch: the wrapped
|
||||
// emailInbox db layer already runs inside withTenantRLS().
|
||||
//
|
||||
// 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-email-inbox-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("Email-inbox RLS tenant isolation gate proof (EmailIntegrationMailbox, EmailIntegrationMessage)", () => {
|
||||
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) Email-inbox RLS block: ENABLE/FORCE + tenant_isolation policy + GRANTs
|
||||
// on the four VA-P23 tables (the deferred P5 activation artifact).
|
||||
const emailInboxRlsSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/email-inbox-isolation.sql"), "utf8");
|
||||
await admin.query(emailInboxRlsSql);
|
||||
await admin.query(`GRANT CONNECT ON DATABASE ${new URL(ADMIN_URL!).pathname.slice(1)} TO ${APP_ROLE}`);
|
||||
|
||||
// 3) Seed two tenants' mailboxes + messages as superuser (bypasses RLS).
|
||||
// Mailbox has no FK on tenantId/ownerUserId, so no User/Tenant rows needed.
|
||||
await admin.query(`INSERT INTO "EmailIntegrationMailbox"(id,"updatedAt","tenantId","ownerUserId",provider,"emailAddress","externalAccountId") VALUES
|
||||
('rls_mboxA',now(),'rls_tenantA','rls_userA','gmail','a@example.com','extA'),
|
||||
('rls_mboxB',now(),'rls_tenantB','rls_userB','microsoft','b@example.com','extB')
|
||||
ON CONFLICT (id) DO NOTHING`);
|
||||
await admin.query(`INSERT INTO "EmailIntegrationMessage"(id,"updatedAt","tenantId","mailboxId","providerMessageId",direction,"fromAddress","sentAt") VALUES
|
||||
('rls_msgA',now(),'rls_tenantA','rls_mboxA','pmA','inbound','x@example.com',now()),
|
||||
('rls_msgB',now(),'rls_tenantB','rls_mboxB','pmB','inbound','y@example.com',now())
|
||||
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 mailboxes are visible", async () => {
|
||||
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "EmailIntegrationMailbox" ORDER BY id`)).rows.map((r) => r.id));
|
||||
expect(ids).toEqual(["rls_mboxA"]);
|
||||
});
|
||||
|
||||
it("cannot read another tenant's messages even with an explicit WHERE filter", async () => {
|
||||
const count = await underTenant(
|
||||
"rls_tenantA",
|
||||
async () => (await app.query(`SELECT count(*)::int AS c FROM "EmailIntegrationMessage" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c,
|
||||
);
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it("sees no mailboxes at all when no tenant context is set", async () => {
|
||||
const count = (await app.query(`SELECT count(*)::int AS c FROM "EmailIntegrationMailbox"`)).rows[0].c;
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it("WITH CHECK blocks inserting a message for a foreign tenant", async () => {
|
||||
await expect(
|
||||
underTenant("rls_tenantA", async () =>
|
||||
app.query(
|
||||
`INSERT INTO "EmailIntegrationMessage"(id,"updatedAt","tenantId","mailboxId","providerMessageId",direction,"fromAddress","sentAt")
|
||||
VALUES ('rls_msgX',now(),'rls_tenantB','rls_mboxB','pmX','inbound','z@example.com',now())`,
|
||||
),
|
||||
),
|
||||
).rejects.toThrow(/row-level security/i);
|
||||
});
|
||||
|
||||
it("allows inserting and reading a message for the active tenant", async () => {
|
||||
await underTenant("rls_tenantA", async () => {
|
||||
await app.query(
|
||||
`INSERT INTO "EmailIntegrationMessage"(id,"updatedAt","tenantId","mailboxId","providerMessageId",direction,"fromAddress","sentAt")
|
||||
VALUES ('rls_msgA2',now(),'rls_tenantA','rls_mboxA','pmA2','outbound','a@example.com',now())
|
||||
ON CONFLICT (id) DO NOTHING`,
|
||||
);
|
||||
const ids = (await app.query(`SELECT id FROM "EmailIntegrationMessage" ORDER BY id`)).rows.map((r) => r.id);
|
||||
expect(ids).toContain("rls_msgA2");
|
||||
expect(ids).not.toContain("rls_msgB");
|
||||
});
|
||||
});
|
||||
|
||||
it("isolates sync cursors and webhook events by tenant as well", async () => {
|
||||
await admin.query(`INSERT INTO "EmailIntegrationSyncCursor"(id,"updatedAt","tenantId","mailboxId","externalFolderId") VALUES
|
||||
('rls_curA',now(),'rls_tenantA','rls_mboxA','*'),
|
||||
('rls_curB',now(),'rls_tenantB','rls_mboxB','inbox')
|
||||
ON CONFLICT (id) DO NOTHING`);
|
||||
await admin.query(`INSERT INTO "EmailIntegrationWebhookEvent"(id,"tenantId","mailboxId",provider,"notificationPayload") VALUES
|
||||
('rls_whA','rls_tenantA','rls_mboxA','gmail','{}'),
|
||||
('rls_whB','rls_tenantB','rls_mboxB','microsoft','{}')
|
||||
ON CONFLICT (id) DO NOTHING`);
|
||||
|
||||
const cursorIds = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "EmailIntegrationSyncCursor" ORDER BY id`)).rows.map((r) => r.id));
|
||||
expect(cursorIds).toEqual(["rls_curA"]);
|
||||
const eventIds = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "EmailIntegrationWebhookEvent" ORDER BY id`)).rows.map((r) => r.id));
|
||||
expect(eventIds).toEqual(["rls_whA"]);
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -7,7 +7,7 @@ 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).
|
||||
// regardless of the cwd vitest runs under (root vs the @hivegrid/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)), "../../../../../..");
|
||||
|
||||
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
// @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. 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-P17a — HR RLS GATE PROOF. Companion to the task/file/tenant isolation tests:
|
||||
// proves that once the HR RLS block (prisma/rls/hr-isolation.sql) is applied, the
|
||||
// restricted hivegrid_app role (NOSUPERUSER, NOBYPASSRLS) is confined to its own
|
||||
// tenant's HR rows (here: HrEmployeeProfile + EmployeePasswordSafeEntry), 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 hr*Service helpers already set the GUC, so flipping RLS on cannot break
|
||||
// the module.
|
||||
//
|
||||
// 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-hr-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("HR RLS tenant isolation gate proof (HrEmployeeProfile, EmployeePasswordSafeEntry)", () => {
|
||||
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) HR RLS block: ENABLE/FORCE + tenant_isolation policy + GRANTs on the HR
|
||||
// tables (the deferred P5 activation artifact, applied here).
|
||||
const hrRlsSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/hr-isolation.sql"), "utf8");
|
||||
await admin.query(hrRlsSql);
|
||||
await admin.query(`GRANT CONNECT ON DATABASE ${new URL(ADMIN_URL!).pathname.slice(1)} TO ${APP_ROLE}`);
|
||||
|
||||
// 3) Seed two tenants' HR rows as superuser (bypasses RLS). The HR models use
|
||||
// bare scalars (AD-21), so no User/Tenant rows are required. The vault is
|
||||
// seeded for the FK from the entry.
|
||||
await admin.query(`INSERT INTO "HrEmployeeProfile"(id,"updatedAt","tenantId","userId","position") VALUES
|
||||
('rls_hrpA',now(),'rls_tenantA','rls_userA','Engineer'),
|
||||
('rls_hrpB',now(),'rls_tenantB','rls_userB','Engineer')
|
||||
ON CONFLICT (id) DO NOTHING`);
|
||||
await admin.query(`INSERT INTO "EmployeePasswordSafeVault"(id,"updatedAt","tenantId","name","createdByUserId") VALUES
|
||||
('rls_vaultA',now(),'rls_tenantA','Vault A','rls_userA'),
|
||||
('rls_vaultB',now(),'rls_tenantB','Vault B','rls_userB')
|
||||
ON CONFLICT (id) DO NOTHING`);
|
||||
await admin.query(`INSERT INTO "EmployeePasswordSafeEntry"(id,"updatedAt","tenantId","vaultId","title") VALUES
|
||||
('rls_entryA',now(),'rls_tenantA','rls_vaultA','Entry A'),
|
||||
('rls_entryB',now(),'rls_tenantB','rls_vaultB','Entry B')
|
||||
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 employee profiles are visible", async () => {
|
||||
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "HrEmployeeProfile" ORDER BY id`)).rows.map((r) => r.id));
|
||||
expect(ids).toEqual(["rls_hrpA"]);
|
||||
});
|
||||
|
||||
it("cannot read another tenant's profile even with an explicit WHERE filter", async () => {
|
||||
const count = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "HrEmployeeProfile" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c);
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it("sees no HR rows at all when no tenant context is set", async () => {
|
||||
const count = (await app.query(`SELECT count(*)::int AS c FROM "HrEmployeeProfile"`)).rows[0].c;
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it("WITH CHECK blocks inserting a profile for a foreign tenant", async () => {
|
||||
await expect(
|
||||
underTenant("rls_tenantA", async () =>
|
||||
app.query(`INSERT INTO "HrEmployeeProfile"(id,"updatedAt","tenantId","userId") VALUES ('rls_hrpX',now(),'rls_tenantB','rls_userB')`),
|
||||
),
|
||||
).rejects.toThrow(/row-level security/i);
|
||||
});
|
||||
|
||||
it("isolates password-safe entries by tenant as well", async () => {
|
||||
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "EmployeePasswordSafeEntry" ORDER BY id`)).rows.map((r) => r.id));
|
||||
expect(ids).toEqual(["rls_entryA"]);
|
||||
const crossCount = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "EmployeePasswordSafeEntry" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c);
|
||||
expect(crossCount).toBe(0);
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -7,7 +7,7 @@ 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).
|
||||
// regardless of the cwd vitest runs under (root vs the @hivegrid/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)), "../../../../../..");
|
||||
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import type { Prisma } from "@toolctrl/db/prisma-browser";
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
|
||||
+12
-28
@@ -16,14 +16,14 @@ import {
|
||||
type LegacyApiKeySimple,
|
||||
type LegacyApiKeyWithDetails,
|
||||
updateLegacyApiKey,
|
||||
} from "@toolctrl/db/api-keys.server";
|
||||
} from "@hivegrid/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 { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { getApiKeyLookupCacheKey, serializeApiLogSearchParams } from "../api/apiKeySecurity.server";
|
||||
|
||||
export type ApiKeyWithDetails = LegacyApiKeyWithDetails;
|
||||
@@ -177,23 +177,14 @@ 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 createApiKey(data: {
|
||||
tenantId: string;
|
||||
createdByUserId: string;
|
||||
alias: string;
|
||||
expires: Date | null;
|
||||
active: boolean;
|
||||
}) {
|
||||
return createLegacyApiKey(data, undefined, getApiKeyHashSecret());
|
||||
}
|
||||
|
||||
export async function createApiKeyLog(
|
||||
@@ -229,16 +220,9 @@ export async function updateApiKey(
|
||||
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);
|
||||
const apiKey = await updateLegacyApiKey(id, data);
|
||||
clearCacheKey(getApiKeyLookupCacheKey(apiKey.key));
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url
|
||||
|
||||
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('import { loadRequiredWebConfig } from "@hivegrid/config"');
|
||||
expect(source).toContain("const webConfig = loadRequiredWebConfig()");
|
||||
expect(source).toContain("instanceUrl: webConfig.captcha.instanceUrl ?? \"\"");
|
||||
expect(source).toContain("const authProviders = getPublicAuthProviders({ request, webConfig })");
|
||||
|
||||
+6
-4
@@ -1,6 +1,6 @@
|
||||
import { defaultBrandTokens } from "@toolctrl/brand";
|
||||
import { loadRequiredWebConfig } from "@toolctrl/config";
|
||||
import { Prisma } from "@toolctrl/db/prisma-browser";
|
||||
import { defaultBrandTokens } from "@hivegrid/brand";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getPublicAuthProviders } from "../auth/authProviders.server";
|
||||
import { cachified, clearCacheKey } from "../cache.server";
|
||||
@@ -41,6 +41,7 @@ export type AppConfiguration = {
|
||||
slug: { require: boolean; type: "tenant" | "username" } | null;
|
||||
captcha: {
|
||||
enabled: boolean;
|
||||
provider: "mcaptcha" | "cap";
|
||||
instanceUrl: string;
|
||||
loginSiteKey: string;
|
||||
};
|
||||
@@ -139,6 +140,7 @@ export async function getAppConfiguration({ request }: { request: Request }): Pr
|
||||
slug: { require: false, type: "username" },
|
||||
captcha: {
|
||||
enabled: Boolean(webConfig.captcha.instanceUrl && webConfig.captcha.loginSiteKey),
|
||||
provider: webConfig.captcha.provider,
|
||||
instanceUrl: webConfig.captcha.instanceUrl ?? "",
|
||||
loginSiteKey: webConfig.captcha.loginSiteKey ?? "",
|
||||
},
|
||||
@@ -220,7 +222,7 @@ export async function getAppConfiguration({ request }: { request: Request }): Pr
|
||||
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.
|
||||
// Captcha is env-driven, not stored per-tenant in the DB.
|
||||
// `conf.auth.captcha` is already populated from webConfig in the default builder.
|
||||
|
||||
conf.analytics.enabled = appConfiguration?.analyticsEnabled;
|
||||
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
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";
|
||||
import { Portal } from "@hivegrid/db/prisma-browser";
|
||||
|
||||
export type PortalConfiguration = {
|
||||
enabled: boolean;
|
||||
@@ -98,8 +98,8 @@ export function getAppPortalConfiguration({ t }: { t: TFunction }): PortalConfig
|
||||
properties: [titleProperty, descriptionProperty, ...seoProperties],
|
||||
errors: (params) => {
|
||||
let errors: string[] = [];
|
||||
if (!params.portal.stripeAccountId) {
|
||||
errors.push(t("models.portal.pages.errors.stripeAccountMissing"));
|
||||
if (!params.portal.paymentProviderAccountId) {
|
||||
errors.push(t("models.portal.pages.errors.paymentAccountMissing"));
|
||||
}
|
||||
return errors;
|
||||
},
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { Blacklist } from "@toolctrl/db/prisma-browser";
|
||||
import { Blacklist } from "@hivegrid/db/prisma-browser";
|
||||
import Constants from "~/application/Constants";
|
||||
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
|
||||
-800
@@ -1,800 +0,0 @@
|
||||
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
@@ -1,137 +0,0 @@
|
||||
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
@@ -1,258 +0,0 @@
|
||||
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
@@ -1,47 +0,0 @@
|
||||
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
@@ -1,65 +0,0 @@
|
||||
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
@@ -1,70 +0,0 @@
|
||||
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
@@ -1,19 +0,0 @@
|
||||
// @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
@@ -1,422 +0,0 @@
|
||||
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
@@ -1,202 +0,0 @@
|
||||
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
@@ -1,133 +0,0 @@
|
||||
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
@@ -1,273 +0,0 @@
|
||||
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
@@ -1,29 +0,0 @@
|
||||
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
@@ -1,91 +0,0 @@
|
||||
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
@@ -1,91 +0,0 @@
|
||||
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
@@ -1,69 +0,0 @@
|
||||
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
@@ -1,46 +0,0 @@
|
||||
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
@@ -1,188 +0,0 @@
|
||||
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
@@ -1,26 +0,0 @@
|
||||
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
@@ -1,505 +0,0 @@
|
||||
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;
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { IpAddress } from "@toolctrl/db/prisma-browser";
|
||||
import { IpAddress } from "@hivegrid/db/prisma-browser";
|
||||
import Constants from "~/application/Constants";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
@@ -1,39 +1,22 @@
|
||||
import { Tenant, Log, ApiKey, Prisma } from "@toolctrl/db/prisma-browser";
|
||||
import { Tenant, Log, ApiKey } from "@hivegrid/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(
|
||||
@@ -89,73 +72,6 @@ export async function getLogs(
|
||||
};
|
||||
}
|
||||
|
||||
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({
|
||||
@@ -181,78 +97,6 @@ export async function createManualLog(userId: string, tenantId: string | null, p
|
||||
});
|
||||
}
|
||||
|
||||
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) });
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { Group, GroupUser } from "@toolctrl/db/prisma-browser";
|
||||
import { Group, GroupUser } from "@hivegrid/db/prisma-browser";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { UserSimple } from "../users.db.server";
|
||||
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
|
||||
|
||||
+12
-43
@@ -17,19 +17,15 @@ vi.mock("../../db.server", () => ({
|
||||
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 { getRoleByName } from "./roles.db.server";
|
||||
import {
|
||||
createEntityPermissions,
|
||||
createPermissions,
|
||||
deleteEntityPermissions,
|
||||
deletePermission,
|
||||
getAllPermissions,
|
||||
getAllPermissionsIdsAndNames,
|
||||
@@ -118,6 +114,17 @@ describe("permission persistence", () => {
|
||||
expect(createRolePermission).toHaveBeenCalledWith({ permissionId: "permission_1", roleId: "role_1" });
|
||||
});
|
||||
|
||||
it("leaves an already-linked role permission untouched instead of recreating it", async () => {
|
||||
vi.mocked(db.permission.findMany).mockResolvedValue([{ id: "permission_1", name: "admin.users.view" }] as never);
|
||||
vi.mocked(getAllRolePermissions).mockResolvedValue([{ roleId: "role_1", permission: { name: "admin.users.view" } }] as never);
|
||||
vi.mocked(getRoleByName).mockResolvedValue({ id: "role_1", name: "SuperAdmin" } as never);
|
||||
|
||||
await createPermissions([{ name: "admin.users.view", description: "View users", type: "admin", inRoles: ["SuperAdmin"] }]);
|
||||
|
||||
expect(db.permission.create).not.toHaveBeenCalled();
|
||||
expect(createRolePermission).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
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);
|
||||
@@ -166,42 +173,4 @@ describe("permission persistence", () => {
|
||||
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" });
|
||||
});
|
||||
});
|
||||
+4
-39
@@ -1,10 +1,9 @@
|
||||
import { db } from "../../db.server";
|
||||
import { Entity, Permission, Role, RolePermission } from "@toolctrl/db/prisma-browser";
|
||||
import { getAllRolesNames, getRoleByName } from "./roles.db.server";
|
||||
import { Permission, Role, RolePermission } from "@hivegrid/db/prisma-browser";
|
||||
import { 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";
|
||||
|
||||
@@ -45,7 +44,6 @@ export async function getAllPermissions(type?: string, filters?: FiltersDto): Pr
|
||||
orderBy: [{ type: "asc" }, { name: "asc" }],
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAllPermissionsIdsAndNames(): Promise<{ id: string; name: string }[]> {
|
||||
return await db.permission.findMany({
|
||||
select: { id: true, name: true },
|
||||
@@ -134,7 +132,7 @@ export async function getNextPermissionsOrder(type?: string): Promise<number> {
|
||||
}
|
||||
|
||||
export async function createPermissions(
|
||||
permissions: { inRoles: string[]; name: string; description: string; type: string; entityId?: string | null }[],
|
||||
permissions: { inRoles: string[]; name: string; description: string; type: string }[],
|
||||
fromOrder: number = 0
|
||||
) {
|
||||
const allRolePermissions = await getAllRolePermissions();
|
||||
@@ -155,7 +153,6 @@ export async function createPermissions(
|
||||
description: data.description,
|
||||
type: data.type,
|
||||
isDefault: true,
|
||||
entityId: data.entityId ?? null,
|
||||
}));
|
||||
createdPermissionNames.add(permission.name);
|
||||
if (existing) {
|
||||
@@ -184,7 +181,7 @@ export async function createPermissions(
|
||||
}
|
||||
}
|
||||
|
||||
export async function createPermission(data: { order: number; name: string; description: string; type: string; isDefault: boolean; entityId: string | null }) {
|
||||
export async function createPermission(data: { order: number; name: string; description: string; type: string; isDefault: boolean }) {
|
||||
return await db.permission.create({
|
||||
data,
|
||||
});
|
||||
@@ -220,35 +217,3 @@ export async function deletePermission(id: string) {
|
||||
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);
|
||||
})
|
||||
);
|
||||
}
|
||||
+23
@@ -117,6 +117,21 @@ describe("role persistence", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("lists roles with users across every type when no type is provided", async () => {
|
||||
vi.mocked(dbMock.role.findMany).mockResolvedValueOnce([] as never);
|
||||
|
||||
await getAllRolesWithUsers(undefined, undefined, "tenant_1");
|
||||
|
||||
expect(dbMock.role.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { OR: [{ tenantId: null }, { tenantId: "tenant_1" }] },
|
||||
include: expect.objectContaining({
|
||||
users: expect.objectContaining({ where: { tenantId: "tenant_1" } }),
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
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);
|
||||
@@ -175,6 +190,14 @@ describe("role persistence", () => {
|
||||
expect(dbMock.role.aggregate).toHaveBeenNthCalledWith(2, { where: {}, _max: { order: true } });
|
||||
});
|
||||
|
||||
it("scopes next role order to the global tenant when no tenant id is given", async () => {
|
||||
vi.mocked(dbMock.role.aggregate).mockResolvedValueOnce({ _max: { order: 2 } } as never);
|
||||
|
||||
await expect(getNextRolesOrder("admin")).resolves.toBe(3);
|
||||
|
||||
expect(dbMock.role.aggregate).toHaveBeenCalledWith({ where: { type: "admin", tenantId: null }, _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);
|
||||
|
||||
+14
-1
@@ -1,5 +1,5 @@
|
||||
import { db } from "../../db.server";
|
||||
import { Permission, Role, RolePermission, UserRole } from "@toolctrl/db/prisma-browser";
|
||||
import { Permission, Role, RolePermission, UserRole } from "@hivegrid/db/prisma-browser";
|
||||
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
|
||||
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
|
||||
import { UserSimple } from "../users.db.server";
|
||||
@@ -199,6 +199,19 @@ export async function getTenantAssignableAppRole(id: string, tenantId: string):
|
||||
});
|
||||
}
|
||||
|
||||
// R-P2b (D01 inline role dropdown): all app roles a tenant may assign — the
|
||||
// shared assignable defaults plus the tenant's own custom/SHK roles. Mirrors
|
||||
// the per-role check in getTenantAssignableAppRole above.
|
||||
export async function getTenantAssignableAppRoles(tenantId: string): Promise<Role[]> {
|
||||
return await db.role.findMany({
|
||||
where: {
|
||||
type: "app",
|
||||
OR: [{ isDefault: true, tenantId: null }, { tenantId }],
|
||||
},
|
||||
orderBy: [{ type: "asc" }, { order: "asc" }],
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantMutableAppRole(id: string, tenantId: string): Promise<RoleWithPermissions | null> {
|
||||
return await db.role.findFirst({
|
||||
where: {
|
||||
|
||||
-81
@@ -1,81 +0,0 @@
|
||||
// @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
@@ -1,102 +0,0 @@
|
||||
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,
|
||||
},
|
||||
});
|
||||
}
|
||||
+28
@@ -8,6 +8,7 @@ vi.mock("../../db.server", () => ({
|
||||
count: vi.fn(),
|
||||
},
|
||||
role: {
|
||||
findFirst: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
userRole: {
|
||||
@@ -33,6 +34,7 @@ import {
|
||||
createUserRoles,
|
||||
deleteAllUserRoles,
|
||||
deleteUserRole,
|
||||
ensureAdminUserRoleByName,
|
||||
ensureTenantUserAppRoles,
|
||||
findPermissionByUser,
|
||||
findUserRolesByIds,
|
||||
@@ -299,6 +301,32 @@ describe("user role persistence", () => {
|
||||
await expect(createUserRole("user_1", "role_1", null)).rejects.toBe(error);
|
||||
});
|
||||
|
||||
it("does not grant an admin role by name when no matching admin role exists", async () => {
|
||||
vi.mocked(dbMock.role.findFirst).mockResolvedValueOnce(null);
|
||||
|
||||
await expect(ensureAdminUserRoleByName("user_1", "SuperAdmin")).resolves.toBeUndefined();
|
||||
|
||||
expect(dbMock.role.findFirst).toHaveBeenCalledWith({
|
||||
where: { name: "SuperAdmin", type: "admin" },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(dbMock.userRole.create).not.toHaveBeenCalled();
|
||||
expect(clearCacheKey).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("grants a matching admin role by name with admin scope and invalidates the role cache", async () => {
|
||||
vi.mocked(dbMock.role.findFirst).mockResolvedValueOnce({ id: "role_super_admin" } as never);
|
||||
vi.mocked(dbMock.userRole.findFirst).mockResolvedValueOnce(null);
|
||||
vi.mocked(dbMock.userRole.create).mockResolvedValueOnce({ id: "ur_admin" } as never);
|
||||
|
||||
await expect(ensureAdminUserRoleByName("user_1", "SuperAdmin")).resolves.toBeUndefined();
|
||||
|
||||
expect(dbMock.userRole.create).toHaveBeenCalledWith({
|
||||
data: { userId: "user_1", roleId: "role_super_admin", tenantId: null },
|
||||
});
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:null");
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { Permission, Role, RolePermission, UserRole } from "@toolctrl/db/prisma-browser";
|
||||
import { Permission, Role, RolePermission, UserRole } from "@hivegrid/db/prisma-browser";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import { db } from "../../db.server";
|
||||
import { cachified, clearCacheKey } from "~/utils/cache.server";
|
||||
|
||||
+68
-17
@@ -16,7 +16,7 @@ const dbMock = {
|
||||
id: `tenant-${where.slug}`,
|
||||
slug: where.slug,
|
||||
name: where.slug,
|
||||
...(include ? { subscription: { id: `subscription-${where.slug}`, products: [] } } : {}),
|
||||
...(include ? { subscription: { id: `subscription-${where.slug}`, lastInvoiceExternalId: null, lastPaymentExternalId: null, products: [] } } : {}),
|
||||
})),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
@@ -34,7 +34,7 @@ const dbMock = {
|
||||
create: vi.fn(),
|
||||
},
|
||||
subscriptionProduct: {
|
||||
findFirst: vi.fn(async ({ where }: { where: { stripeId: string } }) => ({ id: `product-${where.stripeId}` })),
|
||||
findFirst: vi.fn(async ({ where }: { where: { billingProviderId: string } }) => ({ id: `product-${where.billingProviderId}` })),
|
||||
},
|
||||
tenantSubscriptionProduct: {
|
||||
create: vi.fn(),
|
||||
@@ -92,6 +92,9 @@ const dbMock = {
|
||||
supportTicket: {
|
||||
upsert: vi.fn(),
|
||||
},
|
||||
app: {
|
||||
upsert: vi.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
const hashMock = vi.fn(async () => "hashed-password");
|
||||
@@ -109,12 +112,12 @@ vi.mock("~/utils/logger.server", () => ({
|
||||
}));
|
||||
|
||||
vi.mock("bcryptjs", () => ({ default: { genSalt: genSaltMock, hash: hashMock } }));
|
||||
vi.mock("@toolctrl/db/entitlements-seed.server", () => ({
|
||||
getEntitlementPlanStripeId: ({ id }: { id: string }) => `toolctrl_entitlement_plan_${id}`,
|
||||
vi.mock("@hivegrid/db/entitlements-seed.server", () => ({
|
||||
getEntitlementPlanBillingProviderId: ({ id }: { id: string }) => `hivegrid_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");
|
||||
vi.mock("@hivegrid/db/seed.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("@hivegrid/db/seed.server")>("@hivegrid/db/seed.server");
|
||||
return actual;
|
||||
});
|
||||
vi.mock("~/utils/services/emailService", () => ({ getAvailableTenantInboundAddress: vi.fn(async () => "seed@example.test") }));
|
||||
@@ -245,26 +248,23 @@ describe("SeedService", () => {
|
||||
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" },
|
||||
where: { billingProviderId: "hivegrid_entitlement_plan_starter" },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(dbMock.subscriptionProduct.findFirst).toHaveBeenCalledWith({
|
||||
where: { stripeId: "toolctrl_entitlement_plan_pro" },
|
||||
where: { billingProviderId: "hivegrid_entitlement_plan_pro" },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(dbMock.subscriptionProduct.findFirst).toHaveBeenCalledWith({
|
||||
where: { stripeId: "toolctrl_entitlement_plan_business" },
|
||||
where: { billingProviderId: "hivegrid_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" }) }));
|
||||
// R-P6 (DoD 1 + 6): the legacy entity-builder CRM seed
|
||||
// (ensureProductCoreCrmEntities) was removed from the seed path; demo
|
||||
// tenants now receive the (currently empty) SHK custom-field template
|
||||
// instead, so no `company`/`contact`/`opportunity` Entity rows are created.
|
||||
expect(dbMock.entity.create).not.toHaveBeenCalled();
|
||||
expect(dbMock.tenantProductConfiguration.upsert).toHaveBeenCalledTimes(3);
|
||||
expect(dbMock.knowledgeBase.upsert).toHaveBeenCalledTimes(3);
|
||||
expect(dbMock.supportTicket.upsert).toHaveBeenCalledTimes(6);
|
||||
@@ -274,6 +274,41 @@ describe("SeedService", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("does not reassign a demo tenant plan after self-service checkout", async () => {
|
||||
process.env.SEED_DEMO_DATA = "true";
|
||||
dbMock.tenant.findUnique.mockImplementation(async ({ where, include }: { where: { slug: string }; include?: unknown }) => ({
|
||||
id: `tenant-${where.slug}`,
|
||||
slug: where.slug,
|
||||
name: where.slug,
|
||||
...(include
|
||||
? {
|
||||
subscription: {
|
||||
id: `subscription-${where.slug}`,
|
||||
lastInvoiceExternalId: where.slug === "demo-pro-crm" ? "hgco_paid_checkout" : null,
|
||||
lastPaymentExternalId: where.slug === "demo-pro-crm" ? "hgco_paid_checkout" : null,
|
||||
products: [],
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
}));
|
||||
const SeedService = await loadSeedService();
|
||||
|
||||
await SeedService.seed();
|
||||
|
||||
expect(dbMock.subscriptionProduct.findFirst).toHaveBeenCalledWith({
|
||||
where: { billingProviderId: "hivegrid_entitlement_plan_starter" },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(dbMock.subscriptionProduct.findFirst).not.toHaveBeenCalledWith({
|
||||
where: { billingProviderId: "hivegrid_entitlement_plan_pro" },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(dbMock.subscriptionProduct.findFirst).toHaveBeenCalledWith({
|
||||
where: { billingProviderId: "hivegrid_entitlement_plan_business" },
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses demo data in production without the explicit staging override", async () => {
|
||||
process.env.NODE_ENV = "production";
|
||||
process.env.SEED_DEMO_DATA = "true";
|
||||
@@ -341,6 +376,22 @@ describe("SeedService", () => {
|
||||
expect(calls).toEqual(["roles", "entitlements"]);
|
||||
});
|
||||
|
||||
it("upserts the integration catalog into the global App table (R-P5)", async () => {
|
||||
const SeedService = await loadSeedService();
|
||||
const { INTEGRATION_CATALOG } = await import("@hivegrid/integrations");
|
||||
|
||||
await SeedService.seed();
|
||||
|
||||
expect(dbMock.app.upsert).toHaveBeenCalledTimes(INTEGRATION_CATALOG.length);
|
||||
expect(dbMock.app.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { key: "sample-data-sync" },
|
||||
create: expect.objectContaining({ key: "sample-data-sync", title: "integrations.app.sampleDataSync.title", connectionType: "rest_api", isActive: true }),
|
||||
update: expect.objectContaining({ title: "integrations.app.sampleDataSync.title" }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
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";
|
||||
|
||||
+32
-11
@@ -4,12 +4,13 @@ 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 { getEntitlementPlanBillingProviderId, seedStandardEntitlements, type EntitlementsSeedDiagnosticEvent } from "@hivegrid/db/entitlements-seed.server";
|
||||
import { runDbSeed, type DbSeedDiagnosticEvent } from "@hivegrid/db/seed.server";
|
||||
import { entitlementPlanIds, featureKeys, productBlueprintIds, type EntitlementPlanId } from "@hivegrid/entitlements";
|
||||
import { buildCatalogSeedPlan } from "@hivegrid/integrations";
|
||||
import { seedRolesAndPermissions, type RolesAndPermissionsSeedDiagnosticEvent } from "~/utils/services/rolesAndPermissionsService";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { ensureProductCoreCrmEntities } from "~/modules/crm/services/ProductCoreCrmEntities.server";
|
||||
import { seedShkCustomFieldTemplate } from "~/utils/integrations/crm/customFieldService.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
|
||||
const seedLogger = createScopedLogger("seed");
|
||||
@@ -112,10 +113,6 @@ async function seed() {
|
||||
);
|
||||
}
|
||||
|
||||
if (shouldSeedDemoData) {
|
||||
await ensureProductCoreCrmEntities({ ensurePermissions: false });
|
||||
}
|
||||
|
||||
// Permissions
|
||||
await seedRolesAndPermissions({
|
||||
adminEmail: adminUser.email,
|
||||
@@ -127,6 +124,10 @@ async function seed() {
|
||||
diagnostics: logEntitlementsSeedDiagnostic,
|
||||
});
|
||||
|
||||
// R-P5: global App definition table from the code catalog (idempotent by
|
||||
// unique key; the tenant runtime keeps reading INTEGRATION_CATALOG).
|
||||
await seedIntegrationCatalog();
|
||||
|
||||
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)));
|
||||
@@ -135,6 +136,18 @@ async function seed() {
|
||||
});
|
||||
}
|
||||
|
||||
/** Upsert the code catalog into the global `App` table (R-P5, no RLS/tenant). */
|
||||
async function seedIntegrationCatalog() {
|
||||
const plan = buildCatalogSeedPlan();
|
||||
for (const entry of plan) {
|
||||
const { key, connectionSchema, ...rest } = entry;
|
||||
// Prisma's InputJsonValue rejects readonly structures — deep-clone to plain.
|
||||
const data = { ...rest, connectionSchema: JSON.parse(JSON.stringify(connectionSchema)) as object };
|
||||
await db.app.upsert({ where: { key }, create: { key, ...data }, update: data });
|
||||
}
|
||||
seedLogger.info({ op: "seed.integrationCatalog", count: plan.length }, "Upserted integration catalog into App table");
|
||||
}
|
||||
|
||||
function shouldSeedCrmDemoData() {
|
||||
if (process.env.SEED_DEMO_DATA !== "true") {
|
||||
return false;
|
||||
@@ -318,7 +331,7 @@ async function ensureTenantSubscription(tenantId: string) {
|
||||
return db.tenantSubscription.create({
|
||||
data: {
|
||||
tenantId,
|
||||
stripeCustomerId: "",
|
||||
billingProviderCustomerId: "",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -366,9 +379,12 @@ async function assignTenantPlan(tenantSlug: string, planId: EntitlementPlanId) {
|
||||
if (!tenant?.subscription) {
|
||||
return;
|
||||
}
|
||||
if (tenant.subscription.lastPaymentExternalId?.startsWith("hgco_") || tenant.subscription.lastInvoiceExternalId?.startsWith("hgco_")) {
|
||||
return;
|
||||
}
|
||||
|
||||
const product = await db.subscriptionProduct.findFirst({
|
||||
where: { stripeId: getEntitlementPlanStripeId({ id: planId }) },
|
||||
where: { billingProviderId: getEntitlementPlanBillingProviderId({ id: planId }) },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!product) {
|
||||
@@ -384,7 +400,7 @@ async function assignTenantPlan(tenantSlug: string, planId: EntitlementPlanId) {
|
||||
data: {
|
||||
tenantSubscriptionId: tenant.subscription.id,
|
||||
subscriptionProductId: product.id,
|
||||
stripeSubscriptionId: null,
|
||||
billingProviderSubscriptionId: null,
|
||||
quantity: 1,
|
||||
fromCheckoutSessionId: null,
|
||||
customEntitlementPlanId: planId,
|
||||
@@ -406,6 +422,11 @@ async function seedDemoProductCoreTenant(tenantSlug: string, planId: Entitlement
|
||||
seedDemoTenantRoles(tenant.id, demoUsers),
|
||||
seedDemoTenantKnowledgeBase(tenant.id, tenant.slug, tenant.name, planId),
|
||||
seedDemoSupportTickets(tenant.id, tenant.slug, planId, demoUsers[0]?.id),
|
||||
// R-P6 (DoD 6): seed the tenant-scoped SHK custom-field template as demo
|
||||
// data (`isDemoData = true`) instead of the legacy entity-builder CRM
|
||||
// entities. The template is intentionally empty until the Geerkens
|
||||
// workshop (E3), so this is currently an idempotent no-op.
|
||||
seedShkCustomFieldTemplate({ tenantId: tenant.id }),
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
-5
@@ -1,5 +0,0 @@
|
||||
export {
|
||||
createCheckoutSessionStatus,
|
||||
getCheckoutSessionStatus,
|
||||
updateCheckoutSessionStatus,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
+6
-6
@@ -13,16 +13,16 @@ export {
|
||||
getAllSubscriptionProducts,
|
||||
getAllSubscriptionProductsWithTenants,
|
||||
getSubscriptionPrice,
|
||||
getSubscriptionPriceByStripeId,
|
||||
getSubscriptionPriceByBillingProviderId,
|
||||
getSubscriptionPrices,
|
||||
getSubscriptionProduct,
|
||||
getSubscriptionProductByStripeId,
|
||||
getSubscriptionProductByBillingProviderId,
|
||||
getSubscriptionProductsInIds,
|
||||
getSubscriptionUsageBasedPriceByStripeId,
|
||||
getSubscriptionUsageBasedPriceByBillingProviderId,
|
||||
updateSubscriptionPrice,
|
||||
updateSubscriptionPriceStripeId,
|
||||
updateSubscriptionPriceBillingProviderId,
|
||||
updateSubscriptionProduct,
|
||||
updateSubscriptionProductStripeId,
|
||||
updateSubscriptionProductBillingProviderId,
|
||||
type SubscriptionPriceWithProduct,
|
||||
type SubscriptionUsageBasedPriceWithProduct,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
} from "@hivegrid/db/subscriptions.server";
|
||||
+2
-2
@@ -16,7 +16,7 @@ function getMocks(): CacheMocks {
|
||||
return store.__tenantSubProductDbCacheMocks__;
|
||||
}
|
||||
|
||||
vi.mock("@toolctrl/db/subscriptions.server", () => ({
|
||||
vi.mock("@hivegrid/db/subscriptions.server", () => ({
|
||||
addTenantSubscriptionProduct: vi.fn(),
|
||||
cancelTenantSubscriptionProduct: vi.fn(),
|
||||
updateTenantSubscriptionProduct: vi.fn(),
|
||||
@@ -34,7 +34,7 @@ import {
|
||||
addTenantSubscriptionProduct as persistAdd,
|
||||
cancelTenantSubscriptionProduct as persistCancel,
|
||||
updateTenantSubscriptionProduct as persistUpdate,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
} from "@hivegrid/db/subscriptions.server";
|
||||
|
||||
const mocks = getMocks();
|
||||
|
||||
|
||||
+3
-3
@@ -5,7 +5,7 @@ import {
|
||||
type TenantSubscriptionProductCreateInput,
|
||||
type TenantSubscriptionProductUpdateInput,
|
||||
type TenantSubscriptionProductCancelInput,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
} from "@hivegrid/db/subscriptions.server";
|
||||
import { clearTenantSubscriptionCache } from "~/utils/services/.server/subscriptionService";
|
||||
|
||||
export {
|
||||
@@ -13,11 +13,11 @@ export {
|
||||
getAllTenantSubscriptionProducts,
|
||||
getTenantSubscriptionProduct,
|
||||
getTenantSubscriptionProductById,
|
||||
getTenantSubscriptionProductByStripeSubscriptionId,
|
||||
getTenantSubscriptionProductByBillingProviderSubscriptionId,
|
||||
type TenantSubscriptionProductPage,
|
||||
type TenantSubscriptionProductWithDetails,
|
||||
type TenantSubscriptionProductWithTenant,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
} from "@hivegrid/db/subscriptions.server";
|
||||
|
||||
export async function addTenantSubscriptionProduct(data: TenantSubscriptionProductCreateInput) {
|
||||
const item = await persistTenantSubscriptionProduct(data);
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ vi.mock("~/utils/cache.server", () => {
|
||||
});
|
||||
|
||||
vi.mock("~/shared-store.server", async () => {
|
||||
const { MemoryAdapter, createSharedStore } = await import("@toolctrl/shared-store");
|
||||
const { MemoryAdapter, createSharedStore } = await import("@hivegrid/shared-store");
|
||||
const adapter = new MemoryAdapter();
|
||||
const store = createSharedStore({ namespace: "web-test", adapter });
|
||||
return {
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { createTwoTierCache, type TwoTierCache } from "@toolctrl/shared-store";
|
||||
import { createTwoTierCache, type TwoTierCache } from "@hivegrid/shared-store";
|
||||
import { getSharedStore } from "~/shared-store.server";
|
||||
import { clearCacheKey, clearCacheKeyPrefix } from "~/utils/cache.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
|
||||
+4
-4
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
// Stripe-driven subscription mutations must purge the cache cross-replica,
|
||||
// Billing-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).
|
||||
//
|
||||
@@ -15,7 +15,7 @@ function getMocks(): CacheMocks {
|
||||
return store.__tenantSubsDbCacheMocks__;
|
||||
}
|
||||
|
||||
vi.mock("@toolctrl/db/subscriptions.server", () => ({
|
||||
vi.mock("@hivegrid/db/subscriptions.server", () => ({
|
||||
createTenantSubscription: vi.fn(),
|
||||
getTenantSubscription: vi.fn(),
|
||||
getTenantSubscriptions: vi.fn(),
|
||||
@@ -29,7 +29,7 @@ import { createTenantSubscription, updateTenantSubscriptionCustomerId } from "./
|
||||
import {
|
||||
createTenantSubscription as persistTenantSubscription,
|
||||
updateTenantSubscriptionCustomerId as persistTenantSubscriptionCustomerId,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
} from "@hivegrid/db/subscriptions.server";
|
||||
|
||||
const mocks = getMocks();
|
||||
|
||||
@@ -52,7 +52,7 @@ describe("tenantSubscriptions db wrapper — cross-replica cache invalidation",
|
||||
{} as Awaited<ReturnType<typeof persistTenantSubscriptionCustomerId>>,
|
||||
);
|
||||
|
||||
await updateTenantSubscriptionCustomerId("tenant-b", { stripeCustomerId: "cus_y" });
|
||||
await updateTenantSubscriptionCustomerId("tenant-b", { billingProviderCustomerId: "cus_y" });
|
||||
|
||||
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledWith("tenant-b");
|
||||
|
||||
+5
-5
@@ -3,10 +3,10 @@ import {
|
||||
getTenantSubscription as readTenantSubscription,
|
||||
updateTenantSubscriptionCustomerId as persistTenantSubscriptionCustomerId,
|
||||
type TenantSubscriptionWithDetails,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
} from "@hivegrid/db/subscriptions.server";
|
||||
import { clearTenantSubscriptionCache } from "~/utils/services/.server/subscriptionService";
|
||||
|
||||
export { getTenantSubscription, getTenantSubscriptions, type TenantSubscriptionWithDetails } from "@toolctrl/db/subscriptions.server";
|
||||
export { getTenantSubscription, getTenantSubscriptions, type TenantSubscriptionWithDetails } from "@hivegrid/db/subscriptions.server";
|
||||
|
||||
export async function getOrPersistTenantSubscription(tenantId: string): Promise<TenantSubscriptionWithDetails> {
|
||||
const subscription = await readTenantSubscription(tenantId);
|
||||
@@ -17,15 +17,15 @@ export async function getOrPersistTenantSubscription(tenantId: string): Promise<
|
||||
return subscription;
|
||||
}
|
||||
|
||||
export async function createTenantSubscription(tenantId: string, stripeCustomerId: string) {
|
||||
const item = await persistTenantSubscription({ tenantId, stripeCustomerId });
|
||||
export async function createTenantSubscription(tenantId: string, billingProviderCustomerId: string) {
|
||||
const item = await persistTenantSubscription({ tenantId, billingProviderCustomerId });
|
||||
// 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 }) {
|
||||
export async function updateTenantSubscriptionCustomerId(tenantId: string, data: { billingProviderCustomerId: string }) {
|
||||
const item = await persistTenantSubscriptionCustomerId(tenantId, data);
|
||||
clearTenantSubscriptionCache(tenantId);
|
||||
return item;
|
||||
|
||||
+46
-1
@@ -101,6 +101,7 @@ import {
|
||||
getTenantsInIds,
|
||||
requireTenant,
|
||||
updateTenant,
|
||||
updateTenantAnrede,
|
||||
updateTenantDeactivated,
|
||||
updateTenantTheme,
|
||||
} from "./tenants.db.server";
|
||||
@@ -233,12 +234,40 @@ describe("tenants db wrapper", () => {
|
||||
expect(result.pagination).toEqual({ page: 1, pageSize: 10, totalItems: 3, totalPages: 1 });
|
||||
});
|
||||
|
||||
it("filters for tenants without any type when typeId is 'null' and no base or user filter exists", async () => {
|
||||
vi.mocked(RowFiltersHelper.getFiltersCondition).mockReturnValue(undefined as never);
|
||||
vi.mocked(dbMock.tenant.findMany).mockResolvedValueOnce([] as never);
|
||||
vi.mocked(dbMock.tenant.count).mockResolvedValueOnce(0);
|
||||
|
||||
await adminGetAllTenantsWithUsage({ query: "", properties: [{ name: "typeId", value: "null" }] } as never);
|
||||
|
||||
expect(dbMock.tenant.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { types: { none: {} } } }));
|
||||
expect(dbMock.tenant.count).toHaveBeenCalledWith({ where: { types: { none: {} } } });
|
||||
});
|
||||
|
||||
it("filters by a concrete tenant type when no base or user filter exists", async () => {
|
||||
vi.mocked(RowFiltersHelper.getFiltersCondition).mockReturnValue(undefined as never);
|
||||
vi.mocked(dbMock.tenant.findMany).mockResolvedValueOnce([] as never);
|
||||
vi.mocked(dbMock.tenant.count).mockResolvedValueOnce(0);
|
||||
|
||||
await adminGetAllTenantsWithUsage({ query: "", properties: [{ name: "typeId", value: "type_pro" }] } as never);
|
||||
|
||||
expect(dbMock.tenant.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { types: { some: { id: "type_pro" } } } }));
|
||||
});
|
||||
|
||||
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 the resolved tenant when requireTenant finds one", async () => {
|
||||
vi.mocked(dbMock.tenant.findUnique).mockResolvedValueOnce({ id: "tenant_1" } as never);
|
||||
|
||||
await expect(requireTenant("tenant_1")).resolves.toEqual({ id: "tenant_1" });
|
||||
expect(cachified).toHaveBeenCalledWith(expect.objectContaining({ key: "tenant:tenant_1" }));
|
||||
});
|
||||
|
||||
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();
|
||||
@@ -412,6 +441,23 @@ describe("tenants db wrapper", () => {
|
||||
expect(clearCacheKeyPrefix).toHaveBeenCalledWith("apiKeyHash:");
|
||||
});
|
||||
|
||||
it("updates the tenant Anrede (du/Sie) and invalidates all identity and api-key caches", async () => {
|
||||
vi.mocked(dbMock.tenant.update).mockResolvedValueOnce({ id: "tenant_1", slug: "acme" } as never);
|
||||
|
||||
await updateTenantAnrede("tenant_1", "du");
|
||||
|
||||
expect(dbMock.tenant.update).toHaveBeenCalledWith({
|
||||
where: { id: "tenant_1" },
|
||||
data: { anrede: "du" },
|
||||
});
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("tenant:acme");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("tenant:tenant_1");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("tenantIdOrSlug:tenant_1");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("tenantIdOrSlug:acme");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("tenantSimple:tenant_1");
|
||||
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);
|
||||
|
||||
@@ -549,7 +595,6 @@ describe("tenants db wrapper", () => {
|
||||
subscription: true,
|
||||
users: true,
|
||||
invitations: true,
|
||||
rows: true,
|
||||
logs: true,
|
||||
apiKeys: true,
|
||||
userRoles: true,
|
||||
|
||||
+19
-8
@@ -1,4 +1,4 @@
|
||||
import { Prisma, Role, Tenant, TenantInboundAddress, TenantSettingsRow, TenantType, TenantUser } from "@toolctrl/db/prisma-browser";
|
||||
import { Prisma, Role, Tenant, TenantInboundAddress, TenantType, TenantUser } from "@hivegrid/db/prisma-browser";
|
||||
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { TenantUserJoined } from "~/application/enums/tenants/TenantUserJoined";
|
||||
@@ -10,14 +10,12 @@ 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";
|
||||
import { PLUGIN_HOOK_TENANT_CREATED } from "@hivegrid/plugin-runtime";
|
||||
|
||||
export type TenantSimple = {
|
||||
id: string;
|
||||
@@ -42,7 +40,6 @@ export type TenantWithDetails = Tenant & {
|
||||
user: UserSimple;
|
||||
})[];
|
||||
subscription: TenantSubscriptionWithDetails | null;
|
||||
tenantSettingsRow: (TenantSettingsRow & { row: RowWithDetails }) | null;
|
||||
types: TenantType[];
|
||||
};
|
||||
|
||||
@@ -50,7 +47,6 @@ export type TenantWithUsage = TenantWithDetails & {
|
||||
_count: {
|
||||
users?: number;
|
||||
invitations?: number;
|
||||
rows?: number;
|
||||
logs?: number;
|
||||
apiKeys?: number;
|
||||
events?: number;
|
||||
@@ -155,7 +151,6 @@ export async function adminGetAllTenantsWithUsage(
|
||||
products: { include: { ...TenantSubscriptionProductModelHelper.includeTenantSubscriptionProductDetails } },
|
||||
},
|
||||
},
|
||||
tenantSettingsRow: { include: { row: { include: RowModelHelper.includeRowDetails } } },
|
||||
types: true,
|
||||
_count: true,
|
||||
},
|
||||
@@ -445,6 +440,23 @@ export async function updateTenantTheme(id: string, data: { theme: string | null
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateTenantAnrede(id: string, anrede: string) {
|
||||
return await db.tenant
|
||||
.update({
|
||||
where: { id },
|
||||
data: { anrede },
|
||||
})
|
||||
.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({
|
||||
@@ -605,7 +617,6 @@ export async function deleteTenant(id: string) {
|
||||
subscription: true,
|
||||
users: true,
|
||||
invitations: true,
|
||||
rows: true,
|
||||
logs: true,
|
||||
apiKeys: true,
|
||||
userRoles: true,
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const createUniqueTenantIpAddressRecord = vi.fn();
|
||||
|
||||
vi.mock("@toolctrl/db/auth-boundary.server", () => ({
|
||||
vi.mock("@hivegrid/db/auth-boundary.server", () => ({
|
||||
createUniqueTenantIpAddressRecord,
|
||||
}));
|
||||
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
import { createUniqueTenantIpAddressRecord } from "@toolctrl/db/auth-boundary.server";
|
||||
import { ApiKey, Tenant, TenantIpAddress } from "@toolctrl/db/prisma-browser";
|
||||
import { createUniqueTenantIpAddressRecord } from "@hivegrid/db/auth-boundary.server";
|
||||
import { ApiKey, Tenant, TenantIpAddress } from "@hivegrid/db/prisma-browser";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { UserSimple } from "../users.db.server";
|
||||
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
|
||||
|
||||
+55
-26
@@ -1,5 +1,6 @@
|
||||
import { Prisma, SubscriptionProduct, TenantType } from "@toolctrl/db/prisma-browser";
|
||||
import { Prisma, SubscriptionProduct, TenantType } from "@hivegrid/db/prisma-browser";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { cachified, clearCacheKey } from "~/utils/cache.server";
|
||||
|
||||
export type TenantTypeWithDetails = TenantType & {
|
||||
subscriptionProducts: SubscriptionProduct[];
|
||||
@@ -9,15 +10,28 @@ const includeDetails = {
|
||||
subscriptionProducts: true,
|
||||
_count: { select: { tenants: true } },
|
||||
};
|
||||
|
||||
// TenantTypes are a quasi-static, non-tenant-scoped table read on every authenticated app pageview
|
||||
// (loadAppData). The cache is invalidated on every tenant-type mutation below. NOTE: the embedded
|
||||
// `_count.tenants` also changes when tenants are created/deleted (outside this module's scope), so a
|
||||
// short TTL is used to keep that count from drifting more than a few minutes on the app overview.
|
||||
const TENANT_TYPES_CACHE_KEY = "tenantTypes:all";
|
||||
const TENANT_TYPES_CACHE_TTL = 1000 * 60 * 5; // 5min — bounded staleness for the embedded tenant count
|
||||
|
||||
export async function getAllTenantTypes(): Promise<TenantTypeWithDetails[]> {
|
||||
return await db.tenantType.findMany({
|
||||
include: {
|
||||
subscriptionProducts: true,
|
||||
_count: { select: { tenants: true } },
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "asc",
|
||||
},
|
||||
return await cachified({
|
||||
key: TENANT_TYPES_CACHE_KEY,
|
||||
ttl: TENANT_TYPES_CACHE_TTL,
|
||||
getFreshValue: () =>
|
||||
db.tenantType.findMany({
|
||||
include: {
|
||||
subscriptionProducts: true,
|
||||
_count: { select: { tenants: true } },
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "asc",
|
||||
},
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -63,17 +77,22 @@ export async function createTenantType(data: {
|
||||
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 })),
|
||||
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 })),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(TENANT_TYPES_CACHE_KEY);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateTenantType(
|
||||
@@ -97,14 +116,24 @@ export async function updateTenantType(
|
||||
set: data.subscriptionProducts.map((id) => ({ id })),
|
||||
};
|
||||
}
|
||||
return await db.tenantType.update({
|
||||
where: { id: id },
|
||||
data: update,
|
||||
});
|
||||
return await db.tenantType
|
||||
.update({
|
||||
where: { id: id },
|
||||
data: update,
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(TENANT_TYPES_CACHE_KEY);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteTenantType(id: string) {
|
||||
return await db.tenantType.delete({
|
||||
where: { id: id },
|
||||
});
|
||||
return await db.tenantType
|
||||
.delete({
|
||||
where: { id: id },
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(TENANT_TYPES_CACHE_KEY);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { AdminUser, Role, Tenant, TenantUser, UserRole } from "@toolctrl/db/prisma-browser";
|
||||
import { AdminUser, Role, Tenant, TenantUser, UserRole } from "@hivegrid/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";
|
||||
@@ -7,13 +7,13 @@ 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 { Prisma } from "@hivegrid/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";
|
||||
import { PLUGIN_HOOK_USER_CREATED } from "@hivegrid/plugin-runtime";
|
||||
|
||||
const usersLogger = createScopedLogger("db.users");
|
||||
|
||||
@@ -417,6 +417,28 @@ export async function disableUserTotp(userId: string | undefined) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Batch variant of `getUserTotpStatus` for list views (e.g. the members table):
|
||||
* returns the subset of the given user ids that have TOTP fully enabled
|
||||
* (secret + enabledAt set). Uses a single query instead of one findUnique per
|
||||
* user, avoiding an N+1 when rendering member lists. The enabled predicate
|
||||
* matches `getUserTotpStatus().enabled` exactly.
|
||||
*/
|
||||
export async function getEnabledTotpUserIds(userIds: string[]): Promise<string[]> {
|
||||
if (userIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const rows = await db.user.findMany({
|
||||
where: {
|
||||
id: { in: userIds },
|
||||
totpSecretEncrypted: { not: null },
|
||||
totpEnabledAt: { not: null },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
return rows.map((row) => row.id);
|
||||
}
|
||||
|
||||
export async function getUserTotpStatus(userId: string | undefined): Promise<UserTotpStatus | null> {
|
||||
if (!userId) {
|
||||
return null;
|
||||
|
||||
@@ -18,7 +18,8 @@ vi.mock("../db.server", () => ({
|
||||
},
|
||||
}));
|
||||
vi.mock("../cache.server", () => ({ cachified: vi.fn(), clearCacheKey: vi.fn() }));
|
||||
vi.mock("~/modules/crm/services/CrmService", () => ({ default: { createContact: vi.fn() } }));
|
||||
// R-P14C: the modules/crm legacy CrmService was removed; its (vestigial) mock is
|
||||
// dropped — users.db.server no longer imports it (see users.db.server.test.ts).
|
||||
|
||||
const testDir = path.dirname(fileURLToPath(import.meta.url));
|
||||
const usersSource = readFileSync(path.join(testDir, "users.db.server.ts"), "utf8");
|
||||
|
||||
Reference in new issue
Block a user