Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+89
@@ -0,0 +1,89 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
withTenantRLS: vi.fn(),
|
||||
acceptanceUpsert: vi.fn(),
|
||||
projectUpsert: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: mocks.withTenantRLS }));
|
||||
vi.mock("@hivegrid/activity", () => ({ logActivity: vi.fn() }));
|
||||
|
||||
import {
|
||||
ensureDefaultAcceptanceFormTemplate,
|
||||
ensureDefaultAcceptanceFormTemplateWithTx,
|
||||
ensureDefaultProjectTemplate,
|
||||
ensureDefaultProjectTemplateWithTx,
|
||||
} from "./auftragService.server";
|
||||
|
||||
const tx = {
|
||||
acceptanceFormTemplate: { upsert: mocks.acceptanceUpsert },
|
||||
projectTemplate: { upsert: mocks.projectUpsert },
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.acceptanceUpsert.mockResolvedValue({ id: "acceptance-default" });
|
||||
mocks.projectUpsert.mockResolvedValue({ id: "project-default" });
|
||||
mocks.withTenantRLS.mockImplementation(async (_tenantId, callback) => callback(tx));
|
||||
});
|
||||
|
||||
describe("order defaults transaction boundary", () => {
|
||||
it("uses a caller-provided transaction and preserves the acceptance defaults", async () => {
|
||||
await expect(ensureDefaultAcceptanceFormTemplateWithTx(tx as never, "tenant-atomic-bootstrap")).resolves.toEqual({
|
||||
id: "acceptance-default",
|
||||
});
|
||||
|
||||
expect(mocks.withTenantRLS).not.toHaveBeenCalled();
|
||||
expect(mocks.acceptanceUpsert).toHaveBeenCalledWith({
|
||||
where: { tenantId_name: { tenantId: "tenant-atomic-bootstrap", name: "SHK Standard-Abnahme" } },
|
||||
update: { archivedAt: null, isDefault: true, isDemoData: false },
|
||||
create: {
|
||||
tenantId: "tenant-atomic-bootstrap",
|
||||
name: "SHK Standard-Abnahme",
|
||||
definition: {
|
||||
sections: [
|
||||
{ key: "leistungen", labelKey: "projects.defaults.acceptance.sections.leistungen" },
|
||||
{ key: "maengel", labelKey: "projects.defaults.acceptance.sections.maengel" },
|
||||
{ key: "unterschrift", labelKey: "projects.defaults.acceptance.sections.unterschrift" },
|
||||
],
|
||||
},
|
||||
isDefault: true,
|
||||
isDemoData: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("uses a caller-provided transaction and preserves the project defaults", async () => {
|
||||
await expect(ensureDefaultProjectTemplateWithTx(tx as never, "tenant-atomic-bootstrap")).resolves.toEqual({
|
||||
id: "project-default",
|
||||
});
|
||||
|
||||
expect(mocks.withTenantRLS).not.toHaveBeenCalled();
|
||||
expect(mocks.projectUpsert).toHaveBeenCalledWith({
|
||||
where: { tenantId_name: { tenantId: "tenant-atomic-bootstrap", name: "SHK Standard-Projekt" } },
|
||||
update: { archivedAt: null, isDemoData: false },
|
||||
create: {
|
||||
tenantId: "tenant-atomic-bootstrap",
|
||||
name: "SHK Standard-Projekt",
|
||||
defaultMembers: [],
|
||||
defaultTasks: [
|
||||
{ titleKey: "projects.defaults.tasks.prepareSite", priority: "normal" },
|
||||
{ titleKey: "projects.defaults.tasks.checkMaterial", priority: "normal" },
|
||||
{ titleKey: "projects.defaults.tasks.prepareAcceptance", priority: "high" },
|
||||
],
|
||||
customFields: {},
|
||||
isDemoData: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the existing wrappers and binds one RLS transaction per call", async () => {
|
||||
await ensureDefaultAcceptanceFormTemplate({ tenantId: "tenant-wrapper" });
|
||||
await ensureDefaultProjectTemplate({ tenantId: "tenant-wrapper" });
|
||||
|
||||
expect(mocks.withTenantRLS).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.withTenantRLS).toHaveBeenNthCalledWith(1, "tenant-wrapper", expect.any(Function));
|
||||
expect(mocks.withTenantRLS).toHaveBeenNthCalledWith(2, "tenant-wrapper", expect.any(Function));
|
||||
});
|
||||
});
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tx: {
|
||||
projekt: { findFirst: vi.fn() },
|
||||
projektMitglied: { findFirst: vi.fn() },
|
||||
fileEntityLink: { findMany: vi.fn() },
|
||||
file: { findFirst: vi.fn() },
|
||||
projektChecklist: { findFirst: vi.fn() },
|
||||
projektChecklistItem: { findFirst: vi.fn(), create: vi.fn(), update: vi.fn() },
|
||||
acceptanceFormTemplate: { findFirst: vi.fn(), update: vi.fn() },
|
||||
tenantUser: { findFirst: vi.fn() },
|
||||
rechnung: { create: vi.fn() },
|
||||
hiveNumberSeq: { update: vi.fn() },
|
||||
$executeRaw: vi.fn(),
|
||||
$queryRaw: vi.fn(),
|
||||
},
|
||||
logActivity: 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 }));
|
||||
|
||||
import { createProjectInvoice, upsertAcceptanceFormTemplate, upsertProjectChecklistItem, type AuftragVisibilityContext } from "./auftragService.server";
|
||||
|
||||
const TENANT_ID = "tenant-a";
|
||||
const PROJECT_ID = "project-a";
|
||||
|
||||
function context(extraPermissions: readonly string[] = []): AuftragVisibilityContext {
|
||||
return {
|
||||
userId: "actor-a",
|
||||
permissions: ["projects.read_all", ...extraPermissions],
|
||||
roleIds: ["role-a"],
|
||||
groupIds: ["group-a"],
|
||||
};
|
||||
}
|
||||
|
||||
describe("order file-reference authorization", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.projekt.findFirst.mockResolvedValue({
|
||||
id: PROJECT_ID,
|
||||
tenantId: TENANT_ID,
|
||||
projektleiterId: null,
|
||||
zustaendigePersonId: null,
|
||||
});
|
||||
mocks.tx.fileEntityLink.findMany.mockResolvedValue([]);
|
||||
mocks.tx.projektChecklist.findFirst.mockResolvedValue({ id: "checklist-a", tenantId: TENANT_ID, projektId: PROJECT_ID });
|
||||
mocks.tx.projektChecklistItem.create.mockResolvedValue({ id: "item-a", tenantId: TENANT_ID, checklistId: "checklist-a" });
|
||||
});
|
||||
|
||||
it("rejects an invoice file id when the actor has no Files read permission", async () => {
|
||||
mocks.tx.file.findFirst.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
createProjectInvoice({
|
||||
tenantId: TENANT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
ctx: context(),
|
||||
createdByUserId: "actor-a",
|
||||
betrag: "1250.00",
|
||||
dateiId: "guessed-file",
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.file.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: { in: [] }, tenantId: TENANT_ID, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.tx.$executeRaw).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.rechnung.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps invoice file lookup tenant-scoped for a tenant-wide Files reader", async () => {
|
||||
mocks.tx.file.findFirst.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
createProjectInvoice({
|
||||
tenantId: TENANT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
ctx: context(["files.read_all"]),
|
||||
createdByUserId: "actor-a",
|
||||
betrag: "1250.00",
|
||||
dateiId: "file-from-tenant-b",
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.file.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "file-from-tenant-b",
|
||||
tenantId: TENANT_ID,
|
||||
archivedAt: null,
|
||||
links: { none: { tenantId: TENANT_ID, entityType: "user", entityId: { not: "actor-a" } } },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.tx.rechnung.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects a checklist photo id outside the actor's authoritative Files scope", async () => {
|
||||
mocks.tx.file.findFirst.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
upsertProjectChecklistItem({
|
||||
tenantId: TENANT_ID,
|
||||
checklistId: "checklist-a",
|
||||
ctx: context(),
|
||||
titel: "Photo evidence",
|
||||
fotoFileId: "guessed-photo",
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.file.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: { in: [] }, tenantId: TENANT_ID, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.tx.projektChecklistItem.create).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.projektChecklistItem.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("accepts a checklist photo only through the current actor's own-file scope", async () => {
|
||||
mocks.tx.file.findFirst.mockResolvedValueOnce({ id: "own-photo" });
|
||||
|
||||
await upsertProjectChecklistItem({
|
||||
tenantId: TENANT_ID,
|
||||
checklistId: "checklist-a",
|
||||
ctx: context(["files.read_own"]),
|
||||
titel: "Own photo evidence",
|
||||
fotoFileId: "own-photo",
|
||||
});
|
||||
|
||||
expect(mocks.tx.file.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "own-photo",
|
||||
tenantId: TENANT_ID,
|
||||
archivedAt: null,
|
||||
AND: [
|
||||
{
|
||||
OR: [
|
||||
{ createdByUserId: "actor-a" },
|
||||
{ assignedToUserId: "actor-a" },
|
||||
{ links: { some: { tenantId: TENANT_ID, entityType: "user", entityId: "actor-a" } } },
|
||||
],
|
||||
},
|
||||
{ links: { none: { tenantId: TENANT_ID, entityType: "user", entityId: { not: "actor-a" } } } },
|
||||
],
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.tx.projektChecklistItem.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
tenantId: TENANT_ID,
|
||||
checklistId: "checklist-a",
|
||||
fotoFileId: "own-photo",
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects an acceptance template id outside the current tenant before updating", async () => {
|
||||
mocks.tx.acceptanceFormTemplate.findFirst.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
upsertAcceptanceFormTemplate({
|
||||
tenantId: TENANT_ID,
|
||||
templateId: "template-from-tenant-b",
|
||||
name: "Hidden template",
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.acceptanceFormTemplate.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: "template-from-tenant-b", tenantId: TENANT_ID, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.tx.acceptanceFormTemplate.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
withTenantRLS: vi.fn(),
|
||||
invoiceFindFirst: vi.fn(),
|
||||
invoiceUpdate: vi.fn(),
|
||||
requireAccess: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: mocks.withTenantRLS }));
|
||||
vi.mock("@hivegrid/activity", () => ({ logActivity: vi.fn() }));
|
||||
|
||||
import { updateProjectInvoiceStatus } from "./auftragService.server";
|
||||
|
||||
const tx = {
|
||||
rechnung: { findFirst: mocks.invoiceFindFirst, update: mocks.invoiceUpdate },
|
||||
projekt: { findFirst: mocks.requireAccess },
|
||||
projektMitglied: { findFirst: vi.fn().mockResolvedValue(null) },
|
||||
};
|
||||
|
||||
const ctx = { tenantId: "tenant-1", userId: "user-1", permissions: ["projects.read_all", "projects.write", "projects.admin"] };
|
||||
|
||||
function invoice(overrides: Record<string, unknown> = {}) {
|
||||
return { id: "invoice-1", tenantId: "tenant-1", projektId: "project-1", status: "gestellt", bezahltAm: null, ...overrides };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.withTenantRLS.mockImplementation(async (_tenantId: string, callback: (client: unknown) => unknown) => callback(tx));
|
||||
mocks.requireAccess.mockResolvedValue({ id: "project-1", tenantId: "tenant-1", archivedAt: null });
|
||||
mocks.invoiceUpdate.mockImplementation(async ({ data }: { data: Record<string, unknown> }) => ({ ...invoice(), ...data }));
|
||||
});
|
||||
|
||||
describe("invoice payment date", () => {
|
||||
it("stamps the payment date when an invoice is marked paid", async () => {
|
||||
mocks.invoiceFindFirst.mockResolvedValue(invoice());
|
||||
|
||||
const before = Date.now();
|
||||
const row = await updateProjectInvoiceStatus({
|
||||
tenantId: "tenant-1",
|
||||
invoiceId: "invoice-1",
|
||||
ctx: ctx as never,
|
||||
userId: "user-1",
|
||||
status: "bezahlt",
|
||||
});
|
||||
|
||||
const stamped = mocks.invoiceUpdate.mock.calls[0]![0].data.bezahltAm as Date;
|
||||
expect(stamped).toBeInstanceOf(Date);
|
||||
expect(stamped.getTime()).toBeGreaterThanOrEqual(before);
|
||||
expect(row.bezahltAm).toBe(stamped);
|
||||
});
|
||||
|
||||
it("keeps the original payment date when a paid invoice is saved as paid again", async () => {
|
||||
const paidAt = new Date("2026-07-01T10:00:00.000Z");
|
||||
mocks.invoiceFindFirst.mockResolvedValue(invoice({ status: "bezahlt", bezahltAm: paidAt }));
|
||||
|
||||
await updateProjectInvoiceStatus({
|
||||
tenantId: "tenant-1",
|
||||
invoiceId: "invoice-1",
|
||||
ctx: ctx as never,
|
||||
userId: "user-1",
|
||||
status: "bezahlt",
|
||||
});
|
||||
|
||||
expect(mocks.invoiceUpdate.mock.calls[0]![0].data.bezahltAm).toBe(paidAt);
|
||||
});
|
||||
|
||||
it("clears the payment date when a paid invoice moves back to unpaid", async () => {
|
||||
mocks.invoiceFindFirst.mockResolvedValue(invoice({ status: "bezahlt", bezahltAm: new Date("2026-07-01T10:00:00.000Z") }));
|
||||
|
||||
for (const status of ["gestellt", "storniert", "entwurf"] as const) {
|
||||
mocks.invoiceUpdate.mockClear();
|
||||
await updateProjectInvoiceStatus({
|
||||
tenantId: "tenant-1",
|
||||
invoiceId: "invoice-1",
|
||||
ctx: ctx as never,
|
||||
userId: "user-1",
|
||||
status,
|
||||
});
|
||||
expect(mocks.invoiceUpdate.mock.calls[0]![0].data).toEqual({ status, bezahltAm: null });
|
||||
}
|
||||
});
|
||||
});
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tx: {
|
||||
projekt: { findFirst: vi.fn() },
|
||||
projektMitglied: { findMany: vi.fn() },
|
||||
projektTermin: { findMany: vi.fn() },
|
||||
rechnung: { findMany: vi.fn() },
|
||||
projektChecklist: { findMany: vi.fn() },
|
||||
auftragPipelineStageConfig: { findFirst: vi.fn() },
|
||||
acceptanceFormTemplate: { upsert: vi.fn(), findMany: vi.fn() },
|
||||
projectTemplate: { upsert: vi.fn(), findMany: vi.fn() },
|
||||
projektChecklistItem: { count: vi.fn() },
|
||||
task: { findMany: vi.fn() },
|
||||
fileEntityLink: { findMany: vi.fn() },
|
||||
group: { findMany: vi.fn() },
|
||||
kwpMaterialPosition: { findMany: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
|
||||
}));
|
||||
|
||||
import { loadProjectSubAreas } from "./auftragService.server";
|
||||
|
||||
describe("KWP material project sub-area", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.projekt.findFirst.mockResolvedValue({
|
||||
id: "project-1",
|
||||
tenantId: "tenant-1",
|
||||
projektleiterId: null,
|
||||
zustaendigePersonId: null,
|
||||
stageId: "stage-1",
|
||||
});
|
||||
mocks.tx.acceptanceFormTemplate.upsert.mockResolvedValue({ id: "acceptance-default" });
|
||||
mocks.tx.projectTemplate.upsert.mockResolvedValue({ id: "project-default" });
|
||||
mocks.tx.projektMitglied.findMany.mockResolvedValue([]);
|
||||
mocks.tx.projektTermin.findMany.mockResolvedValue([]);
|
||||
mocks.tx.rechnung.findMany.mockResolvedValue([]);
|
||||
mocks.tx.projektChecklist.findMany.mockResolvedValue([]);
|
||||
mocks.tx.auftragPipelineStageConfig.findFirst.mockResolvedValue(null);
|
||||
mocks.tx.acceptanceFormTemplate.findMany.mockResolvedValue([]);
|
||||
mocks.tx.projectTemplate.findMany.mockResolvedValue([]);
|
||||
mocks.tx.projektChecklistItem.count.mockResolvedValue(0);
|
||||
mocks.tx.task.findMany.mockResolvedValue([]);
|
||||
mocks.tx.fileEntityLink.findMany.mockResolvedValue([]);
|
||||
mocks.tx.group.findMany.mockResolvedValue([]);
|
||||
mocks.tx.kwpMaterialPosition.findMany.mockResolvedValue([
|
||||
{
|
||||
id: "material-1",
|
||||
positionNumber: "01.01",
|
||||
text: "Ventil",
|
||||
longText: "DN 20",
|
||||
quantity: "2",
|
||||
unit: "Stk",
|
||||
unitPrice: "12.50",
|
||||
totalPrice: "25.00",
|
||||
lastSyncedAt: new Date("2026-07-24T10:00:00.000Z"),
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("loads only active material positions from the bound tenant and project", async () => {
|
||||
const result = await loadProjectSubAreas({
|
||||
tenantId: "tenant-1",
|
||||
projectId: "project-1",
|
||||
ctx: {
|
||||
userId: "user-1",
|
||||
permissions: ["projects.read_all"],
|
||||
roleIds: [],
|
||||
groupIds: [],
|
||||
},
|
||||
});
|
||||
|
||||
expect(mocks.tx.kwpMaterialPosition.findMany).toHaveBeenCalledWith({
|
||||
where: { tenantId: "tenant-1", projektId: "project-1", archivedAt: null },
|
||||
select: {
|
||||
id: true,
|
||||
positionNumber: true,
|
||||
text: true,
|
||||
longText: true,
|
||||
quantity: true,
|
||||
unit: true,
|
||||
unitPrice: true,
|
||||
totalPrice: true,
|
||||
lastSyncedAt: true,
|
||||
},
|
||||
orderBy: [{ positionNumber: "asc" }, { externalId: "asc" }],
|
||||
take: 500,
|
||||
});
|
||||
expect(result.materials).toEqual([expect.objectContaining({ id: "material-1", text: "Ventil", totalPrice: "25.00" })]);
|
||||
});
|
||||
});
|
||||
+374
-67
@@ -1,8 +1,18 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { archiveProjectChannelIfEnabledWithTx, ensureAndSyncProjectChannelIfEnabledWithTx } from "@hivegrid/chat/project-sync.server";
|
||||
import { autoArchiveProjectsForTenantWithTx } from "@hivegrid/db/project-auto-archive.server";
|
||||
import { lockPermissionGroupsWithTx } from "@hivegrid/chat/sync-locks.server";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
import type { ProjektRow } from "./projectService.server";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import { fileReadScopeWhereWithTx } from "../fileVisibility.server";
|
||||
import {
|
||||
projectEditScopeWhere,
|
||||
projectReadScopeWhere,
|
||||
type ProjectVisibilityContext,
|
||||
type ProjektRow,
|
||||
} from "./projectService.server";
|
||||
|
||||
export class AuftragServiceError extends Error {
|
||||
readonly messageKey: string;
|
||||
@@ -15,15 +25,14 @@ export class AuftragServiceError extends Error {
|
||||
|
||||
export type ProjektMitgliedRolle = "monteur" | "projektleiter" | "zustaendig" | "beobachter";
|
||||
export type ProjektTerminStatus = "geplant" | "bestaetigt" | "erledigt" | "abgesagt";
|
||||
/** WF-P8 S02-T appointment kind. */
|
||||
export type ProjektTerminTyp = "vor_ort" | "telefon" | "online";
|
||||
export type RechnungStatus = "entwurf" | "gestellt" | "bezahlt" | "storniert";
|
||||
export type RechnungQuelle = "manuell" | "kwp";
|
||||
export type ProjektChecklistTyp = "generisch" | "maengel" | "abnahme_doku";
|
||||
export type ProjektChecklistItemStatus = "offen" | "erledigt" | "entfaellt";
|
||||
|
||||
export type AuftragVisibilityContext = {
|
||||
userId: string;
|
||||
permissions: readonly string[];
|
||||
};
|
||||
export type AuftragVisibilityContext = ProjectVisibilityContext;
|
||||
|
||||
export type ProjektMitgliedRow = {
|
||||
id: string;
|
||||
@@ -50,6 +59,7 @@ export type ProjektTerminRow = {
|
||||
startAt: Date;
|
||||
endAt: Date | null;
|
||||
status: ProjektTerminStatus;
|
||||
typ: ProjektTerminTyp;
|
||||
isDemoData: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
@@ -66,6 +76,8 @@ export type RechnungRow = {
|
||||
status: RechnungStatus;
|
||||
datum: Date;
|
||||
faelligAm: Date | null;
|
||||
/** Null for invoices marked paid before the field existed — never treat null as "today". */
|
||||
bezahltAm: Date | null;
|
||||
dateiId: string | null;
|
||||
quelle: RechnungQuelle;
|
||||
isDemoData: boolean;
|
||||
@@ -143,12 +155,47 @@ export type ProjectTemplateRow = {
|
||||
archivedAt: Date | null;
|
||||
};
|
||||
|
||||
export type ProjectSubAreaTaskRow = {
|
||||
id: string;
|
||||
title: string;
|
||||
status: string;
|
||||
priority: string;
|
||||
deadline: Date | null;
|
||||
assignedToUserId: string | null;
|
||||
assignedToGroupId: string | null;
|
||||
};
|
||||
|
||||
export type ProjectSubAreaDocumentRow = {
|
||||
id: string;
|
||||
displayName: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
linkRole: string | null;
|
||||
createdAt: Date;
|
||||
};
|
||||
|
||||
export type ProjectSubAreaMaterialRow = {
|
||||
id: string;
|
||||
positionNumber: string | null;
|
||||
text: string;
|
||||
longText: string | null;
|
||||
quantity: unknown;
|
||||
unit: string | null;
|
||||
unitPrice: unknown;
|
||||
totalPrice: unknown;
|
||||
lastSyncedAt: Date;
|
||||
};
|
||||
|
||||
export type ProjectSubAreasVM = {
|
||||
project: ProjektRow;
|
||||
members: ProjektMitgliedRow[];
|
||||
appointments: ProjektTerminRow[];
|
||||
invoices: RechnungRow[];
|
||||
checklists: ProjektChecklistRow[];
|
||||
tasks: ProjectSubAreaTaskRow[];
|
||||
documents: ProjectSubAreaDocumentRow[];
|
||||
materials: ProjectSubAreaMaterialRow[];
|
||||
groupOptions: { id: string; name: string }[];
|
||||
stageConfig: AuftragPipelineStageConfigRow | null;
|
||||
acceptanceTemplates: AcceptanceFormTemplateRow[];
|
||||
projectTemplates: ProjectTemplateRow[];
|
||||
@@ -185,20 +232,41 @@ function hasPermission(ctx: AuftragVisibilityContext | undefined, permission: st
|
||||
return ctx?.permissions.includes(permission) ?? false;
|
||||
}
|
||||
|
||||
async function canReadProjectSubAreasWithTx(tx: TenantRlsClient, input: { tenantId: string; project: ProjektRow; ctx: AuftragVisibilityContext }): Promise<boolean> {
|
||||
async function canReadProjectSubAreasWithTx(
|
||||
tx: TenantRlsClient,
|
||||
input: { tenantId: string; project: ProjektRow; ctx: AuftragVisibilityContext }
|
||||
): Promise<boolean> {
|
||||
if (hasPermission(input.ctx, "projects.read_all")) return true;
|
||||
if (hasPermission(input.ctx, "projects.read_own_pl") && input.project.projektleiterId === input.ctx.userId) return true;
|
||||
if (hasPermission(input.ctx, "projects.read_own") && input.project.zustaendigePersonId === input.ctx.userId) return true;
|
||||
if (!hasPermission(input.ctx, "projects.read_own_member")) return false;
|
||||
const membership = await tx.projektMitglied.findFirst({
|
||||
where: { tenantId: input.tenantId, projektId: input.project.id, userId: input.ctx.userId, archivedAt: null },
|
||||
where: {
|
||||
tenantId: input.tenantId,
|
||||
projektId: input.project.id,
|
||||
archivedAt: null,
|
||||
OR: [
|
||||
{ userId: input.ctx.userId },
|
||||
...((input.ctx.groupIds?.length ?? 0) > 0 ? [{ groupId: { in: [...(input.ctx.groupIds ?? [])] } }] : []),
|
||||
],
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
return Boolean(membership);
|
||||
}
|
||||
|
||||
async function requireProjectSubAreaReadWithTx(tx: TenantRlsClient, input: { tenantId: string; projectId: string; ctx: AuftragVisibilityContext }): Promise<ProjektRow> {
|
||||
const project = await tx.projekt.findFirst({ where: { id: input.projectId, tenantId: input.tenantId, archivedAt: null } });
|
||||
async function requireProjectSubAreaAccessWithTx(
|
||||
tx: TenantRlsClient,
|
||||
input: { tenantId: string; projectId: string; ctx: AuftragVisibilityContext; editable: boolean }
|
||||
): Promise<ProjektRow> {
|
||||
const project = await tx.projekt.findFirst({
|
||||
where: {
|
||||
id: input.projectId,
|
||||
tenantId: input.tenantId,
|
||||
archivedAt: null,
|
||||
...(input.editable ? projectEditScopeWhere(input.tenantId, input.ctx) : projectReadScopeWhere(input.tenantId, input.ctx)),
|
||||
},
|
||||
});
|
||||
if (!project) throw new CatalogError(foundationErrors.notFound, { projectId: input.projectId });
|
||||
if (!(await canReadProjectSubAreasWithTx(tx, { tenantId: input.tenantId, project: project as ProjektRow, ctx: input.ctx }))) {
|
||||
throw new CatalogError(foundationErrors.notFound, { projectId: input.projectId });
|
||||
@@ -206,6 +274,13 @@ async function requireProjectSubAreaReadWithTx(tx: TenantRlsClient, input: { ten
|
||||
return project as ProjektRow;
|
||||
}
|
||||
|
||||
async function requireProjectSubAreaReadWithTx(
|
||||
tx: TenantRlsClient,
|
||||
input: { tenantId: string; projectId: string; ctx: AuftragVisibilityContext }
|
||||
): Promise<ProjektRow> {
|
||||
return requireProjectSubAreaAccessWithTx(tx, { ...input, editable: false });
|
||||
}
|
||||
|
||||
function requireExactlyOnePrincipal(userId?: string | null, groupId?: string | null): void {
|
||||
const hasUser = Boolean(normalizeText(userId));
|
||||
const hasGroup = Boolean(normalizeText(groupId));
|
||||
@@ -216,10 +291,37 @@ function invoiceNumber(prefix: string, nextNumber: number, padding: number): str
|
||||
return `${prefix}${String(nextNumber).padStart(padding, "0")}`;
|
||||
}
|
||||
|
||||
async function requireProjectWithTx(tx: TenantRlsClient, input: { tenantId: string; projectId: string }): Promise<ProjektRow> {
|
||||
const project = await tx.projekt.findFirst({ where: { id: input.projectId, tenantId: input.tenantId, archivedAt: null } });
|
||||
if (!project) throw new CatalogError(foundationErrors.notFound, { projectId: input.projectId });
|
||||
return project as ProjektRow;
|
||||
async function assertTenantUserWithTx(tx: TenantRlsClient, tenantId: string, userId?: string | null): Promise<void> {
|
||||
const normalized = normalizeText(userId);
|
||||
if (!normalized) return;
|
||||
const membership = await tx.tenantUser.findFirst({
|
||||
where: { tenantId, userId: normalized, status: TenantUserStatus.ACTIVE, user: { active: true } },
|
||||
select: { userId: true },
|
||||
});
|
||||
if (!membership) throw new CatalogError(foundationErrors.notFound, { userId: normalized });
|
||||
}
|
||||
|
||||
async function assertTenantGroupWithTx(tx: TenantRlsClient, tenantId: string, groupId?: string | null): Promise<void> {
|
||||
const normalized = normalizeText(groupId);
|
||||
if (!normalized) return;
|
||||
const group = await tx.group.findFirst({ where: { id: normalized, tenantId }, select: { id: true } });
|
||||
if (!group) throw new CatalogError(foundationErrors.notFound, { groupId: normalized });
|
||||
}
|
||||
|
||||
async function assertVisibleTenantFileWithTx(
|
||||
tx: TenantRlsClient,
|
||||
tenantId: string,
|
||||
fileId: string | null | undefined,
|
||||
ctx: AuftragVisibilityContext,
|
||||
): Promise<void> {
|
||||
const normalized = normalizeText(fileId);
|
||||
if (!normalized) return;
|
||||
const visibility = await fileReadScopeWhereWithTx(tx, tenantId, ctx, [normalized]);
|
||||
const file = await tx.file.findFirst({
|
||||
where: { id: normalized, tenantId, archivedAt: null, ...visibility },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!file) throw new CatalogError(foundationErrors.notFound, { fileId: normalized });
|
||||
}
|
||||
|
||||
async function reserveInvoiceNumberWithTx(tx: TenantRlsClient, tenantId: string): Promise<string> {
|
||||
@@ -252,10 +354,10 @@ export async function ensureDefaultProjectTemplate(input: { tenantId: string }):
|
||||
return withTenantRLS(input.tenantId, (tx) => ensureDefaultProjectTemplateWithTx(tx, input.tenantId));
|
||||
}
|
||||
|
||||
async function ensureDefaultAcceptanceFormTemplateWithTx(tx: TenantRlsClient, tenantId: string): Promise<AcceptanceFormTemplateRow> {
|
||||
export async function ensureDefaultAcceptanceFormTemplateWithTx(tx: TenantRlsClient, tenantId: string): Promise<AcceptanceFormTemplateRow> {
|
||||
const row = await tx.acceptanceFormTemplate.upsert({
|
||||
where: { tenantId_name: { tenantId, name: "SHK Standard-Abnahme" } },
|
||||
update: { archivedAt: null, isDefault: true, isDemoData: true },
|
||||
update: { archivedAt: null, isDefault: true, isDemoData: false },
|
||||
create: {
|
||||
tenantId,
|
||||
name: "SHK Standard-Abnahme",
|
||||
@@ -267,16 +369,16 @@ async function ensureDefaultAcceptanceFormTemplateWithTx(tx: TenantRlsClient, te
|
||||
],
|
||||
},
|
||||
isDefault: true,
|
||||
isDemoData: true,
|
||||
isDemoData: false,
|
||||
},
|
||||
});
|
||||
return row as AcceptanceFormTemplateRow;
|
||||
}
|
||||
|
||||
async function ensureDefaultProjectTemplateWithTx(tx: TenantRlsClient, tenantId: string): Promise<ProjectTemplateRow> {
|
||||
export async function ensureDefaultProjectTemplateWithTx(tx: TenantRlsClient, tenantId: string): Promise<ProjectTemplateRow> {
|
||||
const row = await tx.projectTemplate.upsert({
|
||||
where: { tenantId_name: { tenantId, name: "SHK Standard-Projekt" } },
|
||||
update: { archivedAt: null, isDemoData: true },
|
||||
update: { archivedAt: null, isDemoData: false },
|
||||
create: {
|
||||
tenantId,
|
||||
name: "SHK Standard-Projekt",
|
||||
@@ -287,7 +389,7 @@ async function ensureDefaultProjectTemplateWithTx(tx: TenantRlsClient, tenantId:
|
||||
{ titleKey: "projects.defaults.tasks.prepareAcceptance", priority: "high" },
|
||||
],
|
||||
customFields: {},
|
||||
isDemoData: true,
|
||||
isDemoData: false,
|
||||
},
|
||||
});
|
||||
return row as ProjectTemplateRow;
|
||||
@@ -317,12 +419,72 @@ export async function loadProjectSubAreas(input: { tenantId: string; projectId:
|
||||
},
|
||||
}),
|
||||
]);
|
||||
// R-P9a DoD 2 — tasks + documents sub-areas. Tasks are the tasks-module
|
||||
// rows linked to this project; documents are the files linked through
|
||||
// FileEntityLink, filtered by file visibility.
|
||||
const [tasks, fileLinks, groups, materials] = await Promise.all([
|
||||
tx.task.findMany({
|
||||
where: { tenantId: input.tenantId, linkedEntityType: "project", linkedEntityId: input.projectId, archivedAt: null },
|
||||
select: { id: true, title: true, status: true, priority: true, deadline: true, assignedToUserId: true, assignedToGroupId: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 100,
|
||||
}),
|
||||
tx.fileEntityLink.findMany({
|
||||
where: { tenantId: input.tenantId, entityType: "project", entityId: input.projectId },
|
||||
select: { fileId: true, linkRole: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 200,
|
||||
}),
|
||||
tx.group.findMany({ where: { tenantId: input.tenantId }, select: { id: true, name: true }, orderBy: { name: "asc" } }),
|
||||
tx.kwpMaterialPosition.findMany({
|
||||
where: { tenantId: input.tenantId, projektId: input.projectId, archivedAt: null },
|
||||
select: {
|
||||
id: true,
|
||||
positionNumber: true,
|
||||
text: true,
|
||||
longText: true,
|
||||
quantity: true,
|
||||
unit: true,
|
||||
unitPrice: true,
|
||||
totalPrice: true,
|
||||
lastSyncedAt: true,
|
||||
},
|
||||
orderBy: [{ positionNumber: "asc" }, { externalId: "asc" }],
|
||||
take: 500,
|
||||
}),
|
||||
]);
|
||||
let documents: ProjectSubAreaDocumentRow[] = [];
|
||||
if (fileLinks.length > 0) {
|
||||
const visibility = await fileReadScopeWhereWithTx(
|
||||
tx,
|
||||
input.tenantId,
|
||||
input.ctx,
|
||||
fileLinks.map((link) => link.fileId)
|
||||
);
|
||||
const files = await tx.file.findMany({
|
||||
where: { id: { in: fileLinks.map((link) => link.fileId) }, tenantId: input.tenantId, archivedAt: null, ...visibility },
|
||||
select: { id: true, displayName: true, mimeType: true, sizeBytes: true, createdAt: true },
|
||||
});
|
||||
const linkRoleByFileId = new Map(fileLinks.map((link) => [link.fileId, link.linkRole]));
|
||||
documents = files.map((file) => ({
|
||||
id: file.id,
|
||||
displayName: file.displayName,
|
||||
mimeType: file.mimeType,
|
||||
sizeBytes: file.sizeBytes,
|
||||
linkRole: linkRoleByFileId.get(file.id) ?? null,
|
||||
createdAt: file.createdAt,
|
||||
}));
|
||||
}
|
||||
return {
|
||||
project,
|
||||
members: members as ProjektMitgliedRow[],
|
||||
appointments: appointments as ProjektTerminRow[],
|
||||
invoices: invoices as RechnungRow[],
|
||||
checklists: checklists as ProjektChecklistRow[],
|
||||
tasks: tasks as ProjectSubAreaTaskRow[],
|
||||
documents,
|
||||
materials: materials as ProjectSubAreaMaterialRow[],
|
||||
groupOptions: groups,
|
||||
stageConfig: stageConfig as AuftragPipelineStageConfigRow | null,
|
||||
acceptanceTemplates: acceptanceTemplates as AcceptanceFormTemplateRow[],
|
||||
projectTemplates: projectTemplates as ProjectTemplateRow[],
|
||||
@@ -334,6 +496,7 @@ export async function loadProjectSubAreas(input: { tenantId: string; projectId:
|
||||
export async function addProjectMember(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
ctx: AuftragVisibilityContext;
|
||||
createdByUserId: string | null;
|
||||
userId?: string | null;
|
||||
groupId?: string | null;
|
||||
@@ -341,14 +504,20 @@ export async function addProjectMember(input: {
|
||||
}): Promise<ProjektMitgliedRow> {
|
||||
requireExactlyOnePrincipal(input.userId, input.groupId);
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireProjectWithTx(tx, input);
|
||||
await requireProjectSubAreaAccessWithTx(tx, { ...input, editable: true });
|
||||
const normalizedGroupId = normalizeText(input.groupId);
|
||||
await lockPermissionGroupsWithTx(tx, input.tenantId, normalizedGroupId ? [normalizedGroupId] : []);
|
||||
await Promise.all([
|
||||
assertTenantUserWithTx(tx, input.tenantId, input.userId),
|
||||
assertTenantGroupWithTx(tx, input.tenantId, normalizedGroupId),
|
||||
]);
|
||||
const row = await tx.projektMitglied.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
projektId: input.projectId,
|
||||
createdByUserId: input.createdByUserId,
|
||||
userId: normalizeText(input.userId),
|
||||
groupId: normalizeText(input.groupId),
|
||||
groupId: normalizedGroupId,
|
||||
rolle: input.rolle,
|
||||
},
|
||||
});
|
||||
@@ -360,18 +529,73 @@ export async function addProjectMember(input: {
|
||||
activityType: "project_member_added",
|
||||
subjectType: "project",
|
||||
subjectId: input.projectId,
|
||||
summaryText: "Projektmitglied wurde hinzugefügt.",
|
||||
summaryText: "activity.runtime.projects.memberAdded",
|
||||
metadata: { userId: input.userId ?? null, groupId: input.groupId ?? null, rolle: input.rolle },
|
||||
},
|
||||
{ client: tx },
|
||||
{ client: tx }
|
||||
);
|
||||
await ensureAndSyncProjectChannelIfEnabledWithTx(tx, {
|
||||
tenantId: input.tenantId,
|
||||
projectId: input.projectId,
|
||||
actorUserId: input.createdByUserId,
|
||||
requestId: `project:${input.projectId}:member:${row.id}:chat-add`,
|
||||
});
|
||||
return row as ProjektMitgliedRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeProjectMember(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
memberId: string;
|
||||
ctx: AuftragVisibilityContext;
|
||||
removedByUserId: string | null;
|
||||
}): Promise<{ id: string }> {
|
||||
const memberId = normalizeText(input.memberId);
|
||||
if (!memberId) throw new CatalogError(foundationErrors.notFound, { memberId: input.memberId });
|
||||
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireProjectSubAreaAccessWithTx(tx, { ...input, editable: true });
|
||||
const member = await tx.projektMitglied.findFirst({
|
||||
where: { id: memberId, tenantId: input.tenantId, projektId: input.projectId, archivedAt: null },
|
||||
select: { id: true, userId: true, groupId: true, rolle: true },
|
||||
});
|
||||
if (!member) throw new CatalogError(foundationErrors.notFound, { memberId });
|
||||
|
||||
const archivedAt = new Date();
|
||||
const archived = await tx.projektMitglied.updateMany({
|
||||
where: { id: member.id, tenantId: input.tenantId, projektId: input.projectId, archivedAt: null },
|
||||
data: { archivedAt },
|
||||
});
|
||||
if (archived.count !== 1) throw new CatalogError(foundationErrors.notFound, { memberId });
|
||||
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.removedByUserId,
|
||||
actorKind: input.removedByUserId ? "user" : "system",
|
||||
activityType: "project_member_removed",
|
||||
subjectType: "project",
|
||||
subjectId: input.projectId,
|
||||
summaryText: "activity.runtime.projects.memberRemoved",
|
||||
metadata: { memberId: member.id, userId: member.userId, groupId: member.groupId, rolle: member.rolle },
|
||||
},
|
||||
{ client: tx }
|
||||
);
|
||||
await ensureAndSyncProjectChannelIfEnabledWithTx(tx, {
|
||||
tenantId: input.tenantId,
|
||||
projectId: input.projectId,
|
||||
actorUserId: input.removedByUserId,
|
||||
requestId: `project:${input.projectId}:member:${member.id}:chat-remove`,
|
||||
});
|
||||
return { id: member.id };
|
||||
});
|
||||
}
|
||||
|
||||
export async function createProjectAppointment(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
ctx: AuftragVisibilityContext;
|
||||
createdByUserId: string | null;
|
||||
titel: string;
|
||||
beschreibung?: string | null;
|
||||
@@ -379,13 +603,18 @@ export async function createProjectAppointment(input: {
|
||||
endAt?: string | Date | null;
|
||||
assignedToUserId?: string | null;
|
||||
assignedToGroupId?: string | null;
|
||||
typ?: ProjektTerminTyp;
|
||||
}): Promise<ProjektTerminRow> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const title = normalizeText(input.titel);
|
||||
const startAt = parseDate(input.startAt);
|
||||
if (!title) throw new AuftragServiceError("projects.error.appointmentTitleRequired");
|
||||
if (!startAt) throw new AuftragServiceError("projects.error.appointmentStartRequired");
|
||||
await requireProjectWithTx(tx, input);
|
||||
await requireProjectSubAreaAccessWithTx(tx, { ...input, editable: true });
|
||||
await Promise.all([
|
||||
assertTenantUserWithTx(tx, input.tenantId, input.assignedToUserId),
|
||||
assertTenantGroupWithTx(tx, input.tenantId, input.assignedToGroupId),
|
||||
]);
|
||||
const row = await tx.projektTermin.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
@@ -397,6 +626,7 @@ export async function createProjectAppointment(input: {
|
||||
beschreibung: normalizeText(input.beschreibung),
|
||||
startAt,
|
||||
endAt: parseDate(input.endAt),
|
||||
...(input.typ ? { typ: input.typ } : {}),
|
||||
},
|
||||
});
|
||||
await logActivity(
|
||||
@@ -407,10 +637,10 @@ export async function createProjectAppointment(input: {
|
||||
activityType: "project_appointment_created",
|
||||
subjectType: "project",
|
||||
subjectId: input.projectId,
|
||||
summaryText: "Projekttermin wurde angelegt.",
|
||||
summaryText: "activity.runtime.projects.appointmentCreated",
|
||||
metadata: { appointmentId: row.id, startAt: row.startAt.toISOString() },
|
||||
},
|
||||
{ client: tx },
|
||||
{ client: tx }
|
||||
);
|
||||
return row as ProjektTerminRow;
|
||||
});
|
||||
@@ -419,6 +649,7 @@ export async function createProjectAppointment(input: {
|
||||
export async function createProjectInvoice(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
ctx: AuftragVisibilityContext;
|
||||
createdByUserId: string | null;
|
||||
betrag: string | number;
|
||||
datum?: string | Date | null;
|
||||
@@ -427,7 +658,8 @@ export async function createProjectInvoice(input: {
|
||||
quelle?: RechnungQuelle;
|
||||
}): Promise<RechnungRow> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireProjectWithTx(tx, input);
|
||||
await requireProjectSubAreaAccessWithTx(tx, { ...input, editable: true });
|
||||
await assertVisibleTenantFileWithTx(tx, input.tenantId, input.dateiId, input.ctx);
|
||||
const rechnungsnummer = await reserveInvoiceNumberWithTx(tx, input.tenantId);
|
||||
const row = await tx.rechnung.create({
|
||||
data: {
|
||||
@@ -450,20 +682,39 @@ export async function createProjectInvoice(input: {
|
||||
activityType: "project_invoice_created",
|
||||
subjectType: "project",
|
||||
subjectId: input.projectId,
|
||||
summaryText: `Rechnung ${row.rechnungsnummer} wurde angelegt.`,
|
||||
summaryText: "activity.runtime.projects.invoiceCreated",
|
||||
metadata: { invoiceId: row.id, rechnungsnummer: row.rechnungsnummer },
|
||||
},
|
||||
{ client: tx },
|
||||
{ client: tx }
|
||||
);
|
||||
return row as RechnungRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateProjectInvoiceStatus(input: { tenantId: string; invoiceId: string; userId: string | null; status: RechnungStatus }): Promise<RechnungRow> {
|
||||
export async function updateProjectInvoiceStatus(input: {
|
||||
tenantId: string;
|
||||
invoiceId: string;
|
||||
ctx: AuftragVisibilityContext;
|
||||
userId: string | null;
|
||||
status: RechnungStatus;
|
||||
}): Promise<RechnungRow> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const existing = await tx.rechnung.findFirst({ where: { id: input.invoiceId, tenantId: input.tenantId, archivedAt: null } });
|
||||
if (!existing) throw new CatalogError(foundationErrors.notFound, { invoiceId: input.invoiceId });
|
||||
const row = await tx.rechnung.update({ where: { id: input.invoiceId }, data: { status: input.status } });
|
||||
await requireProjectSubAreaAccessWithTx(tx, {
|
||||
tenantId: input.tenantId,
|
||||
projectId: existing.projektId,
|
||||
ctx: input.ctx,
|
||||
editable: true,
|
||||
});
|
||||
// Stamp the payment date on the transition into `bezahlt` and clear it on the
|
||||
// way out, so revenue by payment date stays truthful when a payment is undone.
|
||||
// Re-setting an already-paid invoice to `bezahlt` keeps the original date.
|
||||
const bezahltAm = input.status === "bezahlt" ? (existing.bezahltAm ?? new Date()) : null;
|
||||
const row = await tx.rechnung.update({
|
||||
where: { id: input.invoiceId, tenantId: input.tenantId },
|
||||
data: { status: input.status, bezahltAm },
|
||||
});
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
@@ -472,10 +723,10 @@ export async function updateProjectInvoiceStatus(input: { tenantId: string; invo
|
||||
activityType: "project_invoice_status_changed",
|
||||
subjectType: "project",
|
||||
subjectId: existing.projektId,
|
||||
summaryText: `Rechnungsstatus wurde auf ${input.status} gesetzt.`,
|
||||
summaryText: "activity.runtime.projects.invoiceStatusChanged",
|
||||
metadata: { invoiceId: input.invoiceId, status: input.status },
|
||||
},
|
||||
{ client: tx },
|
||||
{ client: tx }
|
||||
);
|
||||
return row as RechnungRow;
|
||||
});
|
||||
@@ -484,6 +735,7 @@ export async function updateProjectInvoiceStatus(input: { tenantId: string; invo
|
||||
export async function createProjectChecklist(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
ctx: AuftragVisibilityContext;
|
||||
createdByUserId: string | null;
|
||||
titel: string;
|
||||
typ?: ProjektChecklistTyp;
|
||||
@@ -491,7 +743,7 @@ export async function createProjectChecklist(input: {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const title = normalizeText(input.titel);
|
||||
if (!title) throw new AuftragServiceError("projects.error.checklistTitleRequired");
|
||||
await requireProjectWithTx(tx, input);
|
||||
await requireProjectSubAreaAccessWithTx(tx, { ...input, editable: true });
|
||||
const row = await tx.projektChecklist.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
@@ -509,10 +761,10 @@ export async function createProjectChecklist(input: {
|
||||
activityType: "project_checklist_created",
|
||||
subjectType: "project",
|
||||
subjectId: input.projectId,
|
||||
summaryText: "Projekt-Checkliste wurde angelegt.",
|
||||
summaryText: "activity.runtime.projects.checklistCreated",
|
||||
metadata: { checklistId: row.id, typ: row.typ },
|
||||
},
|
||||
{ client: tx },
|
||||
{ client: tx }
|
||||
);
|
||||
return row as ProjektChecklistRow;
|
||||
});
|
||||
@@ -521,6 +773,7 @@ export async function createProjectChecklist(input: {
|
||||
export async function upsertProjectChecklistItem(input: {
|
||||
tenantId: string;
|
||||
checklistId: string;
|
||||
ctx: AuftragVisibilityContext;
|
||||
itemId?: string | null;
|
||||
titel: string;
|
||||
status?: ProjektChecklistItemStatus;
|
||||
@@ -535,6 +788,16 @@ export async function upsertProjectChecklistItem(input: {
|
||||
if (!title) throw new AuftragServiceError("projects.error.checklistItemTitleRequired");
|
||||
const checklist = await tx.projektChecklist.findFirst({ where: { id: input.checklistId, tenantId: input.tenantId, archivedAt: null } });
|
||||
if (!checklist) throw new CatalogError(foundationErrors.notFound, { checklistId: input.checklistId });
|
||||
await requireProjectSubAreaAccessWithTx(tx, {
|
||||
tenantId: input.tenantId,
|
||||
projectId: checklist.projektId,
|
||||
ctx: input.ctx,
|
||||
editable: true,
|
||||
});
|
||||
await Promise.all([
|
||||
assertTenantUserWithTx(tx, input.tenantId, input.assignedToUserId),
|
||||
assertVisibleTenantFileWithTx(tx, input.tenantId, input.fotoFileId, input.ctx),
|
||||
]);
|
||||
const data = {
|
||||
titel: title,
|
||||
status: input.status ?? "offen",
|
||||
@@ -545,7 +808,15 @@ export async function upsertProjectChecklistItem(input: {
|
||||
position: input.position ?? 0,
|
||||
};
|
||||
if (input.itemId) {
|
||||
const row = await tx.projektChecklistItem.update({ where: { id: input.itemId }, data });
|
||||
const existingItem = await tx.projektChecklistItem.findFirst({
|
||||
where: { id: input.itemId, tenantId: input.tenantId, checklistId: input.checklistId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!existingItem) throw new CatalogError(foundationErrors.notFound, { itemId: input.itemId });
|
||||
const row = await tx.projektChecklistItem.update({
|
||||
where: { id: input.itemId, tenantId: input.tenantId, checklistId: input.checklistId },
|
||||
data,
|
||||
});
|
||||
return row as ProjektChecklistItemRow;
|
||||
}
|
||||
const row = await tx.projektChecklistItem.create({
|
||||
@@ -566,11 +837,19 @@ export async function upsertAuftragPipelineStageConfig(input: {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const stage = await tx.pipelineStage.findFirst({ where: { id: input.stageId, tenantId: input.tenantId, pipelineId: input.pipelineId, archivedAt: null } });
|
||||
if (!stage) throw new CatalogError(foundationErrors.notFound, { stageId: input.stageId });
|
||||
const acceptanceFormTemplateId = normalizeText(input.acceptanceFormTemplateId);
|
||||
if (acceptanceFormTemplateId) {
|
||||
const template = await tx.acceptanceFormTemplate.findFirst({
|
||||
where: { id: acceptanceFormTemplateId, tenantId: input.tenantId, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!template) throw new CatalogError(foundationErrors.notFound, { acceptanceFormTemplateId });
|
||||
}
|
||||
const row = await tx.auftragPipelineStageConfig.upsert({
|
||||
where: { tenantId_stageId: { tenantId: input.tenantId, stageId: input.stageId } },
|
||||
update: {
|
||||
requiresAcceptanceProtocol: input.requiresAcceptanceProtocol ?? false,
|
||||
acceptanceFormTemplateId: normalizeText(input.acceptanceFormTemplateId),
|
||||
acceptanceFormTemplateId,
|
||||
autoArchiveAfterDays: input.autoArchiveAfterDays ?? null,
|
||||
},
|
||||
create: {
|
||||
@@ -578,7 +857,7 @@ export async function upsertAuftragPipelineStageConfig(input: {
|
||||
pipelineId: input.pipelineId,
|
||||
stageId: input.stageId,
|
||||
requiresAcceptanceProtocol: input.requiresAcceptanceProtocol ?? false,
|
||||
acceptanceFormTemplateId: normalizeText(input.acceptanceFormTemplateId),
|
||||
acceptanceFormTemplateId,
|
||||
autoArchiveAfterDays: input.autoArchiveAfterDays ?? null,
|
||||
},
|
||||
});
|
||||
@@ -598,9 +877,22 @@ export async function upsertAcceptanceFormTemplate(input: {
|
||||
const name = normalizeText(input.name);
|
||||
if (!name) throw new AuftragServiceError("projects.error.acceptanceTemplateNameRequired");
|
||||
if (input.templateId) {
|
||||
const existing = await tx.acceptanceFormTemplate.findFirst({
|
||||
where: { id: input.templateId, tenantId: input.tenantId, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!existing) throw new CatalogError(foundationErrors.notFound, { templateId: input.templateId });
|
||||
// Partial update: absent fields stay untouched (undefined = no-op in
|
||||
// Prisma) so e.g. a make-default toggle cannot wipe the definition.
|
||||
const row = await tx.acceptanceFormTemplate.update({
|
||||
where: { id: input.templateId },
|
||||
data: { name, formId: normalizeText(input.formId), definition: input.definition ?? {}, isDefault: input.isDefault ?? false, archivedAt: null },
|
||||
where: { id: existing.id, tenantId: input.tenantId },
|
||||
data: {
|
||||
name,
|
||||
formId: input.formId === undefined ? undefined : normalizeText(input.formId),
|
||||
definition: input.definition === undefined ? undefined : input.definition ?? {},
|
||||
isDefault: input.isDefault,
|
||||
archivedAt: null,
|
||||
},
|
||||
});
|
||||
return row as AcceptanceFormTemplateRow;
|
||||
}
|
||||
@@ -637,17 +929,44 @@ export async function upsertProjectTemplate(input: {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const name = normalizeText(input.name);
|
||||
if (!name) throw new AuftragServiceError("projects.error.projectTemplateNameRequired");
|
||||
const defaultPipelineId = normalizeText(input.defaultPipelineId);
|
||||
const defaultStageId = normalizeText(input.defaultStageId);
|
||||
if (defaultStageId && !defaultPipelineId) throw new AuftragServiceError("projects.error.pipelineRequired");
|
||||
if (defaultStageId && defaultPipelineId) {
|
||||
const stage = await tx.pipelineStage.findFirst({
|
||||
where: {
|
||||
id: defaultStageId,
|
||||
tenantId: input.tenantId,
|
||||
pipelineId: defaultPipelineId,
|
||||
archivedAt: null,
|
||||
pipeline: { tenantId: input.tenantId, archivedAt: null },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (!stage) throw new CatalogError(foundationErrors.notFound, { defaultPipelineId, defaultStageId });
|
||||
} else if (defaultPipelineId) {
|
||||
const pipeline = await tx.pipeline.findFirst({
|
||||
where: { id: defaultPipelineId, tenantId: input.tenantId, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!pipeline) throw new CatalogError(foundationErrors.notFound, { defaultPipelineId });
|
||||
}
|
||||
const data = {
|
||||
name,
|
||||
defaultPipelineId: normalizeText(input.defaultPipelineId),
|
||||
defaultStageId: normalizeText(input.defaultStageId),
|
||||
defaultPipelineId,
|
||||
defaultStageId,
|
||||
defaultMembers: input.defaultMembers ?? [],
|
||||
defaultTasks: input.defaultTasks ?? [],
|
||||
customFields: input.customFields ?? {},
|
||||
archivedAt: null,
|
||||
};
|
||||
if (input.templateId) {
|
||||
const row = await tx.projectTemplate.update({ where: { id: input.templateId }, data });
|
||||
const existing = await tx.projectTemplate.findFirst({
|
||||
where: { id: input.templateId, tenantId: input.tenantId, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!existing) throw new CatalogError(foundationErrors.notFound, { templateId: input.templateId });
|
||||
const row = await tx.projectTemplate.update({ where: { id: existing.id, tenantId: input.tenantId }, data });
|
||||
return row as ProjectTemplateRow;
|
||||
}
|
||||
const row = await tx.projectTemplate.upsert({
|
||||
@@ -670,28 +989,16 @@ export async function listProjectTemplates(input: { tenantId: string }): Promise
|
||||
});
|
||||
}
|
||||
|
||||
// R-P9a DoD 4 — the sweep logic is shared with the worker cron via
|
||||
// @hivegrid/db/project-auto-archive.server; this wrapper only binds the tenant
|
||||
// RLS context and injects the chat-channel archive side effect (AK-P15b).
|
||||
export async function autoArchiveProjectsForStageConfigs(input: { tenantId: string; now?: Date; limit?: number }): Promise<{ archived: number }> {
|
||||
const now = input.now ?? new Date();
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const configs = await tx.auftragPipelineStageConfig.findMany({
|
||||
where: { tenantId: input.tenantId, autoArchiveAfterDays: { not: null } },
|
||||
take: Math.min(Math.max(input.limit ?? 100, 1), 500),
|
||||
});
|
||||
let archived = 0;
|
||||
for (const config of configs) {
|
||||
if (!config.autoArchiveAfterDays) continue;
|
||||
const threshold = new Date(now.getTime() - config.autoArchiveAfterDays * 24 * 60 * 60 * 1000);
|
||||
const result = await tx.projekt.updateMany({
|
||||
where: {
|
||||
tenantId: input.tenantId,
|
||||
stageId: config.stageId,
|
||||
archivedAt: null,
|
||||
updatedAt: { lte: threshold },
|
||||
},
|
||||
data: { archivedAt: now },
|
||||
});
|
||||
archived += result.count;
|
||||
}
|
||||
return { archived };
|
||||
});
|
||||
return withTenantRLS(input.tenantId, (tx) =>
|
||||
autoArchiveProjectsForTenantWithTx(tx as unknown as Parameters<typeof autoArchiveProjectsForTenantWithTx>[0], {
|
||||
tenantId: input.tenantId,
|
||||
now: input.now,
|
||||
limit: input.limit,
|
||||
archiveChannel: (channelInput) => archiveProjectChannelIfEnabledWithTx(tx, channelInput),
|
||||
})
|
||||
);
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tx: {
|
||||
pipeline: { findFirst: vi.fn() },
|
||||
pipelineStage: { findFirst: vi.fn() },
|
||||
acceptanceFormTemplate: { findFirst: vi.fn() },
|
||||
auftragPipelineStageConfig: { upsert: vi.fn() },
|
||||
projectTemplate: { findFirst: vi.fn(), update: vi.fn(), upsert: 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: vi.fn() }));
|
||||
|
||||
import { upsertAuftragPipelineStageConfig, upsertProjectTemplate } from "./auftragService.server";
|
||||
|
||||
describe("order/project template parent ownership boundaries", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.pipeline.findFirst.mockResolvedValue({ id: "pipeline-a" });
|
||||
mocks.tx.pipelineStage.findFirst.mockResolvedValue({ id: "stage-a" });
|
||||
mocks.tx.acceptanceFormTemplate.findFirst.mockResolvedValue({ id: "acceptance-a" });
|
||||
mocks.tx.projectTemplate.findFirst.mockResolvedValue({ id: "template-a" });
|
||||
mocks.tx.projectTemplate.update.mockResolvedValue({ id: "template-a" });
|
||||
});
|
||||
|
||||
it("rejects a cross-tenant acceptance template on stage-config upsert", async () => {
|
||||
mocks.tx.acceptanceFormTemplate.findFirst.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
upsertAuftragPipelineStageConfig({
|
||||
tenantId: "tenant-a",
|
||||
pipelineId: "pipeline-a",
|
||||
stageId: "stage-a",
|
||||
acceptanceFormTemplateId: "acceptance-from-tenant-b",
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(mocks.tx.auftragPipelineStageConfig.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects a project template stage outside its tenant pipeline", async () => {
|
||||
mocks.tx.pipelineStage.findFirst.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
upsertProjectTemplate({
|
||||
tenantId: "tenant-a",
|
||||
name: "Foreign defaults",
|
||||
defaultPipelineId: "pipeline-a",
|
||||
defaultStageId: "stage-from-tenant-b",
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(mocks.tx.projectTemplate.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects a foreign template target and tenant-scopes a valid update", async () => {
|
||||
mocks.tx.projectTemplate.findFirst.mockResolvedValueOnce(null);
|
||||
await expect(
|
||||
upsertProjectTemplate({
|
||||
tenantId: "tenant-a",
|
||||
templateId: "template-from-tenant-b",
|
||||
name: "Foreign target",
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
expect(mocks.tx.projectTemplate.update).not.toHaveBeenCalled();
|
||||
|
||||
await upsertProjectTemplate({ tenantId: "tenant-a", templateId: "template-a", name: "Safe update" });
|
||||
expect(mocks.tx.projectTemplate.update).toHaveBeenCalledWith({
|
||||
where: { id: "template-a", tenantId: "tenant-a" },
|
||||
data: {
|
||||
name: "Safe update",
|
||||
defaultPipelineId: null,
|
||||
defaultStageId: null,
|
||||
defaultMembers: [],
|
||||
defaultTasks: [],
|
||||
customFields: {},
|
||||
archivedAt: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
// WF-P8 Subframe delta (S00 boards start page) — server helper for
|
||||
// `/projects/boards`. Lists the viewer-visible pipelines (listPipelines applies
|
||||
// the deny-based pipeline access scope) and adds stage/project counts. Project
|
||||
// counts use the same read scope as the board/list (projectReadScopeWhere) so
|
||||
// the numbers match what the viewer sees on the board; demo rows are excluded
|
||||
// like the list default. Server-only (.server) — never imported by a component.
|
||||
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { listPipelines, projectReadScopeWhere } from "./projectService.server";
|
||||
import type { ProjectRouteContext } from "./projectAccess.server";
|
||||
|
||||
export type BoardsStartPipeline = {
|
||||
id: string;
|
||||
name: string;
|
||||
typHint: "sales" | "auftrag" | "custom";
|
||||
isDefault: boolean;
|
||||
stageCount: number;
|
||||
projectCount: number;
|
||||
};
|
||||
|
||||
export async function loadBoardsStartPipelines({
|
||||
tenantId,
|
||||
ctx,
|
||||
}: {
|
||||
tenantId: string;
|
||||
ctx: ProjectRouteContext;
|
||||
}): Promise<BoardsStartPipeline[]> {
|
||||
const [pipelines, projectTotals] = await Promise.all([
|
||||
listPipelines({ tenantId, ctx }),
|
||||
withTenantRLS(tenantId, async (tx) =>
|
||||
tx.projekt.groupBy({
|
||||
by: ["pipelineId"],
|
||||
where: {
|
||||
tenantId,
|
||||
archivedAt: null,
|
||||
isDemoData: false,
|
||||
...projectReadScopeWhere(tenantId, ctx),
|
||||
},
|
||||
_count: { _all: true },
|
||||
}),
|
||||
),
|
||||
]);
|
||||
const countsByPipeline = new Map(projectTotals.map((total) => [total.pipelineId, total._count._all]));
|
||||
return pipelines.map((pipeline) => ({
|
||||
id: pipeline.id,
|
||||
name: pipeline.name,
|
||||
typHint: pipeline.typHint,
|
||||
isDefault: pipeline.isDefault,
|
||||
stageCount: pipeline.stages.length,
|
||||
projectCount: countsByPipeline.get(pipeline.id) ?? 0,
|
||||
}));
|
||||
}
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
// WF-P8 Subframe delta — pipelineAccessRequest.server unit test. The Prisma
|
||||
// client is mocked, but NOT as an answer-everything stub: the withTenantRLS
|
||||
// mock binds a tenant context and every tx method re-checks the queried
|
||||
// tenantId against the bound context (mirroring the hg_*_all RLS policy), so
|
||||
// a query for a foreign tenant yields no rows instead of leaking fixtures.
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const TENANT = "tenant-a";
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
const state = {
|
||||
boundTenantId: null as string | null,
|
||||
pipelines: [] as Array<Record<string, unknown>>,
|
||||
requests: [] as Array<Record<string, unknown>>,
|
||||
admins: [] as Array<{ userId: string }>,
|
||||
projectCounts: [] as Array<{ pipelineId: string; _count: { _all: number } }>,
|
||||
};
|
||||
// RLS-shaped guard: rows only exist when the bound context matches the
|
||||
// tenant in the query (no context / wrong tenant -> zero rows, like Postgres).
|
||||
const visible = (whereTenantId: unknown) => state.boundTenantId !== null && whereTenantId === state.boundTenantId;
|
||||
const ownRows = <T extends { tenantId?: unknown }>(rows: T[]) => rows.filter((row) => row.tenantId === state.boundTenantId);
|
||||
const tx = {
|
||||
pipeline: {
|
||||
findMany: vi.fn(async (args: { where: { tenantId: string } }) => (visible(args.where.tenantId) ? ownRows(state.pipelines) : [])),
|
||||
findFirst: vi.fn(async (args: { where: { tenantId: string; id: string } }) => {
|
||||
if (!visible(args.where.tenantId)) return null;
|
||||
return ownRows(state.pipelines).find((pipeline) => pipeline.id === args.where.id) ?? null;
|
||||
}),
|
||||
},
|
||||
projekt: {
|
||||
groupBy: vi.fn(async (args: { where: { tenantId: string } }) => (visible(args.where.tenantId) ? state.projectCounts : [])),
|
||||
},
|
||||
pipelineAccessRequest: {
|
||||
findMany: vi.fn(async (args: { where: { tenantId: string; requestedByUserId: string; status: string } }) => {
|
||||
if (!visible(args.where.tenantId)) return [];
|
||||
return state.requests.filter(
|
||||
(request) => request.requestedByUserId === args.where.requestedByUserId && request.status === args.where.status
|
||||
);
|
||||
}),
|
||||
findFirst: vi.fn(
|
||||
async (args: { where: { tenantId: string; pipelineId: string; requestedByUserId: string; status: string } }) => {
|
||||
if (!visible(args.where.tenantId)) return null;
|
||||
return (
|
||||
state.requests.find(
|
||||
(request) =>
|
||||
request.pipelineId === args.where.pipelineId &&
|
||||
request.requestedByUserId === args.where.requestedByUserId &&
|
||||
request.status === args.where.status
|
||||
) ?? null
|
||||
);
|
||||
}
|
||||
),
|
||||
create: vi.fn(async (args: { data: Record<string, unknown> }) => {
|
||||
if (!visible(args.data.tenantId)) throw new Error("rls: insert with unbound/foreign tenant context denied");
|
||||
const row = { id: "req-new", status: "open", createdAt: new Date(), resolvedAt: null, resolvedByUserId: null, ...args.data };
|
||||
state.requests.push(row);
|
||||
return row;
|
||||
}),
|
||||
updateMany: vi.fn(async (args: { where: { tenantId: string } }) => {
|
||||
if (!visible(args.where.tenantId)) return { count: 0 };
|
||||
return { count: 1 };
|
||||
}),
|
||||
},
|
||||
userRole: {
|
||||
findMany: vi.fn(async (args: { where: { tenantId: string } }) => (visible(args.where.tenantId) ? state.admins : [])),
|
||||
},
|
||||
};
|
||||
return {
|
||||
state,
|
||||
tx,
|
||||
notify: vi.fn(async () => undefined),
|
||||
createAuditEvent: vi.fn(async () => ({ id: "audit-1" })),
|
||||
withTenantRLS: vi.fn(async (tenantId: string, fn: (tx: unknown) => Promise<unknown>) => {
|
||||
state.boundTenantId = tenantId;
|
||||
try {
|
||||
return await fn(tx);
|
||||
} finally {
|
||||
state.boundTenantId = null;
|
||||
}
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: mocks.withTenantRLS }));
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({ createAuditEvent: mocks.createAuditEvent }));
|
||||
vi.mock("@hivegrid/foundation", async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
notify: mocks.notify,
|
||||
}));
|
||||
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import {
|
||||
listLockedPipelinesForViewer,
|
||||
requestPipelineAccess,
|
||||
resolveOpenAccessRequests,
|
||||
} from "./pipelineAccessRequest.server";
|
||||
import type { ProjectRouteContext } from "./projectAccess.server";
|
||||
|
||||
function ctx(overrides: Partial<ProjectRouteContext> = {}): ProjectRouteContext {
|
||||
return {
|
||||
tenantId: TENANT,
|
||||
userId: "user-a",
|
||||
permissions: ["projects.read_own"],
|
||||
roleIds: ["role-1"],
|
||||
groupIds: ["group-1"],
|
||||
hasModule: true,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.state.boundTenantId = null;
|
||||
mocks.state.pipelines = [
|
||||
{ id: "pl-locked", tenantId: TENANT, name: "Geschaeftsleitung", typHint: "sales", isDefault: false, stages: [{ id: "s1" }, { id: "s2" }] },
|
||||
];
|
||||
mocks.state.requests = [];
|
||||
mocks.state.admins = [{ userId: "admin-1" }, { userId: "admin-1" }, { userId: "admin-2" }];
|
||||
mocks.state.projectCounts = [{ pipelineId: "pl-locked", _count: { _all: 7 } }];
|
||||
});
|
||||
|
||||
describe("listLockedPipelinesForViewer", () => {
|
||||
it("lists locked pipelines with counts and the deny-rule scope", async () => {
|
||||
const rows = await listLockedPipelinesForViewer({ tenantId: TENANT, ctx: ctx() });
|
||||
expect(rows).toEqual([
|
||||
{
|
||||
id: "pl-locked",
|
||||
name: "Geschaeftsleitung",
|
||||
typHint: "sales",
|
||||
isDefault: false,
|
||||
stageCount: 2,
|
||||
projectCount: 7,
|
||||
requestPending: false,
|
||||
},
|
||||
]);
|
||||
// The query must match pipelines with an explicit deny rule for one of the
|
||||
// viewer's effective principals (inverse of the visibility scope).
|
||||
const where = mocks.tx.pipeline.findMany.mock.calls[0][0].where as Record<string, unknown>;
|
||||
expect(where.archivedAt).toBeNull();
|
||||
expect(where.accessRules).toEqual({
|
||||
some: {
|
||||
tenantId: TENANT,
|
||||
kannSehen: false,
|
||||
OR: [
|
||||
{ principalType: "user", principalId: "user-a" },
|
||||
{ principalType: "role", principalId: "role-1" },
|
||||
{ principalType: "group", principalId: "group-1" },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("flags pipelines with an open request by the viewer as pending", async () => {
|
||||
mocks.state.requests = [{ id: "req-1", pipelineId: "pl-locked", requestedByUserId: "user-a", status: "open" }];
|
||||
const rows = await listLockedPipelinesForViewer({ tenantId: TENANT, ctx: ctx() });
|
||||
expect(rows[0]?.requestPending).toBe(true);
|
||||
});
|
||||
|
||||
it("yields no rows for a foreign tenant (RLS context mismatch)", async () => {
|
||||
// The fixture pipelines belong to tenant-a; binding tenant-b's context
|
||||
// must answer with zero rows, like the RLS policy in Postgres.
|
||||
const rows = await listLockedPipelinesForViewer({ tenantId: "tenant-b", ctx: ctx({ tenantId: "tenant-b" }) });
|
||||
expect(rows).toEqual([]);
|
||||
expect(mocks.withTenantRLS).toHaveBeenCalledWith("tenant-b", expect.any(Function));
|
||||
});
|
||||
});
|
||||
|
||||
describe("requestPipelineAccess", () => {
|
||||
it("rejects a pipeline that is not locked for the viewer with catalog notFound", async () => {
|
||||
mocks.tx.pipeline.findFirst.mockResolvedValueOnce(null);
|
||||
await expect(
|
||||
requestPipelineAccess({ tenantId: TENANT, pipelineId: "pl-open", userId: "user-a", ctx: ctx() })
|
||||
).rejects.toBeInstanceOf(CatalogError);
|
||||
expect(mocks.tx.pipelineAccessRequest.create).not.toHaveBeenCalled();
|
||||
expect(mocks.notify).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("creates a request, notifies deduped projects.admin users and audits", async () => {
|
||||
const result = await requestPipelineAccess({ tenantId: TENANT, pipelineId: "pl-locked", userId: "user-a", ctx: ctx() });
|
||||
expect(result.created).toBe(true);
|
||||
expect(result.request.pipelineId).toBe("pl-locked");
|
||||
// Fan-out deduped: admin-1 appears twice in the role rows but is notified once.
|
||||
expect(mocks.notify).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.notify.mock.calls.map((call) => (call[0] as { userId: string }).userId).sort()).toEqual(["admin-1", "admin-2"]);
|
||||
expect(mocks.notify.mock.calls[0][0]).toMatchObject({
|
||||
tenantId: TENANT,
|
||||
channel: "IN_APP",
|
||||
category: "projects",
|
||||
messageKey: "projects.notification.pipelineAccessRequested",
|
||||
sourceKey: "pipeline-access-request:req-new",
|
||||
payloadMetadata: { pipelineId: "pl-locked", pipelineName: "Geschaeftsleitung", requesterUserId: "user-a" },
|
||||
});
|
||||
expect(mocks.createAuditEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
tenantId: TENANT,
|
||||
actorId: "user-a",
|
||||
action: "pipeline.access_requested",
|
||||
targetType: "pipeline",
|
||||
targetId: "pl-locked",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("is idempotent for an existing open request of the same user", async () => {
|
||||
mocks.state.requests = [{ id: "req-1", pipelineId: "pl-locked", requestedByUserId: "user-a", status: "open" }];
|
||||
const result = await requestPipelineAccess({ tenantId: TENANT, pipelineId: "pl-locked", userId: "user-a", ctx: ctx() });
|
||||
expect(result.created).toBe(false);
|
||||
expect(result.request.id).toBe("req-1");
|
||||
expect(mocks.tx.pipelineAccessRequest.create).not.toHaveBeenCalled();
|
||||
expect(mocks.notify).not.toHaveBeenCalled();
|
||||
expect(mocks.createAuditEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stays best-effort when notify or audit fail", async () => {
|
||||
mocks.notify.mockRejectedValueOnce(new Error("smtp down"));
|
||||
mocks.createAuditEvent.mockRejectedValueOnce(new Error("audit down"));
|
||||
const result = await requestPipelineAccess({ tenantId: TENANT, pipelineId: "pl-locked", userId: "user-a", ctx: ctx() });
|
||||
expect(result.created).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveOpenAccessRequests", () => {
|
||||
it("marks the user's open requests for the pipeline as approved", async () => {
|
||||
const count = await resolveOpenAccessRequests({
|
||||
tenantId: TENANT,
|
||||
pipelineId: "pl-locked",
|
||||
userId: "user-a",
|
||||
resolvedByUserId: "admin-1",
|
||||
status: "approved",
|
||||
});
|
||||
expect(count).toBe(1);
|
||||
const args = mocks.tx.pipelineAccessRequest.updateMany.mock.calls[0][0] as {
|
||||
where: Record<string, unknown>;
|
||||
data: Record<string, unknown>;
|
||||
};
|
||||
expect(args.where).toEqual({ tenantId: TENANT, pipelineId: "pl-locked", requestedByUserId: "user-a", status: "open" });
|
||||
expect(args.data).toMatchObject({ status: "approved", resolvedByUserId: "admin-1" });
|
||||
expect(args.data.resolvedAt).toBeInstanceOf(Date);
|
||||
});
|
||||
});
|
||||
+242
@@ -0,0 +1,242 @@
|
||||
// WF-P8 Subframe delta (S00 boards start page) — pipeline access requests.
|
||||
//
|
||||
// The pipeline access model is deny-based (PipelineAccess with
|
||||
// kannSehen=false). The Subframe design keeps locked boards visible on the
|
||||
// boards start page (greyed out, "Nutzung anfragen"), so this module lists
|
||||
// the pipelines the viewer is locked OUT of and lets the viewer file an
|
||||
// access request. projects.admin users get an IN_APP notification (M011) and
|
||||
// every request is audited (M001). Server-only (.server) — never imported by
|
||||
// a component.
|
||||
|
||||
import { CatalogError, foundationErrors, notify } from "@hivegrid/foundation";
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
import { effectivePipelinePrincipals } from "./projectService.server";
|
||||
import type { ProjectRouteContext } from "./projectAccess.server";
|
||||
|
||||
export type PipelineAccessRequestResolution = "approved" | "dismissed";
|
||||
|
||||
export type LockedBoardsStartPipeline = {
|
||||
id: string;
|
||||
name: string;
|
||||
typHint: "sales" | "auftrag" | "custom";
|
||||
isDefault: boolean;
|
||||
stageCount: number;
|
||||
projectCount: number;
|
||||
/** The viewer already has an open access request for this pipeline. */
|
||||
requestPending: boolean;
|
||||
};
|
||||
|
||||
export type PipelineAccessRequestRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
pipelineId: string;
|
||||
requestedByUserId: string;
|
||||
status: "open" | PipelineAccessRequestResolution;
|
||||
createdAt: Date;
|
||||
resolvedAt: Date | null;
|
||||
resolvedByUserId: string | null;
|
||||
};
|
||||
|
||||
/** Deny-rule match: the viewer is locked out when ANY rule with
|
||||
* kannSehen=false targets one of their effective principals (inverse of
|
||||
* pipelineVisibilityScopeWhere). */
|
||||
function lockedPipelineScopeWhere(tenantId: string, ctx: ProjectRouteContext): Record<string, unknown> {
|
||||
return {
|
||||
accessRules: {
|
||||
some: {
|
||||
tenantId,
|
||||
kannSehen: false,
|
||||
OR: effectivePipelinePrincipals(ctx),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the non-archived pipelines the viewer is locked out of, with the same
|
||||
* stage/project count shape as loadBoardsStartPipelines. Project counts are
|
||||
* board totals (active, non-demo) WITHOUT the viewer read scope on purpose:
|
||||
* the viewer cannot read any project on a locked board, so the viewer-scoped
|
||||
* count would always be 0 — the greyed-out row shows the board's size, which
|
||||
* the design treats as non-sensitive (like the board name itself).
|
||||
*/
|
||||
export async function listLockedPipelinesForViewer({
|
||||
tenantId,
|
||||
ctx,
|
||||
}: {
|
||||
tenantId: string;
|
||||
ctx: ProjectRouteContext;
|
||||
}): Promise<LockedBoardsStartPipeline[]> {
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
const pipelines = await tx.pipeline.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
archivedAt: null,
|
||||
...lockedPipelineScopeWhere(tenantId, ctx),
|
||||
},
|
||||
include: { stages: { where: { archivedAt: null }, select: { id: true } } },
|
||||
orderBy: { position: "asc" },
|
||||
});
|
||||
if (pipelines.length === 0) return [];
|
||||
const pipelineIds = pipelines.map((pipeline) => pipeline.id);
|
||||
const [projectTotals, openRequests] = await Promise.all([
|
||||
tx.projekt.groupBy({
|
||||
by: ["pipelineId"],
|
||||
where: { tenantId, pipelineId: { in: pipelineIds }, archivedAt: null, isDemoData: false },
|
||||
_count: { _all: true },
|
||||
}),
|
||||
tx.pipelineAccessRequest.findMany({
|
||||
where: { tenantId, pipelineId: { in: pipelineIds }, requestedByUserId: ctx.userId, status: "open" },
|
||||
select: { pipelineId: true },
|
||||
}),
|
||||
]);
|
||||
const countsByPipeline = new Map(projectTotals.map((total) => [total.pipelineId, total._count._all]));
|
||||
const pendingPipelineIds = new Set(openRequests.map((request) => request.pipelineId));
|
||||
return pipelines.map((pipeline) => ({
|
||||
id: pipeline.id,
|
||||
name: pipeline.name,
|
||||
typHint: pipeline.typHint,
|
||||
isDefault: pipeline.isDefault,
|
||||
stageCount: pipeline.stages.length,
|
||||
projectCount: countsByPipeline.get(pipeline.id) ?? 0,
|
||||
requestPending: pendingPipelineIds.has(pipeline.id),
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
/** Best-effort M011 fan-out to every projects.admin user (same recipient
|
||||
* pattern as leadService's notifyLeadSourcePausedAdmins). */
|
||||
async function notifyProjectsAdmins(
|
||||
tx: TenantRlsClient,
|
||||
input: { tenantId: string; requestId: string; pipelineId: string; pipelineName: string; requesterUserId: string }
|
||||
): Promise<void> {
|
||||
try {
|
||||
const admins = await tx.userRole.findMany({
|
||||
where: {
|
||||
tenantId: input.tenantId,
|
||||
role: { permissions: { some: { permission: { name: "projects.admin" } } } },
|
||||
},
|
||||
select: { userId: true },
|
||||
});
|
||||
const userIds = [...new Set(admins.map((row) => row.userId))];
|
||||
await Promise.all(
|
||||
userIds.map((userId) =>
|
||||
notify(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
userId,
|
||||
channel: "IN_APP",
|
||||
category: "projects",
|
||||
messageKey: "projects.notification.pipelineAccessRequested",
|
||||
sourceKey: `pipeline-access-request:${input.requestId}`,
|
||||
payloadMetadata: {
|
||||
pipelineId: input.pipelineId,
|
||||
pipelineName: input.pipelineName,
|
||||
requesterUserId: input.requesterUserId,
|
||||
},
|
||||
},
|
||||
tx as unknown as Parameters<typeof notify>[1]
|
||||
)
|
||||
)
|
||||
);
|
||||
} catch {
|
||||
// Notification failures must not lose the access request.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Files an access request for a pipeline the viewer is locked out of.
|
||||
* 404-semantics: a pipeline that does not exist, is archived or is NOT locked
|
||||
* for this viewer answers with the catalog notFound error (a locked-out
|
||||
* viewer must not be able to probe which pipelines exist). Idempotent: an
|
||||
* existing open request by the same user is returned instead of duplicated.
|
||||
*/
|
||||
export async function requestPipelineAccess({
|
||||
tenantId,
|
||||
pipelineId,
|
||||
userId,
|
||||
ctx,
|
||||
}: {
|
||||
tenantId: string;
|
||||
pipelineId: string;
|
||||
userId: string;
|
||||
ctx: ProjectRouteContext;
|
||||
}): Promise<{ request: PipelineAccessRequestRow; created: boolean }> {
|
||||
const result = await withTenantRLS(tenantId, async (tx) => {
|
||||
const pipeline = await tx.pipeline.findFirst({
|
||||
where: {
|
||||
tenantId,
|
||||
id: pipelineId,
|
||||
archivedAt: null,
|
||||
...lockedPipelineScopeWhere(tenantId, ctx),
|
||||
},
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (!pipeline) {
|
||||
throw new CatalogError(foundationErrors.notFound, { pipelineId });
|
||||
}
|
||||
const existing = await tx.pipelineAccessRequest.findFirst({
|
||||
where: { tenantId, pipelineId, requestedByUserId: userId, status: "open" },
|
||||
});
|
||||
if (existing) {
|
||||
return { request: existing as PipelineAccessRequestRow, created: false, pipelineName: pipeline.name };
|
||||
}
|
||||
const request = await tx.pipelineAccessRequest.create({
|
||||
data: { tenantId, pipelineId, requestedByUserId: userId },
|
||||
});
|
||||
await notifyProjectsAdmins(tx, {
|
||||
tenantId,
|
||||
requestId: request.id,
|
||||
pipelineId,
|
||||
pipelineName: pipeline.name,
|
||||
requesterUserId: userId,
|
||||
});
|
||||
return { request: request as PipelineAccessRequestRow, created: true, pipelineName: pipeline.name };
|
||||
});
|
||||
if (result.created) {
|
||||
// Best-effort audit (M001) — same pattern as auditCrmEvent: the audit
|
||||
// writer manages its own client/chain, failure never breaks the request.
|
||||
try {
|
||||
await createAuditEvent({
|
||||
tenantId,
|
||||
actorId: userId,
|
||||
actorType: "user",
|
||||
action: "pipeline.access_requested",
|
||||
targetType: "pipeline",
|
||||
targetId: pipelineId,
|
||||
metadata: { requestId: result.request.id, pipelineName: result.pipelineName },
|
||||
});
|
||||
} catch {
|
||||
// Audit must never break the user action; the failure is logged upstream.
|
||||
}
|
||||
}
|
||||
return { request: result.request, created: result.created };
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks all open access requests of a user for a pipeline as approved or
|
||||
* dismissed. Called best-effort from the pipeline admin action after a
|
||||
* user-scoped PipelineAccess rule with kannSehen=true was upserted.
|
||||
*/
|
||||
export async function resolveOpenAccessRequests({
|
||||
tenantId,
|
||||
pipelineId,
|
||||
userId,
|
||||
resolvedByUserId,
|
||||
status,
|
||||
}: {
|
||||
tenantId: string;
|
||||
pipelineId: string;
|
||||
userId: string;
|
||||
resolvedByUserId: string;
|
||||
status: PipelineAccessRequestResolution;
|
||||
}): Promise<number> {
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
const result = await tx.pipelineAccessRequest.updateMany({
|
||||
where: { tenantId, pipelineId, requestedByUserId: userId, status: "open" },
|
||||
data: { status, resolvedAt: new Date(), resolvedByUserId },
|
||||
});
|
||||
return result.count;
|
||||
});
|
||||
}
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
// WF-P8 board admin write path. Shared by the S07 board table
|
||||
// (admin.pipelines._index) and the S04 board settings
|
||||
// (admin.pipelines.$pipelineId._index): both screens mutate the same boards,
|
||||
// columns, access rules and field configs, so they must not grow two copies of
|
||||
// the intent handling that can drift apart.
|
||||
//
|
||||
// Every handler is keyed by the ids in the form data and re-checks
|
||||
// `projects.admin` through the caller's context, so a route cannot widen the
|
||||
// permission by forwarding here.
|
||||
|
||||
import { upsertAuftragPipelineStageConfig } from "~/utils/integrations/projects/auftragService.server";
|
||||
import { resolveOpenAccessRequests } from "~/utils/integrations/projects/pipelineAccessRequest.server";
|
||||
import { projectActionErrorResponse } from "~/utils/integrations/projects/projectAccess.server";
|
||||
import {
|
||||
archivePipeline,
|
||||
archivePipelineStage,
|
||||
createPipeline,
|
||||
duplicatePipeline,
|
||||
reorderPipelineStages,
|
||||
updatePipeline,
|
||||
upsertPipelineAccess,
|
||||
upsertPipelineFieldConfig,
|
||||
upsertPipelineFieldVisibility,
|
||||
upsertPipelineStage,
|
||||
type CreatePipelineStageInput,
|
||||
type PipelinePrincipalType,
|
||||
type PipelineStageKind,
|
||||
type PipelineTypHint,
|
||||
} from "~/utils/integrations/projects/projectService.server";
|
||||
|
||||
export function formString(formData: FormData, name: string): string | null {
|
||||
const value = formData.get(name);
|
||||
return typeof value === "string" ? value : null;
|
||||
}
|
||||
|
||||
export function formBoolean(formData: FormData, name: string): boolean | undefined {
|
||||
const value = formString(formData, name);
|
||||
if (value === null) return undefined;
|
||||
return value === "true" || value === "1" || value === "on";
|
||||
}
|
||||
|
||||
export function formNumber(formData: FormData, name: string): number | undefined {
|
||||
const value = formString(formData, name);
|
||||
if (!value) return undefined;
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : undefined;
|
||||
}
|
||||
|
||||
function formStages(formData: FormData): CreatePipelineStageInput[] {
|
||||
const raw = formString(formData, "stages");
|
||||
if (!raw) return [];
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.filter((stage): stage is CreatePipelineStageInput => typeof stage === "object" && stage !== null && "name" in stage && "stageKind" in stage);
|
||||
}
|
||||
|
||||
function formStageIds(formData: FormData): string[] {
|
||||
const raw = formString(formData, "stageIds");
|
||||
if (!raw) return [];
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.filter((id): id is string => typeof id === "string");
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs one board-admin intent. Returns the Response the route hands back, so an
|
||||
* unknown intent stays a 400 here instead of silently succeeding.
|
||||
*/
|
||||
export async function handlePipelineAdminAction(input: {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
formData: FormData;
|
||||
}): Promise<Response> {
|
||||
const { tenantId, userId, formData } = input;
|
||||
const intent = formString(formData, "_action");
|
||||
const success = (messageKey: string, payload: Record<string, unknown> = {}) => Response.json({ ok: true, intent, messageKey, ...payload });
|
||||
try {
|
||||
if (intent === "createPipeline") {
|
||||
const pipeline = await createPipeline({
|
||||
tenantId,
|
||||
userId,
|
||||
name: formString(formData, "name") ?? "",
|
||||
typHint: (formString(formData, "typHint") as PipelineTypHint | null) ?? "custom",
|
||||
position: formNumber(formData, "position"),
|
||||
stages: formStages(formData),
|
||||
});
|
||||
return success("projects.toast.pipelineCreated", { pipeline });
|
||||
}
|
||||
if (intent === "updatePipeline") {
|
||||
const pipeline = await updatePipeline({
|
||||
tenantId,
|
||||
pipelineId: formString(formData, "pipelineId") ?? "",
|
||||
name: formString(formData, "name"),
|
||||
position: formNumber(formData, "position"),
|
||||
typHint: formString(formData, "typHint") as PipelineTypHint | null,
|
||||
// Only forward the successor when the form actually carried the field,
|
||||
// so the rename form does not silently clear it.
|
||||
...(formData.has("nachfolgePipelineId") ? { nachfolgePipelineId: formString(formData, "nachfolgePipelineId") } : {}),
|
||||
});
|
||||
return success("projects.toast.pipelineSaved", { pipeline });
|
||||
}
|
||||
if (intent === "archivePipeline") {
|
||||
const pipeline = await archivePipeline({ tenantId, pipelineId: formString(formData, "pipelineId") ?? "" });
|
||||
return success("projects.toast.pipelineArchived", { pipeline });
|
||||
}
|
||||
if (intent === "duplicatePipeline") {
|
||||
const pipeline = await duplicatePipeline({
|
||||
tenantId,
|
||||
userId,
|
||||
pipelineId: formString(formData, "pipelineId") ?? "",
|
||||
name: formString(formData, "name") ?? "",
|
||||
});
|
||||
return success("projects.toast.pipelineDuplicated", { pipeline });
|
||||
}
|
||||
if (intent === "upsertStage") {
|
||||
await upsertPipelineStage({
|
||||
tenantId,
|
||||
pipelineId: formString(formData, "pipelineId") ?? "",
|
||||
stageId: formString(formData, "stageId"),
|
||||
name: formString(formData, "name") ?? "",
|
||||
stageKind: (formString(formData, "stageKind") as PipelineStageKind | null) ?? "offen",
|
||||
winProbability: formNumber(formData, "winProbability"),
|
||||
color: formString(formData, "color") ?? undefined,
|
||||
position: formNumber(formData, "position"),
|
||||
});
|
||||
return success("projects.toast.pipelineStageSaved");
|
||||
}
|
||||
if (intent === "archiveStage") {
|
||||
await archivePipelineStage({ tenantId, stageId: formString(formData, "stageId") ?? "" });
|
||||
return success("projects.toast.pipelineStageArchived");
|
||||
}
|
||||
if (intent === "reorderStages") {
|
||||
await reorderPipelineStages({
|
||||
tenantId,
|
||||
pipelineId: formString(formData, "pipelineId") ?? "",
|
||||
stageIds: formStageIds(formData),
|
||||
});
|
||||
return success("projects.toast.pipelineStagesReordered");
|
||||
}
|
||||
if (intent === "upsertAccess") {
|
||||
const pipelineId = formString(formData, "pipelineId") ?? "";
|
||||
const principalType = formString(formData, "principalType") as PipelinePrincipalType;
|
||||
const principalId = formString(formData, "principalId") ?? "";
|
||||
const kannSehen = formBoolean(formData, "kannSehen");
|
||||
await upsertPipelineAccess({
|
||||
tenantId,
|
||||
pipelineId,
|
||||
principalType,
|
||||
principalId,
|
||||
kannSehen,
|
||||
kannBearbeiten: formBoolean(formData, "kannBearbeiten"),
|
||||
});
|
||||
if (principalType === "user" && kannSehen === true && principalId) {
|
||||
// Granting a user visibility approves that user's open access
|
||||
// requests for this pipeline (best-effort: the grant already stands).
|
||||
try {
|
||||
await resolveOpenAccessRequests({
|
||||
tenantId,
|
||||
pipelineId,
|
||||
userId: principalId,
|
||||
resolvedByUserId: userId,
|
||||
status: "approved",
|
||||
});
|
||||
} catch {
|
||||
// Best-effort: an unresolved request marker never blocks the grant.
|
||||
}
|
||||
}
|
||||
return success("projects.toast.pipelineAccessSaved");
|
||||
}
|
||||
if (intent === "upsertFieldConfig") {
|
||||
await upsertPipelineFieldConfig({
|
||||
tenantId,
|
||||
pipelineId: formString(formData, "pipelineId") ?? "",
|
||||
stageId: formString(formData, "stageId"),
|
||||
fieldKey: formString(formData, "fieldKey") ?? "",
|
||||
sichtbar: formBoolean(formData, "sichtbar"),
|
||||
pflicht: formBoolean(formData, "pflicht"),
|
||||
reihenfolge: formNumber(formData, "reihenfolge"),
|
||||
});
|
||||
return success("projects.toast.pipelineFieldConfigSaved");
|
||||
}
|
||||
if (intent === "upsertFieldVisibility") {
|
||||
await upsertPipelineFieldVisibility({
|
||||
tenantId,
|
||||
fieldConfigId: formString(formData, "fieldConfigId") ?? "",
|
||||
principalType: formString(formData, "principalType") as PipelinePrincipalType,
|
||||
principalId: formString(formData, "principalId") ?? "",
|
||||
kannSehen: formBoolean(formData, "kannSehen"),
|
||||
kannBearbeiten: formBoolean(formData, "kannBearbeiten"),
|
||||
});
|
||||
return success("projects.toast.pipelineFieldVisibilitySaved");
|
||||
}
|
||||
if (intent === "upsertAuftragStageConfig") {
|
||||
await upsertAuftragPipelineStageConfig({
|
||||
tenantId,
|
||||
pipelineId: formString(formData, "pipelineId") ?? "",
|
||||
stageId: formString(formData, "stageId") ?? "",
|
||||
requiresAcceptanceProtocol: formBoolean(formData, "requiresAcceptanceProtocol"),
|
||||
acceptanceFormTemplateId: formString(formData, "acceptanceFormTemplateId"),
|
||||
autoArchiveAfterDays: formNumber(formData, "autoArchiveAfterDays") ?? null,
|
||||
});
|
||||
return success("projects.toast.pipelineAcceptanceRuleSaved");
|
||||
}
|
||||
return Response.json({ error: "projects.error.unsupportedAction" }, { status: 400 });
|
||||
} catch (error) {
|
||||
return projectActionErrorResponse(error);
|
||||
}
|
||||
}
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
// WF-P8 S05 (Detail-Schablone Edit-Mode) + M05 (Modal Bestandsfeld) — the
|
||||
// project detail template of a pipeline: which field sits in which section, in
|
||||
// which order, and when it becomes mandatory.
|
||||
//
|
||||
// Two invariants from the screen, enforced here rather than in the UI:
|
||||
// - system fields may be reordered, locked, or moved back into the pool, but
|
||||
// never deleted (`istSystem`);
|
||||
// - projektname, status and prioritaet are always visible and can neither be
|
||||
// hidden nor unfiled (`ALWAYS_VISIBLE_FIELD_KEYS`).
|
||||
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
|
||||
export class PipelineFieldTemplateError extends Error {
|
||||
readonly messageKey: string;
|
||||
constructor(messageKey: string) {
|
||||
super(messageKey);
|
||||
this.name = "PipelineFieldTemplateError";
|
||||
this.messageKey = messageKey;
|
||||
}
|
||||
}
|
||||
|
||||
/** Always-visible fields per S05 ("Projektname, Status und Priorität bleiben immer sichtbar"). */
|
||||
export const ALWAYS_VISIBLE_FIELD_KEYS: readonly string[] = ["projektname", "status", "prioritaet"];
|
||||
|
||||
/**
|
||||
* Fixed system info rendered outside the configurable template ("Projekt-ID,
|
||||
* Erstellt und Board-Spalte sind feste Systeminfos außerhalb dieser
|
||||
* Konfiguration"). Listed so the UI can render them read-only and the service
|
||||
* can reject attempts to file them into a group.
|
||||
*/
|
||||
export const FIXED_SYSTEM_FIELD_KEYS: readonly string[] = ["projektNummer", "createdAt", "boardColumn"];
|
||||
|
||||
export type FieldGroupRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
reihenfolge: number;
|
||||
istSystem: boolean;
|
||||
};
|
||||
|
||||
export type TemplateFieldRow = {
|
||||
id: string;
|
||||
fieldKey: string;
|
||||
groupId: string | null;
|
||||
sichtbar: boolean;
|
||||
pflicht: boolean;
|
||||
pflichtAbStageId: string | null;
|
||||
hinweis: string | null;
|
||||
istSystem: boolean;
|
||||
gesperrt: boolean;
|
||||
reihenfolge: number;
|
||||
};
|
||||
|
||||
export type PipelineFieldTemplate = {
|
||||
pipelineId: string;
|
||||
pipelineName: string;
|
||||
groups: FieldGroupRow[];
|
||||
/** Fields filed into a group, ordered by group then position. */
|
||||
fields: TemplateFieldRow[];
|
||||
/** "Bestandsfelder außerhalb der Schablone" — configured but unfiled. */
|
||||
poolFields: TemplateFieldRow[];
|
||||
/** Stages offered by "Pflicht ab Board-Spalte". */
|
||||
stages: { id: string; name: string; position: number }[];
|
||||
};
|
||||
|
||||
function normalizeText(value?: string | null): string | null {
|
||||
const normalized = value?.trim();
|
||||
return normalized || null;
|
||||
}
|
||||
|
||||
async function assertPipelineWithTx(tx: TenantRlsClient, tenantId: string, pipelineId: string) {
|
||||
const pipeline = await tx.pipeline.findFirst({
|
||||
where: { id: pipelineId, tenantId, archivedAt: null },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (!pipeline) throw new CatalogError(foundationErrors.notFound, { pipelineId });
|
||||
return pipeline;
|
||||
}
|
||||
|
||||
export async function loadPipelineFieldTemplate(input: { tenantId: string; pipelineId: string }): Promise<PipelineFieldTemplate> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const pipeline = await assertPipelineWithTx(tx, input.tenantId, input.pipelineId);
|
||||
const [groups, configs, stages] = await Promise.all([
|
||||
tx.pipelineFieldGroup.findMany({
|
||||
where: { tenantId: input.tenantId, pipelineId: input.pipelineId },
|
||||
orderBy: { reihenfolge: "asc" },
|
||||
}),
|
||||
// The template is the pipeline-wide layer (`stageId: null`); per-stage
|
||||
// overrides stay the concern of the pipeline admin screen.
|
||||
tx.pipelineFieldConfig.findMany({
|
||||
where: { tenantId: input.tenantId, pipelineId: input.pipelineId, stageId: null },
|
||||
orderBy: { reihenfolge: "asc" },
|
||||
}),
|
||||
tx.pipelineStage.findMany({
|
||||
where: { tenantId: input.tenantId, pipelineId: input.pipelineId, archivedAt: null },
|
||||
orderBy: { position: "asc" },
|
||||
select: { id: true, name: true, position: true },
|
||||
}),
|
||||
]);
|
||||
const toRow = (config: (typeof configs)[number]): TemplateFieldRow => ({
|
||||
id: config.id,
|
||||
fieldKey: config.fieldKey,
|
||||
groupId: config.groupId,
|
||||
sichtbar: config.sichtbar,
|
||||
pflicht: config.pflicht,
|
||||
pflichtAbStageId: config.pflichtAbStageId,
|
||||
hinweis: config.hinweis,
|
||||
istSystem: config.istSystem,
|
||||
gesperrt: config.gesperrt,
|
||||
reihenfolge: config.reihenfolge,
|
||||
});
|
||||
return {
|
||||
pipelineId: pipeline.id,
|
||||
pipelineName: pipeline.name,
|
||||
groups: groups.map((group) => ({ id: group.id, name: group.name, reihenfolge: group.reihenfolge, istSystem: group.istSystem })),
|
||||
fields: configs.filter((config) => config.groupId).map(toRow),
|
||||
poolFields: configs.filter((config) => !config.groupId).map(toRow),
|
||||
stages,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function createFieldGroup(input: { tenantId: string; pipelineId: string; name: string }): Promise<FieldGroupRow> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const name = normalizeText(input.name);
|
||||
if (!name) throw new PipelineFieldTemplateError("projects.error.fieldGroupNameRequired");
|
||||
await assertPipelineWithTx(tx, input.tenantId, input.pipelineId);
|
||||
const duplicate = await tx.pipelineFieldGroup.findFirst({
|
||||
where: { pipelineId: input.pipelineId, name },
|
||||
select: { id: true },
|
||||
});
|
||||
if (duplicate) throw new PipelineFieldTemplateError("projects.error.fieldGroupNameTaken");
|
||||
const last = await tx.pipelineFieldGroup.findFirst({
|
||||
where: { tenantId: input.tenantId, pipelineId: input.pipelineId },
|
||||
orderBy: { reihenfolge: "desc" },
|
||||
select: { reihenfolge: true },
|
||||
});
|
||||
const group = await tx.pipelineFieldGroup.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
pipelineId: input.pipelineId,
|
||||
name,
|
||||
reihenfolge: (last?.reihenfolge ?? -1) + 1,
|
||||
},
|
||||
});
|
||||
return { id: group.id, name: group.name, reihenfolge: group.reihenfolge, istSystem: group.istSystem };
|
||||
});
|
||||
}
|
||||
|
||||
export async function renameFieldGroup(input: { tenantId: string; pipelineId: string; groupId: string; name: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const name = normalizeText(input.name);
|
||||
if (!name) throw new PipelineFieldTemplateError("projects.error.fieldGroupNameRequired");
|
||||
const group = await tx.pipelineFieldGroup.findFirst({
|
||||
where: { id: input.groupId, tenantId: input.tenantId, pipelineId: input.pipelineId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!group) throw new CatalogError(foundationErrors.notFound, { groupId: input.groupId });
|
||||
const duplicate = await tx.pipelineFieldGroup.findFirst({
|
||||
where: { pipelineId: input.pipelineId, name, NOT: { id: group.id } },
|
||||
select: { id: true },
|
||||
});
|
||||
if (duplicate) throw new PipelineFieldTemplateError("projects.error.fieldGroupNameTaken");
|
||||
await tx.pipelineFieldGroup.update({ where: { id: group.id }, data: { name } });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a group. System groups stay. Its fields are not deleted — they fall
|
||||
* back into the "Bestandsfelder" pool (`groupId: null` via the FK's SET NULL).
|
||||
*/
|
||||
export async function deleteFieldGroup(input: { tenantId: string; pipelineId: string; groupId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const group = await tx.pipelineFieldGroup.findFirst({
|
||||
where: { id: input.groupId, tenantId: input.tenantId, pipelineId: input.pipelineId },
|
||||
select: { id: true, istSystem: true },
|
||||
});
|
||||
if (!group) throw new CatalogError(foundationErrors.notFound, { groupId: input.groupId });
|
||||
if (group.istSystem) throw new PipelineFieldTemplateError("projects.error.fieldGroupSystemUndeletable");
|
||||
await tx.pipelineFieldGroup.delete({ where: { id: group.id } });
|
||||
});
|
||||
}
|
||||
|
||||
export async function reorderFieldGroups(input: { tenantId: string; pipelineId: string; orderedGroupIds: readonly string[] }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const groups = await tx.pipelineFieldGroup.findMany({
|
||||
where: { tenantId: input.tenantId, pipelineId: input.pipelineId },
|
||||
select: { id: true },
|
||||
});
|
||||
const known = new Set(groups.map((group) => group.id));
|
||||
// Reject a partial order outright: silently appending the missing groups
|
||||
// would scramble a layout the user never touched.
|
||||
if (input.orderedGroupIds.length !== known.size || input.orderedGroupIds.some((id) => !known.has(id))) {
|
||||
throw new PipelineFieldTemplateError("projects.error.fieldGroupOrderIncomplete");
|
||||
}
|
||||
for (const [index, groupId] of input.orderedGroupIds.entries()) {
|
||||
await tx.pipelineFieldGroup.update({ where: { id: groupId }, data: { reihenfolge: index } });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a field into a group (or back into the pool with `groupId: null`) and
|
||||
* set its position within that group. This is the drag-and-drop write path of S05.
|
||||
*/
|
||||
export async function moveFieldToGroup(input: {
|
||||
tenantId: string;
|
||||
pipelineId: string;
|
||||
fieldConfigId: string;
|
||||
groupId: string | null;
|
||||
reihenfolge: number;
|
||||
}): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const config = await tx.pipelineFieldConfig.findFirst({
|
||||
where: { id: input.fieldConfigId, tenantId: input.tenantId, pipelineId: input.pipelineId, stageId: null },
|
||||
select: { id: true, fieldKey: true },
|
||||
});
|
||||
if (!config) throw new CatalogError(foundationErrors.notFound, { fieldConfigId: input.fieldConfigId });
|
||||
if (FIXED_SYSTEM_FIELD_KEYS.includes(config.fieldKey)) {
|
||||
throw new PipelineFieldTemplateError("projects.error.fieldFixedSystemInfo");
|
||||
}
|
||||
if (input.groupId === null && ALWAYS_VISIBLE_FIELD_KEYS.includes(config.fieldKey)) {
|
||||
throw new PipelineFieldTemplateError("projects.error.fieldAlwaysVisible");
|
||||
}
|
||||
if (input.groupId) {
|
||||
const group = await tx.pipelineFieldGroup.findFirst({
|
||||
where: { id: input.groupId, tenantId: input.tenantId, pipelineId: input.pipelineId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!group) throw new CatalogError(foundationErrors.notFound, { groupId: input.groupId });
|
||||
}
|
||||
await tx.pipelineFieldConfig.update({
|
||||
where: { id: config.id },
|
||||
data: { groupId: input.groupId, reihenfolge: input.reihenfolge },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Permanently remove a non-system custom field from the template ("Kopieren und
|
||||
* dauerhaftes Löschen mit Datenverlust-Hinweis"). System fields are refused.
|
||||
*/
|
||||
export async function deleteTemplateField(input: { tenantId: string; pipelineId: string; fieldConfigId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const config = await tx.pipelineFieldConfig.findFirst({
|
||||
where: { id: input.fieldConfigId, tenantId: input.tenantId, pipelineId: input.pipelineId, stageId: null },
|
||||
select: { id: true, istSystem: true, fieldKey: true },
|
||||
});
|
||||
if (!config) throw new CatalogError(foundationErrors.notFound, { fieldConfigId: input.fieldConfigId });
|
||||
if (config.istSystem || ALWAYS_VISIBLE_FIELD_KEYS.includes(config.fieldKey)) {
|
||||
throw new PipelineFieldTemplateError("projects.error.fieldSystemUndeletable");
|
||||
}
|
||||
await tx.pipelineFieldConfig.delete({ where: { id: config.id } });
|
||||
});
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
// WF-P8 M04 — route-side assembly of the handover dialog's view-model.
|
||||
//
|
||||
// Two screens reach the same state: the board (S01, right after a card lands in
|
||||
// the final stage) and the detail page (S02, when the project is already
|
||||
// sitting there). Both need the identical answer to "is a handover pending, and
|
||||
// what does it contain", so the permission gate, the preview load and the name
|
||||
// resolution live here once instead of in two route files that could drift.
|
||||
|
||||
import { buildPipelineHandoverVM, type PipelineHandoverVM } from "@hivegrid/view-models";
|
||||
import { resolveUserLabels } from "~/utils/integrations/crm/crmService.server";
|
||||
import { loadPendingHandover } from "./pipelineHandoverService.server";
|
||||
import { toProjektNotizContext } from "./projektNotizService.server";
|
||||
import type { ProjectRouteContext } from "./projectAccess.server";
|
||||
|
||||
/**
|
||||
* The M04 payload for a project, or null when no handover is pending — which is
|
||||
* the normal case and never an error: without the permission, without a
|
||||
* successor board, or anywhere but the final stage there is simply nothing to
|
||||
* offer.
|
||||
*/
|
||||
export async function loadHandoverVM(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
ctx: ProjectRouteContext;
|
||||
}): Promise<PipelineHandoverVM | null> {
|
||||
if (!input.ctx.permissions.includes("projects.handover")) return null;
|
||||
const pending = await loadPendingHandover({
|
||||
tenantId: input.tenantId,
|
||||
projectId: input.projectId,
|
||||
ctx: toProjektNotizContext(input.ctx),
|
||||
});
|
||||
if (!pending) return null;
|
||||
// The preview carries raw author/assignee ids. Resolve exactly those — the
|
||||
// view-model drops what it cannot name rather than print a cuid at a user.
|
||||
const labels = await resolveUserLabels(pending.candidates.map((candidate) => candidate.personId).filter((id): id is string => Boolean(id)));
|
||||
return buildPipelineHandoverVM({ ...pending, userLabels: Object.fromEntries(labels) });
|
||||
}
|
||||
+449
@@ -0,0 +1,449 @@
|
||||
// WF-P8 M04 (Pipeline-Uebergabe) — hand a project into its successor pipeline
|
||||
// together with the companion data the salesperson explicitly picked.
|
||||
//
|
||||
// Trigger (validated with David, see the D-P8 handoff): M04 is NOT a button.
|
||||
// Moving a project into the final stage of its pipeline opens the dialog; only
|
||||
// "Auswahl uebernehmen" runs `executeProjectHandover`.
|
||||
//
|
||||
// AD-20 shape: there is ONE `Projekt` row. The handover re-points
|
||||
// `pipelineId`/`stageId` at the successor pipeline — it never copies the
|
||||
// project. The picked notes/files/tasks/appointments are recorded as the
|
||||
// handover PACKAGE (what the next team is explicitly handed); unpicked
|
||||
// companion data stays on the project untouched. Nothing is deleted here.
|
||||
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
import { projectEditScopeWhere, type ProjectVisibilityContext } from "./projectService.server";
|
||||
import { noteReadScopeWhere, type ProjektNotizContext } from "./projektNotizService.server";
|
||||
|
||||
export class PipelineHandoverServiceError extends Error {
|
||||
readonly messageKey: string;
|
||||
constructor(messageKey: string) {
|
||||
super(messageKey);
|
||||
this.name = "PipelineHandoverServiceError";
|
||||
this.messageKey = messageKey;
|
||||
}
|
||||
}
|
||||
|
||||
export type HandoverItemKind = "notiz" | "datei" | "aufgabe" | "termin";
|
||||
|
||||
export const HANDOVER_ITEM_KINDS: readonly HandoverItemKind[] = ["notiz", "datei", "aufgabe", "termin"];
|
||||
|
||||
export function isHandoverItemKind(value: string): value is HandoverItemKind {
|
||||
return (HANDOVER_ITEM_KINDS as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* M04 posts its selection as a JSON array so one form field carries the whole
|
||||
* pick. Unknown kinds and malformed payloads are dropped rather than failing
|
||||
* the handover: the selection is additive metadata, not the move itself.
|
||||
*
|
||||
* Shared by both callers — the detail page and the board — so a payload that
|
||||
* one accepts can never be one the other silently rejects.
|
||||
*/
|
||||
export function parseHandoverSelection(raw: string | null): { kind: HandoverItemKind; sourceId: string }[] {
|
||||
if (!raw) return [];
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.flatMap((entry) => {
|
||||
if (typeof entry !== "object" || entry === null) return [];
|
||||
const kind = (entry as { kind?: unknown }).kind;
|
||||
const sourceId = (entry as { sourceId?: unknown }).sourceId;
|
||||
if (typeof kind !== "string" || typeof sourceId !== "string" || !sourceId || !isHandoverItemKind(kind)) return [];
|
||||
return [{ kind, sourceId }];
|
||||
});
|
||||
}
|
||||
|
||||
export type HandoverCandidate = {
|
||||
id: string;
|
||||
kind: HandoverItemKind;
|
||||
/** Primary line (note headline, file name, task/appointment title). */
|
||||
title: string;
|
||||
/** Secondary line, where the record has one of its own (note body, description). */
|
||||
body: string | null;
|
||||
/** Raw user id — the view-model resolves it against a name directory. */
|
||||
personId: string | null;
|
||||
/** ISO timestamp used for ordering and for the "12.07. um 10:30 Uhr" style rendering. */
|
||||
atIso: string | null;
|
||||
/** Preselected in the dialog. */
|
||||
defaultSelected: boolean;
|
||||
/** datei */
|
||||
fileExtension?: string | null;
|
||||
fileRole?: string | null;
|
||||
fileSizeBytes?: number | null;
|
||||
/** aufgabe */
|
||||
taskStatus?: string | null;
|
||||
taskPriority?: string | null;
|
||||
deadlineIso?: string | null;
|
||||
/** termin */
|
||||
appointmentType?: string | null;
|
||||
};
|
||||
|
||||
export type HandoverPreview = {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
fromPipelineId: string;
|
||||
fromPipelineName: string;
|
||||
toPipelineId: string;
|
||||
toPipelineName: string;
|
||||
/** Entry stage in the successor pipeline (its lowest-position open stage). */
|
||||
toStageId: string;
|
||||
toStageName: string;
|
||||
candidates: HandoverCandidate[];
|
||||
};
|
||||
|
||||
function excerpt(value: string, max = 120): string {
|
||||
const collapsed = value.replace(/\s+/g, " ").trim();
|
||||
return collapsed.length <= max ? collapsed : `${collapsed.slice(0, max - 1)}…`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A note is one text column, but M04 draws a headline plus a body. Split on the
|
||||
* first line break: what a user typed as the opening line IS the headline. A
|
||||
* one-line note keeps its body empty instead of repeating itself.
|
||||
*/
|
||||
function splitNote(inhalt: string): { title: string; body: string | null } {
|
||||
const [first, ...rest] = inhalt.split(/\r?\n/);
|
||||
const body = rest.join(" ").trim();
|
||||
return { title: excerpt(first ?? "", 80), body: body ? excerpt(body) : null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Badge text of a file row. The extension is what a user recognises ("PDF"),
|
||||
* so it wins over the mime type; a file without one falls back to the mime
|
||||
* subtype rather than showing an empty badge.
|
||||
*/
|
||||
function fileExtensionLabel(displayName: string, mimeType: string): string {
|
||||
const dot = displayName.lastIndexOf(".");
|
||||
const extension = dot > 0 ? displayName.slice(dot + 1) : "";
|
||||
if (extension && extension.length <= 5) return extension.toUpperCase();
|
||||
const subtype = mimeType.split("/")[1] ?? mimeType;
|
||||
return subtype.toUpperCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Entry stage of the successor pipeline: lowest-position stage with
|
||||
* `stageKind: "offen"`. A pipeline without an open stage cannot receive a
|
||||
* handover — `validatePipelineStages` does not guarantee one exists.
|
||||
*/
|
||||
async function resolveEntryStageWithTx(tx: TenantRlsClient, input: { tenantId: string; pipelineId: string }) {
|
||||
const stage = await tx.pipelineStage.findFirst({
|
||||
where: { tenantId: input.tenantId, pipelineId: input.pipelineId, stageKind: "offen", archivedAt: null },
|
||||
orderBy: { position: "asc" },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (!stage) throw new PipelineHandoverServiceError("projects.error.handoverTargetHasNoOpenStage");
|
||||
return stage;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when moving `targetStageId` should open M04: the stage is the terminal
|
||||
* one of its pipeline (highest position, or a `gewonnen` stage) AND the
|
||||
* pipeline declares a successor. Callers use this to decide whether to render
|
||||
* the dialog after a stage move.
|
||||
*/
|
||||
export async function shouldOpenHandoverWithTx(
|
||||
tx: TenantRlsClient,
|
||||
input: { tenantId: string; pipelineId: string; targetStageId: string }
|
||||
): Promise<boolean> {
|
||||
const pipeline = await tx.pipeline.findFirst({
|
||||
where: { id: input.pipelineId, tenantId: input.tenantId, archivedAt: null },
|
||||
select: { nachfolgePipelineId: true },
|
||||
});
|
||||
if (!pipeline?.nachfolgePipelineId) return false;
|
||||
const stage = await tx.pipelineStage.findFirst({
|
||||
where: { id: input.targetStageId, tenantId: input.tenantId, pipelineId: input.pipelineId, archivedAt: null },
|
||||
select: { id: true, stageKind: true, position: true },
|
||||
});
|
||||
if (!stage) return false;
|
||||
if (stage.stageKind === "verloren") return false;
|
||||
if (stage.stageKind === "gewonnen") return true;
|
||||
const last = await tx.pipelineStage.findFirst({
|
||||
where: { tenantId: input.tenantId, pipelineId: input.pipelineId, archivedAt: null, stageKind: { not: "verloren" } },
|
||||
orderBy: { position: "desc" },
|
||||
select: { id: true },
|
||||
});
|
||||
return last?.id === stage.id;
|
||||
}
|
||||
|
||||
/** Everything M04 needs to render: the target pipeline plus the pickable companion data. */
|
||||
export async function loadHandoverPreview(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
ctx: ProjektNotizContext;
|
||||
}): Promise<HandoverPreview> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const project = await tx.projekt.findFirst({
|
||||
where: {
|
||||
id: input.projectId,
|
||||
tenantId: input.tenantId,
|
||||
archivedAt: null,
|
||||
...projectEditScopeWhere(input.tenantId, input.ctx),
|
||||
},
|
||||
include: { pipeline: true },
|
||||
});
|
||||
if (!project) throw new CatalogError(foundationErrors.notFound, { projectId: input.projectId });
|
||||
const successorId = project.pipeline.nachfolgePipelineId;
|
||||
if (!successorId) throw new PipelineHandoverServiceError("projects.error.handoverNoSuccessor");
|
||||
const successor = await tx.pipeline.findFirst({
|
||||
where: { id: successorId, tenantId: input.tenantId, archivedAt: null },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (!successor) throw new PipelineHandoverServiceError("projects.error.handoverNoSuccessor");
|
||||
const entryStage = await resolveEntryStageWithTx(tx, { tenantId: input.tenantId, pipelineId: successor.id });
|
||||
|
||||
// Notes honour the S02-N reader gate — a "nur ich" note of a different user
|
||||
// must not become pickable here.
|
||||
const [notes, fileLinks, tasks, appointments] = await Promise.all([
|
||||
tx.projektNotiz.findMany({
|
||||
where: { tenantId: input.tenantId, projektId: project.id, archivedAt: null, ...noteReadScopeWhere(input.ctx) },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 50,
|
||||
}),
|
||||
tx.fileEntityLink.findMany({
|
||||
where: { tenantId: input.tenantId, entityType: "project", entityId: project.id },
|
||||
include: { file: { select: { id: true, displayName: true, mimeType: true, sizeBytes: true, createdAt: true, archivedAt: true } } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 50,
|
||||
}),
|
||||
// Tasks attach polymorphically, not through a `projektId` column.
|
||||
tx.task.findMany({
|
||||
where: { tenantId: input.tenantId, linkedEntityType: "project", linkedEntityId: project.id, archivedAt: null },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 50,
|
||||
}),
|
||||
tx.projektTermin.findMany({
|
||||
where: { tenantId: input.tenantId, projektId: project.id, archivedAt: null },
|
||||
orderBy: { startAt: "asc" },
|
||||
take: 50,
|
||||
}),
|
||||
]);
|
||||
|
||||
const candidates: HandoverCandidate[] = [
|
||||
...notes.map((note) => ({
|
||||
id: note.id,
|
||||
kind: "notiz" as const,
|
||||
...splitNote(note.inhalt),
|
||||
personId: note.autorUserId,
|
||||
atIso: note.createdAt.toISOString(),
|
||||
// Everything is preselected: the dialog is a "deselect what must not
|
||||
// travel" step, which matches the counts shown in Davids screens.
|
||||
defaultSelected: true,
|
||||
})),
|
||||
...fileLinks
|
||||
.filter((link) => link.file && !link.file.archivedAt)
|
||||
.map((link) => ({
|
||||
id: link.file.id,
|
||||
kind: "datei" as const,
|
||||
title: link.file.displayName,
|
||||
body: null,
|
||||
personId: null,
|
||||
atIso: link.file.createdAt.toISOString(),
|
||||
defaultSelected: true,
|
||||
fileExtension: fileExtensionLabel(link.file.displayName, link.file.mimeType),
|
||||
fileRole: link.linkRole,
|
||||
fileSizeBytes: link.file.sizeBytes,
|
||||
})),
|
||||
...tasks.map((task) => ({
|
||||
id: task.id,
|
||||
kind: "aufgabe" as const,
|
||||
title: task.title,
|
||||
body: task.description ? excerpt(task.description) : null,
|
||||
personId: task.assignedToUserId,
|
||||
atIso: task.deadline ? task.deadline.toISOString() : task.createdAt.toISOString(),
|
||||
defaultSelected: true,
|
||||
taskStatus: task.status,
|
||||
taskPriority: task.priority,
|
||||
deadlineIso: task.deadline ? task.deadline.toISOString() : null,
|
||||
})),
|
||||
...appointments.map((termin) => ({
|
||||
id: termin.id,
|
||||
kind: "termin" as const,
|
||||
title: termin.titel,
|
||||
body: termin.beschreibung ? excerpt(termin.beschreibung) : null,
|
||||
personId: termin.assignedToUserId,
|
||||
atIso: termin.startAt.toISOString(),
|
||||
defaultSelected: true,
|
||||
appointmentType: termin.typ,
|
||||
})),
|
||||
];
|
||||
|
||||
return {
|
||||
projectId: project.id,
|
||||
projectName: project.projektname,
|
||||
fromPipelineId: project.pipelineId,
|
||||
fromPipelineName: project.pipeline.name,
|
||||
toPipelineId: successor.id,
|
||||
toPipelineName: successor.name,
|
||||
toStageId: entryStage.id,
|
||||
toStageName: entryStage.name,
|
||||
candidates,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Commit the handover: record the package, then re-point the project at the
|
||||
* successor pipeline's entry stage. Both happen in one transaction so a project
|
||||
* can never end up in a pipeline without its handover trail.
|
||||
*/
|
||||
export async function executeProjectHandover(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
userId: string | null;
|
||||
ctx: ProjectVisibilityContext;
|
||||
/** The ticked companion records, as `{kind, sourceId}` pairs. */
|
||||
selection: readonly { kind: HandoverItemKind; sourceId: string }[];
|
||||
}): Promise<{ handoverId: string; toPipelineId: string; toStageId: string }> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const project = await tx.projekt.findFirst({
|
||||
where: {
|
||||
id: input.projectId,
|
||||
tenantId: input.tenantId,
|
||||
archivedAt: null,
|
||||
...projectEditScopeWhere(input.tenantId, input.ctx),
|
||||
},
|
||||
include: { pipeline: true },
|
||||
});
|
||||
if (!project) throw new CatalogError(foundationErrors.notFound, { projectId: input.projectId });
|
||||
const successorId = project.pipeline.nachfolgePipelineId;
|
||||
if (!successorId) throw new PipelineHandoverServiceError("projects.error.handoverNoSuccessor");
|
||||
const successor = await tx.pipeline.findFirst({
|
||||
where: { id: successorId, tenantId: input.tenantId, archivedAt: null },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (!successor) throw new PipelineHandoverServiceError("projects.error.handoverNoSuccessor");
|
||||
const entryStage = await resolveEntryStageWithTx(tx, { tenantId: input.tenantId, pipelineId: successor.id });
|
||||
|
||||
const handover = await tx.pipelineHandover.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
projektId: project.id,
|
||||
fromPipelineId: project.pipelineId,
|
||||
toPipelineId: successor.id,
|
||||
fromStageId: project.stageId,
|
||||
toStageId: entryStage.id,
|
||||
performedByUserId: input.userId,
|
||||
},
|
||||
});
|
||||
|
||||
// Dedupe defensively: the dialog can submit the same id twice if a user
|
||||
// double-clicks, and the unique index would otherwise abort the whole move.
|
||||
const seen = new Set<string>();
|
||||
const items = input.selection.filter((item) => {
|
||||
const key = `${item.kind}:${item.sourceId}`;
|
||||
if (seen.has(key) || !item.sourceId) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
if (items.length > 0) {
|
||||
await tx.pipelineHandoverItem.createMany({
|
||||
data: items.map((item) => ({
|
||||
tenantId: input.tenantId,
|
||||
handoverId: handover.id,
|
||||
kind: item.kind,
|
||||
sourceId: item.sourceId,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
await tx.projekt.update({
|
||||
where: { id: project.id, tenantId: input.tenantId },
|
||||
data: {
|
||||
pipelineId: successor.id,
|
||||
stageId: entryStage.id,
|
||||
// Entering a fresh pipeline clears the terminal markers of the old one:
|
||||
// the project is open again in the new view (AD-20, no second row).
|
||||
wonAt: null,
|
||||
lostAt: null,
|
||||
lostReasonId: null,
|
||||
undoStageChangeUntil: null,
|
||||
},
|
||||
});
|
||||
await tx.projektStageChange.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
projektId: project.id,
|
||||
fromStageId: project.stageId,
|
||||
toStageId: entryStage.id,
|
||||
changedByUserId: input.userId,
|
||||
},
|
||||
});
|
||||
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.userId,
|
||||
actorKind: input.userId ? "user" : "system",
|
||||
activityType: "project_pipeline_handover",
|
||||
subjectType: "project",
|
||||
subjectId: project.id,
|
||||
summaryText: "activity.runtime.projects.handoverCompleted",
|
||||
metadata: {
|
||||
handoverId: handover.id,
|
||||
fromPipelineId: project.pipelineId,
|
||||
toPipelineId: successor.id,
|
||||
itemCount: items.length,
|
||||
},
|
||||
},
|
||||
{ client: tx }
|
||||
);
|
||||
|
||||
return { handoverId: handover.id, toPipelineId: successor.id, toStageId: entryStage.id };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The M04 payload when the project currently awaits a handover, otherwise null.
|
||||
*
|
||||
* "Awaits a handover" = it sits in the final stage of a pipeline that declares
|
||||
* a successor. Every not-applicable case (no successor, successor without an
|
||||
* open stage, project not editable) resolves to null rather than throwing: the
|
||||
* detail page must render fine when no handover is pending.
|
||||
*/
|
||||
export async function loadPendingHandover(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
ctx: ProjektNotizContext;
|
||||
}): Promise<HandoverPreview | null> {
|
||||
const pending = await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const project = await tx.projekt.findFirst({
|
||||
where: {
|
||||
id: input.projectId,
|
||||
tenantId: input.tenantId,
|
||||
archivedAt: null,
|
||||
...projectEditScopeWhere(input.tenantId, input.ctx),
|
||||
},
|
||||
select: { pipelineId: true, stageId: true },
|
||||
});
|
||||
if (!project) return false;
|
||||
return shouldOpenHandoverWithTx(tx, {
|
||||
tenantId: input.tenantId,
|
||||
pipelineId: project.pipelineId,
|
||||
targetStageId: project.stageId,
|
||||
});
|
||||
});
|
||||
if (!pending) return null;
|
||||
try {
|
||||
return await loadHandoverPreview(input);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Handover trail of a project, newest first (rendered in the S02 "Verlauf" sidebar area). */
|
||||
export async function listProjectHandovers(input: { tenantId: string; projectId: string }) {
|
||||
return withTenantRLS(input.tenantId, async (tx) =>
|
||||
tx.pipelineHandover.findMany({
|
||||
where: { tenantId: input.tenantId, projektId: input.projectId },
|
||||
include: { items: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
})
|
||||
);
|
||||
}
|
||||
+897
@@ -0,0 +1,897 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
+1006
-321
File diff suppressed because it is too large.
Load diff
+26
@@ -0,0 +1,26 @@
|
||||
// @vitest-environment node
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const SOURCES = [
|
||||
"auftragService.server.ts",
|
||||
"pipelineHandoverService.server.ts",
|
||||
"plantafelAcceptanceService.server.ts",
|
||||
"projectService.server.ts",
|
||||
"projektNotizService.server.ts",
|
||||
].map((file) => readFileSync(`apps/web/app/utils/integrations/projects/${file}`, "utf8"));
|
||||
|
||||
describe("project activity i18n contract", () => {
|
||||
it("persists semantic keys for every machine-authored project summary", () => {
|
||||
const summaries = SOURCES.flatMap((source) =>
|
||||
[...source.matchAll(/summaryText:\s*"([^"]+)"/gu)].map((match) => match[1]),
|
||||
);
|
||||
|
||||
expect(summaries).toContain("activity.runtime.projects.created");
|
||||
expect(summaries).toContain("activity.runtime.projects.handoverCompleted");
|
||||
expect(summaries).toContain("activity.runtime.projects.acceptanceSaved");
|
||||
expect(summaries.length).toBeGreaterThan(20);
|
||||
expect(summaries.every((summary) => summary.startsWith("activity.runtime.projects."))).toBe(true);
|
||||
});
|
||||
});
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
// A KWP-bound project refuses writes that HiveGrid does not own. That refusal
|
||||
// used to fall through projectActionErrorResponse and be rethrown, which turned
|
||||
// a board drag onto another column into a full-page 500 instead of a plain
|
||||
// message plus a card that snaps back.
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { KwpProjectDomainError } from "@hivegrid/integrations/kwp-project-domain.server";
|
||||
import { projectActionErrorResponse } from "./projectAccess.server";
|
||||
|
||||
describe("projectActionErrorResponse — KWP refusals", () => {
|
||||
it("answers a binding conflict with 400 and a plain-text key instead of crashing", async () => {
|
||||
const response = projectActionErrorResponse(new KwpProjectDomainError("binding_conflict"));
|
||||
expect(response.status).toBe(400);
|
||||
await expect(response.json()).resolves.toEqual({ error: "projects.error.kwp.binding_conflict" });
|
||||
});
|
||||
|
||||
it("keys every KWP code separately so each refusal can say what to do", async () => {
|
||||
for (const code of ["capability_paused", "stale_write", "routing_required"] as const) {
|
||||
const response = projectActionErrorResponse(new KwpProjectDomainError(code));
|
||||
expect(response.status).toBe(400);
|
||||
await expect(response.json()).resolves.toEqual({ error: `projects.error.kwp.${code}` });
|
||||
}
|
||||
});
|
||||
|
||||
it("still rethrows what it does not know — an unexpected fault must not read as a handled refusal", () => {
|
||||
const boom = new Error("boom");
|
||||
expect(() => projectActionErrorResponse(boom)).toThrow(boom);
|
||||
});
|
||||
});
|
||||
+56
-2
@@ -1,8 +1,10 @@
|
||||
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
|
||||
import { KwpProjectDomainError } from "@hivegrid/integrations/kwp-project-domain.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { PROJECTS_MODULE_KEY } from "./projectRoutePaths";
|
||||
import { AuftragServiceError } from "./auftragService.server";
|
||||
@@ -13,6 +15,13 @@ export type ProjectRouteContext = ProjectVisibilityContext & {
|
||||
hasModule: boolean;
|
||||
};
|
||||
|
||||
export const PROJECT_READ_PERMISSIONS = [
|
||||
"projects.read_all",
|
||||
"projects.read_own",
|
||||
"projects.read_own_pl",
|
||||
"projects.read_own_member",
|
||||
] as const;
|
||||
|
||||
export async function loadProjectContext({
|
||||
request,
|
||||
params,
|
||||
@@ -27,14 +36,23 @@ export async function loadProjectContext({
|
||||
if (!tenantId || !userInfo.userId) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
const [hasModule, permissions] = await Promise.all([
|
||||
const [hasModule, permissions, roleAssignments, groupMemberships] = await Promise.all([
|
||||
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: PROJECTS_MODULE_KEY }),
|
||||
getPermissionsByUser(userInfo.userId, tenantId),
|
||||
db.userRole.findMany({ where: { tenantId, userId: userInfo.userId }, select: { roleId: true } }),
|
||||
db.groupUser.findMany({ where: { userId: userInfo.userId, group: { tenantId } }, select: { groupId: true } }),
|
||||
]);
|
||||
if (requireModule && !hasModule) {
|
||||
throw new CatalogError(foundationErrors.notFound, { module: PROJECTS_MODULE_KEY });
|
||||
}
|
||||
return { tenantId, userId: userInfo.userId, permissions, hasModule };
|
||||
return {
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
permissions,
|
||||
roleIds: roleAssignments.map(({ roleId }) => roleId),
|
||||
groupIds: groupMemberships.map(({ groupId }) => groupId),
|
||||
hasModule,
|
||||
};
|
||||
}
|
||||
|
||||
export function requireProjectPermission(ctx: ProjectRouteContext, permission: string): ProjectRouteContext {
|
||||
@@ -42,6 +60,36 @@ export function requireProjectPermission(ctx: ProjectRouteContext, permission: s
|
||||
return ctx;
|
||||
}
|
||||
|
||||
/** 404 for a route the caller may not see (Bauprinzip A.5.3: Permission-Denied
|
||||
* renders 404, not 403 — and never a 500). */
|
||||
export function projectNotFoundResponse(): Response {
|
||||
return new Response("Not Found", { status: 404 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Loader-side access guard: resolves the project context and renders a graceful
|
||||
* 404 when the projects module is off OR the viewer lacks the required
|
||||
* permission(s) — instead of letting the underlying CatalogError surface as a
|
||||
* 500. Auth redirects from loadProjectContext propagate untouched (module is not
|
||||
* required here, so requireAuth's redirect Response is not swallowed). Use in
|
||||
* LOADERS only; actions keep throwing so projectActionErrorResponse can map them.
|
||||
*/
|
||||
export async function requireProjectView(
|
||||
args: { request: Request; params: Record<string, string | undefined> },
|
||||
permission: string | readonly string[],
|
||||
): Promise<ProjectRouteContext> {
|
||||
const ctx = await loadProjectContext({ request: args.request, params: args.params, requireModule: false });
|
||||
if (!ctx.hasModule) {
|
||||
throw projectNotFoundResponse();
|
||||
}
|
||||
try {
|
||||
return Array.isArray(permission) ? requireAnyProjectPermission(ctx, permission) : requireProjectPermission(ctx, permission as string);
|
||||
} catch (error) {
|
||||
if (error instanceof Response) throw error;
|
||||
throw projectNotFoundResponse();
|
||||
}
|
||||
}
|
||||
|
||||
export function requireAnyProjectPermission(ctx: ProjectRouteContext, permissions: readonly string[]): ProjectRouteContext {
|
||||
if (permissions.some((permission) => ctx.permissions.includes(permission))) return ctx;
|
||||
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, permissions[0] ?? "projects.read_own");
|
||||
@@ -58,5 +106,11 @@ export function projectActionErrorResponse(error: unknown): Response {
|
||||
if (error instanceof AuftragServiceError) {
|
||||
return Response.json({ error: error.messageKey }, { status: 400 });
|
||||
}
|
||||
// A KWP-bound project refuses writes HiveGrid does not own. That is a normal
|
||||
// "no" for the actor, not a crash: rethrowing turned a drag onto another board
|
||||
// column into a full-page 500 instead of a message plus a card that snaps back.
|
||||
if (error instanceof KwpProjectDomainError) {
|
||||
return Response.json({ error: `projects.error.kwp.${error.code}` }, { status: 400 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
// R-P8b (RA-C2) — real live board pub/sub. Uses the repo's existing in-process
|
||||
// EventEmitter (`~/utils/stream/emitter.server`, the same one that already backs
|
||||
// the workflow-execution SSE stream) so board mutations (stage move, bulk move,
|
||||
// create, update, undo, archive) push real change-events to the connected
|
||||
// pipeline-board SSE clients instead of only a snapshot + heartbeat. No new infra
|
||||
// dependency is introduced.
|
||||
//
|
||||
// Scope caveat: this emitter is per web process. With a single web instance (the
|
||||
// current deployment) every board client shares the process, so events reach all
|
||||
// of them. Horizontal scaling of `hivegrid-web` would need a cross-process
|
||||
// transport (e.g. Redis pub/sub) behind the same publish/subscribe API — tracked
|
||||
// as a follow-up, out of this ticket's scope. This is server-only (.server) and
|
||||
// is never imported by projectService.server (kept out of the pure-service test
|
||||
// import graph) — publishing happens in the route-level orchestration helpers.
|
||||
|
||||
import { publishDashboardChange } from "~/services/dashboard/dashboardEvents.server";
|
||||
import { emitter } from "~/utils/stream/emitter.server";
|
||||
import type { ProjectBoardChange, ProjectBoardChangeType } from "./projectBoardEvents.shared";
|
||||
|
||||
/**
|
||||
* In-process channel name for one pipeline board. Includes the tenantId as
|
||||
* defence-in-depth even though pipeline ids are already globally unique — a
|
||||
* subscriber only ever binds to its own tenant+pipeline channel.
|
||||
*/
|
||||
export function projectBoardChannel(tenantId: string, pipelineId: string): string {
|
||||
return `projectBoard:${tenantId}:${pipelineId}`;
|
||||
}
|
||||
|
||||
let listenerCapRaised = false;
|
||||
|
||||
/** Subscribe an SSE stream to a pipeline board channel. Returns an unsubscribe fn. */
|
||||
export function subscribeToProjectBoard(tenantId: string, pipelineId: string, onChange: (payload: string) => void): () => void {
|
||||
// Many concurrent board viewers can subscribe to the same channel; lift the
|
||||
// default 10-listener cap so Node does not log a MaxListenersExceededWarning.
|
||||
if (!listenerCapRaised) {
|
||||
emitter.setMaxListeners(0);
|
||||
listenerCapRaised = true;
|
||||
}
|
||||
const channel = projectBoardChannel(tenantId, pipelineId);
|
||||
emitter.on(channel, onChange);
|
||||
return () => {
|
||||
emitter.off(channel, onChange);
|
||||
};
|
||||
}
|
||||
|
||||
/** Publish a board change so connected clients of this pipeline board revalidate. */
|
||||
export function publishProjectBoardChange(input: {
|
||||
tenantId: string;
|
||||
pipelineId: string;
|
||||
projectId?: string;
|
||||
type: ProjectBoardChangeType;
|
||||
}): void {
|
||||
const payload: ProjectBoardChange = {
|
||||
type: input.type,
|
||||
pipelineId: input.pipelineId,
|
||||
projectId: input.projectId,
|
||||
at: new Date().toISOString(),
|
||||
};
|
||||
emitter.emit(projectBoardChannel(input.tenantId, input.pipelineId), JSON.stringify(payload));
|
||||
// Project mutations also feed the tenant-wide dashboard stream (R-P11b):
|
||||
// sales/project KPI widgets recompute their snapshot on these changes.
|
||||
publishDashboardChange({ tenantId: input.tenantId, source: "projects" });
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
// R-P8b (RA-C2) — pure shared contract for the live pipeline-board SSE stream.
|
||||
// No server imports (no emitter/config), so it is safe to import from the client
|
||||
// board hook as well as the server publish/subscribe helper. Keeps the SSE event
|
||||
// name and change-payload shape in one place for both sides of the wire.
|
||||
|
||||
/** SSE event name the board stream sends and the client hook listens for. */
|
||||
export const PROJECT_BOARD_SSE_EVENT = "projects.board.changed";
|
||||
|
||||
export type ProjectBoardChangeType = "created" | "stage_changed" | "updated" | "stage_change_undone" | "archived";
|
||||
|
||||
export interface ProjectBoardChange {
|
||||
readonly type: ProjectBoardChangeType;
|
||||
readonly pipelineId: string;
|
||||
readonly projectId?: string;
|
||||
readonly at: string;
|
||||
}
|
||||
+349
@@ -0,0 +1,349 @@
|
||||
// R-P8b (P8 configurable Kanban) Interim-UI (AD-28) — shared server helper for
|
||||
// the board routes (`/projects` and `/projects/pipelines/:id`). Builds the
|
||||
// KanbanBoardVM from projectService.loadProjectBoard + resolved owner labels +
|
||||
// lost reasons, and handles the board actions (stage move, bulk move, undo,
|
||||
// quick-create). Server-only (.server) — never imported by a component.
|
||||
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import { buildBoardFacetsVM, buildKanbanVM, type BoardFacetsVM, type KanbanBoardVM, type PipelineHandoverVM } from "@hivegrid/view-models";
|
||||
import { isDemoDataUiEnabled } from "~/utils/services/.server/demoDataUi.server";
|
||||
import { resolveUserLabels } from "~/utils/integrations/crm/crmService.server";
|
||||
import {
|
||||
archiveProject,
|
||||
bulkMoveProjectStage,
|
||||
createProject,
|
||||
duplicateProject,
|
||||
listLostReasons,
|
||||
loadBoardAssigneeOptions,
|
||||
loadProjectTagOptions,
|
||||
loadProjectBoard,
|
||||
moveProjectStage,
|
||||
moveProjectToPipeline,
|
||||
redoLastProjectStageChange,
|
||||
undoLastProjectStageChange,
|
||||
} from "./projectService.server";
|
||||
import {
|
||||
parseFacetList,
|
||||
parseOwnerList,
|
||||
parsePeriodList,
|
||||
PROJECT_CUSTOMER_TYPES,
|
||||
PROJECT_VALUE_BANDS,
|
||||
type ProjectFacetFilters,
|
||||
} from "./projectFilterFacets";
|
||||
import { executeProjectHandover, parseHandoverSelection } from "./pipelineHandoverService.server";
|
||||
import { loadHandoverVM } from "./pipelineHandoverRoute.server";
|
||||
import { projectNotFoundResponse, type ProjectRouteContext } from "./projectAccess.server";
|
||||
import { projectDetailPath, projectPipelineStreamPath, projectsExportPath, projectsListPath } from "./projectRoutePaths";
|
||||
import { publishProjectBoardChange } from "./projectBoardEvents.server";
|
||||
|
||||
export type KanbanLoaderData = {
|
||||
/** Pipeline name — shell breadcrumb title (Tenant > Boards > <Pipeline>). */
|
||||
title: string;
|
||||
tenantSlug: string;
|
||||
vm: KanbanBoardVM;
|
||||
pipelineId: string;
|
||||
onlyMine: boolean;
|
||||
q: string;
|
||||
includeDemoData: boolean;
|
||||
/** Whether the demo-data toggle may be shown at all (staging/dev only). */
|
||||
demoDataUiEnabled: boolean;
|
||||
/** CSV export of exactly what the board currently shows (same resource the list uses). */
|
||||
exportHref: string;
|
||||
/** List view of the same board and filters — the header view switch target. */
|
||||
listHref: string;
|
||||
/** WF-P8 S01 filter bar: facet dropdowns + active-filter chips. */
|
||||
facets: BoardFacetsVM;
|
||||
/** Raw facet selection, echoed back so the screen can toggle single values. */
|
||||
facetSelection: {
|
||||
owners: string[];
|
||||
customerTypes: string[];
|
||||
periods: string[];
|
||||
periodFrom: string;
|
||||
periodTo: string;
|
||||
valueBands: string[];
|
||||
};
|
||||
};
|
||||
|
||||
export async function loadKanbanData({
|
||||
tenantSlug,
|
||||
tenantId,
|
||||
ctx,
|
||||
pipelineId,
|
||||
onlyMine,
|
||||
includeDemoData,
|
||||
q,
|
||||
facets,
|
||||
locale,
|
||||
}: {
|
||||
tenantSlug: string;
|
||||
tenantId: string;
|
||||
ctx: ProjectRouteContext;
|
||||
pipelineId?: string | null;
|
||||
onlyMine: boolean;
|
||||
includeDemoData: boolean;
|
||||
q?: string | null;
|
||||
facets?: ProjectFacetFilters;
|
||||
locale?: string;
|
||||
}): Promise<KanbanLoaderData> {
|
||||
// Outside staging/dev the `demo=show` query param is ignored server-side —
|
||||
// hiding the checkbox alone would leave demo rows reachable via URL.
|
||||
const demoDataUiEnabled = isDemoDataUiEnabled(undefined, { tenantId, tenantSlug });
|
||||
const withDemoData = demoDataUiEnabled && includeDemoData;
|
||||
const [board, lostReasons] = await Promise.all([
|
||||
// An unknown/unreadable pipelineId (e.g. a stale link that put a project id in
|
||||
// the pipeline slot) must render 404, not surface the CatalogError as a 500.
|
||||
loadProjectBoard({ tenantId, ctx, pipelineId, onlyMine, includeDemoData: withDemoData, q, facets }).catch((error) => {
|
||||
if (error instanceof CatalogError) throw projectNotFoundResponse();
|
||||
throw error;
|
||||
}),
|
||||
listLostReasons({ tenantId }),
|
||||
]);
|
||||
|
||||
const ownerIds = board.columns.flatMap((column) => column.cards.map((card) => card.ownerUserId)).filter((id): id is string => Boolean(id));
|
||||
const [ownerLabels, assignees, tagOptions] = await Promise.all([
|
||||
resolveUserLabels(ownerIds),
|
||||
loadBoardAssigneeOptions({ tenantId, ctx, pipelineId: board.pipeline.id, includeDemoData: withDemoData }),
|
||||
loadProjectTagOptions(tenantId),
|
||||
]);
|
||||
|
||||
const vm = buildKanbanVM({
|
||||
locale,
|
||||
board,
|
||||
lostReasons: lostReasons.map((reason) => ({ id: reason.id, name: reason.name })),
|
||||
ownerLabels,
|
||||
buildDetailHref: (projectId) => projectDetailPath(tenantSlug, projectId),
|
||||
sseHref: projectPipelineStreamPath(tenantSlug, board.pipeline.id),
|
||||
perms: {
|
||||
canWrite: ctx.permissions.includes("projects.write"),
|
||||
canChangeStage: ctx.permissions.includes("projects.change_stage"),
|
||||
canAdmin: ctx.permissions.includes("projects.admin"),
|
||||
canDelete: ctx.permissions.includes("projects.delete"),
|
||||
},
|
||||
});
|
||||
|
||||
// The CSV resource is shared with the list view; the board contributes the
|
||||
// filters it actually has (pipeline, search, only-mine, demo).
|
||||
const exportParams = new URLSearchParams();
|
||||
exportParams.set("pipelineId", board.pipeline.id);
|
||||
if (q) exportParams.set("q", q);
|
||||
if (onlyMine) exportParams.set("onlyMine", "1");
|
||||
if (withDemoData) exportParams.set("demo", "show");
|
||||
|
||||
const facetsVM = buildBoardFacetsVM({
|
||||
assignees: assignees.options,
|
||||
hasUnassigned: assignees.hasUnassigned,
|
||||
tags: tagOptions,
|
||||
selected: {
|
||||
owners: facets?.owners ?? [],
|
||||
customerTypes: facets?.customerTypes ?? [],
|
||||
tagIds: facets?.tagIds ?? [],
|
||||
periods: facets?.periods ?? [],
|
||||
valueBands: facets?.valueBands ?? [],
|
||||
},
|
||||
onlyMine,
|
||||
q: q ?? "",
|
||||
canFilterByValue: ctx.permissions.includes("deals.read_volume_all"),
|
||||
});
|
||||
|
||||
return {
|
||||
title: board.pipeline.name,
|
||||
tenantSlug,
|
||||
vm,
|
||||
pipelineId: board.pipeline.id,
|
||||
onlyMine,
|
||||
q: q ?? "",
|
||||
includeDemoData: withDemoData,
|
||||
demoDataUiEnabled,
|
||||
exportHref: `${projectsExportPath(tenantSlug)}?${exportParams.toString()}`,
|
||||
// Switching to the list keeps the board and its filters — the list names the
|
||||
// board in its headline, so losing the pipeline here would rename the page.
|
||||
listHref: `${projectsListPath(tenantSlug)}?${exportParams.toString()}`,
|
||||
facets: facetsVM,
|
||||
facetSelection: {
|
||||
owners: [...(facets?.owners ?? [])],
|
||||
customerTypes: [...(facets?.customerTypes ?? [])],
|
||||
periods: [...(facets?.periods ?? [])],
|
||||
periodFrom: facets?.periodFrom ?? "",
|
||||
periodTo: facets?.periodTo ?? "",
|
||||
valueBands: [...(facets?.valueBands ?? [])],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* WF-P8 S03: the board a list URL is bound to. The list shows one board (the
|
||||
* flow index dropped the cross-board list), so an absent or stale pipelineId
|
||||
* has to resolve rather than widen the result to every board. Same order the
|
||||
* kanban board falls back in: default board first, then the first visible one.
|
||||
*
|
||||
* Pure, so the list screen and the CSV resource cannot drift apart on which
|
||||
* board they mean.
|
||||
*/
|
||||
export function pickListPipeline<T extends { id: string; isDefault: boolean }>(
|
||||
pipelines: readonly T[],
|
||||
requestedPipelineId: string | null
|
||||
): T | null {
|
||||
return (
|
||||
pipelines.find((pipeline) => pipeline.id === requestedPipelineId) ??
|
||||
pipelines.find((pipeline) => pipeline.isDefault) ??
|
||||
pipelines[0] ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
/** Parse the WF-P8 S01 facet query parameters off a board URL. */
|
||||
export function parseBoardFacetParams(params: URLSearchParams): ProjectFacetFilters {
|
||||
return {
|
||||
owners: parseOwnerList(params.get("owner")),
|
||||
customerTypes: parseFacetList(params.get("kundentyp"), PROJECT_CUSTOMER_TYPES),
|
||||
// Tag ids are tenant data, so they parse like the owner list: unknown ids
|
||||
// simply match nothing instead of rejecting the URL.
|
||||
tagIds: parseOwnerList(params.get("tags")),
|
||||
periods: parsePeriodList(params.get("zeitraum")),
|
||||
periodFrom: params.get("von"),
|
||||
periodTo: params.get("bis"),
|
||||
valueBands: parseFacetList(params.get("wert"), PROJECT_VALUE_BANDS),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Permission required per board intent — used by the route actions so the
|
||||
* pre-check stays in one place (create/duplicate = write, archive = delete,
|
||||
* everything else = stage change).
|
||||
*/
|
||||
export function kanbanIntentPermission(intent: string | null): string {
|
||||
switch (intent) {
|
||||
case "createProject":
|
||||
case "duplicateProject":
|
||||
return "projects.write";
|
||||
case "archiveProject":
|
||||
return "projects.delete";
|
||||
case "handoverProject":
|
||||
return "projects.handover";
|
||||
default:
|
||||
return "projects.change_stage";
|
||||
}
|
||||
}
|
||||
|
||||
/** Handle a board intent. Returns the created project id for "createProject"
|
||||
* (so the route can redirect), else null, plus the M04 payload when the move
|
||||
* just put the project into a stage that offers a pipeline handover. Throws on
|
||||
* failure. */
|
||||
export async function handleKanbanIntent({
|
||||
intent,
|
||||
form,
|
||||
tenantId,
|
||||
ctx,
|
||||
}: {
|
||||
intent: string | null;
|
||||
form: FormData;
|
||||
tenantId: string;
|
||||
ctx: ProjectRouteContext;
|
||||
}): Promise<{ createdProjectId: string | null; handover?: PipelineHandoverVM | null }> {
|
||||
const str = (name: string): string | null => {
|
||||
const value = form.get(name);
|
||||
return typeof value === "string" ? value : null;
|
||||
};
|
||||
switch (intent) {
|
||||
case "moveStage": {
|
||||
const moved = await moveProjectStage({
|
||||
tenantId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
projectId: str("projectId") ?? "",
|
||||
targetStageId: str("targetStageId") ?? "",
|
||||
lostReasonId: str("lostReasonId") || null,
|
||||
notiz: str("notiz") || null,
|
||||
});
|
||||
// Push a real live change-event so every connected board client for this
|
||||
// pipeline revalidates immediately.
|
||||
publishProjectBoardChange({ tenantId, pipelineId: moved.pipelineId, projectId: moved.id, type: "stage_changed" });
|
||||
// M04 is triggered by the move, not by a button (D-P8: "Erreicht eine
|
||||
// Karte die letzte Stage […], oeffnet sich M04 automatisch"). The board
|
||||
// asks right here, so the dialog opens over the board the card was
|
||||
// dropped on instead of waiting for someone to open the project.
|
||||
return { createdProjectId: null, handover: await loadHandoverVM({ tenantId, projectId: moved.id, ctx }) };
|
||||
}
|
||||
case "bulkMoveStage": {
|
||||
const ids = (str("projectIds") ?? "").split(",").map((id) => id.trim()).filter(Boolean);
|
||||
const { pipelineIds } = await bulkMoveProjectStage({
|
||||
tenantId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
projectIds: ids,
|
||||
targetStageId: str("targetStageId") ?? "",
|
||||
lostReasonId: str("lostReasonId") || null,
|
||||
});
|
||||
for (const pipelineId of pipelineIds) {
|
||||
publishProjectBoardChange({ tenantId, pipelineId, type: "stage_changed" });
|
||||
}
|
||||
return { createdProjectId: null };
|
||||
}
|
||||
case "undoStage": {
|
||||
const restored = await undoLastProjectStageChange({ tenantId, userId: ctx.userId, ctx, projectId: str("projectId") ?? "" });
|
||||
publishProjectBoardChange({ tenantId, pipelineId: restored.pipelineId, projectId: restored.id, type: "stage_change_undone" });
|
||||
return { createdProjectId: null };
|
||||
}
|
||||
case "moveToPipeline": {
|
||||
const { project, previousPipelineId } = await moveProjectToPipeline({
|
||||
tenantId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
projectId: str("projectId") ?? "",
|
||||
targetPipelineId: str("targetPipelineId") ?? "",
|
||||
});
|
||||
// The card leaves one board and appears on the other, so both open
|
||||
// boards have to redraw.
|
||||
publishProjectBoardChange({ tenantId, pipelineId: previousPipelineId, projectId: project.id, type: "archived" });
|
||||
publishProjectBoardChange({ tenantId, pipelineId: project.pipelineId, projectId: project.id, type: "created" });
|
||||
return { createdProjectId: null };
|
||||
}
|
||||
case "redoStage": {
|
||||
const reapplied = await redoLastProjectStageChange({ tenantId, userId: ctx.userId, ctx, projectId: str("projectId") ?? "" });
|
||||
publishProjectBoardChange({ tenantId, pipelineId: reapplied.pipelineId, projectId: reapplied.id, type: "stage_changed" });
|
||||
return { createdProjectId: null };
|
||||
}
|
||||
case "createProject": {
|
||||
const project = await createProject({
|
||||
tenantId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
projektname: str("projektname") ?? "",
|
||||
potenziellerAuftragswert: str("potenziellerAuftragswert") || null,
|
||||
// Quick-create lands on the board the user is currently viewing, not the
|
||||
// default sales pipeline. Empty/absent -> service falls back to default.
|
||||
pipelineId: str("pipelineId") || null,
|
||||
zustaendigePersonId: ctx.userId,
|
||||
});
|
||||
publishProjectBoardChange({ tenantId, pipelineId: project.pipelineId, projectId: project.id, type: "created" });
|
||||
return { createdProjectId: project.id };
|
||||
}
|
||||
case "duplicateProject": {
|
||||
const copy = await duplicateProject({ tenantId, userId: ctx.userId, ctx, projectId: str("projectId") ?? "" });
|
||||
publishProjectBoardChange({ tenantId, pipelineId: copy.pipelineId, projectId: copy.id, type: "created" });
|
||||
return { createdProjectId: null };
|
||||
}
|
||||
case "archiveProject": {
|
||||
const archived = await archiveProject({ tenantId, userId: ctx.userId, ctx, projectId: str("projectId") ?? "" });
|
||||
publishProjectBoardChange({ tenantId, pipelineId: archived.pipelineId, projectId: archived.id, type: "archived" });
|
||||
return { createdProjectId: null };
|
||||
}
|
||||
case "handoverProject": {
|
||||
const projectId = str("projectId") ?? "";
|
||||
const result = await executeProjectHandover({
|
||||
tenantId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
projectId,
|
||||
selection: parseHandoverSelection(str("selection")),
|
||||
});
|
||||
// The card leaves this board and appears on the successor's, so both
|
||||
// redraw — same shape as a manual board change.
|
||||
publishProjectBoardChange({ tenantId, pipelineId: str("fromPipelineId") ?? "", projectId, type: "archived" });
|
||||
publishProjectBoardChange({ tenantId, pipelineId: result.toPipelineId, projectId, type: "created" });
|
||||
return { createdProjectId: null, handover: null };
|
||||
}
|
||||
default:
|
||||
return { createdProjectId: null };
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
// WF-P8 S02 "Adressdaten" — payload parsing of the `updateAddresses` intent.
|
||||
// The section posts all three slots in one JSON field, and `null` for a slot is
|
||||
// a real instruction (clear it), so the parser has to keep that apart from
|
||||
// "slot not mentioned" and from a payload it cannot read at all.
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parseAddressSlots } from "./projectDetailRoute.server";
|
||||
|
||||
describe("parseAddressSlots", () => {
|
||||
it("keeps a null slot as an explicit clear and leaves absent slots untouched", () => {
|
||||
const parsed = parseAddressSlots(JSON.stringify({ projekt: { strasse: "Hauptstr.", ort: "Freiburg" }, rechnung: null }));
|
||||
expect(parsed.projekt).toEqual({ strasse: "Hauptstr.", hausnummer: undefined, plz: undefined, ort: "Freiburg", land: undefined });
|
||||
expect("rechnung" in parsed).toBe(true);
|
||||
expect(parsed.rechnung).toBeNull();
|
||||
expect("bauherr" in parsed).toBe(false);
|
||||
});
|
||||
|
||||
it("writes nothing for a payload it cannot read instead of clearing every slot", () => {
|
||||
for (const raw of [null, "", "not json", "[]", '"projekt"']) {
|
||||
expect(parseAddressSlots(raw)).toEqual({});
|
||||
}
|
||||
});
|
||||
|
||||
it("carries the slot extras, including the ones only one slot shows", () => {
|
||||
const parsed = parseAddressSlots(
|
||||
JSON.stringify({
|
||||
projekt: { ort: "Freiburg", zufahrt: "Hofeinfahrt", notizen: "Anlieferung 7-16 Uhr" },
|
||||
rechnung: { ort: "Freiburg", rechnungsEmail: "rechnung@example.de", zahlungsziel: "30 Tage" },
|
||||
bauherr: { ort: "Freiburg", telefon: "+49 761 1", ansprechpartnerVorOrt: "Frau Schneider", postErwuenscht: true },
|
||||
})
|
||||
);
|
||||
expect(parsed.projekt).toMatchObject({ zufahrt: "Hofeinfahrt", notizen: "Anlieferung 7-16 Uhr" });
|
||||
expect(parsed.rechnung).toMatchObject({ rechnungsEmail: "rechnung@example.de", zahlungsziel: "30 Tage" });
|
||||
expect(parsed.bauherr).toMatchObject({ telefon: "+49 761 1", ansprechpartnerVorOrt: "Frau Schneider", postErwuenscht: true });
|
||||
});
|
||||
|
||||
it("leaves an extra undefined when the slot did not post it, so omission cannot clear it", () => {
|
||||
const parsed = parseAddressSlots(JSON.stringify({ projekt: { ort: "Freiburg" } }));
|
||||
expect(parsed.projekt?.notizen).toBeUndefined();
|
||||
expect(parsed.projekt?.rechnungsEmail).toBeUndefined();
|
||||
expect(parsed.projekt?.postErwuenscht).toBeUndefined();
|
||||
});
|
||||
|
||||
it("drops unknown slots and non-string members", () => {
|
||||
const parsed = parseAddressSlots(JSON.stringify({ lieferung: { ort: "Freiburg" }, projekt: { ort: 42, plz: "79098" } }));
|
||||
expect(Object.keys(parsed)).toEqual(["projekt"]);
|
||||
expect(parsed.projekt).toEqual({ strasse: undefined, hausnummer: undefined, plz: "79098", ort: undefined, land: undefined });
|
||||
});
|
||||
});
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
// WF-P8 S02 contact cards — which master-data rows a card gets. The row set
|
||||
// follows the contact type, and unset fields must not become "—" rows, so this
|
||||
// is worth pinning independently of the screen.
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { contactStammdatenRows } from "./projectDetailRoute.server";
|
||||
import type { ProjektKontaktDetail } from "./projectService.server";
|
||||
|
||||
function kontakt(over: Partial<ProjektKontaktDetail> = {}): ProjektKontaktDetail {
|
||||
return {
|
||||
id: "pk1",
|
||||
kontaktId: "c1",
|
||||
kontaktTyp: "organisation",
|
||||
rolle: "auftraggeber",
|
||||
primaer: true,
|
||||
label: "Weber GmbH",
|
||||
email: null,
|
||||
telefon: null,
|
||||
website: null,
|
||||
ustIdNr: null,
|
||||
handelsregister: null,
|
||||
kundennummer: null,
|
||||
kundeSeit: null,
|
||||
branche: null,
|
||||
mitarbeiterzahl: null,
|
||||
position: null,
|
||||
erreichbarkeit: null,
|
||||
portalInviteEligible: false,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
describe("contactStammdatenRows", () => {
|
||||
it("keeps only the company fields that are set, in export order", () => {
|
||||
const rows = contactStammdatenRows(
|
||||
kontakt({ website: "https://weber.test", branche: "SHK", mitarbeiterzahl: 24, kundeSeit: new Date("2021-03-04T00:00:00.000Z") })
|
||||
);
|
||||
expect(rows).toEqual([
|
||||
{ labelKey: "projects.detail.contacts.website", value: "https://weber.test" },
|
||||
{ labelKey: "projects.detail.contacts.customerSince", value: "2021-03-04" },
|
||||
{ labelKey: "projects.detail.contacts.industry", value: "SHK" },
|
||||
{ labelKey: "projects.detail.contacts.headcount", value: "24" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("gives a person the person fields, never the company ones", () => {
|
||||
const rows = contactStammdatenRows(
|
||||
kontakt({ kontaktTyp: "privatperson", position: "Einkauf", erreichbarkeit: "Mo-Do", branche: "SHK", ustIdNr: "DE1" })
|
||||
);
|
||||
expect(rows).toEqual([
|
||||
{ labelKey: "projects.detail.contacts.position", value: "Einkauf" },
|
||||
{ labelKey: "projects.detail.contacts.availability", value: "Mo-Do" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("drops blank and whitespace-only values instead of rendering empty rows", () => {
|
||||
expect(contactStammdatenRows(kontakt({ website: " ", branche: "" }))).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps a headcount of zero, which is a value and not a missing field", () => {
|
||||
expect(contactStammdatenRows(kontakt({ mitarbeiterzahl: 0 }))).toEqual([
|
||||
{ labelKey: "projects.detail.contacts.headcount", value: "0" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
+633
@@ -0,0 +1,633 @@
|
||||
// R-P8a (P8 Projekt core) Interim-UI (AD-28) — server helper for the project
|
||||
// detail (`/projects/:id`). Builds the P8 ProjektDetailVM + ActivityStreamVM
|
||||
// from projectService + the tenant-scoped Activity timeline and handles the P8
|
||||
// action intents (stammdaten inline-edit, stage move, 24h-undo). Server-only
|
||||
// (.server) — never imported by a component. The P9 (auftrag/signature) parts
|
||||
// of the route stay untouched; this only augments the P8 core section.
|
||||
|
||||
import {
|
||||
buildActivityStreamVM,
|
||||
buildProjektDetailVM,
|
||||
datentypLabelKey,
|
||||
type ActivityStreamVM,
|
||||
type ProjectMemberRole,
|
||||
type ProjektDetailVM,
|
||||
} from "@hivegrid/view-models";
|
||||
import { loadKwpProjectPanel } from "@hivegrid/integrations/kwp-project-domain.server";
|
||||
import { canUsePortalInvitationEntrypoint } from "~/services/customer-portal/portal-invitation-entrypoint.server";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { companyDetailPath, contactDetailPath } from "~/utils/integrations/crm/crmRoutePaths";
|
||||
import { createKontakt, listAssignableUsers, resolveUserLabels } from "~/utils/integrations/crm/crmService.server";
|
||||
import { getCustomFieldValues, listCustomFieldDefinitions } from "~/utils/integrations/crm/customFieldService.server";
|
||||
import type { ProjectRouteContext } from "./projectAccess.server";
|
||||
import { publishProjectBoardChange } from "./projectBoardEvents.server";
|
||||
import { listProjectNotes, toProjektNotizContext } from "./projektNotizService.server";
|
||||
import {
|
||||
linkProjektKontakt,
|
||||
unlinkProjektKontakt,
|
||||
loadProjectDetail,
|
||||
moveProjectStage,
|
||||
PROJECT_ADDRESS_SLOTS,
|
||||
setProjectCustomFieldValue,
|
||||
undoLastProjectStageChange,
|
||||
updateProjectAddresses,
|
||||
updateProjectStammdaten,
|
||||
type ProjectAddressInput,
|
||||
type ProjectAddressSlot,
|
||||
type ProjektKontaktDetail,
|
||||
} from "./projectService.server";
|
||||
|
||||
const ACTIVITY_LIMIT = 50;
|
||||
/** Rows per rail tile: the rail is a glance, the modules below are the full list. */
|
||||
const RAIL_LIMIT = 8;
|
||||
/** Polymorphic CustomFieldValue entity type for the project core (ENTITY-MODEL Domäne 5). */
|
||||
const PROJEKT_CUSTOM_FIELD_ENTITY = "projekt" as const;
|
||||
|
||||
type ActivityDbRow = {
|
||||
id: string;
|
||||
createdAt: Date;
|
||||
actorUserId: string | null;
|
||||
actorKind: string;
|
||||
activityType: string;
|
||||
summaryText: string;
|
||||
};
|
||||
|
||||
function decimalToDisplay(value: unknown): string | null {
|
||||
if (value == null) return null;
|
||||
const num = typeof value === "number" ? value : Number(String(value));
|
||||
if (!Number.isFinite(num)) return null;
|
||||
return num.toFixed(2);
|
||||
}
|
||||
|
||||
type MemberDbRow = { id: string; userId: string; rolle: ProjectMemberRole };
|
||||
|
||||
/**
|
||||
* WF-P8 S02 "Planung und Verantwortliche" needs the member rows with their raw
|
||||
* user ids to drive the two people pickers, which the P9 operations VM drops in
|
||||
* favour of a display label. Group principals stay out: the section offers
|
||||
* pickers over named persons, groups remain editable in the operations panel.
|
||||
*/
|
||||
async function loadProjectUserMembers(tenantId: string, projectId: string): Promise<MemberDbRow[]> {
|
||||
const rows = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.projektMitglied.findMany({
|
||||
where: { tenantId, projektId: projectId, archivedAt: null, userId: { not: null } },
|
||||
orderBy: { createdAt: "asc" },
|
||||
select: { id: true, userId: true, rolle: true },
|
||||
})
|
||||
);
|
||||
return rows.flatMap((row) => (row.userId ? [{ id: row.id, userId: row.userId, rolle: row.rolle as ProjectMemberRole }] : []));
|
||||
}
|
||||
|
||||
/**
|
||||
* WF-P8 S02 "Letzter Kontakt" on the contact cards. Derived, never stored: the
|
||||
* timeline already holds every touch (mail, call, note), and a stored column
|
||||
* would be a second truth that drifts the moment one writer forgets it.
|
||||
*
|
||||
* Contacts and companies use different subject types in the timeline, so both
|
||||
* are queried and the newest entry per contact id wins.
|
||||
*/
|
||||
async function loadLastContactTouch(tenantId: string, kontaktIds: readonly string[]): Promise<Map<string, string>> {
|
||||
if (kontaktIds.length === 0) return new Map();
|
||||
const rows = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.activity.findMany({
|
||||
where: { tenantId, subjectType: { in: ["contact", "company"] }, subjectId: { in: [...kontaktIds] } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: { subjectId: true, createdAt: true },
|
||||
})
|
||||
);
|
||||
const newest = new Map<string, string>();
|
||||
for (const row of rows) {
|
||||
if (!newest.has(row.subjectId)) newest.set(row.subjectId, row.createdAt.toISOString());
|
||||
}
|
||||
return newest;
|
||||
}
|
||||
|
||||
/**
|
||||
* WF-P8 S02 rail: the project's stage history. `ProjektStageChange` already keeps
|
||||
* every move, so the rail reads it instead of a second log — and it reads it
|
||||
* read-only: moving a stage stays the board's and the header's job.
|
||||
*/
|
||||
async function loadStageHistory(
|
||||
tenantId: string,
|
||||
projectId: string,
|
||||
stageNameById: Map<string, string>
|
||||
): Promise<{ id: string; label: string; atIso: string; actorUserId: string | null }[]> {
|
||||
const rows = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.projektStageChange.findMany({
|
||||
where: { tenantId, projektId: projectId, undoneAt: null },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: RAIL_LIMIT,
|
||||
select: { id: true, fromStageId: true, toStageId: true, createdAt: true, changedByUserId: true },
|
||||
})
|
||||
);
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
label: `${stageNameById.get(row.fromStageId) ?? row.fromStageId} → ${stageNameById.get(row.toStageId) ?? row.toStageId}`,
|
||||
atIso: row.createdAt.toISOString(),
|
||||
actorUserId: row.changedByUserId,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* WF-P8 S02 rail: the next appointments and the open tasks of this project.
|
||||
*
|
||||
* Read here rather than reused from the P9 operations view model, because that
|
||||
* one formats an assignee as the bare user id (`principalLabel`) — fine for a
|
||||
* panel that shows it next to a picker, useless in a rail line. These rows carry
|
||||
* the ids so the caller can resolve them with the labels it already fetches.
|
||||
*/
|
||||
async function loadRailAgenda(
|
||||
tenantId: string,
|
||||
projectId: string
|
||||
): Promise<{
|
||||
appointments: { id: string; titel: string; startAt: Date; userId: string | null }[];
|
||||
tasks: { id: string; title: string; deadline: Date | null; userId: string | null }[];
|
||||
}> {
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
const [appointments, tasks] = await Promise.all([
|
||||
tx.projektTermin.findMany({
|
||||
where: { tenantId, projektId: projectId, archivedAt: null },
|
||||
orderBy: { startAt: "asc" },
|
||||
take: RAIL_LIMIT,
|
||||
select: { id: true, titel: true, startAt: true, assignedToUserId: true },
|
||||
}),
|
||||
tx.task.findMany({
|
||||
where: { tenantId, linkedEntityType: "project", linkedEntityId: projectId, archivedAt: null, status: { not: "done" } },
|
||||
orderBy: [{ deadline: "asc" }, { createdAt: "desc" }],
|
||||
take: RAIL_LIMIT,
|
||||
select: { id: true, title: true, deadline: true, assignedToUserId: true },
|
||||
}),
|
||||
]);
|
||||
return {
|
||||
appointments: appointments.map((row) => ({ id: row.id, titel: row.titel, startAt: row.startAt, userId: row.assignedToUserId })),
|
||||
tasks: tasks.map((row) => ({ id: row.id, title: row.title, deadline: row.deadline, userId: row.assignedToUserId })),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** S02 KWP block. The module owns the binding, so it owns the read as well. */
|
||||
async function loadKwpPanel(tenantId: string, projectId: string) {
|
||||
return withTenantRLS(tenantId, (tx) => loadKwpProjectPanel(tx as never, tenantId, projectId));
|
||||
}
|
||||
|
||||
async function loadProjectActivities(tenantId: string, projectId: string): Promise<ActivityDbRow[]> {
|
||||
const rows = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.activity.findMany({
|
||||
where: { tenantId, subjectType: "project", subjectId: projectId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: ACTIVITY_LIMIT + 1,
|
||||
select: { id: true, createdAt: true, actorUserId: true, actorKind: true, activityType: true, summaryText: true },
|
||||
})
|
||||
);
|
||||
return rows as ActivityDbRow[];
|
||||
}
|
||||
|
||||
export type ProjektCustomFieldDef = { id: string; key: string; label: string; datentyp: string; datentypLabelKey: string };
|
||||
|
||||
/** One rail entry: a line plus its timestamp and, where known, its author. */
|
||||
export type ProjektRailEntry = { id: string; label: string; meta: string | null; atIso: string | null };
|
||||
|
||||
/**
|
||||
* The read-only content of the S02 rail tiles the screen cannot derive from the
|
||||
* detail VM. Read-only on purpose: the editors for appointments, tasks and notes
|
||||
* live in the operations panel further down the same route, and a second editor
|
||||
* over the same rows is how the two drift apart. A second *view* does not have
|
||||
* that problem.
|
||||
*/
|
||||
export type ProjektDetailRailAreas = {
|
||||
history: ProjektRailEntry[];
|
||||
notes: ProjektRailEntry[];
|
||||
appointments: ProjektRailEntry[];
|
||||
tasks: ProjektRailEntry[];
|
||||
};
|
||||
|
||||
export type ProjektDetailP8Data = {
|
||||
detailVM: ProjektDetailVM;
|
||||
activityVM: ActivityStreamVM;
|
||||
ownerOptions: { id: string; label: string }[];
|
||||
customFieldDefs: ProjektCustomFieldDef[];
|
||||
railAreas: ProjektDetailRailAreas;
|
||||
};
|
||||
|
||||
export async function loadProjektDetailP8({
|
||||
tenantId,
|
||||
tenantSlug,
|
||||
projectId,
|
||||
ctx,
|
||||
nowIso,
|
||||
locale,
|
||||
}: {
|
||||
tenantId: string;
|
||||
/** Needed for the S02 contact cards, which link into the CRM detail screens. */
|
||||
tenantSlug: string;
|
||||
projectId: string;
|
||||
ctx: ProjectRouteContext;
|
||||
nowIso: string;
|
||||
locale?: string;
|
||||
}): Promise<ProjektDetailP8Data> {
|
||||
const detail = await loadProjectDetail({ tenantId, projectId, ctx });
|
||||
const canBrowseTenantMembers = ctx.permissions.includes("projects.write") || ctx.permissions.includes("app.settings.members.view");
|
||||
const canReadCrm = ctx.permissions.includes("crm.read_all") || ctx.permissions.includes("crm.read_own");
|
||||
const [activityRows, memberRows, kwpPanel, ownerOptions, customFieldValues, customFieldDefinitions, canInviteToPortal] = await Promise.all([
|
||||
loadProjectActivities(tenantId, projectId),
|
||||
loadProjectUserMembers(tenantId, projectId),
|
||||
loadKwpPanel(tenantId, projectId),
|
||||
canBrowseTenantMembers ? listAssignableUsers(tenantId) : Promise.resolve([]),
|
||||
getCustomFieldValues({ tenantId, entityType: PROJEKT_CUSTOM_FIELD_ENTITY, entityId: projectId }),
|
||||
listCustomFieldDefinitions({ tenantId, entityType: PROJEKT_CUSTOM_FIELD_ENTITY }),
|
||||
canUsePortalInvitationEntrypoint(ctx),
|
||||
]);
|
||||
|
||||
const stageNameById = new Map(detail.stages.map((stage) => [stage.id, stage.name]));
|
||||
const [lastTouchByKontaktId, stageHistory, noteRows, agenda] = await Promise.all([
|
||||
loadLastContactTouch(
|
||||
tenantId,
|
||||
detail.kontakte.map((kontakt) => kontakt.kontaktId)
|
||||
),
|
||||
loadStageHistory(tenantId, projectId, stageNameById),
|
||||
// The note reader owns the visibility scope, so an internal note stays out of
|
||||
// the rail for somebody who may not read it.
|
||||
listProjectNotes({ tenantId, projectId, ctx: toProjektNotizContext(ctx) }).catch(() => []),
|
||||
loadRailAgenda(tenantId, projectId),
|
||||
]);
|
||||
const actorIds = activityRows.map((row) => row.actorUserId).filter((id): id is string => Boolean(id));
|
||||
const userLabels = await resolveUserLabels(
|
||||
[
|
||||
detail.project.zustaendigePersonId,
|
||||
detail.project.projektleiterId,
|
||||
...memberRows.map((row) => row.userId),
|
||||
...actorIds,
|
||||
...stageHistory.map((entry) => entry.actorUserId),
|
||||
...noteRows.map((note) => note.autorUserId),
|
||||
...agenda.appointments.map((appointment) => appointment.userId),
|
||||
...agenda.tasks.map((task) => task.userId),
|
||||
].filter((id): id is string => Boolean(id))
|
||||
);
|
||||
|
||||
const detailVM = buildProjektDetailVM({
|
||||
locale,
|
||||
project: {
|
||||
id: detail.project.id,
|
||||
projektNummer: detail.project.projektNummer,
|
||||
projektname: detail.project.projektname,
|
||||
beschreibung: detail.project.beschreibung,
|
||||
prioritaet: detail.project.prioritaet,
|
||||
stageId: detail.project.stageId,
|
||||
startDatumIso: detail.project.startDatum?.toISOString() ?? null,
|
||||
projekttyp: detail.project.projekttyp,
|
||||
quelle: detail.project.quelle,
|
||||
promotion: detail.project.promotion,
|
||||
email: detail.project.email,
|
||||
telefon: detail.project.telefon,
|
||||
fax: detail.project.fax,
|
||||
deadlineIso: detail.project.deadline?.toISOString() ?? null,
|
||||
zustaendigePersonId: detail.project.zustaendigePersonId,
|
||||
projektleiterId: detail.project.projektleiterId,
|
||||
konvertiertAusLeadId: detail.project.konvertiertAusLeadId,
|
||||
wonAtIso: detail.project.wonAt?.toISOString() ?? null,
|
||||
lostAtIso: detail.project.lostAt?.toISOString() ?? null,
|
||||
undoStageChangeUntilIso: detail.project.undoStageChangeUntil?.toISOString() ?? null,
|
||||
lostReasonId: detail.project.lostReasonId,
|
||||
},
|
||||
pipelineName: detail.pipeline.name,
|
||||
pipelineTypHint: detail.pipeline.typHint,
|
||||
stages: detail.stages.map((stage) => ({
|
||||
id: stage.id,
|
||||
name: stage.name,
|
||||
stageKind: stage.stageKind,
|
||||
winProbability: stage.winProbability,
|
||||
color: stage.color,
|
||||
})),
|
||||
kontakte: detail.kontakte.map((kontakt) => ({
|
||||
id: kontakt.id,
|
||||
kontaktId: kontakt.kontaktId,
|
||||
kontaktTyp: kontakt.kontaktTyp,
|
||||
rolle: kontakt.rolle,
|
||||
primaer: kontakt.primaer,
|
||||
label: kontakt.label,
|
||||
email: kontakt.email,
|
||||
telefon: kontakt.telefon,
|
||||
// Only offered with a CRM read permission. `crm.read_own` can still land
|
||||
// on a 404 for someone else's contact — that is the module's own owner
|
||||
// gate, and hiding the link entirely would cost the common case.
|
||||
stammdaten: contactStammdatenRows(kontakt),
|
||||
notizen: kontakt.notizen,
|
||||
durchwahl: kontakt.durchwahl,
|
||||
mobil: kontakt.mobil,
|
||||
fax: kontakt.fax,
|
||||
adresseLabel: kontakt.adresseLabel,
|
||||
lastContactAtIso: lastTouchByKontaktId.get(kontakt.kontaktId) ?? null,
|
||||
detailHref: canReadCrm
|
||||
? kontakt.kontaktTyp === "organisation"
|
||||
? companyDetailPath(tenantSlug, kontakt.kontaktId)
|
||||
: contactDetailPath(tenantSlug, kontakt.kontaktId)
|
||||
: null,
|
||||
portalInviteEligible: kontakt.portalInviteEligible,
|
||||
})),
|
||||
lostReasons: detail.lostReasons.map((reason) => ({ id: reason.id, name: reason.name })),
|
||||
adressen: detail.adressen,
|
||||
kwp: kwpPanel,
|
||||
customFields: customFieldValues.map((cf) => ({
|
||||
definitionId: cf.definition.id,
|
||||
key: cf.definition.key,
|
||||
label: cf.definition.label,
|
||||
datentyp: cf.definition.datentyp,
|
||||
wert: cf.wert,
|
||||
optionen: cf.definition.optionen,
|
||||
})),
|
||||
value: detail.canViewVolume ? decimalToDisplay(detail.project.potenziellerAuftragswert) : null,
|
||||
orderVolume: detail.canViewVolume ? decimalToDisplay(detail.project.auftragsvolumen) : null,
|
||||
valueVisible: detail.canViewVolume,
|
||||
ownerLabel: detail.project.zustaendigePersonId ? (userLabels.get(detail.project.zustaendigePersonId) ?? null) : null,
|
||||
projektleiterLabel: detail.project.projektleiterId ? (userLabels.get(detail.project.projektleiterId) ?? null) : null,
|
||||
mitglieder: memberRows.map((row) => ({
|
||||
id: row.id,
|
||||
userId: row.userId,
|
||||
rolle: row.rolle,
|
||||
label: userLabels.get(row.userId) ?? row.userId,
|
||||
})),
|
||||
perms: {
|
||||
canWrite: hasPerm(ctx.permissions, "projects.write"),
|
||||
canChangeStage: hasPerm(ctx.permissions, "projects.change_stage"),
|
||||
canInviteToPortal,
|
||||
canManageMembers: hasPerm(ctx.permissions, "projects.manage_members"),
|
||||
},
|
||||
nowIso,
|
||||
});
|
||||
|
||||
const activityVM = buildActivityStreamVM({
|
||||
rows: activityRows.slice(0, ACTIVITY_LIMIT).map((row) => ({
|
||||
id: row.id,
|
||||
createdAt: row.createdAt,
|
||||
actorUserId: row.actorUserId,
|
||||
actorKind: row.actorKind as never,
|
||||
activityType: row.activityType as never,
|
||||
summaryText: row.summaryText,
|
||||
})),
|
||||
userLabels,
|
||||
hasMore: activityRows.length > ACTIVITY_LIMIT,
|
||||
});
|
||||
|
||||
const customFieldDefs: ProjektCustomFieldDef[] = customFieldDefinitions.map((def) => ({
|
||||
id: def.id,
|
||||
key: def.key,
|
||||
label: def.label,
|
||||
datentyp: def.datentyp,
|
||||
datentypLabelKey: datentypLabelKey(def.datentyp),
|
||||
}));
|
||||
|
||||
const railAreas: ProjektDetailRailAreas = {
|
||||
history: stageHistory.map((entry) => ({
|
||||
id: entry.id,
|
||||
label: entry.label,
|
||||
meta: entry.actorUserId ? (userLabels.get(entry.actorUserId) ?? null) : null,
|
||||
atIso: entry.atIso,
|
||||
})),
|
||||
appointments: agenda.appointments.map((appointment) => ({
|
||||
id: appointment.id,
|
||||
label: appointment.titel,
|
||||
meta: appointment.userId ? (userLabels.get(appointment.userId) ?? null) : null,
|
||||
atIso: appointment.startAt.toISOString(),
|
||||
})),
|
||||
tasks: agenda.tasks.map((task) => ({
|
||||
id: task.id,
|
||||
label: task.title,
|
||||
meta: task.userId ? (userLabels.get(task.userId) ?? null) : null,
|
||||
atIso: task.deadline?.toISOString() ?? null,
|
||||
})),
|
||||
notes: noteRows.slice(0, RAIL_LIMIT).map((note) => ({
|
||||
id: note.id,
|
||||
label: note.inhalt,
|
||||
// The visibility is part of the line: "nur ich" next to a note is what
|
||||
// tells the author that nobody else is reading it.
|
||||
meta: [note.autorUserId ? userLabels.get(note.autorUserId) : null, note.sichtbarkeit].filter(Boolean).join(" · ") || null,
|
||||
atIso: note.createdAt.toISOString(),
|
||||
})),
|
||||
};
|
||||
|
||||
return { detailVM, activityVM, ownerOptions, customFieldDefs, railAreas };
|
||||
}
|
||||
|
||||
function hasPerm(permissions: readonly string[], permission: string): boolean {
|
||||
return permissions.includes(permission);
|
||||
}
|
||||
|
||||
/**
|
||||
* WF-P8 S02 contact cards: the master-data rows below the channels. Only fields
|
||||
* that are actually set become rows — an empty card of "—" labels tells nobody
|
||||
* anything. Company fields go on the organisation card, person fields on the
|
||||
* Ansprechpartner card, so a card never shows the other kind's empty slots.
|
||||
*/
|
||||
export function contactStammdatenRows(kontakt: ProjektKontaktDetail): { labelKey: string; value: string }[] {
|
||||
const candidates: [string, string | null][] =
|
||||
kontakt.kontaktTyp === "organisation"
|
||||
? [
|
||||
["projects.detail.contacts.website", kontakt.website],
|
||||
["projects.detail.contacts.vatId", kontakt.ustIdNr],
|
||||
["projects.detail.contacts.tradeRegister", kontakt.handelsregister],
|
||||
["projects.detail.contacts.customerNumber", kontakt.kundennummer],
|
||||
["projects.detail.contacts.customerSince", kontakt.kundeSeit ? kontakt.kundeSeit.toISOString().slice(0, 10) : null],
|
||||
["projects.detail.contacts.industry", kontakt.branche],
|
||||
["projects.detail.contacts.headcount", kontakt.mitarbeiterzahl === null ? null : String(kontakt.mitarbeiterzahl)],
|
||||
]
|
||||
: [
|
||||
["projects.detail.contacts.position", kontakt.position],
|
||||
["projects.detail.contacts.availability", kontakt.erreichbarkeit],
|
||||
];
|
||||
return candidates.flatMap(([labelKey, value]) => {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed ? [{ labelKey, value: trimmed }] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the S02 address payload. Unknown slots and non-string members are
|
||||
* dropped; `null` for a slot is meaningful (clear it), so it survives. A
|
||||
* malformed payload writes nothing rather than clearing every slot.
|
||||
*/
|
||||
export function parseAddressSlots(raw: string | null): Partial<Record<ProjectAddressSlot, ProjectAddressInput | null>> {
|
||||
if (!raw) return {};
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
|
||||
const out: Partial<Record<ProjectAddressSlot, ProjectAddressInput | null>> = {};
|
||||
for (const slot of PROJECT_ADDRESS_SLOTS) {
|
||||
if (!(slot in parsed)) continue;
|
||||
const value = (parsed as Record<string, unknown>)[slot];
|
||||
if (value === null) {
|
||||
out[slot] = null;
|
||||
continue;
|
||||
}
|
||||
if (typeof value !== "object" || Array.isArray(value)) continue;
|
||||
const record = value as Record<string, unknown>;
|
||||
const pick = (key: string): string | undefined => (typeof record[key] === "string" ? (record[key] as string) : undefined);
|
||||
out[slot] = {
|
||||
strasse: pick("strasse"),
|
||||
hausnummer: pick("hausnummer"),
|
||||
plz: pick("plz"),
|
||||
ort: pick("ort"),
|
||||
land: pick("land"),
|
||||
// Slot extras (ProjektAdressDetail). Absent members stay undefined so a
|
||||
// slot that never shows a field cannot clear it by omission.
|
||||
bauabschnitt: pick("bauabschnitt"),
|
||||
zufahrt: pick("zufahrt"),
|
||||
koordinaten: pick("koordinaten"),
|
||||
empfaenger: pick("empfaenger"),
|
||||
zahlungsziel: pick("zahlungsziel"),
|
||||
rechnungsEmail: pick("rechnungsEmail"),
|
||||
postErwuenscht: typeof record.postErwuenscht === "boolean" ? record.postErwuenscht : undefined,
|
||||
telefon: pick("telefon"),
|
||||
ansprechpartnerVorOrt: pick("ansprechpartnerVorOrt"),
|
||||
notizen: pick("notizen"),
|
||||
};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Handle a P8 detail intent. Returns true if the intent was a P8 one (handled),
|
||||
* false if it should fall through to the existing P9 action switch. Throws
|
||||
* ProjectServiceError/CatalogError on failure (caller maps to a Response). */
|
||||
export async function handleProjektDetailP8Intent({
|
||||
intent,
|
||||
form,
|
||||
tenantId,
|
||||
projectId,
|
||||
ctx,
|
||||
}: {
|
||||
intent: string | null;
|
||||
form: FormData;
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
ctx: ProjectRouteContext;
|
||||
}): Promise<boolean> {
|
||||
const str = (name: string): string | null => {
|
||||
const value = form.get(name);
|
||||
return typeof value === "string" ? value : null;
|
||||
};
|
||||
switch (intent) {
|
||||
case "updateStammdaten": {
|
||||
const updated = await updateProjectStammdaten({
|
||||
tenantId,
|
||||
projectId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
projektname: str("projektname") ?? undefined,
|
||||
beschreibung: form.has("beschreibung") ? str("beschreibung") : undefined,
|
||||
prioritaet: (str("prioritaet") as never) ?? undefined,
|
||||
potenziellerAuftragswert: form.has("potenziellerAuftragswert") ? str("potenziellerAuftragswert") : undefined,
|
||||
auftragsvolumen: form.has("auftragsvolumen") ? str("auftragsvolumen") : undefined,
|
||||
startDatum: form.has("startDatum") ? str("startDatum") : undefined,
|
||||
deadline: form.has("deadline") ? str("deadline") : undefined,
|
||||
zustaendigePersonId: form.has("zustaendigePersonId") ? str("zustaendigePersonId") : undefined,
|
||||
projektleiterId: form.has("projektleiterId") ? str("projektleiterId") : undefined,
|
||||
projekttyp: form.has("projekttyp") ? str("projekttyp") : undefined,
|
||||
quelle: form.has("quelle") ? str("quelle") : undefined,
|
||||
promotion: form.has("promotion") ? str("promotion") : undefined,
|
||||
email: form.has("email") ? str("email") : undefined,
|
||||
telefon: form.has("telefon") ? str("telefon") : undefined,
|
||||
fax: form.has("fax") ? str("fax") : undefined,
|
||||
});
|
||||
// A detail-edit changes a board card (owner/value/priority) — publish a live
|
||||
// board change so any open pipeline board revalidates.
|
||||
publishProjectBoardChange({ tenantId, pipelineId: updated.pipelineId, projectId: updated.id, type: "updated" });
|
||||
return true;
|
||||
}
|
||||
case "updateAddresses": {
|
||||
// One JSON field carries all three slots: the section saves them together
|
||||
// and a slot is a small record, not a flat list of form fields.
|
||||
const updated = await updateProjectAddresses({
|
||||
tenantId,
|
||||
projectId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
slots: parseAddressSlots(str("slots")),
|
||||
});
|
||||
publishProjectBoardChange({ tenantId, pipelineId: updated.pipelineId, projectId: updated.id, type: "updated" });
|
||||
return true;
|
||||
}
|
||||
case "linkKontakt": {
|
||||
// WF-P8 S02 "Bestehende Firma / Kontakt durchsuchen": the picked contact.
|
||||
await linkProjektKontakt({
|
||||
tenantId,
|
||||
projectId,
|
||||
kontaktId: str("kontaktId") ?? "",
|
||||
rolle: (str("rolle") as never) ?? undefined,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
case "unlinkKontakt": {
|
||||
// WF-P8 S02: the contact leaves this project, not the CRM.
|
||||
await unlinkProjektKontakt({
|
||||
tenantId,
|
||||
projectId,
|
||||
projektKontaktId: str("projektKontaktId") ?? "",
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
case "createKontakt": {
|
||||
// "Neuen Kontakt erstellen" / "Neue Firma erstellen" — one intent, because
|
||||
// the only difference is the contact type and which name field is filled.
|
||||
// The contact itself is created through the CRM service, so a project never
|
||||
// becomes a second place where contacts are born.
|
||||
const kontaktTyp = str("kontaktTyp") === "organisation" ? "organisation" : "privatperson";
|
||||
const email = str("email")?.trim() ?? "";
|
||||
const kontakt = await createKontakt({
|
||||
tenantId,
|
||||
userId: ctx.userId ?? "",
|
||||
kontaktTyp,
|
||||
vorname: kontaktTyp === "privatperson" ? str("vorname") : null,
|
||||
nachname: kontaktTyp === "privatperson" ? str("nachname") : null,
|
||||
orgName: kontaktTyp === "organisation" ? str("orgName") : null,
|
||||
emails: email ? [{ email, primaer: true }] : [],
|
||||
});
|
||||
await linkProjektKontakt({
|
||||
tenantId,
|
||||
projectId,
|
||||
kontaktId: kontakt.id,
|
||||
rolle: (str("rolle") as never) ?? undefined,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
case "moveStage": {
|
||||
const moved = await moveProjectStage({
|
||||
tenantId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
projectId,
|
||||
targetStageId: str("targetStageId") ?? "",
|
||||
lostReasonId: str("lostReasonId") || null,
|
||||
notiz: str("notiz") || null,
|
||||
});
|
||||
publishProjectBoardChange({ tenantId, pipelineId: moved.pipelineId, projectId: moved.id, type: "stage_changed" });
|
||||
return true;
|
||||
}
|
||||
case "undoStage": {
|
||||
const restored = await undoLastProjectStageChange({ tenantId, userId: ctx.userId, ctx, projectId });
|
||||
publishProjectBoardChange({ tenantId, pipelineId: restored.pipelineId, projectId: restored.id, type: "stage_change_undone" });
|
||||
return true;
|
||||
}
|
||||
case "setCustomField": {
|
||||
await setProjectCustomFieldValue({
|
||||
tenantId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
projectId,
|
||||
definitionId: str("definitionId") ?? "",
|
||||
wert: str("wert"),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
// WF-P8 S01 — the date and money maths behind the board facets. Pure, so it is
|
||||
// tested without a database.
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildOwnerWhere,
|
||||
buildPeriodWhere,
|
||||
buildValueBandWhere,
|
||||
parseFacetList,
|
||||
parseOwnerList,
|
||||
parsePeriodKey,
|
||||
PROJECT_CUSTOMER_TYPES,
|
||||
PROJECT_VALUE_BANDS,
|
||||
resolvePeriodRange,
|
||||
resolvePeriodRanges,
|
||||
UNASSIGNED_OWNER,
|
||||
} from "./projectFilterFacets";
|
||||
|
||||
describe("parseFacetList", () => {
|
||||
it("keeps only known options and drops duplicates", () => {
|
||||
expect(parseFacetList("privatperson,unfug,privatperson,oeffentlich", PROJECT_CUSTOMER_TYPES)).toEqual([
|
||||
"privatperson",
|
||||
"oeffentlich",
|
||||
]);
|
||||
});
|
||||
|
||||
it("treats a missing or empty parameter as no selection", () => {
|
||||
expect(parseFacetList(null, PROJECT_VALUE_BANDS)).toEqual([]);
|
||||
expect(parseFacetList("", PROJECT_VALUE_BANDS)).toEqual([]);
|
||||
});
|
||||
|
||||
it("takes the first period key only", () => {
|
||||
expect(parsePeriodKey("month,week")).toBe("month");
|
||||
expect(parsePeriodKey("quartal")).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps arbitrary owner ids but drops blanks", () => {
|
||||
expect(parseOwnerList("u1, ,u2,u1")).toEqual(["u1", "u2"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolvePeriodRange", () => {
|
||||
// Wednesday, 2026-07-29.
|
||||
const now = new Date(2026, 6, 29, 14, 30);
|
||||
|
||||
it("spans Monday to Sunday for the current week", () => {
|
||||
const range = resolvePeriodRange("week", now)!;
|
||||
expect(range.from.getDate()).toBe(27);
|
||||
expect(range.to.getDate()).toBe(2); // Sunday, already in August
|
||||
expect(range.to.getMonth()).toBe(7);
|
||||
});
|
||||
|
||||
it("spans the first to the last day of the current month", () => {
|
||||
const range = resolvePeriodRange("month", now)!;
|
||||
expect(range.from.getDate()).toBe(1);
|
||||
expect(range.to.getDate()).toBe(31);
|
||||
});
|
||||
|
||||
it("spans today plus 30 days", () => {
|
||||
const range = resolvePeriodRange("next30", now)!;
|
||||
expect(range.from.getDate()).toBe(29);
|
||||
expect(range.to.getMonth()).toBe(7);
|
||||
expect(range.to.getDate()).toBe(28);
|
||||
});
|
||||
|
||||
it("refuses a half-open or inverted custom range instead of inventing an end", () => {
|
||||
expect(resolvePeriodRange("custom", now, { from: "2026-07-01", to: null })).toBeNull();
|
||||
expect(resolvePeriodRange("custom", now, { from: "2026-08-01", to: "2026-07-01" })).toBeNull();
|
||||
expect(resolvePeriodRange("custom", now, { from: "nonsense", to: "2026-07-01" })).toBeNull();
|
||||
});
|
||||
|
||||
it("accepts a well-formed custom range and closes it at end of day", () => {
|
||||
const range = resolvePeriodRange("custom", now, { from: "2026-07-01", to: "2026-07-15" })!;
|
||||
expect(range.from.getDate()).toBe(1);
|
||||
expect(range.to.getDate()).toBe(15);
|
||||
expect(range.to.getHours()).toBe(23);
|
||||
});
|
||||
|
||||
it("is no filter without a period", () => {
|
||||
expect(resolvePeriodRange(null, now)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildPeriodWhere", () => {
|
||||
it("matches projects that start, end or span the range, and no undated ones", () => {
|
||||
const where = buildPeriodWhere({ from: new Date(2026, 6, 1), to: new Date(2026, 6, 31) });
|
||||
const alternatives = where.OR as Record<string, unknown>[];
|
||||
expect(alternatives).toHaveLength(3);
|
||||
expect(alternatives[0]).toHaveProperty("startDatum");
|
||||
expect(alternatives[1]).toHaveProperty("deadline");
|
||||
// No alternative admits a project without both dates.
|
||||
expect(JSON.stringify(alternatives)).not.toContain("null");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildValueBandWhere", () => {
|
||||
it("is no filter without a band", () => {
|
||||
expect(buildValueBandWhere([])).toBeNull();
|
||||
});
|
||||
|
||||
it("uses the confirmed volume and falls back to the estimate, like the card", () => {
|
||||
const where = buildValueBandWhere(["10k_30k"])!;
|
||||
const [band] = where.OR as Record<string, unknown>[];
|
||||
const [confirmed, fallback] = (band!.OR as Record<string, any>[]);
|
||||
expect(confirmed!.auftragsvolumen).toEqual({ gte: 10_000, lt: 30_000 });
|
||||
expect(fallback!.AND[0]).toEqual({ auftragsvolumen: null });
|
||||
expect(fallback!.AND[1]).toEqual({ potenziellerAuftragswert: { gte: 10_000, lt: 30_000 } });
|
||||
});
|
||||
|
||||
it("leaves the top band open-ended", () => {
|
||||
const where = buildValueBandWhere(["ueber60k"])!;
|
||||
const [band] = where.OR as Record<string, unknown>[];
|
||||
const [confirmed] = (band!.OR as Record<string, any>[]);
|
||||
expect(confirmed!.auftragsvolumen).toEqual({ gte: 60_000 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildOwnerWhere", () => {
|
||||
it("is no filter without a selection", () => {
|
||||
expect(buildOwnerWhere([])).toBeNull();
|
||||
});
|
||||
|
||||
it("uses a plain predicate for ids only", () => {
|
||||
expect(buildOwnerWhere(["u1", "u2"])).toEqual({ zustaendigePersonId: { in: ["u1", "u2"] } });
|
||||
});
|
||||
|
||||
it("adds the unassigned bucket as an alternative, not as an id", () => {
|
||||
const where = buildOwnerWhere(["u1", UNASSIGNED_OWNER]) as Record<string, any>;
|
||||
expect(where.OR).toEqual([{ zustaendigePersonId: { in: ["u1"] } }, { zustaendigePersonId: null }]);
|
||||
});
|
||||
|
||||
it("matches only unassigned projects when that is the sole option", () => {
|
||||
expect(buildOwnerWhere([UNASSIGNED_OWNER])).toEqual({ zustaendigePersonId: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolvePeriodRanges", () => {
|
||||
const now = new Date("2026-07-15T12:00:00.000Z");
|
||||
|
||||
it("returns null when nothing is selected", () => {
|
||||
expect(resolvePeriodRanges([], now)).toBeNull();
|
||||
expect(resolvePeriodRanges(undefined, now)).toBeNull();
|
||||
});
|
||||
|
||||
it("matches the single resolver for one period", () => {
|
||||
expect(resolvePeriodRanges(["month"], now)).toEqual(resolvePeriodRange("month", now));
|
||||
});
|
||||
|
||||
it("unions several periods into the widest range", () => {
|
||||
// "this week" sits inside July, "next 30 days" reaches into August: the union
|
||||
// has to start at the earlier bound and end at the later one.
|
||||
const union = resolvePeriodRanges(["week", "next30"], now);
|
||||
const week = resolvePeriodRange("week", now);
|
||||
const next30 = resolvePeriodRange("next30", now);
|
||||
expect(union?.from.getTime()).toBe(Math.min(week!.from.getTime(), next30!.from.getTime()));
|
||||
expect(union?.to.getTime()).toBe(Math.max(week!.to.getTime(), next30!.to.getTime()));
|
||||
});
|
||||
|
||||
it("ignores a half-open custom range instead of widening to infinity", () => {
|
||||
const union = resolvePeriodRanges(["week", "custom"], now, { from: "2026-07-01", to: null });
|
||||
expect(union).toEqual(resolvePeriodRange("week", now));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
// WF-P8 S01 — the pure half of the board filter facets.
|
||||
//
|
||||
// Parses the facet query parameters and turns them into Prisma `where`
|
||||
// fragments. Deliberately free of server imports so the date and money maths
|
||||
// can be unit-tested without a database: the only impure facet (customer type,
|
||||
// which has to resolve contacts first) stays in projectService.server.ts.
|
||||
|
||||
/** Sentinel option of the "Sachbearbeiter" facet: projects with no assignee. */
|
||||
export const UNASSIGNED_OWNER = "none";
|
||||
|
||||
/**
|
||||
* Customer type of a project, read off its primary contact.
|
||||
*
|
||||
* Davids export lists four options and all four are offered, each with its own
|
||||
* meaning in our model (`KontaktTyp` plus `OrgMerkmal`):
|
||||
*
|
||||
* privatperson – kontaktTyp = privatperson
|
||||
* organisation – every organisation, whatever its legal form (the superset)
|
||||
* unternehmen – organisations with a commercial legal form (gmbh, kg)
|
||||
* oeffentlich – organisations marked as a public body
|
||||
*
|
||||
* "Organisation" being the parent of the other two is the point, not a mistake:
|
||||
* it answers "any organisation" without picking a legal form. Selecting several
|
||||
* behaves like every other facet — the union of their rows.
|
||||
*/
|
||||
export const PROJECT_CUSTOMER_TYPES = ["privatperson", "organisation", "unternehmen", "oeffentlich"] as const;
|
||||
export type ProjectCustomerType = (typeof PROJECT_CUSTOMER_TYPES)[number];
|
||||
|
||||
export const PROJECT_PERIOD_KEYS = ["week", "month", "next30", "custom"] as const;
|
||||
export type ProjectPeriodKey = (typeof PROJECT_PERIOD_KEYS)[number];
|
||||
|
||||
export const PROJECT_VALUE_BANDS = ["bis10k", "10k_30k", "30k_60k", "ueber60k"] as const;
|
||||
export type ProjectValueBand = (typeof PROJECT_VALUE_BANDS)[number];
|
||||
|
||||
/** Lower bound (inclusive) and upper bound (exclusive) of a value band, in €. */
|
||||
const VALUE_BAND_RANGE: Record<ProjectValueBand, { min: number; max: number | null }> = {
|
||||
bis10k: { min: 0, max: 10_000 },
|
||||
"10k_30k": { min: 10_000, max: 30_000 },
|
||||
"30k_60k": { min: 30_000, max: 60_000 },
|
||||
ueber60k: { min: 60_000, max: null },
|
||||
};
|
||||
|
||||
export type ProjectFacetFilters = {
|
||||
/** User ids, plus `UNASSIGNED_OWNER` for projects without an assignee. */
|
||||
owners?: readonly string[];
|
||||
customerTypes?: readonly ProjectCustomerType[];
|
||||
/**
|
||||
* Ids from the tenant `Tag` catalogue. Free-form like the owner list, since a
|
||||
* tag catalogue is tenant data and not a closed set of keys.
|
||||
*/
|
||||
tagIds?: readonly string[];
|
||||
/** Selected periods; several are unioned (see resolvePeriodRanges). */
|
||||
periods?: readonly ProjectPeriodKey[];
|
||||
/** Only meaningful when "custom" is among the periods; ISO date (YYYY-MM-DD). */
|
||||
periodFrom?: string | null;
|
||||
periodTo?: string | null;
|
||||
valueBands?: readonly ProjectValueBand[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Split a comma-separated query parameter and keep only the known options.
|
||||
* Unknown values are dropped rather than rejected — a stale bookmark should
|
||||
* narrow the board, never 500 it.
|
||||
*/
|
||||
export function parseFacetList<T extends string>(raw: string | null | undefined, allowed: readonly T[]): T[] {
|
||||
if (!raw) return [];
|
||||
const allowedSet = new Set<string>(allowed);
|
||||
const seen = new Set<T>();
|
||||
for (const part of raw.split(",")) {
|
||||
const value = part.trim();
|
||||
if (allowedSet.has(value)) seen.add(value as T);
|
||||
}
|
||||
return [...seen];
|
||||
}
|
||||
|
||||
/** Same, but for the free-form owner list (ids are not a closed set). */
|
||||
export function parseOwnerList(raw: string | null | undefined): string[] {
|
||||
if (!raw) return [];
|
||||
const seen = new Set<string>();
|
||||
for (const part of raw.split(",")) {
|
||||
const value = part.trim();
|
||||
if (value) seen.add(value);
|
||||
}
|
||||
return [...seen];
|
||||
}
|
||||
|
||||
/** Every selected period; the where-builder unions them. */
|
||||
export function parsePeriodList(raw: string | null | undefined): ProjectPeriodKey[] {
|
||||
return parseFacetList(raw, PROJECT_PERIOD_KEYS);
|
||||
}
|
||||
|
||||
export function parsePeriodKey(raw: string | null | undefined): ProjectPeriodKey | null {
|
||||
const [key] = parseFacetList(raw, PROJECT_PERIOD_KEYS);
|
||||
return key ?? null;
|
||||
}
|
||||
|
||||
/** Midnight-anchored day boundary in the server's timezone. */
|
||||
function startOfDay(date: Date): Date {
|
||||
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
||||
}
|
||||
|
||||
function endOfDay(date: Date): Date {
|
||||
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59, 999);
|
||||
}
|
||||
|
||||
function parseIsoDate(value: string | null | undefined): Date | null {
|
||||
if (!value) return null;
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})$/u.exec(value.trim());
|
||||
if (!match) return null;
|
||||
const date = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]));
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve several selected periods into the one range that covers them all.
|
||||
*
|
||||
* Davids dropdown offers checkboxes, so several periods can be picked. A project
|
||||
* sits inside a range or it does not, so the union of the selected ranges is the
|
||||
* only reading that makes sense — earliest start to latest end. The chips name
|
||||
* every selected period, so the widening stays visible instead of being implied
|
||||
* by a single collapsed label.
|
||||
*/
|
||||
export function resolvePeriodRanges(
|
||||
periods: readonly ProjectPeriodKey[] | null | undefined,
|
||||
now: Date,
|
||||
custom?: { from?: string | null; to?: string | null }
|
||||
): { from: Date; to: Date } | null {
|
||||
const ranges = (periods ?? []).flatMap((period) => {
|
||||
const range = resolvePeriodRange(period, now, custom);
|
||||
return range ? [range] : [];
|
||||
});
|
||||
if (ranges.length === 0) return null;
|
||||
return ranges.reduce((widest, range) => ({
|
||||
from: range.from < widest.from ? range.from : widest.from,
|
||||
to: range.to > widest.to ? range.to : widest.to,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a period option into a concrete range. Weeks start on Monday (the
|
||||
* calendar convention of every locale this product ships in).
|
||||
*/
|
||||
export function resolvePeriodRange(
|
||||
period: ProjectPeriodKey | null | undefined,
|
||||
now: Date,
|
||||
custom?: { from?: string | null; to?: string | null }
|
||||
): { from: Date; to: Date } | null {
|
||||
switch (period) {
|
||||
case "week": {
|
||||
const weekday = (now.getDay() + 6) % 7; // Monday = 0
|
||||
const monday = startOfDay(new Date(now.getFullYear(), now.getMonth(), now.getDate() - weekday));
|
||||
return { from: monday, to: endOfDay(new Date(monday.getFullYear(), monday.getMonth(), monday.getDate() + 6)) };
|
||||
}
|
||||
case "month": {
|
||||
const first = new Date(now.getFullYear(), now.getMonth(), 1);
|
||||
return { from: first, to: endOfDay(new Date(now.getFullYear(), now.getMonth() + 1, 0)) };
|
||||
}
|
||||
case "next30":
|
||||
return { from: startOfDay(now), to: endOfDay(new Date(now.getFullYear(), now.getMonth(), now.getDate() + 30)) };
|
||||
case "custom": {
|
||||
const from = parseIsoDate(custom?.from);
|
||||
const to = parseIsoDate(custom?.to);
|
||||
// A half-open custom range is not a range — treat it as "no filter"
|
||||
// instead of silently inventing the missing end.
|
||||
if (!from || !to || from > to) return null;
|
||||
return { from, to: endOfDay(to) };
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Projects whose runtime overlaps the range.
|
||||
*
|
||||
* A project counts as "in the period" when its start or its deadline falls
|
||||
* inside the range, or when it spans the whole range. Projects that carry
|
||||
* neither date are excluded on purpose: a date filter that keeps undated rows
|
||||
* would make the facet look broken.
|
||||
*/
|
||||
export function buildPeriodWhere(range: { from: Date; to: Date }): Record<string, unknown> {
|
||||
return {
|
||||
OR: [
|
||||
{ startDatum: { gte: range.from, lte: range.to } },
|
||||
{ deadline: { gte: range.from, lte: range.to } },
|
||||
{ AND: [{ startDatum: { lte: range.from } }, { deadline: { gte: range.to } }] },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Projects whose value falls into any of the selected bands.
|
||||
*
|
||||
* The board shows `auftragsvolumen` and falls back to
|
||||
* `potenziellerAuftragswert`; the filter has to use the same source, which
|
||||
* Prisma cannot express as a COALESCE in `where` — hence the explicit
|
||||
* "confirmed volume, or no confirmed volume and a matching estimate" pair.
|
||||
*/
|
||||
export function buildValueBandWhere(bands: readonly ProjectValueBand[]): Record<string, unknown> | null {
|
||||
if (bands.length === 0) return null;
|
||||
return {
|
||||
OR: bands.map((band) => {
|
||||
const { min, max } = VALUE_BAND_RANGE[band];
|
||||
const range = max == null ? { gte: min } : { gte: min, lt: max };
|
||||
return {
|
||||
OR: [{ auftragsvolumen: range }, { AND: [{ auftragsvolumen: null }, { potenziellerAuftragswert: range }] }],
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Assignee facet, including the "no assignee" sentinel. */
|
||||
export function buildOwnerWhere(owners: readonly string[]): Record<string, unknown> | null {
|
||||
if (owners.length === 0) return null;
|
||||
const userIds = owners.filter((owner) => owner !== UNASSIGNED_OWNER);
|
||||
const alternatives: Record<string, unknown>[] = [];
|
||||
if (userIds.length > 0) alternatives.push({ zustaendigePersonId: { in: userIds } });
|
||||
if (owners.includes(UNASSIGNED_OWNER)) alternatives.push({ zustaendigePersonId: null });
|
||||
return alternatives.length === 1 ? alternatives[0]! : { OR: alternatives };
|
||||
}
|
||||
+39
-16
@@ -8,10 +8,49 @@ export function projectDetailPath(tenantSlug: string, projectId: string): string
|
||||
return `/${tenantSlug}/projects/${projectId}`;
|
||||
}
|
||||
|
||||
/** WF-P8 S02 contact search (loader-only JSON resource of one project). */
|
||||
export function projectContactSearchPath(tenantSlug: string, projectId: string): string {
|
||||
return `/${tenantSlug}/projects/${projectId}/contact-search`;
|
||||
}
|
||||
|
||||
export function projectsListPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/projects/list`;
|
||||
}
|
||||
|
||||
export function projectsBoardsPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/projects/boards`;
|
||||
}
|
||||
|
||||
export function projectsExportPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/projects/export`;
|
||||
}
|
||||
|
||||
export function projectPipelinesAdminPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/admin/pipelines`;
|
||||
}
|
||||
|
||||
/** WF-P8 S04 — settings of one board (columns, access, successor). */
|
||||
export function projectBoardSettingsPath(tenantSlug: string, pipelineId: string): string {
|
||||
return `${projectPipelinesAdminPath(tenantSlug)}/${pipelineId}`;
|
||||
}
|
||||
|
||||
/** WF-P8 S05 — detail-template config of one board. */
|
||||
export function projectPipelineFieldsAdminPath(tenantSlug: string, pipelineId: string): string {
|
||||
return `${projectPipelinesAdminPath(tenantSlug)}/${pipelineId}/fields`;
|
||||
}
|
||||
|
||||
export function projectLostReasonsAdminPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/admin/pipelines/lost-reasons`;
|
||||
}
|
||||
|
||||
export function projectAcceptanceFormsAdminPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/admin/projects/acceptance-forms`;
|
||||
}
|
||||
|
||||
export function projectTemplatesAdminPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/admin/projects/templates`;
|
||||
}
|
||||
|
||||
export function projectPipelinePath(tenantSlug: string, pipelineId: string): string {
|
||||
return `/${tenantSlug}/projects/pipelines/${pipelineId}`;
|
||||
}
|
||||
@@ -31,19 +70,3 @@ export function projectAcceptancePath(tenantSlug: string, projectId: string): st
|
||||
export function projectAcceptanceNewPath(tenantSlug: string, projectId: string): string {
|
||||
return `/${tenantSlug}/projects/${projectId}/acceptance/new`;
|
||||
}
|
||||
|
||||
export function pipelinesAdminPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/admin/pipelines`;
|
||||
}
|
||||
|
||||
export function lostReasonsAdminPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/admin/pipelines/lost-reasons`;
|
||||
}
|
||||
|
||||
export function acceptanceFormsAdminPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/admin/projects/acceptance-forms`;
|
||||
}
|
||||
|
||||
export function projectTemplatesAdminPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/admin/projects/templates`;
|
||||
}
|
||||
+315
@@ -0,0 +1,315 @@
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
withTenantRLS: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: mocks.withTenantRLS,
|
||||
}));
|
||||
|
||||
import {
|
||||
exportProjectListCsv,
|
||||
filterAggregateReadablePipelineIdsWithTx,
|
||||
normalizeProjectListPage,
|
||||
ownerScopeWhere,
|
||||
projectEditScopeWhere,
|
||||
projectReadScopeWhere,
|
||||
PROJECT_CSV_EXPORT_MAX_ROWS,
|
||||
} from "./projectService.server";
|
||||
|
||||
type ProjectFixture = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
pipelineId: string;
|
||||
stageId: string;
|
||||
projektNummer: string;
|
||||
projektname: string;
|
||||
potenziellerAuftragswert: string | null;
|
||||
auftragsvolumen: string | null;
|
||||
zustaendigePersonId: string | null;
|
||||
projektleiterId: string | null;
|
||||
updatedAt: Date;
|
||||
pipeline: { id: string; name: string };
|
||||
stage: { id: string; name: string };
|
||||
};
|
||||
|
||||
function projectFixture(index: number, overrides: Partial<ProjectFixture> = {}): ProjectFixture {
|
||||
const ordinal = String(index + 1).padStart(4, "0");
|
||||
return {
|
||||
id: `project-${ordinal}`,
|
||||
tenantId: "tenant-1",
|
||||
pipelineId: "pipeline-1",
|
||||
stageId: "stage-1",
|
||||
projektNummer: `HG-${ordinal}`,
|
||||
projektname: `Projekt ${ordinal}`,
|
||||
potenziellerAuftragswert: null,
|
||||
auftragsvolumen: `${index + 1}.00`,
|
||||
zustaendigePersonId: "owner-1",
|
||||
projektleiterId: "manager-1",
|
||||
updatedAt: new Date("2026-07-13T12:00:00.000Z"),
|
||||
pipeline: { id: "pipeline-1", name: "Vertrieb" },
|
||||
stage: { id: "stage-1", name: "Neu" },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function installTenantTransaction(projects: readonly ProjectFixture[]) {
|
||||
const findMany = vi.fn().mockResolvedValue(projects);
|
||||
const pipelineFieldConfigFindMany = vi.fn().mockResolvedValue([]);
|
||||
const tx = {
|
||||
projekt: { findMany },
|
||||
pipelineFieldConfig: { findMany: pipelineFieldConfigFindMany },
|
||||
};
|
||||
mocks.withTenantRLS.mockImplementation(async (_tenantId: string, callback: (client: typeof tx) => Promise<unknown>) => callback(tx));
|
||||
return { findMany, pipelineFieldConfigFindMany };
|
||||
}
|
||||
|
||||
const context = {
|
||||
userId: "user-1",
|
||||
permissions: ["projects.read_all", "deals.read_volume_all"],
|
||||
roleIds: ["role-1"],
|
||||
groupIds: ["group-1"],
|
||||
};
|
||||
|
||||
describe("project CSV export", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("exports all 537 matching projects without applying the table pagination clamp", async () => {
|
||||
const projects = Array.from({ length: 537 }, (_, index) => projectFixture(index));
|
||||
const { findMany, pipelineFieldConfigFindMany } = installTenantTransaction(projects);
|
||||
|
||||
const csv = await exportProjectListCsv({ tenantId: "tenant-1", ctx: context });
|
||||
|
||||
expect(mocks.withTenantRLS).toHaveBeenCalledWith("tenant-1", expect.any(Function));
|
||||
expect(findMany).toHaveBeenCalledOnce();
|
||||
expect(findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
tenantId: "tenant-1",
|
||||
archivedAt: null,
|
||||
isDemoData: false,
|
||||
pipeline: {
|
||||
accessRules: {
|
||||
none: {
|
||||
tenantId: "tenant-1",
|
||||
kannSehen: false,
|
||||
OR: [
|
||||
{ principalType: "user", principalId: "user-1" },
|
||||
{ principalType: "role", principalId: "role-1" },
|
||||
{ principalType: "group", principalId: "group-1" },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
select: expect.objectContaining({
|
||||
id: true,
|
||||
projektNummer: true,
|
||||
pipeline: { select: { name: true } },
|
||||
stage: { select: { name: true } },
|
||||
}),
|
||||
orderBy: { updatedAt: "desc" },
|
||||
take: PROJECT_CSV_EXPORT_MAX_ROWS + 1,
|
||||
});
|
||||
expect(pipelineFieldConfigFindMany).toHaveBeenCalledOnce();
|
||||
|
||||
const lines = csv.trimEnd().split("\n");
|
||||
expect(lines).toHaveLength(538);
|
||||
expect(lines[1]).toContain('"HG-0001"');
|
||||
expect(lines.at(-1)).toContain('"HG-0537"');
|
||||
});
|
||||
|
||||
test("neutralizes spreadsheet formulas in every user-controlled CSV cell", async () => {
|
||||
installTenantTransaction([
|
||||
projectFixture(0, {
|
||||
projektNummer: "+SUM(1,1)",
|
||||
projektname: '=HYPERLINK("https://evil.example","click")',
|
||||
auftragsvolumen: "-5",
|
||||
zustaendigePersonId: "@OWNER",
|
||||
pipeline: { id: "pipeline-1", name: "\t=CMD()" },
|
||||
stage: { id: "stage-1", name: " -1+2" },
|
||||
}),
|
||||
]);
|
||||
|
||||
const csv = await exportProjectListCsv({ tenantId: "tenant-1", ctx: context });
|
||||
const row = csv.trimEnd().split("\n")[1];
|
||||
|
||||
expect(row).toContain('"\'+SUM(1,1)"');
|
||||
expect(row).toContain('"\'=HYPERLINK(""https://evil.example"",""click"")"');
|
||||
expect(row).toContain('"\'\t=CMD()"');
|
||||
expect(row).toContain('"\' -1+2"');
|
||||
expect(row).toContain('"\'-5.00"');
|
||||
expect(row).toContain('"\'@OWNER"');
|
||||
expect(row).toContain('"2026-07-13T12:00:00.000Z"');
|
||||
});
|
||||
|
||||
test("hides both monetary columns when the potential-value field is denied", async () => {
|
||||
const { pipelineFieldConfigFindMany } = installTenantTransaction([
|
||||
projectFixture(0, { potenziellerAuftragswert: "95000", auftragsvolumen: null }),
|
||||
]);
|
||||
pipelineFieldConfigFindMany.mockResolvedValue([
|
||||
{
|
||||
pipelineId: "pipeline-1",
|
||||
stageId: "stage-1",
|
||||
fieldKey: "potenziellerAuftragswert",
|
||||
sichtbar: false,
|
||||
visibilities: [],
|
||||
},
|
||||
]);
|
||||
|
||||
const csv = await exportProjectListCsv({ tenantId: "tenant-1", ctx: context });
|
||||
|
||||
expect(csv.trimEnd().split("\n")[1]).toContain('"—"');
|
||||
expect(csv).not.toContain("95000.00");
|
||||
});
|
||||
|
||||
test("keeps volume fields hidden when duplicate legacy configs contain an explicit deny", async () => {
|
||||
const { pipelineFieldConfigFindMany } = installTenantTransaction([
|
||||
projectFixture(0, { potenziellerAuftragswert: "95000", auftragsvolumen: null }),
|
||||
]);
|
||||
pipelineFieldConfigFindMany.mockResolvedValue([
|
||||
{
|
||||
pipelineId: "pipeline-1",
|
||||
stageId: "stage-1",
|
||||
fieldKey: "potenziellerAuftragswert",
|
||||
sichtbar: true,
|
||||
visibilities: [{ kannSehen: true, kannBearbeiten: true }],
|
||||
},
|
||||
{
|
||||
pipelineId: "pipeline-1",
|
||||
stageId: "stage-1",
|
||||
fieldKey: "potenziellerAuftragswert",
|
||||
sichtbar: true,
|
||||
visibilities: [{ kannSehen: false, kannBearbeiten: false }],
|
||||
},
|
||||
]);
|
||||
|
||||
const csv = await exportProjectListCsv({ tenantId: "tenant-1", ctx: context });
|
||||
|
||||
expect(csv.trimEnd().split("\n")[1]).toContain('"—"');
|
||||
expect(csv).not.toContain("95000.00");
|
||||
});
|
||||
|
||||
test("rejects an unbounded export before building field-visibility rows", async () => {
|
||||
const projects = Array.from({ length: PROJECT_CSV_EXPORT_MAX_ROWS + 1 }, (_, index) => projectFixture(index));
|
||||
const { pipelineFieldConfigFindMany } = installTenantTransaction(projects);
|
||||
|
||||
await expect(exportProjectListCsv({ tenantId: "tenant-1", ctx: context })).rejects.toMatchObject({
|
||||
messageKey: "projects.error.exportTooLarge",
|
||||
});
|
||||
expect(pipelineFieldConfigFindMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("keeps owner and pipeline scopes when a search query adds another AND clause", async () => {
|
||||
const { findMany } = installTenantTransaction([]);
|
||||
await exportProjectListCsv({
|
||||
tenantId: "tenant-1",
|
||||
ctx: { userId: "user-1", permissions: ["projects.read_own"], roleIds: [], groupIds: [] },
|
||||
filters: { q: "Dach" },
|
||||
});
|
||||
|
||||
const where = findMany.mock.calls[0]![0].where;
|
||||
expect(where.AND).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ OR: [{ zustaendigePersonId: "user-1" }] },
|
||||
expect.objectContaining({ pipeline: expect.any(Object) }),
|
||||
{ OR: [{ projektname: { contains: "Dach", mode: "insensitive" } }, { projektNummer: { contains: "Dach", mode: "insensitive" } }] },
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("project list visibility helpers", () => {
|
||||
test("keeps owner, project-lead, and membership scopes additive without broadening", () => {
|
||||
expect(ownerScopeWhere("tenant-1", { userId: "user-1", permissions: ["projects.read_own"] })).toEqual({
|
||||
OR: [{ zustaendigePersonId: "user-1" }],
|
||||
});
|
||||
expect(ownerScopeWhere("tenant-1", { userId: "user-1", permissions: ["projects.read_own_pl"] })).toEqual({
|
||||
OR: [{ projektleiterId: "user-1" }],
|
||||
});
|
||||
expect(
|
||||
ownerScopeWhere("tenant-1", {
|
||||
userId: "user-1",
|
||||
permissions: ["projects.read_own_member"],
|
||||
groupIds: ["group-1"],
|
||||
}),
|
||||
).toEqual({
|
||||
OR: [
|
||||
{
|
||||
mitglieder: {
|
||||
some: {
|
||||
tenantId: "tenant-1",
|
||||
archivedAt: null,
|
||||
OR: [{ userId: "user-1" }, { groupId: { in: ["group-1"] } }],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(ownerScopeWhere("tenant-1", { userId: "user-1", permissions: [] })).toEqual({ id: { in: [] } });
|
||||
expect(ownerScopeWhere("tenant-1", { userId: "user-1", permissions: ["projects.read_all"] })).toEqual({});
|
||||
});
|
||||
|
||||
test("resolves aggregate field visibility in one query with explicit deny precedence", async () => {
|
||||
const findMany = vi.fn().mockResolvedValue([
|
||||
{
|
||||
pipelineId: "pipeline-1",
|
||||
sichtbar: true,
|
||||
visibilities: [{ kannSehen: true }],
|
||||
},
|
||||
{
|
||||
pipelineId: "pipeline-1",
|
||||
sichtbar: true,
|
||||
visibilities: [{ kannSehen: false }],
|
||||
},
|
||||
{
|
||||
pipelineId: "pipeline-2",
|
||||
sichtbar: true,
|
||||
visibilities: [],
|
||||
},
|
||||
]);
|
||||
|
||||
await expect(
|
||||
filterAggregateReadablePipelineIdsWithTx(
|
||||
{ pipelineFieldConfig: { findMany } } as never,
|
||||
{
|
||||
tenantId: "tenant-1",
|
||||
pipelineIds: ["pipeline-1", "pipeline-2", "pipeline-2"],
|
||||
ctx: context,
|
||||
backstopPermissions: ["deals.read_volume_all"],
|
||||
},
|
||||
),
|
||||
).resolves.toEqual(["pipeline-2"]);
|
||||
expect(findMany).toHaveBeenCalledOnce();
|
||||
expect(findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({
|
||||
tenantId: "tenant-1",
|
||||
pipelineId: { in: ["pipeline-1", "pipeline-2"] },
|
||||
fieldKey: "aggregate:forecast",
|
||||
stageId: null,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test("normalizes invalid and abusive page values", () => {
|
||||
expect(normalizeProjectListPage("foo")).toBe(1);
|
||||
expect(normalizeProjectListPage(Number.POSITIVE_INFINITY)).toBe(1);
|
||||
expect(normalizeProjectListPage(-5)).toBe(1);
|
||||
expect(normalizeProjectListPage("2")).toBe(2);
|
||||
expect(normalizeProjectListPage(999_999)).toBe(10_000);
|
||||
});
|
||||
|
||||
test("keeps project access scopes inside AND so they cannot replace a concrete project id", () => {
|
||||
const ctx = { userId: "user-1", permissions: [] as string[] };
|
||||
expect(projectReadScopeWhere("tenant-1", ctx)).toMatchObject({
|
||||
AND: [{ id: { in: [] } }, { pipeline: expect.any(Object) }],
|
||||
});
|
||||
expect(projectEditScopeWhere("tenant-1", ctx)).toMatchObject({
|
||||
AND: [{ id: { in: [] } }, { pipeline: expect.any(Object) }],
|
||||
});
|
||||
});
|
||||
});
|
||||
+3050
-228
File diff suppressed because it is too large.
Load diff
+533
@@ -0,0 +1,533 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
+281
-43
@@ -1,4 +1,4 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { resolveRepoPath } from "~/utils/testing/repoPaths";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { ProjectServiceError, validatePipelineStages } from "./projectService.server";
|
||||
@@ -10,7 +10,7 @@ describe("project pipeline validation", () => {
|
||||
{ name: "Neu", stageKind: "offen" },
|
||||
{ name: "Gewonnen", stageKind: "gewonnen" },
|
||||
{ name: "Verloren", stageKind: "verloren" },
|
||||
]),
|
||||
])
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
@@ -19,7 +19,7 @@ describe("project pipeline validation", () => {
|
||||
validatePipelineStages([
|
||||
{ name: "Neu", stageKind: "offen" },
|
||||
{ name: "Verloren", stageKind: "verloren" },
|
||||
]),
|
||||
])
|
||||
).toThrow(ProjectServiceError);
|
||||
});
|
||||
|
||||
@@ -28,7 +28,7 @@ describe("project pipeline validation", () => {
|
||||
validatePipelineStages([
|
||||
{ name: "Neu", stageKind: "offen" },
|
||||
{ name: "Gewonnen", stageKind: "gewonnen" },
|
||||
]),
|
||||
])
|
||||
).toThrow(ProjectServiceError);
|
||||
});
|
||||
});
|
||||
@@ -88,14 +88,26 @@ describe("R-P8a project backend artifacts", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("gates pipeline admin actions through the projects admin permission", () => {
|
||||
const pipelineRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/admin.pipelines._index.tsx"), "utf8");
|
||||
test("gates the restored pipeline admin routes through the projects admin permission", () => {
|
||||
const service = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/projectService.server.ts"), "utf8");
|
||||
// WF-P8 split the board admin into the S07 table and the S04 settings page.
|
||||
// Both forward to the shared action module, so the intents are asserted
|
||||
// there while the permission gate stays asserted per route - a route that
|
||||
// forgot its gate could otherwise reach the intents unguarded.
|
||||
const boardsRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/admin.pipelines._index.tsx"), "utf8");
|
||||
const boardSettingsRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/admin.pipelines.$pipelineId._index.tsx"), "utf8");
|
||||
const adminAction = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/pipelineAdminAction.server.ts"), "utf8");
|
||||
const lostReasonsRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/admin.pipelines.lost-reasons.tsx"), "utf8");
|
||||
expect(pipelineRoute).toContain('"projects.admin"');
|
||||
expect(pipelineRoute).toContain('intent === "duplicatePipeline"');
|
||||
expect(pipelineRoute).toContain('intent === "upsertFieldVisibility"');
|
||||
expect(service).toContain("export async function duplicatePipeline");
|
||||
expect(service).toContain("export async function upsertPipelineFieldVisibility");
|
||||
expect(service).toContain("export async function upsertLostReason");
|
||||
expect(service).toContain("export async function archiveLostReason");
|
||||
expect(boardsRoute).toContain('"projects.admin"');
|
||||
expect(boardsRoute).toContain("handlePipelineAdminAction");
|
||||
expect(boardSettingsRoute).toContain('"projects.admin"');
|
||||
expect(boardSettingsRoute).toContain("handlePipelineAdminAction");
|
||||
expect(adminAction).toContain('intent === "upsertFieldVisibility"');
|
||||
expect(lostReasonsRoute).toContain('"projects.admin"');
|
||||
expect(lostReasonsRoute).toContain('intent === "upsertLostReason"');
|
||||
expect(lostReasonsRoute).toContain('intent === "archiveLostReason"');
|
||||
});
|
||||
|
||||
@@ -135,20 +147,131 @@ describe("R-P8b project board and forecast backend artifacts", () => {
|
||||
expect(service).toContain("deals.read_aggregates");
|
||||
});
|
||||
|
||||
test("batches project-volume visibility instead of querying once per card", () => {
|
||||
const service = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/projectService.server.ts"), "utf8");
|
||||
expect(service).toContain("loadProjectVolumeVisibilityPolicyWithTx");
|
||||
expect(service).toContain("pipelineFieldConfig.findMany");
|
||||
expect(service).toContain("canViewProjectVolumeFromPolicy(project, input.ctx, volumePolicy)");
|
||||
expect(service).not.toMatch(/for \(const project of projectsByStage[\s\S]{0,180}await canViewProjectVolumeWithTx/);
|
||||
});
|
||||
|
||||
test("keeps project-board GET loading read-only and selects only a visible fallback pipeline", () => {
|
||||
const service = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/projectService.server.ts"), "utf8");
|
||||
const boardLoader = service.split("export async function loadProjectBoard")[1]!.split("type ProjectListDbRow")[0]!;
|
||||
expect(boardLoader).not.toContain("ensureDefaultSalesPipelineWithTx");
|
||||
expect(boardLoader).toContain("tx.projekt.groupBy");
|
||||
expect(boardLoader).toContain("potentialFallbackTotals");
|
||||
expect(boardLoader).not.toContain("aggregateValue +=");
|
||||
expect(boardLoader).not.toContain(".upsert(");
|
||||
expect(boardLoader).not.toContain(".create(");
|
||||
expect(boardLoader).toContain("pipelineVisibilityScopeWhere(input.tenantId, input.ctx)");
|
||||
const lostReasonLoader = service.split("export async function listLostReasons")[1]!.split("export async function upsertLostReason")[0]!;
|
||||
expect(lostReasonLoader).not.toContain("ensureDefaultLostReasonsWithTx");
|
||||
const forecastLoader = service.split("export async function getPipelineForecast")[1]!.split("export async function moveProjectStage")[0]!;
|
||||
expect(forecastLoader).not.toContain("rebuildPipelineAggregateCache");
|
||||
expect(forecastLoader).toContain("pipelineAggregateSnapshot.findMany");
|
||||
expect(forecastLoader).toContain("if (!canReadAllProjects(input.ctx))");
|
||||
const aggregateRebuild = service.split("export async function rebuildPipelineAggregateCache")[1]!.split("export async function getPipelineForecast")[0]!;
|
||||
expect(aggregateRebuild).toContain('hasPermission(input.ctx, "projects.admin")');
|
||||
// The stage conversion rate divides by the pipeline total, not by the counter
|
||||
// that is still accumulating inside the stage loop — dividing by the latter made
|
||||
// the rate depend on stage iteration order. Entrants are counted per distinct
|
||||
// project so a project moving back and forth cannot push a stage above 100%.
|
||||
expect(aggregateRebuild).toContain("stageEntrants.length / pipelineProjectCount");
|
||||
expect(aggregateRebuild).toContain('by: ["projektId"]');
|
||||
expect(aggregateRebuild).not.toContain("stageMoves / totalProjectCount");
|
||||
});
|
||||
|
||||
test("quick-create lands on the current board, not the default sales pipeline", () => {
|
||||
const service = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/projectService.server.ts"), "utf8");
|
||||
// createProjectWithTx must resolve the GIVEN pipeline's first open stage when
|
||||
// only a pipelineId is passed, and only fall back to the default pipeline when
|
||||
// no pipelineId is provided at all.
|
||||
const createProject = service.split("async function createProjectWithTx")[1]!.split("async function ")[0]!;
|
||||
expect(createProject).toMatch(/if \(pipelineId && !stageId\)/);
|
||||
expect(createProject).toContain('stageKind: "offen"');
|
||||
expect(createProject).toMatch(/else if \(!pipelineId\)[\s\S]{0,200}ensureDefaultSalesPipelineWithTx/);
|
||||
|
||||
// The board handler forwards the viewed board's pipelineId to createProject.
|
||||
const boardRoute = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/projectBoardRoute.server.ts"), "utf8");
|
||||
const createIntent = boardRoute.split("const project = await createProject({")[1]!.split("});")[0]!;
|
||||
expect(createIntent).toContain('pipelineId: str("pipelineId") || null');
|
||||
|
||||
// Both board and (pipeline-filtered) list routes send the current pipelineId.
|
||||
const boardIndex = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects._index.tsx"), "utf8");
|
||||
expect(boardIndex).toContain('post("createProject", { ...fields, pipelineId: data.pipelineId })');
|
||||
const listRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects.list.tsx"), "utf8");
|
||||
expect(listRoute).toContain('if (data.query.pipelineId) fd.set("pipelineId", data.query.pipelineId)');
|
||||
});
|
||||
|
||||
test("populates the aggregate cache after mutations and exposes owner KPIs", () => {
|
||||
const service = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/projectService.server.ts"), "utf8");
|
||||
// Owner scope rows (REQ-projekt-forecast-kpis: "KPIs pro Verantwortlichem") incl. stale-row cleanup.
|
||||
const aggregateRebuild = service.split("export async function rebuildPipelineAggregateCache")[1]!.split("export async function getPipelineForecast")[0]!;
|
||||
expect(aggregateRebuild).toContain("`owner:${ownerUserId}`");
|
||||
expect(aggregateRebuild).toContain('scopeKey: { startsWith: "owner:", notIn: ownerScopeKeys }');
|
||||
// The refresh helper is derived-data fail-open: log a structured line, never fail the write.
|
||||
expect(aggregateRebuild).toContain("export async function refreshPipelineAggregatesAfterMutation");
|
||||
expect(aggregateRebuild).toContain("project-aggregate-refresh-failed");
|
||||
// Forecast exposes the owner KPI rows; volume strings stay gated by aggregate visibility.
|
||||
const forecastLoader = service.split("export async function getPipelineForecast")[1]!.split("export async function moveProjectStage")[0]!;
|
||||
expect(forecastLoader).toContain("ownerKpis");
|
||||
expect(forecastLoader).toContain('scopeKey.startsWith("owner:")');
|
||||
// Every forecast-relevant mutation refreshes the cache after its committed transaction.
|
||||
for (const fn of [
|
||||
"moveProjectStage",
|
||||
"bulkMoveProjectStage",
|
||||
"undoLastProjectStageChange",
|
||||
"createProject",
|
||||
"createProjectFromQualifiedLead",
|
||||
"updateProjectStammdaten",
|
||||
"upsertPipelineStage",
|
||||
"archivePipelineStage",
|
||||
"archiveProject",
|
||||
"bulkArchiveProjects",
|
||||
]) {
|
||||
const section = service.split(`export async function ${fn}(`)[1]!.split("\nexport ")[0]!;
|
||||
expect(section, `${fn} must refresh the aggregate cache`).toContain("refreshPipelineAggregatesAfterMutation(");
|
||||
}
|
||||
});
|
||||
|
||||
test("routes provide board actions, list CSV, pipeline forecast, and SSE stream contracts", () => {
|
||||
// AD-28 interim UI: board loading + stage actions live in the shared board-route
|
||||
// helper; the `/projects` and pipeline routes wire that helper + the ~/ui screen.
|
||||
const boardHelper = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/projectBoardRoute.server.ts"), "utf8");
|
||||
const boardRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects._index.tsx"), "utf8");
|
||||
const listRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects.list.tsx"), "utf8");
|
||||
const exportRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects.export.tsx"), "utf8");
|
||||
const pipelineRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects.pipelines.$pipelineId.tsx"), "utf8");
|
||||
const streamRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects.pipelines.$pipelineId.stream.tsx"), "utf8");
|
||||
expect(boardRoute).toContain("loadProjectBoard");
|
||||
expect(boardRoute).toContain('intent === "moveStage"');
|
||||
expect(boardRoute).toContain('intent === "undoStage"');
|
||||
expect(boardHelper).toContain("loadProjectBoard");
|
||||
expect(boardHelper).toContain('"moveStage"');
|
||||
expect(boardHelper).toContain('"undoStage"');
|
||||
expect(boardRoute).toContain("loadKanbanData");
|
||||
expect(boardRoute).toContain("PipelineKanbanPage");
|
||||
expect(listRoute).toContain('export") === "csv"');
|
||||
expect(listRoute).toContain("text/csv; charset=utf-8");
|
||||
expect(pipelineRoute).toContain("getPipelineForecast");
|
||||
expect(listRoute).toContain("projectsExportPath");
|
||||
expect(exportRoute).toContain("exportProjectListCsv");
|
||||
expect(exportRoute).toContain("text/csv; charset=utf-8");
|
||||
// Forecast stays a service export (getPipelineForecast, asserted above) consumed as
|
||||
// P11 widgets; the interim pipeline board route wires the shared board helper.
|
||||
expect(pipelineRoute).toContain("loadKanbanData");
|
||||
expect(streamRoute).toContain("eventStream");
|
||||
expect(streamRoute).toContain("projects.board.snapshot");
|
||||
});
|
||||
|
||||
test("builds project sub-area display values in the loader", () => {
|
||||
const detailRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects.$id.tsx"), "utf8");
|
||||
const loaderSource = detailRoute.split("export async function loader")[1]!.split("function formString")[0]!;
|
||||
const componentSource = detailRoute.split("export default function ProjectDetailRoute")[1]!;
|
||||
|
||||
expect(loaderSource).toContain("buildProjectSubAreasVM(subAreas");
|
||||
expect(componentSource).not.toContain("buildProjectSubAreasVM(");
|
||||
// The "Auftrag & Ausführung" panel no longer hangs under S02, but its VM is
|
||||
// still built: the S02 rail lists the project documents it carries.
|
||||
expect(componentSource).not.toContain("<ProjectSubAreasPanel");
|
||||
expect(componentSource).toContain("data.operationsVM");
|
||||
});
|
||||
});
|
||||
|
||||
describe("R-P9a order view and project sub-area backend artifacts", () => {
|
||||
@@ -182,11 +305,18 @@ describe("R-P9a order view and project sub-area backend artifacts", () => {
|
||||
|
||||
test("keeps all order sub-area models in the RLS rollout artifact", () => {
|
||||
const source = readFileSync(resolveRepoPath("prisma/rls/auftrag-isolation.sql"), "utf8");
|
||||
["ProjektMitglied", "ProjektTermin", "Rechnung", "ProjektChecklist", "ProjektChecklistItem", "AuftragPipelineStageConfig", "AcceptanceFormTemplate", "ProjectTemplate"].forEach(
|
||||
(model) => {
|
||||
expect(source).toContain(`'${model}'`);
|
||||
},
|
||||
);
|
||||
[
|
||||
"ProjektMitglied",
|
||||
"ProjektTermin",
|
||||
"Rechnung",
|
||||
"ProjektChecklist",
|
||||
"ProjektChecklistItem",
|
||||
"AuftragPipelineStageConfig",
|
||||
"AcceptanceFormTemplate",
|
||||
"ProjectTemplate",
|
||||
].forEach((model) => {
|
||||
expect(source).toContain(`'${model}'`);
|
||||
});
|
||||
expect(source).toContain("ENABLE ROW LEVEL SECURITY");
|
||||
expect(source).toContain("FORCE ROW LEVEL SECURITY");
|
||||
expect(source).toContain("hivegrid_app");
|
||||
@@ -194,12 +324,19 @@ describe("R-P9a order view and project sub-area backend artifacts", () => {
|
||||
|
||||
test("registers order sub-area tenant models for snapshot and restore", () => {
|
||||
const source = readFileSync(resolveRepoPath("packages/cli/src/commands/tenant/models.ts"), "utf8");
|
||||
["ProjektMitglied", "ProjektTermin", "Rechnung", "ProjektChecklist", "ProjektChecklistItem", "AuftragPipelineStageConfig", "AcceptanceFormTemplate", "ProjectTemplate"].forEach(
|
||||
(model) => {
|
||||
expect(source).toContain(`model: "${model}"`);
|
||||
expect(source).toContain('schema: "auftrag.prisma"');
|
||||
},
|
||||
);
|
||||
[
|
||||
"ProjektMitglied",
|
||||
"ProjektTermin",
|
||||
"Rechnung",
|
||||
"ProjektChecklist",
|
||||
"ProjektChecklistItem",
|
||||
"AuftragPipelineStageConfig",
|
||||
"AcceptanceFormTemplate",
|
||||
"ProjectTemplate",
|
||||
].forEach((model) => {
|
||||
expect(source).toContain(`model: "${model}"`);
|
||||
expect(source).toContain('schema: "auftrag.prisma"');
|
||||
});
|
||||
});
|
||||
|
||||
test("exposes order sub-area service contracts for the later screen layer", () => {
|
||||
@@ -223,20 +360,27 @@ describe("R-P9a order view and project sub-area backend artifacts", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("routes gate sub-area and template actions through the projects module and permissions", () => {
|
||||
test("routes project detail actions through the projects module and keeps the template admin reachable", () => {
|
||||
const detailRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects.$id.tsx"), "utf8");
|
||||
const pipelineAdminRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/admin.pipelines._index.tsx"), "utf8");
|
||||
const acceptanceFormsRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/admin.projects.acceptance-forms.tsx"), "utf8");
|
||||
const templatesRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/admin.projects.templates.tsx"), "utf8");
|
||||
const auftragService = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/auftragService.server.ts"), "utf8");
|
||||
expect(detailRoute).toContain("loadProjectSubAreas");
|
||||
expect(detailRoute).toContain('"projects.read_own_member"');
|
||||
expect(detailRoute).toContain('intent === "createInvoice"');
|
||||
expect(detailRoute).toContain('intent === "upsertChecklistItem"');
|
||||
expect(pipelineAdminRoute).toContain('intent === "upsertAuftragStageConfig"');
|
||||
expect(acceptanceFormsRoute).toContain('"projects.admin"');
|
||||
expect(acceptanceFormsRoute).toContain('intent === "upsertAcceptanceFormTemplate"');
|
||||
expect(templatesRoute).toContain('"projects.admin"');
|
||||
expect(templatesRoute).toContain('intent === "upsertProjectTemplate"');
|
||||
expect(auftragService).toContain("export async function upsertAuftragPipelineStageConfig");
|
||||
expect(auftragService).toContain("export async function upsertAcceptanceFormTemplate");
|
||||
expect(auftragService).toContain("export async function upsertProjectTemplate");
|
||||
// R-P9a DoD 5 — the template admin routes were dropped in the seat-billing
|
||||
// recut (5fe3a2c79) while the backend services stayed callable; the
|
||||
// restwork audit restored them as interim-UI routes. The routes must stay.
|
||||
//
|
||||
// Their entry point does not: the S07 acceptance took both links out of the
|
||||
// board admin, which Davids export does not show. The two screens are now
|
||||
// routable by URL but linked from nowhere. Giving them a home (sidebar entry
|
||||
// or a settings hub) is open work, so this stops asserting that the board
|
||||
// admin links to them — see the S07 note in .planning/ticket-docs/R-P9a.md.
|
||||
expect(existsSync(resolveRepoPath("apps/web/app/routes/app.$tenant/admin.projects.acceptance-forms.tsx"))).toBe(true);
|
||||
expect(existsSync(resolveRepoPath("apps/web/app/routes/app.$tenant/admin.projects.templates.tsx"))).toBe(true);
|
||||
});
|
||||
|
||||
test("seeds the additional projects permission needed by order memberships", () => {
|
||||
@@ -287,6 +431,7 @@ describe("R-P9b schedule board and acceptance backend artifacts", () => {
|
||||
"export async function submitAcceptanceProtocol",
|
||||
"export async function archiveAcceptanceProtocol",
|
||||
"export async function hardDeleteAcceptanceProtocol",
|
||||
"export async function updateAcceptanceProtocolContent",
|
||||
"export async function applyOfflineMutation",
|
||||
].forEach((exportName) => {
|
||||
expect(service).toContain(exportName);
|
||||
@@ -294,8 +439,11 @@ describe("R-P9b schedule board and acceptance backend artifacts", () => {
|
||||
expect(service).toContain("listApprovedAbsencesForRange");
|
||||
expect(service).toContain("buildPdfExportArtifact");
|
||||
expect(service).toContain("queueTransactionalEmail");
|
||||
expect(service).toContain("createNotificationDelivery");
|
||||
expect(service).toContain("createTask");
|
||||
// R-P9b — lead notification goes through the M011 notify() service inside a
|
||||
// tenant-bound RLS transaction, never through a raw delivery insert.
|
||||
expect(service).toContain("notify(");
|
||||
expect(service).not.toContain("createNotificationDelivery");
|
||||
expect(service).toContain("createAcceptanceFollowUpTask");
|
||||
});
|
||||
|
||||
test("blocks stage moves when a target stage requires an acceptance protocol", () => {
|
||||
@@ -303,6 +451,8 @@ describe("R-P9b schedule board and acceptance backend artifacts", () => {
|
||||
expect(service).toContain("requiresAcceptanceProtocol");
|
||||
expect(service).toContain("abnahmeProtokoll.findFirst");
|
||||
expect(service).toContain('"projects.error.acceptanceProtocolRequired"');
|
||||
// R-P9b DoD 6 — only completed acceptances (full/with_defects) open the gate.
|
||||
expect(service).toContain('acceptanceKind: { in: ["full", "with_defects"] }');
|
||||
});
|
||||
|
||||
test("routes expose plantafel, acceptance list, and acceptance submit contracts behind module gates", () => {
|
||||
@@ -323,14 +473,102 @@ describe("R-P9b schedule board and acceptance backend artifacts", () => {
|
||||
const defaultPermissions = readFileSync(resolveRepoPath("apps/web/app/application/dtos/shared/DefaultPermissions.ts"), "utf8");
|
||||
const permissionSeed = readFileSync(resolveRepoPath("packages/db/src/permissions-seed.server.ts"), "utf8");
|
||||
const roleDisplay = readFileSync(resolveRepoPath("apps/web/app/components/core/roles/roleDisplay.ts"), "utf8");
|
||||
["plantafel.read_own", "plantafel.read_all", "plantafel.write", "plantafel.bulk_reassign", "acceptance.read", "acceptance.write", "acceptance.admin"].forEach(
|
||||
(permission) => {
|
||||
expect(defaultPermissions).toContain(`"${permission}"`);
|
||||
expect(permissionSeed).toContain(`"${permission}"`);
|
||||
},
|
||||
);
|
||||
[
|
||||
"plantafel.read_own",
|
||||
"plantafel.read_all",
|
||||
"plantafel.write",
|
||||
"plantafel.bulk_reassign",
|
||||
"acceptance.read",
|
||||
"acceptance.write",
|
||||
"acceptance.admin",
|
||||
].forEach((permission) => {
|
||||
expect(defaultPermissions).toContain(`"${permission}"`);
|
||||
expect(permissionSeed).toContain(`"${permission}"`);
|
||||
});
|
||||
[
|
||||
'"plantafel.read_own": ["SuperUser", "Admin", "User"]',
|
||||
'"plantafel.read_all": ["SuperUser", "Admin"]',
|
||||
'"plantafel.write": ["SuperUser", "Admin", "User"]',
|
||||
'"plantafel.bulk_reassign": ["SuperUser", "Admin"]',
|
||||
'"acceptance.read": ["SuperUser", "Admin", "User"]',
|
||||
'"acceptance.write": ["SuperUser", "Admin", "User"]',
|
||||
'"acceptance.admin": ["SuperUser", "Admin"]',
|
||||
].forEach((grant) => {
|
||||
expect(permissionSeed).toContain(grant);
|
||||
});
|
||||
expect(roleDisplay).toContain("bulk_reassign");
|
||||
expect(roleDisplay).toContain("plantafel");
|
||||
expect(roleDisplay).toContain("acceptance");
|
||||
});
|
||||
});
|
||||
|
||||
describe("P8 board delta: staleness tag + context-menu duplicate/archive", () => {
|
||||
test("resolves in-stage duration in one batch query (no N+1) with createdAt fallback", () => {
|
||||
const service = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/projectService.server.ts"), "utf8");
|
||||
const boardLoader = service.split("export async function loadProjectBoard")[1]!.split("type ProjectListDbRow")[0]!;
|
||||
expect(boardLoader).toContain("loadInStageSinceWithTx(tx, { tenantId: input.tenantId, projects: boardProjects })");
|
||||
const helper = service.split("async function loadInStageSinceWithTx")[1]!.split("export async function loadProjectBoard")[0]!;
|
||||
expect(helper).toContain("projektStageChange.findMany");
|
||||
expect(helper).toContain('distinct: ["projektId"]');
|
||||
expect(helper).toContain("undoneAt: null");
|
||||
expect(helper).toContain("project.createdAt");
|
||||
// The card raw data carries the ISO timestamp for the VM's stuckDays computation.
|
||||
expect(service).toContain("inStageSince: inStageSince.toISOString()");
|
||||
});
|
||||
|
||||
test("duplicateProject gates on write, reuses the number sequence, and skips lifecycle state", () => {
|
||||
const service = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/projectService.server.ts"), "utf8");
|
||||
const section = service.split("export async function duplicateProject(")[1]!.split("\nexport function leadProjectName")[0]!;
|
||||
expect(section).toContain('hasPermission(input.ctx, "projects.write")');
|
||||
expect(section).toContain("projectReadScopeWhere(input.tenantId, input.ctx)");
|
||||
expect(section).toContain('reserveNumberWithTx(tx, input.tenantId, "projekt", "P-")');
|
||||
expect(section).toContain("(Kopie)");
|
||||
expect(section).toContain("projektKontakt.createMany");
|
||||
expect(section).toContain("isDemoData: source.isDemoData");
|
||||
expect(section).toContain("publishProjectSearchUpsert");
|
||||
expect(section).toContain("refreshPipelineAggregatesAfterMutation(");
|
||||
// Lifecycle/conversion state must not be copied onto the new project.
|
||||
expect(section).not.toContain("wonAt:");
|
||||
expect(section).not.toContain("lostAt:");
|
||||
expect(section).not.toContain("lostReasonId:");
|
||||
expect(section).not.toContain("undoStageChangeUntil:");
|
||||
expect(section).not.toContain("konvertiertAusLeadId:");
|
||||
expect(section).not.toContain("appEntityBinding");
|
||||
});
|
||||
|
||||
test("server-side project mutations enforce KWP ownership before changing protected fields", () => {
|
||||
const service = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/projectService.server.ts"), "utf8");
|
||||
const guardedOperations = [
|
||||
{ name: "moveProjectStage", operation: '"stage"' },
|
||||
{ name: "undoLastProjectStageChange", operation: '"stage"' },
|
||||
{ name: "archiveProject", operation: '"archive"' },
|
||||
{ name: "updateProjectStammdaten", operation: '"stammdaten"' },
|
||||
];
|
||||
for (const guarded of guardedOperations) {
|
||||
const section = service.split(`export async function ${guarded.name}(`)[1]!.split("\nexport ")[0]!;
|
||||
expect(section, guarded.name).toContain("assertKwpProjectMutationAllowed");
|
||||
expect(section, guarded.name).toContain(`operation: ${guarded.operation}`);
|
||||
}
|
||||
const update = service.split("export async function updateProjectStammdaten(")[1]!.split("\nexport ")[0]!;
|
||||
for (const field of ["projektname", "startDatum", "auftragsvolumen"]) {
|
||||
expect(update).toContain(`"${field}"`);
|
||||
}
|
||||
const bulkMove = service.split("export async function bulkMoveProjectStage(")[1]!.split("\nexport ")[0]!;
|
||||
const bulkArchive = service.split("export async function bulkArchiveProjects(")[1]!.split("\nexport ")[0]!;
|
||||
expect(bulkMove).toContain("moveProjectStage({");
|
||||
expect(bulkArchive).toContain("archiveProject({");
|
||||
});
|
||||
|
||||
test("board routes wire duplicate/archive intents with per-intent permissions", () => {
|
||||
const boardHelper = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/projectBoardRoute.server.ts"), "utf8");
|
||||
expect(boardHelper).toContain('case "duplicateProject"');
|
||||
expect(boardHelper).toContain('case "archiveProject"');
|
||||
expect(boardHelper).toContain('type: "archived"');
|
||||
expect(boardHelper).toContain("export function kanbanIntentPermission");
|
||||
expect(boardHelper).toContain('canDelete: ctx.permissions.includes("projects.delete")');
|
||||
const boardRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects._index.tsx"), "utf8");
|
||||
expect(boardRoute).toContain("kanbanIntentPermission(intent)");
|
||||
expect(boardRoute).toContain('post("duplicateProject", { projectId })');
|
||||
expect(boardRoute).toContain('post("archiveProject", { projectId })');
|
||||
});
|
||||
});
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
// WF-P8 S02-N — the note reader gate.
|
||||
//
|
||||
// This tests `noteReadScopeWhere` as a pure predicate rather than mocking the
|
||||
// database: a mock that answers every query would hide exactly the bug this
|
||||
// gate exists to prevent (AGENTS.md §RLS — "Tests, die den DB-Client mocken,
|
||||
// beweisen nichts"). Here we evaluate the produced `where` fragment against
|
||||
// concrete note rows, which is the same decision Postgres makes.
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { noteReadScopeWhere, type ProjektNotizContext } from "./projektNotizService.server";
|
||||
|
||||
type NoteRow = { sichtbarkeit: "alle" | "innendienst" | "nur_ich"; autorUserId: string | null };
|
||||
|
||||
/** Evaluate the OR-fragment the service hands to Prisma against one row. */
|
||||
function matches(where: ReturnType<typeof noteReadScopeWhere>, row: NoteRow): boolean {
|
||||
return where.OR.some((clause) =>
|
||||
Object.entries(clause).every(([key, value]) => row[key as keyof NoteRow] === value)
|
||||
);
|
||||
}
|
||||
|
||||
function ctx(overrides: Partial<ProjektNotizContext> = {}): ProjektNotizContext {
|
||||
return { userId: "usr_a", permissions: [], canReadInternal: false, ...overrides } as ProjektNotizContext;
|
||||
}
|
||||
|
||||
const publicNote: NoteRow = { sichtbarkeit: "alle", autorUserId: "usr_b" };
|
||||
const internalNote: NoteRow = { sichtbarkeit: "innendienst", autorUserId: "usr_b" };
|
||||
const ownPrivateNote: NoteRow = { sichtbarkeit: "nur_ich", autorUserId: "usr_a" };
|
||||
const foreignPrivateNote: NoteRow = { sichtbarkeit: "nur_ich", autorUserId: "usr_b" };
|
||||
|
||||
describe("noteReadScopeWhere", () => {
|
||||
it("lets anyone with project access read a public note", () => {
|
||||
expect(matches(noteReadScopeWhere(ctx()), publicNote)).toBe(true);
|
||||
});
|
||||
|
||||
it("hides an internal note without projects.read_internal_notes", () => {
|
||||
expect(matches(noteReadScopeWhere(ctx()), internalNote)).toBe(false);
|
||||
});
|
||||
|
||||
it("shows an internal note with the permission", () => {
|
||||
expect(matches(noteReadScopeWhere(ctx({ canReadInternal: true })), internalNote)).toBe(true);
|
||||
});
|
||||
|
||||
it("shows a private note only to its author", () => {
|
||||
const where = noteReadScopeWhere(ctx());
|
||||
expect(matches(where, ownPrivateNote)).toBe(true);
|
||||
expect(matches(where, foreignPrivateNote)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not open foreign private notes to someone holding the internal permission", () => {
|
||||
// "Nur ich" outranks the internal-notes permission; it is not a hierarchy.
|
||||
expect(matches(noteReadScopeWhere(ctx({ canReadInternal: true })), foreignPrivateNote)).toBe(false);
|
||||
});
|
||||
|
||||
it("matches no private note at all for an anonymous context", () => {
|
||||
const where = noteReadScopeWhere(ctx({ userId: null as unknown as string }));
|
||||
expect(matches(where, ownPrivateNote)).toBe(false);
|
||||
expect(matches(where, foreignPrivateNote)).toBe(false);
|
||||
// …but a public note stays readable.
|
||||
expect(matches(where, publicNote)).toBe(true);
|
||||
});
|
||||
});
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
// WF-P8 S02-N (Modal Notiz erstellen) — project notes with a reader gate.
|
||||
//
|
||||
// The visibility choice is the point of this module: "alle" follows normal
|
||||
// project access, "innendienst" additionally requires the
|
||||
// `projects.read_internal_notes` permission, and "nur_ich" is author-only.
|
||||
// The gate is applied in SQL (see `noteReadScopeWhere`) so a caller cannot
|
||||
// forget it, and RLS still scopes every row to the bound tenant on top.
|
||||
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
import { projectEditScopeWhere, projectReadScopeWhere, type ProjectVisibilityContext } from "./projectService.server";
|
||||
|
||||
export class ProjektNotizServiceError extends Error {
|
||||
readonly messageKey: string;
|
||||
constructor(messageKey: string) {
|
||||
super(messageKey);
|
||||
this.name = "ProjektNotizServiceError";
|
||||
this.messageKey = messageKey;
|
||||
}
|
||||
}
|
||||
|
||||
export type ProjektNotizSichtbarkeit = "alle" | "innendienst" | "nur_ich";
|
||||
|
||||
export const PROJEKT_NOTIZ_SICHTBARKEITEN: readonly ProjektNotizSichtbarkeit[] = ["alle", "innendienst", "nur_ich"];
|
||||
|
||||
export function isProjektNotizSichtbarkeit(value: string): value is ProjektNotizSichtbarkeit {
|
||||
return (PROJEKT_NOTIZ_SICHTBARKEITEN as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
export type ProjektNotizRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
projektId: string;
|
||||
autorUserId: string | null;
|
||||
inhalt: string;
|
||||
sichtbarkeit: ProjektNotizSichtbarkeit;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
archivedAt: Date | null;
|
||||
};
|
||||
|
||||
/** Note-reader context: the project visibility context plus the internal-notes permission. */
|
||||
export type ProjektNotizContext = ProjectVisibilityContext & {
|
||||
/** True when the actor holds `projects.read_internal_notes`. */
|
||||
canReadInternal: boolean;
|
||||
};
|
||||
|
||||
/** Derive the note-reader context from a project context (single source for the gate). */
|
||||
export function toProjektNotizContext(ctx: ProjectVisibilityContext): ProjektNotizContext {
|
||||
return { ...ctx, canReadInternal: ctx.permissions.includes("projects.read_internal_notes") };
|
||||
}
|
||||
|
||||
function normalizeText(value?: string | null): string | null {
|
||||
const normalized = value?.trim();
|
||||
return normalized || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* SQL-level reader gate. Returns a `where` fragment that only matches notes the
|
||||
* actor is allowed to see. Kept as a fragment (not a post-filter) so a caller
|
||||
* cannot accidentally page over rows it may not read.
|
||||
*/
|
||||
export function noteReadScopeWhere(ctx: ProjektNotizContext) {
|
||||
const allowed: Record<string, unknown>[] = [{ sichtbarkeit: "alle" }];
|
||||
if (ctx.canReadInternal) allowed.push({ sichtbarkeit: "innendienst" });
|
||||
// `nur_ich` is author-only. An anonymous/system context matches nothing here,
|
||||
// which is deliberate: a null author must not open up every private note.
|
||||
if (ctx.userId) allowed.push({ sichtbarkeit: "nur_ich", autorUserId: ctx.userId });
|
||||
return { OR: allowed };
|
||||
}
|
||||
|
||||
async function requireProjectWithTx(
|
||||
tx: TenantRlsClient,
|
||||
input: { tenantId: string; projectId: string; ctx: ProjectVisibilityContext; editable: boolean }
|
||||
): Promise<void> {
|
||||
const project = await tx.projekt.findFirst({
|
||||
where: {
|
||||
id: input.projectId,
|
||||
tenantId: input.tenantId,
|
||||
archivedAt: null,
|
||||
...(input.editable ? projectEditScopeWhere(input.tenantId, input.ctx) : projectReadScopeWhere(input.tenantId, input.ctx)),
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
// Permission-denied shows 404, never 403 (Bauprinzip A.5.3).
|
||||
if (!project) throw new CatalogError(foundationErrors.notFound, { projectId: input.projectId });
|
||||
}
|
||||
|
||||
export async function listProjectNotes(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
ctx: ProjektNotizContext;
|
||||
}): Promise<ProjektNotizRow[]> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireProjectWithTx(tx, { ...input, editable: false });
|
||||
const rows = await tx.projektNotiz.findMany({
|
||||
where: {
|
||||
tenantId: input.tenantId,
|
||||
projektId: input.projectId,
|
||||
archivedAt: null,
|
||||
...noteReadScopeWhere(input.ctx),
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return rows as ProjektNotizRow[];
|
||||
});
|
||||
}
|
||||
|
||||
export async function createProjectNote(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
ctx: ProjektNotizContext;
|
||||
autorUserId: string | null;
|
||||
inhalt: string;
|
||||
sichtbarkeit: ProjektNotizSichtbarkeit;
|
||||
}): Promise<ProjektNotizRow> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const inhalt = normalizeText(input.inhalt);
|
||||
if (!inhalt) throw new ProjektNotizServiceError("projects.error.noteContentRequired");
|
||||
// "Nur ich" without an author would be unreadable for everyone including
|
||||
// its creator, so reject it instead of writing an orphan note.
|
||||
if (input.sichtbarkeit === "nur_ich" && !input.autorUserId) {
|
||||
throw new ProjektNotizServiceError("projects.error.notePrivateNeedsAuthor");
|
||||
}
|
||||
await requireProjectWithTx(tx, { ...input, editable: true });
|
||||
const row = await tx.projektNotiz.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
projektId: input.projectId,
|
||||
autorUserId: input.autorUserId,
|
||||
inhalt,
|
||||
sichtbarkeit: input.sichtbarkeit,
|
||||
},
|
||||
});
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.autorUserId,
|
||||
actorKind: input.autorUserId ? "user" : "system",
|
||||
activityType: "project_note_created",
|
||||
subjectType: "project",
|
||||
subjectId: input.projectId,
|
||||
summaryText: "activity.runtime.projects.noteCreated",
|
||||
// The note body itself is deliberately NOT mirrored into the activity
|
||||
// stream: the stream has no reader gate, so a "nur ich" note would leak.
|
||||
metadata: { noteId: row.id, sichtbarkeit: row.sichtbarkeit },
|
||||
},
|
||||
{ client: tx }
|
||||
);
|
||||
return row as ProjektNotizRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function archiveProjectNote(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
noteId: string;
|
||||
ctx: ProjektNotizContext;
|
||||
actorUserId: string | null;
|
||||
}): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireProjectWithTx(tx, { ...input, editable: true });
|
||||
// Reader gate applies to archiving too: you cannot archive what you may not see.
|
||||
const note = await tx.projektNotiz.findFirst({
|
||||
where: {
|
||||
id: input.noteId,
|
||||
tenantId: input.tenantId,
|
||||
projektId: input.projectId,
|
||||
archivedAt: null,
|
||||
...noteReadScopeWhere(input.ctx),
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (!note) throw new CatalogError(foundationErrors.notFound, { noteId: input.noteId });
|
||||
await tx.projektNotiz.update({ where: { id: note.id }, data: { archivedAt: new Date() } });
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.actorUserId,
|
||||
actorKind: input.actorUserId ? "user" : "system",
|
||||
activityType: "project_note_archived",
|
||||
subjectType: "project",
|
||||
subjectId: input.projectId,
|
||||
summaryText: "activity.runtime.projects.noteArchived",
|
||||
metadata: { noteId: note.id },
|
||||
},
|
||||
{ client: tx }
|
||||
);
|
||||
});
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Canonical sales-pipeline baseline shared by legacy provisioning and the
|
||||
* versioned SHK-v2 tenant bootstrap. Keep this module pure so configuration
|
||||
* validation can reuse it without importing server or database code.
|
||||
*/
|
||||
export const DEFAULT_SALES_PIPELINE_STAGES = Object.freeze([
|
||||
{ name: "Neu", stageKind: "offen", winProbability: 10, color: "#64748b", position: 10 },
|
||||
{ name: "Qualifiziert", stageKind: "offen", winProbability: 30, color: "#0ea5e9", position: 20 },
|
||||
{ name: "Angebot", stageKind: "offen", winProbability: 60, color: "#f59e0b", position: 30 },
|
||||
{ name: "Gewonnen", stageKind: "gewonnen", winProbability: 100, color: "#16a34a", position: 40 },
|
||||
{ name: "Verloren", stageKind: "verloren", winProbability: 0, color: "#dc2626", position: 50 },
|
||||
] as const);
|
||||
|
||||
export const DEFAULT_SALES_LOST_REASONS = ["Preis", "Zeitpunkt", "Kein Bedarf", "Wettbewerber", "Nicht erreichbar"] as const;
|
||||
Reference in new issue
Block a user