Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/components/screens/projects/ProjektDetailPage.tsx
T

380 lines
17 KiB
TypeScript

// R-P8a (P8 Projekt core) — project detail screen (WF-P8 S02), composed from
// ~/ui. Pure/presentational: it renders the server-built ProjektDetailData +
// ActivityStreamVM and turns every action (stammdaten inline-edit, stage move,
// 24h-undo) into a single typed onSubmit(intent, fields) callback the route
// POSTs. Moving into a "verloren" stage opens a real Dialog to capture the
// mandatory lost reason. No useLoaderData/useFetcher, no server imports.
//
// This file assembles; the sections live in ./detail. It owns exactly one piece
// of shared state — the stammdaten draft — because the screen has a single save
// path and splitting that across sections is how a second one appears.
import { useState } from "react";
import { useTranslation } from "react-i18next";
import type { ActivityStreamVM, PipelineHandoverKind, PipelineHandoverVM, ProjektDetailData } from "@hivegrid/view-models";
import { PageBody, PageShell } from "../shared/PageShell";
import { Alert } from "~/ui/components/Alert";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Dialog } from "~/ui/components/Dialog";
import { Select } from "~/ui/components/Select";
import { APP_TIME_ZONE } from "~/locale/format";
import { ClickToCallEntryPoint, type ClickToCallEntryPointProps } from "../telephony/ClickToCallDialog";
import {
CreateAppointmentDialog,
CreateNoteDialog,
CreateTaskDialog,
UploadFileDialog,
type ProjectAssigneeOption,
} from "./dialogs/ProjectQuickActionDialogs";
import { PipelineHandoverDialog } from "./dialogs/PipelineHandoverDialog";
import { AdressenSection } from "./detail/AdressenSection";
import { DetailSideRail, type ProjektDetailRailDocument, type ProjektDetailRailEntry } from "./detail/DetailSideRail";
import { DetailHeader } from "./detail/DetailHeader";
import { DetailQuickActionBar } from "./detail/DetailQuickActionBar";
import { GrunddatenSection } from "./detail/GrunddatenSection";
import { KontakteSection } from "./detail/KontakteSection";
import { KwpSection } from "./detail/KwpSection";
import { PlanungSection, type ProjektDetailOwnerOption } from "./detail/PlanungSection";
import { ProjektkontaktSection } from "./detail/ProjektkontaktSection";
import { mutedText, sectionHeading, toStammdatenState, type ProjektDetailSubmit } from "./detail/detailUi";
export type { ProjektDetailOwnerOption, ProjektDetailRailDocument, ProjektDetailSubmit };
export type ProjektDetailPageActions = { onSubmit: ProjektDetailSubmit };
/** WF-P8 S02 quick-action bar + M04 wiring supplied by the route. */
export type ProjektDetailQuickActions = {
/** Directory for the assignee pickers in the task/appointment modals. */
assigneeOptions: readonly ProjectAssigneeOption[];
/** True when the actor may pick "Nur Innendienst" as a note visibility. */
canChooseInternalNote: boolean;
/** Chunked upload injected by the route (S02-F uploads before linking). */
uploadFile: (file: File) => Promise<{ id: string; displayName: string }>;
/**
* M04 payload. Present only when the project sits in the final stage of a
* pipeline that declares a successor — the dialog opens automatically then,
* it is never opened by a button (validated with David).
*/
handover?: PipelineHandoverVM | null;
};
export type ProjektDetailPageProps = {
data: ProjektDetailData;
activity: ActivityStreamVM;
ownerOptions: readonly ProjektDetailOwnerOption[];
/** Project documents for the S02 rail; hrefs are resolved by the route. */
documents?: readonly ProjektDetailRailDocument[];
backHref: string;
/**
* Loader-only JSON resource behind the contact search of the add-contact block.
* Injected as a prop, because a UI component must not know how the route tree
* is laid out.
*/
contactSearchHref: string;
/**
* Read-only rows of the five rail areas besides Dateien. Resolved by the route:
* appointments and tasks come from the operations data it already loads, notes
* and history from their own readers.
*/
railAreas?: {
history: readonly ProjektDetailRailEntry[];
appointments: readonly ProjektDetailRailEntry[];
tasks: readonly ProjektDetailRailEntry[];
notes: readonly ProjektDetailRailEntry[];
activity: readonly ProjektDetailRailEntry[];
};
/** Anchor of the operations panel below, for the "manage" link of a tile. */
operationsHref?: string;
submitting: boolean;
errorKey?: string | null;
messageKey?: string | null;
language?: string;
/** Optional telephony affordance; omitted when the feature or permission gate is closed. */
clickToCall?: ClickToCallEntryPointProps;
/** WF-P8 S02 quick actions; omitted when the actor cannot write. */
quickActions?: ProjektDetailQuickActions;
actions: ProjektDetailPageActions;
};
export function ProjektDetailPage(props: ProjektDetailPageProps) {
const { t, i18n } = useTranslation();
const { data } = props;
const submit = props.actions.onSubmit;
const dateTime = new Intl.DateTimeFormat(props.language ?? i18n.language, { timeZone: APP_TIME_ZONE, dateStyle: "medium", timeStyle: "short" });
const [stammdaten, setStammdaten] = useState(() => toStammdatenState(data));
const [lostDialogStageId, setLostDialogStageId] = useState<string | null>(null);
const [lostReasonId, setLostReasonId] = useState(data.lostReasons[0]?.id ?? "");
// WF-P8 S02 quick actions. `null` = no modal open.
const [quickAction, setQuickAction] = useState<"note" | "task" | "appointment" | "file" | null>(null);
const quickActions = props.quickActions;
// Quick-action targets: the project's own contact data, else the primary
// linked contact's — a project without its own mailbox still has someone to
// write to, and a greyed-out button says the opposite.
const primaryKontakt = data.kontakte.find((kontakt) => kontakt.primaer) ?? data.kontakte[0] ?? null;
const quickActionMail = data.email ?? primaryKontakt?.email ?? null;
const quickActionPhone = data.telefon ?? primaryKontakt?.telefon ?? null;
const handoverVM = quickActions?.handover ?? null;
// M04 is status-driven, not button-driven: it opens as soon as the loader
// reports a pending handover, and closing it is an explicit dismissal.
const [handoverDismissed, setHandoverDismissed] = useState(false);
// Single stammdaten submit path (used by the edit banner; no duplicate logic).
function saveStammdaten() {
submit("updateStammdaten", {
projektname: stammdaten.projektname,
beschreibung: stammdaten.beschreibung,
prioritaet: stammdaten.prioritaet,
startDatum: stammdaten.startDatum,
deadline: stammdaten.deadline,
zustaendigePersonId: stammdaten.zustaendigePersonId,
projektleiterId: stammdaten.projektleiterId,
projekttyp: stammdaten.projekttyp,
quelle: stammdaten.quelle,
promotion: stammdaten.promotion,
email: stammdaten.email,
telefon: stammdaten.telefon,
fax: stammdaten.fax,
...(data.valueVisible ? { potenziellerAuftragswert: stammdaten.potenziellerAuftragswert, auftragsvolumen: stammdaten.auftragsvolumen } : {}),
});
}
/**
* Panel upload: file straight onto the project, without the modal. Category
* and description stay with the quick action — the panel is for "put this
* file on the project", the modal for filing it properly.
*/
async function uploadToProject(file: File) {
if (!quickActions) return;
const uploaded = await quickActions.uploadFile(file);
submit("attachFile", { fileId: uploaded.id, kategorie: "sonstiges", beschreibung: "" });
}
/** Sections report a patch; the draft itself stays here (single save path). */
function patchStammdaten(patch: Partial<typeof stammdaten>) {
setStammdaten((s) => ({ ...s, ...patch }));
}
function moveToStage(stageId: string, stageKind: string) {
if (stageKind === "verloren") {
setLostReasonId(data.lostReasons[0]?.id ?? "");
setLostDialogStageId(stageId);
return;
}
submit("moveStage", { targetStageId: stageId });
}
function confirmLost() {
if (!lostDialogStageId || !lostReasonId) return;
submit("moveStage", { targetStageId: lostDialogStageId, lostReasonId });
setLostDialogStageId(null);
}
return (
<PageShell uiId="ui.projects.detail" className="bg-surface-neutral-primary">
{/* The header band runs the full width of the page; the pipeline panel is
a column below it, not a strip pinned across it. */}
<DetailHeader data={data} backHref={props.backHref} submitting={props.submitting} onSave={data.canWrite ? saveStammdaten : undefined} />
<div className="flex w-full min-w-0 flex-col items-start xl:flex-row">
<div className="flex w-full min-w-0 grow flex-col">
<PageBody className="gap-3 p-3 mobile:p-3">
<div className="flex w-full min-w-0 flex-col gap-3">
{props.errorKey ? (
<div data-ui-id="ui.projects.detail.error">
<BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback>
</div>
) : null}
{props.messageKey ? (
<Alert
variant="success"
title={t("customerPortal.invitation.successTitle")}
description={t(props.messageKey)}
data-ui-id="ui.projects.detail.portalInviteSuccess"
/>
) : null}
{/* --- Won/Lost banner with 24h undo --- */}
{data.outcome ? (
<div className="border-border-default flex flex-wrap items-center gap-3 rounded-md border border-solid p-4" data-ui-id="ui.projects.detail.outcome">
<BadgeFeedback farbe={data.outcome.kind === "gewonnen" ? "subtle-positive" : "subtle-negative"}>
{t(data.outcome.kind === "gewonnen" ? "projects.outcome.won" : "projects.outcome.lost")}
</BadgeFeedback>
{data.outcome.lostReasonName ? <span className={mutedText}>{data.outcome.lostReasonName}</span> : null}
{data.outcome.atIso ? (
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{dateTime.format(new Date(data.outcome.atIso))}
</span>
) : null}
{data.outcome.canUndo ? (
<Button variant="neutral" size="small" loading={props.submitting} onClick={() => submit("undoStage")} data-ui-id="ui.projects.detail.undo">
{t("projects.actions.undoStage")}
</Button>
) : null}
</div>
) : null}
{/* The columns are wider than a laptop's leftover width once the pipeline
panel has its 340px, so the pair scrolls sideways in its own strip.
Without it the overflowing column would end up behind the panel with
no way to reach it. */}
<div className="w-full overflow-x-auto">
{/* Two columns, as in the export: the project's own data on the left, the
records it is linked to on the right. The left one is the wider of the
two — it carries the label gutter plus a full-width control per row.
Both have a minimum, so the pair scrolls sideways instead of squeezing
the fields into unreadable stubs. They stack below 1024px. */}
<div className="grid w-full items-start gap-3 lg:grid-cols-[minmax(585px,1fr)_minmax(596px,1fr)]">
<div className="flex min-w-0 flex-col gap-3">
<GrunddatenSection data={data} value={stammdaten} onChange={patchStammdaten} onMoveToStage={moveToStage} />
<PlanungSection
data={data}
ownerOptions={props.ownerOptions}
value={stammdaten}
onChange={patchStammdaten}
submitting={props.submitting}
submit={submit}
/>
<ProjektkontaktSection data={data} value={stammdaten} onChange={patchStammdaten} />
</div>
<div className="flex min-w-0 flex-col gap-3">
{/* Above the contacts, as in the export — and only for a project that
actually is bound to a KWP project. */}
<KwpSection data={data} dateTime={dateTime} />
<KontakteSection data={data} submitting={props.submitting} submit={submit} dateTime={dateTime} contactSearchHref={props.contactSearchHref} />
<AdressenSection data={data} submitting={props.submitting} submit={submit} />
</div>
</div>
</div>
{/* Sits at the end of the main column so it sticks above the content
without covering the last field of the page. */}
{quickActions ? (
<DetailQuickActionBar
onOpen={setQuickAction}
// The project's own channels first; without them the primary contact
// answers for the project, which is who a caller means anyway.
callHref={quickActionPhone ? `tel:${quickActionPhone}` : null}
mailHref={quickActionMail ? `mailto:${quickActionMail}` : null}
// Telephony belongs next to "Anrufen", not in the header — the export
// keeps the header to project id, board and save.
callSlot={props.clickToCall ? <ClickToCallEntryPoint {...props.clickToCall} variant="tertiary" /> : undefined}
/>
) : null}
</div>
</PageBody>
</div>
{/* Outside PageBody on purpose: the panel is the row's own column and
sticks to the window, so it must not sit in a column that scrolls. */}
<DetailSideRail
documents={props.documents ?? []}
onUpload={quickActions ? uploadToProject : undefined}
areas={props.railAreas ?? { history: [], appointments: [], tasks: [], notes: [], activity: [] }}
operationsHref={props.operationsHref}
dateTime={dateTime}
/>
</div>
{/* --- S02 quick-action modals (A/N/T/F) --- */}
{quickActions ? (
<>
<CreateNoteDialog
open={quickAction === "note"}
onOpenChange={(open) => setQuickAction(open ? "note" : null)}
submitting={props.submitting}
canChooseInternal={quickActions.canChooseInternalNote}
onSubmit={(intent, fields) => {
submit(intent, fields);
setQuickAction(null);
}}
/>
<CreateTaskDialog
open={quickAction === "task"}
onOpenChange={(open) => setQuickAction(open ? "task" : null)}
submitting={props.submitting}
assigneeOptions={quickActions.assigneeOptions}
onSubmit={(intent, fields) => {
submit(intent, fields);
setQuickAction(null);
}}
/>
<CreateAppointmentDialog
open={quickAction === "appointment"}
onOpenChange={(open) => setQuickAction(open ? "appointment" : null)}
submitting={props.submitting}
assigneeOptions={quickActions.assigneeOptions}
onSubmit={(intent, fields) => {
submit(intent, fields);
setQuickAction(null);
}}
/>
<UploadFileDialog
open={quickAction === "file"}
onOpenChange={(open) => setQuickAction(open ? "file" : null)}
submitting={props.submitting}
uploadFile={quickActions.uploadFile}
onSubmit={(intent, fields) => {
submit(intent, fields);
setQuickAction(null);
}}
/>
</>
) : null}
{/* --- M04 pipeline handover (status-driven, no trigger button) --- */}
{handoverVM ? (
<PipelineHandoverDialog
open={!handoverDismissed}
vm={handoverVM}
submitting={props.submitting}
onOpenChange={(open) => setHandoverDismissed(!open)}
onConfirm={(selection: readonly { kind: PipelineHandoverKind; sourceId: string }[]) => {
submit("handoverProject", { selection: JSON.stringify(selection) });
setHandoverDismissed(true);
}}
/>
) : null}
{/* --- Lost-reason dialog (mandatory when moving to a verloren stage) --- */}
<Dialog open={lostDialogStageId !== null} onOpenChange={(open) => (open ? null : setLostDialogStageId(null))}>
<Dialog.Content className="p-6" data-ui-id="ui.projects.detail.lostDialog">
<div className="flex w-full flex-col gap-4" style={{ minWidth: 420 }}>
<span className={sectionHeading}>{t("projects.lostDialog.title")}</span>
<Select label={t("projects.fields.lostReason")} showLabel value={lostReasonId} onValueChange={setLostReasonId}>
{data.lostReasons.map((reason) => (
<Select.Item key={reason.id} value={reason.id}>
{reason.name}
</Select.Item>
))}
</Select>
<div className="flex justify-end gap-2">
<Button variant="neutral" onClick={() => setLostDialogStageId(null)}>
{t("projects.actions.cancel")}
</Button>
<Button
variant="destructive"
disabled={!lostReasonId}
loading={props.submitting}
onClick={confirmLost}
data-ui-id="ui.projects.detail.lostDialog.confirm"
>
{t("projects.actions.confirmLost")}
</Button>
</div>
</div>
</Dialog.Content>
</Dialog>
</PageShell>
);
}
export default ProjektDetailPage;