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.
This commit is contained in:
2026-07-24 23:38:10 +02:00
parent f96773da0f
commit 79f0e19bf8
101 changed files with 6120 additions and 700 deletions

96
docs/data-model.md Normal file
View File

@@ -0,0 +1,96 @@
# Datenmodell
Beschreibt das tatsächliche Supabase-Schema (siehe `supabase/migrations/`),
nicht ein generisches HR-Schema. Quelle der Wahrheit sind immer die
Migrationen; dieses Dokument ist eine lesbare Zusammenfassung und wird bei
strukturellen Änderungen mitgepflegt.
## Grundprinzipien
- **Person ist nicht Position.** `employees` (Personen) und `positions`
(Planstellen/Ausschreibungen) sind getrennte Tabellen. Eine Position wird
bei Einstellung mit einer Person verknüpft (`filled_by_employee_id`),
existiert aber unabhängig davon (offene Ausschreibung).
- **History ist append-only.** `employee_history` (Ereignisse pro Person)
und `audit_log` (systemweit, wer hat was wann geändert) haben keine
Update-/Delete-Policy — RLS erlaubt nur `select`/`insert`. Korrekturen
erfolgen durch einen neuen, kompensierenden Eintrag, nie durch Ändern der
Historie (siehe `undo_reorg`, das eine "Reorganisation rückgängig"-Zeile
anhängt statt die ursprünglichen Zeilen zu löschen).
- **Audit-Log ist Pflicht bei Änderungen — und lebt in der Datenbank, nicht
im App-Code.** Jede mutierende SQL-Funktion (`hire_employee`,
`change_employee_data`, `add_employee_dependent`, `add_employee_note`, …)
schreibt ihren `audit_log`-Eintrag in derselben Transaktion wie die
eigentliche Änderung. Das ist bewusst atomar: ein fehlgeschlagener
Audit-Insert lässt die ganze Transaktion fehlschlagen, statt still eine
Änderung ohne Log zu hinterlassen. Es gibt keinen App-seitigen
`writeAuditLog()`-Helper und es sollte auch keinen geben — das würde eine
zweite, nicht-atomare Logging-Quelle neben der bestehenden schaffen.
- **Service-Role-Zugriff ist server-only.** `lib/supabase/admin.ts` ist die
einzige Stelle, die den Service-Role-Key verwendet; `import "server-only"`
macht einen versehentlichen Client-Import zu einem Build-Fehler. Alles
andere läuft über den anon key + RLS.
- **RLS ist bereits aktiv**, nicht nur für die Produktion vorgemerkt: jede
Tabelle hat `enable row level security` plus mindestens eine Policy
(siehe unten). Zusätzlich existieren explizite `grant`-Statements für
`anon`/`authenticated`/`service_role`
(`20260714120500_default_grants.sql`) — ohne die schlägt jede Query auch
mit korrekter RLS-Policy mit "permission denied" fehl, weil Postgres
Objekt-Rechte unabhängig von RLS prüft.
## Zugriffsmodell
Ein einziges Rollenmodell, kein Mehrfach-Rollen-System:
- `profiles.role` ist per Check-Constraint auf den einzigen Wert `'hr'`
fixiert (Migration `20260714120000_hr_only_access.sql`).
- `profiles.is_active` (default `false`) muss zusätzlich wahr sein.
- Die SQL-Funktion `is_hr_user()` (SECURITY DEFINER, vermeidet RLS-Rekursion
auf `profiles`) prüft beides und gated praktisch jede Policy im Schema.
- `proxy.ts` (Next.js Proxy, ehem. Middleware) spiegelt dieselbe Prüfung auf
App-Ebene: nicht eingeloggt → `/login`; eingeloggt aber nicht aktive
HR-Person → `/login` mit Fehlermeldung. Das ist bewusst nur "defense in
depth" — die eigentliche Schranke ist RLS, nicht die UI-Prüfung.
- Es gibt **keine** granulareren Rollen (kein `hr_admin`/`read_only`/
`it_admin`-Split o. Ä.) und aktuell keinen zweiten Anwendungsfall dafür.
Sollte das nötig werden, ist der richtige Ansatz eine neue Migration, die
`is_hr_user()` um echte Rollenspalten erweitert — nicht ein
App-seitiges Rollenmodell, das der DB-Policy-Ebene nicht entspricht.
## Kernentitäten
| Tabelle | Zweck |
|---|---|
| `divisions` / `departments` / `teams` | Org-Hierarchie ("Bereich" 20xx / "Abteilung" 21xx / "Team" 22xx), je mit eindeutiger `org_number`. |
| `locations` | Standorte, an ein Land gebunden (steuert die Standort-Picklist im UI). |
| `profiles` | Ein Datensatz pro Supabase-Auth-User; Rolle + Aktivierungsstatus (siehe oben). |
| `employees` | Zentrale Personentabelle: Stammdaten, Vertrag (Vollzeit/Teilzeit, befristet/unbefristet), Org-Zuordnung, Status (`Aktiv`/`Karenz`/`Geplant`/`Ausgetreten`), Rolle & Anstellung (Angestellte:r/Arbeiter:in, Kollektivvertrag, Arbeitstage, Betriebsrat/Dienstwagen/laterale Führung/C-Level-Flags), akademische Titel (Prefix/Suffix-Arrays). |
| `employee_history` | Append-only Ereignis-Timeline pro Person (fester Enum: Eintritt, Beförderung, Versetzung, Karenz, Vertragsänderung, Stammdatenänderung, Austritt, Wiedereintritt, Reorganisation, Gehaltsanpassung, Rückkehr). |
| `employee_dependents` | Angehörige (Ehepartner:in/Lebenspartner:in/Kind/Sonstige) je Mitarbeiter:in; Edit = Löschen + Neuanlage, kein In-place-Update. |
| `employee_notes` | HR-Notizen je Mitarbeiter:in, add-only, mit optionalem "Wiedervorlage am"-Datum. Bewusst nicht autor-gescoped — jede aktive HR-Person sieht jede offene Notiz ("Meine Notizen" ist ein geteiltes Postfach, kein persönliches). |
| `positions` | Planstellen mit eindeutiger `position_number` (^6\d{7}$), Status `open`/`filled`, `valid_from`-Gültigkeitsfenster. |
| `hire_drafts` | Fortsetzbarer Zwischenstand des Neueinstellungs-Wizards (JSONB-Payload), eigentümer-gescoped. |
| `saved_reports` | Gespeicherte Report-Konfigurationen, eigentümer-gescoped. |
| `pending_org_changes` | Effective-dated (zukünftig wirksame) Änderungen — Versetzung/Beförderung/Karenz-Start/-Rückkehr/Vertragsänderung/Reorg — die erst am `effective_date` angewendet werden. Wird von `apply_due_pending_changes()` verarbeitet, aufgerufen vom Cron-Route-Handler. Entspricht dem, was in generischen HR-Schemata oft "planned_changes" heißt. |
| `audit_log` | Systemweiter, unveränderlicher Audit-Trail (wer/wann/was/an wem). Wird ausschließlich von SQL-Funktionen beschrieben, nie direkt aus der App. |
| `reorg_scenarios` / `reorg_moves` | Persistierte Reorg-Pläne inkl. `undo_snapshot` (Pre-Change-Zustand für die Rückgängig-Funktion). |
## Cron / effective-dated changes
`apply_due_pending_changes()` (SQL, `SECURITY DEFINER`) ist die einzige
Funktion, deren Ausführungsrecht explizit auf `service_role` beschränkt ist
(`revoke ... from public, anon, authenticated; grant ... to service_role`).
Sie wird von `app/api/cron/apply-pending-changes/route.ts` aufgerufen —
täglich per Vercel Cron (`vercel.json`), außerhalb von Vercel per
Ersatz-Scheduler (siehe `DEPLOYMENT.md`, Docker-Cron-Sidecar). Die Route
selbst authentifiziert per `CRON_SECRET`-Bearer-Token, nicht per
Supabase-Session — es gibt keine anfragende Person, nur den Scheduler.
Idempotenz: `pending_org_changes.status` läuft `pending``applied` (oder
`cancelled` bei Reorg-Undo); die Auswahl-Query filtert immer auf
`status = 'pending'`, ein zweiter Lauf wirkt daher auf bereits angewendete
Einträge nicht erneut.
## Bekannte Lücken vor Produktivbetrieb
Siehe README.md → "Known TODOs" für den aktuellen Stand.