Files
alpenwerk-hr/app/(app)/page.tsx
Maximilian Stubhan 79f0e19bf8 Org assignment history, mobile support, and a correctness pass
Data model
- employee_assignments records org placement over time (valid_from/valid_to),
  written by a trigger on `employees` rather than inside each RPC: ~70
  `update employees` statements spread over fifteen migrations mean per-call
  bookkeeping would miss paths today and again with every future RPC. A
  partial unique index enforces the one-open-interval invariant the trigger
  relies on when closing the current row.
- The Organigramm gains a Stichtag (default today). Membership comes from
  entry/exit/karenz, past placement from the new history, future placement
  projected from pending_org_changes. Placements predating the migration are
  backfilled with today's values and flagged as such in the UI, since
  employee_history only ever stored free text and cannot be reconstructed.

Correctness
- Reports and exports silently truncated at PostgREST's 1000-row cap
  (db.max_rows); employee_history is already past it at ~800 staff. Every
  whole-table read now pages explicitly.
- XLSX date cells were a day early: ExcelJS converts a Date to an Excel
  serial straight off getTime(), so a Date built at local midnight lands on
  the previous day's serial in any positive-offset zone.
- Date handling is pinned to Europe/Vienna throughout, and date-only strings
  are formatted without a Date round-trip. The dashboard's YTD window was
  built by round-tripping a local Date through toISOString(), which shifted
  it a day early and dropped 31 December entirely.
- Export routes parsed measure/group/split/eventType with unchecked `as`
  casts, so an unknown value reached column headers as `undefined` and the
  Content-Disposition filename. Parsed against the label maps now, with the
  filename slugged as a backstop.
- toXlsx keyed columns by header text, silently dropping the second of any
  two columns sharing a name — split columns take their header from data.
- The org chart tree walks had no cycle guard; nothing in the schema forbids
  a manager_id cycle, and one would hang the tab rather than misreport.
- The login page reflected ?error= verbatim, letting anyone put arbitrary
  text on the real sign-in screen; messages are looked up by code now.
- React Flow needs elementsSelectable on, or it sets pointer-events:none on
  the whole node and the expand control stops responding.

UI
- Mobile: the shell was unusable below lg — a fixed 236px margin pushed
  content off-screen with no mobile navigation at all. The sidebar is now a
  drawer, dvh replaces vh, safe-area insets are honoured, inputs are 16px so
  iOS stops zooming on focus, and form grids stack.
- Org chart nodes redesigned: per-kind accent stripes and icons, vacant
  roles called out, expand control moved to the bottom edge carrying the
  child count.
- Pagination is windowed; it previously rendered one link per page (54 for
  the employee list, unbounded for the audit log).
- Positions page reduced to open positions with a single "Besetzen" action.
- The employee Organisation tab links into the org chart focused on that
  person, reusing the chart's existing search-match highlighting.

Also included, uncommitted until now
- Dependants, HR notes, academic titles, split address fields, position
  validity and role/employment fields, with their migrations and UI.
- Docker/compose deployment setup, data-model and security-review docs.
2026-07-24 23:38:10 +02:00

237 lines
9.6 KiB
TypeScript

