Standort Shop mit Unterauswahl; C-Level nur als Code; Sonstige im Import
All checks were successful
CI / Lint, Typen, Tests, Build (push) Successful in 12m26s
CI / Migrationen auf leerer Datenbank (push) Successful in 10m22s
CI / Ausrollen (push) Successful in 7s

Standort: locations.parent_id, eine Ebene. Neu "Shop" mit sechs Shops
(Shop W17, Shop Wodo, Shop Parndorf, Shop Donaupark, Shop W1, Shop Wien
Hauptbahnhof). Personen sitzen nur auf Standorten ohne Unterstandorte;
zwei Trigger halten das auch fuer Import und Nachtlauf fest. Einstellung,
Externe und Versetzung zeigen bei "Shop" eine zweite Auswahl
(StandortAuswahl). Filter in Liste und Berichten und die Importliste
bieten "Shop" selbst nicht an; der Import nennt bei "Shop" die Shops.
rauchtest.sql und vertragsangaben.sql waehlen einen zuweisbaren Standort.

C-Level: ueberall nur der Code (Formular, Akte, Zusammenfassung,
Historie, Berichte, Import). Export ohne Spalte "C-Level Bezeichnung".

Angehoerige und Notfallkontakte im Import wie im Formular: Auswahl als
feste Liste und daneben "Verhaeltnis (Sonstige)" fuer den eigenen Text.
Gespeichert wird bei "Sonstige" der Text; ein Text ohne "Sonstige" ist
ein Fehler. Der Download teilt einen eigenen Text in beide Spalten.

Geprueft: lint, tsc, types:check, npm test, waechter; Migrationen auf
leerer Datenbank zweimal (Nichts anzuwenden), rauchtest.sql,
vertragsangaben.sql; als alpenwerk_app: Einstellung auf "Shop" abgewiesen,
auf "Shop W17" angenommen, Wechsel auf "Shop" abgewiesen, auf "Shop Wodo"
angenommen, Unterstandort unter einem Shop abgewiesen.
This commit is contained in:
2026-11-23 11:50:45 +01:00
parent e1ef57d44b
commit 79979216e4
37 changed files with 587 additions and 113 deletions

View File

@@ -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 },

View File

@@ -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<string, number>;
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}
>
<option value="">Alle Standorte</option>
{locations.map((l) => (
{zuweisbareStandorte(locations).map((l) => (
<option key={l.id} value={l.id}>
{l.name}
</option>

View File

@@ -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 (
<>
<SelectField
label="Standort"
required={required}
value={ober}
onChange={(id) => {
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 && (
<SelectField
label={oberEintrag?.name ?? "Standort"}
required
value={unter.some((s) => s.id === value) ? value : ""}
onChange={onChange}
placeholder="Bitte wählen…"
options={unter.map((s) => ({ value: s.id, label: kurzname(s, oberEintrag) }))}
hint={hint}
/>
)}
</>
);
}

View File

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

View File

@@ -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 && (
<SelectField
label="Standort"
<StandortAuswahl
value={standort}
onChange={setStandort}
options={locations.map((l) => ({ value: l.id, label: l.name }))}
standorte={locations}
hint="Wechselt mit der Versetzung zum selben Tag; sonst bleibt der bisherige."
/>
)}

View File

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

View File

@@ -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<string, unknown> } | null;
initialPositionId?: string;
};

View File

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

View File

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

View File

@@ -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<HireDraftData>) => 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 })}
/>
<SelectField
label="Standort"
<StandortAuswahl
required
mitLand
value={draft.locationId}
onChange={(locationId) => update({ locationId })}
placeholder="Bitte wählen…"
options={locations.map((l) => ({ value: l.id, label: `${l.name} (${l.country})` }))}
standorte={locations}
/>
</div>
);

View File

