Compare commits
11 Commits
02a4ed551b
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6fa03416c6 | ||
| 9ce6375b33 | |||
| 1729c2faad | |||
|
|
dde897a1c8 | ||
| 8fe2e91e56 | |||
| 5dcbc9c7f7 | |||
| 79979216e4 | |||
| e1ef57d44b | |||
| 3465fc4a4e | |||
| 486a273510 | |||
| 75a42fe243 |
@@ -79,3 +79,10 @@ CRON_SECRET=
|
||||
# und hat jemand in der Auswahl kein Geburtsdatum, lehnt der Export mit einem
|
||||
# Hinweis ab; die übrige Anwendung ist nicht betroffen.
|
||||
LOLYO_STARTPASSWORT=
|
||||
|
||||
# ── Testsystem ───────────────────────────────────────────────────────
|
||||
#
|
||||
# Auf einer Testinstallation auf 1 setzen: jede Seite trägt dann oben den
|
||||
# Schriftzug „Testsystem", und der Titel im Browser-Tab beginnt damit. In der
|
||||
# Produktion leer lassen.
|
||||
TESTSYSTEM=
|
||||
|
||||
@@ -94,6 +94,7 @@ Werte eintragen:
|
||||
| `AUTH_MICROSOFT_ENTRA_ID_SECRET` | Entra-Portal → Zertifikate & Geheimnisse (nur einmal sichtbar!) |
|
||||
| `AUTH_MICROSOFT_ENTRA_ID_ISSUER` | `https://login.microsoftonline.com/<verzeichnis-id>/v2.0` |
|
||||
| `CRON_SECRET` | selbst generieren: `openssl rand -hex 32` |
|
||||
| `TESTSYSTEM` | `1` auf dem Testserver: Schriftzug „Testsystem" auf jeder Seite. Sonst leer |
|
||||
|
||||
Details zur Entra-Registrierung: [`docs/entra-sso.md`](docs/entra-sso.md).
|
||||
|
||||
|
||||
@@ -26,6 +26,11 @@ freigegebene Domain (siehe [Sicherheitsprinzipien](#sicherheitsprinzipien)).
|
||||
führen eine Änderung, ihren Historieneintrag und ihren Protokolleintrag in
|
||||
**einer** Transaktion aus.
|
||||
- **Auth.js** gegen **Microsoft Entra ID** — keine eigenen Passwörter.
|
||||
<!-- intern:start -->
|
||||
- *Intern, nicht in der Übergabe:* Für den Testbetrieb gibt es auf `master`
|
||||
zusätzlich eine Anmeldung mit Passwort. Der Übergabestand enthält sie nicht —
|
||||
siehe [`uebergabe/README.md`](uebergabe/README.md).
|
||||
<!-- intern:end -->
|
||||
- **Tailwind CSS v4**
|
||||
- **Vitest** — Unit-Tests (Node), Komponententests (jsdom) und
|
||||
Integrationstests gegen eine erreichbare Datenbank.
|
||||
@@ -67,6 +72,7 @@ Kurzfassung — alles davon ist rein server-seitig:
|
||||
| `AUTH_URL` | Adresse, unter der die Anwendung von aussen erreichbar ist |
|
||||
| `CRON_SECRET` | Schützt `/api/cron/apply-pending-changes` |
|
||||
| `LOLYO_STARTPASSWORT` | Ersatzpasswort im LOLYO-Export für Personen ohne Geburtsdatum (sonst ist das Passwort das Geburtsdatum als TT.MM.JJJJ). Fehlt der Wert und hat jemand in der Auswahl kein Geburtsdatum, lehnt der Export ab |
|
||||
| `TESTSYSTEM` | `1` auf einer Testinstallation: Schriftzug „Testsystem" oben auf jeder Seite und im Titel des Browser-Tabs. In der Produktion leer |
|
||||
|
||||
**Es gibt keine `NEXT_PUBLIC_*`-Variablen.** Nichts wird in das Browser-Bundle
|
||||
eingebacken, weil der Browser mit nichts spricht ausser der Anwendung selbst.
|
||||
|
||||
@@ -1,12 +1,38 @@
|
||||
"use server";
|
||||
|
||||
import { AuthError } from "next-auth";
|
||||
import { signIn, signOut } from "@/auth";
|
||||
|
||||
// Anmeldung und Abmeldung.
|
||||
// Zwei Anmeldewege, und der zweite ist auf Zeit.
|
||||
//
|
||||
// Angemeldet wird ausschliesslich über Microsoft Entra ID. Was der Mandant
|
||||
// vorgibt — Mehrfaktor, bedingter Zugriff, Sperrung beim Austritt — gilt
|
||||
// damit für jede Anmeldung an dieser Anwendung.
|
||||
// **Entra ID ist der Hauptweg.** Was der Mandant vorgibt — Mehrfaktor,
|
||||
// bedingter Zugriff, Sperrung beim Austritt — gilt nur auf diesem Weg. Ein
|
||||
// zweiter Weg daneben hebelt all das aus.
|
||||
//
|
||||
// **Wozu es ihn gibt.** Der Passwortweg lässt Personen ohne Konto im eigenen
|
||||
// Entra-Mandanten an die Anwendung, ohne dass dafür eine Gasteinladung
|
||||
// eingerichtet werden muss. Er ist für den Betrieb mit synthetischen Daten
|
||||
// gedacht.
|
||||
//
|
||||
// **Was den Weg begrenzt** — nichts davon steht hier, alles in der Datenbank
|
||||
// (Migration 20260908120000), weil eine Regel im Anwendungscode die Regel
|
||||
// wäre, die sich umgehen lässt:
|
||||
//
|
||||
// • Zwang zum Wechsel beim ersten Mal; solange er aussteht, liefert
|
||||
// is_hr_user() false und damit gibt keine einzige Policy eine Zeile her
|
||||
// • sieben Tage Frist für einen nie benutzten Zugang
|
||||
// • Sperre für 15 Minuten nach fünf Fehlversuchen
|
||||
// • ein Enddatum in `app_passwoerter.gueltig_bis`, das die Anmeldung
|
||||
// danach kein Passwort mehr annehmen lässt
|
||||
//
|
||||
// Das Enddatum ist bewusst keine feste Prüfbedingung im Schema (Migration
|
||||
// 20260908140000): ein unangekündigt ablaufender Zugang sieht für die
|
||||
// Person davor nach einem Defekt der Anwendung aus und nicht nach einer
|
||||
// Schranke. Die Spalte und die Prüfung gibt es, einen festen Termin nicht —
|
||||
// **der Pfad endet durch eine Entscheidung, nicht von selbst.**
|
||||
//
|
||||
// **Vor echten Personendaten muss der Passwortpfad weg sein.** Das ist die
|
||||
// Bedingung für seinen Einsatz, nicht eine Empfehlung.
|
||||
//
|
||||
// Die Herkunft muss hier nicht aus dem Request geholt werden: Auth.js baut die
|
||||
// Rückruf-Adresse selbst und akzeptiert nur Ziele auf demselben Host. Ein
|
||||
@@ -18,6 +44,47 @@ export async function signInWithEntra() {
|
||||
await signIn("microsoft-entra-id", { redirectTo: "/" });
|
||||
}
|
||||
|
||||
export type AnmeldeZustand = { fehler: string | null };
|
||||
|
||||
/**
|
||||
* Anmeldung mit E-Mail und Passwort.
|
||||
*
|
||||
* Es gibt **eine** Fehlermeldung für jeden Fehlschlag. Ob die Adresse
|
||||
* unbekannt, das Passwort falsch, das Konto gesperrt oder die Frist abgelaufen
|
||||
* ist, steht im Protokoll und nicht auf dem Bildschirm: das Anmeldeformular
|
||||
* ist ohne Anmeldung erreichbar, und eine Meldung, die zwischen „gibt es nicht" und
|
||||
* „falsches Passwort" unterscheidet, ist ein Verzeichnis der Belegschaft.
|
||||
* app_passwort_pruefen() nennt aus demselben Grund keinen Grund.
|
||||
*/
|
||||
export async function anmeldenMitPasswort(
|
||||
_zustand: AnmeldeZustand,
|
||||
formular: FormData
|
||||
): Promise<AnmeldeZustand> {
|
||||
const email = String(formular.get("email") ?? "").trim();
|
||||
const passwort = String(formular.get("passwort") ?? "");
|
||||
|
||||
if (!email || !passwort) {
|
||||
return { fehler: "Bitte E-Mail-Adresse und Passwort eingeben." };
|
||||
}
|
||||
|
||||
try {
|
||||
await signIn("passwort", { email, passwort, redirectTo: "/" });
|
||||
} catch (fehler) {
|
||||
// Bei Erfolg wirft signIn die Weiterleitung von Next.js. Die darf hier
|
||||
// **nicht** hängenbleiben, sonst endet die Anmeldung auf der Anmeldeseite,
|
||||
// obwohl das Cookie längst gesetzt ist. Nur ein AuthError ist ein
|
||||
// Fehlschlag; alles andere gehört weitergereicht.
|
||||
if (fehler instanceof AuthError) {
|
||||
return { fehler: "E-Mail-Adresse oder Passwort stimmt nicht." };
|
||||
}
|
||||
throw fehler;
|
||||
}
|
||||
|
||||
// Unerreichbar — signIn kehrt bei Erfolg nicht zurück. Steht da, weil der
|
||||
// Typprüfer einen Rückgabewert auf jedem Pfad verlangt.
|
||||
return { fehler: null };
|
||||
}
|
||||
|
||||
export async function logout() {
|
||||
await signOut({ redirectTo: "/login" });
|
||||
}
|
||||
|
||||
@@ -144,7 +144,8 @@ export async function hireEmployee(payload: {
|
||||
emergency_contact_phone?: string;
|
||||
emergency_contact_relation?: string;
|
||||
is_laterale_fuehrung?: boolean;
|
||||
is_c_level?: boolean;
|
||||
/** Code aus lib/c-level.ts; "" leert die Angabe. */
|
||||
c_level?: string;
|
||||
/** Form der Beschäftigung — chk_mitarbeiterart. Leer heisst „unverändert". */
|
||||
mitarbeiterart?: string;
|
||||
has_kuendigungsschutz?: boolean;
|
||||
|
||||
61
actions/passwort.ts
Normal file
61
actions/passwort.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
"use server";
|
||||
|
||||
import { redirect } from "next/navigation";
|
||||
import { currentUserId } from "@/lib/auth/session";
|
||||
import { runMutation } from "@/lib/db/rpc";
|
||||
|
||||
// Das eigene Passwort wechseln.
|
||||
//
|
||||
// Getrennt von actions/auth.ts, weil es etwas anderes ist: dort geht es um das
|
||||
// Herstellen einer Sitzung, hier um eine Änderung an den eigenen Daten. Und
|
||||
// getrennt von der Benutzerverwaltung, weil diese Aktion die einzige ist,
|
||||
// die **ohne** HR-Rechte funktionieren muss.
|
||||
|
||||
export type WechselZustand = { fehler: string | null };
|
||||
|
||||
/**
|
||||
* Wechselt das Passwort der angemeldeten Person.
|
||||
*
|
||||
* Kein `revalidatePath`: der Weg danach ist eine Weiterleitung durch die
|
||||
* Komponente, und es gibt keine zwischengespeicherte Seite, die den alten Stand
|
||||
* zeigen könnte.
|
||||
*
|
||||
* Die Meldungen kommen aus app_passwort_aendern() und sind für die Oberfläche
|
||||
* geschrieben („Das bisherige Passwort stimmt nicht.") — sie werden
|
||||
* durchgereicht wie bei jeder anderen Mutation.
|
||||
*/
|
||||
export async function passwortAendern(
|
||||
_zustand: WechselZustand,
|
||||
formular: FormData
|
||||
): Promise<WechselZustand> {
|
||||
const altes = String(formular.get("altes_passwort") ?? "");
|
||||
const neues = String(formular.get("neues_passwort") ?? "");
|
||||
const wiederholung = String(formular.get("wiederholung") ?? "");
|
||||
|
||||
if (!altes || !neues) {
|
||||
return { fehler: "Bitte das bisherige und das neue Passwort eingeben." };
|
||||
}
|
||||
|
||||
// Diese eine Prüfung gehört hierher und nicht in die Datenbank: die
|
||||
// Wiederholung ist ein Bedienelement gegen Vertippen, kein Datum. Die
|
||||
// Datenbank sieht sie nie und soll sie auch nicht sehen.
|
||||
if (neues !== wiederholung) {
|
||||
return { fehler: "Die beiden neuen Passwörter stimmen nicht überein." };
|
||||
}
|
||||
|
||||
const ergebnis = await runMutation(await currentUserId(), "app_passwort_aendern", {
|
||||
altes_passwort: altes,
|
||||
neues_passwort: neues,
|
||||
});
|
||||
|
||||
if (!ergebnis.success) {
|
||||
return { fehler: ergebnis.error ?? "Unbekannter Fehler." };
|
||||
}
|
||||
|
||||
// Ab hier ist der Wechsel erledigt, is_hr_user() liefert wieder true und die
|
||||
// Anwendung ist offen. Die Weiterleitung steht in der Aktion und nicht in der
|
||||
// Komponente: `redirect()` wirft, die Aktion kehrt also nicht zurück, und es
|
||||
// gibt keinen Zwischenzustand, in dem das Formular noch einmal abgeschickt
|
||||
// werden könnte.
|
||||
redirect("/");
|
||||
}
|
||||
@@ -30,8 +30,10 @@ export async function generateMetadata({ params, searchParams }: Props) {
|
||||
const [{ id }, sp] = await Promise.all([params, searchParams]);
|
||||
const art = parseArt(sp.art);
|
||||
const daten = await withUser(await currentUserId(), (tx) => loadChecklistPrint(tx, id, art));
|
||||
if (!daten) return { title: artTitel(art) };
|
||||
return { title: checklistDateiname(art, daten.kopf, todayIso()) };
|
||||
// Absolut: der Titel ist der Dateiname, eine Vorlage des Layouts gehört
|
||||
// nicht hinein.
|
||||
if (!daten) return { title: { absolute: artTitel(art) } };
|
||||
return { title: { absolute: checklistDateiname(art, daten.kopf, todayIso()) } };
|
||||
}
|
||||
|
||||
export default async function ChecklistPrintPage({ params, searchParams }: Props) {
|
||||
|
||||
@@ -22,10 +22,12 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
|
||||
// entzogene Freischaltung wirkt also sofort statt erst mit dem nächsten
|
||||
// Sitzungstoken.
|
||||
//
|
||||
// Die Umleitung ist Bedienkomfort, keine Absicherung: wer sie umgeht,
|
||||
// Beide Umleitungen sind Bedienkomfort, keine Absicherung: wer sie umgeht,
|
||||
// bekommt trotzdem keine Zeile, weil die RLS-Policies dieselbe Frage stellen
|
||||
// (is_hr_user()). Ohne sie stünde die Person nur vor einer leeren Anwendung
|
||||
// und wüsste nicht, warum.
|
||||
if (ergebnis.status === "passwort_wechseln") redirect("/passwort-aendern");
|
||||
|
||||
// Ohne den Grund in der Adresse stünde die Person vor einer wortlosen
|
||||
// Anmeldeseite und versuchte es endlos erneut.
|
||||
if (ergebnis.status === "kein_zugang") redirect("/login?error=no_hr_access");
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { EntraSignInButton } from "@/components/auth/EntraSignInButton";
|
||||
import { PasswortFormular } from "@/components/auth/PasswortFormular";
|
||||
import { AppWortmarke } from "@/components/brand/Logo";
|
||||
import { logout, signInWithEntra } from "@/actions/auth";
|
||||
|
||||
@@ -16,6 +17,15 @@ const ERROR_MESSAGES = {
|
||||
title: "Anmeldung fehlgeschlagen",
|
||||
body: "Die Anmeldung über das Firmenkonto konnte nicht abgeschlossen werden. Bitte versuchen Sie es erneut.",
|
||||
},
|
||||
// Auth.js' eigener Code für eine gescheiterte Passwortanmeldung. Im Regelfall
|
||||
// kommt er hier nicht an — die Server Action fängt den Fehlschlag ab und
|
||||
// zeigt ihn am Formular. Ohne diesen Eintrag fiele er aber auf `sso_failed`
|
||||
// zurück, und dort stünde „über das Firmenkonto", was mit dem tatsächlichen
|
||||
// Weg nichts zu tun hätte.
|
||||
CredentialsSignin: {
|
||||
title: "Anmeldung fehlgeschlagen",
|
||||
body: "E-Mail-Adresse oder Passwort stimmt nicht.",
|
||||
},
|
||||
} as const;
|
||||
|
||||
type ErrorCode = keyof typeof ERROR_MESSAGES;
|
||||
@@ -81,6 +91,20 @@ export default async function LoginPage({ searchParams }: LoginPageProps) {
|
||||
<EntraSignInButton />
|
||||
</form>
|
||||
|
||||
{/* Der Passwortweg steht bewusst *unter* dem Firmenkonto und ohne
|
||||
eigene Überschrift: er ist die Ausnahme, nicht die zweite
|
||||
gleichwertige Möglichkeit. Wer ein Firmenkonto hat,
|
||||
soll oben klicken. */}
|
||||
<div className="mt-6 flex items-center gap-3" aria-hidden>
|
||||
<span className="h-px flex-1 bg-border-subtle" />
|
||||
<span className="text-xs font-semibold uppercase tracking-wider text-ink-muted">oder</span>
|
||||
<span className="h-px flex-1 bg-border-subtle" />
|
||||
</div>
|
||||
|
||||
<div className="mt-6">
|
||||
<PasswortFormular />
|
||||
</div>
|
||||
|
||||
<p className="mt-6 border-t border-border-subtle pt-5 text-xs leading-relaxed text-ink-muted">
|
||||
Die Anmeldung allein erteilt keinen Zugriff. Den HR-Zugang schaltet die IT frei — bis dahin bleiben alle
|
||||
Personaldaten verschlossen.
|
||||
|
||||
@@ -111,9 +111,11 @@ function employeeExportColumns(
|
||||
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 },
|
||||
// Code und Bezeichnung getrennt: der Code ist das, was andere Systeme
|
||||
// weiterverarbeiten, die Bezeichnung das, was ein Mensch liest.
|
||||
{ header: "C-Level", get: (e) => e.c_level },
|
||||
{ header: "Hay-Grade", get: (e) => e.paygrade },
|
||||
{ header: "VL", get: (e) => e.vl },
|
||||
{ header: "FL", get: (e) => e.vl },
|
||||
{ header: "Bonusanspruch", get: (e) => e.has_bonusanspruch },
|
||||
{ header: "Bonusregelung", get: (e) => e.bonusanspruch_art },
|
||||
{ header: "Herkunft", get: (e) => e.source },
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Metadata, Viewport } from "next";
|
||||
import { Barlow } from "next/font/google";
|
||||
import { TestsystemSchriftzug } from "@/components/shell/TestsystemSchriftzug";
|
||||
import { ToastProvider } from "@/components/ui/Toast";
|
||||
import { istTestsystem, TESTSYSTEM_SCHRIFTZUG } from "@/lib/testsystem";
|
||||
import "./globals.css";
|
||||
|
||||
// ═══ Die Schrift ═══
|
||||
@@ -31,7 +33,7 @@ const din = Barlow({
|
||||
weight: ["400", "600", "700", "800"],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
const METADATA: Metadata = {
|
||||
title: "Alpenwerk HR",
|
||||
description: "HR-Stammdaten- und Organisationsmanagement für Alpenwerk Industrie GmbH",
|
||||
// Added to the home screen on iOS this opens without Safari's chrome and
|
||||
@@ -44,6 +46,15 @@ export const metadata: Metadata = {
|
||||
manifest: "/manifest.webmanifest",
|
||||
};
|
||||
|
||||
// Als Funktion, damit TESTSYSTEM bei der Anfrage gelesen wird und nicht beim
|
||||
// Bauen. Die Vorlage setzt den Schriftzug auch vor die Titel der Unterseiten;
|
||||
// Seiten, deren Titel als Dateiname beim Drucken dient, setzen ihn absolut.
|
||||
export function generateMetadata(): Metadata {
|
||||
if (!istTestsystem()) return METADATA;
|
||||
const vorsatz = `[${TESTSYSTEM_SCHRIFTZUG}]`;
|
||||
return { ...METADATA, title: { default: `${vorsatz} Alpenwerk HR`, template: `${vorsatz} %s` } };
|
||||
}
|
||||
|
||||
export const viewport: Viewport = {
|
||||
width: "device-width",
|
||||
initialScale: 1,
|
||||
@@ -63,6 +74,7 @@ export default function RootLayout({
|
||||
return (
|
||||
<html lang="de-AT" className={`${din.variable} h-full antialiased`}>
|
||||
<body className="flex min-h-dvh flex-col font-sans">
|
||||
{istTestsystem() && <TestsystemSchriftzug />}
|
||||
<ToastProvider>{children}</ToastProvider>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
57
app/passwort-aendern/page.tsx
Normal file
57
app/passwort-aendern/page.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { PasswortAendernFormular } from "@/components/auth/PasswortAendernFormular";
|
||||
import { CARD_CLASS } from "@/components/ui/Card";
|
||||
import { currentUserId } from "@/lib/auth/session";
|
||||
import { sql, withUser } from "@/lib/db";
|
||||
|
||||
// Diese Seite liegt **ausserhalb** der Gruppe (app), und das ist der Punkt.
|
||||
//
|
||||
// app/(app)/layout.tsx lässt nur durch, wer aktive HR-Person ist — und genau
|
||||
// das ist man nicht, solange ein Passwortwechsel aussteht: is_hr_user() liefert
|
||||
// dann false (Migration 20260908120000). Läge diese Seite unter (app), wäre sie
|
||||
// für die einzigen Menschen gesperrt, die sie brauchen.
|
||||
//
|
||||
// Angemeldet sein muss man trotzdem: darum kümmert sich proxy.ts, der jede
|
||||
// Adresse ausser /login und /api/auth hinter eine Sitzung stellt. Die Prüfung
|
||||
// unten ist die zweite Linie für den Fall, dass jemand den Matcher ändert.
|
||||
|
||||
export const metadata = { title: "Passwort ändern" };
|
||||
|
||||
export default async function PasswortAendernPage() {
|
||||
const userId = await currentUserId();
|
||||
if (!userId) redirect("/login");
|
||||
|
||||
// Erzwungen oder freiwillig — davon hängt nur die Beschriftung ab und ob es
|
||||
// einen Weg zurück gibt.
|
||||
//
|
||||
// Ob dieses Konto überhaupt ein Passwort hat, wird hier *nicht* gefragt:
|
||||
// app_passwoerter ist für die Anwendungsrolle unerreichbar (Policy
|
||||
// `using (false)`), und eine Auskunftsfunktion nur für diese Anzeige wäre
|
||||
// eine Funktion zu viel. Wer kein Passwort hat, bekommt beim Absenden die
|
||||
// Meldung aus app_passwort_aendern().
|
||||
const erzwungen = await withUser(userId, async (tx) => {
|
||||
const ergebnis = await sql<{ wechseln: boolean }>`select app_muss_passwort_wechseln() as wechseln`.execute(tx);
|
||||
return ergebnis.rows[0]?.wechseln === true;
|
||||
});
|
||||
|
||||
return (
|
||||
<main className="flex min-h-dvh items-center justify-center px-6 py-12">
|
||||
<div className="w-full max-w-sm">
|
||||
<h1 className="text-2xl font-extrabold tracking-tight text-ink">Passwort ändern</h1>
|
||||
|
||||
{erzwungen ? (
|
||||
<p className="mt-1.5 text-sm text-ink-muted">
|
||||
Ihr Zugang wurde mit einem gemeinsamen Startpasswort eingerichtet. Solange es gilt, bleiben alle
|
||||
Personaldaten verschlossen — bitte vergeben Sie jetzt ein eigenes.
|
||||
</p>
|
||||
) : (
|
||||
<p className="mt-1.5 text-sm text-ink-muted">Sie können hier jederzeit ein neues Passwort vergeben.</p>
|
||||
)}
|
||||
|
||||
<div className={`mt-7 p-5 ${CARD_CLASS}`}>
|
||||
<PasswortAendernFormular erzwungen={erzwungen} />
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
75
auth.ts
75
auth.ts
@@ -1,5 +1,6 @@
|
||||
import "server-only";
|
||||
import NextAuth from "next-auth";
|
||||
import Credentials from "next-auth/providers/credentials";
|
||||
import { authConfig } from "@/lib/auth/config";
|
||||
import { asSystem, sql } from "@/lib/db";
|
||||
|
||||
@@ -9,6 +10,14 @@ import { asSystem, sql } from "@/lib/db";
|
||||
// Hier kommt das dazu, was einmal pro Anmeldung passieren muss: aus der
|
||||
// Kennung, die Entra ausstellt, eine Kennung machen, die diese Anwendung
|
||||
// versteht.
|
||||
//
|
||||
// Daneben steht ein zweiter Weg: Anmeldung mit Passwort, mit eingebautem
|
||||
// Enddatum (siehe Migration 20260908120000).
|
||||
// Auch er gehört **hierher** und nicht nach lib/auth/config.ts, denn auch er
|
||||
// spricht mit der Datenbank. Der Proxy sieht ihn nicht und braucht ihn nicht:
|
||||
// er liest nur das Sitzungscookie, und das ist ein signiertes Token, dessen
|
||||
// Entschlüsselung von der Anbieterliste unabhängig ist. Welcher Weg zur
|
||||
// Sitzung geführt hat, steht darin nicht — und muss es auch nicht.
|
||||
|
||||
/**
|
||||
* Legt die app_users-Zeile an oder frischt sie auf und liefert die Kennung,
|
||||
@@ -31,19 +40,77 @@ async function upsertAppUser(externalId: string, email: string, fullName: string
|
||||
return row.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Anmeldung mit Passwort.
|
||||
*
|
||||
* Die Prüfung selbst steht vollständig in app_passwort_pruefen(): Sperre nach
|
||||
* fünf Fehlversuchen, Frist für das Initialpasswort, Enddatum des
|
||||
* Passwortpfads, Protokolleintrag. Hier bleibt nur das Weiterreichen — und
|
||||
* das ist Absicht. Eine zweite Fassung der Regeln im Anwendungscode wäre die
|
||||
* Fassung, die zuerst veraltet, und sie liesse sich umgehen, indem jemand die
|
||||
* Datenbankfunktion direkt aufruft.
|
||||
*
|
||||
* Die Funktion liefert eine Kennung oder null und **nie einen Grund**. Was
|
||||
* hier ankommt, reicht deshalb nicht aus, um zu unterscheiden, ob die Adresse
|
||||
* unbekannt, das Passwort falsch oder das Konto gesperrt war. Genau so soll
|
||||
* die Anmeldemaske antworten.
|
||||
*/
|
||||
const passwortAnbieter = Credentials({
|
||||
id: "passwort",
|
||||
name: "Passwort",
|
||||
credentials: {
|
||||
email: { label: "E-Mail", type: "email" },
|
||||
passwort: { label: "Passwort", type: "password" },
|
||||
},
|
||||
async authorize(eingabe) {
|
||||
const email = typeof eingabe?.email === "string" ? eingabe.email : "";
|
||||
const passwort = typeof eingabe?.passwort === "string" ? eingabe.passwort : "";
|
||||
if (!email || !passwort) return null;
|
||||
|
||||
// asSystem, weil es noch keine angemeldete Person gibt — die entsteht ja
|
||||
// erst aus dem Ergebnis. Dieselbe Rolle ohne BYPASSRLS wie überall; die
|
||||
// Funktion ist SECURITY DEFINER und darf genau das eine.
|
||||
const zeile = await asSystem(async (tx) => {
|
||||
const ergebnis = await sql<{ id: string | null }>`
|
||||
select app_passwort_pruefen(${email}, ${passwort}) as id
|
||||
`.execute(tx);
|
||||
return ergebnis.rows[0];
|
||||
});
|
||||
|
||||
if (!zeile?.id) return null;
|
||||
return { id: zeile.id, email, name: null };
|
||||
},
|
||||
});
|
||||
|
||||
export const { handlers, auth, signIn, signOut } = NextAuth(() => {
|
||||
const base = authConfig();
|
||||
return {
|
||||
...base,
|
||||
// Entra bleibt der erste Eintrag und damit der Hauptweg. Die Basisliste
|
||||
// wird ergänzt, nicht ersetzt: `providers: [passwortAnbieter]` hätte die
|
||||
// Firmenanmeldung stillschweigend entfernt.
|
||||
providers: [...base.providers, passwortAnbieter],
|
||||
callbacks: {
|
||||
// Die Rückrufe aus der Basis **behalten**, nicht ersetzen: dort liegt
|
||||
// session(), das die Kennung aus dem Token auf die Sitzung legt. Ein
|
||||
// schlichtes `callbacks: { jwt }` hätte es stillschweigend entfernt.
|
||||
...base.callbacks,
|
||||
async jwt({ token, profile }) {
|
||||
// Ohne `profile` ist es ein weiterer Aufruf nach der Anmeldung: das
|
||||
// Token trägt die Kennung bereits und wird nur durchgereicht.
|
||||
if (!profile) return token;
|
||||
async jwt({ token, profile, user }) {
|
||||
// Drei Fälle, und die Reihenfolge trägt sie:
|
||||
//
|
||||
// 1. Entra, erster Durchlauf → `profile` liegt vor (und `user` auch)
|
||||
// 2. Passwort, erster Durchlauf → nur `user`, aus authorize()
|
||||
// 3. jeder weitere Aufruf → keins von beiden, Token durchreichen
|
||||
//
|
||||
// Deshalb wird `profile` zuerst geprüft: bei der Anmeldung über Entra
|
||||
// ist `user` ebenfalls gesetzt, und eine Prüfung auf `user` zuerst
|
||||
// führte den Entra-Weg an app_upsert_user() vorbei — die Kennung wäre
|
||||
// dann die `oid` statt app_users.id, und keine einzige Policy fände
|
||||
// dazu eine Zeile.
|
||||
if (!profile) {
|
||||
if (user?.id) token.uid = user.id;
|
||||
return token;
|
||||
}
|
||||
|
||||
// `profile` liegt nur beim ersten Durchlauf nach der Rückkehr von Entra
|
||||
// vor. Danach wird das Token nur noch weitergereicht — die Datenbank
|
||||
|
||||
105
components/auth/PasswortAendernFormular.tsx
Normal file
105
components/auth/PasswortAendernFormular.tsx
Normal file
@@ -0,0 +1,105 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useActionState, useState } from "react";
|
||||
import { passwortAendern, type WechselZustand } from "@/actions/passwort";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { CONTROL_CLASS, Field } from "@/components/ui/Field";
|
||||
import { PASSWORT_REGELN, passwortBeanstandung } from "@/lib/passwort";
|
||||
|
||||
// Das eigene Passwort wechseln.
|
||||
//
|
||||
// Die Regeln stehen schon beim Tippen da, statt erst nach dem Absenden — beim
|
||||
// erzwungenen Wechsel ist das der erste Bildschirm, den jemand in dieser
|
||||
// Anwendung sieht, und dreimal abgewiesen zu werden ist ein schlechter Anfang.
|
||||
// Abgewiesen oder angenommen wird trotzdem in der Datenbank; hier steht nur
|
||||
// eine Vorabanzeige (lib/passwort.ts).
|
||||
|
||||
const START: WechselZustand = { fehler: null };
|
||||
|
||||
export function PasswortAendernFormular({ erzwungen }: { erzwungen: boolean }) {
|
||||
const [zustand, aktion, laeuft] = useActionState(passwortAendern, START);
|
||||
const [neues, setNeues] = useState("");
|
||||
const [wiederholung, setWiederholung] = useState("");
|
||||
|
||||
// Erst beanstanden, wenn etwas dasteht: ein leeres Feld ist noch kein Fehler.
|
||||
const beanstandung = neues ? passwortBeanstandung(neues) : null;
|
||||
const passtNichtZusammen = wiederholung.length > 0 && neues !== wiederholung;
|
||||
|
||||
return (
|
||||
<form action={aktion} className="flex flex-col gap-4">
|
||||
{zustand.fehler && (
|
||||
<p role="alert" className="rounded-md border border-danger-text/20 bg-danger-bg px-3 py-2 text-sm text-danger-text">
|
||||
{zustand.fehler}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Field label="Bisheriges Passwort">
|
||||
{(p) => (
|
||||
<input {...p} name="altes_passwort" type="password" required autoComplete="current-password" className={CONTROL_CLASS} />
|
||||
)}
|
||||
</Field>
|
||||
|
||||
<Field
|
||||
label="Neues Passwort"
|
||||
error={beanstandung}
|
||||
hint={`Erforderlich: ${PASSWORT_REGELN.join(", ")}.`}
|
||||
>
|
||||
{(p) => (
|
||||
<input
|
||||
{...p}
|
||||
name="neues_passwort"
|
||||
type="password"
|
||||
required
|
||||
autoComplete="new-password"
|
||||
value={neues}
|
||||
onChange={(e) => setNeues(e.target.value)}
|
||||
className={CONTROL_CLASS}
|
||||
/>
|
||||
)}
|
||||
</Field>
|
||||
|
||||
<Field label="Neues Passwort wiederholen" error={passtNichtZusammen ? "Die beiden Eingaben stimmen nicht überein." : null}>
|
||||
{(p) => (
|
||||
<input
|
||||
{...p}
|
||||
name="wiederholung"
|
||||
type="password"
|
||||
required
|
||||
autoComplete="new-password"
|
||||
value={wiederholung}
|
||||
onChange={(e) => setWiederholung(e.target.value)}
|
||||
className={CONTROL_CLASS}
|
||||
/>
|
||||
)}
|
||||
</Field>
|
||||
|
||||
{/* Gesperrt, solange die Vorabanzeige etwas zu beanstanden hat. Das ist
|
||||
Bequemlichkeit, keine Absicherung — wer die Schaltfläche freischaltet,
|
||||
landet in app_passwort_regeln() und wird dort abgewiesen. */}
|
||||
<Button
|
||||
type="submit"
|
||||
fullWidth
|
||||
disabled={Boolean(beanstandung) || passtNichtZusammen}
|
||||
pending={laeuft}
|
||||
pendingLabel="Wird gespeichert…"
|
||||
>
|
||||
Passwort ändern
|
||||
</Button>
|
||||
|
||||
{/* `Link` und nicht `<a>`: ein gewöhnlicher Verweis auf eine Seite dieser
|
||||
Anwendung lädt das Dokument neu und damit das ganze Bündel — der Weg
|
||||
zurück fühlte sich an wie ein Neustart. eslint-config-next weist das
|
||||
ab, und zu Recht. */}
|
||||
{!erzwungen && (
|
||||
<Link
|
||||
href="/"
|
||||
className="rounded text-center text-xs text-ink-muted underline underline-offset-2 hover:no-underline
|
||||
focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand-500"
|
||||
>
|
||||
Zurück zur Anwendung
|
||||
</Link>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
54
components/auth/PasswortFormular.tsx
Normal file
54
components/auth/PasswortFormular.tsx
Normal file
@@ -0,0 +1,54 @@
|
||||
"use client";
|
||||
|
||||
import { useActionState } from "react";
|
||||
import { anmeldenMitPasswort, type AnmeldeZustand } from "@/actions/auth";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { CONTROL_CLASS, Field } from "@/components/ui/Field";
|
||||
|
||||
// Anmeldung mit Passwort — der zweite Weg neben dem Firmenkonto (siehe
|
||||
// actions/auth.ts).
|
||||
//
|
||||
// Die Meldung kommt aus der Server Action und ist für jeden Fehlschlag
|
||||
// dieselbe. Kein `autoFocus`: die Seite bietet zwei Wege an, und der obere ist
|
||||
// der gemeinte — den Cursor unten hineinzusetzen kehrte das um.
|
||||
|
||||
const START: AnmeldeZustand = { fehler: null };
|
||||
|
||||
export function PasswortFormular() {
|
||||
const [zustand, aktion, laeuft] = useActionState(anmeldenMitPasswort, START);
|
||||
|
||||
return (
|
||||
<form action={aktion} className="flex flex-col gap-3">
|
||||
{zustand.fehler && (
|
||||
<p role="alert" className="rounded-md border border-danger-text/20 bg-danger-bg px-3 py-2 text-sm text-danger-text">
|
||||
{zustand.fehler}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Field label="E-Mail-Adresse">
|
||||
{(p) => (
|
||||
<input
|
||||
{...p}
|
||||
name="email"
|
||||
type="email"
|
||||
required
|
||||
// `username`, nicht `email`: nur so bietet der Passwortspeicher des
|
||||
// Browsers das Paar aus Adresse und Passwort gemeinsam an.
|
||||
autoComplete="username"
|
||||
className={CONTROL_CLASS}
|
||||
/>
|
||||
)}
|
||||
</Field>
|
||||
|
||||
<Field label="Passwort">
|
||||
{(p) => (
|
||||
<input {...p} name="passwort" type="password" required autoComplete="current-password" className={CONTROL_CLASS} />
|
||||
)}
|
||||
</Field>
|
||||
|
||||
<Button type="submit" fullWidth pending={laeuft} pendingLabel="Anmelden…">
|
||||
Anmelden
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -5,12 +5,14 @@ import { useEffect, useState } from "react";
|
||||
import { FILTER_SELECT_CLASS } from "@/components/ui/Field";
|
||||
import { SearchInput } from "@/components/ui/SearchInput";
|
||||
import { AUSTRITT_GEPLANT } from "@/lib/employee-status-filter";
|
||||
import { zuweisbareStandorte } from "@/lib/standorte";
|
||||
|
||||
type EmployeeFiltersProps = {
|
||||
/** Der ganze Baum, in Tiefensuche-Reihenfolge. */
|
||||
units: { id: string; name: string; unit_type: string }[];
|
||||
depthOf: Map<string, number>;
|
||||
locations: { id: string; name: string }[];
|
||||
/** Zur Auswahl kommen nur Standorte, auf denen jemand sitzen kann. */
|
||||
locations: { id: string; name: string; parent_id: string | null }[];
|
||||
};
|
||||
|
||||
// Aktiv and Langzeitabwesenheit are separate statuses — somebody on a
|
||||
@@ -107,7 +109,7 @@ export function EmployeeFilters({ units, depthOf, locations }: EmployeeFiltersPr
|
||||
className={FILTER_SELECT_CLASS}
|
||||
>
|
||||
<option value="">Alle Standorte</option>
|
||||
{locations.map((l) => (
|
||||
{zuweisbareStandorte(locations).map((l) => (
|
||||
<option key={l.id} value={l.id}>
|
||||
{l.name}
|
||||
</option>
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
KUENDIGUNGSSCHUTZ_GRUENDE,
|
||||
} from "@/lib/kuendigungsschutz";
|
||||
import { MITARBEITERARTEN } from "@/lib/mitarbeiterart";
|
||||
import { C_LEVEL_AUSWAHL } from "@/lib/c-level";
|
||||
import { anzeigeAuswahl } from "@/lib/anzeige";
|
||||
import { sortiereWochentage, WOCHENTAGE } from "@/lib/wochentage";
|
||||
import { KOLLEKTIVVERTRAEGE } from "@/lib/kollektivvertrag";
|
||||
@@ -64,7 +65,8 @@ export type RoleEmploymentValue = {
|
||||
*/
|
||||
dienstwagenArt: DienstwagenArt;
|
||||
isLateraleFuehrung: boolean;
|
||||
isCLevel: boolean;
|
||||
/** Code aus lib/c-level.ts; "" heisst nicht erfasst. */
|
||||
cLevel: string;
|
||||
/** Betriebsrat, Mutterschutz, Karenz, begünstigte Behinderung, Lehre. */
|
||||
hasKuendigungsschutz: boolean;
|
||||
/**
|
||||
@@ -218,6 +220,16 @@ export function RoleEmploymentFields({
|
||||
onChange={(v) => onChange({ collectiveAgreement: v as CollectiveAgreement })}
|
||||
options={KOLLEKTIVVERTRAEGE.map((k) => ({ value: k, label: k }))}
|
||||
/>
|
||||
{/* Freiwillig: „Bitte wählen…" ist ein wählbarer Eintrag und kein
|
||||
gesperrter Platzhalter, damit sich eine Angabe auch wieder
|
||||
entfernen lässt. */}
|
||||
<SelectField
|
||||
label="C-Level"
|
||||
dense
|
||||
value={value.cLevel}
|
||||
onChange={(v) => onChange({ cLevel: v })}
|
||||
options={[{ value: "", label: "Bitte wählen…" }, ...C_LEVEL_AUSWAHL]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Toggle group, not a set of fields: a fieldset names the group, and
|
||||
@@ -259,7 +271,7 @@ export function RoleEmploymentFields({
|
||||
<span className="w-5 font-semibold">{day}</span>
|
||||
<input
|
||||
type="number"
|
||||
step="0.5"
|
||||
step="0.01"
|
||||
min="0"
|
||||
max={MAX_STUNDEN_JE_TAG}
|
||||
inputMode="decimal"
|
||||
@@ -312,10 +324,6 @@ export function RoleEmploymentFields({
|
||||
<input type="checkbox" checked={value.isLateraleFuehrung} onChange={(e) => onChange({ isLateraleFuehrung: e.target.checked })} />
|
||||
Laterale Führung
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm text-ink-body">
|
||||
<input type="checkbox" checked={value.isCLevel} onChange={(e) => onChange({ isCLevel: e.target.checked })} />
|
||||
C-Level
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm text-ink-body">
|
||||
<input
|
||||
type="checkbox"
|
||||
|
||||
63
components/employees/StandortAuswahl.tsx
Normal file
63
components/employees/StandortAuswahl.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { SelectField } from "@/components/ui/Field";
|
||||
import { kurzname, oberstandorte, oberstandortVon, unterstandorte, type StandortEintrag } from "@/lib/standorte";
|
||||
|
||||
type Standort = StandortEintrag & { country?: string };
|
||||
|
||||
// Standort in zwei Stufen: die oberste Ebene, und bei einem Standort mit
|
||||
// Unterstandorten („Shop") eine zweite Auswahl. Gemeldet wird nur ein
|
||||
// Standort, auf dem eine Person sitzen kann; solange die zweite Auswahl
|
||||
// fehlt, ist der Wert leer — ein Pflichtfeld bleibt damit offen.
|
||||
export function StandortAuswahl({
|
||||
value,
|
||||
onChange,
|
||||
standorte,
|
||||
required,
|
||||
mitLand,
|
||||
hint,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (id: string) => void;
|
||||
standorte: readonly Standort[];
|
||||
required?: boolean;
|
||||
/** Land in Klammern dahinter, wie bei der Einstellung. */
|
||||
mitLand?: boolean;
|
||||
hint?: string;
|
||||
}) {
|
||||
// Zustand, weil „Shop" gewählt sein kann, ohne dass schon ein Wert feststeht.
|
||||
const [ober, setOber] = useState(() => oberstandortVon(standorte, value));
|
||||
const unter = unterstandorte(standorte, ober);
|
||||
const oberEintrag = standorte.find((s) => s.id === ober);
|
||||
|
||||
const beschriftung = (s: Standort, name: string) => (mitLand && s.country ? `${name} (${s.country})` : name);
|
||||
|
||||
return (
|
||||
<>
|
||||
<SelectField
|
||||
label="Standort"
|
||||
required={required}
|
||||
value={ober}
|
||||
onChange={(id) => {
|
||||
setOber(id);
|
||||
onChange(unterstandorte(standorte, id).length > 0 ? "" : id);
|
||||
}}
|
||||
placeholder="Bitte wählen…"
|
||||
options={oberstandorte(standorte).map((s) => ({ value: s.id, label: beschriftung(s, s.name) }))}
|
||||
hint={unter.length > 0 ? undefined : hint}
|
||||
/>
|
||||
{unter.length > 0 && (
|
||||
<SelectField
|
||||
label={oberEintrag?.name ?? "Standort"}
|
||||
required
|
||||
value={unter.some((s) => s.id === value) ? value : ""}
|
||||
onChange={onChange}
|
||||
placeholder="Bitte wählen…"
|
||||
options={unter.map((s) => ({ value: s.id, label: kurzname(s, oberEintrag) }))}
|
||||
hint={hint}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { useState } from "react";
|
||||
import { SelectField, TextField } from "@/components/ui/Field";
|
||||
import { anzeigeAuswahl } from "@/lib/anzeige";
|
||||
import { EMERGENCY_RELATIONS } from "@/lib/types";
|
||||
import { istFreiesVerhaeltnis, SONSTIGE } from "@/lib/verhaeltnis";
|
||||
|
||||
// Das Verhältnis zum Notfallkontakt: Auswahl, und unter „Sonstige" ein
|
||||
// Freifeld.
|
||||
@@ -23,12 +24,7 @@ import { EMERGENCY_RELATIONS } from "@/lib/types";
|
||||
// nimmt einen gespeicherten Wert, der nicht in der Liste steht, mit in die
|
||||
// Auswahl auf.
|
||||
|
||||
const SONSTIGE = "Sonstige";
|
||||
|
||||
/** Ob ein gespeicherter Wert frei eingetragen wurde. */
|
||||
export function istFreiesVerhaeltnis(wert: string): boolean {
|
||||
return wert.trim() !== "" && !(EMERGENCY_RELATIONS as readonly string[]).includes(wert);
|
||||
}
|
||||
export { istFreiesVerhaeltnis };
|
||||
|
||||
export function VerhaeltnisField({
|
||||
value,
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { SelectField } from "@/components/ui/Field";
|
||||
import { BONUSREGELUNGEN, VL_STUFEN } from "@/lib/vertragsangaben";
|
||||
|
||||
// VL und Bonusanspruch — dieselben Felder im Einstellungsassistenten, im
|
||||
// FL und Bonusanspruch — dieselben Felder im Einstellungsassistenten, im
|
||||
// Wiedereintritt und in „Daten ändern". Eine Komponente statt drei Kopien,
|
||||
// wie bei „Anstellungsart": drei Kopien laufen auseinander, und dann
|
||||
// bietet eine Stelle eine Bonusregelung an, die eine andere nicht kennt.
|
||||
@@ -28,7 +28,7 @@ export function VertragsangabenFields({
|
||||
return (
|
||||
<>
|
||||
<SelectField
|
||||
label="VL"
|
||||
label="FL"
|
||||
dense={dense}
|
||||
value={value.vl}
|
||||
onChange={(vl) => onChange({ vl })}
|
||||
|
||||
@@ -33,6 +33,7 @@ import { fmtDate, fmtFullName, todayIso } from "@/lib/format";
|
||||
import { plzHinweis, pruefePlzImFormular } from "@/lib/plz";
|
||||
import { requiresAustrianSvnr, svnrErfassbar } from "@/lib/svnr";
|
||||
import { vertragsangabenVollstaendig } from "@/lib/vertragsangaben";
|
||||
import { nachkommaFehler } from "@/lib/wochenstunden";
|
||||
import { NotfallkontaktSection } from "@/components/employees/NotfallkontaktSection";
|
||||
import { AustrittZuruecknehmen } from "@/components/employees/AustrittZuruecknehmen";
|
||||
import { EintrittPlanstelleBerichtigen } from "@/components/employees/EintrittPlanstelleBerichtigen";
|
||||
@@ -205,7 +206,7 @@ export function DatenAendernPanel({
|
||||
behinderungBis: employee.behinderung_bis ?? "",
|
||||
dienstwagenArt: employee.dienstwagen_art ?? "Verbrenner",
|
||||
isLateraleFuehrung: employee.is_laterale_fuehrung ?? false,
|
||||
isCLevel: employee.is_c_level ?? false,
|
||||
cLevel: employee.c_level ?? "",
|
||||
});
|
||||
function updateRole(patch: Partial<RoleEmploymentValue>) {
|
||||
setRole((prev) => ({ ...prev, ...patch }));
|
||||
@@ -233,6 +234,11 @@ export function DatenAendernPanel({
|
||||
showToast(geburtFehler, "error");
|
||||
return;
|
||||
}
|
||||
const nachkomma = nachkommaFehler(weeklyHours);
|
||||
if (nachkomma) {
|
||||
showToast(nachkomma, "error");
|
||||
return;
|
||||
}
|
||||
if (employmentType === "Teilzeit" && (Number(weeklyHours) <= 0 || Number(weeklyHours) >= 38.5)) {
|
||||
showToast("Wochenstunden bei Teilzeit müssen zwischen 0 und 38,5 liegen.", "error");
|
||||
return;
|
||||
@@ -382,7 +388,7 @@ export function DatenAendernPanel({
|
||||
? { teilzeit_art: teilzeit.variante, teilzeit_bis: teilzeit.bis }
|
||||
: {}),
|
||||
is_laterale_fuehrung: role.isLateraleFuehrung,
|
||||
is_c_level: role.isCLevel,
|
||||
c_level: role.cLevel,
|
||||
arbeitszeitmodell: arbeitszeitFuerDb(role.arbeitszeitmodell, role.workDays),
|
||||
},
|
||||
});
|
||||
@@ -533,7 +539,7 @@ export function DatenAendernPanel({
|
||||
label="Wochenstunden"
|
||||
dense
|
||||
type="number"
|
||||
step="0.5"
|
||||
step="0.01"
|
||||
value={weeklyHours}
|
||||
disabled={employmentType === "Vollzeit"}
|
||||
onChange={setWeeklyHours}
|
||||
|
||||
@@ -10,6 +10,7 @@ import { useToast } from "@/components/ui/Toast";
|
||||
import { ABSENCE_TYPES, absenceLabel, RUECKKEHR_GRUENDE } from "@/lib/absence";
|
||||
import { abwesenheitsplan, type PlanZeile } from "@/lib/abwesenheitsplan";
|
||||
import { fmtDate, fmtName } from "@/lib/format";
|
||||
import { nachkommaFehler } from "@/lib/wochenstunden";
|
||||
import type { Database, EmploymentStatus } from "@/lib/types";
|
||||
|
||||
type EmployeeRow = Database["public"]["Tables"]["employees"]["Row"];
|
||||
@@ -112,7 +113,7 @@ export function KarenzPanel({
|
||||
|
||||
async function handleRueckkehr() {
|
||||
if (!returnDate) {
|
||||
showToast("Bitte Rückkehrdatum angeben.", "error");
|
||||
showToast("Bitte angeben, wann die Abwesenheit endet.", "error");
|
||||
return;
|
||||
}
|
||||
if (employmentMode === "Teilzeit") {
|
||||
@@ -124,6 +125,11 @@ export function KarenzPanel({
|
||||
showToast("Wochenstunden müssen zwischen 0 und 38,5 liegen.", "error");
|
||||
return;
|
||||
}
|
||||
const nachkomma = nachkommaFehler(weeklyHours);
|
||||
if (nachkomma) {
|
||||
showToast(nachkomma, "error");
|
||||
return;
|
||||
}
|
||||
}
|
||||
setPending(true);
|
||||
const result = await rueckkehrAnpassen({
|
||||
@@ -163,7 +169,9 @@ export function KarenzPanel({
|
||||
<Button variant="ghost" onClick={folgeAnlegen ? () => setFolgeAnlegen(false) : onClose}>
|
||||
{folgeAnlegen ? "Zurück" : "Abbrechen"}
|
||||
</Button>
|
||||
{isOnKarenz && !folgeAnlegen && !plan.folgende && (
|
||||
{/* Eine anschliessende Abwesenheit gibt es nur nach der Wochenhilfe,
|
||||
fachlich so vorgegeben: auf den Mutterschutz folgt die Karenz. */}
|
||||
{isOnKarenz && istWochenhilfe && !folgeAnlegen && !plan.folgende && (
|
||||
<Button variant="secondary" onClick={() => setFolgeAnlegen(true)}>
|
||||
Anschliessende Abwesenheit planen
|
||||
</Button>
|
||||
@@ -209,7 +217,7 @@ export function KarenzPanel({
|
||||
)}
|
||||
<DateField label="Beginn" required value={karenzStart} onChange={setKarenzStart} />
|
||||
<DateField
|
||||
label={absenceType === WOCHENHILFE ? "Ende" : "Geplante Rückkehr"}
|
||||
label="Endet am"
|
||||
value={plannedReturn}
|
||||
onChange={setPlannedReturn}
|
||||
hint="Optional. Leer lassen, solange es nicht feststeht; später über „Rückkehr anpassen“ nachtragen."
|
||||
@@ -223,18 +231,18 @@ export function KarenzPanel({
|
||||
<p className="rounded bg-surface px-3 py-2 text-sm text-ink-body">
|
||||
<span className="font-semibold">{absenceLabel(status, employee.absence_type)}</span>
|
||||
{employee.karenz_start_date ? ` seit ${fmtDate(employee.karenz_start_date)}` : ""}
|
||||
{bisherigeRueckkehr ? ` · Rückkehr geplant am ${fmtDate(bisherigeRueckkehr)}` : " · Rückkehr offen"}
|
||||
{bisherigeRueckkehr ? ` · endet am ${fmtDate(bisherigeRueckkehr)}` : " · Ende offen"}
|
||||
</p>
|
||||
{plan.folgende && (
|
||||
<p className="rounded bg-surface px-3 py-2 text-sm text-ink-body">
|
||||
Danach geplant: <span className="font-semibold">{plan.folgende.art ?? "Langzeitabwesenheit"}</span> ab{" "}
|
||||
{fmtDate(plan.folgende.datum)}
|
||||
{plan.folgende.rueckkehr ? `, Rückkehr ${fmtDate(plan.folgende.rueckkehr)}` : ""}
|
||||
{plan.folgende.rueckkehr ? `, endet am ${fmtDate(plan.folgende.rueckkehr)}` : ""}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<DateField
|
||||
label="Rückkehrdatum"
|
||||
label="Endet am"
|
||||
required
|
||||
value={returnDate}
|
||||
onChange={setReturnDate}
|
||||
@@ -281,7 +289,7 @@ export function KarenzPanel({
|
||||
label="Reduzierte Wochenstunden"
|
||||
required
|
||||
type="number"
|
||||
step="0.5"
|
||||
step="0.01"
|
||||
max="38"
|
||||
value={weeklyHours}
|
||||
onChange={setWeeklyHours}
|
||||
|
||||
@@ -5,7 +5,8 @@ import { useMemo, useState } from "react";
|
||||
import { geplantenVorgangErsetzen, transferEmployee } from "@/actions/employees";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { PlanstellenAuswahl } from "@/components/positions/PlanstellenAuswahl";
|
||||
import { DateField, SelectField } from "@/components/ui/Field";
|
||||
import { StandortAuswahl } from "@/components/employees/StandortAuswahl";
|
||||
import { DateField } from "@/components/ui/Field";
|
||||
import { SlideOver } from "@/components/ui/SlideOver";
|
||||
import { useToast } from "@/components/ui/Toast";
|
||||
import { mitBisherigerStelle, type GeplanterVorgang } from "@/lib/geplanter-vorgang";
|
||||
@@ -23,7 +24,7 @@ type TransferPanelProps = {
|
||||
/** Eine geplante Versetzung, die geändert wird (lib/geplanter-vorgang.ts). */
|
||||
ersetzt?: GeplanterVorgang | null;
|
||||
/** Die Standorte zur Auswahl — mit der Versetzung kann auch der Standort wechseln. */
|
||||
locations?: { id: string; name: string }[];
|
||||
locations?: { id: string; name: string; parent_id: string | null }[];
|
||||
};
|
||||
|
||||
// Eine Versetzung ist der Wechsel auf eine andere Planstelle — nicht die
|
||||
@@ -58,6 +59,11 @@ export function TransferPanel({ open, onClose, employee, openPositions, ersetzt,
|
||||
showToast("Bitte Datum und Zielplanstelle angeben.", "error");
|
||||
return;
|
||||
}
|
||||
// Leer heisst hier: „Shop" gewählt, der einzelne Shop noch nicht.
|
||||
if (!ersetzt && !standort) {
|
||||
showToast("Bitte den Standort vollständig auswählen.", "error");
|
||||
return;
|
||||
}
|
||||
setPending(true);
|
||||
const result = ersetzt
|
||||
? await geplantenVorgangErsetzen({
|
||||
@@ -125,11 +131,10 @@ export function TransferPanel({ open, onClose, employee, openPositions, ersetzt,
|
||||
{/* Nur bei einer neuen Versetzung: an einer geplanten werden
|
||||
Planstelle und Datum geändert. */}
|
||||
{!ersetzt && locations.length > 0 && (
|
||||
<SelectField
|
||||
label="Standort"
|
||||
<StandortAuswahl
|
||||
value={standort}
|
||||
onChange={setStandort}
|
||||
options={locations.map((l) => ({ value: l.id, label: l.name }))}
|
||||
standorte={locations}
|
||||
hint="Wechselt mit der Versetzung zum selben Tag; sonst bleibt der bisherige."
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -87,7 +87,7 @@ export function VertragTab({
|
||||
// Kollektivvertrag und wird hier nicht geführt. Eine feste Zahl für alle
|
||||
// wäre erfunden, und eine erfundene Zahl ist schlechter als keine.
|
||||
["Hay-Grade", hayGradeLabel(employee.paygrade)],
|
||||
["VL", vlLabel(employee.vl)],
|
||||
["FL", vlLabel(employee.vl)],
|
||||
// Wie beim Dienstwagen: statt eines blossen „Ja" gleich die Regelung.
|
||||
["Bonusanspruch", ohneVorgabe(employee, ["has_bonusanspruch"], bonusanspruchLabel(employee.has_bonusanspruch, employee.bonusanspruch_art))],
|
||||
["Beschäftigtengruppe", ohneVorgabe(employee, ["worker_type"], anzeige(employee.worker_type) ?? "–")],
|
||||
@@ -107,7 +107,7 @@ export function VertragTab({
|
||||
["Dienstwagen", ohneVorgabe(employee, ["has_dienstwagen"], employee.has_dienstwagen ? dienstwagenLabel(employee.dienstwagen_art) : "Nein")],
|
||||
["Betriebsrat", ohneVorgabe(employee, ["is_betriebsrat"], employee.is_betriebsrat ? "Ja" : "Nein")],
|
||||
["Laterale Führung", ohneVorgabe(employee, ["is_laterale_fuehrung"], employee.is_laterale_fuehrung ? "Ja" : "Nein")],
|
||||
["C-Level", ohneVorgabe(employee, ["is_c_level"], employee.is_c_level ? "Ja" : "Nein")],
|
||||
["C-Level", employee.c_level || "–"],
|
||||
// Das Enddatum steht gleich dabei: „Ja" allein liesse offen, ob der
|
||||
// Schutz noch läuft, und genau danach fragt man.
|
||||
// Die Teilzeitvariante gehört neben die Stunden: sie erklärt, warum sie
|
||||
|
||||
@@ -60,7 +60,7 @@ type HireWizardProps = {
|
||||
/** Ein neuer Entwurf ist angelegt — er trägt bereits meine Sperre. */
|
||||
onEntwurfAngelegt: (id: string) => void;
|
||||
openPositions: OpenPositionResolved[];
|
||||
locations: { id: string; name: string; country: string }[];
|
||||
locations: { id: string; name: string; country: string; parent_id: string | null }[];
|
||||
resumeDraft: { id: string; step: number; payload: Record<string, unknown> } | null;
|
||||
initialPositionId?: string;
|
||||
};
|
||||
@@ -484,7 +484,7 @@ export function HireWizard({
|
||||
emergency_contact_phone: draft.emergencyContactPhone.trim() || undefined,
|
||||
emergency_contact_relation: draft.emergencyContactRelation.trim() || undefined,
|
||||
is_laterale_fuehrung: draft.isLateraleFuehrung,
|
||||
is_c_level: draft.isCLevel,
|
||||
c_level: draft.cLevel,
|
||||
});
|
||||
if (!result.success || !result.employeeId) {
|
||||
setSubmitting(false);
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { Entwurf } from "@/lib/entwuerfe";
|
||||
import type { OpenPositionResolved } from "@/lib/positions";
|
||||
import { HireWizard } from "./HireWizard";
|
||||
|
||||
type Location = { id: string; name: string; country: string };
|
||||
type Location = { id: string; name: string; country: string; parent_id: string | null };
|
||||
|
||||
type OpenWizardOptions = { draftId?: string; positionId?: string };
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ type RehireWizardProps = {
|
||||
onClose: () => void;
|
||||
employee: EmployeeRow;
|
||||
openPositions: OpenPositionResolved[];
|
||||
locations: { id: string; name: string; country: string }[];
|
||||
locations: { id: string; name: string; country: string; parent_id: string | null }[];
|
||||
};
|
||||
|
||||
export function RehireWizard({ open, onClose, employee, openPositions, locations }: RehireWizardProps) {
|
||||
@@ -199,7 +199,7 @@ export function RehireWizard({ open, onClose, employee, openPositions, locations
|
||||
has_dienstwagen: draft.hasDienstwagen,
|
||||
dienstwagen_art: draft.hasDienstwagen ? draft.dienstwagenArt : "",
|
||||
is_laterale_fuehrung: draft.isLateraleFuehrung,
|
||||
is_c_level: draft.isCLevel,
|
||||
c_level: draft.cLevel,
|
||||
|
||||
has_kuendigungsschutz: draft.hasKuendigungsschutz,
|
||||
kuendigungsschutz_grund: draft.hasKuendigungsschutz ? draft.kuendigungsschutzGrund : "",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { StandortAuswahl } from "@/components/employees/StandortAuswahl";
|
||||
import { PlanstellenAuswahl } from "@/components/positions/PlanstellenAuswahl";
|
||||
import { DateField, SelectField, TextField } from "@/components/ui/Field";
|
||||
import { todayIso } from "@/lib/format";
|
||||
@@ -24,7 +25,7 @@ export function StepExternePerson({
|
||||
}: {
|
||||
draft: HireDraftData;
|
||||
update: (patch: Partial<HireDraftData>) => void;
|
||||
locations: { id: string; name: string; country: string }[];
|
||||
locations: { id: string; name: string; country: string; parent_id: string | null }[];
|
||||
openPositions: OpenPositionResolved[];
|
||||
stellenFehler?: string | null;
|
||||
onNummerBefund: (befund: { nummer: number; vergeben: boolean }) => void;
|
||||
@@ -78,13 +79,12 @@ export function StepExternePerson({
|
||||
onChange={(id) => update({ positionId: id })}
|
||||
/>
|
||||
|
||||
<SelectField
|
||||
label="Standort"
|
||||
<StandortAuswahl
|
||||
required
|
||||
mitLand
|
||||
value={draft.locationId}
|
||||
onChange={(locationId) => update({ locationId })}
|
||||
placeholder="Bitte wählen…"
|
||||
options={locations.map((l) => ({ value: l.id, label: `${l.name} (${l.country})` }))}
|
||||
standorte={locations}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { StandortAuswahl } from "@/components/employees/StandortAuswahl";
|
||||
import { SvNummerField } from "@/components/employees/SvNummerField";
|
||||
import { TitleFields } from "@/components/employees/TitleFields";
|
||||
import { ZustaendigeHrField } from "@/components/employees/ZustaendigeHrField";
|
||||
@@ -14,7 +15,7 @@ import type { HireDraftData } from "./types";
|
||||
type StepPersonProps = {
|
||||
draft: HireDraftData;
|
||||
update: (patch: Partial<HireDraftData>) => void;
|
||||
locations: { id: string; name: string; country: string }[];
|
||||
locations: { id: string; name: string; country: string; parent_id: string | null }[];
|
||||
/** Meldet die geprüfte Personalnummer und ihr Ergebnis — steuert „Weiter". */
|
||||
onNummerBefund?: (befund: { nummer: number; vergeben: boolean }) => void;
|
||||
/**
|
||||
@@ -185,13 +186,12 @@ export function StepPerson({ draft, update, locations, onNummerBefund, nummerGes
|
||||
/>
|
||||
<TextField label="Private Telefonnummer" type="tel" value={draft.phone} onChange={(phone) => update({ phone })} />
|
||||
</div>
|
||||
<SelectField
|
||||
label="Standort"
|
||||
<StandortAuswahl
|
||||
required
|
||||
mitLand
|
||||
value={draft.locationId}
|
||||
onChange={(locationId) => update({ locationId })}
|
||||
placeholder="Bitte wählen…"
|
||||
options={locations.map((l) => ({ value: l.id, label: `${l.name} (${l.country})` }))}
|
||||
standorte={locations}
|
||||
/>
|
||||
<ZustaendigeHrField value={draft.zustaendigeHrId} onChange={(zustaendigeHrId) => update({ zustaendigeHrId })} />
|
||||
</div>
|
||||
|
||||
@@ -46,7 +46,6 @@ export function StepSummary({ draft, selectedPosition, locations, extern = false
|
||||
draft.isBetriebsrat && "Betriebsrat",
|
||||
draft.hasDienstwagen && `Dienstwagen (${dienstwagenLabel(draft.dienstwagenArt)})`,
|
||||
draft.isLateraleFuehrung && "Laterale Führung",
|
||||
draft.isCLevel && "C-Level",
|
||||
draft.hasKuendigungsschutz &&
|
||||
`Besonderer Kündigungsschutz${draft.kuendigungsschutzBis ? ` bis ${fmtDate(draft.kuendigungsschutzBis)}` : ""}`,
|
||||
].filter(Boolean);
|
||||
@@ -81,7 +80,7 @@ export function StepSummary({ draft, selectedPosition, locations, extern = false
|
||||
["Vertragsart", draft.contractType === "befristet" ? `befristet bis ${fmtDate(draft.contractEndDate)}` : "unbefristet"],
|
||||
["Beschäftigungsausmaß", `${draft.employmentType} (${draft.weeklyHours} h)`],
|
||||
["Hay-Grade", hayGradeLabel(draft.paygrade)],
|
||||
["VL", draft.vl || "–"],
|
||||
["FL", draft.vl || "–"],
|
||||
["Bonusanspruch", bonusanspruchLabel(draft.hasBonusanspruch, draft.bonusanspruchArt)],
|
||||
["Beschäftigtengruppe", anzeige(draft.workerType)],
|
||||
...(draft.workerType === "Lehrling"
|
||||
@@ -89,6 +88,7 @@ export function StepSummary({ draft, selectedPosition, locations, extern = false
|
||||
: []),
|
||||
["Anstellungs-/Beschäftigungsart", anzeige(draft.mitarbeiterart)],
|
||||
["Kollektivvertrag", draft.collectiveAgreement],
|
||||
["C-Level", draft.cLevel || "–"],
|
||||
["Arbeitstage", draft.workDays.join(", ") || "–"],
|
||||
["Merkmale", flags.length > 0 ? flags.join(", ") : "–"],
|
||||
];
|
||||
|
||||
@@ -88,7 +88,7 @@ export function StepVertrag({
|
||||
<TextField
|
||||
label="Wochenstunden"
|
||||
type="number"
|
||||
step="0.5"
|
||||
step="0.01"
|
||||
value={draft.weeklyHours}
|
||||
disabled={draft.employmentType === "Vollzeit"}
|
||||
onChange={(weeklyHours) => update({ weeklyHours })}
|
||||
|
||||
@@ -54,7 +54,7 @@ export function UebernahmeWizard({
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
employee: EmployeeRow;
|
||||
locations: { id: string; name: string; country: string }[];
|
||||
locations: { id: string; name: string; country: string; parent_id: string | null }[];
|
||||
}) {
|
||||
const { showToast } = useToast();
|
||||
const router = useRouter();
|
||||
@@ -202,7 +202,7 @@ export function UebernahmeWizard({
|
||||
has_dienstwagen: draft.hasDienstwagen,
|
||||
dienstwagen_art: draft.hasDienstwagen ? draft.dienstwagenArt : "",
|
||||
is_laterale_fuehrung: draft.isLateraleFuehrung,
|
||||
is_c_level: draft.isCLevel,
|
||||
c_level: draft.cLevel,
|
||||
teilzeit_art: teilzeit,
|
||||
teilzeit_bis: teilzeit ? draft.teilzeitBis : "",
|
||||
has_kuendigungsschutz: draft.hasKuendigungsschutz,
|
||||
|
||||
@@ -84,7 +84,7 @@ export type HireDraftData = {
|
||||
teilzeitBis: string;
|
||||
/** Leer heisst „noch nicht bewertet" und ist der Normalfall beim Anlegen. */
|
||||
paygrade: PaygradeType | "";
|
||||
/** VL 1–8 als Text; "" heisst nicht erfasst. */
|
||||
/** FL 1–7 als Text; "" heisst nicht erfasst. */
|
||||
vl: string;
|
||||
hasBonusanspruch: boolean;
|
||||
/** Nur ausgewertet, wenn hasBonusanspruch gesetzt ist — so will es der CHECK. */
|
||||
@@ -106,7 +106,8 @@ export type HireDraftData = {
|
||||
emergencyContactRelation: string;
|
||||
angehoerige: HireDraftAngehoerige[];
|
||||
isLateraleFuehrung: boolean;
|
||||
isCLevel: boolean;
|
||||
/** Code aus lib/c-level.ts; "" heisst nicht erfasst. */
|
||||
cLevel: string;
|
||||
/** Form der Beschäftigung — zweite Achse neben der Beschäftigtengruppe. */
|
||||
mitarbeiterart: Mitarbeiterart;
|
||||
hasKuendigungsschutz: boolean;
|
||||
@@ -182,7 +183,7 @@ export const EMPTY_HIRE_DRAFT: HireDraftData = {
|
||||
emergencyContactRelation: "",
|
||||
angehoerige: [],
|
||||
isLateraleFuehrung: false,
|
||||
isCLevel: false,
|
||||
cLevel: "",
|
||||
mitarbeiterart: MITARBEITERART_STANDARD,
|
||||
hasKuendigungsschutz: false,
|
||||
kuendigungsschutzBis: "",
|
||||
|
||||
@@ -220,7 +220,7 @@ function KriterienBlock({
|
||||
label="Ab"
|
||||
dense
|
||||
type="number"
|
||||
step="0.5"
|
||||
step="0.01"
|
||||
value={criteria.stundenVon?.toString() ?? ""}
|
||||
onChange={(v) => onChange({ hoursFrom: v || undefined })}
|
||||
/>
|
||||
@@ -228,7 +228,7 @@ function KriterienBlock({
|
||||
label="Bis"
|
||||
dense
|
||||
type="number"
|
||||
step="0.5"
|
||||
step="0.01"
|
||||
value={criteria.stundenBis?.toString() ?? ""}
|
||||
onChange={(v) => onChange({ hoursTo: v || undefined })}
|
||||
/>
|
||||
|
||||
24
components/shell/TestsystemSchriftzug.tsx
Normal file
24
components/shell/TestsystemSchriftzug.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import { TriangleAlert } from "lucide-react";
|
||||
import { TESTSYSTEM_SCHRIFTZUG } from "@/lib/testsystem";
|
||||
|
||||
// Hängt mittig an der Oberkante, über Kopfleiste und Navigation, und bleibt
|
||||
// beim Blättern stehen; ein roter Rahmen um das ganze Fenster wiederholt das
|
||||
// Signal am Rand, wo der Blick beim Arbeiten liegt. Mittig, weil die
|
||||
// Kopfleiste links den Seitentitel und rechts die Bedienelemente trägt.
|
||||
// Beides ist klickdurchlässig, damit es nie etwas verdeckt, das sich sonst
|
||||
// bedienen liesse. Auf Ausdrucken erscheint es nicht: Checkliste und
|
||||
// Organigramm sind Dokumente, kein Bildschirm.
|
||||
export function TestsystemSchriftzug() {
|
||||
return (
|
||||
<>
|
||||
<div aria-hidden className="pointer-events-none fixed inset-0 z-[70] border-[3px] border-red-600 print:hidden" />
|
||||
<div
|
||||
role="note"
|
||||
className="pointer-events-none fixed left-1/2 top-0 z-[70] flex -translate-x-1/2 items-center gap-1.5 rounded-b-lg bg-red-600 px-5 pb-1.5 pt-[max(0.375rem,env(safe-area-inset-top))] text-sm font-bold uppercase tracking-[0.15em] text-white shadow-md print:hidden"
|
||||
>
|
||||
<TriangleAlert className="h-4 w-4" aria-hidden />
|
||||
{TESTSYSTEM_SCHRIFTZUG}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,710 @@
|
||||
-- Anmeldung mit Passwort neben Entra ID, und eine Benutzerverwaltung.
|
||||
--
|
||||
-- ═══ Warum es diesen zweiten Weg gibt ═══
|
||||
--
|
||||
-- Er ist für Personen gedacht, die kein Konto im Entra-Mandanten haben und
|
||||
-- für die eine Gasteinladung nicht rechtzeitig eingerichtet werden kann. Er
|
||||
-- ist eine Übergangslösung neben Entra ID.
|
||||
--
|
||||
-- ═══ Was dieser Weg kostet ═══
|
||||
--
|
||||
-- Er hebelt aus, was der Mandant durchsetzt: Mehrfaktor, bedingten Zugriff,
|
||||
-- Sperrung beim Austritt. Genau davor warnt der Kommentar in actions/auth.ts,
|
||||
-- und die Warnung bleibt richtig. Ist das Anmeldeformular ohne VPN aus dem
|
||||
-- Internet erreichbar, steht auch dieser Weg offen; und das Initialpasswort
|
||||
-- ist allen Zugängen gemeinsam und damit bekannt.
|
||||
--
|
||||
-- Deshalb trägt dieser Weg in dieser Fassung ein **eingebautes Ende**:
|
||||
-- `gueltig_bis` mit einer Prüfbedingung (chk_passwort_pfad_endet), die keinen
|
||||
-- Wert nach einem festen Tag passieren lässt. Danach nimmt die Anmeldung kein
|
||||
-- Passwort mehr an — ohne Zutun und ohne dass es sich über die Oberfläche
|
||||
-- verlängern liesse. Die feste Frist entfällt mit 20260908140000;
|
||||
-- `gueltig_bis` bleibt dort als Abschaltknopf.
|
||||
--
|
||||
-- ═══ Die vier Schranken ═══
|
||||
--
|
||||
-- 1. Erzwungener Wechsel solange muss_wechseln steht, gibt is_hr_user()
|
||||
-- false zurück — also kein Datenzugriff, nirgends
|
||||
-- 2. Initialfrist 7 Tage; ein nie benutzter Zugang läuft ab
|
||||
-- 3. Sperre 5 Fehlversuche → 15 Minuten zu
|
||||
-- 4. Enddatum gueltig_bis, per Prüfbedingung begrenzt
|
||||
-- (siehe 20260908140000)
|
||||
--
|
||||
-- Schranke 1 ist der Kern: sie sitzt nicht in der Oberfläche, sondern in der
|
||||
-- Funktion, die alle 25 RLS-Policies aufrufen. Weder ein direkter Aufruf einer
|
||||
-- Adresse noch eine Server Action noch ein Route Handler kommt daran vorbei,
|
||||
-- weil keiner von ihnen ohne Policies auskommt.
|
||||
|
||||
-- ══════════════════════════════════════════════════════════════════════
|
||||
-- 1. Die Tabelle
|
||||
-- ══════════════════════════════════════════════════════════════════════
|
||||
--
|
||||
-- Ein Passwort je Konto, Schlüssel ist app_users.id. Getrennt von profiles,
|
||||
-- weil das zwei verschiedene Dinge sind: profiles sagt, was jemand darf,
|
||||
-- app_passwoerter sagt nur, wie er sich ausweist. Ein Entra-Konto hat keine
|
||||
-- Zeile hier, und das ist die ganze Unterscheidung.
|
||||
create table if not exists app_passwoerter (
|
||||
user_id uuid primary key references app_users(id) on delete cascade,
|
||||
|
||||
-- bcrypt aus pgcrypto. Der Hash verlässt die Datenbank nie: geprüft wird in
|
||||
-- app_passwort_pruefen(), und an die Tabelle kommt die Anwendungsrolle nicht
|
||||
-- heran (siehe Policy unten).
|
||||
--
|
||||
-- bcrypt schneidet bei 72 Byte ab. Das steht hier, damit es niemand als
|
||||
-- Fehler sucht.
|
||||
hash text not null,
|
||||
|
||||
-- Solange das steht, ist der Zugang wertlos: is_hr_user() liefert false.
|
||||
muss_wechseln boolean not null default true,
|
||||
|
||||
-- Ende der Frist für das Initialpasswort. Wird beim Anlegen und bei jedem
|
||||
-- Zurücksetzen neu gestellt.
|
||||
initialpasswort_bis timestamptz not null default now() + interval '7 days',
|
||||
|
||||
-- Das Ende des Passwortpfads insgesamt. Fester Tag, nicht „einen Monat ab
|
||||
-- Anlage": ein rollendes Fenster liefe mit jedem neuen Zugang weiter, und
|
||||
-- genau das soll es nicht.
|
||||
gueltig_bis date not null default date '2026-10-08',
|
||||
|
||||
letzte_anmeldung_am timestamptz,
|
||||
fehlversuche integer not null default 0,
|
||||
gesperrt_bis timestamptz,
|
||||
created_at timestamptz not null default now(),
|
||||
updated_at timestamptz not null default now(),
|
||||
|
||||
-- Die Prüfbedingung ist der eigentliche Schutz, nicht der Vorgabewert. Ein
|
||||
-- Vorgabewert lässt sich mit einem Feld im Formular übergehen; hier weist die
|
||||
-- Datenbank jeden späteren Tag ab. Verlängern heisst: diese Bedingung in
|
||||
-- einer neuen Migration ändern, bewusst und nachvollziehbar.
|
||||
constraint chk_passwort_pfad_endet check (gueltig_bis <= date '2026-10-08'),
|
||||
constraint chk_fehlversuche check (fehlversuche >= 0)
|
||||
);
|
||||
|
||||
comment on table app_passwoerter is
|
||||
'Anmeldung mit Passwort neben Entra ID — Übergangslösung. Das Ende steht in gueltig_bis (chk_passwort_pfad_endet).';
|
||||
|
||||
alter table app_passwoerter enable row level security;
|
||||
|
||||
-- ── Die Policy, die nichts erlaubt ────────────────────────────────────
|
||||
--
|
||||
-- Das ist Absicht und kein Versehen. Diese Tabelle wird von der Anwendung
|
||||
-- **nie** direkt gelesen oder geschrieben, auch nicht von HR: jeder Zugriff
|
||||
-- läuft über die SECURITY-DEFINER-Funktionen weiter unten, die als
|
||||
-- Eigentümerin laufen und an der Policy vorbeikommen. Damit kann kein
|
||||
-- Anwendungscode — heute nicht und nach keiner künftigen Änderung — einen Hash
|
||||
-- auslesen.
|
||||
--
|
||||
-- Warum überhaupt eine Policy, wenn sie nichts zulässt: eine Tabelle mit RLS
|
||||
-- und *ohne* jede Policy ist von aussen nicht von einer vergessenen zu
|
||||
-- unterscheiden. Diese Zeile sagt ausdrücklich: hier kommt niemand direkt
|
||||
-- heran, und das ist gewollt.
|
||||
drop policy if exists app_passwoerter_kein_direktzugriff on app_passwoerter;
|
||||
create policy app_passwoerter_kein_direktzugriff on app_passwoerter
|
||||
for all using (false) with check (false);
|
||||
|
||||
drop trigger if exists trg_app_passwoerter_touch on app_passwoerter;
|
||||
create trigger trg_app_passwoerter_touch
|
||||
before update on app_passwoerter
|
||||
for each row execute function fn_touch_updated_at();
|
||||
|
||||
-- ══════════════════════════════════════════════════════════════════════
|
||||
-- 2. Regeln für ein Passwort
|
||||
-- ══════════════════════════════════════════════════════════════════════
|
||||
--
|
||||
-- Liefert die Beanstandung im Klartext oder null, wenn nichts zu beanstanden
|
||||
-- ist. Als Rückgabe statt als Ausnahme, damit der Aufrufer entscheidet, wie er
|
||||
-- sie zeigt. Die Oberfläche spiegelt dieselben Regeln in lib/passwort.ts, damit
|
||||
-- sie schon beim Tippen sichtbar sind — verbindlich ist diese Funktion hier.
|
||||
create or replace function app_passwort_regeln(p_passwort text)
|
||||
returns text
|
||||
language sql
|
||||
immutable
|
||||
set search_path = public, pg_temp
|
||||
as $$
|
||||
select case
|
||||
when p_passwort is null or length(p_passwort) < 12
|
||||
then 'Das Passwort muss mindestens 12 Zeichen lang sein.'
|
||||
when length(p_passwort) > 72
|
||||
then 'Das Passwort darf höchstens 72 Zeichen lang sein.'
|
||||
when p_passwort !~ '[[:upper:]]'
|
||||
then 'Das Passwort muss mindestens einen Grossbuchstaben enthalten.'
|
||||
when p_passwort !~ '[[:lower:]]'
|
||||
then 'Das Passwort muss mindestens einen Kleinbuchstaben enthalten.'
|
||||
when p_passwort !~ '[[:digit:]]'
|
||||
then 'Das Passwort muss mindestens eine Ziffer enthalten.'
|
||||
else null
|
||||
end;
|
||||
$$;
|
||||
|
||||
-- ══════════════════════════════════════════════════════════════════════
|
||||
-- 3. Die Prüfung beim Anmelden
|
||||
-- ══════════════════════════════════════════════════════════════════════
|
||||
--
|
||||
-- Die einzige Stelle, an der ein Passwort geprüft wird. Ohne Sitzungskontext —
|
||||
-- den gibt es an dieser Stelle ja noch nicht, er entsteht erst aus dem
|
||||
-- Ergebnis. Deshalb SECURITY DEFINER und deshalb **keine** Prüfung auf HR:
|
||||
-- wer sich anmelden darf, ist eine andere Frage als wer etwas sehen darf. Die
|
||||
-- zweite beantwortet is_hr_user(), und zwar bei jeder Abfrage neu.
|
||||
--
|
||||
-- Rückgabe ist app_users.id oder null. Nie ein Grund: die Anmeldemaske soll
|
||||
-- nicht verraten, ob eine Adresse überhaupt bekannt ist.
|
||||
create or replace function app_passwort_pruefen(p_email text, p_passwort text)
|
||||
returns uuid
|
||||
language plpgsql
|
||||
volatile
|
||||
security definer
|
||||
set search_path = public, pg_temp
|
||||
as $$
|
||||
declare
|
||||
v_email text := lower(btrim(coalesce(p_email, '')));
|
||||
k app_passwoerter%rowtype;
|
||||
v_user app_users%rowtype;
|
||||
begin
|
||||
if v_email = '' or coalesce(p_passwort, '') = '' then
|
||||
return null;
|
||||
end if;
|
||||
|
||||
select u.* into v_user from app_users u where lower(u.email) = v_email limit 1;
|
||||
|
||||
if found then
|
||||
select * into k from app_passwoerter where user_id = v_user.id for update;
|
||||
end if;
|
||||
|
||||
-- Unbekannte Adresse oder Konto ohne Passwort: trotzdem einmal rechnen.
|
||||
-- Ohne das antwortet die Anmeldung für unbekannte Adressen spürbar schneller
|
||||
-- als für bekannte, und damit liesse sich die Belegschaft durchprobieren.
|
||||
-- Derselbe Aufwand wie ein echter Vergleich, dasselbe Ergebnis wie ein
|
||||
-- falsches Passwort.
|
||||
if k.user_id is null then
|
||||
perform crypt(p_passwort, gen_salt('bf', 12));
|
||||
return null;
|
||||
end if;
|
||||
|
||||
-- Gesperrt: der Zähler wird **nicht** erhöht. Sonst verlängert jeder weitere
|
||||
-- Versuch die Sperre, und wer jemanden aussperren will, hält sie beliebig
|
||||
-- offen.
|
||||
if k.gesperrt_bis is not null and k.gesperrt_bis > now() then
|
||||
return null;
|
||||
end if;
|
||||
|
||||
-- Das Ende des Passwortpfads. Läuft ohne Zutun ab; siehe Kopf der Datei.
|
||||
if current_date > k.gueltig_bis then
|
||||
return null;
|
||||
end if;
|
||||
|
||||
-- Ein nie benutzter Zugang mit dem gemeinsamen Initialpasswort läuft nach
|
||||
-- sieben Tagen ab. Zurücksetzen stellt die Frist neu.
|
||||
if k.muss_wechseln and now() > k.initialpasswort_bis then
|
||||
return null;
|
||||
end if;
|
||||
|
||||
if k.hash <> crypt(p_passwort, k.hash) then
|
||||
update app_passwoerter
|
||||
set fehlversuche = case when fehlversuche + 1 >= 5 then 0 else fehlversuche + 1 end,
|
||||
gesperrt_bis = case when fehlversuche + 1 >= 5 then now() + interval '15 minutes' else gesperrt_bis end
|
||||
where user_id = k.user_id;
|
||||
|
||||
-- Protokolliert wird nur für bekannte Konten. Für unbekannte Adressen
|
||||
-- entstünde sonst ein Schreibpfad, den jeder Fremde beliebig oft auslösen
|
||||
-- kann — eine Protokolltabelle, die von aussen vollgeschrieben wird.
|
||||
insert into audit_log (actor_user_id, actor_name, action, target_label, details)
|
||||
values (v_user.id, coalesce(v_user.full_name, v_user.email), 'Anmeldung fehlgeschlagen',
|
||||
v_user.email,
|
||||
case when k.fehlversuche + 1 >= 5
|
||||
then 'Falsches Passwort, Konto für 15 Minuten gesperrt'
|
||||
else 'Falsches Passwort (' || (k.fehlversuche + 1) || '. Versuch)' end);
|
||||
return null;
|
||||
end if;
|
||||
|
||||
update app_passwoerter
|
||||
set fehlversuche = 0,
|
||||
gesperrt_bis = null,
|
||||
letzte_anmeldung_am = now()
|
||||
where user_id = k.user_id;
|
||||
|
||||
update app_users set last_seen_at = now() where id = k.user_id;
|
||||
|
||||
insert into audit_log (actor_user_id, actor_name, action, target_label, details)
|
||||
values (v_user.id, coalesce(v_user.full_name, v_user.email), 'Anmeldung', v_user.email,
|
||||
case when k.muss_wechseln then 'Passwort, Wechsel steht aus' else 'Passwort' end);
|
||||
|
||||
return k.user_id;
|
||||
end;
|
||||
$$;
|
||||
|
||||
comment on function app_passwort_pruefen(text, text) is
|
||||
'Prüft E-Mail und Passwort und liefert app_users.id oder null. Nennt nie einen Grund — die Anmeldemaske soll keine Adressen bestätigen.';
|
||||
|
||||
-- ══════════════════════════════════════════════════════════════════════
|
||||
-- 4. Steht ein Wechsel aus?
|
||||
-- ══════════════════════════════════════════════════════════════════════
|
||||
--
|
||||
-- Für die Oberfläche: lib/shell-data.ts fragt danach, um auf
|
||||
-- /passwort-aendern umzuleiten statt eine leere Anwendung zu zeigen. Die
|
||||
-- Absicherung hängt nicht daran — die steckt in is_hr_user().
|
||||
create or replace function app_muss_passwort_wechseln()
|
||||
returns boolean
|
||||
language sql
|
||||
stable
|
||||
security definer
|
||||
set search_path = public, pg_temp
|
||||
as $$
|
||||
select exists (
|
||||
select 1 from app_passwoerter k
|
||||
where k.user_id = app_current_user_id() and k.muss_wechseln
|
||||
);
|
||||
$$;
|
||||
|
||||
-- ══════════════════════════════════════════════════════════════════════
|
||||
-- 5. Die Schranke: is_hr_user() kennt jetzt den Passwortzwang
|
||||
-- ══════════════════════════════════════════════════════════════════════
|
||||
--
|
||||
-- `create or replace` behält die Funktion samt ihrer Kennung und ihren
|
||||
-- Rechten; die 25 Policies, die sie aufrufen, merken davon nichts und gelten
|
||||
-- unverändert weiter.
|
||||
--
|
||||
-- Warum der Zwang **hier** steht und nicht nur im Layout: ein Layout schützt
|
||||
-- Seiten. Es schützt keine Server Action, keinen Route Handler und keine
|
||||
-- Abfrage, die morgen jemand schreibt. Diese Funktion schützt alles davon auf
|
||||
-- einmal, weil ohne sie keine Zeile aus keiner Tabelle kommt.
|
||||
--
|
||||
-- Die Kehrseite, damit sie nicht als Fehler gemeldet wird: eine Person mit
|
||||
-- offenem Passwortwechsel sieht die Anwendung vollständig leer — auch die
|
||||
-- Benutzerverwaltung. Der Weg dort heraus führt ausschliesslich über
|
||||
-- app_passwort_aendern(), und die kommt ohne is_hr_user() aus.
|
||||
create or replace function is_hr_user()
|
||||
returns boolean
|
||||
language sql
|
||||
security definer
|
||||
set search_path = public, pg_temp
|
||||
stable
|
||||
as $$
|
||||
select exists (
|
||||
select 1 from profiles p
|
||||
where p.id = app_current_user_id()
|
||||
and p.role = 'hr'
|
||||
and p.is_active = true
|
||||
and not exists (
|
||||
select 1 from app_passwoerter k
|
||||
where k.user_id = p.id and k.muss_wechseln
|
||||
)
|
||||
);
|
||||
$$;
|
||||
|
||||
comment on function is_hr_user() is
|
||||
'Aktive HR-Person ohne offenen Passwortwechsel. Aufgerufen von allen RLS-Policies — die eigentliche Zugriffsschranke.';
|
||||
|
||||
-- ══════════════════════════════════════════════════════════════════════
|
||||
-- 6. Sein eigenes Passwort wechseln
|
||||
-- ══════════════════════════════════════════════════════════════════════
|
||||
--
|
||||
-- Braucht eine Sitzung, aber **nicht** is_hr_user() — sonst käme niemand je
|
||||
-- aus dem erzwungenen Wechsel heraus. Das ist die einzige Ausnahme, und sie
|
||||
-- ist eng: die Funktion fasst genau eine Zeile an, die der aufrufenden Person.
|
||||
create or replace function app_passwort_aendern(payload jsonb)
|
||||
returns void
|
||||
language plpgsql
|
||||
security definer
|
||||
set search_path = public, pg_temp
|
||||
as $$
|
||||
declare
|
||||
v_id uuid := app_current_user_id();
|
||||
v_alt text := payload->>'altes_passwort';
|
||||
v_neu text := payload->>'neues_passwort';
|
||||
v_fehler text;
|
||||
k app_passwoerter%rowtype;
|
||||
v_name text;
|
||||
begin
|
||||
if v_id is null then
|
||||
raise exception 'Nicht angemeldet.';
|
||||
end if;
|
||||
|
||||
select * into k from app_passwoerter where user_id = v_id for update;
|
||||
if not found then
|
||||
raise exception 'Für dieses Konto gibt es keine Anmeldung mit Passwort.';
|
||||
end if;
|
||||
|
||||
if k.gesperrt_bis is not null and k.gesperrt_bis > now() then
|
||||
raise exception 'Das Konto ist vorübergehend gesperrt. Bitte später erneut versuchen.';
|
||||
end if;
|
||||
|
||||
-- Auch hier zählt der Fehlversuch. Ohne das wäre dieses Formular eine
|
||||
-- Stelle, an der sich das alte Passwort unbegrenzt durchprobieren lässt —
|
||||
-- die Anmeldemaske daneben ist begrenzt.
|
||||
if k.hash <> crypt(coalesce(v_alt, ''), k.hash) then
|
||||
update app_passwoerter
|
||||
set fehlversuche = case when fehlversuche + 1 >= 5 then 0 else fehlversuche + 1 end,
|
||||
gesperrt_bis = case when fehlversuche + 1 >= 5 then now() + interval '15 minutes' else gesperrt_bis end
|
||||
where user_id = v_id;
|
||||
raise exception 'Das bisherige Passwort stimmt nicht.';
|
||||
end if;
|
||||
|
||||
v_fehler := app_passwort_regeln(v_neu);
|
||||
if v_fehler is not null then
|
||||
raise exception '%', v_fehler;
|
||||
end if;
|
||||
|
||||
-- Das gemeinsame Initialpasswort noch einmal zu setzen wäre ein Wechsel, der
|
||||
-- nichts wechselt.
|
||||
if k.hash = crypt(v_neu, k.hash) then
|
||||
raise exception 'Das neue Passwort muss sich vom bisherigen unterscheiden.';
|
||||
end if;
|
||||
|
||||
update app_passwoerter
|
||||
set hash = crypt(v_neu, gen_salt('bf', 12)),
|
||||
muss_wechseln = false,
|
||||
fehlversuche = 0,
|
||||
gesperrt_bis = null
|
||||
where user_id = v_id;
|
||||
|
||||
select coalesce(u.full_name, u.email) into v_name from app_users u where u.id = v_id;
|
||||
|
||||
insert into audit_log (actor_user_id, actor_name, action, target_label, details)
|
||||
values (v_id, coalesce(v_name, 'Unbekannt'), 'Passwort geändert', coalesce(v_name, 'Unbekannt'),
|
||||
'Von der Person selbst');
|
||||
end;
|
||||
$$;
|
||||
|
||||
-- ══════════════════════════════════════════════════════════════════════
|
||||
-- 7. Benutzerverwaltung
|
||||
-- ══════════════════════════════════════════════════════════════════════
|
||||
|
||||
-- ── Anlegen ───────────────────────────────────────────────────────────
|
||||
--
|
||||
-- Legt bei Bedarf das Konto an, hängt ein Passwort daran und schaltet
|
||||
-- wahlweise gleich frei. Gibt es zu der Adresse schon ein Konto — etwa weil
|
||||
-- die Person sich bereits über Entra angemeldet hat —, bekommt genau dieses
|
||||
-- das Passwort. Ein zweites Konto zur selben Adresse wäre eine zweite
|
||||
-- Identität mit eigener Historie und eigenen Notizen.
|
||||
create or replace function app_benutzer_anlegen(payload jsonb)
|
||||
returns jsonb
|
||||
language plpgsql
|
||||
security definer
|
||||
set search_path = public, pg_temp
|
||||
as $$
|
||||
declare
|
||||
v_email text := lower(btrim(coalesce(payload->>'email', '')));
|
||||
v_name text := nullif(btrim(coalesce(payload->>'full_name', '')), '');
|
||||
v_passwort text := payload->>'passwort';
|
||||
v_hr boolean := coalesce((payload->>'hr_zugang')::boolean, false);
|
||||
v_fehler text;
|
||||
v_id uuid;
|
||||
v_neu boolean := false;
|
||||
begin
|
||||
perform require_hr_admin();
|
||||
|
||||
if v_email = '' or position('@' in v_email) = 0 then
|
||||
raise exception 'Es wurde keine gültige E-Mail-Adresse angegeben.';
|
||||
end if;
|
||||
|
||||
v_fehler := app_passwort_regeln(v_passwort);
|
||||
if v_fehler is not null then
|
||||
raise exception '%', v_fehler;
|
||||
end if;
|
||||
|
||||
select u.id into v_id from app_users u where lower(u.email) = v_email limit 1;
|
||||
|
||||
if v_id is null then
|
||||
v_id := gen_random_uuid();
|
||||
v_neu := true;
|
||||
-- Kein oid von Entra, also eine Kennung, die als solche erkennbar ist.
|
||||
-- Vorbild: 'legacy:' aus 20260805140000.
|
||||
insert into app_users (id, external_id, email, full_name)
|
||||
values (v_id, 'passwort:' || v_id::text, v_email, v_name);
|
||||
elsif v_name is not null then
|
||||
update app_users set full_name = v_name where id = v_id and full_name is null;
|
||||
end if;
|
||||
|
||||
if exists (select 1 from app_passwoerter where user_id = v_id) then
|
||||
raise exception 'Für % besteht bereits eine Anmeldung mit Passwort. Stattdessen das Passwort zurücksetzen.', v_email;
|
||||
end if;
|
||||
|
||||
insert into app_passwoerter (user_id, hash, muss_wechseln, initialpasswort_bis)
|
||||
values (v_id, crypt(v_passwort, gen_salt('bf', 12)), true, now() + interval '7 days');
|
||||
|
||||
if v_hr then
|
||||
insert into profiles (id, email, full_name, role, is_active, created_by)
|
||||
values (v_id, v_email, v_name, 'hr', true, app_current_user_id())
|
||||
on conflict (id) do update set is_active = true, role = 'hr';
|
||||
end if;
|
||||
|
||||
insert into audit_log (actor_user_id, actor_name, action, target_label, details)
|
||||
values (app_current_user_id(), current_actor_name(), 'Benutzer:in angelegt', v_email,
|
||||
case when v_neu then 'Neues Konto' else 'Passwort zu bestehendem Konto' end ||
|
||||
case when v_hr then ', mit HR-Zugang' else ', ohne HR-Zugang' end ||
|
||||
', Initialpasswort gültig bis ' || to_char(now() + interval '7 days', 'DD.MM.YYYY'));
|
||||
|
||||
return jsonb_build_object('user_id', v_id, 'neu', v_neu);
|
||||
end;
|
||||
$$;
|
||||
|
||||
-- ── Passwort zurücksetzen ─────────────────────────────────────────────
|
||||
--
|
||||
-- Zurück auf das Initialpasswort, Wechselzwang wieder an, Frist wieder sieben
|
||||
-- Tage, Sperre weg. Das ist der Weg für „ich komme nicht mehr hinein" und
|
||||
-- ersetzt jeden Selbstbedienungspfad per E-Mail — den gibt es hier bewusst
|
||||
-- nicht.
|
||||
create or replace function app_passwort_zuruecksetzen(payload jsonb)
|
||||
returns void
|
||||
language plpgsql
|
||||
security definer
|
||||
set search_path = public, pg_temp
|
||||
as $$
|
||||
declare
|
||||
v_id uuid := (payload->>'user_id')::uuid;
|
||||
v_passwort text := payload->>'passwort';
|
||||
v_fehler text;
|
||||
v_email text;
|
||||
begin
|
||||
perform require_hr_admin();
|
||||
|
||||
v_fehler := app_passwort_regeln(v_passwort);
|
||||
if v_fehler is not null then
|
||||
raise exception '%', v_fehler;
|
||||
end if;
|
||||
|
||||
select u.email into v_email from app_users u where u.id = v_id;
|
||||
if v_email is null then
|
||||
raise exception 'Das Konto existiert nicht.';
|
||||
end if;
|
||||
|
||||
update app_passwoerter
|
||||
set hash = crypt(v_passwort, gen_salt('bf', 12)),
|
||||
muss_wechseln = true,
|
||||
initialpasswort_bis = now() + interval '7 days',
|
||||
fehlversuche = 0,
|
||||
gesperrt_bis = null
|
||||
where user_id = v_id;
|
||||
|
||||
if not found then
|
||||
raise exception 'Für dieses Konto gibt es keine Anmeldung mit Passwort.';
|
||||
end if;
|
||||
|
||||
insert into audit_log (actor_user_id, actor_name, action, target_label, details)
|
||||
values (app_current_user_id(), current_actor_name(), 'Passwort zurückgesetzt', v_email,
|
||||
'Initialpasswort gültig bis ' || to_char(now() + interval '7 days', 'DD.MM.YYYY'));
|
||||
end;
|
||||
$$;
|
||||
|
||||
-- ── Freischalten und sperren ──────────────────────────────────────────
|
||||
--
|
||||
-- Auch der Weg für ein Entra-Konto ohne profiles-Zeile: ohne ihn bliebe dafür
|
||||
-- nur ein `insert` von Hand über psql, und die Vergabe von Zugriff hinge an
|
||||
-- einer einzelnen Person mit Datenbankzugang.
|
||||
--
|
||||
-- Zwei Riegel, beide gegen dasselbe: dass sich die Anwendung von innen
|
||||
-- zusperrt. Ohne sie liesse sich der letzte Zugang entziehen, und
|
||||
-- wiederherstellen könnte ihn nur noch, wer an die Datenbank kommt — also
|
||||
-- genau der Zustand, den diese Funktion beseitigen soll.
|
||||
create or replace function app_zugang_setzen(payload jsonb)
|
||||
returns void
|
||||
language plpgsql
|
||||
security definer
|
||||
set search_path = public, pg_temp
|
||||
as $$
|
||||
declare
|
||||
v_id uuid := (payload->>'user_id')::uuid;
|
||||
v_aktiv boolean := coalesce((payload->>'aktiv')::boolean, false);
|
||||
v_user app_users%rowtype;
|
||||
v_uebrig integer;
|
||||
begin
|
||||
perform require_hr_admin();
|
||||
|
||||
select * into v_user from app_users where id = v_id;
|
||||
if not found then
|
||||
raise exception 'Das Konto existiert nicht.';
|
||||
end if;
|
||||
|
||||
if v_aktiv then
|
||||
insert into profiles (id, email, full_name, role, is_active, created_by)
|
||||
values (v_id, v_user.email, v_user.full_name, 'hr', true, app_current_user_id())
|
||||
on conflict (id) do update set is_active = true, role = 'hr';
|
||||
else
|
||||
if v_id = app_current_user_id() then
|
||||
raise exception 'Sie können sich nicht selbst deaktivieren.';
|
||||
end if;
|
||||
|
||||
select count(*) into v_uebrig
|
||||
from profiles p
|
||||
where p.role = 'hr' and p.is_active = true and p.id <> v_id;
|
||||
|
||||
if v_uebrig = 0 then
|
||||
raise exception 'Das ist der letzte aktive HR-Zugang. Erst eine andere Person freischalten, dann diesen entziehen.';
|
||||
end if;
|
||||
|
||||
update profiles set is_active = false where id = v_id;
|
||||
end if;
|
||||
|
||||
insert into audit_log (actor_user_id, actor_name, action, target_label, details)
|
||||
values (app_current_user_id(), current_actor_name(),
|
||||
case when v_aktiv then 'HR-Zugang erteilt' else 'HR-Zugang entzogen' end,
|
||||
v_user.email, null);
|
||||
end;
|
||||
$$;
|
||||
|
||||
-- ── Die Liste ─────────────────────────────────────────────────────────
|
||||
--
|
||||
-- Als Funktion und nicht als Abfrage, weil app_passwoerter für die
|
||||
-- Anwendungsrolle unerreichbar ist. Zurück kommt, was die Verwaltungsseite
|
||||
-- zeigt — und kein Hash.
|
||||
create or replace function app_benutzer_liste()
|
||||
returns table (
|
||||
user_id uuid,
|
||||
email text,
|
||||
full_name text,
|
||||
ist_entra boolean,
|
||||
hat_passwort boolean,
|
||||
is_active boolean,
|
||||
letzte_anmeldung timestamptz,
|
||||
muss_wechseln boolean,
|
||||
gesperrt_bis timestamptz,
|
||||
initialpasswort_bis timestamptz,
|
||||
gueltig_bis date
|
||||
)
|
||||
language plpgsql
|
||||
security definer
|
||||
set search_path = public, pg_temp
|
||||
as $$
|
||||
-- Die Ausgabespalten oben sind zugleich plpgsql-Variablen und heissen wie
|
||||
-- Spalten der abgefragten Tabellen. Ohne diese Zeile entschiede die
|
||||
-- Namensauflösung zugunsten der Variablen, sobald irgendwann ein Verweis ohne
|
||||
-- Tabellenpräfix dazukommt — und lieferte still null statt des Werts.
|
||||
#variable_conflict use_column
|
||||
begin
|
||||
-- Nicht `stable`: require_hr_admin() ist volatile, und eine stabile Funktion
|
||||
-- soll keine volatile aufrufen. Gelesen wird die Liste einmal je Seitenaufbau,
|
||||
-- zu optimieren gibt es hier nichts.
|
||||
perform require_hr_admin();
|
||||
|
||||
return query
|
||||
select u.id,
|
||||
u.email,
|
||||
u.full_name,
|
||||
u.external_id not like 'passwort:%' as ist_entra,
|
||||
k.user_id is not null as hat_passwort,
|
||||
coalesce(p.is_active, false) as is_active,
|
||||
greatest(u.last_seen_at, k.letzte_anmeldung_am) as letzte_anmeldung,
|
||||
coalesce(k.muss_wechseln, false) as muss_wechseln,
|
||||
k.gesperrt_bis,
|
||||
k.initialpasswort_bis,
|
||||
k.gueltig_bis
|
||||
from app_users u
|
||||
left join profiles p on p.id = u.id
|
||||
left join app_passwoerter k on k.user_id = u.id
|
||||
order by u.email;
|
||||
end;
|
||||
$$;
|
||||
|
||||
-- ══════════════════════════════════════════════════════════════════════
|
||||
-- 8. Rechte
|
||||
-- ══════════════════════════════════════════════════════════════════════
|
||||
--
|
||||
-- Ausdrücklich nur für die Anwendungsrolle. Der Bestand macht das anders
|
||||
-- (`revoke all from public; grant execute to public`) — das ist wirkungslos,
|
||||
-- weil es die Ausführung am Ende wieder allen gibt. Für neue Funktionen wird
|
||||
-- das nicht fortgeführt; die alten bleiben unangetastet, das gehört in eine
|
||||
-- eigene Migration.
|
||||
--
|
||||
-- app_passwort_pruefen() ist von aussen auslösbar: die Anmeldemaske steht
|
||||
-- offen. Begrenzt wird das durch die Sperre nach fünf Versuchen und dadurch,
|
||||
-- dass für unbekannte Adressen nichts geschrieben wird.
|
||||
revoke execute on function app_passwort_regeln(text) from public;
|
||||
revoke execute on function app_passwort_pruefen(text, text) from public;
|
||||
revoke execute on function app_muss_passwort_wechseln() from public;
|
||||
revoke execute on function app_passwort_aendern(jsonb) from public;
|
||||
revoke execute on function app_benutzer_anlegen(jsonb) from public;
|
||||
revoke execute on function app_passwort_zuruecksetzen(jsonb) from public;
|
||||
revoke execute on function app_zugang_setzen(jsonb) from public;
|
||||
revoke execute on function app_benutzer_liste() from public;
|
||||
|
||||
grant execute on function app_passwort_regeln(text) to alpenwerk_app;
|
||||
grant execute on function app_passwort_pruefen(text, text) to alpenwerk_app;
|
||||
grant execute on function app_muss_passwort_wechseln() to alpenwerk_app;
|
||||
grant execute on function app_passwort_aendern(jsonb) to alpenwerk_app;
|
||||
grant execute on function app_benutzer_anlegen(jsonb) to alpenwerk_app;
|
||||
grant execute on function app_passwort_zuruecksetzen(jsonb) to alpenwerk_app;
|
||||
grant execute on function app_zugang_setzen(jsonb) to alpenwerk_app;
|
||||
grant execute on function app_benutzer_liste() to alpenwerk_app;
|
||||
|
||||
-- ══════════════════════════════════════════════════════════════════════
|
||||
-- 9. Gegenprobe
|
||||
-- ══════════════════════════════════════════════════════════════════════
|
||||
--
|
||||
-- Geprüft wird die eine Aussage, auf der alles andere ruht: solange ein
|
||||
-- Passwortwechsel aussteht, gibt is_hr_user() false zurück. Wäre das nicht so,
|
||||
-- wäre der Zwang eine Beschriftung in der Oberfläche und sonst nichts.
|
||||
--
|
||||
-- Die Probezeilen werden am Ende wieder entfernt; die Migration hinterlässt
|
||||
-- keine Daten. Geschrieben wird dabei absichtlich direkt in die Tabellen und
|
||||
-- nicht über die Funktionen von oben — sonst blieben Protokollzeilen zu einer
|
||||
-- Person stehen, die es nie gab.
|
||||
do $$
|
||||
declare
|
||||
v_id uuid := gen_random_uuid();
|
||||
begin
|
||||
-- 1. Ohne Sitzungskontext: nie wahr. Das ist die Zusicherung aus
|
||||
-- 20260730120000 und muss die Änderung überleben.
|
||||
perform set_config('app.user_id', '', true);
|
||||
if is_hr_user() then
|
||||
raise exception 'is_hr_user() liefert ohne Sitzungskontext true — Abbruch.';
|
||||
end if;
|
||||
|
||||
insert into app_users (id, external_id, email, full_name)
|
||||
values (v_id, 'probe:' || v_id::text, 'probe@example.invalid', 'Probe');
|
||||
insert into profiles (id, email, full_name, role, is_active)
|
||||
values (v_id, 'probe@example.invalid', 'Probe', 'hr', true);
|
||||
|
||||
perform set_config('app.user_id', v_id::text, true);
|
||||
|
||||
-- 2. Freigeschaltet, kein Passwort im Spiel: wahr. Ohne diesen Schritt
|
||||
-- beweisen die folgenden nichts — eine Funktion, die immer false sagt,
|
||||
-- bestünde Punkt 3 ebenfalls.
|
||||
if not is_hr_user() then
|
||||
raise exception 'is_hr_user() liefert für eine freigeschaltete Person ohne Passwort false — Abbruch.';
|
||||
end if;
|
||||
|
||||
-- 3. Derselbe Mensch, jetzt mit offenem Wechsel: falsch.
|
||||
insert into app_passwoerter (user_id, hash, muss_wechseln)
|
||||
values (v_id, crypt('Nur-fuer-die-Probe1', gen_salt('bf', 4)), true);
|
||||
|
||||
if is_hr_user() then
|
||||
raise exception 'is_hr_user() liefert bei offenem Passwortwechsel true — der Zwang wäre umgehbar. Abbruch.';
|
||||
end if;
|
||||
|
||||
if not app_muss_passwort_wechseln() then
|
||||
raise exception 'app_muss_passwort_wechseln() erkennt den offenen Wechsel nicht — Abbruch.';
|
||||
end if;
|
||||
|
||||
-- 4. Nach dem Wechsel wieder wahr — sonst käme niemand je wieder hinein.
|
||||
update app_passwoerter set muss_wechseln = false where user_id = v_id;
|
||||
if not is_hr_user() then
|
||||
raise exception 'is_hr_user() bleibt nach dem Passwortwechsel false — Abbruch.';
|
||||
end if;
|
||||
|
||||
-- 5. Das Enddatum lässt sich nicht hinausschieben.
|
||||
begin
|
||||
update app_passwoerter set gueltig_bis = date '2027-01-01' where user_id = v_id;
|
||||
raise exception 'gueltig_bis liess sich über den 08.10.2026 hinaus setzen — chk_passwort_pfad_endet greift nicht. Abbruch.';
|
||||
exception
|
||||
when check_violation then null;
|
||||
end;
|
||||
|
||||
delete from app_passwoerter where user_id = v_id;
|
||||
delete from profiles where id = v_id;
|
||||
delete from app_users where id = v_id;
|
||||
perform set_config('app.user_id', '', true);
|
||||
end;
|
||||
$$;
|
||||
|
||||
-- Und der Zustand der neuen Tabelle selbst: Row Level Security an und eine
|
||||
-- Policy vorhanden.
|
||||
do $$
|
||||
begin
|
||||
if not (select relrowsecurity from pg_class where oid = 'app_passwoerter'::regclass) then
|
||||
raise exception 'app_passwoerter steht ohne Row Level Security. Abbruch.';
|
||||
end if;
|
||||
if not exists (select 1 from pg_policy where polrelid = 'app_passwoerter'::regclass) then
|
||||
raise exception 'app_passwoerter hat keine Policy. Abbruch.';
|
||||
end if;
|
||||
end;
|
||||
$$;
|
||||
@@ -0,0 +1,157 @@
|
||||
-- Das feste Enddatum des Passwortpfads fällt weg.
|
||||
--
|
||||
-- ═══ Was hier entfällt ═══
|
||||
--
|
||||
-- 20260908120000 versieht den Passwortpfad mit einem eingebauten Ende:
|
||||
-- `gueltig_bis` mit einem festen Vorgabewert und einer Prüfbedingung, die
|
||||
-- keinen späteren Wert zulässt. Diese Migration entfernt beides.
|
||||
--
|
||||
-- Ein fester Stichtag im Schema schaltet Zugänge ab, ohne dass es jemand
|
||||
-- bewusst entscheidet. Ein abgelaufener Zugang sieht für die Person vor dem
|
||||
-- Bildschirm aus wie ein Fehler in der Anwendung, nicht wie eine
|
||||
-- Schutzmassnahme.
|
||||
--
|
||||
-- ═══ Was bleibt ═══
|
||||
--
|
||||
-- Die **Spalte** bleibt, und die Prüfung in app_passwort_pruefen() bleibt Wort
|
||||
-- für Wort stehen. Nur steht in der Spalte künftig nichts:
|
||||
--
|
||||
-- if current_date > k.gueltig_bis then return null; end if;
|
||||
--
|
||||
-- Bei `gueltig_bis is null` ergibt der Vergleich „unbekannt", und ein `if` auf
|
||||
-- unbekannt verzweigt nicht — die Zeile ist also wirkungslos, ohne dass etwas
|
||||
-- daran geändert werden müsste. Sobald ein Ende gebraucht wird, genügt ein
|
||||
-- update; eine Migration braucht es dafür nicht mehr:
|
||||
--
|
||||
-- update app_passwoerter set gueltig_bis = current_date; -- ab morgen zu
|
||||
-- update app_passwoerter set gueltig_bis = null; -- wieder offen
|
||||
--
|
||||
-- Der Abschaltknopf bleibt damit erhalten, er löst nur nicht von selbst aus.
|
||||
-- Wann der Passwortpfad endet, ist eine betriebliche Entscheidung und keine
|
||||
-- Zusicherung des Schemas.
|
||||
--
|
||||
-- Die vier übrigen Schranken sind unberührt: Zwang zum Wechsel beim ersten
|
||||
-- Mal, sieben Tage Frist für einen nie benutzten Zugang, Sperre nach fünf
|
||||
-- Fehlversuchen, und die Freischaltung je Person.
|
||||
|
||||
-- ── 1. Die Prüfbedingung weg ──────────────────────────────────────────
|
||||
alter table app_passwoerter drop constraint if exists chk_passwort_pfad_endet;
|
||||
|
||||
-- ── 2. Die Spalte leer und leerbar ────────────────────────────────────
|
||||
--
|
||||
-- Erst den Vorgabewert weg, dann die Pflicht: in dieser Reihenfolge kann keine
|
||||
-- Zeile mehr entstehen, die den alten Stichtag trägt, während die Migration
|
||||
-- noch läuft.
|
||||
alter table app_passwoerter alter column gueltig_bis drop default;
|
||||
alter table app_passwoerter alter column gueltig_bis drop not null;
|
||||
|
||||
-- Der Bestand: vorhandene Zugänge verlieren ihr festes Enddatum.
|
||||
update app_passwoerter set gueltig_bis = null where gueltig_bis is not null;
|
||||
|
||||
comment on table app_passwoerter is
|
||||
'Anmeldung mit Passwort neben Entra ID — Übergangslösung. gueltig_bis ist leer und begrenzt damit nichts; ein Datum darin schaltet den Zugang ab dem Folgetag ab.';
|
||||
|
||||
comment on column app_passwoerter.gueltig_bis is
|
||||
'Letzter Tag, an dem dieses Passwort angenommen wird. Leer heisst unbefristet — der Abschaltknopf, nicht die Frist.';
|
||||
|
||||
-- ── 3. Den Kommentar in der Funktion nachziehen ───────────────────────
|
||||
--
|
||||
-- Im Rumpf von app_passwort_pruefen() steht an dieser Verzweigung „Läuft ohne
|
||||
-- Zutun ab". Ohne feste Frist stimmt das nicht mehr, und ein Kommentar, der
|
||||
-- eine Zusicherung beschreibt, die es nicht gibt, ist schlimmer als keiner —
|
||||
-- er wird beim nächsten Lesen für den Stand gehalten.
|
||||
--
|
||||
-- Ersetzt wird nur der Kommentartext, über pg_get_functiondef und replace().
|
||||
-- Vorbild ist 20260805110000: der Rumpf bleibt dabei nachweislich unangetastet,
|
||||
-- weil er nicht abgetippt wird. Findet sich der Text nicht, bricht die
|
||||
-- Migration ab, statt still nichts zu tun.
|
||||
do $$
|
||||
declare
|
||||
v_def text;
|
||||
v_alt text := 'Das Ende des Passwortpfads. Läuft ohne Zutun ab; siehe Kopf der Datei.';
|
||||
v_neu text := 'Das Ende des Passwortpfads. Greift nur, wenn gueltig_bis gesetzt ist — '
|
||||
|| 'bei null ist der Vergleich unbekannt und die Verzweigung wirkungslos '
|
||||
|| '(siehe 20260908140000).';
|
||||
begin
|
||||
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.proname = 'app_passwort_pruefen';
|
||||
|
||||
if v_def is null then
|
||||
raise exception 'app_passwort_pruefen() nicht gefunden — Abbruch.';
|
||||
end if;
|
||||
if position(v_alt in v_def) = 0 then
|
||||
raise exception 'Der erwartete Kommentar steht nicht in app_passwort_pruefen(). Der Rumpf wurde zwischenzeitlich geändert; bitte von Hand nachsehen.';
|
||||
end if;
|
||||
|
||||
execute replace(v_def, v_alt, v_neu);
|
||||
end;
|
||||
$$;
|
||||
|
||||
comment on function app_passwort_pruefen(text, text) is
|
||||
'Prüft E-Mail und Passwort und liefert app_users.id oder null. Nennt nie einen Grund. gueltig_bis wird beachtet, ist aber standardmässig leer.';
|
||||
|
||||
-- ── 4. Gegenprobe ─────────────────────────────────────────────────────
|
||||
--
|
||||
-- Zwei Fragen, und die zweite ist die eigentliche: verhält sich die Anmeldung
|
||||
-- bei leerem gueltig_bis so, wie diese Migration behauptet? Der Vergleich mit
|
||||
-- null ist genau die Art Annahme, die stimmt, bis sie es nicht tut.
|
||||
do $$
|
||||
declare
|
||||
v_id uuid := gen_random_uuid();
|
||||
v_treffer uuid;
|
||||
begin
|
||||
-- 1. Die Prüfbedingung ist weg, und ein weit entferntes Datum geht durch.
|
||||
if exists (
|
||||
select 1 from pg_constraint
|
||||
where conrelid = 'app_passwoerter'::regclass and conname = 'chk_passwort_pfad_endet'
|
||||
) then
|
||||
raise exception 'chk_passwort_pfad_endet besteht weiterhin — Abbruch.';
|
||||
end if;
|
||||
|
||||
if exists (
|
||||
select 1 from information_schema.columns
|
||||
where table_schema = 'public' and table_name = 'app_passwoerter'
|
||||
and column_name = 'gueltig_bis'
|
||||
and (is_nullable = 'NO' or column_default is not null)
|
||||
) then
|
||||
raise exception 'gueltig_bis ist weiterhin pflichtig oder trägt einen Vorgabewert — Abbruch.';
|
||||
end if;
|
||||
|
||||
if exists (select 1 from app_passwoerter where gueltig_bis is not null) then
|
||||
raise exception 'Es stehen noch Zeilen mit einem Enddatum in app_passwoerter — Abbruch.';
|
||||
end if;
|
||||
|
||||
-- 2. Eine Probeperson mit Passwort. Der Hash mit gen_salt('bf', 4) statt 12:
|
||||
-- crypt() liest die Stärke aus dem gespeicherten Hash, die Prüfung läuft
|
||||
-- also genauso — nur schneller, und eine Migration soll nicht rechnen.
|
||||
insert into app_users (id, external_id, email, full_name)
|
||||
values (v_id, 'probe:' || v_id::text, 'probe-passwort@example.invalid', 'Probe');
|
||||
insert into app_passwoerter (user_id, hash, muss_wechseln, gueltig_bis)
|
||||
values (v_id, crypt('Nur-fuer-die-Probe1', gen_salt('bf', 4)), true, current_date - 1);
|
||||
|
||||
-- 2a. Mit abgelaufenem Datum: abgewiesen.
|
||||
v_treffer := app_passwort_pruefen('probe-passwort@example.invalid', 'Nur-fuer-die-Probe1');
|
||||
if v_treffer is not null then
|
||||
raise exception 'Ein abgelaufenes gueltig_bis wird nicht mehr beachtet — die Abschaltung wäre wirkungslos. Abbruch.';
|
||||
end if;
|
||||
|
||||
-- 2b. Ohne Datum: angenommen. Das ist der Zustand, den diese Migration
|
||||
-- herstellt, und die Aussage, auf die sich alles Weitere stützt.
|
||||
update app_passwoerter set gueltig_bis = null where user_id = v_id;
|
||||
v_treffer := app_passwort_pruefen('probe-passwort@example.invalid', 'Nur-fuer-die-Probe1');
|
||||
if v_treffer is distinct from v_id then
|
||||
raise exception 'Bei leerem gueltig_bis kommt keine Anmeldung zustande — Abbruch.';
|
||||
end if;
|
||||
|
||||
-- Aufräumen. Der erfolgreiche Versuch oben hat eine Protokollzeile
|
||||
-- geschrieben; sie muss mit weg, sonst scheitert das Löschen des Kontos am
|
||||
-- Fremdschlüssel — und stehenbleiben darf sie erst recht nicht, sie gehört
|
||||
-- zu einer Person, die es nie gab. Eng begrenzt auf diese eine Kennung.
|
||||
delete from audit_log where actor_user_id = v_id;
|
||||
delete from app_passwoerter where user_id = v_id;
|
||||
delete from app_users where id = v_id;
|
||||
end;
|
||||
$$;
|
||||
@@ -20,8 +20,8 @@
|
||||
-- Ein Policy-Ausdruck wird **je Zeile** ausgewertet. `is_hr_user()` ist zwar
|
||||
-- `stable`, aber das erlaubt Postgres nur, den Wert innerhalb einer Anweisung
|
||||
-- als unveränderlich anzusehen — nicht, ihn aus dem Zeilenfilter
|
||||
-- herauszuziehen. Bei jeder Zeile läuft also die Unterabfrage auf
|
||||
-- `profiles`.
|
||||
-- herauszuziehen. Bei jeder Zeile laufen also zwei Unterabfragen auf
|
||||
-- `profiles` und `app_passwoerter`.
|
||||
--
|
||||
-- In einen Unterausdruck gefasst wird daraus ein InitPlan, den der Planer
|
||||
-- **einmal** auswertet. Gemessen, ohne RLS, damit nur dieser Unterschied
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
-- Die Anmeldung läuft ausschliesslich über Microsoft Entra ID.
|
||||
--
|
||||
-- Diese Migration entfernt die Objekte einer Anmeldung mit Passwort, sofern
|
||||
-- eine Datenbank sie noch enthält. Auf einer neu eingerichteten Datenbank gibt
|
||||
-- es sie nicht; dann bewirkt die Datei nichts ausser der Prüfung am Ende.
|
||||
--
|
||||
-- is_hr_user() steht danach in der Fassung ohne Passwortbezug: aktive
|
||||
-- HR-Person, sonst nichts.
|
||||
|
||||
create or replace function is_hr_user()
|
||||
returns boolean
|
||||
language sql
|
||||
security definer
|
||||
set search_path = public, pg_temp
|
||||
stable
|
||||
as $$
|
||||
select exists (
|
||||
select 1 from profiles p
|
||||
where p.id = app_current_user_id() and p.role = 'hr' and p.is_active = true
|
||||
);
|
||||
$$;
|
||||
|
||||
comment on function is_hr_user() is
|
||||
'Aktive HR-Person. Aufgerufen von allen RLS-Policies — die eigentliche Zugriffsschranke.';
|
||||
|
||||
drop function if exists app_passwort_regeln(text);
|
||||
drop function if exists app_passwort_pruefen(text, text);
|
||||
drop function if exists app_muss_passwort_wechseln();
|
||||
drop function if exists app_passwort_aendern(jsonb);
|
||||
drop function if exists app_benutzer_anlegen(jsonb);
|
||||
drop function if exists app_passwort_zuruecksetzen(jsonb);
|
||||
drop function if exists app_zugang_setzen(jsonb);
|
||||
drop function if exists app_benutzer_liste();
|
||||
drop table if exists app_passwoerter;
|
||||
|
||||
-- Gegenprobe: nichts davon ist übrig, und die Berechtigungsprüfung verhält
|
||||
-- sich wie verlangt — ohne Sitzungskontext nie wahr.
|
||||
do $$
|
||||
begin
|
||||
if to_regclass('public.app_passwoerter') is not null then
|
||||
raise exception 'app_passwoerter besteht noch. Abbruch.';
|
||||
end if;
|
||||
if exists (select 1 from pg_proc where proname like 'app\_passwort%' or proname in ('app_muss_passwort_wechseln', 'app_benutzer_anlegen', 'app_zugang_setzen', 'app_benutzer_liste')) then
|
||||
raise exception 'Eine Funktion der Passwortanmeldung besteht noch. Abbruch.';
|
||||
end if;
|
||||
perform set_config('app.user_id', '', true);
|
||||
if is_hr_user() then
|
||||
raise exception 'is_hr_user() liefert ohne Sitzungskontext true. Abbruch.';
|
||||
end if;
|
||||
end;
|
||||
$$;
|
||||
@@ -0,0 +1,148 @@
|
||||
-- Wochenstunden mit zwei Nachkommastellen
|
||||
--
|
||||
-- Teilzeit wird in Viertelstunden vereinbart: 19,25 Stunden sind eine
|
||||
-- übliche Angabe. Eine Spalte mit einer Nachkommastelle rundet sie beim
|
||||
-- Speichern stillschweigend auf 19,3, und in den Stammdaten steht dann ein
|
||||
-- Wert, den niemand vereinbart hat. numeric(4,2) reicht bis 99,99; mehr als 38,5
|
||||
-- lässt chk_weekly_hours ohnehin nicht zu.
|
||||
--
|
||||
-- ── Die IT-Sicht steht der Typänderung im Weg ─────────────────────────────
|
||||
--
|
||||
-- it.mitarbeiter liest die Spalte, und PostgreSQL ändert den Typ einer
|
||||
-- Spalte nicht, solange eine Sicht sie verwendet. Die Sicht wird deshalb aus
|
||||
-- ihrer eigenen, gespeicherten Definition neu angelegt — nicht aus einer
|
||||
-- Abschrift, die hier veralten könnte —, samt Kommentar und Leserechten.
|
||||
--
|
||||
-- ── Verglichen wird ohne angehängte Nullen ────────────────────────────────
|
||||
--
|
||||
-- change_employee_data und record_karenz_return schreiben eine Änderung der
|
||||
-- Wochenstunden nur, wenn sich der Text unterscheidet. Mit zwei
|
||||
-- Nachkommastellen lautete der gespeicherte Wert „38.50", die Eingabe „38.5"
|
||||
-- — eine Änderung über nichts in Historie und Bericht. trim_scale nimmt auf
|
||||
-- beiden Seiten die angehängten Nullen weg; so steht in der Historie „19.25"
|
||||
-- und „38.5", in derselben Schreibweise wie die vorhandenen Einträge.
|
||||
|
||||
do $migration$
|
||||
declare
|
||||
v_sicht text;
|
||||
v_kommentar text;
|
||||
v_recht record;
|
||||
v_rechte text[] := '{}';
|
||||
v_def text;
|
||||
v_anzahl int;
|
||||
v_alt text;
|
||||
v_neu text;
|
||||
begin
|
||||
-- 1. Sicht sichern, entfernen, Typ ändern, Sicht wiederherstellen.
|
||||
select pg_get_viewdef('it.mitarbeiter'::regclass, true),
|
||||
obj_description('it.mitarbeiter'::regclass, 'pg_class')
|
||||
into v_sicht, v_kommentar;
|
||||
if v_sicht is null then raise exception 'it.mitarbeiter ist nicht vorhanden.'; end if;
|
||||
|
||||
for v_recht in
|
||||
select case when a.grantee = 0 then 'public' else quote_ident(r.rolname) end as wem,
|
||||
a.privilege_type as was
|
||||
from pg_class c
|
||||
cross join lateral aclexplode(c.relacl) a
|
||||
left join pg_roles r on r.oid = a.grantee
|
||||
where c.oid = 'it.mitarbeiter'::regclass
|
||||
and a.grantee <> c.relowner
|
||||
loop
|
||||
v_rechte := v_rechte || format('grant %s on it.mitarbeiter to %s', v_recht.was, v_recht.wem);
|
||||
end loop;
|
||||
|
||||
drop view it.mitarbeiter;
|
||||
alter table employees alter column weekly_hours type numeric(4,2);
|
||||
execute 'create view it.mitarbeiter as ' || v_sicht;
|
||||
if v_kommentar is not null then
|
||||
execute format('comment on view it.mitarbeiter is %L', v_kommentar);
|
||||
end if;
|
||||
for i in 1 .. coalesce(array_length(v_rechte, 1), 0) loop
|
||||
execute v_rechte[i];
|
||||
end loop;
|
||||
|
||||
-- 2. change_employee_data: Vergleich ohne angehängte Nullen.
|
||||
v_alt := $anker$v_old.weekly_hours::text, (nullif(v_contract->>'weekly_hours','')::numeric(4,1))::text$anker$;
|
||||
v_neu := $anker$trim_scale(v_old.weekly_hours)::text, trim_scale(nullif(v_contract->>'weekly_hours','')::numeric(4,2))::text$anker$;
|
||||
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.proname = 'change_employee_data' and p.prokind = 'f';
|
||||
if v_def is null then raise exception 'change_employee_data ist nicht vorhanden.'; end if;
|
||||
v_anzahl := (length(v_def) - length(replace(v_def, v_alt, ''))) / length(v_alt);
|
||||
if v_anzahl <> 1 then
|
||||
raise exception 'change_employee_data: Anker der Wochenstunden kommt % mal vor, erwartet einmal.', v_anzahl;
|
||||
end if;
|
||||
execute replace(v_def, v_alt, v_neu);
|
||||
|
||||
-- 3. record_karenz_return: dasselbe bei der Rückkehr mit anderen Stunden.
|
||||
v_alt := $anker$v_old.weekly_hours::text, v_weekly_hours::text)$anker$;
|
||||
v_neu := $anker$trim_scale(v_old.weekly_hours)::text, trim_scale(v_weekly_hours::numeric(4,2))::text)$anker$;
|
||||
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.proname = 'record_karenz_return' and p.prokind = 'f';
|
||||
if v_def is null then raise exception 'record_karenz_return ist nicht vorhanden.'; end if;
|
||||
v_anzahl := (length(v_def) - length(replace(v_def, v_alt, ''))) / length(v_alt);
|
||||
if v_anzahl <> 1 then
|
||||
raise exception 'record_karenz_return: Anker der Wochenstunden kommt % mal vor, erwartet einmal.', v_anzahl;
|
||||
end if;
|
||||
execute replace(v_def, v_alt, v_neu);
|
||||
end
|
||||
$migration$;
|
||||
|
||||
|
||||
-- Selbstprüfung: das Neue und das, was bei der Neuerzeugung verlorengehen kann.
|
||||
do $$
|
||||
declare
|
||||
v_def text;
|
||||
begin
|
||||
if (select format_type(a.atttypid, a.atttypmod)
|
||||
from pg_attribute a
|
||||
where a.attrelid = 'public.employees'::regclass and a.attname = 'weekly_hours') <> 'numeric(4,2)' then
|
||||
raise exception 'employees.weekly_hours ist nicht numeric(4,2).';
|
||||
end if;
|
||||
if (select format_type(a.atttypid, a.atttypmod)
|
||||
from pg_attribute a
|
||||
where a.attrelid = 'it.mitarbeiter'::regclass and a.attname = 'weekly_hours') <> 'numeric(4,2)' then
|
||||
raise exception 'it.mitarbeiter zeigt die Wochenstunden nicht mit zwei Nachkommastellen.';
|
||||
end if;
|
||||
if not has_table_privilege('it_lesen', 'it.mitarbeiter', 'select') then
|
||||
raise exception 'it_lesen kann it.mitarbeiter nicht mehr lesen.';
|
||||
end if;
|
||||
if obj_description('it.mitarbeiter'::regclass, 'pg_class') is null then
|
||||
raise exception 'it.mitarbeiter hat den Kommentar verloren.';
|
||||
end if;
|
||||
|
||||
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.proname = 'change_employee_data' and p.prokind = 'f';
|
||||
if v_def not like '%trim_scale(nullif(v_contract->>''weekly_hours'','''')::numeric(4,2))::text%' then
|
||||
raise exception 'change_employee_data vergleicht die Wochenstunden nicht ohne angehängte Nullen.';
|
||||
end if;
|
||||
if v_def like '%numeric(4,1)%' then
|
||||
raise exception 'change_employee_data rundet noch auf eine Nachkommastelle.';
|
||||
end if;
|
||||
if v_def not like '%require_hr_admin()%' then
|
||||
raise exception 'change_employee_data prüft die Rechte nicht.';
|
||||
end if;
|
||||
if v_def not like '%search_path%' then
|
||||
raise exception 'change_employee_data hat keinen festen search_path.';
|
||||
end if;
|
||||
|
||||
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.proname = 'record_karenz_return' and p.prokind = 'f';
|
||||
if v_def not like '%trim_scale(v_weekly_hours::numeric(4,2))::text%' then
|
||||
raise exception 'record_karenz_return vergleicht die Wochenstunden nicht ohne angehängte Nullen.';
|
||||
end if;
|
||||
if v_def not like '%require_hr_admin()%' then
|
||||
raise exception 'record_karenz_return prüft die Rechte nicht.';
|
||||
end if;
|
||||
if v_def not like '%search_path%' then
|
||||
raise exception 'record_karenz_return hat keinen festen search_path.';
|
||||
end if;
|
||||
|
||||
if (19.25)::numeric(4,2) <> 19.25 then
|
||||
raise exception 'numeric(4,2) hält 19,25 nicht.';
|
||||
end if;
|
||||
end
|
||||
$$;
|
||||
250
db/migrations/20261123120000_c_level_als_auswahl.sql
Normal file
250
db/migrations/20261123120000_c_level_als_auswahl.sql
Normal file
@@ -0,0 +1,250 @@
|
||||
-- C-Level als Auswahl aus einer fachlichen Liste
|
||||
--
|
||||
-- C-Level ist die Führungs- bzw. Funktionsstufe einer Person, als Code:
|
||||
-- C1 Bereichsleitung, C11 Mitarbeiter gfg., C2 Abteilungsleitung, C3 Experte,
|
||||
-- C4 Teamleitung, C8 Lehrling, C9 Mitarbeiter, MG Manager, P Prokurist,
|
||||
-- VD Vorstand. Jede Person hat eine Stufe; ein Ja/Nein sagt darüber nichts.
|
||||
--
|
||||
-- Neue Spalte `c_level`, freiwillig (leer = nicht erfasst), mit CHECK statt
|
||||
-- Aufzählungstyp: eine Liste, die sich ändern kann, ist so eine Migration
|
||||
-- mit einer Zeile — wie Mitarbeiterart und Personenkreis.
|
||||
--
|
||||
-- ── Was mit is_c_level geschieht ──────────────────────────────────────────
|
||||
--
|
||||
-- Die Spalte bleibt, die Oberfläche schreibt sie nicht mehr. Bestehende
|
||||
-- Historieneinträge „C-Level: false → true" beziehen sich auf sie; damit
|
||||
-- sie sich weiter berichtigen und löschen lassen, führt die Feldkarte sie
|
||||
-- unter „C-Level (Ja/Nein)", und die vorhandenen Einträge tragen diese
|
||||
-- Bezeichnung. „C-Level" bezeichnet ab hier die neue Spalte.
|
||||
--
|
||||
-- Die IT-Sicht zeigt statt des Ja/Nein den Code: ein Ja/Nein, das niemand
|
||||
-- mehr pflegt, wäre dort eine falsche Auskunft.
|
||||
--
|
||||
-- Fünf Funktionen werden aus ihrer gespeicherten Definition an genau den
|
||||
-- Stellen ergänzt, an denen is_c_level steht; jeder Anker muss genau einmal
|
||||
-- vorkommen.
|
||||
|
||||
alter table employees add column if not exists c_level text;
|
||||
|
||||
do $$
|
||||
begin
|
||||
if not exists (select 1 from pg_constraint where conname = 'chk_c_level' and conrelid = 'public.employees'::regclass) then
|
||||
alter table employees add constraint chk_c_level
|
||||
check (c_level in ('C1', 'C11', 'C2', 'C3', 'C4', 'C8', 'C9', 'MG', 'P', 'VD'));
|
||||
end if;
|
||||
end
|
||||
$$;
|
||||
|
||||
comment on column employees.c_level is
|
||||
'Führungs-/Funktionsstufe als Code (C1 … VD); leer = nicht erfasst. is_c_level ist abgelöst und wird nicht mehr geschrieben.';
|
||||
|
||||
do $migration$
|
||||
declare
|
||||
v_def text;
|
||||
v_anzahl int;
|
||||
|
||||
-- Ersetzt in der gespeicherten Definition von p_funktion jeden Anker durch
|
||||
-- seinen Ersatz und legt die Funktion neu an. Jeder Anker muss genau einmal
|
||||
-- vorkommen; sonst bricht die Migration ab, bevor etwas geändert ist.
|
||||
v_funktionen text[] := array['hire_employee', 'rehire_employee', 'change_employee_data',
|
||||
'apply_due_pending_changes', 'app_feld_karte'];
|
||||
v_anker jsonb := jsonb_build_object(
|
||||
'hire_employee', jsonb_build_array(
|
||||
jsonb_build_array(
|
||||
$a$is_betriebsrat, has_dienstwagen, is_laterale_fuehrung, is_c_level,$a$,
|
||||
$a$is_betriebsrat, has_dienstwagen, is_laterale_fuehrung, is_c_level, c_level,$a$),
|
||||
jsonb_build_array(
|
||||
$a$coalesce((payload->>'is_c_level')::boolean, false),$a$,
|
||||
$a$coalesce((payload->>'is_c_level')::boolean, false),
|
||||
nullif(payload->>'c_level', ''),$a$)),
|
||||
'rehire_employee', jsonb_build_array(
|
||||
jsonb_build_array(
|
||||
$a$is_c_level = coalesce((payload->>'is_c_level')::boolean, is_c_level),$a$,
|
||||
$a$is_c_level = coalesce((payload->>'is_c_level')::boolean, is_c_level),
|
||||
c_level = case when payload ? 'c_level' then nullif(payload->>'c_level', '') else c_level end,$a$)),
|
||||
'change_employee_data', jsonb_build_array(
|
||||
jsonb_build_array(
|
||||
$a$is_c_level = coalesce((v_role->>'is_c_level')::boolean, is_c_level),$a$,
|
||||
$a$is_c_level = coalesce((v_role->>'is_c_level')::boolean, is_c_level),
|
||||
c_level = case when v_role ? 'c_level' then nullif(v_role->>'c_level', '') else c_level end,$a$),
|
||||
jsonb_build_array(
|
||||
$a$app_aenderung(v_contract_changes, 'C-Level', v_old.is_c_level::text, v_role->>'is_c_level'); end if;$a$,
|
||||
$a$app_aenderung(v_contract_changes, 'C-Level (Ja/Nein)', v_old.is_c_level::text, v_role->>'is_c_level'); end if;
|
||||
if v_role ? 'c_level' then v_contract_changes := app_aenderung(v_contract_changes, 'C-Level', v_old.c_level, nullif(v_role->>'c_level', '')); end if;$a$)),
|
||||
'apply_due_pending_changes', jsonb_build_array(
|
||||
jsonb_build_array(
|
||||
$a$is_c_level = coalesce((v_role->>'is_c_level')::boolean, is_c_level),$a$,
|
||||
$a$is_c_level = coalesce((v_role->>'is_c_level')::boolean, is_c_level),
|
||||
c_level = case when v_role ? 'c_level' then nullif(v_role->>'c_level', '') else c_level end,$a$)),
|
||||
'app_feld_karte', jsonb_build_array(
|
||||
jsonb_build_array(
|
||||
$a$'C-Level', jsonb_build_array('is_c_level', 'boolean', 'role')$a$,
|
||||
$a$'C-Level (Ja/Nein)', jsonb_build_array('is_c_level', 'boolean', 'role')$a$),
|
||||
jsonb_build_array(
|
||||
$a$jsonb_build_array('arbeitszeitmodell', 'arbeitszeit', 'role')$a$,
|
||||
$a$jsonb_build_array('arbeitszeitmodell', 'arbeitszeit', 'role'),
|
||||
'C-Level', jsonb_build_array('c_level', 'text', 'role')$a$))
|
||||
);
|
||||
v_name text;
|
||||
v_paar jsonb;
|
||||
v_alt text;
|
||||
begin
|
||||
foreach v_name in array v_funktionen 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.proname = v_name and p.prokind = 'f';
|
||||
if v_def is null then raise exception '% ist nicht vorhanden.', v_name; end if;
|
||||
|
||||
for v_paar in select * from jsonb_array_elements(v_anker -> v_name) loop
|
||||
v_alt := v_paar ->> 0;
|
||||
v_anzahl := (length(v_def) - length(replace(v_def, v_alt, ''))) / length(v_alt);
|
||||
if v_anzahl <> 1 then
|
||||
raise exception '%: Anker „%" kommt % mal vor, erwartet einmal.', v_name, v_alt, v_anzahl;
|
||||
end if;
|
||||
v_def := replace(v_def, v_alt, v_paar ->> 1);
|
||||
end loop;
|
||||
|
||||
execute v_def;
|
||||
end loop;
|
||||
end
|
||||
$migration$;
|
||||
|
||||
-- Vorhandene Historieneinträge zum Ja/Nein tragen dessen neue Bezeichnung.
|
||||
-- Nur die Bezeichnung im Änderungsdetail ändert sich, nicht Datum, Werte
|
||||
-- oder Reihenfolge. Die Prüfung „kein Vorgang ab Austritt" gilt neuen
|
||||
-- Vorgängen; sie bleibt für diese eine Umbenennung aus.
|
||||
alter table employee_history disable trigger trg_kein_vorgang_ab_austritt;
|
||||
|
||||
update employee_history h
|
||||
set changes = (
|
||||
select jsonb_agg(case when e->>'feld' = 'C-Level'
|
||||
then jsonb_set(e, '{feld}', to_jsonb('C-Level (Ja/Nein)'::text))
|
||||
else e end
|
||||
order by i)
|
||||
from jsonb_array_elements(h.changes) with ordinality t(e, i))
|
||||
where jsonb_typeof(h.changes) = 'array'
|
||||
and h.changes @> '[{"feld": "C-Level"}]';
|
||||
|
||||
alter table employee_history enable trigger trg_kein_vorgang_ab_austritt;
|
||||
|
||||
-- IT-Sicht: der Code statt des abgelösten Ja/Nein. Neu angelegt aus der
|
||||
-- gespeicherten Definition, samt Kommentar und Leserechten.
|
||||
do $sicht$
|
||||
declare
|
||||
v_sicht text;
|
||||
v_kommentar text;
|
||||
v_recht record;
|
||||
v_rechte text[] := '{}';
|
||||
v_anzahl int;
|
||||
begin
|
||||
select pg_get_viewdef('it.mitarbeiter'::regclass, true),
|
||||
obj_description('it.mitarbeiter'::regclass, 'pg_class')
|
||||
into v_sicht, v_kommentar;
|
||||
if v_sicht is null then raise exception 'it.mitarbeiter ist nicht vorhanden.'; end if;
|
||||
|
||||
v_anzahl := (length(v_sicht) - length(replace(v_sicht, 'e.is_c_level,', ''))) / length('e.is_c_level,');
|
||||
if v_anzahl <> 1 then
|
||||
raise exception 'it.mitarbeiter: e.is_c_level kommt % mal vor, erwartet einmal.', v_anzahl;
|
||||
end if;
|
||||
|
||||
for v_recht in
|
||||
select case when a.grantee = 0 then 'public' else quote_ident(r.rolname) end as wem,
|
||||
a.privilege_type as was
|
||||
from pg_class c
|
||||
cross join lateral aclexplode(c.relacl) a
|
||||
left join pg_roles r on r.oid = a.grantee
|
||||
where c.oid = 'it.mitarbeiter'::regclass
|
||||
and a.grantee <> c.relowner
|
||||
loop
|
||||
v_rechte := v_rechte || format('grant %s on it.mitarbeiter to %s', v_recht.was, v_recht.wem);
|
||||
end loop;
|
||||
|
||||
drop view it.mitarbeiter;
|
||||
execute 'create view it.mitarbeiter as ' || replace(v_sicht, 'e.is_c_level,', 'e.c_level,');
|
||||
if v_kommentar is not null then
|
||||
execute format('comment on view it.mitarbeiter is %L', v_kommentar);
|
||||
end if;
|
||||
for i in 1 .. coalesce(array_length(v_rechte, 1), 0) loop
|
||||
execute v_rechte[i];
|
||||
end loop;
|
||||
end
|
||||
$sicht$;
|
||||
|
||||
|
||||
-- ── Selbstprüfung ─────────────────────────────────────────────────────────
|
||||
do $$
|
||||
declare
|
||||
v_def text;
|
||||
v_name text;
|
||||
begin
|
||||
if not exists (select 1 from pg_constraint where conname = 'chk_c_level' and conrelid = 'public.employees'::regclass) then
|
||||
raise exception 'chk_c_level fehlt.';
|
||||
end if;
|
||||
|
||||
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.proname = 'hire_employee' and p.prokind = 'f';
|
||||
if v_def not like '%is_c_level, c_level,%' or v_def not like '%nullif(payload->>''c_level'', ''''),%' then
|
||||
raise exception 'hire_employee schreibt c_level nicht.';
|
||||
end if;
|
||||
|
||||
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.proname = 'rehire_employee' and p.prokind = 'f';
|
||||
if v_def not like '%c_level = case when payload ? ''c_level''%' then
|
||||
raise exception 'rehire_employee schreibt c_level nicht.';
|
||||
end if;
|
||||
|
||||
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.proname = 'change_employee_data' and p.prokind = 'f';
|
||||
if v_def not like '%c_level = case when v_role ? ''c_level''%' then
|
||||
raise exception 'change_employee_data schreibt c_level nicht.';
|
||||
end if;
|
||||
if v_def not like '%''C-Level'', v_old.c_level%' or v_def not like '%''C-Level (Ja/Nein)'', v_old.is_c_level%' then
|
||||
raise exception 'change_employee_data protokolliert C-Level nicht wie vorgesehen.';
|
||||
end if;
|
||||
-- Was bei einer Neuerzeugung dieser Funktion verlorengehen kann.
|
||||
if v_def not like '%trim_scale(nullif(v_contract->>''weekly_hours'','''')::numeric(4,2))::text%' then
|
||||
raise exception 'change_employee_data hat den Vergleich der Wochenstunden verloren.';
|
||||
end if;
|
||||
if v_def not like '%cornerstone_id%' then
|
||||
raise exception 'change_employee_data hat die Cornerstone-ID verloren.';
|
||||
end if;
|
||||
|
||||
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.proname = 'apply_due_pending_changes' and p.prokind = 'f';
|
||||
if v_def not like '%c_level = case when v_role ? ''c_level''%' then
|
||||
raise exception 'apply_due_pending_changes schreibt c_level nicht.';
|
||||
end if;
|
||||
|
||||
if app_feld_karte() -> 'C-Level' ->> 0 is distinct from 'c_level'
|
||||
or app_feld_karte() -> 'C-Level (Ja/Nein)' ->> 0 is distinct from 'is_c_level' then
|
||||
raise exception 'app_feld_karte führt C-Level nicht wie vorgesehen.';
|
||||
end if;
|
||||
|
||||
foreach v_name in array array['hire_employee', 'rehire_employee', 'change_employee_data', 'apply_due_pending_changes'] 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.proname = v_name and p.prokind = 'f';
|
||||
if v_name <> 'apply_due_pending_changes' and v_def not like '%require_hr_admin()%' then
|
||||
raise exception '% prüft die Rechte nicht.', v_name;
|
||||
end if;
|
||||
if v_def not like '%search_path%' then
|
||||
raise exception '% hat keinen festen search_path.', v_name;
|
||||
end if;
|
||||
end loop;
|
||||
|
||||
if exists (select 1 from employee_history
|
||||
where jsonb_typeof(changes) = 'array' and changes @> '[{"feld": "C-Level"}]') then
|
||||
raise exception 'Es gibt noch Historieneinträge mit der alten Bezeichnung „C-Level".';
|
||||
end if;
|
||||
if not exists (select 1 from pg_trigger where tgname = 'trg_kein_vorgang_ab_austritt' and tgenabled = 'O') then
|
||||
raise exception 'trg_kein_vorgang_ab_austritt ist nicht wieder eingeschaltet.';
|
||||
end if;
|
||||
|
||||
if not exists (select 1 from information_schema.columns
|
||||
where table_schema = 'it' and table_name = 'mitarbeiter' and column_name = 'c_level') then
|
||||
raise exception 'it.mitarbeiter zeigt c_level nicht.';
|
||||
end if;
|
||||
if not has_table_privilege('it_lesen', 'it.mitarbeiter', 'select') then
|
||||
raise exception 'it_lesen kann it.mitarbeiter nicht mehr lesen.';
|
||||
end if;
|
||||
end
|
||||
$$;
|
||||
139
db/migrations/20261123140000_standort_shop.sql
Normal file
139
db/migrations/20261123140000_standort_shop.sql
Normal file
@@ -0,0 +1,139 @@
|
||||
-- Standorte mit Unterstandorten: „Shop" und die einzelnen Shops
|
||||
--
|
||||
-- Ein Standort kann Unterstandorte haben. Eine Person sitzt immer auf einem
|
||||
-- Standort ohne Unterstandorte: „Shop" allein sagt nicht, wo jemand
|
||||
-- arbeitet. Die Oberfläche bietet zuerst die Standorte ohne übergeordneten
|
||||
-- an und bei einem mit Unterstandorten eine zweite Auswahl.
|
||||
--
|
||||
-- Der Name eines Unterstandorts nennt den übergeordneten mit („Shop W17"):
|
||||
-- Liste, Berichte, Exporte und IT-Sicht lesen nur den Namen und bleiben so
|
||||
-- ohne weitere Verknüpfung eindeutig.
|
||||
--
|
||||
-- Eine Ebene: ein Unterstandort hat keine eigenen. Zwei Trigger halten das
|
||||
-- fest, auch für den Import und den Nachtlauf, die an der Oberfläche
|
||||
-- vorbeigehen.
|
||||
|
||||
alter table locations add column if not exists parent_id uuid references locations(id);
|
||||
|
||||
comment on column locations.parent_id is
|
||||
'Übergeordneter Standort (etwa „Shop"); leer = Standort der obersten Ebene. Personen sitzen nur auf Standorten ohne Unterstandorte.';
|
||||
|
||||
alter table locations drop constraint if exists chk_location_nicht_eigener_parent;
|
||||
alter table locations add constraint chk_location_nicht_eigener_parent check (parent_id is null or parent_id <> id);
|
||||
|
||||
create index if not exists idx_locations_parent on locations (parent_id) where parent_id is not null;
|
||||
|
||||
-- Sitzt schon jemand auf einem Standort „Shop", fehlt die Angabe, auf welchem.
|
||||
-- Raten wäre schlechter als anhalten.
|
||||
do $pruefung$
|
||||
begin
|
||||
if exists (select 1 from employees e join locations l on l.id = e.location_id where l.name = 'Shop') then
|
||||
raise exception 'Auf dem Standort „Shop" sitzen Personen. Sie brauchen zuerst einen anderen Standort; danach die Migration erneut ausführen.';
|
||||
end if;
|
||||
end
|
||||
$pruefung$;
|
||||
|
||||
-- ── Regeln ──────────────────────────────────────────────────────────────
|
||||
|
||||
create or replace function public.standort_ebene_pruefen()
|
||||
returns trigger
|
||||
language plpgsql
|
||||
set search_path = public, pg_temp
|
||||
as $$
|
||||
begin
|
||||
if new.parent_id is null then
|
||||
return new;
|
||||
end if;
|
||||
if exists (select 1 from locations where id = new.parent_id and parent_id is not null) then
|
||||
raise exception 'Ein Unterstandort kann keine eigenen Unterstandorte haben.';
|
||||
end if;
|
||||
if exists (select 1 from locations where parent_id = new.id) then
|
||||
raise exception 'Ein Standort mit Unterstandorten kann nicht selbst unter einem anderen stehen.';
|
||||
end if;
|
||||
if exists (select 1 from employees where location_id = new.parent_id) then
|
||||
raise exception 'Auf dem Standort „%" sitzen Personen; er kann keine Unterstandorte bekommen.',
|
||||
(select name from locations where id = new.parent_id);
|
||||
end if;
|
||||
return new;
|
||||
end;
|
||||
$$;
|
||||
|
||||
drop trigger if exists trg_standort_ebene on locations;
|
||||
create trigger trg_standort_ebene
|
||||
before insert or update of parent_id on locations
|
||||
for each row execute function public.standort_ebene_pruefen();
|
||||
|
||||
create or replace function public.standort_ohne_unterstandorte()
|
||||
returns trigger
|
||||
language plpgsql
|
||||
set search_path = public, pg_temp
|
||||
as $$
|
||||
begin
|
||||
if new.location_id is not null and exists (select 1 from locations where parent_id = new.location_id) then
|
||||
raise exception 'Der Standort „%" fasst mehrere zusammen. Bitte einen davon auswählen.',
|
||||
(select name from locations where id = new.location_id);
|
||||
end if;
|
||||
return new;
|
||||
end;
|
||||
$$;
|
||||
|
||||
drop trigger if exists trg_standort_ohne_unterstandorte on employees;
|
||||
create trigger trg_standort_ohne_unterstandorte
|
||||
before insert or update of location_id on employees
|
||||
for each row execute function public.standort_ohne_unterstandorte();
|
||||
|
||||
-- ── Shop und die einzelnen Shops ────────────────────────────────────────
|
||||
|
||||
insert into locations (name, country) values ('Shop', 'Österreich') on conflict (name) do nothing;
|
||||
|
||||
insert into locations (name, country, parent_id)
|
||||
select v.name, 'Österreich', (select id from locations where name = 'Shop')
|
||||
from (values ('Shop W17'), ('Shop Wodo'), ('Shop Parndorf'), ('Shop Donaupark'), ('Shop W1'), ('Shop Wien Hauptbahnhof')) v(name)
|
||||
on conflict (name) do nothing;
|
||||
|
||||
-- Bestanden einzelne Shops schon als eigene Standorte, kommen sie unter „Shop".
|
||||
update locations
|
||||
set parent_id = (select id from locations where name = 'Shop')
|
||||
where name in ('Shop W17', 'Shop Wodo', 'Shop Parndorf', 'Shop Donaupark', 'Shop W1', 'Shop Wien Hauptbahnhof')
|
||||
and parent_id is null;
|
||||
|
||||
-- ── Selbstprüfung ───────────────────────────────────────────────────────
|
||||
|
||||
do $migration$
|
||||
declare
|
||||
v_shop uuid;
|
||||
begin
|
||||
select id into v_shop from locations where name = 'Shop';
|
||||
if v_shop is null then
|
||||
raise exception 'Der Standort „Shop" fehlt.';
|
||||
end if;
|
||||
if (select parent_id from locations where id = v_shop) is not null then
|
||||
raise exception '„Shop" steht unter einem anderen Standort.';
|
||||
end if;
|
||||
if (select count(*) from locations where parent_id = v_shop) <> 6 then
|
||||
raise exception 'Unter „Shop" stehen nicht genau die sechs Shops.';
|
||||
end if;
|
||||
if exists (
|
||||
select 1 from (values ('Shop W17'), ('Shop Wodo'), ('Shop Parndorf'), ('Shop Donaupark'), ('Shop W1'), ('Shop Wien Hauptbahnhof')) v(name)
|
||||
where not exists (select 1 from locations l where l.name = v.name and l.parent_id = v_shop)
|
||||
) then
|
||||
raise exception 'Ein Shop fehlt oder steht nicht unter „Shop".';
|
||||
end if;
|
||||
if exists (select 1 from employees e join locations l on l.parent_id = e.location_id) then
|
||||
raise exception 'Eine Person sitzt auf einem Standort mit Unterstandorten.';
|
||||
end if;
|
||||
if (select count(*) from pg_trigger
|
||||
where not tgisinternal and tgenabled = 'O'
|
||||
and tgname in ('trg_standort_ebene', 'trg_standort_ohne_unterstandorte')) <> 2 then
|
||||
raise exception 'Die Trigger zu den Unterstandorten fehlen.';
|
||||
end if;
|
||||
if exists (
|
||||
select 1 from pg_proc p join pg_namespace n on n.oid = p.pronamespace
|
||||
where n.nspname = 'public'
|
||||
and p.proname in ('standort_ebene_pruefen', 'standort_ohne_unterstandorte')
|
||||
and (p.prosecdef or not ('search_path=public, pg_temp' = any (coalesce(p.proconfig, '{}'))))
|
||||
) then
|
||||
raise exception 'Die Triggerfunktionen laufen nicht unter den Rechten des Aufrufers oder ohne search_path.';
|
||||
end if;
|
||||
end
|
||||
$migration$;
|
||||
@@ -0,0 +1,188 @@
|
||||
-- Eine im Nachtlauf verbuchte Rückkehr hält ihre Vorher-Werte fest
|
||||
--
|
||||
-- Eine Rückkehr, die sofort erfasst wird (record_karenz_return mit einem
|
||||
-- Datum heute oder früher), schreibt in ihre Historienzeile, was vorher galt:
|
||||
-- Status, Art der Abwesenheit, Beginn, Ende, gegebenenfalls Ausmass und
|
||||
-- Stunden. Daran setzt delete_history_entry beim Zurücknehmen an.
|
||||
--
|
||||
-- Eine geplante Rückkehr bekommt ihre Zeile schon beim Planen, zu dem
|
||||
-- Zeitpunkt ohne Werte — geändert ist noch nichts. Verbucht der Nachtlauf sie
|
||||
-- am Stichtag, müssen die Werte von diesem Augenblick in die Zeile. Sonst
|
||||
-- liesse sie sich nicht zurücknehmen, und die Abwesenheit davor ebenfalls
|
||||
-- nicht, weil eine Rückkehr zuerst gelöscht werden muss. Ein Austritt, der
|
||||
-- vor einer solchen Rückkehr liegt, liesse sich dann gar nicht erfassen.
|
||||
--
|
||||
-- 1. app_rueckkehr_aenderungen(): die Vorher-Werte aus der Personenzeile
|
||||
-- und dem geplanten Vorgang, in derselben Form wie record_karenz_return.
|
||||
-- 2. apply_due_pending_changes schreibt sie in die Historienzeile, bevor er
|
||||
-- die Person zurücksetzt. Ergänzt an der laufenden Definition, an genau
|
||||
-- einem Anker.
|
||||
-- 3. Bestand: bereits im Nachtlauf verbuchte Rückkehren ohne Werte bekommen
|
||||
-- sie nachgetragen, aus der Abwesenheit davor. Kam die Person mit anderem
|
||||
-- Ausmass zurück, sind die Stunden von davor nicht sicher bekannt; solche
|
||||
-- Zeilen bleiben unverändert und werden gezählt.
|
||||
|
||||
create or replace function public.app_rueckkehr_aenderungen(p_alt employees, p_plan jsonb)
|
||||
returns jsonb
|
||||
language plpgsql
|
||||
stable
|
||||
set search_path = public, pg_temp
|
||||
as $$
|
||||
declare
|
||||
v jsonb := '[]'::jsonb;
|
||||
v_ausmass employment_type := nullif(p_plan->>'employment_type', '')::employment_type;
|
||||
v_stunden numeric := nullif(p_plan->>'weekly_hours', '')::numeric;
|
||||
begin
|
||||
v := app_aenderung(v, 'Status', p_alt.status::text, 'Aktiv');
|
||||
v := app_aenderung(v, 'Art der Abwesenheit', p_alt.absence_type, null);
|
||||
v := app_aenderung(v, 'Abwesend ab', p_alt.karenz_start_date::text, null);
|
||||
v := app_aenderung(v, 'Geplante Rückkehr', p_alt.karenz_return_date::text, null);
|
||||
if v_ausmass is not null then
|
||||
v := app_aenderung(v, 'Beschäftigungsausmaß', p_alt.employment_type::text, v_ausmass::text);
|
||||
v := app_aenderung(v, 'Wochenstunden', trim_scale(p_alt.weekly_hours)::text, trim_scale(v_stunden::numeric(4,2))::text);
|
||||
end if;
|
||||
-- Dieselbe Bedingung wie im Nachtlauf: steht die Teilzeitvariante im
|
||||
-- Vorgang, setzt er Variante und Ende.
|
||||
if p_plan ? 'teilzeit_art' then
|
||||
v := app_aenderung(v, 'Teilzeitvariante', p_alt.teilzeit_art, nullif(p_plan->>'teilzeit_art', ''));
|
||||
v := app_aenderung(v, 'Teilzeit bis', p_alt.teilzeit_bis::text, nullif(p_plan->>'teilzeit_bis', ''));
|
||||
end if;
|
||||
return v;
|
||||
end;
|
||||
$$;
|
||||
|
||||
revoke execute on function public.app_rueckkehr_aenderungen(employees, jsonb) from public;
|
||||
|
||||
comment on function public.app_rueckkehr_aenderungen(employees, jsonb) is
|
||||
'Vorher-Werte einer Rückkehr für die Historie: aus der Personenzeile vor dem Verbuchen und dem geplanten Vorgang.';
|
||||
|
||||
-- ── Nachtlauf ────────────────────────────────────────────────────────────
|
||||
do $migration$
|
||||
declare
|
||||
v_anker constant text := $a$ elsif v_rec.change_type = 'karenz_return' then
|
||||
$a$;
|
||||
v_neu constant text := $a$ elsif v_rec.change_type = 'karenz_return' then
|
||||
-- Die Werte von davor, wie bei einer sofort erfassten Rückkehr: ohne
|
||||
-- sie liesse sich die Rückkehr in der Historie nicht zurücknehmen.
|
||||
update employee_history h
|
||||
set changes = app_rueckkehr_aenderungen(e, v_rec.payload)
|
||||
from employees e
|
||||
where e.id = v_rec.employee_id and h.pending_id = v_rec.id and h.event_type = 'Rückkehr';
|
||||
$a$;
|
||||
v_def text;
|
||||
v_treffer integer;
|
||||
begin
|
||||
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 = 'apply_due_pending_changes';
|
||||
if v_def is null then
|
||||
raise exception 'apply_due_pending_changes ist nicht vorhanden.';
|
||||
end if;
|
||||
if position('app_rueckkehr_aenderungen(e, v_rec.payload)' in v_def) > 0 then
|
||||
raise notice 'apply_due_pending_changes ist bereits angepasst.';
|
||||
return;
|
||||
end if;
|
||||
v_treffer := (length(v_def) - length(replace(v_def, v_anker, ''))) / length(v_anker);
|
||||
if v_treffer <> 1 then
|
||||
raise exception 'apply_due_pending_changes: der Anker kommt % mal vor, erwartet genau einmal.', v_treffer;
|
||||
end if;
|
||||
execute replace(v_def, v_anker, v_neu);
|
||||
end
|
||||
$migration$;
|
||||
|
||||
-- ── Bestand ──────────────────────────────────────────────────────────────
|
||||
do $bestand$
|
||||
declare
|
||||
v_zeile record;
|
||||
v_karenz record;
|
||||
v_art text;
|
||||
v_nachgetragen integer := 0;
|
||||
v_ausmass integer := 0;
|
||||
v_ohne_abwesenheit integer := 0;
|
||||
begin
|
||||
for v_zeile in
|
||||
select h.id, h.employee_id, h.event_date, h.created_at, p.payload
|
||||
from employee_history h
|
||||
join pending_org_changes p on p.id = h.pending_id
|
||||
where h.event_type = 'Rückkehr' and p.status = 'applied'
|
||||
and coalesce(h.changes, '[]'::jsonb) = '[]'::jsonb
|
||||
loop
|
||||
if nullif(v_zeile.payload->>'employment_type', '') is not null then
|
||||
v_ausmass := v_ausmass + 1;
|
||||
continue;
|
||||
end if;
|
||||
|
||||
select k.event_date, k.changes into v_karenz
|
||||
from employee_history k
|
||||
where k.employee_id = v_zeile.employee_id and k.event_type = 'Karenz'
|
||||
and (k.event_date, k.created_at) < (v_zeile.event_date, v_zeile.created_at)
|
||||
order by k.event_date desc, k.created_at desc
|
||||
limit 1;
|
||||
if not found then
|
||||
v_ohne_abwesenheit := v_ohne_abwesenheit + 1;
|
||||
continue;
|
||||
end if;
|
||||
select a->>'nachher' into v_art
|
||||
from jsonb_array_elements(coalesce(v_karenz.changes, '[]'::jsonb)) a
|
||||
where a->>'feld' = 'Art der Abwesenheit';
|
||||
|
||||
update employee_history set changes =
|
||||
app_aenderung(app_aenderung(app_aenderung(app_aenderung('[]'::jsonb,
|
||||
'Status', 'Karenz', 'Aktiv'),
|
||||
'Art der Abwesenheit', v_art, null),
|
||||
'Abwesend ab', v_karenz.event_date::text, null),
|
||||
'Geplante Rückkehr', v_zeile.event_date::text, null)
|
||||
where id = v_zeile.id;
|
||||
v_nachgetragen := v_nachgetragen + 1;
|
||||
end loop;
|
||||
|
||||
raise notice 'Rückkehren aus dem Nachtlauf: % nachgetragen, % mit geändertem Ausmass unverändert, % ohne Abwesenheit davor unverändert.',
|
||||
v_nachgetragen, v_ausmass, v_ohne_abwesenheit;
|
||||
end
|
||||
$bestand$;
|
||||
|
||||
-- ── Prüfung ──────────────────────────────────────────────────────────────
|
||||
do $pruefung$
|
||||
declare
|
||||
v_def text;
|
||||
v_offen integer;
|
||||
begin
|
||||
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 = 'apply_due_pending_changes';
|
||||
if (length(v_def) - length(replace(v_def, 'app_rueckkehr_aenderungen(e, v_rec.payload)', '')))
|
||||
/ length('app_rueckkehr_aenderungen(e, v_rec.payload)') <> 1 then
|
||||
raise exception 'apply_due_pending_changes schreibt die Vorher-Werte der Rückkehr nicht genau einmal.';
|
||||
end if;
|
||||
-- Was der Nachtlauf schon konnte, bleibt: Onboarding-Liste und
|
||||
-- Teilzeitvariante bei der Rückkehr, je Vormerkung ein eigener Block.
|
||||
if position($a$'onboarding', 'Rückkehr'$a$ in v_def) = 0
|
||||
or position($a$v_rec.payload ? 'teilzeit_art'$a$ in v_def) = 0
|
||||
or position('exception when others' in v_def) = 0 then
|
||||
raise exception 'apply_due_pending_changes hat bei der Anpassung Verhalten verloren.';
|
||||
end if;
|
||||
if not exists (select 1 from pg_proc p join pg_namespace n on n.oid = p.pronamespace
|
||||
where n.nspname = 'public' and p.proname = 'apply_due_pending_changes' and p.prosecdef) then
|
||||
raise exception 'apply_due_pending_changes ist nicht mehr SECURITY DEFINER.';
|
||||
end if;
|
||||
if exists (select 1 from pg_proc p join pg_namespace n on n.oid = p.pronamespace
|
||||
where n.nspname = 'public' and p.proname = 'app_rueckkehr_aenderungen'
|
||||
and (p.prosecdef or p.proconfig is null)) then
|
||||
raise exception 'app_rueckkehr_aenderungen muss ohne SECURITY DEFINER und mit festem search_path laufen.';
|
||||
end if;
|
||||
|
||||
-- Nach dem Nachtrag ohne Werte nur noch die gezählten Ausnahmen.
|
||||
select count(*) into v_offen
|
||||
from employee_history h
|
||||
join pending_org_changes p on p.id = h.pending_id
|
||||
where h.event_type = 'Rückkehr' and p.status = 'applied'
|
||||
and coalesce(h.changes, '[]'::jsonb) = '[]'::jsonb
|
||||
and nullif(p.payload->>'employment_type', '') is null
|
||||
and exists (select 1 from employee_history k
|
||||
where k.employee_id = h.employee_id and k.event_type = 'Karenz'
|
||||
and (k.event_date, k.created_at) < (h.event_date, h.created_at));
|
||||
if v_offen > 0 then
|
||||
raise exception 'Es gibt noch % im Nachtlauf verbuchte Rückkehren ohne Vorher-Werte.', v_offen;
|
||||
end if;
|
||||
end
|
||||
$pruefung$;
|
||||
78
db/migrations/20261201120000_fl_ohne_stufe_8.sql
Normal file
78
db/migrations/20261201120000_fl_ohne_stufe_8.sql
Normal file
@@ -0,0 +1,78 @@
|
||||
-- FL: Stufen 1 bis 7
|
||||
--
|
||||
-- Die Angabe heisst fachlich „FL" und kennt die Stufen 1 bis 7. Gespeichert
|
||||
-- bleibt sie in der Spalte vl, und in der Historie und der Feldkarte heisst
|
||||
-- das Feld weiter „VL": daran hängen Berichtigen und Zurücksetzen bestehender
|
||||
-- Einträge. Die Oberfläche zeigt „FL" (lib/anzeige.ts).
|
||||
--
|
||||
-- Bestand mit Stufe 8: welche Stufe stattdessen gilt, geht aus den Daten
|
||||
-- nicht hervor. Die Angabe wird geleert und je Person im Protokoll vermerkt;
|
||||
-- ein geratener Wert sähe aus wie ein erfasster. Geplante Änderungen auf
|
||||
-- Stufe 8 verlieren diese eine Angabe, in der Vormerkung und in ihrer
|
||||
-- Historienzeile; der Rest des Vorgangs bleibt. Bleibt nichts übrig, entfällt
|
||||
-- der Vorgang samt Zeile, wie beim Abbrechen in der Historie.
|
||||
|
||||
do $geplant$
|
||||
declare
|
||||
v_plan record;
|
||||
v_payload jsonb;
|
||||
begin
|
||||
for v_plan in
|
||||
select * from pending_org_changes
|
||||
where status = 'pending' and payload->'contract'->>'vl' = '8'
|
||||
loop
|
||||
v_payload := jsonb_set(v_plan.payload, '{contract}', (v_plan.payload->'contract') - 'vl');
|
||||
|
||||
insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details)
|
||||
select null, 'Wartung', 'Geplante Änderung angepasst', e.first_name || ' ' || e.last_name, e.id,
|
||||
'Zum ' || v_plan.effective_date || ' war FL 8 vorgemerkt. Die Stufe 8 gibt es nicht mehr; '
|
||||
|| 'diese Angabe entfällt aus dem Vorgang.'
|
||||
from employees e where e.id = v_plan.employee_id;
|
||||
|
||||
if coalesce(v_payload->'person', '{}'::jsonb) = '{}'::jsonb
|
||||
and coalesce(v_payload->'contract', '{}'::jsonb) = '{}'::jsonb
|
||||
and coalesce(v_payload->'role', '{}'::jsonb) = '{}'::jsonb then
|
||||
update pending_org_changes set status = 'cancelled' where id = v_plan.id;
|
||||
delete from employee_history where pending_id = v_plan.id;
|
||||
else
|
||||
update pending_org_changes set payload = v_payload where id = v_plan.id;
|
||||
-- In der Beschreibung steht die Liste der Felder, jedes gefolgt von
|
||||
-- einem Komma („Geänderte Felder: VL, Bonusanspruch, wirksam ab …").
|
||||
update employee_history h
|
||||
set changes = (select coalesce(jsonb_agg(a), '[]'::jsonb)
|
||||
from jsonb_array_elements(h.changes) a
|
||||
where a->>'feld' <> 'VL'),
|
||||
description = replace(h.description, 'VL, ', '')
|
||||
where h.pending_id = v_plan.id;
|
||||
end if;
|
||||
end loop;
|
||||
end
|
||||
$geplant$;
|
||||
|
||||
insert into audit_log (actor_user_id, actor_name, action, target_label, target_employee_id, details)
|
||||
select null, 'Wartung', 'FL geleert', e.first_name || ' ' || e.last_name, e.id,
|
||||
'Die Stufe 8 gibt es nicht mehr; FL war 8 und ist jetzt leer. Bitte die zutreffende Stufe (1 bis 7) nachtragen.'
|
||||
from employees e
|
||||
where e.vl = 8;
|
||||
|
||||
update employees set vl = null where vl = 8;
|
||||
|
||||
alter table employees drop constraint if exists chk_vl;
|
||||
alter table employees add constraint chk_vl check (vl is null or vl between 1 and 7);
|
||||
|
||||
comment on column employees.vl is 'FL, Stufe 1 bis 7; leer heisst nicht erfasst. In Historie und Feldkarte als „VL" geführt.';
|
||||
|
||||
do $pruefung$
|
||||
begin
|
||||
if exists (select 1 from employees where vl not between 1 and 7) then
|
||||
raise exception 'Es gibt noch FL-Werte ausserhalb von 1 bis 7.';
|
||||
end if;
|
||||
if exists (select 1 from pending_org_changes where status = 'pending' and payload->'contract'->>'vl' = '8') then
|
||||
raise exception 'Es gibt noch geplante Änderungen auf FL 8.';
|
||||
end if;
|
||||
if pg_get_constraintdef((select oid from pg_constraint where conname = 'chk_vl' and conrelid = 'public.employees'::regclass))
|
||||
not like '%vl >= 1%vl <= 7%' then
|
||||
raise exception 'chk_vl erlaubt nicht genau 1 bis 7.';
|
||||
end if;
|
||||
end
|
||||
$pruefung$;
|
||||
@@ -60,7 +60,7 @@ declare
|
||||
v_psnr text;
|
||||
begin
|
||||
select id into v_wurzel from org_units where parent_id is null;
|
||||
select id into v_ort from locations order by name limit 1;
|
||||
select l.id into v_ort from locations l where not exists (select 1 from locations u where u.parent_id = l.id) order by l.name limit 1;
|
||||
select coalesce(max(personnel_number), 0) + 1 into v_nr from employees;
|
||||
if v_wurzel is null or v_ort is null then
|
||||
raise exception 'Kein Bestand: es fehlt die oberste Einheit oder ein Standort.';
|
||||
|
||||
@@ -62,7 +62,7 @@ begin
|
||||
raise exception 'Voraussetzung fehlt: zwei aktive und ein abgeschaltetes HR-Konto.';
|
||||
end if;
|
||||
select id into v_wurzel from org_units where parent_id is null;
|
||||
select id into v_ort from locations order by name limit 1;
|
||||
select l.id into v_ort from locations l where not exists (select 1 from locations u where u.parent_id = l.id) order by l.name limit 1;
|
||||
select coalesce(max(personnel_number), 0) + 1 into v_nr from employees;
|
||||
|
||||
v_einheit := create_org_unit(jsonb_build_object(
|
||||
@@ -149,14 +149,14 @@ begin
|
||||
perform hire_employee(jsonb_build_object(
|
||||
'personnel_number', v_nr + 2, 'first_name', 'X', 'last_name', 'Y', 'gender', 'm',
|
||||
'birth_date', '1980-01-01', 'location_id', v_ort, 'position_id', v_p3,
|
||||
'entry_date', current_date::text, 'vl', 9));
|
||||
'entry_date', current_date::text, 'vl', 8));
|
||||
v_ging := true;
|
||||
exception when others then v_ging := false;
|
||||
end;
|
||||
if v_ging then
|
||||
raise exception '3: VL 9 wurde angenommen.';
|
||||
raise exception '3: FL 8 wurde angenommen.';
|
||||
end if;
|
||||
raise notice '3/9 Abgewiesen: Bonus ohne Regelung, abgeschaltete HR, „Süßwaren", VL 9';
|
||||
raise notice '3/9 Abgewiesen: Bonus ohne Regelung, abgeschaltete HR, „Süßwaren", FL 8';
|
||||
|
||||
-- ── 4. Daten ändern, sofort ────────────────────────────────────
|
||||
perform change_employee_data(jsonb_build_object(
|
||||
@@ -253,7 +253,7 @@ declare
|
||||
v_e employees%rowtype;
|
||||
v_a uuid := (select id from employees where last_name = 'Test-A' and first_name = 'Vertrag');
|
||||
v_p3 uuid := (select p.id from om_positions p join jobs j on j.id = p.job_id where j.title = 'Vertragstest Drei');
|
||||
v_ort uuid := (select id from locations order by name limit 1);
|
||||
v_ort uuid := (select l.id from locations l where not exists (select 1 from locations u where u.parent_id = l.id) order by l.name limit 1);
|
||||
begin
|
||||
perform apply_due_pending_changes();
|
||||
select * into v_e from employees where id = v_b;
|
||||
@@ -271,16 +271,16 @@ begin
|
||||
'employee_id', v_a, 'rehire_date', current_date::text, 'position_id', v_p3,
|
||||
'first_name', 'Vertrag', 'last_name', 'Test-A', 'gender', 'w',
|
||||
'birth_date', '1990-01-01', 'nationality', 'Österreich', 'location_id', v_ort,
|
||||
'vl', 8, 'has_bonusanspruch', false, 'zustaendige_hr_id', v_hr1,
|
||||
'vl', 6, 'has_bonusanspruch', false, 'zustaendige_hr_id', v_hr1,
|
||||
'collective_agreement', 'Süßware Angestellter', 'erlernter_beruf', 'Bäckerin'));
|
||||
select * into v_e from employees where id = v_a;
|
||||
if v_e.vl <> 8 or v_e.has_bonusanspruch or v_e.bonusanspruch_art is not null
|
||||
if v_e.vl <> 6 or v_e.has_bonusanspruch or v_e.bonusanspruch_art is not null
|
||||
or v_e.zustaendige_hr_id <> v_hr1 or v_e.collective_agreement::text <> 'Süßware Angestellter'
|
||||
or v_e.erlernter_beruf is distinct from 'Bäckerin' then
|
||||
raise exception '9: Wiedereintritt hat VL/Bonus/HR/KV nicht übernommen: % % % % %',
|
||||
v_e.vl, v_e.has_bonusanspruch, v_e.bonusanspruch_art, v_e.zustaendige_hr_id, v_e.collective_agreement;
|
||||
end if;
|
||||
raise notice '9/9 Wiedereintritt übernimmt VL 8, Bonus Nein, HR und Süßware Angestellter';
|
||||
raise notice '9/9 Wiedereintritt übernimmt FL 6, Bonus Nein, HR und Süßware Angestellter';
|
||||
|
||||
raise notice 'Vertragsangaben-Rauchtest bestanden. Alles Angelegte wird gleich verworfen.';
|
||||
end
|
||||
|
||||
@@ -46,6 +46,11 @@ CRON_SECRET={{CRON_SECRET}}
|
||||
# betroffen.
|
||||
# LOLYO_STARTPASSWORT=
|
||||
|
||||
# Nur auf einer Testinstallation: jede Seite traegt dann oben den Schriftzug
|
||||
# "Testsystem", und der Titel im Browser-Tab beginnt damit. In der Produktion
|
||||
# auskommentiert lassen.
|
||||
# TESTSYSTEM=1
|
||||
|
||||
# Nur wenn der Server ins Internet ueber einen Proxy muss: Node.js liest die
|
||||
# Proxy-Einstellung von Windows NICHT, ohne diese Zeilen scheitert die
|
||||
# Anmeldung am Abruf von login.microsoftonline.com. konfiguration-anwenden.ps1
|
||||
|
||||
@@ -16,6 +16,12 @@ an ihnen vorbeiginge, bekäme von der Datenbank trotzdem keine Zeile.
|
||||
|
||||
- **Microsoft Entra ID**, angebunden über Auth.js. Es gibt keine eigenen
|
||||
Passwörter und keinen zweiten Anmeldeweg.
|
||||
<!-- intern:start -->
|
||||
- *Intern, nicht in der Übergabe:* Auf `master` besteht für den Testbetrieb
|
||||
vorübergehend zusätzlich eine Anmeldung mit Passwort. Der Übergabestand
|
||||
enthält sie nicht (Zusatz-Branch `uebergabe-ohne-passwort`, siehe
|
||||
`uebergabe/README.md`).
|
||||
<!-- intern:end -->
|
||||
- **Ein Mandant.** Der Aussteller trägt die Verzeichnis-ID
|
||||
(`AUTH_MICROSOFT_ENTRA_ID_ISSUER`). Fehlt er, startet die Anwendung im
|
||||
Produktionsbetrieb nicht — sonst stünde die Anmeldung über `/common/` jedem
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// Wie gespeicherte Werte angezeigt und exportiert werden, wo die fachliche
|
||||
// Bezeichnung vom gespeicherten Wert abweicht.
|
||||
//
|
||||
// Drei Fälle, alle fachlich vorgegeben (der dritte, das Datum, steht unten):
|
||||
// Vier Fälle, alle fachlich vorgegeben (Datum und Ende der Abwesenheit
|
||||
// stehen unten):
|
||||
//
|
||||
// * Nicht gendern. Gespeichert bleibt „Angestellte:r", „Arbeiter:in",
|
||||
// „Praktikant:in", „Ehepartner:in", „Lebenspartner:in"; angezeigt wird
|
||||
@@ -40,6 +41,21 @@ const REGELN: readonly (readonly [RegExp, string])[] = [
|
||||
// Ganze Wörter, die fachlich anders heissen als gespeichert.
|
||||
const UMBENANNT: readonly (readonly [RegExp, string])[] = [
|
||||
[new RegExp(`(?<![${BUCHSTABE}])Schwangerschaft(?![${BUCHSTABE}])`, "g"), "Mutterschutz"],
|
||||
// Das Feld „VL" der Historie heisst fachlich „FL" (Migration 20261201120000).
|
||||
[new RegExp(`(?<![${BUCHSTABE}])VL(?![${BUCHSTABE}])`, "g"), "FL"],
|
||||
];
|
||||
|
||||
// Das Ende einer Langzeitabwesenheit heisst fachlich „Endet am", nicht
|
||||
// „Rückkehr". Gespeichert bleibt das Datum, an dem die Person zurück ist, und
|
||||
// mit ihm die Texte der Datenbank: „Elternkarenz, geplante Rückkehr am …",
|
||||
// „Rückkehr aus Elternkarenz am …" und das Feld „Geplante Rückkehr". Nur
|
||||
// diese drei Formen mit einem Datum dahinter; die Rückkehr als Ereignis
|
||||
// behält ihren Namen. Läuft nach der Datumsumstellung, deshalb TT.MM.JJJJ.
|
||||
const DATUM_TMJ = String.raw`\d{2}\.\d{2}\.\d{4}`;
|
||||
const ABWESENHEIT_ENDE: readonly (readonly [RegExp, string])[] = [
|
||||
[new RegExp(`geplante Rückkehr (?:am )?(${DATUM_TMJ})`, "g"), "endet am $1"],
|
||||
[new RegExp(`(?<![${BUCHSTABE}])Rückkehr aus ([^,]+?) am (${DATUM_TMJ})`, "g"), "$1 endet am $2"],
|
||||
[/^Geplante Rückkehr$/, "Endet am"],
|
||||
];
|
||||
|
||||
// Ein Datum in einem Text, den die Datenbank zusammensetzt („wirksam ab
|
||||
@@ -56,6 +72,9 @@ export function anzeige(text: string | null | undefined): string | null | undefi
|
||||
if (!text) return text;
|
||||
let ergebnis = text.replace(ISO_DATUM, "$3.$2.$1");
|
||||
for (const [muster, ersatz] of UMBENANNT) ergebnis = ergebnis.replace(muster, ersatz);
|
||||
if (ergebnis.includes("ückkehr")) {
|
||||
for (const [muster, ersatz] of ABWESENHEIT_ENDE) ergebnis = ergebnis.replace(muster, ersatz);
|
||||
}
|
||||
if (!ergebnis.includes(":")) return ergebnis;
|
||||
for (const [gegendert, ungegendert] of AUSNAHMEN) ergebnis = ergebnis.split(gegendert).join(ungegendert);
|
||||
for (const [muster, ersatz] of REGELN) ergebnis = ergebnis.replace(muster, ersatz);
|
||||
|
||||
@@ -18,12 +18,13 @@
|
||||
// nichts aus, und eine Summe, die nicht aufgeht, ist schlechter als keine
|
||||
// Angabe — sie sieht aus wie eine.
|
||||
//
|
||||
// ── Warum in Zehnteln gerechnet wird ──────────────────────────────────────
|
||||
// ── Warum in Hundertsteln gerechnet wird ──────────────────────────────────
|
||||
//
|
||||
// `weekly_hours` ist numeric(4,1), die Eingaben sind es auch. In
|
||||
// Gleitkommazahlen trifft 7,7 × 5 die 38,5 trotzdem nicht (38,49999…), und
|
||||
// die Prüfung „exakt gleich" schlüge bei einer völlig richtigen Eingabe fehl.
|
||||
// Gerechnet wird deshalb in ganzen Zehntelstunden.
|
||||
// `weekly_hours` ist numeric(4,2), die Eingaben sind es auch: 19,25 Stunden
|
||||
// verteilen sich etwa als 3,85 an fünf Tagen. In Gleitkommazahlen trifft
|
||||
// 7,7 × 5 die 38,5 trotzdem nicht (38,49999…), und die Prüfung „exakt
|
||||
// gleich" schlüge bei einer völlig richtigen Eingabe fehl. Gerechnet wird
|
||||
// deshalb in ganzen Hundertstelstunden.
|
||||
|
||||
import type { Weekday } from "./types";
|
||||
|
||||
@@ -41,13 +42,18 @@ export type ArbeitszeitBefund = {
|
||||
fehler: string | null;
|
||||
};
|
||||
|
||||
/** Zehntelstunden als ganze Zahl; null, wenn das Feld leer oder keine Zahl ist. */
|
||||
function zehntel(wert: string | undefined): number | null {
|
||||
/** Hundertstelstunden als ganze Zahl; null, wenn das Feld leer oder keine Zahl ist. */
|
||||
function hundertstel(wert: string | undefined): number | null {
|
||||
const roh = (wert ?? "").trim().replace(",", ".");
|
||||
if (roh === "") return null;
|
||||
const zahl = Number(roh);
|
||||
if (!Number.isFinite(zahl)) return null;
|
||||
return Math.round(zahl * 10);
|
||||
return Math.round(zahl * 100);
|
||||
}
|
||||
|
||||
/** Mehr als zwei Nachkommastellen lassen sich nicht so speichern, wie sie dastehen. */
|
||||
function zuGenau(wert: string | undefined): boolean {
|
||||
return /[.,]\d{3,}$/.test((wert ?? "").trim());
|
||||
}
|
||||
|
||||
export function arbeitszeitBefund(
|
||||
@@ -55,20 +61,23 @@ export function arbeitszeitBefund(
|
||||
tage: readonly Weekday[],
|
||||
wochenstunden: number
|
||||
): ArbeitszeitBefund {
|
||||
const werte = tage.map((tag) => zehntel(modell[tag]));
|
||||
const werte = tage.map((tag) => hundertstel(modell[tag]));
|
||||
const erfasst = werte.some((w) => w !== null);
|
||||
const summeZehntel = werte.reduce<number>((s, w) => s + (w ?? 0), 0);
|
||||
const summe = summeZehntel / 10;
|
||||
const summeHundertstel = werte.reduce<number>((s, w) => s + (w ?? 0), 0);
|
||||
const summe = summeHundertstel / 100;
|
||||
|
||||
if (!erfasst) return { erfasst: false, summe: 0, fehler: null };
|
||||
|
||||
if (werte.some((w) => w === null)) {
|
||||
return { erfasst, summe, fehler: "Für jeden gewählten Arbeitstag müssen Stunden eingetragen sein." };
|
||||
}
|
||||
if (tage.some((tag) => zuGenau(modell[tag]))) {
|
||||
return { erfasst, summe, fehler: "Stunden je Arbeitstag haben höchstens zwei Nachkommastellen." };
|
||||
}
|
||||
if (werte.some((w) => (w as number) <= 0)) {
|
||||
return { erfasst, summe, fehler: "An einem Arbeitstag müssen mehr als 0 Stunden stehen." };
|
||||
}
|
||||
const zuviel = tage.filter((_, i) => (werte[i] as number) > MAX_STUNDEN_JE_TAG * 10);
|
||||
const zuviel = tage.filter((_, i) => (werte[i] as number) > MAX_STUNDEN_JE_TAG * 100);
|
||||
if (zuviel.length > 0) {
|
||||
return {
|
||||
erfasst,
|
||||
@@ -76,7 +85,7 @@ export function arbeitszeitBefund(
|
||||
fehler: `An einem Arbeitstag sind höchstens ${MAX_STUNDEN_JE_TAG} Stunden möglich (${zuviel.join(", ")}).`,
|
||||
};
|
||||
}
|
||||
if (summeZehntel !== Math.round(wochenstunden * 10)) {
|
||||
if (summeHundertstel !== Math.round(wochenstunden * 100)) {
|
||||
return {
|
||||
erfasst,
|
||||
summe,
|
||||
@@ -98,8 +107,8 @@ export function arbeitszeitFuerDb(
|
||||
): Record<string, number> | null {
|
||||
const eintraege: Record<string, number> = {};
|
||||
for (const tag of tage) {
|
||||
const z = zehntel(modell[tag]);
|
||||
if (z !== null) eintraege[tag] = z / 10;
|
||||
const h = hundertstel(modell[tag]);
|
||||
if (h !== null) eintraege[tag] = h / 100;
|
||||
}
|
||||
return Object.keys(eintraege).length > 0 ? eintraege : null;
|
||||
}
|
||||
@@ -114,7 +123,7 @@ export function arbeitszeitAusDb(gespeichert: unknown): Arbeitszeitmodell {
|
||||
return modell;
|
||||
}
|
||||
|
||||
/** 38,5 statt 38.5 — und 8 statt 8,0. */
|
||||
/** 38,5 statt 38.5, 19,25 statt 19.25 — und 8 statt 8,0. */
|
||||
export function formatStunden(stunden: number): string {
|
||||
return (Math.round(stunden * 10) / 10).toLocaleString("de-AT", { maximumFractionDigits: 1 });
|
||||
return (Math.round(stunden * 100) / 100).toLocaleString("de-AT", { maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ export type Format =
|
||||
| { art: "text" }
|
||||
| { art: "datum" }
|
||||
| { art: "zahl"; nachkomma: number }
|
||||
/** Mit `bereich` nur Werte von–bis (VL 1–8). */
|
||||
/** Mit `bereich` nur Werte von–bis (FL 1–7). */
|
||||
| { art: "ganzzahl"; bereich?: readonly [number, number] }
|
||||
| { art: "janein" }
|
||||
/**
|
||||
|
||||
@@ -5,6 +5,7 @@ import { fmtName } from "../format";
|
||||
import { pruefePlz } from "../plz";
|
||||
import { requiresAustrianSvnr, svnrErrorMessage, svnrHaeltAuf, validateSvnr } from "../svnr";
|
||||
import type { Database } from "../types";
|
||||
import { SONSTIGE, verhaeltnisAusDatei } from "../verhaeltnis";
|
||||
import { pruefsumme } from "./abgleich";
|
||||
import { BLAETTER, WIRKSAM_AB, type Blatt, type Spalte } from "./katalog";
|
||||
import {
|
||||
@@ -158,7 +159,7 @@ async function rufe(tx: Tx, fn: MutationFn, payload: Record<string, unknown>): P
|
||||
|
||||
/** Lookups, die sich mit jedem Blatt ändern können: was die Datei neu anlegt, gilt sofort. */
|
||||
type Bestand = {
|
||||
standorte: Map<string, { id: string; name: string; country: string }>;
|
||||
standorte: Map<string, { id: string; name: string; country: string; parent_id: string | null }>;
|
||||
kostenstellen: Map<string, { id: string; name: string }>;
|
||||
einheiten: Map<string, Record<string, unknown> & { id: string }>;
|
||||
planstellen: Map<string, Record<string, unknown> & { id: string }>;
|
||||
@@ -168,7 +169,7 @@ type Bestand = {
|
||||
|
||||
async function bestandLaden(tx: Tx, heute: string): Promise<Bestand> {
|
||||
const [standorte, kostenstellen, einheiten, planstellen, personen, hr] = await Promise.all([
|
||||
tx.selectFrom("locations").select(["id", "name", "country"]).execute(),
|
||||
tx.selectFrom("locations").select(["id", "name", "country", "parent_id"]).execute(),
|
||||
tx.selectFrom("cost_centers").select(["id", "code", "name"]).execute(),
|
||||
tx
|
||||
.selectFrom("org_units as u")
|
||||
@@ -649,6 +650,15 @@ function mitarbeiterZeile(
|
||||
const planstelle = (n: unknown) => bestand.planstellen.get(String(n));
|
||||
if (zeile.wert("location_id") && !standortId(zeile.wert("location_id"))) {
|
||||
zeile.fehler(`Den Standort „${String(zeile.wert("location_id"))}“ gibt es nicht (auch nicht im Blatt „Standorte“).`, "location_id");
|
||||
} else if (zeile.wert("location_id")) {
|
||||
const id = standortId(zeile.wert("location_id"));
|
||||
const unter = [...bestand.standorte.values()].filter((s) => s.parent_id === id).map((s) => s.name);
|
||||
if (unter.length > 0) {
|
||||
zeile.fehler(
|
||||
`„${String(zeile.wert("location_id"))}“ fasst mehrere Standorte zusammen. Bitte einen davon angeben: ${unter.sort((a, b) => a.localeCompare(b, "de")).join(", ")}.`,
|
||||
"location_id"
|
||||
);
|
||||
}
|
||||
}
|
||||
if (zeile.wert("zustaendige_hr_id") && !hrId(zeile.wert("zustaendige_hr_id"))) {
|
||||
zeile.fehler(`„${String(zeile.wert("zustaendige_hr_id"))}“ ist kein aktives HR-Konto.`, "zustaendige_hr_id");
|
||||
@@ -943,6 +953,34 @@ function eintragZu(zeile: Zeile, aktuell: Datensaetze, person: Person) {
|
||||
return eintrag;
|
||||
}
|
||||
|
||||
/**
|
||||
* Das Verhältnis, wie es gespeichert wird: aus der Auswahl und dem Text zu
|
||||
* „Sonstige" (lib/verhaeltnis.ts). Steht eine der beiden Spalten nicht in
|
||||
* der Zeile, gilt der bisherige Wert — der Text aber nur, solange
|
||||
* „Sonstige" gewählt bleibt. `undefined` bei einem Widerspruch.
|
||||
*/
|
||||
function verhaeltnisDerZeile(zeile: Zeile, feld: string, alt: Record<string, unknown> | null): string | null | undefined {
|
||||
const textFeld = `${feld}_sonstige`;
|
||||
const auswahl = (zeile.gesetzt(feld) ? zeile.wert(feld) : alt?.[feld]) as string | null | undefined;
|
||||
const text = (zeile.gesetzt(textFeld) ? zeile.wert(textFeld) : auswahl === SONSTIGE ? alt?.[textFeld] : null) as
|
||||
| string
|
||||
| null
|
||||
| undefined;
|
||||
const ergebnis = verhaeltnisAusDatei(auswahl, text);
|
||||
if ("fehler" in ergebnis) {
|
||||
zeile.fehler(ergebnis.fehler, textFeld);
|
||||
return undefined;
|
||||
}
|
||||
return ergebnis.wert;
|
||||
}
|
||||
|
||||
/** Die geänderten Felder für die SQL-Funktion: Auswahl und Text als ein Verhältnis. */
|
||||
function mitVerhaeltnis(g: Map<string, unknown>, feld: string, wert: string | null): Record<string, unknown> {
|
||||
const out = Object.fromEntries(g);
|
||||
delete out[`${feld}_sonstige`];
|
||||
return { ...out, [feld]: wert };
|
||||
}
|
||||
|
||||
function angehoerigerZeile(tx: Tx, zeile: Zeile, bestand: Bestand, aktuell: Datensaetze, { modus, heute }: { modus: Modus; heute: string }) {
|
||||
const person = personZu(zeile, bestand);
|
||||
if (!person) return;
|
||||
@@ -953,9 +991,15 @@ function angehoerigerZeile(tx: Tx, zeile: Zeile, bestand: Bestand, aktuell: Date
|
||||
if (eintrag === null) {
|
||||
if (zeile.wert("entfernen") === "ja") return zeile.fehler("Ein neuer Eintrag lässt sich nicht entfernen.", "entfernen");
|
||||
if (!pflichtNeu(zeile)) return;
|
||||
const verhaeltnis = verhaeltnisDerZeile(zeile, "relationship", null);
|
||||
if (verhaeltnis === undefined) return;
|
||||
const g = zeile.geaendert(null);
|
||||
zeile.schritt("Angehörige:r angelegt", "last_name", async () => {
|
||||
await rufe(tx, "add_employee_dependent", { employee_id: person.id, effective_date: datum, ...Object.fromEntries(g) });
|
||||
await rufe(tx, "add_employee_dependent", {
|
||||
employee_id: person.id,
|
||||
effective_date: datum,
|
||||
...mitVerhaeltnis(g, "relationship", verhaeltnis),
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -968,6 +1012,8 @@ function angehoerigerZeile(tx: Tx, zeile: Zeile, bestand: Bestand, aktuell: Date
|
||||
});
|
||||
return;
|
||||
}
|
||||
const verhaeltnis = verhaeltnisDerZeile(zeile, "relationship", eintrag.werte);
|
||||
if (verhaeltnis === undefined) return;
|
||||
const g = zeile.geaendert(eintrag.werte, (f) => f !== "id" && f !== "entfernen");
|
||||
if (g.size === 0) return;
|
||||
const neu = { ...eintrag.werte, ...Object.fromEntries(g) };
|
||||
@@ -976,7 +1022,7 @@ function angehoerigerZeile(tx: Tx, zeile: Zeile, bestand: Bestand, aktuell: Date
|
||||
dependent_id: id,
|
||||
first_name: neu.first_name,
|
||||
last_name: neu.last_name,
|
||||
relationship: neu.relationship,
|
||||
relationship: verhaeltnis,
|
||||
birth_date: neu.birth_date ?? "",
|
||||
sv_nummer: neu.sv_nummer ?? "",
|
||||
});
|
||||
@@ -993,9 +1039,11 @@ function notfallkontaktZeile(tx: Tx, zeile: Zeile, bestand: Bestand, aktuell: Da
|
||||
if (eintrag === null) {
|
||||
if (zeile.wert("entfernen") === "ja") return zeile.fehler("Ein neuer Eintrag lässt sich nicht entfernen.", "entfernen");
|
||||
if (!pflichtNeu(zeile)) return;
|
||||
const verhaeltnis = verhaeltnisDerZeile(zeile, "relation", null);
|
||||
if (verhaeltnis === undefined) return;
|
||||
const g = zeile.geaendert(null);
|
||||
zeile.schritt("Notfallkontakt angelegt", "name", async () => {
|
||||
await rufe(tx, "add_emergency_contact", { employee_id: person.id, ...Object.fromEntries(g) });
|
||||
await rufe(tx, "add_emergency_contact", { employee_id: person.id, ...mitVerhaeltnis(g, "relation", verhaeltnis) });
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -1008,10 +1056,12 @@ function notfallkontaktZeile(tx: Tx, zeile: Zeile, bestand: Bestand, aktuell: Da
|
||||
});
|
||||
return;
|
||||
}
|
||||
const verhaeltnis = verhaeltnisDerZeile(zeile, "relation", eintrag.werte);
|
||||
if (verhaeltnis === undefined) return;
|
||||
const g = zeile.geaendert(eintrag.werte, (f) => f !== "id" && f !== "entfernen");
|
||||
if (g.size === 0) return;
|
||||
const neu = { ...eintrag.werte, ...Object.fromEntries(g) };
|
||||
zeile.schritt("Notfallkontakt geändert", [...g.keys()][0], async () => {
|
||||
await rufe(tx, "update_emergency_contact", { id, name: neu.name, phone: neu.phone, relation: neu.relation ?? "" });
|
||||
await rufe(tx, "update_emergency_contact", { id, name: neu.name, phone: neu.phone, relation: verhaeltnis ?? "" });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -227,7 +227,7 @@ const MITARBEITER_ROH: Spalte[] = [
|
||||
feld("Vertrag und Arbeitszeit", "Beschäftigungsausmaß", "Beschäftigungsausmaß", "employment_type", auswahlAusKarte("Beschäftigungsausmaß"), {
|
||||
hinweis: STUNDEN_HINWEIS,
|
||||
}),
|
||||
feld("Vertrag und Arbeitszeit", "Wochenstunden", "Wochenstunden", "weekly_hours", { art: "zahl", nachkomma: 1 }, {
|
||||
feld("Vertrag und Arbeitszeit", "Wochenstunden", "Wochenstunden", "weekly_hours", { art: "zahl", nachkomma: 2 }, {
|
||||
hinweis: STUNDEN_HINWEIS,
|
||||
}),
|
||||
feld("Vertrag und Arbeitszeit", "Arbeitstage", "Arbeitstage", "work_days", {
|
||||
@@ -256,7 +256,7 @@ const MITARBEITER_ROH: Spalte[] = [
|
||||
}),
|
||||
// Eine Zahl, wie in der Spalte; in Excel eine Auswahl 1 bis 8. Die Auswahl
|
||||
// in „Eintrag berichtigen" führt sie als Text.
|
||||
feld("Vertrag und Arbeitszeit", "VL", "VL", "vl", { art: "ganzzahl", bereich: [VL_STUFEN[0], VL_STUFEN[VL_STUFEN.length - 1]] }),
|
||||
feld("Vertrag und Arbeitszeit", "FL", "VL", "vl", { art: "ganzzahl", bereich: [VL_STUFEN[0], VL_STUFEN[VL_STUFEN.length - 1]] }),
|
||||
feld("Vertrag und Arbeitszeit", "Bonusanspruch", "Bonusanspruch", "has_bonusanspruch", JA_NEIN),
|
||||
feld("Vertrag und Arbeitszeit", "Bonusregelung", "Bonusregelung", "bonusanspruch_art", auswahlAusKarte("Bonusregelung"), {
|
||||
hinweis: "Pflicht bei Bonusanspruch „Ja“, sonst leer.",
|
||||
@@ -273,7 +273,9 @@ const MITARBEITER_ROH: Spalte[] = [
|
||||
hinweis: "Pflicht bei Dienstwagen „Ja“.",
|
||||
}),
|
||||
feld("Vertrag und Arbeitszeit", "Laterale Führung", "Laterale Führung", "is_laterale_fuehrung", JA_NEIN),
|
||||
feld("Vertrag und Arbeitszeit", "C-Level", "C-Level", "is_c_level", JA_NEIN),
|
||||
feld("Vertrag und Arbeitszeit", "C-Level", "C-Level", "c_level", auswahlAusKarte("C-Level"), {
|
||||
hinweis: "Der Code aus der Liste, etwa „C9“.",
|
||||
}),
|
||||
feld("Vertrag und Arbeitszeit", "Besonderer Kündigungsschutz", "Besonderer Kündigungsschutz", "has_kuendigungsschutz", JA_NEIN),
|
||||
feld("Vertrag und Arbeitszeit", "Personenkreis", "Kündigungsschutz Personenkreis", "kuendigungsschutz_grund", auswahlAusKarte("Kündigungsschutz Personenkreis"), {
|
||||
hinweis: KUENDIGUNGSSCHUTZ_HINWEIS,
|
||||
@@ -328,7 +330,7 @@ const MITARBEITER_ROH: Spalte[] = [
|
||||
{
|
||||
titel: "Wochenstunden ab Rückkehr",
|
||||
feld: "rueckkehr_stunden",
|
||||
format: { art: "zahl", nachkomma: 1 },
|
||||
format: { art: "zahl", nachkomma: 2 },
|
||||
thema: "Langzeitabwesenheit",
|
||||
hinweis: "Pflicht bei „Reduziert“; weniger als 38,5.",
|
||||
},
|
||||
@@ -403,7 +405,7 @@ const MITARBEITER_ROH: Spalte[] = [
|
||||
const IMMER_BELEGT = new Set([
|
||||
"last_name", "first_name", "gender", "nationality", "location_id", "position_number", "job_title", "entry_date",
|
||||
"employment_type", "weekly_hours", "contract_type", "source", "worker_type", "mitarbeiterart", "collective_agreement",
|
||||
"work_days", "is_betriebsrat", "has_dienstwagen", "is_laterale_fuehrung", "is_c_level", "has_kuendigungsschutz",
|
||||
"work_days", "is_betriebsrat", "has_dienstwagen", "is_laterale_fuehrung", "has_kuendigungsschutz",
|
||||
"hat_aufenthaltstitel", "ist_beguenstigt_behindert", "has_bonusanspruch", "ist_uebernahme_leiharbeit",
|
||||
]);
|
||||
|
||||
@@ -469,8 +471,22 @@ const PERSONALNUMMER_VERWEIS: Spalte = {
|
||||
pflicht: true,
|
||||
};
|
||||
|
||||
/** Verhältnis bei Angehörigen und Notfallkontakten: Liste oder eigener Text. */
|
||||
const VERHAELTNIS: Format = { art: "auswahl", optionen: anzeigeAuswahl(EMERGENCY_RELATIONS), frei: true };
|
||||
/**
|
||||
* Verhältnis bei Angehörigen und Notfallkontakten: die Liste wie im Formular,
|
||||
* und für „Sonstige" eine Spalte daneben mit dem eigenen Text
|
||||
* (lib/verhaeltnis.ts).
|
||||
*/
|
||||
const VERHAELTNIS: Format = { art: "auswahl", optionen: anzeigeAuswahl(EMERGENCY_RELATIONS) };
|
||||
const VERHAELTNIS_HINWEIS = "Aus der Liste. Ist es keines davon: „Sonstige“ und den Text in der Spalte daneben.";
|
||||
|
||||
function verhaeltnisSonstige(feld: string): Spalte {
|
||||
return {
|
||||
titel: "Verhältnis (Sonstige)",
|
||||
feld,
|
||||
format: TEXT,
|
||||
hinweis: "Nur bei „Sonstige“, etwa Onkel oder Nachbarin. Leer bleibt es bei „Sonstige“.",
|
||||
};
|
||||
}
|
||||
|
||||
const ENTFERNEN: Spalte = {
|
||||
titel: "Entfernen",
|
||||
@@ -485,6 +501,7 @@ export const BLATT_ANGEHOERIGE: Blatt = {
|
||||
zweck: "Angehörige je Person. Leere ID = neu anlegen.",
|
||||
schluessel: PERSONALNUMMER_VERWEIS,
|
||||
wirksamAb: "Leer = heute. Gilt für Neuanlage und Entfernen.",
|
||||
bedingungen: [{ feld: "relationship_sonstige", art: "leer", wenn: { feld: "relationship", nicht: "Sonstige" } }],
|
||||
spalten: [
|
||||
{ titel: "ID", feld: "id", format: TEXT, hinweis: "Vergibt das System. Leer = neuer Eintrag." },
|
||||
{ titel: "Nachname", feld: "last_name", format: TEXT, pflichtNeu: true, pflicht: true },
|
||||
@@ -495,8 +512,9 @@ export const BLATT_ANGEHOERIGE: Blatt = {
|
||||
format: VERHAELTNIS,
|
||||
pflichtNeu: true,
|
||||
pflicht: true,
|
||||
hinweis: "Aus der Liste oder frei eingetragen, wie „Sonstige“ in der Personalakte.",
|
||||
hinweis: VERHAELTNIS_HINWEIS,
|
||||
},
|
||||
verhaeltnisSonstige("relationship_sonstige"),
|
||||
{ titel: "Geburtsdatum", feld: "birth_date", format: DATUM },
|
||||
{ titel: "SV-Nummer", feld: "sv_nummer", format: TEXT },
|
||||
ENTFERNEN,
|
||||
@@ -508,6 +526,7 @@ export const BLATT_NOTFALLKONTAKTE: Blatt = {
|
||||
zweck: "Notfallkontakte je Person. Leere ID = neu anlegen.",
|
||||
schluessel: PERSONALNUMMER_VERWEIS,
|
||||
wirksamAb: "Leer lassen: Notfallkontakte gelten sofort.",
|
||||
bedingungen: [{ feld: "relation_sonstige", art: "leer", wenn: { feld: "relation", nicht: "Sonstige" } }],
|
||||
spalten: [
|
||||
{ titel: "ID", feld: "id", format: TEXT, hinweis: "Vergibt das System. Leer = neuer Eintrag." },
|
||||
{ titel: "Name", feld: "name", format: TEXT, pflichtNeu: true, pflicht: true },
|
||||
@@ -516,8 +535,9 @@ export const BLATT_NOTFALLKONTAKTE: Blatt = {
|
||||
titel: "Verhältnis",
|
||||
feld: "relation",
|
||||
format: VERHAELTNIS,
|
||||
hinweis: "Aus der Liste oder frei eingetragen, wie „Sonstige“ in der Personalakte.",
|
||||
hinweis: VERHAELTNIS_HINWEIS,
|
||||
},
|
||||
verhaeltnisSonstige("relation_sonstige"),
|
||||
ENTFERNEN,
|
||||
],
|
||||
};
|
||||
|
||||
@@ -8,6 +8,7 @@ import { loadOrgMaps, type OrgMaps } from "../org";
|
||||
import { loadPlacements, loadReportingLineMap, type Placement } from "../placement";
|
||||
import { deriveStatusAsOf } from "../reports";
|
||||
import type { Database } from "../types";
|
||||
import { verhaeltnisFuerDatei } from "../verhaeltnis";
|
||||
import type { Listen } from "./herunterladen";
|
||||
import type { Datensatz } from "./herunterladen";
|
||||
|
||||
@@ -132,7 +133,14 @@ export async function ladeAngehoerige(tx: Tx, personen: readonly Person[]): Prom
|
||||
.orderBy("employee_id")
|
||||
.orderBy("created_at")
|
||||
.execute();
|
||||
return zeilen.map((z) => ({ schluessel: nummer.get(z.employee_id)!, kennung: z.id, werte: { ...z } }));
|
||||
return zeilen.map((z) => {
|
||||
const v = verhaeltnisFuerDatei(z.relationship);
|
||||
return {
|
||||
schluessel: nummer.get(z.employee_id)!,
|
||||
kennung: z.id,
|
||||
werte: { ...z, relationship: v.auswahl, relationship_sonstige: v.sonstige },
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function ladeNotfallkontakte(tx: Tx, personen: readonly Person[]): Promise<Datensatz[]> {
|
||||
@@ -145,7 +153,14 @@ export async function ladeNotfallkontakte(tx: Tx, personen: readonly Person[]):
|
||||
.orderBy("employee_id")
|
||||
.orderBy("created_at")
|
||||
.execute();
|
||||
return zeilen.map((z) => ({ schluessel: nummer.get(z.employee_id)!, kennung: z.id, werte: { ...z } }));
|
||||
return zeilen.map((z) => {
|
||||
const v = verhaeltnisFuerDatei(z.relation);
|
||||
return {
|
||||
schluessel: nummer.get(z.employee_id)!,
|
||||
kennung: z.id,
|
||||
werte: { ...z, relation: v.auswahl, relation_sonstige: v.sonstige },
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function ladeHistorie(tx: Tx, personen: readonly Person[], b: Bezuege): Promise<Datensatz[]> {
|
||||
@@ -242,7 +257,13 @@ export async function ladeStandorte(tx: Tx): Promise<Datensatz[]> {
|
||||
*/
|
||||
export async function ladeListen(tx: Tx, heute: string): Promise<Listen> {
|
||||
const [standorte, jobs, einheiten, stellen, kostenstellen, hr] = await Promise.all([
|
||||
tx.selectFrom("locations").select("name").orderBy("name").execute(),
|
||||
// Ohne zusammenfassende Standorte wie „Shop": auf ihnen sitzt niemand.
|
||||
tx
|
||||
.selectFrom("locations as l")
|
||||
.select("l.name")
|
||||
.where((eb) => eb.not(eb.exists(eb.selectFrom("locations as u").select("u.id").whereRef("u.parent_id", "=", "l.id"))))
|
||||
.orderBy("l.name")
|
||||
.execute(),
|
||||
tx.selectFrom("jobs").select("title").execute(),
|
||||
tx.selectFrom("org_units").select("org_number").where("valid_to", "is", null).orderBy("org_number").execute(),
|
||||
// Nur freie Planstellen: niemand sitzt heute oder später darauf, keine
|
||||
|
||||
@@ -80,7 +80,9 @@ export const GRUPPE_JE_FELD: Readonly<Record<string, "person" | "contract" | "ro
|
||||
is_betriebsrat: "role",
|
||||
has_dienstwagen: "role",
|
||||
is_laterale_fuehrung: "role",
|
||||
// Abgelöst durch c_level; die Feldkarte führt es weiter für ältere Einträge.
|
||||
is_c_level: "role",
|
||||
c_level: "role",
|
||||
dienstwagen_art: "role",
|
||||
lehrzeit_von: "role",
|
||||
lehrzeit_bis: "role",
|
||||
|
||||
@@ -12,9 +12,10 @@ import { currentUserId } from "./session";
|
||||
//
|
||||
// Gefragt wird is_hr_user() und nicht profiles.role/is_active von Hand.
|
||||
// Der Unterschied ist nicht kosmetisch: is_hr_user() ist dieselbe Funktion, die
|
||||
// alle RLS-Policies aufrufen. Was immer sie prüft, gilt hier automatisch mit.
|
||||
// Eine Prüfung von Hand liefe ihr mit der Zeit davon und lieferte einen
|
||||
// Export aus, den die Policies darunter leer liessen.
|
||||
// alle RLS-Policies aufrufen. Was immer sie zusätzlich prüft, gilt hier
|
||||
// automatisch mit — etwa der ausstehende Passwortwechsel (Migration
|
||||
// 20260908120000). Eine Prüfung von Hand wüsste davon nichts und lieferte
|
||||
// einen Export aus, den die Policies darunter leer liessen.
|
||||
|
||||
export type HrGate = { denied: NextResponse } | { userId: string };
|
||||
|
||||
|
||||
@@ -50,10 +50,10 @@ function arbeitszeitmodellFehler(text: string, stunden: string | undefined, tage
|
||||
}
|
||||
}
|
||||
if (stunden !== undefined) {
|
||||
// In Zehnteln gerechnet, wie lib/arbeitszeit.ts: 7,7 × 5 verfehlte sonst die 38,5.
|
||||
const summe = werte.reduce((s, w) => s + Math.round(w * 10), 0);
|
||||
if (summe !== Math.round(Number(stundenWert(stunden)) * 10)) {
|
||||
return `Die Summe des Arbeitszeitmodells beträgt ${String(summe / 10).replace(".", ",")} und muss den Wochenstunden entsprechen.`;
|
||||
// In Hundertsteln gerechnet, wie lib/arbeitszeit.ts: 7,7 × 5 verfehlte sonst die 38,5.
|
||||
const summe = werte.reduce((s, w) => s + Math.round(w * 100), 0);
|
||||
if (summe !== Math.round(Number(stundenWert(stunden)) * 100)) {
|
||||
return `Die Summe des Arbeitszeitmodells beträgt ${String(summe / 100).replace(".", ",")} und muss den Wochenstunden entsprechen.`;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
|
||||
21
lib/c-level.ts
Normal file
21
lib/c-level.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
// C-Level: die Führungs- bzw. Funktionsstufe einer Person als Code.
|
||||
// Fachlich vorgegebene Liste; dieselben Werte stehen in chk_c_level
|
||||
// (Migration 20261123120000) — tests/unit/c-level.test.ts gleicht beide ab.
|
||||
//
|
||||
// Gespeichert und angezeigt wird nur der Code, in Formularen, Akte,
|
||||
// Historie, Berichten, Export und Import gleich.
|
||||
//
|
||||
// Freiwillig: leer heisst „nicht erfasst".
|
||||
|
||||
export const C_LEVEL_CODES = ["C1", "C11", "C2", "C3", "C4", "C8", "C9", "MG", "P", "VD"] as const;
|
||||
|
||||
export type CLevel = (typeof C_LEVEL_CODES)[number];
|
||||
|
||||
/** Für Anzeigen ohne Wert. */
|
||||
export const OHNE_C_LEVEL = "Ohne C-Level";
|
||||
|
||||
/** Auswahl für Formulare: Wert und Beschriftung sind der Code. */
|
||||
export const C_LEVEL_AUSWAHL: readonly { value: CLevel; label: string }[] = C_LEVEL_CODES.map((c) => ({
|
||||
value: c,
|
||||
label: c,
|
||||
}));
|
||||
@@ -23,7 +23,6 @@ const VORGABEN = {
|
||||
is_betriebsrat: false,
|
||||
has_dienstwagen: false,
|
||||
is_laterale_fuehrung: false,
|
||||
is_c_level: false,
|
||||
has_kuendigungsschutz: false,
|
||||
ist_beguenstigt_behindert: false,
|
||||
has_bonusanspruch: false,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ABSENCE_TYPES, KEINE_TEILZEITVARIANTE, STUNDEN_GRUENDE, statusLabel } from "./absence";
|
||||
import { anzeige, anzeigeAuswahl } from "./anzeige";
|
||||
import { C_LEVEL_AUSWAHL } from "./c-level";
|
||||
import { GESCHLECHTER } from "./geschlecht";
|
||||
import { HAY_GRADE_WERTE } from "./hay-grade";
|
||||
import { KOLLEKTIVVERTRAEGE } from "./kollektivvertrag";
|
||||
@@ -88,7 +89,9 @@ export const FELD_OPTIONEN: Record<string, readonly Option[]> = {
|
||||
Dienstwagen: JA_NEIN,
|
||||
Betriebsrat: JA_NEIN,
|
||||
"Laterale Führung": JA_NEIN,
|
||||
"C-Level": JA_NEIN,
|
||||
// Das abgelöste Ja/Nein (is_c_level); ältere Einträge tragen es.
|
||||
"C-Level (Ja/Nein)": JA_NEIN,
|
||||
"C-Level": C_LEVEL_AUSWAHL,
|
||||
"Besonderer Kündigungsschutz": JA_NEIN,
|
||||
"Begünstigt behindert": JA_NEIN,
|
||||
Aufenthaltstitel: JA_NEIN,
|
||||
|
||||
10
lib/notes.ts
10
lib/notes.ts
@@ -81,7 +81,7 @@ export function sichtbareNotizen(userId: string, spalte = "n.author_user_id"): E
|
||||
* formatiert Postgres sie anders als der Treiber es sonst täte, und der
|
||||
* Unterschied fällt erst beim Vergleichen auf.
|
||||
*/
|
||||
export function offeneNotizenAbfrage(eb: OrgEb, userId: string) {
|
||||
export function offeneNotizenAbfrage(eb: OrgEb, userId: string, heute: string) {
|
||||
return eb
|
||||
.selectFrom("employee_notes as n")
|
||||
.leftJoin("employees as e", "e.id", "n.employee_id")
|
||||
@@ -101,6 +101,10 @@ export function offeneNotizenAbfrage(eb: OrgEb, userId: string) {
|
||||
.select((x) => [zeitstempel(x.ref("n.created_at")).as("created_at"), zeitstempel(x.ref("n.done_at")).as("done_at")])
|
||||
.where("n.done", "=", false)
|
||||
.where(sichtbareNotizen(userId))
|
||||
// Eine Notiz mit Fälligkeit erscheint erst an diesem Tag, fachlich so
|
||||
// vorgegeben: vorher ist sie eine Wiedervorlage, keine Aufgabe. In der
|
||||
// Akte steht sie unabhängig davon. Ohne Fälligkeit gleich.
|
||||
.where((x) => x.or([x("n.due_date", "is", null), x("n.due_date", "<=", heute)]))
|
||||
// Nach Fälligkeit, die nächste oben, fachlich so vorgegeben; ohne
|
||||
// Fälligkeit danach, die jüngste zuerst.
|
||||
.orderBy(sql`n.due_date asc nulls last`)
|
||||
@@ -119,9 +123,9 @@ export function baueOffeneNotizen(rows: NotizZeile[], userId: string): OpenNote[
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadOpenNotes(tx: Tx, userId: string): Promise<OpenNote[]> {
|
||||
export async function loadOpenNotes(tx: Tx, userId: string, heute: string): Promise<OpenNote[]> {
|
||||
const { notes } = await tx
|
||||
.selectNoFrom((eb) => [jsonArrayFrom(offeneNotizenAbfrage(eb, userId)).as("notes")])
|
||||
.selectNoFrom((eb) => [jsonArrayFrom(offeneNotizenAbfrage(eb, userId, heute)).as("notes")])
|
||||
.executeTakeFirstOrThrow();
|
||||
return baueOffeneNotizen(notes as NotizZeile[], userId);
|
||||
}
|
||||
|
||||
44
lib/passwort.ts
Normal file
44
lib/passwort.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
// Die Passwortregeln — noch einmal, für die Oberfläche.
|
||||
//
|
||||
// Verbindlich ist app_passwort_regeln() in der Datenbank
|
||||
// (20260908120000). Hier stehen dieselben Regeln ein zweites Mal, damit die
|
||||
// Maske sie beim Tippen anzeigen kann statt erst nach dem Absenden. Dieselbe
|
||||
// Doppelung wie in lib/history.ts, aus demselben Grund und mit derselben
|
||||
// Rangfolge: läuft eine Seite der anderen davon, gewinnt die Datenbank — sie
|
||||
// weist ab, und die Meldung von dort wird angezeigt.
|
||||
|
||||
/** Was in der Maske als Hinweis steht. Reihenfolge wie in der SQL-Funktion. */
|
||||
export const PASSWORT_REGELN = [
|
||||
"mindestens 12 Zeichen",
|
||||
"mindestens ein Grossbuchstabe",
|
||||
"mindestens ein Kleinbuchstabe",
|
||||
"mindestens eine Ziffer",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Liefert die Beanstandung im Klartext oder null.
|
||||
*
|
||||
* Wortgleich mit app_passwort_regeln(). Ein Unterschied bleibt und ist
|
||||
* unvermeidbar: `length()` in PostgreSQL zählt Zeichen, `String.length` in
|
||||
* JavaScript zählt UTF-16-Einheiten. Bei einem Emoji im Passwort weichen die
|
||||
* beiden um eins ab. Das betrifft nur die Vorabanzeige — abgewiesen oder
|
||||
* angenommen wird in der Datenbank.
|
||||
*/
|
||||
export function passwortBeanstandung(passwort: string): string | null {
|
||||
if (passwort.length < 12) return "Das Passwort muss mindestens 12 Zeichen lang sein.";
|
||||
if (passwort.length > 72) return "Das Passwort darf höchstens 72 Zeichen lang sein.";
|
||||
if (!/\p{Lu}/u.test(passwort)) return "Das Passwort muss mindestens einen Grossbuchstaben enthalten.";
|
||||
if (!/\p{Ll}/u.test(passwort)) return "Das Passwort muss mindestens einen Kleinbuchstaben enthalten.";
|
||||
if (!/\p{Nd}/u.test(passwort)) return "Das Passwort muss mindestens eine Ziffer enthalten.";
|
||||
return null;
|
||||
}
|
||||
|
||||
// Das gemeinsame Initialpasswort steht **nicht** in dieser Datei.
|
||||
//
|
||||
// Sie wird von den Anmelde- und Wechselformularen eingebunden, und die laufen
|
||||
// im Browser. Jede Konstante hier landete damit im ausgelieferten Bündel — und
|
||||
// das Initialpasswort wäre für jede Besucherin der Anmeldeseite lesbar, ohne
|
||||
// dass sie auch nur eine E-Mail-Adresse kennen müsste.
|
||||
//
|
||||
// Es gehört deshalb ausschliesslich auf die Serverseite, dorthin, wo es
|
||||
// gebraucht wird: beim Anlegen und beim Zurücksetzen eines Kontos.
|
||||
@@ -3,6 +3,7 @@ import { AUSTRITTSART_LABELS, AUSTRITTSARTEN, BEENDIGUNGSART_WERTE } from "./bee
|
||||
import { fmtDate } from "./format";
|
||||
import { GESCHLECHTER } from "./geschlecht";
|
||||
import { HAY_GRADE_WERTE } from "./hay-grade";
|
||||
import { C_LEVEL_CODES } from "./c-level";
|
||||
import { KUENDIGUNGSSCHUTZ_GRUENDE } from "./kuendigungsschutz";
|
||||
import { MITARBEITERARTEN } from "./mitarbeiterart";
|
||||
import { anzeige } from "./anzeige";
|
||||
@@ -57,6 +58,7 @@ export const AUSWAHL_KRITERIEN: readonly AuswahlKriterium[] = [
|
||||
{ key: "mitarbeiterart", label: "Anstellungs-/Beschäftigungsart", alle: "Alle Anstellungs-/Beschäftigungsarten", optionen: werte(...MITARBEITERARTEN) },
|
||||
{ key: "kv", label: "Kollektivvertrag", alle: "Alle Kollektivverträge", optionen: werte(...KOLLEKTIVVERTRAEGE) },
|
||||
{ key: "paygrade", label: "Hay-Grade", alle: "Alle Hay-Grades", optionen: werte(...HAY_GRADE_WERTE) },
|
||||
{ key: "clevel", label: "C-Level", alle: "Alle C-Level", optionen: C_LEVEL_CODES.map((c) => ({ wert: c, label: c })) },
|
||||
{ key: "source", label: "Intern/Extern", alle: "Intern und Extern", optionen: werte("Intern", "Extern") },
|
||||
{
|
||||
key: "gender",
|
||||
@@ -101,7 +103,6 @@ export const JANEIN_KRITERIEN: readonly JaNeinKriterium[] = [
|
||||
{ key: "dienstwagen", label: "Dienstwagen" },
|
||||
{ key: "betriebsrat", label: "Betriebsrat" },
|
||||
{ key: "lateral", label: "Laterale Führung" },
|
||||
{ key: "clevel", label: "C-Level" },
|
||||
{ key: "kuendigungsschutz", label: "Besonderer Kündigungsschutz" },
|
||||
{ key: "behindert", label: "Begünstigt behindert" },
|
||||
// Die Auswertung der Übernahmen von Leiharbeitskräften. Das Ereignis
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ancestorsOf, loadOrgMaps, subtreeOf, type OrgMaps } from "./org";
|
||||
import { istBereich } from "./org-art";
|
||||
import { loadKontierungen } from "./cost-centers";
|
||||
import { loadPlacements } from "./placement";
|
||||
import { zuweisbareStandorte } from "./standorte";
|
||||
import type { Austrittsart } from "./types";
|
||||
import { LEERE_CRITERIA, passtImSpeicher, type Criteria } from "./report-criteria";
|
||||
import { werteListe } from "./werteliste";
|
||||
@@ -77,6 +78,7 @@ export function applyCriteria<O>(
|
||||
if (a.mitarbeiterart?.length) q = q.where("mitarbeiterart", "in", a.mitarbeiterart as Mitarbeiterart[]);
|
||||
if (a.kv?.length) q = q.where("collective_agreement", "in", a.kv as CollectiveAgreement[]);
|
||||
if (a.paygrade?.length) q = q.where("paygrade", "in", a.paygrade as PaygradeType[]);
|
||||
if (a.clevel?.length) q = q.where("c_level", "in", a.clevel);
|
||||
if (a.source?.length) q = q.where("source", "in", a.source as SourceType[]);
|
||||
if (a.gender?.length) q = q.where("gender", "in", a.gender as GenderType[]);
|
||||
if (a.dienstwagenArt?.length) q = q.where("dienstwagen_art", "in", a.dienstwagenArt as DienstwagenArt[]);
|
||||
@@ -93,7 +95,6 @@ export function applyCriteria<O>(
|
||||
if (j.dienstwagen) q = q.where("has_dienstwagen", "=", j.dienstwagen === "ja");
|
||||
if (j.betriebsrat) q = q.where("is_betriebsrat", "=", j.betriebsrat === "ja");
|
||||
if (j.lateral) q = q.where("is_laterale_fuehrung", "=", j.lateral === "ja");
|
||||
if (j.clevel) q = q.where("is_c_level", "=", j.clevel === "ja");
|
||||
if (j.kuendigungsschutz) q = q.where("has_kuendigungsschutz", "=", j.kuendigungsschutz === "ja");
|
||||
// „In einer Teilzeitvariante" heisst: es steht eine drin, gleich welche.
|
||||
if (j.teilzeit === "ja") q = q.where("teilzeit_art", "is not", null);
|
||||
@@ -181,10 +182,10 @@ export async function loadOrgLookups(tx: Tx): Promise<{
|
||||
locations: { id: string; name: string }[];
|
||||
}> {
|
||||
const orgMaps = await loadOrgMaps(tx);
|
||||
const locations = orgMaps.locationList.map((l) => ({ id: l.id, name: l.name }));
|
||||
const alleStandorte = orgMaps.locationList.map((l) => ({ id: l.id, name: l.name }));
|
||||
|
||||
return {
|
||||
lookups: lookupsFromOrgMaps(orgMaps, locations),
|
||||
lookups: lookupsFromOrgMaps(orgMaps, alleStandorte),
|
||||
orgMaps,
|
||||
// Jede Ebene, nicht nur die Bereiche: wer eine einzelne Abteilung
|
||||
// auswerten will, soll sie nicht über einen Umweg zusammensuchen müssen.
|
||||
@@ -195,7 +196,9 @@ export async function loadOrgLookups(tx: Tx): Promise<{
|
||||
depth: orgMaps.depthOf.get(u.id) ?? 0,
|
||||
unitType: u.unit_type,
|
||||
})),
|
||||
locations,
|
||||
// Zur Auswahl nur Standorte, auf denen jemand sitzen kann; „Shop" selbst
|
||||
// ergäbe immer eine leere Auswertung.
|
||||
locations: zuweisbareStandorte(orgMaps.locationList).map((l) => ({ id: l.id, name: l.name })),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -222,7 +225,7 @@ const SNAPSHOT_EMPLOYEE_COLUMNS = [
|
||||
"is_betriebsrat",
|
||||
"has_dienstwagen",
|
||||
"is_laterale_fuehrung",
|
||||
"is_c_level",
|
||||
"c_level",
|
||||
"teilzeit_art",
|
||||
"zustaendige_hr_id",
|
||||
] as const;
|
||||
@@ -310,7 +313,7 @@ export async function loadSnapshotEmployees(tx: Tx, filters: SnapshotFilters): P
|
||||
is_betriebsrat: e.is_betriebsrat,
|
||||
has_dienstwagen: e.has_dienstwagen,
|
||||
is_laterale_fuehrung: e.is_laterale_fuehrung,
|
||||
is_c_level: e.is_c_level,
|
||||
c_level: e.c_level,
|
||||
teilzeit_art: e.teilzeit_art,
|
||||
dependents_count: dependentsCounts.get(e.id) ?? 0,
|
||||
// Ein gelöschtes Konto setzt die Zuordnung auf null (on delete set
|
||||
|
||||
@@ -2,6 +2,7 @@ import { ABSENCE_TYPES, statusLabel } from "./absence";
|
||||
import { BEENDIGUNGSART_WERTE } from "./beendigung";
|
||||
import { fmtName, todayIso, yearsBetweenIso } from "./format";
|
||||
import { HAY_GRADE_WERTE, OHNE_HAY_GRADE } from "./hay-grade";
|
||||
import { C_LEVEL_CODES, OHNE_C_LEVEL } from "./c-level";
|
||||
import { anzeige } from "./anzeige";
|
||||
import { WOCHENTAGE } from "./wochentage";
|
||||
import { werteListe } from "./werteliste";
|
||||
@@ -138,7 +139,7 @@ export type ReportEmployee = {
|
||||
is_betriebsrat: boolean;
|
||||
has_dienstwagen: boolean;
|
||||
is_laterale_fuehrung: boolean;
|
||||
is_c_level: boolean;
|
||||
c_level: string | null;
|
||||
teilzeit_art: string | null;
|
||||
/**
|
||||
* Die Kostenstelle der Planstelle zum Stichtag, als „Nummer · Bezeichnung";
|
||||
@@ -265,7 +266,8 @@ export function groupKeyFor(e: ReportEmployee, dim: GroupDimension, lookups: Org
|
||||
case "laterale_fuehrung":
|
||||
return e.is_laterale_fuehrung ? "Ja" : "Nein";
|
||||
case "c_level":
|
||||
return e.is_c_level ? "Ja" : "Nein";
|
||||
// Eine eigene Gruppe statt „–": wer keine Stufe hat, ist hier eine Antwort.
|
||||
return e.c_level || OHNE_C_LEVEL;
|
||||
case "has_dependents":
|
||||
return e.dependents_count > 0 ? "Ja" : "Nein";
|
||||
case "teilzeit_art":
|
||||
@@ -302,6 +304,7 @@ export function groupKeyFor(e: ReportEmployee, dim: GroupDimension, lookups: Org
|
||||
const EIGENE_REIHENFOLGE: Partial<Record<GroupDimension, readonly string[]>> = {
|
||||
weekday: WOCHENTAGE,
|
||||
paygrade: [OHNE_HAY_GRADE, ...HAY_GRADE_WERTE],
|
||||
c_level: [...C_LEVEL_CODES, OHNE_C_LEVEL],
|
||||
};
|
||||
|
||||
function rang(dim: GroupDimension, key: string): number {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { sql } from "kysely";
|
||||
import type { Tx } from "./db";
|
||||
import { jsonArrayFrom, jsonObjectFrom } from "./db/json";
|
||||
import { baueEntwuerfe, entwuerfeAbfrage, type Entwurf, type EntwurfZeile } from "./entwuerfe";
|
||||
@@ -46,9 +47,19 @@ export type ShellData = {
|
||||
|
||||
export type HrBenutzer = { id: string; name: string; aktiv: boolean };
|
||||
|
||||
/** Entweder freigeschaltet mit den Daten der Rahmenseite, oder ohne Zugang. */
|
||||
/**
|
||||
* Drei Ausgänge, nicht zwei.
|
||||
*
|
||||
* Mit der Anmeldung per Passwort ist „darf nicht hinein" nicht
|
||||
* dasselbe wie „hat keinen Zugang": wer sein Startpasswort noch nicht
|
||||
* gewechselt hat, hat einen Zugang und kommt trotzdem an keine Zeile, weil
|
||||
* is_hr_user() das mitprüft (Migration 20260908120000). Unterschieden werden
|
||||
* muss es, weil die beiden Fälle verschiedene Auswege haben — der eine wartet
|
||||
* auf HR, der andere ist in einer Minute erledigt.
|
||||
*/
|
||||
export type ShellErgebnis =
|
||||
| { status: "kein_zugang" }
|
||||
| { status: "passwort_wechseln" }
|
||||
| { status: "ok"; daten: ShellData };
|
||||
|
||||
/**
|
||||
@@ -65,9 +76,13 @@ export async function loadShellData(tx: Tx, userId: string): Promise<ShellErgebn
|
||||
jsonObjectFrom(
|
||||
eb.selectFrom("profiles").select(["full_name", "email", "role", "is_active"]).where("id", "=", userId)
|
||||
).as("profile"),
|
||||
// Eine Spalte mehr in derselben Abfrage, keine zusätzliche Rundreise.
|
||||
// Direkt aus app_passwoerter zu lesen ginge nicht: die Tabelle ist für
|
||||
// die Anwendungsrolle gesperrt, an sie kommt nur diese Funktion.
|
||||
sql<boolean>`app_muss_passwort_wechseln()`.as("passwortWechseln"),
|
||||
...orgMapsAbfragen(eb),
|
||||
jsonArrayFrom(offeneStellenAbfrage(eb, asOf)).as("open"),
|
||||
jsonArrayFrom(offeneNotizenAbfrage(eb, userId)).as("notes"),
|
||||
jsonArrayFrom(offeneNotizenAbfrage(eb, userId, asOf)).as("notes"),
|
||||
// Alle freigeschalteten HR-Personen ausser der eigenen, dazu die
|
||||
// eigene Auswahl. Beides in derselben Rundreise wie der Rest der
|
||||
// Hülle — die Einstellung steckt in der Glocke, also muss sie beim
|
||||
@@ -99,6 +114,13 @@ export async function loadShellData(tx: Tx, userId: string): Promise<ShellErgebn
|
||||
|
||||
const profile = gelesen.profile;
|
||||
|
||||
// Der Passwortwechsel steht **vor** der HR-Prüfung, obwohl er der seltenere
|
||||
// Fall ist: er ist der einzige, den die betroffene Person selbst beheben
|
||||
// kann. Wer beides hat — offener Wechsel und keine Freischaltung — bekommt
|
||||
// danach immer noch „Kein HR-Zugriff", aber wenigstens in dieser Reihenfolge
|
||||
// und nicht als Sackgasse.
|
||||
if (gelesen.passwortWechseln) return { status: "passwort_wechseln" };
|
||||
|
||||
if (profile?.role !== "hr" || profile?.is_active !== true) return { status: "kein_zugang" };
|
||||
|
||||
const orgMaps = buildOrgMaps(gelesen.units as never, gelesen.locations as never);
|
||||
|
||||
34
lib/standorte.ts
Normal file
34
lib/standorte.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
// Standorte mit Unterstandorten (Migration 20261123140000): „Shop" fasst die
|
||||
// einzelnen Shops zusammen. Eine Person sitzt nur auf einem Standort ohne
|
||||
// Unterstandorte; die Auswahl zeigt zuerst die oberste Ebene und bei einem
|
||||
// zusammenfassenden Standort eine zweite Liste.
|
||||
|
||||
export type StandortEintrag = { id: string; name: string; parent_id?: string | null };
|
||||
|
||||
/** Standorte der obersten Ebene, wie die erste Auswahl sie zeigt. */
|
||||
export function oberstandorte<T extends StandortEintrag>(alle: readonly T[]): T[] {
|
||||
return alle.filter((s) => !s.parent_id);
|
||||
}
|
||||
|
||||
/** Die Unterstandorte eines Standorts, leer bei einem gewöhnlichen. */
|
||||
export function unterstandorte<T extends StandortEintrag>(alle: readonly T[], id: string): T[] {
|
||||
return id ? alle.filter((s) => s.parent_id === id) : [];
|
||||
}
|
||||
|
||||
/** Standorte, auf denen eine Person sitzen kann — für Filter und Importlisten. */
|
||||
export function zuweisbareStandorte<T extends StandortEintrag>(alle: readonly T[]): T[] {
|
||||
const gruppen = new Set(alle.map((s) => s.parent_id).filter(Boolean));
|
||||
return alle.filter((s) => !gruppen.has(s.id));
|
||||
}
|
||||
|
||||
/** Welcher Eintrag der ersten Auswahl zu einem gespeicherten Standort gehört. */
|
||||
export function oberstandortVon(alle: readonly StandortEintrag[], id: string): string {
|
||||
const s = alle.find((x) => x.id === id);
|
||||
return s ? (s.parent_id ?? s.id) : "";
|
||||
}
|
||||
|
||||
/** „Shop W17" unter „Shop" zeigt die zweite Auswahl als „W17". */
|
||||
export function kurzname(unter: StandortEintrag, ober: StandortEintrag | undefined): string {
|
||||
const praefix = ober ? `${ober.name} ` : "";
|
||||
return praefix && unter.name.startsWith(praefix) ? unter.name.slice(praefix.length) : unter.name;
|
||||
}
|
||||
14
lib/testsystem.ts
Normal file
14
lib/testsystem.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
// Ob diese Installation ein Testsystem ist (TESTSYSTEM in der Konfiguration
|
||||
// des Servers). Dann trägt jede Seite den Schriftzug „Testsystem" und der
|
||||
// Titel im Browser-Tab beginnt damit — wer zwischen Test und Produktion
|
||||
// wechselt, sieht so auf einen Blick, wo er arbeitet.
|
||||
//
|
||||
// Gelesen wird zur Laufzeit, nicht beim Bauen: dasselbe Paket läuft in Test
|
||||
// und Produktion, und ohne den Eintrag erscheint nichts.
|
||||
|
||||
export const TESTSYSTEM_SCHRIFTZUG = "Testsystem";
|
||||
|
||||
export function istTestsystem(wert: string | undefined = process.env.TESTSYSTEM): boolean {
|
||||
const w = wert?.trim().toLowerCase();
|
||||
return w === "1" || w === "true" || w === "ja";
|
||||
}
|
||||
15
lib/types.ts
15
lib/types.ts
@@ -197,9 +197,9 @@ export type Database = {
|
||||
public: {
|
||||
Tables: {
|
||||
locations: {
|
||||
Row: { id: string; name: string; country: string };
|
||||
Insert: { id?: string; name: string; country: string };
|
||||
Update: Partial<{ id: string; name: string; country: string }>;
|
||||
Row: { id: string; name: string; country: string; parent_id: string | null };
|
||||
Insert: { id?: string; name: string; country: string; parent_id?: string | null };
|
||||
Update: Partial<{ id: string; name: string; country: string; parent_id: string | null }>;
|
||||
};
|
||||
profiles: {
|
||||
Row: {
|
||||
@@ -290,7 +290,7 @@ export type Database = {
|
||||
contract_end_date: string | null;
|
||||
/** Null heisst „noch nicht bewertet" — die Vorgabe. */
|
||||
paygrade: PaygradeType | null;
|
||||
/** VL, Stufe 1 bis 8 — chk_vl. Null heisst nicht erfasst. */
|
||||
/** FL, Stufe 1 bis 7 — chk_vl. Null heisst nicht erfasst. */
|
||||
vl: number | null;
|
||||
has_bonusanspruch: boolean;
|
||||
/** Null genau dann, wenn kein Bonusanspruch besteht — chk_bonusanspruch_art. */
|
||||
@@ -359,6 +359,8 @@ export type Database = {
|
||||
emergency_contact_relation: string | null;
|
||||
is_laterale_fuehrung: boolean;
|
||||
is_c_level: boolean;
|
||||
/** Code aus lib/c-level.ts (chk_c_level); null = nicht erfasst. */
|
||||
c_level: string | null;
|
||||
title_prefix: string[];
|
||||
title_suffix: string[];
|
||||
created_at: string;
|
||||
@@ -433,6 +435,7 @@ export type Database = {
|
||||
emergency_contact_relation?: string | null;
|
||||
is_laterale_fuehrung?: boolean;
|
||||
is_c_level?: boolean;
|
||||
c_level?: string | null;
|
||||
title_prefix?: string[];
|
||||
title_suffix?: string[];
|
||||
created_at?: string;
|
||||
@@ -911,6 +914,10 @@ export type Database = {
|
||||
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.
|
||||
app_passwort_aendern: { Args: { payload: Record<string, unknown> }; Returns: void };
|
||||
// Nimmt eine irrtümliche Stammdaten-/Vertragsänderung zurück. Der einzige
|
||||
// Weg an der fehlenden delete-Policy auf employee_history vorbei.
|
||||
delete_history_entry: { Args: { payload: Record<string, unknown> }; Returns: void };
|
||||
|
||||
41
lib/verhaeltnis.ts
Normal file
41
lib/verhaeltnis.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { EMERGENCY_RELATIONS } from "./types";
|
||||
|
||||
// Das Verhältnis bei Angehörigen und Notfallkontakten: ein Wert aus der Liste,
|
||||
// und unter „Sonstige" ein frei eingetragener Text. Gespeichert wird dann der
|
||||
// Text selbst („Onkel"); steht nichts darin, bleibt „Sonstige" gespeichert
|
||||
// (components/employees/VerhaeltnisField.tsx).
|
||||
//
|
||||
// Die Austauschdatei führt beides wie das Formular in zwei Spalten: die
|
||||
// Auswahl und daneben den Text zu „Sonstige". So bleibt die Auswahl in Excel
|
||||
// eine feste Liste, und ein eigener Text hat trotzdem seinen Platz.
|
||||
|
||||
export const SONSTIGE = "Sonstige";
|
||||
|
||||
/** Ob ein gespeicherter Wert frei eingetragen wurde. */
|
||||
export function istFreiesVerhaeltnis(wert: string): boolean {
|
||||
return wert.trim() !== "" && !(EMERGENCY_RELATIONS as readonly string[]).includes(wert);
|
||||
}
|
||||
|
||||
/** Der gespeicherte Wert, aufgeteilt in Auswahl und Text zu „Sonstige". */
|
||||
export function verhaeltnisFuerDatei(gespeichert: string | null | undefined): { auswahl: string | null; sonstige: string | null } {
|
||||
const wert = gespeichert ?? "";
|
||||
if (istFreiesVerhaeltnis(wert)) return { auswahl: SONSTIGE, sonstige: wert };
|
||||
return { auswahl: wert || null, sonstige: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Auswahl und Text aus der Datei zum Wert, der gespeichert wird. Ein Text
|
||||
* ohne „Sonstige" ist ein Widerspruch; welche der beiden Angaben gilt, lässt
|
||||
* sich nicht entscheiden.
|
||||
*/
|
||||
export function verhaeltnisAusDatei(
|
||||
auswahl: string | null | undefined,
|
||||
sonstige: string | null | undefined
|
||||
): { wert: string | null } | { fehler: string } {
|
||||
const text = sonstige?.trim() ?? "";
|
||||
if (text && auswahl !== SONSTIGE) {
|
||||
return { fehler: `Ein Text zu „Sonstige“ steht nur bei der Auswahl „Sonstige“.` };
|
||||
}
|
||||
if (auswahl === SONSTIGE && text) return { wert: text };
|
||||
return { wert: auswahl ?? null };
|
||||
}
|
||||
@@ -1,15 +1,16 @@
|
||||
import type { Bonusregelung } from "./types";
|
||||
|
||||
// VL und Bonusanspruch — zwei Vertragsangaben aus der Personalabteilung
|
||||
// (Migration 20261007100000).
|
||||
// FL und Bonusanspruch — zwei Vertragsangaben aus der Personalabteilung
|
||||
// (Migrationen 20261007100000 und, für die FL-Stufen, 20261201120000).
|
||||
// Gespeichert ist FL in der Spalte vl.
|
||||
//
|
||||
// Die Listen stehen dort als CHECK und hier für die Oberfläche;
|
||||
// tests/unit/vertragsangaben.test.ts hält beide gegeneinander, damit die
|
||||
// begründete Doppelung keine stille wird. Liefen sie auseinander, böte das
|
||||
// Formular einen Wert an, den die Datenbank abweist.
|
||||
|
||||
/** Die VL-Stufen 1 bis 8. Leer heisst „nicht erfasst" — es gibt keine Stufe 0. */
|
||||
export const VL_STUFEN: readonly number[] = [1, 2, 3, 4, 5, 6, 7, 8] as const;
|
||||
/** Die FL-Stufen 1 bis 7. Leer heisst „nicht erfasst" — es gibt keine Stufe 0. */
|
||||
export const VL_STUFEN: readonly number[] = [1, 2, 3, 4, 5, 6, 7] as const;
|
||||
|
||||
export const BONUSREGELUNGEN: readonly Bonusregelung[] = [
|
||||
"RL ab 01.01.2027",
|
||||
|
||||
@@ -103,7 +103,7 @@ export function vorbelegungAus(employee: EmployeeRow): Partial<HireDraftData> {
|
||||
// „Verbrenner" ist dabei die Vorgabe, nicht eine Behauptung.
|
||||
dienstwagenArt: employee.dienstwagen_art ?? "Verbrenner",
|
||||
isLateraleFuehrung: employee.is_laterale_fuehrung,
|
||||
isCLevel: employee.is_c_level,
|
||||
cLevel: employee.c_level ?? "",
|
||||
// Leer: die Notfallkontakte stehen in employee_emergency_contacts und
|
||||
// bleiben beim Wiedereintritt erhalten. Das Feld im Assistenten nimmt nur
|
||||
// einen weiteren auf. Vorbelegt aus den Spalten an der Person käme ein
|
||||
|
||||
@@ -13,6 +13,15 @@ export function stundenWert(text: string): string {
|
||||
return text.trim().replace(",", ".");
|
||||
}
|
||||
|
||||
/**
|
||||
* Höchstens zwei Nachkommastellen, wie die Spalte (numeric(4,2)). Eine
|
||||
* dritte rundete die Datenbank stillschweigend weg, und gespeichert wäre ein
|
||||
* anderer Wert als der eingegebene.
|
||||
*/
|
||||
export function nachkommaFehler(text: string): string | null {
|
||||
return /\.\d{3,}$/.test(stundenWert(text)) ? "Wochenstunden haben höchstens zwei Nachkommastellen." : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fehlertext oder null. Ohne Beschäftigungsausmaß wird nur der Rahmen
|
||||
* geprüft (mehr als 0, höchstens 38,5).
|
||||
@@ -21,6 +30,8 @@ export function wochenstundenFehler(ausmass: string | undefined, text: string):
|
||||
const wert = stundenWert(text);
|
||||
const stunden = Number(wert);
|
||||
const zahl = wert !== "" && Number.isFinite(stunden);
|
||||
const nachkomma = nachkommaFehler(text);
|
||||
if (nachkomma) return nachkomma;
|
||||
if (ausmass === "Teilzeit" && (!zahl || stunden <= 0 || stunden >= VOLLZEIT_STUNDEN)) {
|
||||
return "Wochenstunden bei Teilzeit müssen zwischen 0 und 38,5 liegen.";
|
||||
}
|
||||
|
||||
250
package-lock.json
generated
250
package-lock.json
generated
@@ -1,19 +1,19 @@
|
||||
{
|
||||
"name": "alpenwerk-hr",
|
||||
"version": "0.2.1",
|
||||
"version": "0.2.3",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "alpenwerk-hr",
|
||||
"version": "0.2.1",
|
||||
"version": "0.2.3",
|
||||
"dependencies": {
|
||||
"@dagrejs/dagre": "^3.0.0",
|
||||
"@xyflow/react": "^12.11.2",
|
||||
"exceljs": "^4.4.0",
|
||||
"kysely": "^0.29.4",
|
||||
"lucide-react": "^1.26.0",
|
||||
"next": "^16.4.3",
|
||||
"next": "^16.4.6",
|
||||
"next-auth": "^5.0.0-beta.32",
|
||||
"pg": "^8.22.0",
|
||||
"react": "^19.2.8",
|
||||
@@ -31,7 +31,7 @@
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitest/coverage-v8": "^4.1.12",
|
||||
"eslint": "^9.39.5",
|
||||
"eslint-config-next": "^16.4.3",
|
||||
"eslint-config-next": "^16.4.6",
|
||||
"jsdom": "^29.1.1",
|
||||
"postcss": "^8.5.19",
|
||||
"tailwindcss": "^4.3.3",
|
||||
@@ -1059,9 +1059,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1078,9 +1075,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1097,9 +1091,6 @@
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1116,9 +1107,6 @@
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1135,9 +1123,6 @@
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1154,9 +1139,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1173,9 +1155,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1192,9 +1171,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1211,9 +1187,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1236,9 +1209,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1261,9 +1231,6 @@
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1286,9 +1253,6 @@
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1311,9 +1275,6 @@
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1336,9 +1297,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1361,9 +1319,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1386,9 +1341,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1573,15 +1525,15 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/env": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/env/-/env-16.4.3.tgz",
|
||||
"integrity": "sha512-a7tz1QCcWWkwC/rPJcPMJk/UNRu9CFhDd3OHYE5hddbJrs8BqRTalxI6GlKCWEGzRLHN+S/B7a4PAHCtm25aBQ==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/env/-/env-16.4.6.tgz",
|
||||
"integrity": "sha512-SunBjJ6t+oBtecS3dTjdVuMhUogP5wD/vrGL5EVuQYM1iS4O5ilL51HkiJ3sPjMzRHiCChvr4dbaSJbR7F3lxA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@next/eslint-plugin-next": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.4.3.tgz",
|
||||
"integrity": "sha512-oxuC06wt/71h6ACYCV9GbKOfnf5a7VlRe/p80YHTut15TNgDEmynDnaq8t/xhy5rlvk7dhItIPs6H3rvIM4kyw==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.4.6.tgz",
|
||||
"integrity": "sha512-HdqERVOafOD8JaUSAkwf9aSu/1rsHlkN8C5GcXYBH3C/z1MxBhZFxB5rz/xqMMRiIj7r9tIv8OCLQ9JWUxCvWA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -1590,9 +1542,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-darwin-arm64": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.4.3.tgz",
|
||||
"integrity": "sha512-4yq5EXBt+VDtAZwTyfijaFp5D2C5oz3Ikw5a2kiX2K9nw72vrZX2q5UuAlkPtUMO1tQz6JTKpaKWjS7OOefTDQ==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.4.6.tgz",
|
||||
"integrity": "sha512-kJ4VVZkley17xKaJx72QN2IBqjrj7zenCQZaUF0l9ShS/1Mt2kW4+Z5KGG6vgr3L/J562xTOizVyM1iA/u5nlg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1606,9 +1558,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-darwin-x64": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.4.3.tgz",
|
||||
"integrity": "sha512-1Rvkn/LUhnEF8WxnRkOrqGhbwXui1bkWFxONKIbN+r7C+9KHDSZ+iUoj4CzymVMWUyZIyx9szcb9+kbKhD500A==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.4.6.tgz",
|
||||
"integrity": "sha512-eIPGZIqC+8JKaeZmvnCANJQF4xWkkHqSnAAajtFxgwDMAOnCgxNvP52SeWZ41PyVwoe+Le/NQuZSaQ8j7YshSA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1622,15 +1574,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-linux-arm64-gnu": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.4.3.tgz",
|
||||
"integrity": "sha512-dCKpXErGg3abUM6t5JTJV/ottVBTStJB5lRJTbgdUdQaQ+jNHiK56Hsc0YAEg/rinSh42hYG3HWiYmEMdilnxg==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.4.6.tgz",
|
||||
"integrity": "sha512-9nI6O8vvczH2D9ZNdMGqb/3NuT15T9ksOZnAmx9/gjF2cOi74+xxyf1Hk96uIMfm14c9y6wHeBq6SH8g6udvcA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1641,15 +1590,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-linux-arm64-musl": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.4.3.tgz",
|
||||
"integrity": "sha512-WwYbhWkhYBvBtib1K4W0kL8MW2snBD2A5b3SN4vPpqalZbZs5+bQ1yzAdepVoOqrFfEW3dmREy4Zs1MrWcrFbw==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.4.6.tgz",
|
||||
"integrity": "sha512-7/qPhTxDp2ScluOJOhLuhWmlA17o1yZ0SIgpISBCpBxXgtnK4+KGywBpFkfLPiU1rnSM1faFGzYkH6i7JdTrqA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1660,15 +1606,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-linux-x64-gnu": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.4.3.tgz",
|
||||
"integrity": "sha512-QymWvfUwDEC5/lpJOsxX5VAbyoR2D13+2Jsjz4be7gT4LPqEgdpkeLIR/HFfCLgKzoMhpJbp6I/JnogyNZHcaA==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.4.6.tgz",
|
||||
"integrity": "sha512-oOpbNa8XOW1qCGd9VvzC4fbkkRxEls7/WI6tz+YHC0xRA7KpV1U7DrAnCPjzVyOk/karzWEepCOcTIDmwK8FwQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1679,15 +1622,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-linux-x64-musl": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.4.3.tgz",
|
||||
"integrity": "sha512-Vmjd9D7DpA4Vv3cUlr82QWgJD/BQZmns801vtC5VWHg6jCIA4a5vMKpQnfrM2pyCrp2eV0ENdUg4PlN3bAc2Yw==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.4.6.tgz",
|
||||
"integrity": "sha512-aM8CZ+OR2EwXaAYw7KGkW2GDmNDsLBIRe1MMRZCJPTdw/xhTD0IMUVO4sf3KqrzuRouGzwwLZn34+gFeVXiUQA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1698,9 +1638,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-win32-arm64-msvc": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.4.3.tgz",
|
||||
"integrity": "sha512-lG1pPdPLk7gTyGb00n5JIMLdBJgjb+UEhSdZvFbhUMg0DyC6z4B7RnpSKF9VCd4imkLObVbXOFA0kFCpw7yFow==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.4.6.tgz",
|
||||
"integrity": "sha512-U0p7/tEtqvHX2crhd841CDwKtp5CFkKXVjOhmfccR3Pvp64sj8KBwRqsvltqLOwVBbj0NtkxwXSDpEHYGbxeXQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1714,9 +1654,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-win32-x64-msvc": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.4.3.tgz",
|
||||
"integrity": "sha512-NmQC9RkJdnPXRaMxtkCzobB3teVjqF33oSOnwDfi+XYGWWYpt+xlGK3mtktSKLbdjwaWbJu2OkkMiRFGUUncKg==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.4.6.tgz",
|
||||
"integrity": "sha512-3ZG15/5WIdlTQsIEvc9sPTTSL5XFrlLklIKmfF4fwsDnoAhu6NcBDXsk3mbGxNyo6aVLEGex+fHCv2MahY7a9g==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1906,9 +1846,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1926,9 +1863,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1946,9 +1880,6 @@
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1966,9 +1897,6 @@
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1986,9 +1914,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2006,9 +1931,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2232,9 +2154,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2252,9 +2171,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2272,9 +2188,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2292,9 +2205,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2984,9 +2894,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3001,9 +2908,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3018,9 +2922,6 @@
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3035,9 +2936,6 @@
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3052,9 +2950,6 @@
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3069,9 +2964,6 @@
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3086,9 +2978,6 @@
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3103,9 +2992,6 @@
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3120,9 +3006,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3137,9 +3020,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4237,9 +4117,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/cross-spawn": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
|
||||
"version": "7.1.2",
|
||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.1.2.tgz",
|
||||
"integrity": "sha512-8BPK2r+sKWC8sDinRwLwrFMq2lXTBBwzYYEB9LiCznfMurOi4FOvQflq3XOLGG+HPdMSVpe+k/s96+AtDEOgPg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -4975,13 +4855,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/eslint-config-next": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.4.3.tgz",
|
||||
"integrity": "sha512-j9IqBma6abp800frdUURaizYMgXOK+jNGyq6CsYcM9AxpSJs5D/TgMNGeAmRUilZvA7g9V1Tr71gNg9/SVTuMQ==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.4.6.tgz",
|
||||
"integrity": "sha512-IBGGrVf9E6pL0NGL0hmeicVGeSyv1VEzIWq6IecDqkw+YFByhEtDJS9u1r6s6a1VxK6rssh69KyNFQUgfaacqw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@next/eslint-plugin-next": "16.4.3",
|
||||
"@next/eslint-plugin-next": "16.4.6",
|
||||
"eslint-import-resolver-node": "^0.3.6",
|
||||
"eslint-import-resolver-typescript": "^3.5.2",
|
||||
"eslint-plugin-import": "^2.32.0",
|
||||
@@ -7099,9 +6979,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -7123,9 +7000,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -7147,9 +7021,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -7171,9 +7042,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -7569,12 +7437,12 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/next": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/next/-/next-16.4.3.tgz",
|
||||
"integrity": "sha512-OqxKTGi9u80FydydsMNYNjnuje9Au+kvHlt2GZ//ftdpDHm1dxKqAaENoOOTX5wKzn+9vaKUNIfZeyZUuLhCnA==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/next/-/next-16.4.6.tgz",
|
||||
"integrity": "sha512-QZJiYhaZLJMo2KpkQGQIwvmd79WVsAWeYIU554a8d7zArS3si/IRy3lBNV/rtYhE70oLwdLYhPAXLPx8HwcwtA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@next/env": "16.4.3",
|
||||
"@next/env": "16.4.6",
|
||||
"@swc/helpers": "0.5.23",
|
||||
"baseline-browser-mapping": "^2.9.19",
|
||||
"caniuse-lite": "^1.0.30001579",
|
||||
@@ -7588,14 +7456,14 @@
|
||||
"node": ">=20.9.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@next/swc-darwin-arm64": "16.4.3",
|
||||
"@next/swc-darwin-x64": "16.4.3",
|
||||
"@next/swc-linux-arm64-gnu": "16.4.3",
|
||||
"@next/swc-linux-arm64-musl": "16.4.3",
|
||||
"@next/swc-linux-x64-gnu": "16.4.3",
|
||||
"@next/swc-linux-x64-musl": "16.4.3",
|
||||
"@next/swc-win32-arm64-msvc": "16.4.3",
|
||||
"@next/swc-win32-x64-msvc": "16.4.3",
|
||||
"@next/swc-darwin-arm64": "16.4.6",
|
||||
"@next/swc-darwin-x64": "16.4.6",
|
||||
"@next/swc-linux-arm64-gnu": "16.4.6",
|
||||
"@next/swc-linux-arm64-musl": "16.4.6",
|
||||
"@next/swc-linux-x64-gnu": "16.4.6",
|
||||
"@next/swc-linux-x64-musl": "16.4.6",
|
||||
"@next/swc-win32-arm64-msvc": "16.4.6",
|
||||
"@next/swc-win32-x64-msvc": "16.4.6",
|
||||
"sharp": "^0.35.5"
|
||||
},
|
||||
"peerDependencies": {
|
||||
@@ -9939,9 +9807,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -9963,9 +9828,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -9987,9 +9849,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -10011,9 +9870,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "alpenwerk-hr",
|
||||
"version": "0.2.1",
|
||||
"version": "0.2.3",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
@@ -25,7 +25,7 @@
|
||||
"exceljs": "^4.4.0",
|
||||
"kysely": "^0.29.4",
|
||||
"lucide-react": "^1.26.0",
|
||||
"next": "^16.4.3",
|
||||
"next": "^16.4.6",
|
||||
"next-auth": "^5.0.0-beta.32",
|
||||
"pg": "^8.22.0",
|
||||
"react": "^19.2.8",
|
||||
@@ -43,7 +43,7 @@
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitest/coverage-v8": "^4.1.12",
|
||||
"eslint": "^9.39.5",
|
||||
"eslint-config-next": "^16.4.3",
|
||||
"eslint-config-next": "^16.4.6",
|
||||
"jsdom": "^29.1.1",
|
||||
"postcss": "^8.5.19",
|
||||
"tailwindcss": "^4.3.3",
|
||||
|
||||
@@ -35,7 +35,7 @@ vi.mock("@/actions/hireDrafts", () => ({
|
||||
}));
|
||||
vi.mock("next/navigation", () => ({ useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }) }));
|
||||
|
||||
const LOCATIONS = [{ id: "l1", name: "Wien", country: "Österreich" }];
|
||||
const LOCATIONS = [{ id: "l1", name: "Wien", country: "Österreich", parent_id: null }];
|
||||
|
||||
function zeige(resumeDraft: { id: string; step: number; payload: Record<string, unknown> } | null = null) {
|
||||
const onClose = vi.fn();
|
||||
|
||||
@@ -40,7 +40,7 @@ const POSITION = {
|
||||
kostenstelle: null,
|
||||
} as unknown as OpenPositionResolved;
|
||||
|
||||
const LOCATIONS = [{ id: "l1", name: "Wien", country: "AT" }];
|
||||
const LOCATIONS = [{ id: "l1", name: "Wien", country: "AT", parent_id: null }];
|
||||
|
||||
/** Ein Entwurf, in dem alles bis einschliesslich Vertrag vollständig ist. */
|
||||
const VOLLSTAENDIG = {
|
||||
|
||||
48
tests/components/KarenzPanel.test.tsx
Normal file
48
tests/components/KarenzPanel.test.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { KarenzPanel } from "@/components/employees/panels/KarenzPanel";
|
||||
import { ToastProvider } from "@/components/ui/Toast";
|
||||
import type { Database } from "@/lib/types";
|
||||
|
||||
vi.mock("@/actions/employees", () => ({
|
||||
rueckkehrAnpassen: vi.fn(async () => ({ success: true })),
|
||||
startKarenz: vi.fn(async () => ({ success: true })),
|
||||
}));
|
||||
vi.mock("next/navigation", () => ({ useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }) }));
|
||||
|
||||
type EmployeeRow = Database["public"]["Tables"]["employees"]["Row"];
|
||||
|
||||
function zeige(absenceType: string) {
|
||||
const employee = {
|
||||
id: "e1",
|
||||
first_name: "Magdalena",
|
||||
last_name: "Zeller",
|
||||
job_title: "Schnitte",
|
||||
weekly_hours: 38.5,
|
||||
absence_type: absenceType,
|
||||
karenz_start_date: "2026-09-01",
|
||||
karenz_return_date: "2027-08-31",
|
||||
geburtstermin_voraussichtlich: null,
|
||||
geburtstermin_tatsaechlich: null,
|
||||
} as unknown as EmployeeRow;
|
||||
return render(
|
||||
<ToastProvider>
|
||||
<KarenzPanel open onClose={() => {}} employee={employee} status="Karenz" history={[]} today="2026-11-23" />
|
||||
</ToastProvider>
|
||||
);
|
||||
}
|
||||
|
||||
// Auf den Mutterschutz folgt die Karenz; bei anderen Arten gibt es keine
|
||||
// anschliessende Abwesenheit.
|
||||
describe("KarenzPanel: anschliessende Abwesenheit", () => {
|
||||
it("bietet sie bei der Wochenhilfe an", () => {
|
||||
zeige("Wochenhilfe (Mutterschutz)");
|
||||
expect(screen.getByRole("button", { name: "Anschliessende Abwesenheit planen" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("bietet sie bei anderen Arten nicht an", () => {
|
||||
zeige("Bildungskarenz");
|
||||
expect(screen.queryByRole("button", { name: "Anschliessende Abwesenheit planen" })).not.toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/^Endet am/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -18,7 +18,7 @@ const WERT: RoleEmploymentValue = {
|
||||
hasDienstwagen: false,
|
||||
dienstwagenArt: "Verbrenner",
|
||||
isLateraleFuehrung: false,
|
||||
isCLevel: false,
|
||||
cLevel: "",
|
||||
hasKuendigungsschutz: false,
|
||||
kuendigungsschutzBis: "",
|
||||
kuendigungsschutzGrund: "",
|
||||
|
||||
53
tests/components/StandortAuswahl.test.tsx
Normal file
53
tests/components/StandortAuswahl.test.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { useState } from "react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { StandortAuswahl } from "@/components/employees/StandortAuswahl";
|
||||
|
||||
const STANDORTE = [
|
||||
{ id: "hernals", name: "Wien-Hernals", country: "Österreich", parent_id: null },
|
||||
{ id: "shop", name: "Shop", country: "Österreich", parent_id: null },
|
||||
{ id: "w17", name: "Shop W17", country: "Österreich", parent_id: "shop" },
|
||||
{ id: "wodo", name: "Shop Wodo", country: "Österreich", parent_id: "shop" },
|
||||
];
|
||||
|
||||
function Formular({ start = "" }: { start?: string }) {
|
||||
const [wert, setWert] = useState(start);
|
||||
return (
|
||||
<>
|
||||
<StandortAuswahl required value={wert} onChange={setWert} standorte={STANDORTE} />
|
||||
<output data-testid="stand">{wert}</output>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
describe("StandortAuswahl", () => {
|
||||
it("zeigt zuerst nur die oberste Ebene", () => {
|
||||
render(<Formular />);
|
||||
const optionen = Array.from((screen.getByLabelText(/^Standort/) as HTMLSelectElement).options).map((o) => o.value);
|
||||
expect(optionen).toEqual(["", "hernals", "shop"]);
|
||||
expect(screen.queryByLabelText(/^Shop/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("verlangt unter „Shop“ den einzelnen Shop und meldet erst ihn", () => {
|
||||
render(<Formular />);
|
||||
fireEvent.change(screen.getByLabelText(/^Standort/), { target: { value: "shop" } });
|
||||
expect(screen.getByTestId("stand").textContent).toBe("");
|
||||
const shops = screen.getByLabelText(/^Shop/) as HTMLSelectElement;
|
||||
expect(Array.from(shops.options).map((o) => o.text)).toEqual(["Bitte wählen…", "W17", "Wodo"]);
|
||||
fireEvent.change(shops, { target: { value: "wodo" } });
|
||||
expect(screen.getByTestId("stand").textContent).toBe("wodo");
|
||||
});
|
||||
|
||||
it("öffnet einen gespeicherten Shop mit beiden Auswahlen", () => {
|
||||
render(<Formular start="w17" />);
|
||||
expect((screen.getByLabelText(/^Standort/) as HTMLSelectElement).value).toBe("shop");
|
||||
expect((screen.getByLabelText(/^Shop/) as HTMLSelectElement).value).toBe("w17");
|
||||
});
|
||||
|
||||
it("schliesst die zweite Auswahl beim Wechsel auf einen gewöhnlichen Standort", () => {
|
||||
render(<Formular start="w17" />);
|
||||
fireEvent.change(screen.getByLabelText(/^Standort/), { target: { value: "hernals" } });
|
||||
expect(screen.getByTestId("stand").textContent).toBe("hernals");
|
||||
expect(screen.queryByLabelText(/^Shop/)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -60,7 +60,7 @@ const MIT_STAATSBUERGERSCHAFT = { ...EXTERN, nationality: "Deutschland" } as Emp
|
||||
function zeige(employee: EmployeeRow = MIT_STAATSBUERGERSCHAFT) {
|
||||
return render(
|
||||
<ToastProvider>
|
||||
<UebernahmeWizard open onClose={() => {}} employee={employee} locations={[{ id: "l1", name: "Wien", country: "Österreich" }]} />
|
||||
<UebernahmeWizard open onClose={() => {}} employee={employee} locations={[{ id: "l1", name: "Wien", country: "Österreich", parent_id: null }]} />
|
||||
</ToastProvider>
|
||||
);
|
||||
}
|
||||
@@ -102,7 +102,7 @@ describe("Übernahme", () => {
|
||||
open
|
||||
onClose={() => {}}
|
||||
employee={{ ...EXTERN, birth_date: "2090-01-01" } as EmployeeRow}
|
||||
locations={[{ id: "l1", name: "Wien", country: "Österreich" }]}
|
||||
locations={[{ id: "l1", name: "Wien", country: "Österreich", parent_id: null }]}
|
||||
/>
|
||||
</ToastProvider>
|
||||
);
|
||||
|
||||
@@ -57,6 +57,7 @@ function mitarbeiter(teil: Partial<EmployeeRow> = {}): EmployeeRow {
|
||||
teilzeit_bis: null,
|
||||
is_laterale_fuehrung: false,
|
||||
is_c_level: false,
|
||||
c_level: null,
|
||||
title_prefix: [],
|
||||
title_suffix: [],
|
||||
emergency_contact_name: null,
|
||||
@@ -87,7 +88,16 @@ describe("VertragTab — Merkmale", () => {
|
||||
render(<VertragTab employee={mitarbeiter()} />);
|
||||
expect(wertZu("Dienstwagen")).toBe("Nein");
|
||||
expect(wertZu("Betriebsrat")).toBe("Nein");
|
||||
expect(wertZu("C-Level")).toBe("Nein");
|
||||
});
|
||||
|
||||
it("zeigt C-Level als Code", () => {
|
||||
render(<VertragTab employee={mitarbeiter({ c_level: "C4" })} />);
|
||||
expect(wertZu("C-Level")).toBe("C4");
|
||||
});
|
||||
|
||||
it("zeigt bei C-Level ohne Angabe einen Strich", () => {
|
||||
render(<VertragTab employee={mitarbeiter()} />);
|
||||
expect(wertZu("C-Level")).toBe("–");
|
||||
});
|
||||
|
||||
it("nennt beim Dienstwagen die Antriebsart statt eines blossen Ja", () => {
|
||||
@@ -101,9 +111,8 @@ describe("VertragTab — Merkmale", () => {
|
||||
});
|
||||
|
||||
it("zeigt gesetzte Merkmale als Ja", () => {
|
||||
render(<VertragTab employee={mitarbeiter({ is_betriebsrat: true, is_c_level: true })} />);
|
||||
render(<VertragTab employee={mitarbeiter({ is_betriebsrat: true })} />);
|
||||
expect(wertZu("Betriebsrat")).toBe("Ja");
|
||||
expect(wertZu("C-Level")).toBe("Ja");
|
||||
expect(wertZu("Laterale Führung")).toBe("Nein");
|
||||
});
|
||||
|
||||
|
||||
@@ -14,16 +14,16 @@ describe("VertragsangabenFields", () => {
|
||||
expect(screen.getByLabelText(/Bonusregelung/)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("steht bei Nein, ohne VL", () => {
|
||||
it("steht bei Nein, ohne FL", () => {
|
||||
render(<VertragsangabenFields value={LEER} onChange={() => {}} />);
|
||||
expect((screen.getByLabelText("Bonusanspruch") as HTMLSelectElement).value).toBe("nein");
|
||||
expect((screen.getByLabelText("VL") as HTMLSelectElement).value).toBe("");
|
||||
expect((screen.getByLabelText("FL") as HTMLSelectElement).value).toBe("");
|
||||
});
|
||||
|
||||
it("bietet VL 1 bis 8 und leer an", () => {
|
||||
it("bietet FL 1 bis 7 und leer an", () => {
|
||||
render(<VertragsangabenFields value={LEER} onChange={() => {}} />);
|
||||
const werte = [...(screen.getByLabelText("VL") as HTMLSelectElement).options].map((o) => o.value);
|
||||
expect(werte).toEqual(["", "1", "2", "3", "4", "5", "6", "7", "8"]);
|
||||
const werte = [...(screen.getByLabelText("FL") as HTMLSelectElement).options].map((o) => o.value);
|
||||
expect(werte).toEqual(["", "1", "2", "3", "4", "5", "6", "7"]);
|
||||
});
|
||||
|
||||
it("belegt bei Ja keine Regelung vor", () => {
|
||||
|
||||
@@ -45,6 +45,17 @@ describe("anzeige", () => {
|
||||
expect(anzeige("Rückkehr vom 2026-12-01 auf 2027-03-12")).toBe("Rückkehr vom 01.12.2026 auf 12.03.2027");
|
||||
});
|
||||
|
||||
it("nennt das Ende einer Langzeitabwesenheit „endet am“, die Rückkehr als Ereignis nicht", () => {
|
||||
expect(anzeige("Elternkarenz, geplante Rückkehr am 2026-12-01")).toBe("Elternkarenz, endet am 01.12.2026");
|
||||
expect(anzeige("Elternkarenz ab 2026-03-01, geplante Rückkehr 2026-12-01")).toBe(
|
||||
"Elternkarenz ab 01.03.2026, endet am 01.12.2026"
|
||||
);
|
||||
expect(anzeige("Rückkehr aus Elternkarenz am 2026-12-01")).toBe("Elternkarenz endet am 01.12.2026");
|
||||
expect(anzeige("Geplante Rückkehr")).toBe("Endet am");
|
||||
expect(anzeige("Rückkehr")).toBe("Rückkehr");
|
||||
expect(anzeige("Beschäftigungsausmaß ab Rückkehr")).toBe("Beschäftigungsausmaß ab Rückkehr");
|
||||
});
|
||||
|
||||
it("lässt Zeitstempel und Kennungen stehen", () => {
|
||||
expect(anzeige("2026-11-03T10:00:00Z")).toBe("2026-11-03T10:00:00Z");
|
||||
expect(anzeige("b83ce601-9191-4b67-8979-5ce851b601cf")).toBe("b83ce601-9191-4b67-8979-5ce851b601cf");
|
||||
|
||||
@@ -24,13 +24,32 @@ describe("arbeitszeitBefund", () => {
|
||||
expect(b.fehler).toBeNull();
|
||||
});
|
||||
|
||||
it("rechnet in Zehnteln und nicht in Gleitkommazahlen", () => {
|
||||
it("rechnet in Hundertsteln und nicht in Gleitkommazahlen", () => {
|
||||
// 7,7 × 5 ergibt als Gleitkommazahl 38,49999… — die Prüfung „exakt
|
||||
// gleich" wiese eine völlig richtige Eingabe zurück.
|
||||
const b = arbeitszeitBefund({ Mo: "7.7", Di: "7.7", Mi: "7.7", Do: "7.7", Fr: "7.7" }, WOCHE, 38.5);
|
||||
expect(b.fehler).toBeNull();
|
||||
});
|
||||
|
||||
it("verteilt Wochenstunden mit zwei Nachkommastellen", () => {
|
||||
// 19,25 Stunden an fünf Tagen sind 3,85 je Tag.
|
||||
const b = arbeitszeitBefund({ Mo: "3,85", Di: "3,85", Mi: "3,85", Do: "3,85", Fr: "3,85" }, WOCHE, 19.25);
|
||||
expect(b.summe).toBe(19.25);
|
||||
expect(b.fehler).toBeNull();
|
||||
});
|
||||
|
||||
it("nennt eine Summe mit zwei Nachkommastellen ungerundet", () => {
|
||||
const b = arbeitszeitBefund({ Mo: "4", Di: "4", Mi: "4", Do: "4", Fr: "3,75" }, WOCHE, 19.25);
|
||||
expect(b.fehler).toContain("19,75");
|
||||
expect(b.fehler).toContain("19,25");
|
||||
});
|
||||
|
||||
it("weist eine dritte Nachkommastelle zurück", () => {
|
||||
// Gespeichert würde ein anderer Wert als der eingegebene.
|
||||
const b = arbeitszeitBefund({ Mo: "3,855", Di: "3,85", Mi: "3,85", Do: "3,85", Fr: "3,845" }, WOCHE, 19.25);
|
||||
expect(b.fehler).toContain("zwei Nachkommastellen");
|
||||
});
|
||||
|
||||
it("nimmt auch das Komma, wie es auf einer deutschen Tastatur entsteht", () => {
|
||||
const b = arbeitszeitBefund({ Mo: "8", Di: "8", Mi: "8", Do: "8", Fr: "6,5" }, WOCHE, 38.5);
|
||||
expect(b.fehler).toBeNull();
|
||||
@@ -79,6 +98,10 @@ describe("arbeitszeitFuerDb", () => {
|
||||
expect(arbeitszeitFuerDb({ Mo: "8", Fr: "6,5" }, ["Mo", "Fr"])).toEqual({ Mo: 8, Fr: 6.5 });
|
||||
});
|
||||
|
||||
it("behält zwei Nachkommastellen", () => {
|
||||
expect(arbeitszeitFuerDb({ Mo: "3,85", Fr: "7,75" }, ["Mo", "Fr"])).toEqual({ Mo: 3.85, Fr: 7.75 });
|
||||
});
|
||||
|
||||
it("lässt weggefallene Arbeitstage heraus", () => {
|
||||
// Sonst bliebe ein Dienstag mit acht Stunden an einer Person stehen, die
|
||||
// dienstags nicht mehr arbeitet — und die Bedingung in der Datenbank
|
||||
|
||||
@@ -48,6 +48,7 @@ const NICHT_IM_BLATT_MITARBEITER: Record<string, string> = {
|
||||
Notfallkontakt: "eigenes Blatt „Notfallkontakte“",
|
||||
"Notfallkontakt Telefon": "eigenes Blatt „Notfallkontakte“",
|
||||
"Notfallkontakt Verhältnis": "eigenes Blatt „Notfallkontakte“",
|
||||
"C-Level (Ja/Nein)": "abgelöst durch „C-Level“, wird nicht mehr erfasst",
|
||||
};
|
||||
|
||||
describe("Blatt „Mitarbeiter“ und die Feldkarte", () => {
|
||||
@@ -116,6 +117,7 @@ const FREIE_EINGABE = new Set([
|
||||
"Nachname", "Vorname", "SV-Nummer", "Adresse", "Postleitzahl", "Ort", "Private E-Mail", "Firmen-E-Mail",
|
||||
"Private Telefonnummer", "Cornerstone-ID", "Erlernter Beruf", "Angaben zur Übernahme", "Wochenstunden",
|
||||
"Arbeitszeitmodell", "Wochenstunden ab Rückkehr", "ID", "Name", "Telefonnummer", "Bezeichnung",
|
||||
"Verhältnis (Sonstige)",
|
||||
]);
|
||||
|
||||
describe("Auswahl in der Datei", () => {
|
||||
@@ -231,6 +233,8 @@ describe("Zellen hin und zurück", () => {
|
||||
expect(ausZelle({ art: "zahl", nachkomma: 1 }, "38,5")).toEqual({ art: "wert", wert: 38.5 });
|
||||
expect(ausZelle({ art: "zahl", nachkomma: 1 }, 7.7)).toEqual({ art: "wert", wert: 7.7 });
|
||||
expect(ausZelle({ art: "zahl", nachkomma: 1 }, "7,75").art).toBe("fehler");
|
||||
expect(ausZelle({ art: "zahl", nachkomma: 2 }, "19,25")).toEqual({ art: "wert", wert: 19.25 });
|
||||
expect(ausZelle({ art: "zahl", nachkomma: 2 }, "19,255").art).toBe("fehler");
|
||||
});
|
||||
|
||||
it("weist Werte ausserhalb der Auswahl ab, ausser bei freier Auswahl", () => {
|
||||
|
||||
40
tests/unit/c-level.test.ts
Normal file
40
tests/unit/c-level.test.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { C_LEVEL_AUSWAHL, C_LEVEL_CODES } from "@/lib/c-level";
|
||||
import { feldwertAnzeige, optionenFuer } from "@/lib/historie-felder";
|
||||
import { parseCriteria } from "@/lib/report-criteria";
|
||||
|
||||
// Die Liste steht als CHECK in der Migration und hier für die Oberfläche.
|
||||
// Laufen die beiden auseinander, bietet das Formular einen Wert an, den die
|
||||
// Datenbank abweist.
|
||||
const MIGRATION = join(process.cwd(), "db/migrations/20261123120000_c_level_als_auswahl.sql");
|
||||
|
||||
function werteAusDerBedingung(): string[] {
|
||||
const sql = readFileSync(MIGRATION, "utf8");
|
||||
const block = sql.match(/check \(c_level in \(([^)]*)\)\)/)?.[1];
|
||||
expect(block, "Die Bedingung steht nicht mehr in der Migration").toBeDefined();
|
||||
return [...block!.matchAll(/'([^']+)'/g)].map((m) => m[1]);
|
||||
}
|
||||
|
||||
describe("C-Level", () => {
|
||||
it("stimmt mit der Bedingung in der Datenbank überein", () => {
|
||||
expect(werteAusDerBedingung()).toEqual([...C_LEVEL_CODES]);
|
||||
});
|
||||
|
||||
it("zeigt nur den Code", () => {
|
||||
expect(C_LEVEL_AUSWAHL[0]).toEqual({ value: "C1", label: "C1" });
|
||||
expect(C_LEVEL_AUSWAHL.every((o) => o.value === o.label)).toBe(true);
|
||||
expect(feldwertAnzeige("C-Level", "C4")).toBe("C4");
|
||||
});
|
||||
|
||||
it("berichtigt in der Historie mit derselben Auswahl, das abgelöste Ja/Nein getrennt davon", () => {
|
||||
expect(optionenFuer("C-Level", "C4")?.map((o) => o.value)).toEqual([...C_LEVEL_CODES]);
|
||||
expect(optionenFuer("C-Level (Ja/Nein)", "true")?.map((o) => o.value)).toEqual(["true", "false"]);
|
||||
});
|
||||
|
||||
it("filtert im Bericht nach mehreren Stufen und verwirft Unbekanntes", () => {
|
||||
const werte: Record<string, string> = { clevel: "C1|C9|ja" };
|
||||
expect(parseCriteria((k) => werte[k]).auswahl.clevel).toEqual(["C1", "C9"]);
|
||||
});
|
||||
});
|
||||
@@ -20,7 +20,6 @@ const EXTERN = {
|
||||
is_betriebsrat: false,
|
||||
has_dienstwagen: false,
|
||||
is_laterale_fuehrung: false,
|
||||
is_c_level: false,
|
||||
has_kuendigungsschutz: false,
|
||||
ist_beguenstigt_behindert: false,
|
||||
has_bonusanspruch: false,
|
||||
|
||||
@@ -14,7 +14,7 @@ const units: OrgUnit[] = [
|
||||
{ id: "cnc", org_number: "22002000", name: "CNC", parent_id: "fert", unit_type: "Team" },
|
||||
{ id: "it", org_number: "20200000", name: "IT", parent_id: "gmbh", unit_type: "Bereich" },
|
||||
];
|
||||
const locations = [{ id: "loc-1", name: "Wien-Hernals", country: "Österreich" }];
|
||||
const locations = [{ id: "loc-1", name: "Wien-Hernals", country: "Österreich", parent_id: null }];
|
||||
const maps = buildOrgMaps(units, locations);
|
||||
|
||||
describe("buildOrgMaps", () => {
|
||||
|
||||
@@ -141,7 +141,7 @@ describe("config.matcher", () => {
|
||||
// aufmachen, was Daten fuehrt.
|
||||
it("schickt alles Uebrige weiterhin durch den Gate", () => {
|
||||
for (const pfad of ["/", "/employees", "/employees/123", "/audit", "/reports", "/import",
|
||||
"/api/export/employees", "/api/austausch/importieren", "/login"]) {
|
||||
"/api/export/employees", "/api/austausch/importieren", "/passwort-aendern", "/login"]) {
|
||||
expect(laeuftDurchDenGate(pfad), pfad).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -37,8 +37,8 @@ describe("parseCriteria", () => {
|
||||
});
|
||||
|
||||
it("nimmt ja/nein an und sonst nichts", () => {
|
||||
const c = aus({ dienstwagen: "ja", betriebsrat: "vielleicht", clevel: "nein" });
|
||||
expect(c.jaNein).toEqual({ dienstwagen: "ja", clevel: "nein" });
|
||||
const c = aus({ dienstwagen: "ja", betriebsrat: "vielleicht", lateral: "nein" });
|
||||
expect(c.jaNein).toEqual({ dienstwagen: "ja", lateral: "nein" });
|
||||
});
|
||||
|
||||
it("prüft Zeiträume auf echte Kalenderdaten", () => {
|
||||
|
||||
@@ -40,7 +40,7 @@ function emp(overrides: Partial<ReportEmployee> = {}): ReportEmployee {
|
||||
is_betriebsrat: false,
|
||||
has_dienstwagen: false,
|
||||
is_laterale_fuehrung: false,
|
||||
is_c_level: false,
|
||||
c_level: null,
|
||||
teilzeit_art: null,
|
||||
dependents_count: 0,
|
||||
...overrides,
|
||||
@@ -128,11 +128,15 @@ describe("groupKeyFor", () => {
|
||||
});
|
||||
|
||||
it("resolves the Rolle & Anstellung boolean dimensions as Ja/Nein", () => {
|
||||
const e = emp({ is_betriebsrat: true, has_dienstwagen: false, is_laterale_fuehrung: true, is_c_level: false });
|
||||
const e = emp({ is_betriebsrat: true, has_dienstwagen: false, is_laterale_fuehrung: true });
|
||||
expect(groupKeyFor(e, "betriebsrat", lookups)).toBe("Ja");
|
||||
expect(groupKeyFor(e, "dienstwagen", lookups)).toBe("Nein");
|
||||
expect(groupKeyFor(e, "laterale_fuehrung", lookups)).toBe("Ja");
|
||||
expect(groupKeyFor(e, "c_level", lookups)).toBe("Nein");
|
||||
});
|
||||
|
||||
it("gruppiert nach C-Level mit Code und Bezeichnung, ohne Angabe als eigene Gruppe", () => {
|
||||
expect(groupKeyFor(emp({ c_level: "C9" }), "c_level", lookups)).toBe("C9");
|
||||
expect(groupKeyFor(emp({ c_level: null }), "c_level", lookups)).toBe("Ohne C-Level");
|
||||
});
|
||||
|
||||
it("resolves worker_type/collective_agreement directly", () => {
|
||||
|
||||
12
tests/unit/testsystem.test.ts
Normal file
12
tests/unit/testsystem.test.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { istTestsystem } from "@/lib/testsystem";
|
||||
|
||||
describe("istTestsystem", () => {
|
||||
it("erkennt die eingeschaltete Einstellung", () => {
|
||||
for (const w of ["1", "true", "TRUE", " ja "]) expect(istTestsystem(w), w).toBe(true);
|
||||
});
|
||||
|
||||
it("bleibt ohne Eintrag oder mit anderem Wert aus", () => {
|
||||
for (const w of [undefined, "", "0", "false", "nein", "Produktion"]) expect(istTestsystem(w), String(w)).toBe(false);
|
||||
});
|
||||
});
|
||||
79
tests/unit/verhaeltnis-standorte.test.ts
Normal file
79
tests/unit/verhaeltnis-standorte.test.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { BLATT_ANGEHOERIGE, BLATT_NOTFALLKONTAKTE } from "@/lib/austausch/katalog";
|
||||
import { kurzname, oberstandorte, oberstandortVon, unterstandorte, zuweisbareStandorte } from "@/lib/standorte";
|
||||
import { verhaeltnisAusDatei, verhaeltnisFuerDatei } from "@/lib/verhaeltnis";
|
||||
|
||||
describe("Verhältnis in der Austauschdatei", () => {
|
||||
it("teilt einen frei eingetragenen Wert in „Sonstige“ und den Text", () => {
|
||||
expect(verhaeltnisFuerDatei("Onkel")).toEqual({ auswahl: "Sonstige", sonstige: "Onkel" });
|
||||
expect(verhaeltnisFuerDatei("Kind")).toEqual({ auswahl: "Kind", sonstige: null });
|
||||
expect(verhaeltnisFuerDatei("Sonstige")).toEqual({ auswahl: "Sonstige", sonstige: null });
|
||||
expect(verhaeltnisFuerDatei(null)).toEqual({ auswahl: null, sonstige: null });
|
||||
});
|
||||
|
||||
it("speichert bei „Sonstige“ den Text, ohne Text „Sonstige“", () => {
|
||||
expect(verhaeltnisAusDatei("Sonstige", " Nachbarin ")).toEqual({ wert: "Nachbarin" });
|
||||
expect(verhaeltnisAusDatei("Sonstige", null)).toEqual({ wert: "Sonstige" });
|
||||
expect(verhaeltnisAusDatei("Kind", null)).toEqual({ wert: "Kind" });
|
||||
expect(verhaeltnisAusDatei(null, null)).toEqual({ wert: null });
|
||||
});
|
||||
|
||||
it("weist einen Text ohne „Sonstige“ ab", () => {
|
||||
expect(verhaeltnisAusDatei("Kind", "Onkel")).toHaveProperty("fehler");
|
||||
expect(verhaeltnisAusDatei(null, "Onkel")).toHaveProperty("fehler");
|
||||
});
|
||||
|
||||
it("hat in beiden Blättern die Spalte gleich hinter der Auswahl, die Auswahl ohne freie Eingabe", () => {
|
||||
for (const [blatt, feld] of [
|
||||
[BLATT_ANGEHOERIGE, "relationship"],
|
||||
[BLATT_NOTFALLKONTAKTE, "relation"],
|
||||
] as const) {
|
||||
const i = blatt.spalten.findIndex((s) => s.feld === feld);
|
||||
expect(blatt.spalten[i + 1].feld).toBe(`${feld}_sonstige`);
|
||||
const format = blatt.spalten[i].format;
|
||||
expect(format.art === "auswahl" && format.frei).toBeFalsy();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const ALLE = [
|
||||
{ id: "hernals", name: "Wien-Hernals", parent_id: null },
|
||||
{ id: "shop", name: "Shop", parent_id: null },
|
||||
{ id: "w17", name: "Shop W17", parent_id: "shop" },
|
||||
{ id: "hbf", name: "Shop Wien Hauptbahnhof", parent_id: "shop" },
|
||||
];
|
||||
|
||||
describe("Standorte mit Unterstandorten", () => {
|
||||
it("zeigt zuerst die oberste Ebene und unter „Shop“ die Shops", () => {
|
||||
expect(oberstandorte(ALLE).map((s) => s.id)).toEqual(["hernals", "shop"]);
|
||||
expect(unterstandorte(ALLE, "shop").map((s) => s.id)).toEqual(["w17", "hbf"]);
|
||||
expect(unterstandorte(ALLE, "hernals")).toEqual([]);
|
||||
expect(kurzname(ALLE[3], ALLE[1])).toBe("Wien Hauptbahnhof");
|
||||
});
|
||||
|
||||
it("findet zu einem gespeicherten Shop die erste Auswahl", () => {
|
||||
expect(oberstandortVon(ALLE, "w17")).toBe("shop");
|
||||
expect(oberstandortVon(ALLE, "hernals")).toBe("hernals");
|
||||
expect(oberstandortVon(ALLE, "")).toBe("");
|
||||
});
|
||||
|
||||
it("bietet in Filtern nur Standorte an, auf denen jemand sitzen kann", () => {
|
||||
expect(zuweisbareStandorte(ALLE).map((s) => s.id)).toEqual(["hernals", "w17", "hbf"]);
|
||||
});
|
||||
|
||||
it("legt in der Migration genau die sechs Shops an", () => {
|
||||
const sql = readFileSync(join(process.cwd(), "db/migrations/20261123140000_standort_shop.sql"), "utf8");
|
||||
const einfuegen = sql.match(/from \(values ([^\n]+)\) v\(name\)\non conflict/)?.[1];
|
||||
expect(einfuegen).toBeDefined();
|
||||
expect([...einfuegen!.matchAll(/'([^']+)'/g)].map((m) => m[1])).toEqual([
|
||||
"Shop W17",
|
||||
"Shop Wodo",
|
||||
"Shop Parndorf",
|
||||
"Shop Donaupark",
|
||||
"Shop W1",
|
||||
"Shop Wien Hauptbahnhof",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { anzeige } from "@/lib/anzeige";
|
||||
import { KOLLEKTIVVERTRAEGE } from "@/lib/kollektivvertrag";
|
||||
import {
|
||||
BONUSREGELUNGEN,
|
||||
@@ -19,6 +20,7 @@ import {
|
||||
const migration = (datei: string) => readFileSync(join(process.cwd(), "db/migrations", datei), "utf8");
|
||||
const VERTRAG = migration("20261007100000_vl_bonus_zustaendige_hr.sql");
|
||||
const KV = migration("20261007090000_kollektivvertraege.sql");
|
||||
const FL = migration("20261201120000_fl_ohne_stufe_8.sql");
|
||||
|
||||
function werteDerBedingung(sql: string, name: string): string[] {
|
||||
const block = sql.match(new RegExp(`${name}\\s+check[\\s\\S]*?\\);`))?.[0];
|
||||
@@ -49,10 +51,18 @@ describe("Bonusregelungen", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("VL", () => {
|
||||
it("geht von 1 bis 8, wie in der Datenbank", () => {
|
||||
expect([...VL_STUFEN]).toEqual([1, 2, 3, 4, 5, 6, 7, 8]);
|
||||
expect(VERTRAG).toContain("vl is null or vl between 1 and 8");
|
||||
describe("FL", () => {
|
||||
it("geht von 1 bis 7, wie in der Datenbank", () => {
|
||||
expect([...VL_STUFEN]).toEqual([1, 2, 3, 4, 5, 6, 7]);
|
||||
expect(FL).toContain("vl is null or vl between 1 and 7");
|
||||
});
|
||||
|
||||
it("heisst in der Anzeige FL, auch als Feld der Historie", () => {
|
||||
expect(anzeige("VL")).toBe("FL");
|
||||
expect(anzeige("Geänderte Felder: VL, Bonusanspruch, wirksam ab 2026-12-01")).toBe(
|
||||
"Geänderte Felder: FL, Bonusanspruch, wirksam ab 01.12.2026"
|
||||
);
|
||||
expect(anzeige("VLB")).toBe("VLB");
|
||||
});
|
||||
|
||||
it("zeigt „–“, wenn nichts erfasst ist", () => {
|
||||
|
||||
45
tests/unit/wochenstunden.test.ts
Normal file
45
tests/unit/wochenstunden.test.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { readFileSync, readdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { nachkommaFehler, wochenstundenFehler } from "@/lib/wochenstunden";
|
||||
import { formatStunden } from "@/lib/arbeitszeit";
|
||||
|
||||
describe("wochenstundenFehler", () => {
|
||||
it("nimmt Teilzeit mit zwei Nachkommastellen, mit Komma und mit Punkt", () => {
|
||||
expect(wochenstundenFehler("Teilzeit", "19,25")).toBeNull();
|
||||
expect(wochenstundenFehler("Teilzeit", "19.25")).toBeNull();
|
||||
expect(wochenstundenFehler("Teilzeit", "19,5")).toBeNull();
|
||||
});
|
||||
|
||||
it("weist eine dritte Nachkommastelle zurück", () => {
|
||||
expect(wochenstundenFehler("Teilzeit", "19,255")).toContain("zwei Nachkommastellen");
|
||||
expect(nachkommaFehler("19.255")).not.toBeNull();
|
||||
expect(nachkommaFehler("19.25")).toBeNull();
|
||||
expect(nachkommaFehler("38")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatStunden", () => {
|
||||
it("zeigt zwei Nachkommastellen ohne angehängte Null", () => {
|
||||
expect(formatStunden(19.25)).toBe("19,25");
|
||||
expect(formatStunden(38.5)).toBe("38,5");
|
||||
expect(formatStunden(8)).toBe("8");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Spalte weekly_hours", () => {
|
||||
// Die Eingaben lassen zwei Nachkommastellen zu. Hätte die Spalte weniger,
|
||||
// rundete die Datenbank stillschweigend, und gespeichert wäre ein anderer
|
||||
// Wert als der eingegebene.
|
||||
it("hat in der zuletzt festgelegten Form zwei Nachkommastellen", () => {
|
||||
const verzeichnis = join(process.cwd(), "db", "migrations");
|
||||
const typen = readdirSync(verzeichnis)
|
||||
.filter((f) => f.endsWith(".sql"))
|
||||
.sort()
|
||||
.flatMap((f) => {
|
||||
const text = readFileSync(join(verzeichnis, f), "utf8");
|
||||
return [...text.matchAll(/weekly_hours\s+(?:type\s+)?numeric\((\d+),(\d+)\)/gi)].map((m) => `${m[1]},${m[2]}`);
|
||||
});
|
||||
expect(typen.at(-1)).toBe("4,2");
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user