Rename Karenz to Langzeitabwesenheit and record its type

Karenz was doing duty as the name for every kind of extended absence, but
the cases behave differently in payroll and reporting — Wochenhilfe, a
Präsenzdienst, a long sick leave and a sabbatical are not the same thing.
The concept is now called Langzeitabwesenheit and carries which kind it is.

- employees.absence_type, constrained to the thirteen kinds. start_karenz
  stores it on both paths (written straight away, or parked in the
  pending_org_changes payload when the absence starts later);
  record_karenz_return and the karenz_return branch of
  apply_due_pending_changes clear it, so a returned employee does not keep
  looking like they are still away. It also reaches employee_history, the
  audit log and the employee export.
- The status enum value stays 'Karenz'. Postgres can rename an enum value in
  place, but every stored function body that spells it would then reference
  a value that no longer exists — a dozen functions across fifteen
  migrations, rewritten for a label. The mapping lives in lib/absence.ts
  instead, which is the single place the UI reads the display name from.
- Where a kind is recorded the chip shows it — "Bildungskarenz" says more
  than "Langzeitabwesenheit". Absences predating the field have none and
  fall back to the generic name rather than to a guess, and a value outside
  the list is dropped rather than echoed into the UI.
- The export prints the display name, not the raw enum: a payroll hand-off
  reading "Karenz" for what the app calls Langzeitabwesenheit only causes
  questions. Audit filter options keep their stored values and change only
  their labels.
- The seed spreads the twelve absences across the kinds; all of them being
  Karenz would leave any breakdown by kind invisible.
This commit is contained in:
2026-07-25 14:34:28 +02:00
parent 37bb107cd4
commit 8282d7f581
16 changed files with 471 additions and 45 deletions

View File

@@ -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<ActionResult> {
return callRpc("start_karenz", payload, [`/employees/${payload.employee_id}`, "/employees", "/"]);

View File

@@ -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} · <span className="tabular-nums">{e.weekly_hours}h</span>
</td>
<td className="px-4 py-2.5">
<StatusChip status={e.status} entryDate={e.entry_date} />
<StatusChip status={e.status} entryDate={e.entry_date} absenceType={e.absence_type} />
</td>
</tr>
);

View File

@@ -33,7 +33,7 @@ const DOT_STYLES: Record<string, string> = {
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" },
];

View File

