Alpenwerk HR -- interne HR-Stammdatenverwaltung

Mitarbeiter:innen, Organisationsstruktur, Planstellen, Eintritt, Austritt,
Versetzung, Befoerderung, Karenz, On- und Offboarding, Berichte, Massenimport
und ein lueckenloser Nachweis jeder Aenderung.

Next.js 16 mit React 19 und TypeScript, PostgreSQL 17 ueber Kysely, Anmeldung
ueber Microsoft Entra ID. Die Fachlogik liegt in der Datenbank: rund dreissig
PL/pgSQL-Funktionen fuehren eine Aenderung, ihren Historieneintrag und ihren
Protokolleintrag in einer Transaktion aus. Die Zugriffsschranke ist Row Level
Security, nicht die Oberflaeche.

Betrieb auf Windows Server ohne Docker: ein fertiges Paket, ein Windows-Dienst,
der IIS als HTTPS-Vorschaltung und zwei geplante Aufgaben. Siehe
deploy/windows/README.md.
This commit is contained in:
2026-10-13 20:11:18 +02:00
commit 6a7106c95d
419 changed files with 75532 additions and 0 deletions

View File

@@ -0,0 +1,51 @@
"use client";
import { hrName, useHrBenutzer } from "@/components/shell/HrBenutzerContext";
import { ZUSTAENDIGE_HR_FELD } from "@/lib/historie-felder";
import type { AuditChange } from "@/lib/types";
// Was sich geändert hat, feldweise — im Protokoll und in der Historie einer
// Person dieselbe Darstellung. Zwei Ansichten derselben Sache verschieden zu
// setzen, hiesse dass jemand sie zweimal lesen lernen muss.
/** Leerer Wert heisst „war nicht gesetzt“ — und das ist eine Aussage. */
function Wert({ text, art }: { text: string | null; art: "vorher" | "nachher" }) {
if (text === null || text === "") {
return <span className="text-ink-muted italic">leer</span>;
}
return <span className={art === "vorher" ? "text-ink-muted line-through decoration-ink-muted/40" : "text-ink"}>{text}</span>;
}
export function AenderungsTabelle({ changes }: { changes: AuditChange[] }) {
// Die zuständige HR steht als Kennung im Protokoll — sie ist es, die sich
// zurücksetzen lässt. Gezeigt wird der Name.
const hrBenutzer = useHrBenutzer();
const anzeige = (feld: string, text: string | null) =>
feld === ZUSTAENDIGE_HR_FELD && text ? hrName(hrBenutzer, text) : text;
return (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border text-left text-[11px] font-bold uppercase tracking-wider text-ink-muted">
<th className="py-2 pr-4">Feld</th>
<th className="py-2 pr-4">Vorher</th>
<th className="py-2">Nachher</th>
</tr>
</thead>
<tbody>
{changes.map((c, i) => (
<tr key={`${c.feld}-${i}`} className="border-b border-border-subtle align-top last:border-0">
<td className="py-2 pr-4 font-semibold text-ink-body">{c.feld}</td>
<td className="py-2 pr-4">
<Wert text={anzeige(c.feld, c.vorher)} art="vorher" />
</td>
<td className="py-2">
<Wert text={anzeige(c.feld, c.nachher)} art="nachher" />
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}

32
components/ui/Avatar.tsx Normal file
View File

@@ -0,0 +1,32 @@
import { avatarColorFor } from "@/lib/colors";
import { initials } from "@/lib/format";
type AvatarProps = {
firstName: string;
lastName: string;
color?: string | null;
size?: "sm" | "md" | "lg";
};
const SIZE_CLASSES: Record<NonNullable<AvatarProps["size"]>, string> = {
sm: "h-7 w-7 text-xs",
md: "h-9 w-9 text-sm",
lg: "h-14 w-14 text-lg",
};
export function Avatar({ firstName, lastName, color, size = "md" }: AvatarProps) {
const bg = color ?? avatarColorFor(`${firstName}${lastName}`);
return (
<span
// A white ring separates adjacent avatars in the org chart and lets a
// strongly coloured one sit on a tinted row without vibrating against
// it. aria-hidden because the name is always rendered next to it —
// otherwise a screen reader reads the initials and then the name again.
className={`inline-flex shrink-0 select-none items-center justify-center rounded-full font-bold leading-none text-white ring-2 ring-white ${SIZE_CLASSES[size]}`}
style={{ backgroundColor: bg }}
aria-hidden
>
{initials(firstName, lastName)}
</span>
);
}

77
components/ui/Button.tsx Normal file
View File

@@ -0,0 +1,77 @@
"use client";
import type { ButtonHTMLAttributes, ReactNode } from "react";
// The primary-button class chain was written out by hand at a dozen call
// sites and the ghost/secondary ones at many more, each drifting slightly in
// padding and hover colour. Collecting them here also gives every button a
// visible keyboard focus ring, which none of them had.
const BASE =
"inline-flex items-center justify-center gap-1.5 rounded font-semibold transition-colors " +
"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand-500 " +
"disabled:cursor-not-allowed disabled:opacity-50";
const VARIANTS = {
primary: "bg-brand-500 text-white hover:bg-brand-600",
// border-strong wie bei den Eingabefeldern: die Umrandung ist hier das
// Einzige, was den Knopf vom Hintergrund trennt, und muss deshalb die
// 3:1 aus WCAG 1.4.11 erreichen.
secondary: "border border-border-strong bg-white text-ink-body hover:bg-surface",
ghost: "text-ink-body hover:bg-surface",
danger: "bg-danger-solid text-white hover:brightness-110",
// Square icon-only button; pair with an aria-label.
icon: "text-ink-muted hover:bg-surface hover:text-ink",
} as const;
const SIZES = {
sm: "px-3 py-1.5 text-xs",
md: "px-4 py-2 text-sm",
// Meets the 44px touch target without looking oversized on desktop.
icon: "p-2",
} as const;
/**
* For anchors that read as buttons (download links, cross-page actions). A
* real <a> keeps middle-click and "open in new tab" working, which a button
* with an onClick would throw away — so those stay anchors and borrow the
* styling instead.
*/
export const LINK_BUTTON_CLASS = `${BASE} ${VARIANTS.secondary} ${SIZES.sm}`;
type ButtonProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, "className"> & {
variant?: keyof typeof VARIANTS;
size?: keyof typeof SIZES;
/** Disables and shows the busy label; use for in-flight server actions. */
pending?: boolean;
pendingLabel?: string;
fullWidth?: boolean;
className?: string;
children?: ReactNode;
};
export function Button({
variant = "primary",
size,
pending = false,
pendingLabel,
fullWidth,
disabled,
className = "",
children,
type = "button",
...rest
}: ButtonProps) {
const resolvedSize = size ?? (variant === "icon" ? "icon" : "md");
return (
<button
{...rest}
type={type}
disabled={disabled || pending}
aria-busy={pending || undefined}
className={`${BASE} ${VARIANTS[variant]} ${SIZES[resolvedSize]} ${fullWidth ? "w-full" : ""} ${className}`}
>
{pending && pendingLabel ? pendingLabel : children}
</button>
);
}

32
components/ui/Card.tsx Normal file
View File

@@ -0,0 +1,32 @@
import type { ReactNode } from "react";
// The same "rounded border border-border bg-white p-4" appeared at 26 call
// sites, all of them flat: a 1px border and nothing else, so a card sat on
// the page with no separation from it. Collecting them here is what makes it
// possible to give the whole app depth by changing one line.
export const CARD_CLASS = "rounded-md border border-border bg-white shadow-[var(--shadow-card)]";
export function Card({
children,
className = "",
padding = "md",
}: {
children: ReactNode;
className?: string;
/** `none` for cards that manage their own inner spacing (tables, lists). */
padding?: "none" | "sm" | "md" | "lg";
}) {
const pad = { none: "", sm: "p-3", md: "p-4", lg: "p-6" }[padding];
return <div className={`${CARD_CLASS} ${pad} ${className}`}>{children}</div>;
}
/**
* Section titles were all `text-sm font-bold text-ink` — the same weight and
* size as emphasised body text, so headings did not read as a level of their
* own. Slightly smaller, letter-spaced and muted separates them without
* shouting.
*/
export function CardTitle({ children, className = "" }: { children: ReactNode; className?: string }) {
return <h2 className={`text-xs font-bold uppercase tracking-wider text-ink-muted ${className}`}>{children}</h2>;
}

View File

@@ -0,0 +1,160 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { CONTROL_CLASS } from "./Field";
type CountryPickerProps = {
value: string;
onChange: (value: string) => void;
countries: string[];
placeholder?: string;
id?: string;
"aria-describedby"?: string;
"aria-invalid"?: true;
};
const MAX_VISIBLE = 50;
// Searchable text combobox constrained to a fixed list (UN member states)
// rather than a Lookup-style "selected card" — a country is a single text
// value, not an object with its own detail fields.
//
// Carries the full combobox contract: without role/aria-expanded/
// aria-activedescendant a screen reader announces a plain text box and never
// mentions that a list appeared, and without the key handling the list is
// reachable by mouse only.
export function CountryPicker({
value,
onChange,
countries,
placeholder = "Land suchen…",
id,
"aria-describedby": describedBy,
"aria-invalid": invalid,
}: CountryPickerProps) {
const [query, setQuery] = useState(value);
const [prevValue, setPrevValue] = useState(value);
const [open, setOpen] = useState(false);
const [activeIndex, setActiveIndex] = useState(0);
const containerRef = useRef<HTMLDivElement>(null);
const listRef = useRef<HTMLDivElement>(null);
// Re-sync the local draft text when `value` changes externally (e.g. the
// surrounding form loads a different employee). Adjusting state directly
// during render — rather than in an effect — avoids an extra render pass
// and the synchronous setState-in-effect this used to do.
if (value !== prevValue) {
setPrevValue(value);
setQuery(value);
}
useEffect(() => {
function onClickOutside(e: MouseEvent) {
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
setOpen(false);
setQuery(value);
}
}
document.addEventListener("mousedown", onClickOutside);
return () => document.removeEventListener("mousedown", onClickOutside);
}, [value]);
const filtered = (query.trim() ? countries.filter((c) => c.toLowerCase().includes(query.trim().toLowerCase())) : countries).slice(
0,
MAX_VISIBLE
);
const listId = id ? `${id}-listbox` : undefined;
const activeId = id && filtered[activeIndex] ? `${id}-option-${activeIndex}` : undefined;
function commit(country: string) {
onChange(country);
setQuery(country);
setOpen(false);
}
// Keeps the highlighted row inside the scroll container as it moves.
useEffect(() => {
if (!open) return;
listRef.current?.querySelector('[data-active="true"]')?.scrollIntoView({ block: "nearest" });
}, [activeIndex, open]);
function onKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
if (!open) {
setOpen(true);
setActiveIndex(0);
return;
}
const delta = e.key === "ArrowDown" ? 1 : -1;
setActiveIndex((i) => (filtered.length === 0 ? 0 : (i + delta + filtered.length) % filtered.length));
} else if (e.key === "Enter") {
if (open && filtered[activeIndex]) {
e.preventDefault();
commit(filtered[activeIndex]);
}
} else if (e.key === "Escape") {
if (open) {
// Stop here rather than letting it bubble — otherwise the dialog
// containing this field closes along with the dropdown.
e.stopPropagation();
setOpen(false);
setQuery(value);
}
}
}
return (
<div ref={containerRef} className="relative">
<input
id={id}
role="combobox"
aria-expanded={open}
aria-controls={listId}
aria-activedescendant={open ? activeId : undefined}
aria-autocomplete="list"
aria-describedby={describedBy}
aria-invalid={invalid}
autoComplete="off"
value={query}
onChange={(e) => {
setQuery(e.target.value);
setActiveIndex(0);
setOpen(true);
}}
onFocus={() => setOpen(true)}
onKeyDown={onKeyDown}
placeholder={placeholder}
className={CONTROL_CLASS}
/>
{open && (
<div
ref={listRef}
id={listId}
role="listbox"
className="absolute z-20 mt-1 max-h-56 w-full overflow-y-auto rounded border border-border bg-white shadow-[var(--shadow-card-hover)]"
>
{filtered.length === 0 && <div className="px-3 py-2 text-sm text-ink-muted">Keine Treffer</div>}
{filtered.map((c, i) => (
<button
key={c}
id={id ? `${id}-option-${i}` : undefined}
role="option"
aria-selected={i === activeIndex}
data-active={i === activeIndex}
type="button"
// Mouse down would blur the input and close the list before
// the click landed.
onMouseDown={(e) => e.preventDefault()}
onMouseEnter={() => setActiveIndex(i)}
onClick={() => commit(c)}
className={`block w-full px-3 py-2 text-left text-sm ${i === activeIndex ? "bg-brand-100 text-brand-700" : "hover:bg-surface"}`}
>
{c}
</button>
))}
</div>
)}
</div>
);
}

262
components/ui/Field.tsx Normal file
View File

@@ -0,0 +1,262 @@
"use client";
import {
useId,
useState,
type ReactNode,
type SelectHTMLAttributes,
type InputHTMLAttributes,
type TextareaHTMLAttributes,
} from "react";
// Form primitives.
//
// Before these existed the same class chain was written out by hand at 85
// call sites, each with a bare `<label>` next to a bare `<input>` and no
// connection between them — 92 labels, 4 of which used htmlFor, and not a
// single input carried an id. Screen readers announced an unnamed edit box
// and clicking a label focused nothing. Generating the id here makes that
// impossible to get wrong, and gives every field one place to fix focus
// styling, error display and sizing.
// `border-strong` und nicht `border`: der blasse Kartenrahmen kommt gegen
// Weiss auf 1.3:1 und ist als Schmuck in Ordnung, die Umrandung eines
// Bedienelements aber nicht — WCAG 1.4.11 verlangt dafuer 3:1, und ohne sie
// ist auf einem hellen Bildschirm nicht zu sehen, wo ein Feld anfaengt.
// border-strong liegt bei 3.56:1.
export const CONTROL_CLASS =
"w-full rounded border border-border-strong bg-white px-3 py-2 text-sm text-ink " +
"focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-brand-500 " +
"disabled:cursor-not-allowed disabled:border-border disabled:bg-surface disabled:text-ink-muted";
const INVALID_CLASS = "border-danger-solid";
/** Auto-width select for filter bars, where the label is an aria-label. */
export const FILTER_SELECT_CLASS =
"rounded border border-border-strong bg-white px-3 py-2 text-sm text-ink " +
"focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-brand-500";
type FieldChildProps = {
id: string;
"aria-describedby": string | undefined;
"aria-invalid": true | undefined;
};
type FieldShellProps = {
label: string;
/** Marks the label and sets required on the control. */
required?: boolean;
/** Helper text below the control; announced with the field. */
hint?: string;
/** Replaces the hint when set and marks the control invalid. */
error?: string | null;
/** Smaller label, used inside dense side panels. */
dense?: boolean;
className?: string;
};
/**
* Escape hatch for controls this module does not wrap (Lookup, CountryPicker,
* Picklist). Hands the wiring to the caller instead of guessing at it:
*
* <Field label="Land">{(p) => <CountryPicker {...p} … />}</Field>
*/
export function Field({
label,
required,
hint,
error,
dense,
className,
children,
}: FieldShellProps & { children: (props: FieldChildProps) => ReactNode }) {
const id = useId();
const messageId = `${id}-message`;
const message = error ?? hint;
return (
<div className={className}>
<label htmlFor={id} className={dense ? "mb-1 block text-xs font-semibold text-ink-muted" : "mb-1 block text-sm font-semibold text-ink"}>
{label}
{required && <span aria-hidden> *</span>}
{required && <span className="sr-only"> (Pflichtfeld)</span>}
</label>
{children({
id,
"aria-describedby": message ? messageId : undefined,
"aria-invalid": error ? true : undefined,
})}
{message && (
<p id={messageId} className={`mt-1 text-xs ${error ? "font-semibold text-danger-text" : "text-ink-muted"}`}>
{message}
</p>
)}
</div>
);
}
type TextFieldProps = FieldShellProps &
Omit<InputHTMLAttributes<HTMLInputElement>, "onChange" | "id" | "className"> & {
value: string;
/** Receives the value directly — every call site wanted e.target.value. */
onChange: (value: string) => void;
};
export function TextField({ label, required, hint, error, dense, className, value, onChange, ...rest }: TextFieldProps) {
return (
<Field label={label} required={required} hint={hint} error={error} dense={dense} className={className}>
{(p) => (
<input
{...p}
{...rest}
required={required}
value={value}
onChange={(e) => onChange(e.target.value)}
className={`${CONTROL_CLASS} ${error ? INVALID_CLASS : ""}`}
/>
)}
</Field>
);
}
/** Ein vollständiges Datum mit vierstelliger Jahreszahl. */
const VOLLSTAENDIGES_DATUM = /^\d{4}-\d{2}-\d{2}$/;
/**
* Ob ein Datumswert eine Aussage ist — oder ein Zwischenstand beim Tippen.
*
* Exportiert, weil der Stichtag im Organigramm dieselbe Frage stellt und dort
* ein blankes `<input>` steht. Zwei Fassungen derselben Regel laufen in diesem
* Projekt erfahrungsgemäss auseinander.
*/
export function istMeldbaresDatum(wert: string): boolean {
// Leer ist eine Aussage — „kein Datum" —, und die soll durchkommen.
if (wert === "") return true;
if (!VOLLSTAENDIGES_DATUM.test(wert)) return false;
// Ein Jahr unter 1000 entsteht beim Tippen: wer „2026" eingibt, erzeugt
// unterwegs 0002, 0020 und 0202. Das sind gültige Daten und damit nicht von
// einer echten Eingabe zu unterscheiden — ausser an ihrer Grösse.
return Number(wert.slice(0, 4)) >= 1000;
}
/**
* Ein Datumsfeld, das Zwischenstände für sich behält.
*
* Der Anlass: in den Berichten hängt jedes Feld an der Adresszeile — eine
* Änderung heisst `router.push`, also neu laden und neu rendern. Ein
* `<input type="date">` meldet beim Tippen der Jahreszahl aber viermal:
* 0002, 0020, 0202, 2026. Die ersten drei lösten je eine Navigation aus, und
* jede setzte das Feld auf den Stand aus der Adresse zurück — mitten im
* Tippen. Mit der Maus über den Kalender ging es, weil der in einem Zug ein
* fertiges Datum setzt.
*
* Deshalb: der Tippstand bleibt hier, gemeldet wird nur, was eine Aussage ist
* — ein vollständiges Datum mit plausibler Jahreszahl, oder das Leeren des
* Feldes. Beim Verlassen wird nachgereicht, was bis dahin liegengeblieben ist.
*/
export function DateField({ value, onChange, onBlur, ...rest }: Omit<TextFieldProps, "type">) {
const [entwurf, setEntwurf] = useState(value);
const [zuletzt, setZuletzt] = useState(value);
// Von aussen gewinnt: „Zurücksetzen" in den Kriterien leert das Feld, und
// nach dem Melden steht hier ohnehin schon dasselbe.
//
// Während des Renderns angeglichen und nicht in einem Effekt: ein Effekt
// liefe erst nach dem Zeichnen, das Feld zeigte also für einen Bildaufbau
// den alten Stand — und die Regel „kein setState im Effekt" verbietet ihn
// aus genau diesem Grund.
if (value !== zuletzt) {
setZuletzt(value);
setEntwurf(value);
}
return (
<TextField
{...rest}
type="date"
value={entwurf}
onChange={(v) => {
setEntwurf(v);
if (istMeldbaresDatum(v) && v !== value) onChange(v);
}}
onBlur={(e) => {
if (entwurf !== value && istMeldbaresDatum(entwurf)) onChange(entwurf);
onBlur?.(e);
}}
/>
);
}
type Option = { value: string; label: string; disabled?: boolean };
type SelectFieldProps = FieldShellProps &
Omit<SelectHTMLAttributes<HTMLSelectElement>, "onChange" | "id" | "className" | "children"> & {
value: string;
onChange: (value: string) => void;
options: readonly Option[];
/** Prepends a disabled placeholder, for "Bitte wählen…" selects. */
placeholder?: string;
};
export function SelectField({
label,
required,
hint,
error,
dense,
className,
value,
onChange,
options,
placeholder,
...rest
}: SelectFieldProps) {
return (
<Field label={label} required={required} hint={hint} error={error} dense={dense} className={className}>
{(p) => (
<select
{...p}
{...rest}
required={required}
value={value}
onChange={(e) => onChange(e.target.value)}
className={`${CONTROL_CLASS} ${error ? INVALID_CLASS : ""}`}
>
{placeholder && (
<option value="" disabled>
{placeholder}
</option>
)}
{options.map((o) => (
<option key={o.value} value={o.value} disabled={o.disabled}>
{o.label}
</option>
))}
</select>
)}
</Field>
);
}
type TextareaFieldProps = FieldShellProps &
Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, "onChange" | "id" | "className"> & {
value: string;
onChange: (value: string) => void;
};
export function TextareaField({ label, required, hint, error, dense, className, value, onChange, ...rest }: TextareaFieldProps) {
return (
<Field label={label} required={required} hint={hint} error={error} dense={dense} className={className}>
{(p) => (
<textarea
{...p}
{...rest}
required={required}
value={value}
onChange={(e) => onChange(e.target.value)}
className={`${CONTROL_CLASS} ${error ? INVALID_CLASS : ""}`}
/>
)}
</Field>
);
}

View File

@@ -0,0 +1,48 @@
"use client";
import { Info } from "lucide-react";
import { useId } from "react";
// Ein (i), das beim Darüberfahren erklärt, was eine Zahl bedeutet.
//
// Ein Knopf und kein blosses Symbol: so erreicht man die Erklärung auch mit
// der Tastatur und durch Antippen, nicht nur mit der Maus. Der Text hängt per
// aria-describedby am Knopf und wird damit auch vorgelesen.
//
// Er steht **neben** einer Kachel, nicht in ihr: die Kacheln sind Links mit
// `overflow-hidden`, und ein Tooltip darin würde abgeschnitten — und ein
// Klick aufs (i) öffnete statt der Erklärung die verlinkte Liste.
export function InfoHinweis({
text,
label,
className = "",
}: {
text: string;
label: string;
className?: string;
}) {
const id = useId();
return (
<span className={`group/info ${className}`}>
<button
type="button"
aria-label={`Was bedeutet „${label}“?`}
aria-describedby={id}
className="flex h-5 w-5 items-center justify-center rounded-full text-ink-muted hover:text-ink
focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-brand-500"
>
<Info className="h-3.5 w-3.5" aria-hidden />
</button>
<span
id={id}
role="tooltip"
className="pointer-events-none invisible absolute right-0 top-7 z-30 w-64 rounded border border-border bg-white p-3
text-left text-xs font-normal leading-snug text-ink-body opacity-0 shadow-lg transition-opacity
group-hover/info:visible group-hover/info:opacity-100
group-focus-within/info:visible group-focus-within/info:opacity-100"
>
{text}
</span>
</span>
);
}

189
components/ui/Lookup.tsx Normal file
View File

@@ -0,0 +1,189 @@
"use client";
import { Search, X } from "lucide-react";
import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
type LookupProps<T> = {
placeholder?: string;
onSearch: (query: string) => Promise<T[]>;
renderResult: (item: T) => ReactNode;
onSelect: (item: T) => void;
minChars?: number;
id?: string;
"aria-describedby"?: string;
"aria-invalid"?: true;
};
// Generic async search-select used by the position lookup (hire wizard),
// manager/superior lookup (create position), and the reorg workbench.
//
// Implements the combobox contract rather than just looking like one: it was
// a plain text input with a div of clickable buttons underneath, so a
// keyboard user could type but never reach a result, and a screen reader was
// never told a list had appeared. Arrow keys move the selection, Enter takes
// it, Escape closes without also closing the surrounding dialog.
export function Lookup<T>({
placeholder = "Suchen…",
onSearch,
renderResult,
onSelect,
minChars = 2,
id: idProp,
"aria-describedby": describedBy,
"aria-invalid": invalid,
}: LookupProps<T>) {
const generatedId = useId();
const id = idProp ?? generatedId;
const [query, setQuery] = useState("");
const [results, setResults] = useState<T[]>([]);
const [open, setOpen] = useState(false);
const [activeIndex, setActiveIndex] = useState(0);
// Derived from "have we finished searching for the current query yet",
// rather than a separate state flag flipped synchronously at the top of
// the effect below — the effect only ever sets state from the async
// search's own completion callback now.
const [lastSearchedQuery, setLastSearchedQuery] = useState<string | null>(null);
const containerRef = useRef<HTMLDivElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const tooShort = query.trim().length < minChars;
const loading = !tooShort && lastSearchedQuery !== query.trim();
useEffect(() => {
if (tooShort) return;
let cancelled = false;
const timeout = setTimeout(() => {
onSearch(query.trim()).then((res) => {
if (cancelled) return;
setResults(res);
setActiveIndex(0);
setOpen(true);
setLastSearchedQuery(query.trim());
});
}, 200);
return () => {
cancelled = true;
clearTimeout(timeout);
};
}, [query, minChars, onSearch, tooShort]);
// Derived rather than reset via effect: once the query drops below
// minChars, hide the dropdown and any stale results immediately without
// needing a synchronous setState inside the effect above.
const showDropdown = open && !tooShort;
const visibleResults = tooShort ? [] : results;
const selectable = loading ? [] : visibleResults;
useEffect(() => {
function onClickOutside(e: MouseEvent) {
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
setOpen(false);
}
}
document.addEventListener("mousedown", onClickOutside);
return () => document.removeEventListener("mousedown", onClickOutside);
}, []);
useEffect(() => {
if (!showDropdown) return;
listRef.current?.querySelector('[data-active="true"]')?.scrollIntoView({ block: "nearest" });
}, [activeIndex, showDropdown]);
function reset() {
setQuery("");
setResults([]);
setOpen(false);
setActiveIndex(0);
}
function choose(item: T) {
onSelect(item);
reset();
}
function onKeyDown(e: KeyboardEvent<HTMLInputElement>) {
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
if (selectable.length === 0) return;
e.preventDefault();
const delta = e.key === "ArrowDown" ? 1 : -1;
setActiveIndex((i) => (i + delta + selectable.length) % selectable.length);
} else if (e.key === "Enter") {
if (showDropdown && selectable[activeIndex]) {
e.preventDefault();
choose(selectable[activeIndex]);
}
} else if (e.key === "Escape") {
if (showDropdown) {
// Without this the Escape also reaches Modal/SlideOver and closes
// the whole dialog behind the dropdown.
e.stopPropagation();
setOpen(false);
}
}
}
const listId = `${id}-listbox`;
return (
<div ref={containerRef} className="relative">
<div className="flex items-center gap-2 rounded border border-border-strong bg-white px-3 py-2 focus-within:outline-2 focus-within:outline-offset-1 focus-within:outline-brand-500">
<Search className="h-4 w-4 shrink-0 text-ink-muted" aria-hidden />
<input
id={id}
role="combobox"
aria-expanded={showDropdown}
aria-controls={listId}
aria-activedescendant={showDropdown && selectable[activeIndex] ? `${id}-option-${activeIndex}` : undefined}
aria-autocomplete="list"
aria-describedby={describedBy}
aria-invalid={invalid}
autoComplete="off"
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={onKeyDown}
placeholder={placeholder}
className="w-full text-sm outline-none placeholder:text-ink-muted"
/>
{query && (
<button type="button" onClick={reset} aria-label="Zurücksetzen" className="rounded p-0.5 hover:bg-surface">
<X className="h-4 w-4 text-ink-muted" />
</button>
)}
</div>
{/* Announces "Suche…" / result count without stealing focus. */}
<span aria-live="polite" className="sr-only">
{showDropdown ? (loading ? "Suche läuft" : `${visibleResults.length} Treffer`) : ""}
</span>
{showDropdown && (
<div
ref={listRef}
id={listId}
role="listbox"
className="absolute z-20 mt-1 max-h-64 w-full overflow-y-auto rounded border border-border bg-white shadow-[var(--shadow-card-hover)]"
>
{loading && <div className="px-3 py-2 text-sm text-ink-muted">Suche…</div>}
{!loading && visibleResults.length === 0 && <div className="px-3 py-2 text-sm text-ink-muted">Keine Treffer</div>}
{!loading &&
visibleResults.map((item, i) => (
<button
key={i}
id={`${id}-option-${i}`}
role="option"
aria-selected={i === activeIndex}
data-active={i === activeIndex}
type="button"
// Mouse down would blur the input and close the list before
// the click landed.
onMouseDown={(e) => e.preventDefault()}
onMouseEnter={() => setActiveIndex(i)}
onClick={() => choose(item)}
className={`block w-full px-3 py-2 text-left text-sm ${i === activeIndex ? "bg-brand-100" : "hover:bg-surface"}`}
>
{renderResult(item)}
</button>
))}
</div>
)}
</div>
);
}

