Phase 6/7: Reports builder and Audit log - all 7 routes now complete

Reports (§4.8):
- lib/reports.ts: generic server-side aggregation engine over 9 measures
  (Headcount, FTE, Eintritte, Austritte, Ø Bruttogehalt, Teilzeitquote,
  Ø Alter, Ø Zugehoerigkeit, Frauenanteil) x 10 group-by dimensions, with
  an optional second-dimension split (disabled for average-type
  measures) and per-row drill-down data.
- app/(app)/reports/page.tsx: reads filters from the URL, fetches the
  matching employees_directory rows server-side, aggregates in Node
  (not shipped raw to the client), computes the total.
- ReportsPageClient: measure/group/split/filter controls, 6 preset
  chips, saved-reports list (actions/reports.ts), CSV export
  (client-side blob download), stacked bars with a color-keyed legend
  when split is active, and click-to-drill-down into the underlying
  people (capped at 12, "+N weitere", linking to /employees/[id]).

Audit log (§4.9):
- app/(app)/audit/page.tsx + AuditFilters: search (target/details/actor)
  + action-type filter, paginated table with colored action badges,
  row links to the affected employee when target_employee_id is set,
  and the required "unveraenderbar" footer note.

This completes every route from the spec's information architecture:
Dashboard, Mitarbeiter:innen (list+detail), Organigramm (3 views),
Positionen & Bereiche, Berichte, Audit-Log, plus the Hire wizard and all
6 action panels reachable from them.

Final verification: clean npm run build + tsc --noEmit, then a full
browser walkthrough of all 6 authenticated routes as hr_admin (zero
console errors, zero 5xx responses) and a role-check pass as the
manager test account confirming action buttons and the "+ Neueinstellung"
button are hidden, and salary is masked as "... (ausgeblendet)" on the
Vertrag & Gehalt tab. Swept the database for leftover test data from
the debugging sessions above - none found, seed data is clean.
This commit is contained in:
2026-07-13 23:11:23 +02:00
parent 108da8d5e6
commit e27db5f030
6 changed files with 894 additions and 0 deletions

27
actions/reports.ts Normal file
View File

@@ -0,0 +1,27 @@
"use server";
import { revalidatePath } from "next/cache";
import { createClient } from "@/lib/supabase/server";
type ActionResult = { success: boolean; error?: string };
export async function saveReport(payload: { name: string; config: Record<string, unknown> }): Promise<ActionResult> {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) return { success: false, error: "Nicht angemeldet." };
const { error } = await supabase.from("saved_reports").insert({ created_by: user.id, name: payload.name, config: payload.config });
if (error) return { success: false, error: error.message };
revalidatePath("/reports");
return { success: true };
}
export async function deleteReport(id: string): Promise<ActionResult> {
const supabase = await createClient();
const { error } = await supabase.from("saved_reports").delete().eq("id", id);
if (error) return { success: false, error: error.message };
revalidatePath("/reports");
return { success: true };
}

119
app/(app)/audit/page.tsx Normal file
View File