@@ -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) {

View File

@@ -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() {
>
<option value="">Alle Aktionen</option>
{ACTIONS.map((a) => (
<option key={a} value={a}>
{a}
<option key={a.value} value={a.value}>
{a.label}
</option>
))}
</select>

View File

@@ -77,7 +77,7 @@ export function EmployeeDetail(props: EmployeeDetailProps) {
<h2 className="text-xl font-extrabold text-ink">
{fmtFullName(employee.first_name, employee.last_name, employee.title_prefix, employee.title_suffix)}
</h2>
<StatusChip status={employee.status} entryDate={employee.entry_date} />
<StatusChip status={employee.status} entryDate={employee.entry_date} absenceType={employee.absence_type} />
</div>
<p className="text-sm text-ink-body">{employee.job_title}</p>
<p className="text-xs text-ink-muted">{breadcrumb}</p>
@@ -93,7 +93,11 @@ export function EmployeeDetail(props: EmployeeDetailProps) {
<>
<ActionButton icon={ArrowRightLeft} label="Versetzen" onClick={() => setPanel("transfer")} />
<ActionButton icon={TrendingUp} label="Befördern" onClick={() => setPanel("promote")} />
<ActionButton icon={Clock} label={employee.status === "Karenz" ? "Karenz verwalten" : "Karenz"} onClick={() => setPanel("karenz")} />
<ActionButton
icon={Clock}
label={employee.status === "Karenz" ? "Abwesenheit verwalten" : "Langzeitabwesenheit"}
onClick={() => setPanel("karenz")}
/>
</>
)}
{canEditData && <ActionButton icon={Pencil} label="Daten ändern" onClick={() => setPanel("daten")} />}

View File

@@ -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;

View File

@@ -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<string>(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
<SlideOver
open={open}
onClose={onClose}
title={isOnKarenz ? "Karenz verwalten" : "Karenz"}
title={isOnKarenz ? "Langzeitabwesenheit verwalten" : "Langzeitabwesenheit erfassen"}
subtitle={`${employee.first_name} ${employee.last_name} · ${employee.job_title}`}
footer={
<>
<Button variant="ghost" onClick={onClose}>
Abbrechen
</Button>
{/* Karenz keeps the warning tone it uses everywhere else. */}
{/* Long-term absence keeps the warning tone it uses elsewhere. */}
{!isOnKarenz && (
<Button onClick={handleStart} pending={pending} className="!bg-warning-text text-white hover:brightness-110">
Karenz erfassen
Abwesenheit erfassen
</Button>
)}
{isOnKarenz && mode === "adjust" && (
@@ -134,7 +142,14 @@ export function KarenzPanel({ open, onClose, employee }: { open: boolean; onClos
>
{!isOnKarenz && (
<div className="flex flex-col gap-4">
<TextField label="Karenzbeginn" required type="date" value={karenzStart} onChange={setKarenzStart} />
<SelectField
label="Art der Langzeitabwesenheit"
required
value={absenceType}
onChange={setAbsenceType}
options={ABSENCE_TYPES.map((t) => ({ value: t, label: t }))}
/>
<TextField label="Beginn" required type="date" value={karenzStart} onChange={setKarenzStart} />
<TextField label="Geplante Rückkehr" required type="date" value={plannedReturn} onChange={setPlannedReturn} />
<TextareaField label="Anmerkung" rows={3} value={startNote} onChange={setStartNote} />
</div>
@@ -153,7 +168,11 @@ export function KarenzPanel({ open, onClose, employee }: { open: boolean; onClos
{mode === "adjust" && (
<>
<p className="text-sm text-ink-muted">Aktuelles Rückkehrdatum: {fmtDate(employee.karenz_return_date)}</p>
<p className="rounded bg-surface px-3 py-2 text-sm text-ink-body">
<span className="font-semibold">{absenceLabel(employee.status, employee.absence_type)}</span>
{" · Rückkehr "}
{fmtDate(employee.karenz_return_date)}
</p>
<TextField label="Neues Rückkehrdatum" required type="date" value={newReturnDate} onChange={setNewReturnDate} />
{diffDays !== 0 && (
<div className={`rounded px-3 py-2 text-sm ${diffDays > 0 ? "bg-warning-bg text-warning-text" : "bg-success-bg text-success-text"}`}>

View File

@@ -280,7 +280,8 @@ export function ReportsPageClient(props: ReportsPageClientProps) {
)}
</div>
<p className="mt-1 text-xs text-ink-muted">
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.
</p>
</div>
</div>

View File

@@ -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 (
<span
className={`inline-flex items-center whitespace-nowrap rounded-full px-2.5 py-0.5 text-xs font-semibold ${STATUS_STYLES[status]}`}

53
lib/absence.ts Normal file
View File

@@ -0,0 +1,53 @@
import type { EmploymentStatus } from "./supabase/types";
// Langzeitabwesenheit.
//
// The database still stores the employment status as 'Karenz' — renaming an
// enum value would mean rewriting every stored function that spells it, for
// a label change (see supabase/migrations/*_absence_type.sql). So the value
// is mapped to its display name here, in the one place the UI reads it from.
export const ABSENCE_TYPES = [
"Wochenhilfe (Mutterschutz)",
"Elternkarenz (inkl. Väterkarenz)",
"Papamonat",
"Bildungskarenz",
"Bildungsteilzeit",
"Präsenzdienst",
"Zivildienst",
"Langer Krankenstand",
"Wiedereingliederungsteilzeit",
"Pflegekarenz",
"Pflegeteilzeit",
"Familienhospizkarenz",
"Sabbatical",
] as const;
export type AbsenceType = (typeof ABSENCE_TYPES)[number];
export function isAbsenceType(value: string | null | undefined): value is AbsenceType {
return ABSENCE_TYPES.includes(value as AbsenceType);
}
/** Display names for the stored status values. */
const STATUS_LABELS: Record<EmploymentStatus, string> = {
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;
}

View File

@@ -329,14 +329,15 @@ export const EVENT_TYPE_LABELS: Record<HistoryEventType, string> = {
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 = {

View File

@@ -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;

View File

@@ -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;
$$;

View File

@@ -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<typeof newHireBase>, 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)}`,
});
}

View File

@@ -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);
});
});