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 { 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>> { 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> = []; 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>; overridden: boolean; }): Promise { 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 { 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 { 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 }): Promise { 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 { 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 { 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 { 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; } export async function archiveAcceptanceProtocol(input: { tenantId: string; protocolId: string; userId: string }): Promise { 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 { throw new AuftragServiceError("projects.error.acceptanceHardDeleteBlocked"); } export async function applyOfflineMutation(input: { tenantId: string; userId: string; clientMutationId: string; operation: OfflineSyncOperation; payload: Record; }): 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; } }