@@ -0,0 +1,119 @@
import Link from "next/link";
import { Suspense } from "react";
import { AuditFilters } from "@/components/audit/AuditFilters";
import { actionBadgeStyle } from "@/lib/colors";
import { fmtDate } from "@/lib/format";
import { createClient } from "@/lib/supabase/server";
const PAGE_SIZE = 25;
type SearchParams = { q?: string; action?: string; page?: string };
function pageHref(params: SearchParams, page: number): string {
const sp = new URLSearchParams();
if (params.q) sp.set("q", params.q);
if (params.action) sp.set("action", params.action);
sp.set("page", String(page));
return `/audit?${sp.toString()}`;
}
function fmtDateTime(iso: string): string {
return new Intl.DateTimeFormat("de-AT", { day: "2-digit", month: "2-digit", year: "numeric", hour: "2-digit", minute: "2-digit" }).format(
new Date(iso)
);
}
export default async function AuditPage({ searchParams }: { searchParams: Promise<SearchParams> }) {
const params = await searchParams;
const supabase = await createClient();
const page = Math.max(1, Number(params.page ?? "1") || 1);
const from = (page - 1) * PAGE_SIZE;
const to = from + PAGE_SIZE - 1;
let query = supabase
.from("audit_log")
.select("id, occurred_at, actor_name, action, target_label, target_employee_id, details", { count: "exact" })
.order("occurred_at", { ascending: false })
.range(from, to);
if (params.action) query = query.eq("action", params.action);
if (params.q) {
const q = params.q.trim();
query = query.or(`target_label.ilike.%${q}%,details.ilike.%${q}%,actor_name.ilike.%${q}%`);
}
const { data: entries, count } = await query;
const totalPages = Math.max(1, Math.ceil((count ?? 0) / PAGE_SIZE));
return (
<div className="flex flex-col gap-4">
<Suspense>
<AuditFilters />
</Suspense>
<p className="text-sm text-ink-muted">{count ?? 0} Einträge</p>
<div className="overflow-x-auto rounded border border-border bg-white">
<table className="w-full min-w-[800px] text-sm">
<thead>
<tr className="border-b border-border bg-surface text-left text-xs font-semibold uppercase tracking-wide text-ink-muted">
<th className="px-4 py-3">Zeitpunkt</th>
<th className="px-4 py-3">Benutzer:in</th>
<th className="px-4 py-3">Aktion</th>
<th className="px-4 py-3">Objekt</th>
<th className="px-4 py-3">Details</th>
</tr>
</thead>
<tbody>
{(entries ?? []).map((entry) => {
return (
<tr key={entry.id} className="border-b border-border last:border-0 hover:bg-surface">
<td className="px-4 py-3 text-ink-body">{fmtDateTime(entry.occurred_at)}</td>
<td className="px-4 py-3 text-ink-body">{entry.actor_name}</td>
<td className="px-4 py-3">
<span className={`rounded-full px-2 py-0.5 text-xs font-semibold ${actionBadgeStyle(entry.action)}`}>{entry.action}</span>
</td>
<td className="px-4 py-3 text-ink">
{entry.target_employee_id ? (
<Link href={`/employees/${entry.target_employee_id}`} className="hover:text-brand-700 hover:underline">
{entry.target_label}
</Link>
) : (
entry.target_label
)}
</td>
<td className="px-4 py-3 text-ink-muted">{entry.details ?? ""}</td>
</tr>
);
})}
{(entries ?? []).length === 0 && (
<tr>
<td colSpan={5} className="px-4 py-8 text-center text-sm text-ink-muted">
Keine Einträge gefunden.
</td>
</tr>
)}
</tbody>
</table>
</div>
{totalPages > 1 && (
<div className="flex items-center justify-center gap-2 text-sm">
{Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
<Link
key={p}
href={pageHref(params, p)}
className={`rounded px-3 py-1 ${p === page ? "bg-brand-500 text-white" : "text-ink-body hover:bg-surface"}`}
>
{p}
</Link>
))}
</div>
)}
<p className="text-xs text-ink-muted">
Alle Änderungen an Personal-Stammdaten werden automatisch protokolliert und sind unveränderbar.
</p>
</div>
);
}

117
app/(app)/reports/page.tsx Normal file
View File

