HR can now delete a history entry, but only where deleting one is an honest thing to do — and deleting it also undoes it. The rule they asked for is the interesting part: the last valid change wins. Deleting an entry walks its fields one at a time. If a later entry touched the same field, the current value stays — that later change is the one in force. Otherwise the field goes back to what the deleted entry recorded as its "before". So the middle of three entries can be removed without an old value overwriting a newer one. Four kinds of entry refuse to be deleted, each saying why in the place the button would have been. Eintritt anchors the timeline. Transfers, promotions, absences and exits moved positions and status — they have proper operations for that, and guessing backwards is how you corrupt an org chart. Anything not yet effective hangs off a planned change, and that link is not trustworthy: there is no key between a history row and its pending row, only a person and a date, and the data already has an Eintritt and a Vertragsänderung sharing one. Matching on the date would eventually cancel a change nobody meant. And entries from before the history carried values have nothing to fall back to. Confirmation is not "are you sure" — that question gets a reflex yes by the third time. The dialog says what will be different afterwards: which field goes back to which value, and which one stays because something later claimed it. employee_history keeps its append-only policies; delete_history_entry is SECURITY DEFINER and checks the permission itself in its first line. The audit log keeps the deletion with the values that were removed, and the audit log genuinely cannot be edited. The rule lives twice — in SQL and in lib/history.ts. The database is the authority; the copy exists so the UI can hide a button that would fail and print the reason instead. Rehearsed against real data in a rolled-back transaction first: the later change held, the untouched field reverted, all four refusals fired. Also corrected in the data catalogue: I had written that require_hr_admin was called by nothing. It guards all sixteen mutating functions. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
210 lines
9.9 KiB
PL/PgSQL
210 lines
9.9 KiB
PL/PgSQL
-- Einen Historieneintrag zurücknehmen — samt seiner Wirkung.
|
|
--
|
|
-- Die Historie ist bewusst fortschreibend: employee_history hat nur Policies
|
|
-- für select und insert, es gibt kein update und kein delete. Das bleibt so.
|
|
-- Was hier entsteht, ist ein einzelner kontrollierter Weg daran vorbei, und
|
|
-- er ist eng: nur eine irrtümlich erfasste Stammdaten- oder Vertragsänderung,
|
|
-- nur mit Feldwerten, nur wenn sie bereits wirksam ist.
|
|
--
|
|
-- ═══ Warum überhaupt löschen ═══
|
|
--
|
|
-- Eine Adresse, die versehentlich geändert wurde, steht sonst für immer als
|
|
-- Änderung in der Akte — und die Person wohnt an der falschen Anschrift, bis
|
|
-- jemand sie von Hand zurücksetzt. Dieses Zurücksetzen erzeugt dann eine
|
|
-- *zweite* Änderung, und in der Historie stehen zwei Einträge, von denen
|
|
-- keiner je stattgefunden hat. Genau das soll der Vorgang hier ersparen.
|
|
--
|
|
-- ═══ „Die letztgültige Änderung ist die schlagende" ═══
|
|
--
|
|
-- Beim Zurücknehmen wird je Feld einzeln entschieden:
|
|
--
|
|
-- * Hat ein **späterer** Eintrag dasselbe Feld angefasst, bleibt der
|
|
-- heutige Wert stehen — die spätere Änderung ist die gültige.
|
|
-- * Sonst wird der Wert auf das „vorher" des gelöschten Eintrags gesetzt.
|
|
--
|
|
-- Deshalb lässt sich auch der mittlere von drei Einträgen entfernen, ohne
|
|
-- dass ein alter Wert einen neueren überschreibt.
|
|
--
|
|
-- ═══ Was nicht geht, und warum ═══
|
|
--
|
|
-- * **Eintritt** — der Anker der Zeitleiste. Ohne ihn hat die Person keinen
|
|
-- Anfang, und ein Trigger verbietet ohnehin Ereignisse davor.
|
|
-- * **Zukünftiges** — dazu gehört eine Zeile in pending_org_changes, und
|
|
-- die lässt sich einem Historieneintrag nicht zuverlässig zuordnen: es
|
|
-- gibt keinen Schlüssel zwischen beiden, nur Person und Datum. In den
|
|
-- Daten hängt bereits ein „Eintritt" und eine Vertragsänderung am selben
|
|
-- Tag. Eine Zuordnung über das Datum träfe irgendwann die falsche Zeile,
|
|
-- und dann verschwände eine geplante Änderung, die niemand gemeint hat.
|
|
-- * **Versetzung, Beförderung, Karenz, Rückkehr, Austritt, Wiedereintritt,
|
|
-- Reorganisation** — die haben Planstellen und Zuordnungen bewegt.
|
|
-- Dafür gibt es die fachlichen Vorgänge, die das sauber fortschreiben,
|
|
-- statt rückwärts zu raten.
|
|
-- * **Einträge ohne Feldwerte** — alles vor der Erweiterung der Historie.
|
|
-- Es gibt nichts, worauf zurückgesetzt werden könnte.
|
|
--
|
|
-- ═══ Der Nachweis bleibt ═══
|
|
--
|
|
-- Gelöscht wird die Historienzeile, nicht die Spur: das Audit-Log bekommt
|
|
-- einen Eintrag mit den Werten der gelöschten Zeile. Das Protokoll ist selbst
|
|
-- fortschreibend, dort kann nichts verschwinden.
|
|
|
|
create or replace function delete_history_entry(payload jsonb)
|
|
returns void
|
|
language plpgsql
|
|
security definer
|
|
set search_path to 'public', 'pg_temp'
|
|
as $function$
|
|
declare
|
|
v_id uuid := (payload->>'history_id')::uuid;
|
|
v_eintrag employee_history%rowtype;
|
|
v_name text;
|
|
v_aenderung jsonb;
|
|
v_feld text;
|
|
v_wert text;
|
|
v_spalte text;
|
|
v_typ text;
|
|
v_spaeter boolean;
|
|
v_zurueckgesetzt jsonb := '[]'::jsonb;
|
|
-- Feldbeschriftung → Spalte und Typ. Geschlossene Liste: was
|
|
-- change_employee_data schreiben kann, steht hier, sonst nichts. Der
|
|
-- Spaltenname geht in dynamisches SQL, deshalb darf er nur von hier kommen.
|
|
v_karte constant jsonb := jsonb_build_object(
|
|
'Vorname', jsonb_build_array('first_name', 'text'),
|
|
'Nachname', jsonb_build_array('last_name', 'text'),
|
|
'Geschlecht', jsonb_build_array('gender', 'gender_type'),
|
|
'Geburtsdatum', jsonb_build_array('birth_date', 'date'),
|
|
'SV-Nummer', jsonb_build_array('sv_nummer', 'text'),
|
|
'Staatsbürgerschaft', jsonb_build_array('nationality', 'text'),
|
|
'Adresse', jsonb_build_array('address', 'text'),
|
|
'Postleitzahl', jsonb_build_array('postal_code', 'text'),
|
|
'Ort', jsonb_build_array('city', 'text'),
|
|
'Land', jsonb_build_array('address_country', 'text'),
|
|
'E-Mail', jsonb_build_array('email', 'text'),
|
|
'Telefon', jsonb_build_array('phone', 'text'),
|
|
'Notfallkontakt', jsonb_build_array('emergency_contact_name', 'text'),
|
|
'Notfallkontakt Telefon', jsonb_build_array('emergency_contact_phone', 'text'),
|
|
'Notfallkontakt Verhältnis', jsonb_build_array('emergency_contact_relation', 'text'),
|
|
'Titel (vorangestellt)', jsonb_build_array('title_prefix', 'liste'),
|
|
'Titel (nachgestellt)', jsonb_build_array('title_suffix', 'liste'),
|
|
'Beschäftigungsausmaß', jsonb_build_array('employment_type', 'employment_type'),
|
|
'Wochenstunden', jsonb_build_array('weekly_hours', 'numeric'),
|
|
'Vertragsart', jsonb_build_array('contract_type', 'contract_type'),
|
|
'Befristet bis', jsonb_build_array('contract_end_date', 'date'),
|
|
'Angestellte:r/Arbeiter:in', jsonb_build_array('worker_type', 'worker_type'),
|
|
'Kollektivvertrag', jsonb_build_array('collective_agreement', 'collective_agreement'),
|
|
'Arbeitstage', jsonb_build_array('work_days', 'liste'),
|
|
'Betriebsrat', jsonb_build_array('is_betriebsrat', 'boolean'),
|
|
'Dienstwagen', jsonb_build_array('has_dienstwagen', 'boolean'),
|
|
'Laterale Führung', jsonb_build_array('is_laterale_fuehrung', 'boolean'),
|
|
'C-Level', jsonb_build_array('is_c_level', 'boolean'),
|
|
'Dienstwagen Antrieb', jsonb_build_array('dienstwagen_art', 'text')
|
|
);
|
|
begin
|
|
perform require_hr_admin();
|
|
|
|
select * into v_eintrag from employee_history where id = v_id;
|
|
if not found then
|
|
raise exception 'Historieneintrag nicht gefunden.';
|
|
end if;
|
|
|
|
if v_eintrag.event_type = 'Eintritt' then
|
|
raise exception 'Der Eintritt lässt sich nicht löschen — er ist der Anfang der Zeitleiste.';
|
|
end if;
|
|
|
|
if v_eintrag.event_type not in ('Stammdatenänderung', 'Vertragsänderung') then
|
|
raise exception 'Nur Stammdaten- und Vertragsänderungen lassen sich hier zurücknehmen. Für % gibt es den passenden Vorgang.', v_eintrag.event_type;
|
|
end if;
|
|
|
|
if v_eintrag.event_date > current_date then
|
|
raise exception 'Diese Änderung ist noch nicht wirksam und hängt an einem geplanten Vorgang. Sie muss dort abgebrochen werden.';
|
|
end if;
|
|
|
|
if v_eintrag.changes is null or jsonb_array_length(v_eintrag.changes) = 0 then
|
|
raise exception 'Zu diesem Eintrag sind keine Feldwerte erfasst — es gibt nichts, worauf zurückgesetzt werden könnte.';
|
|
end if;
|
|
|
|
select first_name || ' ' || last_name into v_name from employees where id = v_eintrag.employee_id;
|
|
|
|
-- Je Feld: nur zurücksetzen, wenn kein späterer Eintrag dasselbe Feld
|
|
-- angefasst hat. Sonst gilt der spätere Wert weiter.
|
|
for v_aenderung in select * from jsonb_array_elements(v_eintrag.changes) loop
|
|
v_feld := v_aenderung->>'feld';
|
|
|
|
if not v_karte ? v_feld then
|
|
continue; -- unbekannte Beschriftung: nichts anfassen
|
|
end if;
|
|
|
|
select exists (
|
|
select 1
|
|
from employee_history h,
|
|
lateral jsonb_array_elements(coalesce(h.changes, '[]'::jsonb)) a
|
|
where h.employee_id = v_eintrag.employee_id
|
|
and h.id <> v_eintrag.id
|
|
and a->>'feld' = v_feld
|
|
and (h.event_date, h.created_at) > (v_eintrag.event_date, v_eintrag.created_at)
|
|
) into v_spaeter;
|
|
|
|
if v_spaeter then
|
|
continue;
|
|
end if;
|
|
|
|
v_spalte := v_karte->v_feld->>0;
|
|
v_typ := v_karte->v_feld->>1;
|
|
v_wert := v_aenderung->>'vorher';
|
|
|
|
if v_typ = 'liste' then
|
|
execute format('update employees set %I = coalesce(string_to_array(%L, '', ''), ''{}'') where id = %L',
|
|
v_spalte, nullif(v_wert, ''), v_eintrag.employee_id);
|
|
else
|
|
execute format('update employees set %I = %L::%s where id = %L',
|
|
v_spalte, nullif(v_wert, ''), v_typ, v_eintrag.employee_id);
|
|
end if;
|
|
|
|
v_zurueckgesetzt := v_zurueckgesetzt || jsonb_build_object(
|
|
'feld', v_feld,
|
|
'vorher', v_aenderung->>'nachher',
|
|
'nachher', v_wert
|
|
);
|
|
end loop;
|
|
|
|
delete from employee_history where id = v_id;
|
|
|
|
insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details, changes)
|
|
values (app_current_user_id(), current_actor_name(), 'Historieneintrag gelöscht', v_name, v_eintrag.employee_id,
|
|
v_eintrag.event_type || ' vom ' || v_eintrag.event_date ||
|
|
case when jsonb_array_length(v_zurueckgesetzt) = 0
|
|
then ' gelöscht; keine Werte zurückgesetzt (spätere Änderungen gelten)'
|
|
else ' gelöscht und zurückgesetzt: ' || app_aenderungsfelder(v_zurueckgesetzt) end,
|
|
v_zurueckgesetzt);
|
|
end;
|
|
$function$;
|
|
|
|
comment on function delete_history_entry(jsonb) is
|
|
'Nimmt eine irrtümliche Stammdaten- oder Vertragsänderung zurück: setzt je Feld auf den Wert davor, sofern kein späterer Eintrag dasselbe Feld geändert hat, und entfernt die Historienzeile. Der Vorgang selbst wird im Audit-Log festgehalten. SECURITY DEFINER, weil employee_history absichtlich keine delete-Policy hat.';
|
|
|
|
-- Selbstprüfung: lieber laut scheitern als still nichts tun.
|
|
do $$
|
|
declare
|
|
v_def text;
|
|
begin
|
|
select pg_get_functiondef('public.delete_history_entry(jsonb)'::regprocedure) into v_def;
|
|
|
|
if not (select prosecdef from pg_proc where oid = 'public.delete_history_entry(jsonb)'::regprocedure) then
|
|
raise exception 'delete_history_entry muss SECURITY DEFINER sein, sonst greift die fehlende delete-Policy';
|
|
end if;
|
|
|
|
if v_def not like '%require_hr_admin%' then
|
|
raise exception 'delete_history_entry prüft die Berechtigung nicht';
|
|
end if;
|
|
|
|
-- Die delete-Policy darf es weiterhin nicht geben: der Weg hier ist der
|
|
-- einzige, und er ist geprüft.
|
|
if exists (
|
|
select 1 from pg_policy p join pg_class c on c.oid = p.polrelid
|
|
where c.relname = 'employee_history' and p.polcmd = 'd'
|
|
) then
|
|
raise exception 'employee_history hat eine delete-Policy bekommen — das war nicht beabsichtigt';
|
|
end if;
|
|
end
|
|
$$;
|