55
components/ui/Modal.tsx Normal file
View File

@@ -0,0 +1,55 @@
"use client";
import { X } from "lucide-react";
import { useId, useRef, type ReactNode } from "react";
import { Button } from "./Button";
import { useDialogFocus } from "./useDialogFocus";
type ModalProps = {
open: boolean;
onClose: () => void;
title: string;
children: ReactNode;
footer?: ReactNode;
widthClassName?: string;
};
export function Modal({ open, onClose, title, children, footer, widthClassName = "max-w-lg" }: ModalProps) {
const dialogRef = useRef<HTMLDivElement>(null);
const titleId = useId();
useDialogFocus(open, onClose, dialogRef);
if (!open) return null;
return (
// Bottom-aligned on a phone (thumb reach, and it clears the keyboard when
// a field is focused), centred from sm up.
<div className="fixed inset-0 z-50 flex items-end justify-center bg-black/40 p-0 sm:items-center sm:p-4">
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
// Points at the real heading rather than duplicating the string, so
// the accessible name cannot drift from what is on screen.
aria-labelledby={titleId}
tabIndex={-1}
className={`flex max-h-[92dvh] w-full flex-col rounded-t-xl bg-white shadow-[var(--shadow-overlay)] outline-none sm:max-h-[85dvh] sm:rounded ${widthClassName}`}
>
<div className="flex shrink-0 items-center justify-between border-b border-border px-4 py-3 sm:px-6 sm:py-4">
<h2 id={titleId} className="text-lg font-bold text-ink">
{title}
</h2>
<Button variant="icon" onClick={onClose} aria-label="Schließen" className="-mr-1">
<X className="h-5 w-5" />
</Button>
</div>
<div className="flex-1 overflow-y-auto overscroll-contain px-4 py-4 sm:px-6">{children}</div>
{footer && (
<div className="flex shrink-0 flex-wrap items-center justify-end gap-2 border-t border-border px-4 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] sm:px-6 sm:py-4">
{footer}
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,57 @@
import Link from "next/link";
// Shared by the employee list and the audit log, which both used to render
// one link per page: 54 of them for ~800 employees, and an unbounded number
// for the audit log, all in a single overflowing row. This shows the first
// and last page plus a window around the current one, with the gaps elided.
const WINDOW = 2;
function pageItems(current: number, total: number): number[] {
const pages = new Set<number>([1, total]);
for (let p = current - WINDOW; p <= current + WINDOW; p++) {
if (p >= 1 && p <= total) pages.add(p);
}
return [...pages].sort((a, b) => a - b);
}
type PaginationProps = {
page: number;
totalPages: number;
hrefFor: (page: number) => string;
/** Screen-reader name, e.g. "Mitarbeiter:innen" — several lists per app. */
label: string;
};
export function Pagination({ page, totalPages, hrefFor, label }: PaginationProps) {
if (totalPages <= 1) return null;
const current = Math.min(Math.max(1, page), totalPages);
const items = pageItems(current, totalPages);
return (
<nav aria-label={`Seiten – ${label}`} className="flex flex-wrap items-center justify-center gap-1 text-sm">
{current > 1 && (
<Link href={hrefFor(current - 1)} rel="prev" className="rounded px-3 py-1 font-semibold text-ink-body hover:bg-surface">
Zurück
</Link>
)}
{items.map((p, i) => (
<span key={p} className="flex items-center gap-1">
{i > 0 && p - items[i - 1] > 1 && <span className="px-1 text-ink-muted">…</span>}
<Link
href={hrefFor(p)}
aria-current={p === current ? "page" : undefined}
className={`rounded px-3 py-1 ${p === current ? "bg-brand-500 font-semibold text-white" : "text-ink-body hover:bg-surface"}`}
>
{p}
</Link>
</span>
))}
{current < totalPages && (
<Link href={hrefFor(current + 1)} rel="next" className="rounded px-3 py-1 font-semibold text-ink-body hover:bg-surface">
Weiter
</Link>
)}
</nav>
);
}

View File

@@ -0,0 +1,68 @@
"use client";
import { X } from "lucide-react";
import { CONTROL_CLASS } from "./Field";
// Dropdown-to-add, chip-to-remove multi-select for short, fixed option
// lists (no search needed) — e.g. academic titles. The dropdown only offers
// options not yet picked; the reset key forces the <select> back to its
// placeholder after each pick instead of showing the just-added option.
export function Picklist({
options,
value,
onChange,
placeholder = "Hinzufügen…",
// Forwarded onto the <select> so a surrounding <Field> can label it.
id,
"aria-describedby": describedBy,
}: {
options: string[];
value: string[];
onChange: (value: string[]) => void;
placeholder?: string;
id?: string;
"aria-describedby"?: string;
}) {
const available = options.filter((o) => !value.includes(o));
function remove(option: string) {
onChange(value.filter((v) => v !== option));
}
return (
<div className="flex flex-col gap-2">
<select
key={value.length}
id={id}
aria-describedby={describedBy}
defaultValue=""
onChange={(e) => {
if (e.target.value) onChange([...value, e.target.value]);
}}
disabled={available.length === 0}
className={CONTROL_CLASS}
>
<option value="" disabled>
{available.length > 0 ? placeholder : "Alle Optionen ausgewählt"}
</option>
{available.map((o) => (
<option key={o} value={o}>
{o}
</option>
))}
</select>
{value.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{value.map((v) => (
<span key={v} className="flex items-center gap-1 rounded-full bg-brand-500 px-3 py-1.5 text-xs font-semibold text-white">
{v}
<button type="button" onClick={() => remove(v)} aria-label={`${v} entfernen`} className="text-white/80 hover:text-white">
<X className="h-3 w-3" />
</button>
</span>
))}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,45 @@
"use client";
import { Search } from "lucide-react";
import { useId } from "react";
// The icon-in-a-box search field used by the employee list, the audit log and
// the org chart. Each was a hand-rolled copy whose <input> carried only a
// placeholder — no label at all — and killed its own focus ring with
// outline-none. A placeholder is not a label: it disappears on the first
// keystroke and is not reliably announced.
export function SearchInput({
value,
onChange,
placeholder,
label,
className = "",
}: {
value: string;
onChange: (value: string) => void;
placeholder: string;
/** Visually hidden; this is what a screen reader announces. */
label: string;
className?: string;
}) {
const id = useId();
return (
<div
className={`flex min-w-[240px] flex-1 items-center gap-2 rounded border border-border-strong bg-white px-3 py-2 focus-within:outline-2 focus-within:outline-offset-1 focus-within:outline-brand-500 ${className}`}
>
<Search className="h-4 w-4 shrink-0 text-ink-muted" aria-hidden />
<label htmlFor={id} className="sr-only">
{label}
</label>
<input
id={id}
type="search"
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
// The ring lives on the wrapper so it encloses the icon too.
className="w-full text-sm text-ink outline-none placeholder:text-ink-muted"
/>
</div>
);
}

View File

@@ -0,0 +1,28 @@
"use client";
type Option<T extends string> = { value: T; label: string };
type SegmentedControlProps<T extends string> = {
value: T;
onChange: (value: T) => void;
options: Option<T>[];
};
export function SegmentedControl<T extends string>({ value, onChange, options }: SegmentedControlProps<T>) {
return (
<div className="inline-flex rounded bg-surface p-1">
{options.map((opt) => (
<button
key={opt.value}
type="button"
onClick={() => onChange(opt.value)}
className={`rounded px-3 py-1.5 text-sm font-semibold transition-colors ${
value === opt.value ? "bg-white text-brand-700 shadow-sm" : "text-ink-muted hover:text-ink"
}`}
>
{opt.label}
</button>
))}
</div>
);
}

View File

@@ -0,0 +1,82 @@
"use client";
import { X } from "lucide-react";
import { useId, useRef, type ReactNode } from "react";
import { Button } from "./Button";
import { useDialogFocus } from "./useDialogFocus";
type SlideOverProps = {
open: boolean;
onClose: () => void;
title: string;
subtitle?: string;
children: ReactNode;
footer?: ReactNode;
};
export function SlideOver({ open, onClose, title, subtitle, children, footer }: SlideOverProps) {
const dialogRef = useRef<HTMLDivElement>(null);
const titleId = useId();
useDialogFocus(open, onClose, dialogRef);
return (
// Stays mounted so the slide transition can run, which means a closed
// panel's fields are still in the tab order — aria-hidden does not remove
// them. `inert` does, and also blocks clicks, so several closed panels no
// longer pile up invisible tab stops at the end of the page.
<div className="fixed inset-0 z-50" inert={!open}>
<div
className={`absolute inset-0 bg-black/40 transition-opacity ${open ? "opacity-100" : "opacity-0"}`}
onClick={onClose}
aria-hidden
/>
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
tabIndex={-1}
// ── Warum der Schatten am geschlossenen Panel wegfällt ──────────
//
// Geschlossen steht das Panel per `translate-x-full` genau hinter dem
// rechten Bildschirmrand: die eigene linke Kante liegt auf dem Rand.
// Der Schatten ist das Einzige, was von dort noch ins Bild reicht —
// 32 px Weichzeichnung nach aussen, und „aussen" heisst hier: nach
// links, in die Seite hinein.
//
// Bei einem Panel fällt das nicht auf. Die Protokollseite rendert
// jedoch eines **je Zeile**, also fünfzig übereinander an derselben
// Stelle. Bei 18 % Deckkraft bleiben nach fünfzig Lagen rechnerisch
// 0,01 % Durchsicht — ein fast schwarzer Streifen neben der
// Bildlaufleiste, mit sichtbaren Stufen dort, wo sich die
// Weichzeichnungen der einzelnen Lagen überlagern. Genau das hat der
// Kunde gemeldet.
//
// Die Tiefe gehört zum geöffneten Panel, nicht zum weggeschobenen.
// Sie erst beim Öffnen zu setzen kostet nichts und nimmt dem Stapel
// seine Wirkung.
className={`absolute right-0 top-0 flex h-dvh w-full max-w-md flex-col bg-white outline-none transition-transform duration-200 ${
open ? "translate-x-0 shadow-[var(--shadow-overlay)]" : "translate-x-full"
}`}
>
<div className="flex shrink-0 items-start justify-between border-b border-border px-4 py-3 pt-[max(0.75rem,env(safe-area-inset-top))] sm:px-6 sm:py-4">
<div className="min-w-0">
<h2 id={titleId} className="text-lg font-bold text-ink">
{title}
</h2>
{subtitle && <p className="truncate text-sm text-ink-muted">{subtitle}</p>}
</div>
<Button variant="icon" onClick={onClose} aria-label="Schließen" className="-mr-1">
<X className="h-5 w-5" />
</Button>
</div>
<div className="flex-1 overflow-y-auto overscroll-contain px-4 py-4 sm:px-6">{children}</div>
{footer && (
<div className="flex shrink-0 flex-wrap items-center justify-end gap-2 border-t border-border px-4 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] sm:px-6 sm:py-4">
{footer}
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,51 @@
import { absenceLabel } from "@/lib/absence";
import { STATUS_STYLES } from "@/lib/colors";
import { fmtDate } from "@/lib/format";
import { deriveStatusAsOf } from "@/lib/reports";
// ── Warum der Status hier abgeleitet und nicht übergeben wird ────────
//
// Vorher nahm dieses Bauteil einen fertigen Status entgegen, und beide
// Aufrufer reichten `employees.status` durch — die gespeicherte Spalte. Die
// Liste daneben filtert aber über die Datumsspalten (lib/employee-status-
// filter.ts), und sobald die Spalte nachhängt, widersprechen sich Filter und
// Beschriftung: der Filter „Ausgetreten" fand 48 Personen, von denen mehrere
// als „Aktiv" beschriftet waren.
//
// Nachhängen kann sie regelmässig. terminate_employee (Migration
// 20260814100000) setzt die Spalte nur, wenn das Austrittsdatum nicht in der
// Zukunft liegt — „es gibt keinen Lauf, der das später nachzieht" steht dort
// als Kommentar. Ein Austritt, der zum Zeitpunkt der Erfassung noch bevorstand,
// lässt die Spalte also für immer auf „Aktiv" stehen.
//
// Deshalb nimmt das Bauteil jetzt die Zeile und den Stichtag und leitet
// selbst ab. Die Spalte lässt sich nicht mehr hineinreichen: die zweite
// Quelle ist nicht bloss ungenutzt, es gibt sie hier nicht mehr.
export type StatusChipEmployee = {
entry_date: string;
exit_date: string | null;
karenz_start_date: string | null;
karenz_return_date: string | null;
/** Shown instead of the generic label when the kind of absence is known. */
absence_type?: string | null;
};
type StatusChipProps = {
employee: StatusChipEmployee;
/** Der Tag, zu dem der Status gilt — derselbe, nach dem die Seite filtert. */
asOf: string;
};
export function StatusChip({ employee, asOf }: StatusChipProps) {
const status = deriveStatusAsOf(employee, asOf);
// Der abgeleitete Status ist 'Karenz'; absenceLabel macht daraus
// "Langzeitabwesenheit", oder die konkrete Art, wenn eine erfasst ist.
const label = status === "Geplant" ? `Eintritt ${fmtDate(employee.entry_date)}` : absenceLabel(status, employee.absence_type ?? null);
return (
<span
className={`inline-flex items-center whitespace-nowrap rounded-full px-2.5 py-0.5 text-xs font-semibold ${STATUS_STYLES[status]}`}
>
{label}
</span>
);
}

53
components/ui/Toast.tsx Normal file
View File

@@ -0,0 +1,53 @@
"use client";
import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from "react";
type ToastVariant = "success" | "error" | "info";
type ToastItem = { id: number; message: string; variant: ToastVariant };
type ToastContextValue = { showToast: (message: string, variant?: ToastVariant) => void };
const ToastContext = createContext<ToastContextValue | null>(null);
const VARIANT_STYLES: Record<ToastVariant, string> = {
success: "bg-success-text",
error: "bg-danger-solid",
info: "bg-info-text",
};
export function ToastProvider({ children }: { children: ReactNode }) {
const [toasts, setToasts] = useState<ToastItem[]>([]);
const showToast = useCallback((message: string, variant: ToastVariant = "success") => {
const id = Date.now() + Math.random();
setToasts((prev) => [...prev, { id, message, variant }]);
setTimeout(() => setToasts((prev) => prev.filter((t) => t.id !== id)), 4000);
}, []);
// This provider wraps the whole app, so an inline object literal here would
// hand every consumer a new context value on each toast and re-render the
// entire tree for a 4-second banner.
const value = useMemo(() => ({ showToast }), [showToast]);
return (
<ToastContext.Provider value={value}>
{children}
<div className="pointer-events-none fixed bottom-4 right-4 z-[100] flex flex-col gap-2">
{toasts.map((t) => (
<div
key={t.id}
role="status"
className={`pointer-events-auto rounded px-4 py-2 text-sm font-semibold text-white shadow-lg ${VARIANT_STYLES[t.variant]}`}
>
{t.message}
</div>
))}
</div>
</ToastContext.Provider>
);
}
export function useToast(): ToastContextValue {
const ctx = useContext(ToastContext);
if (!ctx) throw new Error("useToast must be used within a ToastProvider");
return ctx;
}

View File

@@ -0,0 +1,90 @@
"use client";
import { useEffect, useRef, type RefObject } from "react";
// Everything a dialog owes the keyboard, in one place so Modal and SlideOver
// cannot drift apart. Both previously handled only Escape: focus stayed on
// whatever was behind the overlay, Tab walked straight out of the dialog into
// the page underneath, and closing left focus on <body> — so the next Tab
// started again from the top of the document.
const FOCUSABLE = [
"a[href]",
"button:not([disabled])",
"input:not([disabled]):not([type='hidden'])",
"select:not([disabled])",
"textarea:not([disabled])",
"[tabindex]:not([tabindex='-1'])",
].join(",");
function focusableWithin(container: HTMLElement): HTMLElement[] {
return [...container.querySelectorAll<HTMLElement>(FOCUSABLE)].filter(
(el) => el.offsetParent !== null || el.getClientRects().length > 0
);
}
export function useDialogFocus(open: boolean, onClose: () => void, containerRef: RefObject<HTMLElement | null>) {
const restoreToRef = useRef<HTMLElement | null>(null);
// onClose wird von den meisten Aufrufern bei jedem Rendern neu erzeugt.
// Stünde es in den Abhängigkeiten, liefe dieser Effekt nach jedem Rendern
// erneut — und sein Aufräumen holt den Fokus dorthin zurück, wo er vor dem
// Öffnen war. In einem Dialog mit Eingabefeldern hiesse das: nach dem
// ersten Zeichen springt der Fokus auf den Knopf, der ihn geöffnet hat, und
// der Rest der Eingabe geht ins Leere. Über eine Referenz bleibt der
// aktuelle Rückruf erreichbar, ohne dass der Effekt daran hängt.
const schliessen = useRef(onClose);
useEffect(() => {
schliessen.current = onClose;
});
useEffect(() => {
if (!open) return;
const container = containerRef.current;
restoreToRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
// First field rather than the close button: the point of opening these is
// to fill them in. autoFocus on a child wins, since it has already run.
if (container && !container.contains(document.activeElement)) {
const [first] = focusableWithin(container);
(first ?? container).focus();
}
function onKeyDown(e: KeyboardEvent) {
if (e.key === "Escape") {
schliessen.current();
return;
}
if (e.key !== "Tab" || !container) return;
const focusable = focusableWithin(container);
if (focusable.length === 0) {
e.preventDefault();
return;
}
const first = focusable[0];
const last = focusable[focusable.length - 1];
const active = document.activeElement;
// Wrap around at both ends, and pull focus back in if it somehow
// escaped (a click on the backdrop, say).
if (!container.contains(active)) {
e.preventDefault();
(e.shiftKey ? last : first).focus();
} else if (e.shiftKey && active === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && active === last) {
e.preventDefault();
first.focus();
}
}
window.addEventListener("keydown", onKeyDown);
return () => {
window.removeEventListener("keydown", onKeyDown);
// Back to whatever opened the dialog, so the next Tab continues from
// there instead of restarting at the top of the page.
restoreToRef.current?.focus();
};
}, [open, containerRef]);
}