Files
alpenwerk-hr/components/reports/ReportsPageClient.tsx
Andrei Laas 676cecbf15
Some checks failed
CI / Migrationen auf leerer Datenbank (push) Has been cancelled
CI / Lint, Typen, Tests, Build (push) Has been cancelled
Export fuer LOLYO, und die Zielsystem-Exporte in einem eigenen Abschnitt
LOLYO ist die dritte Datei, die in ein fremdes System geladen wird. Spalten,
Trennzeichen und Schreibweise kommen aus der Vorlage des Anbieters, Zeichen fuer
Zeichen -- einschliesslich der gemischten Kopfzeile ("Titel prefix" deutsch,
"Title Suffix" englisch). Semikolon und kein BOM: das BOM haenge unsichtbar am
Namen der ersten Spalte, und "Benutzer/Code" kaeme in keiner Zuordnung mehr vor.

Der Benutzercode ist die Alpenwerk-UUID. Anders als bei Cornerstone ist das
hier richtig: LOLYO kennt die Person noch nicht und vergibt keine eigene
Kennung, die wir treffen muessten.

Diese Datei legt Konten an, samt Passwort in der Zeile. Das Startpasswort steht
deshalb in der Route und nicht in lib/lolyo.ts: eine Route ist serverseitig, eine
lib-Datei waere nur so lange sicher, wie niemand sie aus einem Client-Bauteil
heraus einbindet -- und das saehe man dem Buendel nicht an. Dieselbe Ueberlegung
steht in lib/passwort.ts.

Die drei Zielsystem-Exporte stehen jetzt unter einer gemeinsamen Ueberschrift,
getrennt vom Datenexport darueber. Der gibt Zahlen heraus, die jemand ansieht;
diese legen im Zielsystem Datensaetze an. Nebeneinander in einer Reihe
gleichartiger Karten war das nicht zu sehen. Die Auswahl steht damit einmal
statt dreimal da.

Der erklaerende Text unter dem Cornerstone-Export entfaellt auf Wunsch des
Kunden.
2026-09-28 13:45:38 +02:00

