import { useActionData, useLoaderData, useNavigation, useSubmit, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router"; import { buildProjectSubAreasVM, type ClickToCallVM, type PipelineHandoverVM, type ProjectSignaturePanelVM, type ProjectSubAreasScreenVM, } from "@hivegrid/view-models"; import { addProjectMember, createProjectAppointment, createProjectChecklist, createProjectInvoice, loadProjectSubAreas, removeProjectMember, updateProjectInvoiceStatus, upsertProjectChecklistItem, type ProjektChecklistTyp, type ProjektMitgliedRolle, type ProjektTerminTyp, type RechnungStatus, } from "~/utils/integrations/projects/auftragService.server"; import { CatalogError, foundationErrors } from "@hivegrid/foundation"; import { loadProjectContext, projectActionErrorResponse, projectNotFoundResponse, requireProjectPermission, requireProjectView, } from "~/utils/integrations/projects/projectAccess.server"; import { projectAcceptancePath, projectContactSearchPath, projectsBoardsPath, projectsPath } from "~/utils/integrations/projects/projectRoutePaths"; import { getTranslations } from "~/locale/i18next.server"; import { getProject, type ProjektRow } from "~/utils/integrations/projects/projectService.server"; import { createTask, TaskServiceError } from "~/utils/integrations/taskService.server"; import { loadProjektDetailP8, handleProjektDetailP8Intent, type ProjektDetailP8Data } from "~/utils/integrations/projects/projectDetailRoute.server"; import { ProjektDetailPage } from "~/components/screens/projects/ProjektDetailPage"; import { createSignatureDraft, loadProjectSignaturePanel, parseSignatureSigners, remindSignatureSigner, revokeSignatureDocument, sendSignatureDocument, SignatureServiceError, } from "~/modules/signature/services/signatureService.server"; import { filesDetailPath } from "~/utils/integrations/fileRoutePaths"; import { uploadFileInChunks } from "~/utils/files/uploadFileClient"; import { loadTelephonyContext } from "~/modules/telephony/routes/telephonyAccess.server"; import { loadProjectTelephonyClickToCallVM, startTelephonyEntityCall, TelephonyServiceError } from "~/modules/telephony/services/TelephonyService.server"; import { linkFile } from "~/utils/integrations/fileService.server"; import { createProjectNote, isProjektNotizSichtbarkeit, ProjektNotizServiceError, toProjektNotizContext, type ProjektNotizSichtbarkeit, } from "~/utils/integrations/projects/projektNotizService.server"; import { executeProjectHandover, parseHandoverSelection, PipelineHandoverServiceError, } from "~/utils/integrations/projects/pipelineHandoverService.server"; import { loadHandoverVM } from "~/utils/integrations/projects/pipelineHandoverRoute.server"; import { appendCSRFToken } from "~/utils/csrf"; import { validateCSRFToken } from "~/utils/session.server"; import { chatChannelPath } from "~/modules/chat/routes/chatRoutePaths"; import { loadOptionalProjectChatLink } from "~/modules/chat/services/projectChatLink.server"; import { invitePortalProjectContactFromEntrypoint, portalInvitationActionErrorResponse } from "~/services/customer-portal/portal-invitation-entrypoint.server"; import { useSaveToast } from "~/hooks/use-save-toast"; const PROJECT_DETAIL_SUCCESS_KEYS: Record = { invitePortalProjectContact: "projects.toast.portalInvitationSent", startTelephonyCall: "projects.toast.callStarted", updateStammdaten: "projects.toast.masterDataSaved", setCustomField: "projects.toast.customFieldSaved", updateAddresses: "projects.toast.addressesSaved", linkKontakt: "projects.toast.contactLinked", unlinkKontakt: "projects.toast.contactUnlinked", createKontakt: "projects.toast.contactCreatedAndLinked", moveStage: "projects.toast.stageChanged", undoStage: "projects.toast.stageChangeUndone", addMember: "projects.toast.memberAdded", removeMember: "projects.toast.memberRemoved", createAppointment: "projects.toast.appointmentCreated", createInvoice: "projects.toast.invoiceCreated", updateInvoiceStatus: "projects.toast.invoiceStatusSaved", createChecklist: "projects.toast.checklistCreated", upsertChecklistItem: "projects.toast.checklistItemSaved", createTask: "projects.toast.taskCreated", createNote: "projects.toast.noteCreated", attachFile: "projects.toast.fileAttached", handoverProject: "projects.toast.handoverCompleted", createSignatureDraft: "projects.toast.signatureDraftCreated", createAndSendSignatureDocument: "projects.toast.signatureDocumentSent", sendSignatureDocument: "projects.toast.signatureDocumentSent", remindSignatureSigner: "projects.toast.signatureReminderSent", revokeSignatureDocument: "projects.toast.signatureDocumentRevoked", }; function projectDetailSuccess(intent: string, payload: Record = {}) { return { ok: true, intent, messageKey: PROJECT_DETAIL_SUCCESS_KEYS[intent], ...payload }; } type LoaderData = { /** Page title consumed by the shell breadcrumb (useTitleData). */ title: string; /** Extra shell-breadcrumb crumbs before the project: Boards > . */ breadcrumbAncestors: { label: string; href: string }[]; tenantSlug: string; project: ProjektRow; operationsVM: ProjectSubAreasScreenVM; signature: ProjectSignaturePanelVM; p8: ProjektDetailP8Data; clickToCallVM: ClickToCallVM; /** WF-P8 M04 — non-null only when the project awaits a pipeline handover. */ handoverVM: PipelineHandoverVM | null; canChooseInternalNote: boolean; }; export async function loader({ request, params }: LoaderFunctionArgs) { const ctx = await requireProjectView({ request, params }, ["projects.read_all", "projects.read_own_pl", "projects.read_own", "projects.read_own_member"]); const { t, locale } = await getTranslations(request); const nowIso = new Date().toISOString(); try { const [subAreas, signature, p8, projectChat] = await Promise.all([ loadProjectSubAreas({ tenantId: ctx.tenantId, projectId: params.id!, ctx }), loadProjectSignaturePanel({ tenantId: ctx.tenantId, projectId: params.id!, tenantSlug: params.tenant!, ctx }), loadProjektDetailP8({ tenantId: ctx.tenantId, tenantSlug: params.tenant!, projectId: params.id!, ctx, nowIso, locale }), loadOptionalProjectChatLink({ request, params, projectId: params.id! }), ]); const operationsVM = buildProjectSubAreasVM(subAreas, { acceptanceHref: projectAcceptancePath(params.tenant!, subAreas.project.id), locale, chat: projectChat ? { href: chatChannelPath(params.tenant!, projectChat.chatId), archivedAtIso: projectChat.archivedAtIso, canWrite: projectChat.canWrite, } : null, }); const telephonyCtx = await loadTelephonyContext({ request, params, requireModule: false }); const detailData = p8.detailVM.status === "ready" ? p8.detailVM.data : null; const clickToCallVM = await loadProjectTelephonyClickToCallVM(telephonyCtx, { projectId: params.id!, contacts: detailData?.kontakte.map((contact) => ({ contactId: contact.kontaktId, label: contact.label, primary: contact.primaer, })) ?? [], }); // M04 is status-driven: the dialog is offered exactly when the project sits // in the final stage of a pipeline that declares a successor. Any failure // here (no successor, successor without an open stage) simply means "no // handover pending" and must not break the detail page. const handoverVM = await loadHandoverVM({ tenantId: ctx.tenantId, projectId: params.id!, ctx }); const boardHref = `${projectsPath(params.tenant!)}?pipelineId=${subAreas.project.pipelineId}`; return Response.json({ title: subAreas.project.projektname, // Shell breadcrumb: tenant > Boards > > . breadcrumbAncestors: [ { label: t("projects.boards.nav"), href: projectsBoardsPath(params.tenant!) }, ...(detailData ? [{ label: detailData.pipelineName, href: boardHref }] : []), ], tenantSlug: params.tenant!, project: subAreas.project, operationsVM, signature, p8, clickToCallVM, handoverVM, canChooseInternalNote: ctx.permissions.includes("projects.read_internal_notes"), } satisfies LoaderData); } catch (error) { // Unknown / not-visible project id -> graceful 404 instead of a 500. if (error instanceof CatalogError) throw projectNotFoundResponse(); throw error; } } function formString(formData: FormData, name: string): string | null { const value = formData.get(name); return typeof value === "string" ? value : null; } function formRole(formData: FormData): ProjektMitgliedRolle { const value = formString(formData, "rolle"); if (value === "projektleiter" || value === "zustaendig" || value === "beobachter") return value; return "monteur"; } function formChecklistType(formData: FormData): ProjektChecklistTyp { const value = formString(formData, "typ"); if (value === "maengel" || value === "abnahme_doku") return value; return "generisch"; } function formInvoiceStatus(formData: FormData): RechnungStatus { const value = formString(formData, "status"); if (value === "gestellt" || value === "bezahlt" || value === "storniert") return value; return "entwurf"; } function formNoteVisibility(formData: FormData): ProjektNotizSichtbarkeit { const value = formString(formData, "sichtbarkeit"); return value && isProjektNotizSichtbarkeit(value) ? value : "alle"; } function formAppointmentType(formData: FormData): ProjektTerminTyp | undefined { const value = formString(formData, "typ"); return value === "telefon" || value === "online" || value === "vor_ort" ? value : undefined; } function formPosition(formData: FormData): number | undefined { const value = formString(formData, "position"); if (!value) return undefined; const parsed = Number(value); return Number.isInteger(parsed) ? parsed : undefined; } export async function action({ request, params }: ActionFunctionArgs) { const ctx = await loadProjectContext({ request, params, requireModule: true }); const formData = await request.formData(); const intent = formString(formData, "_action"); const projectId = params.id!; try { if (intent === "invitePortalProjectContact") { await invitePortalProjectContactFromEntrypoint({ request, formData, context: ctx, projectId, contactId: formString(formData, "contactId") ?? "", assertTargetVisible: async () => { await getProject({ tenantId: ctx.tenantId, projectId, ctx }); }, }); return Response.json(projectDetailSuccess(intent)); } if (intent === "startTelephonyCall") { await validateCSRFToken(request, { formData }); await getProject({ tenantId: ctx.tenantId, projectId, ctx }); const telephonyCtx = await loadTelephonyContext({ request, params, requireModule: true }); await startTelephonyEntityCall(telephonyCtx, { entityType: "project", entityId: projectId, numberId: formString(formData, "numberId") ?? "", destination: formString(formData, "destination") ?? "", }); return Response.json(projectDetailSuccess(intent)); } // P8 core intents (stammdaten inline-edit, stage move, 24h-undo) — gated, // then delegated to the P8 handler. P9 (auftrag/signature) intents follow. if (intent === "updateStammdaten" || intent === "setCustomField" || intent === "updateAddresses") requireProjectPermission(ctx, "projects.write"); if (intent === "moveStage" || intent === "undoStage") requireProjectPermission(ctx, "projects.change_stage"); const handledP8 = await handleProjektDetailP8Intent({ intent, form: formData, tenantId: ctx.tenantId, projectId, ctx }); if (handledP8) { return Response.json(projectDetailSuccess(intent ?? "")); } if (intent === "addMember") { requireProjectPermission(ctx, "projects.manage_members"); const member = await addProjectMember({ tenantId: ctx.tenantId, projectId, ctx, createdByUserId: ctx.userId, userId: formString(formData, "userId"), groupId: formString(formData, "groupId"), rolle: formRole(formData), }); return Response.json(projectDetailSuccess(intent, { member })); } if (intent === "removeMember") { requireProjectPermission(ctx, "projects.manage_members"); const member = await removeProjectMember({ tenantId: ctx.tenantId, projectId, memberId: formString(formData, "memberId") ?? "", ctx, removedByUserId: ctx.userId, }); return Response.json(projectDetailSuccess(intent, { member })); } if (intent === "createAppointment") { requireProjectPermission(ctx, "projects.write"); const appointment = await createProjectAppointment({ tenantId: ctx.tenantId, projectId, ctx, createdByUserId: ctx.userId, titel: formString(formData, "titel") ?? "", beschreibung: formString(formData, "beschreibung"), startAt: formString(formData, "startAt") ?? "", endAt: formString(formData, "endAt"), assignedToUserId: formString(formData, "assignedToUserId"), assignedToGroupId: formString(formData, "assignedToGroupId"), typ: formAppointmentType(formData), }); return Response.json(projectDetailSuccess(intent, { appointment })); } if (intent === "createInvoice") { requireProjectPermission(ctx, "projects.write"); const invoice = await createProjectInvoice({ tenantId: ctx.tenantId, projectId, ctx, createdByUserId: ctx.userId, betrag: formString(formData, "betrag") ?? "0", datum: formString(formData, "datum"), faelligAm: formString(formData, "faelligAm"), dateiId: formString(formData, "dateiId"), }); return Response.json(projectDetailSuccess(intent, { invoice })); } if (intent === "updateInvoiceStatus") { requireProjectPermission(ctx, "projects.write"); const invoice = await updateProjectInvoiceStatus({ tenantId: ctx.tenantId, invoiceId: formString(formData, "invoiceId") ?? "", ctx, userId: ctx.userId, status: formInvoiceStatus(formData), }); return Response.json(projectDetailSuccess(intent, { invoice })); } if (intent === "createChecklist") { requireProjectPermission(ctx, "projects.write"); const checklist = await createProjectChecklist({ tenantId: ctx.tenantId, projectId, ctx, createdByUserId: ctx.userId, titel: formString(formData, "titel") ?? "", typ: formChecklistType(formData), }); return Response.json(projectDetailSuccess(intent, { checklist })); } if (intent === "upsertChecklistItem") { requireProjectPermission(ctx, "projects.write"); const item = await upsertProjectChecklistItem({ tenantId: ctx.tenantId, checklistId: formString(formData, "checklistId") ?? "", ctx, itemId: formString(formData, "itemId"), titel: formString(formData, "titel") ?? "", status: formString(formData, "status") === "erledigt" ? "erledigt" : "offen", maengelKlasse: formString(formData, "maengelKlasse"), fotoFileId: formString(formData, "fotoFileId"), assignedToUserId: formString(formData, "assignedToUserId"), dueAt: formString(formData, "dueAt"), position: formPosition(formData), }); return Response.json(projectDetailSuccess(intent, { item })); } if (intent === "createTask") { // Tasks sub-area quick-create; createTask enforces tasks.write and the // linked-entity visibility itself. const task = await createTask({ tenantId: ctx.tenantId, ctx, title: formString(formData, "title") ?? "", linkedEntityType: "project", linkedEntityId: projectId, tenantSlug: params.tenant, }); return Response.json(projectDetailSuccess(intent, { task })); } // --- WF-P8 S02 quick actions + M04 handover --- if (intent === "createNote") { requireProjectPermission(ctx, "projects.write"); const note = await createProjectNote({ tenantId: ctx.tenantId, projectId, ctx: toProjektNotizContext(ctx), autorUserId: ctx.userId, inhalt: formString(formData, "inhalt") ?? "", sichtbarkeit: formNoteVisibility(formData), }); return Response.json(projectDetailSuccess(intent, { note })); } if (intent === "attachFile") { requireProjectPermission(ctx, "projects.write"); if (!ctx.userId) throw new CatalogError(foundationErrors.notFound, { projectId }); // The file itself was already uploaded by the dialog; this only links it // to the project and stores the S02-F category as the link role. await linkFile({ tenantId: ctx.tenantId, userId: ctx.userId, fileId: formString(formData, "fileId") ?? "", entityType: "project", entityId: projectId, linkRole: formString(formData, "kategorie"), ctx, }); return Response.json(projectDetailSuccess(intent)); } if (intent === "handoverProject") { requireProjectPermission(ctx, "projects.handover"); const result = await executeProjectHandover({ tenantId: ctx.tenantId, projectId, userId: ctx.userId, ctx, selection: parseHandoverSelection(formString(formData, "selection")), }); return Response.json(projectDetailSuccess(intent, { handover: result })); } if (intent === "createSignatureDraft") { const document = await createSignatureDraft({ tenantId: ctx.tenantId, projectId, userId: ctx.userId, ctx, title: formString(formData, "title"), sourcePdfFileId: formString(formData, "sourcePdfFileId"), signers: parseSignatureSigners(formString(formData, "signers")), subject: formString(formData, "subject"), message: formString(formData, "message"), }); return Response.json(projectDetailSuccess(intent, { document })); } if (intent === "createAndSendSignatureDocument") { // Composition of the two existing service calls so the wizard can finish // in one submit; permissions are enforced inside both service functions. const document = await createSignatureDraft({ tenantId: ctx.tenantId, projectId, userId: ctx.userId, ctx, title: formString(formData, "title"), sourcePdfFileId: formString(formData, "sourcePdfFileId"), signers: parseSignatureSigners(formString(formData, "signers")), subject: formString(formData, "subject"), message: formString(formData, "message"), }); const publicBaseUrl = new URL(request.url).origin; const result = await sendSignatureDocument({ tenantId: ctx.tenantId, documentId: document.id, userId: ctx.userId, ctx, publicBaseUrl }); return Response.json(projectDetailSuccess(intent, { document, result })); } if (intent === "sendSignatureDocument") { const publicBaseUrl = new URL(request.url).origin; const result = await sendSignatureDocument({ tenantId: ctx.tenantId, documentId: formString(formData, "documentId") ?? "", userId: ctx.userId, ctx, publicBaseUrl, }); return Response.json(projectDetailSuccess(intent, { result })); } if (intent === "remindSignatureSigner") { const result = await remindSignatureSigner({ tenantId: ctx.tenantId, signerId: formString(formData, "signerId") ?? "", userId: ctx.userId, ctx }); return Response.json(projectDetailSuccess(intent, { result })); } if (intent === "revokeSignatureDocument") { const result = await revokeSignatureDocument({ tenantId: ctx.tenantId, documentId: formString(formData, "documentId") ?? "", userId: ctx.userId, ctx }); return Response.json(projectDetailSuccess(intent, { result })); } return Response.json({ intent, error: "projects.error.unsupportedAction" }, { status: 400 }); } catch (error) { if (error instanceof TelephonyServiceError) { return Response.json({ intent, error: error.messageKey }, { status: 400 }); } if (error instanceof SignatureServiceError) { return Response.json({ intent, error: error.messageKey }, { status: 400 }); } if (error instanceof TaskServiceError) { return Response.json({ intent, error: error.messageKey }, { status: 400 }); } if (error instanceof ProjektNotizServiceError || error instanceof PipelineHandoverServiceError) { return Response.json({ intent, error: error.messageKey }, { status: 400 }); } const portalInvitationError = portalInvitationActionErrorResponse(error); if (portalInvitationError) return portalInvitationError; return projectActionErrorResponse(error); } } export default function ProjectDetailRoute() { const data = useLoaderData(); const navigation = useNavigation(); const submit = useSubmit(); const actionData = useActionData<{ intent?: string; ok?: boolean; error?: string; messageKey?: string }>(); useSaveToast(actionData); const detailData = data.p8.detailVM.status === "ready" ? data.p8.detailVM.data : null; // The S02 rail lists the same project documents as the operations panel; only // the file-detail URL is added here, so the rail stays routing-agnostic. const railDocuments = data.operationsVM.status === "ready" ? data.operationsVM.data.documents.map((document) => ({ id: document.id, name: document.name, mimeType: document.mimeType, sizeLabel: document.sizeLabel, linkRole: document.linkRole, href: filesDetailPath(data.tenantSlug, document.id), })) : []; // Four of the five areas come from the P8 rail loader (which resolves assignee // names); the activity tile reuses the timeline the section below renders. const railAreas = { ...data.p8.railAreas, activity: (data.p8.activityVM.status === "ready" ? data.p8.activityVM.data.entries : []).slice(0, 8).map((entry) => ({ id: entry.id, label: entry.summaryText, labelKey: entry.summaryKey, meta: entry.actorLabel, atIso: entry.createdAtIso, })), }; const postAction = (intent: string, fields?: Record) => { const fd = new FormData(); fd.set("_action", intent); for (const [key, value] of Object.entries(fields ?? {})) fd.set(key, value); submit(intent === "invitePortalProjectContact" ? appendCSRFToken(fd) : fd, { method: "post" }); }; return (
{detailData ? ( uploadFileInChunks({ tenantSlug: data.tenantSlug, file }), handover: data.handoverVM, } : undefined } clickToCall={{ vm: data.clickToCallVM, // Only while a call is actually being placed. Tied to the page's // submitting flag, the button spun on every save — which reads as // "the call is going out" when the user pressed Speichern. busy: navigation.state !== "idle" && navigation.formData?.get("_action") === "startTelephonyCall", onCall: (number, mode) => { if (mode === "tel-fallback") { window.location.assign(`tel:${number.e164}`); return; } const form = new FormData(); form.set("_action", "startTelephonyCall"); form.set("numberId", number.id); form.set("destination", number.e164); submit(appendCSRFToken(form), { method: "post" }); }, }} actions={{ onSubmit: postAction, }} /> ) : null} {/* The "Auftrag & Ausführung" panel (P9) no longer hangs under S02 — the detail screen ends with its own groups. Its VM stays loaded: the S02 rail lists the project documents it carries. */}
); }