Files

898 lines
35 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from "vitest";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
const mocks = vi.hoisted(() => ({
withTenantRLS: vi.fn(),
listApprovedAbsencesForRange: vi.fn(),
putBufferAsFile: vi.fn(),
deleteFile: vi.fn(),
buildPdfExportArtifact: vi.fn(),
withStorageReservation: vi.fn(),
publishOutboxEvent: vi.fn(),
createAcceptanceFollowUpTask: vi.fn(),
tx: {
projekt: { findFirst: vi.fn(), findMany: vi.fn(), update: vi.fn() },
pipelineStage: { findFirst: vi.fn() },
projektStageChange: { create: vi.fn() },
scheduleEntry: { findFirst: vi.fn(), findMany: vi.fn(), findUniqueOrThrow: vi.fn(), update: vi.fn(), updateMany: vi.fn(), create: vi.fn() },
scheduleConflict: { deleteMany: vi.fn(), createMany: vi.fn() },
tenantUser: { findFirst: vi.fn() },
projektChecklist: { findFirst: vi.fn() },
file: { findMany: vi.fn(), create: vi.fn() },
fileEntityLink: { create: vi.fn() },
abnahmeProtokoll: { findFirst: vi.fn(), findMany: vi.fn(), findUniqueOrThrow: vi.fn(), create: vi.fn(), update: vi.fn() },
abnahmeSignatur: { createMany: vi.fn() },
notificationDelivery: { upsert: vi.fn(), create: vi.fn() },
offlineSyncMutation: { findUnique: vi.fn(), create: vi.fn(), updateMany: vi.fn() },
$executeRaw: vi.fn(),
},
idempotency: { claim: vi.fn(), complete: vi.fn(), get: vi.fn(), forget: vi.fn() },
}));
vi.mock("@hivegrid/shared-store", () => ({
createIdempotencyStore: () => mocks.idempotency,
}));
vi.mock("@hivegrid/db/storage-capacity.server", () => ({
withTenantStorageWriteReservation: (...args: unknown[]) => mocks.withStorageReservation(...args),
}));
vi.mock("~/shared-store.server", () => ({ getSharedStore: () => ({}) }));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
withTenantRLS: mocks.withTenantRLS,
}));
vi.mock("~/utils/integrations/hrLeaveService.server", () => ({
listApprovedAbsencesForRange: mocks.listApprovedAbsencesForRange,
listApprovedAbsencesForRangeWithTx: mocks.listApprovedAbsencesForRange,
}));
vi.mock("~/utils/integrations/storageService", () => ({
putBufferAsFile: mocks.putBufferAsFile,
deleteFile: mocks.deleteFile,
resolveStorageBucket: () => "test-bucket",
}));
vi.mock("@hivegrid/exports/pdf", () => ({ buildPdfExportArtifact: mocks.buildPdfExportArtifact }));
vi.mock("~/locale/i18next.global.server", () => ({ ensureServerGlobalI18n: vi.fn() }));
vi.mock("~/locale/request-scoped-t", () => ({ requestScopedT: (key: string) => key }));
vi.mock("@hivegrid/activity", () => ({ logActivity: vi.fn(async () => undefined) }));
vi.mock("@hivegrid/db/outbox", () => ({ publishOutboxEvent: mocks.publishOutboxEvent }));
vi.mock("~/utils/integrations/taskService.server", () => ({
createAcceptanceFollowUpTask: mocks.createAcceptanceFollowUpTask,
}));
import {
applyOfflineMutation,
archiveAcceptanceProtocol,
bulkReassignScheduleEntries,
listEditablePlantafelProjectOptions,
listAcceptanceProtocols,
loadPlantafel,
ensurePlantafelRange,
normalizeBulkScheduleEntryIds,
parseOfflineSyncOperation,
parsePlantafelDateInput,
PLANTAFEL_BULK_REASSIGN_MAX_ENTRIES,
PLANTAFEL_MAX_RANGE_DAYS,
PLANTAFEL_PROJECT_PICKER_LIMIT,
submitAcceptanceProtocol,
updateAcceptanceProtocolContent,
upsertScheduleEntry,
updateScheduleEntryStatus,
type PlantafelContext,
} from "./plantafelAcceptanceService.server";
function context(permissions: readonly string[]): PlantafelContext {
return {
tenantId: "tenant-a",
userId: "user-a",
permissions,
roleIds: ["role-a"],
groupIds: ["group-a"],
hasModule: true,
};
}
function project(id = "project-a") {
return {
id,
tenantId: "tenant-a",
projektNummer: "P-001",
projektname: "Project",
pipelineId: "pipeline-a",
stageId: "stage-a",
};
}
describe("plantafel and acceptance authorization", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.withTenantRLS.mockImplementation(async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx));
mocks.listApprovedAbsencesForRange.mockResolvedValue([]);
mocks.putBufferAsFile.mockResolvedValue({ publicUrl: null });
mocks.deleteFile.mockResolvedValue(undefined);
mocks.publishOutboxEvent.mockResolvedValue(undefined);
mocks.createAcceptanceFollowUpTask.mockResolvedValue(undefined);
mocks.buildPdfExportArtifact.mockResolvedValue({
bytes: new Uint8Array([1, 2, 3]),
contentType: "application/pdf",
byteLength: 3,
});
mocks.withStorageReservation.mockImplementation(async (input) => {
const stored = await input.upload();
return input.runTransaction((tx) => input.commit(tx, stored));
});
mocks.tx.scheduleEntry.updateMany.mockResolvedValue({ count: 0 });
mocks.tx.offlineSyncMutation.updateMany.mockResolvedValue({ count: 1 });
mocks.idempotency.claim.mockResolvedValue(true);
mocks.idempotency.complete.mockResolvedValue(undefined);
mocks.idempotency.get.mockResolvedValue(null);
mocks.idempotency.forget.mockResolvedValue(undefined);
});
it("rejects unknown offline operations instead of falling through to acceptance", async () => {
expect(parseOfflineSyncOperation("schedule_upsert")).toBe("schedule_upsert");
expect(() => parseOfflineSyncOperation("acceptance_delete")).toThrow("projects.error.unsupportedAction");
await expect(
applyOfflineMutation({
tenantId: "tenant-a",
ctx: context(["plantafel.write", "projects.read_all"]),
clientMutationId: "mutation-a",
operation: "acceptance_delete",
payload: {},
})
).rejects.toThrow("projects.error.unsupportedAction");
expect(mocks.withTenantRLS).not.toHaveBeenCalled();
});
it("requires the exact permission for each offline operation", async () => {
await expect(
applyOfflineMutation({
tenantId: "tenant-a",
ctx: context(["acceptance.write", "projects.read_all"]),
clientMutationId: "mutation-schedule",
operation: "schedule_status",
payload: { entryId: "entry-a", status: "done" },
})
).rejects.toThrow();
await expect(
applyOfflineMutation({
tenantId: "tenant-a",
ctx: context(["plantafel.write", "projects.read_all"]),
clientMutationId: "mutation-acceptance",
operation: "acceptance_submit",
payload: { projectId: "project-a" },
})
).rejects.toThrow();
expect(mocks.withTenantRLS).not.toHaveBeenCalled();
});
it("keeps an offline mutation payload immutable for a reused client id", async () => {
mocks.tx.offlineSyncMutation.findUnique.mockResolvedValue({
id: "offline-a",
tenantId: "tenant-a",
clientMutationId: "mutation-a",
createdByUserId: "user-a",
operation: "schedule_status",
payload: { entryId: "entry-a", status: "done" },
status: "pending",
resultEntityType: null,
resultEntityId: null,
});
await expect(
applyOfflineMutation({
tenantId: "tenant-a",
ctx: context(["plantafel.write", "projects.read_all"]),
clientMutationId: "mutation-a",
operation: "schedule_status",
payload: { entryId: "entry-a", status: "cancelled" },
})
).rejects.toMatchObject({ status: 404 });
expect(mocks.idempotency.claim).not.toHaveBeenCalled();
expect(mocks.tx.scheduleEntry.update).not.toHaveBeenCalled();
});
it("does not execute an offline mutation while another replica owns the claim", async () => {
const existing = {
id: "offline-a",
tenantId: "tenant-a",
clientMutationId: "mutation-a",
createdByUserId: "user-a",
operation: "schedule_status",
payload: { entryId: "entry-a", status: "done" },
status: "pending",
resultEntityType: null,
resultEntityId: null,
};
mocks.tx.offlineSyncMutation.findUnique.mockResolvedValue(existing);
mocks.idempotency.claim.mockResolvedValue(false);
await expect(
applyOfflineMutation({
tenantId: "tenant-a",
ctx: context(["plantafel.write", "projects.read_all"]),
clientMutationId: "mutation-a",
operation: "schedule_status",
payload: { status: "done", entryId: "entry-a" },
})
).rejects.toThrow("projects.error.offlineMutationPending");
expect(mocks.tx.scheduleEntry.findFirst).not.toHaveBeenCalled();
expect(mocks.tx.offlineSyncMutation.updateMany).not.toHaveBeenCalled();
});
it("limits plantafel entries to centrally readable projects", async () => {
mocks.tx.projekt.findMany.mockResolvedValue([{ id: "project-a", projektNummer: "P-001", projektname: "Project" }]);
mocks.tx.scheduleEntry.findMany.mockResolvedValue([
{
id: "entry-a",
projektId: "project-a",
assignedUserId: "user-a",
startAt: new Date("2026-07-02T08:00:00.000Z"),
endAt: new Date("2026-07-02T10:00:00.000Z"),
conflicts: [],
},
]);
await loadPlantafel({
tenantId: "tenant-a",
ctx: context(["plantafel.read_own", "projects.read_own_member"]),
from: new Date("2026-07-01T00:00:00.000Z"),
to: new Date("2026-07-08T00:00:00.000Z"),
});
expect(mocks.tx.scheduleEntry.findMany).toHaveBeenCalledWith({
where: expect.objectContaining({
tenantId: "tenant-a",
archivedAt: null,
assignedUserId: "user-a",
startAt: { lt: new Date("2026-07-08T00:00:00.000Z") },
endAt: { gt: new Date("2026-07-01T00:00:00.000Z") },
}),
include: { conflicts: { where: { resolvedAt: null }, orderBy: { createdAt: "asc" } } },
orderBy: [{ startAt: "asc" }, { assignedUserId: "asc" }],
});
expect(mocks.tx.projekt.findMany).toHaveBeenCalledWith({
where: expect.objectContaining({
tenantId: "tenant-a",
id: { in: ["project-a"] },
archivedAt: null,
AND: expect.arrayContaining([
{
OR: [
{
mitglieder: {
some: {
tenantId: "tenant-a",
archivedAt: null,
OR: [{ userId: "user-a" }, { groupId: { in: ["group-a"] } }],
},
},
},
],
},
expect.objectContaining({ pipeline: expect.any(Object) }),
]),
}),
select: { id: true, projektNummer: true, projektname: true },
});
});
it("reports a visible project as non-editable when the central edit scope denies it", async () => {
mocks.tx.scheduleEntry.findMany.mockResolvedValue([
{
id: "entry-visible",
projektId: "project-visible",
assignedUserId: "user-a",
startAt: new Date("2026-07-02T08:00:00.000Z"),
endAt: new Date("2026-07-02T10:00:00.000Z"),
conflicts: [],
},
]);
mocks.tx.projekt.findMany.mockResolvedValueOnce([{ id: "project-visible", projektNummer: "P-001", projektname: "Visible" }]).mockResolvedValueOnce([]);
const result = await loadPlantafel({
tenantId: "tenant-a",
ctx: context(["plantafel.read_all", "plantafel.write", "projects.read_all"]),
from: new Date("2026-07-01T00:00:00.000Z"),
to: new Date("2026-07-08T00:00:00.000Z"),
});
expect(result.entries).toHaveLength(1);
expect(result.editableProjectIds).toEqual([]);
expect(mocks.tx.projekt.findMany).toHaveBeenCalledTimes(2);
expect(JSON.stringify(mocks.tx.projekt.findMany.mock.calls[1]?.[0]?.where)).toContain("kannBearbeiten");
});
it("searches only editable projects with an explicit bounded result", async () => {
mocks.tx.projekt.findMany.mockResolvedValue(
Array.from({ length: PLANTAFEL_PROJECT_PICKER_LIMIT + 1 }, (_, index) => ({
id: `project-${index}`,
projektNummer: `P-${index}`,
projektname: `Wärmepumpe ${index}`,
}))
);
const result = await listEditablePlantafelProjectOptions({
tenantId: "tenant-a",
ctx: context(["plantafel.write", "projects.read_all"]),
query: " Wärme ",
});
expect(result.options).toHaveLength(PLANTAFEL_PROJECT_PICKER_LIMIT);
expect(result.hasMore).toBe(true);
expect(result.query).toBe("Wärme");
expect(mocks.tx.projekt.findMany).toHaveBeenCalledWith({
where: expect.objectContaining({
tenantId: "tenant-a",
archivedAt: null,
AND: expect.arrayContaining([
expect.objectContaining({ pipeline: expect.any(Object) }),
{
OR: [{ projektNummer: { contains: "Wärme", mode: "insensitive" } }, { projektname: { contains: "Wärme", mode: "insensitive" } }],
},
]),
}),
select: { id: true, projektNummer: true, projektname: true },
orderBy: [{ updatedAt: "desc" }, { id: "asc" }],
take: PLANTAFEL_PROJECT_PICKER_LIMIT + 1,
});
expect(JSON.stringify(mocks.tx.projekt.findMany.mock.calls[0]?.[0]?.where)).toContain("kannBearbeiten");
});
it("rejects reversed and remotely oversized plantafel windows before querying", async () => {
const from = new Date("2026-07-01T00:00:00.000Z");
expect(() => ensurePlantafelRange(from, from)).toThrow("projects.error.scheduleRangeInvalid");
expect(() => ensurePlantafelRange(from, new Date(from.getTime() + (PLANTAFEL_MAX_RANGE_DAYS + 1) * 24 * 60 * 60 * 1000))).toThrow(
"projects.error.scheduleRangeInvalid"
);
await expect(
loadPlantafel({
tenantId: "tenant-a",
ctx: context(["plantafel.read_all", "projects.read_all"]),
from,
to: new Date(from.getTime() + (PLANTAFEL_MAX_RANGE_DAYS + 1) * 24 * 60 * 60 * 1000),
})
).rejects.toThrow("projects.error.scheduleRangeInvalid");
expect(mocks.withTenantRLS).not.toHaveBeenCalled();
});
it("parses zoneless Plantafel inputs as Europe/Berlin in a UTC runtime and preserves explicit ISO zones", () => {
const previousTimezone = process.env.TZ;
process.env.TZ = "UTC";
try {
expect(parsePlantafelDateInput("2026-07-21T09:00")?.toISOString()).toBe("2026-07-21T07:00:00.000Z");
expect(parsePlantafelDateInput("2026-01-21T09:00")?.toISOString()).toBe("2026-01-21T08:00:00.000Z");
expect(parsePlantafelDateInput("2026-07-21T09:00:00.000Z")?.toISOString()).toBe("2026-07-21T09:00:00.000Z");
expect(parsePlantafelDateInput("2026-07-21T09:00:00+02:00")?.toISOString()).toBe("2026-07-21T07:00:00.000Z");
} finally {
if (previousTimezone === undefined) delete process.env.TZ;
else process.env.TZ = previousTimezone;
}
});
it("checks workday bounds in the app time zone instead of the UTC runtime", async () => {
const created = {
id: "entry-workday-start",
tenantId: "tenant-a",
projektId: "project-a",
assignedUserId: "user-a",
startAt: new Date("2026-07-21T04:00:00.000Z"),
endAt: new Date("2026-07-21T06:00:00.000Z"),
conflicts: [],
};
mocks.tx.tenantUser.findFirst.mockResolvedValue({ userId: "user-a" });
mocks.tx.projekt.findFirst.mockResolvedValue(project());
mocks.tx.scheduleEntry.findMany.mockResolvedValue([]);
mocks.tx.scheduleEntry.create.mockResolvedValue(created);
mocks.tx.scheduleEntry.findUniqueOrThrow.mockResolvedValue(created);
mocks.tx.scheduleConflict.deleteMany.mockResolvedValue({ count: 0 });
const previousTimezone = process.env.TZ;
process.env.TZ = "UTC";
try {
await upsertScheduleEntry({
tenantId: "tenant-a",
ctx: context(["plantafel.write", "projects.read_all"]),
projektId: "project-a",
assignedUserId: "user-a",
title: "Frühtermin",
startAt: "2026-07-21T06:00",
endAt: "2026-07-21T08:00",
});
} finally {
if (previousTimezone === undefined) delete process.env.TZ;
else process.env.TZ = previousTimezone;
}
expect(mocks.tx.scheduleEntry.create).toHaveBeenCalledWith({
data: expect.objectContaining({ startAt: created.startAt, endAt: created.endAt }),
});
expect(mocks.tx.scheduleConflict.createMany).not.toHaveBeenCalled();
});
it("rejects an inactive or foreign assignee on a single schedule upsert", async () => {
mocks.tx.tenantUser.findFirst.mockResolvedValue(null);
await expect(
upsertScheduleEntry({
tenantId: "tenant-a",
ctx: context(["plantafel.write", "projects.read_all"]),
projektId: "project-a",
assignedUserId: "user-foreign",
title: "Montage",
startAt: "2026-07-01T08:00:00.000Z",
endAt: "2026-07-01T10:00:00.000Z",
})
).rejects.toThrow();
expect(mocks.tx.projekt.findFirst).not.toHaveBeenCalled();
expect(mocks.tx.scheduleEntry.create).not.toHaveBeenCalled();
});
it("locks the assignee and persists a schedule entry with its conflicts in one transaction", async () => {
const created = {
id: "entry-a",
tenantId: "tenant-a",
projektId: "project-a",
assignedUserId: "user-a",
startAt: new Date("2026-07-01T08:00:00.000Z"),
endAt: new Date("2026-07-01T10:00:00.000Z"),
conflicts: [],
};
mocks.tx.tenantUser.findFirst.mockResolvedValue({ userId: "user-a" });
mocks.tx.projekt.findFirst.mockResolvedValue(project());
mocks.tx.scheduleEntry.findMany.mockResolvedValue([]);
mocks.tx.scheduleEntry.create.mockResolvedValue(created);
mocks.tx.scheduleEntry.findUniqueOrThrow.mockResolvedValue(created);
mocks.tx.scheduleConflict.deleteMany.mockResolvedValue({ count: 0 });
await expect(
upsertScheduleEntry({
tenantId: "tenant-a",
ctx: context(["plantafel.write", "projects.read_all"]),
projektId: "project-a",
assignedUserId: "user-a",
title: "Montage",
startAt: created.startAt,
endAt: created.endAt,
})
).resolves.toMatchObject({ entry: { id: "entry-a" }, conflicts: [] });
expect(mocks.withTenantRLS).toHaveBeenCalledTimes(1);
expect(mocks.tx.$executeRaw).toHaveBeenCalledOnce();
expect(String(mocks.tx.$executeRaw.mock.calls[0]?.[0])).toContain("pg_advisory_xact_lock");
expect(mocks.tx.scheduleConflict.deleteMany).toHaveBeenCalledWith({ where: { tenantId: "tenant-a", entryId: "entry-a" } });
});
it("returns the existing entry for a repeated create mutation instead of creating a duplicate", async () => {
const existing = {
id: "entry-existing",
tenantId: "tenant-a",
projektId: "project-a",
assignedUserId: "user-a",
createdByUserId: "user-a",
startAt: new Date("2026-07-21T07:00:00.000Z"),
endAt: new Date("2026-07-21T09:00:00.000Z"),
conflicts: [],
};
mocks.tx.tenantUser.findFirst.mockResolvedValue({ userId: "user-a" });
mocks.tx.projekt.findFirst.mockResolvedValue(project());
mocks.tx.scheduleEntry.findFirst.mockResolvedValue(existing);
await expect(
upsertScheduleEntry({
tenantId: "tenant-a",
ctx: context(["plantafel.write", "projects.read_all"]),
projektId: "project-a",
assignedUserId: "user-a",
title: "Montage",
startAt: "2026-07-21T09:00",
endAt: "2026-07-21T11:00",
clientMutationId: "stable-create-id",
})
).resolves.toMatchObject({ entry: { id: "entry-existing" }, conflicts: [] });
expect(mocks.tx.scheduleEntry.create).not.toHaveBeenCalled();
expect(mocks.tx.$executeRaw).toHaveBeenCalledTimes(2);
expect(mocks.tx.$executeRaw.mock.calls[0]?.[1]).toContain("plantafel:mutation");
});
it("rejects hidden signature files before generating an acceptance PDF", async () => {
mocks.tx.projekt.findFirst.mockResolvedValue(project());
mocks.tx.file.findMany.mockResolvedValue([]);
await expect(
submitAcceptanceProtocol({
tenantId: "tenant-a",
ctx: context(["acceptance.write", "projects.read_all", "files.read_all"]),
projectId: "project-a",
signatures: [
{ signerName: "Kunde", signerRole: "kunde", signatureFileId: "file-hidden" },
{ signerName: "Monteur", signerRole: "monteur" },
],
})
).rejects.toThrow();
expect(mocks.tx.file.findMany).toHaveBeenCalledWith({
where: expect.objectContaining({ tenantId: "tenant-a", id: { in: ["file-hidden"] }, archivedAt: null }),
select: { id: true },
});
expect(mocks.buildPdfExportArtifact).not.toHaveBeenCalled();
});
it("removes the uploaded acceptance PDF when the atomic database write fails", async () => {
mocks.tx.projekt.findFirst.mockResolvedValue(project());
mocks.tx.file.create.mockResolvedValue({ id: "file-created" });
mocks.tx.fileEntityLink.create.mockResolvedValue({ id: "link-created" });
mocks.tx.abnahmeProtokoll.create.mockRejectedValue(new Error("database write failed"));
mocks.withStorageReservation.mockImplementationOnce(async (input) => {
const stored = await input.upload();
try {
return await input.runTransaction((tx) => input.commit(tx, stored));
} catch (error) {
await input.rollbackUpload(stored);
throw error;
}
});
await expect(
submitAcceptanceProtocol({
tenantId: "tenant-a",
ctx: context(["acceptance.write", "projects.read_all", "files.read_all"]),
projectId: "project-a",
signatures: [
{ signerName: "Kunde", signerRole: "kunde" },
{ signerName: "Monteur", signerRole: "monteur" },
],
})
).rejects.toThrow("database write failed");
expect(mocks.putBufferAsFile).toHaveBeenCalledOnce();
expect(mocks.withStorageReservation).toHaveBeenCalledWith(
expect.objectContaining({ reservation: expect.objectContaining({ tenantId: "tenant-a", actorUserId: "user-a", sizeBytes: 3 }) })
);
expect(mocks.tx.file.create).toHaveBeenCalledOnce();
expect(mocks.deleteFile).toHaveBeenCalledWith({
bucket: "test-bucket",
key: expect.stringMatching(/^tenants\/tenant-a\/files\/file_.+\/original$/u),
});
});
it("preserves an acceptance PDF when a lost commit response already persisted its protocol", async () => {
const committed = { id: "protocol-committed", tenantId: "tenant-a", projektId: "project-a", signatures: [] };
mocks.tx.projekt.findFirst.mockResolvedValue(project());
mocks.tx.file.create.mockResolvedValue({ id: "file-created" });
mocks.tx.fileEntityLink.create.mockResolvedValue({ id: "link-created" });
mocks.tx.abnahmeProtokoll.create.mockRejectedValue(new Error("connection lost after commit"));
mocks.tx.abnahmeProtokoll.findFirst.mockResolvedValue(committed);
mocks.tx.abnahmeProtokoll.findUniqueOrThrow.mockResolvedValue(committed);
await expect(
submitAcceptanceProtocol({
tenantId: "tenant-a",
ctx: context(["acceptance.write", "projects.read_all", "files.read_all"]),
projectId: "project-a",
signatures: [
{ signerName: "Kunde", signerRole: "kunde" },
{ signerName: "Monteur", signerRole: "monteur" },
],
})
).resolves.toMatchObject({ id: "protocol-committed" });
expect(mocks.tx.abnahmeProtokoll.findFirst).toHaveBeenCalledWith({
where: {
id: expect.stringMatching(/^abn_/u),
tenantId: "tenant-a",
pdfFileId: expect.stringMatching(/^file_/u),
},
include: { signatures: true },
});
expect(mocks.deleteFile).not.toHaveBeenCalled();
});
it("keeps an acceptance PDF when the post-error commit check is itself unavailable", async () => {
mocks.tx.projekt.findFirst.mockResolvedValue(project());
mocks.tx.file.create.mockResolvedValue({ id: "file-created" });
mocks.tx.fileEntityLink.create.mockResolvedValue({ id: "link-created" });
mocks.tx.abnahmeProtokoll.create.mockRejectedValue(new Error("connection lost after commit"));
mocks.tx.abnahmeProtokoll.findFirst.mockRejectedValue(new Error("database unavailable"));
await expect(
submitAcceptanceProtocol({
tenantId: "tenant-a",
ctx: context(["acceptance.write", "projects.read_all", "files.read_all"]),
projectId: "project-a",
signatures: [
{ signerName: "Kunde", signerRole: "kunde" },
{ signerName: "Monteur", signerRole: "monteur" },
],
})
).rejects.toThrow("connection lost after commit");
expect(mocks.deleteFile).not.toHaveBeenCalled();
});
it("publishes the rejected-acceptance stage transition to workflows and the portal mail debounce", async () => {
const rejectedProject = { ...project(), projektleiterId: "lead-user" };
const protocol = {
id: "protocol-rejected",
tenantId: "tenant-a",
projektId: "project-a",
signatures: [],
};
mocks.tx.projekt.findFirst.mockResolvedValue(rejectedProject);
mocks.tx.projektChecklist.findFirst.mockResolvedValue({ id: "checklist-a" });
mocks.tx.file.create.mockResolvedValue({ id: "file-created" });
mocks.tx.fileEntityLink.create.mockResolvedValue({ id: "link-created" });
mocks.tx.abnahmeProtokoll.create.mockResolvedValue(protocol);
mocks.tx.abnahmeProtokoll.findUniqueOrThrow.mockResolvedValue(protocol);
mocks.tx.abnahmeSignatur.createMany.mockResolvedValue({ count: 2 });
mocks.tx.pipelineStage.findFirst.mockResolvedValue({ id: "stage-execution" });
mocks.tx.projekt.update.mockResolvedValue({
...rejectedProject,
stageId: "stage-execution",
});
mocks.tx.projektStageChange.create.mockResolvedValue({ id: "stage-change-rejected" });
await submitAcceptanceProtocol({
tenantId: "tenant-a",
ctx: context(["acceptance.write", "projects.read_all", "files.read_all"]),
projectId: "project-a",
maengelChecklistId: "checklist-a",
defects: [{ title: "Kritischer Mangel", classification: "critical" }],
signatures: [
{ signerName: "Kunde", signerRole: "kunde" },
{ signerName: "Monteur", signerRole: "monteur" },
],
});
expect(mocks.tx.projekt.update).toHaveBeenCalledWith({
where: { id: "project-a", tenantId: "tenant-a" },
data: { stageId: "stage-execution", wonAt: null, lostAt: null, lostReasonId: null },
});
expect(mocks.tx.projektStageChange.create).toHaveBeenCalledWith({
data: expect.objectContaining({
tenantId: "tenant-a",
projektId: "project-a",
fromStageId: "stage-a",
toStageId: "stage-execution",
changedByUserId: "user-a",
}),
});
expect(mocks.publishOutboxEvent).toHaveBeenCalledTimes(2);
expect(mocks.publishOutboxEvent.mock.calls.map(([, event]) => event)).toEqual(
expect.arrayContaining([
expect.objectContaining({
type: "workflow.trigger.event",
payload: expect.objectContaining({ event: "project.stage_changed" }),
}),
expect.objectContaining({
type: "mail.portal-status.stage-changed",
payload: expect.objectContaining({
tenantId: "tenant-a",
projectId: "project-a",
previousStageId: "stage-a",
expectedStageId: "stage-execution",
stageChangeId: "stage-change-rejected",
}),
}),
])
);
// R-P9b DoD 4 — the lead notification runs through M011 notify() on the
// tenant-bound transaction client (RLS policy visible), not a raw insert.
expect(mocks.tx.notificationDelivery.upsert).toHaveBeenCalledWith(
expect.objectContaining({
create: expect.objectContaining({
tenantId: "tenant-a",
userId: "lead-user",
channel: "IN_APP",
category: "projects",
messageKey: "projects.notify.acceptance.rejected",
}),
})
);
});
it("refuses content updates on saved acceptance protocols", async () => {
await expect(updateAcceptanceProtocolContent()).rejects.toThrow("projects.error.acceptanceProtocolImmutable");
});
it("does not read acceptance protocols when the central project scope denies the project", async () => {
mocks.tx.projekt.findFirst.mockResolvedValue(null);
await expect(
listAcceptanceProtocols({
tenantId: "tenant-a",
projectId: "project-denied",
ctx: context(["acceptance.read", "projects.read_own"]),
})
).rejects.toThrow();
expect(mocks.tx.abnahmeProtokoll.findMany).not.toHaveBeenCalled();
expect(mocks.tx.projekt.findFirst).toHaveBeenCalledWith({
where: expect.objectContaining({
tenantId: "tenant-a",
AND: expect.arrayContaining([{ id: "project-denied" }, expect.objectContaining({ AND: expect.any(Array) })]),
}),
});
});
it("edit-gates schedule status changes through the entry project", async () => {
mocks.tx.scheduleEntry.findFirst.mockResolvedValue({
id: "entry-a",
projektId: "project-denied",
assignedUserId: "user-a",
status: "planned",
startAt: new Date("2026-07-01T08:00:00.000Z"),
endAt: new Date("2026-07-01T10:00:00.000Z"),
});
mocks.tx.projekt.findFirst.mockResolvedValue(null);
await expect(
updateScheduleEntryStatus({
tenantId: "tenant-a",
ctx: context(["plantafel.write", "projects.read_all"]),
entryId: "entry-a",
status: "done",
})
).rejects.toThrow();
expect(mocks.tx.scheduleEntry.update).not.toHaveBeenCalled();
const projectWhere = mocks.tx.projekt.findFirst.mock.calls[0]?.[0]?.where;
expect(JSON.stringify(projectWhere)).toContain("kannBearbeiten");
});
it("serializes a cancelled entry reactivation and rejects a new double booking", async () => {
const cancelled = {
id: "entry-a",
tenantId: "tenant-a",
projektId: "project-a",
assignedUserId: "user-a",
status: "cancelled",
startAt: new Date("2026-07-01T08:00:00.000Z"),
endAt: new Date("2026-07-01T10:00:00.000Z"),
};
mocks.tx.scheduleEntry.findFirst.mockResolvedValue(cancelled);
mocks.tx.projekt.findFirst.mockResolvedValue(project());
mocks.tx.scheduleEntry.findMany.mockResolvedValue([
{
id: "entry-overlap",
startAt: new Date("2026-07-01T09:00:00.000Z"),
endAt: new Date("2026-07-01T11:00:00.000Z"),
},
]);
await expect(
updateScheduleEntryStatus({
tenantId: "tenant-a",
ctx: context(["plantafel.write", "projects.read_all"]),
entryId: "entry-a",
status: "planned",
})
).rejects.toThrow("projects.error.scheduleConflictOverrideRequired");
expect(mocks.tx.$executeRaw).toHaveBeenCalledTimes(2);
expect(String(mocks.tx.$executeRaw.mock.calls[0]?.[0])).toContain("pg_advisory_xact_lock");
expect(String(mocks.tx.$executeRaw.mock.calls[1]?.[0])).toContain('FROM "ScheduleEntry"');
expect(mocks.tx.scheduleEntry.update).not.toHaveBeenCalled();
});
it("deduplicates bulk entry ids and rejects payloads above the hard cap", () => {
expect(normalizeBulkScheduleEntryIds([" entry-a ", "entry-a", "", "entry-b"])).toEqual(["entry-a", "entry-b"]);
expect(() => normalizeBulkScheduleEntryIds(Array.from({ length: PLANTAFEL_BULK_REASSIGN_MAX_ENTRIES + 1 }, (_, index) => `entry-${index}`))).toThrow(
"foundation.mass_action_exceeds_limit"
);
});
it("rejects a bulk assignee who is not an active user in the tenant", async () => {
mocks.tx.tenantUser.findFirst.mockResolvedValue(null);
await expect(
bulkReassignScheduleEntries({
tenantId: "tenant-a",
ctx: context(["plantafel.bulk_reassign", "projects.read_all"]),
entryIds: ["entry-a"],
assignedUserId: "user-inactive",
})
).rejects.toThrow();
expect(mocks.tx.tenantUser.findFirst).toHaveBeenCalledWith({
where: {
tenantId: "tenant-a",
userId: "user-inactive",
status: TenantUserStatus.ACTIVE,
user: { active: true },
},
select: { userId: true },
});
expect(mocks.tx.scheduleEntry.findMany).not.toHaveBeenCalled();
expect(mocks.tx.scheduleEntry.update).not.toHaveBeenCalled();
});
it("batch-loads and batch-authorizes deduplicated bulk entries before updating", async () => {
const startAt = new Date("2026-07-01T08:00:00.000Z");
const endAt = new Date("2026-07-01T10:00:00.000Z");
const laterStartAt = new Date("2026-07-01T11:00:00.000Z");
const laterEndAt = new Date("2026-07-01T13:00:00.000Z");
mocks.tx.tenantUser.findFirst.mockResolvedValue({ userId: "user-b" });
mocks.tx.scheduleEntry.findMany
.mockResolvedValueOnce([
{ id: "entry-a", projektId: "project-a", startAt, endAt, status: "planned" },
{ id: "entry-b", projektId: "project-b", startAt: laterStartAt, endAt: laterEndAt, status: "planned" },
])
.mockResolvedValue([]);
mocks.tx.projekt.findMany.mockResolvedValue([{ id: "project-a" }, { id: "project-b" }]);
mocks.tx.scheduleEntry.updateMany.mockResolvedValue({ count: 2 });
mocks.tx.scheduleConflict.deleteMany.mockResolvedValue({ count: 0 });
mocks.tx.scheduleConflict.createMany.mockResolvedValue({ count: 0 });
await expect(
bulkReassignScheduleEntries({
tenantId: "tenant-a",
ctx: context(["plantafel.bulk_reassign", "projects.read_all"]),
entryIds: ["entry-a", "entry-a", "entry-b"],
assignedUserId: "user-b",
})
).resolves.toEqual({ updated: 2 });
expect(mocks.tx.scheduleEntry.findMany.mock.calls[0]?.[0]).toEqual({
where: { id: { in: ["entry-a", "entry-b"] }, tenantId: "tenant-a", archivedAt: null },
select: { id: true, projektId: true, startAt: true, endAt: true, status: true },
});
expect(mocks.tx.projekt.findMany).toHaveBeenCalledTimes(1);
expect(mocks.tx.projekt.findMany.mock.calls[0]?.[0]).toMatchObject({
where: { tenantId: "tenant-a", id: { in: ["project-a", "project-b"] }, archivedAt: null },
select: { id: true },
});
expect(JSON.stringify(mocks.tx.projekt.findMany.mock.calls[0]?.[0]?.where)).toContain("kannBearbeiten");
expect(mocks.tx.projekt.findFirst).not.toHaveBeenCalled();
expect(mocks.tx.scheduleEntry.update).not.toHaveBeenCalled();
expect(mocks.tx.scheduleEntry.updateMany).toHaveBeenCalledOnce();
expect(mocks.tx.scheduleEntry.updateMany).toHaveBeenCalledWith({
where: {
id: { in: ["entry-a", "entry-b"] },
tenantId: "tenant-a",
projektId: { in: ["project-a", "project-b"] },
archivedAt: null,
},
data: { assignedUserId: "user-b", syncStatus: "pending", conflictOverrideReason: null },
});
expect(mocks.tx.scheduleConflict.deleteMany).toHaveBeenCalledWith({
where: { tenantId: "tenant-a", entryId: { in: ["entry-a", "entry-b"] } },
});
});
it("scopes protocol archival to the route project and its edit access", async () => {
mocks.tx.projekt.findFirst.mockResolvedValue(project());
mocks.tx.abnahmeProtokoll.findFirst.mockResolvedValue({ id: "protocol-a" });
mocks.tx.abnahmeProtokoll.update.mockResolvedValue({ id: "protocol-a" });
await archiveAcceptanceProtocol({
tenantId: "tenant-a",
projectId: "project-a",
protocolId: "protocol-a",
ctx: context(["acceptance.admin", "projects.read_all"]),
});
expect(mocks.tx.abnahmeProtokoll.findFirst).toHaveBeenCalledWith({
where: {
id: "protocol-a",
tenantId: "tenant-a",
projektId: "project-a",
archivedAt: null,
},
select: { id: true },
});
expect(mocks.tx.abnahmeProtokoll.update).toHaveBeenCalledWith({
where: { id: "protocol-a", tenantId: "tenant-a" },
data: { archivedAt: expect.any(Date) },
});
const projectWhere = mocks.tx.projekt.findFirst.mock.calls[0]?.[0]?.where;
expect(JSON.stringify(projectWhere)).toContain("kannBearbeiten");
});
});