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,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>
);
}