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
This commit is contained in:
@@ -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<string, unknown>)) as string;
|
||||
const id = (await callFunction(tx, "hire_employee", person as Record<string, unknown>)) 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<ActionResult> {
|
||||
// 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<string, unknown>);
|
||||
await callFunction(tx, "rehire_employee", rest as unknown as Record<string, unknown>);
|
||||
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<ActionResult> {
|
||||
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<ActionResult> {
|
||||
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<ActionResult> {
|
||||
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<ActionResult> {
|
||||
return callRpc("delete_employee_note", { note_id: payload.note_id }, [`/employees/${payload.employee_id}`, "/"]);
|
||||
|
||||
@@ -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 (
|
||||
<EmployeeDetail
|
||||
@@ -49,12 +50,14 @@ export default async function EmployeeDetailPage({ params }: PageProps) {
|
||||
})}
|
||||
history={history ?? []}
|
||||
dependents={dependents ?? []}
|
||||
notfallkontakte={notfallkontakte ?? []}
|
||||
// Wer verfasst hat, entscheidet über den Papierkorb; die Kennung bleibt
|
||||
// auf dem Server, mit hinaus geht nur das Ja oder Nein.
|
||||
notes={(notes ?? []).map((n) => ({ ...n, author_user_id: null, vonMir: n.author_user_id === userId }))}
|
||||
locations={orgMaps.locationList}
|
||||
openPositions={openPositions}
|
||||
today={today}
|
||||
startTab={tab}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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<string, string>,
|
||||
dependentsCounts: Map<string, number>,
|
||||
asOf?: string,
|
||||
hrName: Map<string, string> = new Map()
|
||||
hrName: Map<string, string> = new Map(),
|
||||
notfallkontakte: Map<string, { name: string; phone: string; relation: string | null }[]> = new Map()
|
||||
): ExportColumn<EmployeeRow>[] {
|
||||
const columns: ExportColumn<EmployeeRow>[] = [
|
||||
{ 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 },
|
||||
|
||||
@@ -91,8 +91,11 @@ export function AnstehendListe({
|
||||
const ueberfaellig = item.date < today;
|
||||
return (
|
||||
<li key={`${item.kind}-${item.id}`}>
|
||||
{/* 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. */}
|
||||
<Link
|
||||
href={`/employees/${item.employeeId}`}
|
||||
href={`/employees/${item.employeeId}?tab=${encodeURIComponent(item.kind === "note" ? "HR-Notizen" : "Historie")}`}
|
||||
className="-mx-2 flex items-center justify-between gap-2 rounded px-2 py-2.5 text-sm hover:bg-surface"
|
||||
>
|
||||
<span className="min-w-0">
|
||||
|
||||
@@ -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<Tab>("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<Tab>(
|
||||
(ALLE_TABS as readonly string[]).includes(props.startTab ?? "") ? (props.startTab as Tab) : "Stammdaten"
|
||||
);
|
||||
const [panel, setPanel] = useState<PanelType>(null);
|
||||
const [geplant, setGeplant] = useState<GeplanterVorgang | null>(null);
|
||||
|
||||
@@ -201,8 +210,26 @@ export function EmployeeDetail(props: EmployeeDetailProps) {
|
||||
</div>
|
||||
|
||||
<div className="rounded border border-border bg-white p-6">
|
||||
{tab === "Stammdaten" && <StammdatenTab employee={employee} location={location} dependents={dependents} />}
|
||||
{tab === "Vertrag" && <VertragTab employee={employee} />}
|
||||
{tab === "Stammdaten" && (
|
||||
<StammdatenTab
|
||||
employee={employee}
|
||||
location={location}
|
||||
dependents={dependents}
|
||||
notfallkontakte={props.notfallkontakte}
|
||||
/>
|
||||
)}
|
||||
{tab === "Vertrag" && (
|
||||
<VertragTab
|
||||
employee={employee}
|
||||
uebernahmeAm={
|
||||
history
|
||||
.filter((h) => h.event_type === "Übernahme" && h.event_date <= today)
|
||||
.map((h) => h.event_date)
|
||||
.sort()
|
||||
.at(-1) ?? null
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{tab === "Organisation" && (
|
||||
<OrganisationTab
|
||||
employeeId={employee.id}
|
||||
@@ -291,6 +318,7 @@ export function EmployeeDetail(props: EmployeeDetailProps) {
|
||||
employee={employee}
|
||||
dependents={dependents}
|
||||
locationCountry={location?.country}
|
||||
notfallkontakte={props.notfallkontakte}
|
||||
planstelle={placement ? { positionNumber: placement.positionNumber, jobTitle: placement.jobTitle } : null}
|
||||
// Wie in eintritt_planstelle_berichtigen: berichtigt wird nur, solange
|
||||
// seit dem Eintritt keine Versetzung und keine Beförderung steht.
|
||||
|
||||
@@ -2,28 +2,25 @@
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { changeEmployeeData } from "@/actions/employees";
|
||||
import { addEmergencyContact, updateEmergencyContact } from "@/actions/employees";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { VerhaeltnisField } from "@/components/employees/VerhaeltnisField";
|
||||
import { TextField } from "@/components/ui/Field";
|
||||
import { Modal } from "@/components/ui/Modal";
|
||||
import { useToast } from "@/components/ui/Toast";
|
||||
import { todayIso } from "@/lib/format";
|
||||
|
||||
// Der Notfallkontakt, ohne den Umweg über „Daten ändern".
|
||||
// Einen Notfallkontakt anlegen oder ändern — dasselbe Fenster für beides,
|
||||
// wie bei den Angehörigen.
|
||||
//
|
||||
// Geschrieben wird über dieselbe Funktion wie dort: change_employee_data mit
|
||||
// **nur** den drei Feldern im Abschnitt `person`. Das ist keine Abkürzung,
|
||||
// sondern die Bedingung dafür, dass der Eintrag in der Historie und im
|
||||
// Protokoll landet wie jede andere Stammdatenänderung. Die Datenbank fasst
|
||||
// ausschliesslich die Felder an, die im Aufruf stehen — sie prüft auf das
|
||||
// Vorhandensein des Schlüssels, nicht auf seinen Wert (Migration
|
||||
// 20260917120000). Adresse, E-Mail und der Rest bleiben deshalb unberührt.
|
||||
// Kein „Wirksam ab": ein Notfallkontakt gilt ab sofort. Bei einer Nummer, die
|
||||
// im Ernstfall gewählt wird, ist ein Datum in der Zukunft keine sinnvolle
|
||||
// Angabe, sondern eine Frage zu viel.
|
||||
|
||||
export type Notfallkontakt = {
|
||||
name: string | null;
|
||||
telefon: string | null;
|
||||
verhaeltnis: string | null;
|
||||
id: string;
|
||||
name: string;
|
||||
phone: string;
|
||||
relation: string | null;
|
||||
};
|
||||
|
||||
export function NotfallkontaktModal({
|
||||
@@ -31,24 +28,20 @@ export function NotfallkontaktModal({
|
||||
onClose,
|
||||
employeeId,
|
||||
kontakt,
|
||||
effectiveDate,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => 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({
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title={vorhanden ? "Notfallkontakt ändern" : "Notfallkontakt hinterlegen"}
|
||||
title={kontakt ? "Notfallkontakt ändern" : "Notfallkontakt hinzufügen"}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
@@ -95,15 +81,11 @@ export function NotfallkontaktModal({
|
||||
</>
|
||||
}
|
||||
>
|
||||
{/* Kein „Wirksam ab", obwohl die Datenbankfunktion einen Stichtag
|
||||
kennt: ein Notfallkontakt gilt ab sofort. Bei einer Telefonnummer,
|
||||
die im Ernstfall gewählt wird, ist ein Datum in der Zukunft keine
|
||||
sinnvolle Angabe, sondern eine Frage zu viel. */}
|
||||
<div className="flex flex-col gap-4">
|
||||
<TextField label="Name" required value={name} onChange={setName} />
|
||||
<TextField label="Telefonnummer" required type="tel" value={telefon} onChange={setTelefon} />
|
||||
{/* Dasselbe Bauteil wie im Einstellungsassistenten: die Liste, und
|
||||
unter „Sonstige" ein Freifeld. */}
|
||||
{/* Dasselbe Bauteil wie im Einstellungsassistenten: die Liste der
|
||||
Angehörigen, und unter „Sonstige" ein Freifeld. */}
|
||||
<VerhaeltnisField value={verhaeltnis} onChange={setVerhaeltnis} />
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
@@ -3,57 +3,35 @@
|
||||
import { Pencil, Plus, Trash2 } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { changeEmployeeData } from "@/actions/employees";
|
||||
import { deleteEmergencyContact } from "@/actions/employees";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { useToast } from "@/components/ui/Toast";
|
||||
import { todayIso } from "@/lib/format";
|
||||
import { anzeige } from "@/lib/anzeige";
|
||||
import { NotfallkontaktModal, type Notfallkontakt } from "./NotfallkontaktModal";
|
||||
|
||||
// Eigener Abschnitt statt einer Zelle im Raster, und unterhalb der
|
||||
// Angehörigen: beides sind Personen im Umfeld, und der Notfallkontakt ist die
|
||||
// Ausnahme davon — deshalb steht er zuletzt, nicht dazwischen. Im Ernstfall
|
||||
// greift jemand in Eile danach; dann muss die Nummer sofort zu finden sein
|
||||
// und wählbar.
|
||||
// Die Notfallkontakte einer Person — so viele, wie es braucht, angelegt und
|
||||
// geändert wie die Angehörigen darüber (fachlich so vorgegeben).
|
||||
//
|
||||
// Der Knopf steht hier, weil er bei den Angehörigen darüber auch steht. Ohne
|
||||
// ihn führte der einzige Weg über „Daten ändern" — ein Formular über alle
|
||||
// Stammdaten, um eine Telefonnummer einzutragen.
|
||||
// Eigener Abschnitt unterhalb der Angehörigen: im Ernstfall greift jemand in
|
||||
// Eile danach; dann muss die Nummer sofort zu finden sein und wählbar.
|
||||
|
||||
export function NotfallkontaktSection({
|
||||
employeeId,
|
||||
kontakt,
|
||||
effectiveDate,
|
||||
kontakte,
|
||||
}: {
|
||||
employeeId: string;
|
||||
kontakt: Notfallkontakt;
|
||||
/**
|
||||
* Nur, wenn der Abschnitt in „Daten ändern" steht: dann treibt dessen
|
||||
* „Wirksam ab" auch diesen Vorgang — wie bei den Angehörigen darüber.
|
||||
* Ohne Angabe gilt heute.
|
||||
*/
|
||||
effectiveDate?: string;
|
||||
kontakte: Notfallkontakt[];
|
||||
}) {
|
||||
const { showToast } = useToast();
|
||||
const router = useRouter();
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [entfernt, setEntfernt] = useState(false);
|
||||
const stichtag = effectiveDate || todayIso();
|
||||
const [bearbeitet, setBearbeitet] = useState<Notfallkontakt | null>(null);
|
||||
const [entferntId, setEntferntId] = useState<string | null>(null);
|
||||
|
||||
const vorhanden = Boolean(kontakt.name);
|
||||
|
||||
async function handleEntfernen() {
|
||||
setEntfernt(true);
|
||||
// Leere Zeichenketten, nicht ausgelassene Felder: die Datenbank macht
|
||||
// daraus null. Würden die Schlüssel fehlen, bliebe der Kontakt stehen.
|
||||
const result = await changeEmployeeData({
|
||||
employee_id: employeeId,
|
||||
effective_date: stichtag,
|
||||
person: { emergency_contact_name: "", emergency_contact_phone: "", emergency_contact_relation: "" },
|
||||
contract: {},
|
||||
role: {},
|
||||
});
|
||||
setEntfernt(false);
|
||||
async function handleEntfernen(k: Notfallkontakt) {
|
||||
setEntferntId(k.id);
|
||||
const result = await deleteEmergencyContact({ id: k.id, employee_id: employeeId });
|
||||
setEntferntId(null);
|
||||
if (result.success) {
|
||||
showToast("Notfallkontakt entfernt.");
|
||||
router.refresh();
|
||||
@@ -65,27 +43,23 @@ export function NotfallkontaktSection({
|
||||
return (
|
||||
<div className="border-t border-border pt-6">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<h3 className="text-xs font-bold uppercase tracking-wide text-brand-700">Notfallkontakt</h3>
|
||||
{/* Nur, solange keiner hinterlegt ist: es gibt genau einen. Ein
|
||||
zweites „Hinzufügen" daneben verspräche eine Liste, die es hier
|
||||
nicht gibt — geändert und entfernt wird in der Zeile selbst. */}
|
||||
{!vorhanden && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setModalOpen(true)}
|
||||
className="!px-1 text-brand-700 hover:!bg-transparent hover:underline"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" /> Hinzufügen
|
||||
</Button>
|
||||
)}
|
||||
<h3 className="text-xs font-bold uppercase tracking-wide text-brand-700">Notfallkontakte</h3>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setBearbeitet(null);
|
||||
setModalOpen(true);
|
||||
}}
|
||||
className="!px-1 text-brand-700 hover:!bg-transparent hover:underline"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" /> Hinzufügen
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 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 ? (
|
||||
<div className="overflow-x-auto rounded border border-border">
|
||||
<table className="w-full min-w-[600px] text-sm">
|
||||
<thead>
|
||||
@@ -97,43 +71,44 @@ export function NotfallkontaktSection({
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr className="border-b border-border last:border-0">
|
||||
<td className="px-4 py-2.5 font-semibold text-ink">{kontakt.name}</td>
|
||||
<td className="px-4 py-2.5 text-ink-body">
|
||||
{kontakt.telefon ? (
|
||||
// Wählbar: im Ernstfall greift jemand in Eile danach.
|
||||
{kontakte.map((k) => (
|
||||
<tr key={k.id} className="border-b border-border last:border-0">
|
||||
<td className="px-4 py-2.5 font-semibold text-ink">{k.name}</td>
|
||||
<td className="px-4 py-2.5 text-ink-body">
|
||||
{/* Wählbar: im Ernstfall greift jemand in Eile danach. */}
|
||||
<a
|
||||
href={`tel:${kontakt.telefon.replace(/\s/g, "")}`}
|
||||
href={`tel:${k.phone.replace(/\s/g, "")}`}
|
||||
className="rounded font-semibold hover:text-brand-700 hover:underline
|
||||
focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand-500"
|
||||
>
|
||||
{kontakt.telefon}
|
||||
{k.phone}
|
||||
</a>
|
||||
) : (
|
||||
"–"
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-ink-body">{anzeige(kontakt.verhaeltnis) || "–"}</td>
|
||||
<td className="px-4 py-2.5 text-right">
|
||||
<Button
|
||||
variant="icon"
|
||||
onClick={() => setModalOpen(true)}
|
||||
aria-label="Notfallkontakt ändern"
|
||||
className="hover:!text-brand-700"
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="icon"
|
||||
onClick={handleEntfernen}
|
||||
pending={entfernt}
|
||||
aria-label="Notfallkontakt entfernen"
|
||||
className="hover:!text-danger-solid"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-ink-body">{anzeige(k.relation) || "–"}</td>
|
||||
<td className="px-4 py-2.5 text-right">
|
||||
<Button
|
||||
variant="icon"
|
||||
onClick={() => {
|
||||
setBearbeitet(k);
|
||||
setModalOpen(true);
|
||||
}}
|
||||
aria-label={`Notfallkontakt ${k.name} ändern`}
|
||||
className="hover:!text-brand-700"
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="icon"
|
||||
onClick={() => handleEntfernen(k)}
|
||||
pending={entferntId === k.id}
|
||||
aria-label={`Notfallkontakt ${k.name} entfernen`}
|
||||
className="hover:!text-danger-solid"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@@ -141,17 +116,17 @@ export function NotfallkontaktSection({
|
||||
<p className="text-sm text-ink-muted">Kein Notfallkontakt hinterlegt.</p>
|
||||
)}
|
||||
|
||||
{/* `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. */}
|
||||
<NotfallkontaktModal
|
||||
key={`${kontakt.name ?? ""}|${kontakt.telefon ?? ""}|${kontakt.verhaeltnis ?? ""}`}
|
||||
open={modalOpen}
|
||||
onClose={() => 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 && (
|
||||
<NotfallkontaktModal
|
||||
key={bearbeitet?.id ?? "neu"}
|
||||
open
|
||||
onClose={() => setModalOpen(false)}
|
||||
employeeId={employeeId}
|
||||
kontakt={bearbeitet}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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. */}
|
||||
<NotfallkontaktSection
|
||||
employeeId={employee.id}
|
||||
effectiveDate={effectiveDate}
|
||||
kontakt={{
|
||||
name: employee.emergency_contact_name,
|
||||
telefon: employee.emergency_contact_phone,
|
||||
verhaeltnis: employee.emergency_contact_relation,
|
||||
}}
|
||||
/>
|
||||
aber eine zweite Bauform für denselben Zweck. Die Angehörigen
|
||||
laufen über das „Wirksam ab" dieses Formulars; ein Notfallkontakt
|
||||
gilt ab sofort. */}
|
||||
<NotfallkontaktSection employeeId={employee.id} kontakte={notfallkontakte} />
|
||||
</div>
|
||||
</SlideOver>
|
||||
);
|
||||
|
||||
@@ -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
|
||||
|
||||
<AngehoerigeSection employeeId={employee.id} dependents={dependents} />
|
||||
|
||||
<NotfallkontaktSection
|
||||
employeeId={employee.id}
|
||||
kontakt={{
|
||||
name: employee.emergency_contact_name,
|
||||
telefon: employee.emergency_contact_phone,
|
||||
verhaeltnis: employee.emergency_contact_relation,
|
||||
}}
|
||||
/>
|
||||
<NotfallkontaktSection employeeId={employee.id} kontakte={notfallkontakte} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 && (
|
||||
<div className="absolute right-0 z-20 mt-2 max-h-[28rem] w-96 overflow-y-auto rounded border border-border bg-white shadow-[var(--shadow-card-hover)]">
|
||||
<div className="flex items-center justify-between gap-2 border-b border-border px-4 py-2.5">
|
||||
<span className="text-xs font-bold uppercase tracking-wide text-ink-muted">
|
||||
Meine Notizen ({notes.length})
|
||||
</span>
|
||||
{/* 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 ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setNurMeine((v) => !v)}
|
||||
aria-pressed={nurMeine}
|
||||
className={`rounded px-1.5 py-0.5 text-xs font-bold uppercase tracking-wide hover:bg-surface focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand-500 ${
|
||||
nurMeine ? "bg-accent-200 text-brand-700" : "text-ink-muted"
|
||||
}`}
|
||||
>
|
||||
Meine Notizen ({notes.filter((n) => n.vonMir).length})
|
||||
</button>
|
||||
) : (
|
||||
<span className="text-xs font-bold uppercase tracking-wide text-ink-muted">
|
||||
Meine Notizen ({notes.length})
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setZeigeEinstellung((v) => !v)}
|
||||
@@ -136,11 +156,11 @@ export function NotesBell({ notes, kollegen }: { notes: OpenNote[]; kollegen: Ko
|
||||
</div>
|
||||
)}
|
||||
|
||||
{notes.length === 0 ? (
|
||||
{sichtbar.length === 0 ? (
|
||||
<p className="px-4 py-6 text-center text-sm text-ink-muted">Keine offenen Notizen.</p>
|
||||
) : (
|
||||
<ul className="divide-y divide-border">
|
||||
{notes.map((n) => (
|
||||
{sichtbar.map((n) => (
|
||||
<li key={n.id} className="px-4 py-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className={`rounded-full px-2 py-0.5 text-xs font-semibold ${NOTE_CATEGORY_STYLES[n.category]}`}>{n.category}</span>
|
||||
|
||||
@@ -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$;
|
||||
177
db/migrations/20261019160000_mehrere_notfallkontakte.sql
Normal file
177
db/migrations/20261019160000_mehrere_notfallkontakte.sql
Normal file
@@ -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$;
|
||||
@@ -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;
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -63,6 +63,8 @@ export async function ladeExportMitarbeiter(
|
||||
/** Name je HR-Konto — für „Zuständige HR". */
|
||||
hrName: Map<string, string>;
|
||||
dependentsCounts: Map<string, number>;
|
||||
/** Die Notfallkontakte je Person, in der Reihenfolge ihrer Erfassung. */
|
||||
notfallkontakte: Map<string, { name: string; phone: string; relation: string | null }[]>;
|
||||
}> {
|
||||
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<string, { name: string; phone: string; relation: string | null }[]>();
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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) => ({
|
||||
|
||||
@@ -30,7 +30,7 @@ export const KPI_ERKLAERUNGEN: Record<string, string> = {
|
||||
"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“. " +
|
||||
|
||||
38
lib/types.ts
38
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<Database["public"]["Tables"]["employee_dependents"]["Insert"]>;
|
||||
};
|
||||
// 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<Database["public"]["Tables"]["employee_emergency_contacts"]["Insert"]>;
|
||||
};
|
||||
employee_notes: {
|
||||
Row: {
|
||||
id: string;
|
||||
@@ -839,6 +850,9 @@ export type Database = {
|
||||
// werden konnte (20261019140000).
|
||||
austritt_zuruecknehmen: { Args: { payload: Record<string, unknown> }; Returns: string | null };
|
||||
eintritt_planstelle_berichtigen: { Args: { payload: Record<string, unknown> }; Returns: void };
|
||||
add_emergency_contact: { Args: { payload: Record<string, unknown> }; Returns: string };
|
||||
update_emergency_contact: { Args: { payload: Record<string, unknown> }; Returns: void };
|
||||
delete_emergency_contact: { Args: { payload: Record<string, unknown> }; 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.
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
Reference in New Issue
Block a user