From d25778d2fa339606ba33ffa7a9bbe87e6c42ccb3 Mon Sep 17 00:00:00 2001 From: Andrei Laas Date: Mon, 19 Oct 2026 17:17:02 +0200 Subject: [PATCH] Mehrere Notfallkontakte, Planstelle nicht vor ihrer Einheit, Anstehend fuehrt in die Historie, Uebernahme, Meine Notizen - Notfallkontakte: eigene Tabelle employee_emergency_contacts (Migration 20261019160000), beliebig viele je Person, angelegt, geaendert und entfernt wie Angehoerige (add_/update_/delete_emergency_contact, mit Historie und Protokoll). Bestand uebernommen. Verhaeltnis-Liste wie bei den Angehoerigen (Ehepartner, Lebenspartner, Kind, Sonstige mit Freitext). Neueinstellung, Wiedereintritt, Import und Mitarbeiterexport schreiben und lesen die Tabelle. - Planstelle beginnt nicht vor und nicht nach dem Bestehen ihrer Organisationseinheit: Ausloeser an om_positions (Migration 20261019150000), gilt fuer Anlegen, Aendern und Klonen. - Anstehend auf der Uebersicht: Klick oeffnet die Akte im Reiter Historie, bei einer Wiedervorlage im Reiter HR-Notizen (?tab=). - Uebernahme: Vertrag zeigt Besetzungsart und "Uebernahme Ja/Nein" aus der Historie; die Kachel Eintritte (YTD) zaehlt Uebernahmen mit. - Glocke: "Meine Notizen" schaltet bei hinzugewaehlten Kollegen auf nur die eigenen Notizen um. Rauchtest Schritt 18. Geprueft: lint, tsc, types:check, 921 Tests, Waechter --- actions/employees.ts | 61 +++++- app/(app)/employees/[id]/page.tsx | 9 +- app/api/export/employees/route.ts | 18 +- components/dashboard/AnstehendListe.tsx | 5 +- components/employees/EmployeeDetail.tsx | 34 +++- components/employees/NotfallkontaktModal.tsx | 64 +++---- .../employees/NotfallkontaktSection.tsx | 169 +++++++---------- .../employees/panels/DatenAendernPanel.tsx | 18 +- components/employees/tabs/StammdatenTab.tsx | 22 ++- components/employees/tabs/VertragTab.tsx | 14 +- components/shell/NotesBell.tsx | 30 ++- ...019150000_planstelle_nicht_vor_einheit.sql | 63 +++++++ ...20261019160000_mehrere_notfallkontakte.sql | 177 ++++++++++++++++++ db/tests/rauchtest.sql | 59 ++++-- lib/dashboard-data.ts | 4 +- lib/employee-detail-data.ts | 10 + lib/export-auswahl.ts | 17 +- lib/import/load.ts | 18 +- lib/kpi-erklaerungen.ts | 2 +- lib/types.ts | 38 ++-- tests/components/AnstehendListe.test.tsx | 9 +- tests/components/NotesBell.test.tsx | 14 ++ tests/components/VerhaeltnisField.test.tsx | 5 +- tests/unit/historie-felder.test.ts | 2 +- 24 files changed, 642 insertions(+), 220 deletions(-) create mode 100644 db/migrations/20261019150000_planstelle_nicht_vor_einheit.sql create mode 100644 db/migrations/20261019160000_mehrere_notfallkontakte.sql diff --git a/actions/employees.ts b/actions/employees.ts index 9a13ed1..51bd4f9 100644 --- a/actions/employees.ts +++ b/actions/employees.ts @@ -156,8 +156,19 @@ export async function hireEmployee(payload: { // Einzige Mutation, deren Rückgabewert gebraucht wird: die neue // Personen-Kennung, damit die Oberfläche direkt auf die Akte springen kann. try { + // Der Notfallkontakt geht in die eigene Tabelle (20261019160000), nicht + // in die Spalten an employees — dieselbe Stelle, an der die Akte liest. + const { emergency_contact_name, emergency_contact_phone, emergency_contact_relation, ...person } = payload; const employeeId = await withUser(await currentUserId(), async (tx) => { - const id = (await callFunction(tx, "hire_employee", payload as Record)) as string; + const id = (await callFunction(tx, "hire_employee", person as Record)) as string; + if (emergency_contact_name?.trim()) { + await callFunction(tx, "add_emergency_contact", { + employee_id: id, + name: emergency_contact_name, + phone: emergency_contact_phone, + relation: emergency_contact_relation, + }); + } // In derselben Transaktion: eine Einstellung ohne Checkliste wäre eine // halb erfasste Einstellung, und sie später nachzureichen hiesse, dass // jemand daran denken muss. @@ -345,9 +356,30 @@ export async function rehireEmployee(payload: { */ [feld: string]: unknown; }): Promise { + // Notfallkontakte stehen in eigener Tabelle (20261019160000). Was der + // Assistent zeigt, kommt hinzu, wenn es dort noch nicht steht — die + // Kontakte vom ersten Eintritt bleiben. + const { emergency_contact_name, emergency_contact_phone, emergency_contact_relation, ...rest } = payload; + const kontaktName = typeof emergency_contact_name === "string" ? emergency_contact_name.trim() : ""; + const kontaktTelefon = typeof emergency_contact_phone === "string" ? emergency_contact_phone.trim() : ""; try { await withUser(await currentUserId(), async (tx) => { - await callFunction(tx, "rehire_employee", payload as unknown as Record); + await callFunction(tx, "rehire_employee", rest as unknown as Record); + if (kontaktName && kontaktTelefon) { + const vorhanden = await tx + .selectFrom("employee_emergency_contacts") + .select(["name", "phone"]) + .where("employee_id", "=", payload.employee_id) + .execute(); + if (!vorhanden.some((k) => k.name === kontaktName && k.phone === kontaktTelefon)) { + await callFunction(tx, "add_emergency_contact", { + employee_id: payload.employee_id, + name: kontaktName, + phone: kontaktTelefon, + relation: emergency_contact_relation, + }); + } + } // Auch bei der Wiedereinstellung: Dienstzettel, Bankverbindung und // E-Card sind wieder zu erledigen. Die Punkte vom ersten Eintritt // bleiben stehen — start_onboarding legt nur an, was fehlt, statt @@ -539,6 +571,31 @@ export async function eintrittPlanstelleBerichtigen(payload: { employee_id: stri return callRpc("eintritt_planstelle_berichtigen", payload, [`/employees/${payload.employee_id}`, "/employees", "/positions"]); } +// ── Notfallkontakte (20261019160000) ───────────────────────────────────── +export async function addEmergencyContact(payload: { + employee_id: string; + name: string; + phone: string; + relation?: string; +}): Promise { + return callRpc("add_emergency_contact", payload, [`/employees/${payload.employee_id}`]); +} + +export async function updateEmergencyContact(payload: { + id: string; + employee_id: string; + name: string; + phone: string; + relation?: string; +}): Promise { + const { employee_id, ...angaben } = payload; + return callRpc("update_emergency_contact", angaben, [`/employees/${employee_id}`]); +} + +export async function deleteEmergencyContact(payload: { id: string; employee_id: string }): Promise { + return callRpc("delete_emergency_contact", { id: payload.id }, [`/employees/${payload.employee_id}`]); +} + /** Eine irrtümlich erfasste Notiz löschen — nur durch die Verfasserin. */ export async function deleteEmployeeNote(payload: { note_id: string; employee_id: string }): Promise { return callRpc("delete_employee_note", { note_id: payload.note_id }, [`/employees/${payload.employee_id}`, "/"]); diff --git a/app/(app)/employees/[id]/page.tsx b/app/(app)/employees/[id]/page.tsx index c50af56..62fd4bd 100644 --- a/app/(app)/employees/[id]/page.tsx +++ b/app/(app)/employees/[id]/page.tsx @@ -6,10 +6,11 @@ import { todayIso } from "@/lib/format"; import { breadcrumbLabel } from "@/lib/org"; import { loadEmployeeDetail } from "@/lib/employee-detail-data"; -type PageProps = { params: Promise<{ id: string }> }; +type PageProps = { params: Promise<{ id: string }>; searchParams: Promise<{ tab?: string }> }; -export default async function EmployeeDetailPage({ params }: PageProps) { +export default async function EmployeeDetailPage({ params, searchParams }: PageProps) { const { id } = await params; + const { tab } = await searchParams; const today = todayIso(); // Was die Akte liest und in wie vielen Rundreisen, steht in @@ -18,7 +19,7 @@ export default async function EmployeeDetailPage({ params }: PageProps) { const data = await withUser(userId, (tx) => loadEmployeeDetail(tx, id, today)); if (!data) notFound(); - const { employee, line, reports, history, dependents, notes, orgMaps, placement, kostenstelle, onboarding, offboarding, openPositions, byId } = data; + const { employee, line, reports, history, dependents, notfallkontakte, notes, orgMaps, placement, kostenstelle, onboarding, offboarding, openPositions, byId } = data; return ( ({ ...n, author_user_id: null, vonMir: n.author_user_id === userId }))} locations={orgMaps.locationList} openPositions={openPositions} today={today} + startTab={tab} /> ); } diff --git a/app/api/export/employees/route.ts b/app/api/export/employees/route.ts index cf215ca..0c6df8e 100644 --- a/app/api/export/employees/route.ts +++ b/app/api/export/employees/route.ts @@ -20,11 +20,11 @@ export async function GET(request: NextRequest) { if ("denied" in gate) return gate.denied; const { format, asOf, filters } = exportParameter(request.nextUrl.searchParams); - const { rows, lookups, managerName, dependentsCounts, hrName } = await withUser(gate.userId, (tx) => + const { rows, lookups, managerName, dependentsCounts, hrName, notfallkontakte } = await withUser(gate.userId, (tx) => ladeExportMitarbeiter(tx, { asOf, filters }) ); - const columns = employeeExportColumns(lookups, managerName, dependentsCounts, asOf, hrName); + const columns = employeeExportColumns(lookups, managerName, dependentsCounts, asOf, hrName, notfallkontakte); const filename = exportFilename("mitarbeiter-export", format); const body = format === "xlsx" ? await toXlsx(rows, columns, "Mitarbeiter") : toCsv(rows, columns); @@ -38,7 +38,8 @@ function employeeExportColumns( managerName: Map, dependentsCounts: Map, asOf?: string, - hrName: Map = new Map() + hrName: Map = new Map(), + notfallkontakte: Map = new Map() ): ExportColumn[] { const columns: ExportColumn[] = [ { header: "Pers.-Nr.", get: (e) => e.personnel_number }, @@ -98,9 +99,14 @@ function employeeExportColumns( { header: "Bescheid bis", get: (e) => e.behinderung_bis, kind: "date" }, { header: "Teilzeitvariante", get: (e) => e.teilzeit_art ?? "" }, { header: "Teilzeit bis", get: (e) => e.teilzeit_bis, kind: "date" }, - { header: "Notfallkontakt", get: (e) => e.emergency_contact_name ?? "" }, - { header: "Notfallkontakt Telefon", get: (e) => e.emergency_contact_phone ?? "" }, - { header: "Notfallkontakt Verhältnis", get: (e) => anzeige(e.emergency_contact_relation) ?? "" }, + // Mehrere Kontakte je Person: in jeder Spalte durch „; " getrennt, in + // derselben Reihenfolge — der zweite Name gehört zur zweiten Nummer. + { header: "Notfallkontakt", get: (e) => (notfallkontakte.get(e.id) ?? []).map((k) => k.name).join("; ") }, + { header: "Notfallkontakt Telefon", get: (e) => (notfallkontakte.get(e.id) ?? []).map((k) => k.phone).join("; ") }, + { + header: "Notfallkontakt Verhältnis", + get: (e) => (notfallkontakte.get(e.id) ?? []).map((k) => anzeige(k.relation) ?? "").join("; "), + }, { header: "Laterale Führung", get: (e) => e.is_laterale_fuehrung }, { header: "C-Level", get: (e) => e.is_c_level }, { header: "Hay-Grade", get: (e) => e.paygrade }, diff --git a/components/dashboard/AnstehendListe.tsx b/components/dashboard/AnstehendListe.tsx index abb345c..689a024 100644 --- a/components/dashboard/AnstehendListe.tsx +++ b/components/dashboard/AnstehendListe.tsx @@ -91,8 +91,11 @@ export function AnstehendListe({ const ueberfaellig = item.date < today; return (
  • + {/* Wie in der Historie: der Klick führt zum Vorgang — in die + Akte, Reiter Historie; bei einer Wiedervorlage zu den + Notizen, denn dort steht sie. Fachlich so vorgegeben. */} diff --git a/components/employees/EmployeeDetail.tsx b/components/employees/EmployeeDetail.tsx index c79a1c7..8982c81 100644 --- a/components/employees/EmployeeDetail.tsx +++ b/components/employees/EmployeeDetail.tsx @@ -16,6 +16,7 @@ import type { Database } from "@/lib/types"; import { DatenAendernPanel } from "./panels/DatenAendernPanel"; import { KarenzPanel } from "./panels/KarenzPanel"; import type { GeplanterVorgang } from "@/lib/geplanter-vorgang"; +import type { Notfallkontakt } from "./NotfallkontaktModal"; import { PromotePanel } from "./panels/PromotePanel"; import { RehireWizard } from "../hire/RehireWizard"; import { TerminatePanel } from "./panels/TerminatePanel"; @@ -53,12 +54,15 @@ type EmployeeDetailProps = { directReports: MiniEmployee[]; history: HistoryRow[]; dependents: Dependent[]; + notfallkontakte: Notfallkontakt[]; /** vonMir: von der angemeldeten Person verfasst — nur sie darf löschen. */ notes: (NoteRow & { vonMir?: boolean })[]; locations: Location[]; openPositions: OpenPositionResolved[]; /** Der Tag, zu dem die Akte gelesen wurde — derselbe wie in loadEmployeeDetail. */ today: string; + /** Reiter, mit dem die Akte öffnet (?tab= in der Adresse); sonst Stammdaten. */ + startTab?: string; }; type PanelType = "transfer" | "promote" | "karenz" | "daten" | "terminate" | "rehire" | null; @@ -67,7 +71,12 @@ type Tab = (typeof ALLE_TABS)[number]; export function EmployeeDetail(props: EmployeeDetailProps) { const { employee, placement, breadcrumb, kostenstelle, onboarding, offboarding, manager, formalManager, directReports, history, dependents, notes, locations, openPositions, today } = props; - const [tab, setTab] = useState("Stammdaten"); + // Wer aus „Anstehend" kommt, will den Vorgang sehen und nicht die + // Stammdaten — die Übersicht verlinkt deshalb mit ?tab=. Unbekanntes führt + // auf die Stammdaten. + const [tab, setTab] = useState( + (ALLE_TABS as readonly string[]).includes(props.startTab ?? "") ? (props.startTab as Tab) : "Stammdaten" + ); const [panel, setPanel] = useState(null); const [geplant, setGeplant] = useState(null); @@ -201,8 +210,26 @@ export function EmployeeDetail(props: EmployeeDetailProps) {
    - {tab === "Stammdaten" && } - {tab === "Vertrag" && } + {tab === "Stammdaten" && ( + + )} + {tab === "Vertrag" && ( + h.event_type === "Übernahme" && h.event_date <= today) + .map((h) => h.event_date) + .sort() + .at(-1) ?? null + } + /> + )} {tab === "Organisation" && ( void; employeeId: string; - kontakt: Notfallkontakt; - /** Aus „Daten ändern"; ohne Angabe gilt heute. */ - effectiveDate?: string; + /** Der zu ändernde Kontakt; ohne ihn wird einer angelegt. */ + kontakt: Notfallkontakt | null; }) { const { showToast } = useToast(); const router = useRouter(); - const [name, setName] = useState(kontakt.name ?? ""); - const [telefon, setTelefon] = useState(kontakt.telefon ?? ""); - const [verhaeltnis, setVerhaeltnis] = useState(kontakt.verhaeltnis ?? ""); + const [name, setName] = useState(kontakt?.name ?? ""); + const [telefon, setTelefon] = useState(kontakt?.phone ?? ""); + const [verhaeltnis, setVerhaeltnis] = useState(kontakt?.relation ?? ""); const [pending, setPending] = useState(false); - const vorhanden = Boolean(kontakt.name); - async function handleSubmit() { // Name und Telefonnummer gehören zusammen: ein Name ohne Nummer hilft im // Ernstfall niemandem, eine Nummer ohne Namen sagt nicht, wen man dran @@ -58,20 +51,13 @@ export function NotfallkontaktModal({ return; } setPending(true); - const result = await changeEmployeeData({ - employee_id: employeeId, - effective_date: effectiveDate || todayIso(), - person: { - emergency_contact_name: name.trim(), - emergency_contact_phone: telefon.trim(), - emergency_contact_relation: verhaeltnis.trim(), - }, - contract: {}, - role: {}, - }); + const angaben = { name: name.trim(), phone: telefon.trim(), relation: verhaeltnis.trim() }; + const result = kontakt + ? await updateEmergencyContact({ ...angaben, id: kontakt.id, employee_id: employeeId }) + : await addEmergencyContact({ ...angaben, employee_id: employeeId }); setPending(false); if (result.success) { - showToast(vorhanden ? "Notfallkontakt geändert." : "Notfallkontakt hinterlegt."); + showToast(kontakt ? "Notfallkontakt geändert." : "Notfallkontakt hinzugefügt."); router.refresh(); onClose(); } else { @@ -83,7 +69,7 @@ export function NotfallkontaktModal({ - )} +

    Notfallkontakte

    +
    - {/* Dieselbe Tabelle wie bei den Angehörigen darüber, Zeile für Zeile - derselbe Aufbau. Eine Beschreibungsliste wäre fachlich dasselbe, - optisch aber ein zweiter Baustil im selben Reiter. Zwei Listen - von Personen im Umfeld sollen gleich aussehen. */} - {vorhanden ? ( + {/* Dieselbe Tabelle wie bei den Angehörigen darüber: zwei Listen von + Personen im Umfeld sollen gleich aussehen. */} + {kontakte.length > 0 ? (
    @@ -97,43 +71,44 @@ export function NotfallkontaktSection({ - - - + + - - - + + + + + ))}
    {kontakt.name} - {kontakt.telefon ? ( - // Wählbar: im Ernstfall greift jemand in Eile danach. + {kontakte.map((k) => ( +
    {k.name} + {/* Wählbar: im Ernstfall greift jemand in Eile danach. */} - {kontakt.telefon} + {k.phone} - ) : ( - "–" - )} - {anzeige(kontakt.verhaeltnis) || "–"} - - -
    {anzeige(k.relation) || "–"} + + +
    @@ -141,17 +116,17 @@ export function NotfallkontaktSection({

    Kein Notfallkontakt hinterlegt.

    )} - {/* `key` setzt die Felder auf den gespeicherten Stand zurück, sobald - sich der Kontakt geändert hat — das Fenster bleibt sonst montiert - und zeigte beim zweiten Öffnen den alten Entwurf. */} - setModalOpen(false)} - employeeId={employeeId} - kontakt={kontakt} - effectiveDate={stichtag} - /> + {/* `key` baut das Fenster je Kontakt neu auf — sonst zeigte es beim + zweiten Öffnen die Felder des vorigen. */} + {modalOpen && ( + setModalOpen(false)} + employeeId={employeeId} + kontakt={bearbeitet} + /> + )} ); } diff --git a/components/employees/panels/DatenAendernPanel.tsx b/components/employees/panels/DatenAendernPanel.tsx index 677d4a9..f550b76 100644 --- a/components/employees/panels/DatenAendernPanel.tsx +++ b/components/employees/panels/DatenAendernPanel.tsx @@ -35,6 +35,7 @@ import { NotfallkontaktSection } from "@/components/employees/NotfallkontaktSect import { AustrittZuruecknehmen } from "@/components/employees/AustrittZuruecknehmen"; import { EintrittPlanstelleBerichtigen } from "@/components/employees/EintrittPlanstelleBerichtigen"; import type { OpenPositionResolved } from "@/lib/positions"; +import type { Notfallkontakt } from "@/components/employees/NotfallkontaktModal"; import type { ContractType, Database, EmploymentType, GenderType, PaygradeType } from "@/lib/types"; type EmployeeRow = Database["public"]["Tables"]["employees"]["Row"]; @@ -49,6 +50,7 @@ export function DatenAendernPanel({ planstelle = null, planstelleBerichtigbar = false, openPositions = [], + notfallkontakte = [], }: { open: boolean; onClose: () => void; @@ -60,6 +62,7 @@ export function DatenAendernPanel({ /** Kein Versetzung oder Beförderung seit dem Eintritt — dann lässt sie sich hier berichtigen. */ planstelleBerichtigbar?: boolean; openPositions?: OpenPositionResolved[]; + notfallkontakte?: Notfallkontakt[]; }) { const { showToast } = useToast(); const router = useRouter(); @@ -622,17 +625,10 @@ export function DatenAendernPanel({ {/* Derselbe Abschnitt wie im Reiter „Stammdaten", unmittelbar unter den Angehörigen — beides Personen im Umfeld, beides dieselbe Tabelle mit denselben Knöpfen. Lose Eingabefelder wären fachlich dasselbe, - aber eine zweite Bauform für denselben Zweck. Beide Abschnitte - laufen über das „Wirksam ab" dieses Formulars. */} - + aber eine zweite Bauform für denselben Zweck. Die Angehörigen + laufen über das „Wirksam ab" dieses Formulars; ein Notfallkontakt + gilt ab sofort. */} + ); diff --git a/components/employees/tabs/StammdatenTab.tsx b/components/employees/tabs/StammdatenTab.tsx index 28f863b..37a4d39 100644 --- a/components/employees/tabs/StammdatenTab.tsx +++ b/components/employees/tabs/StammdatenTab.tsx @@ -1,5 +1,6 @@ import { AngehoerigeSection } from "@/components/employees/AngehoerigeSection"; import { NotfallkontaktSection } from "@/components/employees/NotfallkontaktSection"; +import type { Notfallkontakt } from "@/components/employees/NotfallkontaktModal"; import { hrName, useHrBenutzer } from "@/components/shell/HrBenutzerContext"; import { teilzeitvarianteText } from "@/lib/absence"; import { brauchtAufenthaltstitel } from "@/lib/countries"; @@ -11,7 +12,17 @@ type EmployeeRow = Database["public"]["Tables"]["employees"]["Row"]; type Location = Database["public"]["Tables"]["locations"]["Row"]; type Dependent = Database["public"]["Tables"]["employee_dependents"]["Row"]; -export function StammdatenTab({ employee, location, dependents }: { employee: EmployeeRow; location?: Location; dependents: Dependent[] }) { +export function StammdatenTab({ + employee, + location, + dependents, + notfallkontakte, +}: { + employee: EmployeeRow; + location?: Location; + dependents: Dependent[]; + notfallkontakte: Notfallkontakt[]; +}) { // Defensive against a DB that hasn't received the title_prefix/title_suffix // migration yet — select("*") simply omits unknown columns, so these can // be undefined rather than the empty array the column default implies. @@ -83,14 +94,7 @@ export function StammdatenTab({ employee, location, dependents }: { employee: Em - + ); } diff --git a/components/employees/tabs/VertragTab.tsx b/components/employees/tabs/VertragTab.tsx index 2a86741..13dde40 100644 --- a/components/employees/tabs/VertragTab.tsx +++ b/components/employees/tabs/VertragTab.tsx @@ -45,7 +45,14 @@ function behinderungText(e: EmployeeRow): string { return teile.length > 0 ? teile.join(" · ") : "Ja"; } -export function VertragTab({ employee }: { employee: EmployeeRow }) { +export function VertragTab({ + employee, + uebernahmeAm = null, +}: { + employee: EmployeeRow; + /** Datum der Übernahme von extern aus der Historie; null heisst keine. */ + uebernahmeAm?: string | null; +}) { // Jedes Merkmal steht für sich, mit Ja oder Nein, wie jede andere Zeile auf // diesem Blatt auch. Eine Sammelzeile mit allem, was zutrifft, und einem // Gedankenstrich, wenn nichts zutrifft, liesse nicht ablesen, ob jemand @@ -64,6 +71,11 @@ export function VertragTab({ employee }: { employee: EmployeeRow }) { // Wie beim Dienstwagen: statt eines blossen „Ja" gleich die Regelung. ["Bonusanspruch", bonusanspruchLabel(employee.has_bonusanspruch, employee.bonusanspruch_art)], ["Beschäftigtengruppe", anzeige(employee.worker_type) ?? "–"], + ["Besetzungsart", employee.source], + // Fachlich vorgegeben: ob die Person von extern übernommen wurde. Gelesen + // aus dem Ereignis „Übernahme" in der Historie und nicht als eigene + // Spalte geführt — so kann die Angabe dem Ereignis nicht widersprechen. + ["Übernahme", uebernahmeAm ? `Ja (am ${fmtDate(uebernahmeAm)})` : "Nein"], ["Arbeitstage", employee.work_days?.join(", ") || "–"], // Beim Dienstwagen steht die Antriebsart statt eines blossen „Ja" — darum // geht es bei der Frage, weil E-Fahrzeuge getrennt zu führen sind. diff --git a/components/shell/NotesBell.tsx b/components/shell/NotesBell.tsx index a1e8b77..67c0562 100644 --- a/components/shell/NotesBell.tsx +++ b/components/shell/NotesBell.tsx @@ -29,6 +29,9 @@ export function NotesBell({ notes, kollegen }: { notes: OpenNote[]; kollegen: Ko const sichtbarkeit = (k: Kollege) => eigen[k.id] ?? k.sichtbar; const dazugewaehlt = kollegen.filter((k) => sichtbarkeit(k)).length; + const [nurMeine, setNurMeine] = useState(false); + // Ohne hinzugewählte Kollegen sind ohnehin nur die eigenen da. + const sichtbar = nurMeine && dazugewaehlt > 0 ? notes.filter((n) => n.vonMir) : notes; async function schalte(k: Kollege) { const neu = !sichtbarkeit(k); @@ -85,9 +88,26 @@ export function NotesBell({ notes, kollegen }: { notes: OpenNote[]; kollegen: Ko {open && (
    - - Meine Notizen ({notes.length}) - + {/* Sind Kollegen hinzugewählt, ist „Meine Notizen" ein Schalter: + ein Klick zeigt nur die selbst angelegten, ein zweiter wieder + alle. Fachlich so vorgegeben. Ohne Kollegen gibt es nichts + umzuschalten — dann bleibt es eine Überschrift. */} + {dazugewaehlt > 0 ? ( + + ) : ( + + Meine Notizen ({notes.length}) + + )}
    )} - {notes.length === 0 ? ( + {sichtbar.length === 0 ? (

    Keine offenen Notizen.

    ) : (
      - {notes.map((n) => ( + {sichtbar.map((n) => (
    • {n.category} diff --git a/db/migrations/20261019150000_planstelle_nicht_vor_einheit.sql b/db/migrations/20261019150000_planstelle_nicht_vor_einheit.sql new file mode 100644 index 0000000..a8ff58d --- /dev/null +++ b/db/migrations/20261019150000_planstelle_nicht_vor_einheit.sql @@ -0,0 +1,63 @@ +-- Eine Planstelle beginnt nicht vor ihrer Organisationseinheit. +-- +-- Eine Planstelle gehört zu einer Einheit; ohne die Einheit hat sie keinen +-- Ort im Organigramm und keine Berichtslinie. Liesse sich eine Planstelle ab +-- 01.10. an eine Einheit hängen, die erst ab 01.11. besteht, zeigte jeder +-- Stichtag dazwischen eine Stelle ohne Einheit — im Organigramm, in den +-- Berichten und in der Berichtslinie ihrer Besetzung. +-- +-- Die Prüfung sitzt als Auslöser an der Tabelle und nicht in +-- create_position, update_position und clone_position: drei Wege führen +-- hinein, und eine Bedingung, die an einem fehlt, ist keine. Geprüft wird nur +-- beim Anlegen und wenn sich Einheit oder Zeitraum ändern; Planstellen, die +-- schon so stehen, bleiben, bis jemand sie anfasst. + +create or replace function public.fn_planstelle_in_einheit() +returns trigger +language plpgsql +set search_path = public, pg_temp +as $$ +declare + v_einheit org_units%rowtype; +begin + if tg_op = 'UPDATE' + and new.org_unit_id is not distinct from old.org_unit_id + and new.valid_from is not distinct from old.valid_from + and new.valid_to is not distinct from old.valid_to then + return new; + end if; + + select * into v_einheit from org_units where id = new.org_unit_id; + if not found then + return new; + end if; + + if new.valid_from < v_einheit.valid_from then + raise exception 'Die Organisationseinheit „%" besteht erst ab %. Die Planstelle kann nicht früher beginnen.', + v_einheit.name, to_char(v_einheit.valid_from, 'DD.MM.YYYY'); + end if; + if v_einheit.valid_to is not null and new.valid_from >= v_einheit.valid_to then + raise exception 'Die Organisationseinheit „%" besteht nur bis %. Die Planstelle kann nicht danach beginnen.', + v_einheit.name, to_char(v_einheit.valid_to - 1, 'DD.MM.YYYY'); + end if; + return new; +end; +$$; + +grant execute on function public.fn_planstelle_in_einheit() to alpenwerk_app; + +drop trigger if exists trg_planstelle_in_einheit on om_positions; +create trigger trg_planstelle_in_einheit + before insert or update on om_positions + for each row execute function fn_planstelle_in_einheit(); + +-- ── Selbstprüfung ───────────────────────────────────────────────────────── +do $pruefung$ +begin + if not exists (select 1 from pg_trigger + where tgname = 'trg_planstelle_in_einheit' + and tgrelid = 'public.om_positions'::regclass) then + raise exception 'Der Auslöser an om_positions fehlt.'; + end if; +end +$pruefung$; diff --git a/db/migrations/20261019160000_mehrere_notfallkontakte.sql b/db/migrations/20261019160000_mehrere_notfallkontakte.sql new file mode 100644 index 0000000..6fbd460 --- /dev/null +++ b/db/migrations/20261019160000_mehrere_notfallkontakte.sql @@ -0,0 +1,177 @@ +-- Mehrere Notfallkontakte je Person, wie bei den Angehörigen. +-- +-- Fachlich vorgegeben: so viele Notfallkontakte, wie es braucht, angelegt +-- und geändert wie Angehörige. Drei Spalten an `employees` fassen genau +-- einen; deshalb eine eigene Tabelle mit einer Zeile je Kontakt. +-- +-- Die vorhandenen Kontakte werden übernommen. Die drei Spalten +-- emergency_contact_name, _phone, _relation bleiben an `employees` stehen, +-- weil ältere Einträge in Historie und Protokoll sie nennen; Oberfläche, +-- Import und Export lesen und schreiben die Kontakte ab hier in dieser +-- Tabelle. +-- +-- Ein Notfallkontakt hat keinen Stichtag: eine Nummer, die im Ernstfall +-- gewählt wird, gilt ab sofort. In der Historie steht der Vorgang zum +-- heutigen Tag, vor dem Eintritt zum Eintrittstag (app_stichtag_vor_eintritt). + +create table if not exists employee_emergency_contacts ( + id uuid primary key default gen_random_uuid(), + employee_id uuid not null references employees(id) on delete cascade, + name text not null check (btrim(name) <> ''), + phone text not null check (btrim(phone) <> ''), + relation text, + created_at timestamptz not null default now() +); + +create index if not exists employee_emergency_contacts_employee_idx on employee_emergency_contacts (employee_id); + +alter table employee_emergency_contacts enable row level security; +drop policy if exists employee_emergency_contacts_hr_all on employee_emergency_contacts; +create policy employee_emergency_contacts_hr_all on employee_emergency_contacts + for all using ((select is_hr_user())) with check ((select is_hr_user())); + +grant select, insert, update, delete on employee_emergency_contacts to alpenwerk_app; + +-- Bestand übernehmen. chk_emergency_contact verlangt Name und Nummer +-- gemeinsam; steht trotzdem ein Name ohne Nummer da, gilt „nicht erfasst". +insert into employee_emergency_contacts (employee_id, name, phone, relation) +select e.id, btrim(e.emergency_contact_name), coalesce(nullif(btrim(e.emergency_contact_phone), ''), 'nicht erfasst'), + nullif(btrim(e.emergency_contact_relation), '') + from employees e + where nullif(btrim(e.emergency_contact_name), '') is not null + and not exists (select 1 from employee_emergency_contacts k where k.employee_id = e.id); + +-- ── Hinzufügen, ändern, entfernen ───────────────────────────────────────── +create or replace function public.add_emergency_contact(payload jsonb) +returns uuid +language plpgsql +set search_path = public, pg_temp +as $$ +declare + v_employee_id uuid := (payload->>'employee_id')::uuid; + v_name text := nullif(btrim(payload->>'name'), ''); + v_phone text := nullif(btrim(payload->>'phone'), ''); + v_relation text := nullif(btrim(payload->>'relation'), ''); + v_person text; + v_id uuid; +begin + perform require_hr_admin(); + select first_name || ' ' || last_name into v_person from employees where id = v_employee_id; + if v_person is null then + raise exception 'Die Person existiert nicht.'; + end if; + if v_name is null or v_phone is null then + raise exception 'Name und Telefonnummer sind nötig.'; + end if; + + insert into employee_emergency_contacts (employee_id, name, phone, relation) + values (v_employee_id, v_name, v_phone, v_relation) + returning id into v_id; + + insert into employee_history (employee_id, event_date, event_type, description) + values (v_employee_id, app_stichtag_vor_eintritt(v_employee_id, current_date), 'Stammdatenänderung', + 'Notfallkontakt hinzugefügt: ' || v_name || coalesce(' (' || v_relation || ')', '')); + insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details) + values (app_current_user_id(), current_actor_name(), 'Notfallkontakt hinzugefügt', v_person, v_employee_id, + v_name || coalesce(' (' || v_relation || ')', '') || ', ' || v_phone); + return v_id; +end; +$$; + +create or replace function public.update_emergency_contact(payload jsonb) +returns void +language plpgsql +set search_path = public, pg_temp +as $$ +declare + v_alt employee_emergency_contacts%rowtype; + v_name text := nullif(btrim(payload->>'name'), ''); + v_phone text := nullif(btrim(payload->>'phone'), ''); + v_relation text := nullif(btrim(payload->>'relation'), ''); + v_person text; +begin + perform require_hr_admin(); + select * into v_alt from employee_emergency_contacts where id = (payload->>'id')::uuid for update; + if not found then + raise exception 'Notfallkontakt nicht gefunden.'; + end if; + if v_name is null or v_phone is null then + raise exception 'Name und Telefonnummer sind nötig.'; + end if; + select first_name || ' ' || last_name into v_person from employees where id = v_alt.employee_id; + + update employee_emergency_contacts set name = v_name, phone = v_phone, relation = v_relation where id = v_alt.id; + + insert into employee_history (employee_id, event_date, event_type, description) + values (v_alt.employee_id, app_stichtag_vor_eintritt(v_alt.employee_id, current_date), 'Stammdatenänderung', + 'Notfallkontakt geändert: ' || v_alt.name || ' → ' || v_name || coalesce(' (' || v_relation || ')', '')); + insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details, changes) + values (app_current_user_id(), current_actor_name(), 'Notfallkontakt geändert', v_person, v_alt.employee_id, + v_alt.name || ' → ' || v_name, + app_aenderung(app_aenderung(app_aenderung('[]'::jsonb, + 'Name', v_alt.name, v_name), + 'Telefon', v_alt.phone, v_phone), + 'Verhältnis', v_alt.relation, v_relation)); +end; +$$; + +create or replace function public.delete_emergency_contact(payload jsonb) +returns void +language plpgsql +set search_path = public, pg_temp +as $$ +declare + v_alt employee_emergency_contacts%rowtype; + v_person text; +begin + perform require_hr_admin(); + select * into v_alt from employee_emergency_contacts where id = (payload->>'id')::uuid; + if not found then + raise exception 'Notfallkontakt nicht gefunden.'; + end if; + select first_name || ' ' || last_name into v_person from employees where id = v_alt.employee_id; + + delete from employee_emergency_contacts where id = v_alt.id; + + insert into employee_history (employee_id, event_date, event_type, description) + values (v_alt.employee_id, app_stichtag_vor_eintritt(v_alt.employee_id, current_date), 'Stammdatenänderung', + 'Notfallkontakt entfernt: ' || v_alt.name || coalesce(' (' || v_alt.relation || ')', '')); + insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details) + values (app_current_user_id(), current_actor_name(), 'Notfallkontakt entfernt', v_person, v_alt.employee_id, + v_alt.name || coalesce(' (' || v_alt.relation || ')', '') || ', ' || v_alt.phone); +end; +$$; + +grant execute on function public.add_emergency_contact(jsonb) to alpenwerk_app; +grant execute on function public.update_emergency_contact(jsonb) to alpenwerk_app; +grant execute on function public.delete_emergency_contact(jsonb) to alpenwerk_app; + +-- ── Selbstprüfung ───────────────────────────────────────────────────────── +do $pruefung$ +declare + v_fn text; + v_def text; + v_bestand integer; + v_uebernommen integer; +begin + if not (select relrowsecurity from pg_class where oid = 'public.employee_emergency_contacts'::regclass) then + raise exception 'employee_emergency_contacts ist ohne Zeilenschutz.'; + end if; + + foreach v_fn in array array['add_emergency_contact', 'update_emergency_contact', 'delete_emergency_contact'] loop + select pg_get_functiondef(p.oid) into v_def + from pg_proc p join pg_namespace n on n.oid = p.pronamespace + where n.nspname = 'public' and p.prokind = 'f' and p.proname = v_fn; + if position('require_hr_admin()' in v_def) = 0 or position('insert into audit_log' in v_def) = 0 then + raise exception '% prüft die Rechte nicht oder schreibt kein Protokoll.', v_fn; + end if; + end loop; + + -- Jeder vorhandene Kontakt ist übernommen. + select count(*) into v_bestand from employees where nullif(btrim(emergency_contact_name), '') is not null; + select count(distinct employee_id) into v_uebernommen from employee_emergency_contacts; + if v_uebernommen < v_bestand then + raise exception 'Von % Notfallkontakten sind nur % übernommen.', v_bestand, v_uebernommen; + end if; +end +$pruefung$; diff --git a/db/tests/rauchtest.sql b/db/tests/rauchtest.sql index 015cae1..40f5025 100644 --- a/db/tests/rauchtest.sql +++ b/db/tests/rauchtest.sql @@ -46,6 +46,7 @@ declare v_einheit uuid; v_p1 uuid; v_p2 uuid; v_p3 uuid; v_p4 uuid; v_p5 uuid; v_p6 uuid; v_p7 uuid; v_p8 uuid; v_p9 uuid; v_a uuid; v_b uuid; v_c uuid; v_d uuid; v_e uuid; + v_spaet uuid; v_notiz uuid; v_ort uuid; v_nr int; @@ -76,14 +77,14 @@ begin 'job_title', 'Rauchtest Drei', 'is_chief', false, 'valid_from', (current_date - 30)::text)); v_p4 := create_position(jsonb_build_object('org_unit_id', v_einheit, 'job_title', 'Rauchtest Vier', 'is_chief', false, 'valid_from', (current_date - 30)::text)); - raise notice '1/17 Einheit und vier Planstellen angelegt'; + raise notice '1/18 Einheit und vier Planstellen angelegt'; -- ── Einstellung ───────────────────────────────────────────────── v_a := hire_employee(jsonb_build_object( 'personnel_number', v_nr, 'first_name', 'Rauch', 'last_name', 'Test-A', 'gender', 'w', 'birth_date', '1990-01-01', 'location_id', v_ort, 'position_id', v_p1, 'entry_date', current_date::text)); - raise notice '2/17 Einstellung auf Planstelle 1'; + raise notice '2/18 Einstellung auf Planstelle 1'; -- ── Versetzung am selben Tag (20260929180000) ─────────────────── -- Die Besetzung begann heute; sie auf heute zu schliessen wäre ein @@ -96,7 +97,7 @@ begin if v_stelle is distinct from v_p2 then raise exception 'Nach der Versetzung sitzt die Person nicht auf Planstelle 2.'; end if; - raise notice '3/17 Versetzung am selben Tag'; + raise notice '3/18 Versetzung am selben Tag'; -- ── Beförderung mit Planstellenwechsel, ebenfalls heute ───────── perform promote_employee(jsonb_build_object( @@ -121,7 +122,7 @@ begin if v_titel <> 'Rauchtest Leitung' then raise exception 'Die Zielplanstelle heisst nach der Beförderung „%", erwartet „Rauchtest Leitung".', v_titel; end if; - raise notice '4/17 Beförderung am selben Tag: Hay-Grade und Planstellenbezeichnung'; + raise notice '4/18 Beförderung am selben Tag: Hay-Grade und Planstellenbezeichnung'; -- Dieselbe Planstelle, nur ein neuer Name. perform promote_employee(jsonb_build_object( @@ -139,7 +140,7 @@ begin if not exists (select 1 from jobs where title = 'Rauchtest Leitung') then raise exception 'Der alte Katalogeintrag wurde umbenannt statt die Planstelle umgehängt.'; end if; - raise notice '4b/17 Beförderung ohne Stellenwechsel benennt dieselbe Planstelle um'; + raise notice '4b/18 Beförderung ohne Stellenwechsel benennt dieselbe Planstelle um'; -- ── Vorgemerkte Planstelle (20260929200000) ───────────────────── -- Eine Versetzung in die Zukunft belegt die Zielstelle, obwohl dort noch @@ -170,13 +171,13 @@ begin if v_meldung not like '%bereits eine Versetzung vorgemerkt%' then raise exception 'Erwartet wurde die Meldung zur Vormerkung, kam aber: %', v_meldung; end if; - raise notice '5/17 Vorgemerkte Planstelle wird abgewiesen'; + raise notice '5/18 Vorgemerkte Planstelle wird abgewiesen'; -- Die eigene Vormerkung darf nicht im Weg stehen: dieselbe Versetzung noch -- einmal zu erfassen ist eine Berichtigung. perform transfer_employee(jsonb_build_object( 'employee_id', v_a, 'target_position_id', v_p4, 'effective_date', (current_date + 20)::text)); - raise notice '6/17 Die eigene Vormerkung steht nicht im Weg'; + raise notice '6/18 Die eigene Vormerkung steht nicht im Weg'; -- ── Austritt am selben Tag (20260929220000) ───────────────────── perform terminate_employee(jsonb_build_object( @@ -188,7 +189,7 @@ begin if v_offen <> 0 then raise exception 'Nach dem Austritt ist die Planstelle nicht frei.'; end if; - raise notice '7/17 Austritt am selben Tag, Planstelle frei'; + raise notice '7/18 Austritt am selben Tag, Planstelle frei'; -- ── Wiedereintritt (20260929160000) ───────────────────────────── perform rehire_employee(jsonb_build_object( @@ -205,7 +206,7 @@ begin if v_stelle is distinct from v_p1 then raise exception 'Nach dem Wiedereintritt sitzt die Person nicht auf Planstelle 1.'; end if; - raise notice '8/17 Wiedereintritt'; + raise notice '8/18 Wiedereintritt'; -- ── Rückdatierte Versetzung (20261013140000) ──────────────────── -- @@ -240,7 +241,7 @@ begin if v_stelle is distinct from v_p2 then raise exception 'Nach der rückdatierten Versetzung sitzt die Person nicht auf Planstelle 2.'; end if; - raise notice '9/17 Rückdatierte Versetzung lässt keine zweite Besetzung stehen'; + raise notice '9/18 Rückdatierte Versetzung lässt keine zweite Besetzung stehen'; -- ── Versetzung bei datiertem Austritt (20261013140000) ────────── -- @@ -274,7 +275,7 @@ begin if v_offen <> 1 then raise exception 'Die neue Besetzung endet nicht am Austrittstag.'; end if; - raise notice '10/17 Versetzung bei datiertem Austritt: kein Überlappen, kein Überleben'; + raise notice '10/18 Versetzung bei datiertem Austritt: kein Überlappen, kein Überleben'; -- ── Änderung vor dem Eintritt (20261018100000) ────────────────── -- @@ -313,7 +314,7 @@ begin and event_date = current_date + 40) then raise exception 'Mit dem Eintritt ist die Änderung davor nicht mitgewandert.'; end if; - raise notice '11/17 Änderung vor dem Eintritt wirkt sofort und wandert mit dem Eintritt'; + raise notice '11/18 Änderung vor dem Eintritt wirkt sofort und wandert mit dem Eintritt'; -- ── Abwesenheit mit geplanter Rückkehr löschen (20261019100000) ─ -- @@ -347,7 +348,7 @@ begin if v_status <> 'Aktiv' then raise exception 'Nach dem Löschen der Abwesenheit steht der Status auf %, erwartet Aktiv.', v_status; end if; - raise notice '12/17 Abwesenheit mit geplanter Rückkehr lässt sich löschen'; + raise notice '12/18 Abwesenheit mit geplanter Rückkehr lässt sich löschen'; -- ── Zweite Versetzung zum selben Tag (20261019110000) ─────────── -- @@ -387,7 +388,7 @@ begin if exists (select 1 from pending_org_changes where employee_id = v_d and status = 'pending') then raise exception 'Nach dem Abbrechen ist die Versetzung weiter vorgemerkt.'; end if; - raise notice '13/17 Zweite Versetzung zum selben Tag abgewiesen, die erste lässt sich abbrechen'; + raise notice '13/18 Zweite Versetzung zum selben Tag abgewiesen, die erste lässt sich abbrechen'; -- ── Notiz löschen (20261019130000) ────────────────────────────── -- Die eigene lässt sich löschen; das Protokoll behält den Text. @@ -400,7 +401,7 @@ begin if not exists (select 1 from audit_log where action = 'HR-Notiz gelöscht' and details like '%Rauchtest-Notiz%') then raise exception 'Das Löschen der Notiz steht nicht im Protokoll.'; end if; - raise notice '14/17 Eigene Notiz lässt sich löschen, das Protokoll behält sie'; + raise notice '14/18 Eigene Notiz lässt sich löschen, das Protokoll behält sie'; -- ── Austritt zurücknehmen (20261019140000) ────────────────────── -- v_b hat seit Schritt 10 einen datierten Austritt; die Besetzung auf @@ -415,7 +416,7 @@ begin if exists (select 1 from employee_history where employee_id = v_b and event_type = 'Austritt') then raise exception 'Nach der Rücknahme steht der Austritt noch in der Historie.'; end if; - raise notice '15/17 Austritt zurückgenommen, Besetzung läuft wieder'; + raise notice '15/18 Austritt zurückgenommen, Besetzung läuft wieder'; -- ── Letzte Versetzung zurücknehmen (20261019140000) ───────────── v_p8 := create_position(jsonb_build_object('org_unit_id', v_einheit, @@ -438,7 +439,7 @@ begin if exists (select 1 from position_assignments where position_id = v_p9) then raise exception 'Nach der Rücknahme steht auf der Zielplanstelle noch eine Besetzung.'; end if; - raise notice '16/17 Letzte Versetzung zurückgenommen, vorherige Planstelle wieder besetzt'; + raise notice '16/18 Letzte Versetzung zurückgenommen, vorherige Planstelle wieder besetzt'; -- ── Planstelle beim Eintritt berichtigen (20261019140000) ─────── -- v_c (Schritt 11) ist noch nicht eingetreten und nie versetzt worden. @@ -452,7 +453,27 @@ begin if exists (select 1 from employee_history where employee_id = v_c and event_type = 'Versetzung') then raise exception 'Die Berichtigung hat eine Versetzung hinterlassen.'; end if; - raise notice '17/17 Planstelle beim Eintritt berichtigt, ohne Versetzung'; + raise notice '17/18 Planstelle beim Eintritt berichtigt, ohne Versetzung'; + + -- ── Planstelle nicht vor ihrer Einheit (20261019150000) ───────── + v_spaet := create_org_unit(jsonb_build_object( + 'parent_id', v_wurzel, 'org_number', 'RAUCHTEST-SPAET', 'name', 'Rauchtest später', + 'unit_type', 'Team', 'valid_from', (current_date + 30)::text)); + v_ging := false; + begin + perform create_position(jsonb_build_object('org_unit_id', v_spaet, + 'job_title', 'Rauchtest zu früh', 'is_chief', false, 'valid_from', current_date::text)); + v_ging := true; + exception + when others then v_meldung := SQLERRM; + end; + if v_ging then + raise exception 'Eine Planstelle liess sich vor ihrer Einheit anlegen.'; + end if; + if v_meldung not like '%besteht erst ab%' then + raise exception 'Erwartet wurde die Meldung zur Einheit, kam aber: %', v_meldung; + end if; + raise notice '18/18 Planstelle vor ihrer Einheit wird abgewiesen'; raise notice ''; raise notice 'Rauchtest bestanden. Alles Angelegte wird gleich verworfen.'; @@ -464,6 +485,6 @@ rollback; -- Beweis, dass nichts geblieben ist. Läuft ausserhalb der verworfenen -- Transaktion und muss überall 0 liefern. select - (select count(*) from org_units where org_number = 'RAUCHTEST') as einheiten, + (select count(*) from org_units where org_number like 'RAUCHTEST%') as einheiten, (select count(*) from employees where last_name like 'Test-%' and first_name = 'Rauch') as personen, (select count(*) from jobs where title like 'Rauchtest %') as taetigkeiten; diff --git a/lib/dashboard-data.ts b/lib/dashboard-data.ts index 5421e5b..4f7762e 100644 --- a/lib/dashboard-data.ts +++ b/lib/dashboard-data.ts @@ -71,7 +71,9 @@ export async function loadDashboardData(tx: Tx, p: DashboardParams) { // counts too. `entry_date` would also sweep up rehires, whose event is // logged as 'Wiedereintritt' — the tile and its destination would then // show different numbers for the same year. - jsonObjectFrom(countIn(eb, ["Eintritt", "Wiedereintritt"])).as("hiresYtd"), + // Eine Übernahme von extern zählt wie ein Eintritt, fachlich so + // vorgegeben: die Person kommt neu in den eigenen Bestand. + jsonObjectFrom(countIn(eb, ["Eintritt", "Wiedereintritt", "Übernahme"])).as("hiresYtd"), jsonObjectFrom(countIn(eb, ["Austritt"])).as("exitsYtd"), ...orgMapsAbfragen(eb), diff --git a/lib/employee-detail-data.ts b/lib/employee-detail-data.ts index be647ba..7d433bd 100644 --- a/lib/employee-detail-data.ts +++ b/lib/employee-detail-data.ts @@ -91,6 +91,15 @@ export async function loadEmployeeDetail(tx: Tx, id: string, today: string = tod .orderBy("created_at") ).as("dependents"), + jsonArrayFrom( + eb + .selectFrom("employee_emergency_contacts") + .select(["id", "employee_id", "name", "phone", "relation"]) + .select((x) => zeitstempel(x.ref("created_at")).as("created_at")) + .where("employee_id", "=", id) + .orderBy("created_at") + ).as("notfallkontakte"), + jsonArrayFrom( eb .selectFrom("employee_notes") @@ -175,6 +184,7 @@ export async function loadEmployeeDetail(tx: Tx, id: string, today: string = tod reports, history: g.history, dependents: g.dependents, + notfallkontakte: g.notfallkontakte, notes: g.notes, orgMaps, placement, diff --git a/lib/export-auswahl.ts b/lib/export-auswahl.ts index cc38cdd..e5362b6 100644 --- a/lib/export-auswahl.ts +++ b/lib/export-auswahl.ts @@ -63,6 +63,8 @@ export async function ladeExportMitarbeiter( /** Name je HR-Konto — für „Zuständige HR". */ hrName: Map; dependentsCounts: Map; + /** Die Notfallkontakte je Person, in der Reihenfolge ihrer Erfassung. */ + notfallkontakte: Map; }> { const statuses = parseStatuses(filters.status); const stichtag = asOf ?? todayIso(); @@ -84,7 +86,7 @@ export async function ladeExportMitarbeiter( return applyCriteria(q, criteria); } - const [employees, lookupResult, allEmployees, dependentsCounts, placements, lines, hrKonten] = await Promise.all([ + const [employees, lookupResult, allEmployees, dependentsCounts, placements, lines, hrKonten, kontakte] = await Promise.all([ employeeQuery().execute(), loadOrgLookups(tx), // Absichtlich schmal: die Liste umfasst **alle** Personen, nicht nur die @@ -95,7 +97,19 @@ export async function ladeExportMitarbeiter( loadReportingLineMap(tx, stichtag), // Für „Zuständige HR": gespeichert ist die Kennung, in die Datei gehört der Name. tx.selectFrom("profiles").select(["id", "full_name", "email"]).where("role", "=", "hr").execute(), + tx + .selectFrom("employee_emergency_contacts") + .select(["employee_id", "name", "phone", "relation"]) + .orderBy("employee_id") + .orderBy("created_at") + .execute(), ]); + const notfallkontakte = new Map(); + for (const k of kontakte) { + const liste = notfallkontakte.get(k.employee_id) ?? []; + liste.push({ name: k.name, phone: k.phone, relation: k.relation }); + notfallkontakte.set(k.employee_id, liste); + } const orgMaps = lookupResult.orgMaps; // Der Einheitenfilter meint den ganzen Teilbaum — sonst enthielte ein @@ -133,5 +147,6 @@ export async function ladeExportMitarbeiter( managerKennung: new Map(allEmployees.map((e) => [e.id, e.cornerstone_id])), hrName: new Map(hrKonten.map((p) => [p.id, p.full_name?.trim() || p.email])), dependentsCounts, + notfallkontakte, }; } diff --git a/lib/import/load.ts b/lib/import/load.ts index b2f386e..13cc330 100644 --- a/lib/import/load.ts +++ b/lib/import/load.ts @@ -190,6 +190,7 @@ export async function laden( const personId = new Map(bestand.personalnummern); const personenZeilen = hole("Personen"); const besetzungen: { position_id: string; employee_id: string; valid_from: string; valid_to: string | null }[] = []; + const notfallkontakte: { employee_id: string; name: string; phone: string; relation: string | null }[] = []; for (const z of personenZeilen) { const w = z.werte; @@ -242,9 +243,6 @@ export async function laden( // so verlangt es chk_dienstwagen_art. Fehlt die Angabe in der Datei, // gilt Verbrenner, wie im übernommenen Bestand. dienstwagen_art: bool(w.has_dienstwagen, false) ? (txt(w.dienstwagen_art) ?? "Verbrenner") : null, - emergency_contact_name: txt(w.emergency_contact_name), - emergency_contact_phone: txt(w.emergency_contact_phone), - emergency_contact_relation: txt(w.emergency_contact_relation), is_laterale_fuehrung: bool(w.is_laterale_fuehrung, false), is_c_level: bool(w.is_c_level, false), has_kuendigungsschutz: bool(w.has_kuendigungsschutz, false), @@ -281,6 +279,19 @@ export async function laden( personId.set(r.rows[0].personnel_number, r.rows[0].id); + // Der Notfallkontakt aus der Datei — in die eigene Tabelle, wie in der + // Akte (20261019160000). Name und Nummer nur gemeinsam. + const kontaktName = txt(w.emergency_contact_name); + const kontaktTelefon = txt(w.emergency_contact_phone); + if (kontaktName && kontaktTelefon) { + notfallkontakte.push({ + employee_id: r.rows[0].id, + name: kontaktName, + phone: kontaktTelefon, + relation: txt(w.emergency_contact_relation), + }); + } + const stelle = txt(w.position_number); if (stelle) { besetzungen.push({ @@ -300,6 +311,7 @@ export async function laden( // Index — beim Import wie im Assistenten. await einfuegen(tx, "position_assignments", besetzungen); + await einfuegen(tx, "employee_emergency_contacts", notfallkontakte); // ── Historie und Angehörige ─────────────────────────────────── const historie = hole("Historie").map((z) => ({ diff --git a/lib/kpi-erklaerungen.ts b/lib/kpi-erklaerungen.ts index 3a3bc23..c371e91 100644 --- a/lib/kpi-erklaerungen.ts +++ b/lib/kpi-erklaerungen.ts @@ -30,7 +30,7 @@ export const KPI_ERKLAERUNGEN: Record = { "Vollzeitäquivalente der Personen im Headcount Aktiv: Summe ihrer Wochenstunden geteilt durch 38,5. " + "Eine Vollzeitkraft zählt 1,0, eine Teilzeitkraft mit 19,25 Stunden 0,5. Langzeitabwesende zählen nicht.", "Eintritte (YTD)": - "Eintritte und Wiedereintritte vom 1. Jänner bis heute (YTD = year to date). " + + "Eintritte, Wiedereintritte und Übernahmen von extern vom 1. Jänner bis heute (YTD = year to date). " + "Eintritte, die erst nach heute beginnen, zählen noch nicht.", "Austritte (YTD)": "Austritte mit Austrittsdatum vom 1. Jänner bis heute (YTD = year to date), einschliesslich „Nicht angetreten“. " + diff --git a/lib/types.ts b/lib/types.ts index dae2cd4..bc2af6f 100644 --- a/lib/types.ts +++ b/lib/types.ts @@ -130,18 +130,9 @@ export type KuendigungsschutzGrund = * „Sonstige" frei eingetragen wird, steht als eigener Text in der Spalte * (VerhaeltnisField). */ -export const EMERGENCY_RELATIONS = [ - "Ehepartner:in", - "Lebenspartner:in", - "Mutter", - "Vater", - "Tochter", - "Sohn", - "Schwester", - "Bruder", - "Freundin/Freund", - "Sonstige", -] as const; +// Dieselbe Liste wie bei den Angehörigen, fachlich so vorgegeben; alles +// Weitere — Eltern, Geschwister, Nachbarn — unter „Sonstige" als freier Text. +export const EMERGENCY_RELATIONS = ["Ehepartner:in", "Lebenspartner:in", "Kind", "Sonstige"] as const; export type EmergencyRelation = (typeof EMERGENCY_RELATIONS)[number]; @@ -468,6 +459,26 @@ export type Database = { }; Update: Partial; }; + // Notfallkontakte, beliebig viele je Person (20261019160000). + employee_emergency_contacts: { + Row: { + id: string; + employee_id: string; + name: string; + phone: string; + relation: string | null; + created_at: string; + }; + Insert: { + id?: string; + employee_id: string; + name: string; + phone: string; + relation?: string | null; + created_at?: string; + }; + Update: Partial; + }; employee_notes: { Row: { id: string; @@ -839,6 +850,9 @@ export type Database = { // werden konnte (20261019140000). austritt_zuruecknehmen: { Args: { payload: Record }; Returns: string | null }; eintritt_planstelle_berichtigen: { Args: { payload: Record }; Returns: void }; + add_emergency_contact: { Args: { payload: Record }; Returns: string }; + update_emergency_contact: { Args: { payload: Record }; Returns: void }; + delete_emergency_contact: { Args: { payload: Record }; Returns: void }; // Eigenes Passwort wechseln. Die einzige mutierende Funktion **ohne** // require_hr_admin() — sonst käme niemand aus dem erzwungenen Wechsel // heraus, denn solange er aussteht, ist is_hr_user() false. diff --git a/tests/components/AnstehendListe.test.tsx b/tests/components/AnstehendListe.test.tsx index 1863254..bd936e7 100644 --- a/tests/components/AnstehendListe.test.tsx +++ b/tests/components/AnstehendListe.test.tsx @@ -94,8 +94,13 @@ describe("AnstehendListe", () => { expect(screen.getByText(/überfällig/)).toBeInTheDocument(); }); - it("verlinkt auf die Akte, nicht auf die Notiz", () => { + it("führt bei einer Wiedervorlage in die Akte, Reiter Notizen", () => { zeige([eintrag(1, { kind: "note", employeeId: "e42" })]); - expect(screen.getByRole("link")).toHaveAttribute("href", "/employees/e42"); + expect(screen.getByRole("link")).toHaveAttribute("href", "/employees/e42?tab=HR-Notizen"); + }); + + it("führt bei allen anderen in die Akte, Reiter Historie", () => { + zeige([eintrag(1, { kind: "exit", employeeId: "e7" })]); + expect(screen.getByRole("link")).toHaveAttribute("href", "/employees/e7?tab=Historie"); }); }); diff --git a/tests/components/NotesBell.test.tsx b/tests/components/NotesBell.test.tsx index dabdf48..12a1a95 100644 --- a/tests/components/NotesBell.test.tsx +++ b/tests/components/NotesBell.test.tsx @@ -148,6 +148,20 @@ describe("Sichtbarkeit der Kolleg:innen", () => { expect(screen.queryByText(/Max Mustermann/)).not.toBeInTheDocument(); }); + it("zeigt mit „Meine Notizen“ nur die eigenen, wenn Kollegen hinzugewählt sind", async () => { + const user = userEvent.setup(); + zeige(KOLLEGEN, [ + notiz({ id: "a", vonMir: true, note_text: "Eigene Notiz" }), + notiz({ id: "b", vonMir: false, author_name: "Anna Berger", note_text: "Fremde Notiz" }), + ]); + await user.click(screen.getByRole("button", { name: /^Meine Notizen$/i })); + expect(screen.getByText("Fremde Notiz")).toBeInTheDocument(); + + await user.click(screen.getByRole("button", { name: /Meine Notizen \(1\)/ })); + expect(screen.getByText("Eigene Notiz")).toBeInTheDocument(); + expect(screen.queryByText("Fremde Notiz")).not.toBeInTheDocument(); + }); + it("kommt ohne Kolleg:innen zurecht", async () => { // Eine Personalabteilung aus einer Person: die Liste ist leer, und ein // Kasten ohne Inhalt wäre eine Sackgasse. diff --git a/tests/components/VerhaeltnisField.test.tsx b/tests/components/VerhaeltnisField.test.tsx index 01f86b2..137eb5f 100644 --- a/tests/components/VerhaeltnisField.test.tsx +++ b/tests/components/VerhaeltnisField.test.tsx @@ -44,7 +44,10 @@ describe("VerhaeltnisField", () => { }); it("unterscheidet Listenwerte von freien", () => { - expect(istFreiesVerhaeltnis("Mutter")).toBe(false); + // Dieselbe Liste wie bei den Angehörigen: „Kind" steht darin, „Mutter" + // ist frei eingetragen. + expect(istFreiesVerhaeltnis("Kind")).toBe(false); + expect(istFreiesVerhaeltnis("Mutter")).toBe(true); expect(istFreiesVerhaeltnis("Onkel")).toBe(true); expect(istFreiesVerhaeltnis("")).toBe(false); }); diff --git a/tests/unit/historie-felder.test.ts b/tests/unit/historie-felder.test.ts index 4e4f7ac..63968b6 100644 --- a/tests/unit/historie-felder.test.ts +++ b/tests/unit/historie-felder.test.ts @@ -41,7 +41,7 @@ describe("Die Auswahllisten im Dialog „Eintrag berichtigen“", () => { // Freier Text wäre hier ein Bruch: die Erfassung führt überall sonst // eine Liste. expect(auswahlFuer("Notfallkontakt Verhältnis")).toContain("Ehepartner:in"); - expect(auswahlFuer("Notfallkontakt Verhältnis")).toContain("Tochter"); + expect(auswahlFuer("Notfallkontakt Verhältnis")).toContain("Kind"); }); it("lassen Felder ohne feste Liste als Textfeld stehen", () => {