Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,138 @@
// R-P9a interim UI (AD-28) — acceptance-form template admin (D-ABN scope),
// restored after the admin route was dropped in the seat-billing recut.
// Pure/presentational: renders the server-built VM and turns every mutation
// into a typed onSubmit(intent, fields) callback the route POSTs. No
// useLoaderData/useFetcher, no server imports. Final Subframe optics =
// tracked design-nachzug. Modeled on LostReasonAdminPage (same admin-subpage
// chrome under /admin/pipelines).
import { useState } from "react";
import { useTranslation } from "react-i18next";
import type { AcceptanceFormTemplatesAdminScreenVM } from "@hivegrid/view-models";
import { FeatherArrowLeft, FeatherPlus } from "@subframe/core";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Card } from "~/ui/components/Card";
import { Checkbox } from "~/ui/components/Checkbox";
import { EmptyState } from "~/ui/components/EmptyState";
import { Table } from "~/ui/components/Table";
import { TextInput } from "~/ui/components/TextInput";
import { AppLink } from "~/components/app/AppLink";
export type AcceptanceFormTemplatesAdminSubmit = (intent: string, fields: Record<string, string>) => void;
export type AcceptanceFormTemplatesAdminPageProps = {
vm: AcceptanceFormTemplatesAdminScreenVM;
backHref: string;
submitting: boolean;
errorKey?: string | null;
actions: { onSubmit: AcceptanceFormTemplatesAdminSubmit };
};
const mutedText = "text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary";
export function AcceptanceFormTemplatesAdminPage(props: AcceptanceFormTemplatesAdminPageProps) {
const { t } = useTranslation();
const submit = props.actions.onSubmit;
const [name, setName] = useState("");
const [formId, setFormId] = useState("");
const [isDefault, setIsDefault] = useState(false);
return (
<div className="flex w-full flex-col items-start bg-surface-neutral-primary" data-ui-id="ui.projects.acceptanceFormsAdmin">
<div className="flex w-full flex-wrap items-center justify-between gap-4 border-b border-solid border-border-default bg-surface-neutral-secondary px-6 py-4 mobile:px-4">
<div className="flex flex-col gap-0">
<span className="text-heading- font-heading- text-text-neutral-primary">{t("projects.acceptanceFormsAdmin.title")}</span>
<span className={mutedText}>{t("projects.acceptanceFormsAdmin.subtitle")}</span>
</div>
<AppLink href={props.backHref}>
<Button variant="tertiary" size="small" icon={<FeatherArrowLeft />}>{t("projects.lostReasonsAdmin.backToPipelines")}</Button>
</AppLink>
</div>
<div className="flex w-full max-w-4xl flex-col gap-6 px-6 py-6 mobile:px-4">
{props.errorKey ? <BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback> : null}
{props.vm.status !== "ready" ? (
<EmptyState title={t("projects.acceptanceFormsAdmin.loading")} />
) : (
<>
<Card data-ui-id="ui.projects.acceptanceFormsAdmin.new">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{t("projects.acceptanceFormsAdmin.newTemplate")}
</span>
<div className="flex flex-wrap items-end gap-2">
<TextInput label={t("projects.fields.templateName")} showLabel>
<TextInput.Input value={name} onChange={(e) => setName(e.target.value)} data-ui-id="ui.projects.acceptanceFormsAdmin.new.name" />
</TextInput>
<TextInput label={t("projects.fields.formId")} showLabel>
<TextInput.Input value={formId} onChange={(e) => setFormId(e.target.value)} data-ui-id="ui.projects.acceptanceFormsAdmin.new.formId" />
</TextInput>
<Checkbox label={t("projects.fields.isDefault")} checked={isDefault} onCheckedChange={setIsDefault} />
<Button
icon={<FeatherPlus />}
disabled={!name.trim()}
loading={props.submitting}
onClick={() => {
submit("upsertAcceptanceFormTemplate", { name: name.trim(), formId: formId.trim(), isDefault: isDefault ? "1" : "" });
setName("");
setFormId("");
setIsDefault(false);
}}
data-ui-id="ui.projects.acceptanceFormsAdmin.new.create"
>
{t("projects.actions.saveTemplate")}
</Button>
</div>
</Card>
{props.vm.data.templates.length === 0 ? (
<div data-ui-id="ui.projects.acceptanceFormsAdmin.empty">
<EmptyState title={t("projects.acceptanceFormsAdmin.empty")} body={t("projects.acceptanceFormsAdmin.emptyBody")} />
</div>
) : (
<Card data-ui-id="ui.projects.acceptanceFormsAdmin.list">
<Table>
<Table.HeaderRow>
<Table.HeaderCell>{t("projects.fields.templateName")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.formId")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.isDefault")}</Table.HeaderCell>
</Table.HeaderRow>
{props.vm.data.templates.map((template) => (
<Table.Row key={template.id}>
<Table.Cell>
<div className="flex items-center gap-2">
<span>{template.name}</span>
{template.isDemoData ? (
<BadgeFeedback farbe="subtle-neutral" size="small">{t("projects.lostReasonsAdmin.demoBadge")}</BadgeFeedback>
) : null}
</div>
</Table.Cell>
<Table.Cell>{template.formId ?? t("projects.acceptanceForms.noForm")}</Table.Cell>
<Table.Cell>
{template.isDefault ? (
<BadgeFeedback farbe="subtle-positive">{t("projects.fields.isDefault")}</BadgeFeedback>
) : (
<Button
variant="tertiary"
size="small"
loading={props.submitting}
onClick={() => submit("upsertAcceptanceFormTemplate", { templateId: template.id, name: template.name, isDefault: "1" })}
data-ui-id={`ui.projects.acceptanceFormsAdmin.row.${template.id}.makeDefault`}
>
{t("projects.actions.makeDefault")}
</Button>
)}
</Table.Cell>
</Table.Row>
))}
</Table>
</Card>
)}
</>
)}
</div>
</div>
);
}
export default AcceptanceFormTemplatesAdminPage;
@@ -0,0 +1,89 @@
import { useTranslation } from "react-i18next";
import type { AcceptanceListScreenVM } from "@hivegrid/view-models";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Card } from "~/ui/components/Card";
import { EmptyState } from "~/ui/components/EmptyState";
import { Table } from "~/ui/components/Table";
import { APP_TIME_ZONE } from "~/locale/format";
import { AppLink } from "~/components/app/AppLink";
export type AcceptanceListPageProps = {
vm: AcceptanceListScreenVM;
createHref: string;
submitting: boolean;
errorKey?: string | null;
actions: { onSubmit: (intent: string, fields?: Record<string, string>) => void };
};
const mutedText = "text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary";
function formatDate(value: string | null, language: string): string {
if (!value) return "—";
return new Intl.DateTimeFormat(language, { timeZone: APP_TIME_ZONE, dateStyle: "medium", timeStyle: "short" }).format(new Date(value));
}
export function AcceptanceListPage(props: AcceptanceListPageProps) {
const { t, i18n } = useTranslation();
if (props.vm.status !== "ready") {
// DoD E.24 — plain-language loading state instead of a blank screen.
return (
<main className="mx-auto flex w-full max-w-5xl flex-col gap-6 p-6" data-ui-id="ui.projects.acceptance.list">
<EmptyState outlined title={t("projects.acceptance.loading")} />
</main>
);
}
const data = props.vm.data;
return (
<main className="mx-auto flex w-full max-w-5xl flex-col gap-6 p-6" data-ui-id="ui.projects.acceptance.list">
<header className="flex flex-wrap items-center justify-between gap-3">
<div className="flex flex-col gap-1">
<h1 className="text-heading-2 font-heading-2 text-text-neutral-primary">{t("projects.acceptance.title")}</h1>
<span className={mutedText}>{data.projectNumber} · {data.projectName}</span>
</div>
<AppLink href={props.createHref} className="text-body-default-medium-0 font-body-default-medium-0 text-brand-brand-text-default hover:underline">
{t("projects.actions.createAcceptance")}
</AppLink>
</header>
{props.errorKey ? <BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback> : null}
<Card>
{data.protocols.length === 0 ? (
<EmptyState outlined title={t("projects.empty.acceptance.title")} body={t("projects.empty.acceptance.body")} action={<AppLink href={props.createHref} className="text-body-default-medium-0 font-body-default-medium-0 text-brand-brand-text-default hover:underline">{t("projects.actions.createAcceptance")}</AppLink>} />
) : (
<Table>
<Table.HeaderRow>
<Table.HeaderCell>{t("projects.acceptance.protocol")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.startDate")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.stage")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.acceptance.pdf.title")}</Table.HeaderCell>
<Table.HeaderCell>{t("signature.fields.signers")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.actions.archive")}</Table.HeaderCell>
</Table.HeaderRow>
{data.protocols.map((protocol) => (
<Table.Row key={protocol.id}>
<Table.Cell>
<div className="flex flex-col gap-1">
<span>{t(protocol.kindLabelKey)}</span>
{protocol.notes ? <span className={mutedText}>{protocol.notes}</span> : null}
</div>
</Table.Cell>
<Table.Cell>{formatDate(protocol.dateIso, i18n.language)}</Table.Cell>
<Table.Cell><BadgeFeedback farbe={protocol.lockedAtIso ? "subtle-positive" : "subtle-warning"}>{t(protocol.statusLabelKey)}</BadgeFeedback></Table.Cell>
<Table.Cell>{protocol.pdfFileId ?? t("projects.acceptance.noPdf")}</Table.Cell>
<Table.Cell>{protocol.signatureCount}</Table.Cell>
<Table.Cell>
<Button variant="tertiary" size="small" loading={props.submitting} onClick={() => props.actions.onSubmit("archiveAcceptanceProtocol", { protocolId: protocol.id })}>
{t("projects.actions.archive")}
</Button>
</Table.Cell>
</Table.Row>
))}
</Table>
)}
</Card>
</main>
);
}
@@ -0,0 +1,145 @@
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import type { AcceptanceListScreenVM } from "@hivegrid/view-models";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Card } from "~/ui/components/Card";
import { Select } from "~/ui/components/Select";
import { TextArea } from "~/ui/components/TextArea";
import { TextInput } from "~/ui/components/TextInput";
export type AcceptanceNewPageProps = {
vm: AcceptanceListScreenVM;
submitting: boolean;
errorKey?: string | null;
actions: { onSubmit: (intent: string, fields?: Record<string, string>) => void };
};
type DefectDraft = { classification: "minor" | "critical" | "cosmetic"; title: string; photoFileId: string };
type SignatureDraft = { signerRole: "kunde" | "monteur"; signerName: string; signatureFileId: string };
const headingText = "text-body-large-0 font-body-large-0 text-text-neutral-primary";
const mutedText = "text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary";
function nonEmpty(value: string): string | null {
const normalized = value.trim();
return normalized.length > 0 ? normalized : null;
}
export function AcceptanceNewPage(props: AcceptanceNewPageProps) {
const { t } = useTranslation();
const [form, setForm] = useState({ maengelChecklistId: "", customerEmail: "", bemerkungen: "", clientMutationId: "" });
const [defects, setDefects] = useState<DefectDraft[]>([{ classification: "minor", title: "", photoFileId: "" }]);
const [signatures, setSignatures] = useState<SignatureDraft[]>([
{ signerRole: "kunde", signerName: "", signatureFileId: "" },
{ signerRole: "monteur", signerName: "", signatureFileId: "" },
]);
const serializedDefects = useMemo(
() => JSON.stringify(defects.map((defect) => ({ classification: defect.classification, title: nonEmpty(defect.title), photoFileId: nonEmpty(defect.photoFileId) })).filter((defect) => defect.title || defect.photoFileId)),
[defects],
);
const serializedSignatures = useMemo(
() => JSON.stringify(signatures.map((signature) => ({ signerRole: signature.signerRole, signerName: signature.signerName, signatureFileId: nonEmpty(signature.signatureFileId) })).filter((signature) => signature.signerName.trim().length > 0)),
[signatures],
);
if (props.vm.status !== "ready") return null;
const data = props.vm.data;
return (
<main className="mx-auto flex w-full max-w-5xl flex-col gap-6 p-6" data-ui-id="ui.projects.acceptance.new">
<header className="flex flex-col gap-1">
<h1 className="text-heading-2 font-heading-2 text-text-neutral-primary">{t("projects.acceptance.newTitle")}</h1>
<span className={mutedText}>{data.projectNumber} · {data.projectName}</span>
</header>
{props.errorKey ? <BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback> : null}
<div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]">
<Card data-ui-id="ui.projects.acceptance.new.form">
<span className={headingText}>{t("projects.acceptance.protocol")}</span>
<div className="grid gap-4 md:grid-cols-2">
<TextInput showLabel label={t("projects.fields.defectChecklistId")} className="max-w-none">
<TextInput.Input value={form.maengelChecklistId} onChange={(event) => setForm((current) => ({ ...current, maengelChecklistId: event.target.value }))} />
</TextInput>
<TextInput showLabel label={t("projects.fields.customerEmail")} className="max-w-none">
<TextInput.Input type="email" value={form.customerEmail} onChange={(event) => setForm((current) => ({ ...current, customerEmail: event.target.value }))} />
</TextInput>
<TextInput showLabel label={t("projects.fields.clientMutationId")} className="max-w-none">
<TextInput.Input value={form.clientMutationId} onChange={(event) => setForm((current) => ({ ...current, clientMutationId: event.target.value }))} />
</TextInput>
<TextArea showLabel label={t("projects.fields.notes")} className="max-w-none md:col-span-2">
<TextArea.Input value={form.bemerkungen} onChange={(event) => setForm((current) => ({ ...current, bemerkungen: event.target.value }))} />
</TextArea>
</div>
</Card>
<Card data-ui-id="ui.projects.acceptance.new.summary">
<span className={headingText}>{t("projects.acceptance.summary")}</span>
<span className={mutedText}>{t("projects.acceptance.defectCount", { count: JSON.parse(serializedDefects).length })}</span>
<span className={mutedText}>{t("projects.acceptance.signatureCount", { count: JSON.parse(serializedSignatures).length })}</span>
<Button
loading={props.submitting}
onClick={() =>
props.actions.onSubmit("submitAcceptanceProtocol", {
...form,
defects: serializedDefects,
signatures: serializedSignatures,
})
}
>
{t("projects.actions.submitAcceptance")}
</Button>
</Card>
</div>
<Card data-ui-id="ui.projects.acceptance.new.defects">
<div className="flex flex-wrap items-center justify-between gap-3">
<span className={headingText}>{t("projects.acceptance.defects")}</span>
<Button variant="tertiary" size="small" onClick={() => setDefects((current) => [...current, { classification: "minor", title: "", photoFileId: "" }])}>{t("projects.actions.addDefect")}</Button>
</div>
<div className="grid gap-4">
{defects.map((defect, index) => (
<div key={index} className="grid gap-3 rounded-md border border-solid border-border-default p-4 md:grid-cols-[180px_minmax(0,1fr)_minmax(0,1fr)]">
<Select showLabel label={t("projects.fields.classification")} value={defect.classification} onValueChange={(classification) => setDefects((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, classification: classification as DefectDraft["classification"] } : item))} className="max-w-none">
<Select.Item value="minor">{t("projects.defectClass.minor")}</Select.Item>
<Select.Item value="critical">{t("projects.defectClass.critical")}</Select.Item>
<Select.Item value="cosmetic">{t("projects.defectClass.cosmetic")}</Select.Item>
</Select>
<TextInput showLabel label={t("projects.fields.checklistItem")} className="max-w-none">
<TextInput.Input value={defect.title} onChange={(event) => setDefects((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, title: event.target.value } : item))} />
</TextInput>
<TextInput showLabel label={t("projects.fields.fileId")} className="max-w-none">
<TextInput.Input value={defect.photoFileId} onChange={(event) => setDefects((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, photoFileId: event.target.value } : item))} />
</TextInput>
</div>
))}
</div>
</Card>
<Card data-ui-id="ui.projects.acceptance.new.signatures">
<div className="flex flex-wrap items-center justify-between gap-3">
<span className={headingText}>{t("signature.fields.signers")}</span>
<Button variant="tertiary" size="small" onClick={() => setSignatures((current) => [...current, { signerRole: "kunde", signerName: "", signatureFileId: "" }])}>{t("projects.actions.addSigner")}</Button>
</div>
<div className="grid gap-4">
{signatures.map((signature, index) => (
<div key={index} className="grid gap-3 rounded-md border border-solid border-border-default p-4 md:grid-cols-[180px_minmax(0,1fr)_minmax(0,1fr)]">
<Select showLabel label={t("projects.fields.role")} value={signature.signerRole} onValueChange={(signerRole) => setSignatures((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, signerRole: signerRole as SignatureDraft["signerRole"] } : item))} className="max-w-none">
<Select.Item value="kunde">{t("projects.signerRole.kunde")}</Select.Item>
<Select.Item value="monteur">{t("projects.signerRole.monteur")}</Select.Item>
</Select>
<TextInput showLabel label={t("projects.fields.name")} className="max-w-none">
<TextInput.Input value={signature.signerName} onChange={(event) => setSignatures((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, signerName: event.target.value } : item))} />
</TextInput>
<TextInput showLabel label={t("projects.fields.fileId")} className="max-w-none">
<TextInput.Input value={signature.signatureFileId} onChange={(event) => setSignatures((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, signatureFileId: event.target.value } : item))} />
</TextInput>
</div>
))}
</div>
</Card>
</main>
);
}
@@ -0,0 +1,233 @@
// WF-P8 S01 — the board filter bar (David's `FilterBar` +
// `DropdownMenuMultiSelect`, 2026-07-28). Pure/presentational: it renders the
// BoardFacetsVM the loader built and reports every interaction as a callback;
// the route turns those into query parameters.
//
// Deliberate deltas from the export:
// * The "Tags" facet is left out — there is no project tag model, so the
// dropdown would have nothing to list and the chips nothing to remove.
// Tracked as a design-nachzug together with the tag data model.
// * "Zeitraum" behaves as single-select. The export draws checkboxes, but two
// periods at once only ever mean "the wider of the two", which no user can
// predict from the UI.
// * "Auftragswert" only renders for a viewer with tenant-wide volume access.
// Picking a band reveals the band, so offering it to someone who sees "—"
// on the cards would hand out exactly the number the gate withholds.
import { useEffect, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import type { BoardFacet, BoardFacetChip, BoardFacetsVM } from "@hivegrid/view-models";
import { FeatherCalendar, FeatherEuro, FeatherTag, FeatherTags, FeatherUser, FeatherX } from "@subframe/core";
import { DropdownMenuMultiSelect } from "~/ui/components/DropdownMenuMultiSelect";
import { FilterBar } from "~/ui/components/FilterBar";
import { tagTone } from "./tagTone";
import { Switch } from "~/ui/components/Switch";
import { Tag_Label } from "~/ui/components/Tag_Label";
const FACET_ICON: Record<BoardFacet["key"], ReactNode> = {
owner: <FeatherUser />,
customerType: <FeatherTag />,
tags: <FeatherTags />,
period: <FeatherCalendar />,
value: <FeatherEuro />,
};
/** Chip tone per facet, so a glance tells the groups apart. */
const CHIP_TONE: Record<BoardFacetChip["facet"], "blue-subtle" | "sky-subtle" | "violet-subtle" | "yellow-subtle" | "neutral-subtle"> = {
owner: "blue-subtle",
customerType: "violet-subtle",
tags: "neutral-subtle",
period: "sky-subtle",
value: "yellow-subtle",
onlyMine: "neutral-subtle",
q: "neutral-subtle",
};
/** Inline date field of the custom period, sized to match a facet button. */
const DATE_INPUT_CLASS =
"h-6 rounded-md border border-solid border-border-default bg-surface-neutral-primary px-1.5 text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-primary focus:shadow-focus focus:outline-none";
const LABEL_CLASS = "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary";
export type BoardFilterBarProps = {
facets: BoardFacetsVM;
/** Last committed server search. Typing stays local until Enter/search click. */
search: string;
onSearch: (value: string) => void;
onlyMine: boolean;
onToggleOnlyMine: (checked: boolean) => void;
/** Toggle one option of a facet on or off. */
onToggleFacet: (facet: BoardFacet["key"], value: string) => void;
/** Remove exactly one active chip. */
onRemoveChip: (chip: BoardFacetChip) => void;
onReset: () => void;
/** Custom period bounds (ISO yyyy-mm-dd), only used by the period facet. */
periodFrom: string;
periodTo: string;
onPeriodRangeChange: (from: string, to: string) => void;
/**
* Control placed directly behind the vertical rule that closes the facet row —
* a board control (which columns are on screen), not a filter, so it stands on
* the other side of the rule while keeping the facet buttons' looks.
*/
afterDivider?: ReactNode;
/** Extra controls next to the only-mine switch (staging demo toggle). */
trailing?: ReactNode;
/**
* Prefix of every data-ui-id. The list renders the same bar, and two screens
* answering to the same ids would make a test ambiguous about which one it hit.
*/
uiId?: string;
};
export function BoardFilterBar(props: BoardFilterBarProps) {
const { t } = useTranslation();
const uiId = props.uiId ?? "ui.projects.board";
// Keep the transient input here instead of on the heavy board/list parent.
// That prevents every key press from rebuilding all card and column nodes.
const [searchDraft, setSearchDraft] = useState(props.search);
useEffect(() => setSearchDraft(props.search), [props.search]);
const customPeriodActive = props.facets.facets.some(
(facet) => facet.key === "period" && facet.options.some((option) => option.value === "custom" && option.selected)
);
function optionLabel(label: string | undefined, labelKey: string | undefined): string {
return label ?? (labelKey ? t(labelKey) : "");
}
function commitSearch() {
const next = searchDraft.trim();
setSearchDraft(next);
if (next !== props.search.trim()) props.onSearch(next);
}
function resetFilters() {
setSearchDraft("");
props.onReset();
}
return (
<FilterBar
className="rounded-none border-b border-solid border-border-default px-6 py-2.5 mobile:rounded-none mobile:px-4"
data-ui-id={`${uiId}.filterBar`}
searchValue={searchDraft}
searchPlaceholder={t("projects.board.filter.searchPlaceholder")}
searchUiId={`${uiId}.search`}
searchSubmitUiId={`${uiId}.search.submit`}
searchSubmitLabel={t("shared.search")}
onSearchChange={setSearchDraft}
onSearchSubmit={commitSearch}
showActiveFilters={props.facets.hasActiveFilters}
onReset={props.facets.hasActiveFilters ? resetFilters : undefined}
resetLabel={t("projects.board.filter.reset")}
activeFilters={props.facets.chips.map((chip) => (
<Tag_Label
key={`${chip.facet}:${chip.value}`}
// A tag chip carries the tag's own colour; every other facet has a
// fixed tone so the groups stay distinguishable at a glance.
tone={chip.facet === "tags" ? tagTone(chip.farbe) : CHIP_TONE[chip.facet]}
size="small"
data-ui-id={`${uiId}.filterChip.${chip.facet}.${chip.value}`}
actionChildren={
<Tag_Label.Action
icon={<FeatherX />}
onClick={() => props.onRemoveChip(chip)}
// The kit renders the action as a div, so the chip carries the
// button semantics itself and stays keyboard-reachable.
role="button"
tabIndex={0}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
props.onRemoveChip(chip);
}
}}
aria-label={t("projects.board.filter.removeChip")}
data-ui-id={`${uiId}.filterChip.${chip.facet}.${chip.value}.remove`}
/>
}
>
{optionLabel(chip.label, chip.labelKey)}
</Tag_Label>
))}
>
{props.facets.facets.map((facet) => (
<FilterBar.StatusFilterButton
key={facet.key}
icon={FACET_ICON[facet.key]}
label={t(facet.labelKey)}
showCount={facet.selectedCount > 0}
count={facet.selectedCount > 0 ? String(facet.selectedCount) : ""}
data-ui-id={`${uiId}.facet.${facet.key}`}
dropdown={
<DropdownMenuMultiSelect>
{facet.options.length === 0 ? (
<DropdownMenuMultiSelect.DropdownCustomItem>
<span className="px-1 text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{t("projects.board.filter.noOptions")}
</span>
</DropdownMenuMultiSelect.DropdownCustomItem>
) : null}
{facet.options.map((option) => (
<DropdownMenuMultiSelect.DropdownItem
key={option.value}
showCheckbox
selected={option.selected}
onClick={() => props.onToggleFacet(facet.key, option.value)}
data-ui-id={`${uiId}.facet.${facet.key}.${option.value}`}
>
{optionLabel(option.label, option.labelKey)}
</DropdownMenuMultiSelect.DropdownItem>
))}
</DropdownMenuMultiSelect>
}
/>
))}
{/* The custom range lives in the bar, not in the period dropdown: a native
date picker opens its own popup, which closes the menu underneath it,
and the panel does not grow to cover the two fields. */}
{customPeriodActive ? (
<div className="flex items-center gap-1.5" data-ui-id={`${uiId}.facet.period.range`}>
<span className={LABEL_CLASS}>{t("projects.board.filter.period.from")}</span>
<input
type="date"
className={DATE_INPUT_CLASS}
value={props.periodFrom}
onChange={(event) => props.onPeriodRangeChange(event.target.value, props.periodTo)}
aria-label={t("projects.board.filter.period.from")}
data-ui-id={`${uiId}.facet.period.from`}
/>
<span className={LABEL_CLASS}>{t("projects.board.filter.period.to")}</span>
<input
type="date"
className={DATE_INPUT_CLASS}
value={props.periodTo}
onChange={(event) => props.onPeriodRangeChange(props.periodFrom, event.target.value)}
aria-label={t("projects.board.filter.period.to")}
data-ui-id={`${uiId}.facet.period.to`}
/>
</div>
) : null}
<div className="flex h-5 w-px flex-none items-start bg-border-default" />
{props.afterDivider ? (
<>
{props.afterDivider}
{/* The view controls get their own compartment: with a rule on each
side, only the only-mine switch stays behind the last one. */}
<div className="flex h-5 w-px flex-none items-start bg-border-default" />
</>
) : null}
<div className="flex grow shrink-0 basis-0 items-center justify-end gap-2 mobile:grow-0 mobile:justify-start">
<Switch
checked={props.onlyMine}
onCheckedChange={props.onToggleOnlyMine}
data-ui-id={`${uiId}.onlyMine`}
aria-label={t("projects.fields.onlyMine")}
/>
<span className="whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-secondary">
{t("projects.fields.onlyMine")}
</span>
{props.trailing}
</div>
</FilterBar>
);
}
@@ -0,0 +1,182 @@
// WF-P8 S04 — BoardSettingsPage unit test. Fixture via the real
// buildBoardSettingsVM on top of buildPipelineAdminVM; interactions asserted on
// the injected onSubmit. The column tests moved here from the old combined
// admin page, which no longer configures anything itself.
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { MemoryRouter } from "react-router";
import { buildBoardSettingsVM, buildPipelineAdminVM, type BoardSettingsData } from "@hivegrid/view-models";
import { BoardSettingsPage } from "./BoardSettingsPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }),
}));
// Radix selects are not interactable in jsdom; swap ~/ui Select for a native one.
vi.mock("~/ui/components/Select", () => {
const Select = ({ value, onValueChange, label, triggerAriaLabel, children, ...rest }: any) => (
<div data-ui-id={rest["data-ui-id"]}>
<select
aria-label={typeof label === "string" ? label : (triggerAriaLabel ?? "select")}
value={value ?? ""}
onChange={(e: any) => onValueChange?.(e.target.value)}
data-ui-id={rest["data-ui-id"] ? `${rest["data-ui-id"]}.native` : undefined}
>
<option value="" />
{children}
</select>
</div>
);
Select.Item = ({ value, children }: any) => <option value={value}>{children}</option>;
return { Select };
});
const byUiId = (id: string) => document.querySelector(`[data-ui-id='${id}']`) as HTMLElement;
type FixturePipeline = Parameters<typeof buildPipelineAdminVM>[0]["pipelines"][number];
const board: FixturePipeline = {
id: "pl1",
name: "Sales",
typHint: "sales",
isDefault: true,
projectCount: 11,
updatedAtIso: "2026-07-12T06:12:00.000Z",
stages: [
{ id: "s1", name: "Neu", stageKind: "offen", winProbability: 10, color: "#000000", position: 10, projectCount: 4 },
{ id: "s2", name: "Gewonnen", stageKind: "gewonnen", winProbability: 100, color: "#00aa00", position: 20, projectCount: 5 },
{ id: "s3", name: "Verloren", stageKind: "verloren", winProbability: 0, color: "#aa0000", position: 30, projectCount: 2 },
],
accessRules: [],
fieldConfigs: [],
};
const otherBoard: FixturePipeline = {
id: "pl2",
name: "Wartung",
typHint: "auftrag",
isDefault: false,
projectCount: 3,
stages: [],
accessRules: [],
fieldConfigs: [],
};
function settingsData(boardId = "pl1"): BoardSettingsData {
const admin = buildPipelineAdminVM({ canAdmin: true, pipelines: [board, otherBoard] });
if (admin.status !== "ready") throw new Error("fixture not ready");
const vm = buildBoardSettingsVM({ boards: admin.data.pipelines, boardId, canAdmin: true });
if (vm.status !== "ready") throw new Error("board not found");
return vm.data;
}
function renderPage(data = settingsData()) {
const onSubmit = vi.fn();
render(
<MemoryRouter>
<BoardSettingsPage
data={data}
submitting={false}
fieldTemplateHref="/acme/admin/pipelines/pl1/fields"
actions={{ onSubmit }}
/>
</MemoryRouter>
);
return onSubmit;
}
describe("buildBoardSettingsVM", () => {
it("returns empty for an unknown board so the route can 404", () => {
const admin = buildPipelineAdminVM({ canAdmin: true, pipelines: [board] });
if (admin.status !== "ready") throw new Error("fixture not ready");
expect(buildBoardSettingsVM({ boards: admin.data.pipelines, boardId: "nope", canAdmin: true }).status).toBe("empty");
});
it("never offers the board itself as its own successor", () => {
const data = settingsData();
expect(data.successorOptions.map((option) => option.id)).toEqual(["pl2"]);
});
});
describe("BoardSettingsPage", () => {
it("renders the column table with per-column project counts", () => {
renderPage();
expect(byUiId("ui.projects.boardSettings.stageList.pl1")).toBeTruthy();
expect(byUiId("ui.projects.boardSettings.stage.s1.projects").textContent).toContain("projects.boardSettings.columns.projectCount");
expect(byUiId("ui.projects.boardSettings.stage.s1.drag")).toBeTruthy();
});
it("offers a save action only once a column actually changed", () => {
const onSubmit = renderPage();
expect(byUiId("ui.projects.boardSettings.stage.s1.save")).toBeNull();
fireEvent.change(byUiId("ui.projects.boardSettings.stage.s1.name"), { target: { value: "Eingang" } });
fireEvent.click(byUiId("ui.projects.boardSettings.stage.s1.save"));
expect(onSubmit).toHaveBeenCalledWith("upsertStage", expect.objectContaining({ pipelineId: "pl1", stageId: "s1", name: "Eingang" }));
});
it("archives a column", () => {
const onSubmit = renderPage();
fireEvent.click(byUiId("ui.projects.boardSettings.stage.s1.archive"));
expect(onSubmit).toHaveBeenCalledWith("archiveStage", { stageId: "s1" });
});
it("adds a column", () => {
const onSubmit = renderPage();
fireEvent.click(byUiId("ui.projects.boardSettings.addStage.pl1.open"));
fireEvent.change(byUiId("ui.projects.boardSettings.addStage.pl1.name"), { target: { value: "Angebot" } });
fireEvent.click(byUiId("ui.projects.boardSettings.addStage.pl1.submit"));
expect(onSubmit).toHaveBeenCalledWith("upsertStage", expect.objectContaining({ pipelineId: "pl1", name: "Angebot" }));
});
it("renames the board from the header", () => {
const onSubmit = renderPage();
fireEvent.click(byUiId("ui.projects.boardSettings.rename.open"));
fireEvent.change(byUiId("ui.projects.boardSettings.rename.input"), { target: { value: "Vertrieb" } });
fireEvent.click(byUiId("ui.projects.boardSettings.rename.save"));
expect(onSubmit).toHaveBeenCalledWith("updatePipeline", { pipelineId: "pl1", name: "Vertrieb" });
// Saving leaves the edit mode right away. Waiting for a changed loader
// value would keep the header in the input whenever the name stayed equal.
expect(byUiId("ui.projects.boardSettings.rename.input")).toBeNull();
});
it("closes the rename editor even when the name did not change", () => {
const onSubmit = renderPage();
fireEvent.click(byUiId("ui.projects.boardSettings.rename.open"));
fireEvent.click(byUiId("ui.projects.boardSettings.rename.save"));
expect(onSubmit).toHaveBeenCalledWith("updatePipeline", { pipelineId: "pl1", name: "Sales" });
expect(byUiId("ui.projects.boardSettings.rename.input")).toBeNull();
});
it("links to the S05 detail-field template", () => {
renderPage();
expect(byUiId("ui.projects.boardSettings.fieldTemplate").getAttribute("href")).toBe("/acme/admin/pipelines/pl1/fields");
});
it("shows the export's three columns and hides the win rate behind the pencil", () => {
const onSubmit = renderPage();
// Name / Status / Projekte, plus the leading drag+colour cell.
const headers = [...document.querySelectorAll("th")].map((th) => th.textContent?.trim());
expect(headers).toEqual(["", "projects.fields.name", "projects.boardSettings.columns.status", "projects.boardSettings.columns.projects"]);
expect(byUiId("ui.projects.boardSettings.stage.s1.winProbability")).toBeNull();
fireEvent.click(byUiId("ui.projects.boardSettings.stage.s1.edit"));
fireEvent.change(byUiId("ui.projects.boardSettings.stage.s1.winProbability"), { target: { value: "40" } });
fireEvent.click(byUiId("ui.projects.boardSettings.stage.s1.save"));
expect(onSubmit).toHaveBeenCalledWith("upsertStage", expect.objectContaining({ stageId: "s1", winProbability: "40" }));
});
it("has no back link and keeps the access rules behind one expander", () => {
renderPage();
expect(byUiId("ui.projects.boardSettings.back")).toBeNull();
// Raw principal-id assignment is gone; the rules are read-only here.
expect(document.querySelector("[data-ui-id^='ui.projects.boardSettings.addAccess']")).toBeNull();
expect(byUiId("ui.projects.boardSettings.access")).toBeTruthy();
});
it("warns when the board has no won and no lost column", () => {
renderPage(settingsData("pl2"));
expect(byUiId("ui.projects.boardSettings.invalid")).toBeTruthy();
expect(screen.getByText("projects.admin.invalidHint")).toBeTruthy();
});
});
@@ -0,0 +1,622 @@
// WF-P8 S04 "Board-Einstellungen" — built against Davids Subframe export of
// 2026-07-28 (page 0b946683-2cca-4cd4-864d-f69ed1937fdb).
//
// This screen is the per-board half of the admin split: S07 lists the boards,
// S04 configures one. Pure/presentational — renders the server-built
// BoardSettingsData and turns every mutation into a typed
// onSubmit(intent, fields) the route POSTs. No useLoaderData/useFetcher, no
// server imports.
//
// Deliberate deltas against the export:
// * The export imports `@/ui/components/SettingsPage`, which the local ~/ui
// kit does not ship. The section headers are rendered with the same two
// lines of markup instead.
// * `Table.Cell variant="align-right"` only exists in the export; locally the
// variants are align-left/align-center, so right-aligned cells use a
// justify-end wrapper.
// * The column "Status" select offers the three real stage kinds
// (offen/gewonnen/verloren). The export's free-text statuses plus "Neuen
// Status eingeben …" would need a schema change that the kanban, the M01
// lost dialog and the win/loss numbers all read from — out of ticket scope.
// * The export shows a per-row pencil next to always-editable inputs. The
// inputs already are the edit affordance, so the row shows a save action
// when it is dirty rather than a pencil that toggles nothing.
// * Colour and win-% per column are kept although the export drops them: both
// are live data the board and the forecast render.
// * "Zugriff" has no section in the export but no other screen configures
// it; dropping it here would make a shipped feature unreachable.
// * The M04 successor board USED to sit at the bottom of this page for the
// same reason. It was taken out on request (acceptance 2026-07-31): the
// export does not show it here. Nothing else sets
// `Pipeline.nachfolgePipelineId` today, so the handover cannot be
// configured from the UI until it gets a new home — the write path
// (`updatePipeline`) is untouched and still accepts the field.
import { useEffect, useState, type CSSProperties } from "react";
import { useTranslation } from "react-i18next";
import { AppLink } from "~/components/app/AppLink";
import {
DndContext,
KeyboardSensor,
PointerSensor,
closestCenter,
useSensor,
useSensors,
type DragEndEvent,
} from "@dnd-kit/core";
import { SortableContext, arrayMove, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import type { BoardSettingsData, PipelineAdminItem, PipelineAdminStage } from "@hivegrid/view-models";
import {
FeatherArrowRightCircle,
FeatherCheck,
FeatherClipboardList,
FeatherGripVertical,
FeatherKanban,
FeatherPencil,
FeatherPlus,
FeatherTrash,
FeatherX,
} from "@subframe/core";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
import { Accordion } from "~/ui/components/Accordion";
import { Alert } from "~/ui/components/Alert";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { IconButton } from "~/ui/components/IconButton";
import { Select } from "~/ui/components/Select";
import { Table } from "~/ui/components/Table";
import { TextInput } from "~/ui/components/TextInput";
import { useLocaleFormatters } from "~/locale/format";
export type BoardSettingsSubmit = (intent: string, fields: Record<string, string>) => void;
export type BoardSettingsPageProps = {
data: BoardSettingsData;
submitting: boolean;
errorKey?: string | null;
/** S05 detail-field template of this board. */
fieldTemplateHref: string;
actions: { onSubmit: BoardSettingsSubmit };
};
const STAGE_KINDS = ["offen", "gewonnen", "verloren"] as const;
const sectionTitle = "text-body-large font-body-large text-text-neutral-primary";
const sectionDescription = "text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary";
const mutedText = "text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary";
// Native <input type="color"> rendered as a round swatch (no padded border):
// it is both the colour dot the export draws and the way to change it, so the
// row does not need a second control. The webkit/moz pseudo-elements strip the
// default swatch padding and border.
const colorSwatchClass =
"h-3.5 w-3.5 shrink-0 cursor-pointer appearance-none rounded-full border-none bg-transparent p-0 [&::-webkit-color-swatch-wrapper]:p-0 [&::-webkit-color-swatch]:rounded-full [&::-webkit-color-swatch]:border-none [&::-moz-color-swatch]:rounded-full [&::-moz-color-swatch]:border-none";
function SectionHeader({ title, description }: { title: string; description: string }) {
return (
<div className="flex w-full flex-col items-start gap-1">
<h2 className={sectionTitle}>{title}</h2>
<p className={sectionDescription}>{description}</p>
</div>
);
}
type StageDraft = { name: string; stageKind: string; winProbability: string; color: string };
function draftOf(stage: PipelineAdminStage): StageDraft {
return { name: stage.name, stageKind: stage.stageKind, winProbability: String(stage.winProbability), color: stage.color };
}
function draftDiffers(draft: StageDraft, stage: PipelineAdminStage): boolean {
return (
draft.name !== stage.name ||
draft.stageKind !== stage.stageKind ||
draft.winProbability !== String(stage.winProbability) ||
draft.color !== stage.color
);
}
/** One draggable column row. Name, kind, win-% and colour edit in place; the
* save action only appears once the row actually differs from the server state,
* so an untouched table has no buttons inviting a pointless write. */
function SortableStageRow({
stage,
pipelineId,
submit,
submitting,
}: {
stage: PipelineAdminStage;
pipelineId: string;
submit: BoardSettingsSubmit;
submitting: boolean;
}) {
const { t } = useTranslation();
const [draft, setDraft] = useState<StageDraft>(() => draftOf(stage));
useEffect(() => {
setDraft(draftOf(stage));
}, [stage]);
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: stage.id });
const style: CSSProperties = { transform: CSS.Transform.toString(transform), transition, opacity: isDragging ? 0.6 : 1 };
const idBase = `ui.projects.boardSettings.stage.${stage.id}`;
const dirty = draftDiffers(draft, stage);
// The export's row has Name, Status and Projektanzahl only. The win
// probability is live data (forecast, board) with no other screen to edit it,
// so the export's per-row pencil opens it instead of showing a fourth column.
const [expanded, setExpanded] = useState(false);
return (
<>
<Table.Row ref={setNodeRef} style={style} data-row-id={stage.id} data-ui-id={idBase}>
<Table.Cell className="w-12">
<div className="flex items-center gap-2">
<button
type="button"
className="inline-flex min-h-8 min-w-8 cursor-grab touch-none items-center justify-center text-icon-neutral-tertiary hover:text-icon-neutral-secondary focus:outline-none"
aria-label={t("projects.admin.dragStageAria", { name: stage.name })}
data-ui-id={`${idBase}.drag`}
{...listeners}
{...attributes}
>
<FeatherGripVertical aria-hidden />
</button>
<input
type="color"
value={draft.color}
onChange={(e) => setDraft((s) => ({ ...s, color: e.target.value }))}
className={colorSwatchClass}
aria-label={t("projects.fields.color")}
data-ui-id={`${idBase}.color`}
/>
</div>
</Table.Cell>
<Table.Cell>
<TextInput className="w-full min-w-0" size="small" variant="filled">
<TextInput.Input
value={draft.name}
placeholder={t("projects.fields.name")}
aria-label={t("projects.fields.name")}
onChange={(e) => setDraft((s) => ({ ...s, name: e.target.value }))}
data-ui-id={`${idBase}.name`}
/>
</TextInput>
</Table.Cell>
<Table.Cell>
<Select
className="w-full min-w-0"
size="small"
variant="filled"
triggerAriaLabel={t("projects.fields.stageKind")}
value={draft.stageKind}
onValueChange={(value) => setDraft((s) => ({ ...s, stageKind: value }))}
data-ui-id={`${idBase}.kind`}
>
{STAGE_KINDS.map((kind) => (
<Select.Item key={kind} value={kind}>
{t(kind === "gewonnen" ? "projects.outcome.won" : kind === "verloren" ? "projects.outcome.lost" : "projects.outcome.open")}
</Select.Item>
))}
</Select>
</Table.Cell>
<Table.Cell className="w-56">
<div className="flex w-full items-center justify-end gap-2">
<span
className="whitespace-nowrap text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary"
data-ui-id={`${idBase}.projects`}
>
{t("projects.boardSettings.columns.projectCount", { count: stage.projectCount })}
</span>
<IconButton
variant="ghost"
size="small"
square
icon={<FeatherPencil />}
aria-label={t("projects.actions.edit")}
aria-expanded={expanded}
onClick={() => setExpanded((value) => !value)}
data-ui-id={`${idBase}.edit`}
/>
{dirty ? (
<IconButton
variant="success"
size="small"
square
icon={<FeatherCheck />}
loading={submitting}
disabled={!draft.name.trim()}
aria-label={t("projects.actions.save")}
onClick={() =>
submit("upsertStage", {
pipelineId,
stageId: stage.id,
name: draft.name.trim(),
stageKind: draft.stageKind,
winProbability: draft.winProbability,
color: draft.color,
})
}
data-ui-id={`${idBase}.save`}
/>
) : null}
<IconButton
variant="ghost"
size="small"
square
icon={<FeatherTrash />}
aria-label={t("projects.actions.remove")}
onClick={() => submit("archiveStage", { stageId: stage.id })}
data-ui-id={`${idBase}.archive`}
/>
</div>
</Table.Cell>
</Table.Row>
{expanded ? (
<Table.Row data-ui-id={`${idBase}.details`}>
<Table.Cell colSpan={4} className="bg-surface-neutral-primary">
<div className="flex flex-wrap items-center gap-2 py-1">
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{t("projects.fields.winProbability")}
</span>
<TextInput className="w-20 min-w-0" size="small" variant="filled">
<TextInput.Input
type="number"
value={draft.winProbability}
aria-label={t("projects.fields.winProbability")}
onChange={(e) => setDraft((s) => ({ ...s, winProbability: e.target.value }))}
data-ui-id={`${idBase}.winProbability`}
/>
</TextInput>
<span aria-hidden className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">%</span>
</div>
</Table.Cell>
</Table.Row>
) : null}
</>
);
}
/** Drag&drop-orderable column list. On drop it persists the whole new
* top-to-bottom order via `reorderStages`; the service reassigns positions. */
function StageTable({ board, submit, submitting }: { board: PipelineAdminItem; submit: BoardSettingsSubmit; submitting: boolean }) {
const { t } = useTranslation();
const [order, setOrder] = useState<string[]>(() => board.stages.map((stage) => stage.id));
useEffect(() => {
setOrder(board.stages.map((stage) => stage.id));
}, [board.stages]);
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
);
const stageById = new Map(board.stages.map((stage) => [stage.id, stage]));
const ordered = order.map((id) => stageById.get(id)).filter((stage): stage is PipelineAdminStage => Boolean(stage));
function handleDragEnd(event: DragEndEvent) {
const { active, over } = event;
if (!over || active.id === over.id) return;
const oldIndex = order.indexOf(String(active.id));
const newIndex = order.indexOf(String(over.id));
if (oldIndex < 0 || newIndex < 0) return;
const next = arrayMove(order, oldIndex, newIndex);
setOrder(next);
submit("reorderStages", { pipelineId: board.id, stageIds: JSON.stringify(next) });
}
return (
<div className="flex w-full flex-col items-start overflow-hidden rounded-lg border border-solid border-border-default bg-surface-neutral-secondary shadow-sm overflow-x-auto">
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext items={order} strategy={verticalListSortingStrategy}>
<Table
className="border-none min-w-[640px]"
data-ui-id={`ui.projects.boardSettings.stageList.${board.id}`}
header={
<Table.HeaderRow>
<Table.HeaderCell className="w-12" />
<Table.HeaderCell>{t("projects.fields.name")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.boardSettings.columns.status")}</Table.HeaderCell>
<Table.HeaderCell className="w-56">{t("projects.boardSettings.columns.projects")}</Table.HeaderCell>
</Table.HeaderRow>
}
emptyText={t("projects.boardSettings.columns.empty")}
>
{ordered.map((stage) => (
<SortableStageRow key={stage.id} stage={stage} pipelineId={board.id} submit={submit} submitting={submitting} />
))}
</Table>
</SortableContext>
</DndContext>
</div>
);
}
/** Create row for a new column. Resets to an empty draft after each write so the
* next column can be typed right away. */
function AddStageForm({ pipelineId, submit, submitting }: { pipelineId: string; submit: BoardSettingsSubmit; submitting: boolean }) {
const { t } = useTranslation();
const emptyDraft: StageDraft = { name: "", stageKind: "offen", winProbability: "0", color: "#6b7280" };
const [draft, setDraft] = useState<StageDraft>(emptyDraft);
const [open, setOpen] = useState(false);
const idBase = `ui.projects.boardSettings.addStage.${pipelineId}`;
if (!open) {
return (
<Button variant="tertiary" size="small" icon={<FeatherPlus />} onClick={() => setOpen(true)} data-ui-id={`${idBase}.open`}>
{t("projects.boardSettings.columns.add")}
</Button>
);
}
return (
<div className="grid w-full items-end gap-3 sm:grid-cols-2 lg:grid-cols-4" data-ui-id={idBase}>
<TextInput label={t("projects.fields.name")} showLabel>
<TextInput.Input
autoFocus
value={draft.name}
onChange={(e) => setDraft((s) => ({ ...s, name: e.target.value }))}
data-ui-id={`${idBase}.name`}
/>
</TextInput>
<Select
label={t("projects.fields.stageKind")}
showLabel
value={draft.stageKind}
onValueChange={(value) => setDraft((s) => ({ ...s, stageKind: value }))}
data-ui-id={`${idBase}.kind`}
>
{STAGE_KINDS.map((kind) => (
<Select.Item key={kind} value={kind}>
{t(kind === "gewonnen" ? "projects.outcome.won" : kind === "verloren" ? "projects.outcome.lost" : "projects.outcome.open")}
</Select.Item>
))}
</Select>
<TextInput label={t("projects.fields.winProbability")} showLabel>
<TextInput.Input
type="number"
value={draft.winProbability}
onChange={(e) => setDraft((s) => ({ ...s, winProbability: e.target.value }))}
data-ui-id={`${idBase}.winProbability`}
/>
</TextInput>
<div className="flex items-center gap-2">
<input
type="color"
value={draft.color}
onChange={(e) => setDraft((s) => ({ ...s, color: e.target.value }))}
className={`${colorSwatchClass} h-6 w-6`}
aria-label={t("projects.fields.color")}
data-ui-id={`${idBase}.color`}
/>
<Button
size="small"
icon={<FeatherPlus />}
disabled={!draft.name.trim()}
loading={submitting}
onClick={() => {
submit("upsertStage", {
pipelineId,
name: draft.name.trim(),
stageKind: draft.stageKind,
winProbability: draft.winProbability,
color: draft.color,
});
setDraft(emptyDraft);
}}
data-ui-id={`${idBase}.submit`}
>
{t("projects.actions.addStage")}
</Button>
<Button
variant="tertiary"
size="small"
onClick={() => {
setDraft(emptyDraft);
setOpen(false);
}}
>
{t("projects.actions.cancel")}
</Button>
</div>
</div>
);
}
export function BoardSettingsPage(props: BoardSettingsPageProps) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const submit = props.actions.onSubmit;
const board = props.data.board;
const [renaming, setRenaming] = useState(false);
const [name, setName] = useState(board.name);
useEffect(() => {
setName(board.name);
setRenaming(false);
}, [board.name]);
/** Saves the board name and leaves the edit mode. Closing here rather than
* waiting for the loader matters when the name did not actually change:
* `board.name` stays the same, so the effect above never fires and the
* header would sit in the input forever. */
function saveName() {
const next = name.trim();
if (!next) return;
submit("updatePipeline", { pipelineId: board.id, name: next });
setRenaming(false);
}
const metaParts = [
// The export shows a short board id ("BRD-014") next to the status. Pipeline
// has no such number, so this is the real id — the value support and a
// deep link actually need — rather than an invented display number.
t("projects.boardSettings.meta.boardId", { id: board.id }),
t(board.typHintLabelKey),
t("projects.boardSettings.meta.projects", { count: board.projectCount }),
board.updatedAtIso
? t("projects.boardSettings.meta.updated", { date: formatters.dateTime(board.updatedAtIso) })
: t("projects.boardSettings.meta.neverUpdated"),
];
return (
<PageShell uiId="ui.projects.boardSettings" className="bg-surface-neutral-primary">
<PageHeader
icon={<FeatherKanban className={PAGE_HEADER_ICON_CLASS} />}
title={
renaming ? (
<span className="flex items-center gap-2">
<TextInput>
<TextInput.Input
autoFocus
value={name}
aria-label={t("projects.fields.name")}
onChange={(e) => setName(e.target.value)}
// Enter saves, Escape drops the draft — a one-field editor
// should not force the mouse onto the check mark.
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
saveName();
}
if (event.key === "Escape") {
setName(board.name);
setRenaming(false);
}
}}
data-ui-id="ui.projects.boardSettings.rename.input"
/>
</TextInput>
<IconButton
variant="success"
size="small"
square
icon={<FeatherCheck />}
disabled={!name.trim()}
loading={props.submitting}
aria-label={t("projects.actions.save")}
onClick={saveName}
data-ui-id="ui.projects.boardSettings.rename.save"
/>
<IconButton
variant="ghost"
size="small"
square
icon={<FeatherX />}
aria-label={t("projects.actions.cancel")}
onClick={() => {
setName(board.name);
setRenaming(false);
}}
/>
</span>
) : (
<span className="flex items-center gap-2">
{board.name}
<IconButton
variant="ghost"
size="small"
square
icon={<FeatherPencil />}
aria-label={t("projects.actions.edit")}
onClick={() => setRenaming(true)}
data-ui-id="ui.projects.boardSettings.rename.open"
/>
<BadgeFeedback farbe={board.statusKey === "active" ? "subtle-positive" : "subtle-neutral"} size="small">
{t(`projects.boardSettings.status.${board.statusKey}`)}
</BadgeFeedback>
{board.isDefault ? (
<BadgeFeedback farbe="subtle-brand-primary" size="small">{t("projects.admin.defaultBadge")}</BadgeFeedback>
) : null}
</span>
)
}
subtitle={metaParts.join(" · ")}
/>
<PageBody>
{props.errorKey ? (
<Alert variant="error" notDismissible title={t(props.errorKey)} data-ui-id="ui.projects.boardSettings.error" />
) : null}
{!board.valid ? (
<Alert variant="warning" notDismissible title={t("projects.admin.invalidHint")} data-ui-id="ui.projects.boardSettings.invalid" />
) : null}
<section className="flex w-full flex-col items-start gap-4">
<SectionHeader title={t("projects.boardSettings.columns.title")} description={t("projects.boardSettings.columns.description")} />
<Alert variant="information" notDismissible description={t("projects.boardSettings.columns.hint")} />
<StageTable board={board} submit={submit} submitting={props.submitting} />
<AddStageForm pipelineId={board.id} submit={submit} submitting={props.submitting} />
</section>
<section className="flex w-full flex-col items-start gap-4">
<SectionHeader
title={t("projects.boardSettings.detailFields.title")}
description={t("projects.boardSettings.detailFields.description")}
/>
<div className="flex w-full items-stretch rounded-lg border border-solid border-border-default bg-surface-neutral-secondary shadow-sm mobile:flex-col">
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-3 px-5 py-4">
<p className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("projects.boardSettings.detailFields.body")}
</p>
<div className="flex w-full flex-col items-start gap-2 border-t border-solid border-border-default pt-3">
<div className="flex w-full items-start gap-2">
<FeatherArrowRightCircle aria-hidden className="text-body-default-regular-0 text-icon-neutral-tertiary" />
<span className={sectionDescription}>{t("projects.boardSettings.detailFields.bulletOrder")}</span>
</div>
<div className="flex w-full items-start gap-2">
<FeatherClipboardList aria-hidden className="text-body-default-regular-0 text-icon-neutral-tertiary" />
<span className={sectionDescription}>{t("projects.boardSettings.detailFields.bulletRights")}</span>
</div>
</div>
</div>
<div className="flex w-80 flex-none flex-col items-start justify-center gap-3 border-l border-solid border-border-default px-5 py-4 mobile:w-full mobile:border-l-0 mobile:border-t">
<span className="text-body-small-semibold-150 font-body-small-semibold-150 text-text-neutral-primary">
{t("projects.boardSettings.detailFields.openTitle")}
</span>
<AppLink href={props.fieldTemplateHref} className="w-full no-underline" data-ui-id="ui.projects.boardSettings.fieldTemplate">
<Button className="w-full" iconRight={<FeatherArrowRightCircle />}>
{t("projects.admin.fieldTemplateLink")}
</Button>
</AppLink>
</div>
</div>
</section>
<section className="flex w-full flex-col items-start gap-4">
<SectionHeader title={t("projects.admin.access")} description={t("projects.boardSettings.access.description")} />
{/* Same card as the sections above, but collapsed: the rules are read
here far less often than the columns are edited, so the section
states how many there are and opens on demand. */}
<Accordion
className="rounded-lg border-border-default bg-surface-neutral-secondary shadow-sm hover:bg-surface-neutral-secondary"
data-ui-id="ui.projects.boardSettings.access"
trigger={
<div className="flex w-full items-center gap-3 px-5 py-4">
<Accordion.Chevron />
<span className="text-body-small-semibold-150 font-body-small-semibold-150 text-text-neutral-primary">
{t("projects.boardSettings.access.toggle")}
</span>
<BadgeFeedback farbe="subtle-neutral" size="small">
{t("projects.boardSettings.access.count", { count: board.accessRules.length })}
</BadgeFeedback>
</div>
}
>
<div className="flex w-full flex-col items-start gap-2 border-t border-solid border-border-default px-5 py-4">
{board.accessRules.length === 0 ? (
<span className={mutedText}>{t("projects.admin.noAccessRules")}</span>
) : (
board.accessRules.map((rule) => (
<div key={rule.id} className="flex flex-wrap items-center gap-2" data-row-id={rule.id}>
<BadgeFeedback farbe="subtle-neutral" size="small">{t(rule.principalTypeLabelKey)}</BadgeFeedback>
<span className={mutedText}>{rule.principalId}</span>
{rule.kannSehen ? <BadgeFeedback farbe="subtle-positive" size="small">{t("projects.admin.canSee")}</BadgeFeedback> : null}
{rule.kannBearbeiten ? <BadgeFeedback farbe="subtle-positive" size="small">{t("projects.admin.canEdit")}</BadgeFeedback> : null}
</div>
))
)}
</div>
</Accordion>
</section>
</PageBody>
</PageShell>
);
}
export default BoardSettingsPage;
@@ -0,0 +1,186 @@
// WF-P8 Subframe delta — BoardsStartPage unit test. Fixture via the real
// buildBoardsStartVM; assertions cover rendering, admin gating, the
// client-side search/type filter and the locked-board rows (greyed out,
// request-access action / pending badge, no links). i18n mocked.
import { fireEvent, render, screen, within } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { vi } from "vitest";
import { buildBoardsStartVM, type BoardsStartData } from "@hivegrid/view-models";
import { BoardsStartPage, filterBoardRows } from "./BoardsStartPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }),
}));
// Radix dropdowns neither open nor provide their menu context in jsdom, so the
// facet options would be unreachable. Both the SubframeCore wrapper and the
// ~/ui menu are swapped for passthroughs; the entries stay real buttons.
vi.mock("@subframe/core", async () => {
const actual = await vi.importActual<Record<string, unknown>>("@subframe/core");
const Pass = ({ children }: { children?: React.ReactNode }) => <>{children}</>;
return { ...actual, DropdownMenu: { Root: Pass, Trigger: Pass, Portal: Pass, Content: Pass, Item: Pass } };
});
vi.mock("~/ui/components/DropdownMenuMultiSelect", () => {
const DropdownMenuMultiSelect = ({ children }: { children?: React.ReactNode }) => <div>{children}</div>;
DropdownMenuMultiSelect.DropdownItem = ({ children, onClick, selected, ...rest }: any) => (
<button type="button" onClick={onClick} aria-pressed={Boolean(selected)} data-ui-id={rest["data-ui-id"]}>
{children}
</button>
);
DropdownMenuMultiSelect.DropdownCustomItem = ({ children }: any) => <div>{children}</div>;
DropdownMenuMultiSelect.DropdownUserItem = ({ title }: any) => <div>{title}</div>;
DropdownMenuMultiSelect.DropdownDivider = () => <hr />;
return { DropdownMenuMultiSelect };
});
const byUiId = (id: string) => document.querySelector(`[data-ui-id='${id}']`) as HTMLElement;
const noopActions = { onRequestAccess: () => undefined };
function boardsData(
overrides: { canAdmin?: boolean; empty?: boolean; locked?: boolean; requestPending?: boolean } = {}
): BoardsStartData {
const vm = buildBoardsStartVM({
pipelines: overrides.empty
? []
: [
{ id: "pl1", name: "Vertrieb", typHint: "sales", isDefault: true, stageCount: 5, projectCount: 12 },
{ id: "pl2", name: "Montage", typHint: "auftrag", isDefault: false, stageCount: 4, projectCount: 3 },
],
lockedPipelines: overrides.locked
? [
{
id: "pl3",
name: "Geschaeftsleitung",
typHint: "custom",
isDefault: false,
stageCount: 3,
projectCount: 9,
requestPending: overrides.requestPending ?? false,
},
]
: [],
perms: { canAdmin: overrides.canAdmin ?? true },
buildOpenHref: (id) => `/acme/projects?pipelineId=${id}`,
buildSettingsHref: (id) => `/acme/admin/pipelines/${id}`,
adminHref: "/acme/admin/pipelines",
lostReasonsHref: "/acme/admin/pipelines/lost-reasons",
});
if (vm.status !== "ready") throw new Error("fixture not ready");
return vm.data;
}
describe("BoardsStartPage", () => {
it("renders the boards with counts, open links and status", () => {
render(<BoardsStartPage data={boardsData()} actions={noopActions} />);
expect(screen.getByText("Vertrieb")).toBeTruthy();
expect(screen.getByText("Montage")).toBeTruthy();
expect(byUiId("ui.projects.boards.open.pl1").getAttribute("href")).toBe("/acme/projects?pipelineId=pl1");
expect(byUiId("ui.projects.boards.table")).toBeTruthy();
expect(byUiId("ui.projects.boards.count").textContent).toContain("projects.boards.countLine");
// Scoped to the table: the facet menus carry the same option captions.
const table = within(byUiId("ui.projects.boards.table"));
expect(table.getAllByText("projects.boards.status.usable")).toHaveLength(2);
// New S00 columns: type tag, "N Spalten", access state and the footer line.
expect(table.getAllByText("projects.typHint.sales")).toHaveLength(1);
expect(table.getAllByText("projects.boards.stagesValue")).toHaveLength(2);
expect(table.getAllByText("projects.boards.access.granted")).toHaveLength(2);
expect(byUiId("ui.projects.boards.footer").textContent).toContain("projects.boards.footerLine");
});
it("filters by access and by status", () => {
const rows = boardsData({ locked: true }).rows;
const base = { search: "", typ: new Set<string>(), access: new Set<string>(), status: new Set<string>() };
const names = (result: readonly { name: string }[]) => result.map((row) => row.name);
expect(names(filterBoardRows(rows, { ...base, access: new Set(["requestable"]) }))).toEqual(["Geschaeftsleitung"]);
expect(names(filterBoardRows(rows, { ...base, access: new Set(["granted"]) }))).toEqual(["Vertrieb", "Montage"]);
expect(names(filterBoardRows(rows, { ...base, status: new Set(["active"]) }))).toEqual(["Vertrieb", "Montage"]);
expect(names(filterBoardRows(rows, { ...base, status: new Set(["locked"]) }))).toEqual(["Geschaeftsleitung"]);
expect(names(filterBoardRows(rows, { ...base, typ: new Set(["auftrag"]) }))).toEqual(["Montage"]);
// Several values inside one facet are OR-ed, not AND-ed.
expect(names(filterBoardRows(rows, { ...base, typ: new Set(["sales", "auftrag"]) }))).toEqual(["Vertrieb", "Montage"]);
// Facets combine rather than override each other.
expect(filterBoardRows(rows, { ...base, typ: new Set(["custom"]), status: new Set(["active"]) })).toEqual([]);
// An empty facet is not a filter.
expect(names(filterBoardRows(rows, base))).toHaveLength(rows.length);
});
it("renders all three facet controls", () => {
render(<BoardsStartPage data={boardsData()} actions={noopActions} />);
expect(byUiId("ui.projects.boards.filter.typ")).toBeTruthy();
expect(byUiId("ui.projects.boards.filter.access")).toBeTruthy();
expect(byUiId("ui.projects.boards.filter.status")).toBeTruthy();
});
it("filters on a facet click and takes the filter back off via its chip", () => {
render(<BoardsStartPage data={boardsData()} actions={noopActions} />);
fireEvent.click(byUiId("ui.projects.boards.filter.typ.auftrag"));
expect(within(byUiId("ui.projects.boards.table")).queryByText("Vertrieb")).toBeNull();
// Every active facet leaves a chip, so there is always a way back.
fireEvent.click(byUiId("ui.projects.boards.filter.chip.typ.auftrag.remove"));
expect(within(byUiId("ui.projects.boards.table")).getByText("Vertrieb")).toBeTruthy();
});
it("shows admin actions only for projects.admin viewers", () => {
const { unmount } = render(<BoardsStartPage data={boardsData({ canAdmin: true })} actions={noopActions} />);
// Davids S00 (Subframe 2026-07-28) has all three header actions back, plus
// the per-row gear that deep-links into that board's settings card (S04).
expect(byUiId("ui.projects.boards.newBoard").getAttribute("href")).toBe("/acme/admin/pipelines");
expect(byUiId("ui.projects.boards.adminSettings").getAttribute("href")).toBe("/acme/admin/pipelines");
expect(byUiId("ui.projects.boards.lostReasons").getAttribute("href")).toBe("/acme/admin/pipelines/lost-reasons");
expect(byUiId("ui.projects.boards.settings.pl1").getAttribute("href")).toBe("/acme/admin/pipelines/pl1");
unmount();
render(<BoardsStartPage data={boardsData({ canAdmin: false })} actions={noopActions} />);
expect(byUiId("ui.projects.boards.newBoard")).toBeNull();
expect(byUiId("ui.projects.boards.adminSettings")).toBeNull();
expect(byUiId("ui.projects.boards.lostReasons")).toBeNull();
expect(byUiId("ui.projects.boards.settings.pl1")).toBeNull();
});
it("renders locked boards greyed out without links and requests access on click", () => {
const onRequestAccess = vi.fn();
render(<BoardsStartPage data={boardsData({ locked: true })} actions={{ onRequestAccess }} />);
// Name is plain text (no open link), lock status + Klartext hint shown.
expect(byUiId("ui.projects.boards.open.pl3")).toBeNull();
expect(byUiId("ui.projects.boards.lockedName.pl3").textContent).toBe("Geschaeftsleitung");
// The gear survives on a locked board: configuring it is an admin
// capability, separate from being allowed to work on it.
expect(byUiId("ui.projects.boards.settings.pl3").getAttribute("href")).toBe("/acme/admin/pipelines/pl3");
const table = within(byUiId("ui.projects.boards.table"));
expect(table.getByText("projects.boards.status.locked")).toBeTruthy();
expect(table.getByText("projects.boards.locked.noPermission")).toBeTruthy();
// Counts line switches to the variant including the locked part.
expect(byUiId("ui.projects.boards.count").textContent).toContain("projects.boards.countLineWithLocked");
// Request-access button posts via the injected callback.
fireEvent.click(byUiId("ui.projects.boards.requestAccess.pl3"));
expect(onRequestAccess).toHaveBeenCalledWith("pl3");
});
it("shows a pending badge instead of a dead button once a request is open", () => {
render(<BoardsStartPage data={boardsData({ locked: true, requestPending: true })} actions={noopActions} />);
expect(byUiId("ui.projects.boards.requestAccess.pl3")).toBeNull();
expect(byUiId("ui.projects.boards.requestPending.pl3").textContent).toContain("projects.boards.locked.requestPending");
});
it("filters boards client-side by search text", () => {
render(<BoardsStartPage data={boardsData()} actions={noopActions} />);
const input = byUiId("ui.projects.boards.filter.search") as HTMLInputElement;
fireEvent.change(input, { target: { value: "mont" } });
expect(screen.queryByText("Vertrieb")).toBeNull();
expect(screen.getByText("Montage")).toBeTruthy();
fireEvent.change(input, { target: { value: "gibtsnicht" } });
expect(byUiId("ui.projects.boards.noMatches")).toBeTruthy();
});
it("renders a klartext empty state when the tenant has no boards", () => {
render(<BoardsStartPage data={boardsData({ empty: true })} actions={noopActions} />);
expect(byUiId("ui.projects.boards.empty")).toBeTruthy();
expect(screen.getByText("projects.boards.emptyTitle")).toBeTruthy();
});
});
@@ -0,0 +1,390 @@
// WF-P8 S00 "Boards-Startseite" — rebuilt against Davids Subframe export of
// 2026-07-28 (page 1778cf5e-777b-439c-81b6-c51f85283cc4) plus the local
// wireframe doc, which is the authoritative copy for this nachzug.
//
// Pure/presentational: renders the server-built BoardsStartData; search and the
// three facet filters are client-side (the board list is small). Usable boards
// navigate via links; locked boards (deny-based PipelineAccess rule) stay
// visible per the design — greyed out, no links, with a "request access" action
// that the route wires to a POST. No useLoaderData/useFetcher, no server
// imports, plain document flow (the app shell's <main> scrolls).
//
// Deltas against the export that are deliberate, not oversights:
// * The Status facet offers Aktiv/Gesperrt only. "Entwurf"/"Archiviert" have
// no board state behind them (archived boards are not listed at all), and a
// filter option that can never match is worse than an absent one.
// * The Zugriff facet offers Freigegeben/Freigabe nötig. The export's third
// option "Nur ich" needs an owner concept that PipelineAccess does not have.
// * Board icons are derived from the board type. Pipeline carries no icon
// column, and inventing one per board would be data we do not have.
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
FeatherActivity,
FeatherCheckCircle,
FeatherChevronRight,
FeatherFilter,
FeatherKanbanSquare,
FeatherLock,
FeatherPlus,
FeatherSettings,
FeatherUnlockKeyhole,
FeatherXCircle,
} from "@subframe/core";
import { BOARD_TYP_ICON, BOARD_TYP_TONE } from "./boardTypeVisuals";
import type { BoardsStartData, BoardsStartRowVM, BoardsStartTypHint } from "@hivegrid/view-models";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { AppLink } from "~/components/app/AppLink";
import { EmptyState } from "~/ui/components/EmptyState";
import { IconButton } from "~/ui/components/IconButton";
import { Table } from "~/ui/components/Table";
import { Tag_Label } from "~/ui/components/Tag_Label";
import { useLocaleFormatters } from "~/locale/format";
import { FacetFilterBar, type ClientFacet } from "../shared/FacetFilterBar";
import { PAGE_HEADER_ICON_CLASS, PageHeader, PageShell } from "../shared/PageShell";
export type BoardsStartPageProps = {
data: BoardsStartData;
/** Route-injected action callbacks (M014 shape) — the screen never posts itself. */
actions: {
onRequestAccess: (pipelineId: string) => void;
};
/** Disables the request-access buttons while a submission is in flight. */
submitting?: boolean;
};
export type BoardsStartTypFilter = BoardsStartTypHint;
export type BoardsStartAccessFilter = "granted" | "requestable";
export type BoardsStartStatusFilter = "active" | "locked";
const TYP_VALUES: readonly BoardsStartTypFilter[] = ["sales", "auftrag", "custom"];
const ACCESS_VALUES: readonly BoardsStartAccessFilter[] = ["granted", "requestable"];
const STATUS_VALUES: readonly BoardsStartStatusFilter[] = ["active", "locked"];
/** Muted styling for locked (greyed-out) board rows. */
const LOCKED_CELL_CLASS = "opacity-60";
// Board type → icon tile / tag tone. Shared with the S07 board table; Pipeline
// has no icon column, the type is what we know.
const TYP_ICON = BOARD_TYP_ICON;
const TYP_TONE = BOARD_TYP_TONE;
export type BoardsStartFilters = {
readonly search: string;
/** Empty set = facet not filtered. Several values in one facet are OR-ed. */
readonly typ: ReadonlySet<string>;
readonly access: ReadonlySet<string>;
readonly status: ReadonlySet<string>;
};
/**
* Client-side facet filter, exported so it can be tested as a plain function.
* The facet menus are Radix widgets that jsdom cannot drive, so asserting the
* behaviour through the rendered dropdown would test the widget, not the rule.
*/
export function filterBoardRows(
rows: readonly BoardsStartRowVM[],
filters: BoardsStartFilters
): readonly BoardsStartRowVM[] {
const q = filters.search.trim().toLowerCase();
return rows.filter((row) => {
if (filters.typ.size > 0 && !filters.typ.has(row.typHint)) return false;
if (filters.access.size > 0 && !filters.access.has(row.locked ? "requestable" : "granted")) return false;
if (filters.status.size > 0 && !filters.status.has(row.locked ? "locked" : "active")) return false;
if (q && !row.name.toLowerCase().includes(q)) return false;
return true;
});
}
const EMPTY_SELECTION: ReadonlySet<string> = new Set();
/** Adds or removes one value of a facet. */
function toggleValue(current: ReadonlySet<string>, value: string): ReadonlySet<string> {
const next = new Set(current);
if (!next.delete(value)) next.add(value);
return next;
}
export function BoardsStartPage(props: BoardsStartPageProps) {
const { t } = useTranslation();
const { number } = useLocaleFormatters();
const { data, actions, submitting = false } = props;
const [search, setSearch] = useState("");
const [typ, setTyp] = useState<ReadonlySet<string>>(EMPTY_SELECTION);
const [access, setAccess] = useState<ReadonlySet<string>>(EMPTY_SELECTION);
const [status, setStatus] = useState<ReadonlySet<string>>(EMPTY_SELECTION);
const rows = useMemo(
() => filterBoardRows(data.rows, { search, typ, access, status }),
[data.rows, search, typ, access, status]
);
const facets: ClientFacet[] = [
{
key: "typ",
label: t("projects.boards.columns.typ"),
icon: <FeatherFilter />,
selected: typ,
options: TYP_VALUES.map((value) => ({ value, label: t(`projects.typHint.${value}`), tone: TYP_TONE[value] })),
},
{
key: "access",
label: t("projects.boards.columns.access"),
icon: <FeatherLock />,
tone: "blue-subtle",
selected: access,
options: ACCESS_VALUES.map((value) => ({ value, label: t(`projects.boards.access.${value}`) })),
},
{
key: "status",
label: t("projects.boards.columns.status"),
icon: <FeatherActivity />,
tone: "sky-subtle",
selected: status,
options: STATUS_VALUES.map((value) => ({
value,
label: value === "active" ? t("projects.boards.status.usable") : t("projects.boards.status.locked"),
})),
},
];
const FACET_SETTERS: Record<string, (value: string) => void> = {
typ: (value) => setTyp((current) => toggleValue(current, value)),
access: (value) => setAccess((current) => toggleValue(current, value)),
status: (value) => setStatus((current) => toggleValue(current, value)),
};
function resetFilters() {
setSearch("");
setTyp(EMPTY_SELECTION);
setAccess(EMPTY_SELECTION);
setStatus(EMPTY_SELECTION);
}
function renderAccessCell(row: BoardsStartRowVM) {
if (!row.locked) {
return (
<div className="flex items-center gap-1.5">
<FeatherCheckCircle className="text-body-small-regular-0 text-icon-feedback-positive" aria-hidden />
<span className="whitespace-nowrap text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
{t("projects.boards.access.granted")}
</span>
</div>
);
}
return (
<div className="flex items-center gap-1.5">
<FeatherLock className="text-body-small-regular-0 text-icon-neutral-subtle" aria-hidden />
<span className="whitespace-nowrap text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{row.requestPending ? t("projects.boards.access.pending") : t("projects.boards.locked.noPermission")}
</span>
</div>
);
}
function renderActionCell(row: BoardsStartRowVM) {
// The row gear opens this board's settings (S04). It stays available on
// locked boards for admins — configuring a board is an admin capability,
// not a "can I work on it" capability.
const gear = row.settingsHref ? (
<AppLink href={row.settingsHref} aria-label={t("projects.boards.actions.boardSettings")} data-ui-id={`ui.projects.boards.settings.${row.id}`}>
<IconButton variant="ghost" size="small" icon={<FeatherSettings />} />
</AppLink>
) : null;
if (!row.locked) {
return (
<div className="flex items-center justify-end gap-1">
{row.openHref ? (
<AppLink href={row.openHref}>
<Button variant="tertiary" size="small" iconRight={<FeatherChevronRight />} data-ui-id={`ui.projects.boards.openButton.${row.id}`}>
{t("projects.boards.actions.open")}
</Button>
</AppLink>
) : null}
{gear}
</div>
);
}
return (
<div className="flex items-center justify-end gap-1">
{row.requestPending ? (
// No dead button: a pending request renders as a plain status badge.
<BadgeFeedback farbe="subtle-information" size="small" data-ui-id={`ui.projects.boards.requestPending.${row.id}`}>
{t("projects.boards.locked.requestPending")}
</BadgeFeedback>
) : (
<Button
variant="tertiary"
size="small"
icon={<FeatherUnlockKeyhole />}
disabled={submitting}
onClick={() => actions.onRequestAccess(row.id)}
data-ui-id={`ui.projects.boards.requestAccess.${row.id}`}
>
{t("projects.boards.locked.requestAccess")}
</Button>
)}
{gear}
</div>
);
}
return (
<PageShell uiId="ui.projects.boards">
<PageHeader
icon={<FeatherKanbanSquare className={PAGE_HEADER_ICON_CLASS} />}
title={t("projects.boards.title")}
subtitle={t("projects.boards.subtitle")}
actions={
data.canAdmin ? (
<>
{data.adminHref ? (
<AppLink href={data.adminHref} data-ui-id="ui.projects.boards.adminSettings">
<Button variant="tertiary" icon={<FeatherSettings />}>{t("projects.boards.actions.adminSettings")}</Button>
</AppLink>
) : null}
{data.lostReasonsHref ? (
<AppLink href={data.lostReasonsHref} data-ui-id="ui.projects.boards.lostReasons">
<Button variant="tertiary" icon={<FeatherXCircle />}>{t("projects.boards.actions.lostReasons")}</Button>
</AppLink>
) : null}
{data.newBoardHref ? (
<AppLink href={data.newBoardHref} data-ui-id="ui.projects.boards.newBoard">
<Button variant="primary" icon={<FeatherPlus />}>{t("projects.boards.actions.newBoard")}</Button>
</AppLink>
) : null}
</>
) : undefined
}
/>
{data.rows.length === 0 ? (
<div className="w-full p-6" data-ui-id="ui.projects.boards.empty">
<EmptyState
title={t("projects.boards.emptyTitle")}
body={data.canAdmin ? t("projects.boards.emptyAdminHint") : t("projects.boards.emptyReaderHint")}
action={
data.canAdmin && data.newBoardHref ? (
<AppLink href={data.newBoardHref} data-ui-id="ui.projects.boards.empty.newBoard">
<Button variant="primary" icon={<FeatherPlus />}>{t("projects.boards.actions.newBoard")}</Button>
</AppLink>
) : undefined
}
/>
</div>
) : (
<>
{/* --- Filter bar (S00: Typ / Zugriff / Status) --- */}
<FacetFilterBar
uiId="ui.projects.boards.filter"
facets={facets}
onToggle={(facetKey, value) => FACET_SETTERS[facetKey]?.(value)}
search={search}
onSearchChange={setSearch}
searchPlaceholder={t("projects.boards.searchPlaceholder")}
onReset={resetFilters}
labels={{ reset: t("projects.board.filter.reset"), removeChip: t("projects.board.filter.removeChip") }}
trailing={
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary" data-ui-id="ui.projects.boards.count">
{data.lockedCount > 0
? t("projects.boards.countLineWithLocked", { total: number(data.totalCount), usable: number(data.usableCount), locked: number(data.lockedCount) })
: t("projects.boards.countLine", { total: number(data.totalCount), usable: number(data.usableCount) })}
</span>
}
/>
{/* --- Boards table (the ~/ui Table ignores its emptyText prop, so the
no-matches state is rendered explicitly below) --- */}
{rows.length === 0 ? (
<div className="w-full px-6 pt-4 pb-6 mobile:px-4" data-ui-id="ui.projects.boards.noMatches">
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-tertiary">{t("projects.boards.noMatches")}</span>
</div>
) : (
<div className="w-full px-6 pt-4 pb-6 mobile:px-4">
<div className="w-full overflow-x-auto rounded-lg border border-solid border-border-default shadow-sm">
<Table
data-ui-id="ui.projects.boards.table"
header={
<Table.HeaderRow className="bg-surface-neutral-tertiary">
<Table.HeaderCell>{t("projects.boards.columns.board")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.boards.columns.typ")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.boards.columns.stages")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.boards.columns.projects")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.boards.columns.access")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.boards.columns.status")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.boards.columns.action")}</Table.HeaderCell>
</Table.HeaderRow>
}
>
{rows.map((row) => (
<Table.Row key={row.id} data-row-id={row.id} className={row.locked ? "bg-surface-neutral-tertiary" : undefined}>
<Table.Cell className={row.locked ? LOCKED_CELL_CLASS : undefined}>
<div className="flex items-center gap-3">
<div className="flex h-8 w-8 flex-none items-center justify-center rounded-md border border-solid border-border-default bg-surface-neutral-tertiary text-body-default-regular-0 text-icon-neutral-tertiary">
{TYP_ICON[row.typHint]}
</div>
<div className="flex items-center gap-2">
{row.locked ? (
<>
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-tertiary" data-ui-id={`ui.projects.boards.lockedName.${row.id}`}>
{row.name}
</span>
<FeatherLock className="text-body-small-regular-0 text-icon-neutral-subtle" aria-hidden />
</>
) : (
<AppLink href={row.openHref!} className="text-body-default-medium-0 font-body-default-medium-0 text-text-feedback-link-default" data-ui-id={`ui.projects.boards.open.${row.id}`}>
{row.name}
</AppLink>
)}
{row.isDefault ? (
<BadgeFeedback farbe="subtle-information" size="small">{t("projects.boards.defaultBadge")}</BadgeFeedback>
) : null}
</div>
</div>
</Table.Cell>
<Table.Cell className={row.locked ? LOCKED_CELL_CLASS : undefined}>
<Tag_Label tone={row.locked ? "neutral-subtle" : TYP_TONE[row.typHint]} noAction size="small">
{t(row.typLabelKey)}
</Tag_Label>
</Table.Cell>
<Table.Cell className={row.locked ? LOCKED_CELL_CLASS : undefined}>
<span className="whitespace-nowrap text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("projects.boards.stagesValue", { count: row.stageCount, formatted: number(row.stageCount) })}
</span>
</Table.Cell>
<Table.Cell className={row.locked ? LOCKED_CELL_CLASS : undefined}>
<span className="whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary">{number(row.projectCount)}</span>
</Table.Cell>
<Table.Cell className={row.locked ? LOCKED_CELL_CLASS : undefined}>{renderAccessCell(row)}</Table.Cell>
<Table.Cell className={row.locked ? LOCKED_CELL_CLASS : undefined}>
<BadgeFeedback farbe={row.locked ? "subtle-neutral" : "subtle-positive"} size="small">
{row.locked ? t("projects.boards.status.locked") : t("projects.boards.status.usable")}
</BadgeFeedback>
</Table.Cell>
{/* Export pins the action column to the right edge. */}
<Table.Cell variant="align-right">{renderActionCell(row)}</Table.Cell>
</Table.Row>
))}
</Table>
</div>
{/* Footer line from the export: makes the locked rows self-explaining. */}
<div className="flex w-full items-center gap-3 pt-3 mobile:flex-col mobile:items-start" data-ui-id="ui.projects.boards.footer">
<span className="grow shrink-0 basis-0 text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{data.lockedCount > 0
? t("projects.boards.footerLineWithLocked", { count: data.totalCount, formatted: number(data.totalCount) })
: t("projects.boards.footerLine", { count: data.totalCount, formatted: number(data.totalCount) })}
</span>
</div>
</div>
)}
</>
)}
</PageShell>
);
}
export default BoardsStartPage;
@@ -0,0 +1,195 @@
// WF-P8 S06 — LostReasonAdminPage unit test. Fixture via the real
// buildLostReasonAdminVM; interactions asserted on the injected onSubmit.
// The row menu is a Radix dropdown, so the entries are driven through the
// component's own state rather than through the portal.
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildLostReasonAdminVM, type LostReasonAdminData } from "@hivegrid/view-models";
import { filterLostReasons, LostReasonAdminPage } from "./LostReasonAdminPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }),
}));
// Radix dropdowns neither open nor provide their menu context in jsdom, so the
// row actions would be unreachable. Both the SubframeCore wrapper and the ~/ui
// menu are swapped for plain passthroughs; the entries stay real buttons, which
// is what these tests are about.
vi.mock("@subframe/core", async () => {
const actual = await vi.importActual<Record<string, unknown>>("@subframe/core");
const Pass = ({ children }: { children?: React.ReactNode }) => <>{children}</>;
return { ...actual, DropdownMenu: { Root: Pass, Trigger: Pass, Portal: Pass, Content: Pass } };
});
vi.mock("~/ui/components/DropdownMenu", () => {
const DropdownMenu = ({ children }: { children?: React.ReactNode }) => <div>{children}</div>;
DropdownMenu.DropdownItem = ({ children, onSelect, ...rest }: any) => (
<button type="button" onClick={() => onSelect?.()} data-ui-id={rest["data-ui-id"]}>
{children}
</button>
);
DropdownMenu.DropdownDivider = () => <hr />;
return { DropdownMenu };
});
const byUiId = (id: string) => document.querySelector(`[data-ui-id='${id}']`) as HTMLElement;
type FixtureReason = Parameters<typeof buildLostReasonAdminVM>[0]["reasons"][number];
const defaultReasons: FixtureReason[] = [
{
id: "lr1",
name: "Preis zu hoch",
beschreibung: "Angebot lag über dem Budgetrahmen.",
kategorie: "Preis",
position: 10,
isDemoData: false,
istVorlage: true,
projectCount: 34,
lastUsedIso: "2026-07-12T06:42:00.000Z",
},
{
id: "lr2",
name: "Dublette",
position: 20,
isDemoData: false,
istVorlage: false,
archivedAt: "2026-07-01T00:00:00.000Z",
projectCount: 0,
lastUsedIso: null,
},
];
function reasonData(
reasons: FixtureReason[] = defaultReasons,
insights?: { topReasonName: string | null; recentLossCount: number; previousLossCount: number }
): LostReasonAdminData {
const vm = buildLostReasonAdminVM({ canAdmin: true, reasons, insights });
if (vm.status !== "ready") throw new Error("fixture not ready");
return vm.data;
}
function renderPage(data = reasonData()) {
const onSubmit = vi.fn();
render(<LostReasonAdminPage data={data} submitting={false} actions={{ onSubmit }} />);
return onSubmit;
}
describe("LostReasonAdminPage", () => {
it("renders the S06 table with origin, usage and status", () => {
renderPage();
expect(byUiId("ui.projects.lostReasons.list")).toBeTruthy();
expect(screen.getByText("Preis zu hoch")).toBeTruthy();
expect(screen.getByText("Angebot lag über dem Budgetrahmen.")).toBeTruthy();
expect(screen.getAllByText("projects.lostReasonsAdmin.origin.template")).toHaveLength(1);
expect(screen.getAllByText("projects.lostReasonsAdmin.origin.own")).toHaveLength(1);
expect(byUiId("ui.projects.lostReasons.row.lr1.projects").textContent).toContain("projects.lostReasonsAdmin.projectCount");
expect(byUiId("ui.projects.lostReasons.footer").textContent).toContain("projects.lostReasonsAdmin.footerLine");
});
it("labels the export's five columns and leaves the row-menu column unheaded", () => {
renderPage();
expect([...document.querySelectorAll("th")].map((th) => th.textContent?.trim())).toEqual([
"projects.lostReasonsAdmin.columns.reason",
"projects.lostReasonsAdmin.columns.description",
"projects.lostReasonsAdmin.columns.projects",
"projects.lostReasonsAdmin.columns.status",
"projects.lostReasonsAdmin.columns.lastUsed",
"",
]);
});
it("sorts archived reasons to the end, whatever their position says", () => {
// The archived "Dublette" carries the higher position but used to arrive
// first, pushing the reasons still in use down the list.
const data = reasonData();
expect(data.reasons.map((reason) => reason.name)).toEqual(["Preis zu hoch", "Dublette"]);
renderPage(data);
expect([...document.querySelectorAll("[data-row-id]")].map((row) => row.getAttribute("data-row-id"))).toEqual(["lr1", "lr2"]);
});
it("keeps both insight compartments, even with nothing to compare against", () => {
// The card used to drop the comparison entirely, which read as a broken header.
renderPage(reasonData(defaultReasons, { topReasonName: null, recentLossCount: 0, previousLossCount: 0 }));
const insights = byUiId("ui.projects.lostReasons.insights");
expect(insights.textContent).toContain("projects.lostReasonsAdmin.insights.topReason");
expect(insights.textContent).toContain("projects.lostReasonsAdmin.insights.monthComparison");
expect(byUiId("ui.projects.lostReasons.insights.change").textContent).toContain("projects.lostReasonsAdmin.insights.noComparison");
});
it("puts search, status and the add action into one filter bar and no button into the header", () => {
renderPage();
const bar = byUiId("ui.projects.lostReasons.filter");
expect(bar.querySelector("[data-ui-id='ui.projects.lostReasons.filter.search']")).toBeTruthy();
expect(bar.querySelector("[data-ui-id='ui.projects.lostReasons.filter.status']")).toBeTruthy();
expect(bar.querySelector("[data-ui-id='ui.projects.lostReasons.new.toggle']")).toBeTruthy();
// The header carries the loss picture only — no back link, no add button.
expect(byUiId("ui.projects.lostReasons.insights").querySelector("button")).toBeNull();
});
it("shows an empty state when there are no reasons", () => {
renderPage(reasonData([]));
expect(byUiId("ui.projects.lostReasons.empty")).toBeTruthy();
});
it("adds a reason with description and category", () => {
const onSubmit = renderPage();
fireEvent.click(byUiId("ui.projects.lostReasons.new.toggle"));
fireEvent.change(byUiId("ui.projects.lostReasons.new.name"), { target: { value: "Timing" } });
fireEvent.change(byUiId("ui.projects.lostReasons.new.kategorie"), { target: { value: "Zeitplan" } });
fireEvent.change(byUiId("ui.projects.lostReasons.new.beschreibung"), { target: { value: "Kunde verschiebt." } });
fireEvent.click(byUiId("ui.projects.lostReasons.new.create"));
expect(onSubmit).toHaveBeenCalledWith("upsertLostReason", {
name: "Timing",
kategorie: "Zeitplan",
beschreibung: "Kunde verschiebt.",
});
});
it("archives an active reason and reactivates an archived one", () => {
const onSubmit = renderPage();
fireEvent.click(byUiId("ui.projects.lostReasons.row.lr1.archive"));
expect(onSubmit).toHaveBeenCalledWith("archiveLostReason", { reasonId: "lr1" });
// The archived row offers the way back instead of a second archive.
expect(byUiId("ui.projects.lostReasons.row.lr2.archive")).toBeNull();
fireEvent.click(byUiId("ui.projects.lostReasons.row.lr2.reactivate"));
expect(onSubmit).toHaveBeenCalledWith("reactivateLostReason", { reasonId: "lr2" });
});
it("edits a reason in place", () => {
const onSubmit = renderPage();
fireEvent.click(byUiId("ui.projects.lostReasons.row.lr1.edit"));
fireEvent.change(byUiId("ui.projects.lostReasons.row.lr1.kategorieInput"), { target: { value: "Budget" } });
fireEvent.click(byUiId("ui.projects.lostReasons.row.lr1.save"));
expect(onSubmit).toHaveBeenCalledWith("upsertLostReason", {
reasonId: "lr1",
name: "Preis zu hoch",
beschreibung: "Angebot lag über dem Budgetrahmen.",
kategorie: "Budget",
position: "10",
});
});
it("filters by search text and status", () => {
const rows = reasonData().reasons;
const names = (result: readonly { name: string }[]) => result.map((row) => row.name);
expect(names(filterLostReasons(rows, { search: "", status: "active" }))).toEqual(["Preis zu hoch"]);
expect(names(filterLostReasons(rows, { search: "", status: "archived" }))).toEqual(["Dublette"]);
// Search covers description and category, not just the name.
expect(names(filterLostReasons(rows, { search: "budgetrahmen", status: "all" }))).toEqual(["Preis zu hoch"]);
expect(names(filterLostReasons(rows, { search: "preis", status: "all" }))).toEqual(["Preis zu hoch"]);
expect(filterLostReasons(rows, { search: "gibtsnicht", status: "all" })).toEqual([]);
});
it("compares the loss windows and does not invent a percentage out of zero", () => {
const withPrevious = reasonData(defaultReasons, { topReasonName: "Preis zu hoch", recentLossCount: 28, previousLossCount: 25 });
expect(withPrevious.insights.changePercent).toBe(12);
expect(withPrevious.insights.changeIsWorse).toBe(true);
// Nothing to compare against: a jump from 0 is not "+infinity percent".
const withoutPrevious = reasonData(defaultReasons, { topReasonName: null, recentLossCount: 5, previousLossCount: 0 });
expect(withoutPrevious.insights.changePercent).toBeNull();
expect(withoutPrevious.insights.changeIsWorse).toBe(false);
});
});
@@ -0,0 +1,547 @@
// WF-P8 S06 "Verlust-Gründe" — rebuilt against Davids Subframe export of
// 2026-07-28 (page 3c95e1e1-728b-460c-996f-5a641c971dfe) plus the local
// wireframe doc.
//
// Pure/presentational: renders the server-built LostReasonAdminData and turns
// create/edit/archive/reactivate into a typed onSubmit(intent, fields) the
// route POSTs. Search and the status facet are client-side (the list is a
// handful of rows). No useLoaderData/useFetcher and no server imports.
//
// Deliberate deltas against the export:
// * "Verlauf ansehen" has no screen behind it and is left out rather than
// shipped as a dead menu entry.
// * The export's DropdownMenuSelect is not in the local ~/ui kit; the row
// actions use the synced DropdownMenu, which is the same interaction.
import { useMemo, useState, type ChangeEvent } from "react";
import { useTranslation } from "react-i18next";
import type { LostReasonAdminData, LostReasonRowVM } from "@hivegrid/view-models";
import {
FeatherAlignLeft,
FeatherArchive,
FeatherCircleDot,
FeatherClock,
FeatherFilter,
FeatherFolderKanban,
FeatherMoreHorizontal,
FeatherPencil,
FeatherPlus,
FeatherThumbsDown,
FeatherTrendingDown,
FeatherTrendingUp,
FeatherUndo2,
} from "@subframe/core";
import * as SubframeCore from "@subframe/core";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, 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 { DropdownMenu } from "~/ui/components/DropdownMenu";
import { EmptyState } from "~/ui/components/EmptyState";
import { IconButton } from "~/ui/components/IconButton";
import { SearchInput } from "~/ui/components/SearchInput";
import { Select } from "~/ui/components/Select";
import { Table } from "~/ui/components/Table";
import { Tag_Label } from "~/ui/components/Tag_Label";
import { TextArea } from "~/ui/components/TextArea";
import { TextInput } from "~/ui/components/TextInput";
import { useLocaleFormatters } from "~/locale/format";
export type LostReasonAdminSubmit = (intent: string, fields: Record<string, string>) => void;
export type LostReasonAdminPageProps = {
data: LostReasonAdminData;
submitting: boolean;
errorKey?: string | null;
actions: { onSubmit: LostReasonAdminSubmit };
};
export type LostReasonStatusFilter = "all" | "active" | "archived";
const insightLabel =
"text-body-extra-small-medium-150 font-body-extra-small-medium-150 uppercase tracking-wide text-text-neutral-tertiary";
/** Client-side filter, exported so the rule can be tested without the Radix widget. */
export function filterLostReasons(
reasons: readonly LostReasonRowVM[],
filters: { search: string; status: LostReasonStatusFilter }
): readonly LostReasonRowVM[] {
const q = filters.search.trim().toLowerCase();
return reasons.filter((reason) => {
if (filters.status === "active" && reason.archived) return false;
if (filters.status === "archived" && !reason.archived) return false;
if (!q) return true;
return [reason.name, reason.beschreibung, reason.kategorie].some((field) => field?.toLowerCase().includes(q));
});
}
export function LostReasonAdminPage(props: LostReasonAdminPageProps) {
const { t } = useTranslation();
const { number, dateTime } = useLocaleFormatters();
const submit = props.actions.onSubmit;
const { data } = props;
const [search, setSearch] = useState("");
const [status, setStatus] = useState<LostReasonStatusFilter>("all");
const [createOpen, setCreateOpen] = useState(false);
const [draft, setDraft] = useState({ name: "", beschreibung: "", kategorie: "" });
const [editing, setEditing] = useState<string | null>(null);
const rows = useMemo(() => filterLostReasons(data.reasons, { search, status }), [data.reasons, search, status]);
function resetDraft() {
setDraft({ name: "", beschreibung: "", kategorie: "" });
setCreateOpen(false);
}
return (
<PageShell uiId="ui.projects.lostReasons" className="bg-surface-neutral-primary">
<PageHeader
icon={<FeatherThumbsDown className={PAGE_HEADER_ICON_CLASS} />}
title={t("projects.lostReasonsAdmin.title")}
subtitle={t("projects.lostReasonsAdmin.subtitle")}
actions={
/* Loss picture of the last 30 days, straight from the stage-change
history — the whole point of maintaining reasons. Both compartments
always render: a missing comparison is itself an answer, and a card
that changes width between tenants reads as a broken header. */
<div
className="flex items-center gap-3 rounded-md border border-solid border-border-default bg-surface-neutral-primary px-4 py-2.5 mobile:hidden"
data-ui-id="ui.projects.lostReasons.insights"
>
<div className="flex flex-col items-start gap-0.5">
<span className={insightLabel}>{t("projects.lostReasonsAdmin.insights.topReason")}</span>
<span className="text-body-default-semibold-150 font-body-default-semibold-150 text-text-neutral-primary">
{data.insights.topReasonName ?? t("projects.lostReasonsAdmin.insights.noLosses")}
</span>
</div>
<div className="flex h-8 w-px flex-none flex-col items-center bg-border-default" />
<div className="flex flex-col items-start gap-0.5">
<span className={insightLabel}>{t("projects.lostReasonsAdmin.insights.monthComparison")}</span>
{data.insights.changePercent === null ? (
<span
className="text-body-default-semibold-150 font-body-default-semibold-150 text-text-neutral-tertiary"
data-ui-id="ui.projects.lostReasons.insights.change"
>
{t("projects.lostReasonsAdmin.insights.noComparison")}
</span>
) : (
<div className="flex items-center gap-1">
{data.insights.changeIsWorse ? (
<FeatherTrendingUp className="text-body-small-regular-0 text-icon-feedback-negative" aria-hidden />
) : (
<FeatherTrendingDown className="text-body-small-regular-0 text-icon-feedback-positive" aria-hidden />
)}
<span
className={`text-body-default-semibold-150 font-body-default-semibold-150 ${
data.insights.changeIsWorse ? "text-text-feedback-negative" : "text-text-feedback-positive"
}`}
data-ui-id="ui.projects.lostReasons.insights.change"
>
{t("projects.lostReasonsAdmin.insights.changeValue", {
value: `${data.insights.changePercent > 0 ? "+" : ""}${number(data.insights.changePercent)}`,
})}
</span>
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("projects.lostReasonsAdmin.insights.versusPreviousMonth")}
</span>
</div>
)}
</div>
</div>
}
/>
<PageBody>
<div className="flex w-full flex-col gap-5">
{props.errorKey ? <BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback> : null}
<Alert
variant="information"
notDismissible
title={t("projects.lostReasonsAdmin.archiveNotice.title")}
description={t("projects.lostReasonsAdmin.archiveNotice.body")}
textSize="small"
/>
{/* Search and status facet as one bordered bar, as in the export. The
add action sits at its right end: the export draws no button at all,
but reasons have to come from somewhere, and the header card is the
loss picture, not a place for controls. */}
<div className="flex w-full flex-col items-start gap-3">
<div
className="flex w-full items-center gap-2 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-3 py-2 shadow-sm mobile:flex-col mobile:items-stretch"
data-ui-id="ui.projects.lostReasons.filter"
>
<SearchInput
// The bar itself is the bordered surface, so the field must not
// draw a second focus ring inside it.
className="h-8 grow shrink-0 basis-0 [&_label]:!shadow-none"
size="small"
borderless
// No `noPadding`: our SearchInput ties that to `w-auto`, which
// beats the fill and leaves the field at its minimum width.
fillContainer
hideShortcut
placeholder={t("projects.lostReasonsAdmin.searchPlaceholder")}
value={search}
onChange={(event: ChangeEvent<HTMLInputElement>) => setSearch(event.target.value)}
data-ui-id="ui.projects.lostReasons.filter.search"
/>
<div className="h-5 w-px flex-none bg-border-default mobile:hidden" />
<div className="flex items-center gap-2 mobile:w-full mobile:flex-none">
<FeatherFilter className="flex-none text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" aria-hidden />
<span className="whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-tertiary">
{t("projects.lostReasonsAdmin.statusLabel")}
</span>
<Select
size="small"
variant="filled"
borderless
className="h-8 w-36 flex-none mobile:w-full"
triggerAriaLabel={t("projects.lostReasonsAdmin.statusLabel")}
value={status}
onValueChange={(value) => setStatus(value as LostReasonStatusFilter)}
data-ui-id="ui.projects.lostReasons.filter.status"
>
<Select.Item value="all">{t("projects.lostReasonsAdmin.status.all")}</Select.Item>
<Select.Item value="active">{t("projects.lostReasonsAdmin.status.active")}</Select.Item>
<Select.Item value="archived">{t("projects.lostReasonsAdmin.status.archived")}</Select.Item>
</Select>
</div>
{data.canAdmin ? (
<>
<div className="h-5 w-px flex-none bg-border-default mobile:hidden" />
<Button
size="small"
className="flex-none"
icon={<FeatherPlus />}
onClick={() => setCreateOpen((open) => !open)}
data-ui-id="ui.projects.lostReasons.new.toggle"
>
{t("projects.actions.addLostReason")}
</Button>
</>
) : null}
</div>
<div className="flex w-full items-center justify-end mobile:justify-start">
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary" data-ui-id="ui.projects.lostReasons.count">
{t("projects.lostReasonsAdmin.countLine", {
total: number(data.totalCount),
templates: number(data.templateCount),
own: number(data.ownCount),
})}
</span>
</div>
</div>
{/* Creating a reason is a short, self-contained form. As an inline card
it pushed the whole table down; as a dialog the list stays put. */}
<Dialog open={createOpen && data.canAdmin} onOpenChange={(open) => (open ? setCreateOpen(true) : resetDraft())}>
<Dialog.Content className="p-6" data-ui-id="ui.projects.lostReasons.new">
<div className="flex w-full flex-col gap-4" style={{ minWidth: 480 }}>
<div className="flex items-center gap-2">
<FeatherThumbsDown className="text-body-large font-body-large text-icon-neutral-tertiary" aria-hidden />
<span className="text-body-large font-body-large text-text-neutral-primary">{t("projects.lostReasonsAdmin.newReason")}</span>
</div>
<div className="grid w-full items-end gap-3 sm:grid-cols-2">
<TextInput className="w-full" fillContainer showLabel label={t("projects.fields.name")}>
<TextInput.Input
autoFocus
value={draft.name}
onChange={(event) => setDraft((current) => ({ ...current, name: event.target.value }))}
data-ui-id="ui.projects.lostReasons.new.name"
/>
</TextInput>
<TextInput className="w-full" fillContainer showLabel label={t("projects.lostReasonsAdmin.fields.category")}>
<TextInput.Input
value={draft.kategorie}
onChange={(event) => setDraft((current) => ({ ...current, kategorie: event.target.value }))}
data-ui-id="ui.projects.lostReasons.new.kategorie"
/>
</TextInput>
</div>
<TextArea className="w-full max-w-none" showLabel label={t("projects.lostReasonsAdmin.fields.description")}>
<TextArea.Input
value={draft.beschreibung}
onChange={(event) => setDraft((current) => ({ ...current, beschreibung: event.target.value }))}
data-ui-id="ui.projects.lostReasons.new.beschreibung"
/>
</TextArea>
<div className="flex w-full items-center justify-end gap-2">
<Button variant="tertiary" onClick={resetDraft} data-ui-id="ui.projects.lostReasons.new.cancel">
{t("projects.actions.cancel")}
</Button>
<Button
icon={<FeatherPlus />}
disabled={!draft.name.trim()}
loading={props.submitting}
onClick={() => {
submit("upsertLostReason", {
name: draft.name.trim(),
beschreibung: draft.beschreibung.trim(),
kategorie: draft.kategorie.trim(),
});
resetDraft();
}}
data-ui-id="ui.projects.lostReasons.new.create"
>
{t("projects.actions.addLostReason")}
</Button>
</div>
</div>
</Dialog.Content>
</Dialog>
{data.reasons.length === 0 ? (
<div data-ui-id="ui.projects.lostReasons.empty">
<EmptyState title={t("projects.lostReasonsAdmin.empty")} />
</div>
) : rows.length === 0 ? (
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-tertiary" data-ui-id="ui.projects.lostReasons.noMatches">
{t("projects.lostReasonsAdmin.noMatches")}
</span>
) : (
<div className="w-full overflow-x-auto rounded-lg border border-solid border-border-default shadow-sm" data-ui-id="ui.projects.lostReasons.list">
<Table
header={
<Table.HeaderRow className="bg-surface-neutral-tertiary">
<Table.HeaderCell icon={<FeatherThumbsDown />}>{t("projects.lostReasonsAdmin.columns.reason")}</Table.HeaderCell>
<Table.HeaderCell icon={<FeatherAlignLeft />}>{t("projects.lostReasonsAdmin.columns.description")}</Table.HeaderCell>
<Table.HeaderCell icon={<FeatherFolderKanban />}>{t("projects.lostReasonsAdmin.columns.projects")}</Table.HeaderCell>
<Table.HeaderCell icon={<FeatherCircleDot />}>{t("projects.lostReasonsAdmin.columns.status")}</Table.HeaderCell>
<Table.HeaderCell icon={<FeatherClock />}>{t("projects.lostReasonsAdmin.columns.lastUsed")}</Table.HeaderCell>
{/* The row menu needs no heading — the export leaves it blank
rather than labelling a column of three dots. */}
<Table.HeaderCell />
</Table.HeaderRow>
}
>
{rows.map((reason) =>
editing === reason.id ? (
<LostReasonEditRow
key={reason.id}
reason={reason}
submit={submit}
submitting={props.submitting}
onDone={() => setEditing(null)}
/>
) : (
<LostReasonRow
key={reason.id}
reason={reason}
canAdmin={data.canAdmin}
submit={submit}
onEdit={() => setEditing(reason.id)}
formatDateTime={dateTime}
formatNumber={number}
/>
)
)}
</Table>
</div>
)}
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary" data-ui-id="ui.projects.lostReasons.footer">
{t("projects.lostReasonsAdmin.footerLine", {
total: number(data.totalCount),
projects: number(data.assignedProjectCount),
})}
</span>
</div>
</PageBody>
</PageShell>
);
}
function LostReasonRow({
reason,
canAdmin,
submit,
onEdit,
formatDateTime,
formatNumber,
}: {
reason: LostReasonRowVM;
canAdmin: boolean;
submit: LostReasonAdminSubmit;
onEdit: () => void;
formatDateTime: (value: string) => string;
formatNumber: (value: number) => string;
}) {
const { t } = useTranslation();
const muted = reason.archived ? "text-text-neutral-tertiary" : "text-text-neutral-primary";
return (
<Table.Row className={reason.archived ? "bg-surface-neutral-tertiary" : undefined} data-row-id={reason.id}>
<Table.Cell>
<div className="flex items-center gap-2">
<span className={`whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 ${muted}`}>{reason.name}</span>
<Tag_Label tone={reason.istVorlage ? "sky-subtle" : "neutral-subtle"} noAction size="small">
{t(reason.istVorlage ? "projects.lostReasonsAdmin.origin.template" : "projects.lostReasonsAdmin.origin.own")}
</Tag_Label>
{reason.isDemoData ? (
<BadgeFeedback farbe="subtle-neutral" size="small">{t("projects.lostReasonsAdmin.demoBadge")}</BadgeFeedback>
) : null}
</div>
</Table.Cell>
<Table.Cell>
<div className="flex flex-col items-start gap-0.5">
{reason.beschreibung ? (
<span className="line-clamp-2 max-w-[280px] text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
{reason.beschreibung}
</span>
) : null}
{reason.kategorie ? (
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("projects.lostReasonsAdmin.categoryPrefix", { category: reason.kategorie })}
</span>
) : null}
</div>
</Table.Cell>
<Table.Cell>
<span className={`whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 ${muted}`} data-ui-id={`ui.projects.lostReasons.row.${reason.id}.projects`}>
{t("projects.lostReasonsAdmin.projectCount", { count: reason.projectCount, formatted: formatNumber(reason.projectCount) })}
</span>
</Table.Cell>
<Table.Cell>
<BadgeFeedback farbe={reason.archived ? "subtle-neutral" : "subtle-positive"} size="small">
{t(reason.archived ? "projects.lostReasonsAdmin.status.archived" : "projects.lostReasonsAdmin.status.active")}
</BadgeFeedback>
</Table.Cell>
<Table.Cell>
<span className="whitespace-nowrap text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{reason.lastUsedIso ? formatDateTime(reason.lastUsedIso) : t("projects.lostReasonsAdmin.neverUsed")}
</span>
</Table.Cell>
<Table.Cell>
{canAdmin ? (
<div className="flex w-full items-center justify-end gap-1">
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<IconButton
variant="ghost"
size="small"
icon={<FeatherMoreHorizontal />}
aria-label={t("projects.lostReasonsAdmin.columns.actions")}
data-ui-id={`ui.projects.lostReasons.row.${reason.id}.menu`}
/>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="end" sideOffset={4} asChild>
<DropdownMenu>
<DropdownMenu.DropdownItem
icon={<FeatherPencil />}
onSelect={onEdit}
data-ui-id={`ui.projects.lostReasons.row.${reason.id}.edit`}
>
{t("projects.actions.edit")}
</DropdownMenu.DropdownItem>
<DropdownMenu.DropdownDivider />
{reason.canArchive ? (
<DropdownMenu.DropdownItem
className="text-text-feedback-negative"
icon={<FeatherArchive />}
onSelect={() => submit("archiveLostReason", { reasonId: reason.id })}
data-ui-id={`ui.projects.lostReasons.row.${reason.id}.archive`}
>
{t("projects.actions.archive")}
</DropdownMenu.DropdownItem>
) : (
<DropdownMenu.DropdownItem
icon={<FeatherUndo2 />}
onSelect={() => submit("reactivateLostReason", { reasonId: reason.id })}
data-ui-id={`ui.projects.lostReasons.row.${reason.id}.reactivate`}
>
{t("projects.actions.reactivate")}
</DropdownMenu.DropdownItem>
)}
</DropdownMenu>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
</div>
) : null}
</Table.Cell>
</Table.Row>
);
}
/** Inline edit row — name, category and description in place of the read row. */
function LostReasonEditRow({
reason,
submit,
submitting,
onDone,
}: {
reason: LostReasonRowVM;
submit: LostReasonAdminSubmit;
submitting: boolean;
onDone: () => void;
}) {
const { t } = useTranslation();
const [draft, setDraft] = useState({
name: reason.name,
beschreibung: reason.beschreibung ?? "",
kategorie: reason.kategorie ?? "",
});
return (
<Table.Row data-row-id={reason.id}>
<Table.Cell>
<TextInput className="w-full" data-ui-id={`ui.projects.lostReasons.row.${reason.id}.nameInput`}>
<TextInput.Input value={draft.name} onChange={(event) => setDraft((current) => ({ ...current, name: event.target.value }))} />
</TextInput>
</Table.Cell>
<Table.Cell>
<div className="flex w-full flex-col gap-2">
<TextInput className="w-full">
<TextInput.Input
placeholder={t("projects.lostReasonsAdmin.fields.description")}
value={draft.beschreibung}
onChange={(event) => setDraft((current) => ({ ...current, beschreibung: event.target.value }))}
data-ui-id={`ui.projects.lostReasons.row.${reason.id}.beschreibungInput`}
/>
</TextInput>
<TextInput className="w-full">
<TextInput.Input
placeholder={t("projects.lostReasonsAdmin.fields.category")}
value={draft.kategorie}
onChange={(event) => setDraft((current) => ({ ...current, kategorie: event.target.value }))}
data-ui-id={`ui.projects.lostReasons.row.${reason.id}.kategorieInput`}
/>
</TextInput>
</div>
</Table.Cell>
<Table.Cell />
<Table.Cell />
<Table.Cell />
<Table.Cell>
<div className="flex w-full items-center justify-end gap-2">
<Button variant="tertiary" size="small" onClick={onDone} data-ui-id={`ui.projects.lostReasons.row.${reason.id}.cancel`}>
{t("projects.actions.cancel")}
</Button>
<Button
variant="neutral"
size="small"
disabled={!draft.name.trim()}
loading={submitting}
onClick={() => {
submit("upsertLostReason", {
reasonId: reason.id,
name: draft.name.trim(),
beschreibung: draft.beschreibung.trim(),
kategorie: draft.kategorie.trim(),
position: String(reason.position),
});
onDone();
}}
data-ui-id={`ui.projects.lostReasons.row.${reason.id}.save`}
>
{t("projects.actions.save")}
</Button>
</div>
</Table.Cell>
</Table.Row>
);
}
export default LostReasonAdminPage;
@@ -0,0 +1,245 @@
// WF-P8 S07 — PipelineAdminPage unit test. Fixture via the real
// buildPipelineAdminVM; interactions asserted on the injected onSubmit.
// The column config moved to S04 (BoardSettingsPage.test.tsx); what is left
// here is the board table, its filters and the create dialog incl. S07a.
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildPipelineAdminVM, type PipelineAdminData, type PipelineAdminItem } from "@hivegrid/view-models";
import { filterBoards, PipelineAdminPage } from "./PipelineAdminPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }),
}));
// Radix selects are not interactable in jsdom; swap ~/ui Select for a native
// one so the create dialog's type field can be driven and asserted.
vi.mock("~/ui/components/Select", () => {
const Select = ({ value, onValueChange, label, error, errorText, children, ...rest }: any) => (
<div data-ui-id={rest["data-ui-id"]}>
<select
aria-label={typeof label === "string" ? label : "select"}
value={value ?? ""}
onChange={(e: any) => onValueChange?.(e.target.value)}
data-ui-id={rest["data-ui-id"] ? `${rest["data-ui-id"]}.native` : undefined}
>
<option value="" />
{children}
</select>
{error && errorText ? <span data-ui-id={rest["data-ui-id"] ? `${rest["data-ui-id"]}.errorText` : undefined}>{errorText}</span> : null}
</div>
);
Select.Item = ({ value, children }: any) => <option value={value}>{children}</option>;
return { Select };
});
// Radix dropdowns neither open nor provide their menu context in jsdom, so the
// row actions would be unreachable. Both the SubframeCore wrapper and the ~/ui
// menu are swapped for plain passthroughs; the entries stay real buttons.
vi.mock("@subframe/core", async () => {
const actual = await vi.importActual<Record<string, unknown>>("@subframe/core");
const Pass = ({ children }: { children?: React.ReactNode }) => <>{children}</>;
return { ...actual, DropdownMenu: { Root: Pass, Trigger: Pass, Portal: Pass, Content: Pass, Item: Pass } };
});
// Same reason for the facet menus of the filter bar.
vi.mock("~/ui/components/DropdownMenuMultiSelect", () => {
const DropdownMenuMultiSelect = ({ children }: { children?: React.ReactNode }) => <div>{children}</div>;
DropdownMenuMultiSelect.DropdownItem = ({ children, onClick, selected, ...rest }: any) => (
<button type="button" onClick={onClick} aria-pressed={Boolean(selected)} data-ui-id={rest["data-ui-id"]}>
{children}
</button>
);
DropdownMenuMultiSelect.DropdownCustomItem = ({ children }: any) => <div>{children}</div>;
DropdownMenuMultiSelect.DropdownUserItem = ({ title }: any) => <div>{title}</div>;
DropdownMenuMultiSelect.DropdownDivider = () => <hr />;
return { DropdownMenuMultiSelect };
});
vi.mock("~/ui/components/DropdownMenu", () => {
const DropdownMenu = ({ children }: { children?: React.ReactNode }) => <div>{children}</div>;
DropdownMenu.DropdownItem = ({ children, onSelect, ...rest }: any) => (
<button type="button" onClick={() => onSelect?.()} data-ui-id={rest["data-ui-id"]}>
{children}
</button>
);
DropdownMenu.DropdownDivider = () => <hr />;
return { DropdownMenu };
});
const byUiId = (id: string) => document.querySelector(`[data-ui-id='${id}']`) as HTMLElement;
type FixturePipeline = Parameters<typeof buildPipelineAdminVM>[0]["pipelines"][number];
const salesBoard: FixturePipeline = {
id: "pl1",
name: "Sales",
typHint: "sales",
isDefault: true,
projectCount: 11,
updatedAtIso: "2026-07-12T06:12:00.000Z",
stages: [
{ id: "s1", name: "Neu", stageKind: "offen", winProbability: 10, color: "#000", position: 10, projectCount: 4 },
{ id: "s2", name: "Gewonnen", stageKind: "gewonnen", winProbability: 100, color: "#0a0", position: 20, projectCount: 5 },
{ id: "s3", name: "Verloren", stageKind: "verloren", winProbability: 0, color: "#a00", position: 30, projectCount: 2 },
],
accessRules: [],
fieldConfigs: [],
};
// No won/lost stage -> the VM calls this a draft; one deny rule -> restricted.
const draftBoard: FixturePipeline = {
id: "pl2",
name: "Eigenes Board",
typHint: "custom",
isDefault: false,
projectCount: 0,
stages: [{ id: "s9", name: "Neu", stageKind: "offen", winProbability: 0, color: "#666", position: 10, projectCount: 0 }],
accessRules: [{ id: "a1", principalType: "group", principalId: "grp-montage", kannSehen: false, kannBearbeiten: false }],
fieldConfigs: [],
};
function adminData(pipelines: FixturePipeline[] = [salesBoard, draftBoard]): PipelineAdminData {
const vm = buildPipelineAdminVM({ canAdmin: true, pipelines });
if (vm.status !== "ready") throw new Error("fixture not ready");
return vm.data;
}
const baseProps = {
lostReasonsHref: "/acme/admin/pipelines/lost-reasons",
settingsHref: (id: string) => `/acme/admin/pipelines/${id}`,
};
function renderPage(data = adminData()) {
const onSubmit = vi.fn();
render(<PipelineAdminPage {...baseProps} data={data} submitting={false} actions={{ onSubmit }} />);
return onSubmit;
}
describe("PipelineAdminPage", () => {
it("points the header settings button at the default board", () => {
renderPage();
// The export's button names no board; the default one is the only sensible
// target, and it is the board the footer line already calls out.
expect(byUiId("ui.projects.admin.headerSettings").getAttribute("href")).toBe("/acme/admin/pipelines/pl1");
});
it("falls back to the first board when none is marked as the default", () => {
renderPage(adminData([{ ...draftBoard, isDefault: false }]));
expect(byUiId("ui.projects.admin.headerSettings").getAttribute("href")).toBe("/acme/admin/pipelines/pl2");
});
it("renders one row per board with counts, access and status", () => {
renderPage();
expect(byUiId("ui.projects.admin.list")).toBeTruthy();
expect(screen.getByText("Sales")).toBeTruthy();
expect(byUiId("ui.projects.admin.row.pl1.projects").textContent).toBe("11");
// getAllByText: the mocked native filter selects render the same labels as
// <option> text, so a row badge is never the only match.
// A board without a won and a lost column cannot complete a project.
expect(screen.getAllByText("projects.boardSettings.status.draft").length).toBeGreaterThan(0);
expect(screen.getAllByText("projects.admin.accessScope.restricted").length).toBeGreaterThan(0);
expect(screen.getAllByText("projects.admin.accessScope.everyone").length).toBeGreaterThan(0);
});
it("links every row to its own S04 settings page", () => {
renderPage();
expect(byUiId("ui.projects.admin.row.pl1.open").getAttribute("href")).toBe("/acme/admin/pipelines/pl1");
expect(byUiId("ui.projects.admin.row.pl1.settings").getAttribute("href")).toBe("/acme/admin/pipelines/pl1");
});
it("names the default board in the footer line", () => {
renderPage();
expect(byUiId("ui.projects.admin.footer").textContent).toContain("projects.admin.footerLine");
});
it("shows an empty state when no board is left", () => {
renderPage(adminData([]));
expect(byUiId("ui.projects.admin.empty")).toBeTruthy();
expect(byUiId("ui.projects.admin.list")).toBeNull();
});
it("archives and duplicates a board from the row menu", () => {
const onSubmit = renderPage();
fireEvent.click(byUiId("ui.projects.admin.row.pl1.archive"));
expect(onSubmit).toHaveBeenCalledWith("archivePipeline", { pipelineId: "pl1" });
fireEvent.click(byUiId("ui.projects.admin.row.pl1.duplicate"));
expect(onSubmit).toHaveBeenCalledWith("duplicatePipeline", expect.objectContaining({ pipelineId: "pl1" }));
});
it("filters by search, type, status, access and rules", () => {
const boards: readonly PipelineAdminItem[] = adminData().pipelines;
const names = (result: readonly { name: string }[]) => result.map((row) => row.name);
const all = { search: "", typ: new Set<string>(), status: new Set<string>(), access: new Set<string>(), rules: new Set<string>() };
expect(names(filterBoards(boards, all))).toEqual(["Sales", "Eigenes Board"]);
expect(names(filterBoards(boards, { ...all, search: "eigen" }))).toEqual(["Eigenes Board"]);
expect(names(filterBoards(boards, { ...all, typ: new Set(["sales"]) }))).toEqual(["Sales"]);
expect(names(filterBoards(boards, { ...all, status: new Set(["draft"]) }))).toEqual(["Eigenes Board"]);
expect(names(filterBoards(boards, { ...all, access: new Set(["everyone"]) }))).toEqual(["Sales"]);
// "Regeln" asks whether a board carries access rules at all, which is not
// the same question as the access scope (that one counts denying rules).
expect(names(filterBoards(boards, { ...all, rules: new Set(["withRules"]) }))).toEqual(["Eigenes Board"]);
expect(names(filterBoards(boards, { ...all, rules: new Set(["withoutRules"]) }))).toEqual(["Sales"]);
// Several values inside one facet are OR-ed, not AND-ed.
expect(names(filterBoards(boards, { ...all, status: new Set(["active", "draft"]) }))).toEqual(["Sales", "Eigenes Board"]);
expect(filterBoards(boards, { ...all, search: "gibtsnicht" })).toEqual([]);
});
it("creates a board with default columns once name and type are valid", () => {
const onSubmit = renderPage();
fireEvent.click(byUiId("ui.projects.admin.newPipeline.open"));
fireEvent.change(byUiId("ui.projects.admin.newPipeline.name"), { target: { value: "Service" } });
fireEvent.change(byUiId("ui.projects.admin.newPipeline.typ.native"), { target: { value: "custom" } });
fireEvent.click(byUiId("ui.projects.admin.newPipeline.create"));
expect(onSubmit).toHaveBeenCalledWith("createPipeline", expect.objectContaining({ name: "Service", typHint: "custom" }));
expect(byUiId("ui.projects.admin.newPipeline.error")).toBeNull();
});
it("shows the S07a error state when no board type is chosen", () => {
const onSubmit = renderPage();
fireEvent.click(byUiId("ui.projects.admin.newPipeline.open"));
fireEvent.change(byUiId("ui.projects.admin.newPipeline.name"), { target: { value: "Service" } });
fireEvent.click(byUiId("ui.projects.admin.newPipeline.create"));
expect(onSubmit).not.toHaveBeenCalled();
expect(byUiId("ui.projects.admin.newPipeline.error")).toBeTruthy();
expect(screen.getByText("projects.admin.createDialog.createError")).toBeTruthy();
expect(screen.getByText("projects.admin.createDialog.typRequired")).toBeTruthy();
});
it("flags a duplicate board name against the loaded board list", () => {
const onSubmit = renderPage();
fireEvent.click(byUiId("ui.projects.admin.newPipeline.open"));
fireEvent.change(byUiId("ui.projects.admin.newPipeline.name"), { target: { value: " sales " } });
fireEvent.change(byUiId("ui.projects.admin.newPipeline.typ.native"), { target: { value: "sales" } });
fireEvent.click(byUiId("ui.projects.admin.newPipeline.create"));
expect(onSubmit).not.toHaveBeenCalled();
expect(screen.getByText("projects.admin.createDialog.nameDuplicate")).toBeTruthy();
// Correcting the name clears the field message.
fireEvent.change(byUiId("ui.projects.admin.newPipeline.name"), { target: { value: "Service" } });
expect(screen.queryByText("projects.admin.createDialog.nameDuplicate")).toBeNull();
});
it("maps a server-side duplicate error onto the name field and keeps the dialog open", () => {
const onSubmit = vi.fn();
const props = { ...baseProps, data: adminData(), actions: { onSubmit } };
const view = render(<PipelineAdminPage {...props} submitting={false} errorKey={null} />);
fireEvent.click(byUiId("ui.projects.admin.newPipeline.open"));
fireEvent.change(byUiId("ui.projects.admin.newPipeline.name"), { target: { value: "Service" } });
fireEvent.change(byUiId("ui.projects.admin.newPipeline.typ.native"), { target: { value: "custom" } });
fireEvent.click(byUiId("ui.projects.admin.newPipeline.create"));
expect(onSubmit).toHaveBeenCalled();
// Simulate the POST round-trip ending in a duplicate-name server error.
view.rerender(<PipelineAdminPage {...props} submitting errorKey={null} />);
view.rerender(<PipelineAdminPage {...props} submitting={false} errorKey="projects.error.pipelineNameDuplicate" />);
expect(byUiId("ui.projects.admin.newPipeline.error")).toBeTruthy();
expect(screen.getByText("projects.admin.createDialog.nameDuplicate")).toBeTruthy();
});
it("renders the info box about configuring columns and access afterwards", () => {
renderPage();
fireEvent.click(byUiId("ui.projects.admin.newPipeline.open"));
expect(byUiId("ui.projects.admin.newPipeline.info")).toBeTruthy();
expect(screen.getByText("projects.admin.createDialog.infoTitle")).toBeTruthy();
expect(screen.getByText("projects.admin.createDialog.infoBody")).toBeTruthy();
});
});
@@ -0,0 +1,564 @@
// WF-P8 S07 "Boards-Übersicht" — rebuilt against Davids Subframe export of
// 2026-07-28 (page 5190e285-e92f-4ad2-9f3d-2a2f511fe695), including the create
// dialog variants S07-D (50219cd7-…) and S07a (a0139eb6-…).
//
// The screen used to be a stack of accordion cards that configured every board
// inline. David split that: this page lists the boards and each row links to
// S04 (BoardSettingsPage) for the configuration. Pure/presentational — renders
// the server-built PipelineAdminData and turns create/duplicate/archive into a
// typed onSubmit(intent, fields) the route POSTs. No useLoaderData/useFetcher.
//
// Deliberate deltas against the export:
// * The "Zugriff" column reports the shape of the restriction, not a team
// name. PipelineAccess stores a role/group/user id, and resolving those to
// display names is a lookup this table does not do.
// * The export's header "Board-Einstellungen" button names no board. Settings
// are per board, so it opens the default one (the board the footer line
// names) and hides itself when the tenant has no board at all.
// * S07-D and S07a are the same dialog in two states, so they are one
// component here: the error state is what it renders once a create attempt
// came back with field errors.
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { AppLink } from "~/components/app/AppLink";
import type { PipelineAdminData, PipelineAdminItem, PipelineTypHint } from "@hivegrid/view-models";
import {
FeatherActivity,
FeatherChevronRight,
FeatherFilter,
FeatherColumns,
FeatherCopy,
FeatherFolderKanban,
FeatherGlobe,
FeatherKanbanSquare,
FeatherLayers,
FeatherLock,
FeatherMoreHorizontal,
FeatherPlus,
FeatherSettings,
FeatherShield,
FeatherTag,
FeatherThumbsDown,
FeatherTrash,
FeatherUsers,
FeatherX,
} from "@subframe/core";
import * as SubframeCore from "@subframe/core";
import { FacetFilterBar } from "../shared/FacetFilterBar";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
import { BOARD_TYP_ICON, BOARD_TYP_TONE } from "./boardTypeVisuals";
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 { DropdownMenu } from "~/ui/components/DropdownMenu";
import { EmptyState } from "~/ui/components/EmptyState";
import { IconButton } from "~/ui/components/IconButton";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
import { Select } from "~/ui/components/Select";
import { Table } from "~/ui/components/Table";
import { Tag_Label } from "~/ui/components/Tag_Label";
import { TextInput } from "~/ui/components/TextInput";
import { useLocaleFormatters } from "~/locale/format";
export type PipelineAdminSubmit = (intent: string, fields: Record<string, string>) => void;
export type PipelineAdminPageProps = {
data: PipelineAdminData;
submitting: boolean;
errorKey?: string | null;
lostReasonsHref: string;
/** S04 board settings of one board. */
settingsHref: (pipelineId: string) => string;
actions: { onSubmit: PipelineAdminSubmit };
};
const DEFAULT_STAGES = JSON.stringify([
{ name: "Neu", stageKind: "offen" },
{ name: "Gewonnen", stageKind: "gewonnen" },
{ name: "Verloren", stageKind: "verloren" },
]);
const TYP_OPTIONS = ["sales", "auftrag", "custom"] as const;
export type BoardTypFilter = PipelineTypHint;
export type BoardStatusFilter = "active" | "draft";
export type BoardAccessFilter = "everyone" | "restricted";
export type BoardRulesFilter = "withRules" | "withoutRules";
export type BoardFilters = {
readonly search: string;
/** Empty set = facet not filtered. Several values in one facet are OR-ed. */
readonly typ: ReadonlySet<string>;
readonly status: ReadonlySet<string>;
readonly access: ReadonlySet<string>;
readonly rules: ReadonlySet<string>;
};
const STATUS_OPTIONS: readonly BoardStatusFilter[] = ["active", "draft"];
const ACCESS_OPTIONS: readonly BoardAccessFilter[] = ["everyone", "restricted"];
const RULES_OPTIONS: readonly BoardRulesFilter[] = ["withRules", "withoutRules"];
const EMPTY_SELECTION: ReadonlySet<string> = new Set();
/** Adds or removes one value of a facet. */
function toggleValue(current: ReadonlySet<string>, value: string): ReadonlySet<string> {
const next = new Set(current);
if (!next.delete(value)) next.add(value);
return next;
}
/**
* Client-side board filter, exported so the rule can be tested without driving
* the Radix menus. The list is a handful of rows, so filtering here rather
* than round-tripping to the server is the cheaper answer.
*/
export function filterBoards(boards: readonly PipelineAdminItem[], filters: BoardFilters): readonly PipelineAdminItem[] {
const query = filters.search.trim().toLowerCase();
return boards.filter((board) => {
if (filters.typ.size > 0 && !filters.typ.has(board.typHint)) return false;
if (filters.status.size > 0 && !filters.status.has(board.statusKey)) return false;
if (filters.access.size > 0 && !filters.access.has(board.access.scope)) return false;
// "Regeln" is not the same question as "Zugriff": the access scope counts
// denying rules only, so a board configured purely with granting rules
// reads as "everyone" while still carrying rules.
if (filters.rules.size > 0 && !filters.rules.has(board.accessRules.length > 0 ? "withRules" : "withoutRules")) return false;
if (query && !board.name.toLowerCase().includes(query)) return false;
return true;
});
}
/** Field errors of the create dialog hold i18n keys so the render stays dumb. */
type NewBoardErrors = { nameKey?: string; typKey?: string };
export function PipelineAdminPage(props: PipelineAdminPageProps) {
const { t } = useTranslation();
const submit = props.actions.onSubmit;
const boards = props.data.pipelines;
const [filters, setFilters] = useState<BoardFilters>({
search: "",
typ: EMPTY_SELECTION,
status: EMPTY_SELECTION,
access: EMPTY_SELECTION,
rules: EMPTY_SELECTION,
});
const visible = useMemo(() => filterBoards(boards, filters), [boards, filters]);
const defaultBoard = boards.find((board) => board.isDefault) ?? null;
const headerSettingsBoard = defaultBoard ?? boards[0] ?? null;
const [newBoard, setNewBoard] = useState({ name: "", typHint: "" });
const [dialogOpen, setDialogOpen] = useState(false);
const [createErrors, setCreateErrors] = useState<NewBoardErrors>({});
const [createFailed, setCreateFailed] = useState(false);
// "waiting" = submit fired, POST not started yet; "inflight" = POST running.
const [createPhase, setCreatePhase] = useState<"idle" | "waiting" | "inflight">("idle");
function resetDialog() {
setNewBoard({ name: "", typHint: "" });
setCreateErrors({});
setCreateFailed(false);
setCreatePhase("idle");
}
// S07a error state: keep the dialog open until the create round-trip
// succeeded. A server error re-shows the alert and maps the duplicate-name
// key onto the name field; success closes and resets the dialog.
useEffect(() => {
if (createPhase === "waiting" && props.submitting) {
setCreatePhase("inflight");
return;
}
if (createPhase === "inflight" && !props.submitting) {
setCreatePhase("idle");
if (props.errorKey) {
setCreateFailed(true);
if (props.errorKey === "projects.error.pipelineNameDuplicate") {
setCreateErrors({ nameKey: "projects.admin.createDialog.nameDuplicate" });
}
} else {
setDialogOpen(false);
resetDialog();
}
}
}, [createPhase, props.submitting, props.errorKey]);
function handleCreate() {
const name = newBoard.name.trim();
const nextErrors: NewBoardErrors = {};
if (boards.some((board) => board.name.trim().toLowerCase() === name.toLowerCase())) {
nextErrors.nameKey = "projects.admin.createDialog.nameDuplicate";
}
if (!newBoard.typHint) {
nextErrors.typKey = "projects.admin.createDialog.typRequired";
}
if (nextErrors.nameKey || nextErrors.typKey) {
setCreateErrors(nextErrors);
setCreateFailed(true);
return;
}
setCreateErrors({});
setCreateFailed(false);
setCreatePhase("waiting");
submit("createPipeline", { name, typHint: newBoard.typHint, stages: DEFAULT_STAGES });
}
return (
<PageShell uiId="ui.projects.admin" className="bg-surface-neutral-primary">
<PageHeader
icon={<FeatherColumns className={PAGE_HEADER_ICON_CLASS} />}
title={t("projects.admin.title")}
subtitle={t("projects.admin.subtitle")}
actions={
<>
<AppLink href={props.lostReasonsHref} className="no-underline">
<Button variant="tertiary" size="small" icon={<FeatherThumbsDown />}>
{t("projects.lostReasonsAdmin.title")}
</Button>
</AppLink>
{/* The export draws this button without saying which board it
configures. It opens the default board — the one the footer line
names — and falls back to the first board when none is marked.
With no boards at all there is nothing to configure. */}
{headerSettingsBoard ? (
<AppLink href={props.settingsHref(headerSettingsBoard.id)} className="no-underline" data-ui-id="ui.projects.admin.headerSettings">
<Button variant="tertiary" size="small" icon={<FeatherSettings />}>
{t("projects.board.contextMenu.settings")}
</Button>
</AppLink>
) : null}
<Button size="small" icon={<FeatherPlus />} onClick={() => setDialogOpen(true)} data-ui-id="ui.projects.admin.newPipeline.open">
{t("projects.admin.newPipeline")}
</Button>
</>
}
/>
<FacetFilterBar
uiId="ui.projects.admin.filter"
facets={[
{
key: "typ",
label: t("projects.admin.filter.typ"),
icon: <FeatherFilter />,
selected: filters.typ,
options: TYP_OPTIONS.map((typ) => ({ value: typ, label: t(`projects.typHint.${typ}`), tone: BOARD_TYP_TONE[typ] })),
},
{
key: "status",
label: t("projects.admin.filter.status"),
icon: <FeatherActivity />,
tone: "sky-subtle",
selected: filters.status,
options: STATUS_OPTIONS.map((status) => ({ value: status, label: t(`projects.boardSettings.status.${status}`) })),
},
{
key: "access",
label: t("projects.admin.filter.access"),
icon: <FeatherLock />,
tone: "blue-subtle",
selected: filters.access,
options: ACCESS_OPTIONS.map((scope) => ({ value: scope, label: t(`projects.admin.accessScope.${scope}`) })),
},
{
key: "rules",
label: t("projects.admin.filter.rules"),
icon: <FeatherShield />,
tone: "sand-subtle",
selected: filters.rules,
options: RULES_OPTIONS.map((rules) => ({ value: rules, label: t(`projects.admin.rulesScope.${rules}`) })),
},
]}
onToggle={(facetKey, value) =>
setFilters((current) => ({
...current,
[facetKey]: toggleValue(current[facetKey as "typ" | "status" | "access" | "rules"], value),
}))
}
search={filters.search}
onSearchChange={(value) => setFilters((current) => ({ ...current, search: value }))}
searchPlaceholder={t("projects.fields.search")}
onReset={() =>
setFilters({ search: "", typ: EMPTY_SELECTION, status: EMPTY_SELECTION, access: EMPTY_SELECTION, rules: EMPTY_SELECTION })
}
labels={{ reset: t("projects.board.filter.reset"), removeChip: t("projects.board.filter.removeChip") }}
trailing={
<span
className="whitespace-nowrap text-body-extra-small-medium-0 font-body-extra-small-medium-0 text-text-neutral-tertiary"
data-ui-id="ui.projects.admin.count"
>
{t("projects.admin.boardCount", { count: visible.length })}
</span>
}
/>
<PageBody>
{props.errorKey ? (
<Alert variant="error" notDismissible title={t(props.errorKey)} data-ui-id="ui.projects.admin.error" />
) : null}
{visible.length === 0 ? (
<EmptyState title={t("projects.admin.empty")} data-ui-id="ui.projects.admin.empty" />
) : (
<>
<div className="flex w-full flex-col items-start overflow-hidden rounded-lg border border-solid border-border-default shadow-sm overflow-x-auto">
<Table
className="border-none min-w-[880px]"
data-ui-id="ui.projects.admin.list"
header={
<Table.HeaderRow className="bg-surface-neutral-tertiary">
<Table.HeaderCell icon={<FeatherColumns />}>{t("projects.admin.columns.board")}</Table.HeaderCell>
<Table.HeaderCell icon={<FeatherTag />}>{t("projects.admin.columns.typ")}</Table.HeaderCell>
<Table.HeaderCell icon={<FeatherLayers />}>{t("projects.admin.columns.stages")}</Table.HeaderCell>
<Table.HeaderCell icon={<FeatherFolderKanban />}>{t("projects.admin.columns.projects")}</Table.HeaderCell>
<Table.HeaderCell icon={<FeatherUsers />}>{t("projects.admin.columns.access")}</Table.HeaderCell>
<Table.HeaderCell icon={<FeatherActivity />}>{t("projects.admin.columns.status")}</Table.HeaderCell>
{/* "Aktionen" carries no icon in the export. */}
<Table.HeaderCell>{t("projects.admin.columns.actions")}</Table.HeaderCell>
</Table.HeaderRow>
}
emptyText={t("projects.admin.empty")}
>
{visible.map((board) => (
<BoardRow key={board.id} board={board} settingsHref={props.settingsHref(board.id)} submit={submit} />
))}
</Table>
</div>
<span
className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary"
data-ui-id="ui.projects.admin.footer"
>
{defaultBoard
? t("projects.admin.footerLine", { shown: visible.length, total: boards.length, name: defaultBoard.name })
: t("projects.admin.footerLineNoDefault", { shown: visible.length, total: boards.length })}
</span>
</>
)}
</PageBody>
<Dialog
open={dialogOpen}
onOpenChange={(open) => {
setDialogOpen(open);
if (!open) resetDialog();
}}
>
{/* One flat card, as in the export: no tinted header or footer band —
the dialog is short enough that the tints only cut it into stripes. */}
<Dialog.Content className="w-[448px] max-w-[92vw] p-0" data-ui-id="ui.projects.admin.newPipeline">
<div className="flex w-full flex-col gap-5 px-4 py-4">
<div className="flex w-full items-start justify-between gap-3">
<div className="flex items-start gap-3">
<IconWithBackground variant="information" size="large" round icon={<FeatherKanbanSquare />} />
<div className="flex min-w-0 flex-col items-start gap-1">
{/* The trigger says "Neues Board", the dialog names the act. */}
<span className="text-heading- font-heading- text-text-neutral-primary">{t("projects.admin.createDialog.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("projects.admin.createDialog.subtitle")}
</span>
</div>
</div>
<IconButton
type="button"
variant="ghost"
size="small"
icon={<FeatherX />}
aria-label={t("projects.actions.cancel")}
onClick={() => {
setDialogOpen(false);
resetDialog();
}}
/>
</div>
<div className="flex w-full flex-col gap-4">
{createFailed ? (
<Alert
variant="error"
notDismissible
title={t("projects.admin.createDialog.createError")}
data-ui-id="ui.projects.admin.newPipeline.error"
/>
) : null}
<TextInput
className="h-auto w-full flex-none"
fillContainer
label={t("projects.admin.createDialog.nameLabel")}
showLabel
error={Boolean(createErrors.nameKey)}
message={createErrors.nameKey ? t(createErrors.nameKey) : undefined}
>
<TextInput.Input
autoFocus
value={newBoard.name}
placeholder={t("projects.admin.createDialog.namePlaceholder")}
onChange={(e) => {
setNewBoard((s) => ({ ...s, name: e.target.value }));
setCreateErrors((s) => ({ ...s, nameKey: undefined }));
}}
data-ui-id="ui.projects.admin.newPipeline.name"
/>
</TextInput>
<Select
className="h-auto w-full flex-none"
variant="outline"
icon={<FeatherLayers />}
label={t("projects.admin.createDialog.typLabel")}
showLabel
placeholder={t("projects.admin.createDialog.typPlaceholder")}
error={Boolean(createErrors.typKey)}
errorText={createErrors.typKey ? t(createErrors.typKey) : undefined}
value={newBoard.typHint}
onValueChange={(v) => {
setNewBoard((s) => ({ ...s, typHint: v }));
setCreateErrors((s) => ({ ...s, typKey: undefined }));
}}
data-ui-id="ui.projects.admin.newPipeline.typ"
>
{TYP_OPTIONS.map((typ) => (
<Select.Item key={typ} value={typ}>{t(`projects.typHint.${typ}`)}</Select.Item>
))}
</Select>
<Alert
variant="information"
notDismissible
title={t("projects.admin.createDialog.infoTitle")}
description={t("projects.admin.createDialog.infoBody")}
data-ui-id="ui.projects.admin.newPipeline.info"
/>
</div>
<div className="flex w-full items-center justify-end gap-2 mobile:flex-col-reverse mobile:items-stretch">
<Button
type="button"
className="mobile:w-full"
variant="tertiary"
icon={<FeatherX />}
onClick={() => {
setDialogOpen(false);
resetDialog();
}}
>
{t("projects.actions.cancel")}
</Button>
<Button
className="mobile:w-full"
icon={<FeatherPlus />}
disabled={!newBoard.name.trim()}
loading={props.submitting}
onClick={handleCreate}
data-ui-id="ui.projects.admin.newPipeline.create"
>
{t("projects.actions.createPipeline")}
</Button>
</div>
</div>
</Dialog.Content>
</Dialog>
</PageShell>
);
}
function BoardRow({ board, settingsHref, submit }: { board: PipelineAdminItem; settingsHref: string; submit: PipelineAdminSubmit }) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const idBase = `ui.projects.admin.row.${board.id}`;
return (
<Table.Row data-row-id={board.id} data-ui-id={idBase}>
<Table.Cell>
<div className="flex items-center gap-3">
<div className="flex h-8 w-8 flex-none items-center justify-center rounded-md border border-solid border-border-default bg-surface-neutral-tertiary text-icon-neutral-tertiary">
{BOARD_TYP_ICON[board.typHint]}
</div>
{/* The board name is the one link in the row, so it is drawn as one.
No badge next to it — which board is the default is what the footer
line under the table says. */}
<AppLink href={settingsHref} className="flex items-center gap-1 no-underline hover:underline" data-ui-id={`${idBase}.open`}>
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-feedback-link-default">{board.name}</span>
<FeatherChevronRight aria-hidden className="text-body-small-regular-0 text-text-feedback-link-default" />
</AppLink>
</div>
</Table.Cell>
<Table.Cell>
<Tag_Label tone={BOARD_TYP_TONE[board.typHint]} noAction size="small">
{t(board.typHintLabelKey)}
</Tag_Label>
</Table.Cell>
<Table.Cell>
<span className="whitespace-nowrap text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("projects.boards.stagesValue", { formatted: formatters.number(board.stageCount) })}
</span>
</Table.Cell>
<Table.Cell>
<span
className={`whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 ${
board.projectCount === 0 ? "text-text-neutral-tertiary" : "text-text-neutral-primary"
}`}
data-ui-id={`${idBase}.projects`}
>
{board.projectCount}
</span>
</Table.Cell>
<Table.Cell>
<div className="flex items-center gap-1.5">
{board.access.scope === "everyone" ? (
<FeatherGlobe aria-hidden className="text-body-small-regular-0 text-icon-neutral-tertiary" />
) : (
<FeatherLock aria-hidden className="text-body-small-regular-0 text-icon-neutral-subtle" />
)}
<span className="whitespace-nowrap text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
{t(board.access.labelKey)}
</span>
</div>
</Table.Cell>
<Table.Cell>
<BadgeFeedback farbe={board.statusKey === "active" ? "subtle-positive" : "subtle-neutral"} size="small">
{t(`projects.boardSettings.status.${board.statusKey}`)}
</BadgeFeedback>
</Table.Cell>
{/* Export pins the action column to the right edge. */}
<Table.Cell variant="align-right">
<div className="flex w-full items-center justify-end gap-1">
<AppLink href={settingsHref} className="no-underline" data-ui-id={`${idBase}.settings`}>
<Button variant="tertiary" size="small" icon={<FeatherSettings />}>
{t("projects.admin.openSettings")}
</Button>
</AppLink>
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<IconButton
variant="ghost"
size="small"
square
icon={<FeatherMoreHorizontal />}
aria-label={t("projects.fields.actions")}
data-ui-id={`${idBase}.menu`}
/>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content align="end" sideOffset={4} asChild>
<DropdownMenu>
<DropdownMenu.DropdownItem
icon={<FeatherCopy />}
onSelect={() => submit("duplicatePipeline", { pipelineId: board.id, name: t("projects.admin.copyName", { name: board.name }) })}
data-ui-id={`${idBase}.duplicate`}
>
{t("projects.actions.duplicatePipeline")}
</DropdownMenu.DropdownItem>
<DropdownMenu.DropdownDivider />
<DropdownMenu.DropdownItem
icon={<FeatherTrash />}
onSelect={() => submit("archivePipeline", { pipelineId: board.id })}
data-ui-id={`${idBase}.archive`}
>
{t("projects.actions.archivePipeline")}
</DropdownMenu.DropdownItem>
</DropdownMenu>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
</div>
</Table.Cell>
</Table.Row>
);
}
export default PipelineAdminPage;
@@ -0,0 +1,228 @@
// WF-P8 S05 — the field-type picker and the options editor of the inspector.
// Fixture built through the real buildPipelineFieldTemplateVM; interactions are
// asserted on the injected onSubmit. i18n mocked so `t` echoes the key.
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildPipelineFieldTemplateVM, type BuildPipelineFieldTemplateVMInput } from "@hivegrid/view-models";
import { PipelineFieldTemplatePage } from "./PipelineFieldTemplatePage";
const byUiId = (id: string) => document.querySelector(`[data-ui-id='${id}']`) as HTMLElement;
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }),
}));
function vmInput(over: Partial<BuildPipelineFieldTemplateVMInput> = {}): BuildPipelineFieldTemplateVMInput {
return {
pipelineId: "pipe_1",
pipelineName: "Vertrieb",
groups: [{ id: "grp_base", name: "Grunddaten", reihenfolge: 0, istSystem: true }],
fields: [
{
id: "cfg_sys",
fieldKey: "projektname",
groupId: "grp_base",
sichtbar: true,
pflicht: true,
pflichtAbStageId: null,
hinweis: null,
istSystem: true,
gesperrt: false,
reihenfolge: 0,
},
{
id: "cfg_custom",
fieldKey: "status_aufmass",
groupId: "grp_base",
sichtbar: true,
pflicht: false,
pflichtAbStageId: null,
hinweis: null,
istSystem: false,
gesperrt: false,
reihenfolge: 1,
},
],
poolFields: [],
stages: [{ id: "stage_1", name: "Qualifiziert" }],
definitions: {
projektname: { label: "Projektname", datentyp: "text" },
status_aufmass: {
id: "def_1",
label: "Aufmaß-Status",
datentyp: "select",
optionen: { options: [{ value: "offen", label: "Offen", color: "#ff0000" }, { value: "erledigt", label: "Erledigt", color: null }] },
},
},
alwaysVisibleKeys: ["projektname"],
canEdit: true,
...over,
};
}
function renderPage(over: Partial<BuildPipelineFieldTemplateVMInput> = {}) {
const onSubmit = vi.fn();
render(<PipelineFieldTemplatePage data={buildPipelineFieldTemplateVM(vmInput(over))} backHref="/acme/admin/pipelines" submitting={false} actions={{ onSubmit }} />);
return onSubmit;
}
function selectField(id: string) {
fireEvent.click(byUiId(`ui.projects.fieldTemplate.field.${id}.select`));
}
describe("PipelineFieldTemplatePage — type and options", () => {
it("offers the type picker for a custom field", () => {
renderPage();
selectField("cfg_custom");
expect(byUiId("ui.projects.fieldTemplate.inspector.typeEditor")).toBeTruthy();
expect(byUiId("ui.projects.fieldTemplate.inspector.type")).toBeTruthy();
});
it("keeps a system field's type read-only, because it has no definition to change", () => {
renderPage();
selectField("cfg_sys");
expect(byUiId("ui.projects.fieldTemplate.inspector.typeEditor")).toBeNull();
expect(screen.getAllByText("projects.fieldTemplate.type.text").length).toBeGreaterThan(0);
});
it("shows the stored options in their stored order", () => {
renderPage();
selectField("cfg_custom");
expect((byUiId("ui.projects.fieldTemplate.inspector.option.0.label") as HTMLInputElement).value).toBe("Offen");
expect((byUiId("ui.projects.fieldTemplate.inspector.option.1.label") as HTMLInputElement).value).toBe("Erledigt");
expect((byUiId("ui.projects.fieldTemplate.inspector.option.0.color") as HTMLInputElement).value).toBe("#ff0000");
});
it("saves reordered options with their labels and colours", () => {
const onSubmit = renderPage();
selectField("cfg_custom");
fireEvent.click(byUiId("ui.projects.fieldTemplate.inspector.option.1.up"));
fireEvent.click(byUiId("ui.projects.fieldTemplate.inspector.saveType"));
const [[intent, fields]] = onSubmit.mock.calls.slice(-1);
expect(intent).toBe("updateCustomField");
expect(fields.definitionId).toBe("def_1");
expect(JSON.parse(fields.optionen).map((option: { value: string }) => option.value)).toEqual(["erledigt", "offen"]);
});
it("adds an option whose value the server derives from the typed label", () => {
const onSubmit = renderPage();
selectField("cfg_custom");
fireEvent.click(byUiId("ui.projects.fieldTemplate.inspector.addOption"));
fireEvent.change(byUiId("ui.projects.fieldTemplate.inspector.option.2.label"), { target: { value: "Geplant" } });
fireEvent.click(byUiId("ui.projects.fieldTemplate.inspector.saveType"));
const [[, fields]] = onSubmit.mock.calls.slice(-1);
// The new entry travels with an empty value; the shared parser fills it from
// the label, so an existing option never has its value rewritten.
expect(JSON.parse(fields.optionen)[2]).toEqual({ value: "", label: "Geplant", color: null });
});
it("removes an option", () => {
const onSubmit = renderPage();
selectField("cfg_custom");
fireEvent.click(byUiId("ui.projects.fieldTemplate.inspector.option.0.remove"));
fireEvent.click(byUiId("ui.projects.fieldTemplate.inspector.saveType"));
const [[, fields]] = onSubmit.mock.calls.slice(-1);
expect(JSON.parse(fields.optionen).map((option: { value: string }) => option.value)).toEqual(["erledigt"]);
});
it("expresses Mehrfachauswahl as the multiselect type instead of a second flag", () => {
const onSubmit = renderPage();
selectField("cfg_custom");
fireEvent.click(byUiId("ui.projects.fieldTemplate.inspector.multiple"));
fireEvent.click(byUiId("ui.projects.fieldTemplate.inspector.saveType"));
const [[, fields]] = onSubmit.mock.calls.slice(-1);
expect(fields.datentyp).toBe("multiselect");
});
it("hides the options editor for a type that carries none", () => {
renderPage({
definitions: {
projektname: { label: "Projektname", datentyp: "text" },
status_aufmass: { id: "def_1", label: "Aufmaß-Status", datentyp: "zahl", optionen: null },
},
});
selectField("cfg_custom");
expect(byUiId("ui.projects.fieldTemplate.inspector.type")).toBeTruthy();
expect(byUiId("ui.projects.fieldTemplate.inspector.options")).toBeNull();
});
it("previews the template with its groups, order and required marker", () => {
renderPage();
const preview = byUiId("ui.projects.fieldTemplate.preview");
expect(preview.textContent).toContain("Grunddaten");
// Projektname is a required field, so the line carries the marker.
expect(byUiId("ui.projects.fieldTemplate.preview.field.cfg_sys").textContent).toContain("Projektname *");
expect(byUiId("ui.projects.fieldTemplate.preview.field.cfg_custom").textContent).toContain("Aufmaß-Status");
});
it("saves a renamed custom field together with its type", () => {
const onSubmit = renderPage();
selectField("cfg_custom");
fireEvent.change(byUiId("ui.projects.fieldTemplate.inspector.label"), { target: { value: "Aufmaß" } });
fireEvent.click(byUiId("ui.projects.fieldTemplate.inspector.saveType"));
const [[intent, fields]] = onSubmit.mock.calls.slice(-1);
expect(intent).toBe("updateCustomField");
expect(fields.label).toBe("Aufmaß");
});
it("keeps a system field's name read-only — there is no definition to rename", () => {
renderPage();
selectField("cfg_sys");
expect((byUiId("ui.projects.fieldTemplate.inspector.label") as HTMLInputElement).readOnly).toBe(true);
expect(byUiId("ui.projects.fieldTemplate.inspector.delete")).toBeNull();
});
it("names a system field that has no definition from its i18n key, not from its column key", () => {
// Without a definition the label used to fall through to "prioritaet".
renderPage({
fields: [
{ id: "cfg_prio", fieldKey: "prioritaet", groupId: "grp_base", sichtbar: true, pflicht: false, pflichtAbStageId: null, hinweis: null, istSystem: true, gesperrt: false, reihenfolge: 0 },
],
definitions: {},
});
expect(byUiId("ui.projects.fieldTemplate.field.cfg_prio").textContent).toContain("projects.fieldTemplate.systemField.prioritaet");
});
it("files a pool field into the group whose add row was used", () => {
const onSubmit = renderPage({
poolFields: [
{ id: "cfg_pool", fieldKey: "foerdernummer", groupId: null, sichtbar: true, pflicht: false, pflichtAbStageId: null, hinweis: null, istSystem: false, gesperrt: false, reihenfolge: 0 },
],
});
fireEvent.click(byUiId("ui.projects.fieldTemplate.group.grp_base.addExisting"));
// M05 picks first and confirms after — the dialog names the target group,
// so the pairing is meant to be checked before it happens.
fireEvent.click(byUiId("ui.projects.fieldTemplate.poolDialog.option.cfg_pool"));
fireEvent.click(byUiId("ui.projects.fieldTemplate.poolDialog.confirm"));
expect(onSubmit).toHaveBeenCalledWith("moveTemplateField", { fieldConfigId: "cfg_pool", groupId: "grp_base", reihenfolge: "0" });
});
it("lets a pick be taken back by clicking the same row again", () => {
renderPage({
poolFields: [
{ id: "cfg_pool", fieldKey: "foerdernummer", groupId: null, sichtbar: true, pflicht: false, pflichtAbStageId: null, hinweis: null, istSystem: false, gesperrt: false, reihenfolge: 0 },
],
});
fireEvent.click(byUiId("ui.projects.fieldTemplate.group.grp_base.addExisting"));
const row = byUiId("ui.projects.fieldTemplate.poolDialog.option.cfg_pool");
fireEvent.click(row);
expect(row.getAttribute("aria-pressed")).toBe("true");
fireEvent.click(row);
expect(row.getAttribute("aria-pressed")).toBe("false");
// Nothing picked means nothing to add.
expect((byUiId("ui.projects.fieldTemplate.poolDialog.confirm") as HTMLButtonElement).disabled).toBe(true);
});
it("leaves a hidden field out of the preview, like the detail page will", () => {
renderPage({
fields: [
{ id: "cfg_sys", fieldKey: "projektname", groupId: "grp_base", sichtbar: true, pflicht: true, pflichtAbStageId: null, hinweis: null, istSystem: true, gesperrt: false, reihenfolge: 0 },
{ id: "cfg_hidden", fieldKey: "status_aufmass", groupId: "grp_base", sichtbar: false, pflicht: false, pflichtAbStageId: null, hinweis: null, istSystem: false, gesperrt: false, reihenfolge: 1 },
],
});
expect(byUiId("ui.projects.fieldTemplate.preview.field.cfg_sys")).toBeTruthy();
expect(byUiId("ui.projects.fieldTemplate.preview.field.cfg_hidden")).toBeNull();
});
});
@@ -0,0 +1,688 @@
// R-P8b interim-UI (AD-28) — PipelineKanbanPage unit test. Fixture built via the
// real buildKanbanVM; interactions asserted on injected callbacks. i18n mocked.
// SortableKanbanBoard is stubbed so a "drag-end" is simulated by invoking its
// onCardMove prop directly — this keeps the test deterministic (no dnd-kit
// layout math in jsdom) while still exercising the screen's requestMove routing.
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildBoardFacetsVM, buildKanbanVM, buildPipelineHandoverVM, type KanbanBoardData, type PipelineHandoverVM } from "@hivegrid/view-models";
import { PipelineKanbanPage, type PipelineKanbanActions } from "./PipelineKanbanPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }),
}));
// Radix dropdowns neither open nor expose their menu context in jsdom, so the
// board switcher chip and every facet dropdown would be unreachable. The
// SubframeCore wrapper and both ~/ui menus become plain passthroughs; the
// entries stay real buttons. The ContextMenu is left alone — the card menu
// tests rely on the real one.
vi.mock("@subframe/core", async () => {
const actual = await vi.importActual<Record<string, unknown>>("@subframe/core");
const Pass = ({ children }: { children?: React.ReactNode }) => <>{children}</>;
return { ...actual, DropdownMenu: { Root: Pass, Trigger: Pass, Portal: Pass, Content: Pass } };
});
vi.mock("~/ui/components/DropdownMenu", () => {
const DropdownMenu = ({ children }: { children?: React.ReactNode }) => <div>{children}</div>;
DropdownMenu.DropdownItem = ({ children, onSelect, onClick, ...rest }: any) => (
<button type="button" onClick={(event: any) => { onSelect?.(); onClick?.(event); }} data-ui-id={rest["data-ui-id"]}>
{children}
</button>
);
DropdownMenu.DropdownDivider = () => <hr />;
return { DropdownMenu };
});
vi.mock("~/ui/components/DropdownMenuMultiSelect", () => {
const DropdownMenuMultiSelect = ({ children }: { children?: React.ReactNode }) => <div>{children}</div>;
DropdownMenuMultiSelect.DropdownItem = ({ children, onClick, selected, ...rest }: any) => (
<button type="button" onClick={onClick} aria-pressed={Boolean(selected)} data-ui-id={rest["data-ui-id"]}>
{children}
</button>
);
DropdownMenuMultiSelect.DropdownCustomItem = ({ children }: any) => <div>{children}</div>;
DropdownMenuMultiSelect.DropdownUserItem = ({ title }: any) => <div>{title}</div>;
DropdownMenuMultiSelect.DropdownDivider = () => <hr />;
return { DropdownMenuMultiSelect };
});
// Radix selects are not interactable in jsdom; swap ~/ui Select for a native
// one so the M01 lost-reason field can actually be chosen and asserted.
vi.mock("~/ui/components/Select", () => {
const Select = ({ value, onValueChange, label, error, errorText, children, ...rest }: any) => (
<div data-ui-id={rest["data-ui-id"]}>
<select
aria-label={typeof label === "string" ? label : "select"}
value={value ?? ""}
onChange={(e: any) => onValueChange?.(e.target.value)}
data-ui-id={rest["data-ui-id"] ? `${rest["data-ui-id"]}.native` : undefined}
>
<option value="" />
{children}
</select>
{error && errorText ? <span data-ui-id={rest["data-ui-id"] ? `${rest["data-ui-id"]}.errorText` : undefined}>{errorText}</span> : null}
</div>
);
Select.Item = ({ value, children }: any) => <option value={value}>{children}</option>;
return { Select };
});
// Stub the shared board: render each card via the real renderCard slot and expose
// one "move" button per (card, target column) that fires onCardMove — the same
// signal a real drag-end emits.
vi.mock("~/components/ui/kanban/SortableKanbanBoard", () => ({
SortableKanbanBoard: (p: {
columns: { id: string; name: React.ReactNode; price: React.ReactNode; sumMode?: "visible" | "locked" | "hidden"; twoColumn?: boolean; wrapAfter?: number; cards: { id: string }[] }[];
renderCard: (card: { id: string }, dragHandle?: React.ReactNode) => React.ReactNode;
onCardMove: (cardId: string, toColumnId: string, toIndex: number) => void;
dragHandlePlacement?: "above" | "inline";
}) => (
<div data-ui-id="ui.projects.board.columns">
{p.columns.map((col) => (
<div
key={col.id}
data-ui-id={`stub.col.${col.id}`}
data-sum-mode={col.sumMode}
data-two-column={String(col.twoColumn)}
data-wrap-after={String(col.wrapAfter)}
>
<span>{col.name}</span>
<span>{col.price}</span>
{col.cards.map((card) => (
<div key={card.id}>
{p.renderCard(
card,
p.dragHandlePlacement === "inline" ? (
<button type="button" aria-label={`drag-${card.id}`} data-ui-id={`stub.drag.${card.id}`} />
) : undefined,
)}
{p.columns
.filter((target) => target.id !== col.id)
.map((target) => (
<button
key={target.id}
type="button"
data-ui-id={`stub.move.${card.id}.${target.id}`}
onClick={() => p.onCardMove(card.id, target.id, 0)}
/>
))}
</div>
))}
</div>
))}
</div>
),
}));
const byUiId = (id: string) => document.querySelector(`[data-ui-id='${id}']`) as HTMLElement;
function boardData(
opts: {
empty?: boolean;
manyInS1?: boolean;
stuckP1?: boolean;
canAdmin?: boolean;
canDelete?: boolean;
undoP1?: boolean;
redoP1?: boolean;
cardTags?: { id: string; name: string; farbe: string }[];
} = {}
): KanbanBoardData {
const s1Cards = opts.empty
? []
: opts.manyInS1
? Array.from({ length: 7 }, (_, index) => ({
id: `p${index + 1}`,
projektNummer: `P-${index + 1}`,
projektname: `Projekt ${index + 1}`,
prioritaet: "normal" as const,
value: null,
valueVisible: false,
ownerUserId: null,
deadline: null,
isStuck: false,
}))
: [
// stuckP1: 9 full days in stage relative to generatedAt (2026-07-08T12:00Z).
{ id: "p1", projektNummer: "P-1", projektname: "Dach Nord", prioritaet: "normal" as const, value: "10000.00", valueVisible: true, ownerUserId: "u1", deadline: "2026-07-30", isStuck: false, inStageSince: opts.stuckP1 ? "2026-06-29T12:00:00.000Z" : "2026-07-08T00:00:00.000Z", kontaktLabel: "Fam. Bergmann", ort: "Freiburg", projekttyp: "PV / Solar", tags: opts.cardTags ?? [], startDatum: "2026-07-14", nextTerminTitel: "Ortstermin", nextTerminStartAt: "2026-07-22T08:00:00.000Z", undoStageChangeUntil: opts.undoP1 ? "2026-07-09T12:00:00.000Z" : null, redoStageId: opts.redoP1 ? "s3" : null },
{ id: "p2", projektNummer: "P-2", projektname: "Halle Sued", prioritaet: "normal" as const, value: null, valueVisible: false, ownerUserId: null, deadline: null, isStuck: false, inStageSince: "2026-07-08T00:00:00.000Z" },
];
const vm = buildKanbanVM({
board: {
pipeline: { id: "pl1", name: "Sales" },
pipelines: [
{ id: "pl1", name: "Sales", typHint: "sales" },
{ id: "pl2", name: "Auftrag", typHint: "auftrag" },
],
columns: [
{
stage: { id: "s1", name: "Neu", stageKind: "offen", color: "#000", winProbability: 10 },
projectCount: s1Cards.length,
aggregateValue: opts.empty ? null : "10000.00",
aggregateVisible: !opts.empty,
cards: s1Cards,
},
{ stage: { id: "s4", name: "In Arbeit", stageKind: "offen", color: "#00a", winProbability: 40 }, projectCount: 0, aggregateValue: null, aggregateVisible: false, cards: [] },
{ stage: { id: "s2", name: "Gewonnen", stageKind: "gewonnen", color: "#0a0", winProbability: 100 }, projectCount: 0, aggregateValue: null, aggregateVisible: false, cards: [] },
{ stage: { id: "s3", name: "Verloren", stageKind: "verloren", color: "#a00", winProbability: 0 }, projectCount: 0, aggregateValue: null, aggregateVisible: false, cards: [] },
],
generatedAt: "2026-07-08T12:00:00.000Z",
},
lostReasons: [{ id: "lr1", name: "Preis" }],
ownerLabels: new Map([["u1", "Rita Richter"]]),
buildDetailHref: (id) => `/acme/projects/${id}`,
sseHref: "/acme/stream",
perms: { canWrite: true, canChangeStage: true, canAdmin: opts.canAdmin ?? false, canDelete: opts.canDelete ?? false },
});
if (vm.status !== "ready") throw new Error("fixture not ready");
return vm.data;
}
function renderPage(
over: Partial<PipelineKanbanActions> = {},
opts: { showDemoToggle?: boolean; empty?: boolean; manyInS1?: boolean; q?: string; onlyMine?: boolean; stuckP1?: boolean; canAdmin?: boolean; canDelete?: boolean; undoP1?: boolean; canFilterByValue?: boolean; selectedOwners?: string[]; hasUnassigned?: boolean; tags?: { id: string; name: string; farbe: string }[]; selectedTagIds?: string[]; cardTags?: { id: string; name: string; farbe: string }[]; handover?: PipelineHandoverVM | null } = {},
) {
const actions: PipelineKanbanActions = {
onShowList: vi.fn(),
onOpenProject: vi.fn(),
onManageBoard: vi.fn(),
onSwitchPipeline: vi.fn(),
onToggleOnlyMine: vi.fn(),
onSearch: vi.fn(),
onToggleFacet: vi.fn(),
onRemoveChip: vi.fn(),
onResetFilters: vi.fn(),
onPeriodRangeChange: vi.fn(),
onToggleDemo: vi.fn(),
onMove: vi.fn(),
onBulkMove: vi.fn(),
onCreateProject: vi.fn(),
onDuplicate: vi.fn(),
onArchive: vi.fn(),
onUndoStage: vi.fn(),
onRedoStage: vi.fn(),
onMoveToPipeline: vi.fn(),
...over,
};
render(
<PipelineKanbanPage
data={boardData({
empty: opts.empty,
manyInS1: opts.manyInS1,
stuckP1: opts.stuckP1,
canAdmin: opts.canAdmin,
canDelete: opts.canDelete,
undoP1: opts.undoP1,
redoP1: opts.redoP1,
cardTags: opts.cardTags,
})}
onlyMine={opts.onlyMine ?? false}
q={opts.q ?? ""}
facets={buildBoardFacetsVM({
assignees: [{ userId: "u1", label: "Ada Lovelace" }],
hasUnassigned: opts.hasUnassigned ?? true,
tags: opts.tags ?? [],
selected: { owners: opts.selectedOwners ?? [], customerTypes: [], tagIds: opts.selectedTagIds ?? [], period: null, valueBands: [] },
onlyMine: opts.onlyMine ?? false,
q: opts.q ?? "",
canFilterByValue: opts.canFilterByValue ?? true,
})}
periodFrom=""
periodTo=""
includeDemoData={false}
showDemoToggle={opts.showDemoToggle ?? true}
submitting={false}
handover={opts.handover ?? null}
actions={actions}
/>
);
return actions;
}
describe("PipelineKanbanPage", () => {
it("renders columns and a project card", () => {
renderPage();
expect(screen.getAllByText("Neu").length).toBeGreaterThan(0);
expect(screen.getAllByText("Gewonnen").length).toBeGreaterThan(0);
expect(screen.getAllByText("Dach Nord").length).toBeGreaterThan(0);
expect(byUiId("ui.projects.board")).toBeTruthy();
expect(byUiId("ui.projects.board").getAttribute("data-sse-href")).toBe("/acme/stream");
expect((document.body.textContent ?? "").replace(/[\u00a0\u202f]/g, " ").match(/10\.000,00 €/g)).toHaveLength(2);
const card = byUiId("ui.projects.board.card.p1");
const dragHandle = byUiId("stub.drag.p1");
expect(card.contains(dragHandle)).toBe(true);
expect(dragHandle.textContent).toBe("");
expect(screen.getByRole("link", { name: "Dach Nord" }).getAttribute("href")).toBe("/acme/projects/p1");
});
it("keeps search typing local and commits once on Enter", () => {
const actions = renderPage();
const input = byUiId("ui.projects.board.search");
fireEvent.change(input, { target: { value: " Dach " } });
expect(actions.onSearch).not.toHaveBeenCalled();
fireEvent.keyDown(input, { key: "Enter" });
expect(actions.onSearch).toHaveBeenCalledOnce();
expect(actions.onSearch).toHaveBeenCalledWith("Dach");
});
it("toggles the demo-data checkbox through onToggleDemo", () => {
const actions = renderPage();
fireEvent.click(byUiId("ui.projects.board.demo"));
expect(actions.onToggleDemo).toHaveBeenCalledWith(true);
});
it("hides the demo-data checkbox when the demo UI is disabled (production)", () => {
renderPage({}, { showDemoToggle: false });
expect(document.querySelector('[data-ui-id="ui.projects.board.demo"]')).toBeNull();
});
it("creates a project through the quick-create dialog", () => {
const actions = renderPage();
fireEvent.click(byUiId("ui.projects.board.new"));
fireEvent.change(byUiId("ui.projects.board.createDialog.name"), { target: { value: "Neubau" } });
fireEvent.click(byUiId("ui.projects.board.createDialog.confirm"));
expect(actions.onCreateProject).toHaveBeenCalledWith({ projektname: "Neubau", potenziellerAuftragswert: "" });
});
it("submits directly on a drag into an open column (no dialog)", () => {
const actions = renderPage();
fireEvent.click(byUiId("stub.move.p1.s4"));
expect(actions.onMove).toHaveBeenCalledWith("p1", "s4");
expect(byUiId("ui.projects.board.moveDialog")).toBeFalsy();
});
it("opens the won confirm dialog on a drag into a won column, then submits on confirm", () => {
const actions = renderPage();
fireEvent.click(byUiId("stub.move.p1.s2"));
// Dialog opened, nothing submitted yet.
expect(actions.onMove).not.toHaveBeenCalled();
const confirm = byUiId("ui.projects.board.moveDialog.confirm");
expect(confirm).toBeTruthy();
expect(confirm.textContent).toContain("projects.actions.confirmWon");
fireEvent.click(confirm);
expect(actions.onMove).toHaveBeenCalledWith("p1", "s2");
});
it("blocks the lost move until a reason is chosen and says why (M01)", () => {
// Davids M01 shows a placeholder, not a preselected reason: the choice is
// deliberate. A blind confirm must therefore not record a reason nobody
// picked, and it must not look like a dead button either.
const actions = renderPage();
fireEvent.click(byUiId("stub.move.p1.s3"));
expect(actions.onMove).not.toHaveBeenCalled();
const confirm = byUiId("ui.projects.board.moveDialog.confirm");
expect(confirm.textContent).toContain("projects.actions.confirmLost");
fireEvent.click(confirm);
expect(actions.onMove).not.toHaveBeenCalled();
expect(byUiId("ui.projects.board.moveDialog.reason.errorText").textContent).toBe("projects.lostDialog.reasonRequired");
const reason = byUiId("ui.projects.board.moveDialog.reason.native") as HTMLSelectElement;
fireEvent.change(reason, { target: { value: "lr1" } });
fireEvent.click(confirm);
expect(actions.onMove).toHaveBeenCalledWith("p1", "s3", "lr1", undefined);
});
it("passes the optional M01 note along with the reason", () => {
const actions = renderPage();
fireEvent.click(byUiId("stub.move.p1.s3"));
fireEvent.change(byUiId("ui.projects.board.moveDialog.reason.native"), { target: { value: "lr1" } });
const note = byUiId("ui.projects.board.moveDialog.note") as HTMLTextAreaElement;
fireEvent.change(note, { target: { value: " Kunde hat intern entschieden. " } });
fireEvent.click(byUiId("ui.projects.board.moveDialog.confirm"));
expect(actions.onMove).toHaveBeenCalledWith("p1", "s3", "lr1", "Kunde hat intern entschieden.");
});
it("shows the 24h undo hint so the loss does not read as final", () => {
renderPage();
fireEvent.click(byUiId("stub.move.p1.s3"));
expect(byUiId("ui.projects.board.moveDialog").textContent).toContain("projects.lostDialog.undoHint");
});
it("offers M03 undo only inside the undo window and routes it", () => {
// The service clears undoStageChangeUntil once the window has passed, so a
// present value is the whole condition — no clock arithmetic in the screen.
const actions = renderPage({}, { undoP1: true });
fireEvent.contextMenu(byUiId("ui.projects.board.card.p1"));
fireEvent.click(byUiId("ui.projects.board.contextMenu.p1.undo"));
expect(actions.onUndoStage).toHaveBeenCalledWith("p1");
});
it("hides M03 undo when nothing can be undone", () => {
renderPage();
fireEvent.contextMenu(byUiId("ui.projects.board.card.p1"));
expect(byUiId("ui.projects.board.contextMenu.p1.undo")).toBeNull();
});
it("offers M03 redo only while an undone move can be re-applied and routes it", () => {
// Same shape as undo: the service keeps the redo pointer and clears it on
// the next forward move, so the screen only asks whether one is there.
const actions = renderPage({}, { redoP1: true });
fireEvent.contextMenu(byUiId("ui.projects.board.card.p1"));
fireEvent.click(byUiId("ui.projects.board.contextMenu.p1.redo"));
expect(actions.onRedoStage).toHaveBeenCalledWith("p1");
});
it("offers M03 board switching for every board except the current one", () => {
const actions = renderPage();
fireEvent.contextMenu(byUiId("ui.projects.board.card.p1"));
// The board being looked at is not a move target.
expect(byUiId("ui.projects.board.contextMenu.p1.moveToBoard.pl1")).toBeNull();
fireEvent.click(byUiId("ui.projects.board.contextMenu.p1.moveToBoard.pl2"));
expect(actions.onMoveToPipeline).toHaveBeenCalledWith("p1", "pl2");
});
it("hides M03 redo when nothing was undone", () => {
renderPage();
fireEvent.contextMenu(byUiId("ui.projects.board.card.p1"));
expect(byUiId("ui.projects.board.contextMenu.p1.redo")).toBeNull();
});
it("shows the locked-value state instead of an amount when the value is masked", () => {
renderPage();
const visible = byUiId("ui.projects.board.card.p1");
expect(visible.textContent).toContain("10.000,00");
const locked = byUiId("ui.projects.board.card.p2");
expect(locked.textContent).toContain("projects.board.valueLocked");
});
it("renders the owner as an avatar and the deadline as the end of the card date range", () => {
// Davids ProjectCard (Subframe 2026-07-28) replaced the footer row: the
// assignee is an avatar (no photo source, so initials) and the deadline is
// the right-hand end of the start/end range, in day.month form.
renderPage();
const owner = byUiId("ui.projects.board.owner.p1");
expect(owner.textContent).toBe("RR");
const card = byUiId("ui.projects.board.card.p1");
expect(card.textContent).toMatch(/30\.0?7\./u);
// A card without a deadline shows no date at all rather than an open range.
expect(byUiId("ui.projects.board.card.p2").textContent).not.toMatch(/\d{2}\.\d{2}\./u);
});
it("renders the S01 card subtitle, type tag and appointment pill", () => {
renderPage();
const card = byUiId("ui.projects.board.card.p1");
expect(card.textContent).toContain("Fam. Bergmann \u00b7 Freiburg");
expect(byUiId("ui.projects.board.typ.p1").textContent).toBe("PV / Solar");
expect(card.textContent).toContain("projects.board.nextAppointment");
// Start of the range comes from startDatum, formatted day.month like the export.
expect(card.textContent).toMatch(/14\.0?7\./u);
// A card without any of it stays clean instead of rendering empty chrome.
const bare = byUiId("ui.projects.board.card.p2");
expect(bare.textContent).not.toContain("projects.board.nextAppointment");
expect(byUiId("ui.projects.board.typ.p2")).toBeNull();
});
it("shows a dashed stage-aware placeholder in every empty column", () => {
renderPage();
for (const stageId of ["s4", "s2", "s3"]) {
const placeholder = byUiId(`ui.projects.board.column.empty.${stageId}`);
expect(placeholder).toBeTruthy();
expect(placeholder.textContent).toContain("projects.board.columnEmpty.title");
}
expect(byUiId("ui.projects.board.column.empty.s1")).toBeFalsy();
});
it("shows the filtered empty banner with reset + create when a filter yields zero cards", () => {
const actions = renderPage({}, { empty: true, q: "dach" });
expect(byUiId("ui.projects.board.emptyFiltered")).toBeTruthy();
expect(byUiId("ui.projects.board.empty")).toBeFalsy();
fireEvent.click(byUiId("ui.projects.board.emptyFiltered.reset"));
// One navigation drops every filter — search, only-mine and all facets.
expect(actions.onResetFilters).toHaveBeenCalled();
fireEvent.click(byUiId("ui.projects.board.emptyFiltered.create"));
expect(byUiId("ui.projects.board.createDialog")).toBeTruthy();
});
it("keeps the kanban columns under the notice when a filter empties the board", () => {
renderPage({}, { empty: true, q: "dach" });
// S01a: the message sits above the board, it does not replace it — the
// stages a project would land in stay visible.
expect(byUiId("ui.projects.board.columns")).toBeTruthy();
expect(byUiId("stub.col.s1")).toBeTruthy();
});
it("shows the plain empty notice above the board when the board is empty and unfiltered", () => {
renderPage({}, { empty: true });
expect(byUiId("ui.projects.board.empty")).toBeTruthy();
expect(byUiId("ui.projects.board.emptyFiltered")).toBeFalsy();
// Nothing to reset without a filter, but the board itself still renders.
expect(byUiId("ui.projects.board.emptyFiltered.reset")).toBeFalsy();
expect(byUiId("ui.projects.board.columns")).toBeTruthy();
});
it("maps aggregate visibility to the column sum mode", () => {
renderPage();
expect(byUiId("stub.col.s1").getAttribute("data-sum-mode")).toBe("visible");
expect(byUiId("stub.col.s4").getAttribute("data-sum-mode")).toBe("locked");
});
it("keeps every stage a single card column, even when it overflows", () => {
renderPage({}, { manyInS1: true });
expect(byUiId("stub.col.s1").getAttribute("data-two-column")).toBe("undefined");
expect(byUiId("stub.col.s4").getAttribute("data-two-column")).toBe("undefined");
expect(byUiId("ui.projects.board.twoColumnHint")).toBeFalsy();
});
it("keeps the staleness chip off the card, even past the 7-day threshold", () => {
// Davids S01 card carries the tag catalogue and the project type, nothing
// else; the VM still computes stuckDays for other readers.
renderPage({}, { stuckP1: true });
expect(byUiId("ui.projects.board.stuckDays.p1")).toBeFalsy();
expect(document.body.textContent).not.toContain("projects.board.stuckDays");
});
it("offers duplicate in the context menu when canWrite and routes it", () => {
const actions = renderPage();
fireEvent.contextMenu(byUiId("ui.projects.board.card.p1"));
const duplicate = byUiId("ui.projects.board.contextMenu.p1.duplicate");
expect(duplicate).toBeTruthy();
fireEvent.click(duplicate);
expect(actions.onDuplicate).toHaveBeenCalledWith("p1");
});
it("hides duplicate when the callback is not wired (no dead buttons)", () => {
renderPage({ onDuplicate: undefined });
fireEvent.contextMenu(byUiId("ui.projects.board.card.p1"));
expect(byUiId("ui.projects.board.contextMenu.p1")).toBeTruthy();
expect(byUiId("ui.projects.board.contextMenu.p1.duplicate")).toBeFalsy();
});
it("hides archive without the delete permission", () => {
renderPage();
fireEvent.contextMenu(byUiId("ui.projects.board.card.p1"));
expect(byUiId("ui.projects.board.contextMenu.p1")).toBeTruthy();
expect(byUiId("ui.projects.board.contextMenu.p1.archive")).toBeFalsy();
});
it("archives only after the confirm dialog is confirmed", () => {
const actions = renderPage({}, { canDelete: true });
fireEvent.contextMenu(byUiId("ui.projects.board.card.p1"));
const archiveItem = byUiId("ui.projects.board.contextMenu.p1.archive");
expect(archiveItem).toBeTruthy();
fireEvent.click(archiveItem);
// Dialog opened, nothing submitted yet.
expect(actions.onArchive).not.toHaveBeenCalled();
const confirm = byUiId("ui.projects.board.archiveDialog.confirm");
expect(confirm).toBeTruthy();
fireEvent.click(confirm);
expect(actions.onArchive).toHaveBeenCalledWith("p1");
expect(byUiId("ui.projects.board.archiveDialog")).toBeFalsy();
});
it("does not archive when the confirm dialog is cancelled", () => {
const actions = renderPage({}, { canDelete: true });
fireEvent.contextMenu(byUiId("ui.projects.board.card.p1"));
fireEvent.click(byUiId("ui.projects.board.contextMenu.p1.archive"));
fireEvent.click(screen.getByText("projects.actions.cancel"));
expect(actions.onArchive).not.toHaveBeenCalled();
expect(byUiId("ui.projects.board.archiveDialog")).toBeFalsy();
});
it("opens a right-click context menu with open / move / settings entries and routes a move", () => {
const actions = renderPage();
fireEvent.contextMenu(byUiId("ui.projects.board.card.p1"));
expect(byUiId("ui.projects.board.contextMenu.p1")).toBeTruthy();
expect(byUiId("ui.projects.board.contextMenu.p1.open")).toBeTruthy();
// Own column (s1) is not offered as a move target; admin entry hidden (canAdmin=false fixture).
expect(byUiId("ui.projects.board.contextMenu.p1.moveTo.s1")).toBeFalsy();
expect(byUiId("ui.projects.board.contextMenu.p1.settings")).toBeFalsy();
const moveItem = byUiId("ui.projects.board.contextMenu.p1.moveTo.s4");
expect(moveItem).toBeTruthy();
fireEvent.click(moveItem);
expect(actions.onMove).toHaveBeenCalledWith("p1", "s4");
});
it("routes the card context-menu open action without a document reload", () => {
const actions = renderPage();
fireEvent.contextMenu(byUiId("ui.projects.board.card.p1"));
fireEvent.click(byUiId("ui.projects.board.contextMenu.p1.open"));
expect(actions.onOpenProject).toHaveBeenCalledWith("/acme/projects/p1");
});
it("keeps board settings in the card context menu only and switches views from the header", () => {
const actions = renderPage();
// The header carries the view switch and the create CTA — board settings are
// reachable from the card context menu, not from a header button.
expect(byUiId("ui.projects.board.viewToggle")).toBeTruthy();
expect(byUiId("ui.projects.board.new")).toBeTruthy();
expect(byUiId("ui.projects.board.manage")).toBeFalsy();
// No CSV button in the head — the export is not part of Davids S01.
expect(byUiId("ui.projects.board.export")).toBeFalsy();
fireEvent.click(byUiId("ui.projects.board.viewToggle.list"));
expect(actions.onShowList).toHaveBeenCalled();
});
it("shows every configured stage until the column picker hides one", () => {
renderPage();
for (const stageId of ["s1", "s2", "s3", "s4"]) expect(byUiId(`stub.col.${stageId}`)).toBeTruthy();
fireEvent.click(byUiId("ui.projects.board.columnPicker.s3"));
expect(byUiId("stub.col.s3")).toBeFalsy();
// Hiding a column does not take the stage off the card context menu (see the
// move-target test), so losing a project never depends on showing it.
fireEvent.click(byUiId("ui.projects.board.columnPicker.s3"));
expect(byUiId("stub.col.s3")).toBeTruthy();
});
it("offers board settings in the header only for an admin", () => {
const actions = renderPage({}, { canAdmin: true });
const button = byUiId("ui.projects.board.settings");
expect(byUiId("ui.projects.board.header").contains(button)).toBe(true);
fireEvent.click(button);
expect(actions.onManageBoard).toHaveBeenCalled();
renderPage();
expect(document.querySelectorAll('[data-ui-id="ui.projects.board.settings"]').length).toBe(1);
});
it("puts the board switcher in the header and the search into the filter bar", () => {
const actions = renderPage();
// S01: the switcher is a header chip, not a toolbar select; the free-text
// search moved into the filter bar next to the facets.
const switcher = byUiId("ui.projects.board.switcher");
expect(byUiId("ui.projects.board.header").contains(switcher)).toBe(true);
expect(byUiId("ui.projects.board.filterBar").contains(byUiId("ui.projects.board.search"))).toBe(true);
fireEvent.click(switcher);
fireEvent.click(byUiId("ui.projects.board.switcher.pl2"));
expect(actions.onSwitchPipeline).toHaveBeenCalledWith("pl2");
});
it("renders one facet button per available facet and toggles an option", () => {
const actions = renderPage();
for (const facet of ["owner", "customerType", "period", "value"]) {
expect(byUiId(`ui.projects.board.facet.${facet}`)).toBeTruthy();
}
fireEvent.click(byUiId("ui.projects.board.facet.owner"));
fireEvent.click(byUiId("ui.projects.board.facet.owner.u1"));
expect(actions.onToggleFacet).toHaveBeenCalledWith("owner", "u1");
});
it("hides the value facet from a viewer without tenant-wide volume access", () => {
renderPage({}, { canFilterByValue: false });
expect(byUiId("ui.projects.board.facet.owner")).toBeTruthy();
// Picking a band would reveal the very number the card gate withholds.
expect(byUiId("ui.projects.board.facet.value")).toBeFalsy();
});
it("keeps a selected unassigned bucket visible even when no project is unassigned", () => {
renderPage({}, { hasUnassigned: false, selectedOwners: ["none"] });
// Dropping the option would leave the filter active with no chip to remove.
expect(byUiId("ui.projects.board.filterChip.owner.none")).toBeTruthy();
});
it("shows one removable chip per active filter", () => {
const actions = renderPage({}, { onlyMine: true, selectedOwners: ["u1"] });
expect(byUiId("ui.projects.board.filterChip.owner.u1")).toBeTruthy();
expect(byUiId("ui.projects.board.filterChip.onlyMine.1")).toBeTruthy();
fireEvent.click(byUiId("ui.projects.board.filterChip.onlyMine.1.remove"));
expect(actions.onRemoveChip).toHaveBeenCalledWith(expect.objectContaining({ facet: "onlyMine" }));
});
it("shows the project tags as chips on the card and offers them as a facet", () => {
renderPage(
{},
{
cardTags: [{ id: "t1", name: "PV / Solar", farbe: "yellow-subtle" }],
tags: [{ id: "t1", name: "PV / Solar", farbe: "yellow-subtle" }],
}
);
expect(byUiId("ui.projects.board.tag.p1.t1").textContent).toContain("PV / Solar");
expect(byUiId("ui.projects.board.facet.tags")).toBeTruthy();
});
});
// --- M04 handover ---------------------------------------------------------
// D-P8: the move is the trigger ("Erreicht eine Karte die letzte Stage […],
// oeffnet sich M04 automatisch"). The board therefore has to open the dialog on
// what the move handed back — leaving it to the detail page would mean the
// board offers nothing at the moment the flow says it should.
const handoverVM = buildPipelineHandoverVM({
projectId: "p1",
projectName: "Projekt Eins",
fromPipelineId: "pipe1",
fromPipelineName: "Vertrieb",
toPipelineId: "pipe2",
toPipelineName: "Auftrag",
toStageId: "s-neu",
toStageName: "Neu",
candidates: [{ id: "note_1", kind: "notiz", title: "BAFA-Antrag läuft", atIso: null, defaultSelected: true }],
});
describe("PipelineKanbanPage — M04 handover", () => {
it("stays out of the way while no move has offered one", () => {
renderPage();
expect(document.querySelector("[data-ui-id='ui.projects.handover']")).toBeNull();
});
it("opens the dialog on the payload the move handed back", () => {
renderPage({ onHandover: vi.fn() }, { handover: handoverVM });
const dialog = document.querySelector("[data-ui-id='ui.projects.handover']") as HTMLElement;
expect(dialog).not.toBeNull();
expect(dialog.textContent).toContain("Vertrieb → Auftrag");
});
it("commits the handover with the project, its board and the ticked records", () => {
const onHandover = vi.fn();
renderPage({ onHandover }, { handover: handoverVM });
fireEvent.click(document.querySelector("[data-ui-id='ui.projects.handover.confirm']")!);
expect(onHandover).toHaveBeenCalledWith("p1", "pipe1", [{ kind: "notiz", sourceId: "note_1" }]);
});
it("keeps the dialog shut once it is dismissed, so the board is usable again", () => {
renderPage({ onHandover: vi.fn() }, { handover: handoverVM });
fireEvent.click(document.querySelector("[data-ui-id='ui.projects.handover.cancel']")!);
expect(document.querySelector("[data-ui-id='ui.projects.handover']")).toBeNull();
});
});
@@ -0,0 +1,945 @@
// R-P8b (P8 configurable Kanban) Interim-UI (AD-28) — pipeline board screen
// (D-KANBAN), composed from ~/ui (ProjectCard + Dialog) on top of the shared
// SortableKanbanBoard (dnd-kit). Pure/presentational: renders the server-built
// KanbanBoardData and turns each action into a typed callback the route POSTs.
// Primary stage change = drag&drop (mouse + keyboard via the board's drag
// handle). A drop into a "gewonnen" stage opens a confirm dialog; "verloren"
// opens a mandatory lost-reason dialog — so DnD still routes through requestMove
// and never submits won/lost blindly. Live SSE stays a tracked design-nachzug
// (sseHref kept on the root as a hint). No useLoaderData/useFetcher, no server
// imports.
import { useMemo, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import {
FeatherAlertCircle,
FeatherArchive,
FeatherArrowLeftRight,
FeatherArrowRight,
FeatherCheck,
FeatherChevronDown,
FeatherChevronsLeft,
FeatherColumns,
FeatherCommand,
FeatherCopy,
FeatherExternalLink,
FeatherKanbanSquare,
FeatherList,
FeatherMoreVertical,
FeatherPlus,
FeatherRotateCcw,
FeatherRedo2,
FeatherSearchX,
FeatherSettings2,
FeatherTrendingDown,
FeatherTrendingUp,
FeatherUndo2,
FeatherX,
} from "@subframe/core";
import * as SubframeCore from "@subframe/core";
import type { BoardFacet, BoardFacetChip, BoardFacetsVM, KanbanBoardData, PipelineHandoverKind, PipelineHandoverVM } from "@hivegrid/view-models";
import { BoardFilterBar } from "./BoardFilterBar";
import { PipelineHandoverDialog } from "./dialogs/PipelineHandoverDialog";
import { PAGE_HEADER_ICON_CLASS, PageHeader, PageShell } from "../shared/PageShell";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Checkbox } from "~/ui/components/Checkbox";
import { BadgeShortcut } from "~/ui/components/BadgeShortcut";
import { ContextMenu } from "~/ui/components/ContextMenu";
import { Alert } from "~/ui/components/Alert";
import { Dialog } from "~/ui/components/Dialog";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
import { TextArea } from "~/ui/components/TextArea";
import { DropdownMenu } from "~/ui/components/DropdownMenu";
import { DropdownMenuMultiSelect } from "~/ui/components/DropdownMenuMultiSelect";
import { FilterBar } from "~/ui/components/FilterBar";
import { IconButton } from "~/ui/components/IconButton";
import { Avatar } from "~/ui/components/Avatar";
import { ProjectCard } from "~/ui/components/ProjectCard";
import { Tag_Label } from "~/ui/components/Tag_Label";
import { Select } from "~/ui/components/Select";
import { TextInput } from "~/ui/components/TextInput";
import { ToggleGroup } from "~/ui/components/ToggleGroup";
import { useLocaleFormatters } from "~/locale/format";
import { SortableKanbanBoard, type SortableKanbanColumn } from "~/components/ui/kanban/SortableKanbanBoard";
import { useRecommendedSidebarCollapse } from "~/components/app/AppShellSidebarContext";
import { AppLink } from "~/components/app/AppLink";
import { tagTone } from "./tagTone";
/** Day+month only, matching the export's "14.07." on the card date range. */
const SHORT_DATE: Intl.DateTimeFormatOptions = { day: "2-digit", month: "2-digit" };
/** Project priority → ProjectCard colour variant. */
const PRIORITY_VARIANT: Record<string, "none" | "low" | "medium" | "high" | "critical"> = {
niedrig: "low",
normal: "none",
hoch: "high",
dringend: "critical",
};
/** Up to two initials for the assignee avatar (the card has no photo source). */
function initialsOf(label: string): string {
return label
.split(/\s+/u)
.filter(Boolean)
.slice(0, 2)
.map((part) => part[0]!.toUpperCase())
.join("");
}
export type PipelineKanbanActions = {
onShowList: () => void;
onOpenProject: (detailHref: string) => void;
/** Board settings — reachable from the card context menu, not from the header. */
onManageBoard: () => void;
onSwitchPipeline: (pipelineId: string) => void;
onToggleOnlyMine: (checked: boolean) => void;
onSearch: (q: string) => void;
/** S01 facet option toggled on/off (assignee, customer type, period, value). */
onToggleFacet: (facet: BoardFacet["key"], value: string) => void;
/** One active-filter chip removed. */
onRemoveChip: (chip: BoardFacetChip) => void;
/** Clear search, only-mine and every facet in a single navigation. */
onResetFilters: () => void;
/** Bounds of the custom period option (ISO yyyy-mm-dd, "" = unset). */
onPeriodRangeChange: (from: string, to: string) => void;
onToggleDemo: (show: boolean) => void;
onMove: (projectId: string, targetStageId: string, lostReasonId?: string, notiz?: string) => void;
onBulkMove: (projectIds: string[], targetStageId: string) => void;
onCreateProject: (fields: { projektname: string; potenziellerAuftragswert: string }) => void;
/** Optional: context-menu duplicate. Item only renders when callback + write permission exist. */
onDuplicate?: (projectId: string) => void;
/** Optional: M03 "Rückgängig" — undo the last won/lost move inside its window. */
onUndoStage?: (projectId: string) => void;
/** Optional: M03 "Wiederholen" — re-apply the move an undo reverted. */
onRedoStage?: (projectId: string) => void;
/** Optional: M03 "Board wechseln" — move the project into another board. */
onMoveToPipeline?: (projectId: string, targetPipelineId: string) => void;
/** Optional: context-menu archive (behind a confirm dialog). Item only renders when callback + delete permission exist. */
onArchive?: (projectId: string) => void;
/** M04 confirmed — commit the handover with the picked companion records. */
onHandover?: (projectId: string, fromPipelineId: string, selection: readonly { kind: PipelineHandoverKind; sourceId: string }[]) => void;
};
export type PipelineKanbanPageProps = {
data: KanbanBoardData;
onlyMine: boolean;
q: string;
/** S01 filter bar: facet dropdowns + active-filter chips. */
facets: BoardFacetsVM;
/** Bounds of the custom period option (ISO yyyy-mm-dd, "" = unset). */
periodFrom: string;
periodTo: string;
includeDemoData: boolean;
/** Demo-data toggle is a staging/dev-only affordance (env-gated by the loader). */
showDemoToggle: boolean;
submitting: boolean;
errorKey?: string | null;
/**
* M04, handed back by the last stage move: non-null exactly when the card
* landed in a stage that offers a handover. D-P8 makes the move the trigger,
* so the board opens the dialog itself instead of waiting for someone to
* open the project.
*/
handover?: PipelineHandoverVM | null;
language?: string;
actions: PipelineKanbanActions;
};
type PendingMove = { projectId: string; stageId: string; kind: "gewonnen" | "verloren" };
type BoardCard = KanbanBoardData["columns"][number]["cards"][number];
// Pseudo-card injected into empty columns so each of them renders a dashed,
// stage-aware placeholder (S01a). Placeholders never get a drag handle and are
// filtered out of every move path.
type ColumnPlaceholder = { readonly id: string; readonly kind: "column-placeholder"; readonly stageId: string; readonly stageName: string };
type BoardEntry = BoardCard | ColumnPlaceholder;
const PLACEHOLDER_PREFIX = "column-placeholder:";
function isPlaceholder(entry: BoardEntry): entry is ColumnPlaceholder {
return "kind" in entry && entry.kind === "column-placeholder";
}
const mutedText = "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary";
export function PipelineKanbanPage(props: PipelineKanbanPageProps) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const { data } = props;
useRecommendedSidebarCollapse(`projects:${data.pipelineId}`);
const [selected, setSelected] = useState<ReadonlySet<string>>(new Set());
const [bulkStage, setBulkStage] = useState(data.openStages[0]?.id ?? "");
const [pendingMove, setPendingMove] = useState<PendingMove | null>(null);
// M01 starts with no preselected reason: the dialog demands a deliberate
// choice, and preselecting the first one would let a blind confirm record a
// reason the user never picked.
const [lostReasonId, setLostReasonId] = useState("");
const [lostNote, setLostNote] = useState("");
const [lostReasonMissing, setLostReasonMissing] = useState(false);
const [createOpen, setCreateOpen] = useState(false);
// Archive goes through an explicit confirm dialog — never a one-click destroy.
const [pendingArchive, setPendingArchive] = useState<string | null>(null);
const [draft, setDraft] = useState({ projektname: "", potenziellerAuftragswert: "" });
// Bumped whenever an optimistic DnD drop must be reverted (won/lost dialog
// cancelled) so SortableKanbanBoard snaps the card back to the server order.
const [resetToken, setResetToken] = useState(0);
// Which columns this person wants on screen. Only the deliberate deviations
// are stored, so the default below keeps applying to every other stage — and
// to the stages of another board after a switch.
const [columnVisibility, setColumnVisibility] = useState<Readonly<Record<string, boolean>>>({});
// Which handover the user closed without deciding. Keyed by project so the
// next move that offers one opens the dialog again rather than staying shut.
const [handoverDismissed, setHandoverDismissed] = useState<string | null>(null);
// The board shows the board: every configured stage is on screen until this
// person hides one. Hiding is theirs to choose, not ours to preselect.
function isColumnVisible(column: KanbanBoardData["columns"][number]): boolean {
return columnVisibility[column.stageId] ?? true;
}
const visibleColumns = data.columns.filter(isColumnVisible);
// Shown on the picker button, so a missing column is never a silent one.
const hiddenColumnCount = data.columns.length - visibleColumns.length;
const stageKindById = useMemo(() => new Map(data.columns.map((column) => [column.stageId, column.stageKind])), [data.columns]);
// Owning stage per card — used by the context menu to offer only the OTHER
// stages as move targets.
const stageIdByCardId = useMemo(() => {
const map = new Map<string, string>();
for (const column of data.columns) for (const card of column.cards) map.set(card.id, column.stageId);
return map;
}, [data.columns]);
// Every stage change (drag-end OR keyboard-DnD) funnels through here so a move
// into a "gewonnen"/"verloren" column opens the confirm / lost-reason dialog
// instead of submitting blindly.
function requestMove(projectId: string, stageId: string) {
if (projectId.startsWith(PLACEHOLDER_PREFIX)) return; // placeholder cards never move
const kind = stageKindById.get(stageId);
if (kind === "gewonnen" || kind === "verloren") {
setLostReasonId("");
setLostNote("");
setLostReasonMissing(false);
setPendingMove({ projectId, stageId, kind });
return;
}
props.actions.onMove(projectId, stageId);
}
function cancelPending() {
setPendingMove(null);
setResetToken((token) => token + 1); // revert the optimistic drop
}
function confirmPending() {
if (!pendingMove) return;
if (pendingMove.kind === "verloren") {
// Silently returning would leave the user pressing a button that appears
// to do nothing; the dialog says what is missing instead.
if (!lostReasonId) {
setLostReasonMissing(true);
return;
}
props.actions.onMove(pendingMove.projectId, pendingMove.stageId, lostReasonId, lostNote.trim() || undefined);
} else {
props.actions.onMove(pendingMove.projectId, pendingMove.stageId);
}
setPendingMove(null);
}
function toggleSelect(id: string, checked: boolean) {
setSelected((prev) => {
const next = new Set(prev);
if (checked) next.add(id);
else next.delete(id);
return next;
});
}
const someSelected = selected.size > 0;
// "Empty" is what the person actually looks at: a card parked in a hidden
// column is not something they can see or work on here.
const boardIsEmpty = visibleColumns.every((column) => column.cards.length === 0);
const filterActive = props.facets.hasActiveFilters;
// One navigation clears everything — search, only-mine and every facet. The
// route drops the parameters in a single history entry, so the board does not
// flicker through half-reset states.
function resetFilters() {
props.actions.onResetFilters();
}
// Card body slot for SortableKanbanBoard. The board supplies the DnD handle;
// the card places its invisible target in the tag-row whitespace so the title
// link and bulk-select checkbox stay independent. Stage change is drag&drop;
// right-click opens a context menu (open / move to stage / board settings).
function renderProjectCard(entry: BoardEntry, dragHandle?: ReactNode): ReactNode {
if (isPlaceholder(entry)) {
// Dashed stage-aware placeholder for an empty column (S01a).
return (
<div
className="flex min-h-[144px] w-full flex-col items-center justify-center gap-2 rounded-md border border-dashed border-border-default bg-surface-neutral-secondary px-4 py-6"
data-ui-id={`ui.projects.board.column.empty.${entry.stageId}`}
>
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-secondary">
{t("projects.board.columnEmpty.title", { stage: entry.stageName })}
</span>
<span className="text-center text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("projects.board.columnEmpty.body")}
</span>
</div>
);
}
const card = entry;
const currentStageId = stageIdByCardId.get(card.id);
// Every stage, including a hidden one: "Verloren" is off the board by
// default, and losing a project must not depend on showing that column.
const moveTargets = data.canChangeStage ? data.columns.filter((column) => column.stageId !== currentStageId) : [];
// No dead buttons: items render only with both the permission AND a wired callback.
const onDuplicate = data.canWrite ? props.actions.onDuplicate : undefined;
const onArchive = data.canDelete ? props.actions.onArchive : undefined;
// The undo entry only appears while the service still accepts it: the VM
// carries the window end and the service clears it once it has passed.
const onUndo = data.canChangeStage && card.undoUntilIso ? props.actions.onUndoStage : undefined;
// Redo is offered only right after an undo — the VM turns the service's
// redo pointer into canRedo, and the next forward move clears it.
const onRedo = data.canChangeStage && card.canRedo ? props.actions.onRedoStage : undefined;
const onMoveToPipeline = data.canChangeStage ? props.actions.onMoveToPipeline : undefined;
const boardTargets = data.pipelines.filter((pipeline) => pipeline.id !== data.pipelineId);
return (
<SubframeCore.ContextMenu.Root>
<SubframeCore.ContextMenu.Trigger asChild>
<ProjectCard
title={<AppLink href={card.detailHref} className="text-text-feedback-link-default">{card.projektname}</AppLink>}
subtitle={card.subtitle ?? undefined}
tags={
<div className="flex w-full flex-col gap-1">
<div className="flex flex-wrap items-center gap-1">
{card.projekttyp ? (
<Tag_Label tone="blue-subtle" noAction size="small" data-ui-id={`ui.projects.board.typ.${card.id}`}>
{card.projekttyp}
</Tag_Label>
) : null}
{/* Tags from the tenant catalogue, in their own colour. */}
{card.tags.map((tag) => (
<Tag_Label key={tag.id} tone={tagTone(tag.farbe)} noAction size="small" data-ui-id={`ui.projects.board.tag.${card.id}.${tag.id}`}>
{tag.name}
</Tag_Label>
))}
{/* No staleness chip on the card: Davids S01 card carries the
tag catalogue and the project type, nothing else. The VM
still computes `stuckDays` for other readers. */}
{card.isStuck ? <BadgeFeedback farbe="subtle-warning" size="small">{t("projects.board.stuck")}</BadgeFeedback> : null}
</div>
{/* Drag handle and bulk-select live on their own row: Davids
ProjectCard has no slot for them, and squeezing them into
the tag row pushes the tags out of the clamped height. */}
<div className="flex w-full items-center justify-between gap-2">
{dragHandle}
{data.canChangeStage ? (
<Checkbox
checked={selected.has(card.id)}
onCheckedChange={(c) => toggleSelect(card.id, c)}
hideLabel
label={card.projektname}
data-ui-id={`ui.projects.board.select.${card.id}`}
/>
) : null}
</div>
</div>
}
price={
card.valueVisible ? (
card.value ?? "\u2014"
) : (
<span className={mutedText}>{t("projects.board.valueLocked")}</span>
)
}
priorityLabel={t(card.prioritaetLabelKey)}
variant={PRIORITY_VARIANT[card.prioritaet]}
avatar={
card.ownerLabel ? (
<Avatar size="extra-small" data-ui-id={`ui.projects.board.owner.${card.id}`}>{initialsOf(card.ownerLabel)}</Avatar>
) : undefined
}
hideAvatar={!card.ownerLabel}
startDate={card.startIso ? formatters.date(card.startIso, SHORT_DATE) : undefined}
endDate={card.deadlineIso ? formatters.date(card.deadlineIso, SHORT_DATE) : undefined}
// The range needs at least one end to say anything; without both
// the row would be two icons around an empty line.
hideDateRange={!card.startIso && !card.deadlineIso}
appointmentLabel={
card.appointmentIso
? t("projects.board.nextAppointment", {
title: card.appointmentTitle ?? "",
date: formatters.date(card.appointmentIso, SHORT_DATE),
})
: undefined
}
hideAppointment={!card.appointmentIso}
className="h-auto w-full flex-none"
data-row-id={card.id}
data-ui-id={`ui.projects.board.card.${card.id}`}
/>
</SubframeCore.ContextMenu.Trigger>
<SubframeCore.ContextMenu.Portal>
<SubframeCore.ContextMenu.Content asChild>
{/* M03 order: open/settings, then the undo block, then the move
block, then the destructive action. Local kit drift: the export
names the shortcut icon prop `iconLeft1`, the synced
BadgeShortcut has `icon`. */}
<ContextMenu data-ui-id={`ui.projects.board.contextMenu.${card.id}`}>
<ContextMenu.ContextItem
icon={<FeatherExternalLink />}
onSelect={() => props.actions.onOpenProject(card.detailHref)}
data-ui-id={`ui.projects.board.contextMenu.${card.id}.open`}
>
{t("projects.board.contextMenu.open")}
</ContextMenu.ContextItem>
{data.canAdmin ? (
<ContextMenu.ContextItem
icon={<FeatherSettings2 />}
onSelect={props.actions.onManageBoard}
data-ui-id={`ui.projects.board.contextMenu.${card.id}.settings`}
>
{t("projects.board.contextMenu.settings")}
</ContextMenu.ContextItem>
) : null}
{onUndo || onRedo ? <ContextMenu.ContextDivider /> : null}
{onUndo ? (
<ContextMenu.ContextItem
icon={<FeatherUndo2 />}
rightSlot={<BadgeShortcut icon={<FeatherCommand />}>Z</BadgeShortcut>}
onSelect={() => onUndo(card.id)}
data-ui-id={`ui.projects.board.contextMenu.${card.id}.undo`}
>
{t("projects.board.contextMenu.undo")}
</ContextMenu.ContextItem>
) : null}
{onRedo ? (
<ContextMenu.ContextItem
icon={<FeatherRedo2 />}
rightSlot={<BadgeShortcut icon={<FeatherCommand />}>⇧Z</BadgeShortcut>}
onSelect={() => onRedo(card.id)}
data-ui-id={`ui.projects.board.contextMenu.${card.id}.redo`}
>
{t("projects.board.contextMenu.redo")}
</ContextMenu.ContextItem>
) : null}
{moveTargets.length > 0 ? <ContextMenu.ContextDivider /> : null}
{moveTargets.map((column) => (
<ContextMenu.ContextItem
key={column.stageId}
icon={<FeatherArrowRight />}
onSelect={() => requestMove(card.id, column.stageId)}
data-ui-id={`ui.projects.board.contextMenu.${card.id}.moveTo.${column.stageId}`}
>
{t("projects.board.contextMenu.moveTo", { stage: column.stageName })}
</ContextMenu.ContextItem>
))}
{/* M03 "Board wechseln". Rendered flat, one entry per other
board: the kit's ContextMenu has no submenu, and the number
of boards is the same handful the switcher chip lists. */}
{onMoveToPipeline && boardTargets.length > 0 ? <ContextMenu.ContextDivider /> : null}
{onMoveToPipeline
? boardTargets.map((pipeline) => (
<ContextMenu.ContextItem
key={pipeline.id}
icon={<FeatherArrowLeftRight />}
onSelect={() => onMoveToPipeline(card.id, pipeline.id)}
data-ui-id={`ui.projects.board.contextMenu.${card.id}.moveToBoard.${pipeline.id}`}
>
{t("projects.board.contextMenu.moveToBoard", { board: pipeline.name })}
</ContextMenu.ContextItem>
))
: null}
{onDuplicate ? (
<ContextMenu.ContextItem
icon={<FeatherCopy />}
rightSlot={<BadgeShortcut icon={<FeatherCommand />}>D</BadgeShortcut>}
onSelect={() => onDuplicate(card.id)}
data-ui-id={`ui.projects.board.contextMenu.${card.id}.duplicate`}
>
{t("projects.board.contextMenu.duplicate")}
</ContextMenu.ContextItem>
) : null}
{onArchive ? (
<>
<ContextMenu.ContextDivider />
{/* Davids entry says "Löschen". HiveGrid archives instead:
a project carries stage history, files and appointments,
and there is no hard delete behind it. */}
<ContextMenu.ContextItem
className="text-text-feedback-negative hover:bg-surface-feedback-subtle-negative"
icon={<FeatherArchive />}
rightSlot={<BadgeShortcut icon={null}>&#8998;</BadgeShortcut>}
onSelect={() => setPendingArchive(card.id)}
data-ui-id={`ui.projects.board.contextMenu.${card.id}.archive`}
>
{t("projects.board.contextMenu.archive")}
</ContextMenu.ContextItem>
</>
) : null}
</ContextMenu>
</SubframeCore.ContextMenu.Content>
</SubframeCore.ContextMenu.Portal>
</SubframeCore.ContextMenu.Root>
);
}
const boardColumns: SortableKanbanColumn<BoardEntry>[] = visibleColumns.map((column) => ({
id: column.stageId,
label: column.stageName,
name: column.stageName,
price: column.aggregateVisible ? (column.aggregateValue ?? "—") : "—",
badge: <BadgeFeedback farbe="subtle-neutral" size="small">{String(column.projectCount)}</BadgeFeedback>,
sumMode: column.aggregateVisible ? "visible" : "locked",
lockedSumSlot: t("projects.board.sumLocked"),
// No stage tint: Davids S01 draws every column on the same neutral surface,
// and the card already carries the only colour that means something here
// (priority). The stage colour stays the detail view's stage bar.
// A stage column always stays a single card column, however many cards it
// holds — the board scrolls instead of widening a column into a grid.
cards:
column.cards.length > 0
? column.cards
: [{ id: `${PLACEHOLDER_PREFIX}${column.stageId}`, kind: "column-placeholder", stageId: column.stageId, stageName: column.stageName } satisfies ColumnPlaceholder],
}));
return (
<PageShell uiId="ui.projects.board" className="bg-surface-neutral-primary" sseHref={data.sseHref}>
<PageHeader
uiId="ui.projects.board.header"
dense
icon={<FeatherKanbanSquare className={PAGE_HEADER_ICON_CLASS} />}
// The module names the page; which board is being shown is the switcher's
// job, right next to it behind a vertical rule (Davids S01).
title={t("projects.board.headline")}
titleTrailing={
<>
{/* S01 board switcher as a header chip — the control that decides
which board the page shows. */}
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<button
type="button"
className="flex items-center gap-2 rounded-md border border-solid border-border-default bg-surface-neutral-primary px-3 py-1.5 hover:bg-surface-neutral-tertiary"
data-ui-id="ui.projects.board.switcher"
aria-label={t("projects.fields.pipeline")}
>
<FeatherTrendingUp className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
<span className="break-words text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary">
{data.pipelineName}
</span>
<FeatherChevronDown className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
</button>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="start" sideOffset={4} asChild>
<DropdownMenu>
{data.pipelines.map((pipeline) => (
<DropdownMenu.DropdownItem
key={pipeline.id}
icon={pipeline.id === data.pipelineId ? <FeatherCheck /> : null}
onClick={() => props.actions.onSwitchPipeline(pipeline.id)}
data-ui-id={`ui.projects.board.switcher.${pipeline.id}`}
>
{pipeline.name}
</DropdownMenu.DropdownItem>
))}
</DropdownMenu>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
</>
}
actions={
<>
<ToggleGroup
value="board"
onValueChange={(value: string) => value === "list" && props.actions.onShowList()}
data-ui-id="ui.projects.board.viewToggle"
>
<ToggleGroup.Item icon={<FeatherColumns />} value="board" aria-label={t("projects.viewMode.board")} data-ui-id="ui.projects.board.viewToggle.board">
{t("projects.viewMode.board")}
</ToggleGroup.Item>
<ToggleGroup.Item icon={<FeatherList />} value="list" aria-label={t("projects.viewMode.list")} data-ui-id="ui.projects.board.viewToggle.list">
{t("projects.viewMode.list")}
</ToggleGroup.Item>
</ToggleGroup>
{data.canAdmin ? (
<Button
variant="tertiary"
icon={<FeatherSettings2 />}
onClick={props.actions.onManageBoard}
data-ui-id="ui.projects.board.settings"
>
{t("projects.board.contextMenu.settings")}
</Button>
) : null}
{data.canWrite ? (
<Button icon={<FeatherPlus />} onClick={() => setCreateOpen(true)} data-ui-id="ui.projects.board.new">
{t("projects.actions.newProject")}
</Button>
) : null}
</>
}
/>
{/* --- Filter bar (S01): free text + facets + active-filter chips ---
The board switcher moved into the header chip above; search lives in
the bar itself, so the old PageToolbar row is gone. */}
<BoardFilterBar
facets={props.facets}
search={props.q}
onSearch={props.actions.onSearch}
onlyMine={props.onlyMine}
onToggleOnlyMine={props.actions.onToggleOnlyMine}
onToggleFacet={props.actions.onToggleFacet}
onRemoveChip={props.actions.onRemoveChip}
onReset={resetFilters}
periodFrom={props.periodFrom}
periodTo={props.periodTo}
onPeriodRangeChange={props.actions.onPeriodRangeChange}
// Which stages are on screen. It sits behind the rule because it is not
// a filter — it changes nothing about which projects the board holds, so
// it needs no permission and is not persisted. Multi-select, so hiding
// two columns does not mean opening the menu twice.
afterDivider={
<FilterBar.StatusFilterButton
icon={<FeatherColumns />}
label={t("projects.board.columnPicker.label")}
showCount={hiddenColumnCount > 0}
count={hiddenColumnCount > 0 ? String(hiddenColumnCount) : ""}
data-ui-id="ui.projects.board.columnPicker"
dropdown={
<DropdownMenuMultiSelect>
{data.columns.map((column) => (
<DropdownMenuMultiSelect.DropdownItem
key={column.stageId}
showCheckbox
selected={isColumnVisible(column)}
onClick={() =>
setColumnVisibility((current) => ({ ...current, [column.stageId]: !isColumnVisible(column) }))
}
data-ui-id={`ui.projects.board.columnPicker.${column.stageId}`}
>
{column.stageName}
</DropdownMenuMultiSelect.DropdownItem>
))}
</DropdownMenuMultiSelect>
}
/>
}
trailing={
props.showDemoToggle ? (
<Checkbox
checked={props.includeDemoData}
onCheckedChange={props.actions.onToggleDemo}
label={t("onboarding.demoData.showInLists")}
data-ui-id="ui.projects.board.demo"
/>
) : null
}
/>
{props.errorKey ? <div className="w-full px-6 pt-4 mobile:px-4"><BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback></div> : null}
{/* --- Bulk bar --- */}
{data.canChangeStage && someSelected && data.openStages.length > 0 ? (
<div className="flex w-full flex-wrap items-end gap-2 px-6 pt-4 mobile:px-4" data-ui-id="ui.projects.board.bulk">
<Select label={t("projects.board.moveTo")} showLabel value={bulkStage} onValueChange={setBulkStage}>
{data.openStages.map((stage) => (
<Select.Item key={stage.id} value={stage.id}>{stage.name}</Select.Item>
))}
</Select>
<Button
variant="neutral"
size="small"
loading={props.submitting}
onClick={() => {
props.actions.onBulkMove([...selected], bulkStage);
setSelected(new Set());
}}
data-ui-id="ui.projects.board.bulk.apply"
>
{t("projects.board.bulkApply")}
</Button>
</div>
) : null}
{/* --- Empty state (S01a). One block for both cases: an empty board is an
empty board, and a different icon per reason only makes the two look
like different failures. It is a notice above the board, not a
replacement for it — the columns stay, so the board a project would
land in is still visible while the message explains why none is. --- */}
{boardIsEmpty ? (
<div className="w-full px-6 pt-4 mobile:px-3">
<div
className="flex w-full items-center gap-4 rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-4 py-4 mobile:flex-col mobile:items-start"
data-ui-id={filterActive ? "ui.projects.board.emptyFiltered" : "ui.projects.board.empty"}
>
<div className="flex h-10 w-10 flex-none items-center justify-center rounded-md bg-surface-neutral-tertiary">
<FeatherSearchX className="text-body-large font-body-large text-icon-neutral-tertiary" />
</div>
<div className="flex min-w-[0px] grow shrink-0 basis-0 flex-col items-start gap-1">
{/* Same headline either way — the reason belongs in the line below
it, not in two different verdicts about the same empty board. */}
<span className="text-body-default-medium-150 font-body-default-medium-150 text-text-neutral-primary">
{t("projects.board.emptyFiltered.title")}
</span>
<span className={mutedText}>{t(filterActive ? "projects.board.emptyFiltered.body" : "projects.board.emptyHint")}</span>
</div>
<div className="flex items-center gap-2 mobile:w-full mobile:flex-none mobile:flex-col">
{/* Reset only where there is something to reset. */}
{filterActive ? (
<Button
className="mobile:w-full"
variant="tertiary"
size="small"
icon={<FeatherRotateCcw />}
onClick={resetFilters}
data-ui-id="ui.projects.board.emptyFiltered.reset"
>
{t("projects.board.emptyFiltered.reset")}
</Button>
) : null}
{data.canWrite ? (
<Button
className="mobile:w-full"
size="small"
icon={<FeatherPlus />}
onClick={() => setCreateOpen(true)}
data-ui-id={filterActive ? "ui.projects.board.emptyFiltered.create" : "ui.projects.board.empty.create"}
>
{t("projects.board.emptyFiltered.create")}
</Button>
) : null}
</div>
</div>
</div>
) : null}
{/* --- Columns (drag&drop board). They render whether or not the board
holds cards: each column keeps its dashed placeholder, so an empty
board still shows its stages. --- */}
<div className="w-full overflow-x-auto px-6 py-4 mobile:px-3">
<SortableKanbanBoard<BoardEntry>
columns={boardColumns}
renderCard={renderProjectCard}
renderColumnMenu={(column, api) => (
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<button type="button" aria-label={t("projects.board.column.menu")} data-ui-id={`ui.projects.board.column.${column.id}.menu`}>
<FeatherMoreVertical />
</button>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="end" sideOffset={4} asChild>
<DropdownMenu>
<DropdownMenu.DropdownItem
icon={<FeatherChevronsLeft />}
onClick={api.toggleCollapse}
data-ui-id={`ui.projects.board.column.${column.id}.collapse`}
>
{api.collapsed ? t("projects.board.column.expand") : t("projects.board.column.collapse")}
</DropdownMenu.DropdownItem>
{data.canAdmin ? (
<DropdownMenu.DropdownItem
icon={<FeatherSettings2 />}
onClick={props.actions.onManageBoard}
data-ui-id={`ui.projects.board.column.${column.id}.settings`}
>
{t("projects.board.contextMenu.settings")}
</DropdownMenu.DropdownItem>
) : null}
</DropdownMenu>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
)}
getCardLabel={(entry) => (isPlaceholder(entry) ? entry.stageName : entry.projektname)}
// An empty column's placeholder is scenery, not a project.
isCardDraggable={(entry) => !isPlaceholder(entry)}
onCardMove={(cardId, toColumnId) => requestMove(cardId, toColumnId)}
disabled={!data.canChangeStage}
dragHandlePlacement="inline"
errorKey={props.errorKey}
resetToken={resetToken}
data-ui-id="ui.projects.board.columns"
/>
</div>
{/* --- M01 Verloren-Dialog / Gewonnen-Bestätigung --- */}
<Dialog open={pendingMove !== null} onOpenChange={(open) => (open ? null : cancelPending())}>
<Dialog.Content className="p-4" data-ui-id="ui.projects.board.moveDialog">
{/* w-112 like the export, and `items-stretch` (not `items-start`): with
items-start the Select shrank to its content while the TextArea
filled the row, so the two fields ended up different widths. */}
<div className="flex w-full flex-col items-stretch gap-5" style={{ width: 448, maxWidth: "92vw" }}>
<div className="flex w-full items-start justify-between gap-3">
<div className="flex items-start gap-3">
<IconWithBackground
variant={pendingMove?.kind === "verloren" ? "destructive" : "success"}
size="large"
round
icon={pendingMove?.kind === "verloren" ? <FeatherTrendingDown /> : <FeatherTrendingUp />}
/>
<div className="flex flex-col items-start gap-1">
<span className="text-heading-0 font-heading-0 text-text-neutral-primary">
{t(pendingMove?.kind === "verloren" ? "projects.lostDialog.title" : "projects.wonDialog.title")}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t(pendingMove?.kind === "verloren" ? "projects.lostDialog.subtitle" : "projects.wonDialog.body")}
</span>
</div>
</div>
<IconButton variant="tertiary" size="small" icon={<FeatherX />} onClick={cancelPending} data-ui-id="ui.projects.board.moveDialog.close" />
</div>
{pendingMove?.kind === "verloren" ? (
<>
{/* Local kit drift: the cloud export names the error text prop
`message`; the synced Select only has `errorText`. */}
<Select
// `max-w-none`: the kit caps a Select at 320px, which left it
// narrower than the note field right under it.
className="w-full max-w-none"
variant="outline"
showLabel
label={t("projects.lostDialog.reasonLabel")}
placeholder={t("projects.lostDialog.reasonPlaceholder")}
// The error only appears once the user tried to confirm
// without a reason — showing it on open would scold them for
// a form they have not touched yet.
error={lostReasonMissing}
icon={lostReasonMissing ? <FeatherAlertCircle /> : undefined}
errorText={lostReasonMissing ? t("projects.lostDialog.reasonRequired") : undefined}
value={lostReasonId || undefined}
onValueChange={(value) => {
setLostReasonId(value);
setLostReasonMissing(false);
}}
data-ui-id="ui.projects.board.moveDialog.reason"
>
{data.lostReasons.map((reason) => (
<Select.Item key={reason.id} value={reason.id}>{reason.name}</Select.Item>
))}
</Select>
<TextArea className="w-full max-w-none" showLabel label={t("projects.lostDialog.noteLabel")}>
<TextArea.Input
placeholder={t("projects.lostDialog.notePlaceholder")}
value={lostNote}
onChange={(event) => setLostNote(event.target.value)}
data-ui-id="ui.projects.board.moveDialog.note"
/>
</TextArea>
<Alert
className="w-full"
variant="information"
notDismissible
description={t("projects.lostDialog.undoHint")}
textSize="small"
/>
</>
) : null}
<div className="flex w-full items-center justify-end gap-2">
<Button variant="tertiary" onClick={cancelPending}>{t("projects.actions.cancel")}</Button>
<Button
variant={pendingMove?.kind === "verloren" ? "destructive" : undefined}
icon={pendingMove?.kind === "verloren" ? <FeatherX /> : undefined}
loading={props.submitting}
onClick={confirmPending}
data-ui-id="ui.projects.board.moveDialog.confirm"
>
{t(pendingMove?.kind === "verloren" ? "projects.actions.confirmLost" : "projects.actions.confirmWon")}
</Button>
</div>
</div>
</Dialog.Content>
</Dialog>
{/* --- Archive confirm dialog (same Dialog pattern as the won/lost confirm) --- */}
<Dialog open={pendingArchive !== null} onOpenChange={(open) => (open ? null : setPendingArchive(null))}>
<Dialog.Content className="p-6" data-ui-id="ui.projects.board.archiveDialog">
<div className="flex w-full flex-col gap-4" style={{ minWidth: 420 }}>
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{t("projects.archiveDialog.title")}
</span>
<span className={mutedText}>{t("projects.archiveDialog.body")}</span>
<div className="flex justify-end gap-2">
<Button variant="neutral" onClick={() => setPendingArchive(null)}>{t("projects.actions.cancel")}</Button>
<Button
variant="destructive"
loading={props.submitting}
onClick={() => {
if (pendingArchive) props.actions.onArchive?.(pendingArchive);
setPendingArchive(null);
}}
data-ui-id="ui.projects.board.archiveDialog.confirm"
>
{t("projects.actions.archive")}
</Button>
</div>
</div>
</Dialog.Content>
</Dialog>
{/* --- Quick-create dialog (interim-UI shell mirroring TaskNewDialog) --- */}
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
<Dialog.Content className="w-[440px] max-w-[92vw] p-0" data-ui-id="ui.projects.board.createDialog">
<div className="flex w-full flex-col">
<div className="flex w-full items-start justify-between gap-3 border-b border-solid border-border-default bg-surface-neutral-secondary px-6 py-5 mobile:px-4">
<div className="flex flex-col items-start gap-1">
<span className="text-heading- font-heading- text-text-neutral-primary">{t("projects.actions.newProject")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("projects.createDialog.subtitle")}</span>
</div>
<IconButton type="button" variant="ghost" size="small" icon={<FeatherX />} aria-label={t("projects.actions.cancel")} onClick={() => setCreateOpen(false)} />
</div>
<div className="flex w-full flex-col gap-4 px-6 py-5 max-h-[65vh] overflow-y-auto mobile:px-4">
<TextInput label={t("projects.fields.name")} showLabel>
<TextInput.Input autoFocus value={draft.projektname} onChange={(e) => setDraft((d) => ({ ...d, projektname: e.target.value }))} data-ui-id="ui.projects.board.createDialog.name" />
</TextInput>
</div>
<div className="flex w-full items-center justify-end gap-2 border-t border-solid border-border-default bg-surface-neutral-secondary px-6 py-4 mobile:flex-col-reverse mobile:items-stretch mobile:px-4">
<Button type="button" className="mobile:w-full" variant="tertiary" onClick={() => setCreateOpen(false)}>{t("projects.actions.cancel")}</Button>
<Button
className="mobile:w-full"
icon={<FeatherPlus />}
disabled={!draft.projektname.trim()}
loading={props.submitting}
onClick={() => {
props.actions.onCreateProject({ projektname: draft.projektname.trim(), potenziellerAuftragswert: draft.potenziellerAuftragswert.trim() });
setCreateOpen(false);
setDraft({ projektname: "", potenziellerAuftragswert: "" });
}}
data-ui-id="ui.projects.board.createDialog.confirm"
>
{t("projects.actions.create")}
</Button>
</div>
</div>
</Dialog.Content>
</Dialog>
{/* --- M04 pipeline handover. Status-driven: the move hands the payload
back, there is no button that opens this. --- */}
{props.handover && props.actions.onHandover ? (
<PipelineHandoverDialog
key={props.handover.projectId}
open={handoverDismissed !== props.handover.projectId}
vm={props.handover}
submitting={props.submitting}
onOpenChange={(open) => setHandoverDismissed(open ? null : props.handover!.projectId)}
onConfirm={(selection) => {
props.actions.onHandover?.(props.handover!.projectId, props.handover!.fromPipelineId, selection);
setHandoverDismissed(props.handover!.projectId);
}}
/>
) : null}
</PageShell>
);
}
export default PipelineKanbanPage;
@@ -0,0 +1,674 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildPlantafelVM, type PlantafelScreenVM } from "@hivegrid/view-models";
import { PlantafelPage, type PlantafelActionResult, type PlantafelPageProps } from "./PlantafelPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key, i18n: { language: "de" } }),
}));
// Radix scrolls the active option into view when a Select opens; jsdom has no
// such method. Same stub the command-palette test uses.
HTMLElement.prototype.scrollIntoView = HTMLElement.prototype.scrollIntoView ?? vi.fn();
const PROJECT_ID = "rheinmain-shk-v1-project-0315";
const ASSIGNEE_ID = "rheinmain-shk-v1-employee-0049";
function plantafelVM(): PlantafelScreenVM {
return buildPlantafelVM({
entries: [
{
id: "schedule-1",
projektId: PROJECT_ID,
assignedUserId: ASSIGNEE_ID,
title: "Heizungstausch Auenland Gastronomie Frankfurt",
startAt: "2026-07-20T09:00:00.000Z",
endAt: "2026-07-20T12:00:00.000Z",
status: "confirmed",
syncStatus: "synced",
conflicts: [],
},
],
absences: [],
generatedAt: "2026-07-15T11:17:00.000Z",
});
}
/** More rows than fit on one page, so the pager has something to page through. */
function manyEntryVM(count: number): PlantafelScreenVM {
return buildPlantafelVM({
entries: Array.from({ length: count }, (_, index) => ({
id: `schedule-${index + 1}`,
projektId: PROJECT_ID,
assignedUserId: ASSIGNEE_ID,
title: `Einsatz ${String(index + 1).padStart(3, "0")}`,
// One per day so the chronological default gives a stable, readable order.
startAt: new Date(Date.UTC(2026, 6, 20, 7, 0) + index * 24 * 60 * 60 * 1000).toISOString(),
endAt: new Date(Date.UTC(2026, 6, 20, 9, 0) + index * 24 * 60 * 60 * 1000).toISOString(),
status: "planned" as const,
syncStatus: "synced" as const,
conflicts: [],
})),
absences: [],
generatedAt: "2026-07-15T11:17:00.000Z",
});
}
/** Two entries on different days - enough to tell one order from another. */
function twoEntryVM(): PlantafelScreenVM {
return buildPlantafelVM({
entries: [
{
id: "schedule-1",
projektId: PROJECT_ID,
assignedUserId: ASSIGNEE_ID,
title: "Heizungstausch Auenland Gastronomie Frankfurt",
startAt: "2026-07-20T09:00:00.000Z",
endAt: "2026-07-20T12:00:00.000Z",
status: "confirmed",
syncStatus: "synced",
conflicts: [],
},
{
id: "schedule-2",
projektId: PROJECT_ID,
assignedUserId: ASSIGNEE_ID,
title: "Wartung Brennwerttherme",
startAt: "2026-07-22T07:00:00.000Z",
endAt: "2026-07-22T09:00:00.000Z",
status: "planned",
syncStatus: "synced",
conflicts: [],
},
],
absences: [],
generatedAt: "2026-07-15T11:17:00.000Z",
});
}
function pageProps(overrides: Partial<PlantafelPageProps> = {}): PlantafelPageProps {
const onSubmit = vi.fn();
const onProjectSearch = vi.fn();
const onFilterChange = vi.fn();
const onViewChange = vi.fn();
const onAnchorChange = vi.fn();
return {
vm: plantafelVM(),
projectLabels: [{ id: PROJECT_ID, label: "RM-2026-700315 · Heizungstausch Auenland" }],
editableProjectIds: [PROJECT_ID],
projectOptions: [{ id: PROJECT_ID, label: "RM-2026-700315 · Heizungstausch Auenland" }],
projectOptionsHasMore: false,
projectPickerLoading: false,
assigneeOptions: [{ id: ASSIGNEE_ID, label: "Anna Schneider" }],
canWrite: true,
canBulkReassign: false,
filter: { assignedUserId: null, includePast: false, sort: "start_asc" },
view: "table",
// The fixture entry sits on Monday 2026-07-20, so the anchored week contains it.
anchorIso: "2026-07-22",
todayIso: "2026-07-22",
submitting: false,
actions: { onSubmit, onProjectSearch, onFilterChange, onViewChange, onAnchorChange },
...overrides,
};
}
function renderPage(overrides: Partial<PlantafelPageProps> = {}) {
let props = pageProps(overrides);
const view = render(<PlantafelPage {...props} />);
return {
get props() {
return props;
},
rerender(next: Partial<PlantafelPageProps>) {
props = { ...props, ...next };
view.rerender(<PlantafelPage {...props} />);
},
};
}
function byUiId(id: string): HTMLElement {
const element = document.querySelector(`[data-ui-id='${id}']`);
if (!(element instanceof HTMLElement)) throw new Error(`Missing element ${id}`);
return element;
}
describe("PlantafelPage", () => {
it("keeps the schedule table contained and renders a semantic header", () => {
renderPage();
const table = screen.getByRole("table");
expect(table.querySelector("thead tr")).toBeTruthy();
expect(table.querySelector("tbody tr")).toBeTruthy();
expect(byUiId("ui.projects.plantafel.table").className).toContain("min-w-0");
expect(byUiId("ui.projects.plantafel.tableScroll").className).toContain("overflow-x-auto");
});
it("frames the table like the other list screens instead of wrapping it in a card", () => {
renderPage();
const section = byUiId("ui.projects.plantafel.table");
// The heading stays; the surrounding card does not - only the table itself
// keeps a border, exactly as on the forms list.
expect(section.textContent).toContain("projects.plantafel.entriesTitle");
expect(section.className).not.toContain("bg-surface-neutral-primary");
expect(byUiId("ui.projects.plantafel.tableScroll").className).toContain("border-border-default");
});
it("puts the data-freshness line under the table instead of above it", () => {
renderPage();
const stand = byUiId("ui.projects.plantafel.generatedAt");
const table = byUiId("ui.projects.plantafel.tableScroll");
// A detail that is only read after the rows must not push them down.
expect(table.compareDocumentPosition(stand) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(stand.textContent).toContain("projects.plantafel.generatedAt");
});
it("pages an overfull table instead of printing every row at once", () => {
renderPage({ vm: manyEntryVM(30) });
const titles = () => [...document.querySelectorAll("tbody tr td:first-child")].map((cell) => cell.textContent ?? "");
expect(titles()).toHaveLength(25);
expect(titles()[0]).toContain("Einsatz 001");
expect(byUiId("ui.projects.plantafel.pagination.position").textContent).toContain("projects.plantafel.pagination.position");
expect((byUiId("ui.projects.plantafel.pagination.prev") as HTMLButtonElement).disabled).toBe(true);
fireEvent.click(byUiId("ui.projects.plantafel.pagination.next"));
expect(titles()).toHaveLength(5);
expect(titles()[0]).toContain("Einsatz 026");
expect((byUiId("ui.projects.plantafel.pagination.next") as HTMLButtonElement).disabled).toBe(true);
});
it("sends the reader back to page one when the result set is narrowed", () => {
renderPage({ vm: manyEntryVM(30) });
fireEvent.click(byUiId("ui.projects.plantafel.pagination.next"));
fireEvent.change(byUiId("ui.projects.plantafel.filter.search"), { target: { value: "Einsatz 0" } });
// Page two of the old set no longer exists in the narrowed one; landing
// there would look like an empty result.
const titles = [...document.querySelectorAll("tbody tr td:first-child")].map((cell) => cell.textContent ?? "");
expect(titles[0]).toContain("Einsatz 001");
});
it("keeps a single page free of a pager but still dates the table", () => {
renderPage();
expect(document.querySelector("[data-ui-id='ui.projects.plantafel.pagination']")).not.toBeNull();
expect(byUiId("ui.projects.plantafel.pagination.position").textContent).toContain("projects.plantafel.pagination.position");
expect((byUiId("ui.projects.plantafel.pagination.prev") as HTMLButtonElement).disabled).toBe(true);
expect((byUiId("ui.projects.plantafel.pagination.next") as HTMLButtonElement).disabled).toBe(true);
});
it("marks an openable entry with the link colour", () => {
renderPage();
expect(byUiId("ui.projects.plantafel.detail.open.schedule-1").querySelector("span")?.className).toContain("text-text-feedback-link-default");
});
it("selects and clears every selectable row of the page from the header", () => {
renderPage({ vm: twoEntryVM(), canBulkReassign: true });
fireEvent.click(byUiId("ui.projects.plantafel.selectAll"));
// Both rows are in the selection the bulk action would act on.
expect(byUiId("ui.projects.plantafel.select.schedule-1").getAttribute("data-state")).toBe("checked");
expect(byUiId("ui.projects.plantafel.select.schedule-2").getAttribute("data-state")).toBe("checked");
expect(byUiId("ui.projects.plantafel.bulk").textContent).toContain("projects.plantafel.bulkSelected");
fireEvent.click(byUiId("ui.projects.plantafel.selectAll"));
expect(document.querySelector("[data-ui-id='ui.projects.plantafel.bulk']")).toBeNull();
});
it("offers no select-all where no row may be reassigned", () => {
renderPage({ canBulkReassign: true, editableProjectIds: [] });
expect(document.querySelector("[data-ui-id='ui.projects.plantafel.selectAll']")).toBeNull();
});
it("switches to the calendar view through the header toggle", () => {
const page = renderPage();
fireEvent.click(byUiId("ui.projects.plantafel.viewToggle.calendar"));
expect(page.props.actions.onViewChange).toHaveBeenCalledWith("calendar");
});
it("renders the anchored working week from Monday to Sunday and drops the table", () => {
renderPage({ view: "calendar" });
const days = byUiId("ui.projects.plantafel.week").querySelectorAll("[data-date]");
expect([...days].map((day) => day.getAttribute("data-date"))).toEqual([
"2026-07-20",
"2026-07-21",
"2026-07-22",
"2026-07-23",
"2026-07-24",
"2026-07-25",
"2026-07-26",
]);
expect(document.querySelector("table")).toBeNull();
// The Monday entry lands in the Monday column, not somewhere else.
expect(byUiId("ui.projects.plantafel.week.entry.schedule-1").closest("[data-date]")?.getAttribute("data-date")).toBe("2026-07-20");
});
it("navigates whole weeks from the calendar view", () => {
const page = renderPage({ view: "calendar" });
fireEvent.click(byUiId("ui.projects.plantafel.weekNav.next"));
expect(page.props.actions.onAnchorChange).toHaveBeenCalledWith("2026-07-27");
fireEvent.click(byUiId("ui.projects.plantafel.weekNav.previous"));
expect(page.props.actions.onAnchorChange).toHaveBeenCalledWith("2026-07-13");
});
it("offers search and a monteur picker instead of the quick ranges", () => {
const page = renderPage();
expect(document.querySelector('[data-ui-id="ui.projects.plantafel.filter.search"]')).not.toBeNull();
expect(document.querySelector('[data-ui-id="ui.projects.plantafel.filter.assignee"]')).not.toBeNull();
// The old quick-range strip and its checkbox are gone.
expect(document.body.textContent).not.toContain("projects.plantafel.filterToday");
expect(document.body.textContent).not.toContain("projects.plantafel.filterMine");
expect(document.querySelector('[data-ui-id="ui.projects.plantafel.weekNav"]')).toBeNull();
expect(page.props.actions.onFilterChange).not.toHaveBeenCalled();
});
it("offers the past-appointments switch in the table view only", () => {
const page = renderPage();
// The window is a loader concern, so the switch goes back to the route
// instead of filtering rows that were never fetched.
fireEvent.click(byUiId("ui.projects.plantafel.filter.past"));
expect(page.props.actions.onFilterChange).toHaveBeenCalledWith({ assignedUserId: null, includePast: true, sort: "start_asc" });
// Keeps the picked monteur - the two filters must not overwrite each other.
page.rerender({ filter: { assignedUserId: ASSIGNEE_ID, includePast: true, sort: "start_asc" } });
fireEvent.click(byUiId("ui.projects.plantafel.filter.past"));
expect(page.props.actions.onFilterChange).toHaveBeenLastCalledWith({ assignedUserId: ASSIGNEE_ID, includePast: false, sort: "start_asc" });
// The calendar reaches the past by paging back, so it has no switch.
page.rerender({ view: "calendar" });
expect(document.querySelector('[data-ui-id="ui.projects.plantafel.filter.past"]')).toBeNull();
});
it("adds the week navigation only in the calendar view", () => {
renderPage({ view: "calendar" });
expect(document.querySelector('[data-ui-id="ui.projects.plantafel.weekNav"]')).not.toBeNull();
// The monteur picker stays; search and sorting are table controls and go.
expect(document.querySelector('[data-ui-id="ui.projects.plantafel.filter.assignee"]')).not.toBeNull();
expect(document.querySelector('[data-ui-id="ui.projects.plantafel.filter.search"]')).toBeNull();
expect(document.querySelector('[data-ui-id="ui.projects.plantafel.filter.sort"]')).toBeNull();
});
it("puts the sorting button directly behind the monteur facet", () => {
renderPage();
const assignee = byUiId("ui.projects.plantafel.filter.assignee");
const sort = byUiId("ui.projects.plantafel.filter.sort");
// Same row, and nothing of the bar in between - sorting orders exactly the
// rows the monteur facet narrows.
expect(sort.parentElement).toBe(assignee.parentElement);
expect(assignee.nextElementSibling).toBe(sort);
});
it("orders the table rows by the picked sorting", async () => {
const page = renderPage();
const titles = () => [...document.querySelectorAll("tbody tr td:first-child")].map((cell) => cell.textContent ?? "");
// The facet button states the active order without being opened, the same
// way the project list's sort button does.
expect(byUiId("ui.projects.plantafel.filter.sort").textContent).toContain("projects.plantafel.sortOption.start_asc");
fireEvent.keyDown(byUiId("ui.projects.plantafel.filter.sort"), { key: "Enter" });
// The kit's checkbox contributes its own label markup, so match on the
// caption rather than on the whole node text.
expect((await screen.findAllByRole("menuitem")).map((option) => option.textContent)).toEqual([
expect.stringContaining("projects.plantafel.sortOption.start_asc"),
expect.stringContaining("projects.plantafel.sortOption.start_desc"),
expect.stringContaining("projects.plantafel.sortOption.title_asc"),
expect.stringContaining("projects.plantafel.sortOption.assignee_asc"),
]);
fireEvent.click(byUiId("ui.projects.plantafel.filter.sort.title_asc"));
expect(page.props.actions.onFilterChange).toHaveBeenLastCalledWith({ assignedUserId: null, includePast: false, sort: "title_asc" });
page.rerender({ vm: twoEntryVM(), filter: { assignedUserId: null, includePast: false, sort: "start_asc" } });
expect(titles()[0]).toContain("Heizungstausch Auenland Gastronomie Frankfurt");
page.rerender({ filter: { assignedUserId: null, includePast: false, sort: "start_desc" } });
expect(titles()[0]).toContain("Wartung Brennwerttherme");
});
it("narrows the table to the searched appointment, monteur or project", () => {
renderPage();
fireEvent.change(byUiId("ui.projects.plantafel.filter.search"), { target: { value: "schneider" } });
expect(screen.getByText("Heizungstausch Auenland Gastronomie Frankfurt")).toBeTruthy();
// Matches the assignee label too, not just the title.
fireEvent.change(byUiId("ui.projects.plantafel.filter.search"), { target: { value: "anna" } });
expect(screen.getByText("Heizungstausch Auenland Gastronomie Frankfurt")).toBeTruthy();
});
it("says so in Klartext when the search matches nothing, instead of looking empty", () => {
renderPage();
fireEvent.change(byUiId("ui.projects.plantafel.filter.search"), { target: { value: "kabelkanal" } });
expect(document.querySelector("table")).toBeNull();
expect(screen.getByText("projects.plantafel.filterNoMatches")).toBeTruthy();
expect(screen.getByText("projects.plantafel.filterNoMatchesBody")).toBeTruthy();
// The header count follows the filter rather than contradicting the rows.
expect(document.body.textContent).toContain("projects.plantafel.entries");
});
it("does not carry a table search over into the week grid", () => {
const page = renderPage();
fireEvent.change(byUiId("ui.projects.plantafel.filter.search"), { target: { value: "kabelkanal" } });
page.rerender({ view: "calendar" });
// The calendar has no search box, so a leftover term must not silently
// empty the week.
expect(document.querySelector('[data-ui-id="ui.projects.plantafel.filter.search"]')).toBeNull();
expect(document.querySelector('[data-ui-id="ui.projects.plantafel.week.entry.schedule-1"]')).not.toBeNull();
});
it("shows human-readable project and assignee labels instead of raw ids", () => {
renderPage();
expect(screen.getAllByText("RM-2026-700315 · Heizungstausch Auenland").length).toBeGreaterThan(0);
expect(screen.getAllByText("Anna Schneider").length).toBeGreaterThan(0);
expect(document.body.textContent).not.toContain(PROJECT_ID);
expect(document.body.textContent).not.toContain(ASSIGNEE_ID);
});
it("creates an appointment from the preserved form", () => {
const page = renderPage();
fireEvent.click(byUiId("ui.projects.plantafel.new"));
expect(screen.getByRole("dialog", { name: "projects.plantafel.newEntry" })).toBeTruthy();
expect(byUiId("ui.projects.plantafel.createDialog").className).toContain("min-w-0");
fireEvent.change(byUiId("ui.projects.plantafel.createDialog.title"), { target: { value: "Wartung" } });
fireEvent.change(byUiId("ui.projects.plantafel.createDialog.start"), { target: { value: "2026-07-21T09:00" } });
fireEvent.change(byUiId("ui.projects.plantafel.createDialog.end"), { target: { value: "2026-07-21T11:00" } });
fireEvent.click(byUiId("ui.projects.plantafel.createDialog.confirm"));
expect(page.props.actions.onSubmit).toHaveBeenCalledWith(
"upsertSchedule",
expect.objectContaining({
projektId: PROJECT_ID,
assignedUserId: ASSIGNEE_ID,
title: "Wartung",
startAt: "2026-07-21T09:00",
endAt: "2026-07-21T11:00",
status: "planned",
conflictOverrideReason: "",
clientMutationId: expect.any(String),
}),
);
expect(byUiId("ui.projects.plantafel.createDialog.start").getAttribute("type")).toBe("datetime-local");
expect(byUiId("ui.projects.plantafel.createDialog.end").getAttribute("type")).toBe("datetime-local");
expect(screen.getByRole("combobox", { name: "projects.plantafel.fields.project" })).toBeTruthy();
expect(screen.getByRole("combobox", { name: "projects.plantafel.fields.assignee" })).toBeTruthy();
expect(screen.getByRole("dialog", { name: "projects.plantafel.newEntry" })).toBeTruthy();
});
it("changes an appointment status from the status flyout in one pick", async () => {
const page = renderPage();
// The badge itself opens the flyout - no separate save button any more.
// Radix opens on keyboard/pointerdown, so drive it the way the leads test does.
fireEvent.keyDown(byUiId("ui.projects.plantafel.status.schedule-1"), { key: "Enter" });
await waitFor(() => byUiId("ui.projects.plantafel.status.schedule-1.done"));
fireEvent.click(byUiId("ui.projects.plantafel.status.schedule-1.done"));
expect(page.props.actions.onSubmit).toHaveBeenCalledWith("updateStatus", {
entryId: "schedule-1",
status: "done",
});
});
it("does not resubmit when the already active status is picked", async () => {
const page = renderPage();
fireEvent.keyDown(byUiId("ui.projects.plantafel.status.schedule-1"), { key: "Enter" });
await waitFor(() => byUiId("ui.projects.plantafel.status.schedule-1.confirmed"));
fireEvent.click(byUiId("ui.projects.plantafel.status.schedule-1.confirmed"));
expect(page.props.actions.onSubmit).not.toHaveBeenCalled();
});
it("drops the separate save-status column from the table", () => {
renderPage();
const headers = [...document.querySelectorAll("thead th")].map((cell) => cell.textContent);
expect(headers).not.toContain("projects.actions.updateStatus");
expect(document.body.textContent).not.toContain("projects.plantafel.readOnly");
});
it("keeps the existing offline sync bridge available", () => {
const page = renderPage();
fireEvent.click(byUiId("ui.projects.plantafel.offline.submit"));
expect(page.props.actions.onSubmit).toHaveBeenCalledWith("offlineSync", {
clientMutationId: "",
operation: "schedule_upsert",
payload: "{}",
});
});
it("hides schedule write actions for read-only users", () => {
renderPage({ canWrite: false, projectOptions: [] });
expect(document.querySelector('[data-ui-id="ui.projects.plantafel.new"]')).toBeNull();
expect(document.querySelector('[data-ui-id="ui.projects.plantafel.status.schedule-1"]')).toBeNull();
expect(document.querySelector('[data-ui-id="ui.projects.plantafel.createDialog"]')).toBeNull();
expect(document.querySelector('[data-ui-id="ui.projects.plantafel.offline"]')).not.toBeNull();
});
it("hides a status control when a project is visible but not editable", () => {
renderPage({ editableProjectIds: [] });
expect(screen.getByText("Heizungstausch Auenland Gastronomie Frankfurt")).toBeTruthy();
expect(document.querySelector('[data-ui-id="ui.projects.plantafel.status.schedule-1"]')).toBeNull();
});
it("searches editable projects and makes a truncated result explicit", () => {
const page = renderPage({ projectOptionsHasMore: true });
fireEvent.click(byUiId("ui.projects.plantafel.new"));
fireEvent.change(byUiId("ui.projects.plantafel.createDialog.projectSearch"), { target: { value: "wärme" } });
fireEvent.click(byUiId("ui.projects.plantafel.createDialog.projectSearchSubmit"));
expect(page.props.actions.onProjectSearch).toHaveBeenCalledWith("wärme");
expect((byUiId("ui.projects.plantafel.createDialog.projectSearchSubmit") as HTMLButtonElement).disabled).toBe(true);
page.rerender({ projectPickerLoading: true });
page.rerender({ projectPickerLoading: false });
expect(screen.getByText("projects.plantafel.projectPickerLimited")).toBeTruthy();
});
it("deduplicates rapid create clicks and cannot close while the request is pending", () => {
const page = renderPage();
fireEvent.click(byUiId("ui.projects.plantafel.new"));
fireEvent.change(byUiId("ui.projects.plantafel.createDialog.title"), { target: { value: "Wartung" } });
fireEvent.change(byUiId("ui.projects.plantafel.createDialog.start"), { target: { value: "2026-07-21T09:00" } });
fireEvent.change(byUiId("ui.projects.plantafel.createDialog.end"), { target: { value: "2026-07-21T11:00" } });
const confirm = byUiId("ui.projects.plantafel.createDialog.confirm");
fireEvent.click(confirm);
fireEvent.click(confirm);
fireEvent.click(byUiId("ui.projects.plantafel.createDialog.cancel"));
expect(page.props.actions.onSubmit).toHaveBeenCalledTimes(1);
expect((confirm as HTMLButtonElement).disabled).toBe(true);
expect((byUiId("ui.projects.plantafel.createDialog.cancel") as HTMLButtonElement).disabled).toBe(true);
expect(screen.getByRole("dialog", { name: "projects.plantafel.newEntry" })).toBeTruthy();
});
it("keeps the dialog open on a blocking conflict and resubmits with a clear override reason", async () => {
const page = renderPage();
fireEvent.click(byUiId("ui.projects.plantafel.new"));
fireEvent.change(byUiId("ui.projects.plantafel.createDialog.title"), { target: { value: "Wartung" } });
fireEvent.change(byUiId("ui.projects.plantafel.createDialog.start"), { target: { value: "2026-07-21T09:00" } });
fireEvent.change(byUiId("ui.projects.plantafel.createDialog.end"), { target: { value: "2026-07-21T11:00" } });
fireEvent.click(byUiId("ui.projects.plantafel.createDialog.confirm"));
const firstMutationId = (page.props.actions.onSubmit as ReturnType<typeof vi.fn>).mock.calls[0]?.[1]?.clientMutationId;
const conflictResult: PlantafelActionResult = {
intent: "upsertSchedule",
error: "projects.error.scheduleConflictOverrideRequired",
};
page.rerender({ actionResult: conflictResult });
expect(screen.getByRole("dialog", { name: "projects.plantafel.newEntry" })).toBeTruthy();
expect(screen.getByRole("alert").textContent).toContain("projects.error.scheduleConflictOverrideRequired");
const overrideReason = byUiId("ui.projects.plantafel.createDialog.conflictOverrideReason");
fireEvent.change(overrideReason, { target: { value: "Kunde hat den Termin ausdrücklich bestätigt." } });
fireEvent.click(byUiId("ui.projects.plantafel.createDialog.confirm"));
expect(page.props.actions.onSubmit).toHaveBeenLastCalledWith(
"upsertSchedule",
expect.objectContaining({
conflictOverrideReason: "Kunde hat den Termin ausdrücklich bestätigt.",
clientMutationId: firstMutationId,
}),
);
page.rerender({ actionResult: { intent: "upsertSchedule", ok: true } });
await waitFor(() => expect(screen.queryByRole("dialog", { name: "projects.plantafel.newEntry" })).toBeNull());
});
it("reads the loaded monteur filter back off the facet button and clears it again", async () => {
// Same read/write contract the leads filters follow: what the loader
// resolved has to be visible on the trigger, otherwise a shared link looks
// unfiltered.
const page = renderPage({ filter: { assignedUserId: null, includePast: false, sort: "start_asc" } });
const trigger = () => byUiId("ui.projects.plantafel.filter.assignee");
expect(trigger().textContent).toContain("projects.plantafel.filterAssignee");
page.rerender({ filter: { assignedUserId: ASSIGNEE_ID, includePast: false, sort: "start_asc" } });
await waitFor(() => expect(trigger().textContent).toContain("Anna Schneider"));
// Every assignable monteur is offered, and picking the active one again is
// the way back to "all" - the chip's X does the same.
fireEvent.keyDown(trigger(), { key: "Enter" });
const options = await screen.findAllByRole("menuitem");
expect(options.map((option) => option.textContent)).toEqual([expect.stringContaining("Anna Schneider")]);
fireEvent.click(byUiId("ui.projects.plantafel.filter.assignee.rheinmain-shk-v1-employee-0049"));
expect(page.props.actions.onFilterChange).toHaveBeenLastCalledWith({ assignedUserId: null, includePast: false, sort: "start_asc" });
});
it("resets search and the loader filters through the bar's reset pill", () => {
const page = renderPage({ filter: { assignedUserId: ASSIGNEE_ID, includePast: true, sort: "title_asc" } });
fireEvent.change(byUiId("ui.projects.plantafel.filter.search"), { target: { value: "kabelkanal" } });
fireEvent.click(screen.getByText("projects.plantafel.filterReset"));
expect(page.props.actions.onFilterChange).toHaveBeenLastCalledWith({ assignedUserId: null, includePast: false, sort: "start_asc" });
expect((byUiId("ui.projects.plantafel.filter.search") as HTMLInputElement).value).toBe("");
});
it("bulk-reassigns selected entries with the picked assignee", async () => {
const page = renderPage({ canBulkReassign: true });
fireEvent.click(byUiId("ui.projects.plantafel.select.schedule-1"));
expect(byUiId("ui.projects.plantafel.bulk")).toBeTruthy();
fireEvent.click(byUiId("ui.projects.plantafel.bulk.submit"));
expect(page.props.actions.onSubmit).toHaveBeenLastCalledWith(
"bulkReassign",
expect.objectContaining({ assignedUserId: ASSIGNEE_ID }),
);
const fields = (page.props.actions.onSubmit as ReturnType<typeof vi.fn>).mock.lastCall?.[1] as Record<string, string>;
expect(JSON.parse(fields.entryIds)).toEqual(["schedule-1"]);
page.rerender({ actionResult: { intent: "bulkReassign", ok: true } });
await waitFor(() => expect(document.querySelector("[data-ui-id='ui.projects.plantafel.bulk']")).toBeNull());
});
it("opens the details read-only on a double-click in the table", () => {
renderPage();
fireEvent.doubleClick(screen.getByRole("table").querySelector("tbody tr")!);
// Read-only means: the stored values, no form, and no way to save yet.
expect(byUiId("ui.projects.plantafel.detailDialog.readOnly").textContent).toContain("Anna Schneider");
expect(document.querySelector("[data-ui-id='ui.projects.plantafel.detailDialog.save']")).toBeNull();
expect(byUiId("ui.projects.plantafel.detailDialog.close")).toBeTruthy();
});
it("opens the same popup from a calendar block, for mouse and keyboard alike", () => {
renderPage({ view: "calendar" });
const block = byUiId("ui.projects.plantafel.week.entry.schedule-1");
fireEvent.keyDown(block, { key: "Enter" });
expect(byUiId("ui.projects.plantafel.detailDialog")).toBeTruthy();
fireEvent.click(byUiId("ui.projects.plantafel.detailDialog.close"));
fireEvent.doubleClick(block);
expect(byUiId("ui.projects.plantafel.detailDialog")).toBeTruthy();
});
it("swaps the close button for save only after editing is switched on", () => {
renderPage();
fireEvent.click(byUiId("ui.projects.plantafel.detail.open.schedule-1"));
fireEvent.click(byUiId("ui.projects.plantafel.detailDialog.edit"));
expect(byUiId("ui.projects.plantafel.detailDialog.save")).toBeTruthy();
expect(document.querySelector("[data-ui-id='ui.projects.plantafel.detailDialog.close']")).toBeNull();
// The edit button has done its job and gives its place to the form.
expect(document.querySelector("[data-ui-id='ui.projects.plantafel.detailDialog.edit']")).toBeNull();
});
it("prefills the form from the stored entry and saves it back under its own id", () => {
const page = renderPage();
fireEvent.click(byUiId("ui.projects.plantafel.detail.open.schedule-1"));
fireEvent.click(byUiId("ui.projects.plantafel.detailDialog.edit"));
const title = byUiId("ui.projects.plantafel.detailDialog.title") as HTMLInputElement;
expect(title.value).toBe("Heizungstausch Auenland Gastronomie Frankfurt");
// 09:00Z in July is 11:00 in Berlin - the form shows the local wall clock.
expect((byUiId("ui.projects.plantafel.detailDialog.start") as HTMLInputElement).value).toBe("2026-07-20T11:00");
fireEvent.change(title, { target: { value: "Heizungstausch Auenland (verschoben)" } });
fireEvent.click(byUiId("ui.projects.plantafel.detailDialog.save"));
expect(page.props.actions.onSubmit).toHaveBeenLastCalledWith(
"upsertSchedule",
expect.objectContaining({
entryId: "schedule-1",
title: "Heizungstausch Auenland (verschoben)",
startAt: "2026-07-20T11:00",
endAt: "2026-07-20T14:00",
status: "confirmed",
}),
);
});
it("closes the popup once the save came back green", async () => {
const page = renderPage();
fireEvent.click(byUiId("ui.projects.plantafel.detail.open.schedule-1"));
fireEvent.click(byUiId("ui.projects.plantafel.detailDialog.edit"));
fireEvent.click(byUiId("ui.projects.plantafel.detailDialog.save"));
page.rerender({ actionResult: { intent: "upsertSchedule", ok: true } });
await waitFor(() => expect(document.querySelector("[data-ui-id='ui.projects.plantafel.detailDialog']")).toBeNull());
});
it("keeps the popup read-only for an entry the user may not edit", () => {
renderPage({ editableProjectIds: [] });
fireEvent.click(byUiId("ui.projects.plantafel.detail.open.schedule-1"));
expect(byUiId("ui.projects.plantafel.detailDialog")).toBeTruthy();
expect(document.querySelector("[data-ui-id='ui.projects.plantafel.detailDialog.edit']")).toBeNull();
});
});
@@ -0,0 +1,74 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildProjectSubAreasVM, type ProjectSignaturePanelVM } from "@hivegrid/view-models";
import { ProjectSubAreasPanel } from "./ProjectSubAreasPanel";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key, i18n: { language: "de" } }),
}));
const signature: ProjectSignaturePanelVM = { status: "empty" };
function renderPanel() {
const vm = buildProjectSubAreasVM(
{
project: { id: "p1", projektNummer: "P-1", projektname: "Dach Nord" },
members: [],
appointments: [],
invoices: [
{
id: "r1",
rechnungsnummer: "R-1",
betrag: "2500.00",
status: "gestellt",
datum: "2026-07-15T10:00:00.000Z",
faelligAm: null,
dateiId: null,
},
],
checklists: [],
materials: [
{
id: "material-1",
positionNumber: "01.01",
text: "Ventil",
longText: "DN 20",
quantity: "2",
unit: "Stk",
unitPrice: "12.50",
totalPrice: "25.00",
lastSyncedAt: "2026-07-16T10:00:00.000Z",
},
],
stageConfig: null,
openDefects: 0,
},
{ acceptanceHref: "/acme/projects/p1/acceptance" }
);
render(<ProjectSubAreasPanel vm={vm} signature={signature} submitting={false} actions={{ onSubmit: vi.fn() }} />);
}
describe("ProjectSubAreasPanel", () => {
it("formats invoice amounts as euros and keeps the input raw", () => {
renderPanel();
fireEvent.click(screen.getByText("projects.subAreas.invoices"));
expect((document.body.textContent ?? "").replace(/[\u00a0\u202f]/g, " ")).toContain("2.500,00 €");
const amountInput = document.querySelector('input[type="number"]') as HTMLInputElement;
fireEvent.change(amountInput, { target: { value: "2500.00" } });
expect(amountInput.value).toBe("2500.00");
});
it("shows synchronized KWP material positions read-only", () => {
renderPanel();
fireEvent.click(screen.getByText("projects.subAreas.materials"));
expect(screen.getByText("01.01")).toBeTruthy();
expect(screen.getByText("Ventil")).toBeTruthy();
expect(screen.getByText("DN 20")).toBeTruthy();
expect((document.body.textContent ?? "").replace(/[\u00a0\u202f]/g, " ")).toContain("25,00 €");
expect(screen.queryByRole("button", { name: /save|speichern/iu })).toBeNull();
});
});
@@ -0,0 +1,504 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { fileTypeLabelKey } from "~/utils/files/fileTypeLabel";
import type { ProjectSignaturePanelVM, ProjectSubAreasScreenVM } from "@hivegrid/view-models";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { ButtonGroup } from "~/ui/components/ButtonGroup";
import { Card } from "~/ui/components/Card";
import { EmptyState } from "~/ui/components/EmptyState";
import { Select } from "~/ui/components/Select";
import { Table } from "~/ui/components/Table";
import { Tabs } from "~/ui/components/Tabs";
import { TextInput } from "~/ui/components/TextInput";
import { APP_TIME_ZONE } from "~/locale/format";
import { ProjectSignaturePanel } from "~/components/screens/signature/ProjectSignaturePanel";
import { AppLink } from "~/components/app/AppLink";
export type ProjectOperationSubmit = (intent: string, fields?: Record<string, string>) => void;
export type ProjectSubAreasPanelProps = {
vm: ProjectSubAreasScreenVM;
signature: ProjectSignaturePanelVM;
submitting: boolean;
errorKey?: string | null;
/** User picker options for the member add form (route supplies the tenant directory). */
userOptions?: readonly { id: string; label: string }[];
actions: {
onSubmit: ProjectOperationSubmit;
onOpenChat: (href: string) => void;
/** Chunked PDF upload for the signature wizard (injected by the route). */
uploadPdf?: (file: File) => Promise<{ id: string; displayName: string }>;
};
};
type SubAreaTab = "members" | "appointments" | "invoices" | "checklists" | "tasks" | "materials" | "documents";
const DATETIME_INPUT_TYPE = "datetime-local" as unknown as "text";
const DATE_INPUT_TYPE = "date" as unknown as "text";
const mutedText = "text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary";
const headingText = "text-body-large-0 font-body-large-0 text-text-neutral-primary";
function formatDateTime(value: string | null, language: string): string {
if (!value) return "—";
return new Intl.DateTimeFormat(language, { timeZone: APP_TIME_ZONE, dateStyle: "medium", timeStyle: "short" }).format(new Date(value));
}
function formatDate(value: string | null, language: string): string {
if (!value) return "—";
return new Intl.DateTimeFormat(language, { timeZone: APP_TIME_ZONE, dateStyle: "medium" }).format(new Date(value));
}
function submitFields(submit: ProjectOperationSubmit, intent: string, fields: Record<string, string>) {
submit(intent, fields);
}
export function ProjectSubAreasPanel(props: ProjectSubAreasPanelProps) {
const { t, i18n } = useTranslation();
const submit = props.actions.onSubmit;
const [member, setMember] = useState({ principalType: "user", userId: "", groupId: "", rolle: "monteur" });
const [taskDraft, setTaskDraft] = useState("");
const [appointment, setAppointment] = useState({ titel: "", startAt: "", endAt: "", assignedToUserId: "" });
const [invoice, setInvoice] = useState({ betrag: "", datum: "", faelligAm: "", dateiId: "" });
const [checklist, setChecklist] = useState({ titel: "", typ: "generisch" });
const [itemDrafts, setItemDrafts] = useState<Record<string, string>>({});
const [invoiceStatuses, setInvoiceStatuses] = useState<Record<string, string>>({});
const [activeTab, setActiveTab] = useState<SubAreaTab>("members");
if (props.vm.status !== "ready") return null;
const data = props.vm.data;
return (
<div className="flex flex-col gap-6" data-ui-id="ui.projects.operations">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex flex-col gap-1">
<span className={headingText}>{t("projects.operations.title")}</span>
<span className={mutedText}>{data.projectNumber} · {data.projectName}</span>
</div>
<AppLink href={data.acceptanceHref} className="text-body-default-medium-0 font-body-default-medium-0 text-brand-brand-text-default hover:underline" data-ui-id="ui.projects.operations.acceptance-link">
{t("projects.actions.openAcceptance")}
</AppLink>
</div>
{props.errorKey ? <BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback> : null}
{data.requiresAcceptanceProtocol ? <BadgeFeedback farbe="subtle-warning">{t("projects.operations.acceptanceRequired")}</BadgeFeedback> : null}
{data.openDefects > 0 ? <BadgeFeedback farbe="subtle-warning">{t("projects.subAreas.openDefects", { count: data.openDefects })}</BadgeFeedback> : null}
{data.chat ? (
<Card data-ui-id="ui.projects.operations.chat">
<ButtonGroup align="space-between">
<ButtonGroup align="stack">
<span className={headingText}>{t("projects.chat.title")}</span>
<span className={mutedText}>{t(data.chat.isArchived ? "projects.chat.archived" : data.chat.canWrite ? "projects.chat.active" : "projects.chat.readOnly")}</span>
</ButtonGroup>
<Button variant="tertiary" onClick={() => props.actions.onOpenChat(data.chat!.href)}>
{t("projects.actions.openChat")}
</Button>
</ButtonGroup>
</Card>
) : null}
<ProjectSignaturePanel
vm={props.signature}
submitting={props.submitting}
errorKey={props.errorKey?.startsWith("signature.") ? props.errorKey : null}
actions={{ onSubmit: submit, uploadPdf: props.actions.uploadPdf }}
/>
<Tabs data-ui-id="ui.projects.operations.tabs">
<Tabs.Item active={activeTab === "members"} onClick={() => setActiveTab("members")} role="tab" aria-selected={activeTab === "members"}>
{t("projects.subAreas.members")}
</Tabs.Item>
<Tabs.Item
active={activeTab === "appointments"}
onClick={() => setActiveTab("appointments")}
role="tab"
aria-selected={activeTab === "appointments"}
>
{t("projects.subAreas.appointments")}
</Tabs.Item>
<Tabs.Item active={activeTab === "invoices"} onClick={() => setActiveTab("invoices")} role="tab" aria-selected={activeTab === "invoices"}>
{t("projects.subAreas.invoices")}
</Tabs.Item>
<Tabs.Item
active={activeTab === "checklists"}
onClick={() => setActiveTab("checklists")}
role="tab"
aria-selected={activeTab === "checklists"}
>
{t("projects.subAreas.checklists")}
</Tabs.Item>
<Tabs.Item active={activeTab === "tasks"} onClick={() => setActiveTab("tasks")} role="tab" aria-selected={activeTab === "tasks"}>
{t("projects.subAreas.tasks")}
</Tabs.Item>
<Tabs.Item active={activeTab === "materials"} onClick={() => setActiveTab("materials")} role="tab" aria-selected={activeTab === "materials"}>
{t("projects.subAreas.materials")}
</Tabs.Item>
<Tabs.Item active={activeTab === "documents"} onClick={() => setActiveTab("documents")} role="tab" aria-selected={activeTab === "documents"}>
{t("projects.subAreas.documents")}
</Tabs.Item>
</Tabs>
{activeTab === "members" ? (
<div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]">
<Card data-ui-id="ui.projects.operations.members">
<span className={headingText}>{t("projects.subAreas.members")}</span>
{data.members.length === 0 ? (
<EmptyState outlined title={t("projects.empty.members.title")} body={t("projects.empty.members.body")} />
) : (
<Table>
<Table.HeaderRow>
<Table.HeaderCell>{t("projects.fields.userId")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.role")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.actions")}</Table.HeaderCell>
</Table.HeaderRow>
{data.members.map((row) => (
<Table.Row key={row.id}>
<Table.Cell>{row.principal === "projects.fields.none" ? t(row.principal) : row.principal}</Table.Cell>
<Table.Cell><BadgeFeedback farbe="subtle-neutral">{t(row.roleLabelKey)}</BadgeFeedback></Table.Cell>
<Table.Cell>
<Button
size="small"
variant="ghost"
loading={props.submitting}
onClick={() => submitFields(submit, "removeMember", { memberId: row.id })}
>
{t("projects.actions.removeMember")}
</Button>
</Table.Cell>
</Table.Row>
))}
</Table>
)}
</Card>
<Card data-ui-id="ui.projects.operations.members.form">
<span className={headingText}>{t("projects.actions.addMember")}</span>
<Select
showLabel
label={t("projects.fields.principalType")}
value={member.principalType}
onValueChange={(principalType) => setMember((current) => ({ ...current, principalType, userId: "", groupId: "" }))}
className="max-w-none"
>
<Select.Item value="user">{t("projects.fields.principalUser")}</Select.Item>
<Select.Item value="group">{t("projects.fields.principalGroup")}</Select.Item>
</Select>
{member.principalType === "group" ? (
data.groupOptions.length > 0 ? (
<Select
showLabel
label={t("projects.fields.groupId")}
value={member.groupId}
onValueChange={(groupId) => setMember((current) => ({ ...current, groupId }))}
className="max-w-none"
>
{data.groupOptions.map((group) => (
<Select.Item key={group.id} value={group.id}>{group.name}</Select.Item>
))}
</Select>
) : (
<span className={mutedText}>{t("projects.empty.groups.body")}</span>
)
) : props.userOptions && props.userOptions.length > 0 ? (
<Select
showLabel
label={t("projects.fields.userId")}
value={member.userId}
onValueChange={(userId) => setMember((current) => ({ ...current, userId }))}
className="max-w-none"
>
{props.userOptions.map((user) => (
<Select.Item key={user.id} value={user.id}>{user.label}</Select.Item>
))}
</Select>
) : (
<TextInput showLabel label={t("projects.fields.userId")} className="max-w-none">
<TextInput.Input value={member.userId} onChange={(event) => setMember((current) => ({ ...current, userId: event.target.value }))} />
</TextInput>
)}
<Select showLabel label={t("projects.fields.role")} value={member.rolle} onValueChange={(rolle) => setMember((current) => ({ ...current, rolle }))} className="max-w-none">
{["monteur", "projektleiter", "zustaendig", "beobachter"].map((role) => <Select.Item key={role} value={role}>{t(`projects.roles.${role}`)}</Select.Item>)}
</Select>
<Button
loading={props.submitting}
disabled={member.principalType === "group" ? !member.groupId : !member.userId}
onClick={() =>
submitFields(
submit,
"addMember",
member.principalType === "group" ? { groupId: member.groupId, rolle: member.rolle } : { userId: member.userId, rolle: member.rolle }
)
}
>
{t("projects.actions.addMember")}
</Button>
</Card>
</div>
) : null}
{activeTab === "appointments" ? (
<div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]">
<Card data-ui-id="ui.projects.operations.appointments">
<span className={headingText}>{t("projects.subAreas.appointments")}</span>
{data.appointments.length === 0 ? (
<EmptyState outlined title={t("projects.empty.appointments.title")} body={t("projects.empty.appointments.body")} />
) : (
<Table>
<Table.HeaderRow>
<Table.HeaderCell>{t("projects.fields.appointmentTitle")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.owner")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.startDate")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.stage")}</Table.HeaderCell>
</Table.HeaderRow>
{data.appointments.map((row) => (
<Table.Row key={row.id}>
<Table.Cell>{row.title}</Table.Cell>
<Table.Cell>{row.assignee === "projects.fields.none" ? t(row.assignee) : row.assignee}</Table.Cell>
<Table.Cell>{formatDateTime(row.startAtIso, i18n.language)}</Table.Cell>
<Table.Cell><BadgeFeedback farbe="subtle-information">{t(row.statusLabelKey)}</BadgeFeedback></Table.Cell>
</Table.Row>
))}
</Table>
)}
</Card>
<Card data-ui-id="ui.projects.operations.appointments.form">
<span className={headingText}>{t("projects.actions.createAppointment")}</span>
<TextInput showLabel label={t("projects.fields.appointmentTitle")} className="max-w-none">
<TextInput.Input value={appointment.titel} onChange={(event) => setAppointment((current) => ({ ...current, titel: event.target.value }))} />
</TextInput>
<TextInput showLabel label={t("projects.fields.userId")} className="max-w-none">
<TextInput.Input value={appointment.assignedToUserId} onChange={(event) => setAppointment((current) => ({ ...current, assignedToUserId: event.target.value }))} />
</TextInput>
<TextInput showLabel label={t("projects.fields.startDate")} className="max-w-none">
<TextInput.Input type={DATETIME_INPUT_TYPE} value={appointment.startAt} onChange={(event) => setAppointment((current) => ({ ...current, startAt: event.target.value }))} />
</TextInput>
<TextInput showLabel label={t("projects.fields.deadline")} className="max-w-none">
<TextInput.Input type={DATETIME_INPUT_TYPE} value={appointment.endAt} onChange={(event) => setAppointment((current) => ({ ...current, endAt: event.target.value }))} />
</TextInput>
<Button loading={props.submitting} onClick={() => submitFields(submit, "createAppointment", appointment)}>{t("projects.actions.createAppointment")}</Button>
</Card>
</div>
) : null}
{activeTab === "invoices" ? (
<div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]">
<Card data-ui-id="ui.projects.operations.invoices">
<span className={headingText}>{t("projects.subAreas.invoices")}</span>
{data.invoices.length === 0 ? (
<EmptyState outlined title={t("projects.empty.invoices.title")} body={t("projects.empty.invoices.body")} />
) : (
<Table>
<Table.HeaderRow>
<Table.HeaderCell>{t("projects.fields.number")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.amount")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.stage")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.deadline")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.actions.updateStatus")}</Table.HeaderCell>
</Table.HeaderRow>
{data.invoices.map((row) => (
<Table.Row key={row.id}>
<Table.Cell>{row.number}</Table.Cell>
<Table.Cell>{row.amount}</Table.Cell>
<Table.Cell><BadgeFeedback farbe={row.status === "bezahlt" ? "subtle-positive" : "subtle-neutral"}>{t(row.statusLabelKey)}</BadgeFeedback></Table.Cell>
<Table.Cell>{formatDate(row.dueAtIso, i18n.language)}</Table.Cell>
<Table.Cell>
<div className="flex flex-wrap items-center gap-2">
<Select value={invoiceStatuses[row.id] ?? row.status} onValueChange={(status) => setInvoiceStatuses((current) => ({ ...current, [row.id]: status }))} className="max-w-[180px]">
{["entwurf", "gestellt", "bezahlt", "storniert"].map((status) => <Select.Item key={status} value={status}>{t(`projects.invoiceStatus.${status}`)}</Select.Item>)}
</Select>
<Button variant="tertiary" size="small" loading={props.submitting} onClick={() => submit("updateInvoiceStatus", { invoiceId: row.id, status: invoiceStatuses[row.id] ?? row.status })}>
{t("projects.actions.save")}
</Button>
</div>
</Table.Cell>
</Table.Row>
))}
</Table>
)}
</Card>
<Card data-ui-id="ui.projects.operations.invoices.form">
<span className={headingText}>{t("projects.actions.createInvoice")}</span>
<TextInput showLabel label={t("projects.fields.amount")} className="max-w-none">
<TextInput.Input type="number" value={invoice.betrag} onChange={(event) => setInvoice((current) => ({ ...current, betrag: event.target.value }))} />
</TextInput>
<TextInput showLabel label={t("projects.fields.startDate")} className="max-w-none">
<TextInput.Input type={DATE_INPUT_TYPE} value={invoice.datum} onChange={(event) => setInvoice((current) => ({ ...current, datum: event.target.value }))} />
</TextInput>
<TextInput showLabel label={t("projects.fields.deadline")} className="max-w-none">
<TextInput.Input type={DATE_INPUT_TYPE} value={invoice.faelligAm} onChange={(event) => setInvoice((current) => ({ ...current, faelligAm: event.target.value }))} />
</TextInput>
<TextInput showLabel label={t("projects.fields.fileId")} className="max-w-none">
<TextInput.Input value={invoice.dateiId} onChange={(event) => setInvoice((current) => ({ ...current, dateiId: event.target.value }))} />
</TextInput>
<Button loading={props.submitting} onClick={() => submitFields(submit, "createInvoice", invoice)}>{t("projects.actions.createInvoice")}</Button>
</Card>
</div>
) : null}
{activeTab === "checklists" ? (
<div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]">
<Card data-ui-id="ui.projects.operations.checklists">
<span className={headingText}>{t("projects.subAreas.checklists")}</span>
{data.checklists.length === 0 ? (
<EmptyState outlined title={t("projects.empty.checklists.title")} body={t("projects.empty.checklists.body")} />
) : (
<div className="flex flex-col gap-4">
{data.checklists.map((row) => (
<div key={row.id} className="flex flex-col gap-3 rounded-md border border-solid border-border-default p-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex flex-col gap-1">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{row.title}</span>
<span className={mutedText}>{row.itemCount} · {row.openItemCount} {t("projects.checklists.open")}</span>
</div>
<BadgeFeedback farbe="subtle-neutral">{t(row.typeLabelKey)}</BadgeFeedback>
</div>
{row.items.length === 0 ? <span className={mutedText}>{t("projects.empty.checklistItems.body")}</span> : null}
{row.items.map((item) => (
<div key={item.id} className="flex flex-wrap items-center justify-between gap-2 rounded-sm bg-surface-neutral-secondary px-3 py-2">
<span className={mutedText}>{item.title}</span>
<BadgeFeedback farbe={item.status === "erledigt" ? "subtle-positive" : "subtle-neutral"}>{t(item.statusLabelKey)}</BadgeFeedback>
</div>
))}
<div className="flex flex-col gap-2 sm:flex-row">
<TextInput showLabel={false} className="max-w-none">
<TextInput.Input placeholder={t("projects.fields.checklistItem")} value={itemDrafts[row.id] ?? ""} onChange={(event) => setItemDrafts((current) => ({ ...current, [row.id]: event.target.value }))} />
</TextInput>
<Button variant="tertiary" loading={props.submitting} onClick={() => submit("upsertChecklistItem", { checklistId: row.id, titel: itemDrafts[row.id] ?? "" })}>
{t("projects.actions.addItem")}
</Button>
</div>
</div>
))}
</div>
)}
</Card>
<Card data-ui-id="ui.projects.operations.checklists.form">
<span className={headingText}>{t("projects.actions.createChecklist")}</span>
<TextInput showLabel label={t("projects.fields.checklistTitle")} className="max-w-none">
<TextInput.Input value={checklist.titel} onChange={(event) => setChecklist((current) => ({ ...current, titel: event.target.value }))} />
</TextInput>
<Select showLabel label={t("projects.fields.stageKind")} value={checklist.typ} onValueChange={(typ) => setChecklist((current) => ({ ...current, typ }))} className="max-w-none">
<Select.Item value="generisch">{t("projects.checklistTypes.generisch")}</Select.Item>
<Select.Item value="maengel">{t("projects.checklistTypes.maengel")}</Select.Item>
<Select.Item value="abnahme_doku">{t("projects.checklistTypes.abnahmeDoku")}</Select.Item>
</Select>
<Button loading={props.submitting} onClick={() => submitFields(submit, "createChecklist", checklist)}>{t("projects.actions.createChecklist")}</Button>
</Card>
</div>
) : null}
{activeTab === "tasks" ? (
<div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]">
<Card data-ui-id="ui.projects.operations.tasks">
<span className={headingText}>{t("projects.subAreas.tasks")}</span>
{data.tasks.length === 0 ? (
<EmptyState outlined title={t("projects.empty.tasks.title")} body={t("projects.empty.tasks.body")} />
) : (
<Table>
<Table.HeaderRow>
<Table.HeaderCell>{t("projects.fields.taskTitle")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.stage")}</Table.HeaderCell>
<Table.HeaderCell>{t("shared.priority")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.deadline")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.owner")}</Table.HeaderCell>
</Table.HeaderRow>
{data.tasks.map((task) => (
<Table.Row key={task.id}>
<Table.Cell>{task.title}</Table.Cell>
<Table.Cell>
<BadgeFeedback farbe={task.status === "done" ? "subtle-positive" : "subtle-neutral"}>{t(task.statusLabelKey)}</BadgeFeedback>
</Table.Cell>
<Table.Cell>
<BadgeFeedback farbe={task.priority === "urgent" || task.priority === "high" ? "subtle-warning" : "subtle-neutral"}>
{t(task.priorityLabelKey)}
</BadgeFeedback>
</Table.Cell>
<Table.Cell>{formatDate(task.deadlineIso, i18n.language)}</Table.Cell>
<Table.Cell>{task.assignee === "projects.fields.none" ? t(task.assignee) : task.assignee}</Table.Cell>
</Table.Row>
))}
</Table>
)}
</Card>
<Card data-ui-id="ui.projects.operations.tasks.form">
<span className={headingText}>{t("projects.actions.createTask")}</span>
<TextInput showLabel label={t("projects.fields.taskTitle")} className="max-w-none">
<TextInput.Input value={taskDraft} onChange={(event) => setTaskDraft(event.target.value)} />
</TextInput>
<Button
loading={props.submitting}
disabled={!taskDraft.trim()}
onClick={() => {
submitFields(submit, "createTask", { title: taskDraft.trim() });
setTaskDraft("");
}}
>
{t("projects.actions.createTask")}
</Button>
</Card>
</div>
) : null}
{activeTab === "materials" ? (
<Card data-ui-id="ui.projects.operations.materials">
<span className={headingText}>{t("projects.subAreas.materials")}</span>
{data.materials.length === 0 ? (
<EmptyState outlined title={t("projects.empty.materials.title")} body={t("projects.empty.materials.body")} />
) : (
<Table>
<Table.HeaderRow>
<Table.HeaderCell>{t("projects.fields.position")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.description")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.quantity")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.unit")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.unitPrice")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.totalPrice")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.updatedAt")}</Table.HeaderCell>
</Table.HeaderRow>
{data.materials.map((position) => (
<Table.Row key={position.id}>
<Table.Cell>{position.positionNumber}</Table.Cell>
<Table.Cell>
<span>{position.text}</span>
{position.longText ? <span className={mutedText}>{position.longText}</span> : null}
</Table.Cell>
<Table.Cell>{position.quantity}</Table.Cell>
<Table.Cell>{position.unit}</Table.Cell>
<Table.Cell>{position.unitPrice}</Table.Cell>
<Table.Cell>{position.totalPrice}</Table.Cell>
<Table.Cell>{formatDate(position.lastSyncedAtIso, i18n.language)}</Table.Cell>
</Table.Row>
))}
</Table>
)}
</Card>
) : null}
{activeTab === "documents" ? (
<Card data-ui-id="ui.projects.operations.documents">
<span className={headingText}>{t("projects.subAreas.documents")}</span>
{data.documents.length === 0 ? (
<EmptyState outlined title={t("projects.empty.documents.title")} body={t("projects.empty.documents.body")} />
) : (
<Table>
<Table.HeaderRow>
<Table.HeaderCell>{t("projects.fields.fileName")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.fileType")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.fileSize")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.startDate")}</Table.HeaderCell>
</Table.HeaderRow>
{data.documents.map((document) => (
<Table.Row key={document.id}>
<Table.Cell>{document.name}</Table.Cell>
<Table.Cell><span className={mutedText} title={document.mimeType}>{t(fileTypeLabelKey(document.mimeType))}</span></Table.Cell>
<Table.Cell>{document.sizeLabel}</Table.Cell>
<Table.Cell>{formatDate(document.createdAtIso, i18n.language)}</Table.Cell>
</Table.Row>
))}
</Table>
)}
</Card>
) : null}
</div>
);
}
@@ -0,0 +1,153 @@
// R-P9a interim UI (AD-28) — project template admin (D-P9 scope), restored
// after the admin route was dropped in the seat-billing recut.
// Pure/presentational: renders the server-built VM and turns every mutation
// into a typed onSubmit(intent, fields) callback the route POSTs. No
// useLoaderData/useFetcher, no server imports. Final Subframe optics =
// tracked design-nachzug. Modeled on LostReasonAdminPage (same admin-subpage
// chrome under /admin/pipelines).
import { useState } from "react";
import { useTranslation } from "react-i18next";
import type { ProjectTemplatesAdminScreenVM } from "@hivegrid/view-models";
import { FeatherArrowLeft, FeatherPlus } from "@subframe/core";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Card } from "~/ui/components/Card";
import { EmptyState } from "~/ui/components/EmptyState";
import { Select } from "~/ui/components/Select";
import { Table } from "~/ui/components/Table";
import { TextInput } from "~/ui/components/TextInput";
import { AppLink } from "~/components/app/AppLink";
export type ProjectTemplatesAdminSubmit = (intent: string, fields: Record<string, string>) => void;
export type ProjectTemplatesAdminPageProps = {
vm: ProjectTemplatesAdminScreenVM;
backHref: string;
submitting: boolean;
errorKey?: string | null;
actions: { onSubmit: ProjectTemplatesAdminSubmit };
};
const mutedText = "text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary";
const NONE = "__none__";
export function ProjectTemplatesAdminPage(props: ProjectTemplatesAdminPageProps) {
const { t } = useTranslation();
const submit = props.actions.onSubmit;
const [name, setName] = useState("");
const [pipelineId, setPipelineId] = useState<string>(NONE);
const [stageId, setStageId] = useState<string>(NONE);
const pipelineOptions = props.vm.status === "ready" ? props.vm.data.pipelineOptions : [];
const stageOptions = pipelineId === NONE ? [] : (pipelineOptions.find((pipeline) => pipeline.id === pipelineId)?.stages ?? []);
return (
<div className="flex w-full flex-col items-start bg-surface-neutral-primary" data-ui-id="ui.projects.templatesAdmin">
<div className="flex w-full flex-wrap items-center justify-between gap-4 border-b border-solid border-border-default bg-surface-neutral-secondary px-6 py-4 mobile:px-4">
<div className="flex flex-col gap-0">
<span className="text-heading- font-heading- text-text-neutral-primary">{t("projects.templatesAdmin.title")}</span>
<span className={mutedText}>{t("projects.templatesAdmin.subtitle")}</span>
</div>
<AppLink href={props.backHref}>
<Button variant="tertiary" size="small" icon={<FeatherArrowLeft />}>{t("projects.lostReasonsAdmin.backToPipelines")}</Button>
</AppLink>
</div>
<div className="flex w-full max-w-4xl flex-col gap-6 px-6 py-6 mobile:px-4">
{props.errorKey ? <BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback> : null}
{props.vm.status !== "ready" ? (
<EmptyState title={t("projects.templatesAdmin.loading")} />
) : (
<>
<Card data-ui-id="ui.projects.templatesAdmin.new">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{t("projects.templatesAdmin.newTemplate")}
</span>
<div className="flex flex-wrap items-end gap-2">
<TextInput label={t("projects.fields.templateName")} showLabel>
<TextInput.Input value={name} onChange={(e) => setName(e.target.value)} data-ui-id="ui.projects.templatesAdmin.new.name" />
</TextInput>
<Select
value={pipelineId}
onValueChange={(value) => {
setPipelineId(value);
setStageId(NONE);
}}
triggerAriaLabel={t("projects.fields.defaultPipelineId")}
>
<Select.Item value={NONE}>{t("projects.templates.noPipeline")}</Select.Item>
{pipelineOptions.map((pipeline) => (
<Select.Item key={pipeline.id} value={pipeline.id}>{pipeline.name}</Select.Item>
))}
</Select>
<Select value={stageId} onValueChange={setStageId} disabled={pipelineId === NONE} triggerAriaLabel={t("projects.fields.defaultStageId")}>
<Select.Item value={NONE}>{t("projects.templatesAdmin.noStage")}</Select.Item>
{stageOptions.map((stage) => (
<Select.Item key={stage.id} value={stage.id}>{stage.name}</Select.Item>
))}
</Select>
<Button
icon={<FeatherPlus />}
disabled={!name.trim()}
loading={props.submitting}
onClick={() => {
submit("upsertProjectTemplate", {
name: name.trim(),
defaultPipelineId: pipelineId === NONE ? "" : pipelineId,
defaultStageId: stageId === NONE ? "" : stageId,
});
setName("");
setPipelineId(NONE);
setStageId(NONE);
}}
data-ui-id="ui.projects.templatesAdmin.new.create"
>
{t("projects.actions.saveTemplate")}
</Button>
</div>
</Card>
{props.vm.data.templates.length === 0 ? (
<div data-ui-id="ui.projects.templatesAdmin.empty">
<EmptyState title={t("projects.templatesAdmin.empty")} body={t("projects.templatesAdmin.emptyBody")} />
</div>
) : (
<Card data-ui-id="ui.projects.templatesAdmin.list">
<Table>
<Table.HeaderRow>
<Table.HeaderCell>{t("projects.fields.templateName")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.pipeline")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.fields.stage")}</Table.HeaderCell>
<Table.HeaderCell>{t("projects.templatesAdmin.defaults")}</Table.HeaderCell>
</Table.HeaderRow>
{props.vm.data.templates.map((template) => (
<Table.Row key={template.id}>
<Table.Cell>
<div className="flex items-center gap-2">
<span>{template.name}</span>
{template.isDemoData ? (
<BadgeFeedback farbe="subtle-neutral" size="small">{t("projects.lostReasonsAdmin.demoBadge")}</BadgeFeedback>
) : null}
</div>
</Table.Cell>
<Table.Cell>{template.pipelineName ?? t("projects.templates.noPipeline")}</Table.Cell>
<Table.Cell>{template.stageName ?? t("projects.templatesAdmin.noStage")}</Table.Cell>
<Table.Cell>
<span className={mutedText}>
{t("projects.templatesAdmin.defaultCounts", { members: template.memberCount, tasks: template.taskCount })}
</span>
</Table.Cell>
</Table.Row>
))}
</Table>
</Card>
)}
</>
)}
</div>
</div>
);
}
export default ProjectTemplatesAdminPage;
@@ -0,0 +1,684 @@
// R-P8a interim-UI (AD-28) — ProjektDetailPage unit test. Fixture built via the
// real buildProjektDetailVM / buildActivityStreamVM; interactions asserted on the
// injected onSubmit callback. i18n mocked so `t` echoes the key.
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildActivityStreamVM, buildProjektDetailVM, type BuildProjektDetailVMInput, type ProjektDetailData } from "@hivegrid/view-models";
import { ProjektDetailPage, type ProjektDetailPageActions } from "./ProjektDetailPage";
const byUiId = (id: string) => document.querySelector(`[data-ui-id='${id}']`) as HTMLElement;
/** S02 contacts fold; their details only exist in the DOM while a row is open. */
const openContact = (contactId: string) => fireEvent.click(byUiId(`ui.projects.detail.contacts.${contactId}.trigger`));
/** The three ways to add a contact hang behind one button. */
const openAddContactMenu = () => fireEvent.keyDown(byUiId("ui.projects.detail.contacts.add.trigger"), { key: "ArrowDown" });
/** Address slots fold like contacts; their fields only exist while open. */
const openAddressSlot = (slot: string) => fireEvent.click(byUiId(`ui.projects.detail.addresses.${slot}.trigger`));
const openRailArea = (area: string) => fireEvent.click(byUiId(`ui.projects.detail.rail.tab.${area}`));
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }),
}));
const NOW = "2026-07-08T12:00:00.000Z";
const emptyActivity = buildActivityStreamVM({ rows: [], userLabels: new Map(), hasMore: false });
function baseInput(over: Partial<BuildProjektDetailVMInput> = {}): BuildProjektDetailVMInput {
return {
project: {
id: "p1",
projektNummer: "P-00001",
projektname: "Dach Nord",
beschreibung: null,
prioritaet: "normal",
stageId: "s1",
startDatumIso: null,
deadlineIso: null,
zustaendigePersonId: null,
projektleiterId: null,
konvertiertAusLeadId: null,
wonAtIso: null,
lostAtIso: null,
undoStageChangeUntilIso: null,
lostReasonId: null,
},
pipelineName: "Sales",
pipelineTypHint: "sales",
stages: [
{ id: "s1", name: "Neu", stageKind: "offen", winProbability: 10, color: "#000" },
{ id: "s2", name: "Angebot", stageKind: "offen", winProbability: 60, color: "#111" },
{ id: "s3", name: "Gewonnen", stageKind: "gewonnen", winProbability: 100, color: "#0a0" },
{ id: "s4", name: "Verloren", stageKind: "verloren", winProbability: 0, color: "#a00" },
],
kontakte: [],
lostReasons: [{ id: "lr1", name: "Preis" }],
value: "10000.00",
orderVolume: "20000.00",
valueVisible: true,
ownerLabel: null,
projektleiterLabel: null,
mitglieder: [],
adressen: { projekt: null, rechnung: null, bauherr: null },
perms: { canWrite: true, canChangeStage: true, canInviteToPortal: true, canManageMembers: true },
nowIso: NOW,
...over,
};
}
type KontaktInput = BuildProjektDetailVMInput["kontakte"][number];
function kontakt(over: Partial<KontaktInput> = {}): KontaktInput {
return {
id: "project-contact-1",
kontaktId: "contact-1",
kontaktTyp: "privatperson",
rolle: "auftraggeber",
primaer: true,
label: "Ada Lovelace",
email: null,
telefon: null,
detailHref: null,
portalInviteEligible: true,
stammdaten: [],
lastContactAtIso: null,
...over,
};
}
function data(over: Partial<BuildProjektDetailVMInput> = {}): ProjektDetailData {
const vm = buildProjektDetailVM(baseInput(over));
if (vm.status !== "ready") throw new Error("fixture not ready");
return vm.data;
}
function renderPage(props: Partial<Parameters<typeof ProjektDetailPage>[0]> = {}) {
const acts: ProjektDetailPageActions = props.actions ?? { onSubmit: vi.fn() };
render(
<ProjektDetailPage
data={props.data ?? data()}
activity={props.activity ?? emptyActivity}
ownerOptions={props.ownerOptions ?? []}
backHref="/acme/projects"
contactSearchHref="/acme/projects/p1/contact-search"
submitting={false}
actions={acts}
{...props}
/>
);
return acts;
}
describe("ProjektDetailPage", () => {
it("renders the project number, name and stages", () => {
renderPage();
// Number/stage name also appear in the edit-mode system boxes.
expect(screen.getAllByText("P-00001").length).toBeGreaterThan(0);
expect(screen.getAllByText("Dach Nord").length).toBeGreaterThan(0);
expect(screen.getAllByText("Neu").length).toBeGreaterThan(0);
fireEvent.keyDown(byUiId("ui.projects.detail.status.trigger"), { key: "ArrowDown" });
expect(screen.getByText("Gewonnen")).toBeTruthy();
});
it("submits stammdaten via onSubmit", () => {
const acts = renderPage();
fireEvent.click(byUiId("ui.projects.detail.stammdaten.save"));
expect(acts.onSubmit).toHaveBeenCalledWith("updateStammdaten", expect.objectContaining({ projektname: "Dach Nord", prioritaet: "normal" }));
});
it("puts save in the header and keeps Grunddaten to the export's fields", () => {
renderPage();
// S02: the single save path lives in the header, not in a banner above the
// fields, so it stays reachable while scrolling through the sections.
expect(byUiId("ui.projects.detail.header").contains(byUiId("ui.projects.detail.stammdaten.save"))).toBe(true);
// Project id, board, board column and outcome were four grey "System" boxes
// at the end of Grunddaten. They repeat the header and the status field, and
// the export has no such boxes.
expect(byUiId("ui.projects.detail.systemFields")).toBeNull();
expect(byUiId("ui.projects.detail.system.projectId")).toBeNull();
// Priority is a coloured badge picker, like the export's.
expect(byUiId("ui.projects.detail.priority.current").textContent).toBe("projects.priority.normal");
});
it("offers the S02 quick-action bar with the direct call and mail actions", () => {
renderPage({
data: data({ project: { ...baseInput().project, telefon: "+49 761 1", email: "bau@example.test" } }),
quickActions: { assigneeOptions: [], canChooseInternalNote: false, uploadFile: vi.fn() },
});
const bar = byUiId("ui.projects.detail.quickActions");
expect(bar).toBeTruthy();
// Anrufen and E-Mail are direct actions, the four others open a modal.
expect(bar.contains(byUiId("ui.projects.detail.quickActions.call"))).toBe(true);
expect(bar.contains(byUiId("ui.projects.detail.quickActions.mail"))).toBe(true);
for (const action of ["appointment", "task", "note", "file"]) {
expect(bar.contains(byUiId(`ui.projects.detail.quickActions.${action}`))).toBe(true);
}
});
it("keeps call and mail in place but disabled when the project carries neither", () => {
renderPage({ quickActions: { assigneeOptions: [], canChooseInternalNote: false, uploadFile: vi.fn() } });
// The bar keeps its six buttons in the export's order; a missing number
// disables the button rather than moving the five next to it.
expect((byUiId("ui.projects.detail.quickActions.call") as HTMLButtonElement).disabled).toBe(true);
expect((byUiId("ui.projects.detail.quickActions.mail") as HTMLButtonElement).disabled).toBe(true);
});
it("hides save and the system boxes without write permission", () => {
renderPage({ data: data({ perms: { canWrite: false, canChangeStage: false } }) });
expect(byUiId("ui.projects.detail.stammdaten.save")).toBeNull();
expect(byUiId("ui.projects.detail.systemFields")).toBeNull();
});
it("keeps the header to the export's three controls", () => {
renderPage();
const header = byUiId("ui.projects.detail.header");
// Project id, the way back to the board and save — nothing else. A cancel
// button next to save is not part of S02.
expect(header.contains(byUiId("ui.projects.detail.header.projectId"))).toBe(true);
expect(header.contains(byUiId("ui.projects.detail.header.board.link"))).toBe(true);
expect(header.contains(byUiId("ui.projects.detail.stammdaten.save"))).toBe(true);
expect(byUiId("ui.projects.detail.stammdaten.cancel")).toBeNull();
// The board this project sits on reads as the line under its name.
expect(byUiId("ui.projects.detail.header.board").textContent).toBe("Sales");
});
it("formats the read-only project value as euros", () => {
renderPage({ data: data({ perms: { canWrite: false, canChangeStage: false, canInviteToPortal: false } }) });
expect((document.body.textContent ?? "").replace(/[\u00a0\u202f]/g, " ")).toContain("10.000,00 €");
});
it("keeps editable monetary inputs as raw decimal values", () => {
renderPage();
expect(screen.getByDisplayValue("10000.00").getAttribute("type")).toBe("number");
expect(screen.getByDisplayValue("20000.00").getAttribute("type")).toBe("number");
});
it("submits the project leader together with the other stammdaten", () => {
const acts = renderPage({ ownerOptions: [{ id: "u9", label: "Lea Leiter" }] });
fireEvent.click(byUiId("ui.projects.detail.stammdaten.save"));
expect(acts.onSubmit).toHaveBeenCalledWith("updateStammdaten", expect.objectContaining({ projektleiterId: "" }));
});
it("adds and removes S02 members through the two people pickers", () => {
const acts = renderPage({
ownerOptions: [
{ id: "u9", label: "Lea Leiter" },
{ id: "u8", label: "Mo Monteur" },
],
data: data({ mitglieder: [{ id: "m1", userId: "u8", rolle: "monteur", label: "Mo Monteur" }] }),
});
// A user who is not a member yet is added with the picker's role...
fireEvent.keyDown(byUiId("ui.projects.detail.members.zustaendig.trigger"), { key: "ArrowDown" });
fireEvent.click(byUiId("ui.projects.detail.members.zustaendig.option.u9"));
expect(acts.onSubmit).toHaveBeenCalledWith("addMember", { userId: "u9", rolle: "zustaendig" });
// ...and an existing member row is removed by its member id, not its user id.
fireEvent.keyDown(byUiId("ui.projects.detail.members.monteur.trigger"), { key: "ArrowDown" });
fireEvent.click(byUiId("ui.projects.detail.members.monteur.option.u8"));
expect(acts.onSubmit).toHaveBeenCalledWith("removeMember", { memberId: "m1" });
});
it("shows the members as plain names without a picker when the actor cannot manage members", () => {
renderPage({
ownerOptions: [{ id: "u8", label: "Mo Monteur" }],
data: data({
mitglieder: [{ id: "m1", userId: "u8", rolle: "monteur", label: "Mo Monteur" }],
perms: { canWrite: true, canChangeStage: true, canInviteToPortal: true, canManageMembers: false },
}),
});
expect(byUiId("ui.projects.detail.members.monteur.value").textContent).toBe("Mo Monteur");
expect(byUiId("ui.projects.detail.members.monteur.trigger")).toBeNull();
});
it("drops the single owner select in favour of the people multi-select", () => {
renderPage({ ownerOptions: [{ id: "u9", label: "Lea Leiter" }] });
// "Zuständig" held one name and said the same thing as "Zuständige
// Personen"; only the multi-select survives.
expect(byUiId("ui.projects.detail.field.owner")).toBeNull();
expect(byUiId("ui.projects.detail.members.zustaendig.trigger")).toBeTruthy();
expect(byUiId("ui.projects.detail.field.projectLeader")).toBeTruthy();
});
it("moves directly to an open stage", () => {
const acts = renderPage();
fireEvent.keyDown(byUiId("ui.projects.detail.status.trigger"), { key: "ArrowDown" });
fireEvent.click(byUiId("ui.projects.detail.stage.s2"));
expect(acts.onSubmit).toHaveBeenCalledWith("moveStage", { targetStageId: "s2" });
});
it("invites a linked contact from a sales project through the project-contact action", () => {
const acts = renderPage({
data: data({
pipelineTypHint: "sales",
kontakte: [kontakt()],
}),
});
openContact("project-contact-1");
fireEvent.click(byUiId("ui.projects.detail.contacts.project-contact-1.portalInvite"));
expect(acts.onSubmit).toHaveBeenCalledWith("invitePortalProjectContact", { contactId: "contact-1" });
});
it("splits the S02 contacts accordion into a company card and the person cards", () => {
renderPage({
data: data({
kontakte: [
kontakt({ id: "pc-person", kontaktId: "c-person", primaer: true, label: "Ada Lovelace", telefon: "+49 761 2" }),
kontakt({
id: "pc-firma",
kontaktId: "c-firma",
kontaktTyp: "organisation",
rolle: "auftraggeber",
primaer: false,
label: "Weber GmbH",
email: "info@weber.test",
detailHref: "/acme/contacts/companies/c-firma",
portalInviteEligible: false,
}),
],
}),
});
expect(byUiId("ui.projects.detail.contacts.pc-firma").textContent).toContain("projects.detail.contacts.company");
// The pencil leads to the record in the CRM, which owns contact master data.
expect(byUiId("ui.projects.detail.contacts.pc-firma.open").getAttribute("href")).toBe("/acme/contacts/companies/c-firma");
openContact("pc-firma");
expect(byUiId("ui.projects.detail.contacts.pc-firma.email").textContent).toContain("info@weber.test");
// The primary link is the first person card, whatever order the loader used.
expect(byUiId("ui.projects.detail.contacts.pc-person").textContent).toContain("projects.detail.contacts.primaryPerson");
openContact("pc-person");
expect(byUiId("ui.projects.detail.contacts.pc-person.telefon").textContent).toContain("+49 761 2");
});
it("shows the KWP block read-only for a bound project and not at all otherwise", () => {
renderPage();
expect(byUiId("ui.projects.detail.kwp")).toBeNull();
renderPage({
data: data({ kwp: { externalProjectNumber: "2026-0815", statusLabel: "In Bearbeitung", lastSyncedAtIso: "2026-07-08T10:00:00.000Z" } }),
});
const block = byUiId("ui.projects.detail.kwp");
expect(block.textContent).toContain("2026-0815");
expect(block.textContent).toContain("In Bearbeitung");
// Abteilungsnummer and Sachbearbeiter are drawn by the export, but the
// inbound contract carries neither — a row that can never fill is out.
expect(byUiId("ui.projects.detail.kwp.departmentNumber")).toBeNull();
expect(byUiId("ui.projects.detail.kwp.agent")).toBeNull();
// KWP is an inbound mirror: no field in this block may be writable.
expect(block.querySelector("input")).toBeNull();
});
it("shows the contact master data the loader resolved on the card", () => {
renderPage({
data: data({
kontakte: [
kontakt({
id: "pc-firma",
kontaktTyp: "organisation",
label: "Weber GmbH",
stammdaten: [
{ labelKey: "projects.detail.contacts.vatId", value: "DE123456789" },
{ labelKey: "projects.detail.contacts.industry", value: "SHK" },
],
}),
],
}),
});
openContact("pc-firma");
expect(byUiId("ui.projects.detail.contacts.pc-firma.stammdaten.vatId").textContent).toContain("DE123456789");
expect(byUiId("ui.projects.detail.contacts.pc-firma.stammdaten.industry").textContent).toContain("SHK");
});
it("shows the derived last contact only when the timeline has one", () => {
renderPage({ data: data({ kontakte: [kontakt({ id: "pc-1" })] }) });
openContact("pc-1");
expect(byUiId("ui.projects.detail.contacts.pc-1.lastContact")).toBeNull();
renderPage({ data: data({ kontakte: [kontakt({ id: "pc-2", lastContactAtIso: "2026-07-08T10:00:00.000Z" })] }) });
openContact("pc-2");
expect(byUiId("ui.projects.detail.contacts.pc-2.lastContact")).toBeTruthy();
});
it("saves the three S02 address slots and clears the ones left switched off", () => {
const acts = renderPage({
data: data({
adressen: {
projekt: { strasse: "Hauptstr.", hausnummer: "1", plz: "79098", ort: "Freiburg", land: "DE" },
rechnung: { strasse: "Rechnungsweg", hausnummer: "9", plz: "79100", ort: "Freiburg", land: "DE", zahlungsziel: "30 Tage" },
bauherr: null,
},
}),
});
// Each slot ships collapsed, like the export.
openAddressSlot("projekt");
fireEvent.change(byUiId("ui.projects.detail.addresses.projekt.ort"), { target: { value: "Emmendingen" } });
// A slot extra rides along in the same payload as the address itself.
fireEvent.change(byUiId("ui.projects.detail.addresses.projekt.zufahrt"), { target: { value: "Hofeinfahrt links" } });
// Switching the invoice slot off must clear it, not keep the old row. The
// switch sits in the project address, which is the row already open.
fireEvent.click(byUiId("ui.projects.detail.addresses.rechnung.toggle"));
fireEvent.click(byUiId("ui.projects.detail.addresses.projekt.save"));
const [[, fields]] = (acts.onSubmit as ReturnType<typeof vi.fn>).mock.calls.slice(-1);
const slots = JSON.parse((fields as { slots: string }).slots);
expect(slots.projekt).toMatchObject({ ort: "Emmendingen", zufahrt: "Hofeinfahrt links" });
expect(slots.rechnung).toBeNull();
expect(slots.bauherr).toBeNull();
});
it("only offers a slot the extras that belong to it", () => {
renderPage({
data: data({
adressen: {
projekt: { strasse: "Hauptstr.", hausnummer: "1", plz: "79098", ort: "Freiburg", land: "DE" },
rechnung: { strasse: "Rechnungsweg", hausnummer: "9", plz: "79100", ort: "Freiburg", land: "DE" },
bauherr: { strasse: "Bauherrweg", hausnummer: "3", plz: "79101", ort: "Freiburg", land: "DE" },
},
}),
});
for (const slot of ["projekt", "rechnung", "bauherr"]) openAddressSlot(slot);
// Site access belongs to the project address, payment terms to the invoice
// one, and the postal-mail switch to the building owner.
expect(byUiId("ui.projects.detail.addresses.projekt.zufahrt")).toBeTruthy();
expect(byUiId("ui.projects.detail.addresses.rechnung.zufahrt")).toBeNull();
expect(byUiId("ui.projects.detail.addresses.rechnung.zahlungsziel")).toBeTruthy();
expect(byUiId("ui.projects.detail.addresses.projekt.zahlungsziel")).toBeNull();
expect(byUiId("ui.projects.detail.addresses.bauherr.postErwuenscht")).toBeTruthy();
expect(byUiId("ui.projects.detail.addresses.projekt.postErwuenscht")).toBeNull();
// Invoice mail only on the invoice slot, the on-site contact only on the
// building owner's — a slot must not offer a field nobody would fill there.
expect(byUiId("ui.projects.detail.addresses.rechnung.rechnungsEmail")).toBeTruthy();
expect(byUiId("ui.projects.detail.addresses.projekt.rechnungsEmail")).toBeNull();
expect(byUiId("ui.projects.detail.addresses.bauherr.ansprechpartnerVorOrt")).toBeTruthy();
expect(byUiId("ui.projects.detail.addresses.rechnung.ansprechpartnerVorOrt")).toBeNull();
// The note is the one extra every slot has.
for (const slot of ["projekt", "rechnung", "bauherr"]) {
expect(byUiId(`ui.projects.detail.addresses.${slot}.notizen`)).toBeTruthy();
}
});
it("saves a slot note together with its address instead of through a second intent", () => {
const acts = renderPage({
data: data({
adressen: {
projekt: { strasse: "Hauptstr.", hausnummer: "1", plz: "79098", ort: "Freiburg", land: "DE" },
rechnung: null,
bauherr: null,
},
}),
});
openAddressSlot("projekt");
fireEvent.change(byUiId("ui.projects.detail.addresses.projekt.notizen"), { target: { value: "Anlieferung nur 7-16 Uhr" } });
fireEvent.click(byUiId("ui.projects.detail.addresses.projekt.save"));
const [[intent, fields]] = (acts.onSubmit as ReturnType<typeof vi.fn>).mock.calls.slice(-1);
expect(intent).toBe("updateAddresses");
expect(JSON.parse((fields as { slots: string }).slots).projekt.notizen).toBe("Anlieferung nur 7-16 Uhr");
});
it("gives each typed number its own row and shows the contact's address", () => {
renderPage({
data: data({
kontakte: [
kontakt({
telefon: "+49 761 1",
durchwahl: "+49 761 117",
mobil: "+49 170 2",
fax: "+49 761 199",
adresseLabel: "Lindenweg 14, 79110 Freiburg",
}),
],
}),
});
openContact("project-contact-1");
expect(byUiId("ui.projects.detail.contacts.project-contact-1.durchwahl").textContent).toContain("+49 761 117");
expect(byUiId("ui.projects.detail.contacts.project-contact-1.mobil").textContent).toContain("+49 170 2");
expect(byUiId("ui.projects.detail.contacts.project-contact-1.fax").textContent).toContain("+49 761 199");
expect(byUiId("ui.projects.detail.contacts.project-contact-1.adresse").textContent).toContain("Lindenweg 14, 79110 Freiburg");
});
it("leaves out a typed number the contact does not have instead of rendering an empty row", () => {
renderPage({ data: data({ kontakte: [kontakt({ telefon: "+49 761 1" })] }) });
openContact("project-contact-1");
expect(byUiId("ui.projects.detail.contacts.project-contact-1.telefon")).toBeTruthy();
expect(byUiId("ui.projects.detail.contacts.project-contact-1.durchwahl")).toBeNull();
expect(byUiId("ui.projects.detail.contacts.project-contact-1.mobil")).toBeNull();
expect(byUiId("ui.projects.detail.contacts.project-contact-1.adresse")).toBeNull();
});
it("shows the contact note as its own block, keeping the author's line breaks", () => {
renderPage({
data: data({
kontakte: [kontakt({ notizen: "Entscheider für Budget.\nRuft lieber vormittags an." })],
}),
});
openContact("project-contact-1");
const block = byUiId("ui.projects.detail.contacts.project-contact-1.notizen");
expect(block).toBeTruthy();
expect(block.textContent).toContain("Entscheider für Budget.");
expect(block.textContent).toContain("Ruft lieber vormittags an.");
});
it("lists the project documents in the S02 rail grouped by their upload category", () => {
renderPage({
documents: [
{ id: "f1", name: "Angebot.pdf", mimeType: "application/pdf", sizeLabel: "1 MB", linkRole: "angebot", href: "/acme/files/f1" },
{ id: "f2", name: "Auftrag.pdf", mimeType: "application/pdf", sizeLabel: "2 MB", linkRole: "auftrag", href: "/acme/files/f2" },
],
quickActions: { assigneeOptions: [], canChooseInternalNote: false, uploadFile: vi.fn() },
});
expect(byUiId("ui.projects.detail.rail.files.group.angebot").textContent).toContain("Angebot.pdf");
expect(byUiId("ui.projects.detail.rail.files.f2").getAttribute("href")).toBe("/acme/files/f2");
expect(byUiId("ui.projects.detail.rail.upload")).toBeTruthy();
});
it("keeps the rail upload out of reach without the quick actions", () => {
renderPage();
expect(byUiId("ui.projects.detail.rail")).toBeTruthy();
expect(byUiId("ui.projects.detail.rail.upload")).toBeNull();
expect(byUiId("ui.projects.detail.rail.dropzone")).toBeNull();
});
it("links a file dropped on the pipeline panel without opening the modal", async () => {
const uploadFile = vi.fn().mockResolvedValue({ id: "file-9", displayName: "Angebot.pdf" });
const acts = renderPage({ quickActions: { assigneeOptions: [], canChooseInternalNote: false, uploadFile } });
const file = new File(["x"], "Angebot.pdf", { type: "application/pdf" });
fireEvent.drop(byUiId("ui.projects.detail.rail.dropzone"), { dataTransfer: { files: [file] } });
await waitFor(() => expect(uploadFile).toHaveBeenCalledWith(file));
// No category dialog in between: the panel attaches, the quick action files.
expect(byUiId("ui.projects.quickAction.file")).toBeNull();
const [[intent, fields]] = (acts.onSubmit as ReturnType<typeof vi.fn>).mock.calls.slice(-1);
expect(intent).toBe("attachFile");
expect(fields).toMatchObject({ fileId: "file-9", kategorie: "sonstiges" });
});
it("says so when the panel upload failed instead of pretending it worked", async () => {
const uploadFile = vi.fn().mockRejectedValue(new Error("nope"));
renderPage({ quickActions: { assigneeOptions: [], canChooseInternalNote: false, uploadFile } });
fireEvent.drop(byUiId("ui.projects.detail.rail.dropzone"), {
dataTransfer: { files: [new File(["x"], "Angebot.pdf", { type: "application/pdf" })] },
});
await waitFor(() => expect(byUiId("ui.projects.detail.rail.uploadError")).toBeTruthy());
});
it("shows clear feedback after the project invitation was queued", () => {
renderPage({ messageKey: "customerPortal.invitation.sent" });
expect(byUiId("ui.projects.detail.portalInviteSuccess")).toBeTruthy();
expect(screen.getByText("customerPortal.invitation.sent")).toBeTruthy();
});
it("hides project-contact portal invitations when the loader gate is closed", () => {
renderPage({
data: data({
kontakte: [kontakt()],
perms: { canWrite: true, canChangeStage: true, canInviteToPortal: false, canManageMembers: true },
}),
});
expect(document.querySelector("[data-ui-id$='.portalInvite']")).toBeNull();
});
it("does not move immediately when picking a verloren stage (opens the lost dialog)", () => {
const acts = renderPage();
fireEvent.keyDown(byUiId("ui.projects.detail.status.trigger"), { key: "ArrowDown" });
fireEvent.click(byUiId("ui.projects.detail.stage.s4"));
expect(acts.onSubmit).not.toHaveBeenCalled();
});
it("carries no custom-field group any more", () => {
renderPage();
// "Individuelle Felder" is off S02; the definitions live in the pipeline
// field template (S05), not in a set-form at the end of the detail page.
expect(byUiId("ui.projects.detail.customFields")).toBeNull();
});
it("shows a won outcome with an undo button and fires undoStage", () => {
const acts = renderPage({
data: data({ project: { ...baseInput().project, stageId: "s3", wonAtIso: NOW, undoStageChangeUntilIso: "2026-07-08T20:00:00.000Z" } }),
});
fireEvent.click(byUiId("ui.projects.detail.undo"));
expect(acts.onSubmit).toHaveBeenCalledWith("undoStage");
});
it("exposes click-to-call only through the optional VM and callback prop", () => {
const onCall = vi.fn();
const number = { id: "phone-1", label: "Hauptkontakt", e164: "+49401234567", primary: true } as const;
renderPage({
// Telephony rides in the quick-action bar next to "Anrufen" (S02 keeps the
// header to project id, board and save), so the bar has to be there.
quickActions: { assigneeOptions: [], canChooseInternalNote: false, uploadFile: vi.fn() },
clickToCall: {
vm: { mode: "provider", numbers: [number], requiresSelection: false, reasonKey: null },
onCall,
},
});
expect(byUiId("ui.projects.detail.quickActions").contains(byUiId("ui.telephony.clickToCall.open"))).toBe(true);
fireEvent.click(screen.getByRole("button", { name: "telephony.clickToCall.open" }));
fireEvent.click(screen.getByRole("button", { name: "telephony.clickToCall.startCall" }));
expect(onCall).toHaveBeenCalledWith(number, "provider");
});
it("offers Davids three ways to add a contact, and only to a writer", () => {
renderPage();
openAddContactMenu();
expect(byUiId("ui.projects.detail.contacts.add.search")).toBeTruthy();
expect(byUiId("ui.projects.detail.contacts.add.person")).toBeTruthy();
expect(byUiId("ui.projects.detail.contacts.add.company")).toBeTruthy();
cleanup();
renderPage({ data: data({ perms: { canWrite: false, canChangeStage: false, canInviteToPortal: false, canManageMembers: false } }) });
expect(byUiId("ui.projects.detail.contacts.add")).toBeNull();
});
it("links the picked contact through the link intent", async () => {
const rows = [{ id: "c9", label: "Weber Immobilien GmbH", kontaktTyp: "organisation", email: "kontakt@weber.test" }];
const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ rows }) });
vi.stubGlobal("fetch", fetchMock);
const acts = renderPage();
openAddContactMenu();
fireEvent.click(byUiId("ui.projects.detail.contacts.add.search"));
// The search is debounced, so the result list needs the timer to elapse.
await waitFor(() => expect(byUiId("ui.projects.detail.contacts.add.result.c9")).toBeTruthy());
fireEvent.click(byUiId("ui.projects.detail.contacts.add.result.c9"));
const [[intent, fields]] = (acts.onSubmit as ReturnType<typeof vi.fn>).mock.calls.slice(-1);
expect(intent).toBe("linkKontakt");
expect(fields).toMatchObject({ kontaktId: "c9" });
expect(String(fetchMock.mock.calls[0][0])).toContain("/acme/projects/p1/contact-search?q=");
vi.unstubAllGlobals();
});
it("creates a company with its name and links it in one intent", () => {
const acts = renderPage();
openAddContactMenu();
fireEvent.click(byUiId("ui.projects.detail.contacts.add.company"));
fireEvent.change(byUiId("ui.projects.detail.contacts.add.orgName"), { target: { value: "Weber Immobilien GmbH" } });
fireEvent.click(byUiId("ui.projects.detail.contacts.add.createSubmit"));
const [[intent, fields]] = (acts.onSubmit as ReturnType<typeof vi.fn>).mock.calls.slice(-1);
expect(intent).toBe("createKontakt");
expect(fields).toMatchObject({ kontaktTyp: "organisation", orgName: "Weber Immobilien GmbH" });
});
it("keeps the create button closed until the name the type needs is there", () => {
renderPage();
openAddContactMenu();
fireEvent.click(byUiId("ui.projects.detail.contacts.add.person"));
// A person without a surname would be a contact nobody can find again.
expect((byUiId("ui.projects.detail.contacts.add.createSubmit") as HTMLButtonElement).disabled).toBe(true);
fireEvent.change(byUiId("ui.projects.detail.contacts.add.nachname"), { target: { value: "Weber" } });
expect((byUiId("ui.projects.detail.contacts.add.createSubmit") as HTMLButtonElement).disabled).toBe(false);
});
it("fills all six rail areas and links only the ones whose editor lives below", () => {
renderPage({
railAreas: {
history: [{ id: "h1", label: "Neu → Angebot", meta: "Birgit Büro", atIso: NOW }],
appointments: [{ id: "a1", label: "Aufmaß vor Ort", meta: "Murat Monteur", atIso: NOW }],
tasks: [{ id: "t1", label: "Angebot schreiben", meta: "Vera Vertrieb", atIso: NOW }],
notes: [{ id: "n1", label: "Kunde ruft vormittags an", meta: "Vera Vertrieb · alle", atIso: NOW }],
activity: [
{
id: "ac1",
label: "Projekt P-00001 wurde aktualisiert.",
labelKey: "activity.runtime.projects.detailsUpdated",
meta: "Vera Vertrieb",
atIso: NOW,
},
],
},
operationsHref: "#operations",
});
// The panel shows one area at a time, like the export — switch to each.
const expected: Record<string, [string, string]> = {
history: ["h1", "Neu → Angebot"],
appointments: ["a1", "Aufmaß vor Ort"],
tasks: ["t1", "Angebot schreiben"],
notes: ["n1", "Kunde ruft vormittags an"],
activity: ["ac1", "activity.runtime.projects.detailsUpdated"],
};
for (const [area, [entryId, label]] of Object.entries(expected)) {
openRailArea(area);
expect(byUiId(`ui.projects.detail.rail.${area}.${entryId}`).textContent).toContain(label);
// Appointments and tasks are edited in the operations panel, so those two
// areas point there; history, notes and activity have nothing to manage.
const manage = byUiId(`ui.projects.detail.rail.${area}.manage`);
expect(Boolean(manage)).toBe(area === "appointments" || area === "tasks");
}
});
it("keeps the pipeline panel open, with no way to fold it away", () => {
renderPage();
expect(byUiId("ui.projects.detail.rail")).toBeTruthy();
expect(byUiId("ui.projects.detail.rail.files")).toBeTruthy();
expect(byUiId("ui.projects.detail.rail.toggle")).toBeNull();
});
it("opens on the files area and keeps the other five one click away", () => {
renderPage();
// Dateien is the built area of the export, and the only one with an editor.
expect(byUiId("ui.projects.detail.rail.files")).toBeTruthy();
expect(byUiId("ui.projects.detail.rail.history")).toBeNull();
openRailArea("history");
expect(byUiId("ui.projects.detail.rail.files")).toBeNull();
expect(byUiId("ui.projects.detail.rail.history")).toBeTruthy();
});
it("shows a plain empty state per rail area instead of a blank panel", () => {
renderPage();
openRailArea("history");
expect(byUiId("ui.projects.detail.rail.history").textContent).toContain("projects.detail.rail.historyEmpty");
});
});
@@ -0,0 +1,379 @@
// 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;
@@ -0,0 +1,355 @@
// R-P8b interim-UI (AD-28) — ProjektListPage unit test. Fixture via the real
// buildProjectListVM; interactions asserted on injected callbacks. i18n mocked.
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildBoardFacetsVM, buildProjectListVM, PROJECT_LIST_COLUMNS, type ProjectListData } from "@hivegrid/view-models";
import { ProjektListPage, type ProjektListActions, type ProjectListQuery } from "./ProjektListPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }),
}));
// Radix dropdowns neither open nor expose their menu context in jsdom, so the
// board switcher chip, the column chooser and every facet dropdown would be
// unreachable. The SubframeCore wrapper and both ~/ui menus become plain
// passthroughs; the entries stay real buttons.
vi.mock("@subframe/core", async () => {
const actual = await vi.importActual<Record<string, unknown>>("@subframe/core");
const Pass = ({ children }: { children?: React.ReactNode }) => <>{children}</>;
return { ...actual, DropdownMenu: { Root: Pass, Trigger: Pass, Portal: Pass, Content: Pass, Item: Pass } };
});
vi.mock("~/ui/components/DropdownMenu", () => {
const DropdownMenu = ({ children }: { children?: React.ReactNode }) => <div>{children}</div>;
DropdownMenu.DropdownItem = ({ children, onClick, onSelect, ...rest }: any) => (
<button
type="button"
onClick={(event: any) => {
onClick?.(event);
onSelect?.({ preventDefault: () => undefined });
}}
data-ui-id={rest["data-ui-id"]}
>
{children}
</button>
);
DropdownMenu.DropdownDivider = () => <hr />;
return { DropdownMenu };
});
vi.mock("~/ui/components/DropdownMenuMultiSelect", () => {
const DropdownMenuMultiSelect = ({ children }: { children?: React.ReactNode }) => <div>{children}</div>;
DropdownMenuMultiSelect.DropdownItem = ({ children, onClick, selected, ...rest }: any) => (
<button type="button" onClick={onClick} aria-pressed={Boolean(selected)} data-ui-id={rest["data-ui-id"]}>
{children}
</button>
);
DropdownMenuMultiSelect.DropdownCustomItem = ({ children }: any) => <div>{children}</div>;
DropdownMenuMultiSelect.DropdownUserItem = ({ title }: any) => <div>{title}</div>;
DropdownMenuMultiSelect.DropdownDivider = () => <hr />;
return { DropdownMenuMultiSelect };
});
const byUiId = (id: string) => document.querySelector(`[data-ui-id='${id}']`) as HTMLElement;
function listData(total = 120, canArchive = false, empty = false, canAdmin = false): ProjectListData {
const vm = buildProjectListVM({
result: {
rows: empty ? [] : [
{ id: "p1", projektNummer: "P-1", projektname: "Dach Nord", pipelineName: "Sales", stageName: "Neu", value: "10000.00", valueVisible: true, ownerUserId: "u1", updatedAt: "2026-07-08T12:00:00.000Z", kontaktLabel: "Bergmann", projekttyp: "Privatperson", ort: "Ulm", nextTerminTitel: "Aufmaß", nextTerminStartAt: "2026-07-14T08:00:00.000Z", tags: [{ id: "t1", name: "PV / Solar", farbe: "yellow-subtle" }] },
// No volume access and no companions - the row must still be readable.
{ id: "p2", projektNummer: "P-2", projektname: "Fassade Süd", pipelineName: "Auftrag", stageName: "Montage", value: null, valueVisible: false, ownerUserId: "u2", updatedAt: "2026-07-09T12:00:00.000Z" },
],
total: empty ? 0 : total,
page: 1,
pageSize: 50,
},
ownerLabels: new Map([
["u1", "Owner One"],
["u2", "Owner Two"],
]),
buildDetailHref: (id) => `/acme/projects/${id}`,
perms: { canWrite: true, canArchive, canAdmin },
});
if (vm.status !== "ready") throw new Error("fixture not ready");
return vm.data;
}
const query: ProjectListQuery = { pipelineId: "", q: "", onlyMine: false, includeDemoData: false, sort: "updated_desc" };
/** Every action the screen can fire, so a spy is never accidentally undefined. */
function actionSpies(over: Partial<ProjektListActions> = {}): ProjektListActions {
return {
onShowBoard: vi.fn(),
onOpenProject: vi.fn(),
onManageBoard: vi.fn(),
onSwitchPipeline: vi.fn(),
onSearch: vi.fn(),
onToggleOnlyMine: vi.fn(),
onToggleDemo: vi.fn(),
onToggleFacet: vi.fn(),
onRemoveChip: vi.fn(),
onResetFilters: vi.fn(),
onPeriodRangeChange: vi.fn(),
onSort: vi.fn(),
onGoToPage: vi.fn(),
onBulkArchive: vi.fn(),
onCreateProject: vi.fn(),
...over,
};
}
function facetsVM(
over: { owners?: string[]; q?: string; onlyMine?: boolean; tags?: { id: string; name: string; farbe: string }[]; tagIds?: string[] } = {}
) {
return buildBoardFacetsVM({
assignees: [{ userId: "u1", label: "Owner One" }],
hasUnassigned: true,
tags: over.tags ?? [],
selected: { owners: over.owners ?? [], customerTypes: [], tagIds: over.tagIds ?? [], period: null, valueBands: [] },
onlyMine: over.onlyMine ?? false,
q: over.q ?? "",
canFilterByValue: true,
});
}
function renderPage(
over: Partial<ProjektListActions> = {},
opts: { showDemoToggle?: boolean; canArchive?: boolean; empty?: boolean; canAdmin?: boolean; filtered?: boolean } = {},
) {
const actions = actionSpies(over);
render(
<ProjektListPage
data={listData(120, opts.canArchive ?? false, opts.empty ?? false, opts.canAdmin ?? false)}
query={query}
pipelineOptions={[{ id: "pl1", label: "Sales" }]}
facets={facetsVM(opts.filtered ? { q: "dach" } : {})}
periodFrom=""
periodTo=""
showDemoToggle={opts.showDemoToggle ?? true}
submitting={false}
actions={actions}
/>,
);
return actions;
}
describe("ProjektListPage", () => {
it("renders rows with a detail link and owner label", () => {
renderPage();
expect(screen.getByText("P-1")).toBeTruthy();
expect(screen.getByText("Dach Nord")).toBeTruthy();
// Scoped to the row: the assignee facet offers the same name.
expect(byUiId("ui.projects.list.cell.p1.owner").textContent).toContain("Owner One");
expect((document.body.textContent ?? "").replace(/[\u00a0\u202f]/g, " ")).toContain("10.000,00 €");
});
it("routes a plain row click without reloading the document", () => {
const actions = renderPage();
fireEvent.click(document.querySelector("tr[data-row-id='p1']")!);
expect(actions.onOpenProject).toHaveBeenCalledWith("/acme/projects/p1");
});
it("renders the S03 customer and appointment cells, and both of their absent states", () => {
renderPage();
expect(byUiId("ui.projects.list.cell.p1.customer").textContent).toContain("Bergmann");
// Project type and city share the sub-line rather than one winning.
expect(byUiId("ui.projects.list.cell.p1.customer").textContent).toContain("Privatperson · Ulm");
expect(byUiId("ui.projects.list.cell.p1.appointment").textContent).toContain("Aufmaß");
// A project without a contact or a date shows a dash, not an empty cell.
expect(byUiId("ui.projects.list.cell.p2.customer").textContent).toBe("—");
expect(byUiId("ui.projects.list.cell.p2.appointment").textContent).toBe("—");
});
it("says why an order value is hidden instead of showing a bare dash", () => {
renderPage();
expect(byUiId("ui.projects.list.cell.p2.value").textContent).toContain("projects.listView.valueLocked");
expect(byUiId("ui.projects.list.cell.p1.value").textContent).not.toContain("projects.listView.valueLocked");
});
it("commits search on the search button, and pages", () => {
const actions = renderPage();
fireEvent.change(byUiId("ui.projects.list.search"), { target: { value: " dach " } });
expect(actions.onSearch).not.toHaveBeenCalled();
fireEvent.click(byUiId("ui.projects.list.search.submit"));
expect(actions.onSearch).toHaveBeenCalledWith("dach");
fireEvent.click(byUiId("ui.projects.list.next"));
expect(actions.onGoToPage).toHaveBeenCalledWith(2);
});
it("filters through the shared facets, the same ones the board uses", () => {
const actions = renderPage();
fireEvent.click(byUiId("ui.projects.list.facet.owner.u1"));
expect(actions.onToggleFacet).toHaveBeenCalledWith("owner", "u1");
// The value facet is offered because the fixture viewer may see volumes.
expect(byUiId("ui.projects.list.facet.value")).toBeTruthy();
});
it("includes demo data when the toggle is on", () => {
const actions = renderPage();
fireEvent.click(byUiId("ui.projects.list.demo"));
expect(actions.onToggleDemo).toHaveBeenCalledWith(true);
});
it("hides the demo-data checkbox when the demo UI is disabled (production)", () => {
renderPage({}, { showDemoToggle: false });
expect(document.querySelector('[data-ui-id="ui.projects.list.demo"]')).toBeNull();
});
it("hides bulk-archive selection without the archive permission", () => {
renderPage({}, { canArchive: false });
expect(document.querySelector('[data-ui-id="ui.projects.list.selectAll"]')).toBeNull();
expect(document.querySelector('[data-ui-id="ui.projects.list.select.p1"]')).toBeNull();
});
it("shows the filtered empty state and resets the filters", () => {
const actions = renderPage({}, { empty: true, filtered: true });
expect(byUiId("ui.projects.list.empty")).toBeTruthy();
expect(document.querySelector('[data-ui-id="ui.projects.list.next"]')).toBeNull();
// Footer counter stays visible with the shared-data hint key.
expect(byUiId("ui.projects.list.pagination").textContent).toContain("projects.listView.footerCount");
fireEvent.click(byUiId("ui.projects.list.empty.reset"));
expect(actions.onResetFilters).toHaveBeenCalled();
});
it("renders no table at all when there is nothing to list", () => {
renderPage({}, { empty: true });
// S03a: only the message. A header row over zero rows would claim there is
// a result set to read.
expect(document.querySelector('[data-ui-id="ui.projects.list.table"]')).toBeNull();
expect(document.querySelectorAll("th").length).toBe(0);
// Nothing narrows the list, so there is nothing to reset — only "create".
expect(document.querySelector('[data-ui-id="ui.projects.list.empty.reset"]')).toBeNull();
expect(byUiId("ui.projects.list.empty.create")).toBeTruthy();
});
it("cross-pipeline bulk-archives the selected rows", () => {
const actions = renderPage({}, { canArchive: true });
// Select rows from two different pipelines (Sales + Auftrag).
fireEvent.click(byUiId("ui.projects.list.select.p1"));
fireEvent.click(byUiId("ui.projects.list.select.p2"));
fireEvent.click(byUiId("ui.projects.list.bulk.archive"));
fireEvent.click(byUiId("ui.projects.list.bulk.dialog.confirm"));
expect(actions.onBulkArchive).toHaveBeenCalledTimes(1);
expect(actions.onBulkArchive).toHaveBeenCalledWith(expect.arrayContaining(["p1", "p2"]));
});
it("offers the same board/list switch and quick-create the board screen has", () => {
const actions = renderPage();
expect(byUiId("ui.projects.list.viewToggle")).toBeTruthy();
fireEvent.click(byUiId("ui.projects.list.viewToggle.board"));
expect(actions.onShowBoard).toHaveBeenCalled();
fireEvent.click(byUiId("ui.projects.list.new"));
fireEvent.change(byUiId("ui.projects.list.createDialog.name"), { target: { value: "Neubau Nord" } });
fireEvent.click(byUiId("ui.projects.list.createDialog.confirm"));
expect(actions.onCreateProject).toHaveBeenCalledWith({ projektname: "Neubau Nord", potenziellerAuftragswert: "" });
});
it("hides the quick-create CTA without write permission", () => {
render(
<ProjektListPage
data={{ ...listData(), canWrite: false }}
query={query}
pipelineOptions={[]}
facets={facetsVM()}
periodFrom=""
periodTo=""
showDemoToggle={false}
submitting={false}
actions={actionSpies()}
/>,
);
expect(document.querySelectorAll("[data-ui-id='ui.projects.list.new']").length).toBe(0);
});
it("summarises visible columns in the Select-styled dropdown trigger", () => {
renderPage();
// The column chooser is a dropdown next to the sort filter, not an inline row.
const trigger = byUiId("ui.projects.list.columns.trigger");
expect(trigger).toBeTruthy();
// Every column visible up front -> "all" summary + every header rendered.
// Counted off PROJECT_LIST_COLUMNS so adding an S03 column does not turn
// this into a guessing game about the magic number.
expect(trigger.textContent).toContain("projects.listView.columnsAll");
// +1 for the headerless row-menu column; no bulk-select column without canArchive.
expect(document.querySelectorAll("th").length).toBe(PROJECT_LIST_COLUMNS.length + 1);
});
it("puts the board switcher in the header and the search in the filter bar", () => {
const actions = renderPage();
// Same split as the board view, so switching board <-> list moves neither.
expect(byUiId("ui.projects.list.header").contains(byUiId("ui.projects.list.switcher"))).toBe(true);
expect(byUiId("ui.projects.list.filterBar").contains(byUiId("ui.projects.list.search"))).toBe(true);
// The list is bound to one board, so the switcher offers boards only —
// no "all boards" entry (Subframe flow index dropped that view).
expect(document.querySelector('[data-ui-id="ui.projects.list.switcher.all"]')).toBeNull();
fireEvent.click(byUiId("ui.projects.list.switcher.pl1"));
expect(actions.onSwitchPipeline).toHaveBeenCalledWith("pl1");
});
it("offers the board settings only with the admin permission", () => {
// Same control the board view carries; without projects.admin it is absent.
renderPage();
expect(byUiId("ui.projects.list.settings")).toBeNull();
document.body.innerHTML = "";
const actions = renderPage({}, { canAdmin: true });
fireEvent.click(byUiId("ui.projects.list.settings"));
expect(actions.onManageBoard).toHaveBeenCalled();
});
it("titles the page after the module and renders the S03 column order", () => {
renderPage();
// The H1 names the module; which board is listed is the switcher's job.
expect(document.querySelector("h1")?.textContent).toBe("projects.board.headline");
// Column order of Davids S03 export, each header with its own icon.
const headers = [...document.querySelectorAll("th")].map((th) => th.textContent?.trim());
expect(headers.slice(0, PROJECT_LIST_COLUMNS.length)).toEqual([
"projects.listView.columns.number",
"projects.listView.columns.name",
"projects.listView.columns.board",
"projects.listView.columns.column",
"projects.listView.columns.value",
"projects.listView.columns.customer",
"projects.listView.columns.appointment",
"projects.listView.columns.tags",
"projects.listView.columns.owner",
"projects.listView.columns.updated",
]);
expect(document.querySelectorAll("th svg").length).toBeGreaterThanOrEqual(PROJECT_LIST_COLUMNS.length);
// The project name reads as body text, not as a link colour.
const name = byUiId("ui.projects.list.cell.p1.name").querySelector("a");
expect(name?.className).not.toContain("text-text-feedback-link-default");
expect(name?.getAttribute("href")).toBeTruthy();
});
it("sorts through the filter bar and offers the row menu next to each project", () => {
const actions = renderPage();
// Sort sits in the bar, behind the rule, next to the column chooser.
const bar = byUiId("ui.projects.list.filterBar");
expect(bar.contains(byUiId("ui.projects.list.filter.sort"))).toBe(true);
expect(bar.contains(byUiId("ui.projects.list.columns.trigger"))).toBe(true);
fireEvent.click(byUiId("ui.projects.list.filter.sort"));
fireEvent.click(byUiId("ui.projects.list.filter.sort.name_asc"));
expect(actions.onSort).toHaveBeenCalledWith("name_asc");
expect(byUiId("ui.projects.list.rowMenu.p1")).toBeTruthy();
});
it("shows the project tags in their own column and a dash when a row has none", () => {
renderPage();
expect(byUiId("ui.projects.list.tag.p1.t1").textContent).toContain("PV / Solar");
// p2 carries no tags; the cell must read as empty, not as a missing column.
expect(byUiId("ui.projects.list.tag.p2.t1")).toBeNull();
});
});
@@ -0,0 +1,700 @@
// WF-P8 S03 "Projekt-Liste" — rebuilt against Davids Subframe export of
// 2026-07-28 (page 5c5bdb0a-995e-4c22-aa8b-e48333c60297). Pure/presentational:
// renders the server-built ProjectListData; filter/sort/paging are navigation
// callbacks, column visibility is a client toggle, CSV export is a link. No
// useLoaderData/useFetcher, no server imports.
//
// The list is bound to one board, as the export's flow index states: it shows
// the projects of the selected pipeline and keeps "Board" as a column. Bulk
// archive (RA-C2) therefore acts within that board; the archive intent itself
// is id-based and the server enforces per-project edit scope, so a later
// cross-board selection would not need a different write path.
//
// The export gives list and board the same filter bar, so this screen renders
// the shared BoardFilterBar with the loader-built facet view model instead of
// keeping a second, narrower owner select. Sort and column visibility have no
// counterpart on the board and sit in the bar's trailing slot.
import { useMemo, useState, type MouseEvent, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import {
FeatherArchive,
FeatherArrowUpDown,
FeatherBuilding,
FeatherCalendar,
FeatherCheck,
FeatherChevronDown,
FeatherChevronRight,
FeatherCircleDot,
FeatherClock,
FeatherCoins,
FeatherColumns,
FeatherExternalLink,
FeatherFileText,
FeatherHash,
FeatherKanban,
FeatherKanbanSquare,
FeatherList,
FeatherLock,
FeatherMoreHorizontal,
FeatherPlus,
FeatherRotateCcw,
FeatherSearchX,
FeatherSettings2,
FeatherTag,
FeatherTrendingUp,
FeatherUser,
FeatherX,
} from "@subframe/core";
import * as SubframeCore from "@subframe/core";
import type { BoardFacet, BoardFacetChip, BoardFacetsVM, ProjectListColumnKey, ProjectListData } from "@hivegrid/view-models";
import { BoardFilterBar } from "./BoardFilterBar";
import { tagTone } from "./tagTone";
import { Avatar } from "~/ui/components/Avatar";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Checkbox } from "~/ui/components/Checkbox";
import { Dialog } from "~/ui/components/Dialog";
import { DropdownMenu } from "~/ui/components/DropdownMenu";
import { DropdownMenuMultiSelect } from "~/ui/components/DropdownMenuMultiSelect";
import { FilterBar } from "~/ui/components/FilterBar";
import { IconButton } from "~/ui/components/IconButton";
import { Table } from "~/ui/components/Table";
import { Tag_Label } from "~/ui/components/Tag_Label";
import { TextInput } from "~/ui/components/TextInput";
import { ToggleGroup } from "~/ui/components/ToggleGroup";
import { APP_TIME_ZONE } from "~/locale/format";
import { AppLink } from "~/components/app/AppLink";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
export type ProjectListQuery = {
pipelineId: string;
q: string;
onlyMine: boolean;
includeDemoData: boolean;
sort: string;
};
export type ProjectListOption = { id: string; label: string };
const cellStrong = "whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary";
/** Header icon per column, as the S03 export labels them. */
const COLUMN_ICON: Record<ProjectListColumnKey, ReactNode> = {
number: <FeatherHash />,
name: <FeatherFileText />,
pipeline: <FeatherKanban />,
stage: <FeatherCircleDot />,
value: <FeatherCoins />,
customer: <FeatherBuilding />,
appointment: <FeatherCalendar />,
tags: <FeatherTag />,
owner: <FeatherUser />,
updated: <FeatherClock />,
};
const cellMuted = "whitespace-nowrap text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary";
/** Two-letter avatar fallback, same rule the board card uses. */
function initialsOf(label: string): string {
return label
.split(/\s+/)
.filter(Boolean)
.slice(0, 2)
.map((part) => part[0]?.toUpperCase() ?? "")
.join("");
}
export type ProjektListActions = {
onShowBoard: () => void;
onOpenProject: (detailHref: string) => void;
/** Opens the settings of the listed board — same target as on the board view. */
onManageBoard: () => void;
/** Quick-create, same contract as the board screen: the route POSTs it. */
onCreateProject: (fields: { projektname: string; potenziellerAuftragswert: string }) => void;
/** Board picker of the header chip. The list is always bound to one board. */
onSwitchPipeline: (pipelineId: string) => void;
onSearch: (q: string) => void;
onToggleOnlyMine: (checked: boolean) => void;
onToggleDemo: (checked: boolean) => void;
onToggleFacet: (facet: BoardFacet["key"], value: string) => void;
onRemoveChip: (chip: BoardFacetChip) => void;
onResetFilters: () => void;
onPeriodRangeChange: (from: string, to: string) => void;
onSort: (sort: string) => void;
onGoToPage: (page: number) => void;
/** Cross-pipeline bulk archive of the selected rows (server enforces edit scope). */
onBulkArchive: (projectIds: string[]) => void;
};
export type ProjektListPageProps = {
data: ProjectListData;
query: ProjectListQuery;
pipelineOptions: readonly ProjectListOption[];
/** S01 filter bar, built by the loader — same view model as the board. */
facets: BoardFacetsVM;
periodFrom: string;
periodTo: string;
/** Demo-data toggle is a staging/dev-only affordance (env-gated by the loader). */
showDemoToggle: boolean;
submitting: boolean;
language?: string;
actions: ProjektListActions;
};
const SORTS = ["updated_desc", "updated_asc", "name_asc", "name_desc", "number_asc", "value_desc"] as const;
export function ProjektListPage(props: ProjektListPageProps) {
const { t, i18n } = useTranslation();
const { data, query } = props;
const dateFmt = new Intl.DateTimeFormat(props.language ?? i18n.language, { timeZone: APP_TIME_ZONE, dateStyle: "medium" });
const [visibleColumns, setVisibleColumns] = useState<ReadonlySet<ProjectListColumnKey>>(new Set(data.columns.map((c) => c.key)));
// Bulk selection (RA-C2) is keyed by project id and spans the stages of the
// listed board; the server validates each project's own edit scope.
const [selected, setSelected] = useState<ReadonlySet<string>>(new Set());
const [confirmArchive, setConfirmArchive] = useState(false);
// Creating a project is a short form, so the CTA opens the same quick-create
// dialog the board screen uses instead of navigating away from the list.
const [createOpen, setCreateOpen] = useState(false);
const [draft, setDraft] = useState({ projektname: "", potenziellerAuftragswert: "" });
const columns = useMemo(() => data.columns.filter((column) => visibleColumns.has(column.key)), [data.columns, visibleColumns]);
// Header chip mirrors the Pipeline-Board headline: shows the active pipeline filter.
const selectedPipeline = query.pipelineId ? props.pipelineOptions.find((option) => option.id === query.pipelineId) ?? null : null;
const selectableIds = useMemo(() => data.rows.map((row) => row.id), [data.rows]);
const allSelected = selectableIds.length > 0 && selectableIds.every((id) => selected.has(id));
function toggleRow(id: string, checked: boolean) {
setSelected((prev) => {
const next = new Set(prev);
if (checked) next.add(id);
else next.delete(id);
return next;
});
}
function toggleAll(checked: boolean) {
setSelected(checked ? new Set(selectableIds) : new Set());
}
function confirmBulkArchive() {
props.actions.onBulkArchive([...selected]);
setSelected(new Set());
setConfirmArchive(false);
}
// Whether anything is narrowing the list. Decides which empty state the screen
// tells: "no match, reset" vs. "this board has no projects yet".
const filterActive = props.facets.hasActiveFilters;
// Reset drops search, only-mine and every facet in one navigation (sort stays
// untouched, it is not a filter).
function resetFilter() {
props.actions.onResetFilters();
}
/**
* Row click opens the project, like the name link does. Clicks that landed on
* a control inside the row (select checkbox, row menu, the name link itself)
* keep their own behaviour, and a click that only ended a text selection is
* not a navigation request either.
*/
function openRow(event: MouseEvent<HTMLTableRowElement>, detailHref: string) {
const target = event.target as HTMLElement | null;
if (target?.closest("a,button,input,label,[role='menuitem'],[role='checkbox']")) return;
if (window.getSelection()?.toString()) return;
props.actions.onOpenProject(detailHref);
}
function toggleColumn(key: ProjectListColumnKey, checked: boolean) {
setVisibleColumns((prev) => {
const next = new Set(prev);
if (checked) next.add(key);
else next.delete(key);
return next;
});
}
/**
* WF-P8 S03 cell renderer. Each column carries its own shape in the export -
* the board is a tag, the column a badge, a blocked value says so instead of
* showing a dash, and the customer cell is two lines. A single string
* renderer cannot express that, so cells return nodes.
*/
function cell(row: ProjectListData["rows"][number], key: ProjectListColumnKey): ReactNode {
switch (key) {
case "number":
return <span className={cellStrong}>{row.projektNummer}</span>;
case "name":
// Same affordance as every other table that opens a record (e.g. the
// board admin list): link colour plus a chevron, so the row reads as
// "click me to open" instead of as static text. The whole row carries
// the click; the anchor keeps it reachable by keyboard.
return (
<AppLink
href={row.detailHref}
className="flex items-center gap-1 no-underline hover:underline"
data-ui-id={`ui.projects.list.open.${row.id}`}
>
<span className="whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 text-text-feedback-link-default">
{row.projektname}
</span>
<FeatherChevronRight aria-hidden className="text-body-small-regular-0 text-text-feedback-link-default" />
</AppLink>
);
case "pipeline":
return (
<Tag_Label tone="sky-subtle" noAction size="small">
{row.pipelineName}
</Tag_Label>
);
case "stage":
return (
<BadgeFeedback farbe="subtle-neutral" size="small">
{row.stageName}
</BadgeFeedback>
);
case "value":
// A viewer without volume access gets the reason, not a dash that reads
// like "this project has no value".
return row.valueVisible ? (
<span className={cellStrong}>{row.value ?? "—"}</span>
) : (
<span className="flex items-center gap-1.5 text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
<FeatherLock aria-hidden />
{t("projects.listView.valueLocked")}
</span>
);
case "customer":
return row.customerLabel ? (
<span className="flex flex-col items-start gap-0.5">
<span className={cellMuted}>{row.customerLabel}</span>
{row.customerSubLabel ? (
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{row.customerSubLabel}
</span>
) : null}
</span>
) : (
<span className={cellMuted}>—</span>
);
case "tags":
return row.tags.length > 0 ? (
<span className="flex flex-wrap items-center gap-1">
{row.tags.map((tag) => (
<Tag_Label key={tag.id} tone={tagTone(tag.farbe)} noAction size="small" data-ui-id={`ui.projects.list.tag.${row.id}.${tag.id}`}>
{tag.name}
</Tag_Label>
))}
</span>
) : (
<span className={cellMuted}>—</span>
);
case "appointment":
return row.appointmentIso ? (
<Tag_Label tone="blue-subtle" noAction size="small">
{[row.appointmentTitle, dateFmt.format(new Date(row.appointmentIso))].filter(Boolean).join(" · ")}
</Tag_Label>
) : (
<span className={cellMuted}>—</span>
);
case "owner":
return row.ownerLabel ? (
<span className="flex items-center gap-2">
<Avatar size="extra-small">{initialsOf(row.ownerLabel)}</Avatar>
<span className={cellMuted}>{row.ownerLabel}</span>
</span>
) : (
<span className={cellMuted}>{t("projects.fields.none")}</span>
);
case "updated":
return <span className={cellMuted}>{dateFmt.format(new Date(row.updatedAtIso))}</span>;
default:
return null;
}
}
return (
<PageShell uiId="ui.projects.list" className="bg-surface-neutral-primary">
<PageHeader
uiId="ui.projects.list.header"
dense
icon={<FeatherKanbanSquare className={PAGE_HEADER_ICON_CLASS} />}
// Same headline rule as the board view: the module names the page, the
// switcher behind the rule says which board is being listed.
title={t("projects.board.headline")}
titleTrailing={
<>
{/* Board switcher as a header chip, same control as on the board. */}
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<button
type="button"
className="flex items-center gap-2 rounded-md border border-solid border-border-default bg-surface-neutral-primary px-3 py-1.5 hover:bg-surface-neutral-tertiary"
data-ui-id="ui.projects.list.switcher"
aria-label={t("projects.fields.pipeline")}
>
<FeatherTrendingUp className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
<span className="break-words text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary">
{selectedPipeline?.label ?? t("projects.list.title")}
</span>
<FeatherChevronDown className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
</button>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="start" sideOffset={4} asChild>
<DropdownMenu>
{props.pipelineOptions.map((option) => (
<DropdownMenu.DropdownItem
key={option.id}
icon={option.id === query.pipelineId ? <FeatherCheck /> : null}
onClick={() => props.actions.onSwitchPipeline(option.id)}
data-ui-id={`ui.projects.list.switcher.${option.id}`}
>
{option.label}
</DropdownMenu.DropdownItem>
))}
</DropdownMenu>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
</>
}
actions={
<>
<ToggleGroup
value="list"
onValueChange={(value: string) => value === "board" && props.actions.onShowBoard()}
data-ui-id="ui.projects.list.viewToggle"
>
<ToggleGroup.Item icon={<FeatherColumns />} value="board" aria-label={t("projects.viewMode.board")} data-ui-id="ui.projects.list.viewToggle.board">
{t("projects.viewMode.board")}
</ToggleGroup.Item>
<ToggleGroup.Item icon={<FeatherList />} value="list" aria-label={t("projects.viewMode.list")} data-ui-id="ui.projects.list.viewToggle.list">
{t("projects.viewMode.list")}
</ToggleGroup.Item>
</ToggleGroup>
{data.canAdmin ? (
<Button
variant="tertiary"
icon={<FeatherSettings2 />}
onClick={props.actions.onManageBoard}
data-ui-id="ui.projects.list.settings"
>
{t("projects.board.contextMenu.settings")}
</Button>
) : null}
{data.canWrite ? (
<Button icon={<FeatherPlus />} onClick={() => setCreateOpen(true)} data-ui-id="ui.projects.list.new">
{t("projects.actions.newProject")}
</Button>
) : null}
</>
}
/>
{/* --- Filter bar (S01): the list shares the board's bar, so both views
filter through one definition. Sort and column visibility are list-only
view controls; they wear the facet buttons' looks but stand behind the
rule, in their own compartment before the only-mine switch. --- */}
<BoardFilterBar
uiId="ui.projects.list"
facets={props.facets}
search={query.q}
onSearch={props.actions.onSearch}
onlyMine={query.onlyMine}
onToggleOnlyMine={props.actions.onToggleOnlyMine}
onToggleFacet={props.actions.onToggleFacet}
onRemoveChip={props.actions.onRemoveChip}
onReset={resetFilter}
periodFrom={props.periodFrom}
periodTo={props.periodTo}
onPeriodRangeChange={props.actions.onPeriodRangeChange}
afterDivider={
<>
{/* Sorting: the button carries the active criterion as its label, so
the bar states how the list is ordered without opening it. */}
<FilterBar.StatusFilterButton
icon={<FeatherArrowUpDown />}
label={t(`projects.sort.${query.sort}`)}
count=""
data-ui-id="ui.projects.list.filter.sort"
dropdown={
<DropdownMenuMultiSelect>
{SORTS.map((sort) => (
<DropdownMenuMultiSelect.DropdownItem
key={sort}
showCheckbox
selected={sort === query.sort}
onClick={() => props.actions.onSort(sort)}
data-ui-id={`ui.projects.list.filter.sort.${sort}`}
>
{t(`projects.sort.${sort}`)}
</DropdownMenuMultiSelect.DropdownItem>
))}
</DropdownMenuMultiSelect>
}
/>
{/* Which columns are on screen — a view control, not a filter. */}
<FilterBar.StatusFilterButton
icon={<FeatherColumns />}
label={
visibleColumns.size === data.columns.length
? t("projects.listView.columnsAll")
: t("projects.listView.columnsCount", { count: visibleColumns.size, total: data.columns.length })
}
count=""
data-ui-id="ui.projects.list.columns.trigger"
dropdown={
<DropdownMenuMultiSelect>
{data.columns.map((column) => (
<DropdownMenuMultiSelect.DropdownItem
key={column.key}
showCheckbox
selected={visibleColumns.has(column.key)}
onClick={() => toggleColumn(column.key, !visibleColumns.has(column.key))}
data-ui-id={`ui.projects.list.columns.item.${column.key}`}
>
{t(column.labelKey)}
</DropdownMenuMultiSelect.DropdownItem>
))}
</DropdownMenuMultiSelect>
}
/>
{/* Staging/dev affordance — kept inside the view-control block so
the only-mine switch stays the last control of the bar. */}
{props.showDemoToggle ? (
<Checkbox
checked={query.includeDemoData}
onCheckedChange={props.actions.onToggleDemo}
label={t("onboarding.demoData.showInLists")}
data-ui-id="ui.projects.list.demo"
/>
) : null}
</>
}
/>
<PageBody>
{/* --- Cross-pipeline bulk bar (archive) --- */}
{data.canArchive && selected.size > 0 ? (
<div className="flex w-full flex-wrap items-center gap-3" data-ui-id="ui.projects.list.bulk">
<BadgeFeedback farbe="subtle-neutral" size="small">{t("projects.listView.selectedCount", { count: selected.size })}</BadgeFeedback>
<Button variant="destructive" size="small" icon={<FeatherArchive />} loading={props.submitting} onClick={() => setConfirmArchive(true)} data-ui-id="ui.projects.list.bulk.archive">
{t("projects.listView.bulkArchive")}
</Button>
<Button variant="neutral" size="small" onClick={() => setSelected(new Set())} data-ui-id="ui.projects.list.bulk.clear">
{t("projects.listView.clearSelection")}
</Button>
</div>
) : null}
{data.rows.length === 0 ? (
// Empty state (S03a): the message stands in place of the table. A header
// row over no rows would claim there is a result set to read, so the
// table does not render at all. Reset only where a filter narrows.
<div className="w-full" data-ui-id="ui.projects.list.empty">
<div className="flex min-h-[360px] w-full flex-col items-center justify-center rounded-lg border border-solid border-border-default bg-surface-neutral-primary px-6 py-16 shadow-sm">
<div className="flex max-w-[384px] flex-col items-center gap-5">
<FeatherSearchX className="text-subtitle font-subtitle text-icon-neutral-subtle" />
<div className="flex flex-col items-center gap-1.5">
<span className="text-center text-body-default-semibold-150 font-body-default-semibold-150 text-text-neutral-primary">
{t("projects.listView.emptyFiltered.title")}
</span>
<span className="text-center text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t(filterActive ? "projects.listView.emptyFiltered.body" : "projects.board.emptyHint")}
</span>
</div>
<div className="flex items-center gap-2 mobile:flex-col mobile:items-stretch">
{filterActive ? (
<Button variant="tertiary" size="small" icon={<FeatherRotateCcw />} onClick={resetFilter} data-ui-id="ui.projects.list.empty.reset">
{t("projects.listView.emptyFiltered.reset")}
</Button>
) : null}
{data.canWrite ? (
<Button size="small" icon={<FeatherPlus />} onClick={() => setCreateOpen(true)} data-ui-id="ui.projects.list.empty.create">
{t("projects.board.emptyFiltered.create")}
</Button>
) : null}
</div>
</div>
</div>
</div>
) : (
<div className="flex w-full flex-col items-start overflow-hidden overflow-x-auto rounded-lg border border-solid border-border-default shadow-sm">
<Table
data-ui-id="ui.projects.list.table"
header={
<Table.HeaderRow className="bg-surface-neutral-tertiary">
{data.canArchive ? (
<Table.HeaderCell>
<Checkbox
checked={allSelected}
onCheckedChange={toggleAll}
hideLabel
label={t("projects.listView.selectAll")}
data-ui-id="ui.projects.list.selectAll"
/>
</Table.HeaderCell>
) : null}
{columns.map((column) => (
<Table.HeaderCell key={column.key} icon={COLUMN_ICON[column.key]}>
{t(column.labelKey)}
</Table.HeaderCell>
))}
{/* Row menu column — headerless, like the export. */}
<Table.HeaderCell />
</Table.HeaderRow>
}
>
{data.rows.map((row) => (
<Table.Row
key={row.id}
data-row-id={row.id}
clickable
className="cursor-pointer"
onClick={(event) => openRow(event, row.detailHref)}
>
{data.canArchive ? (
<Table.Cell>
<Checkbox
checked={selected.has(row.id)}
onCheckedChange={(c) => toggleRow(row.id, c)}
hideLabel
label={row.projektname}
data-ui-id={`ui.projects.list.select.${row.id}`}
/>
</Table.Cell>
) : null}
{columns.map((column) => (
<Table.Cell key={column.key} data-ui-id={`ui.projects.list.cell.${row.id}.${column.key}`}>
{cell(row, column.key)}
</Table.Cell>
))}
<Table.Cell variant="align-right">
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<IconButton
variant="ghost"
size="small"
icon={<FeatherMoreHorizontal />}
aria-label={t("projects.listView.rowMenu")}
data-ui-id={`ui.projects.list.rowMenu.${row.id}`}
/>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="end" sideOffset={4} asChild>
<DropdownMenu>
<DropdownMenu.DropdownItem
icon={<FeatherExternalLink />}
onClick={() => props.actions.onOpenProject(row.detailHref)}
data-ui-id={`ui.projects.list.rowMenu.${row.id}.open`}
>
{t("projects.listView.openProject")}
</DropdownMenu.DropdownItem>
{data.canArchive ? (
<DropdownMenu.DropdownItem
icon={<FeatherArchive />}
onClick={() => props.actions.onBulkArchive([row.id])}
data-ui-id={`ui.projects.list.rowMenu.${row.id}.archive`}
>
{t("projects.actions.archive")}
</DropdownMenu.DropdownItem>
) : null}
</DropdownMenu>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
</Table.Cell>
</Table.Row>
))}
</Table>
</div>
)}
{/* Footer: total counter (shared data basis with the Kanban board) + paging. */}
<div className="flex w-full items-center justify-between gap-2" data-ui-id="ui.projects.list.pagination">
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{t("projects.listView.footerCount", { count: data.total })}
</span>
{data.rows.length > 0 ? (
<div className="flex items-center gap-2">
<Button variant="neutral" size="small" disabled={!data.hasPrev} onClick={() => props.actions.onGoToPage(data.page - 1)} data-ui-id="ui.projects.list.prev">
{t("projects.actions.prevPage")}
</Button>
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">{data.page} / {data.pageCount}</span>
<Button variant="neutral" size="small" disabled={!data.hasNext} onClick={() => props.actions.onGoToPage(data.page + 1)} data-ui-id="ui.projects.list.next">
{t("projects.actions.nextPage")}
</Button>
</div>
) : null}
</div>
</PageBody>
{/* --- Bulk archive confirm dialog --- */}
<Dialog open={confirmArchive} onOpenChange={setConfirmArchive}>
<Dialog.Content className="p-6" data-ui-id="ui.projects.list.bulk.dialog">
<div className="flex w-full flex-col gap-4" style={{ minWidth: 420 }}>
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{t("projects.listView.bulkArchiveTitle")}</span>
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{t("projects.listView.bulkArchiveBody", { count: selected.size })}
</span>
<div className="flex justify-end gap-2">
<Button variant="neutral" onClick={() => setConfirmArchive(false)}>{t("projects.actions.cancel")}</Button>
<Button variant="destructive" loading={props.submitting} onClick={confirmBulkArchive} data-ui-id="ui.projects.list.bulk.dialog.confirm">
{t("projects.listView.bulkArchive")}
</Button>
</div>
</div>
</Dialog.Content>
</Dialog>
{/* --- Quick-create dialog (interim-UI shell mirroring TaskNewDialog) --- */}
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
<Dialog.Content className="w-[440px] max-w-[92vw] p-0" data-ui-id="ui.projects.list.createDialog">
<div className="flex w-full flex-col">
<div className="flex w-full items-start justify-between gap-3 border-b border-solid border-border-default bg-surface-neutral-secondary px-6 py-5 mobile:px-4">
<div className="flex flex-col items-start gap-1">
<span className="text-heading- font-heading- text-text-neutral-primary">{t("projects.actions.newProject")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("projects.createDialog.subtitle")}</span>
</div>
<IconButton type="button" variant="ghost" size="small" icon={<FeatherX />} aria-label={t("projects.actions.cancel")} onClick={() => setCreateOpen(false)} />
</div>
<div className="flex w-full flex-col gap-4 px-6 py-5 max-h-[65vh] overflow-y-auto mobile:px-4">
<TextInput label={t("projects.fields.name")} showLabel>
<TextInput.Input
autoFocus
value={draft.projektname}
onChange={(e) => setDraft((d) => ({ ...d, projektname: e.target.value }))}
data-ui-id="ui.projects.list.createDialog.name"
/>
</TextInput>
</div>
<div className="flex w-full items-center justify-end gap-2 border-t border-solid border-border-default bg-surface-neutral-secondary px-6 py-4 mobile:flex-col-reverse mobile:items-stretch mobile:px-4">
<Button type="button" className="mobile:w-full" variant="tertiary" onClick={() => setCreateOpen(false)}>{t("projects.actions.cancel")}</Button>
<Button
className="mobile:w-full"
icon={<FeatherPlus />}
disabled={!draft.projektname.trim()}
loading={props.submitting}
onClick={() => {
props.actions.onCreateProject({ projektname: draft.projektname.trim(), potenziellerAuftragswert: draft.potenziellerAuftragswert.trim() });
setCreateOpen(false);
setDraft({ projektname: "", potenziellerAuftragswert: "" });
}}
data-ui-id="ui.projects.list.createDialog.confirm"
>
{t("projects.actions.create")}
</Button>
</div>
</div>
</Dialog.Content>
</Dialog>
</PageShell>
);
}
export default ProjektListPage;
@@ -0,0 +1,3 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`R-P9 operations interim visual baseline > renders the plantafel, acceptance list, and sub-areas surfaces from ~/ui 1`] = `"<div><main data-ui-id="ui.projects.operations.interim.visualBaseline"><div class="flex w-full flex-col items-start min-w-0" data-ui-id="ui.projects.plantafel"><div class="flex w-full items-start gap-4 border-b border-solid border-border-default bg-surface-neutral-secondary px-6 py-5 mobile:flex-col mobile:px-4"><div class="flex grow shrink-0 basis-0 flex-col items-start gap-1"><div class="flex items-center gap-2"><span class="text-heading- font-heading- text-icon-neutral-tertiary icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><h1 class="text-subtitle font-subtitle text-text-neutral-primary mobile:text-heading- mobile:font-heading-">projects.plantafel.title</h1></div><p class="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">projects.plantafel.subtitle</p></div><div class="flex items-center gap-2 mobile:w-full mobile:flex-none mobile:flex-wrap"><div class="flex flex-wrap items-center gap-2"><div class="group/896531e4 flex h-6 items-center gap-2 rounded-round px-2.5 py-1 bg-surface-feedback-subtle-neutral"><div class="flex h-1 w-1 flex-none flex-col items-start gap-2 rounded-round bg-icon-neutral-on-subtle"></div><span class="whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-on-subtle">projects.plantafel.entries:2</span></div><div class="group/896531e4 flex h-6 items-center gap-2 rounded-round px-2.5 py-1 bg-surface-feedback-subtle-warning"><div class="flex h-1 w-1 flex-none flex-col items-start gap-2 rounded-round bg-icon-feedback-warning"></div><span class="whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-on-subtle">projects.plantafel.conflicts:1</span></div><div class="group/896531e4 flex h-6 items-center gap-2 rounded-round px-2.5 py-1 bg-surface-feedback-subtle-information"><div class="flex h-1 w-1 flex-none flex-col items-start gap-2 rounded-round bg-icon-feedback-information"></div><span class="whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-on-subtle">projects.plantafel.absences:1</span></div><div class="group/2026f10a flex h-9 items-center gap-0.5 overflow-hidden rounded-md border border-solid border-border-default bg-surface-neutral-tertiary px-0.5 py-0.5" role="group" dir="ltr" data-ui-id="ui.projects.plantafel.viewToggle" tabindex="0" data-orientation="horizontal" style="outline: none;"><div class="group/56dea6ed flex h-full w-full cursor-pointer items-center justify-center gap-2 rounded-md px-3.5 py-2.5 group-[.is-small]/2026f10a:px-3 group-[.is-small]/2026f10a:py-2 group-[.is-large]/2026f10a:gap-2.5 group-[.is-large]/2026f10a:px-5 group-[.is-large]/2026f10a:py-3.5 hover:bg-surface-neutral-primary aria-[checked=true]:bg-brand-brand-surface-solid-default hover:aria-[checked=true]:bg-brand-brand-surface-solid-hover active:aria-[checked=true]:bg-brand-brand-surface-solid-active" type="button" data-state="on" role="radio" aria-checked="true" aria-label="projects.plantafel.viewMode.table" data-ui-id="ui.projects.plantafel.viewToggle.table" tabindex="-1" data-orientation="horizontal" data-radix-collection-item=""><span class="text-body-small-medium-0 font-body-small-medium-0 text-icon-neutral-primary group-disabled/56dea6ed:text-icon-neutral-disabled group-[.is-disabled]/2026f10a:text-icon-neutral-disabled group-[.is-large]/2026f10a:text-body-large-0 group-[.is-large]/2026f10a:font-body-large-0 group-aria-[checked=true]/56dea6ed:text-icon-neutral-on-solid icon-wrapper-module_root__-l6uP"><span class="icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span></span><span class="whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary group-disabled/56dea6ed:text-text-neutral-disabled group-[.is-disabled]/2026f10a:text-text-neutral-disabled group-[.is-large]/2026f10a:text-body-large-0 group-[.is-large]/2026f10a:font-body-large-0 group-aria-[checked=true]/56dea6ed:text-text-neutral-on-solid">projects.plantafel.viewMode.table</span></div><div class="group/56dea6ed flex h-full w-full cursor-pointer items-center justify-center gap-2 rounded-md px-3.5 py-2.5 group-[.is-small]/2026f10a:px-3 group-[.is-small]/2026f10a:py-2 group-[.is-large]/2026f10a:gap-2.5 group-[.is-large]/2026f10a:px-5 group-[.is-large]/2026f10a:py-3.5 hover:bg-surface-neutral-primary aria-[checked=true]:bg-brand-brand-surface-solid-default hover:aria-[checked=true]:bg-brand-brand-surface-solid-hover active:aria-[checked=true]:bg-brand-brand-surface-solid-active" type="button" data-state="off" role="radio" aria-checked="false" aria-label="projects.plantafel.viewMode.calendar" data-ui-id="ui.projects.plantafel.viewToggle.calendar" tabindex="-1" data-orientation="horizontal" data-radix-collection-item=""><span class="text-body-small-medium-0 font-body-small-medium-0 text-icon-neutral-primaLine truncated
@@ -0,0 +1,23 @@
// WF-P8 board type visuals, shared by the S00 boards start page and the S07
// board table. Both screens list the same boards; keeping one copy of the
// icon/tone mapping is what stops a board from reading "Vertrieb blau" on one
// screen and something else on the other.
import type { ReactNode } from "react";
import { FeatherHardHat, FeatherPuzzle, FeatherTrendingUp } from "@subframe/core";
export type BoardTypHint = "sales" | "auftrag" | "custom";
/** Board type → row icon, mirroring Davids export. */
export const BOARD_TYP_ICON: Record<BoardTypHint, ReactNode> = {
sales: <FeatherTrendingUp />,
auftrag: <FeatherHardHat />,
custom: <FeatherPuzzle />,
};
/** Board type → Tag tone (Vertrieb blau, Auftrag violett, Eigenes sand). */
export const BOARD_TYP_TONE: Record<BoardTypHint, "blue-subtle" | "violet-subtle" | "sand-subtle"> = {
sales: "blue-subtle",
auftrag: "violet-subtle",
custom: "sand-subtle",
};
@@ -0,0 +1,224 @@
// WF-P8 S02 "Firma oder Kontakt hinzufügen" — the block below the contact cards
// with Davids three paths.
//
// Searching and creating are two dialogs, not one form with a mode switch: the
// search needs a result list and the creation needs name fields, and putting
// both behind one control would hide half of it at any time.
//
// The search hits the loader-only `contact-search` resource of this project, so
// a keystroke costs one contact query instead of re-running the whole detail
// loader. Creation goes through the CRM service on the server side, so a project
// never becomes a second place where contacts are born.
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherBuilding2, FeatherPlus, FeatherSearch, FeatherUserPlus } from "@subframe/core";
import * as SubframeCore from "@subframe/core";
import { Button } from "~/ui/components/Button";
import { Dialog } from "~/ui/components/Dialog";
import { DropdownMenu } from "~/ui/components/DropdownMenu";
import { TextInput } from "~/ui/components/TextInput";
import { labelText, mutedText, sectionHeading, type ProjektDetailSubmit } from "./detailUi";
export type AddKontaktBlockProps = {
/** Search endpoint of this project (loader-only JSON resource). */
searchHref: string;
submitting: boolean;
submit: ProjektDetailSubmit;
};
type SearchRow = { id: string; label: string; kontaktTyp: "organisation" | "privatperson"; email: string | null };
type Mode = "search" | "person" | "company";
export function AddKontaktBlock({ searchHref, submitting, submit }: AddKontaktBlockProps) {
const { t } = useTranslation();
const [mode, setMode] = useState<Mode | null>(null);
const [query, setQuery] = useState("");
const [rows, setRows] = useState<SearchRow[]>([]);
const [searchState, setSearchState] = useState<"idle" | "loading" | "failed">("idle");
const [draft, setDraft] = useState({ vorname: "", nachname: "", orgName: "", email: "" });
// Debounced, and aborted on the next keystroke: without the abort a slow early
// response can overwrite the results of a later, narrower query.
useEffect(() => {
if (mode !== "search") return;
const controller = new AbortController();
const timer = setTimeout(() => {
setSearchState("loading");
fetch(`${searchHref}?q=${encodeURIComponent(query)}`, { signal: controller.signal })
.then((response) => (response.ok ? response.json() : Promise.reject(new Error(String(response.status)))))
.then((data: { rows: SearchRow[] }) => {
setRows(data.rows);
setSearchState("idle");
})
.catch((error: unknown) => {
if (error instanceof DOMException && error.name === "AbortError") return;
setSearchState("failed");
});
}, 250);
return () => {
controller.abort();
clearTimeout(timer);
};
}, [mode, query, searchHref]);
function close() {
setMode(null);
setQuery("");
setRows([]);
setSearchState("idle");
setDraft({ vorname: "", nachname: "", orgName: "", email: "" });
}
function link(kontaktId: string) {
submit("linkKontakt", { kontaktId });
close();
}
function create(kontaktTyp: "privatperson" | "organisation") {
submit("createKontakt", {
kontaktTyp,
vorname: draft.vorname,
nachname: draft.nachname,
orgName: draft.orgName,
email: draft.email,
});
close();
}
const createDisabled = mode === "person" ? !draft.nachname.trim() : !draft.orgName.trim();
return (
<div className="flex w-full flex-col gap-2 px-3 pb-1" data-ui-id="ui.projects.detail.contacts.add">
{/* Rule between the linked contacts and the way to add one, as in the
export: the button belongs to the tile, not to the last contact. */}
{/* Same hairline the field rows use, so the tile has one kind of rule. */}
<div className="h-px w-full flex-none bg-icon-neutral-subtle" />
{/* The export closes the tile with one dark button. The three paths stay —
they are three separate dialogs — but they hang behind that button
instead of standing next to each other in the tile. */}
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<Button className="w-3/5 justify-center mobile:w-full" size="small" icon={<FeatherPlus />} data-ui-id="ui.projects.detail.contacts.add.trigger">
{t("projects.detail.contacts.add.title")}
</Button>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="start" sideOffset={4} asChild>
<DropdownMenu>
<DropdownMenu.DropdownItem icon={<FeatherSearch />} onSelect={() => setMode("search")} data-ui-id="ui.projects.detail.contacts.add.search">
{t("projects.detail.contacts.add.search")}
</DropdownMenu.DropdownItem>
<DropdownMenu.DropdownItem icon={<FeatherUserPlus />} onSelect={() => setMode("person")} data-ui-id="ui.projects.detail.contacts.add.person">
{t("projects.detail.contacts.add.person")}
</DropdownMenu.DropdownItem>
<DropdownMenu.DropdownItem icon={<FeatherBuilding2 />} onSelect={() => setMode("company")} data-ui-id="ui.projects.detail.contacts.add.company">
{t("projects.detail.contacts.add.company")}
</DropdownMenu.DropdownItem>
</DropdownMenu>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
<Dialog open={mode === "search"} onOpenChange={(open) => (open ? null : close())}>
<Dialog.Content className="p-6" data-ui-id="ui.projects.detail.contacts.add.searchDialog">
<div className="flex w-full flex-col gap-3">
<span className={sectionHeading}>{t("projects.detail.contacts.add.search")}</span>
<TextInput label="" className="w-full" icon={<FeatherSearch />}>
<TextInput.Input
placeholder={t("projects.detail.contacts.add.searchPlaceholder")}
value={query}
onChange={(event) => setQuery(event.target.value)}
data-ui-id="ui.projects.detail.contacts.add.searchInput"
/>
</TextInput>
{searchState === "failed" ? (
<span className={mutedText} data-ui-id="ui.projects.detail.contacts.add.searchError">
{t("projects.detail.contacts.add.searchFailed")}
</span>
) : null}
{searchState !== "failed" && rows.length === 0 ? (
<span className={mutedText}>{t("projects.detail.contacts.add.searchEmpty")}</span>
) : null}
<div className="flex max-h-[280px] w-full flex-col gap-1 overflow-y-auto">
{rows.map((row) => (
<button
key={row.id}
type="button"
className="flex w-full items-center justify-between gap-3 rounded-md px-2 py-2 text-left hover:bg-surface-neutral-tertiary"
onClick={() => link(row.id)}
disabled={submitting}
data-ui-id={`ui.projects.detail.contacts.add.result.${row.id}`}
>
<span className={labelText}>{row.label}</span>
<span className={mutedText}>{row.email ?? t(`crm.kontaktTyp.${row.kontaktTyp}`)}</span>
</button>
))}
</div>
</div>
</Dialog.Content>
</Dialog>
<Dialog open={mode === "person" || mode === "company"} onOpenChange={(open) => (open ? null : close())}>
<Dialog.Content className="p-6" data-ui-id="ui.projects.detail.contacts.add.createDialog">
<div className="flex w-full flex-col gap-3">
<span className={sectionHeading}>
{mode === "company" ? t("projects.detail.contacts.add.company") : t("projects.detail.contacts.add.person")}
</span>
{mode === "company" ? (
<TextInput label={t("crm.fields.orgName")} showLabel className="w-full">
<TextInput.Input
value={draft.orgName}
onChange={(event) => setDraft((state) => ({ ...state, orgName: event.target.value }))}
data-ui-id="ui.projects.detail.contacts.add.orgName"
/>
</TextInput>
) : (
<>
<TextInput label={t("crm.fields.vorname")} showLabel className="w-full">
<TextInput.Input
value={draft.vorname}
onChange={(event) => setDraft((state) => ({ ...state, vorname: event.target.value }))}
data-ui-id="ui.projects.detail.contacts.add.vorname"
/>
</TextInput>
<TextInput label={t("crm.fields.nachname")} showLabel className="w-full">
<TextInput.Input
value={draft.nachname}
onChange={(event) => setDraft((state) => ({ ...state, nachname: event.target.value }))}
data-ui-id="ui.projects.detail.contacts.add.nachname"
/>
</TextInput>
</>
)}
<TextInput label={t("projects.fields.email")} showLabel className="w-full">
<TextInput.Input
type="email"
value={draft.email}
onChange={(event) => setDraft((state) => ({ ...state, email: event.target.value }))}
data-ui-id="ui.projects.detail.contacts.add.email"
/>
</TextInput>
<div className="flex justify-end gap-2">
<Button variant="tertiary" size="small" onClick={close}>
{t("projects.actions.cancel")}
</Button>
<Button
variant="neutral"
size="small"
icon={<FeatherPlus />}
disabled={createDisabled}
loading={submitting}
onClick={() => create(mode === "company" ? "organisation" : "privatperson")}
data-ui-id="ui.projects.detail.contacts.add.createSubmit"
>
{t("projects.actions.save")}
</Button>
</div>
</div>
</Dialog.Content>
</Dialog>
</div>
);
}
@@ -0,0 +1,283 @@
// WF-P8 S02 "Adressdaten" — built like the contacts tile: a divider-headed
// group whose rows fold, one row per address slot.
//
// The project has three address slots (`projektAdresseId`, `rechnungsAdresseId`,
// `bauherrAdresseId`). The export gates the latter two behind "separate
// Rechnungsadresse" / "separate Bauherradresse" switches, which is exactly the
// slot being set or cleared, so the switch is the FK and not a display flag.
//
// This section keeps its own draft and its own save: the slots write through
// `updateAddresses`, not through the stammdaten path, and mixing them would put
// two intents behind one button.
//
// The per-slot extras (Bauabschnitt/Zufahrt/Koordinaten on the site address,
// Empfaenger/Zahlungsziel/Rechnungs-Mail on the invoice one, Post-erwuenscht plus
// the on-site contact on the Bauherr slot, and a free-text note on each) live in
// `ProjektAdressDetail` and are edited right here — the slot they belong to is
// the only place their meaning is clear.
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherMapPin } from "@subframe/core";
import type { ProjektAdressSlot, ProjektDetailAdresse, ProjektDetailData } from "@hivegrid/view-models";
import { Accordion } from "~/ui/components/Accordion";
import { Button } from "~/ui/components/Button";
import { Switch } from "~/ui/components/Switch";
import { TextArea } from "~/ui/components/TextArea";
import { TextInput } from "~/ui/components/TextInput";
import { DetailCard, FieldRow, SectionDivider, mutedText, type ProjektDetailSubmit } from "./detailUi";
export type AdressenSectionProps = {
data: ProjektDetailData;
submitting: boolean;
submit: ProjektDetailSubmit;
};
const EMPTY: ProjektDetailAdresse = {
strasse: "",
hausnummer: "",
plz: "",
ort: "",
land: "DE",
bauabschnitt: "",
zufahrt: "",
koordinaten: "",
empfaenger: "",
zahlungsziel: "",
rechnungsEmail: "",
postErwuenscht: false,
telefon: "",
ansprechpartnerVorOrt: "",
notizen: "",
};
/**
* The slot extras from `ProjektAdressDetail`. Each slot shows only its own: a
* Zahlungsziel on the site address or a Zufahrt on the invoice address would be
* a field nobody fills.
*/
type SlotExtraKey =
| "bauabschnitt"
| "zufahrt"
| "koordinaten"
| "empfaenger"
| "zahlungsziel"
| "rechnungsEmail"
| "telefon"
| "ansprechpartnerVorOrt";
const SLOT_EXTRAS: Record<ProjektAdressSlot, { key: SlotExtraKey; labelKey: string }[]> = {
projekt: [
{ key: "bauabschnitt", labelKey: "projects.detail.addresses.section" },
{ key: "zufahrt", labelKey: "projects.detail.addresses.access" },
{ key: "koordinaten", labelKey: "projects.detail.addresses.coordinates" },
],
rechnung: [
{ key: "empfaenger", labelKey: "projects.detail.addresses.recipient" },
{ key: "zahlungsziel", labelKey: "projects.detail.addresses.paymentTerms" },
{ key: "rechnungsEmail", labelKey: "projects.detail.addresses.invoiceEmail" },
],
bauherr: [
{ key: "telefon", labelKey: "projects.fields.phone" },
{ key: "ansprechpartnerVorOrt", labelKey: "projects.detail.addresses.onSiteContact" },
],
};
/** The project address is always shown; the other two are opt-in slots. */
const SLOTS: { slot: ProjektAdressSlot; labelKey: string; optional: boolean }[] = [
{ slot: "projekt", labelKey: "projects.detail.addresses.project", optional: false },
{ slot: "rechnung", labelKey: "projects.detail.addresses.invoice", optional: true },
{ slot: "bauherr", labelKey: "projects.detail.addresses.owner", optional: true },
];
type DraftState = Record<ProjektAdressSlot, { enabled: boolean; value: ProjektDetailAdresse }>;
function toDraft(data: ProjektDetailData): DraftState {
return {
projekt: { enabled: true, value: data.adressen.projekt ?? EMPTY },
rechnung: { enabled: data.adressen.rechnung !== null, value: data.adressen.rechnung ?? EMPTY },
bauherr: { enabled: data.adressen.bauherr !== null, value: data.adressen.bauherr ?? EMPTY },
};
}
function formatAddress(address: ProjektDetailAdresse | null): string | null {
if (!address) return null;
const street = [address.strasse, address.hausnummer].filter(Boolean).join(" ");
const city = [address.plz, address.ort].filter(Boolean).join(" ");
const line = [street, city].filter(Boolean).join(", ");
return line || null;
}
export function AdressenSection({ data, submitting, submit }: AdressenSectionProps) {
const { t } = useTranslation();
const [draft, setDraft] = useState<DraftState>(() => toDraft(data));
function patch(slot: ProjektAdressSlot, part: Partial<ProjektDetailAdresse>) {
setDraft((state) => ({ ...state, [slot]: { ...state[slot], value: { ...state[slot].value, ...part } } }));
}
function toggle(slot: ProjektAdressSlot, enabled: boolean) {
setDraft((state) => ({ ...state, [slot]: { ...state[slot], enabled } }));
}
function save() {
// A disabled slot posts null, which clears the FK server-side.
const slots: Record<string, ProjektDetailAdresse | null> = {};
for (const entry of SLOTS) slots[entry.slot] = draft[entry.slot].enabled ? draft[entry.slot].value : null;
submit("updateAddresses", { slots: JSON.stringify(slots) });
}
return (
<DetailCard uiId="ui.projects.detail.addresses">
<SectionDivider icon={<FeatherMapPin />} title={t("projects.detail.section.addresses")} uiId="ui.projects.detail.section.addresses" />
{/* Same shape as the contacts tile: one foldable row per slot, name and
the address itself in the head, the fields inside. The project address
is always there, the other two hang behind their switch. */}
{SLOTS.map((entry) => {
const summary = formatAddress(data.canWrite ? draft[entry.slot].value : data.adressen[entry.slot]);
const enabled = draft[entry.slot].enabled;
// An optional slot that is switched off has no row at all — the project
// simply has one address then.
if (entry.optional && !enabled) return null;
return (
<Accordion
key={entry.slot}
variant="ghost"
className="w-full"
data-ui-id={`ui.projects.detail.addresses.${entry.slot}`}
trigger={
<div className="flex w-full items-center gap-2 px-3 py-4" data-ui-id={`ui.projects.detail.addresses.${entry.slot}.trigger`}>
<Accordion.Chevron />
<span className="flex h-9 w-9 flex-none items-center justify-center rounded-md bg-surface-neutral-tertiary text-icon-neutral-secondary">
<FeatherMapPin />
</span>
<span className="flex min-w-0 grow shrink-0 basis-0 flex-col items-start gap-0.5">
<span className="text-body-small-semibold-0 font-body-small-semibold-0 text-text-neutral-primary">{t(entry.labelKey)}</span>
<span className="w-full break-words text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{summary ?? t("projects.detail.addresses.empty")}
</span>
</span>
</div>
}
>
<div className="flex w-full flex-col gap-2 px-3 pb-3">
{!data.canWrite ? (
<span className={mutedText}>{summary ?? t("projects.fields.none")}</span>
) : (
<AddressFields slot={entry.slot} value={draft[entry.slot].value} onChange={(part) => patch(entry.slot, part)} />
)}
{/* The two optional slots are switched on from inside the project
address — they only exist because this project needs a second
address, so that decision belongs to the first one. */}
{entry.slot === "projekt" && data.canWrite
? SLOTS.filter((other) => other.optional).map((other) => (
<FieldRow
key={other.slot}
icon={<FeatherMapPin />}
label={t(other.labelKey)}
uiId={`ui.projects.detail.addresses.${other.slot}.separate`}
>
<Switch
checked={draft[other.slot].enabled}
onCheckedChange={(checked: boolean) => toggle(other.slot, checked)}
data-ui-id={`ui.projects.detail.addresses.${other.slot}.toggle`}
/>
</FieldRow>
))
: null}
{/* Saving sits where the editing happens, at the end of the open
slot. It posts all three slots in one intent, so it says the
same thing wherever it is pressed. */}
{data.canWrite ? (
<div className="flex w-full justify-end pt-1">
<Button
variant="neutral"
size="small"
loading={submitting}
onClick={save}
data-ui-id={`ui.projects.detail.addresses.${entry.slot}.save`}
>
{t("projects.actions.save")}
</Button>
</div>
) : null}
</div>
</Accordion>
);
})}
</DetailCard>
);
}
function AddressFields({
slot,
value,
onChange,
}: {
slot: ProjektAdressSlot;
value: ProjektDetailAdresse;
onChange: (part: Partial<ProjektDetailAdresse>) => void;
}) {
const { t } = useTranslation();
const uiId = `ui.projects.detail.addresses.${slot}`;
return (
<DetailCard>
<FieldRow label={t("projects.detail.addresses.street")} uiId={`${uiId}.street`}>
<TextInput label="" className="w-full">
<TextInput.Input value={value.strasse} onChange={(e) => onChange({ strasse: e.target.value })} data-ui-id={`${uiId}.strasse`} />
</TextInput>
</FieldRow>
<FieldRow label={t("projects.detail.addresses.houseNumber")} uiId={`${uiId}.houseNumber`}>
<TextInput label="" className="w-full">
<TextInput.Input value={value.hausnummer} onChange={(e) => onChange({ hausnummer: e.target.value })} data-ui-id={`${uiId}.hausnummer`} />
</TextInput>
</FieldRow>
<FieldRow label={t("projects.detail.addresses.postalCode")} uiId={`${uiId}.postalCode`}>
<TextInput label="" className="w-full">
<TextInput.Input value={value.plz} onChange={(e) => onChange({ plz: e.target.value })} data-ui-id={`${uiId}.plz`} />
</TextInput>
</FieldRow>
<FieldRow label={t("projects.detail.addresses.city")} uiId={`${uiId}.city`}>
<TextInput label="" className="w-full">
<TextInput.Input value={value.ort} onChange={(e) => onChange({ ort: e.target.value })} data-ui-id={`${uiId}.ort`} />
</TextInput>
</FieldRow>
<FieldRow label={t("projects.detail.addresses.country")} uiId={`${uiId}.country`}>
<TextInput label="" className="w-full">
<TextInput.Input value={value.land} onChange={(e) => onChange({ land: e.target.value })} data-ui-id={`${uiId}.land`} />
</TextInput>
</FieldRow>
{SLOT_EXTRAS[slot].map((extra) => (
<FieldRow key={extra.key} label={t(extra.labelKey)} uiId={`${uiId}.${extra.key}Row`}>
<TextInput label="" className="w-full">
<TextInput.Input
value={value[extra.key]}
onChange={(e) => onChange({ [extra.key]: e.target.value })}
data-ui-id={`${uiId}.${extra.key}`}
/>
</TextInput>
</FieldRow>
))}
{slot === "bauherr" ? (
<FieldRow label={t("projects.detail.addresses.postWanted")} uiId={`${uiId}.postWantedRow`}>
<Switch
checked={value.postErwuenscht}
onCheckedChange={(checked: boolean) => onChange({ postErwuenscht: checked })}
data-ui-id={`${uiId}.postErwuenscht`}
/>
</FieldRow>
) : null}
{/* The note closes each slot, as in the export: it comments on the address
above it, so it belongs to that slot and not to the section. */}
<FieldRow label={t("projects.detail.addresses.notes")} uiId={`${uiId}.notesRow`}>
<TextArea label="" className="w-full">
<TextArea.Input
value={value.notizen}
onChange={(event) => onChange({ notizen: event.target.value })}
data-ui-id={`${uiId}.notizen`}
/>
</TextArea>
</FieldRow>
</DetailCard>
);
}
@@ -0,0 +1,75 @@
// WF-P8 S02 header — project name with the board it sits on underneath, and the
// export's three controls: the copyable project id, the way back to the board
// ("Pipeline") and the single save action.
//
// Built on the app shell's PageHeader rather than on the export's own header
// row, so the detail page keeps the same title band as every other screen; the
// export's pieces sit in the actions slot. The bar is `dense` — the S02 header
// is a one-line strip in the export, not the tall title band of a list screen.
import { useTranslation } from "react-i18next";
import { FeatherArrowLeftRight, FeatherCheck, FeatherKanbanSquare, FeatherLock } from "@subframe/core";
import type { ProjektDetailData } from "@hivegrid/view-models";
import { Button } from "~/ui/components/Button";
import { CopyToClipboardButton } from "~/ui/components/CopyToClipboardButton";
import { PageHeader } from "../../shared/PageShell";
import { AppLink } from "~/components/app/AppLink";
export type DetailHeaderProps = {
data: ProjektDetailData;
/** Back to the board this project sits on — the export's "Pipeline" button. */
backHref: string;
submitting: boolean;
/** Single save path of the whole screen; absent for a reader. */
onSave?: () => void;
};
export function DetailHeader({ data, backHref, submitting, onSave }: DetailHeaderProps) {
const { t } = useTranslation();
return (
<PageHeader
uiId="ui.projects.detail.header"
dense
title={data.projektname}
// The board reads as the line under the project name — as the export's
// pill, so it says "you are inside this pipeline" instead of looking like
// a description of the project.
subtitle={
<span className="rounded-round bg-surface-neutral-tertiary inline-flex items-center gap-1.5 px-2.5 py-1" data-ui-id="ui.projects.detail.header.board">
<FeatherKanbanSquare className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-icon-neutral-tertiary" />
<span className="text-body-extra-small-medium-0 font-body-extra-small-medium-0 text-text-neutral-secondary">{data.pipelineName}</span>
</span>
}
actions={
<>
<span
className="border-border-default bg-surface-neutral-tertiary flex items-center gap-2 rounded-md border border-solid px-2.5 py-1"
data-ui-id="ui.projects.detail.header.projectId"
>
<FeatherLock className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-icon-neutral-tertiary" />
<span className="text-body-extra-small-medium-0 font-body-extra-small-medium-0 text-text-neutral-tertiary">
{t("projects.detail.projectIdLabel")}
</span>
<span className="text-body-small-semibold-0 font-body-small-semibold-0 text-text-neutral-secondary">{data.projektNummer}</span>
<CopyToClipboardButton
clipboardText={data.projektNummer}
tooltipText={t("projects.detail.copyProjectId")}
successKey="projects.detail.toast.projectIdCopied"
data-ui-id="ui.projects.detail.header.copyProjectId"
/>
</span>
<AppLink href={backHref} data-ui-id="ui.projects.detail.header.board.link">
<Button variant="tertiary" size="small" icon={<FeatherArrowLeftRight />}>
{t("projects.actions.pipeline")}
</Button>
</AppLink>
{onSave ? (
<Button size="small" icon={<FeatherCheck />} loading={submitting} onClick={onSave} data-ui-id="ui.projects.detail.stammdaten.save">
{t("projects.actions.save")}
</Button>
) : null}
</>
}
/>
);
}
@@ -0,0 +1,75 @@
// WF-P8 S02 — "Priorität" as the export draws it: a select whose trigger and
// options are coloured badges, not a text row.
//
// Same shape as DetailStatusField (the synced Select of this kit carries no
// `selectedContent`, so a badge trigger needs the DropdownMenuSelect), but the
// value rides in the stammdaten draft — priority is saved with the rest.
import { useTranslation } from "react-i18next";
import { FeatherChevronDown } from "@subframe/core";
import * as SubframeCore from "@subframe/core";
import { Badge } from "~/ui/components/Badge";
import { DropdownMenuSelect } from "~/ui/components/DropdownMenuSelect";
import { PRIORITIES } from "./detailUi";
/** Export tones: Niedrig green, Mittel yellow, Hoch red, Kritisch violet. */
const PRIORITY_TONE: Record<string, "green-solid" | "yellow-solid" | "red-solid" | "violet-solid"> = {
niedrig: "green-solid",
normal: "yellow-solid",
hoch: "red-solid",
dringend: "violet-solid",
};
export type DetailPriorityFieldProps = {
value: string;
onChange: (prioritaet: string) => void;
/** A reader sees the badge alone — there is nothing to pick. */
readOnly?: boolean;
};
export function DetailPriorityField({ value, onChange, readOnly }: DetailPriorityFieldProps) {
const { t } = useTranslation();
const badge = (
<Badge tone={PRIORITY_TONE[value] ?? "yellow-solid"} size="small" data-ui-id="ui.projects.detail.priority.current">
{t(`projects.priority.${value}`)}
</Badge>
);
if (readOnly) return badge;
return (
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
{/* Borderless like the export's filled select: the badge stands raw in
the row and only the chevron marks the far right as the handle. */}
<button
type="button"
className="flex h-8 w-full items-center justify-between gap-2 rounded-md px-1 hover:bg-surface-neutral-tertiary"
aria-label={t("projects.fields.priority")}
data-ui-id="ui.projects.detail.priority.trigger"
>
{badge}
<FeatherChevronDown className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
</button>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="start" sideOffset={4} asChild>
<DropdownMenuSelect>
{PRIORITIES.map((prioritaet) => (
<DropdownMenuSelect.DropdownItem
key={prioritaet}
selected={prioritaet === value}
onSelect={() => onChange(prioritaet)}
data-ui-id={`ui.projects.detail.priority.${prioritaet}`}
>
<Badge tone={PRIORITY_TONE[prioritaet]} size="small">
{t(`projects.priority.${prioritaet}`)}
</Badge>
</DropdownMenuSelect.DropdownItem>
))}
</DropdownMenuSelect>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
);
}
@@ -0,0 +1,81 @@
// WF-P8 S02 — the floating quick-action bar (Anrufen, E-Mail, Termin, Aufgabe,
// Notiz, Hochladen).
//
// Two deliberate deviations from the export:
// * `sticky bottom-4` at the end of the main column, not `absolute`. The app
// shell's <main> is the scroll container, so an absolutely placed bar would
// scroll away with the content instead of staying reachable.
// * The export hides the bar on mobile. It is the only entry to the four
// quick-action modals, so hiding it there would remove the actions rather
// than the decoration.
import { useTranslation } from "react-i18next";
import { FeatherCalendarPlus, FeatherCheckSquare, FeatherMail, FeatherPhone, FeatherStickyNote, FeatherUpload } from "@subframe/core";
import { Button } from "~/ui/components/Button";
export type DetailQuickAction = "note" | "task" | "appointment" | "file";
export type DetailQuickActionBarProps = {
onOpen: (action: DetailQuickAction) => void;
/** Direct actions, not modals. Omitted when there is no number/address. */
callHref?: string | null;
mailHref?: string | null;
/** Telephony entry point of the tenant, if the feature gate is open. */
callSlot?: React.ReactNode;
};
export function DetailQuickActionBar({ onOpen, callHref, mailHref, callSlot }: DetailQuickActionBarProps) {
const { t } = useTranslation();
return (
<div className="sticky bottom-4 z-10 flex w-full justify-center" data-ui-id="ui.projects.detail.quickActions">
{/* One line, always. When the bar is wider than the column it scrolls
inside itself — wrapping turns the strip into a two-storey block that
covers the fields it floats over. `justify-start`, not `center`: a
centred overflowing flex row hides its first buttons out of reach. */}
<div className="flex max-w-full flex-nowrap items-center justify-start gap-1.5 overflow-x-auto rounded-lg border border-solid border-border-default bg-surface-neutral-secondary pl-2.5 pr-1.5 py-1.5 shadow-lg [&>*]:flex-none">
<span className="whitespace-nowrap pr-1 uppercase tracking-wide text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 text-text-neutral-tertiary">
{t("projects.quickAction.barLabel")}
</span>
<div className="flex h-5 w-px flex-none items-start bg-border-default" />
{/* Anrufen and E-Mail keep their place in the row even without a target,
like in the export — a bar whose buttons move around depending on the
project is harder to use than a disabled button. Telephony, when the
tenant has it, takes over the calling slot. */}
{callSlot ?? (
<Button
variant="tertiary"
size="small"
icon={<FeatherPhone />}
disabled={!callHref}
onClick={() => callHref && window.location.assign(callHref)}
data-ui-id="ui.projects.detail.quickActions.call"
>
{t("projects.quickAction.call")}
</Button>
)}
<Button
variant="tertiary"
size="small"
icon={<FeatherMail />}
disabled={!mailHref}
onClick={() => mailHref && window.location.assign(mailHref)}
data-ui-id="ui.projects.detail.quickActions.mail"
>
{t("projects.quickAction.mail")}
</Button>
<Button variant="tertiary" size="small" icon={<FeatherCalendarPlus />} onClick={() => onOpen("appointment")} data-ui-id="ui.projects.detail.quickActions.appointment">
{t("projects.quickAction.bar.appointment")}
</Button>
<Button variant="tertiary" size="small" icon={<FeatherCheckSquare />} onClick={() => onOpen("task")} data-ui-id="ui.projects.detail.quickActions.task">
{t("projects.quickAction.bar.task")}
</Button>
<Button variant="tertiary" size="small" icon={<FeatherStickyNote />} onClick={() => onOpen("note")} data-ui-id="ui.projects.detail.quickActions.note">
{t("projects.quickAction.bar.note")}
</Button>
<Button size="small" icon={<FeatherUpload />} onClick={() => onOpen("file")} data-ui-id="ui.projects.detail.quickActions.file">
{t("projects.quickAction.bar.file")}
</Button>
</div>
</div>
);
}
@@ -0,0 +1,290 @@
// WF-P8 S02 right-hand pipeline panel: one white column that stays put while the
// editor scrolls, with the six areas (Verlauf, Termine, Dateien, Aufgaben,
// Notizen, Aktivitäten) as a button grid on top and the picked area below it —
// exactly as in the export, where Dateien is the built and preselected one.
//
// Layout: `sticky top-0 h-screen` inside the document flow (the app shell scrolls
// the document, and its icon sidebar sticks the same way). The export root is
// `h-full overflow-hidden` with an inner scroller, which the layout-boundary gate
// bans — the shell hands down no definite height, so that markup collapses the
// screen to 0px.
//
// All six areas carry content, but the five besides Dateien are read-only: the
// editors for appointments, tasks and notes live in the P9 operations panel of
// the same module, and a second editor over the same rows is how the two drift
// apart. A second view does not have that problem — the panel is the glance, the
// module is where things change. Each area therefore ends in a link to its owner.
import { useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { AppLink } from "~/components/app/AppLink";
import {
FeatherActivity,
FeatherCalendar,
FeatherCheckSquare,
FeatherClock,
FeatherFile,
FeatherPaperclip,
FeatherStickyNote,
FeatherUpload,
FeatherUploadCloud,
} from "@subframe/core";
import { Button } from "~/ui/components/Button";
import { fileTypeLabelKey } from "~/utils/files/fileTypeLabel";
import { mutedText } from "./detailUi";
/** A project document plus the file-detail URL the route resolved for it. */
export type ProjektDetailRailDocument = {
id: string;
name: string;
mimeType: string;
sizeLabel: string;
/** S02-F upload category, stored as the file link role. */
linkRole: string | null;
href: string;
};
/** One read-only line in a rail area. */
export type ProjektDetailRailEntry = { id: string; label: string; labelKey?: string | null; meta: string | null; atIso: string | null };
export type DetailSideRailProps = {
documents: readonly ProjektDetailRailDocument[];
/**
* Uploads a picked or dropped file and links it to the project. Resolves once
* the link is on its way; rejects so the panel can say that it failed.
* Omitted without write access, which also removes the button and the zone.
*/
onUpload?: (file: File) => Promise<void>;
/** Read-only rows per area, resolved by the route. */
areas: {
history: readonly ProjektDetailRailEntry[];
appointments: readonly ProjektDetailRailEntry[];
tasks: readonly ProjektDetailRailEntry[];
notes: readonly ProjektDetailRailEntry[];
activity: readonly ProjektDetailRailEntry[];
};
/** Anchor of the operations panel, so an area can point at the full list. */
operationsHref?: string;
/** Formatter injected by the page so the panel speaks the screen's locale. */
dateTime: Intl.DateTimeFormat;
};
type EntryAreaKey = "history" | "appointments" | "tasks" | "notes" | "activity";
type AreaKey = EntryAreaKey | "files";
const AREAS: { key: AreaKey; icon: React.ReactNode; labelKey: string; emptyKey: string }[] = [
{ key: "history", icon: <FeatherClock />, labelKey: "projects.detail.rail.history", emptyKey: "projects.detail.rail.historyEmpty" },
{ key: "appointments", icon: <FeatherCalendar />, labelKey: "projects.subAreas.appointments", emptyKey: "projects.detail.rail.appointmentsEmpty" },
{ key: "files", icon: <FeatherPaperclip />, labelKey: "projects.detail.rail.files", emptyKey: "projects.empty.documents.body" },
{ key: "tasks", icon: <FeatherCheckSquare />, labelKey: "projects.subAreas.tasks", emptyKey: "projects.detail.rail.tasksEmpty" },
{ key: "notes", icon: <FeatherStickyNote />, labelKey: "projects.detail.rail.notes", emptyKey: "projects.detail.rail.notesEmpty" },
{ key: "activity", icon: <FeatherActivity />, labelKey: "projects.detail.rail.activity", emptyKey: "projects.detail.activityEmpty" },
];
/** Areas whose editor lives in the operations panel get the link to it. */
const AREAS_WITH_EDITOR: ReadonlySet<AreaKey> = new Set(["appointments", "tasks"]);
export function DetailSideRail({ documents, onUpload, areas, operationsHref, dateTime }: DetailSideRailProps) {
const { t } = useTranslation();
// Dateien is the area the export opens on, and the one with an editor here.
const [active, setActive] = useState<AreaKey>("files");
const fileInputRef = useRef<HTMLInputElement>(null);
const [dragging, setDragging] = useState(false);
const [uploading, setUploading] = useState(false);
const [uploadErrorKey, setUploadErrorKey] = useState<string | null>(null);
async function upload(file: File | null | undefined) {
if (!file || !onUpload) return;
setUploading(true);
setUploadErrorKey(null);
try {
await onUpload(file);
} catch (error) {
// The upload client carries the server's own key ("type not allowed",
// "too large"), which says more than a blanket "did not work".
const key = (error as { errorKey?: unknown }).errorKey;
setUploadErrorKey(typeof key === "string" ? key : "projects.quickAction.file.uploadFailed");
} finally {
setUploading(false);
}
}
const activeArea = AREAS.find((area) => area.key === active) ?? AREAS[2];
// Grouped by upload category so the panel reads like the export's document
// groups (Angebot, Auftrag, …) instead of one flat list.
const groups = new Map<string, ProjektDetailRailDocument[]>();
for (const document of documents) {
const key = document.linkRole ?? "";
const bucket = groups.get(key);
if (bucket) bucket.push(document);
else groups.set(key, [document]);
}
return (
<aside
// From xl on the panel is the right column next to the editor: it starts
// under the page header, which spans the full width, and sticks to the
// window from there on. `top-14` is the app shell's own header bar, so a
// scrolled page parks the panel right below it. Below xl it is a plain
// block at the end of the page, because a window-height column leaves a
// narrow screen no room for the editor.
//
// The panel has no collapsed state: the areas it holds (history, files,
// tasks, notes) are what the project is worked from, so it stays open.
className="relative flex w-full flex-col border-t border-solid border-border-default bg-surface-neutral-secondary xl:sticky xl:top-14 xl:h-[calc(100dvh-3.5rem)] xl:w-[340px] xl:flex-none xl:border-l xl:border-t-0"
data-ui-id="ui.projects.detail.rail"
>
<div className="flex h-full w-full flex-col gap-4 overflow-y-auto px-4 py-4">
<span className="text-body-small-medium-0 font-body-small-medium-0 uppercase text-text-neutral-tertiary">
{t("projects.detail.rail.title")}
</span>
{/* Area picker: three per row, icon over label, as in the export. */}
<div className="grid w-full grid-cols-3 gap-2">
{AREAS.map((area) => {
const isActive = area.key === active;
return (
<button
key={area.key}
type="button"
aria-pressed={isActive}
onClick={() => setActive(area.key)}
className={`flex flex-col items-center justify-center gap-1 rounded-md border border-solid px-2 py-3 ${
isActive
? // Blue, as in the export. Not the brand tone — that one is
// near-black here and reads as "pressed", not "selected".
"border-border-information-solid bg-surface-feedback-subtle-information text-text-feedback-information"
: "border-border-default bg-surface-neutral-secondary text-text-neutral-primary hover:bg-surface-neutral-tertiary"
}`}
data-ui-id={`ui.projects.detail.rail.tab.${area.key}`}
>
<span className="flex items-center text-body-large-0 font-body-large-0">{area.icon}</span>
<span className="text-body-small-regular-0 font-body-small-regular-0">{t(area.labelKey)}</span>
</button>
);
})}
</div>
<span className="text-body-large font-body-large text-text-neutral-primary">{t(activeArea.labelKey)}</span>
{active === "files" ? (
<div className="flex w-full flex-col gap-3" data-ui-id="ui.projects.detail.rail.files">
{onUpload ? (
<>
{/* The button opens the file dialog straight away — in the panel a
file lands on the project as it is, with no modal in between.
Category and description stay with the quick action, which is
where a file gets filed rather than just attached. */}
<input
ref={fileInputRef}
type="file"
className="sr-only"
aria-label={t("projects.quickAction.file.field.file")}
onChange={(event) => {
void upload(event.target.files?.[0]);
// Same file twice in a row must fire again.
event.target.value = "";
}}
data-ui-id="ui.projects.detail.rail.fileInput"
/>
<Button
variant="tertiary"
icon={<FeatherUpload />}
loading={uploading}
onClick={() => fileInputRef.current?.click()}
className="w-full justify-center"
data-ui-id="ui.projects.detail.rail.upload"
>
{t("projects.quickAction.bar.file")}
</Button>
{/* Drop target only, deliberately not clickable: the button right
above it already opens the picker, and a zone that does both
swallows the drop gesture on a mis-click. */}
<div
onDragOver={(event) => {
event.preventDefault();
setDragging(true);
}}
onDragLeave={() => setDragging(false)}
onDrop={(event) => {
event.preventDefault();
setDragging(false);
void upload(event.dataTransfer.files?.[0]);
}}
className={`flex w-full flex-col items-center gap-1 rounded-md border border-dashed px-4 py-6 ${
dragging ? "border-border-information-solid bg-surface-feedback-subtle-information" : "border-border-default"
}`}
data-ui-id="ui.projects.detail.rail.dropzone"
>
<FeatherUploadCloud className="text-icon-neutral-tertiary" />
{/* Only the headline: the second line of the shared dropzone copy
says "or click to select", which this zone does not do. */}
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
{t("files.upload.dropzone.headline")}
</span>
</div>
{uploadErrorKey ? (
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative" data-ui-id="ui.projects.detail.rail.uploadError">
{t(uploadErrorKey)}
</span>
) : null}
</>
) : null}
{documents.length === 0 ? <span className={mutedText}>{t("projects.empty.documents.body")}</span> : null}
{[...groups.entries()].map(([linkRole, group]) => (
<div
key={linkRole || "ungrouped"}
className="flex w-full flex-col gap-1 rounded-md border border-solid border-border-default p-2"
data-ui-id={`ui.projects.detail.rail.files.group.${linkRole || "ungrouped"}`}
>
<span className="text-body-extra-small-medium-0 font-body-extra-small-medium-0 uppercase text-text-neutral-tertiary">
{linkRole || t("projects.detail.rail.uncategorised")}
</span>
{group.map((document) => (
<AppLink
key={document.id}
href={document.href}
className="flex items-center gap-2 rounded-md px-1 py-1 hover:bg-surface-neutral-tertiary"
data-ui-id={`ui.projects.detail.rail.files.${document.id}`}
>
<FeatherFile className="text-icon-neutral-tertiary" />
<div className="flex min-w-0 grow flex-col">
<span className="truncate text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-primary">{document.name}</span>
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t(fileTypeLabelKey(document.mimeType))} · {document.sizeLabel}
</span>
</div>
</AppLink>
))}
</div>
))}
</div>
) : (
<div className="flex w-full flex-col gap-2" data-ui-id={`ui.projects.detail.rail.${active}`}>
{areas[active as EntryAreaKey].length === 0 ? <span className={mutedText}>{t(activeArea.emptyKey)}</span> : null}
{areas[active as EntryAreaKey].map((entry) => (
<div key={entry.id} className="flex w-full flex-col gap-0.5" data-ui-id={`ui.projects.detail.rail.${active}.${entry.id}`}>
<span className="break-words text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-primary">
{entry.labelKey ? t(entry.labelKey) : entry.label}
</span>
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{[entry.atIso ? dateTime.format(new Date(entry.atIso)) : null, entry.meta].filter(Boolean).join(" · ")}
</span>
</div>
))}
{operationsHref && AREAS_WITH_EDITOR.has(active) ? (
<AppLink
href={operationsHref}
className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-brand-brand-text-default hover:underline"
data-ui-id={`ui.projects.detail.rail.${active}.manage`}
>
{t("projects.detail.rail.manage")}
</AppLink>
) : null}
</div>
)}
</div>
</aside>
);
}
@@ -0,0 +1,98 @@
// WF-P8 S02 — "Status" as the first field of Grunddaten.
//
// The export draws a select whose options are Badges, so this uses the synced
// DropdownMenuSelect rather than the plain Select: the trigger and the items
// have to render a badge, not a text row.
//
// Changing the status is an immediate action, not part of the stammdaten draft:
// a stage move has server-side consequences (won/lost stamps, the lost reason,
// the handover) that a "save later" would misrepresent.
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherChevronDown } from "@subframe/core";
import * as SubframeCore from "@subframe/core";
import type { ProjektDetailData } from "@hivegrid/view-models";
import { Badge } from "~/ui/components/Badge";
import { DropdownMenuSelect } from "~/ui/components/DropdownMenuSelect";
/** Outcome tone of a column; the board colour rides along as a dot. */
function toneOf(stageKind: string): "green-subtle" | "red-subtle" | "neutral-subtle" {
if (stageKind === "gewonnen") return "green-subtle";
if (stageKind === "verloren") return "red-subtle";
return "neutral-subtle";
}
export type DetailStatusFieldProps = {
data: ProjektDetailData;
/** Moving into a "verloren" column needs the reason dialog, so the parent decides. */
onMoveToStage: (stageId: string, stageKind: string) => void;
};
export function DetailStatusField({ data, onMoveToStage }: DetailStatusFieldProps) {
const { t } = useTranslation();
const [search, setSearch] = useState("");
const current = data.stages.find((stage) => stage.isCurrent) ?? null;
const query = search.trim().toLowerCase();
const visible = query ? data.stages.filter((stage) => stage.name.toLowerCase().includes(query)) : data.stages;
if (!data.canChangeStage) {
return (
<Badge tone={toneOf(current?.stageKind ?? "offen")} data-ui-id="ui.projects.detail.status.current">
{current?.name ?? "—"}
</Badge>
);
}
return (
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
{/* Borderless like the export's filled select: the badge stands raw in
the row and only the chevron marks the far right as the handle. */}
<button
type="button"
className="flex h-8 w-full items-center justify-between gap-2 rounded-md px-1 hover:bg-surface-neutral-tertiary"
aria-label={t("projects.detail.system.status")}
data-ui-id="ui.projects.detail.status.trigger"
>
<Badge tone={toneOf(current?.stageKind ?? "offen")} data-ui-id="ui.projects.detail.status.current">
{current?.name ?? "—"}
</Badge>
<FeatherChevronDown className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
</button>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="start" sideOffset={4} asChild>
<DropdownMenuSelect
showSearch={data.stages.length > 6}
searchValue={search}
searchPlaceholder={t("projects.fields.search")}
onSearchChange={setSearch}
>
{visible.map((stage) => (
<DropdownMenuSelect.DropdownItem
key={stage.id}
selected={stage.isCurrent}
disabled={stage.isCurrent}
onSelect={() => onMoveToStage(stage.id, stage.stageKind)}
data-ui-id={`ui.projects.detail.stage.${stage.id}`}
>
<span className="flex items-center gap-2">
{/* The board colour of the column; the badge tone only says
whether the column is an outcome. */}
<span className="h-2 w-2 flex-none rounded-round" style={{ backgroundColor: stage.color }} />
<Badge tone={toneOf(stage.stageKind)} hideDot>
{stage.name}
</Badge>
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{stage.winProbability}%
</span>
</span>
</DropdownMenuSelect.DropdownItem>
))}
</DropdownMenuSelect>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
);
}
@@ -0,0 +1,141 @@
// WF-P8 S02 "Grunddaten" — the export's eight fields in its order: project
// name, status, priority, source, project type, promotion and the two money
// fields.
//
// The draft state lives in the parent (single save path); this section takes a
// value and reports a patch. Status is the exception: a stage move is immediate,
// so it goes straight to the callback.
//
// Deltas from the export, both waiting on data rather than on markup:
// * Quelle, Projekttyp and Promotion are tag multi-selects there and single
// free-text columns here. There is no option catalogue behind them, so a
// picker would have nothing to offer.
// * The money fields stay `type=number` with the raw decimal. The export
// shows "42.500,00 €" in a text field, which cannot round-trip a typed
// value across locales.
import { useTranslation } from "react-i18next";
import {
FeatherBriefcase,
FeatherCircleDot,
FeatherFlag,
FeatherHeart,
FeatherLayoutGrid,
FeatherTag,
FeatherTrendingUp,
FeatherWallet,
FeatherWrench,
} from "@subframe/core";
import type { ProjektDetailData } from "@hivegrid/view-models";
import { TextInput } from "~/ui/components/TextInput";
import { DetailPriorityField } from "./DetailPriorityField";
import { DetailStatusField } from "./DetailStatusField";
import { CURRENCY_SYMBOL, DetailCard, FIELD_CONTROL_PROPS, FieldRow, SectionDivider, mutedText, type StammdatenState } from "./detailUi";
export type GrunddatenSectionProps = {
data: ProjektDetailData;
value: StammdatenState;
onChange: (patch: Partial<StammdatenState>) => void;
onMoveToStage: (stageId: string, stageKind: string) => void;
};
/**
* Money row: the raw decimal stays editable as a number, and the currency sits
* next to it — a bare "48200,00" does not say what it counts.
*/
function MoneyInput({ value, onChange, uiId }: { value: string; onChange: (value: string) => void; uiId: string }) {
return (
<span className="flex w-full items-center gap-1.5">
<TextInput {...FIELD_CONTROL_PROPS} className="h-auto w-40 max-w-none">
<TextInput.Input
variant="small"
type="number"
inputMode="decimal"
placeholder="0,00"
value={value}
onChange={(event) => onChange(event.target.value)}
data-ui-id={uiId}
/>
</TextInput>
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">{CURRENCY_SYMBOL}</span>
</span>
);
}
export function GrunddatenSection({ data, value, onChange, onMoveToStage }: GrunddatenSectionProps) {
const { t } = useTranslation();
return (
<DetailCard uiId="ui.projects.detail.stammdaten">
<SectionDivider icon={<FeatherLayoutGrid />} title={t("projects.detail.section.stammdaten")} uiId="ui.projects.detail.section.grunddaten" />
{data.canWrite ? (
<FieldRow icon={<FeatherBriefcase />} label={t("projects.detail.fieldProjectName")} uiId="ui.projects.detail.field.name">
<TextInput {...FIELD_CONTROL_PROPS}>
<TextInput.Input
variant="small"
value={value.projektname}
onChange={(e) => onChange({ projektname: e.target.value })}
data-ui-id="ui.projects.detail.name"
/>
</TextInput>
</FieldRow>
) : null}
<FieldRow icon={<FeatherCircleDot />} label={t("projects.detail.system.status")} uiId="ui.projects.detail.field.status">
<DetailStatusField data={data} onMoveToStage={onMoveToStage} />
</FieldRow>
{data.canWrite ? (
<>
<FieldRow icon={<FeatherFlag />} label={t("projects.fields.priority")} uiId="ui.projects.detail.field.priority">
<DetailPriorityField value={value.prioritaet} onChange={(prioritaet) => onChange({ prioritaet })} />
</FieldRow>
<FieldRow icon={<FeatherHeart />} label={t("projects.fields.source")} uiId="ui.projects.detail.field.source">
<TextInput {...FIELD_CONTROL_PROPS}>
<TextInput.Input variant="small" value={value.quelle} onChange={(e) => onChange({ quelle: e.target.value })} data-ui-id="ui.projects.detail.quelle" />
</TextInput>
</FieldRow>
<FieldRow icon={<FeatherWrench />} label={t("projects.fields.projectType")} uiId="ui.projects.detail.field.projectType">
<TextInput {...FIELD_CONTROL_PROPS}>
<TextInput.Input variant="small" value={value.projekttyp} onChange={(e) => onChange({ projekttyp: e.target.value })} data-ui-id="ui.projects.detail.projekttyp" />
</TextInput>
</FieldRow>
<FieldRow icon={<FeatherTag />} label={t("projects.fields.promotion")} uiId="ui.projects.detail.field.promotion">
<TextInput {...FIELD_CONTROL_PROPS}>
<TextInput.Input variant="small" value={value.promotion} onChange={(e) => onChange({ promotion: e.target.value })} data-ui-id="ui.projects.detail.promotion" />
</TextInput>
</FieldRow>
{data.valueVisible ? (
<>
<FieldRow icon={<FeatherTrendingUp />} label={t("projects.detail.fieldPotentialValue")} uiId="ui.projects.detail.field.value">
<MoneyInput
value={value.potenziellerAuftragswert}
onChange={(potenziellerAuftragswert) => onChange({ potenziellerAuftragswert })}
uiId="ui.projects.detail.value"
/>
</FieldRow>
<FieldRow icon={<FeatherWallet />} label={t("projects.fields.orderVolume")} uiId="ui.projects.detail.field.orderVolume">
<MoneyInput
value={value.auftragsvolumen}
onChange={(auftragsvolumen) => onChange({ auftragsvolumen })}
uiId="ui.projects.detail.orderVolume"
/>
</FieldRow>
</>
) : null}
</>
) : (
<>
{/* A reader gets the same rows, only without controls. */}
<FieldRow icon={<FeatherFlag />} label={t("projects.fields.priority")} uiId="ui.projects.detail.field.priority">
<DetailPriorityField value={value.prioritaet} onChange={() => {}} readOnly />
</FieldRow>
<FieldRow icon={<FeatherTrendingUp />} label={t("projects.detail.fieldPotentialValue")} uiId="ui.projects.detail.field.value">
<span className={mutedText}>{data.valueVisible ? (data.valueDisplay ?? "—") : "—"}</span>
</FieldRow>
</>
)}
</DetailCard>
);
}
@@ -0,0 +1,269 @@
// WF-P8 S02 "Kontakte" — a divider-headed tile like the other groups; only the
// contacts inside it fold. Each row shows the type icon, the name and a one-line
// summary, opens on click and carries the pencil that leads to the CRM record.
//
// The export shows a company card and two contact-person cards. That split is
// `Kontakt.kontaktTyp`, not a project field: organisations become the company
// cards, persons the Ansprechpartner cards with the `primaer` link first. The
// cards stay read-only except for the portal invitation the loader gates per
// contact — editing contact master data belongs to P6, and the card links there.
//
// Deliberately not built: "Firma/Kontakt suchen oder neu anlegen". Linking a new
// contact to a project has no intent on this route yet; recorded as an open
// point rather than invented here.
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { AppLink } from "~/components/app/AppLink";
import { FeatherBuilding2, FeatherClock, FeatherEdit2, FeatherMail, FeatherMapPin, FeatherPhone, FeatherPrinter, FeatherSmartphone, FeatherTrash2, FeatherUsers } from "@subframe/core";
import type { ProjektDetailData, ProjektDetailKontakt } from "@hivegrid/view-models";
import { Accordion } from "~/ui/components/Accordion";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Dialog } from "~/ui/components/Dialog";
import { DetailCard, FieldRow, SectionDivider, mutedText, sectionHeading, type ProjektDetailSubmit } from "./detailUi";
import { AddKontaktBlock } from "./AddKontaktBlock";
/** Typed numbers in the order the export lists them under the primary one. */
const TYPED_PHONES: { key: "durchwahl" | "mobil" | "fax"; labelKey: string; icon: React.ReactNode }[] = [
{ key: "durchwahl", labelKey: "projects.detail.contacts.directDial", icon: <FeatherPhone /> },
{ key: "mobil", labelKey: "projects.detail.contacts.mobile", icon: <FeatherSmartphone /> },
{ key: "fax", labelKey: "projects.fields.fax", icon: <FeatherPrinter /> },
];
export type KontakteSectionProps = {
data: ProjektDetailData;
submitting: boolean;
submit: ProjektDetailSubmit;
/** Formatter injected by the page so the whole screen speaks one locale. */
dateTime: Intl.DateTimeFormat;
/** Search endpoint for the add-contact block. */
contactSearchHref: string;
};
/** Primary link first, then the order the loader delivered. */
function primaryFirst(kontakte: readonly ProjektDetailKontakt[]): ProjektDetailKontakt[] {
return [...kontakte].sort((a, b) => Number(b.primaer) - Number(a.primaer));
}
export function KontakteSection({ data, submitting, submit, dateTime, contactSearchHref }: KontakteSectionProps) {
const { t } = useTranslation();
const firmen = primaryFirst(data.kontakte.filter((kontakt) => kontakt.kontaktTyp === "organisation"));
const personen = primaryFirst(data.kontakte.filter((kontakt) => kontakt.kontaktTyp === "privatperson"));
return (
<DetailCard uiId="ui.projects.detail.contacts">
<SectionDivider icon={<FeatherUsers />} title={t("projects.detail.section.contacts")} uiId="ui.projects.detail.section.contacts" />
{data.kontakte.length === 0 ? <span className={mutedText}>{t("projects.detail.contactsEmpty")}</span> : null}
{firmen.map((kontakt) => (
<KontaktCard
key={kontakt.id}
kontakt={kontakt}
icon={<FeatherBuilding2 />}
captionKey="projects.detail.contacts.company"
canWrite={data.canWrite}
submitting={submitting}
submit={submit}
dateTime={dateTime}
/>
))}
{personen.map((kontakt, index) => (
<KontaktCard
key={kontakt.id}
kontakt={kontakt}
icon={<FeatherUsers />}
captionKey={index === 0 ? "projects.detail.contacts.primaryPerson" : "projects.detail.contacts.otherPerson"}
canWrite={data.canWrite}
submitting={submitting}
submit={submit}
dateTime={dateTime}
/>
))}
{data.sourceLeadId ? (
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary" data-ui-id="ui.projects.detail.sourceLead">
{t("projects.detail.sourceLeadHint")}
</span>
) : null}
{/* Linking a contact is a write on the project, so the block follows the
same permission as every other editor on this screen. */}
{data.canWrite ? <AddKontaktBlock searchHref={contactSearchHref} submitting={submitting} submit={submit} /> : null}
</DetailCard>
);
}
type KontaktCardProps = {
kontakt: ProjektDetailKontakt;
icon: React.ReactNode;
captionKey: string;
/** Only a writer may drop the link between project and contact. */
canWrite: boolean;
submitting: boolean;
submit: ProjektDetailSubmit;
dateTime: Intl.DateTimeFormat;
};
/** The export's one-line summary under the name: mail / phone / address. */
function summaryOf(kontakt: ProjektDetailKontakt): string {
return [kontakt.email, kontakt.telefon, kontakt.adresseLabel].filter(Boolean).join(" / ");
}
function KontaktCard({ kontakt, icon, captionKey, canWrite, submitting, submit, dateTime }: KontaktCardProps) {
const { t } = useTranslation();
const [confirmOpen, setConfirmOpen] = useState(false);
const uiId = `ui.projects.detail.contacts.${kontakt.id}`;
const summary = summaryOf(kontakt);
return (
<Accordion
variant="ghost"
className="w-full"
data-ui-id={uiId}
data-row-id={kontakt.id}
trigger={
<div className="flex w-full items-center gap-2 px-3 py-4" data-ui-id={`${uiId}.trigger`}>
<Accordion.Chevron />
<span className="flex h-9 w-9 flex-none items-center justify-center rounded-md bg-surface-neutral-tertiary text-icon-neutral-secondary">{icon}</span>
<span className="flex min-w-0 grow shrink-0 basis-0 flex-col items-start gap-0.5">
<span className="flex flex-wrap items-center gap-1.5">
<span className="text-body-extra-small-medium-0 font-body-extra-small-medium-0 uppercase text-text-neutral-tertiary">{t(captionKey)}</span>
<span className="text-body-small-semibold-0 font-body-small-semibold-0 text-text-neutral-primary">{kontakt.label}</span>
<BadgeFeedback farbe="subtle-neutral" size="small">
{t(kontakt.rolleLabelKey)}
</BadgeFeedback>
{kontakt.primaer ? (
<BadgeFeedback farbe="subtle-brand-primary" size="small">
{t("projects.detail.primaryContact")}
</BadgeFeedback>
) : null}
</span>
{summary ? (
// Wraps instead of truncating: mail, number and address together
// never fit one line in the narrow column, and a cut-off address
// is worse than a row that grows by a line.
<span className="w-full break-words text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">{summary}</span>
) : null}
</span>
{/* The pencil goes to the record in the CRM, which is where contact
master data is edited (S02 renders it read-only). It sits inside the
trigger, so the click must not also fold the row open — and it is a
styled link rather than the kit's IconButton, because the trigger is
itself a <button> and a button inside a button is invalid markup. */}
{kontakt.detailHref ? (
<AppLink
href={kontakt.detailHref}
onClick={(event) => event.stopPropagation()}
aria-label={t("projects.detail.contacts.edit")}
className="flex h-9 w-9 flex-none items-center justify-center rounded-md border border-solid border-border-default bg-surface-neutral-secondary text-icon-neutral-secondary hover:bg-surface-neutral-tertiary"
data-ui-id={`${uiId}.open`}
>
<FeatherEdit2 />
</AppLink>
) : null}
</div>
}
>
<div className="flex w-full flex-col gap-1.5 px-3 pb-3">
<div className="flex w-full flex-wrap items-center justify-end gap-2">
{kontakt.canInviteToPortal ? (
<Button
variant="tertiary"
size="small"
loading={submitting}
onClick={() => submit("invitePortalProjectContact", { contactId: kontakt.kontaktId })}
data-ui-id={`${uiId}.portalInvite`}
>
{t("customerPortal.admin.users.invite")}
</Button>
) : null}
{canWrite ? (
<Button variant="tertiary" size="small" icon={<FeatherTrash2 />} onClick={() => setConfirmOpen(true)} data-ui-id={`${uiId}.unlink`}>
{t("projects.detail.contacts.unlink")}
</Button>
) : null}
</div>
{kontakt.email ? (
<FieldRow icon={<FeatherMail />} label={t("projects.fields.email")} uiId={`${uiId}.email`}>
<a href={`mailto:${kontakt.email}`} className={`${mutedText} hover:underline`}>
{kontakt.email}
</a>
</FieldRow>
) : null}
{kontakt.telefon ? (
<FieldRow icon={<FeatherPhone />} label={t("projects.fields.phone")} uiId={`${uiId}.telefon`}>
<a href={`tel:${kontakt.telefon}`} className={`${mutedText} hover:underline`}>
{kontakt.telefon}
</a>
</FieldRow>
) : null}
{/* The typed numbers get their own rows: a caller chooses between Durchwahl
and Mobil, and one merged phone row hides that choice. */}
{TYPED_PHONES.map((phone) => {
const value = kontakt[phone.key];
if (!value) return null;
return (
<FieldRow key={phone.key} icon={phone.icon} label={t(phone.labelKey)} uiId={`${uiId}.${phone.key}`}>
<a href={`tel:${value}`} className={`${mutedText} hover:underline`}>
{value}
</a>
</FieldRow>
);
})}
{kontakt.adresseLabel ? (
<FieldRow icon={<FeatherMapPin />} label={t("projects.detail.contacts.address")} uiId={`${uiId}.adresse`}>
<span className={mutedText}>{kontakt.adresseLabel}</span>
</FieldRow>
) : null}
{kontakt.lastContactAtIso ? (
<FieldRow icon={<FeatherClock />} label={t("projects.detail.contacts.lastContact")} uiId={`${uiId}.lastContact`}>
<span className={mutedText}>{dateTime.format(new Date(kontakt.lastContactAtIso))}</span>
</FieldRow>
) : null}
{/* Master data, read-only: the row set differs by contact type and the
loader already dropped everything unset. */}
{kontakt.stammdaten.map((row) => (
<FieldRow key={row.labelKey} label={t(row.labelKey)} uiId={`${uiId}.stammdaten.${row.labelKey.split(".").pop()}`}>
<span className={mutedText}>{row.value}</span>
</FieldRow>
))}
{/* The note runs over several lines, so it gets its own block below the
label/value rows instead of being squeezed into one. `whitespace-pre-line`
keeps the paragraphs the author typed. */}
{kontakt.notizen ? (
<div className="flex w-full flex-col gap-1 pt-1" data-ui-id={`${uiId}.notizen`}>
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 uppercase tracking-wide text-text-neutral-tertiary">
{t("projects.detail.contacts.notes")}
</span>
<span className={`${mutedText} whitespace-pre-line`}>{kontakt.notizen}</span>
</div>
) : null}
</div>
{/* Unlinking is not undoable from this screen, so it asks first. It says
plainly that only the link goes — the contact stays in the CRM. */}
<Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>
<Dialog.Content className="p-6" data-ui-id={`${uiId}.unlinkDialog`}>
<div className="flex w-full max-w-[420px] flex-col gap-4">
<span className={sectionHeading}>{t("projects.detail.contacts.unlinkTitle")}</span>
<span className={mutedText}>{t("projects.detail.contacts.unlinkBody", { name: kontakt.label })}</span>
<div className="flex justify-end gap-2">
<Button variant="neutral" onClick={() => setConfirmOpen(false)} data-ui-id={`${uiId}.unlinkCancel`}>
{t("projects.actions.cancel")}
</Button>
<Button
variant="destructive"
loading={submitting}
onClick={() => {
submit("unlinkKontakt", { projektKontaktId: kontakt.id });
setConfirmOpen(false);
}}
data-ui-id={`${uiId}.unlinkConfirm`}
>
{t("projects.detail.contacts.unlink")}
</Button>
</div>
</div>
</Dialog.Content>
</Dialog>
</Accordion>
);
}
@@ -0,0 +1,99 @@
// WF-P8 S02 "KWP-Integration" — read-only, and that is the deliberate delta.
//
// The export draws the fields as inputs, but KWP is an inbound mirror: the
// module declares itself read-only and has no outbound write path, so editable
// fields here would be controls that silently drop what you type. They are drawn
// as locked value boxes instead, which is what the export's greyed-out selects
// look like anyway.
//
// The export also draws Abteilungsnummer and Sachbearbeiter. The inbound KWP
// contract carries neither, and a row that can never fill is worse than no row,
// so they are out (decided with the user on 2026-07-30). If the contract ever
// grows them, they come back here.
//
// The whole section is absent for a project without a KWP binding, which also
// covers every tenant without the capability — the panel loader returns null
// unless an AppEntityBinding ties this project to a KWP project.
import { useTranslation } from "react-i18next";
import { FeatherCircleDot, FeatherHash, FeatherLink, FeatherLock, FeatherPlug, FeatherRefreshCw } from "@subframe/core";
import type { ProjektDetailData } from "@hivegrid/view-models";
import { CopyToClipboardButton } from "~/ui/components/CopyToClipboardButton";
import { DetailCard, EMPTY_VALUE_CLASS, FieldRow, SectionDivider } from "./detailUi";
export type KwpSectionProps = {
data: ProjektDetailData;
/** Formatter injected by the page so the whole screen speaks one locale. */
dateTime: Intl.DateTimeFormat;
};
/** The "this came from KWP" marker the export puts on both ends of the rule. */
function KwpBadge({ label, hint }: { label: string; hint: string }) {
return (
// Fixed hex rather than a token: this exact grey is what the badge is meant
// to be, and no surface token carries it.
<span className="flex h-5 flex-none items-center gap-1.5 rounded-sm bg-[#505057] px-1.5" title={hint}>
<FeatherPlug className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-icon-neutral-on-solid" />
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 text-text-neutral-on-solid">{label}</span>
</span>
);
}
/** A mirrored value: locked box, greyed out, never an input. */
function MirroredValue({ value, trailing }: { value: string | null; trailing?: React.ReactNode }) {
return (
<span className="border-border-default bg-surface-neutral-disabled flex h-8 w-full items-center gap-2 rounded-sm border border-solid px-3">
<FeatherLock className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
<span
className={`text-body-small-medium-0 font-body-small-medium-0 shrink-0 grow basis-0 truncate ${
value ? "text-text-neutral-secondary" : EMPTY_VALUE_CLASS
}`}
>
{value ?? "—"}
</span>
{trailing}
</span>
);
}
export function KwpSection({ data, dateTime }: KwpSectionProps) {
const { t } = useTranslation();
const kwp = data.kwp;
if (!kwp) return null;
const hint = t("projects.detail.kwp.hint");
return (
<DetailCard variant="information" uiId="ui.projects.detail.kwp">
<SectionDivider
icon={<FeatherLink />}
title={t("projects.detail.section.kwp")}
uiId="ui.projects.detail.section.kwp"
// The export marks this tile as foreign data on both ends of the rule,
// which is also the whole "read-only" story: it mirrors KWP, it does not
// own it.
leading={<KwpBadge label={t("projects.detail.kwp.badge")} hint={hint} />}
trailing={<KwpBadge label={t("projects.detail.kwp.badge")} hint={hint} />}
/>
<FieldRow icon={<FeatherHash />} label={t("projects.detail.kwp.projectNumber")} uiId="ui.projects.detail.kwp.projectNumber">
<MirroredValue
value={kwp.externalProjectNumber}
trailing={
<CopyToClipboardButton
clipboardText={kwp.externalProjectNumber}
tooltipText={t("projects.detail.kwp.copyProjectNumber")}
successKey="projects.detail.toast.kwpNumberCopied"
/>
}
/>
</FieldRow>
<FieldRow icon={<FeatherCircleDot />} label={t("projects.detail.kwp.orderStatus")} uiId="ui.projects.detail.kwp.orderStatus">
<MirroredValue value={kwp.statusLabel} />
</FieldRow>
{/* Not in the export, but it is the one thing a mirror owes its reader:
how fresh the mirrored data is. */}
<FieldRow icon={<FeatherRefreshCw />} label={t("projects.detail.kwp.lastSynced")} uiId="ui.projects.detail.kwp.lastSynced">
<MirroredValue value={kwp.lastSyncedAtIso ? dateTime.format(new Date(kwp.lastSyncedAtIso)) : null} />
</FieldRow>
</DetailCard>
);
}
@@ -0,0 +1,329 @@
// WF-P8 S02 "Planung und Verantwortliche" — dates and the people on the project.
//
// The dates stay native `<input type="date">`. The kit's DatePicker is purely
// presentational (it takes a `value` node and has no change handler), so using
// it here would trade a working, keyboard- and locale-aware control for a
// picture of one. Reported to David together with the other kit findings.
//
// Projektleiter is a project column and rides along in the stammdaten draft;
// "Zuständige Personen" and "Monteure" are `ProjektMitglied` rows, so each pick
// is an immediate addMember/removeMember intent — there is no draft that could
// hold a half-built member list.
//
// The single "Zuständig" owner select is gone: it said the same thing as
// "Zuständige Personen", only capped at one name. `Projekt.zustaendigePersonId`
// still travels with the draft untouched, so nothing this screen saves clears
// the column the board filters read.
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherFlag, FeatherHardHat, FeatherPlayCircle, FeatherTimer, FeatherUsers, FeatherWrench } from "@subframe/core";
import * as SubframeCore from "@subframe/core";
import type { ProjectMemberRole, ProjektDetailData, ProjektDetailMitglied } from "@hivegrid/view-models";
import { DropdownMenuMultiSelect } from "~/ui/components/DropdownMenuMultiSelect";
import { MultiSelect } from "~/ui/components/MultiSelect";
import { TextInput } from "~/ui/components/TextInput";
import {
DATE_INPUT_TYPE,
DetailCard,
EMPTY_VALUE_CLASS,
FIELD_CONTROL_PROPS,
FieldRow,
SectionDivider,
mutedText,
type ProjektDetailSubmit,
type StammdatenState,
} from "./detailUi";
export type ProjektDetailOwnerOption = { id: string; label: string };
export type PlanungSectionProps = {
data: ProjektDetailData;
ownerOptions: readonly ProjektDetailOwnerOption[];
value: StammdatenState;
onChange: (patch: Partial<StammdatenState>) => void;
submitting: boolean;
submit: ProjektDetailSubmit;
};
function membersOfRole(mitglieder: readonly ProjektDetailMitglied[], rolle: ProjectMemberRole): ProjektDetailMitglied[] {
return mitglieder.filter((member) => member.rolle === rolle);
}
export function PlanungSection({ data, ownerOptions, value, onChange, submitting, submit }: PlanungSectionProps) {
const { t } = useTranslation();
return (
<DetailCard uiId="ui.projects.detail.planung">
<SectionDivider icon={<FeatherTimer />} title={t("projects.detail.section.planning")} uiId="ui.projects.detail.section.planung" />
{data.canWrite ? (
<>
<FieldRow icon={<FeatherPlayCircle />} label={t("projects.fields.startDate")} uiId="ui.projects.detail.field.startDate">
<TextInput {...FIELD_CONTROL_PROPS}>
{/* An empty date input shows the browser's "tt.mm.jjjj" — that is a
placeholder and gets the placeholder tone, like every other
unset field in this card. */}
<TextInput.Input
variant="small"
type={DATE_INPUT_TYPE}
className={value.startDatum ? undefined : EMPTY_VALUE_CLASS}
value={value.startDatum}
onChange={(e) => onChange({ startDatum: e.target.value })}
/>
</TextInput>
</FieldRow>
<FieldRow icon={<FeatherFlag />} label={t("projects.fields.deadline")} uiId="ui.projects.detail.field.deadline">
<TextInput {...FIELD_CONTROL_PROPS}>
<TextInput.Input
variant="small"
type={DATE_INPUT_TYPE}
className={value.deadline ? undefined : EMPTY_VALUE_CLASS}
value={value.deadline}
onChange={(e) => onChange({ deadline: e.target.value })}
/>
</TextInput>
</FieldRow>
{/* Export order: the people who work on it, then who leads it, then
who is on site. */}
<MemberPicker
icon={<FeatherUsers />}
label={t("projects.fields.assignedPersons")}
rolle="zustaendig"
members={membersOfRole(data.mitglieder, "zustaendig")}
options={ownerOptions}
canManage={data.canManageMembers}
submitting={submitting}
submit={submit}
/>
{ownerOptions.length > 0 ? (
<LeaderPicker
value={value.projektleiterId}
onChange={(projektleiterId) => onChange({ projektleiterId })}
options={ownerOptions}
/>
) : null}
<MemberPicker
icon={<FeatherWrench />}
label={t("projects.fields.fitters")}
rolle="monteur"
members={membersOfRole(data.mitglieder, "monteur")}
options={ownerOptions}
canManage={data.canManageMembers}
submitting={submitting}
submit={submit}
/>
</>
) : (
<>
{/* A reader gets the same rows, only without controls. */}
<MemberPicker
icon={<FeatherUsers />}
label={t("projects.fields.assignedPersons")}
rolle="zustaendig"
members={membersOfRole(data.mitglieder, "zustaendig")}
options={ownerOptions}
canManage={false}
submitting={submitting}
submit={submit}
/>
<FieldRow icon={<FeatherHardHat />} label={t("projects.fields.projectLeader")} uiId="ui.projects.detail.field.projectLeader">
<span className="flex items-center gap-2">
<span className="text-icon-neutral-subtle">
<FeatherHardHat />
</span>
<span className={mutedText}>{data.projektleiterLabel ?? t("projects.fields.none")}</span>
</span>
</FieldRow>
<MemberPicker
icon={<FeatherWrench />}
label={t("projects.fields.fitters")}
rolle="monteur"
members={membersOfRole(data.mitglieder, "monteur")}
options={ownerOptions}
canManage={false}
submitting={submitting}
submit={submit}
/>
</>
)}
</DetailCard>
);
}
/**
* The single Projektleiter, drawn as the same people field as the two member
* pickers: without a pick it shows the greyed placeholder rather than an em
* dash that reads like a value.
*/
function LeaderPicker({
value,
onChange,
options,
}: {
value: string;
onChange: (userId: string) => void;
options: readonly ProjektDetailOwnerOption[];
}) {
const { t } = useTranslation();
const [search, setSearch] = useState("");
const query = search.trim().toLowerCase();
const visible = query ? options.filter((option) => option.label.toLowerCase().includes(query)) : options;
const selected = options.find((option) => option.id === value) ?? null;
return (
<FieldRow icon={<FeatherHardHat />} label={t("projects.fields.projectLeader")} uiId="ui.projects.detail.field.projectLeader">
<div className="flex w-full items-center">
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<MultiSelect
className="h-8 w-full min-w-0 max-w-none"
size="small"
variant="filled"
borderless
hasValue={Boolean(selected)}
icon={<FeatherHardHat />}
value={selected?.label ?? ""}
placeholder={t("projects.fields.selectPerson")}
label=""
aria-label={t("projects.fields.projectLeader")}
data-ui-id="ui.projects.detail.projektleiter.trigger"
/>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="start" sideOffset={4} asChild>
<DropdownMenuMultiSelect
showSearch={options.length > 6}
searchValue={search}
searchPlaceholder={t("projects.fields.search")}
onSearchChange={setSearch}
>
<DropdownMenuMultiSelect.DropdownItem
showCheckbox
selected={!selected}
onClick={() => onChange("")}
data-ui-id="ui.projects.detail.projektleiter.none"
>
{t("projects.fields.none")}
</DropdownMenuMultiSelect.DropdownItem>
{visible.map((option) => (
<DropdownMenuMultiSelect.DropdownItem
key={option.id}
showCheckbox
selected={option.id === value}
onClick={() => onChange(option.id === value ? "" : option.id)}
data-ui-id={`ui.projects.detail.projektleiter.option.${option.id}`}
>
{option.label}
</DropdownMenuMultiSelect.DropdownItem>
))}
</DropdownMenuMultiSelect>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
</div>
</FieldRow>
);
}
type MemberPickerProps = {
icon: React.ReactNode;
label: string;
rolle: ProjectMemberRole;
members: readonly ProjektDetailMitglied[];
options: readonly ProjektDetailOwnerOption[];
canManage: boolean;
submitting: boolean;
submit: ProjektDetailSubmit;
};
/**
* One people picker on top of `ProjektMitglied`, drawn as the export's people
* field: the kit's MultiSelect fills the row (icon left, the picked names,
* chevron at the far right) and opens the checkbox menu. Without
* `projects.manage_members` it degrades to the plain names rather than to a menu
* that would fail on the server.
*/
function MemberPicker({ icon, label, rolle, members, options, canManage, submitting, submit }: MemberPickerProps) {
const { t } = useTranslation();
const [search, setSearch] = useState("");
const uiId = `ui.projects.detail.members.${rolle}`;
const memberByUserId = new Map(members.map((member) => [member.userId, member]));
const query = search.trim().toLowerCase();
const visible = query ? options.filter((option) => option.label.toLowerCase().includes(query)) : options;
const names = members.map((member) => member.label).join(", ");
function toggle(userId: string) {
const existing = memberByUserId.get(userId);
if (existing) submit("removeMember", { memberId: existing.id });
else submit("addMember", { userId, rolle });
}
if (!canManage) {
return (
<FieldRow icon={icon} label={label} uiId={uiId}>
<span className="flex items-center gap-2">
<span className="text-icon-neutral-subtle">{icon}</span>
<span className={mutedText} data-ui-id={`${uiId}.value`}>
{names || t("projects.fields.none")}
</span>
</span>
</FieldRow>
);
}
return (
<FieldRow icon={icon} label={label} uiId={uiId}>
<div className="flex w-full items-center">
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
{/* MultiSelect is the trigger itself: it forwards its ref and props
to its root div, so Radix can drive it without a second box. */}
<MultiSelect
className="h-8 w-full min-w-0 max-w-none"
size="small"
variant="filled"
borderless
hasValue={members.length > 0}
icon={icon}
value={names}
placeholder={t("projects.fields.selectPersons")}
label=""
aria-label={label}
aria-disabled={submitting || undefined}
data-ui-id={`${uiId}.trigger`}
/>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="start" sideOffset={4} asChild>
<DropdownMenuMultiSelect
showSearch={options.length > 6}
searchValue={search}
searchPlaceholder={t("projects.fields.search")}
onSearchChange={setSearch}
>
{visible.length === 0 ? (
<DropdownMenuMultiSelect.DropdownCustomItem>
<span className="px-1 text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{t("projects.board.filter.noOptions")}
</span>
</DropdownMenuMultiSelect.DropdownCustomItem>
) : null}
{visible.map((option) => (
<DropdownMenuMultiSelect.DropdownItem
key={option.id}
showCheckbox
selected={memberByUserId.has(option.id)}
onClick={() => toggle(option.id)}
data-ui-id={`${uiId}.option.${option.id}`}
>
{option.label}
</DropdownMenuMultiSelect.DropdownItem>
))}
</DropdownMenuMultiSelect>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
</div>
</FieldRow>
);
}
@@ -0,0 +1,54 @@
// WF-P8 S02 "Projektkontaktdaten" — the channels of the project itself, which
// are not the same thing as the linked Kontakt records below.
import { useTranslation } from "react-i18next";
import { FeatherAtSign, FeatherMail, FeatherPhone, FeatherPrinter } from "@subframe/core";
import type { ProjektDetailData } from "@hivegrid/view-models";
import { TextInput } from "~/ui/components/TextInput";
import { DetailCard, FIELD_CONTROL_PROPS, FieldRow, SectionDivider, mutedText, type StammdatenState } from "./detailUi";
export type ProjektkontaktSectionProps = {
data: ProjektDetailData;
value: StammdatenState;
onChange: (patch: Partial<StammdatenState>) => void;
};
export function ProjektkontaktSection({ data, value, onChange }: ProjektkontaktSectionProps) {
const { t } = useTranslation();
if (!data.canWrite) {
const lines = [value.email, value.telefon, value.fax].filter(Boolean);
if (lines.length === 0) return null;
return (
<DetailCard uiId="ui.projects.detail.projectContact">
<SectionDivider icon={<FeatherAtSign />} title={t("projects.detail.section.projectContact")} uiId="ui.projects.detail.section.projectContact" />
{lines.map((line) => (
<span key={line} className={mutedText}>
{line}
</span>
))}
</DetailCard>
);
}
return (
<DetailCard uiId="ui.projects.detail.projectContact">
<SectionDivider icon={<FeatherAtSign />} title={t("projects.detail.section.projectContact")} uiId="ui.projects.detail.section.projectContact" />
<FieldRow icon={<FeatherMail />} label={t("projects.fields.email")} uiId="ui.projects.detail.field.email">
<TextInput {...FIELD_CONTROL_PROPS}>
<TextInput.Input variant="small" value={value.email} onChange={(e) => onChange({ email: e.target.value })} data-ui-id="ui.projects.detail.email" />
</TextInput>
</FieldRow>
<FieldRow icon={<FeatherPhone />} label={t("projects.fields.phone")} uiId="ui.projects.detail.field.phone">
<TextInput {...FIELD_CONTROL_PROPS}>
<TextInput.Input variant="small" value={value.telefon} onChange={(e) => onChange({ telefon: e.target.value })} data-ui-id="ui.projects.detail.telefon" />
</TextInput>
</FieldRow>
<FieldRow icon={<FeatherPrinter />} label={t("projects.fields.fax")} uiId="ui.projects.detail.field.fax">
<TextInput {...FIELD_CONTROL_PROPS}>
<TextInput.Input variant="small" value={value.fax} onChange={(e) => onChange({ fax: e.target.value })} data-ui-id="ui.projects.detail.fax" />
</TextInput>
</FieldRow>
</DetailCard>
);
}
@@ -0,0 +1,160 @@
// WF-P8 S02 — the pieces every detail section shares: typography constants,
// the editable stammdaten state and the small value helpers.
//
// Extracted so the section components below stay about their own fields rather
// than each carrying its own copy of the same three class strings.
import type { ReactNode } from "react";
import type { ProjektDetailData } from "@hivegrid/view-models";
import { Card } from "~/ui/components/Card";
/** POST a detail action with its string fields; the route builds FormData. */
export type ProjektDetailSubmit = (intent: string, fields?: Record<string, string>) => void;
export const PRIORITIES = ["niedrig", "normal", "hoch", "dringend"] as const;
/** Money on a project is EUR everywhere in v1 (EU stack, single currency). */
export const CURRENCY_SYMBOL = "€";
/** Tone of a field that holds no value yet — same grey as a placeholder. */
export const EMPTY_VALUE_CLASS = "text-text-neutral-subtle";
// TextInput.Input's typed `type` union omits "date"; the native input supports it.
export const DATE_INPUT_TYPE = "date" as unknown as "text";
export const sectionHeading = "text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary";
export const mutedText = "text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary";
export const labelText = "text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-tertiary";
/**
* The S02 tile. The export draws every group as a flat, tight card on the page
* surface — no border, no shadow, 12/8 padding — so the tiles read as one sheet
* of paper rather than as six floating panels.
*/
export function DetailCard({
children,
variant,
uiId,
}: {
children: ReactNode;
/** "information" is the KWP tile: an inbound mirror, tinted to say so. */
variant?: "information";
uiId?: string;
}) {
return (
<Card size="small" variant={variant} className="gap-2 border-none px-3 py-2 shadow-none" data-ui-id={uiId}>
{children}
</Card>
);
}
/**
* WF-P8 S02 section heading: a rule, an icon, an uppercase caption and a rule.
*
* Only "Kontakte" and "Adressdaten" are accordions in the export; the other
* four groups are divider-headed sections like this one.
*/
export function SectionDivider({
icon,
title,
uiId,
leading,
trailing,
}: {
icon: ReactNode;
title: string;
uiId?: string;
/** Badge at the far left of the rule (the KWP tile marks its origin on both ends). */
leading?: ReactNode;
/** Badge at the far right of the rule (the KWP tile marks its origin there). */
trailing?: ReactNode;
}) {
return (
<div className="flex w-full items-center gap-2" data-ui-id={uiId}>
{leading}
<div className="h-0.5 grow shrink-0 basis-0 bg-icon-neutral-subtle" />
<span className="flex items-center text-body-default-regular-150 font-body-default-regular-150 text-icon-neutral-tertiary">{icon}</span>
<span className="whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 uppercase text-text-neutral-tertiary">{title}</span>
<div className="h-0.5 grow shrink-0 basis-0 bg-icon-neutral-subtle" />
{trailing}
</div>
);
}
/**
* The repeating unit of the S02 field groups: a fixed 12rem label gutter with
* its icon, a hairline that separates label from control, and the control. Each
* row closes with a full-width hairline, which is what gives the tile its
* table-like look in the export.
*
* The gutter collapses above the control on mobile — the export keeps the two
* side by side, which leaves a 320px viewport with no room for the field.
*/
export function FieldRow({
icon,
label,
children,
uiId,
}: {
icon?: ReactNode;
label: string;
children: ReactNode;
uiId?: string;
}) {
return (
<div className="flex w-full flex-col items-center gap-1.5" data-ui-id={uiId}>
<div className="flex w-full items-center mobile:flex-col mobile:items-start mobile:gap-1">
<div className="flex h-8 w-48 flex-none items-center justify-between mobile:h-auto mobile:w-full">
<div className="flex w-48 flex-none items-center gap-2 pl-1 pr-3 mobile:w-full">
{icon ? <span className="flex items-center text-body-large-0 font-body-large-0 text-icon-neutral-primary">{icon}</span> : null}
<span className="line-clamp-2 grow shrink-0 basis-0 break-words text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-primary">
{label}
</span>
</div>
<div className="w-px flex-none self-stretch bg-icon-neutral-subtle mobile:hidden" />
</div>
<div className="flex min-w-0 grow shrink-0 basis-0 items-center px-2 py-0.5 mobile:w-full mobile:px-0">{children}</div>
</div>
<div className="h-px w-full flex-none bg-icon-neutral-subtle" />
</div>
);
}
/**
* Field chrome of the S02 tiles: the control carries no border of its own, the
* row around it already draws every line the export shows.
*/
export const FIELD_CONTROL_PROPS = {
size: "small",
variant: "filled",
borderless: true,
// `max-w-none` rather than `fillContainer`: the kit caps a field at 320px and
// only TextInput has that prop, while Select passes it straight to the DOM.
className: "h-auto w-full max-w-none",
label: "",
} as const;
export function isoToDateInput(iso: string | null): string {
return iso ? iso.slice(0, 10) : "";
}
/** Editable stammdaten form state derived from the VM (also used to reset on cancel). */
export function toStammdatenState(data: ProjektDetailData) {
return {
projektname: data.projektname,
beschreibung: data.beschreibung ?? "",
prioritaet: data.prioritaet as string,
potenziellerAuftragswert: data.value ?? "",
auftragsvolumen: data.orderVolume ?? "",
startDatum: isoToDateInput(data.startDatumIso),
deadline: isoToDateInput(data.deadlineIso),
zustaendigePersonId: data.ownerUserId ?? "",
projektleiterId: data.projektleiterId ?? "",
// WF-P8 S02 "Grunddaten" / "Projektkontaktdaten".
projekttyp: data.projekttyp ?? "",
quelle: data.quelle ?? "",
promotion: data.promotion ?? "",
email: data.email ?? "",
telefon: data.telefon ?? "",
fax: data.fax ?? "",
};
}
export type StammdatenState = ReturnType<typeof toStammdatenState>;
@@ -0,0 +1,166 @@
// WF-P8 M04/M04a/M04b/M04c — the four Subframe pages are four tab states of
// one dialog, so the test walks the tabs and asserts that each kind keeps the
// detail its own screen shows (file meta line, task badges, appointment date
// block) instead of collapsing into one generic row.
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildPipelineHandoverVM, type BuildPipelineHandoverVMInput } from "@hivegrid/view-models";
import { PipelineHandoverDialog } from "./PipelineHandoverDialog";
// Interpolating mock: several rows render "<key> <value>" (due date, counts),
// and a key-only mock would hide exactly the value under test.
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, options?: Record<string, unknown>) =>
options ? `${key} ${Object.values(options).join(" ")}` : key,
i18n: { language: "de" },
}),
}));
const byUiId = (id: string) => document.querySelector(`[data-ui-id='${id}']`) as HTMLElement;
const allByUiId = (id: string) => Array.from(document.querySelectorAll(`[data-ui-id='${id}']`)) as HTMLElement[];
const candidates: BuildPipelineHandoverVMInput["candidates"] = [
{
id: "note_1",
kind: "notiz",
title: "BAFA-Antrag läuft",
body: "Familie ist förderprogramm-affin.",
personId: "usr_markus",
atIso: "2026-07-09T08:00:00.000Z",
defaultSelected: true,
},
{ id: "note_2", kind: "notiz", title: "Zwei Vergleichsangebote", personId: null, atIso: null, defaultSelected: false },
{
id: "file_1",
kind: "datei",
title: "Angebot_v1.pdf",
atIso: "2026-07-10T08:00:00.000Z",
defaultSelected: true,
fileExtension: "PDF",
fileRole: "Angebotsdokument",
fileSizeBytes: 253952,
},
{
id: "task_1",
kind: "aufgabe",
title: "Förderzusage prüfen",
body: "BAFA-Zusage kontrollieren.",
personId: "usr_markus",
atIso: "2026-07-15T08:00:00.000Z",
defaultSelected: true,
taskStatus: "open",
taskPriority: "high",
deadlineIso: "2026-07-15T08:00:00.000Z",
},
{
id: "apt_1",
kind: "termin",
title: "Vor-Ort-Termin",
personId: "usr_sandra",
atIso: "2026-07-12T08:30:00.000Z",
defaultSelected: true,
appointmentType: "vor_ort",
},
];
function renderDialog(onConfirm = vi.fn()) {
const vm = buildPipelineHandoverVM({
projectId: "prj_1",
projectName: "Wärmepumpe Müller",
fromPipelineId: "pipe_sales",
fromPipelineName: "Angebot",
toPipelineId: "pipe_install",
toPipelineName: "Anlagen-Installation",
toStageId: "stage_new",
toStageName: "Neu",
candidates,
userLabels: { usr_markus: "Markus Weber", usr_sandra: "Sandra Koch" },
});
render(<PipelineHandoverDialog open vm={vm} submitting={false} onOpenChange={vi.fn()} onConfirm={onConfirm} />);
return { onConfirm };
}
describe("PipelineHandoverDialog", () => {
it("names the project and the route the handover takes", () => {
renderDialog();
expect(byUiId("ui.projects.handover.route").textContent).toContain("Wärmepumpe Müller");
expect(byUiId("ui.projects.handover.route").textContent).toContain("Angebot → Anlagen-Installation");
});
it("opens on the notes tab and shows body and 'date · author' under the headline", () => {
renderDialog();
const rows = allByUiId("ui.projects.handover.item.notiz");
expect(rows).toHaveLength(2);
expect(rows[0].textContent).toContain("Familie ist förderprogramm-affin.");
expect(rows[0].textContent).toContain("09.07.2026 · Markus Weber");
});
it("shows a file as 'role · size · date' with its type as the badge", () => {
renderDialog();
fireEvent.click(byUiId("ui.projects.handover.tab.datei"));
const row = byUiId("ui.projects.handover.item.datei");
expect(row.textContent).toContain("PDF");
expect(row.textContent).toContain("Angebotsdokument · 248.0 KB · 10.07.2026");
});
it("badges a task with status, due date, priority and assignee", () => {
renderDialog();
fireEvent.click(byUiId("ui.projects.handover.tab.aufgabe"));
const row = byUiId("ui.projects.handover.item.aufgabe");
expect(row.textContent).toContain("tasks.status.open");
expect(row.textContent).toContain("projects.handover.task.due 15.07.2026");
expect(row.textContent).toContain("tasks.priority.high");
expect(row.textContent).toContain("Markus Weber");
});
it("gives an appointment a date block instead of an icon", () => {
renderDialog();
fireEvent.click(byUiId("ui.projects.handover.tab.termin"));
const row = byUiId("ui.projects.handover.item.termin");
expect(row.textContent).toContain("12.07.");
expect(row.textContent).toContain("10:30");
expect(row.textContent).toContain("projects.quickAction.appointment.type.vor_ort");
});
it("counts what is ticked and drops a candidate from the selection when it is unticked", () => {
const { onConfirm } = renderDialog();
expect(byUiId("ui.projects.handover.summary").textContent).toContain("projects.handover.selectedCount 4");
const noteRow = allByUiId("ui.projects.handover.item.notiz")[0];
// Radix renders the checkbox as a button, not an <input>.
fireEvent.click(noteRow.querySelector("[role='checkbox']")!);
expect(byUiId("ui.projects.handover.summary").textContent).toContain("projects.handover.selectedCount 3");
fireEvent.click(byUiId("ui.projects.handover.confirm"));
expect(onConfirm).toHaveBeenCalledWith([
{ kind: "datei", sourceId: "file_1" },
{ kind: "aufgabe", sourceId: "task_1" },
{ kind: "termin", sourceId: "apt_1" },
]);
});
it("states that a tab is empty rather than showing a bare list", () => {
render(
<PipelineHandoverDialog
open
vm={buildPipelineHandoverVM({
projectId: "p",
projectName: "P",
fromPipelineId: "a",
fromPipelineName: "A",
toPipelineId: "b",
toPipelineName: "B",
toStageId: "s",
toStageName: "S",
candidates: [],
})}
submitting={false}
onOpenChange={vi.fn()}
onConfirm={vi.fn()}
/>
);
expect(screen.getAllByText("projects.handover.empty.title").length).toBeGreaterThan(0);
});
});
@@ -0,0 +1,423 @@
// WF-P8 M04 / M04a / M04b / M04c (Pipeline-Uebergabe) — Subframe baseline.
//
// Davids four Subframe pages are four TAB STATES of one dialog, not four
// dialogs, so they are one component here. The tab strip uses the local
// `Tabs.Item` (the cloud export's `Tabs.TabBottom` does not exist in our kit),
// stretched to equal widths the way the export lays them out.
//
// Each tab draws its own row: a note is a headline plus body plus
// "date · author", a file is name plus "role · size · date" with its type as
// the badge, a task adds due-date/priority/assignee under the description, and
// an appointment trades the icon for a date block. That per-kind detail is what
// makes the four screens different — a single generic row would flatten it.
//
// Trigger: this dialog is opened by the caller after a stage move into the
// pipeline's final stage — there is deliberately no button that opens it.
// Pure/presentational: the VM comes from the route loader, the selection is
// local state, and "Auswahl uebernehmen" hands the picked ids back through
// `onConfirm`.
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
FeatherArrowRightCircle,
FeatherCheck,
FeatherCheckSquare,
FeatherFileArchive,
FeatherFileText,
FeatherStickyNote,
FeatherX,
} from "@subframe/core";
import type { PipelineHandoverVM, PipelineHandoverCandidateVM, PipelineHandoverKind } from "@hivegrid/view-models";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Checkbox } from "~/ui/components/Checkbox";
import { Dialog } from "~/ui/components/Dialog";
import { EmptyState } from "~/ui/components/EmptyState";
import { IconButton } from "~/ui/components/IconButton";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
import { Tabs } from "~/ui/components/Tabs";
import { useLocaleFormatters } from "~/locale/format";
/** Tab order mirrors Davids M04 → M04a → M04b → M04c. */
const TAB_ORDER: readonly PipelineHandoverKind[] = ["notiz", "datei", "aufgabe", "termin"];
/** The export gives every tab the same share of the strip. */
const TAB_CLASS = "h-auto w-auto min-w-[0px] flex-none grow shrink basis-0 px-2 py-2";
const TAB_LABEL_KEY: Record<PipelineHandoverKind, string> = {
notiz: "projects.handover.tab.notes",
datei: "projects.handover.tab.files",
aufgabe: "projects.handover.tab.tasks",
termin: "projects.handover.tab.appointments",
};
const KIND_COUNT_KEY: Record<PipelineHandoverKind, string> = {
notiz: "projects.handover.count.notes",
datei: "projects.handover.count.files",
aufgabe: "projects.handover.count.tasks",
termin: "projects.handover.count.appointments",
};
/** Row shells — the selected one is the export's tinted brand-secondary card. */
const ROW_SELECTED = "rounded-md border border-solid border-brand-brand-secondary-border-subtle-default bg-brand-brand-secondary-surface-subtle-default px-3 py-2.5";
const ROW_PLAIN = "rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-3 py-2.5";
const TITLE_CLASS = "min-w-[0px] grow shrink-0 basis-0 text-body-small-semibold-150 font-body-small-semibold-150 text-text-neutral-primary";
const BODY_CLASS = "text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-secondary";
const META_CLASS = "text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary";
/** Priority tones follow the export: the two urgent levels read as a warning. */
const PRIORITY_TONE: Record<string, "subtle-negative" | "subtle-warning" | "subtle-neutral"> = {
urgent: "subtle-negative",
high: "subtle-negative",
normal: "subtle-neutral",
low: "subtle-neutral",
};
/**
* Appointment types carry their own colour in the export — the badge and the
* date block share it, which is what makes a phone call readable as a phone
* call at a glance.
*/
const APPOINTMENT_TONE: Record<
string,
{ badge: "subtle-information" | "subtle-blue" | "subtle-neutral"; box: string; day: string }
> = {
vor_ort: {
badge: "subtle-information",
box: "border-brand-brand-border-subtle-default bg-brand-brand-surface-subtle-default",
day: "text-brand-brand-surface-solid-default",
},
telefon: {
badge: "subtle-blue",
box: "border-border-default bg-surface-ui-subtle-blue-default",
day: "text-text-ui-blue",
},
online: {
badge: "subtle-neutral",
box: "border-border-default bg-surface-feedback-subtle-neutral",
day: "text-text-neutral-primary",
},
};
const APPOINTMENT_FALLBACK = APPOINTMENT_TONE.online!;
/** Same scale as the file browser: a size is read, not calculated. */
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
const units = ["KB", "MB", "GB"];
let value = bytes / 1024;
let unitIndex = 0;
while (value >= 1024 && unitIndex < units.length - 1) {
value /= 1024;
unitIndex += 1;
}
return `${value.toFixed(1)} ${units[unitIndex]}`;
}
export type PipelineHandoverDialogProps = {
open: boolean;
vm: PipelineHandoverVM;
submitting: boolean;
onOpenChange: (open: boolean) => void;
/** Commits the handover with the ticked companion records. */
onConfirm: (selection: readonly { kind: PipelineHandoverKind; sourceId: string }[]) => void;
};
/** Stable selection key — ids are only unique per kind, not across kinds. */
function selectionKey(candidate: Pick<PipelineHandoverCandidateVM, "kind" | "id">): string {
return `${candidate.kind}:${candidate.id}`;
}
export function PipelineHandoverDialog(props: PipelineHandoverDialogProps) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const { vm } = props;
const [activeTab, setActiveTab] = useState<PipelineHandoverKind>("notiz");
const [selected, setSelected] = useState<ReadonlySet<string>>(
() => new Set(vm.candidates.filter((candidate) => candidate.defaultSelected).map(selectionKey))
);
const byKind = useMemo(() => {
const grouped = new Map<PipelineHandoverKind, PipelineHandoverCandidateVM[]>();
for (const kind of TAB_ORDER) grouped.set(kind, []);
for (const candidate of vm.candidates) grouped.get(candidate.kind)?.push(candidate);
return grouped;
}, [vm.candidates]);
const counts = useMemo(() => {
const result = new Map<PipelineHandoverKind, number>();
for (const kind of TAB_ORDER) {
result.set(kind, (byKind.get(kind) ?? []).filter((candidate) => selected.has(selectionKey(candidate))).length);
}
return result;
}, [byKind, selected]);
const totalSelected = TAB_ORDER.reduce((sum, kind) => sum + (counts.get(kind) ?? 0), 0);
function toggle(candidate: PipelineHandoverCandidateVM) {
setSelected((current) => {
const next = new Set(current);
const key = selectionKey(candidate);
if (next.has(key)) next.delete(key);
else next.add(key);
return next;
});
}
function confirm() {
props.onConfirm(
vm.candidates.filter((candidate) => selected.has(selectionKey(candidate))).map((candidate) => ({ kind: candidate.kind, sourceId: candidate.id }))
);
}
// `date`, not `dateTime`: our dateTime helper pins dateStyle/timeStyle, and
// Intl rejects those next to explicit day/month/hour fields.
const date = (iso: string) => formatters.date(iso, { day: "2-digit", month: "2-digit", year: "numeric" });
/** "09.07.2026 · Markus Weber" — either half may be missing. */
function metaLine(parts: readonly (string | null | undefined)[]): string | null {
const kept = parts.filter((part): part is string => Boolean(part));
return kept.length > 0 ? kept.join(" · ") : null;
}
function renderNote(candidate: PipelineHandoverCandidateVM, isSelected: boolean) {
const meta = metaLine([candidate.atIso ? date(candidate.atIso) : null, candidate.personLabel]);
return (
<>
<IconWithBackground variant={isSelected ? "warning" : "neutral"} size="small" icon={<FeatherStickyNote />} />
<div className="flex min-w-[0px] grow shrink-0 basis-0 flex-col items-start gap-1">
<div className="flex w-full items-center justify-between gap-2">
<span className={TITLE_CLASS}>{candidate.title}</span>
<BadgeFeedback farbe={isSelected ? "subtle-warning" : "subtle-neutral"} size="small">
{t("projects.handover.kind.note")}
</BadgeFeedback>
</div>
{candidate.body ? <span className={BODY_CLASS}>{candidate.body}</span> : null}
{meta ? <span className={META_CLASS}>{meta}</span> : null}
</div>
</>
);
}
function renderFile(candidate: PipelineHandoverCandidateVM, isSelected: boolean) {
const isArchive = candidate.fileExtension === "ZIP" || candidate.fileExtension === "RAR" || candidate.fileExtension === "7Z";
const meta = metaLine([
candidate.fileRole,
candidate.fileSizeBytes === null ? null : formatBytes(candidate.fileSizeBytes),
candidate.atIso ? date(candidate.atIso) : null,
]);
return (
<>
<IconWithBackground
variant={isSelected ? "information" : "neutral"}
size="small"
icon={isArchive ? <FeatherFileArchive /> : <FeatherFileText />}
/>
<div className="flex min-w-[0px] grow shrink-0 basis-0 flex-col items-start gap-1">
<div className="flex w-full items-center justify-between gap-2">
<span className={TITLE_CLASS}>{candidate.title}</span>
{candidate.fileExtension ? (
<BadgeFeedback farbe={isSelected ? "subtle-information" : "subtle-neutral"} size="small">
{candidate.fileExtension}
</BadgeFeedback>
) : null}
</div>
{meta ? <span className={META_CLASS}>{meta}</span> : null}
</div>
</>
);
}
function renderTask(candidate: PipelineHandoverCandidateVM, isSelected: boolean) {
return (
<>
<IconWithBackground variant={isSelected ? "success" : "neutral"} size="small" icon={<FeatherCheckSquare />} />
<div className="flex min-w-[0px] grow shrink-0 basis-0 flex-col items-start gap-1">
<div className="flex w-full items-center justify-between gap-2">
<span className={TITLE_CLASS}>{candidate.title}</span>
{candidate.taskStatus ? (
<BadgeFeedback farbe={isSelected ? "subtle-positive" : "subtle-neutral"} size="small">
{t(`tasks.status.${candidate.taskStatus}`)}
</BadgeFeedback>
) : null}
</div>
{candidate.body ? <span className={BODY_CLASS}>{candidate.body}</span> : null}
<div className="flex flex-wrap items-center gap-2">
{candidate.deadlineIso ? (
<BadgeFeedback farbe="subtle-warning" size="small">
{t("projects.handover.task.due", { date: date(candidate.deadlineIso) })}
</BadgeFeedback>
) : null}
{candidate.taskPriority ? (
<BadgeFeedback farbe={PRIORITY_TONE[candidate.taskPriority] ?? "subtle-neutral"} size="small">
{t(`tasks.priority.${candidate.taskPriority}`)}
</BadgeFeedback>
) : null}
{candidate.personLabel ? <span className={META_CLASS}>{candidate.personLabel}</span> : null}
</div>
</div>
</>
);
}
function renderAppointment(candidate: PipelineHandoverCandidateVM) {
const tone = (candidate.appointmentType ? APPOINTMENT_TONE[candidate.appointmentType] : null) ?? APPOINTMENT_FALLBACK;
const meta = metaLine([candidate.personLabel, candidate.body]);
return (
<>
<div className={`flex flex-none flex-col items-center justify-center rounded-md border border-solid px-2 py-1 ${tone.box}`}>
<span className={`text-body-extra-small-semibold-150 font-body-extra-small-semibold-150 ${tone.day}`}>
{candidate.atIso ? formatters.date(candidate.atIso, { day: "2-digit", month: "2-digit" }) : "—"}
</span>
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-secondary">
{candidate.atIso ? formatters.date(candidate.atIso, { hour: "2-digit", minute: "2-digit" }) : ""}
</span>
</div>
<div className="flex min-w-[0px] grow shrink-0 basis-0 flex-col items-start gap-1">
<div className="flex w-full items-center justify-between gap-2">
<span className={TITLE_CLASS}>{candidate.title}</span>
{candidate.appointmentType ? (
<BadgeFeedback farbe={tone.badge} size="small">
{t(`projects.quickAction.appointment.type.${candidate.appointmentType}`)}
</BadgeFeedback>
) : null}
</div>
{meta ? <span className={META_CLASS}>{meta}</span> : null}
</div>
</>
);
}
const visible = byKind.get(activeTab) ?? [];
return (
<Dialog open={props.open} onOpenChange={props.onOpenChange}>
<Dialog.Content className="h-auto w-112 max-w-[92vw] p-6" data-ui-id="ui.projects.handover">
<div className="flex w-full flex-col items-start gap-5">
<div className="flex w-full items-start justify-between gap-3">
<div className="flex items-start gap-3">
<IconWithBackground variant="information" size="large" round icon={<FeatherArrowRightCircle />} />
<div className="flex min-w-[0px] grow shrink-0 basis-0 flex-col items-start gap-1">
<span className="text-heading-0 font-heading-0 text-text-neutral-primary">{t("projects.handover.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("projects.handover.subtitle")}
</span>
</div>
</div>
<IconButton
variant="tertiary"
size="small"
icon={<FeatherX />}
onClick={() => props.onOpenChange(false)}
data-ui-id="ui.projects.handover.close"
/>
</div>
{/* Project + route line ("Wärmepumpe Müller" / "Angebot → Anlagen-Installation"). */}
<div className="flex w-full flex-col items-start gap-1 rounded-md bg-surface-neutral-tertiary px-3 py-2" data-ui-id="ui.projects.handover.route">
<span className="text-body-extra-small-medium-0 font-body-extra-small-medium-0 text-text-neutral-tertiary">{vm.projectName}</span>
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary">
{vm.fromPipelineName} → {vm.toPipelineName}
</span>
</div>
<div className="flex w-full flex-col items-start gap-3">
<Tabs>
{TAB_ORDER.map((kind) => (
<Tabs.Item
key={kind}
className={TAB_CLASS}
active={activeTab === kind}
onClick={() => setActiveTab(kind)}
data-ui-id={`ui.projects.handover.tab.${kind}`}
>
{t(TAB_LABEL_KEY[kind])}
</Tabs.Item>
))}
</Tabs>
<div className="flex w-full flex-col items-start gap-2">
{visible.length === 0 ? (
<div className="w-full" data-ui-id="ui.projects.handover.empty">
<EmptyState outlined title={t("projects.handover.empty.title")} body={t("projects.handover.empty.body")} />
</div>
) : (
visible.map((candidate) => {
const isSelected = selected.has(selectionKey(candidate));
// Notes and tasks stack several lines, so their checkbox sits
// at the top; a file/appointment row is one line tall and
// centres like the export.
const align = candidate.kind === "notiz" || candidate.kind === "aufgabe" ? "items-start" : "items-center";
return (
<div
key={selectionKey(candidate)}
className={`flex w-full gap-3 ${align} ${isSelected ? ROW_SELECTED : ROW_PLAIN}`}
data-row-id={candidate.id}
data-ui-id={`ui.projects.handover.item.${candidate.kind}`}
>
<Checkbox
label=""
hideLabel
checked={isSelected}
onCheckedChange={() => toggle(candidate)}
aria-label={candidate.title}
/>
{candidate.kind === "notiz" ? renderNote(candidate, isSelected) : null}
{candidate.kind === "datei" ? renderFile(candidate, isSelected) : null}
{candidate.kind === "aufgabe" ? renderTask(candidate, isSelected) : null}
{candidate.kind === "termin" ? renderAppointment(candidate) : null}
</div>
);
})
)}
</div>
</div>
{/* Selection summary — counts stay live while the user ticks. The
highlighted chip is the tab being looked at, so the row reads as
"you are here" instead of "these are non-empty". */}
<div
className="flex w-full flex-col items-start gap-2 rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-3 py-3"
data-ui-id="ui.projects.handover.summary"
>
<div className="flex w-full items-center justify-between gap-3">
<span className="text-body-small-semibold-150 font-body-small-semibold-150 text-text-neutral-primary">
{t("projects.handover.selection")}
</span>
<BadgeFeedback farbe="subtle-information" size="small">
{t("projects.handover.selectedCount", { count: totalSelected })}
</BadgeFeedback>
</div>
<div className="flex w-full flex-wrap items-center gap-2">
{TAB_ORDER.map((kind) => (
<BadgeFeedback key={kind} farbe={activeTab === kind ? "subtle-information" : "subtle-neutral"} size="small">
{t(KIND_COUNT_KEY[kind], { count: counts.get(kind) ?? 0 })}
</BadgeFeedback>
))}
</div>
</div>
<div className="flex w-full items-center justify-end gap-2">
<Button variant="tertiary" onClick={() => props.onOpenChange(false)} data-ui-id="ui.projects.handover.cancel">
{t("projects.actions.cancel")}
</Button>
<Button
variant="primary"
icon={<FeatherCheck />}
loading={props.submitting}
onClick={confirm}
data-ui-id="ui.projects.handover.confirm"
>
{t("projects.handover.confirm")}
</Button>
</div>
</div>
</Dialog.Content>
</Dialog>
);
}
export default PipelineHandoverDialog;
@@ -0,0 +1,484 @@
// WF-P8 S02-A / S02-N / S02-T / S02-F — the four quick-action modals of the
// project detail screen (Aufgabe, Notiz, Termin, Datei).
//
// Davids Subframe pages build their surface by hand inside `DialogLayout`
// instead of using `Dialog.Content` (the P8 handoff records this as a known
// inconsistency on the Subframe side, not as a target). We use the real
// `Dialog`/`Dialog.Content` structure here — same optics, correct semantics
// (focus trap, escape, aria).
//
// Pure/presentational: each dialog owns its draft state and hands the fields to
// a single `onSubmit(intent, fields)` the route turns into a POST.
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherCalendarPlus, FeatherCheckSquare, FeatherStickyNote, FeatherUpload } from "@subframe/core";
import { QuickActionDialog } from "../../shared/QuickActionDialog";
import { Button } from "~/ui/components/Button";
import { Select } from "~/ui/components/Select";
import { TextArea } from "~/ui/components/TextArea";
import { TextInput } from "~/ui/components/TextInput";
/** POST a detail action with its string fields; the route builds the FormData. */
export type ProjectQuickActionSubmit = (intent: string, fields?: Record<string, string>) => void;
/** TextInput.Input's typed `type` union omits date/time; the native input supports both. */
const DATE_INPUT_TYPE = "date" as unknown as "text";
const TIME_INPUT_TYPE = "time" as unknown as "text";
export type ProjectAssigneeOption = { id: string; label: string };
/** Reset a draft whenever the dialog opens, so a cancelled entry never reappears. */
function useResetOnOpen<T>(open: boolean, initial: () => T): [T, React.Dispatch<React.SetStateAction<T>>] {
const [value, setValue] = useState<T>(initial);
useEffect(() => {
if (open) setValue(initial());
// `initial` is a fresh closure each render; keying on `open` is the intent.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
return [value, setValue];
}
// --- S02-N Notiz erstellen -------------------------------------------------
const NOTE_VISIBILITIES = ["alle", "innendienst", "nur_ich"] as const;
export type CreateNoteDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
submitting: boolean;
/** Hidden when the actor lacks `projects.read_internal_notes`. */
canChooseInternal: boolean;
onSubmit: ProjectQuickActionSubmit;
};
export function CreateNoteDialog(props: CreateNoteDialogProps) {
const { t } = useTranslation();
const [draft, setDraft] = useResetOnOpen(props.open, () => ({ inhalt: "", sichtbarkeit: "alle" as (typeof NOTE_VISIBILITIES)[number] }));
const visibilities = props.canChooseInternal ? NOTE_VISIBILITIES : NOTE_VISIBILITIES.filter((value) => value !== "innendienst");
return (
<QuickActionDialog
open={props.open}
onOpenChange={props.onOpenChange}
icon={<FeatherStickyNote />}
iconVariant="warning"
title={t("projects.quickAction.note.title")}
subtitle={t("projects.quickAction.note.subtitle")}
submitLabel={t("projects.quickAction.note.submit")}
submitting={props.submitting}
submitDisabled={draft.inhalt.trim().length === 0}
onSubmit={() => props.onSubmit("createNote", { inhalt: draft.inhalt, sichtbarkeit: draft.sichtbarkeit })}
uiId="ui.projects.quickAction.note"
>
{/* No visible label: the dialog title already says what is being written,
and the export leaves the field bare with only its placeholder. */}
<TextArea label={t("projects.quickAction.note.field.body")} className="w-full max-w-none">
<TextArea.Input
placeholder={t("projects.quickAction.note.placeholder")}
value={draft.inhalt}
onChange={(event) => setDraft((current) => ({ ...current, inhalt: event.target.value }))}
data-ui-id="ui.projects.quickAction.note.body"
/>
</TextArea>
<Select
variant="outline"
// `max-w-none`: the kit caps a Select at 320px, which would leave it
// narrower than every other field in the 448px dialog.
className="w-full max-w-none"
showLabel
label={t("projects.quickAction.note.field.visibility")}
value={draft.sichtbarkeit}
onValueChange={(value) => setDraft((current) => ({ ...current, sichtbarkeit: value as (typeof NOTE_VISIBILITIES)[number] }))}
>
{visibilities.map((value) => (
<Select.Item key={value} value={value}>
{t(`projects.quickAction.note.visibility.${value}`)}
</Select.Item>
))}
</Select>
</QuickActionDialog>
);
}
// --- S02-A Aufgabe erstellen -----------------------------------------------
const TASK_PRIORITIES = ["niedrig", "normal", "hoch"] as const;
export type CreateTaskDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
submitting: boolean;
assigneeOptions: readonly ProjectAssigneeOption[];
onSubmit: ProjectQuickActionSubmit;
};
export function CreateTaskDialog(props: CreateTaskDialogProps) {
const { t } = useTranslation();
const [draft, setDraft] = useResetOnOpen(props.open, () => ({
title: "",
deadline: "",
assignedToUserId: "",
priority: "normal" as (typeof TASK_PRIORITIES)[number],
description: "",
}));
return (
<QuickActionDialog
open={props.open}
onOpenChange={props.onOpenChange}
icon={<FeatherCheckSquare />}
// All three "erstellen" dialogs carry the same warm icon tile in the
// export; only the upload dialog is neutral.
iconVariant="warning"
title={t("projects.quickAction.task.title")}
subtitle={t("projects.quickAction.task.subtitle")}
submitLabel={t("projects.quickAction.task.submit")}
submitting={props.submitting}
submitDisabled={draft.title.trim().length === 0}
onSubmit={() =>
props.onSubmit("createTask", {
title: draft.title,
deadline: draft.deadline,
assignedToUserId: draft.assignedToUserId,
priority: draft.priority,
description: draft.description,
})
}
uiId="ui.projects.quickAction.task"
>
<TextInput label={t("projects.quickAction.task.field.title")} showLabel fillContainer className="w-full">
<TextInput.Input
placeholder={t("projects.quickAction.task.placeholder")}
value={draft.title}
onChange={(event) => setDraft((current) => ({ ...current, title: event.target.value }))}
data-ui-id="ui.projects.quickAction.task.title"
/>
</TextInput>
{/* One field per row, in the export's order. The two-column pairing of
date and priority was ours; David stacks them. */}
<TextInput label={t("projects.quickAction.task.field.deadline")} showLabel fillContainer className="w-full">
<TextInput.Input
type={DATE_INPUT_TYPE}
value={draft.deadline}
onChange={(event) => setDraft((current) => ({ ...current, deadline: event.target.value }))}
data-ui-id="ui.projects.quickAction.task.deadline"
/>
</TextInput>
{props.assigneeOptions.length > 0 ? (
<Select
variant="outline"
className="w-full max-w-none"
showLabel
label={t("projects.quickAction.task.field.assignee")}
value={draft.assignedToUserId || "__none__"}
onValueChange={(value) => setDraft((current) => ({ ...current, assignedToUserId: value === "__none__" ? "" : value }))}
>
<Select.Item value="__none__">{t("projects.fields.none")}</Select.Item>
{props.assigneeOptions.map((option) => (
<Select.Item key={option.id} value={option.id}>
{option.label}
</Select.Item>
))}
</Select>
) : null}
<Select
variant="outline"
className="w-full max-w-none"
showLabel
label={t("projects.quickAction.task.field.priority")}
value={draft.priority}
onValueChange={(value) => setDraft((current) => ({ ...current, priority: value as (typeof TASK_PRIORITIES)[number] }))}
>
{TASK_PRIORITIES.map((value) => (
<Select.Item key={value} value={value}>
{t(`projects.priority.${value}`)}
</Select.Item>
))}
</Select>
{/* Bare like the export — the placeholder carries the meaning. */}
<TextArea label={t("projects.quickAction.task.field.description")} className="w-full max-w-none">
<TextArea.Input
placeholder={t("projects.quickAction.task.descriptionPlaceholder")}
value={draft.description}
onChange={(event) => setDraft((current) => ({ ...current, description: event.target.value }))}
data-ui-id="ui.projects.quickAction.task.description"
/>
</TextArea>
</QuickActionDialog>
);
}
// --- S02-T Termin erstellen ------------------------------------------------
const APPOINTMENT_TYPES = ["vor_ort", "telefon", "online"] as const;
export type CreateAppointmentDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
submitting: boolean;
assigneeOptions: readonly ProjectAssigneeOption[];
onSubmit: ProjectQuickActionSubmit;
};
export function CreateAppointmentDialog(props: CreateAppointmentDialogProps) {
const { t } = useTranslation();
const [draft, setDraft] = useResetOnOpen(props.open, () => ({
titel: "",
datum: "",
von: "",
bis: "",
typ: "vor_ort" as (typeof APPOINTMENT_TYPES)[number],
assignedToUserId: "",
notiz: "",
}));
const complete = draft.titel.trim().length > 0 && draft.datum.length > 0 && draft.von.length > 0;
return (
<QuickActionDialog
open={props.open}
onOpenChange={props.onOpenChange}
icon={<FeatherCalendarPlus />}
iconVariant="warning"
title={t("projects.quickAction.appointment.title")}
subtitle={t("projects.quickAction.appointment.subtitle")}
submitLabel={t("projects.quickAction.appointment.submit")}
submitting={props.submitting}
submitDisabled={!complete}
onSubmit={() =>
props.onSubmit("createAppointment", {
titel: draft.titel,
// The route joins date + time into the ISO instants the service wants.
startAt: `${draft.datum}T${draft.von}`,
endAt: draft.bis ? `${draft.datum}T${draft.bis}` : "",
typ: draft.typ,
assignedToUserId: draft.assignedToUserId,
beschreibung: draft.notiz,
})
}
uiId="ui.projects.quickAction.appointment"
>
<TextInput label={t("projects.quickAction.appointment.field.title")} showLabel fillContainer className="w-full">
<TextInput.Input
placeholder={t("projects.quickAction.appointment.titlePlaceholder")}
value={draft.titel}
onChange={(event) => setDraft((current) => ({ ...current, titel: event.target.value }))}
data-ui-id="ui.projects.quickAction.appointment.title"
/>
</TextInput>
<TextInput label={t("projects.quickAction.appointment.field.date")} showLabel fillContainer className="w-full">
<TextInput.Input
type={DATE_INPUT_TYPE}
value={draft.datum}
onChange={(event) => setDraft((current) => ({ ...current, datum: event.target.value }))}
data-ui-id="ui.projects.quickAction.appointment.date"
/>
</TextInput>
{/* Grid, not a flex row: the ~/ui TextInput root carries `h-full w-full`,
so as a flex child it claims the whole line. In a grid track it fills
the track, which is what the export's two halves need. */}
<div className="grid w-full grid-cols-2 items-end gap-3">
<TextInput label={t("projects.quickAction.appointment.field.from")} showLabel fillContainer className="w-full">
<TextInput.Input
type={TIME_INPUT_TYPE}
value={draft.von}
onChange={(event) => setDraft((current) => ({ ...current, von: event.target.value }))}
data-ui-id="ui.projects.quickAction.appointment.from"
/>
</TextInput>
<TextInput label={t("projects.quickAction.appointment.field.to")} showLabel fillContainer className="w-full">
<TextInput.Input
type={TIME_INPUT_TYPE}
value={draft.bis}
onChange={(event) => setDraft((current) => ({ ...current, bis: event.target.value }))}
data-ui-id="ui.projects.quickAction.appointment.to"
/>
</TextInput>
</div>
<Select
variant="outline"
className="w-full max-w-none"
showLabel
label={t("projects.quickAction.appointment.field.type")}
value={draft.typ}
onValueChange={(value) => setDraft((current) => ({ ...current, typ: value as (typeof APPOINTMENT_TYPES)[number] }))}
data-ui-id="ui.projects.quickAction.appointment.type"
>
{APPOINTMENT_TYPES.map((value) => (
<Select.Item key={value} value={value}>
{t(`projects.quickAction.appointment.type.${value}`)}
</Select.Item>
))}
</Select>
{props.assigneeOptions.length > 0 ? (
<Select
variant="outline"
className="w-full max-w-none"
showLabel
label={t("projects.quickAction.appointment.field.assignee")}
value={draft.assignedToUserId || "__none__"}
onValueChange={(value) => setDraft((current) => ({ ...current, assignedToUserId: value === "__none__" ? "" : value }))}
>
<Select.Item value="__none__">{t("projects.fields.none")}</Select.Item>
{props.assigneeOptions.map((option) => (
<Select.Item key={option.id} value={option.id}>
{option.label}
</Select.Item>
))}
</Select>
) : null}
{/* Davids "Eingeladene Personen" chip field is NOT built: ProjektTermin
holds one assignee (user or group) and there is no invitee model, so
the chips would be a control that stores nothing. Flagged as a delta
rather than faked. */}
<TextArea label={t("projects.quickAction.appointment.field.note")} showLabel className="w-full max-w-none">
<TextArea.Input
placeholder={t("projects.quickAction.appointment.notePlaceholder")}
value={draft.notiz}
onChange={(event) => setDraft((current) => ({ ...current, notiz: event.target.value }))}
data-ui-id="ui.projects.quickAction.appointment.note"
/>
</TextArea>
</QuickActionDialog>
);
}
// --- S02-F Datei hochladen -------------------------------------------------
const FILE_CATEGORIES = ["angebot", "rechnung", "auftragsdokument", "foto", "sonstiges"] as const;
export type UploadFileDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
submitting: boolean;
/** Chunked upload injected by the route; resolves once the File row exists. */
uploadFile: (file: File) => Promise<{ id: string; displayName: string }>;
onSubmit: ProjectQuickActionSubmit;
};
export function UploadFileDialog(props: UploadFileDialogProps) {
const { t } = useTranslation();
const [draft, setDraft] = useResetOnOpen(props.open, () => ({
kategorie: "sonstiges" as (typeof FILE_CATEGORIES)[number],
beschreibung: "",
}));
const [file, setFile] = useState<File | null>(null);
const [uploading, setUploading] = useState(false);
const [uploadErrorKey, setUploadErrorKey] = useState<string | null>(null);
const [dragging, setDragging] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (props.open) {
setFile(null);
setUploadErrorKey(null);
}
}, [props.open]);
async function submit() {
if (!file) return;
setUploading(true);
setUploadErrorKey(null);
try {
// Upload first, then link: the route only needs the resulting file id, and
// a failed upload must not create a dangling project link.
const uploaded = await props.uploadFile(file);
props.onSubmit("attachFile", { fileId: uploaded.id, kategorie: draft.kategorie, beschreibung: draft.beschreibung });
} catch (error) {
// The upload client carries the server's own key ("type not allowed",
// "too large"), which says more than a blanket "did not work".
const key = (error as { errorKey?: unknown }).errorKey;
setUploadErrorKey(typeof key === "string" ? key : "projects.quickAction.file.uploadFailed");
} finally {
setUploading(false);
}
}
return (
<QuickActionDialog
open={props.open}
onOpenChange={props.onOpenChange}
icon={<FeatherUpload />}
iconVariant="neutral"
title={t("projects.quickAction.file.title")}
subtitle={t("projects.quickAction.file.subtitle")}
submitLabel={t("projects.quickAction.file.submit")}
submitIcon={<FeatherUpload />}
submitting={props.submitting || uploading}
submitDisabled={!file}
onSubmit={() => void submit()}
uiId="ui.projects.quickAction.file"
>
{/* One dashed zone like the export: icon, line, browse button. The picker
stays a real (hidden) file input because that is the only element a
browser lets open the file dialog. The zone itself takes the drop. */}
<div className="flex w-full flex-col items-start gap-2">
<input
ref={fileInputRef}
type="file"
onChange={(event) => setFile(event.target.files?.[0] ?? null)}
aria-label={t("projects.quickAction.file.field.file")}
data-ui-id="ui.projects.quickAction.file.input"
className="sr-only"
/>
<div
onDragOver={(event) => {
event.preventDefault();
setDragging(true);
}}
onDragLeave={() => setDragging(false)}
onDrop={(event) => {
event.preventDefault();
setDragging(false);
const dropped = event.dataTransfer.files?.[0];
if (dropped) setFile(dropped);
}}
className={`flex w-full flex-col items-center justify-center gap-5 rounded-lg border border-dashed px-6 py-8 ${
dragging ? "border-border-information-solid bg-surface-feedback-subtle-information" : "border-border-strong bg-surface-neutral-primary"
}`}
data-ui-id="ui.projects.quickAction.file.dropzone"
>
<FeatherUpload className="text-subtitle font-subtitle text-icon-neutral-secondary" />
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">
{t("projects.quickAction.file.dropzone")}
</span>
<Button variant="tertiary" onClick={() => fileInputRef.current?.click()} data-ui-id="ui.projects.quickAction.file.select">
{t("projects.quickAction.file.browse")}
</Button>
</div>
{file ? (
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-primary" data-ui-id="ui.projects.quickAction.file.selected">
{file.name}
</span>
) : null}
{uploadErrorKey ? (
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative" data-ui-id="ui.projects.quickAction.file.error">
{t(uploadErrorKey)}
</span>
) : null}
</div>
<Select
variant="outline"
className="w-full max-w-none"
showLabel
label={t("projects.quickAction.file.field.category")}
value={draft.kategorie}
onValueChange={(value) => setDraft((current) => ({ ...current, kategorie: value as (typeof FILE_CATEGORIES)[number] }))}
>
{FILE_CATEGORIES.map((value) => (
<Select.Item key={value} value={value}>
{t(`projects.quickAction.file.category.${value}`)}
</Select.Item>
))}
</Select>
<TextArea label={t("projects.quickAction.file.field.description")} showLabel className="w-full max-w-none">
<TextArea.Input
placeholder={t("projects.quickAction.file.descriptionPlaceholder")}
value={draft.beschreibung}
onChange={(event) => setDraft((current) => ({ ...current, beschreibung: event.target.value }))}
/>
</TextArea>
</QuickActionDialog>
);
}
@@ -0,0 +1,60 @@
import { createProjektOperationsInterimFixtureViewModels } from "@hivegrid/ui-mock";
import type { ProjectSignaturePanelVM } from "@hivegrid/view-models";
import { AcceptanceListPage } from "./AcceptanceListPage";
import { PlantafelPage } from "./PlantafelPage";
import { ProjectSubAreasPanel } from "./ProjectSubAreasPanel";
export const P9_OPERATIONS_INTERIM_VISUAL_SCREENS = ["plantafel", "acceptance-list", "sub-areas"] as const;
export type P9OperationsInterimVisualScreen = (typeof P9_OPERATIONS_INTERIM_VISUAL_SCREENS)[number];
const noOp = (): void => undefined;
const emptySignature: ProjectSignaturePanelVM = { status: "empty" };
/** Shared AD-28 fixture for the R-P9 interim markup snapshots (interim baseline, re-baseline on the D-PLAN/D-ABN nachzug). */
export function P9OperationsInterimVisualFixture({ screen }: { readonly screen: P9OperationsInterimVisualScreen }): React.JSX.Element {
const vms = createProjektOperationsInterimFixtureViewModels();
switch (screen) {
case "plantafel":
return (
<PlantafelPage
vm={vms.plantafel}
projectLabels={[{ id: "project-1", label: "P-2026-0001 · Heizungstausch Auenland" }]}
editableProjectIds={["project-1"]}
projectOptions={[{ id: "project-1", label: "P-2026-0001 · Heizungstausch Auenland" }]}
projectOptionsHasMore={false}
projectPickerLoading={false}
assigneeOptions={[{ id: "user-monteur", label: "Anna Schneider" }]}
canWrite
canBulkReassign
filter={{ assignedUserId: null, includePast: false, sort: "start_asc" }}
view="table"
anchorIso="2026-07-20"
todayIso="2026-07-20"
submitting={false}
actions={{ onSubmit: noOp, onProjectSearch: noOp, onFilterChange: noOp, onViewChange: noOp, onAnchorChange: noOp }}
/>
);
case "acceptance-list":
return (
<AcceptanceListPage
vm={vms.acceptanceList}
createHref="/:tenant/projects/project-1/acceptance/new"
submitting={false}
actions={{ onSubmit: noOp }}
/>
);
case "sub-areas":
return (
<ProjectSubAreasPanel
vm={vms.subAreas}
signature={emptySignature}
submitting={false}
userOptions={[{ id: "user-monteur", label: "Anna Schneider" }]}
actions={{ onSubmit: noOp, onOpenChat: noOp }}
/>
);
}
}
@@ -0,0 +1,33 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import React from "react";
import { render } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { P9_OPERATIONS_INTERIM_VISUAL_SCREENS, P9OperationsInterimVisualFixture } from "./p9-operations-interim.visual-fixture";
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, values?: Record<string, unknown>) => (values ? `${key}:${Object.values(values).join("/")}` : key),
i18n: { language: "de" },
}),
}));
describe("R-P9 operations interim visual baseline", () => {
it("renders the plantafel, acceptance list, and sub-areas surfaces from ~/ui", () => {
render(
<main data-ui-id="ui.projects.operations.interim.visualBaseline">
{P9_OPERATIONS_INTERIM_VISUAL_SCREENS.map((screen) => (
<P9OperationsInterimVisualFixture key={screen} screen={screen} />
))}
</main>,
);
expect(document.querySelectorAll("[data-ui-id='ui.projects.plantafel']")).toHaveLength(1);
expect(document.querySelectorAll("[data-ui-id='ui.projects.acceptance.list']")).toHaveLength(1);
expect(document.querySelectorAll("[data-ui-id='ui.projects.operations']")).toHaveLength(1);
const stableMarkup = document.body.innerHTML.replace(/<svg\b[^>]*>[\s\S]*?<\/svg>/gu, '<svg data-visual-icon="true"></svg>');
expect(stableMarkup).toMatchSnapshot();
});
});
@@ -0,0 +1,28 @@
// WF-P8 project tags — mapping `Tag.farbe` onto a kit tone.
import { describe, expect, it } from "vitest";
import { tagTone } from "./tagTone";
describe("tagTone", () => {
it("keeps a stored tone name", () => {
expect(tagTone("yellow-subtle")).toBe("yellow-subtle");
expect(tagTone("sky-subtle")).toBe("sky-subtle");
});
it("accepts a bare palette name and adds the subtle variant", () => {
expect(tagTone("orange")).toBe("orange-subtle");
expect(tagTone("BLUE")).toBe("blue-subtle");
});
it("falls back to neutral for a hex colour, because the kit tone is an enum", () => {
// The column also allows "#RRGGBB"; there is no tone to map that onto, and a
// wrong-but-colourful tone would be worse than an honest neutral chip.
expect(tagTone("#ff8800")).toBe("neutral-subtle");
});
it("falls back to neutral for an unset or unknown value", () => {
expect(tagTone(null)).toBe("neutral-subtle");
expect(tagTone("")).toBe("neutral-subtle");
expect(tagTone("chartreuse")).toBe("neutral-subtle");
});
});
@@ -0,0 +1,42 @@
// WF-P8 project tags — `Tag.farbe` mapped onto a kit Tag_Label tone.
//
// The column stores "a hex code (#RRGGBB) or palette name", but the kit tone is
// an enum of named tones, not a colour value: an arbitrary hex has no tone to
// land on. So a stored palette name is used as-is, a hex falls back to the
// neutral tone, and the tag still reads as a tag instead of losing its chip.
//
// Board card, list row and filter bar all import this, so one tag cannot show up
// yellow on the board and grey in the list.
export type TagTone =
| "neutral-subtle"
| "blue-subtle"
| "sky-subtle"
| "violet-subtle"
| "green-subtle"
| "yellow-subtle"
| "orange-subtle"
| "red-subtle"
| "sand-subtle";
const KNOWN_TONES: ReadonlySet<string> = new Set<TagTone>([
"neutral-subtle",
"blue-subtle",
"sky-subtle",
"violet-subtle",
"green-subtle",
"yellow-subtle",
"orange-subtle",
"red-subtle",
"sand-subtle",
]);
/** Bare palette names ("yellow") are accepted too and get the subtle variant. */
export function tagTone(farbe: string | null | undefined): TagTone {
const value = farbe?.trim().toLowerCase();
if (!value) return "neutral-subtle";
if (KNOWN_TONES.has(value)) return value as TagTone;
const withSuffix = `${value}-subtle`;
if (KNOWN_TONES.has(withSuffix)) return withSuffix as TagTone;
return "neutral-subtle";
}