@@ -0,0 +1,117 @@
import { Suspense } from "react";
import { ReportsPageClient } from "@/components/reports/ReportsPageClient";
import {
aggregateReport,
DATE_SCOPED_MEASURES,
type GroupDimension,
type Measure,
type OrgLookups,
type ReportEmployee,
} from "@/lib/reports";
import { createClient } from "@/lib/supabase/server";
import type { EmploymentStatus, EmploymentType } from "@/lib/supabase/types";
type SearchParams = {
measure?: string;
group?: string;
split?: string;
division?: string;
location?: string;
status?: string;
employment?: string;
from?: string;
to?: string;
};
export default async function ReportsPage({ searchParams }: { searchParams: Promise<SearchParams> }) {
const params = await searchParams;
const supabase = await createClient();
const measure = (params.measure as Measure) || "headcount";
const group = (params.group as GroupDimension) || "division";
const split = (params.split as GroupDimension) || undefined;
const [{ data: divisions }, { data: departments }, { data: teams }, { data: locations }] = await Promise.all([
supabase.from("divisions").select("id, name").order("name"),
supabase.from("departments").select("id, name"),
supabase.from("teams").select("id, name, department_id"),
supabase.from("locations").select("id, name").order("name"),
]);
const departmentNameById = new Map((departments ?? []).map((d) => [d.id, d.name]));
const lookups: OrgLookups = {
divisionName: new Map((divisions ?? []).map((d) => [d.id, d.name])),
departmentNameByTeam: new Map((teams ?? []).map((t) => [t.id, departmentNameById.get(t.department_id) ?? "Unbekannt"])),
teamName: new Map((teams ?? []).map((t) => [t.id, t.name])),
locationName: new Map((locations ?? []).map((l) => [l.id, l.name])),
};
let query = supabase
.from("employees_directory")
.select(
"id, first_name, last_name, job_title, division_id, team_id, location_id, status, employment_type, contract_type, entry_date, exit_date, weekly_hours, monthly_salary_gross, source, paygrade, birth_date, gender"
);
if (params.division) query = query.eq("division_id", params.division);
if (params.location) query = query.eq("location_id", params.location);
if (params.status) query = query.eq("status", params.status as EmploymentStatus);
if (params.employment) query = query.eq("employment_type", params.employment as EmploymentType);
const isDateScoped = DATE_SCOPED_MEASURES.includes(measure);
const currentYear = new Date().getFullYear();
const from = params.from || `${currentYear}-01-01`;
const to = params.to || `${currentYear}-12-31`;
if (isDateScoped) {
if (measure === "hires") query = query.gte("entry_date", from).lte("entry_date", to);
else query = query.gte("exit_date", from).lte("exit_date", to).not("exit_date", "is", null);
} else if (!params.status) {
query = query.in("status", ["Aktiv", "Karenz"]);
}
const { data: employeesData } = await query;
const employees = (employeesData ?? []) as ReportEmployee[];
const rows = aggregateReport(employees, measure, group, split ?? null, lookups);
const total = measureValueForTotal(rows, measure);
const {
data: { user },
} = await supabase.auth.getUser();
const { data: savedReports } = user
? await supabase.from("saved_reports").select("id, name, config").eq("created_by", user.id).order("created_at", { ascending: false })
: { data: [] };
return (
<Suspense>
<ReportsPageClient
measure={measure}
group={group}
split={split ?? ""}
filters={{
division: params.division ?? "",
location: params.location ?? "",
status: params.status ?? "",
employment: params.employment ?? "",
from: params.from ?? "",
to: params.to ?? "",
}}
rows={rows}
total={total}
recordCount={employees.length}
divisions={divisions ?? []}
locations={locations ?? []}
savedReports={savedReports ?? []}
/>
</Suspense>
);
}
function measureValueForTotal(rows: { value: number; count: number }[], measure: Measure): number {
if (["headcount", "fte", "hires", "exits"].includes(measure)) {
return rows.reduce((s, r) => s + r.value, 0);
}
// averages/ratios: weight by underlying count for a sensible overall figure
const totalCount = rows.reduce((s, r) => s + r.count, 0);
if (totalCount === 0) return 0;
return rows.reduce((s, r) => s + r.value * r.count, 0) / totalCount;
}

View File