892 lines
38 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { ChevronDown, FileSpreadsheet, FileText, Save, Trash2 } from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useState } from "react";
import { deleteReport, saveReport } from "@/actions/reports";
import { Button, LINK_BUTTON_CLASS } from "@/components/ui/Button";
import { CONTROL_CLASS, SelectField, TextField } from "@/components/ui/Field";
import { Modal } from "@/components/ui/Modal";
import { useToast } from "@/components/ui/Toast";
import { fmtDate } from "@/lib/format";
import {
anzahlKriterien,
AUSWAHL_KRITERIEN,
beschreibeKriterien,
JANEIN_KRITERIEN,
kriterienParameter,
ZEITRAUM_KRITERIEN,
type Criteria,
} from "@/lib/report-criteria";
import {
AVERAGE_MEASURES,
EVENT_DATE_OPEN,
EVENT_GROUP_LABELS,
EREIGNIS_AUSWAHL,
EREIGNIS_UNTERTYP,
EVENT_REPORT_PRESETS,
EVENT_TYPE_LABELS,
GROUP_LABELS,
MEASURE_LABELS,
parseStatuses,
REPORT_PRESETS,
sortKeysForDimension,
STATUS_OPTIONS,
todayIso,
untertypOptionen,
type EventGroupDimension,
type GroupDimension,
type Measure,
type ReportRow,
type UnitOption,
} from "@/lib/reports";
import type { HistoryEventType } from "@/lib/types";
const SPLIT_COLORS = ["bg-brand-500", "bg-info-text", "bg-purple-text", "bg-warning-text", "bg-success-text", "bg-danger-solid"];
const EVENT_TYPES = EREIGNIS_AUSWAHL;
/** Wie viele Namen eine aufgeklappte Zeile zeigt, bevor der Rest auf Klick kommt. */
const VORSCHAU_NAMEN = 12;
/**
* Die Exporte, die in ein anderes System geladen werden.
*
* Sie stehen zusammen und getrennt vom Datenexport darüber, weil sie etwas
* anderes sind: der Datenexport gibt Zahlen heraus, die jemand ansieht, diese
* hier legen im Zielsystem Datensätze an. Nebeneinander in einer Reihe
* gleichartiger Karten war das nicht zu sehen — und eine versehentlich
* eingeschränkte Auswahl wirkt sich hier ganz anders aus.
*/
const ZIELSYSTEME: readonly { name: string; pfad: string }[] = [
{ name: "Honestly — Mitarbeiterbefragung", pfad: "/api/export/honestly" },
{ name: "Cornerstone — Lernsystem", pfad: "/api/export/cornerstone" },
{ name: "LOLYO — Mitarbeiter-App", pfad: "/api/export/lolyo" },
];
type SavedReport = { id: string; name: string; config: Record<string, unknown> };
type OrgOption = { id: string; name: string };
type CommonProps = {
rows: ReportRow[];
total: number;
recordCount: number;
units: UnitOption[];
locations: OrgOption[];
savedReports: SavedReport[];
};
type SnapshotProps = CommonProps & {
mode: "snapshot";
measure: Measure;
group: GroupDimension;
split: GroupDimension | "";
asOf: string;
filters: { division: string; location: string; status: string };
criteria: Criteria;
};
type EventsProps = CommonProps & {
mode: "events";
eventGroup: EventGroupDimension;
eventSplit: EventGroupDimension | "";
eventType: string;
/** Beendigungsart bzw. Art der Langzeitabwesenheit; leer heisst „alle". */
eventSubtype: string;
eventFilters: { division: string; location: string; from: string; to: string };
};
type ReportsPageClientProps = SnapshotProps | EventsProps;
/**
* Alle übrigen Auswahlkriterien, eingeklappt.
*
* Aufgeklappt wäre die Leiste dreimal so lang wie der Bericht daneben, und
* die vier Filter, die fast immer gemeint sind, würden darin untergehen.
* Eingeklappt steht nur die Zahl der gesetzten Kriterien da — und die ist
* das, was man wissen muss: ob gerade etwas einschränkt, das man vergessen
* hat.
*/
function KriterienBlock({
criteria,
onChange,
onReset,
}: {
criteria: Criteria;
onChange: (patch: Record<string, string | undefined>) => void;
onReset: () => void;
}) {
const [offen, setOffen] = useState(false);
const anzahl = anzahlKriterien(criteria);
return (
<div className="mt-2 border-t border-border-subtle pt-2">
<div className="flex items-center justify-between">
<button
type="button"
onClick={() => setOffen(!offen)}
aria-expanded={offen}
className="flex items-center gap-1 rounded text-xs font-semibold text-brand-700 hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand-500"
>
<ChevronDown className={`h-3.5 w-3.5 transition-transform ${offen ? "rotate-180" : ""}`} />
Weitere Kriterien
{anzahl > 0 && <span className="rounded-full bg-brand-500 px-1.5 text-[10px] text-white">{anzahl}</span>}
</button>
{anzahl > 0 && (
<button
type="button"
onClick={onReset}
className="rounded text-xs text-ink-muted hover:text-ink hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand-500"
>
Zurücksetzen
</button>
)}
</div>
{offen && (
<div className="mt-3 flex flex-col gap-2">
{AUSWAHL_KRITERIEN.map((k) => (
<select
key={k.key}
aria-label={`Nach ${k.label} filtern`}
value={criteria.auswahl[k.key] ?? ""}
onChange={(e) => onChange({ [k.key]: e.target.value || undefined })}
className={CONTROL_CLASS}
>
<option value="">{k.alle}</option>
{k.optionen.map((o) => (
<option key={o.wert} value={o.wert}>
{o.label}
</option>
))}
</select>
))}
<fieldset className="rounded border border-border px-3 py-2">
<legend className="mb-1.5 text-xs font-semibold text-ink-muted">Merkmale</legend>
<div className="flex flex-col gap-1.5">
{JANEIN_KRITERIEN.map((k) => (
<div key={k.key} className="flex items-center justify-between gap-2 text-sm text-ink-body">
<span>{k.label}</span>
<select
aria-label={`${k.label}: ja oder nein`}
value={criteria.jaNein[k.key] ?? ""}
onChange={(e) => onChange({ [k.key]: e.target.value || undefined })}
className="rounded border border-border px-2 py-1 text-xs focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-brand-500"
>
<option value="">egal</option>
<option value="ja">ja</option>
<option value="nein">nein</option>
</select>
</div>
))}
</div>
</fieldset>
{ZEITRAUM_KRITERIEN.map((k) => (
<fieldset key={k.key} className="rounded border border-border px-3 py-2">
<legend className="mb-1 text-xs font-semibold text-ink-muted">{k.label}</legend>
<div className="grid grid-cols-2 gap-2">
<TextField
label="Von"
dense
type="date"
value={criteria.zeitraum[k.key]?.von ?? ""}
onChange={(v) => onChange({ [`${k.key}From`]: v || undefined })}
/>
<TextField
label="Bis"
dense
type="date"
value={criteria.zeitraum[k.key]?.bis ?? ""}
onChange={(v) => onChange({ [`${k.key}To`]: v || undefined })}
/>
</div>
</fieldset>
))}
<fieldset className="rounded border border-border px-3 py-2">
<legend className="mb-1 text-xs font-semibold text-ink-muted">Wochenstunden</legend>
<div className="grid grid-cols-2 gap-2">
<TextField
label="Ab"
dense
type="number"
step="0.5"
value={criteria.stundenVon?.toString() ?? ""}
onChange={(v) => onChange({ hoursFrom: v || undefined })}
/>
<TextField
label="Bis"
dense
type="number"
step="0.5"
value={criteria.stundenBis?.toString() ?? ""}
onChange={(v) => onChange({ hoursTo: v || undefined })}
/>
</div>
</fieldset>
<p className="text-xs text-ink-muted">
Alle Kriterien gelten für den Bericht <em>und</em> für jeden Export dieser Seite — auch für den
Honestly- und den Cornerstone-Report. Was gerade eingestellt ist, steht auf der jeweiligen Karte.
</p>
</div>
)}
</div>
);
}
/**
* Was gerade in die Datei geht — Stichtag, Status, Einheit, Standort und jedes
* gesetzte Kriterium, dazu die Zeilenzahl.
*
* Auf den Karten stand nur der Status. Alles andere schränkt den Export
* genauso ein, steht aber eingeklappt weiter oben: eine Datei mit 40 statt 785
* Personen sah genauso aus wie eine vollständige. Für einen Bericht ist das
* ärgerlich, für ein Load-File ins Zielsystem ist es ein Datenstand, den dort
* niemand mehr hinterfragt.
*/
function AuswahlHinweis({ texte, anzahl }: { texte: string[]; anzahl: number }) {
return (
<div className="mb-2 rounded bg-surface px-2 py-1.5 text-xs text-ink-body">
<span className="font-semibold">Auswahl:</span> {texte.join(" · ")}
<span className="mt-0.5 block font-semibold">
{anzahl} {anzahl === 1 ? "Person" : "Personen"}
</span>
</div>
);
}
function formatValue(measure: Measure, value: number): string {
if (measure === "headcount") return String(Math.round(value));
if (measure === "fte") return value.toFixed(1);
if (measure === "parttime_rate" || measure === "female_share") return `${value.toFixed(1)}%`;
if (measure === "avg_age" || measure === "avg_tenure") return `${value.toFixed(1)} Jahre`;
return value.toFixed(1);
}
export function ReportsPageClient(props: ReportsPageClientProps) {
const { mode, rows, total, recordCount, units, locations, savedReports } = props;
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const { showToast } = useToast();
const [expandedKey, setExpandedKey] = useState<string | null>(null);
// Welche aufgeklappte Zeile ihre Namen **vollständig** zeigt. Vorher stand
// dort „+794 weitere" als blosser Text: die Auskunft, dass es mehr gibt,
// ohne einen Weg dorthin. Wer die Liste brauchte, musste sie exportieren.
const [volleListeKey, setVolleListeKey] = useState<string | null>(null);
const [saveModalOpen, setSaveModalOpen] = useState(false);
const [newReportName, setNewReportName] = useState("");
const [savingReport, setSavingReport] = useState(false);
function updateParams(patch: Record<string, string | undefined>) {
const sp = new URLSearchParams(searchParams.toString());
for (const [k, v] of Object.entries(patch)) {
if (v) sp.set(k, v);
else sp.delete(k);
}
router.push(`${pathname}?${sp.toString()}`, { scroll: false });
}
function switchMode(next: "snapshot" | "events") {
router.push(`${pathname}?mode=${next}`, { scroll: false });
}
function toggleStatus(status: string) {
if (mode !== "snapshot") return;
const current = parseStatuses(props.filters.status);
const next = current.includes(status as (typeof current)[number]) ? current.filter((s) => s !== status) : [...current, status];
updateParams({ status: next.length > 0 ? next.join(",") : undefined });
}
function resetKriterien() {
const patch: Record<string, undefined> = {};
for (const p of kriterienParameter()) patch[p] = undefined;
updateParams(patch);
}
function applyPreset(preset: { group: string; split?: string; eventType?: string; measure?: string }) {
const sp = new URLSearchParams({ mode });
if (preset.measure) sp.set("measure", preset.measure);
sp.set("group", preset.group);
if (preset.split) sp.set("split", preset.split);
if (preset.eventType) sp.set("eventType", preset.eventType);
router.push(`${pathname}?${sp.toString()}`, { scroll: false });
}
function applySavedReport(config: Record<string, unknown>) {
const sp = new URLSearchParams();
for (const [k, v] of Object.entries(config)) {
if (typeof v === "string" && v) sp.set(k, v);
}
if (!sp.get("mode")) sp.set("mode", "snapshot");
router.push(`${pathname}?${sp.toString()}`, { scroll: false });
}
async function handleConfirmSaveReport() {
if (!newReportName.trim()) {
showToast("Bitte einen Namen angeben.", "error");
return;
}
// Auch hier die ganze Adresszeile: ein gespeicherter Bericht, der die
// Hälfte der Kriterien vergisst, führt beim nächsten Öffnen still zu
// anderen Zahlen.
const config: Record<string, string> = Object.fromEntries(searchParams.entries());
config.mode = mode;
config.group = mode === "snapshot" ? props.group : props.eventGroup;
if (mode === "snapshot") config.measure = props.measure;
setSavingReport(true);
const result = await saveReport({ name: newReportName.trim(), config });
setSavingReport(false);
if (result.success) {
showToast("Bericht gespeichert.");
setSaveModalOpen(false);
setNewReportName("");
router.refresh();
} else {
showToast(result.error ?? "Fehler beim Speichern.", "error");
}
}
async function handleDeleteReport(id: string) {
const result = await deleteReport(id);
if (result.success) {
showToast("Bericht gelöscht.");
router.refresh();
} else {
showToast(result.error ?? "Fehler beim Löschen.", "error");
}
}
// Beide Ausgänge übernehmen die Adresszeile unverändert, statt die
// Parameter einzeln aufzuzählen. Genau diese Aufzählung war der Grund,
// warum ein neues Kriterium im Bericht wirkte und im Export fehlte — man
// musste daran denken, sie an drei Stellen zu ergänzen. Jetzt sieht der
// Export das, was der Bericht gesehen hat, weil es dieselbe Auswahl ist.
function exportHref(ziel: string, format: "csv" | "xlsx"): string {
const sp = new URLSearchParams(searchParams.toString());
sp.set("format", format);
return `${ziel}?${sp.toString()}`;
}
function reportExportHref(format: "csv" | "xlsx"): string {
const sp = new URLSearchParams(searchParams.toString());
sp.set("format", format);
sp.set("mode", mode);
// Die Vorgaben stehen nicht zwingend in der Adresszeile; die Route
// braucht sie aber, um dieselbe Auswertung zu bauen.
sp.set("group", mode === "snapshot" ? props.group : props.eventGroup);
if (mode === "snapshot") sp.set("measure", props.measure);
return `/api/export/report?${sp.toString()}`;
}
function fullExportHref(format: "csv" | "xlsx"): string {
return exportHref(mode === "snapshot" ? "/api/export/employees" : "/api/export/events", format);
}
const isAverage = mode === "snapshot" && AVERAGE_MEASURES.includes(props.measure);
const maxValue = Math.max(1, ...rows.map((r) => r.value));
const rawSplitKeys = Array.from(new Set(rows.flatMap((r) => r.split?.map((s) => s.key) ?? [])));
const splitKeys = mode === "snapshot" && props.split ? sortKeysForDimension(rawSplitKeys, props.split) : rawSplitKeys;
const showWeekdayMultiCountNote = mode === "snapshot" && (props.group === "weekday" || props.split === "weekday");
const selectedStatuses = mode === "snapshot" ? parseStatuses(props.filters.status) : [];
const statusExportLabel = selectedStatuses.length === STATUS_OPTIONS.length ? "Alle" : selectedStatuses.join(", ");
// Einheit und Standort stehen in der Adresszeile als Kennung; auf der Karte
// hilft nur der Name.
const einheitName = mode === "snapshot" ? units.find((u) => u.id === props.filters.division)?.name : undefined;
const standortName = mode === "snapshot" ? locations.find((l) => l.id === props.filters.location)?.name : undefined;
const auswahlTexte =
mode === "snapshot"
? [
`Stichtag ${fmtDate(props.asOf || todayIso())}`,
`Status ${statusExportLabel}`,
...(einheitName ? [`Einheit ${einheitName}`] : []),
...(standortName ? [`Standort ${standortName}`] : []),
...beschreibeKriterien(props.criteria),
]
: [];
const currentYear = new Date().getFullYear();
const defaultEventFrom = `${currentYear}-01-01`;
const defaultEventTo = `${currentYear}-12-31`;
const heading =
mode === "snapshot"
? `${MEASURE_LABELS[props.measure]} nach ${GROUP_LABELS[props.group]}`
: `${props.eventType ? EVENT_TYPE_LABELS[props.eventType as HistoryEventType] : "Ereignisse"} nach ${EVENT_GROUP_LABELS[props.eventGroup]}`;
const totalDisplay = mode === "snapshot" ? formatValue(props.measure, total) : String(Math.round(total));
return (
<div className="grid grid-cols-1 gap-4 lg:grid-cols-[320px_1fr]">
<div className="flex flex-col gap-4">
<div role="tablist" aria-label="Berichtsart" className="flex rounded border border-border bg-white p-1 text-sm font-semibold">
{(["snapshot", "events"] as const).map((m) => (
<button
key={m}
type="button"
role="tab"
aria-selected={mode === m}
onClick={() => switchMode(m)}
className={`flex-1 rounded px-3 py-1.5 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-brand-500 ${
mode === m ? "bg-brand-500 text-white" : "text-ink-body hover:bg-surface"
}`}
>
{m === "snapshot" ? "Bestand" : "Ereignisse"}
</button>
))}
</div>
{mode === "snapshot" ? (
<div className="rounded border border-border bg-white p-4">
<div className="flex flex-col gap-3">
<SelectField
label="Kennzahl"
dense
value={props.measure}
onChange={(v) => updateParams({ measure: v, split: AVERAGE_MEASURES.includes(v as Measure) ? undefined : props.split })}
options={(Object.keys(MEASURE_LABELS) as Measure[]).map((m) => ({ value: m, label: MEASURE_LABELS[m] }))}
/>
<SelectField
label="Gruppieren nach"
dense
value={props.group}
onChange={(v) => updateParams({ group: v })}
options={(Object.keys(GROUP_LABELS) as GroupDimension[]).map((g) => ({ value: g, label: GROUP_LABELS[g] }))}
/>
<SelectField
label="Aufteilen nach"
dense
value={props.split}
disabled={isAverage}
onChange={(v) => updateParams({ split: v || undefined })}
hint={isAverage ? "Bei Durchschnittswerten nicht verfügbar." : undefined}
options={[
{ value: "", label: "Keine Aufteilung" },
...(Object.keys(GROUP_LABELS) as GroupDimension[])
.filter((g) => g !== props.group)
.map((g) => ({ value: g, label: GROUP_LABELS[g] })),
]}
/>
<div>
<div className="flex items-end gap-2">
<TextField
label="Stichtag"
dense
className="flex-1"
type="date"
value={props.asOf || todayIso()}
onChange={(v) => updateParams({ asOf: v })}
/>
{props.asOf && (
<Button
variant="ghost"
size="sm"
onClick={() => updateParams({ asOf: undefined })}
className="!px-1 whitespace-nowrap text-brand-700 hover:!bg-transparent hover:underline"
>
Heute
</Button>
)}
</div>
<p className="mt-1 text-xs text-ink-muted">
Bestand wird rückgerechnet (Eintritt/Austritt/Langzeitabwesenheit); Bereich/Team zeigen die aktuelle
Zuordnung.
</p>
</div>
</div>
</div>
) : (
<div className="rounded border border-border bg-white p-4">
<div className="flex flex-col gap-3">
<SelectField
label="Ereignistyp"
dense
value={props.eventType}
// Der Untertyp gehört zum Ereignistyp und fällt mit ihm weg.
// Bliebe er in der Adresse stehen, filterte eine Auswahl
// weiter, die auf dem Bildschirm nicht mehr zu sehen ist.
onChange={(v) => updateParams({ eventType: v || undefined, eventSubtype: undefined })}
options={[
{ value: "", label: "Alle Ereignistypen" },
...EVENT_TYPES.map((t) => ({ value: t, label: EVENT_TYPE_LABELS[t] })),
]}
/>
{/* Nur dort, wo es einen gibt: eine Versetzung hat keine
Beendigungsart, und ein leeres zweites Feld wäre eine Frage
ohne Antwortmöglichkeit. */}
{(() => {
const typ = props.eventType ? (props.eventType as HistoryEventType) : null;
const untertyp = typ ? EREIGNIS_UNTERTYP[typ] : undefined;
if (!untertyp) return null;
return (
<SelectField
label={untertyp.label}
dense
value={props.eventSubtype}
onChange={(v) => updateParams({ eventSubtype: v || undefined })}
options={[
{ value: "", label: untertyp.alle },
...untertypOptionen(typ).map((o) => ({ value: o, label: o })),
]}
/>
);
})()}
<SelectField
label="Gruppieren nach"
dense
value={props.eventGroup}
onChange={(v) => updateParams({ group: v })}
options={(Object.keys(EVENT_GROUP_LABELS) as EventGroupDimension[]).map((g) => ({ value: g, label: EVENT_GROUP_LABELS[g] }))}
/>
<SelectField
label="Aufteilen nach"
dense
value={props.eventSplit}
onChange={(v) => updateParams({ split: v || undefined })}
options={[
{ value: "", label: "Keine Aufteilung" },
...(Object.keys(EVENT_GROUP_LABELS) as EventGroupDimension[])
.filter((g) => g !== props.eventGroup)
.map((g) => ({ value: g, label: EVENT_GROUP_LABELS[g] })),
]}
/>
<fieldset>
<legend className="mb-1 block text-xs font-semibold uppercase tracking-wide text-ink-muted">Zeitraum</legend>
<div className="grid grid-cols-2 gap-2">
<div>
<TextField
label="Von"
dense
type="date"
value={props.eventFilters.from === EVENT_DATE_OPEN ? "" : props.eventFilters.from || defaultEventFrom}
disabled={props.eventFilters.from === EVENT_DATE_OPEN}
onChange={(v) => updateParams({ from: v })}
/>
<Button
variant="ghost"
size="sm"
onClick={() => updateParams({ from: props.eventFilters.from === EVENT_DATE_OPEN ? defaultEventFrom : EVENT_DATE_OPEN })}
className="mt-1 !px-0 text-brand-700 hover:!bg-transparent hover:underline"
>
{props.eventFilters.from === EVENT_DATE_OPEN ? "Startdatum setzen" : "Ab Anfang (offen)"}
</Button>
</div>
<div>
<TextField
label="Bis"
dense
type="date"
value={props.eventFilters.to === EVENT_DATE_OPEN ? "" : props.eventFilters.to || defaultEventTo}
disabled={props.eventFilters.to === EVENT_DATE_OPEN}
onChange={(v) => updateParams({ to: v })}
/>
<Button
variant="ghost"
size="sm"
onClick={() => updateParams({ to: props.eventFilters.to === EVENT_DATE_OPEN ? defaultEventTo : EVENT_DATE_OPEN })}
className="mt-1 !px-0 text-brand-700 hover:!bg-transparent hover:underline"
>
{props.eventFilters.to === EVENT_DATE_OPEN ? "Enddatum setzen" : "Bis heute (offen)"}
</Button>
</div>
</div>
</fieldset>
</div>
</div>
)}
<div className="rounded border border-border bg-white p-4">
<h3 className="mb-2 text-xs font-semibold uppercase tracking-wide text-ink-muted">Filter</h3>
<div className="flex flex-col gap-2">
<select
aria-label="Nach Organisationseinheit filtern"
value={mode === "snapshot" ? props.filters.division : props.eventFilters.division}
onChange={(e) => updateParams({ division: e.target.value })}
className={CONTROL_CLASS}
>
<option value="">Alle Organisationseinheiten</option>
{units.map((u) => (
// Einrückung mit geschützten Leerzeichen: ein <optgroup> je
// Ebene ginge nicht, weil Einheiten dort auswählbar bleiben
// müssen — eine Abteilung ist selbst ein Filterwert.
<option key={u.id} value={u.id}>
{"  ".repeat(u.depth)}
{u.name}
</option>
))}
</select>
<select
aria-label="Nach Standort filtern"
value={mode === "snapshot" ? props.filters.location : props.eventFilters.location}
onChange={(e) => updateParams({ location: e.target.value })}
className={CONTROL_CLASS}
>
<option value="">Alle Standorte</option>
{locations.map((l) => (
<option key={l.id} value={l.id}>
{l.name}
</option>
))}
</select>
{mode === "snapshot" && (
<>
<fieldset className="rounded border border-border px-3 py-2">
<legend className="mb-1.5 text-xs font-semibold text-ink-muted">Status (zum Stichtag)</legend>
<div className="flex flex-wrap gap-x-4 gap-y-1.5">
{STATUS_OPTIONS.map((s) => (
<label key={s} className="flex items-center gap-1.5 text-sm text-ink-body">
<input
type="checkbox"
checked={selectedStatuses.includes(s)}
onChange={() => toggleStatus(s)}
className="h-4 w-4 rounded border-border accent-brand-500"
/>
{s}
</label>
))}
</div>
</fieldset>
</>
)}
</div>
{mode === "snapshot" && (
<KriterienBlock criteria={props.criteria} onChange={updateParams} onReset={resetKriterien} />
)}
</div>
<div className="rounded border border-border bg-white p-4">
<h3 className="mb-2 text-xs font-semibold uppercase tracking-wide text-ink-muted">Vorlagen</h3>
<div className="flex flex-wrap gap-1.5">
{(mode === "snapshot" ? REPORT_PRESETS : EVENT_REPORT_PRESETS).map((preset) => (
<Button key={preset.name} variant="secondary" size="sm" onClick={() => applyPreset(preset)} className="!rounded-full !px-2.5 !py-1">
{preset.name}
</Button>
))}
</div>
</div>
<div className="rounded border border-border bg-white p-4">
<h3 className="mb-1 text-xs font-semibold uppercase tracking-wide text-ink-muted">Vollständiger Datenexport</h3>
{mode === "snapshot" ? (
<>
<p className="mb-1 text-xs text-ink-muted">Alle Mitarbeiterdaten, nicht nur die Kennzahl.</p>
<AuswahlHinweis texte={auswahlTexte} anzahl={recordCount} />
</>
) : (
<p className="mb-2 text-xs text-ink-muted">Alle Ereignisse im gewählten Zeitraum als Rohdaten (eine Zeile pro Ereignis).</p>
)}
<div className="flex gap-2">
<a href={fullExportHref("csv")} className={LINK_BUTTON_CLASS}>
<FileText className="h-4 w-4" />
CSV
</a>
<a href={fullExportHref("xlsx")} className={LINK_BUTTON_CLASS}>
<FileSpreadsheet className="h-4 w-4" />
Excel
</a>
</div>
</div>
{/* Nur im Bestand: ein Zielsystem führt Personen, keine Ereignisse.
Dieselben Filter wie der vollständige Export darüber. */}
{mode === "snapshot" && (
<div className="rounded border border-border bg-white p-4">
<h3 className="mb-1 text-xs font-semibold uppercase tracking-wide text-ink-muted">Exporte für Zielsysteme</h3>
<p className="mb-1 text-xs text-ink-muted">
Load-Dateien für Fremdsysteme, jede in deren eigenem Format. Für alle gilt dieselbe Auswahl.
</p>
<AuswahlHinweis texte={auswahlTexte} anzahl={recordCount} />
<div className="flex flex-col divide-y divide-border-subtle">
{ZIELSYSTEME.map((z) => (
<div key={z.pfad} className="py-2 first:pt-0 last:pb-0">
<p className="mb-1.5 text-sm font-semibold text-ink">{z.name}</p>
<div className="flex gap-2">
<a href={exportHref(z.pfad, "csv")} className={LINK_BUTTON_CLASS}>
<FileText className="h-4 w-4" />
CSV
</a>
<a href={exportHref(z.pfad, "xlsx")} className={LINK_BUTTON_CLASS}>
<FileSpreadsheet className="h-4 w-4" />
Excel
</a>
</div>
</div>
))}
</div>
</div>
)}
{savedReports.length > 0 && (
<div className="rounded border border-border bg-white p-4">
<h3 className="mb-2 text-xs font-semibold uppercase tracking-wide text-ink-muted">Gespeicherte Berichte</h3>
<ul className="flex flex-col divide-y divide-border">
{savedReports.map((r) => (
<li key={r.id} className="flex items-center justify-between py-1.5 text-sm">
<Button
variant="ghost"
size="sm"
onClick={() => applySavedReport(r.config)}
className="!px-0 !justify-start text-left hover:!bg-transparent hover:text-brand-700 hover:underline"
>
{r.name}
</Button>
<Button
variant="icon"
onClick={() => handleDeleteReport(r.id)}
aria-label={`Bericht ${r.name} löschen`}
className="hover:!text-danger-solid"
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</li>
))}
</ul>
</div>
)}
</div>
<div className="rounded border border-border bg-white p-4">
<div className="mb-4 flex flex-wrap items-center justify-between gap-2">
<div>
<h2 className="text-base font-bold text-ink">{heading}</h2>
<p className="text-xs text-ink-muted">{recordCount} {mode === "snapshot" ? "Datensätze" : "Ereignisse"}</p>
</div>
<div className="flex gap-2">
<a href={reportExportHref("csv")} className={LINK_BUTTON_CLASS}>
<FileText className="h-4 w-4" />
CSV
</a>
<a href={reportExportHref("xlsx")} className={LINK_BUTTON_CLASS}>
<FileSpreadsheet className="h-4 w-4" />
Excel
</a>
<Button variant="secondary" size="sm" onClick={() => setSaveModalOpen(true)}>
<Save className="h-4 w-4" />
Bericht speichern
</Button>
</div>
</div>
<p className="mb-4 text-2xl font-extrabold text-ink">{totalDisplay}</p>
{showWeekdayMultiCountNote && (
<p className="mb-3 text-xs text-ink-muted">
Mitarbeitende mit mehreren Arbeitstagen zählen bei „Wochentag“ an jedem ihrer Arbeitstage mehrfach – Summe und Anteile ergeben daher mehr als den Gesamt-Headcount bzw. 100%.
</p>
)}
{((mode === "snapshot" && props.split) || (mode === "events" && props.eventSplit)) && (
<div className="mb-3 flex flex-wrap gap-3">
{splitKeys.map((key, i) => (
<span key={key} className="flex items-center gap-1.5 text-xs text-ink-body">
<span className={`h-2.5 w-2.5 rounded-full ${SPLIT_COLORS[i % SPLIT_COLORS.length]}`} />
{key}
</span>
))}
</div>
)}
<div className="flex flex-col gap-3">
{rows.map((row) => {
const share = total > 0 ? (row.value / total) * 100 : 0;
const isExpanded = expandedKey === row.key;
return (
<div key={row.key}>
<button
type="button"
onClick={() => {
setExpandedKey(isExpanded ? null : row.key);
// Zuklappen setzt auch die volle Liste zurück: sonst
// stünde sie beim nächsten Aufklappen unerwartet offen.
setVolleListeKey(null);
}}
className="w-full text-left"
>
<div className="mb-1 flex items-center justify-between text-sm">
<span className="font-semibold text-ink">{row.key}</span>
<span className="text-ink-body">
{mode === "snapshot" ? formatValue(props.measure, row.value) : Math.round(row.value)}{" "}
<span className="text-xs text-ink-muted">({share.toFixed(1)}%)</span>
</span>
</div>
<div className="flex h-2.5 overflow-hidden rounded bg-surface">
{row.split ? (
row.split.map((s, i) => (
<div key={s.key} className={SPLIT_COLORS[i % SPLIT_COLORS.length]} style={{ width: `${maxValue > 0 ? (s.value / maxValue) * 100 : 0}%` }} />
))
) : (
<div className="bg-brand-500" style={{ width: `${(row.value / maxValue) * 100}%` }} />
)}
</div>
</button>
{isExpanded &&
(() => {
const alle = volleListeKey === row.key;
const sichtbar = alle ? row.people : row.people.slice(0, VORSCHAU_NAMEN);
const rest = row.people.length - VORSCHAU_NAMEN;
return (
<div className="mt-2 rounded border border-border bg-surface p-3">
{/* Bei achthundert Namen scrollt die Liste in sich,
statt die Auswertung darüber aus dem Bild zu
schieben. */}
<ul className={`flex flex-col divide-y divide-border ${alle ? "max-h-[28rem] overflow-y-auto" : ""}`}>
{sichtbar.map((p, i) => (
<li key={`${p.id}-${i}`} className="flex items-center justify-between gap-3 py-1.5 text-sm">
<Link href={`/employees/${p.id}`} className="font-semibold text-ink hover:text-brand-700 hover:underline">
{p.name}
</Link>
<span className="text-right text-xs text-ink-muted">
{p.title} · {p.team} · {fmtDate(p.entry_date)}
</span>
</li>
))}
</ul>
{rest > 0 && (
<button
type="button"
onClick={() => setVolleListeKey(alle ? null : row.key)}
className="mt-2 rounded text-xs font-semibold text-brand-700 hover:underline
focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand-500"
>
{alle ? `Nur die ersten ${VORSCHAU_NAMEN} zeigen` : `+${rest} weitere anzeigen`}
</button>
)}
</div>
);
})()}
</div>
);
})}
{rows.length === 0 && <p className="text-sm text-ink-muted">Keine Daten für diese Auswahl.</p>}
</div>
</div>
<Modal
open={saveModalOpen}
onClose={() => setSaveModalOpen(false)}
title="Bericht speichern"
footer={
<>
<Button variant="ghost" onClick={() => setSaveModalOpen(false)}>
Abbrechen
</Button>
<Button onClick={handleConfirmSaveReport} pending={savingReport}>
Speichern
</Button>
</>
}
>
<TextField
label="Name für diesen Bericht"
required
value={newReportName}
onChange={setNewReportName}
onKeyDown={(e) => e.key === "Enter" && handleConfirmSaveReport()}
autoFocus
/>
</Modal>
</div>
);
}