Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+697
@@ -0,0 +1,697 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
import type { ProjektRow } from "./projectService.server";
|
||||
|
||||
export class AuftragServiceError extends Error {
|
||||
readonly messageKey: string;
|
||||
constructor(messageKey: string) {
|
||||
super(messageKey);
|
||||
this.name = "AuftragServiceError";
|
||||
this.messageKey = messageKey;
|
||||
}
|
||||
}
|
||||
|
||||
export type ProjektMitgliedRolle = "monteur" | "projektleiter" | "zustaendig" | "beobachter";
|
||||
export type ProjektTerminStatus = "geplant" | "bestaetigt" | "erledigt" | "abgesagt";
|
||||
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 ProjektMitgliedRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
projektId: string;
|
||||
userId: string | null;
|
||||
groupId: string | null;
|
||||
rolle: ProjektMitgliedRolle;
|
||||
createdByUserId: string | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
archivedAt: Date | null;
|
||||
};
|
||||
|
||||
export type ProjektTerminRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
projektId: string;
|
||||
createdByUserId: string | null;
|
||||
assignedToUserId: string | null;
|
||||
assignedToGroupId: string | null;
|
||||
titel: string;
|
||||
beschreibung: string | null;
|
||||
startAt: Date;
|
||||
endAt: Date | null;
|
||||
status: ProjektTerminStatus;
|
||||
isDemoData: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
archivedAt: Date | null;
|
||||
};
|
||||
|
||||
export type RechnungRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
projektId: string;
|
||||
createdByUserId: string | null;
|
||||
rechnungsnummer: string;
|
||||
betrag: unknown;
|
||||
status: RechnungStatus;
|
||||
datum: Date;
|
||||
faelligAm: Date | null;
|
||||
dateiId: string | null;
|
||||
quelle: RechnungQuelle;
|
||||
isDemoData: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
archivedAt: Date | null;
|
||||
};
|
||||
|
||||
export type ProjektChecklistItemRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
checklistId: string;
|
||||
titel: string;
|
||||
status: ProjektChecklistItemStatus;
|
||||
maengelKlasse: string | null;
|
||||
fotoFileId: string | null;
|
||||
assignedToUserId: string | null;
|
||||
dueAt: Date | null;
|
||||
position: number;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
export type ProjektChecklistRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
projektId: string;
|
||||
createdByUserId: string | null;
|
||||
titel: string;
|
||||
typ: ProjektChecklistTyp;
|
||||
isDemoData: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
archivedAt: Date | null;
|
||||
items?: ProjektChecklistItemRow[];
|
||||
};
|
||||
|
||||
export type AuftragPipelineStageConfigRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
pipelineId: string;
|
||||
stageId: string;
|
||||
requiresAcceptanceProtocol: boolean;
|
||||
acceptanceFormTemplateId: string | null;
|
||||
autoArchiveAfterDays: number | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
export type AcceptanceFormTemplateRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
name: string;
|
||||
formId: string | null;
|
||||
definition: unknown;
|
||||
isDefault: boolean;
|
||||
isDemoData: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
archivedAt: Date | null;
|
||||
};
|
||||
|
||||
export type ProjectTemplateRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
name: string;
|
||||
defaultPipelineId: string | null;
|
||||
defaultStageId: string | null;
|
||||
defaultMembers: unknown;
|
||||
defaultTasks: unknown;
|
||||
customFields: unknown;
|
||||
isDemoData: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
archivedAt: Date | null;
|
||||
};
|
||||
|
||||
export type ProjectSubAreasVM = {
|
||||
project: ProjektRow;
|
||||
members: ProjektMitgliedRow[];
|
||||
appointments: ProjektTerminRow[];
|
||||
invoices: RechnungRow[];
|
||||
checklists: ProjektChecklistRow[];
|
||||
stageConfig: AuftragPipelineStageConfigRow | null;
|
||||
acceptanceTemplates: AcceptanceFormTemplateRow[];
|
||||
projectTemplates: ProjectTemplateRow[];
|
||||
openDefects: number;
|
||||
};
|
||||
|
||||
function normalizeText(value?: string | null): string | null {
|
||||
const normalized = value?.trim();
|
||||
return normalized || null;
|
||||
}
|
||||
|
||||
function parseDate(value?: string | Date | null): Date | null {
|
||||
if (!value) return null;
|
||||
if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;
|
||||
const parsed = new Date(value);
|
||||
return Number.isNaN(parsed.getTime()) ? null : parsed;
|
||||
}
|
||||
|
||||
function decimalToString(value: unknown): string {
|
||||
if (value == null) return "0.00";
|
||||
if (typeof value === "number") return Number.isFinite(value) ? value.toFixed(2) : "0.00";
|
||||
if (typeof value === "string") {
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed.toFixed(2) : "0.00";
|
||||
}
|
||||
if (typeof value === "object" && "toString" in value && typeof value.toString === "function") {
|
||||
const parsed = Number(value.toString());
|
||||
return Number.isFinite(parsed) ? parsed.toFixed(2) : "0.00";
|
||||
}
|
||||
return "0.00";
|
||||
}
|
||||
|
||||
function hasPermission(ctx: AuftragVisibilityContext | undefined, permission: string): boolean {
|
||||
return ctx?.permissions.includes(permission) ?? false;
|
||||
}
|
||||
|
||||
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 },
|
||||
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 } });
|
||||
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 });
|
||||
}
|
||||
return project as ProjektRow;
|
||||
}
|
||||
|
||||
function requireExactlyOnePrincipal(userId?: string | null, groupId?: string | null): void {
|
||||
const hasUser = Boolean(normalizeText(userId));
|
||||
const hasGroup = Boolean(normalizeText(groupId));
|
||||
if (hasUser === hasGroup) throw new AuftragServiceError("projects.error.memberPrincipalRequired");
|
||||
}
|
||||
|
||||
function invoiceNumber(prefix: string, nextNumber: number, padding: number): string {
|
||||
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 reserveInvoiceNumberWithTx(tx: TenantRlsClient, tenantId: string): Promise<string> {
|
||||
const sequenceId = `seq_${randomUUID()}`;
|
||||
await tx.$executeRaw`
|
||||
INSERT INTO "HiveNumberSeq" ("id", "tenantId", "entityType", "prefix", "nextNumber", "padding", "createdAt", "updatedAt")
|
||||
VALUES (${sequenceId}, ${tenantId}, 'rechnung', 'R-', 1, 5, now(), now())
|
||||
ON CONFLICT ("tenantId", "entityType") DO NOTHING
|
||||
`;
|
||||
const rows = await tx.$queryRaw<Array<{ nextNumber: number; padding: number; prefix: string }>>`
|
||||
SELECT "nextNumber", "padding", "prefix"
|
||||
FROM "HiveNumberSeq"
|
||||
WHERE "tenantId" = ${tenantId} AND "entityType" = 'rechnung'
|
||||
FOR UPDATE
|
||||
`;
|
||||
const current = rows[0];
|
||||
if (!current) throw new AuftragServiceError("projects.error.invoiceNumberSequenceMissing");
|
||||
await tx.hiveNumberSeq.update({
|
||||
where: { tenantId_entityType: { tenantId, entityType: "rechnung" } },
|
||||
data: { nextNumber: current.nextNumber + 1 },
|
||||
});
|
||||
return invoiceNumber(current.prefix || "R-", current.nextNumber, current.padding);
|
||||
}
|
||||
|
||||
export async function ensureDefaultAcceptanceFormTemplate(input: { tenantId: string; userId?: string | null }): Promise<AcceptanceFormTemplateRow> {
|
||||
return withTenantRLS(input.tenantId, (tx) => ensureDefaultAcceptanceFormTemplateWithTx(tx, input.tenantId));
|
||||
}
|
||||
|
||||
export async function ensureDefaultProjectTemplate(input: { tenantId: string }): Promise<ProjectTemplateRow> {
|
||||
return withTenantRLS(input.tenantId, (tx) => ensureDefaultProjectTemplateWithTx(tx, input.tenantId));
|
||||
}
|
||||
|
||||
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 },
|
||||
create: {
|
||||
tenantId,
|
||||
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: true,
|
||||
},
|
||||
});
|
||||
return row as AcceptanceFormTemplateRow;
|
||||
}
|
||||
|
||||
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 },
|
||||
create: {
|
||||
tenantId,
|
||||
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: true,
|
||||
},
|
||||
});
|
||||
return row as ProjectTemplateRow;
|
||||
}
|
||||
|
||||
export async function loadProjectSubAreas(input: { tenantId: string; projectId: string; ctx: AuftragVisibilityContext }): Promise<ProjectSubAreasVM> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const project = await requireProjectSubAreaReadWithTx(tx, input);
|
||||
await Promise.all([ensureDefaultAcceptanceFormTemplateWithTx(tx, input.tenantId), ensureDefaultProjectTemplateWithTx(tx, input.tenantId)]);
|
||||
const [members, appointments, invoices, checklists, stageConfig, acceptanceTemplates, projectTemplates, openDefects] = await Promise.all([
|
||||
tx.projektMitglied.findMany({ where: { tenantId: input.tenantId, projektId: input.projectId, archivedAt: null }, orderBy: { createdAt: "asc" } }),
|
||||
tx.projektTermin.findMany({ where: { tenantId: input.tenantId, projektId: input.projectId, archivedAt: null }, orderBy: { startAt: "asc" } }),
|
||||
tx.rechnung.findMany({ where: { tenantId: input.tenantId, projektId: input.projectId, archivedAt: null }, orderBy: { createdAt: "desc" } }),
|
||||
tx.projektChecklist.findMany({
|
||||
where: { tenantId: input.tenantId, projektId: input.projectId, archivedAt: null },
|
||||
include: { items: { orderBy: { position: "asc" } } },
|
||||
orderBy: { createdAt: "asc" },
|
||||
}),
|
||||
tx.auftragPipelineStageConfig.findFirst({ where: { tenantId: input.tenantId, stageId: project.stageId } }),
|
||||
tx.acceptanceFormTemplate.findMany({ where: { tenantId: input.tenantId, archivedAt: null }, orderBy: [{ isDefault: "desc" }, { name: "asc" }] }),
|
||||
tx.projectTemplate.findMany({ where: { tenantId: input.tenantId, archivedAt: null }, orderBy: [{ isDemoData: "desc" }, { name: "asc" }] }),
|
||||
tx.projektChecklistItem.count({
|
||||
where: {
|
||||
tenantId: input.tenantId,
|
||||
status: "offen",
|
||||
checklist: { projektId: input.projectId, typ: "maengel", archivedAt: null },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
return {
|
||||
project,
|
||||
members: members as ProjektMitgliedRow[],
|
||||
appointments: appointments as ProjektTerminRow[],
|
||||
invoices: invoices as RechnungRow[],
|
||||
checklists: checklists as ProjektChecklistRow[],
|
||||
stageConfig: stageConfig as AuftragPipelineStageConfigRow | null,
|
||||
acceptanceTemplates: acceptanceTemplates as AcceptanceFormTemplateRow[],
|
||||
projectTemplates: projectTemplates as ProjectTemplateRow[],
|
||||
openDefects,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function addProjectMember(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
createdByUserId: string | null;
|
||||
userId?: string | null;
|
||||
groupId?: string | null;
|
||||
rolle: ProjektMitgliedRolle;
|
||||
}): Promise<ProjektMitgliedRow> {
|
||||
requireExactlyOnePrincipal(input.userId, input.groupId);
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireProjectWithTx(tx, input);
|
||||
const row = await tx.projektMitglied.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
projektId: input.projectId,
|
||||
createdByUserId: input.createdByUserId,
|
||||
userId: normalizeText(input.userId),
|
||||
groupId: normalizeText(input.groupId),
|
||||
rolle: input.rolle,
|
||||
},
|
||||
});
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.createdByUserId,
|
||||
actorKind: input.createdByUserId ? "user" : "system",
|
||||
activityType: "project_member_added",
|
||||
subjectType: "project",
|
||||
subjectId: input.projectId,
|
||||
summaryText: "Projektmitglied wurde hinzugefügt.",
|
||||
metadata: { userId: input.userId ?? null, groupId: input.groupId ?? null, rolle: input.rolle },
|
||||
},
|
||||
{ client: tx },
|
||||
);
|
||||
return row as ProjektMitgliedRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function createProjectAppointment(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
createdByUserId: string | null;
|
||||
titel: string;
|
||||
beschreibung?: string | null;
|
||||
startAt: string | Date;
|
||||
endAt?: string | Date | null;
|
||||
assignedToUserId?: string | null;
|
||||
assignedToGroupId?: string | null;
|
||||
}): 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);
|
||||
const row = await tx.projektTermin.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
projektId: input.projectId,
|
||||
createdByUserId: input.createdByUserId,
|
||||
assignedToUserId: normalizeText(input.assignedToUserId),
|
||||
assignedToGroupId: normalizeText(input.assignedToGroupId),
|
||||
titel: title,
|
||||
beschreibung: normalizeText(input.beschreibung),
|
||||
startAt,
|
||||
endAt: parseDate(input.endAt),
|
||||
},
|
||||
});
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.createdByUserId,
|
||||
actorKind: input.createdByUserId ? "user" : "system",
|
||||
activityType: "project_appointment_created",
|
||||
subjectType: "project",
|
||||
subjectId: input.projectId,
|
||||
summaryText: "Projekttermin wurde angelegt.",
|
||||
metadata: { appointmentId: row.id, startAt: row.startAt.toISOString() },
|
||||
},
|
||||
{ client: tx },
|
||||
);
|
||||
return row as ProjektTerminRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function createProjectInvoice(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
createdByUserId: string | null;
|
||||
betrag: string | number;
|
||||
datum?: string | Date | null;
|
||||
faelligAm?: string | Date | null;
|
||||
dateiId?: string | null;
|
||||
quelle?: RechnungQuelle;
|
||||
}): Promise<RechnungRow> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireProjectWithTx(tx, input);
|
||||
const rechnungsnummer = await reserveInvoiceNumberWithTx(tx, input.tenantId);
|
||||
const row = await tx.rechnung.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
projektId: input.projectId,
|
||||
createdByUserId: input.createdByUserId,
|
||||
rechnungsnummer,
|
||||
betrag: decimalToString(input.betrag),
|
||||
datum: parseDate(input.datum) ?? new Date(),
|
||||
faelligAm: parseDate(input.faelligAm),
|
||||
dateiId: normalizeText(input.dateiId),
|
||||
quelle: input.quelle ?? "manuell",
|
||||
},
|
||||
});
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.createdByUserId,
|
||||
actorKind: input.createdByUserId ? "user" : "system",
|
||||
activityType: "project_invoice_created",
|
||||
subjectType: "project",
|
||||
subjectId: input.projectId,
|
||||
summaryText: `Rechnung ${row.rechnungsnummer} wurde angelegt.`,
|
||||
metadata: { invoiceId: row.id, rechnungsnummer: row.rechnungsnummer },
|
||||
},
|
||||
{ client: tx },
|
||||
);
|
||||
return row as RechnungRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateProjectInvoiceStatus(input: { tenantId: string; invoiceId: string; 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 logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.userId,
|
||||
actorKind: input.userId ? "user" : "system",
|
||||
activityType: "project_invoice_status_changed",
|
||||
subjectType: "project",
|
||||
subjectId: existing.projektId,
|
||||
summaryText: `Rechnungsstatus wurde auf ${input.status} gesetzt.`,
|
||||
metadata: { invoiceId: input.invoiceId, status: input.status },
|
||||
},
|
||||
{ client: tx },
|
||||
);
|
||||
return row as RechnungRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function createProjectChecklist(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
createdByUserId: string | null;
|
||||
titel: string;
|
||||
typ?: ProjektChecklistTyp;
|
||||
}): Promise<ProjektChecklistRow> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const title = normalizeText(input.titel);
|
||||
if (!title) throw new AuftragServiceError("projects.error.checklistTitleRequired");
|
||||
await requireProjectWithTx(tx, input);
|
||||
const row = await tx.projektChecklist.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
projektId: input.projectId,
|
||||
createdByUserId: input.createdByUserId,
|
||||
titel: title,
|
||||
typ: input.typ ?? "generisch",
|
||||
},
|
||||
});
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.createdByUserId,
|
||||
actorKind: input.createdByUserId ? "user" : "system",
|
||||
activityType: "project_checklist_created",
|
||||
subjectType: "project",
|
||||
subjectId: input.projectId,
|
||||
summaryText: "Projekt-Checkliste wurde angelegt.",
|
||||
metadata: { checklistId: row.id, typ: row.typ },
|
||||
},
|
||||
{ client: tx },
|
||||
);
|
||||
return row as ProjektChecklistRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function upsertProjectChecklistItem(input: {
|
||||
tenantId: string;
|
||||
checklistId: string;
|
||||
itemId?: string | null;
|
||||
titel: string;
|
||||
status?: ProjektChecklistItemStatus;
|
||||
maengelKlasse?: string | null;
|
||||
fotoFileId?: string | null;
|
||||
assignedToUserId?: string | null;
|
||||
dueAt?: string | Date | null;
|
||||
position?: number;
|
||||
}): Promise<ProjektChecklistItemRow> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const title = normalizeText(input.titel);
|
||||
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 });
|
||||
const data = {
|
||||
titel: title,
|
||||
status: input.status ?? "offen",
|
||||
maengelKlasse: normalizeText(input.maengelKlasse),
|
||||
fotoFileId: normalizeText(input.fotoFileId),
|
||||
assignedToUserId: normalizeText(input.assignedToUserId),
|
||||
dueAt: parseDate(input.dueAt),
|
||||
position: input.position ?? 0,
|
||||
};
|
||||
if (input.itemId) {
|
||||
const row = await tx.projektChecklistItem.update({ where: { id: input.itemId }, data });
|
||||
return row as ProjektChecklistItemRow;
|
||||
}
|
||||
const row = await tx.projektChecklistItem.create({
|
||||
data: { tenantId: input.tenantId, checklistId: input.checklistId, ...data },
|
||||
});
|
||||
return row as ProjektChecklistItemRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function upsertAuftragPipelineStageConfig(input: {
|
||||
tenantId: string;
|
||||
pipelineId: string;
|
||||
stageId: string;
|
||||
requiresAcceptanceProtocol?: boolean;
|
||||
acceptanceFormTemplateId?: string | null;
|
||||
autoArchiveAfterDays?: number | null;
|
||||
}): Promise<AuftragPipelineStageConfigRow> {
|
||||
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 row = await tx.auftragPipelineStageConfig.upsert({
|
||||
where: { tenantId_stageId: { tenantId: input.tenantId, stageId: input.stageId } },
|
||||
update: {
|
||||
requiresAcceptanceProtocol: input.requiresAcceptanceProtocol ?? false,
|
||||
acceptanceFormTemplateId: normalizeText(input.acceptanceFormTemplateId),
|
||||
autoArchiveAfterDays: input.autoArchiveAfterDays ?? null,
|
||||
},
|
||||
create: {
|
||||
tenantId: input.tenantId,
|
||||
pipelineId: input.pipelineId,
|
||||
stageId: input.stageId,
|
||||
requiresAcceptanceProtocol: input.requiresAcceptanceProtocol ?? false,
|
||||
acceptanceFormTemplateId: normalizeText(input.acceptanceFormTemplateId),
|
||||
autoArchiveAfterDays: input.autoArchiveAfterDays ?? null,
|
||||
},
|
||||
});
|
||||
return row as AuftragPipelineStageConfigRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function upsertAcceptanceFormTemplate(input: {
|
||||
tenantId: string;
|
||||
templateId?: string | null;
|
||||
name: string;
|
||||
formId?: string | null;
|
||||
definition?: unknown;
|
||||
isDefault?: boolean;
|
||||
}): Promise<AcceptanceFormTemplateRow> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const name = normalizeText(input.name);
|
||||
if (!name) throw new AuftragServiceError("projects.error.acceptanceTemplateNameRequired");
|
||||
if (input.templateId) {
|
||||
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 },
|
||||
});
|
||||
return row as AcceptanceFormTemplateRow;
|
||||
}
|
||||
const row = await tx.acceptanceFormTemplate.upsert({
|
||||
where: { tenantId_name: { tenantId: input.tenantId, name } },
|
||||
update: { formId: normalizeText(input.formId), definition: input.definition ?? {}, isDefault: input.isDefault ?? false, archivedAt: null },
|
||||
create: { tenantId: input.tenantId, name, formId: normalizeText(input.formId), definition: input.definition ?? {}, isDefault: input.isDefault ?? false },
|
||||
});
|
||||
return row as AcceptanceFormTemplateRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function listAcceptanceFormTemplates(input: { tenantId: string }): Promise<AcceptanceFormTemplateRow[]> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
await ensureDefaultAcceptanceFormTemplateWithTx(tx, input.tenantId);
|
||||
const rows = await tx.acceptanceFormTemplate.findMany({
|
||||
where: { tenantId: input.tenantId, archivedAt: null },
|
||||
orderBy: [{ isDefault: "desc" }, { name: "asc" }],
|
||||
});
|
||||
return rows as AcceptanceFormTemplateRow[];
|
||||
});
|
||||
}
|
||||
|
||||
export async function upsertProjectTemplate(input: {
|
||||
tenantId: string;
|
||||
templateId?: string | null;
|
||||
name: string;
|
||||
defaultPipelineId?: string | null;
|
||||
defaultStageId?: string | null;
|
||||
defaultMembers?: unknown;
|
||||
defaultTasks?: unknown;
|
||||
customFields?: unknown;
|
||||
}): Promise<ProjectTemplateRow> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const name = normalizeText(input.name);
|
||||
if (!name) throw new AuftragServiceError("projects.error.projectTemplateNameRequired");
|
||||
const data = {
|
||||
name,
|
||||
defaultPipelineId: normalizeText(input.defaultPipelineId),
|
||||
defaultStageId: normalizeText(input.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 });
|
||||
return row as ProjectTemplateRow;
|
||||
}
|
||||
const row = await tx.projectTemplate.upsert({
|
||||
where: { tenantId_name: { tenantId: input.tenantId, name } },
|
||||
update: data,
|
||||
create: { tenantId: input.tenantId, ...data },
|
||||
});
|
||||
return row as ProjectTemplateRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function listProjectTemplates(input: { tenantId: string }): Promise<ProjectTemplateRow[]> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
await ensureDefaultProjectTemplateWithTx(tx, input.tenantId);
|
||||
const rows = await tx.projectTemplate.findMany({
|
||||
where: { tenantId: input.tenantId, archivedAt: null },
|
||||
orderBy: [{ isDemoData: "desc" }, { name: "asc" }],
|
||||
});
|
||||
return rows as ProjectTemplateRow[];
|
||||
});
|
||||
}
|
||||
|
||||
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 };
|
||||
});
|
||||
}
|
||||
+790
@@ -0,0 +1,790 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import i18next from "i18next";
|
||||
import { buildFileStorageKeys } from "@hivegrid/storage";
|
||||
import { buildPdfExportArtifact } from "@hivegrid/exports/pdf";
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { createNotificationDelivery } from "@hivegrid/db/notifications.server";
|
||||
import { ensureServerGlobalI18n } from "~/locale/i18next.global.server";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
import { putBufferAsFile, resolveStorageBucket } from "~/utils/integrations/storageService";
|
||||
import { queueTransactionalEmail } from "~/modules/emails/services/TransactionalEmailQueue.server";
|
||||
import { createTask } from "~/utils/integrations/taskService.server";
|
||||
import { listApprovedAbsencesForRange, type ApprovedAbsence } from "~/utils/integrations/hrLeaveService.server";
|
||||
import { AuftragServiceError } from "./auftragService.server";
|
||||
import type { ProjektRow } from "./projectService.server";
|
||||
|
||||
export type ScheduleEntryStatus = "planned" | "confirmed" | "in_progress" | "done" | "cancelled";
|
||||
export type ScheduleConflictType = "double_booking" | "absence" | "availability";
|
||||
export type ScheduleConflictSeverity = "warning" | "blocking";
|
||||
export type ScheduleSyncStatus = "pending" | "synced" | "failed";
|
||||
export type AcceptanceKind = "full" | "with_defects" | "rejected";
|
||||
export type AcceptanceSignerRole = "kunde" | "monteur";
|
||||
export type OfflineSyncOperation = "schedule_upsert" | "schedule_status" | "acceptance_submit";
|
||||
|
||||
export type PlantafelContext = {
|
||||
userId: string;
|
||||
permissions: readonly string[];
|
||||
};
|
||||
|
||||
export type ScheduleConflictRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
entryId: string;
|
||||
type: ScheduleConflictType;
|
||||
severity: ScheduleConflictSeverity;
|
||||
messageKey: string;
|
||||
sourceKind: string | null;
|
||||
sourceId: string | null;
|
||||
createdAt: Date;
|
||||
resolvedAt: Date | null;
|
||||
overriddenAt: Date | null;
|
||||
};
|
||||
|
||||
export type ScheduleEntryRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
projektId: string;
|
||||
assignedUserId: string;
|
||||
createdByUserId: string | null;
|
||||
title: string;
|
||||
startAt: Date;
|
||||
endAt: Date;
|
||||
status: ScheduleEntryStatus;
|
||||
calendarEventId: string | null;
|
||||
syncStatus: ScheduleSyncStatus;
|
||||
conflictOverrideReason: string | null;
|
||||
clientMutationId: string | null;
|
||||
isDemoData: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
archivedAt: Date | null;
|
||||
conflicts?: ScheduleConflictRow[];
|
||||
};
|
||||
|
||||
export type AbnahmeSignaturRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
protokollId: string;
|
||||
signerName: string;
|
||||
signerRole: AcceptanceSignerRole;
|
||||
signatureFileId: string | null;
|
||||
signerIpHash: string | null;
|
||||
signedAt: Date;
|
||||
createdAt: Date;
|
||||
};
|
||||
|
||||
export type AbnahmeProtokollRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
projektId: string;
|
||||
maengelChecklistId: string | null;
|
||||
createdByUserId: string | null;
|
||||
datum: Date;
|
||||
acceptanceKind: AcceptanceKind;
|
||||
anwesende: unknown;
|
||||
druckprobe: unknown;
|
||||
funktionspruefung: unknown;
|
||||
zaehlerstaende: unknown;
|
||||
dokumente: unknown;
|
||||
bemerkungen: string | null;
|
||||
pdfFileId: string | null;
|
||||
customerEmail: string | null;
|
||||
customerEmailQueuedAt: Date | null;
|
||||
clientMutationId: string | null;
|
||||
gesperrtAt: Date | null;
|
||||
isDemoData: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
archivedAt: Date | null;
|
||||
signatures?: AbnahmeSignaturRow[];
|
||||
};
|
||||
|
||||
export type PlantafelVM = {
|
||||
entries: ScheduleEntryRow[];
|
||||
absences: ApprovedAbsence[];
|
||||
generatedAt: string;
|
||||
};
|
||||
|
||||
export type AcceptanceListVM = {
|
||||
project: ProjektRow;
|
||||
protocols: AbnahmeProtokollRow[];
|
||||
};
|
||||
|
||||
export type AcceptanceDefectInput = {
|
||||
classification: "critical" | "minor" | "cosmetic";
|
||||
title?: string | null;
|
||||
photoFileId?: string | null;
|
||||
};
|
||||
|
||||
export type AcceptanceSignatureInput = {
|
||||
signerName: string;
|
||||
signerRole: AcceptanceSignerRole;
|
||||
signatureFileId?: string | null;
|
||||
signerIpAddress?: string | null;
|
||||
};
|
||||
|
||||
const DEFAULT_WORKDAY_START_HOUR = 6;
|
||||
const DEFAULT_WORKDAY_END_HOUR = 20;
|
||||
|
||||
function normalizeText(value?: string | null): string | null {
|
||||
const normalized = value?.trim();
|
||||
return normalized || null;
|
||||
}
|
||||
|
||||
function hasPermission(ctx: PlantafelContext, permission: string): boolean {
|
||||
return ctx.permissions.includes(permission);
|
||||
}
|
||||
|
||||
function parseDate(value: string | Date | null | undefined): Date | null {
|
||||
if (!value) return null;
|
||||
if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;
|
||||
const parsed = new Date(value);
|
||||
return Number.isNaN(parsed.getTime()) ? null : parsed;
|
||||
}
|
||||
|
||||
function ensureRange(startAt: Date | null, endAt: Date | null): { startAt: Date; endAt: Date } {
|
||||
if (!startAt || !endAt || endAt <= startAt) {
|
||||
throw new AuftragServiceError("projects.error.scheduleRangeInvalid");
|
||||
}
|
||||
return { startAt, endAt };
|
||||
}
|
||||
|
||||
function intervalsOverlap(aStart: Date, aEnd: Date, bStart: Date, bEnd: Date): boolean {
|
||||
return aStart < bEnd && aEnd > bStart;
|
||||
}
|
||||
|
||||
function hashIpAddress(value?: string | null): string | null {
|
||||
const normalized = normalizeText(value);
|
||||
return normalized ? createHash("sha256").update(normalized).digest("hex") : null;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
function canReadPlantafel(ctx: PlantafelContext): boolean {
|
||||
return hasPermission(ctx, "plantafel.read_all") || hasPermission(ctx, "plantafel.read_own");
|
||||
}
|
||||
|
||||
function canReadAllPlantafel(ctx: PlantafelContext): boolean {
|
||||
return hasPermission(ctx, "plantafel.read_all");
|
||||
}
|
||||
|
||||
function requirePlantafelRead(ctx: PlantafelContext): void {
|
||||
if (!canReadPlantafel(ctx)) throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
|
||||
function requireAcceptanceRead(ctx: PlantafelContext): void {
|
||||
if (!hasPermission(ctx, "acceptance.read") && !hasPermission(ctx, "acceptance.write") && !hasPermission(ctx, "acceptance.admin")) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeClientMutationId(value?: string | null): string | null {
|
||||
return normalizeText(value)?.slice(0, 120) ?? null;
|
||||
}
|
||||
|
||||
function classifyAcceptanceKind(defects: readonly AcceptanceDefectInput[] = []): AcceptanceKind {
|
||||
if (defects.some((defect) => defect.classification === "critical")) return "rejected";
|
||||
if (defects.some((defect) => defect.classification === "minor")) return "with_defects";
|
||||
return "full";
|
||||
}
|
||||
|
||||
async function detectScheduleConflicts(input: {
|
||||
tenantId: string;
|
||||
assignedUserId: string;
|
||||
startAt: Date;
|
||||
endAt: Date;
|
||||
excludeEntryId?: string | null;
|
||||
}): Promise<Array<Omit<ScheduleConflictRow, "id" | "tenantId" | "entryId" | "createdAt" | "resolvedAt" | "overriddenAt">>> {
|
||||
const [overlapping, absences] = await Promise.all([
|
||||
withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.scheduleEntry.findMany({
|
||||
where: {
|
||||
tenantId: input.tenantId,
|
||||
assignedUserId: input.assignedUserId,
|
||||
archivedAt: null,
|
||||
status: { not: "cancelled" },
|
||||
startAt: { lt: input.endAt },
|
||||
endAt: { gt: input.startAt },
|
||||
...(input.excludeEntryId ? { id: { not: input.excludeEntryId } } : {}),
|
||||
},
|
||||
select: { id: true },
|
||||
}),
|
||||
),
|
||||
listApprovedAbsencesForRange(input.tenantId, input.startAt, input.endAt),
|
||||
]);
|
||||
const conflicts: Array<Omit<ScheduleConflictRow, "id" | "tenantId" | "entryId" | "createdAt" | "resolvedAt" | "overriddenAt">> = [];
|
||||
for (const entry of overlapping) {
|
||||
conflicts.push({
|
||||
type: "double_booking",
|
||||
severity: "blocking",
|
||||
messageKey: "projects.error.scheduleDoubleBooking",
|
||||
sourceKind: "schedule_entry",
|
||||
sourceId: entry.id,
|
||||
});
|
||||
}
|
||||
for (const absence of absences) {
|
||||
if (absence.employeeUserId === input.assignedUserId && intervalsOverlap(input.startAt, input.endAt, absence.startDate, absence.endDate)) {
|
||||
conflicts.push({
|
||||
type: "absence",
|
||||
severity: "blocking",
|
||||
messageKey: absence.source === "sick" ? "projects.error.scheduleSickConflict" : "projects.error.scheduleAbsenceConflict",
|
||||
sourceKind: absence.source,
|
||||
sourceId: absence.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
const startsBeforeWorkday = input.startAt.getHours() < DEFAULT_WORKDAY_START_HOUR;
|
||||
const endsAfterWorkday = input.endAt.getHours() > DEFAULT_WORKDAY_END_HOUR || (input.endAt.getHours() === DEFAULT_WORKDAY_END_HOUR && input.endAt.getMinutes() > 0);
|
||||
if (startsBeforeWorkday || endsAfterWorkday) {
|
||||
conflicts.push({
|
||||
type: "availability",
|
||||
severity: "warning",
|
||||
messageKey: "projects.error.scheduleAvailabilityConflict",
|
||||
sourceKind: "default_workday",
|
||||
sourceId: null,
|
||||
});
|
||||
}
|
||||
return conflicts;
|
||||
}
|
||||
|
||||
async function replaceScheduleConflicts(input: {
|
||||
tenantId: string;
|
||||
entryId: string;
|
||||
conflicts: Array<Omit<ScheduleConflictRow, "id" | "tenantId" | "entryId" | "createdAt" | "resolvedAt" | "overriddenAt">>;
|
||||
overridden: boolean;
|
||||
}): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
await tx.scheduleConflict.deleteMany({ where: { tenantId: input.tenantId, entryId: input.entryId } });
|
||||
if (input.conflicts.length === 0) return;
|
||||
const now = new Date();
|
||||
await tx.scheduleConflict.createMany({
|
||||
data: input.conflicts.map((conflict) => ({
|
||||
tenantId: input.tenantId,
|
||||
entryId: input.entryId,
|
||||
type: conflict.type,
|
||||
severity: conflict.severity,
|
||||
messageKey: conflict.messageKey,
|
||||
sourceKind: conflict.sourceKind,
|
||||
sourceId: conflict.sourceId,
|
||||
overriddenAt: input.overridden ? now : null,
|
||||
})),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadPlantafel(input: { tenantId: string; ctx: PlantafelContext; from: Date; to: Date; assignedUserId?: string | null }): Promise<PlantafelVM> {
|
||||
requirePlantafelRead(input.ctx);
|
||||
const assignedUserId = canReadAllPlantafel(input.ctx) ? normalizeText(input.assignedUserId) : input.ctx.userId;
|
||||
const [entries, absences] = await Promise.all([
|
||||
withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.scheduleEntry.findMany({
|
||||
where: {
|
||||
tenantId: input.tenantId,
|
||||
archivedAt: null,
|
||||
startAt: { lt: input.to },
|
||||
endAt: { gt: input.from },
|
||||
...(assignedUserId ? { assignedUserId } : {}),
|
||||
},
|
||||
include: { conflicts: { where: { resolvedAt: null }, orderBy: { createdAt: "asc" } } },
|
||||
orderBy: [{ startAt: "asc" }, { assignedUserId: "asc" }],
|
||||
}),
|
||||
),
|
||||
listApprovedAbsencesForRange(input.tenantId, input.from, input.to),
|
||||
]);
|
||||
return {
|
||||
entries: entries as ScheduleEntryRow[],
|
||||
absences: canReadAllPlantafel(input.ctx) ? absences : absences.filter((absence) => absence.employeeUserId === input.ctx.userId),
|
||||
generatedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
export async function upsertScheduleEntry(input: {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
projektId: string;
|
||||
assignedUserId: string;
|
||||
title: string;
|
||||
startAt: string | Date;
|
||||
endAt: string | Date;
|
||||
status?: ScheduleEntryStatus;
|
||||
entryId?: string | null;
|
||||
calendarEventId?: string | null;
|
||||
conflictOverrideReason?: string | null;
|
||||
clientMutationId?: string | null;
|
||||
}): Promise<{ entry: ScheduleEntryRow; conflicts: ScheduleConflictRow[] }> {
|
||||
const title = normalizeText(input.title);
|
||||
const assignedUserId = normalizeText(input.assignedUserId);
|
||||
const range = ensureRange(parseDate(input.startAt), parseDate(input.endAt));
|
||||
if (!title) throw new AuftragServiceError("projects.error.scheduleTitleRequired");
|
||||
if (!assignedUserId) throw new AuftragServiceError("projects.error.scheduleAssigneeRequired");
|
||||
const clientMutationId = normalizeClientMutationId(input.clientMutationId);
|
||||
if (clientMutationId) {
|
||||
const existing = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.scheduleEntry.findUnique({ where: { tenantId_clientMutationId: { tenantId: input.tenantId, clientMutationId } }, include: { conflicts: true } }),
|
||||
);
|
||||
if (existing) return { entry: existing as ScheduleEntryRow, conflicts: (existing.conflicts ?? []) as ScheduleConflictRow[] };
|
||||
}
|
||||
const conflicts = await detectScheduleConflicts({
|
||||
tenantId: input.tenantId,
|
||||
assignedUserId,
|
||||
startAt: range.startAt,
|
||||
endAt: range.endAt,
|
||||
excludeEntryId: input.entryId,
|
||||
});
|
||||
const blockingConflicts = conflicts.filter((conflict) => conflict.severity === "blocking");
|
||||
const overrideReason = normalizeText(input.conflictOverrideReason);
|
||||
if (blockingConflicts.length > 0 && !overrideReason) {
|
||||
throw new AuftragServiceError("projects.error.scheduleConflictOverrideRequired");
|
||||
}
|
||||
const entry = await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const project = await requireProjectWithTx(tx, { tenantId: input.tenantId, projectId: input.projektId });
|
||||
if (input.entryId) {
|
||||
const existing = await tx.scheduleEntry.findFirst({ where: { id: input.entryId, tenantId: input.tenantId, archivedAt: null }, select: { id: true } });
|
||||
if (!existing) throw new CatalogError(foundationErrors.notFound, { entryId: input.entryId });
|
||||
return tx.scheduleEntry.update({
|
||||
where: { id: input.entryId },
|
||||
data: {
|
||||
projektId: project.id,
|
||||
assignedUserId,
|
||||
title,
|
||||
startAt: range.startAt,
|
||||
endAt: range.endAt,
|
||||
status: input.status ?? "planned",
|
||||
calendarEventId: normalizeText(input.calendarEventId),
|
||||
syncStatus: "pending",
|
||||
conflictOverrideReason: overrideReason,
|
||||
},
|
||||
});
|
||||
}
|
||||
return tx.scheduleEntry.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
projektId: project.id,
|
||||
assignedUserId,
|
||||
createdByUserId: input.userId,
|
||||
title,
|
||||
startAt: range.startAt,
|
||||
endAt: range.endAt,
|
||||
status: input.status ?? "planned",
|
||||
calendarEventId: normalizeText(input.calendarEventId),
|
||||
conflictOverrideReason: overrideReason,
|
||||
clientMutationId,
|
||||
},
|
||||
});
|
||||
});
|
||||
await replaceScheduleConflicts({ tenantId: input.tenantId, entryId: entry.id, conflicts, overridden: Boolean(overrideReason) });
|
||||
await logActivity({
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.userId,
|
||||
actorKind: "user",
|
||||
activityType: "project_schedule_changed",
|
||||
subjectType: "project",
|
||||
subjectId: input.projektId,
|
||||
summaryText: "Plantafel-Termin wurde gespeichert.",
|
||||
metadata: { scheduleEntryId: entry.id, assignedUserId },
|
||||
}).catch(() => undefined);
|
||||
const saved = await withTenantRLS(input.tenantId, (tx) => tx.scheduleEntry.findUniqueOrThrow({ where: { id: entry.id }, include: { conflicts: true } }));
|
||||
return { entry: saved as ScheduleEntryRow, conflicts: (saved.conflicts ?? []) as ScheduleConflictRow[] };
|
||||
}
|
||||
|
||||
export async function updateScheduleEntryStatus(input: {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
entryId: string;
|
||||
status: ScheduleEntryStatus;
|
||||
clientMutationId?: string | null;
|
||||
}): Promise<ScheduleEntryRow> {
|
||||
const row = await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const existing = await tx.scheduleEntry.findFirst({ where: { id: input.entryId, tenantId: input.tenantId, archivedAt: null } });
|
||||
if (!existing) throw new CatalogError(foundationErrors.notFound, { entryId: input.entryId });
|
||||
return tx.scheduleEntry.update({ where: { id: existing.id }, data: { status: input.status, syncStatus: "pending" } });
|
||||
});
|
||||
await logActivity({
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.userId,
|
||||
actorKind: "user",
|
||||
activityType: "project_schedule_changed",
|
||||
subjectType: "project",
|
||||
subjectId: row.projektId,
|
||||
summaryText: "Plantafel-Status wurde geändert.",
|
||||
metadata: { scheduleEntryId: row.id, status: input.status },
|
||||
}).catch(() => undefined);
|
||||
return row as ScheduleEntryRow;
|
||||
}
|
||||
|
||||
export async function bulkReassignScheduleEntries(input: {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
entryIds: readonly string[];
|
||||
assignedUserId: string;
|
||||
conflictOverrideReason?: string | null;
|
||||
}): Promise<{ updated: number }> {
|
||||
const assignedUserId = normalizeText(input.assignedUserId);
|
||||
if (!assignedUserId) throw new AuftragServiceError("projects.error.scheduleAssigneeRequired");
|
||||
const overrideReason = normalizeText(input.conflictOverrideReason);
|
||||
let updated = 0;
|
||||
for (const entryId of input.entryIds) {
|
||||
const existing = await withTenantRLS(input.tenantId, (tx) => tx.scheduleEntry.findFirst({ where: { id: entryId, tenantId: input.tenantId, archivedAt: null } }));
|
||||
if (!existing) continue;
|
||||
const conflicts = await detectScheduleConflicts({
|
||||
tenantId: input.tenantId,
|
||||
assignedUserId,
|
||||
startAt: existing.startAt,
|
||||
endAt: existing.endAt,
|
||||
excludeEntryId: existing.id,
|
||||
});
|
||||
if (conflicts.some((conflict) => conflict.severity === "blocking") && !overrideReason) {
|
||||
throw new AuftragServiceError("projects.error.scheduleConflictOverrideRequired");
|
||||
}
|
||||
await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.scheduleEntry.update({ where: { id: existing.id }, data: { assignedUserId, syncStatus: "pending", conflictOverrideReason: overrideReason } }),
|
||||
);
|
||||
await replaceScheduleConflicts({ tenantId: input.tenantId, entryId: existing.id, conflicts, overridden: Boolean(overrideReason) });
|
||||
updated += 1;
|
||||
}
|
||||
return { updated };
|
||||
}
|
||||
|
||||
async function createAcceptancePdfFile(input: {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
project: ProjektRow;
|
||||
protocolId: string;
|
||||
acceptanceKind: AcceptanceKind;
|
||||
datum: Date;
|
||||
signatures: readonly AcceptanceSignatureInput[];
|
||||
}): Promise<{ fileId: string; storageKey: string; byteLength: number }> {
|
||||
await ensureServerGlobalI18n();
|
||||
const pdf = await buildPdfExportArtifact(
|
||||
{
|
||||
columns: [
|
||||
{ key: "field", label: i18next.t("projects.acceptance.pdf.columns.field") },
|
||||
{ key: "value", label: i18next.t("projects.acceptance.pdf.columns.value") },
|
||||
],
|
||||
rows: [
|
||||
{ field: i18next.t("projects.acceptance.pdf.fields.project"), value: `${input.project.projektNummer} ${input.project.projektname}` },
|
||||
{ field: i18next.t("projects.acceptance.pdf.fields.acceptance"), value: input.acceptanceKind },
|
||||
{ field: i18next.t("projects.acceptance.pdf.fields.date"), value: input.datum.toISOString() },
|
||||
{ field: i18next.t("projects.acceptance.pdf.fields.signatures"), value: input.signatures.map((signature) => `${signature.signerRole}:${signature.signerName}`).join(", ") },
|
||||
],
|
||||
},
|
||||
{ title: i18next.t("projects.acceptance.pdf.title") },
|
||||
);
|
||||
const fileId = `file_${randomUUID()}`;
|
||||
const { original } = buildFileStorageKeys(input.tenantId, fileId);
|
||||
const storageKey = original;
|
||||
await putBufferAsFile({ bucket: resolveStorageBucket(), key: storageKey, body: pdf.bytes, contentType: pdf.contentType });
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
await tx.file.create({
|
||||
data: {
|
||||
id: fileId,
|
||||
tenantId: input.tenantId,
|
||||
createdByUserId: input.userId,
|
||||
displayName: `acceptance-${input.project.projektNummer}.pdf`,
|
||||
mimeType: pdf.contentType,
|
||||
sizeBytes: pdf.byteLength,
|
||||
storageKey,
|
||||
source: "automation",
|
||||
scanStatus: "skipped",
|
||||
previewStatus: "pending",
|
||||
},
|
||||
});
|
||||
await tx.fileEntityLink.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
createdByUserId: input.userId,
|
||||
fileId,
|
||||
entityType: "project",
|
||||
entityId: input.project.id,
|
||||
linkRole: "acceptance_protocol",
|
||||
},
|
||||
});
|
||||
});
|
||||
return { fileId, storageKey, byteLength: pdf.byteLength };
|
||||
}
|
||||
|
||||
async function notifyProjectLead(input: { tenantId: string; userId: string | null; messageKey: string; sourceKey: string; metadata: Record<string, string> }): Promise<void> {
|
||||
if (!input.userId) return;
|
||||
await createNotificationDelivery({
|
||||
tenantId: input.tenantId,
|
||||
userId: input.userId,
|
||||
channel: "IN_APP",
|
||||
category: "projects",
|
||||
messageKey: input.messageKey,
|
||||
sourceKey: input.sourceKey,
|
||||
payloadMetadata: input.metadata,
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
|
||||
async function moveRejectedProjectBackWithTx(tx: TenantRlsClient, input: { tenantId: string; project: ProjektRow }): Promise<void> {
|
||||
const executionStage = await tx.pipelineStage.findFirst({
|
||||
where: { tenantId: input.tenantId, pipelineId: input.project.pipelineId, stageKind: "offen", archivedAt: null },
|
||||
orderBy: { position: "desc" },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!executionStage || executionStage.id === input.project.stageId) return;
|
||||
await tx.projekt.update({ where: { id: input.project.id }, data: { stageId: executionStage.id, wonAt: null, lostAt: null, lostReasonId: null } });
|
||||
}
|
||||
|
||||
export async function listAcceptanceProtocols(input: { tenantId: string; projectId: string; ctx: PlantafelContext }): Promise<AcceptanceListVM> {
|
||||
requireAcceptanceRead(input.ctx);
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const project = await requireProjectWithTx(tx, { tenantId: input.tenantId, projectId: input.projectId });
|
||||
const protocols = await tx.abnahmeProtokoll.findMany({
|
||||
where: { tenantId: input.tenantId, projektId: input.projectId, archivedAt: null },
|
||||
include: { signatures: { orderBy: { signedAt: "asc" } } },
|
||||
orderBy: { datum: "desc" },
|
||||
});
|
||||
return { project, protocols: protocols as AbnahmeProtokollRow[] };
|
||||
});
|
||||
}
|
||||
|
||||
export async function submitAcceptanceProtocol(input: {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
projectId: string;
|
||||
datum?: string | Date | null;
|
||||
maengelChecklistId?: string | null;
|
||||
defects?: readonly AcceptanceDefectInput[];
|
||||
anwesende?: unknown;
|
||||
druckprobe?: unknown;
|
||||
funktionspruefung?: unknown;
|
||||
zaehlerstaende?: unknown;
|
||||
dokumente?: unknown;
|
||||
bemerkungen?: string | null;
|
||||
signatures: readonly AcceptanceSignatureInput[];
|
||||
customerEmail?: string | null;
|
||||
clientMutationId?: string | null;
|
||||
}): Promise<AbnahmeProtokollRow> {
|
||||
const clientMutationId = normalizeClientMutationId(input.clientMutationId);
|
||||
if (clientMutationId) {
|
||||
const existing = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.abnahmeProtokoll.findUnique({ where: { tenantId_clientMutationId: { tenantId: input.tenantId, clientMutationId } }, include: { signatures: true } }),
|
||||
);
|
||||
if (existing) return existing as AbnahmeProtokollRow;
|
||||
}
|
||||
const datum = parseDate(input.datum) ?? new Date();
|
||||
const acceptanceKind = classifyAcceptanceKind(input.defects ?? []);
|
||||
const signatures = input.signatures.map((signature) => ({
|
||||
signerName: normalizeText(signature.signerName),
|
||||
signerRole: signature.signerRole,
|
||||
signatureFileId: normalizeText(signature.signatureFileId),
|
||||
signerIpHash: hashIpAddress(signature.signerIpAddress),
|
||||
}));
|
||||
if (!signatures.some((signature) => signature.signerRole === "kunde" && signature.signerName)) {
|
||||
throw new AuftragServiceError("projects.error.acceptanceCustomerSignatureRequired");
|
||||
}
|
||||
if (!signatures.some((signature) => signature.signerRole === "monteur" && signature.signerName)) {
|
||||
throw new AuftragServiceError("projects.error.acceptanceTechnicianSignatureRequired");
|
||||
}
|
||||
const maengelChecklistId = normalizeText(input.maengelChecklistId);
|
||||
const { project, checklistOk } = await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const project = await requireProjectWithTx(tx, { tenantId: input.tenantId, projectId: input.projectId });
|
||||
if (!maengelChecklistId) return { project, checklistOk: acceptanceKind === "full" };
|
||||
const checklist = await tx.projektChecklist.findFirst({
|
||||
where: { id: maengelChecklistId, tenantId: input.tenantId, projektId: input.projectId, typ: "maengel", archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
return { project, checklistOk: Boolean(checklist) };
|
||||
});
|
||||
if (!checklistOk) throw new AuftragServiceError("projects.error.acceptanceDefectChecklistRequired");
|
||||
const protocolId = `abn_${randomUUID()}`;
|
||||
const pdfFile = await createAcceptancePdfFile({
|
||||
tenantId: input.tenantId,
|
||||
userId: input.userId,
|
||||
project,
|
||||
protocolId,
|
||||
acceptanceKind,
|
||||
datum,
|
||||
signatures: input.signatures,
|
||||
});
|
||||
const protocol = await withTenantRLS(input.tenantId, async (tx) => {
|
||||
await tx.abnahmeProtokoll.create({
|
||||
data: {
|
||||
id: protocolId,
|
||||
tenantId: input.tenantId,
|
||||
projektId: project.id,
|
||||
maengelChecklistId,
|
||||
createdByUserId: input.userId,
|
||||
datum,
|
||||
acceptanceKind,
|
||||
anwesende: input.anwesende ?? [],
|
||||
druckprobe: input.druckprobe ?? {},
|
||||
funktionspruefung: input.funktionspruefung ?? {},
|
||||
zaehlerstaende: input.zaehlerstaende ?? {},
|
||||
dokumente: input.dokumente ?? [],
|
||||
bemerkungen: normalizeText(input.bemerkungen),
|
||||
pdfFileId: pdfFile.fileId,
|
||||
customerEmail: normalizeText(input.customerEmail),
|
||||
clientMutationId,
|
||||
gesperrtAt: new Date(),
|
||||
},
|
||||
});
|
||||
await tx.abnahmeSignatur.createMany({
|
||||
data: signatures.map((signature) => ({
|
||||
tenantId: input.tenantId,
|
||||
protokollId: protocolId,
|
||||
signerName: signature.signerName ?? "",
|
||||
signerRole: signature.signerRole,
|
||||
signatureFileId: signature.signatureFileId,
|
||||
signerIpHash: signature.signerIpHash,
|
||||
})),
|
||||
});
|
||||
if (acceptanceKind === "rejected") {
|
||||
await moveRejectedProjectBackWithTx(tx, { tenantId: input.tenantId, project });
|
||||
}
|
||||
return tx.abnahmeProtokoll.findUniqueOrThrow({ where: { id: protocolId }, include: { signatures: true } });
|
||||
});
|
||||
if (acceptanceKind === "with_defects" || acceptanceKind === "rejected") {
|
||||
await createTask({
|
||||
tenantId: input.tenantId,
|
||||
userId: input.userId,
|
||||
title: "projects.defaults.tasks.resolveAcceptanceDefects",
|
||||
description: protocol.id,
|
||||
priority: acceptanceKind === "rejected" ? "urgent" : "high",
|
||||
assignedToUserId: project.projektleiterId ?? project.zustaendigePersonId ?? input.userId,
|
||||
linkedEntityType: "project",
|
||||
linkedEntityId: project.id,
|
||||
source: "automation",
|
||||
sourceRef: protocol.id,
|
||||
}).catch(() => undefined);
|
||||
await notifyProjectLead({
|
||||
tenantId: input.tenantId,
|
||||
userId: project.projektleiterId ?? project.zustaendigePersonId,
|
||||
messageKey: acceptanceKind === "rejected" ? "projects.notify.acceptance.rejected" : "projects.notify.acceptance.withDefects",
|
||||
sourceKey: `acceptance:${protocol.id}:${acceptanceKind}`,
|
||||
metadata: { projectId: project.id, protocolId: protocol.id },
|
||||
});
|
||||
}
|
||||
const customerEmail = normalizeText(input.customerEmail);
|
||||
if (customerEmail) {
|
||||
await ensureServerGlobalI18n();
|
||||
const queued = await queueTransactionalEmail({
|
||||
tenantId: input.tenantId,
|
||||
userId: input.userId,
|
||||
to: customerEmail,
|
||||
subject: i18next.t("projects.acceptance.email.subject"),
|
||||
body: i18next.t("projects.acceptance.email.body", { pdfFileId: pdfFile.fileId }),
|
||||
alias: "projects.acceptance.protocol",
|
||||
data: { projectId: project.id, protocolId: protocol.id, pdfFileId: pdfFile.fileId },
|
||||
priorityOverride: "normal",
|
||||
}).then(
|
||||
() => true,
|
||||
() => false,
|
||||
);
|
||||
if (queued) {
|
||||
await withTenantRLS(input.tenantId, (tx) => tx.abnahmeProtokoll.update({ where: { id: protocol.id }, data: { customerEmailQueuedAt: new Date() } })).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
await logActivity({
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.userId,
|
||||
actorKind: "user",
|
||||
activityType: "project_acceptance_submitted",
|
||||
subjectType: "project",
|
||||
subjectId: project.id,
|
||||
summaryText: "Abnahmeprotokoll wurde gespeichert.",
|
||||
metadata: { protocolId: protocol.id, acceptanceKind, pdfFileId: pdfFile.fileId },
|
||||
}).catch(() => undefined);
|
||||
return withTenantRLS(input.tenantId, (tx) => tx.abnahmeProtokoll.findUniqueOrThrow({ where: { id: protocol.id }, include: { signatures: true } })) as Promise<AbnahmeProtokollRow>;
|
||||
}
|
||||
|
||||
export async function archiveAcceptanceProtocol(input: { tenantId: string; protocolId: string; userId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const protocol = await tx.abnahmeProtokoll.findFirst({ where: { id: input.protocolId, tenantId: input.tenantId, archivedAt: null }, select: { id: true } });
|
||||
if (!protocol) throw new CatalogError(foundationErrors.notFound, { protocolId: input.protocolId });
|
||||
await tx.abnahmeProtokoll.update({ where: { id: protocol.id }, data: { archivedAt: new Date() } });
|
||||
});
|
||||
}
|
||||
|
||||
export async function hardDeleteAcceptanceProtocol(): Promise<never> {
|
||||
throw new AuftragServiceError("projects.error.acceptanceHardDeleteBlocked");
|
||||
}
|
||||
|
||||
export async function applyOfflineMutation(input: {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
clientMutationId: string;
|
||||
operation: OfflineSyncOperation;
|
||||
payload: Record<string, unknown>;
|
||||
}): Promise<{ entityType: string; entityId: string }> {
|
||||
const clientMutationId = normalizeClientMutationId(input.clientMutationId);
|
||||
if (!clientMutationId) throw new AuftragServiceError("projects.error.offlineMutationIdRequired");
|
||||
const payloadJson = input.payload as Prisma.InputJsonValue;
|
||||
const existing = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.offlineSyncMutation.findUnique({ where: { tenantId_clientMutationId: { tenantId: input.tenantId, clientMutationId } } }),
|
||||
);
|
||||
if (existing?.status === "applied" && existing.resultEntityType && existing.resultEntityId) {
|
||||
return { entityType: existing.resultEntityType, entityId: existing.resultEntityId };
|
||||
}
|
||||
await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.offlineSyncMutation.upsert({
|
||||
where: { tenantId_clientMutationId: { tenantId: input.tenantId, clientMutationId } },
|
||||
update: { payload: payloadJson, status: "pending", errorMessageKey: null },
|
||||
create: {
|
||||
tenantId: input.tenantId,
|
||||
clientMutationId,
|
||||
createdByUserId: input.userId,
|
||||
operation: input.operation,
|
||||
payload: payloadJson,
|
||||
},
|
||||
}),
|
||||
);
|
||||
try {
|
||||
let result: { entityType: string; entityId: string };
|
||||
if (input.operation === "schedule_upsert") {
|
||||
const schedule = await upsertScheduleEntry({
|
||||
tenantId: input.tenantId,
|
||||
userId: input.userId,
|
||||
projektId: String(input.payload.projektId ?? ""),
|
||||
assignedUserId: String(input.payload.assignedUserId ?? ""),
|
||||
title: String(input.payload.title ?? ""),
|
||||
startAt: String(input.payload.startAt ?? ""),
|
||||
endAt: String(input.payload.endAt ?? ""),
|
||||
status: input.payload.status as ScheduleEntryStatus | undefined,
|
||||
clientMutationId,
|
||||
conflictOverrideReason: typeof input.payload.conflictOverrideReason === "string" ? input.payload.conflictOverrideReason : null,
|
||||
});
|
||||
result = { entityType: "schedule_entry", entityId: schedule.entry.id };
|
||||
} else if (input.operation === "schedule_status") {
|
||||
const schedule = await updateScheduleEntryStatus({
|
||||
tenantId: input.tenantId,
|
||||
userId: input.userId,
|
||||
entryId: String(input.payload.entryId ?? ""),
|
||||
status: input.payload.status as ScheduleEntryStatus,
|
||||
clientMutationId,
|
||||
});
|
||||
result = { entityType: "schedule_entry", entityId: schedule.id };
|
||||
} else {
|
||||
const protocol = await submitAcceptanceProtocol({
|
||||
tenantId: input.tenantId,
|
||||
userId: input.userId,
|
||||
projectId: String(input.payload.projectId ?? ""),
|
||||
maengelChecklistId: typeof input.payload.maengelChecklistId === "string" ? input.payload.maengelChecklistId : null,
|
||||
defects: Array.isArray(input.payload.defects) ? (input.payload.defects as AcceptanceDefectInput[]) : [],
|
||||
signatures: Array.isArray(input.payload.signatures) ? (input.payload.signatures as AcceptanceSignatureInput[]) : [],
|
||||
clientMutationId,
|
||||
});
|
||||
result = { entityType: "acceptance_protocol", entityId: protocol.id };
|
||||
}
|
||||
await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.offlineSyncMutation.update({
|
||||
where: { tenantId_clientMutationId: { tenantId: input.tenantId, clientMutationId } },
|
||||
data: { status: "applied", resultEntityType: result.entityType, resultEntityId: result.entityId, appliedAt: new Date() },
|
||||
}),
|
||||
);
|
||||
return result;
|
||||
} catch (error) {
|
||||
const messageKey = error instanceof AuftragServiceError ? error.messageKey : "projects.error.offlineMutationFailed";
|
||||
await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.offlineSyncMutation.update({ where: { tenantId_clientMutationId: { tenantId: input.tenantId, clientMutationId } }, data: { status: "failed", errorMessageKey: messageKey } }),
|
||||
).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
|
||||
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 { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { PROJECTS_MODULE_KEY } from "./projectRoutePaths";
|
||||
import { AuftragServiceError } from "./auftragService.server";
|
||||
import { ProjectServiceError, type ProjectVisibilityContext } from "./projectService.server";
|
||||
|
||||
export type ProjectRouteContext = ProjectVisibilityContext & {
|
||||
tenantId: string;
|
||||
hasModule: boolean;
|
||||
};
|
||||
|
||||
export async function loadProjectContext({
|
||||
request,
|
||||
params,
|
||||
requireModule = false,
|
||||
}: {
|
||||
request: Request;
|
||||
params: Record<string, string | undefined>;
|
||||
requireModule?: boolean;
|
||||
}): Promise<ProjectRouteContext> {
|
||||
await requireAuth({ request, params });
|
||||
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
|
||||
if (!tenantId || !userInfo.userId) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
const [hasModule, permissions] = await Promise.all([
|
||||
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: PROJECTS_MODULE_KEY }),
|
||||
getPermissionsByUser(userInfo.userId, tenantId),
|
||||
]);
|
||||
if (requireModule && !hasModule) {
|
||||
throw new CatalogError(foundationErrors.notFound, { module: PROJECTS_MODULE_KEY });
|
||||
}
|
||||
return { tenantId, userId: userInfo.userId, permissions, hasModule };
|
||||
}
|
||||
|
||||
export function requireProjectPermission(ctx: ProjectRouteContext, permission: string): ProjectRouteContext {
|
||||
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, permission);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
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");
|
||||
return ctx;
|
||||
}
|
||||
|
||||
export function projectActionErrorResponse(error: unknown): Response {
|
||||
if (error instanceof CatalogError) {
|
||||
return Response.json({ error: error.i18nKey, code: error.code }, { status: error.status });
|
||||
}
|
||||
if (error instanceof ProjectServiceError) {
|
||||
return Response.json({ error: error.messageKey }, { status: 400 });
|
||||
}
|
||||
if (error instanceof AuftragServiceError) {
|
||||
return Response.json({ error: error.messageKey }, { status: 400 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
export const PROJECTS_MODULE_KEY = "projects";
|
||||
|
||||
export function projectsPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/projects`;
|
||||
}
|
||||
|
||||
export function projectDetailPath(tenantSlug: string, projectId: string): string {
|
||||
return `/${tenantSlug}/projects/${projectId}`;
|
||||
}
|
||||
|
||||
export function projectsListPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/projects/list`;
|
||||
}
|
||||
|
||||
export function projectPipelinePath(tenantSlug: string, pipelineId: string): string {
|
||||
return `/${tenantSlug}/projects/pipelines/${pipelineId}`;
|
||||
}
|
||||
|
||||
export function projectPipelineStreamPath(tenantSlug: string, pipelineId: string): string {
|
||||
return `/${tenantSlug}/projects/pipelines/${pipelineId}/stream`;
|
||||
}
|
||||
|
||||
export function projectPlantafelPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/projects/plantafel`;
|
||||
}
|
||||
|
||||
export function projectAcceptancePath(tenantSlug: string, projectId: string): string {
|
||||
return `/${tenantSlug}/projects/${projectId}/acceptance`;
|
||||
}
|
||||
|
||||
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`;
|
||||
}
|
||||
+1454
File diff suppressed because it is too large.
Load diff
+336
@@ -0,0 +1,336 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolveRepoPath } from "~/utils/testing/repoPaths";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { ProjectServiceError, validatePipelineStages } from "./projectService.server";
|
||||
|
||||
describe("project pipeline validation", () => {
|
||||
test("accepts a pipeline with at least one won and lost stage", () => {
|
||||
expect(() =>
|
||||
validatePipelineStages([
|
||||
{ name: "Neu", stageKind: "offen" },
|
||||
{ name: "Gewonnen", stageKind: "gewonnen" },
|
||||
{ name: "Verloren", stageKind: "verloren" },
|
||||
]),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
test("rejects pipelines without a won stage", () => {
|
||||
expect(() =>
|
||||
validatePipelineStages([
|
||||
{ name: "Neu", stageKind: "offen" },
|
||||
{ name: "Verloren", stageKind: "verloren" },
|
||||
]),
|
||||
).toThrow(ProjectServiceError);
|
||||
});
|
||||
|
||||
test("rejects pipelines without a lost stage", () => {
|
||||
expect(() =>
|
||||
validatePipelineStages([
|
||||
{ name: "Neu", stageKind: "offen" },
|
||||
{ name: "Gewonnen", stageKind: "gewonnen" },
|
||||
]),
|
||||
).toThrow(ProjectServiceError);
|
||||
});
|
||||
});
|
||||
|
||||
describe("R-P8a project backend artifacts", () => {
|
||||
test("reserves project numbers with a row lock and without database extensions", () => {
|
||||
const source = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/projectService.server.ts"), "utf8");
|
||||
expect(source).toContain('FROM "HiveNumberSeq"');
|
||||
expect(source).toContain("FOR UPDATE");
|
||||
expect(source).not.toContain("gen_random_uuid");
|
||||
});
|
||||
|
||||
test("keeps all project models in the RLS rollout artifact", () => {
|
||||
const source = readFileSync(resolveRepoPath("prisma/rls/projekt-isolation.sql"), "utf8");
|
||||
[
|
||||
"HiveNumberSeq",
|
||||
"Pipeline",
|
||||
"PipelineStage",
|
||||
"PipelineAccess",
|
||||
"PipelineFieldConfig",
|
||||
"PipelineFieldVisibility",
|
||||
"LostReason",
|
||||
"Projekt",
|
||||
"ProjektStageChange",
|
||||
"PipelineAggregateSnapshot",
|
||||
"ProjektKontakt",
|
||||
].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");
|
||||
});
|
||||
|
||||
test("registers the project tenant models for snapshot and restore", () => {
|
||||
const source = readFileSync(resolveRepoPath("packages/cli/src/commands/tenant/models.ts"), "utf8");
|
||||
["HiveNumberSeq", "Pipeline", "PipelineStage", "Projekt", "ProjektStageChange", "PipelineAggregateSnapshot", "ProjektKontakt"].forEach((model) => {
|
||||
expect(source).toContain(`model: "${model}"`);
|
||||
expect(source).toContain('schema: "projekt.prisma"');
|
||||
});
|
||||
});
|
||||
|
||||
test("exposes server-side pipeline and lost-reason mutations for the later screen layer", () => {
|
||||
const service = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/projectService.server.ts"), "utf8");
|
||||
[
|
||||
"export async function createPipeline",
|
||||
"export async function updatePipeline",
|
||||
"export async function archivePipeline",
|
||||
"export async function duplicatePipeline",
|
||||
"export async function upsertPipelineAccess",
|
||||
"export async function upsertPipelineFieldConfig",
|
||||
"export async function upsertPipelineFieldVisibility",
|
||||
"export async function upsertLostReason",
|
||||
"export async function archiveLostReason",
|
||||
].forEach((exportName) => {
|
||||
expect(service).toContain(exportName);
|
||||
});
|
||||
});
|
||||
|
||||
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");
|
||||
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(lostReasonsRoute).toContain('"projects.admin"');
|
||||
expect(lostReasonsRoute).toContain('intent === "upsertLostReason"');
|
||||
expect(lostReasonsRoute).toContain('intent === "archiveLostReason"');
|
||||
});
|
||||
|
||||
test("wires the lead conversion route into the P8 auto-project service", () => {
|
||||
const route = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/leads.$id.tsx"), "utf8");
|
||||
expect(route).toContain("createProjectFromQualifiedLead");
|
||||
expect(route).toContain('intent === "convert"');
|
||||
});
|
||||
});
|
||||
|
||||
describe("R-P8b project board and forecast backend artifacts", () => {
|
||||
test("persists stage history and aggregate cache in the project schema", () => {
|
||||
const source = readFileSync(resolveRepoPath("prisma/schema/projekt.prisma"), "utf8");
|
||||
expect(source).toContain("model ProjektStageChange");
|
||||
expect(source).toContain("undoUntil");
|
||||
expect(source).toContain("model PipelineAggregateSnapshot");
|
||||
expect(source).toContain("weightedForecast");
|
||||
expect(source).toContain("@@unique([tenantId, pipelineId, scopeKey])");
|
||||
});
|
||||
|
||||
test("exposes board, list, forecast, stage move, undo, and CSV service contracts", () => {
|
||||
const service = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/projectService.server.ts"), "utf8");
|
||||
[
|
||||
"export async function loadProjectBoard",
|
||||
"export async function listProjectsForTable",
|
||||
"export async function exportProjectListCsv",
|
||||
"export async function rebuildPipelineAggregateCache",
|
||||
"export async function getPipelineForecast",
|
||||
"export async function moveProjectStage",
|
||||
"export async function undoLastProjectStageChange",
|
||||
].forEach((exportName) => {
|
||||
expect(service).toContain(exportName);
|
||||
});
|
||||
expect(service).toContain('event: "deal.won"');
|
||||
expect(service).toContain('"projects.error.lostReasonRequired"');
|
||||
expect(service).toContain("pipelineFieldVisibility");
|
||||
expect(service).toContain("deals.read_aggregates");
|
||||
});
|
||||
|
||||
test("routes provide board actions, list CSV, pipeline forecast, and SSE stream contracts", () => {
|
||||
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 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(listRoute).toContain('export") === "csv"');
|
||||
expect(listRoute).toContain("text/csv; charset=utf-8");
|
||||
expect(pipelineRoute).toContain("getPipelineForecast");
|
||||
expect(streamRoute).toContain("eventStream");
|
||||
expect(streamRoute).toContain("projects.board.snapshot");
|
||||
});
|
||||
});
|
||||
|
||||
describe("R-P9a order view and project sub-area backend artifacts", () => {
|
||||
test("keeps order work as sub-areas on the existing project core", () => {
|
||||
const source = readFileSync(resolveRepoPath("prisma/schema/auftrag.prisma"), "utf8");
|
||||
[
|
||||
"model ProjektMitglied",
|
||||
"model ProjektTermin",
|
||||
"model Rechnung",
|
||||
"model ProjektChecklist",
|
||||
"model ProjektChecklistItem",
|
||||
"model AuftragPipelineStageConfig",
|
||||
"model AcceptanceFormTemplate",
|
||||
"model ProjectTemplate",
|
||||
].forEach((model) => {
|
||||
expect(source).toContain(model);
|
||||
});
|
||||
expect(source).toContain("projektId");
|
||||
expect(source).not.toMatch(/^model\s+Auftrag\s+\{/m);
|
||||
expect(source).not.toContain("ProjektExternesFeld");
|
||||
});
|
||||
|
||||
test("reserves invoice numbers through HiveNumberSeq with a row lock", () => {
|
||||
const source = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/auftragService.server.ts"), "utf8");
|
||||
expect(source).toContain('FROM "HiveNumberSeq"');
|
||||
expect(source).toContain("FOR UPDATE");
|
||||
expect(source).toContain("entityType");
|
||||
expect(source).toContain("rechnung");
|
||||
expect(source).toContain('padStart(padding, "0")');
|
||||
});
|
||||
|
||||
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}'`);
|
||||
},
|
||||
);
|
||||
expect(source).toContain("ENABLE ROW LEVEL SECURITY");
|
||||
expect(source).toContain("FORCE ROW LEVEL SECURITY");
|
||||
expect(source).toContain("hivegrid_app");
|
||||
});
|
||||
|
||||
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"');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("exposes order sub-area service contracts for the later screen layer", () => {
|
||||
const service = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/auftragService.server.ts"), "utf8");
|
||||
[
|
||||
"export async function loadProjectSubAreas",
|
||||
"export async function addProjectMember",
|
||||
"export async function createProjectAppointment",
|
||||
"export async function createProjectInvoice",
|
||||
"export async function updateProjectInvoiceStatus",
|
||||
"export async function createProjectChecklist",
|
||||
"export async function upsertProjectChecklistItem",
|
||||
"export async function upsertAuftragPipelineStageConfig",
|
||||
"export async function listAcceptanceFormTemplates",
|
||||
"export async function upsertAcceptanceFormTemplate",
|
||||
"export async function listProjectTemplates",
|
||||
"export async function upsertProjectTemplate",
|
||||
"export async function autoArchiveProjectsForStageConfigs",
|
||||
].forEach((exportName) => {
|
||||
expect(service).toContain(exportName);
|
||||
});
|
||||
});
|
||||
|
||||
test("routes gate sub-area and template actions through the projects module and permissions", () => {
|
||||
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");
|
||||
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"');
|
||||
});
|
||||
|
||||
test("seeds the additional projects permission needed by order memberships", () => {
|
||||
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");
|
||||
expect(defaultPermissions).toContain('"projects.read_own_member"');
|
||||
expect(permissionSeed).toContain('"projects.read_own_member"');
|
||||
});
|
||||
});
|
||||
|
||||
describe("R-P9b schedule board and acceptance backend artifacts", () => {
|
||||
test("persists plantafel, acceptance, signature, and offline-sync models in the order schema", () => {
|
||||
const source = readFileSync(resolveRepoPath("prisma/schema/auftrag.prisma"), "utf8");
|
||||
[
|
||||
"model ScheduleEntry",
|
||||
"model ScheduleConflict",
|
||||
"model AbnahmeProtokoll",
|
||||
"model AbnahmeSignatur",
|
||||
"model OfflineSyncMutation",
|
||||
"enum AcceptanceKind",
|
||||
"enum ScheduleEntryStatus",
|
||||
].forEach((needle) => {
|
||||
expect(source).toContain(needle);
|
||||
});
|
||||
expect(source).toContain("gesperrtAt");
|
||||
expect(source).toContain("signerIpHash");
|
||||
expect(source).toContain("@@unique([tenantId, clientMutationId])");
|
||||
});
|
||||
|
||||
test("keeps all R-P9b models in RLS and tenant snapshot artifacts", () => {
|
||||
const rls = readFileSync(resolveRepoPath("prisma/rls/auftrag-isolation.sql"), "utf8");
|
||||
const tenantModels = readFileSync(resolveRepoPath("packages/cli/src/commands/tenant/models.ts"), "utf8");
|
||||
["ScheduleEntry", "ScheduleConflict", "AbnahmeProtokoll", "AbnahmeSignatur", "OfflineSyncMutation"].forEach((model) => {
|
||||
expect(rls).toContain(`'${model}'`);
|
||||
expect(tenantModels).toContain(`model: "${model}"`);
|
||||
expect(tenantModels).toContain('schema: "auftrag.prisma"');
|
||||
});
|
||||
});
|
||||
|
||||
test("exposes plantafel, acceptance, offline sync, PDF, and notification contracts", () => {
|
||||
const service = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/plantafelAcceptanceService.server.ts"), "utf8");
|
||||
[
|
||||
"export async function loadPlantafel",
|
||||
"export async function upsertScheduleEntry",
|
||||
"export async function updateScheduleEntryStatus",
|
||||
"export async function bulkReassignScheduleEntries",
|
||||
"export async function listAcceptanceProtocols",
|
||||
"export async function submitAcceptanceProtocol",
|
||||
"export async function archiveAcceptanceProtocol",
|
||||
"export async function hardDeleteAcceptanceProtocol",
|
||||
"export async function applyOfflineMutation",
|
||||
].forEach((exportName) => {
|
||||
expect(service).toContain(exportName);
|
||||
});
|
||||
expect(service).toContain("listApprovedAbsencesForRange");
|
||||
expect(service).toContain("buildPdfExportArtifact");
|
||||
expect(service).toContain("queueTransactionalEmail");
|
||||
expect(service).toContain("createNotificationDelivery");
|
||||
expect(service).toContain("createTask");
|
||||
});
|
||||
|
||||
test("blocks stage moves when a target stage requires an acceptance protocol", () => {
|
||||
const service = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/projectService.server.ts"), "utf8");
|
||||
expect(service).toContain("requiresAcceptanceProtocol");
|
||||
expect(service).toContain("abnahmeProtokoll.findFirst");
|
||||
expect(service).toContain('"projects.error.acceptanceProtocolRequired"');
|
||||
});
|
||||
|
||||
test("routes expose plantafel, acceptance list, and acceptance submit contracts behind module gates", () => {
|
||||
const plantafelRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects.plantafel.tsx"), "utf8");
|
||||
const acceptanceRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects.$id.acceptance._index.tsx"), "utf8");
|
||||
const acceptanceNewRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects.$id.acceptance.new.tsx"), "utf8");
|
||||
expect(plantafelRoute).toContain("loadPlantafel");
|
||||
expect(plantafelRoute).toContain('intent === "upsertSchedule"');
|
||||
expect(plantafelRoute).toContain('intent === "offlineSync"');
|
||||
expect(plantafelRoute).toContain('"plantafel.bulk_reassign"');
|
||||
expect(acceptanceRoute).toContain("listAcceptanceProtocols");
|
||||
expect(acceptanceRoute).toContain('intent === "archiveAcceptanceProtocol"');
|
||||
expect(acceptanceNewRoute).toContain("submitAcceptanceProtocol");
|
||||
expect(acceptanceNewRoute).toContain('"acceptance.write"');
|
||||
});
|
||||
|
||||
test("registers R-P9b permissions and labels", () => {
|
||||
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}"`);
|
||||
},
|
||||
);
|
||||
expect(roleDisplay).toContain("bulk_reassign");
|
||||
expect(roleDisplay).toContain("plantafel");
|
||||
expect(roleDisplay).toContain("acceptance");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user