diff --git a/app/api/export/employees/route.ts b/app/api/export/employees/route.ts index 3672235..a83c2f2 100644 --- a/app/api/export/employees/route.ts +++ b/app/api/export/employees/route.ts @@ -5,7 +5,6 @@ import { exportFilename, exportResponseHeaders, toCsv, toXlsx, type ExportColumn import { exportParameter, ladeExportMitarbeiter, type ExportMitarbeiter } from "@/lib/export-auswahl"; import { geschlechtLabel } from "@/lib/geschlecht"; import { anzeige } from "@/lib/anzeige"; -import { C_LEVEL } from "@/lib/c-level"; import { sortiereWochentage } from "@/lib/wochentage"; import { deriveStatusAsOf, type OrgLookups } from "@/lib/reports"; import { requireHrUser } from "@/lib/auth/require-hr"; @@ -115,7 +114,6 @@ function employeeExportColumns( // Code und Bezeichnung getrennt: der Code ist das, was andere Systeme // weiterverarbeiten, die Bezeichnung das, was ein Mensch liest. { header: "C-Level", get: (e) => e.c_level }, - { header: "C-Level Bezeichnung", get: (e) => C_LEVEL.find((c) => c.code === e.c_level)?.bezeichnung ?? null }, { header: "Hay-Grade", get: (e) => e.paygrade }, { header: "VL", get: (e) => e.vl }, { header: "Bonusanspruch", get: (e) => e.has_bonusanspruch }, diff --git a/components/employees/EmployeeFilters.tsx b/components/employees/EmployeeFilters.tsx index 2176ef5..0328cae 100644 --- a/components/employees/EmployeeFilters.tsx +++ b/components/employees/EmployeeFilters.tsx @@ -5,12 +5,14 @@ import { useEffect, useState } from "react"; import { FILTER_SELECT_CLASS } from "@/components/ui/Field"; import { SearchInput } from "@/components/ui/SearchInput"; import { AUSTRITT_GEPLANT } from "@/lib/employee-status-filter"; +import { zuweisbareStandorte } from "@/lib/standorte"; type EmployeeFiltersProps = { /** Der ganze Baum, in Tiefensuche-Reihenfolge. */ units: { id: string; name: string; unit_type: string }[]; depthOf: Map; - locations: { id: string; name: string }[]; + /** Zur Auswahl kommen nur Standorte, auf denen jemand sitzen kann. */ + locations: { id: string; name: string; parent_id: string | null }[]; }; // Aktiv and Langzeitabwesenheit are separate statuses — somebody on a @@ -107,7 +109,7 @@ export function EmployeeFilters({ units, depthOf, locations }: EmployeeFiltersPr className={FILTER_SELECT_CLASS} > - {locations.map((l) => ( + {zuweisbareStandorte(locations).map((l) => ( diff --git a/components/employees/StandortAuswahl.tsx b/components/employees/StandortAuswahl.tsx new file mode 100644 index 0000000..799ccd4 --- /dev/null +++ b/components/employees/StandortAuswahl.tsx @@ -0,0 +1,63 @@ +"use client"; + +import { useState } from "react"; +import { SelectField } from "@/components/ui/Field"; +import { kurzname, oberstandorte, oberstandortVon, unterstandorte, type StandortEintrag } from "@/lib/standorte"; + +type Standort = StandortEintrag & { country?: string }; + +// Standort in zwei Stufen: die oberste Ebene, und bei einem Standort mit +// Unterstandorten („Shop") eine zweite Auswahl. Gemeldet wird nur ein +// Standort, auf dem eine Person sitzen kann; solange die zweite Auswahl +// fehlt, ist der Wert leer — ein Pflichtfeld bleibt damit offen. +export function StandortAuswahl({ + value, + onChange, + standorte, + required, + mitLand, + hint, +}: { + value: string; + onChange: (id: string) => void; + standorte: readonly Standort[]; + required?: boolean; + /** Land in Klammern dahinter, wie bei der Einstellung. */ + mitLand?: boolean; + hint?: string; +}) { + // Zustand, weil „Shop" gewählt sein kann, ohne dass schon ein Wert feststeht. + const [ober, setOber] = useState(() => oberstandortVon(standorte, value)); + const unter = unterstandorte(standorte, ober); + const oberEintrag = standorte.find((s) => s.id === ober); + + const beschriftung = (s: Standort, name: string) => (mitLand && s.country ? `${name} (${s.country})` : name); + + return ( + <> + { + setOber(id); + onChange(unterstandorte(standorte, id).length > 0 ? "" : id); + }} + placeholder="Bitte wählen…" + options={oberstandorte(standorte).map((s) => ({ value: s.id, label: beschriftung(s, s.name) }))} + hint={unter.length > 0 ? undefined : hint} + /> + {unter.length > 0 && ( + s.id === value) ? value : ""} + onChange={onChange} + placeholder="Bitte wählen…" + options={unter.map((s) => ({ value: s.id, label: kurzname(s, oberEintrag) }))} + hint={hint} + /> + )} + + ); +} diff --git a/components/employees/VerhaeltnisField.tsx b/components/employees/VerhaeltnisField.tsx index 9e31ab5..9d2d0f0 100644 --- a/components/employees/VerhaeltnisField.tsx +++ b/components/employees/VerhaeltnisField.tsx @@ -4,6 +4,7 @@ import { useState } from "react"; import { SelectField, TextField } from "@/components/ui/Field"; import { anzeigeAuswahl } from "@/lib/anzeige"; import { EMERGENCY_RELATIONS } from "@/lib/types"; +import { istFreiesVerhaeltnis, SONSTIGE } from "@/lib/verhaeltnis"; // Das Verhältnis zum Notfallkontakt: Auswahl, und unter „Sonstige" ein // Freifeld. @@ -23,12 +24,7 @@ import { EMERGENCY_RELATIONS } from "@/lib/types"; // nimmt einen gespeicherten Wert, der nicht in der Liste steht, mit in die // Auswahl auf. -const SONSTIGE = "Sonstige"; - -/** Ob ein gespeicherter Wert frei eingetragen wurde. */ -export function istFreiesVerhaeltnis(wert: string): boolean { - return wert.trim() !== "" && !(EMERGENCY_RELATIONS as readonly string[]).includes(wert); -} +export { istFreiesVerhaeltnis }; export function VerhaeltnisField({ value, diff --git a/components/employees/panels/TransferPanel.tsx b/components/employees/panels/TransferPanel.tsx index c30881e..2f7973e 100644 --- a/components/employees/panels/TransferPanel.tsx +++ b/components/employees/panels/TransferPanel.tsx @@ -5,7 +5,8 @@ import { useMemo, useState } from "react"; import { geplantenVorgangErsetzen, transferEmployee } from "@/actions/employees"; import { Button } from "@/components/ui/Button"; import { PlanstellenAuswahl } from "@/components/positions/PlanstellenAuswahl"; -import { DateField, SelectField } from "@/components/ui/Field"; +import { StandortAuswahl } from "@/components/employees/StandortAuswahl"; +import { DateField } from "@/components/ui/Field"; import { SlideOver } from "@/components/ui/SlideOver"; import { useToast } from "@/components/ui/Toast"; import { mitBisherigerStelle, type GeplanterVorgang } from "@/lib/geplanter-vorgang"; @@ -23,7 +24,7 @@ type TransferPanelProps = { /** Eine geplante Versetzung, die geändert wird (lib/geplanter-vorgang.ts). */ ersetzt?: GeplanterVorgang | null; /** Die Standorte zur Auswahl — mit der Versetzung kann auch der Standort wechseln. */ - locations?: { id: string; name: string }[]; + locations?: { id: string; name: string; parent_id: string | null }[]; }; // Eine Versetzung ist der Wechsel auf eine andere Planstelle — nicht die @@ -58,6 +59,11 @@ export function TransferPanel({ open, onClose, employee, openPositions, ersetzt, showToast("Bitte Datum und Zielplanstelle angeben.", "error"); return; } + // Leer heisst hier: „Shop" gewählt, der einzelne Shop noch nicht. + if (!ersetzt && !standort) { + showToast("Bitte den Standort vollständig auswählen.", "error"); + return; + } setPending(true); const result = ersetzt ? await geplantenVorgangErsetzen({ @@ -125,11 +131,10 @@ export function TransferPanel({ open, onClose, employee, openPositions, ersetzt, {/* Nur bei einer neuen Versetzung: an einer geplanten werden Planstelle und Datum geändert. */} {!ersetzt && locations.length > 0 && ( - ({ value: l.id, label: l.name }))} + standorte={locations} hint="Wechselt mit der Versetzung zum selben Tag; sonst bleibt der bisherige." /> )} diff --git a/components/employees/tabs/VertragTab.tsx b/components/employees/tabs/VertragTab.tsx index 30ccc4c..0cff082 100644 --- a/components/employees/tabs/VertragTab.tsx +++ b/components/employees/tabs/VertragTab.tsx @@ -6,7 +6,6 @@ import { hayGradeLabel } from "@/lib/hay-grade"; import { ohneVorgabe } from "@/lib/extern-vorgaben"; import { lehrzeitText } from "@/lib/lehrzeit"; import { anzeige } from "@/lib/anzeige"; -import { cLevelText } from "@/lib/c-level"; import type { Database } from "@/lib/types"; import { bonusanspruchLabel, vlLabel } from "@/lib/vertragsangaben"; @@ -108,7 +107,7 @@ export function VertragTab({ ["Dienstwagen", ohneVorgabe(employee, ["has_dienstwagen"], employee.has_dienstwagen ? dienstwagenLabel(employee.dienstwagen_art) : "Nein")], ["Betriebsrat", ohneVorgabe(employee, ["is_betriebsrat"], employee.is_betriebsrat ? "Ja" : "Nein")], ["Laterale Führung", ohneVorgabe(employee, ["is_laterale_fuehrung"], employee.is_laterale_fuehrung ? "Ja" : "Nein")], - ["C-Level", cLevelText(employee.c_level) || "–"], + ["C-Level", employee.c_level || "–"], // Das Enddatum steht gleich dabei: „Ja" allein liesse offen, ob der // Schutz noch läuft, und genau danach fragt man. // Die Teilzeitvariante gehört neben die Stunden: sie erklärt, warum sie diff --git a/components/hire/HireWizard.tsx b/components/hire/HireWizard.tsx index d405240..7f76658 100644 --- a/components/hire/HireWizard.tsx +++ b/components/hire/HireWizard.tsx @@ -60,7 +60,7 @@ type HireWizardProps = { /** Ein neuer Entwurf ist angelegt — er trägt bereits meine Sperre. */ onEntwurfAngelegt: (id: string) => void; openPositions: OpenPositionResolved[]; - locations: { id: string; name: string; country: string }[]; + locations: { id: string; name: string; country: string; parent_id: string | null }[]; resumeDraft: { id: string; step: number; payload: Record } | null; initialPositionId?: string; }; diff --git a/components/hire/HireWizardContext.tsx b/components/hire/HireWizardContext.tsx index 3df1a4f..5d1c8d4 100644 --- a/components/hire/HireWizardContext.tsx +++ b/components/hire/HireWizardContext.tsx @@ -8,7 +8,7 @@ import type { Entwurf } from "@/lib/entwuerfe"; import type { OpenPositionResolved } from "@/lib/positions"; import { HireWizard } from "./HireWizard"; -type Location = { id: string; name: string; country: string }; +type Location = { id: string; name: string; country: string; parent_id: string | null }; type OpenWizardOptions = { draftId?: string; positionId?: string }; diff --git a/components/hire/RehireWizard.tsx b/components/hire/RehireWizard.tsx index 12ed3fe..6864655 100644 --- a/components/hire/RehireWizard.tsx +++ b/components/hire/RehireWizard.tsx @@ -64,7 +64,7 @@ type RehireWizardProps = { onClose: () => void; employee: EmployeeRow; openPositions: OpenPositionResolved[]; - locations: { id: string; name: string; country: string }[]; + locations: { id: string; name: string; country: string; parent_id: string | null }[]; }; export function RehireWizard({ open, onClose, employee, openPositions, locations }: RehireWizardProps) { diff --git a/components/hire/StepExternePerson.tsx b/components/hire/StepExternePerson.tsx index 6691676..669432c 100644 --- a/components/hire/StepExternePerson.tsx +++ b/components/hire/StepExternePerson.tsx @@ -1,3 +1,4 @@ +import { StandortAuswahl } from "@/components/employees/StandortAuswahl"; import { PlanstellenAuswahl } from "@/components/positions/PlanstellenAuswahl"; import { DateField, SelectField, TextField } from "@/components/ui/Field"; import { todayIso } from "@/lib/format"; @@ -24,7 +25,7 @@ export function StepExternePerson({ }: { draft: HireDraftData; update: (patch: Partial) => void; - locations: { id: string; name: string; country: string }[]; + locations: { id: string; name: string; country: string; parent_id: string | null }[]; openPositions: OpenPositionResolved[]; stellenFehler?: string | null; onNummerBefund: (befund: { nummer: number; vergeben: boolean }) => void; @@ -78,13 +79,12 @@ export function StepExternePerson({ onChange={(id) => update({ positionId: id })} /> - update({ locationId })} - placeholder="Bitte wählen…" - options={locations.map((l) => ({ value: l.id, label: `${l.name} (${l.country})` }))} + standorte={locations} /> ); diff --git a/components/hire/StepPerson.tsx b/components/hire/StepPerson.tsx index 7b32ab3..c9254c6 100644 --- a/components/hire/StepPerson.tsx +++ b/components/hire/StepPerson.tsx @@ -1,3 +1,4 @@ +import { StandortAuswahl } from "@/components/employees/StandortAuswahl"; import { SvNummerField } from "@/components/employees/SvNummerField"; import { TitleFields } from "@/components/employees/TitleFields"; import { ZustaendigeHrField } from "@/components/employees/ZustaendigeHrField"; @@ -14,7 +15,7 @@ import type { HireDraftData } from "./types"; type StepPersonProps = { draft: HireDraftData; update: (patch: Partial) => void; - locations: { id: string; name: string; country: string }[]; + locations: { id: string; name: string; country: string; parent_id: string | null }[]; /** Meldet die geprüfte Personalnummer und ihr Ergebnis — steuert „Weiter". */ onNummerBefund?: (befund: { nummer: number; vergeben: boolean }) => void; /** @@ -185,13 +186,12 @@ export function StepPerson({ draft, update, locations, onNummerBefund, nummerGes /> update({ phone })} /> - update({ locationId })} - placeholder="Bitte wählen…" - options={locations.map((l) => ({ value: l.id, label: `${l.name} (${l.country})` }))} + standorte={locations} /> update({ zustaendigeHrId })} /> diff --git a/components/hire/StepSummary.tsx b/components/hire/StepSummary.tsx index d064527..197de3a 100644 --- a/components/hire/StepSummary.tsx +++ b/components/hire/StepSummary.tsx @@ -5,7 +5,6 @@ import { geschlechtLabel } from "@/lib/geschlecht"; import { hayGradeLabel } from "@/lib/hay-grade"; import { lehrzeitText } from "@/lib/lehrzeit"; import { anzeige } from "@/lib/anzeige"; -import { cLevelText } from "@/lib/c-level"; import type { OpenPositionResolved } from "@/lib/positions"; import { bonusanspruchLabel } from "@/lib/vertragsangaben"; import type { HireDraftData } from "./types"; @@ -89,7 +88,7 @@ export function StepSummary({ draft, selectedPosition, locations, extern = false : []), ["Anstellungs-/Beschäftigungsart", anzeige(draft.mitarbeiterart)], ["Kollektivvertrag", draft.collectiveAgreement], - ["C-Level", cLevelText(draft.cLevel) || "–"], + ["C-Level", draft.cLevel || "–"], ["Arbeitstage", draft.workDays.join(", ") || "–"], ["Merkmale", flags.length > 0 ? flags.join(", ") : "–"], ]; diff --git a/components/hire/UebernahmeWizard.tsx b/components/hire/UebernahmeWizard.tsx index d6bd8ee..a41e002 100644 --- a/components/hire/UebernahmeWizard.tsx +++ b/components/hire/UebernahmeWizard.tsx @@ -54,7 +54,7 @@ export function UebernahmeWizard({ open: boolean; onClose: () => void; employee: EmployeeRow; - locations: { id: string; name: string; country: string }[]; + locations: { id: string; name: string; country: string; parent_id: string | null }[]; }) { const { showToast } = useToast(); const router = useRouter(); diff --git a/db/migrations/20261123140000_standort_shop.sql b/db/migrations/20261123140000_standort_shop.sql new file mode 100644 index 0000000..83d865c --- /dev/null +++ b/db/migrations/20261123140000_standort_shop.sql @@ -0,0 +1,139 @@ +-- Standorte mit Unterstandorten: „Shop" und die einzelnen Shops +-- +-- Ein Standort kann Unterstandorte haben. Eine Person sitzt immer auf einem +-- Standort ohne Unterstandorte: „Shop" allein sagt nicht, wo jemand +-- arbeitet. Die Oberfläche bietet zuerst die Standorte ohne übergeordneten +-- an und bei einem mit Unterstandorten eine zweite Auswahl. +-- +-- Der Name eines Unterstandorts nennt den übergeordneten mit („Shop W17"): +-- Liste, Berichte, Exporte und IT-Sicht lesen nur den Namen und bleiben so +-- ohne weitere Verknüpfung eindeutig. +-- +-- Eine Ebene: ein Unterstandort hat keine eigenen. Zwei Trigger halten das +-- fest, auch für den Import und den Nachtlauf, die an der Oberfläche +-- vorbeigehen. + +alter table locations add column if not exists parent_id uuid references locations(id); + +comment on column locations.parent_id is + 'Übergeordneter Standort (etwa „Shop"); leer = Standort der obersten Ebene. Personen sitzen nur auf Standorten ohne Unterstandorte.'; + +alter table locations drop constraint if exists chk_location_nicht_eigener_parent; +alter table locations add constraint chk_location_nicht_eigener_parent check (parent_id is null or parent_id <> id); + +create index if not exists idx_locations_parent on locations (parent_id) where parent_id is not null; + +-- Sitzt schon jemand auf einem Standort „Shop", fehlt die Angabe, auf welchem. +-- Raten wäre schlechter als anhalten. +do $pruefung$ +begin + if exists (select 1 from employees e join locations l on l.id = e.location_id where l.name = 'Shop') then + raise exception 'Auf dem Standort „Shop" sitzen Personen. Sie brauchen zuerst einen anderen Standort; danach die Migration erneut ausführen.'; + end if; +end +$pruefung$; + +-- ── Regeln ────────────────────────────────────────────────────────────── + +create or replace function public.standort_ebene_pruefen() +returns trigger +language plpgsql +set search_path = public, pg_temp +as $$ +begin + if new.parent_id is null then + return new; + end if; + if exists (select 1 from locations where id = new.parent_id and parent_id is not null) then + raise exception 'Ein Unterstandort kann keine eigenen Unterstandorte haben.'; + end if; + if exists (select 1 from locations where parent_id = new.id) then + raise exception 'Ein Standort mit Unterstandorten kann nicht selbst unter einem anderen stehen.'; + end if; + if exists (select 1 from employees where location_id = new.parent_id) then + raise exception 'Auf dem Standort „%" sitzen Personen; er kann keine Unterstandorte bekommen.', + (select name from locations where id = new.parent_id); + end if; + return new; +end; +$$; + +drop trigger if exists trg_standort_ebene on locations; +create trigger trg_standort_ebene + before insert or update of parent_id on locations + for each row execute function public.standort_ebene_pruefen(); + +create or replace function public.standort_ohne_unterstandorte() +returns trigger +language plpgsql +set search_path = public, pg_temp +as $$ +begin + if new.location_id is not null and exists (select 1 from locations where parent_id = new.location_id) then + raise exception 'Der Standort „%" fasst mehrere zusammen. Bitte einen davon auswählen.', + (select name from locations where id = new.location_id); + end if; + return new; +end; +$$; + +drop trigger if exists trg_standort_ohne_unterstandorte on employees; +create trigger trg_standort_ohne_unterstandorte + before insert or update of location_id on employees + for each row execute function public.standort_ohne_unterstandorte(); + +-- ── Shop und die einzelnen Shops ──────────────────────────────────────── + +insert into locations (name, country) values ('Shop', 'Österreich') on conflict (name) do nothing; + +insert into locations (name, country, parent_id) +select v.name, 'Österreich', (select id from locations where name = 'Shop') + from (values ('Shop W17'), ('Shop Wodo'), ('Shop Parndorf'), ('Shop Donaupark'), ('Shop W1'), ('Shop Wien Hauptbahnhof')) v(name) +on conflict (name) do nothing; + +-- Bestanden einzelne Shops schon als eigene Standorte, kommen sie unter „Shop". +update locations + set parent_id = (select id from locations where name = 'Shop') + where name in ('Shop W17', 'Shop Wodo', 'Shop Parndorf', 'Shop Donaupark', 'Shop W1', 'Shop Wien Hauptbahnhof') + and parent_id is null; + +-- ── Selbstprüfung ─────────────────────────────────────────────────────── + +do $migration$ +declare + v_shop uuid; +begin + select id into v_shop from locations where name = 'Shop'; + if v_shop is null then + raise exception 'Der Standort „Shop" fehlt.'; + end if; + if (select parent_id from locations where id = v_shop) is not null then + raise exception '„Shop" steht unter einem anderen Standort.'; + end if; + if (select count(*) from locations where parent_id = v_shop) <> 6 then + raise exception 'Unter „Shop" stehen nicht genau die sechs Shops.'; + end if; + if exists ( + select 1 from (values ('Shop W17'), ('Shop Wodo'), ('Shop Parndorf'), ('Shop Donaupark'), ('Shop W1'), ('Shop Wien Hauptbahnhof')) v(name) + where not exists (select 1 from locations l where l.name = v.name and l.parent_id = v_shop) + ) then + raise exception 'Ein Shop fehlt oder steht nicht unter „Shop".'; + end if; + if exists (select 1 from employees e join locations l on l.parent_id = e.location_id) then + raise exception 'Eine Person sitzt auf einem Standort mit Unterstandorten.'; + end if; + if (select count(*) from pg_trigger + where not tgisinternal and tgenabled = 'O' + and tgname in ('trg_standort_ebene', 'trg_standort_ohne_unterstandorte')) <> 2 then + raise exception 'Die Trigger zu den Unterstandorten fehlen.'; + end if; + if exists ( + select 1 from pg_proc p join pg_namespace n on n.oid = p.pronamespace + where n.nspname = 'public' + and p.proname in ('standort_ebene_pruefen', 'standort_ohne_unterstandorte') + and (p.prosecdef or not ('search_path=public, pg_temp' = any (coalesce(p.proconfig, '{}')))) + ) then + raise exception 'Die Triggerfunktionen laufen nicht unter den Rechten des Aufrufers oder ohne search_path.'; + end if; +end +$migration$; diff --git a/db/tests/rauchtest.sql b/db/tests/rauchtest.sql index 246f5cb..6cdd576 100644 --- a/db/tests/rauchtest.sql +++ b/db/tests/rauchtest.sql @@ -60,7 +60,7 @@ declare v_psnr text; begin select id into v_wurzel from org_units where parent_id is null; - select id into v_ort from locations order by name limit 1; + select l.id into v_ort from locations l where not exists (select 1 from locations u where u.parent_id = l.id) order by l.name limit 1; select coalesce(max(personnel_number), 0) + 1 into v_nr from employees; if v_wurzel is null or v_ort is null then raise exception 'Kein Bestand: es fehlt die oberste Einheit oder ein Standort.'; diff --git a/db/tests/vertragsangaben.sql b/db/tests/vertragsangaben.sql index bbda0d3..352d6db 100644 --- a/db/tests/vertragsangaben.sql +++ b/db/tests/vertragsangaben.sql @@ -62,7 +62,7 @@ begin raise exception 'Voraussetzung fehlt: zwei aktive und ein abgeschaltetes HR-Konto.'; end if; select id into v_wurzel from org_units where parent_id is null; - select id into v_ort from locations order by name limit 1; + select l.id into v_ort from locations l where not exists (select 1 from locations u where u.parent_id = l.id) order by l.name limit 1; select coalesce(max(personnel_number), 0) + 1 into v_nr from employees; v_einheit := create_org_unit(jsonb_build_object( @@ -253,7 +253,7 @@ declare v_e employees%rowtype; v_a uuid := (select id from employees where last_name = 'Test-A' and first_name = 'Vertrag'); v_p3 uuid := (select p.id from om_positions p join jobs j on j.id = p.job_id where j.title = 'Vertragstest Drei'); - v_ort uuid := (select id from locations order by name limit 1); + v_ort uuid := (select l.id from locations l where not exists (select 1 from locations u where u.parent_id = l.id) order by l.name limit 1); begin perform apply_due_pending_changes(); select * into v_e from employees where id = v_b; diff --git a/lib/austausch/importieren.ts b/lib/austausch/importieren.ts index 7a49c24..d9ad154 100644 --- a/lib/austausch/importieren.ts +++ b/lib/austausch/importieren.ts @@ -5,6 +5,7 @@ import { fmtName } from "../format"; import { pruefePlz } from "../plz"; import { requiresAustrianSvnr, svnrErrorMessage, svnrHaeltAuf, validateSvnr } from "../svnr"; import type { Database } from "../types"; +import { SONSTIGE, verhaeltnisAusDatei } from "../verhaeltnis"; import { pruefsumme } from "./abgleich"; import { BLAETTER, WIRKSAM_AB, type Blatt, type Spalte } from "./katalog"; import { @@ -158,7 +159,7 @@ async function rufe(tx: Tx, fn: MutationFn, payload: Record): P /** Lookups, die sich mit jedem Blatt ändern können: was die Datei neu anlegt, gilt sofort. */ type Bestand = { - standorte: Map; + standorte: Map; kostenstellen: Map; einheiten: Map & { id: string }>; planstellen: Map & { id: string }>; @@ -168,7 +169,7 @@ type Bestand = { async function bestandLaden(tx: Tx, heute: string): Promise { const [standorte, kostenstellen, einheiten, planstellen, personen, hr] = await Promise.all([ - tx.selectFrom("locations").select(["id", "name", "country"]).execute(), + tx.selectFrom("locations").select(["id", "name", "country", "parent_id"]).execute(), tx.selectFrom("cost_centers").select(["id", "code", "name"]).execute(), tx .selectFrom("org_units as u") @@ -649,6 +650,15 @@ function mitarbeiterZeile( const planstelle = (n: unknown) => bestand.planstellen.get(String(n)); if (zeile.wert("location_id") && !standortId(zeile.wert("location_id"))) { zeile.fehler(`Den Standort „${String(zeile.wert("location_id"))}“ gibt es nicht (auch nicht im Blatt „Standorte“).`, "location_id"); + } else if (zeile.wert("location_id")) { + const id = standortId(zeile.wert("location_id")); + const unter = [...bestand.standorte.values()].filter((s) => s.parent_id === id).map((s) => s.name); + if (unter.length > 0) { + zeile.fehler( + `„${String(zeile.wert("location_id"))}“ fasst mehrere Standorte zusammen. Bitte einen davon angeben: ${unter.sort((a, b) => a.localeCompare(b, "de")).join(", ")}.`, + "location_id" + ); + } } if (zeile.wert("zustaendige_hr_id") && !hrId(zeile.wert("zustaendige_hr_id"))) { zeile.fehler(`„${String(zeile.wert("zustaendige_hr_id"))}“ ist kein aktives HR-Konto.`, "zustaendige_hr_id"); @@ -943,6 +953,34 @@ function eintragZu(zeile: Zeile, aktuell: Datensaetze, person: Person) { return eintrag; } +/** + * Das Verhältnis, wie es gespeichert wird: aus der Auswahl und dem Text zu + * „Sonstige" (lib/verhaeltnis.ts). Steht eine der beiden Spalten nicht in + * der Zeile, gilt der bisherige Wert — der Text aber nur, solange + * „Sonstige" gewählt bleibt. `undefined` bei einem Widerspruch. + */ +function verhaeltnisDerZeile(zeile: Zeile, feld: string, alt: Record | null): string | null | undefined { + const textFeld = `${feld}_sonstige`; + const auswahl = (zeile.gesetzt(feld) ? zeile.wert(feld) : alt?.[feld]) as string | null | undefined; + const text = (zeile.gesetzt(textFeld) ? zeile.wert(textFeld) : auswahl === SONSTIGE ? alt?.[textFeld] : null) as + | string + | null + | undefined; + const ergebnis = verhaeltnisAusDatei(auswahl, text); + if ("fehler" in ergebnis) { + zeile.fehler(ergebnis.fehler, textFeld); + return undefined; + } + return ergebnis.wert; +} + +/** Die geänderten Felder für die SQL-Funktion: Auswahl und Text als ein Verhältnis. */ +function mitVerhaeltnis(g: Map, feld: string, wert: string | null): Record { + const out = Object.fromEntries(g); + delete out[`${feld}_sonstige`]; + return { ...out, [feld]: wert }; +} + function angehoerigerZeile(tx: Tx, zeile: Zeile, bestand: Bestand, aktuell: Datensaetze, { modus, heute }: { modus: Modus; heute: string }) { const person = personZu(zeile, bestand); if (!person) return; @@ -953,9 +991,15 @@ function angehoerigerZeile(tx: Tx, zeile: Zeile, bestand: Bestand, aktuell: Date if (eintrag === null) { if (zeile.wert("entfernen") === "ja") return zeile.fehler("Ein neuer Eintrag lässt sich nicht entfernen.", "entfernen"); if (!pflichtNeu(zeile)) return; + const verhaeltnis = verhaeltnisDerZeile(zeile, "relationship", null); + if (verhaeltnis === undefined) return; const g = zeile.geaendert(null); zeile.schritt("Angehörige:r angelegt", "last_name", async () => { - await rufe(tx, "add_employee_dependent", { employee_id: person.id, effective_date: datum, ...Object.fromEntries(g) }); + await rufe(tx, "add_employee_dependent", { + employee_id: person.id, + effective_date: datum, + ...mitVerhaeltnis(g, "relationship", verhaeltnis), + }); }); return; } @@ -968,6 +1012,8 @@ function angehoerigerZeile(tx: Tx, zeile: Zeile, bestand: Bestand, aktuell: Date }); return; } + const verhaeltnis = verhaeltnisDerZeile(zeile, "relationship", eintrag.werte); + if (verhaeltnis === undefined) return; const g = zeile.geaendert(eintrag.werte, (f) => f !== "id" && f !== "entfernen"); if (g.size === 0) return; const neu = { ...eintrag.werte, ...Object.fromEntries(g) }; @@ -976,7 +1022,7 @@ function angehoerigerZeile(tx: Tx, zeile: Zeile, bestand: Bestand, aktuell: Date dependent_id: id, first_name: neu.first_name, last_name: neu.last_name, - relationship: neu.relationship, + relationship: verhaeltnis, birth_date: neu.birth_date ?? "", sv_nummer: neu.sv_nummer ?? "", }); @@ -993,9 +1039,11 @@ function notfallkontaktZeile(tx: Tx, zeile: Zeile, bestand: Bestand, aktuell: Da if (eintrag === null) { if (zeile.wert("entfernen") === "ja") return zeile.fehler("Ein neuer Eintrag lässt sich nicht entfernen.", "entfernen"); if (!pflichtNeu(zeile)) return; + const verhaeltnis = verhaeltnisDerZeile(zeile, "relation", null); + if (verhaeltnis === undefined) return; const g = zeile.geaendert(null); zeile.schritt("Notfallkontakt angelegt", "name", async () => { - await rufe(tx, "add_emergency_contact", { employee_id: person.id, ...Object.fromEntries(g) }); + await rufe(tx, "add_emergency_contact", { employee_id: person.id, ...mitVerhaeltnis(g, "relation", verhaeltnis) }); }); return; } @@ -1008,10 +1056,12 @@ function notfallkontaktZeile(tx: Tx, zeile: Zeile, bestand: Bestand, aktuell: Da }); return; } + const verhaeltnis = verhaeltnisDerZeile(zeile, "relation", eintrag.werte); + if (verhaeltnis === undefined) return; const g = zeile.geaendert(eintrag.werte, (f) => f !== "id" && f !== "entfernen"); if (g.size === 0) return; const neu = { ...eintrag.werte, ...Object.fromEntries(g) }; zeile.schritt("Notfallkontakt geändert", [...g.keys()][0], async () => { - await rufe(tx, "update_emergency_contact", { id, name: neu.name, phone: neu.phone, relation: neu.relation ?? "" }); + await rufe(tx, "update_emergency_contact", { id, name: neu.name, phone: neu.phone, relation: verhaeltnis ?? "" }); }); } diff --git a/lib/austausch/katalog.ts b/lib/austausch/katalog.ts index e9d3b35..3463216 100644 --- a/lib/austausch/katalog.ts +++ b/lib/austausch/katalog.ts @@ -274,7 +274,7 @@ const MITARBEITER_ROH: Spalte[] = [ }), feld("Vertrag und Arbeitszeit", "Laterale Führung", "Laterale Führung", "is_laterale_fuehrung", JA_NEIN), feld("Vertrag und Arbeitszeit", "C-Level", "C-Level", "c_level", auswahlAusKarte("C-Level"), { - hinweis: "Code oder Code mit Bezeichnung, etwa „C9“ oder „C9 – Mitarbeiter“.", + hinweis: "Der Code aus der Liste, etwa „C9“.", }), feld("Vertrag und Arbeitszeit", "Besonderer Kündigungsschutz", "Besonderer Kündigungsschutz", "has_kuendigungsschutz", JA_NEIN), feld("Vertrag und Arbeitszeit", "Personenkreis", "Kündigungsschutz Personenkreis", "kuendigungsschutz_grund", auswahlAusKarte("Kündigungsschutz Personenkreis"), { @@ -471,8 +471,22 @@ const PERSONALNUMMER_VERWEIS: Spalte = { pflicht: true, }; -/** Verhältnis bei Angehörigen und Notfallkontakten: Liste oder eigener Text. */ -const VERHAELTNIS: Format = { art: "auswahl", optionen: anzeigeAuswahl(EMERGENCY_RELATIONS), frei: true }; +/** + * Verhältnis bei Angehörigen und Notfallkontakten: die Liste wie im Formular, + * und für „Sonstige" eine Spalte daneben mit dem eigenen Text + * (lib/verhaeltnis.ts). + */ +const VERHAELTNIS: Format = { art: "auswahl", optionen: anzeigeAuswahl(EMERGENCY_RELATIONS) }; +const VERHAELTNIS_HINWEIS = "Aus der Liste. Ist es keines davon: „Sonstige“ und den Text in der Spalte daneben."; + +function verhaeltnisSonstige(feld: string): Spalte { + return { + titel: "Verhältnis (Sonstige)", + feld, + format: TEXT, + hinweis: "Nur bei „Sonstige“, etwa Onkel oder Nachbarin. Leer bleibt es bei „Sonstige“.", + }; +} const ENTFERNEN: Spalte = { titel: "Entfernen", @@ -487,6 +501,7 @@ export const BLATT_ANGEHOERIGE: Blatt = { zweck: "Angehörige je Person. Leere ID = neu anlegen.", schluessel: PERSONALNUMMER_VERWEIS, wirksamAb: "Leer = heute. Gilt für Neuanlage und Entfernen.", + bedingungen: [{ feld: "relationship_sonstige", art: "leer", wenn: { feld: "relationship", nicht: "Sonstige" } }], spalten: [ { titel: "ID", feld: "id", format: TEXT, hinweis: "Vergibt das System. Leer = neuer Eintrag." }, { titel: "Nachname", feld: "last_name", format: TEXT, pflichtNeu: true, pflicht: true }, @@ -497,8 +512,9 @@ export const BLATT_ANGEHOERIGE: Blatt = { format: VERHAELTNIS, pflichtNeu: true, pflicht: true, - hinweis: "Aus der Liste oder frei eingetragen, wie „Sonstige“ in der Personalakte.", + hinweis: VERHAELTNIS_HINWEIS, }, + verhaeltnisSonstige("relationship_sonstige"), { titel: "Geburtsdatum", feld: "birth_date", format: DATUM }, { titel: "SV-Nummer", feld: "sv_nummer", format: TEXT }, ENTFERNEN, @@ -510,6 +526,7 @@ export const BLATT_NOTFALLKONTAKTE: Blatt = { zweck: "Notfallkontakte je Person. Leere ID = neu anlegen.", schluessel: PERSONALNUMMER_VERWEIS, wirksamAb: "Leer lassen: Notfallkontakte gelten sofort.", + bedingungen: [{ feld: "relation_sonstige", art: "leer", wenn: { feld: "relation", nicht: "Sonstige" } }], spalten: [ { titel: "ID", feld: "id", format: TEXT, hinweis: "Vergibt das System. Leer = neuer Eintrag." }, { titel: "Name", feld: "name", format: TEXT, pflichtNeu: true, pflicht: true }, @@ -518,8 +535,9 @@ export const BLATT_NOTFALLKONTAKTE: Blatt = { titel: "Verhältnis", feld: "relation", format: VERHAELTNIS, - hinweis: "Aus der Liste oder frei eingetragen, wie „Sonstige“ in der Personalakte.", + hinweis: VERHAELTNIS_HINWEIS, }, + verhaeltnisSonstige("relation_sonstige"), ENTFERNEN, ], }; diff --git a/lib/austausch/laden.ts b/lib/austausch/laden.ts index 3f26b25..95432ff 100644 --- a/lib/austausch/laden.ts +++ b/lib/austausch/laden.ts @@ -8,6 +8,7 @@ import { loadOrgMaps, type OrgMaps } from "../org"; import { loadPlacements, loadReportingLineMap, type Placement } from "../placement"; import { deriveStatusAsOf } from "../reports"; import type { Database } from "../types"; +import { verhaeltnisFuerDatei } from "../verhaeltnis"; import type { Listen } from "./herunterladen"; import type { Datensatz } from "./herunterladen"; @@ -132,7 +133,14 @@ export async function ladeAngehoerige(tx: Tx, personen: readonly Person[]): Prom .orderBy("employee_id") .orderBy("created_at") .execute(); - return zeilen.map((z) => ({ schluessel: nummer.get(z.employee_id)!, kennung: z.id, werte: { ...z } })); + return zeilen.map((z) => { + const v = verhaeltnisFuerDatei(z.relationship); + return { + schluessel: nummer.get(z.employee_id)!, + kennung: z.id, + werte: { ...z, relationship: v.auswahl, relationship_sonstige: v.sonstige }, + }; + }); } export async function ladeNotfallkontakte(tx: Tx, personen: readonly Person[]): Promise { @@ -145,7 +153,14 @@ export async function ladeNotfallkontakte(tx: Tx, personen: readonly Person[]): .orderBy("employee_id") .orderBy("created_at") .execute(); - return zeilen.map((z) => ({ schluessel: nummer.get(z.employee_id)!, kennung: z.id, werte: { ...z } })); + return zeilen.map((z) => { + const v = verhaeltnisFuerDatei(z.relation); + return { + schluessel: nummer.get(z.employee_id)!, + kennung: z.id, + werte: { ...z, relation: v.auswahl, relation_sonstige: v.sonstige }, + }; + }); } export async function ladeHistorie(tx: Tx, personen: readonly Person[], b: Bezuege): Promise { @@ -242,7 +257,13 @@ export async function ladeStandorte(tx: Tx): Promise { */ export async function ladeListen(tx: Tx, heute: string): Promise { const [standorte, jobs, einheiten, stellen, kostenstellen, hr] = await Promise.all([ - tx.selectFrom("locations").select("name").orderBy("name").execute(), + // Ohne zusammenfassende Standorte wie „Shop": auf ihnen sitzt niemand. + tx + .selectFrom("locations as l") + .select("l.name") + .where((eb) => eb.not(eb.exists(eb.selectFrom("locations as u").select("u.id").whereRef("u.parent_id", "=", "l.id")))) + .orderBy("l.name") + .execute(), tx.selectFrom("jobs").select("title").execute(), tx.selectFrom("org_units").select("org_number").where("valid_to", "is", null).orderBy("org_number").execute(), // Nur freie Planstellen: niemand sitzt heute oder später darauf, keine diff --git a/lib/c-level.ts b/lib/c-level.ts index b31e45e..2bca76a 100644 --- a/lib/c-level.ts +++ b/lib/c-level.ts @@ -1,44 +1,21 @@ -// C-Level: die Führungs- bzw. Funktionsstufe einer Person, als Code mit -// Bezeichnung. Fachlich vorgegebene Liste; dieselben Werte stehen in -// chk_c_level (Migration 20261123120000) — tests/unit/c-level.test.ts -// gleicht beide ab. +// C-Level: die Führungs- bzw. Funktionsstufe einer Person als Code. +// Fachlich vorgegebene Liste; dieselben Werte stehen in chk_c_level +// (Migration 20261123120000) — tests/unit/c-level.test.ts gleicht beide ab. // -// Gespeichert wird der Code, angezeigt Code und Bezeichnung zusammen -// („C9 – Mitarbeiter"): der Code allein ist ausserhalb der -// Personalabteilung nicht lesbar, die Bezeichnung allein nicht eindeutig -// genug für die Systeme, die den Code weiterverarbeiten. +// Gespeichert und angezeigt wird nur der Code, in Formularen, Akte, +// Historie, Berichten, Export und Import gleich. // // Freiwillig: leer heisst „nicht erfasst". -export const C_LEVEL = [ - { code: "C1", bezeichnung: "Bereichsleitung" }, - { code: "C11", bezeichnung: "Mitarbeiter gfg." }, - { code: "C2", bezeichnung: "Abteilungsleitung" }, - { code: "C3", bezeichnung: "Experte" }, - { code: "C4", bezeichnung: "Teamleitung" }, - { code: "C8", bezeichnung: "Lehrling" }, - { code: "C9", bezeichnung: "Mitarbeiter" }, - { code: "MG", bezeichnung: "Manager" }, - { code: "P", bezeichnung: "Prokurist" }, - { code: "VD", bezeichnung: "Vorstand" }, -] as const; +export const C_LEVEL_CODES = ["C1", "C11", "C2", "C3", "C4", "C8", "C9", "MG", "P", "VD"] as const; -export type CLevel = (typeof C_LEVEL)[number]["code"]; - -export const C_LEVEL_CODES: readonly CLevel[] = C_LEVEL.map((c) => c.code); +export type CLevel = (typeof C_LEVEL_CODES)[number]; /** Für Anzeigen ohne Wert. */ export const OHNE_C_LEVEL = "Ohne C-Level"; -/** „C9 – Mitarbeiter"; ein unbekannter Code bleibt, wie er ist; leer bleibt leer. */ -export function cLevelText(code: string | null | undefined): string { - if (!code) return ""; - const eintrag = C_LEVEL.find((c) => c.code === code); - return eintrag ? `${eintrag.code} – ${eintrag.bezeichnung}` : code; -} - -/** Auswahl für Formulare: Wert = Code, Beschriftung = Code und Bezeichnung. */ -export const C_LEVEL_AUSWAHL: readonly { value: CLevel; label: string }[] = C_LEVEL.map((c) => ({ - value: c.code, - label: cLevelText(c.code), +/** Auswahl für Formulare: Wert und Beschriftung sind der Code. */ +export const C_LEVEL_AUSWAHL: readonly { value: CLevel; label: string }[] = C_LEVEL_CODES.map((c) => ({ + value: c, + label: c, })); diff --git a/lib/historie-felder.ts b/lib/historie-felder.ts index 7e6de57..da1c09a 100644 --- a/lib/historie-felder.ts +++ b/lib/historie-felder.ts @@ -1,6 +1,6 @@ import { ABSENCE_TYPES, KEINE_TEILZEITVARIANTE, STUNDEN_GRUENDE, statusLabel } from "./absence"; import { anzeige, anzeigeAuswahl } from "./anzeige"; -import { C_LEVEL_AUSWAHL, cLevelText } from "./c-level"; +import { C_LEVEL_AUSWAHL } from "./c-level"; import { GESCHLECHTER } from "./geschlecht"; import { HAY_GRADE_WERTE } from "./hay-grade"; import { KOLLEKTIVVERTRAEGE } from "./kollektivvertrag"; @@ -128,7 +128,6 @@ export const STATUS_FELD = "Status"; /** Ein gespeicherter Feldwert, wie Historie und Protokoll ihn zeigen. */ export function feldwertAnzeige(feld: string, text: string | null): string | null { if (feld === STATUS_FELD && text) return statusLabel(text as EmploymentStatus); - if (feld === "C-Level" && text) return cLevelText(text); return anzeige(text); } diff --git a/lib/report-criteria.ts b/lib/report-criteria.ts index bae0c76..d84dca0 100644 --- a/lib/report-criteria.ts +++ b/lib/report-criteria.ts @@ -3,7 +3,7 @@ import { AUSTRITTSART_LABELS, AUSTRITTSARTEN, BEENDIGUNGSART_WERTE } from "./bee import { fmtDate } from "./format"; import { GESCHLECHTER } from "./geschlecht"; import { HAY_GRADE_WERTE } from "./hay-grade"; -import { C_LEVEL_CODES, cLevelText } from "./c-level"; +import { C_LEVEL_CODES } from "./c-level"; import { KUENDIGUNGSSCHUTZ_GRUENDE } from "./kuendigungsschutz"; import { MITARBEITERARTEN } from "./mitarbeiterart"; import { anzeige } from "./anzeige"; @@ -58,7 +58,7 @@ export const AUSWAHL_KRITERIEN: readonly AuswahlKriterium[] = [ { key: "mitarbeiterart", label: "Anstellungs-/Beschäftigungsart", alle: "Alle Anstellungs-/Beschäftigungsarten", optionen: werte(...MITARBEITERARTEN) }, { key: "kv", label: "Kollektivvertrag", alle: "Alle Kollektivverträge", optionen: werte(...KOLLEKTIVVERTRAEGE) }, { key: "paygrade", label: "Hay-Grade", alle: "Alle Hay-Grades", optionen: werte(...HAY_GRADE_WERTE) }, - { key: "clevel", label: "C-Level", alle: "Alle C-Level", optionen: C_LEVEL_CODES.map((c) => ({ wert: c, label: cLevelText(c) })) }, + { key: "clevel", label: "C-Level", alle: "Alle C-Level", optionen: C_LEVEL_CODES.map((c) => ({ wert: c, label: c })) }, { key: "source", label: "Intern/Extern", alle: "Intern und Extern", optionen: werte("Intern", "Extern") }, { key: "gender", diff --git a/lib/reports-data.ts b/lib/reports-data.ts index 601f683..af16c02 100644 --- a/lib/reports-data.ts +++ b/lib/reports-data.ts @@ -5,6 +5,7 @@ import { ancestorsOf, loadOrgMaps, subtreeOf, type OrgMaps } from "./org"; import { istBereich } from "./org-art"; import { loadKontierungen } from "./cost-centers"; import { loadPlacements } from "./placement"; +import { zuweisbareStandorte } from "./standorte"; import type { Austrittsart } from "./types"; import { LEERE_CRITERIA, passtImSpeicher, type Criteria } from "./report-criteria"; import { werteListe } from "./werteliste"; @@ -181,10 +182,10 @@ export async function loadOrgLookups(tx: Tx): Promise<{ locations: { id: string; name: string }[]; }> { const orgMaps = await loadOrgMaps(tx); - const locations = orgMaps.locationList.map((l) => ({ id: l.id, name: l.name })); + const alleStandorte = orgMaps.locationList.map((l) => ({ id: l.id, name: l.name })); return { - lookups: lookupsFromOrgMaps(orgMaps, locations), + lookups: lookupsFromOrgMaps(orgMaps, alleStandorte), orgMaps, // Jede Ebene, nicht nur die Bereiche: wer eine einzelne Abteilung // auswerten will, soll sie nicht über einen Umweg zusammensuchen müssen. @@ -195,7 +196,9 @@ export async function loadOrgLookups(tx: Tx): Promise<{ depth: orgMaps.depthOf.get(u.id) ?? 0, unitType: u.unit_type, })), - locations, + // Zur Auswahl nur Standorte, auf denen jemand sitzen kann; „Shop" selbst + // ergäbe immer eine leere Auswertung. + locations: zuweisbareStandorte(orgMaps.locationList).map((l) => ({ id: l.id, name: l.name })), }; } diff --git a/lib/reports.ts b/lib/reports.ts index 839071d..6920775 100644 --- a/lib/reports.ts +++ b/lib/reports.ts @@ -2,7 +2,7 @@ import { ABSENCE_TYPES, statusLabel } from "./absence"; import { BEENDIGUNGSART_WERTE } from "./beendigung"; import { fmtName, todayIso, yearsBetweenIso } from "./format"; import { HAY_GRADE_WERTE, OHNE_HAY_GRADE } from "./hay-grade"; -import { C_LEVEL_CODES, cLevelText, OHNE_C_LEVEL } from "./c-level"; +import { C_LEVEL_CODES, OHNE_C_LEVEL } from "./c-level"; import { anzeige } from "./anzeige"; import { WOCHENTAGE } from "./wochentage"; import { werteListe } from "./werteliste"; @@ -267,7 +267,7 @@ export function groupKeyFor(e: ReportEmployee, dim: GroupDimension, lookups: Org return e.is_laterale_fuehrung ? "Ja" : "Nein"; case "c_level": // Eine eigene Gruppe statt „–": wer keine Stufe hat, ist hier eine Antwort. - return e.c_level ? cLevelText(e.c_level) : OHNE_C_LEVEL; + return e.c_level || OHNE_C_LEVEL; case "has_dependents": return e.dependents_count > 0 ? "Ja" : "Nein"; case "teilzeit_art": @@ -304,7 +304,7 @@ export function groupKeyFor(e: ReportEmployee, dim: GroupDimension, lookups: Org const EIGENE_REIHENFOLGE: Partial> = { weekday: WOCHENTAGE, paygrade: [OHNE_HAY_GRADE, ...HAY_GRADE_WERTE], - c_level: [...C_LEVEL_CODES.map(cLevelText), OHNE_C_LEVEL], + c_level: [...C_LEVEL_CODES, OHNE_C_LEVEL], }; function rang(dim: GroupDimension, key: string): number { diff --git a/lib/standorte.ts b/lib/standorte.ts new file mode 100644 index 0000000..9036cbe --- /dev/null +++ b/lib/standorte.ts @@ -0,0 +1,34 @@ +// Standorte mit Unterstandorten (Migration 20261123140000): „Shop" fasst die +// einzelnen Shops zusammen. Eine Person sitzt nur auf einem Standort ohne +// Unterstandorte; die Auswahl zeigt zuerst die oberste Ebene und bei einem +// zusammenfassenden Standort eine zweite Liste. + +export type StandortEintrag = { id: string; name: string; parent_id?: string | null }; + +/** Standorte der obersten Ebene, wie die erste Auswahl sie zeigt. */ +export function oberstandorte(alle: readonly T[]): T[] { + return alle.filter((s) => !s.parent_id); +} + +/** Die Unterstandorte eines Standorts, leer bei einem gewöhnlichen. */ +export function unterstandorte(alle: readonly T[], id: string): T[] { + return id ? alle.filter((s) => s.parent_id === id) : []; +} + +/** Standorte, auf denen eine Person sitzen kann — für Filter und Importlisten. */ +export function zuweisbareStandorte(alle: readonly T[]): T[] { + const gruppen = new Set(alle.map((s) => s.parent_id).filter(Boolean)); + return alle.filter((s) => !gruppen.has(s.id)); +} + +/** Welcher Eintrag der ersten Auswahl zu einem gespeicherten Standort gehört. */ +export function oberstandortVon(alle: readonly StandortEintrag[], id: string): string { + const s = alle.find((x) => x.id === id); + return s ? (s.parent_id ?? s.id) : ""; +} + +/** „Shop W17" unter „Shop" zeigt die zweite Auswahl als „W17". */ +export function kurzname(unter: StandortEintrag, ober: StandortEintrag | undefined): string { + const praefix = ober ? `${ober.name} ` : ""; + return praefix && unter.name.startsWith(praefix) ? unter.name.slice(praefix.length) : unter.name; +} diff --git a/lib/types.ts b/lib/types.ts index 2864dad..8b68cca 100644 --- a/lib/types.ts +++ b/lib/types.ts @@ -197,9 +197,9 @@ export type Database = { public: { Tables: { locations: { - Row: { id: string; name: string; country: string }; - Insert: { id?: string; name: string; country: string }; - Update: Partial<{ id: string; name: string; country: string }>; + Row: { id: string; name: string; country: string; parent_id: string | null }; + Insert: { id?: string; name: string; country: string; parent_id?: string | null }; + Update: Partial<{ id: string; name: string; country: string; parent_id: string | null }>; }; profiles: { Row: { diff --git a/lib/verhaeltnis.ts b/lib/verhaeltnis.ts new file mode 100644 index 0000000..60e4b72 --- /dev/null +++ b/lib/verhaeltnis.ts @@ -0,0 +1,41 @@ +import { EMERGENCY_RELATIONS } from "./types"; + +// Das Verhältnis bei Angehörigen und Notfallkontakten: ein Wert aus der Liste, +// und unter „Sonstige" ein frei eingetragener Text. Gespeichert wird dann der +// Text selbst („Onkel"); steht nichts darin, bleibt „Sonstige" gespeichert +// (components/employees/VerhaeltnisField.tsx). +// +// Die Austauschdatei führt beides wie das Formular in zwei Spalten: die +// Auswahl und daneben den Text zu „Sonstige". So bleibt die Auswahl in Excel +// eine feste Liste, und ein eigener Text hat trotzdem seinen Platz. + +export const SONSTIGE = "Sonstige"; + +/** Ob ein gespeicherter Wert frei eingetragen wurde. */ +export function istFreiesVerhaeltnis(wert: string): boolean { + return wert.trim() !== "" && !(EMERGENCY_RELATIONS as readonly string[]).includes(wert); +} + +/** Der gespeicherte Wert, aufgeteilt in Auswahl und Text zu „Sonstige". */ +export function verhaeltnisFuerDatei(gespeichert: string | null | undefined): { auswahl: string | null; sonstige: string | null } { + const wert = gespeichert ?? ""; + if (istFreiesVerhaeltnis(wert)) return { auswahl: SONSTIGE, sonstige: wert }; + return { auswahl: wert || null, sonstige: null }; +} + +/** + * Auswahl und Text aus der Datei zum Wert, der gespeichert wird. Ein Text + * ohne „Sonstige" ist ein Widerspruch; welche der beiden Angaben gilt, lässt + * sich nicht entscheiden. + */ +export function verhaeltnisAusDatei( + auswahl: string | null | undefined, + sonstige: string | null | undefined +): { wert: string | null } | { fehler: string } { + const text = sonstige?.trim() ?? ""; + if (text && auswahl !== SONSTIGE) { + return { fehler: `Ein Text zu „Sonstige“ steht nur bei der Auswahl „Sonstige“.` }; + } + if (auswahl === SONSTIGE && text) return { wert: text }; + return { wert: auswahl ?? null }; +} diff --git a/tests/components/HireWizardEntwurf.test.tsx b/tests/components/HireWizardEntwurf.test.tsx index 3e66106..064c121 100644 --- a/tests/components/HireWizardEntwurf.test.tsx +++ b/tests/components/HireWizardEntwurf.test.tsx @@ -35,7 +35,7 @@ vi.mock("@/actions/hireDrafts", () => ({ })); vi.mock("next/navigation", () => ({ useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }) })); -const LOCATIONS = [{ id: "l1", name: "Wien", country: "Österreich" }]; +const LOCATIONS = [{ id: "l1", name: "Wien", country: "Österreich", parent_id: null }]; function zeige(resumeDraft: { id: string; step: number; payload: Record } | null = null) { const onClose = vi.fn(); diff --git a/tests/components/HireWizardSchritte.test.tsx b/tests/components/HireWizardSchritte.test.tsx index d6e9eb1..a4a97e6 100644 --- a/tests/components/HireWizardSchritte.test.tsx +++ b/tests/components/HireWizardSchritte.test.tsx @@ -40,7 +40,7 @@ const POSITION = { kostenstelle: null, } as unknown as OpenPositionResolved; -const LOCATIONS = [{ id: "l1", name: "Wien", country: "AT" }]; +const LOCATIONS = [{ id: "l1", name: "Wien", country: "AT", parent_id: null }]; /** Ein Entwurf, in dem alles bis einschliesslich Vertrag vollständig ist. */ const VOLLSTAENDIG = { diff --git a/tests/components/StandortAuswahl.test.tsx b/tests/components/StandortAuswahl.test.tsx new file mode 100644 index 0000000..111aa86 --- /dev/null +++ b/tests/components/StandortAuswahl.test.tsx @@ -0,0 +1,53 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import { useState } from "react"; +import { describe, expect, it } from "vitest"; +import { StandortAuswahl } from "@/components/employees/StandortAuswahl"; + +const STANDORTE = [ + { id: "hernals", name: "Wien-Hernals", country: "Österreich", parent_id: null }, + { id: "shop", name: "Shop", country: "Österreich", parent_id: null }, + { id: "w17", name: "Shop W17", country: "Österreich", parent_id: "shop" }, + { id: "wodo", name: "Shop Wodo", country: "Österreich", parent_id: "shop" }, +]; + +function Formular({ start = "" }: { start?: string }) { + const [wert, setWert] = useState(start); + return ( + <> + + {wert} + + ); +} + +describe("StandortAuswahl", () => { + it("zeigt zuerst nur die oberste Ebene", () => { + render(); + const optionen = Array.from((screen.getByLabelText(/^Standort/) as HTMLSelectElement).options).map((o) => o.value); + expect(optionen).toEqual(["", "hernals", "shop"]); + expect(screen.queryByLabelText(/^Shop/)).not.toBeInTheDocument(); + }); + + it("verlangt unter „Shop“ den einzelnen Shop und meldet erst ihn", () => { + render(); + fireEvent.change(screen.getByLabelText(/^Standort/), { target: { value: "shop" } }); + expect(screen.getByTestId("stand").textContent).toBe(""); + const shops = screen.getByLabelText(/^Shop/) as HTMLSelectElement; + expect(Array.from(shops.options).map((o) => o.text)).toEqual(["Bitte wählen…", "W17", "Wodo"]); + fireEvent.change(shops, { target: { value: "wodo" } }); + expect(screen.getByTestId("stand").textContent).toBe("wodo"); + }); + + it("öffnet einen gespeicherten Shop mit beiden Auswahlen", () => { + render(); + expect((screen.getByLabelText(/^Standort/) as HTMLSelectElement).value).toBe("shop"); + expect((screen.getByLabelText(/^Shop/) as HTMLSelectElement).value).toBe("w17"); + }); + + it("schliesst die zweite Auswahl beim Wechsel auf einen gewöhnlichen Standort", () => { + render(); + fireEvent.change(screen.getByLabelText(/^Standort/), { target: { value: "hernals" } }); + expect(screen.getByTestId("stand").textContent).toBe("hernals"); + expect(screen.queryByLabelText(/^Shop/)).not.toBeInTheDocument(); + }); +}); diff --git a/tests/components/UebernahmeWizard.test.tsx b/tests/components/UebernahmeWizard.test.tsx index e233b8e..529b249 100644 --- a/tests/components/UebernahmeWizard.test.tsx +++ b/tests/components/UebernahmeWizard.test.tsx @@ -60,7 +60,7 @@ const MIT_STAATSBUERGERSCHAFT = { ...EXTERN, nationality: "Deutschland" } as Emp function zeige(employee: EmployeeRow = MIT_STAATSBUERGERSCHAFT) { return render( - {}} employee={employee} locations={[{ id: "l1", name: "Wien", country: "Österreich" }]} /> + {}} employee={employee} locations={[{ id: "l1", name: "Wien", country: "Österreich", parent_id: null }]} /> ); } @@ -102,7 +102,7 @@ describe("Übernahme", () => { open onClose={() => {}} employee={{ ...EXTERN, birth_date: "2090-01-01" } as EmployeeRow} - locations={[{ id: "l1", name: "Wien", country: "Österreich" }]} + locations={[{ id: "l1", name: "Wien", country: "Österreich", parent_id: null }]} /> ); diff --git a/tests/components/VertragTab.test.tsx b/tests/components/VertragTab.test.tsx index ceab9d8..c8dc098 100644 --- a/tests/components/VertragTab.test.tsx +++ b/tests/components/VertragTab.test.tsx @@ -90,9 +90,9 @@ describe("VertragTab — Merkmale", () => { expect(wertZu("Betriebsrat")).toBe("Nein"); }); - it("zeigt C-Level mit Code und Bezeichnung", () => { + it("zeigt C-Level als Code", () => { render(); - expect(wertZu("C-Level")).toBe("C4 – Teamleitung"); + expect(wertZu("C-Level")).toBe("C4"); }); it("zeigt bei C-Level ohne Angabe einen Strich", () => { diff --git a/tests/unit/austausch-katalog.test.ts b/tests/unit/austausch-katalog.test.ts index 39f8964..0da718f 100644 --- a/tests/unit/austausch-katalog.test.ts +++ b/tests/unit/austausch-katalog.test.ts @@ -117,6 +117,7 @@ const FREIE_EINGABE = new Set([ "Nachname", "Vorname", "SV-Nummer", "Adresse", "Postleitzahl", "Ort", "Private E-Mail", "Firmen-E-Mail", "Private Telefonnummer", "Cornerstone-ID", "Erlernter Beruf", "Angaben zur Übernahme", "Wochenstunden", "Arbeitszeitmodell", "Wochenstunden ab Rückkehr", "ID", "Name", "Telefonnummer", "Bezeichnung", + "Verhältnis (Sonstige)", ]); describe("Auswahl in der Datei", () => { diff --git a/tests/unit/c-level.test.ts b/tests/unit/c-level.test.ts index 7b0aa8c..fd333d5 100644 --- a/tests/unit/c-level.test.ts +++ b/tests/unit/c-level.test.ts @@ -1,7 +1,7 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; -import { C_LEVEL_AUSWAHL, C_LEVEL_CODES, cLevelText } from "@/lib/c-level"; +import { C_LEVEL_AUSWAHL, C_LEVEL_CODES } from "@/lib/c-level"; import { feldwertAnzeige, optionenFuer } from "@/lib/historie-felder"; import { parseCriteria } from "@/lib/report-criteria"; @@ -22,18 +22,15 @@ describe("C-Level", () => { expect(werteAusDerBedingung()).toEqual([...C_LEVEL_CODES]); }); - it("zeigt Code und Bezeichnung", () => { - expect(cLevelText("C9")).toBe("C9 – Mitarbeiter"); - expect(cLevelText("MG")).toBe("MG – Manager"); - expect(cLevelText(null)).toBe(""); - expect(cLevelText("XY")).toBe("XY"); - expect(C_LEVEL_AUSWAHL[0]).toEqual({ value: "C1", label: "C1 – Bereichsleitung" }); + it("zeigt nur den Code", () => { + expect(C_LEVEL_AUSWAHL[0]).toEqual({ value: "C1", label: "C1" }); + expect(C_LEVEL_AUSWAHL.every((o) => o.value === o.label)).toBe(true); + expect(feldwertAnzeige("C-Level", "C4")).toBe("C4"); }); it("berichtigt in der Historie mit derselben Auswahl, das abgelöste Ja/Nein getrennt davon", () => { expect(optionenFuer("C-Level", "C4")?.map((o) => o.value)).toEqual([...C_LEVEL_CODES]); expect(optionenFuer("C-Level (Ja/Nein)", "true")?.map((o) => o.value)).toEqual(["true", "false"]); - expect(feldwertAnzeige("C-Level", "C4")).toBe("C4 – Teamleitung"); }); it("filtert im Bericht nach mehreren Stufen und verwirft Unbekanntes", () => { diff --git a/tests/unit/org.test.ts b/tests/unit/org.test.ts index 401485e..6491551 100644 --- a/tests/unit/org.test.ts +++ b/tests/unit/org.test.ts @@ -14,7 +14,7 @@ const units: OrgUnit[] = [ { id: "cnc", org_number: "22002000", name: "CNC", parent_id: "fert", unit_type: "Team" }, { id: "it", org_number: "20200000", name: "IT", parent_id: "gmbh", unit_type: "Bereich" }, ]; -const locations = [{ id: "loc-1", name: "Wien-Hernals", country: "Österreich" }]; +const locations = [{ id: "loc-1", name: "Wien-Hernals", country: "Österreich", parent_id: null }]; const maps = buildOrgMaps(units, locations); describe("buildOrgMaps", () => { diff --git a/tests/unit/reports.test.ts b/tests/unit/reports.test.ts index 9746283..6de553f 100644 --- a/tests/unit/reports.test.ts +++ b/tests/unit/reports.test.ts @@ -135,7 +135,7 @@ describe("groupKeyFor", () => { }); it("gruppiert nach C-Level mit Code und Bezeichnung, ohne Angabe als eigene Gruppe", () => { - expect(groupKeyFor(emp({ c_level: "C9" }), "c_level", lookups)).toBe("C9 – Mitarbeiter"); + expect(groupKeyFor(emp({ c_level: "C9" }), "c_level", lookups)).toBe("C9"); expect(groupKeyFor(emp({ c_level: null }), "c_level", lookups)).toBe("Ohne C-Level"); }); diff --git a/tests/unit/verhaeltnis-standorte.test.ts b/tests/unit/verhaeltnis-standorte.test.ts new file mode 100644 index 0000000..89e42ca --- /dev/null +++ b/tests/unit/verhaeltnis-standorte.test.ts @@ -0,0 +1,79 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { BLATT_ANGEHOERIGE, BLATT_NOTFALLKONTAKTE } from "@/lib/austausch/katalog"; +import { kurzname, oberstandorte, oberstandortVon, unterstandorte, zuweisbareStandorte } from "@/lib/standorte"; +import { verhaeltnisAusDatei, verhaeltnisFuerDatei } from "@/lib/verhaeltnis"; + +describe("Verhältnis in der Austauschdatei", () => { + it("teilt einen frei eingetragenen Wert in „Sonstige“ und den Text", () => { + expect(verhaeltnisFuerDatei("Onkel")).toEqual({ auswahl: "Sonstige", sonstige: "Onkel" }); + expect(verhaeltnisFuerDatei("Kind")).toEqual({ auswahl: "Kind", sonstige: null }); + expect(verhaeltnisFuerDatei("Sonstige")).toEqual({ auswahl: "Sonstige", sonstige: null }); + expect(verhaeltnisFuerDatei(null)).toEqual({ auswahl: null, sonstige: null }); + }); + + it("speichert bei „Sonstige“ den Text, ohne Text „Sonstige“", () => { + expect(verhaeltnisAusDatei("Sonstige", " Nachbarin ")).toEqual({ wert: "Nachbarin" }); + expect(verhaeltnisAusDatei("Sonstige", null)).toEqual({ wert: "Sonstige" }); + expect(verhaeltnisAusDatei("Kind", null)).toEqual({ wert: "Kind" }); + expect(verhaeltnisAusDatei(null, null)).toEqual({ wert: null }); + }); + + it("weist einen Text ohne „Sonstige“ ab", () => { + expect(verhaeltnisAusDatei("Kind", "Onkel")).toHaveProperty("fehler"); + expect(verhaeltnisAusDatei(null, "Onkel")).toHaveProperty("fehler"); + }); + + it("hat in beiden Blättern die Spalte gleich hinter der Auswahl, die Auswahl ohne freie Eingabe", () => { + for (const [blatt, feld] of [ + [BLATT_ANGEHOERIGE, "relationship"], + [BLATT_NOTFALLKONTAKTE, "relation"], + ] as const) { + const i = blatt.spalten.findIndex((s) => s.feld === feld); + expect(blatt.spalten[i + 1].feld).toBe(`${feld}_sonstige`); + const format = blatt.spalten[i].format; + expect(format.art === "auswahl" && format.frei).toBeFalsy(); + } + }); +}); + +const ALLE = [ + { id: "hernals", name: "Wien-Hernals", parent_id: null }, + { id: "shop", name: "Shop", parent_id: null }, + { id: "w17", name: "Shop W17", parent_id: "shop" }, + { id: "hbf", name: "Shop Wien Hauptbahnhof", parent_id: "shop" }, +]; + +describe("Standorte mit Unterstandorten", () => { + it("zeigt zuerst die oberste Ebene und unter „Shop“ die Shops", () => { + expect(oberstandorte(ALLE).map((s) => s.id)).toEqual(["hernals", "shop"]); + expect(unterstandorte(ALLE, "shop").map((s) => s.id)).toEqual(["w17", "hbf"]); + expect(unterstandorte(ALLE, "hernals")).toEqual([]); + expect(kurzname(ALLE[3], ALLE[1])).toBe("Wien Hauptbahnhof"); + }); + + it("findet zu einem gespeicherten Shop die erste Auswahl", () => { + expect(oberstandortVon(ALLE, "w17")).toBe("shop"); + expect(oberstandortVon(ALLE, "hernals")).toBe("hernals"); + expect(oberstandortVon(ALLE, "")).toBe(""); + }); + + it("bietet in Filtern nur Standorte an, auf denen jemand sitzen kann", () => { + expect(zuweisbareStandorte(ALLE).map((s) => s.id)).toEqual(["hernals", "w17", "hbf"]); + }); + + it("legt in der Migration genau die sechs Shops an", () => { + const sql = readFileSync(join(process.cwd(), "db/migrations/20261123140000_standort_shop.sql"), "utf8"); + const einfuegen = sql.match(/from \(values ([^\n]+)\) v\(name\)\non conflict/)?.[1]; + expect(einfuegen).toBeDefined(); + expect([...einfuegen!.matchAll(/'([^']+)'/g)].map((m) => m[1])).toEqual([ + "Shop W17", + "Shop Wodo", + "Shop Parndorf", + "Shop Donaupark", + "Shop W1", + "Shop Wien Hauptbahnhof", + ]); + }); +});