@@ -0,0 +1,76 @@
"use client";
import { Search } from "lucide-react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
const ACTIONS = [
"Neueinstellung",
"Wiedereinstellung",
"Rückkehr",
"Austritt",
"Versetzung",
"Ausschreibung",
"Interne Besetzung",
"Beförderung",
"Reorganisation",
"Reorganisation rückgängig",
"Karenz",
"Vertragsänderung",
"Stammdatenänderung",
"Gehaltsanpassung",
];
export function AuditFilters() {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const [q, setQ] = useState(searchParams.get("q") ?? "");
useEffect(() => {
const handle = setTimeout(() => {
const current = new URLSearchParams(searchParams.toString());
if (q) current.set("q", q);
else current.delete("q");
current.delete("page");
const next = current.toString();
if (next !== searchParams.toString()) router.push(`${pathname}?${next}`);
}, 300);
return () => clearTimeout(handle);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [q]);
function updateParam(key: string, value: string) {
const params = new URLSearchParams(searchParams.toString());
if (value) params.set(key, value);
else params.delete(key);
params.delete("page");
router.push(`${pathname}?${params.toString()}`);
}
return (
<div className="flex flex-wrap items-center gap-3">
<div className="flex min-w-[240px] flex-1 items-center gap-2 rounded border border-border bg-white px-3 py-2">
<Search className="h-4 w-4 shrink-0 text-ink-muted" />
<input
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="Objekt, Details, Benutzer:in…"
className="w-full text-sm text-ink outline-none placeholder:text-ink-muted"
/>
</div>
<select
defaultValue={searchParams.get("action") ?? ""}
onChange={(e) => updateParam("action", e.target.value)}
className="rounded border border-border bg-white px-3 py-2 text-sm text-ink"
>
<option value="">Alle Aktionen</option>
{ACTIONS.map((a) => (
<option key={a} value={a}>
{a}
</option>
))}
</select>
</div>
);
}

View File

@@ -0,0 +1,354 @@
"use client";
import { Download, 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 { useToast } from "@/components/ui/Toast";
import { fmtDate } from "@/lib/format";
import {
AVERAGE_MEASURES,
DATE_SCOPED_MEASURES,
GROUP_LABELS,
MEASURE_LABELS,
REPORT_PRESETS,
type GroupDimension,
type Measure,
type ReportRow,
} from "@/lib/reports";
const SPLIT_COLORS = ["bg-brand-500", "bg-info-text", "bg-purple-text", "bg-warning-text", "bg-success-text", "bg-danger-solid"];
type SavedReport = { id: string; name: string; config: Record<string, unknown> };
type ReportsPageClientProps = {
measure: Measure;
group: GroupDimension;
split: GroupDimension | "";
filters: { division: string; location: string; status: string; employment: string; from: string; to: string };
rows: ReportRow[];
total: number;
recordCount: number;
divisions: { id: string; name: string }[];
locations: { id: string; name: string }[];
savedReports: SavedReport[];
};
function formatValue(measure: Measure, value: number): string {
if (["headcount", "hires", "exits"].includes(measure)) return String(Math.round(value));
if (measure === "fte") return value.toFixed(1);
if (measure === "avg_salary") return new Intl.NumberFormat("de-AT", { style: "currency", currency: "EUR" }).format(value);
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 { measure, group, split, filters, rows, total, recordCount, divisions, locations, savedReports } = props;
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const { showToast } = useToast();
const [expandedKey, setExpandedKey] = useState<string | null>(null);
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()}`);
}
function applyPreset(preset: (typeof REPORT_PRESETS)[number]) {
router.push(`${pathname}?measure=${preset.measure}&group=${preset.group}${preset.split ? `&split=${preset.split}` : ""}`);
}
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);
}
router.push(`${pathname}?${sp.toString()}`);
}
async function handleSaveReport() {
const name = window.prompt("Name für diesen Bericht:");
if (!name) return;
const result = await saveReport({ name, config: { measure, group, split, ...filters } });
if (result.success) {
showToast("Bericht gespeichert.");
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");
}
}
function handleExportCsv() {
const header = [GROUP_LABELS[group], MEASURE_LABELS[measure], "Anzahl", "Anteil (%)"];
const lines = [header.join(";")];
for (const row of rows) {
const share = total > 0 ? ((row.value / total) * 100).toFixed(1) : "0";
lines.push([row.key, formatValue(measure, row.value), String(row.count), share].join(";"));
}
const blob = new Blob([lines.join("\n")], { type: "text/csv;charset=utf-8;" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `bericht-${measure}-${group}.csv`;
a.click();
URL.revokeObjectURL(url);
}
const isAverage = AVERAGE_MEASURES.includes(measure);
const isDateScoped = DATE_SCOPED_MEASURES.includes(measure);
const maxValue = Math.max(1, ...rows.map((r) => r.value));
return (
<div className="grid grid-cols-1 gap-4 lg:grid-cols-[320px_1fr]">
<div className="flex flex-col gap-4">
<div className="rounded border border-border bg-white p-4">
<div className="flex flex-col gap-3">
<div>
<label className="mb-1 block text-xs font-semibold uppercase tracking-wide text-ink-muted">Kennzahl</label>
<select
value={measure}
onChange={(e) => updateParams({ measure: e.target.value, split: AVERAGE_MEASURES.includes(e.target.value as Measure) ? undefined : split })}
className="w-full rounded border border-border px-3 py-2 text-sm"
>
{(Object.keys(MEASURE_LABELS) as Measure[]).map((m) => (
<option key={m} value={m}>
{MEASURE_LABELS[m]}
</option>
))}
</select>
</div>
<div>
<label className="mb-1 block text-xs font-semibold uppercase tracking-wide text-ink-muted">Gruppieren nach</label>
<select value={group} onChange={(e) => updateParams({ group: e.target.value })} className="w-full rounded border border-border px-3 py-2 text-sm">
{(Object.keys(GROUP_LABELS) as GroupDimension[]).map((g) => (
<option key={g} value={g}>
{GROUP_LABELS[g]}
</option>
))}
</select>
</div>
<div>
<label className="mb-1 block text-xs font-semibold uppercase tracking-wide text-ink-muted">Aufteilen nach</label>
<select
value={split}
disabled={isAverage}
onChange={(e) => updateParams({ split: e.target.value || undefined })}
className="w-full rounded border border-border px-3 py-2 text-sm disabled:bg-surface disabled:text-ink-muted"
>
<option value="">Keine Aufteilung</option>
{(Object.keys(GROUP_LABELS) as GroupDimension[])
.filter((g) => g !== group)
.map((g) => (
<option key={g} value={g}>
{GROUP_LABELS[g]}
</option>
))}
</select>
</div>
</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 value={filters.division} onChange={(e) => updateParams({ division: e.target.value })} className="w-full rounded border border-border px-3 py-2 text-sm">
<option value="">Alle Bereiche</option>
{divisions.map((d) => (
<option key={d.id} value={d.id}>
{d.name}
</option>
))}
</select>
<select value={filters.location} onChange={(e) => updateParams({ location: e.target.value })} className="w-full rounded border border-border px-3 py-2 text-sm">
<option value="">Alle Standorte</option>
{locations.map((l) => (
<option key={l.id} value={l.id}>
{l.name}
</option>
))}
</select>
<select value={filters.status} onChange={(e) => updateParams({ status: e.target.value })} className="w-full rounded border border-border px-3 py-2 text-sm">
<option value="">Alle Status</option>
<option value="Aktiv">Aktiv</option>
<option value="Karenz">Karenz</option>
<option value="Geplant">Geplant</option>
<option value="Ausgetreten">Ausgetreten</option>
</select>
<select
value={filters.employment}
onChange={(e) => updateParams({ employment: e.target.value })}
className="w-full rounded border border-border px-3 py-2 text-sm"
>
<option value="">Alle Beschäftigungsarten</option>
<option value="Vollzeit">Vollzeit</option>
<option value="Teilzeit">Teilzeit</option>
</select>
{isDateScoped && (
<div className="grid grid-cols-2 gap-2">
<input
type="date"
value={filters.from}
onChange={(e) => updateParams({ from: e.target.value })}
className="w-full rounded border border-border px-2 py-2 text-xs"
/>
<input
type="date"
value={filters.to}
onChange={(e) => updateParams({ to: e.target.value })}
className="w-full rounded border border-border px-2 py-2 text-xs"
/>
</div>
)}
</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">Vorlagen</h3>
<div className="flex flex-wrap gap-1.5">
{REPORT_PRESETS.map((preset) => (
<button
key={preset.name}
type="button"
onClick={() => applyPreset(preset)}
className="rounded-full border border-border px-2.5 py-1 text-xs font-semibold text-ink-body hover:bg-surface"
>
{preset.name}
</button>
))}
</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 type="button" onClick={() => applySavedReport(r.config)} className="text-left text-ink-body hover:text-brand-700 hover:underline">
{r.name}
</button>
<button type="button" onClick={() => handleDeleteReport(r.id)} aria-label="Löschen" className="text-ink-muted 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">
{MEASURE_LABELS[measure]} nach {GROUP_LABELS[group]}
</h2>
<p className="text-xs text-ink-muted">{recordCount} Datensätze</p>
</div>
<div className="flex gap-2">
<button
type="button"
onClick={handleExportCsv}
className="flex items-center gap-1.5 rounded border border-border px-3 py-1.5 text-sm font-semibold text-ink-body hover:bg-surface"
>
<Download className="h-4 w-4" />
CSV exportieren
</button>
<button
type="button"
onClick={handleSaveReport}
className="flex items-center gap-1.5 rounded border border-border px-3 py-1.5 text-sm font-semibold text-ink-body hover:bg-surface"
>
<Save className="h-4 w-4" />
Bericht speichern
</button>
</div>
</div>
<p className="mb-4 text-2xl font-extrabold text-ink">{formatValue(measure, total)}</p>
{split && (
<div className="mb-3 flex flex-wrap gap-3">
{Array.from(new Set(rows.flatMap((r) => r.split?.map((s) => s.key) ?? []))).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)}
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">
{formatValue(measure, 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 && (
<div className="mt-2 rounded border border-border bg-surface p-3">
<ul className="flex flex-col divide-y divide-border">
{row.people.slice(0, 12).map((p) => (
<li key={p.id} className="flex items-center justify-between 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-xs text-ink-muted">
{p.title} · {p.team} · {fmtDate(p.entry_date)}
</span>
</li>
))}
</ul>
{row.people.length > 12 && <p className="mt-2 text-xs text-ink-muted">+{row.people.length - 12} weitere</p>}
</div>
)}
</div>
);
})}
{rows.length === 0 && <p className="text-sm text-ink-muted">Keine Daten für diese Auswahl.</p>}
</div>
</div>
</div>
);
}

201
lib/reports.ts Normal file
View File

@@ -0,0 +1,201 @@
export type Measure =
| "headcount"
| "fte"
| "hires"
| "exits"
| "avg_salary"
| "parttime_rate"
| "avg_age"
| "avg_tenure"
| "female_share";
export type GroupDimension =
| "division"
| "department"
| "team"
| "location"
| "status"
| "employment_type"
| "contract_type"
| "entry_year"
| "source"
| "paygrade";
export const MEASURE_LABELS: Record<Measure, string> = {
headcount: "Headcount",
fte: "FTE",
hires: "Eintritte",
exits: "Austritte",
avg_salary: "Ø Bruttogehalt",
parttime_rate: "Teilzeitquote",
avg_age: "Ø Alter",
avg_tenure: "Ø Zugehörigkeit",
female_share: "Frauenanteil",
};
export const GROUP_LABELS: Record<GroupDimension, string> = {
division: "Bereich",
department: "Abteilung",
team: "Team",
location: "Standort",
status: "Status",
employment_type: "Beschäftigung",
contract_type: "Vertragsart",
entry_year: "Eintrittsjahr",
source: "Intern/Extern",
paygrade: "Paygrade",
};
export const AVERAGE_MEASURES: Measure[] = ["avg_salary", "parttime_rate", "avg_age", "avg_tenure", "female_share"];
export const DATE_SCOPED_MEASURES: Measure[] = ["hires", "exits"];
export type ReportEmployee = {
id: string;
first_name: string;
last_name: string;
job_title: string;
division_id: string;
team_id: string | null;
location_id: string;
status: string;
employment_type: string;
contract_type: string;
entry_date: string;
exit_date: string | null;
weekly_hours: number;
monthly_salary_gross: number | null;
source: string;
paygrade: string;
birth_date: string;
gender: string;
};
export type OrgLookups = {
divisionName: Map<string, string>;
departmentNameByTeam: Map<string, string>;
teamName: Map<string, string>;
locationName: Map<string, string>;
};
function ageFromBirthDate(birthDate: string): number {
const d = new Date(birthDate);
const today = new Date();
let age = today.getFullYear() - d.getFullYear();
if (today.getMonth() < d.getMonth() || (today.getMonth() === d.getMonth() && today.getDate() < d.getDate())) age -= 1;
return age;
}
function tenureYears(entryDate: string, exitDate: string | null): number {
const start = new Date(entryDate);
const end = exitDate ? new Date(exitDate) : new Date();
return Math.max(0, (end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24 * 365.25));
}
export function groupKeyFor(e: ReportEmployee, dim: GroupDimension, lookups: OrgLookups): string {
switch (dim) {
case "division":
return lookups.divisionName.get(e.division_id) ?? "Unbekannt";
case "department":
return e.team_id ? (lookups.departmentNameByTeam.get(e.team_id) ?? "Unbekannt") : "";
case "team":
return e.team_id ? (lookups.teamName.get(e.team_id) ?? "Unbekannt") : "";
case "location":
return lookups.locationName.get(e.location_id) ?? "Unbekannt";
case "status":
return e.status;
case "employment_type":
return e.employment_type;
case "contract_type":
return e.contract_type;
case "entry_year":
return String(new Date(e.entry_date).getFullYear());
case "source":
return e.source;
case "paygrade":
return e.paygrade;
default:
return "Unbekannt";
}
}
export function measureValue(rows: ReportEmployee[], measure: Measure): number {
if (rows.length === 0) return 0;
switch (measure) {
case "headcount":
case "hires":
case "exits":
return rows.length;
case "fte":
return rows.reduce((s, e) => s + e.weekly_hours / 38.5, 0);
case "avg_salary": {
const withSalary = rows.filter((e) => e.monthly_salary_gross != null);
return withSalary.length ? withSalary.reduce((s, e) => s + (e.monthly_salary_gross ?? 0), 0) / withSalary.length : 0;
}
case "parttime_rate":
return (rows.filter((e) => e.employment_type === "Teilzeit").length / rows.length) * 100;
case "avg_age":
return rows.reduce((s, e) => s + ageFromBirthDate(e.birth_date), 0) / rows.length;
case "avg_tenure":
return rows.reduce((s, e) => s + tenureYears(e.entry_date, e.exit_date), 0) / rows.length;
case "female_share":
return (rows.filter((e) => e.gender === "w").length / rows.length) * 100;
default:
return 0;
}
}
export type ReportPerson = { id: string; name: string; title: string; team: string; entry_date: string };
export type ReportSplitRow = { key: string; value: number; count: number };
export type ReportRow = { key: string; value: number; count: number; people: ReportPerson[]; split?: ReportSplitRow[] };
export function aggregateReport(
employees: ReportEmployee[],
measure: Measure,
group: GroupDimension,
split: GroupDimension | null,
lookups: OrgLookups
): ReportRow[] {
const byGroup = new Map<string, ReportEmployee[]>();
for (const e of employees) {
const key = groupKeyFor(e, group, lookups);
if (!byGroup.has(key)) byGroup.set(key, []);
byGroup.get(key)!.push(e);
}
const rows: ReportRow[] = [];
for (const [key, rowsForGroup] of byGroup) {
const value = measureValue(rowsForGroup, measure);
const people: ReportPerson[] = rowsForGroup.map((e) => ({
id: e.id,
name: `${e.first_name} ${e.last_name}`,
title: e.job_title,
team: e.team_id ? (lookups.teamName.get(e.team_id) ?? "") : "",
entry_date: e.entry_date,
}));
const row: ReportRow = { key, value, count: rowsForGroup.length, people };
if (split) {
const bySplit = new Map<string, ReportEmployee[]>();
for (const e of rowsForGroup) {
const sKey = groupKeyFor(e, split, lookups);
if (!bySplit.has(sKey)) bySplit.set(sKey, []);
bySplit.get(sKey)!.push(e);
}
row.split = Array.from(bySplit.entries()).map(([sKey, sRows]) => ({
key: sKey,
value: measureValue(sRows, measure),
count: sRows.length,
}));
}
rows.push(row);
}
return rows.sort((a, b) => b.value - a.value);
}
export const REPORT_PRESETS: { name: string; measure: Measure; group: GroupDimension; split?: GroupDimension }[] = [
{ name: "Headcount nach Bereich", measure: "headcount", group: "division" },
{ name: "Frauenanteil nach Bereich", measure: "female_share", group: "division" },
{ name: "Ø Gehalt nach Paygrade", measure: "avg_salary", group: "paygrade" },
{ name: "Teilzeitquote nach Standort", measure: "parttime_rate", group: "location" },
{ name: "Eintritte nach Bereich", measure: "hires", group: "division" },
{ name: "Austritte nach Abteilung", measure: "exits", group: "department" },
];