diff --git a/actions/employees.ts b/actions/employees.ts index 20fe57c..6bb9933 100644 --- a/actions/employees.ts +++ b/actions/employees.ts @@ -84,6 +84,7 @@ export async function startKarenz(payload: { employee_id: string; karenz_start_date: string; planned_return_date: string; + absence_type: string; note?: string; }): Promise { return callRpc("start_karenz", payload, [`/employees/${payload.employee_id}`, "/employees", "/"]); diff --git a/app/(app)/employees/page.tsx b/app/(app)/employees/page.tsx index ce11b41..c03e585 100644 --- a/app/(app)/employees/page.tsx +++ b/app/(app)/employees/page.tsx @@ -42,7 +42,7 @@ export default async function EmployeesPage({ searchParams }: EmployeesPageProps let query = supabase .from("employees") .select( - "id, first_name, last_name, personnel_number, job_title, team_id, division_id, location_id, entry_date, employment_type, weekly_hours, status", + "id, first_name, last_name, personnel_number, job_title, team_id, division_id, location_id, entry_date, employment_type, weekly_hours, status, absence_type", { count: "exact" } ) .order("last_name", { ascending: true }) @@ -130,7 +130,7 @@ export default async function EmployeesPage({ searchParams }: EmployeesPageProps {e.employment_type} · {e.weekly_hours}h - + ); diff --git a/app/(app)/page.tsx b/app/(app)/page.tsx index ad09501..2e323a5 100644 --- a/app/(app)/page.tsx +++ b/app/(app)/page.tsx @@ -33,7 +33,7 @@ const DOT_STYLES: Record = { Gehaltsanpassung: "bg-warning-text", }; -const KIND_LABEL = { hire: "Eintritt", exit: "Austritt", return: "Karenz-Rückkehr" } as const; +const KIND_LABEL = { hire: "Eintritt", exit: "Austritt", return: "Rückkehr aus Abwesenheit" } as const; export default async function DashboardPage() { const supabase = await createClient(); @@ -213,7 +213,7 @@ export default async function DashboardPage() { tone: "danger", href: `/reports?mode=events&eventType=Austritt&from=${yearStart}&to=${yearEnd}`, }, - { label: "In Karenz", value: karenzCount, tone: "warning", href: "/employees?status=Karenz" }, + { label: "Langzeitabwesend", value: karenzCount, tone: "warning", href: "/employees?status=Karenz" }, { label: "Offene Positionen", value: openPositionsRes.count ?? 0, tone: "brand", href: "/positions" }, ]; diff --git a/app/api/export/employees/route.ts b/app/api/export/employees/route.ts index b6b9128..ad17ecb 100644 --- a/app/api/export/employees/route.ts +++ b/app/api/export/employees/route.ts @@ -1,4 +1,5 @@ import { NextResponse, type NextRequest } from "next/server"; +import { statusLabel } from "@/lib/absence"; import { exportFilename, exportResponseHeaders, toCsv, toXlsx, type ExportColumn } from "@/lib/export"; import { deriveStatusAsOf, parseIsoDateParam, parseStatuses, type OrgLookups } from "@/lib/reports"; import { loadDependentsCounts, loadOrgLookups, type ReportFilters } from "@/lib/reports-data"; @@ -103,12 +104,16 @@ function employeeExportColumns( { header: "C-Level", get: (e) => e.is_c_level }, { header: "Paygrade", get: (e) => e.paygrade }, { header: "Herkunft", get: (e) => e.source }, - { header: "Status", get: (e) => e.status }, + // The export shows the display name, not the raw enum value — a payroll + // hand-off saying "Karenz" for what the app calls Langzeitabwesenheit + // would just cause questions. + { header: "Status", get: (e) => statusLabel(e.status) }, + { header: "Art der Langzeitabwesenheit", get: (e) => e.absence_type }, { header: "Eintrittsdatum", get: (e) => e.entry_date, kind: "date" }, { header: "Austrittsdatum", get: (e) => e.exit_date, kind: "date" }, { header: "Austrittsgrund", get: (e) => e.exit_reason }, - { header: "Karenzbeginn", get: (e) => e.karenz_start_date, kind: "date" }, - { header: "Karenz-Rückkehrdatum", get: (e) => e.karenz_return_date, kind: "date" }, + { header: "Abwesenheit ab", get: (e) => e.karenz_start_date, kind: "date" }, + { header: "Rückkehr geplant", get: (e) => e.karenz_return_date, kind: "date" }, { header: "Anzahl Angehörige", get: (e) => dependentsCounts.get(e.id) ?? 0 }, ]; if (asOf) { diff --git a/components/audit/AuditFilters.tsx b/components/audit/AuditFilters.tsx index 96d147e..ac311a3 100644 --- a/components/audit/AuditFilters.tsx +++ b/components/audit/AuditFilters.tsx @@ -5,21 +5,24 @@ import { useEffect, useState } from "react"; import { FILTER_SELECT_CLASS } from "@/components/ui/Field"; import { SearchInput } from "@/components/ui/SearchInput"; -const ACTIONS = [ - "Neueinstellung", - "Wiedereinstellung", - "Rückkehr", - "Austritt", - "Versetzung", - "Ausschreibung", - "Interne Besetzung", - "Beförderung", - "Reorganisation", - "Reorganisation rückgängig", - "Karenz", - "Vertragsänderung", - "Stammdatenänderung", - "Gehaltsanpassung", +// The value is the string stored in audit_log.action and must not change; +// only what the user reads does — 'Karenz' is displayed as +// "Langzeitabwesenheit" (see lib/absence.ts). +const ACTIONS: { value: string; label: string }[] = [ + { value: "Neueinstellung", label: "Neueinstellung" }, + { value: "Wiedereinstellung", label: "Wiedereinstellung" }, + { value: "Rückkehr", label: "Rückkehr aus Langzeitabwesenheit" }, + { value: "Austritt", label: "Austritt" }, + { value: "Versetzung", label: "Versetzung" }, + { value: "Ausschreibung", label: "Ausschreibung" }, + { value: "Interne Besetzung", label: "Interne Besetzung" }, + { value: "Beförderung", label: "Beförderung" }, + { value: "Reorganisation", label: "Reorganisation" }, + { value: "Reorganisation rückgängig", label: "Reorganisation rückgängig" }, + { value: "Karenz", label: "Langzeitabwesenheit" }, + { value: "Vertragsänderung", label: "Vertragsänderung" }, + { value: "Stammdatenänderung", label: "Stammdatenänderung" }, + { value: "Gehaltsanpassung", label: "Gehaltsanpassung" }, ]; export function AuditFilters() { @@ -60,8 +63,8 @@ export function AuditFilters() { > {ACTIONS.map((a) => ( - ))} diff --git a/components/employees/EmployeeDetail.tsx b/components/employees/EmployeeDetail.tsx index cad1578..3101577 100644 --- a/components/employees/EmployeeDetail.tsx +++ b/components/employees/EmployeeDetail.tsx @@ -77,7 +77,7 @@ export function EmployeeDetail(props: EmployeeDetailProps) {

{fmtFullName(employee.first_name, employee.last_name, employee.title_prefix, employee.title_suffix)}

- +

{employee.job_title}

{breadcrumb}

@@ -93,7 +93,11 @@ export function EmployeeDetail(props: EmployeeDetailProps) { <> setPanel("transfer")} /> setPanel("promote")} /> - setPanel("karenz")} /> + setPanel("karenz")} + /> )} {canEditData && setPanel("daten")} />} diff --git a/components/employees/EmployeeFilters.tsx b/components/employees/EmployeeFilters.tsx index 1901157..11d22bc 100644 --- a/components/employees/EmployeeFilters.tsx +++ b/components/employees/EmployeeFilters.tsx @@ -10,13 +10,14 @@ type EmployeeFiltersProps = { locations: { id: string; name: string }[]; }; -// Aktiv and Karenz are separate statuses — somebody on Karenz is employed -// but not active. The combined entry is offered explicitly, and named after -// the two statuses it selects rather than calling the pair "aktiv". +// Aktiv and Langzeitabwesenheit are separate statuses — somebody on a +// long-term absence is employed but not active. The combined entry is +// offered explicitly, named after the two it selects rather than calling +// the pair "aktiv". The stored value is still 'Karenz' (see lib/absence.ts). const STATUS_OPTIONS = [ { value: "Aktiv", label: "Aktiv" }, - { value: "Karenz", label: "Karenz" }, - { value: "Aktiv,Karenz", label: "Aktiv + Karenz (beschäftigt)" }, + { value: "Karenz", label: "Langzeitabwesenheit" }, + { value: "Aktiv,Karenz", label: "Aktiv + Langzeitabwesenheit (beschäftigt)" }, { value: "Geplant", label: "Geplant" }, { value: "Ausgetreten", label: "Ausgetreten" }, ] as const; diff --git a/components/employees/panels/KarenzPanel.tsx b/components/employees/panels/KarenzPanel.tsx index 6fb518b..9aa06f8 100644 --- a/components/employees/panels/KarenzPanel.tsx +++ b/components/employees/panels/KarenzPanel.tsx @@ -8,6 +8,7 @@ import { SelectField, TextField, TextareaField } from "@/components/ui/Field"; import { SegmentedControl } from "@/components/ui/SegmentedControl"; import { SlideOver } from "@/components/ui/SlideOver"; import { useToast } from "@/components/ui/Toast"; +import { ABSENCE_TYPES, absenceLabel } from "@/lib/absence"; import { fmtDate } from "@/lib/format"; import type { Database } from "@/lib/supabase/types"; @@ -24,6 +25,7 @@ export function KarenzPanel({ open, onClose, employee }: { open: boolean; onClos const [karenzStart, setKarenzStart] = useState(""); const [plannedReturn, setPlannedReturn] = useState(""); + const [absenceType, setAbsenceType] = useState(ABSENCE_TYPES[0]); const [startNote, setStartNote] = useState(""); const [newReturnDate, setNewReturnDate] = useState(employee.karenz_return_date ?? ""); @@ -44,10 +46,16 @@ export function KarenzPanel({ open, onClose, employee }: { open: boolean; onClos return; } setPending(true); - const result = await startKarenz({ employee_id: employee.id, karenz_start_date: karenzStart, planned_return_date: plannedReturn, note: startNote }); + const result = await startKarenz({ + employee_id: employee.id, + karenz_start_date: karenzStart, + planned_return_date: plannedReturn, + absence_type: absenceType, + note: startNote, + }); setPending(false); if (result.success) { - showToast("Karenz erfasst."); + showToast("Langzeitabwesenheit erfasst."); router.refresh(); onClose(); } else { @@ -106,17 +114,17 @@ export function KarenzPanel({ open, onClose, employee }: { open: boolean; onClos - {/* Karenz keeps the warning tone it uses everywhere else. */} + {/* Long-term absence keeps the warning tone it uses elsewhere. */} {!isOnKarenz && ( )} {isOnKarenz && mode === "adjust" && ( @@ -134,7 +142,14 @@ export function KarenzPanel({ open, onClose, employee }: { open: boolean; onClos > {!isOnKarenz && (
- + ({ value: t, label: t }))} + /> +
@@ -153,7 +168,11 @@ export function KarenzPanel({ open, onClose, employee }: { open: boolean; onClos {mode === "adjust" && ( <> -

Aktuelles Rückkehrdatum: {fmtDate(employee.karenz_return_date)}

+

+ {absenceLabel(employee.status, employee.absence_type)} + {" · Rückkehr "} + {fmtDate(employee.karenz_return_date)} +

{diffDays !== 0 && (
0 ? "bg-warning-bg text-warning-text" : "bg-success-bg text-success-text"}`}> diff --git a/components/reports/ReportsPageClient.tsx b/components/reports/ReportsPageClient.tsx index c50ae5e..4714480 100644 --- a/components/reports/ReportsPageClient.tsx +++ b/components/reports/ReportsPageClient.tsx @@ -280,7 +280,8 @@ export function ReportsPageClient(props: ReportsPageClientProps) { )}

- Bestand wird rückgerechnet (Eintritt/Austritt/Karenz); Bereich/Team zeigen die aktuelle Zuordnung. + Bestand wird rückgerechnet (Eintritt/Austritt/Langzeitabwesenheit); Bereich/Team zeigen die aktuelle + Zuordnung.

diff --git a/components/ui/StatusChip.tsx b/components/ui/StatusChip.tsx index a2f1121..da90cf7 100644 --- a/components/ui/StatusChip.tsx +++ b/components/ui/StatusChip.tsx @@ -1,3 +1,4 @@ +import { absenceLabel } from "@/lib/absence"; import { STATUS_STYLES } from "@/lib/colors"; import { fmtDate } from "@/lib/format"; import type { EmploymentStatus } from "@/lib/supabase/types"; @@ -5,10 +6,14 @@ import type { EmploymentStatus } from "@/lib/supabase/types"; type StatusChipProps = { status: EmploymentStatus; entryDate?: string | null; // shown as "Eintritt {date}" when status is Geplant + /** Shown instead of the generic label when the kind of absence is known. */ + absenceType?: string | null; }; -export function StatusChip({ status, entryDate }: StatusChipProps) { - const label = status === "Geplant" && entryDate ? `Eintritt ${fmtDate(entryDate)}` : status; +export function StatusChip({ status, entryDate, absenceType }: StatusChipProps) { + // The stored status is still 'Karenz'; absenceLabel maps it to + // "Langzeitabwesenheit", or to the specific kind when one is recorded. + const label = status === "Geplant" && entryDate ? `Eintritt ${fmtDate(entryDate)}` : absenceLabel(status, absenceType); return ( = { + Aktiv: "Aktiv", + Karenz: "Langzeitabwesenheit", + Geplant: "Geplant", + Ausgetreten: "Ausgetreten", +}; + +export function statusLabel(status: EmploymentStatus): string { + return STATUS_LABELS[status] ?? status; +} + +/** + * The chip and the detail header show the specific kind when it is known — + * "Bildungskarenz" says more than "Langzeitabwesenheit". Absences recorded + * before the type existed have none, and fall back to the generic name + * rather than to a guess. + */ +export function absenceLabel(status: EmploymentStatus, absenceType: string | null | undefined): string { + if (status !== "Karenz") return statusLabel(status); + return isAbsenceType(absenceType) ? absenceType : STATUS_LABELS.Karenz; +} diff --git a/lib/reports.ts b/lib/reports.ts index 0794f1e..954f25e 100644 --- a/lib/reports.ts +++ b/lib/reports.ts @@ -329,14 +329,15 @@ export const EVENT_TYPE_LABELS: Record = { Eintritt: "Eintritt", Beförderung: "Beförderung", Versetzung: "Versetzung", - Karenz: "Karenz", + // Stored value stays 'Karenz'; the label follows the renamed concept. + Karenz: "Langzeitabwesenheit", Vertragsänderung: "Vertragsänderung", Stammdatenänderung: "Stammdatenänderung", Austritt: "Austritt", Wiedereintritt: "Wiedereintritt", Reorganisation: "Reorganisation", Gehaltsanpassung: "Gehaltsanpassung", - Rückkehr: "Rückkehr (Karenz)", + Rückkehr: "Rückkehr aus Langzeitabwesenheit", }; export type ReportEvent = { diff --git a/lib/supabase/types.ts b/lib/supabase/types.ts index c8507e5..672f613 100644 --- a/lib/supabase/types.ts +++ b/lib/supabase/types.ts @@ -138,6 +138,7 @@ export type Database = { exit_reason: string | null; karenz_start_date: string | null; karenz_return_date: string | null; + absence_type: string | null; avatar_color: string | null; worker_type: WorkerType; collective_agreement: CollectiveAgreement; @@ -184,6 +185,7 @@ export type Database = { exit_reason?: string | null; karenz_start_date?: string | null; karenz_return_date?: string | null; + absence_type?: string | null; avatar_color?: string | null; worker_type?: WorkerType; collective_agreement?: CollectiveAgreement; diff --git a/supabase/migrations/20260726120000_absence_type.sql b/supabase/migrations/20260726120000_absence_type.sql new file mode 100644 index 0000000..9b5d702 --- /dev/null +++ b/supabase/migrations/20260726120000_absence_type.sql @@ -0,0 +1,266 @@ +-- Long-term absence gets a type. +-- +-- "Karenz" was being used as the name for every kind of extended absence, +-- but the cases behave differently in payroll and reporting: Wochenhilfe, +-- Präsenz-/Zivildienst, a long sick leave and a sabbatical are not the same +-- thing. The UI now calls the concept "Langzeitabwesenheit" and asks which +-- kind it is. +-- +-- Deliberately NOT renaming the 'Karenz' enum value in employment_status or +-- history_event_type. Postgres can rename an enum value in place, but every +-- stored function body that spells 'Karenz' would then reference a value +-- that no longer exists — that is a dozen functions across fifteen +-- migrations, all of them rewritten for a label change. The name is a +-- presentation concern, so it is mapped to "Langzeitabwesenheit" in one +-- place in the UI (lib/absence.ts) and the stored value stays put. + +alter table employees add column if not exists absence_type text; + +alter table employees drop constraint if exists chk_absence_type; +alter table employees add constraint chk_absence_type check ( + absence_type is null or absence_type in ( + 'Wochenhilfe (Mutterschutz)', + 'Elternkarenz (inkl. Väterkarenz)', + 'Papamonat', + 'Bildungskarenz', + 'Bildungsteilzeit', + 'Präsenzdienst', + 'Zivildienst', + 'Langer Krankenstand', + 'Wiedereingliederungsteilzeit', + 'Pflegekarenz', + 'Pflegeteilzeit', + 'Familienhospizkarenz', + 'Sabbatical' + ) +); + +comment on column employees.absence_type is + 'Art der laufenden Langzeitabwesenheit; null, wenn keine besteht. Wird bei der Rückkehr geleert.'; + +-- Existing absences predate the field and their kind was never recorded, so +-- they stay null rather than being guessed at. The UI shows them as +-- "Langzeitabwesenheit" without a type until someone sets one. + +-- ── start_karenz ─────────────────────────────────────────────────── +-- Unchanged apart from carrying absence_type through both paths: written +-- straight away when the absence has already begun, or parked in the +-- pending_org_changes payload when it starts later. +create or replace function start_karenz(payload jsonb) +returns void language plpgsql as $$ +declare + v_employee_id uuid := (payload->>'employee_id')::uuid; + v_start_date date := (payload->>'karenz_start_date')::date; + v_absence_type text := nullif(payload->>'absence_type', ''); + v_name text; +begin + perform require_hr_admin(); + select first_name || ' ' || last_name into v_name from employees where id = v_employee_id; + + if v_start_date <= current_date then + update employees set status = 'Karenz', karenz_start_date = v_start_date, + karenz_return_date = (payload->>'planned_return_date')::date, + absence_type = v_absence_type + where id = v_employee_id; + else + update employees set karenz_start_date = v_start_date where id = v_employee_id; + insert into pending_org_changes (employee_id, change_type, effective_date, payload) + values (v_employee_id, 'karenz_start', v_start_date, + jsonb_build_object('planned_return_date', payload->>'planned_return_date', 'absence_type', v_absence_type)); + end if; + + insert into employee_history (employee_id, event_date, event_type, description) + values (v_employee_id, v_start_date, 'Karenz', + coalesce(v_absence_type, 'Langzeitabwesenheit') || ', geplante Rückkehr am ' || (payload->>'planned_return_date') || + case when payload->>'note' is not null and payload->>'note' <> '' then ' — ' || (payload->>'note') else '' end); + + insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details) + values (auth.uid(), current_actor_name(), 'Karenz', v_name, v_employee_id, + coalesce(v_absence_type, 'Langzeitabwesenheit') || ', geplante Rückkehr ' || (payload->>'planned_return_date')); +end; +$$; + +-- ── record_karenz_return ─────────────────────────────────────────── +-- Clears absence_type alongside the dates: the absence is over, so leaving +-- its kind behind would make a returned employee look like they were still +-- on one. +create or replace function record_karenz_return(payload jsonb) +returns void language plpgsql as $$ +declare + v_employee_id uuid := (payload->>'employee_id')::uuid; + v_return_date date := (payload->>'return_date')::date; + v_name text; + v_team_id uuid; + v_division_id uuid; + v_is_lead boolean; + v_manager uuid; + v_employment_type employment_type; + v_weekly_hours numeric; + v_karenz_start date; + v_absence_type text; +begin + perform require_hr_admin(); + select first_name || ' ' || last_name, team_id, division_id, is_lead, karenz_start_date, absence_type + into v_name, v_team_id, v_division_id, v_is_lead, v_karenz_start, v_absence_type + from employees where id = v_employee_id; + + if v_karenz_start is not null and v_return_date <= v_karenz_start then + raise exception 'Das Rückkehrdatum muss nach dem Beginn der Langzeitabwesenheit (%) liegen.', v_karenz_start; + end if; + + if payload->>'employment_mode' = 'Vollzeit' then + v_employment_type := 'Vollzeit'; v_weekly_hours := 38.5; + elsif payload->>'employment_mode' = 'Teilzeit' then + v_employment_type := 'Teilzeit'; v_weekly_hours := (payload->>'weekly_hours')::numeric; + end if; + + if v_return_date <= current_date then + v_manager := resolve_manager_for(v_team_id, v_is_lead, v_division_id); + update employees set + status = 'Aktiv', + karenz_return_date = null, + karenz_start_date = null, + absence_type = null, + manager_id = v_manager, + employment_type = coalesce(v_employment_type, employment_type), + weekly_hours = coalesce(v_weekly_hours, weekly_hours) + where id = v_employee_id; + else + update employees set karenz_return_date = v_return_date where id = v_employee_id; + insert into pending_org_changes (employee_id, change_type, effective_date, payload) + values (v_employee_id, 'karenz_return', v_return_date, + jsonb_build_object('employment_type', v_employment_type, 'weekly_hours', v_weekly_hours)); + end if; + + insert into employee_history (employee_id, event_date, event_type, description) + values (v_employee_id, v_return_date, 'Rückkehr', + 'Rückkehr aus ' || coalesce(v_absence_type, 'Langzeitabwesenheit') || ' am ' || (payload->>'return_date')); + + insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details) + values (auth.uid(), current_actor_name(), 'Rückkehr', v_name, v_employee_id, 'Rückkehr am ' || (payload->>'return_date')); +end; +$$; + +-- ── apply_due_pending_changes ────────────────────────────────────── +-- Only the two karenz branches change; the rest of the body is carried over +-- unchanged from 20260718160000_dependents_effective_dating.sql. +create or replace function apply_due_pending_changes() +returns int language plpgsql security definer set search_path = public as $$ +declare + v_rec record; + v_count int := 0; + v_manager uuid; + v_team_id uuid; + v_division_id uuid; + v_is_lead boolean; +begin + for v_rec in + select * from pending_org_changes + where status = 'pending' and effective_date <= current_date + order by effective_date, created_at + loop + if v_rec.change_type = 'transfer' then + select is_lead into v_is_lead from employees where id = v_rec.employee_id; + select division_id into v_division_id from teams t + join departments d on d.id = t.department_id + where t.id = (v_rec.payload->>'new_team_id')::uuid; + v_manager := resolve_manager_for((v_rec.payload->>'new_team_id')::uuid, v_is_lead, v_division_id); + update employees set + team_id = (v_rec.payload->>'new_team_id')::uuid, + manager_id = v_manager, + job_title = coalesce(v_rec.payload->>'new_title', job_title) + where id = v_rec.employee_id; + + elsif v_rec.change_type = 'promotion' then + update employees set + job_title = coalesce(v_rec.payload->>'new_title', job_title), + paygrade = coalesce((v_rec.payload->>'new_paygrade')::paygrade_type, paygrade) + where id = v_rec.employee_id; + + elsif v_rec.change_type = 'karenz_start' then + update employees set + status = 'Karenz', + karenz_return_date = (v_rec.payload->>'planned_return_date')::date, + absence_type = coalesce(nullif(v_rec.payload->>'absence_type', ''), absence_type) + where id = v_rec.employee_id; + + elsif v_rec.change_type = 'karenz_return' then + select team_id, division_id, is_lead into v_team_id, v_division_id, v_is_lead + from employees where id = v_rec.employee_id; + v_manager := resolve_manager_for(v_team_id, v_is_lead, v_division_id); + update employees set + status = 'Aktiv', + karenz_return_date = null, + karenz_start_date = null, + absence_type = null, + manager_id = v_manager, + employment_type = coalesce((v_rec.payload->>'employment_type')::employment_type, employment_type), + weekly_hours = coalesce((v_rec.payload->>'weekly_hours')::numeric, weekly_hours) + where id = v_rec.employee_id; + + elsif v_rec.change_type = 'contract_change' then + update employees set + first_name = coalesce(v_rec.payload->'person'->>'first_name', first_name), + last_name = coalesce(v_rec.payload->'person'->>'last_name', last_name), + gender = coalesce((v_rec.payload->'person'->>'gender')::gender_type, gender), + birth_date = coalesce((v_rec.payload->'person'->>'birth_date')::date, birth_date), + sv_nummer = coalesce(v_rec.payload->'person'->>'sv_nummer', sv_nummer), + nationality = coalesce(v_rec.payload->'person'->>'nationality', nationality), + address = coalesce(v_rec.payload->'person'->>'address', address), + postal_code = coalesce(v_rec.payload->'person'->>'postal_code', postal_code), + city = coalesce(v_rec.payload->'person'->>'city', city), + address_country = coalesce(v_rec.payload->'person'->>'address_country', address_country), + email = coalesce(v_rec.payload->'person'->>'email', email), + phone = coalesce(v_rec.payload->'person'->>'phone', phone), + title_prefix = coalesce( + case when v_rec.payload->'person' ? 'title_prefix' + then array(select jsonb_array_elements_text(v_rec.payload->'person'->'title_prefix')) end, title_prefix), + title_suffix = coalesce( + case when v_rec.payload->'person' ? 'title_suffix' + then array(select jsonb_array_elements_text(v_rec.payload->'person'->'title_suffix')) end, title_suffix), + employment_type = coalesce((v_rec.payload->'contract'->>'employment_type')::employment_type, employment_type), + weekly_hours = coalesce((v_rec.payload->'contract'->>'weekly_hours')::numeric, weekly_hours), + contract_type = coalesce((v_rec.payload->'contract'->>'contract_type')::contract_type, contract_type), + contract_end_date = case + when v_rec.payload->'contract' ? 'contract_end_date' + then nullif(v_rec.payload->'contract'->>'contract_end_date', '')::date + else contract_end_date end, + worker_type = coalesce((v_rec.payload->'role'->>'worker_type')::worker_type, worker_type), + collective_agreement = coalesce((v_rec.payload->'role'->>'collective_agreement')::collective_agreement, collective_agreement), + work_days = coalesce( + case when v_rec.payload->'role' ? 'work_days' + then array(select jsonb_array_elements_text(v_rec.payload->'role'->'work_days'))::weekday[] end, work_days), + is_betriebsrat = coalesce((v_rec.payload->'role'->>'is_betriebsrat')::boolean, is_betriebsrat), + has_dienstwagen = coalesce((v_rec.payload->'role'->>'has_dienstwagen')::boolean, has_dienstwagen), + is_laterale_fuehrung = coalesce((v_rec.payload->'role'->>'is_laterale_fuehrung')::boolean, is_laterale_fuehrung), + is_c_level = coalesce((v_rec.payload->'role'->>'is_c_level')::boolean, is_c_level) + where id = v_rec.employee_id; + + elsif v_rec.change_type = 'reorg' then + select is_lead into v_is_lead from employees where id = v_rec.employee_id; + select division_id into v_division_id from teams t + join departments d on d.id = t.department_id + where t.id = (v_rec.payload->>'target_team_id')::uuid; + v_manager := resolve_manager_for((v_rec.payload->>'target_team_id')::uuid, v_is_lead, v_division_id); + update employees set team_id = (v_rec.payload->>'target_team_id')::uuid, manager_id = v_manager + where id = v_rec.employee_id; + + elsif v_rec.change_type = 'dependent_add' then + insert into employee_dependents (employee_id, first_name, last_name, relationship, sv_nummer, birth_date) + values ( + v_rec.employee_id, v_rec.payload->>'first_name', v_rec.payload->>'last_name', + (v_rec.payload->>'relationship')::relationship_type, + nullif(v_rec.payload->>'sv_nummer', ''), (v_rec.payload->>'birth_date')::date + ); + + elsif v_rec.change_type = 'dependent_remove' then + delete from employee_dependents where id = (v_rec.payload->>'dependent_id')::uuid; + end if; + + update pending_org_changes set status = 'applied', applied_at = now() where id = v_rec.id; + v_count := v_count + 1; + end loop; + + return v_count; +end; +$$; diff --git a/supabase/seed.ts b/supabase/seed.ts index f5b85a2..c22ce30 100644 --- a/supabase/seed.ts +++ b/supabase/seed.ts @@ -11,6 +11,7 @@ import { randomUUID } from "node:crypto"; // Explicit .ts extension: this file is run directly by Node (type-stripping, // ESM), where an extensionless relative import does not resolve. import { svnrCheckDigit } from "../lib/svnr.ts"; +import { ABSENCE_TYPES } from "../lib/absence.ts"; const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL; const SERVICE_ROLE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY; @@ -344,7 +345,9 @@ type EmployeeRow = { entry_date: string; exit_date: string | null; exit_reason: string | null; + karenz_start_date: string | null; karenz_return_date: string | null; + absence_type: string | null; }; type HistoryRow = { @@ -460,7 +463,9 @@ function finalizeEmployee(base: ReturnType, opts: { paygrade entry_date: isoDate(entryDate), exit_date: null, exit_reason: null, + karenz_start_date: null, karenz_return_date: null, + absence_type: null, }; history.push({ @@ -578,19 +583,23 @@ for (let i = 0; i < 40 && cursor < shuffledIcs.length; i++, cursor++) { history.push({ employee_id: e.id, event_date: e.exit_date, event_type: "Austritt", description: `Austritt (${e.exit_reason})` }); } -// ~12 Karenz +// ~12 Langzeitabwesenheiten, über die Arten gestreut statt alle als Karenz — +// die Auswertung nach Art ist sonst nicht zu sehen. for (let i = 0; i < 12 && cursor < shuffledIcs.length; i++, cursor++) { const e = shuffledIcs[cursor]; const entryDate = new Date(e.entry_date); const karenzStart = randomDateBetween(addDays(entryDate, 180), addDays(TODAY, -10)); const returnDate = addDays(TODAY, randInt(10, 300)); + const absenceType = pick(ABSENCE_TYPES); e.status = "Karenz"; + e.karenz_start_date = isoDate(karenzStart); e.karenz_return_date = isoDate(returnDate); + e.absence_type = absenceType; history.push({ employee_id: e.id, event_date: isoDate(karenzStart), event_type: "Karenz", - description: `Karenzantritt, geplante Rückkehr am ${isoDate(returnDate)}`, + description: `${absenceType}, geplante Rückkehr am ${isoDate(returnDate)}`, }); } diff --git a/tests/unit/absence.test.ts b/tests/unit/absence.test.ts new file mode 100644 index 0000000..9ad5e07 --- /dev/null +++ b/tests/unit/absence.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "vitest"; +import { ABSENCE_TYPES, absenceLabel, isAbsenceType, statusLabel } from "@/lib/absence"; + +// The stored employment status is still 'Karenz' — renaming the enum value +// would mean rewriting every stored function that spells it. The rename +// therefore lives entirely in this mapping, which makes it the one thing +// standing between the database value and what an HR user reads. +describe("statusLabel", () => { + it("renders the stored 'Karenz' value as Langzeitabwesenheit", () => { + expect(statusLabel("Karenz")).toBe("Langzeitabwesenheit"); + }); + + it("leaves the other statuses alone", () => { + expect(statusLabel("Aktiv")).toBe("Aktiv"); + expect(statusLabel("Geplant")).toBe("Geplant"); + expect(statusLabel("Ausgetreten")).toBe("Ausgetreten"); + }); +}); + +describe("absenceLabel", () => { + it("shows the specific kind when one is recorded", () => { + expect(absenceLabel("Karenz", "Bildungskarenz")).toBe("Bildungskarenz"); + expect(absenceLabel("Karenz", "Präsenzdienst")).toBe("Präsenzdienst"); + }); + + it("falls back to the generic name for absences recorded before the field existed", () => { + expect(absenceLabel("Karenz", null)).toBe("Langzeitabwesenheit"); + expect(absenceLabel("Karenz", "")).toBe("Langzeitabwesenheit"); + }); + + it("ignores a type that is not on the list rather than displaying it", () => { + // The column has a check constraint, but the value arrives here as a + // plain string — echoing an unknown one would put unvalidated text in + // the status chip. + expect(absenceLabel("Karenz", "Ausgedachte Karenz")).toBe("Langzeitabwesenheit"); + }); + + it("ignores the absence type entirely for any other status", () => { + expect(absenceLabel("Aktiv", "Sabbatical")).toBe("Aktiv"); + expect(absenceLabel("Ausgetreten", "Papamonat")).toBe("Ausgetreten"); + }); +}); + +describe("ABSENCE_TYPES", () => { + it("holds the thirteen kinds, in the order they are offered", () => { + expect(ABSENCE_TYPES).toHaveLength(13); + expect(ABSENCE_TYPES[0]).toBe("Wochenhilfe (Mutterschutz)"); + expect(ABSENCE_TYPES.at(-1)).toBe("Sabbatical"); + }); + + it("guards every entry with isAbsenceType", () => { + for (const t of ABSENCE_TYPES) expect(isAbsenceType(t)).toBe(true); + expect(isAbsenceType("Karenz")).toBe(false); + expect(isAbsenceType(null)).toBe(false); + }); +});