@@ -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<HireDraftData>) => 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
/>
<TextField label="Private Telefonnummer" type="tel" value={draft.phone} onChange={(phone) => update({ phone })} />
</div>
<SelectField
label="Standort"
<StandortAuswahl
required
mitLand
value={draft.locationId}
onChange={(locationId) => update({ locationId })}
placeholder="Bitte wählen…"
options={locations.map((l) => ({ value: l.id, label: `${l.name} (${l.country})` }))}
standorte={locations}
/>
<ZustaendigeHrField value={draft.zustaendigeHrId} onChange={(zustaendigeHrId) => update({ zustaendigeHrId })} />
</div>

View File

@@ -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(", ") : "–"],
];

View File

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

View File

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

View File

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

View File

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

View File

@@ -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<string, unknown>): P
/** Lookups, die sich mit jedem Blatt ändern können: was die Datei neu anlegt, gilt sofort. */
type Bestand = {
standorte: Map<string, { id: string; name: string; country: string }>;
standorte: Map<string, { id: string; name: string; country: string; parent_id: string | null }>;
kostenstellen: Map<string, { id: string; name: string }>;
einheiten: Map<string, Record<string, unknown> & { id: string }>;
planstellen: Map<string, Record<string, unknown> & { id: string }>;
@@ -168,7 +169,7 @@ type Bestand = {
async function bestandLaden(tx: Tx, heute: string): Promise<Bestand> {
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<string, unknown> | 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<string, unknown>, feld: string, wert: string | null): Record<string, unknown> {
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 ?? "" });
});
}

View File

@@ -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,
],
};

View File

@@ -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<Datensatz[]> {
@@ -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<Datensatz[]> {
@@ -242,7 +257,13 @@ export async function ladeStandorte(tx: Tx): Promise<Datensatz[]> {
*/
export async function ladeListen(tx: Tx, heute: string): Promise<Listen> {
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

View File

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

View File

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

View File

@@ -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",

View File

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

View File

@@ -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<Record<GroupDimension, readonly string[]>> = {
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 {

34
lib/standorte.ts Normal file
View File

@@ -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<T extends StandortEintrag>(alle: readonly T[]): T[] {
return alle.filter((s) => !s.parent_id);
}
/** Die Unterstandorte eines Standorts, leer bei einem gewöhnlichen. */
export function unterstandorte<T extends StandortEintrag>(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<T extends StandortEintrag>(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;
}

View File

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

41
lib/verhaeltnis.ts Normal file
View File

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

View File

@@ -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<string, unknown> } | null = null) {
const onClose = vi.fn();

View File

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

View File

@@ -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 (
<>
<StandortAuswahl required value={wert} onChange={setWert} standorte={STANDORTE} />
<output data-testid="stand">{wert}</output>
</>
);
}
describe("StandortAuswahl", () => {
it("zeigt zuerst nur die oberste Ebene", () => {
render(<Formular />);
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(<Formular />);
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(<Formular start="w17" />);
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(<Formular start="w17" />);
fireEvent.change(screen.getByLabelText(/^Standort/), { target: { value: "hernals" } });
expect(screen.getByTestId("stand").textContent).toBe("hernals");
expect(screen.queryByLabelText(/^Shop/)).not.toBeInTheDocument();
});
});

View File

@@ -60,7 +60,7 @@ const MIT_STAATSBUERGERSCHAFT = { ...EXTERN, nationality: "Deutschland" } as Emp
function zeige(employee: EmployeeRow = MIT_STAATSBUERGERSCHAFT) {
return render(
<ToastProvider>
<UebernahmeWizard open onClose={() => {}} employee={employee} locations={[{ id: "l1", name: "Wien", country: "Österreich" }]} />
<UebernahmeWizard open onClose={() => {}} employee={employee} locations={[{ id: "l1", name: "Wien", country: "Österreich", parent_id: null }]} />
</ToastProvider>
);
}
@@ -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 }]}
/>
</ToastProvider>
);

View File

@@ -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(<VertragTab employee={mitarbeiter({ c_level: "C4" })} />);
expect(wertZu("C-Level")).toBe("C4 – Teamleitung");
expect(wertZu("C-Level")).toBe("C4");
});
it("zeigt bei C-Level ohne Angabe einen Strich", () => {

View File

@@ -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", () => {

View File

@@ -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", () => {

View File

@@ -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", () => {

View File

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

View File

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