Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/utils/integrations/projects/projectService.tenant-ownership.test.ts
T

534 lines
19 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
tx: {
pipeline: { findFirst: vi.fn(), update: vi.fn() },
pipelineStage: { findFirst: vi.fn(), update: vi.fn(), create: vi.fn(), findMany: vi.fn() },
pipelineAccess: { findFirst: vi.fn(), update: vi.fn(), create: vi.fn() },
pipelineFieldConfig: { findFirst: vi.fn(), findMany: vi.fn(), update: vi.fn(), create: vi.fn() },
pipelineFieldVisibility: { findFirst: vi.fn(), update: vi.fn(), create: vi.fn() },
role: { findFirst: vi.fn() },
group: { findFirst: vi.fn() },
tenantUser: { findFirst: vi.fn(), findMany: vi.fn() },
kontakt: { findFirst: vi.fn() },
inboxLead: { findFirst: vi.fn() },
projekt: { findFirst: vi.fn(), create: vi.fn(), update: vi.fn() },
projektKontakt: { create: vi.fn() },
auftragPipelineStageConfig: { findFirst: vi.fn() },
lostReason: { findFirst: vi.fn() },
abnahmeProtokoll: { findFirst: vi.fn() },
appEntityBinding: { findFirst: vi.fn() },
projektStageChange: { findFirst: vi.fn(), create: vi.fn(), update: vi.fn() },
hiveNumberSeq: { findUnique: vi.fn(), update: vi.fn() },
$executeRaw: vi.fn(),
$queryRaw: vi.fn(),
},
logActivity: vi.fn(),
publishOutboxEvent: vi.fn(),
publishProjectSearchUpsert: vi.fn(),
}));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
withTenantRLS: async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
}));
vi.mock("@hivegrid/activity", () => ({ logActivity: mocks.logActivity }));
vi.mock("@hivegrid/db/outbox", () => ({ publishOutboxEvent: mocks.publishOutboxEvent }));
vi.mock("@hivegrid/queue", () => ({ buildWorkflowTriggerOutboxEvent: vi.fn(() => ({})) }));
vi.mock("~/services/search/searchIndexProjection.server", () => ({
publishLeadSearchUpsert: vi.fn(),
publishProjectSearchUpsert: mocks.publishProjectSearchUpsert,
}));
import {
createProject,
moveProjectStage,
normalizeBulkProjectIds,
PROJECT_BULK_MOVE_MAX_ENTRIES,
undoLastProjectStageChange,
updateProjectStammdaten,
upsertPipelineAccess,
upsertPipelineFieldConfig,
upsertPipelineFieldVisibility,
upsertPipelineStage,
} from "./projectService.server";
describe("project parent ownership boundaries", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.tx.pipeline.findFirst.mockResolvedValue({ id: "pipeline-a" });
mocks.tx.pipelineStage.findFirst.mockResolvedValue({ id: "stage-a" });
mocks.tx.role.findFirst.mockResolvedValue({ id: "role-a" });
mocks.tx.group.findFirst.mockResolvedValue({ id: "group-a" });
mocks.tx.tenantUser.findFirst.mockResolvedValue({ userId: "user-a" });
mocks.tx.tenantUser.findMany.mockResolvedValue([]);
mocks.tx.pipelineAccess.findFirst.mockResolvedValue(null);
mocks.tx.pipelineFieldConfig.findFirst.mockResolvedValue(null);
mocks.tx.pipelineFieldConfig.findMany.mockResolvedValue([]);
mocks.tx.pipelineFieldVisibility.findFirst.mockResolvedValue(null);
mocks.tx.projektStageChange.create.mockResolvedValue({ id: "stage-change-a" });
mocks.tx.appEntityBinding.findFirst.mockResolvedValue(null);
mocks.tx.$queryRaw.mockResolvedValue([{ blueprintId: null, tenantOverride: "disabled" }]);
});
it("bounds and deduplicates bulk stage-move IDs", () => {
expect(normalizeBulkProjectIds([" project-a ", "project-a", "", "project-b"])).toEqual(["project-a", "project-b"]);
expect(() => normalizeBulkProjectIds(Array.from({ length: PROJECT_BULK_MOVE_MAX_ENTRIES + 1 }, (_, index) => `project-${index}`))).toThrow(
"foundation.mass_action_exceeds_limit"
);
});
it("rejects a pipeline access rule whose pipeline belongs to another tenant", async () => {
mocks.tx.pipeline.findFirst.mockResolvedValueOnce(null);
await expect(
upsertPipelineAccess({
tenantId: "tenant-a",
pipelineId: "pipeline-from-tenant-b",
principalType: "role",
principalId: "role-a",
}),
).rejects.toThrow();
expect(mocks.tx.pipeline.findFirst).toHaveBeenCalledWith({
where: { id: "pipeline-from-tenant-b", tenantId: "tenant-a", archivedAt: null },
select: { id: true },
});
expect(mocks.tx.pipelineAccess.create).not.toHaveBeenCalled();
expect(mocks.tx.pipelineAccess.update).not.toHaveBeenCalled();
});
it("rejects a cross-tenant principal and scopes an existing access update", async () => {
mocks.tx.role.findFirst.mockResolvedValueOnce(null);
await expect(
upsertPipelineAccess({
tenantId: "tenant-a",
pipelineId: "pipeline-a",
principalType: "role",
principalId: "role-from-tenant-b",
}),
).rejects.toThrow();
expect(mocks.tx.pipelineAccess.create).not.toHaveBeenCalled();
expect(mocks.tx.role.findFirst).toHaveBeenCalledWith({
where: { id: "role-from-tenant-b", tenantId: "tenant-a" },
select: { id: true },
});
mocks.tx.pipelineAccess.findFirst.mockResolvedValueOnce({ id: "access-a" });
await upsertPipelineAccess({
tenantId: "tenant-a",
pipelineId: "pipeline-a",
principalType: "role",
principalId: "role-a",
kannBearbeiten: true,
});
expect(mocks.tx.pipelineAccess.update).toHaveBeenCalledWith({
where: { id: "access-a", tenantId: "tenant-a" },
data: { kannSehen: true, kannBearbeiten: true },
});
});
it("rejects a field config whose stage is not owned by the tenant pipeline", async () => {
mocks.tx.pipelineStage.findFirst.mockResolvedValueOnce(null);
await expect(
upsertPipelineFieldConfig({
tenantId: "tenant-a",
pipelineId: "pipeline-a",
stageId: "stage-from-tenant-b",
fieldKey: "auftragsvolumen",
}),
).rejects.toThrow();
expect(mocks.tx.pipelineFieldConfig.create).not.toHaveBeenCalled();
expect(mocks.tx.pipelineFieldConfig.update).not.toHaveBeenCalled();
});
it("serializes nullable-stage field config upserts with a transaction advisory lock", async () => {
await upsertPipelineFieldConfig({
tenantId: "tenant-a",
pipelineId: "pipeline-a",
stageId: null,
fieldKey: "aggregate:forecast",
});
expect(mocks.tx.$executeRaw).toHaveBeenCalledOnce();
expect(mocks.tx.pipelineFieldConfig.findFirst).toHaveBeenCalledWith({
where: {
tenantId: "tenant-a",
pipelineId: "pipeline-a",
stageId: null,
fieldKey: "aggregate:forecast",
},
select: { id: true },
});
expect(mocks.tx.pipelineFieldConfig.create).toHaveBeenCalledOnce();
});
it("rejects field visibility for a foreign field config before its compound key can upsert", async () => {
mocks.tx.pipelineFieldConfig.findFirst.mockResolvedValueOnce(null);
await expect(
upsertPipelineFieldVisibility({
tenantId: "tenant-a",
fieldConfigId: "config-from-tenant-b",
principalType: "user",
principalId: "user-a",
}),
).rejects.toThrow();
expect(mocks.tx.pipelineFieldVisibility.create).not.toHaveBeenCalled();
expect(mocks.tx.pipelineFieldVisibility.update).not.toHaveBeenCalled();
});
it("rejects project creation with a stage outside the tenant pipeline before reserving a number", async () => {
mocks.tx.pipelineStage.findFirst.mockResolvedValueOnce(null);
await expect(
createProject({
tenantId: "tenant-a",
userId: null,
ctx: { userId: "user-a", permissions: ["projects.write", "projects.read_all"] },
projektname: "Cross tenant attempt",
pipelineId: "pipeline-a",
stageId: "stage-from-tenant-b",
}),
).rejects.toThrow();
expect(mocks.tx.$executeRaw).not.toHaveBeenCalled();
expect(mocks.tx.projekt.create).not.toHaveBeenCalled();
});
it("rejects cross-tenant project owner, contact, and lead references before create", async () => {
mocks.tx.tenantUser.findMany.mockResolvedValueOnce([]);
await expect(
createProject({
tenantId: "tenant-a",
userId: null,
ctx: { userId: "user-a", permissions: ["projects.write", "projects.read_all"] },
projektname: "Foreign owner",
pipelineId: "pipeline-a",
stageId: "stage-a",
zustaendigePersonId: "user-from-tenant-b",
}),
).rejects.toThrow();
mocks.tx.kontakt.findFirst.mockResolvedValueOnce(null);
await expect(
createProject({
tenantId: "tenant-a",
userId: null,
ctx: { userId: "user-a", permissions: ["projects.write", "projects.read_all"] },
projektname: "Foreign contact",
pipelineId: "pipeline-a",
stageId: "stage-a",
kontaktId: "contact-from-tenant-b",
}),
).rejects.toThrow();
mocks.tx.inboxLead.findFirst.mockResolvedValueOnce(null);
await expect(
createProject({
tenantId: "tenant-a",
userId: null,
ctx: { userId: "user-a", permissions: ["projects.write", "projects.read_all"] },
projektname: "Foreign lead",
pipelineId: "pipeline-a",
stageId: "stage-a",
konvertiertAusLeadId: "lead-from-tenant-b",
}),
).rejects.toThrow();
expect(mocks.tx.$executeRaw).not.toHaveBeenCalled();
expect(mocks.tx.projekt.create).not.toHaveBeenCalled();
});
it("rejects cross-tenant stage IDs on project moves and stage upserts", async () => {
mocks.tx.projekt.findFirst.mockResolvedValueOnce({ id: "project-a", pipelineId: "pipeline-a" });
mocks.tx.pipelineStage.findFirst.mockResolvedValueOnce(null);
await expect(
moveProjectStage({
tenantId: "tenant-a",
projectId: "project-a",
targetStageId: "stage-from-tenant-b",
userId: "user-a",
ctx: { userId: "user-a", permissions: ["projects.read_all", "projects.change_stage"] },
}),
).rejects.toThrow();
expect(mocks.tx.projekt.findFirst).toHaveBeenCalledWith({
where: expect.objectContaining({
id: "project-a",
tenantId: "tenant-a",
pipeline: {
accessRules: {
none: {
tenantId: "tenant-a",
AND: [
{ OR: [{ principalType: "user", principalId: "user-a" }] },
{ OR: [{ kannSehen: false }, { kannBearbeiten: false }] },
],
},
},
},
}),
include: { stage: true },
});
expect(mocks.tx.projekt.update).not.toHaveBeenCalled();
mocks.tx.pipeline.findFirst.mockResolvedValueOnce(null);
await expect(
upsertPipelineStage({
tenantId: "tenant-a",
pipelineId: "pipeline-from-tenant-b",
name: "Foreign stage",
stageKind: "offen",
}),
).rejects.toThrow();
expect(mocks.tx.pipelineStage.create).not.toHaveBeenCalled();
});
it("rejects stage moves before database access when change-stage permission is missing", async () => {
await expect(
moveProjectStage({
tenantId: "tenant-a",
projectId: "project-a",
targetStageId: "stage-a",
userId: "user-a",
ctx: { userId: "user-a", permissions: ["projects.read_all"] },
}),
).rejects.toThrow();
expect(mocks.tx.projekt.findFirst).not.toHaveBeenCalled();
});
it("gates acceptance-required stages on completed protocols only, never on rejected ones", async () => {
// R-P9b DoD 6 — the gate must not open for a rejected protocol; only
// full/with_defects count as a completed acceptance.
mocks.tx.projekt.findFirst.mockResolvedValueOnce({
id: "project-a",
tenantId: "tenant-a",
pipelineId: "pipeline-a",
stageId: "stage-old",
wonAt: null,
lostAt: null,
stage: { id: "stage-old", stageKind: "offen" },
});
mocks.tx.pipelineStage.findFirst.mockResolvedValueOnce({
id: "stage-done",
tenantId: "tenant-a",
pipelineId: "pipeline-a",
name: "Abgeschlossen",
stageKind: "gewonnen",
});
mocks.tx.auftragPipelineStageConfig.findFirst.mockResolvedValueOnce({ requiresAcceptanceProtocol: true });
mocks.tx.abnahmeProtokoll.findFirst.mockResolvedValueOnce(null);
await expect(
moveProjectStage({
tenantId: "tenant-a",
projectId: "project-a",
targetStageId: "stage-done",
userId: "user-a",
ctx: { userId: "user-a", permissions: ["projects.read_all", "projects.change_stage"] },
}),
).rejects.toThrow("projects.error.acceptanceProtocolRequired");
expect(mocks.tx.abnahmeProtokoll.findFirst).toHaveBeenCalledWith({
where: expect.objectContaining({
tenantId: "tenant-a",
projektId: "project-a",
gesperrtAt: { not: null },
archivedAt: null,
acceptanceKind: { in: ["full", "with_defects"] },
}),
select: { id: true },
});
expect(mocks.tx.projekt.update).not.toHaveBeenCalled();
});
it("publishes a PII-free portal status-mail debounce event in the stage transaction", async () => {
const now = new Date("2026-07-15T10:00:00.000Z");
vi.useFakeTimers();
vi.setSystemTime(now);
mocks.tx.projekt.findFirst.mockResolvedValueOnce({
id: "project-a",
tenantId: "tenant-a",
pipelineId: "pipeline-a",
stageId: "stage-old",
projektNummer: "P-1",
wonAt: null,
lostAt: null,
stage: { id: "stage-old", stageKind: "gewonnen" },
});
mocks.tx.pipelineStage.findFirst.mockResolvedValueOnce({
id: "stage-new",
tenantId: "tenant-a",
pipelineId: "pipeline-a",
name: "Montage",
stageKind: "offen",
});
mocks.tx.auftragPipelineStageConfig.findFirst.mockResolvedValueOnce(null);
mocks.tx.projekt.update.mockResolvedValueOnce({
id: "project-a",
tenantId: "tenant-a",
pipelineId: "pipeline-a",
stageId: "stage-new",
projektNummer: "P-1",
projektname: "Projekt A",
konvertiertAusLeadId: null,
zustaendigePersonId: "user-a",
});
await moveProjectStage({
tenantId: "tenant-a",
projectId: "project-a",
targetStageId: "stage-new",
userId: "user-a",
ctx: { userId: "user-a", permissions: ["projects.read_all", "projects.change_stage"] },
});
expect(mocks.publishOutboxEvent).toHaveBeenCalledWith(
mocks.tx,
expect.objectContaining({
tenantId: "tenant-a",
type: "mail.portal-status.stage-changed",
dispatchKey: "portal-status:stage-change-a",
scheduledAt: new Date("2026-07-15T10:05:00.000Z"),
payload: {
version: 1,
tenantId: "tenant-a",
projectId: "project-a",
previousStageId: "stage-old",
expectedStageId: "stage-new",
stageChangeId: "stage-change-a",
},
}),
);
expect(JSON.stringify(mocks.publishOutboxEvent.mock.calls.at(-1)?.[1])).not.toContain("@");
vi.useRealTimers();
});
it("records an undo as a reverse stage transition and publishes the debounced portal status mail", async () => {
const now = new Date("2026-07-15T12:00:00.000Z");
vi.useFakeTimers();
vi.setSystemTime(now);
mocks.tx.projekt.findFirst.mockResolvedValueOnce({
id: "project-a",
tenantId: "tenant-a",
pipelineId: "pipeline-a",
stageId: "stage-new",
projektNummer: "P-1",
wonAt: null,
lostAt: null,
lostReasonId: null,
});
mocks.tx.projektStageChange.findFirst.mockResolvedValueOnce({
id: "forward-change",
fromStageId: "stage-old",
toStageId: "stage-new",
});
mocks.tx.pipelineStage.findFirst.mockResolvedValueOnce({ id: "stage-old", name: "Planung", stageKind: "offen" });
mocks.tx.projekt.update.mockResolvedValueOnce({
id: "project-a",
tenantId: "tenant-a",
pipelineId: "pipeline-a",
stageId: "stage-old",
projektNummer: "P-1",
projektname: "Projekt A",
konvertiertAusLeadId: null,
zustaendigePersonId: "user-a",
});
mocks.tx.projektStageChange.create.mockResolvedValueOnce({ id: "reverse-change" });
await undoLastProjectStageChange({
tenantId: "tenant-a",
projectId: "project-a",
userId: "user-a",
ctx: { userId: "user-a", permissions: ["projects.read_all", "projects.change_stage"] },
});
expect(mocks.tx.projektStageChange.update).toHaveBeenCalledWith({
where: { id: "forward-change", tenantId: "tenant-a" },
data: { undoneAt: now },
});
expect(mocks.tx.projektStageChange.create).toHaveBeenCalledWith({
data: expect.objectContaining({
tenantId: "tenant-a",
projektId: "project-a",
fromStageId: "stage-new",
toStageId: "stage-old",
}),
});
expect(mocks.publishOutboxEvent).toHaveBeenCalledWith(
mocks.tx,
expect.objectContaining({
type: "mail.portal-status.stage-changed",
dispatchKey: "portal-status:reverse-change",
scheduledAt: new Date("2026-07-15T12:05:00.000Z"),
payload: expect.objectContaining({
previousStageId: "stage-new",
expectedStageId: "stage-old",
stageChangeId: "reverse-change",
}),
}),
);
vi.useRealTimers();
});
it("honors an explicit field edit denial during project quick-create", async () => {
mocks.tx.pipelineFieldConfig.findMany.mockResolvedValueOnce([
{
fieldKey: "potenziellerAuftragswert",
stageId: "stage-a",
sichtbar: true,
visibilities: [{ kannSehen: true, kannBearbeiten: false }],
},
]);
await expect(
createProject({
tenantId: "tenant-a",
userId: null,
ctx: { userId: "user-a", permissions: ["projects.write", "projects.read_all", "deals.read_volume_all"] },
projektname: "Blocked value",
pipelineId: "pipeline-a",
stageId: "stage-a",
potenziellerAuftragswert: "50000",
}),
).rejects.toMatchObject({ messageKey: "projects.error.volumeNotEditable" });
expect(mocks.tx.projekt.create).not.toHaveBeenCalled();
});
it("honors an explicit field edit denial when updating project volume", async () => {
mocks.tx.projekt.findFirst.mockResolvedValueOnce({
id: "project-a",
tenantId: "tenant-a",
pipelineId: "pipeline-a",
stageId: "stage-a",
zustaendigePersonId: "user-a",
projektleiterId: null,
});
mocks.tx.pipelineFieldConfig.findMany.mockResolvedValueOnce([
{
fieldKey: "auftragsvolumen",
stageId: "stage-a",
sichtbar: true,
visibilities: [{ kannSehen: true, kannBearbeiten: false }],
},
]);
await expect(
updateProjectStammdaten({
tenantId: "tenant-a",
projectId: "project-a",
userId: "user-a",
ctx: {
userId: "user-a",
permissions: ["projects.read_all", "projects.write", "deals.read_volume_all"],
},
auftragsvolumen: "12500",
}),
).rejects.toMatchObject({ messageKey: "projects.error.volumeNotEditable" });
expect(mocks.tx.projekt.update).not.toHaveBeenCalled();
});
});