import { createHash, randomUUID } from "node:crypto"; import { fromZonedTime, toZonedTime } from "date-fns-tz"; import { createIdempotencyStore } from "@hivegrid/shared-store"; import { requestScopedT as i18nT } from "~/locale/request-scoped-t"; import { APP_TIME_ZONE } from "~/locale/format"; import { buildFileStorageKeys } from "@hivegrid/storage"; import type { Prisma } from "@hivegrid/db/prisma-browser"; import { withTenantStorageWriteReservation } from "@hivegrid/db/storage-capacity.server"; import { buildPortalStatusMailOutboxEvent, CatalogError, foundationErrors, massActionErrors, notify } from "@hivegrid/foundation"; import { logActivity } from "@hivegrid/activity"; import { createScopedLogger } from "~/utils/logger.server"; import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox"; import { buildWorkflowTriggerOutboxEvent } from "@hivegrid/queue"; import { ensureServerGlobalI18n } from "~/locale/i18next.global.server"; import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server"; import { deleteFile, putBufferAsFile, resolveStorageBucket } from "~/utils/integrations/storageService"; import { queueTransactionalEmail } from "~/modules/emails/services/TransactionalEmailQueue.server"; import { renderSystemMessageEmail } from "@hivegrid/mail"; import { getSharedStore } from "~/shared-store.server"; import { createAcceptanceFollowUpTask } from "~/utils/integrations/taskService.server"; import { listApprovedAbsencesForRange, listApprovedAbsencesForRangeWithTx, type ApprovedAbsence } from "~/utils/integrations/hrLeaveService.server"; import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus"; import { fileReadScopeWhereWithTx } from "../fileVisibility.server"; import { AuftragServiceError } from "./auftragService.server"; import type { ProjectRouteContext } from "./projectAccess.server"; import { projectEditScopeWhere, projectReadScopeWhere, 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 = ProjectRouteContext; 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[]; projectLabels: PlantafelProjectOption[]; editableProjectIds: string[]; generatedAt: string; }; export type PlantafelProjectOption = { id: string; label: string; }; export type PlantafelProjectPickerResult = { options: PlantafelProjectOption[]; hasMore: boolean; query: 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; export const PLANTAFEL_BULK_REASSIGN_MAX_ENTRIES = 100; export const PLANTAFEL_MAX_RANGE_DAYS = 31; export const PLANTAFEL_PROJECT_PICKER_LIMIT = 25; const OFFLINE_SYNC_OPERATIONS = ["schedule_upsert", "schedule_status", "acceptance_submit"] as const; const SCHEDULE_ENTRY_STATUSES = ["planned", "confirmed", "in_progress", "done", "cancelled"] as const; function normalizeText(value?: string | null): string | null { const normalized = value?.trim(); return normalized || null; } export function normalizeBulkScheduleEntryIds(entryIds: readonly string[]): string[] { if (entryIds.length > PLANTAFEL_BULK_REASSIGN_MAX_ENTRIES) { throw new CatalogError(massActionErrors.exceedsLimit, { affected: entryIds.length, hardLimit: PLANTAFEL_BULK_REASSIGN_MAX_ENTRIES, }); } return [...new Set(entryIds.map((entryId) => normalizeText(entryId)).filter((entryId): entryId is string => Boolean(entryId)))]; } function hasPermission(ctx: PlantafelContext, permission: string): boolean { return ctx.permissions.includes(permission); } function requireContextTenant(tenantId: string, ctx: PlantafelContext): void { if (ctx.tenantId !== tenantId) throw new CatalogError(foundationErrors.notFound); } function requirePermission(ctx: PlantafelContext, permission: string): void { if (!hasPermission(ctx, permission)) throw new CatalogError(foundationErrors.notFound); } export function parseOfflineSyncOperation(value: unknown): OfflineSyncOperation { if (typeof value === "string" && (OFFLINE_SYNC_OPERATIONS as readonly string[]).includes(value)) { return value as OfflineSyncOperation; } throw new AuftragServiceError("projects.error.unsupportedAction"); } function parseScheduleEntryStatus(value: unknown): ScheduleEntryStatus { if (typeof value === "string" && (SCHEDULE_ENTRY_STATUSES as readonly string[]).includes(value)) { return value as ScheduleEntryStatus; } throw new AuftragServiceError("projects.error.unsupportedAction"); } export function permissionForOfflineSyncOperation(operation: OfflineSyncOperation): "plantafel.write" | "acceptance.write" { switch (operation) { case "schedule_upsert": case "schedule_status": return "plantafel.write"; case "acceptance_submit": return "acceptance.write"; } } const ZONELESS_DATE_TIME_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?$/u; 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; } export function parsePlantafelDateInput(value: string | Date | null | undefined): Date | null { if (!value) return null; if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value; const normalized = value.trim(); const parsed = ZONELESS_DATE_TIME_PATTERN.test(normalized) ? fromZonedTime(normalized, APP_TIME_ZONE) : new Date(normalized); 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 }; } export function ensurePlantafelRange(from: Date, to: Date): { from: Date; to: Date } { const range = ensureRange(parsePlantafelDateInput(from), parsePlantafelDateInput(to)); const maxRangeMs = PLANTAFEL_MAX_RANGE_DAYS * 24 * 60 * 60 * 1000; if (range.endAt.getTime() - range.startAt.getTime() > maxRangeMs) { throw new AuftragServiceError("projects.error.scheduleRangeInvalid"); } return { from: range.startAt, to: range.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; ctx: PlantafelContext; editable?: boolean } ): Promise { const accessScope = input.editable ? projectEditScopeWhere(input.tenantId, input.ctx) : projectReadScopeWhere(input.tenantId, input.ctx); const project = await tx.projekt.findFirst({ where: { tenantId: input.tenantId, archivedAt: null, AND: [{ id: input.projectId }, accessScope], }, }); 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; } const OFFLINE_MUTATION_CLAIM_TTL_SECONDS = 30 * 60; function canonicalJsonValue(value: unknown): unknown { if (Array.isArray(value)) return value.map((item) => canonicalJsonValue(item)); if (value && typeof value === "object") { return Object.fromEntries( Object.entries(value) .filter(([, item]) => item !== undefined) .sort(([left], [right]) => left.localeCompare(right)) .map(([key, item]) => [key, canonicalJsonValue(item)]) ); } if (typeof value === "number" && !Number.isFinite(value)) return null; return value; } function offlinePayloadFingerprint(payload: unknown): string { return createHash("sha256") .update(JSON.stringify(canonicalJsonValue(payload))) .digest("hex"); } async function requireActiveTenantAssigneeWithTx(tx: TenantRlsClient, tenantId: string, userId: string): Promise { const assignee = await tx.tenantUser.findFirst({ where: { tenantId, userId, status: TenantUserStatus.ACTIVE, user: { active: true }, }, select: { userId: true }, }); if (!assignee) throw new CatalogError(foundationErrors.notFound, { assignedUserId: userId }); } async function lockScheduleWriteWithTx( tx: TenantRlsClient, input: { tenantId: string; assignedUserId: string; clientMutationId?: string | null } ): Promise { if (input.clientMutationId) { const mutationLockKey = `plantafel:mutation:${input.tenantId}:${input.clientMutationId}`; await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${mutationLockKey}, 0))`; } const assigneeLockKey = `plantafel:assignee:${input.tenantId}:${input.assignedUserId}`; await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${assigneeLockKey}, 0))`; } async function lockScheduleEntryRowWithTx(tx: TenantRlsClient, tenantId: string, entryId: string): Promise { await tx.$executeRaw` SELECT 1 FROM "ScheduleEntry" WHERE "tenantId" = ${tenantId} AND "id" = ${entryId} AND "archivedAt" IS NULL FOR UPDATE `; } async function requireVisibleSignatureFilesWithTx( tx: TenantRlsClient, input: { tenantId: string; fileIds: readonly string[]; ctx: PlantafelContext } ): Promise { const fileIds = [...new Set(input.fileIds.filter(Boolean))]; if (fileIds.length === 0) return; const visibility = await fileReadScopeWhereWithTx(tx, input.tenantId, input.ctx, fileIds); const files = await tx.file.findMany({ where: { tenantId: input.tenantId, id: { in: fileIds }, archivedAt: null, ...visibility }, select: { id: true }, }); if (files.length !== fileIds.length) throw new CatalogError(foundationErrors.notFound); } 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"; } type DetectedScheduleConflict = Omit; function buildScheduleConflicts(input: { assignedUserId: string; startAt: Date; endAt: Date; overlapping: ReadonlyArray<{ id: string; startAt: Date; endAt: Date }>; absences: readonly ApprovedAbsence[]; }): DetectedScheduleConflict[] { const conflicts: DetectedScheduleConflict[] = []; for (const entry of input.overlapping) { if (!intervalsOverlap(input.startAt, input.endAt, entry.startAt, entry.endAt)) continue; conflicts.push({ type: "double_booking", severity: "blocking", messageKey: "projects.error.scheduleDoubleBooking", sourceKind: "schedule_entry", sourceId: entry.id, }); } for (const absence of input.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 localStart = toZonedTime(input.startAt, APP_TIME_ZONE); const localEnd = toZonedTime(input.endAt, APP_TIME_ZONE); const startsBeforeWorkday = localStart.getHours() < DEFAULT_WORKDAY_START_HOUR; const endsAfterWorkday = localEnd.getHours() > DEFAULT_WORKDAY_END_HOUR || (localEnd.getHours() === DEFAULT_WORKDAY_END_HOUR && localEnd.getMinutes() > 0); if (startsBeforeWorkday || endsAfterWorkday) { conflicts.push({ type: "availability", severity: "warning", messageKey: "projects.error.scheduleAvailabilityConflict", sourceKind: "default_workday", sourceId: null, }); } return conflicts; } export async function loadPlantafel(input: { tenantId: string; ctx: PlantafelContext; from: Date; to: Date; assignedUserId?: string | null; }): Promise { requireContextTenant(input.tenantId, input.ctx); requirePlantafelRead(input.ctx); const range = ensurePlantafelRange(input.from, input.to); const assignedUserId = canReadAllPlantafel(input.ctx) ? normalizeText(input.assignedUserId) : input.ctx.userId; const [schedule, absences] = await Promise.all([ withTenantRLS(input.tenantId, async (tx) => { const candidates = await tx.scheduleEntry.findMany({ where: { tenantId: input.tenantId, archivedAt: null, startAt: { lt: range.to }, endAt: { gt: range.from }, ...(assignedUserId ? { assignedUserId } : {}), }, include: { conflicts: { where: { resolvedAt: null }, orderBy: { createdAt: "asc" } } }, orderBy: [{ startAt: "asc" }, { assignedUserId: "asc" }], }); if (candidates.length === 0) return { entries: [], projectLabels: [], editableProjectIds: [] }; const candidateProjectIds = [...new Set(candidates.map(({ projektId }) => projektId))]; const [projects, editableProjects] = await Promise.all([ tx.projekt.findMany({ where: { tenantId: input.tenantId, id: { in: candidateProjectIds }, archivedAt: null, ...projectReadScopeWhere(input.tenantId, input.ctx), }, select: { id: true, projektNummer: true, projektname: true }, }), hasPermission(input.ctx, "plantafel.write") ? tx.projekt.findMany({ where: { tenantId: input.tenantId, id: { in: candidateProjectIds }, archivedAt: null, ...projectEditScopeWhere(input.tenantId, input.ctx), }, select: { id: true }, }) : Promise.resolve([]), ]); const visibleProjectIds = new Set(projects.map(({ id }) => id)); return { entries: candidates.filter(({ projektId }) => visibleProjectIds.has(projektId)), projectLabels: projects.map((project) => ({ id: project.id, label: `${project.projektNummer} · ${project.projektname}`, })), editableProjectIds: editableProjects.map(({ id }) => id).filter((id) => visibleProjectIds.has(id)), }; }), listApprovedAbsencesForRange(input.tenantId, range.from, range.to), ]); return { entries: schedule.entries as ScheduleEntryRow[], absences: canReadAllPlantafel(input.ctx) ? absences : absences.filter((absence) => absence.employeeUserId === input.ctx.userId), projectLabels: schedule.projectLabels, editableProjectIds: schedule.editableProjectIds, generatedAt: new Date().toISOString(), }; } export async function listEditablePlantafelProjectOptions(input: { tenantId: string; ctx: PlantafelContext; query?: string | null; }): Promise { requireContextTenant(input.tenantId, input.ctx); requirePermission(input.ctx, "plantafel.write"); const query = normalizeText(input.query)?.slice(0, 120) ?? ""; return withTenantRLS(input.tenantId, async (tx) => { const projects = await tx.projekt.findMany({ where: { tenantId: input.tenantId, archivedAt: null, AND: [ projectEditScopeWhere(input.tenantId, input.ctx), ...(query ? [ { OR: [{ projektNummer: { contains: query, mode: "insensitive" } }, { projektname: { contains: query, mode: "insensitive" } }], }, ] : []), ], }, select: { id: true, projektNummer: true, projektname: true }, orderBy: [{ updatedAt: "desc" }, { id: "asc" }], take: PLANTAFEL_PROJECT_PICKER_LIMIT + 1, }); const hasMore = projects.length > PLANTAFEL_PROJECT_PICKER_LIMIT; return { options: projects.slice(0, PLANTAFEL_PROJECT_PICKER_LIMIT).map((project) => ({ id: project.id, label: `${project.projektNummer} · ${project.projektname}`, })), hasMore, query, }; }); } export async function upsertScheduleEntry(input: { tenantId: string; ctx: PlantafelContext; 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[] }> { requireContextTenant(input.tenantId, input.ctx); requirePermission(input.ctx, "plantafel.write"); const title = normalizeText(input.title); const assignedUserId = normalizeText(input.assignedUserId); const range = ensureRange(parsePlantafelDateInput(input.startAt), parsePlantafelDateInput(input.endAt)); const status = parseScheduleEntryStatus(input.status ?? "planned"); if (!title) throw new AuftragServiceError("projects.error.scheduleTitleRequired"); if (!assignedUserId) throw new AuftragServiceError("projects.error.scheduleAssigneeRequired"); const clientMutationId = normalizeClientMutationId(input.clientMutationId); const overrideReason = normalizeText(input.conflictOverrideReason); const saved = await withTenantRLS(input.tenantId, async (tx) => { await lockScheduleWriteWithTx(tx, { tenantId: input.tenantId, assignedUserId, clientMutationId }); await requireActiveTenantAssigneeWithTx(tx, input.tenantId, assignedUserId); const project = await requireProjectWithTx(tx, { tenantId: input.tenantId, projectId: input.projektId, ctx: input.ctx, editable: true, }); if (clientMutationId) { const idempotentEntry = await tx.scheduleEntry.findFirst({ where: { tenantId: input.tenantId, clientMutationId }, include: { conflicts: true }, }); if (idempotentEntry) { if (idempotentEntry.projektId !== project.id || idempotentEntry.createdByUserId !== input.ctx.userId) { throw new CatalogError(foundationErrors.notFound); } return idempotentEntry; } } if (input.entryId) { const existing = await tx.scheduleEntry.findFirst({ where: { id: input.entryId, tenantId: input.tenantId, archivedAt: null }, select: { projektId: true }, }); if (!existing) throw new CatalogError(foundationErrors.notFound, { entryId: input.entryId }); await requireProjectWithTx(tx, { tenantId: input.tenantId, projectId: existing.projektId, ctx: input.ctx, editable: true, }); } const [overlapping, absences] = await Promise.all([ tx.scheduleEntry.findMany({ where: { tenantId: input.tenantId, assignedUserId, archivedAt: null, status: { not: "cancelled" }, startAt: { lt: range.endAt }, endAt: { gt: range.startAt }, ...(input.entryId ? { id: { not: input.entryId } } : {}), }, select: { id: true, startAt: true, endAt: true }, }), listApprovedAbsencesForRangeWithTx(tx, input.tenantId, range.startAt, range.endAt), ]); const conflicts = buildScheduleConflicts({ assignedUserId, startAt: range.startAt, endAt: range.endAt, overlapping, absences, }); if (!overrideReason && conflicts.some(({ severity }) => severity === "blocking")) { throw new AuftragServiceError("projects.error.scheduleConflictOverrideRequired"); } const entry = input.entryId ? await tx.scheduleEntry.update({ where: { id: input.entryId, tenantId: input.tenantId }, data: { projektId: project.id, assignedUserId, title, startAt: range.startAt, endAt: range.endAt, status, calendarEventId: normalizeText(input.calendarEventId), syncStatus: "pending", conflictOverrideReason: overrideReason, }, }) : await tx.scheduleEntry.create({ data: { tenantId: input.tenantId, projektId: project.id, assignedUserId, createdByUserId: input.ctx.userId, title, startAt: range.startAt, endAt: range.endAt, status, calendarEventId: normalizeText(input.calendarEventId), conflictOverrideReason: overrideReason, clientMutationId, }, }); await tx.scheduleConflict.deleteMany({ where: { tenantId: input.tenantId, entryId: entry.id } }); if (conflicts.length > 0) { const now = new Date(); await tx.scheduleConflict.createMany({ data: conflicts.map((conflict) => ({ tenantId: input.tenantId, entryId: entry.id, type: conflict.type, severity: conflict.severity, messageKey: conflict.messageKey, sourceKind: conflict.sourceKind, sourceId: conflict.sourceId, overriddenAt: overrideReason ? now : null, })), }); } return tx.scheduleEntry.findUniqueOrThrow({ where: { id: entry.id }, include: { conflicts: true } }); }); await logActivity({ tenantId: input.tenantId, actorUserId: input.ctx.userId, actorKind: "user", activityType: "project_schedule_changed", subjectType: "project", subjectId: input.projektId, summaryText: "activity.runtime.projects.scheduleSaved", metadata: { scheduleEntryId: saved.id, assignedUserId }, }).catch(() => undefined); return { entry: saved as ScheduleEntryRow, conflicts: (saved.conflicts ?? []) as ScheduleConflictRow[] }; } export async function updateScheduleEntryStatus(input: { tenantId: string; ctx: PlantafelContext; entryId: string; status: ScheduleEntryStatus; clientMutationId?: string | null; }): Promise { requireContextTenant(input.tenantId, input.ctx); requirePermission(input.ctx, "plantafel.write"); const status = parseScheduleEntryStatus(input.status); const row = await withTenantRLS(input.tenantId, async (tx) => { const candidate = await tx.scheduleEntry.findFirst({ where: { id: input.entryId, tenantId: input.tenantId, archivedAt: null }, select: { assignedUserId: true }, }); if (!candidate) throw new CatalogError(foundationErrors.notFound, { entryId: input.entryId }); await lockScheduleWriteWithTx(tx, { tenantId: input.tenantId, assignedUserId: candidate.assignedUserId, clientMutationId: normalizeClientMutationId(input.clientMutationId), }); await lockScheduleEntryRowWithTx(tx, input.tenantId, input.entryId); // Reload after taking the assignee lock. A concurrent reassign or status // change may have invalidated the pre-lock snapshot. const existing = await tx.scheduleEntry.findFirst({ where: { id: input.entryId, tenantId: input.tenantId, archivedAt: null }, }); if (!existing || existing.assignedUserId !== candidate.assignedUserId) { throw new CatalogError(foundationErrors.notFound, { entryId: input.entryId }); } await requireProjectWithTx(tx, { tenantId: input.tenantId, projectId: existing.projektId, ctx: input.ctx, editable: true }); if (existing.status === "cancelled" && status !== "cancelled") { const [overlapping, absences] = await Promise.all([ tx.scheduleEntry.findMany({ where: { tenantId: input.tenantId, assignedUserId: existing.assignedUserId, archivedAt: null, status: { not: "cancelled" }, startAt: { lt: existing.endAt }, endAt: { gt: existing.startAt }, id: { not: existing.id }, }, select: { id: true, startAt: true, endAt: true }, }), listApprovedAbsencesForRangeWithTx(tx, input.tenantId, existing.startAt, existing.endAt), ]); const conflicts = buildScheduleConflicts({ assignedUserId: existing.assignedUserId, startAt: existing.startAt, endAt: existing.endAt, overlapping, absences, }); if (conflicts.some(({ severity }) => severity === "blocking")) { throw new AuftragServiceError("projects.error.scheduleConflictOverrideRequired"); } } return tx.scheduleEntry.update({ where: { id: existing.id, tenantId: input.tenantId }, data: { status, syncStatus: "pending" } }); }); await logActivity({ tenantId: input.tenantId, actorUserId: input.ctx.userId, actorKind: "user", activityType: "project_schedule_changed", subjectType: "project", subjectId: row.projektId, summaryText: "activity.runtime.projects.scheduleStatusChanged", metadata: { scheduleEntryId: row.id, status }, }).catch(() => undefined); return row as ScheduleEntryRow; } export async function bulkReassignScheduleEntries(input: { tenantId: string; ctx: PlantafelContext; entryIds: readonly string[]; assignedUserId: string; conflictOverrideReason?: string | null; }): Promise<{ updated: number }> { requireContextTenant(input.tenantId, input.ctx); requirePermission(input.ctx, "plantafel.bulk_reassign"); const assignedUserId = normalizeText(input.assignedUserId); if (!assignedUserId) throw new AuftragServiceError("projects.error.scheduleAssigneeRequired"); const entryIds = normalizeBulkScheduleEntryIds(input.entryIds); if (entryIds.length === 0) return { updated: 0 }; const overrideReason = normalizeText(input.conflictOverrideReason); const updated = await withTenantRLS(input.tenantId, async (tx) => { await lockScheduleWriteWithTx(tx, { tenantId: input.tenantId, assignedUserId }); await requireActiveTenantAssigneeWithTx(tx, input.tenantId, assignedUserId); const rows = await tx.scheduleEntry.findMany({ where: { id: { in: entryIds }, tenantId: input.tenantId, archivedAt: null }, select: { id: true, projektId: true, startAt: true, endAt: true, status: true }, }); if (rows.length !== entryIds.length) throw new CatalogError(foundationErrors.notFound); const projectIds = [...new Set(rows.map(({ projektId }) => projektId))]; const editableProjects = await tx.projekt.findMany({ where: { tenantId: input.tenantId, id: { in: projectIds }, archivedAt: null, ...projectEditScopeWhere(input.tenantId, input.ctx), }, select: { id: true }, }); if (editableProjects.length !== projectIds.length) { throw new CatalogError(foundationErrors.notFound); } const entryById = new Map(rows.map((row) => [row.id, row])); const entries = entryIds.flatMap((entryId) => { const entry = entryById.get(entryId); return entry ? [entry] : []; }); const minStart = new Date(Math.min(...entries.map(({ startAt }) => startAt.getTime()))); const maxEnd = new Date(Math.max(...entries.map(({ endAt }) => endAt.getTime()))); ensurePlantafelRange(minStart, maxEnd); const [externalOverlaps, absences] = await Promise.all([ tx.scheduleEntry.findMany({ where: { tenantId: input.tenantId, assignedUserId, id: { notIn: entryIds }, archivedAt: null, status: { not: "cancelled" }, startAt: { lt: maxEnd }, endAt: { gt: minStart }, }, select: { id: true, startAt: true, endAt: true }, }), listApprovedAbsencesForRangeWithTx(tx, input.tenantId, minStart, maxEnd), ]); const conflictsByEntry = new Map(); for (const entry of entries) { const selectedOverlaps = entries .filter((other) => other.id !== entry.id && other.status !== "cancelled") .map(({ id, startAt, endAt }) => ({ id, startAt, endAt })); const conflicts = buildScheduleConflicts({ assignedUserId, startAt: entry.startAt, endAt: entry.endAt, overlapping: [...externalOverlaps, ...selectedOverlaps], absences, }); conflictsByEntry.set(entry.id, conflicts); } if (!overrideReason && [...conflictsByEntry.values()].some((conflicts) => conflicts.some(({ severity }) => severity === "blocking"))) { throw new AuftragServiceError("projects.error.scheduleConflictOverrideRequired"); } const now = new Date(); const conflictRows = entries.flatMap((entry) => (conflictsByEntry.get(entry.id) ?? []).map((conflict) => ({ tenantId: input.tenantId, entryId: entry.id, type: conflict.type, severity: conflict.severity, messageKey: conflict.messageKey, sourceKind: conflict.sourceKind, sourceId: conflict.sourceId, overriddenAt: overrideReason ? now : null, })) ); const result = await tx.scheduleEntry.updateMany({ where: { id: { in: entryIds }, tenantId: input.tenantId, projektId: { in: projectIds }, archivedAt: null }, data: { assignedUserId, syncStatus: "pending", conflictOverrideReason: overrideReason }, }); if (result.count !== entries.length) throw new CatalogError(foundationErrors.notFound); await tx.scheduleConflict.deleteMany({ where: { tenantId: input.tenantId, entryId: { in: entryIds } } }); if (conflictRows.length > 0) await tx.scheduleConflict.createMany({ data: conflictRows }); return result.count; }); return { updated }; } type AcceptancePdfArtifact = { fileId: string; storageKey: string; bytes: Uint8Array; byteLength: number; mimeType: string; displayName: string; checksumSha256: string; }; async function createAcceptancePdfArtifact(input: { tenantId: string; project: ProjektRow; acceptanceKind: AcceptanceKind; datum: Date; signatures: readonly AcceptanceSignatureInput[]; }): Promise { await ensureServerGlobalI18n(); const { buildPdfExportArtifact } = await import("@hivegrid/exports/pdf"); const pdf = await buildPdfExportArtifact( { columns: [ { key: "field", label: i18nT("projects.acceptance.pdf.columns.field") }, { key: "value", label: i18nT("projects.acceptance.pdf.columns.value") }, ], rows: [ { field: i18nT("projects.acceptance.pdf.fields.project"), value: `${input.project.projektNummer} ${input.project.projektname}` }, { field: i18nT("projects.acceptance.pdf.fields.acceptance"), value: input.acceptanceKind }, { field: i18nT("projects.acceptance.pdf.fields.date"), value: input.datum.toISOString() }, { field: i18nT("projects.acceptance.pdf.fields.signatures"), value: input.signatures.map((signature) => `${signature.signerRole}:${signature.signerName}`).join(", "), }, ], }, { title: i18nT("projects.acceptance.pdf.title") } ); const fileId = `file_${randomUUID()}`; const { original } = buildFileStorageKeys(input.tenantId, fileId); const storageKey = original; return { fileId, storageKey, bytes: pdf.bytes, byteLength: pdf.bytes.byteLength, mimeType: pdf.contentType, displayName: `acceptance-${input.project.projektNummer}.pdf`, checksumSha256: createHash("sha256").update(pdf.bytes).digest("hex"), }; } function isUniqueConstraintError(error: unknown): boolean { return typeof error === "object" && error !== null && "code" in error && (error as { code?: unknown }).code === "P2002"; } const acceptanceNotifyLogger = createScopedLogger("projects.acceptance-notify"); /** * R-P9b DoD 4 — notify the project lead via the M011 service inside a * tenant-bound RLS transaction. Under FORCE RLS an unbound insert on * NotificationDelivery is rejected by the policy; the previous raw delivery * insert ran without a bound tenant context and swallowed that reject * silently. Still best-effort (the acceptance mutation * must not fail on notification delivery), but failures are logged now. */ async function notifyProjectLead(input: { tenantId: string; userId: string | null; messageKey: string; sourceKey: string; metadata: Record; }): Promise { if (!input.userId) return; const userId = input.userId; try { await withTenantRLS(input.tenantId, (tx) => notify( { tenantId: input.tenantId, userId, channel: "IN_APP", category: "projects", messageKey: input.messageKey, sourceKey: input.sourceKey, payloadMetadata: input.metadata, }, tx as unknown as Parameters[1] ) ); } catch (error) { acceptanceNotifyLogger.error({ error, sourceKey: input.sourceKey, messageKey: input.messageKey }, "acceptance-notify-failed"); } } async function moveRejectedProjectBackWithTx( tx: TenantRlsClient, input: { tenantId: string; project: ProjektRow; userId: string | null; sourceId: string } ): 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; const now = new Date(); const updated = await tx.projekt.update({ where: { id: input.project.id, tenantId: input.tenantId }, data: { stageId: executionStage.id, wonAt: null, lostAt: null, lostReasonId: null }, }); const stageChange = await tx.projektStageChange.create({ data: { tenantId: input.tenantId, projektId: input.project.id, fromStageId: input.project.stageId, toStageId: executionStage.id, changedByUserId: input.userId, undoUntil: null, }, }); await publishOutboxEvent( tx as unknown as OutboxPublisherTransaction, buildWorkflowTriggerOutboxEvent({ tenantId: input.tenantId, event: "project.stage_changed", data: { projectId: updated.id, tenantId: updated.tenantId, pipelineId: updated.pipelineId, stageId: updated.stageId, fromStageId: input.project.stageId, toStageId: executionStage.id, transitionReason: "acceptance_rejected", }, userId: input.userId, sourceId: `project:${input.project.id}:acceptance-rejected:${input.sourceId}`, }) ); await publishOutboxEvent( tx as unknown as OutboxPublisherTransaction, buildPortalStatusMailOutboxEvent( { tenantId: input.tenantId, projectId: input.project.id, previousStageId: input.project.stageId, expectedStageId: executionStage.id, stageChangeId: stageChange.id, }, { now } ) ); } export async function listAcceptanceProtocols(input: { tenantId: string; projectId: string; ctx: PlantafelContext }): Promise { requireContextTenant(input.tenantId, input.ctx); requireAcceptanceRead(input.ctx); return withTenantRLS(input.tenantId, async (tx) => { const project = await requireProjectWithTx(tx, { tenantId: input.tenantId, projectId: input.projectId, ctx: input.ctx }); 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; ctx: PlantafelContext; 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 { requireContextTenant(input.tenantId, input.ctx); requirePermission(input.ctx, "acceptance.write"); const project = await withTenantRLS(input.tenantId, (tx) => requireProjectWithTx(tx, { tenantId: input.tenantId, projectId: input.projectId, ctx: input.ctx, editable: true }) ); const clientMutationId = normalizeClientMutationId(input.clientMutationId); if (clientMutationId) { const existing = await withTenantRLS(input.tenantId, (tx) => tx.abnahmeProtokoll.findFirst({ where: { tenantId: input.tenantId, clientMutationId, projektId: project.id, createdByUserId: input.ctx.userId, }, 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 checklistOk = await withTenantRLS(input.tenantId, async (tx) => { await requireProjectWithTx(tx, { tenantId: input.tenantId, projectId: input.projectId, ctx: input.ctx, editable: true }); await requireVisibleSignatureFilesWithTx(tx, { tenantId: input.tenantId, fileIds: signatures.flatMap(({ signatureFileId }) => (signatureFileId ? [signatureFileId] : [])), ctx: input.ctx, }); if (!maengelChecklistId) return 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 Boolean(checklist); }); if (!checklistOk) throw new AuftragServiceError("projects.error.acceptanceDefectChecklistRequired"); const protocolId = `abn_${randomUUID()}`; const pdfFile = await createAcceptancePdfArtifact({ tenantId: input.tenantId, project, acceptanceKind, datum, signatures: input.signatures, }); const storageBucket = resolveStorageBucket(); let protocol: AbnahmeProtokollRow; try { const result = await withTenantStorageWriteReservation({ reservation: { tenantId: input.tenantId, actorUserId: input.ctx.userId, targetFileId: pdfFile.fileId, originalFilename: pdfFile.displayName, mimeType: pdfFile.mimeType, sizeBytes: pdfFile.byteLength, }, runTransaction: (operation) => withTenantRLS(input.tenantId, operation), upload: () => putBufferAsFile({ bucket: storageBucket, key: pdfFile.storageKey, body: pdfFile.bytes, contentType: pdfFile.mimeType, }), commit: async (tx) => { const editableProject = await requireProjectWithTx(tx, { tenantId: input.tenantId, projectId: input.projectId, ctx: input.ctx, editable: true, }); if (clientMutationId) { const existing = await tx.abnahmeProtokoll.findFirst({ where: { tenantId: input.tenantId, clientMutationId, projektId: editableProject.id, createdByUserId: input.ctx.userId, }, include: { signatures: true }, }); if (existing) return { protocol: existing as AbnahmeProtokollRow, created: false }; } await tx.file.create({ data: { id: pdfFile.fileId, tenantId: input.tenantId, createdByUserId: input.ctx.userId, displayName: pdfFile.displayName, mimeType: pdfFile.mimeType, sizeBytes: pdfFile.byteLength, storageKey: pdfFile.storageKey, checksumSha256: pdfFile.checksumSha256, source: "automation", // The PDF bytes are generated inside HiveGrid and never originate // from an uploaded object, so they are trusted at creation time. scanStatus: "clean", previewStatus: "pending", }, }); await tx.fileEntityLink.create({ data: { tenantId: input.tenantId, createdByUserId: input.ctx.userId, fileId: pdfFile.fileId, entityType: "project", entityId: editableProject.id, linkRole: "acceptance_protocol", }, }); await tx.abnahmeProtokoll.create({ data: { id: protocolId, tenantId: input.tenantId, projektId: editableProject.id, maengelChecklistId, createdByUserId: input.ctx.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: editableProject, userId: input.ctx.userId, sourceId: protocolId, }); } const created = await tx.abnahmeProtokoll.findUniqueOrThrow({ where: { id: protocolId }, include: { signatures: true } }); return { protocol: created as AbnahmeProtokollRow, created: true }; }, rollbackUpload: () => deleteFile({ bucket: storageBucket, key: pdfFile.storageKey }), }); if (!result.created) { await deleteFile({ bucket: storageBucket, key: pdfFile.storageKey }).catch(() => undefined); return result.protocol; } protocol = result.protocol; } catch (error) { let committed: AbnahmeProtokollRow | null; try { committed = (await withTenantRLS(input.tenantId, (tx) => tx.abnahmeProtokoll.findFirst({ where: { id: protocolId, tenantId: input.tenantId, pdfFileId: pdfFile.fileId, }, include: { signatures: true }, }) )) as AbnahmeProtokollRow | null; } catch { // The commit outcome is ambiguous. Preserve the object rather than risk // deleting bytes that a committed protocol may already reference. throw error; } if (committed) { protocol = committed; } else { if (clientMutationId && isUniqueConstraintError(error)) { const existing = await withTenantRLS(input.tenantId, (tx) => tx.abnahmeProtokoll.findFirst({ where: { tenantId: input.tenantId, clientMutationId, projektId: project.id, createdByUserId: input.ctx.userId, }, include: { signatures: true }, }) ); if (existing) return existing as AbnahmeProtokollRow; } throw error; } } if (acceptanceKind === "with_defects" || acceptanceKind === "rejected") { await createAcceptanceFollowUpTask({ tenantId: input.tenantId, ctx: input.ctx, title: "projects.defaults.tasks.resolveAcceptanceDefects", description: protocol.id, priority: acceptanceKind === "rejected" ? "urgent" : "high", assignedToUserId: project.projektleiterId ?? project.zustaendigePersonId ?? input.ctx.userId, linkedEntityType: "project", linkedEntityId: project.id, 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 subject = i18nT("projects.acceptance.email.subject"); const rendered = renderSystemMessageEmail({ locale: "de", subject, eyebrow: i18nT("projects.acceptance.email.eyebrow"), title: i18nT("projects.acceptance.email.title"), intro: i18nT("projects.acceptance.email.body", { pdfFileId: pdfFile.fileId }), notice: i18nT("projects.acceptance.email.notice"), }); const queued = await queueTransactionalEmail({ tenantId: input.tenantId, userId: input.ctx.userId, to: customerEmail, subject, body: rendered.html, text: rendered.text, 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.ctx.userId, actorKind: "user", activityType: "project_acceptance_submitted", subjectType: "project", subjectId: project.id, summaryText: "activity.runtime.projects.acceptanceSaved", 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; projectId: string; protocolId: string; ctx: PlantafelContext }): Promise { requireContextTenant(input.tenantId, input.ctx); requirePermission(input.ctx, "acceptance.admin"); await withTenantRLS(input.tenantId, async (tx) => { const project = await requireProjectWithTx(tx, { tenantId: input.tenantId, projectId: input.projectId, ctx: input.ctx, editable: true, }); const protocol = await tx.abnahmeProtokoll.findFirst({ where: { id: input.protocolId, tenantId: input.tenantId, projektId: project.id, archivedAt: null }, select: { id: true }, }); if (!protocol) throw new CatalogError(foundationErrors.notFound, { protocolId: input.protocolId }); await tx.abnahmeProtokoll.update({ where: { id: protocol.id, tenantId: input.tenantId }, data: { archivedAt: new Date() } }); }); } export async function hardDeleteAcceptanceProtocol(): Promise { throw new AuftragServiceError("projects.error.acceptanceHardDeleteBlocked"); } /** * R-P9b DoD 3 — AbnahmeProtokoll is immutable once `gesperrtAt` is stamped * (which happens at creation). There is intentionally NO content-update API; * this explicit refusal exists so a future caller hits a clear error instead * of quietly growing an update path. Allowed post-lock mutations remain only * the system-side `customerEmailQueuedAt` stamp and archiving via * archiveAcceptanceProtocol(). */ export async function updateAcceptanceProtocolContent(): Promise { throw new AuftragServiceError("projects.error.acceptanceProtocolImmutable"); } export async function applyOfflineMutation(input: { tenantId: string; ctx: PlantafelContext; clientMutationId: string; operation: unknown; payload: Record; }): Promise<{ entityType: string; entityId: string }> { requireContextTenant(input.tenantId, input.ctx); const operation = parseOfflineSyncOperation(input.operation); requirePermission(input.ctx, permissionForOfflineSyncOperation(operation)); const clientMutationId = normalizeClientMutationId(input.clientMutationId); if (!clientMutationId) throw new AuftragServiceError("projects.error.offlineMutationIdRequired"); const payloadJson = input.payload as Prisma.InputJsonValue; let existing = await withTenantRLS(input.tenantId, (tx) => tx.offlineSyncMutation.findUnique({ where: { tenantId_clientMutationId: { tenantId: input.tenantId, clientMutationId } } }) ); if (!existing) { try { existing = await withTenantRLS(input.tenantId, (tx) => tx.offlineSyncMutation.create({ data: { tenantId: input.tenantId, clientMutationId, createdByUserId: input.ctx.userId, operation, payload: payloadJson, }, }) ); } catch (error) { if (!isUniqueConstraintError(error)) throw error; existing = await withTenantRLS(input.tenantId, (tx) => tx.offlineSyncMutation.findUnique({ where: { tenantId_clientMutationId: { tenantId: input.tenantId, clientMutationId } } }) ); } } if ( !existing || existing.createdByUserId !== input.ctx.userId || existing.operation !== operation || offlinePayloadFingerprint(existing.payload) !== offlinePayloadFingerprint(input.payload) ) { throw new CatalogError(foundationErrors.notFound); } if (existing?.status === "applied" && existing.resultEntityType && existing.resultEntityId) { return { entityType: existing.resultEntityType, entityId: existing.resultEntityId }; } const claims = createIdempotencyStore({ store: getSharedStore(), prefix: "plantafel-offline-mutation", ttlSeconds: OFFLINE_MUTATION_CLAIM_TTL_SECONDS, }); const claimKey = `${input.tenantId}:${clientMutationId}`; if (!(await claims.claim(claimKey))) { const current = await withTenantRLS(input.tenantId, (tx) => tx.offlineSyncMutation.findUnique({ where: { tenantId_clientMutationId: { tenantId: input.tenantId, clientMutationId } } }) ); if ( current?.createdByUserId === input.ctx.userId && current.operation === operation && offlinePayloadFingerprint(current.payload) === offlinePayloadFingerprint(input.payload) && current.status === "applied" && current.resultEntityType && current.resultEntityId ) { return { entityType: current.resultEntityType, entityId: current.resultEntityId }; } throw new AuftragServiceError("projects.error.offlineMutationPending"); } try { if (existing.status === "failed") { await withTenantRLS(input.tenantId, (tx) => tx.offlineSyncMutation.updateMany({ where: { id: existing.id, tenantId: input.tenantId, status: "failed" }, data: { status: "pending", errorMessageKey: null }, }) ); } let result: { entityType: string; entityId: string }; switch (operation) { case "schedule_upsert": { const schedule = await upsertScheduleEntry({ tenantId: input.tenantId, ctx: input.ctx, 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 }; break; } case "schedule_status": { const schedule = await updateScheduleEntryStatus({ tenantId: input.tenantId, ctx: input.ctx, entryId: String(input.payload.entryId ?? ""), status: input.payload.status as ScheduleEntryStatus, clientMutationId, }); result = { entityType: "schedule_entry", entityId: schedule.id }; break; } case "acceptance_submit": { const protocol = await submitAcceptanceProtocol({ tenantId: input.tenantId, ctx: input.ctx, 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 }; break; } } const applied = await withTenantRLS(input.tenantId, (tx) => tx.offlineSyncMutation.updateMany({ where: { id: existing.id, tenantId: input.tenantId, status: "pending" }, data: { status: "applied", resultEntityType: result.entityType, resultEntityId: result.entityId, appliedAt: new Date() }, }) ); if (applied.count !== 1) throw new AuftragServiceError("projects.error.offlineMutationFailed"); await claims.complete(claimKey, result).catch(() => undefined); return result; } catch (error) { const messageKey = error instanceof AuftragServiceError ? error.messageKey : "projects.error.offlineMutationFailed"; await withTenantRLS(input.tenantId, (tx) => tx.offlineSyncMutation.updateMany({ where: { id: existing.id, tenantId: input.tenantId, status: "pending" }, data: { status: "failed", errorMessageKey: messageKey }, }) ).catch(() => undefined); await claims.forget(claimKey).catch(() => undefined); throw error; } }