import Link from "next/link";
import { DraftsCard } from "@/components/dashboard/DraftsCard";
import { actionBadgeStyle } from "@/lib/colors";
import { addDaysIso, fmtDate, todayIso } from "@/lib/format";
import { createClient } from "@/lib/supabase/server";
import { fetchAllRows } from "@/lib/supabase/query";
const TONE_TEXT: Record<string, string> = {
default: "text-ink",
success: "text-success-text",
danger: "text-danger-text",
warning: "text-warning-text",
brand: "text-brand-700",
};
const DOT_STYLES: Record<string, string> = {
Eintritt: "bg-success-text",
Wiedereintritt: "bg-success-text",
Rückkehr: "bg-success-text",
Austritt: "bg-danger-text",
Versetzung: "bg-info-text",
Beförderung: "bg-purple-text",
Reorganisation: "bg-purple-text",
Karenz: "bg-warning-text",
Vertragsänderung: "bg-warning-text",
Stammdatenänderung: "bg-warning-text",
Gehaltsanpassung: "bg-warning-text",
};
const KIND_LABEL = { hire: "Eintritt", exit: "Austritt", return: "Karenz-Rückkehr" } as const;
export default async function DashboardPage() {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
const { data: drafts } = user
? await supabase
.from("hire_drafts")
.select("id, step, payload, updated_at")
.eq("created_by", user.id)
.order("updated_at", { ascending: false })
: { data: [] };
// Built as strings, not by round-tripping a local Date through
// toISOString(): in any positive-offset zone new Date(year, 0, 1) is still
// the previous year in UTC, which shifted the whole YTD window a day early
// and dropped 31 December from it entirely.
const today = todayIso();
const year = today.slice(0, 4);
const yearStart = `${year}-01-01`;
const yearEnd = `${year}-12-31`;
const in60Iso = addDaysIso(today, 60);
const [
activeCountRes,
karenzCountRes,
hiresYtdRes,
exitsYtdRes,
openPositionsRes,
fteRows,
divisionsRes,
headcountRows,
upcomingHiresRes,
upcomingExitsRes,
upcomingReturnsRes,
historyRes,
] = await Promise.all([
supabase.from("employees").select("id", { count: "exact", head: true }).in("status", ["Aktiv", "Karenz"]),
supabase.from("employees").select("id", { count: "exact", head: true }).eq("status", "Karenz"),
supabase
.from("employees")
.select("id", { count: "exact", head: true })
.gte("entry_date", yearStart)
.lte("entry_date", yearEnd),
supabase
.from("employees")
.select("id", { count: "exact", head: true })
.gte("exit_date", yearStart)
.lte("exit_date", yearEnd),
supabase.from("positions").select("id", { count: "exact", head: true }).eq("status", "open"),
fetchAllRows(() => supabase.from("employees").select("weekly_hours").in("status", ["Aktiv", "Karenz"]).order("id")),
supabase.from("divisions").select("id, name"),
fetchAllRows(() => supabase.from("employees").select("division_id").in("status", ["Aktiv", "Karenz"]).order("id")),
supabase
.from("employees")
.select("id, first_name, last_name, entry_date")
.eq("status", "Geplant")
.gte("entry_date", today)
.lte("entry_date", in60Iso),
supabase
.from("employees")
.select("id, first_name, last_name, exit_date")
.not("exit_date", "is", null)
.gte("exit_date", today)
.lte("exit_date", in60Iso),
supabase
.from("employees")
.select("id, first_name, last_name, karenz_return_date")
.eq("status", "Karenz")
.not("karenz_return_date", "is", null)
.gte("karenz_return_date", today)
.lte("karenz_return_date", in60Iso),
supabase
.from("employee_history")
.select("id, employee_id, event_date, event_type, description")
.order("event_date", { ascending: false })
.order("created_at", { ascending: false })
.limit(10),
]);
const fte = fteRows.reduce((sum, row) => sum + Number(row.weekly_hours), 0) / 38.5;
const headcountByDivision = new Map<string, number>();
for (const row of headcountRows) {
if (!row.division_id) continue;
headcountByDivision.set(row.division_id, (headcountByDivision.get(row.division_id) ?? 0) + 1);
}
const divisionBars = (divisionsRes.data ?? [])
.map((d) => ({ name: d.name, count: headcountByDivision.get(d.id) ?? 0 }))
.sort((a, b) => b.count - a.count);
const maxDivisionCount = Math.max(1, ...divisionBars.map((d) => d.count));
type UpcomingItem = { id: string; label: string; date: string; kind: keyof typeof KIND_LABEL };
const upcoming: UpcomingItem[] = [
...(upcomingHiresRes.data ?? []).map((e) => ({
id: e.id,
label: `${e.first_name} ${e.last_name}`,
date: e.entry_date,
kind: "hire" as const,
})),
...(upcomingExitsRes.data ?? []).map((e) => ({
id: e.id,
label: `${e.first_name} ${e.last_name}`,
date: e.exit_date!,
kind: "exit" as const,
})),
...(upcomingReturnsRes.data ?? []).map((e) => ({
id: e.id,
label: `${e.first_name} ${e.last_name}`,
date: e.karenz_return_date!,
kind: "return" as const,
})),
]
.sort((a, b) => a.date.localeCompare(b.date))
.slice(0, 8);
const historyEmployeeIds = Array.from(new Set((historyRes.data ?? []).map((h) => h.employee_id)));
const historyEmployeesRes = historyEmployeeIds.length
? await supabase.from("employees").select("id, first_name, last_name").in("id", historyEmployeeIds)
: { data: [] as { id: string; first_name: string; last_name: string }[] };
const employeeNameById = new Map((historyEmployeesRes.data ?? []).map((e) => [e.id, `${e.first_name} ${e.last_name}`]));
const kpis = [
{ label: "Aktive Mitarbeiter:innen", value: activeCountRes.count ?? 0, tone: "default" },
{ label: "FTE", value: fte.toFixed(1), tone: "default" },
{ label: "Eintritte (Jahr)", value: hiresYtdRes.count ?? 0, tone: "success" },
{ label: "Austritte (Jahr)", value: exitsYtdRes.count ?? 0, tone: "danger" },
{ label: "In Karenz", value: karenzCountRes.count ?? 0, tone: "warning" },
{ label: "Offene Positionen", value: openPositionsRes.count ?? 0, tone: "brand" },
];
return (
<div className="flex flex-col gap-6">
{drafts && drafts.length > 0 && <DraftsCard drafts={drafts} />}
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-6">
{kpis.map((kpi) => (
<div key={kpi.label} className="rounded border border-border bg-white p-4">
<div className="text-xs font-semibold uppercase tracking-wide text-ink-muted">{kpi.label}</div>
<div className={`mt-2 text-2xl font-extrabold ${TONE_TEXT[kpi.tone]}`}>{kpi.value}</div>
</div>
))}
</div>
<div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
<div className="rounded border border-border bg-white p-4">
<h2 className="mb-3 text-sm font-bold text-ink">Headcount nach Bereich</h2>
<div className="flex flex-col gap-2">
{divisionBars.map((d) => (
<div key={d.name}>
<div className="mb-0.5 flex justify-between text-xs text-ink-body">
<span>{d.name}</span>
<span className="font-semibold">{d.count}</span>
</div>
<div className="h-2 rounded bg-surface">
<div className="h-2 rounded bg-brand-500" style={{ width: `${(d.count / maxDivisionCount) * 100}%` }} />
</div>
</div>
))}
{divisionBars.length === 0 && <p className="text-sm text-ink-muted">Keine Daten vorhanden.</p>}
</div>
</div>
<div className="rounded border border-border bg-white p-4">
<h2 className="mb-3 text-sm font-bold text-ink">Anstehend (60 Tage)</h2>
<ul className="flex flex-col divide-y divide-border">
{upcoming.map((item) => (
<li key={`${item.kind}-${item.id}`}>
<Link
href={`/employees/${item.id}`}
className="flex items-center justify-between py-2 text-sm hover:text-brand-700"
>
<span>
<span className="font-semibold text-ink">{item.label}</span>
<span className="ml-2 text-xs text-ink-muted">{KIND_LABEL[item.kind]}</span>
</span>
<span className="text-ink-muted">{fmtDate(item.date)}</span>
</Link>
</li>
))}
{upcoming.length === 0 && <p className="py-2 text-sm text-ink-muted">Keine anstehenden Ereignisse.</p>}
</ul>
</div>
<div className="rounded border border-border bg-white p-4">
<h2 className="mb-3 text-sm font-bold text-ink">Letzte Aktivitäten</h2>
<ul className="flex flex-col divide-y divide-border">
{(historyRes.data ?? []).map((h) => (
<li key={h.id} className="py-2">
<div className="flex items-center gap-2">
<span className={`inline-block h-2 w-2 shrink-0 rounded-full ${DOT_STYLES[h.event_type] ?? "bg-ink-muted"}`} />
<span className="text-sm font-semibold text-ink">{employeeNameById.get(h.employee_id) ?? "Unbekannt"}</span>
<span className={`rounded-full px-2 py-0.5 text-xs font-semibold ${actionBadgeStyle(h.event_type)}`}>
{h.event_type}
</span>
</div>
<p className="mt-1 text-xs text-ink-muted">{h.description}</p>
</li>
))}
{(historyRes.data ?? []).length === 0 && <p className="py-2 text-sm text-ink-muted">Keine Aktivitäten vorhanden.</p>}
</ul>
</div>
</div>
</div>
);
}