Übergabestand 2026-10-14

Alpenwerk HR — HR-Stammdatenverwaltung

Mitarbeiter:innen, Organisationsstruktur, Planstellen, Eintritt, Austritt,
Versetzung, Beförderung, Karenz, On- und Offboarding, Berichte, Exporte,
Massenimport und ein lückenloser Nachweis jeder Änderung.

Next.js 16, React 19 und TypeScript; PostgreSQL über Kysely; Anmeldung
ausschliesslich über Microsoft Entra ID. Die Fachlogik liegt in der
Datenbank, die Zugriffsschranke ist Row Level Security.

Betrieb auf Windows Server: siehe deploy/windows/README.md.
Sicherheitskonzept: docs/sicherheitskonzept.md.
This commit is contained in:
2026-10-14 10:12:22 +02:00
commit b47dec6387
410 changed files with 73368 additions and 0 deletions

147
scripts/build-org.ts Normal file
View File

@@ -0,0 +1,147 @@
// Baut den Organisationsbaum im SAP-OM-Modell aus der fachlichen
// Bereichsdefinition des Seeds.
//
// Bewusst frei von Zufall, Datenbank und IDs aus der Umgebung: die
// Konstruktion ist die Stelle, an der sich Nummernkreise, Leitungsplanstellen
// und die Elternbeziehung falsch verdrahten lassen, ohne dass es jemandem
// auffällt — ein Team unter dem falschen Bereich sieht im Organigramm
// plausibel aus. Deshalb ist sie eine reine Funktion mit Tests.
export type OrgUnitType = "Gesellschaft" | "Bereich" | "Abteilung" | "Team";
export type TeamDef = { name: string; leadTitle: string; icTitles: string[]; baseSize: number };
export type DeptDef = { name: string; leadTitle: string; teams: TeamDef[] };
export type DivisionDef = { name: string; headTitle: string; departments: DeptDef[] };
export type BuiltUnit = {
id: string;
org_number: string;
name: string;
parent_id: string | null;
unit_type: OrgUnitType;
};
export type BuiltJob = { id: string; code: string; title: string };
export type BuiltPosition = {
id: string;
position_number: string;
org_unit_id: string;
job_id: string;
is_chief: boolean;
};
export type BuiltOrg = {
units: BuiltUnit[];
jobs: BuiltJob[];
positions: BuiltPosition[];
/** Für jedes Team die Planstellen der Mitarbeitenden, in Reihenfolge. */
icPositionsByTeam: Map<string, BuiltPosition[]>;
};
// Feste Nummernkreise je Ebene, damit sich an der Nummer einer Einheit ihre
// Ebene ablesen lässt.
const PREFIX: Record<OrgUnitType, string> = {
Gesellschaft: "10",
Bereich: "20",
Abteilung: "21",
Team: "22",
};
function orgNumber(type: OrgUnitType, counter: number): string {
return `${PREFIX[type]}${String(counter).padStart(6, "0")}`;
}
/** Planstellennummern folgen dem bestehenden Muster ^6\d{7}$. */
function positionNumber(counter: number): string {
return `6${String(counter).padStart(7, "0")}`;
}
function jobCode(counter: number): string {
return `J${String(counter).padStart(4, "0")}`;
}
/**
* `newId` wird hereingereicht, damit die Funktion in Tests deterministisch
* bleibt und im Seed randomUUID benutzt.
*/
export function buildOrg(
companyName: string,
divisions: DivisionDef[],
newId: () => string
): BuiltOrg {
const units: BuiltUnit[] = [];
const positions: BuiltPosition[] = [];
const icPositionsByTeam = new Map<string, BuiltPosition[]>();
// Job-Katalog: gleiche Tätigkeit, ein Eintrag. Nur so lassen sich
// Tätigkeiten auswerten — Freitext je Person liesse das nicht zu.
const jobIdByTitle = new Map<string, string>();
const jobs: BuiltJob[] = [];
function jobFor(title: string): string {
const existing = jobIdByTitle.get(title);
if (existing) return existing;
const job = { id: newId(), code: jobCode(jobs.length + 1), title };
jobs.push(job);
jobIdByTitle.set(title, job.id);
return job.id;
}
let unitCounter = { Gesellschaft: 0, Bereich: 0, Abteilung: 0, Team: 0 };
let positionCounter = 0;
function addUnit(name: string, type: OrgUnitType, parentId: string | null): BuiltUnit {
unitCounter = { ...unitCounter, [type]: unitCounter[type] + 1 };
const unit: BuiltUnit = {
id: newId(),
org_number: orgNumber(type, unitCounter[type] * (type === "Team" ? 1000 : type === "Abteilung" ? 10000 : 100000)),
name,
parent_id: parentId,
unit_type: type,
};
units.push(unit);
return unit;
}
function addPosition(unitId: string, title: string, isChief: boolean): BuiltPosition {
positionCounter += 1;
const position: BuiltPosition = {
id: newId(),
position_number: positionNumber(positionCounter),
org_unit_id: unitId,
job_id: jobFor(title),
is_chief: isChief,
};
positions.push(position);
return position;
}
const company = addUnit(companyName, "Gesellschaft", null);
addPosition(company.id, "Geschäftsführer:in", true);
// Die Assistenz hängt an der Gesellschaft, führt sie aber nicht.
addPosition(company.id, "Assistenz der Geschäftsführung", false);
for (const div of divisions) {
const bereich = addUnit(div.name, "Bereich", company.id);
addPosition(bereich.id, div.headTitle, true);
for (const dept of div.departments) {
const abteilung = addUnit(dept.name, "Abteilung", bereich.id);
// Eine Abteilung hat eine eigene Leitungsplanstelle.
addPosition(abteilung.id, dept.leadTitle, true);
for (const team of dept.teams) {
const teamUnit = addUnit(team.name, "Team", abteilung.id);
addPosition(teamUnit.id, team.leadTitle, true);
const size = Math.max(1, team.baseSize);
const icPositions = Array.from({ length: size }, (_, i) =>
addPosition(teamUnit.id, team.icTitles[i % team.icTitles.length], false)
);
icPositionsByTeam.set(teamUnit.id, icPositions);
}
}
}
return { units, jobs, positions, icPositionsByTeam };
}

View File

@@ -0,0 +1,204 @@
#!/usr/bin/env node
// Guards lib/types.ts against drifting away from the migrations.
//
// That file is maintained by hand — nothing generates it — so a new
// column can reach the database without the TypeScript side noticing — and
// `tsc` stays perfectly happy while the app reads a field that is typed but
// absent, or writes one that exists but is not typed.
//
// Reads the migrations rather than a live database on purpose: CI then needs
// no Postgres, and the migrations are the actual source of truth for what
// gets deployed.
import { readFileSync, readdirSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const migrationsDir = join(root, "db", "migrations");
// Columns are compared, not their types: the hand-written file deliberately
// uses richer unions than the SQL (`EmploymentStatus` for a text column with
// a check constraint), and flagging those would be noise.
const NON_COLUMN_START =
/^(constraint|check|primary|unique|foreign|exclude|like|inherits|partition|)$/i;
function stripComments(sql) {
return sql.replace(/--[^\n]*/g, "");
}
/** Splits on top-level commas only, so `numeric(10,2)` stays in one piece. */
function splitTopLevel(body) {
const parts = [];
let depth = 0;
let current = "";
for (const ch of body) {
if (ch === "(") depth++;
if (ch === ")") depth--;
if (ch === "," && depth === 0) {
parts.push(current);
current = "";
continue;
}
current += ch;
}
if (current.trim()) parts.push(current);
return parts;
}
function parseMigrations() {
const tables = new Map();
const files = readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
for (const file of files) {
const sql = stripComments(readFileSync(join(migrationsDir, file), "utf8"));
for (const match of sql.matchAll(/create table (?:if not exists )?(\w+)\s*\(/gi)) {
const name = match[1];
// Walk from the opening paren to its match so nested parens in column
// definitions do not end the table early.
let depth = 0;
let end = match.index + match[0].length - 1;
for (let i = end; i < sql.length; i++) {
if (sql[i] === "(") depth++;
else if (sql[i] === ")") {
depth--;
if (depth === 0) {
end = i;
break;
}
}
}
const body = sql.slice(match.index + match[0].length, end);
const columns = new Set();
for (const part of splitTopLevel(body)) {
const first = part.trim().split(/\s+/)[0] ?? "";
if (!first || NON_COLUMN_START.test(first)) continue;
columns.add(first.toLowerCase());
}
tables.set(name, columns);
}
// ── ALTER TABLE, vollständig ────────────────────────────────────
//
// Eine Anweisung kann mehrere Klauseln tragen, durch Komma getrennt:
//
// alter table employees
// drop column if exists division_id,
// drop column if exists team_id,
// drop column if exists manager_id;
//
// Wer nur nach `alter table … drop column …` als **einem** Muster sucht,
// findet davon genau die erste. Die übrigen blieben im Modell stehen, und der
// Abgleich meldete Spalten als vorhanden, die längst gelöscht sind.
// Umgekehrt fehlten Spalten, die als zweite Klausel eines `add column`
// hinzukommen.
//
// Deshalb wird hier erst die ganze Anweisung bis zum Semikolon
// aufgesammelt und dann jede Klausel darin ausgewertet. Klammern zählen
// mit, damit ein Semikolon in einer Prüfbedingung die Anweisung nicht
// vorzeitig beendet.
for (const kopf of sql.matchAll(/alter table (?:if exists )?(\w+)/gi)) {
const tabelle = tables.get(kopf[1]);
if (!tabelle) continue;
let tiefe = 0;
let ende = kopf.index + kopf[0].length;
for (; ende < sql.length; ende++) {
const c = sql[ende];
if (c === "(") tiefe++;
else if (c === ")") tiefe--;
else if (c === ";" && tiefe === 0) break;
}
const anweisung = sql.slice(kopf.index + kopf[0].length, ende);
// Eine umbenannte Tabelle behält ihre Spalten und wechselt den Namen.
// Ohne diesen Fall stünde der alte Name weiter im Modell aus den
// Migrationen, und der Abgleich meldete zwei Fehler für eine Änderung:
// die alte Tabelle fehle in lib/types.ts, die neue kenne das Schema
// nicht. `rename constraint` und `rename column` sind davon nicht
// betroffen — nur das unmittelbare `rename to`.
const umbenannt = anweisung.match(/^\s*rename to (\w+)/i);
if (umbenannt) {
tables.delete(kopf[1].toLowerCase());
tables.set(umbenannt[1].toLowerCase(), tabelle);
continue;
}
for (const m of anweisung.matchAll(/\badd column (?:if not exists )?(\w+)/gi)) {
tabelle.add(m[1].toLowerCase());
}
for (const m of anweisung.matchAll(/\bdrop column (?:if exists )?(\w+)/gi)) {
tabelle.delete(m[1].toLowerCase());
}
for (const m of anweisung.matchAll(/\brename column (\w+) to (\w+)/gi)) {
if (tabelle.delete(m[1].toLowerCase())) tabelle.add(m[2].toLowerCase());
}
}
for (const m of sql.matchAll(/drop table (?:if exists )?(\w+)/gi)) {
tables.delete(m[1]);
}
}
return tables;
}
function parseTypes() {
const source = readFileSync(join(root, "lib", "types.ts"), "utf8");
const start = source.indexOf("Tables: {");
if (start === -1) throw new Error("Tables block not found in lib/types.ts");
const tables = new Map();
// Each entry looks like `name: NoRelationships & { Row: { … } … }`; the Row
// block is the one that has to match the database.
const entry = /^ {6}(\w+): /gm;
for (const m of source.slice(start).matchAll(entry)) {
const rest = source.slice(start + m.index);
const rowAt = rest.indexOf("Row: {");
if (rowAt === -1) continue;
let depth = 0;
let end = rowAt + "Row: ".length;
for (let i = end; i < rest.length; i++) {
if (rest[i] === "{") depth++;
else if (rest[i] === "}") {
depth--;
if (depth === 0) {
end = i;
break;
}
}
}
const body = rest.slice(rowAt + "Row: {".length, end);
const columns = new Set();
for (const f of body.matchAll(/(\w+)\s*\??\s*:/g)) columns.add(f[1].toLowerCase());
tables.set(m[1], columns);
}
return tables;
}
const sqlTables = parseMigrations();
const tsTables = parseTypes();
const problems = [];
for (const [name, columns] of tsTables) {
const sqlColumns = sqlTables.get(name);
if (!sqlColumns) {
problems.push(`Tabelle "${name}" ist in types.ts typisiert, existiert aber in keiner Migration.`);
continue;
}
for (const c of columns) {
if (!sqlColumns.has(c)) problems.push(`${name}.${c}: in types.ts typisiert, in den Migrationen nicht vorhanden.`);
}
for (const c of sqlColumns) {
if (!columns.has(c)) problems.push(`${name}.${c}: in den Migrationen vorhanden, in types.ts nicht typisiert.`);
}
}
if (problems.length > 0) {
console.error("Schema-Drift zwischen db/migrations und lib/types.ts:\n");
for (const p of problems.sort()) console.error(" - " + p);
console.error(`\n${problems.length} Abweichung(en). types.ts entsprechend nachziehen.`);
process.exit(1);
}
console.log(`Kein Schema-Drift: ${tsTables.size} typisierte Tabellen stimmen mit den Migrationen überein.`);

141
scripts/db-setup.mjs Normal file
View File

@@ -0,0 +1,141 @@
#!/usr/bin/env node
// Richtet eine vorhandene PostgreSQL-Installation für die Anwendung ein:
// Datenbank, Anwendungsrolle, Erweiterungen, Schemarecht.
//
// ═══ Warum es das als Node-Skript gibt ═══
//
// Es braucht nur Node und `pg`, also genau das, was der Migrationsläufer auch
// braucht — kein psql, keine Shell, kein Paketzugang. Auf dem Server ist das
// der Unterschied zwischen „läuft" und „läuft nur dort, wo jemand vorher
// Werkzeug installiert hat".
//
// Es ist wiederholbar: ein zweiter Lauf legt nichts doppelt an und gleicht nur
// das Passwort der Anwendungsrolle ab.
//
// ═══ Woher die Werte kommen ═══
//
// Keine eigenen Variablen — es liest dieselben zwei Verbindungen wie der Rest:
//
// MIGRATE_DATABASE_URL Verwalter (postgres) und Name der Datenbank
// DATABASE_URL Name und Passwort der Anwendungsrolle
//
// Steht das Passwort der Anwendungsrolle nur an einer Stelle, kann es nicht
// auseinanderlaufen. Ein Wechsel heisst: DATABASE_URL ändern, dieses Skript
// erneut laufen lassen, Dienst neu starten.
//
// ═══ Aufruf ═══
//
// node --env-file=.env --env-file=verwaltung.env scripts/db-setup.mjs
//
// Danach: scripts/migrate.mjs.
import { readFileSync } from "node:fs";
import pg from "pg";
function verbindungLesen(name) {
const wert = process.env[name];
if (!wert) {
console.error(`${name} fehlt.`);
process.exit(1);
}
try {
return new URL(wert);
} catch {
console.error(`${name} ist keine gültige Verbindungs-URL.`);
process.exit(1);
}
}
const verwalter = verbindungLesen("MIGRATE_DATABASE_URL");
const anwendung = verbindungLesen("DATABASE_URL");
const datenbank = decodeURIComponent(verwalter.pathname.replace(/^\//, ""));
const appRolle = decodeURIComponent(anwendung.username);
const appPasswort = decodeURIComponent(anwendung.password);
if (!datenbank) {
console.error("MIGRATE_DATABASE_URL nennt keine Datenbank (…/alpenwerk am Ende).");
process.exit(1);
}
if (decodeURIComponent(anwendung.pathname.replace(/^\//, "")) !== datenbank) {
console.error("DATABASE_URL und MIGRATE_DATABASE_URL zeigen auf verschiedene Datenbanken.");
process.exit(1);
}
if (!appRolle || !appPasswort) {
console.error("DATABASE_URL braucht Benutzer und Passwort der Anwendungsrolle.");
process.exit(1);
}
// Die Anwendung darf nicht als Verwalter laufen: der umgeht RLS, und die ganze
// Zugriffsprüfung wäre wirkungslos, ohne dass es jemand merkt.
if (appRolle === decodeURIComponent(verwalter.username)) {
console.error("DATABASE_URL benutzt denselben Benutzer wie MIGRATE_DATABASE_URL — die Anwendung braucht eine eigene Rolle.");
process.exit(1);
}
const ssl = process.env.DATABASE_SSL === "false" ? undefined : { rejectUnauthorized: false };
async function mitVerbindung(url, arbeit) {
const client = new pg.Client({ connectionString: url.toString(), ssl });
await client.connect();
try {
return await arbeit(client);
} finally {
await client.end();
}
}
const ident = (name) => `"${name.replace(/"/g, '""')}"`;
// ── 1. Datenbank und Rollen (auf der Wartungsdatenbank `postgres`) ──────
const wartung = new URL(verwalter);
wartung.pathname = "/postgres";
await mitVerbindung(wartung, async (client) => {
const vorhanden = (await client.query("select 1 from pg_database where datname = $1", [datenbank])).rowCount > 0;
if (vorhanden) {
console.log(`Datenbank ${datenbank} besteht bereits.`);
} else {
// ICU mit de-AT: Umlaute sortieren
// in einer Mitarbeiterliste dort, wo man sie sucht. Unabhängig von der
// Gebietsschema-Einstellung des Betriebssystems — unter Windows hiesse sie
// sonst „German_Austria.1252" und unter Linux „de_AT.UTF-8".
await client.query(
`create database ${ident(datenbank)} with template template0 encoding 'UTF8' locale_provider icu icu_locale 'de-AT'`
);
console.log(`Datenbank ${datenbank} angelegt (UTF8, ICU de-AT).`);
}
// Ohne BYPASSRLS — das ist der Punkt, siehe deploy/db-init/00-….sql.
const rolleDa = (await client.query("select 1 from pg_roles where rolname = $1", [appRolle])).rowCount > 0;
const passwort = client.escapeLiteral(appPasswort);
if (rolleDa) {
await client.query(`alter role ${ident(appRolle)} with login nobypassrls nosuperuser password ${passwort}`);
console.log(`Rolle ${appRolle} besteht, Passwort abgeglichen.`);
} else {
await client.query(`create role ${ident(appRolle)} with login nobypassrls nosuperuser password ${passwort}`);
console.log(`Rolle ${appRolle} angelegt (ohne BYPASSRLS).`);
}
// Platzhalterrollen ohne Anmelderecht: die ersten Migrationen vergeben
// Rechte auf diese Namen und brächen ohne sie ab. Anmelden kann sich damit
// niemand.
for (const name of ["anon", "authenticated", "service_role"]) {
const da = (await client.query("select 1 from pg_roles where rolname = $1", [name])).rowCount > 0;
if (!da) await client.query(`create role ${ident(name)} nologin`);
}
});
// ── 2. Erweiterungen, auth-Attrappe, Schemarecht (in der Datenbank) ──────
await mitVerbindung(verwalter, async (client) => {
// In `public`, nicht in einem eigenen Schema: der search_path der
// SECURITY-DEFINER-Funktionen ist auf `public, pg_temp` festgelegt.
await client.query("create extension if not exists pgcrypto");
await client.query("create extension if not exists pg_trgm");
// Reines SQL, ohne psql-Eigenheiten — deshalb direkt ausführbar.
await client.query(readFileSync("deploy/db-init/01-auth-attrappe.sql", "utf8"));
await client.query(`grant usage on schema public to ${ident(appRolle)}`);
});
console.log("Einrichtung fertig. Als Nächstes: scripts/migrate.mjs");

140
scripts/migrate.mjs Normal file
View File

@@ -0,0 +1,140 @@
#!/usr/bin/env node
// Spielt ausstehende Migrationen ein — und führt Buch darüber.
//
// ═══ Warum ein eigener Läufer ═══
//
// Zwei Gründe, beide praktisch:
//
// 1. **Er braucht nur `pg`.** Das Paket liegt ohnehin im Projekt; auf dem
// Server ist ausser Node nichts zu installieren.
// 2. **Er tut genau eine Sache.** Nur die fehlenden Dateien, in Reihenfolge,
// jede in ihrer eigenen Transaktion — und nichts darüber hinaus.
//
// Die Buchführung liegt in `migrationen.schema_migrations`.
//
// ═══ Aufrufe ═══
//
// node scripts/migrate.mjs ausstehende anwenden
// node scripts/migrate.mjs --dry-run nur zeigen, was anstünde
// node scripts/migrate.mjs --baseline alles als angewendet verbuchen,
// **ohne** es auszuführen
//
// `--baseline` ist für den einen Fall gedacht, in dem eine Datenbank schon auf
// dem Stand ist, die Buchführung aber fehlt, etwa nach dem Einspielen einer
// Sicherung ohne das Schema `migrationen`. Ohne diesen Schritt hielte der
// Läufer alle Dateien für ausstehend und liesse sie gegen eine bereits
// migrierte Datenbank laufen.
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import pg from "pg";
const VERZEICHNIS = "db/migrations";
const argumente = new Set(process.argv.slice(2));
const nurZeigen = argumente.has("--dry-run");
const baseline = argumente.has("--baseline");
// Der **direkte** Zugang als Verwalter — nicht DATABASE_URL.
//
// DATABASE_URL gehört der Anwendungsrolle, und die darf bewusst kein Schema
// ändern.
const verbindung = process.env.MIGRATE_DATABASE_URL;
if (!verbindung) {
console.error(
"MIGRATE_DATABASE_URL fehlt. Erwartet wird der **direkte** Zugang als Verwalter,\n" +
"nicht die Verbindung der Anwendung aus DATABASE_URL."
);
process.exit(1);
}
/** Dateiname → { version, name }; „20260818100000_offboarding.sql". */
function zerlegen(datei) {
const punkt = datei.indexOf("_");
return punkt === -1
? { version: datei.replace(/\.sql$/, ""), name: "" }
: { version: datei.slice(0, punkt), name: datei.slice(punkt + 1).replace(/\.sql$/, "") };
}
const dateien = readdirSync(VERZEICHNIS)
.filter((f) => f.endsWith(".sql"))
.sort();
const client = new pg.Client({
connectionString: verbindung,
ssl: process.env.DATABASE_SSL === "false" ? undefined : { rejectUnauthorized: false },
});
await client.connect();
try {
await client.query(`create schema if not exists migrationen`);
await client.query(`
create table if not exists migrationen.schema_migrations (
version text primary key,
statements text[],
name text
)`);
const verbucht = new Set(
(await client.query(`select version from migrationen.schema_migrations`)).rows.map((r) => r.version)
);
const ausstehend = dateien.filter((f) => !verbucht.has(zerlegen(f).version));
if (ausstehend.length === 0) {
console.log(`Nichts anzuwenden — ${verbucht.size} Migrationen verbucht, ${dateien.length} Dateien vorhanden.`);
process.exit(0);
}
if (nurZeigen) {
console.log(`${ausstehend.length} ausstehend:`);
for (const f of ausstehend) console.log(" " + f);
process.exit(0);
}
if (baseline) {
// Nur verbuchen. Der Inhalt wird trotzdem mitgeschrieben, damit später
// nachvollziehbar ist, welcher Text als angewendet galt.
for (const datei of ausstehend) {
const { version, name } = zerlegen(datei);
const inhalt = readFileSync(join(VERZEICHNIS, datei), "utf8");
await client.query(
`insert into migrationen.schema_migrations (version, statements, name)
values ($1, $2, $3) on conflict (version) do nothing`,
[version, [inhalt], name]
);
}
console.log(`${ausstehend.length} Migrationen als angewendet verbucht, ohne sie auszuführen.`);
process.exit(0);
}
console.log(`${ausstehend.length} ausstehend, werden angewendet:`);
for (const datei of ausstehend) {
const { version, name } = zerlegen(datei);
const inhalt = readFileSync(join(VERZEICHNIS, datei), "utf8");
const start = Date.now();
// Jede Datei in ihrer eigenen Transaktion: eine, die scheitert, hinterlässt
// nichts Halbes, und die davor bleiben angewendet und verbucht. Der Lauf
// bricht danach ab — weiterzumachen hiesse, auf einem Stand aufzubauen,
// den es nicht gibt.
await client.query("begin");
try {
await client.query(inhalt);
await client.query(
`insert into migrationen.schema_migrations (version, statements, name) values ($1, $2, $3)`,
[version, [inhalt], name]
);
await client.query("commit");
console.log(` ok ${datei} (${Date.now() - start} ms)`);
} catch (fehler) {
await client.query("rollback");
console.error(` FEHLGESCHLAGEN ${datei}`);
console.error(" " + (fehler instanceof Error ? fehler.message : String(fehler)));
process.exit(1);
}
}
console.log("Fertig.");
} finally {
await client.end();
}

148
scripts/windows-paket.mjs Normal file
View File

@@ -0,0 +1,148 @@
#!/usr/bin/env node
// Baut das Auslieferungspaket für den Betrieb auf einem Windows-Server
// (siehe deploy/windows/README.md).
//
// npm run paket:windows baut neu und packt
// npm run paket:windows -- --ohne-build packt den vorhandenen Build
//
// Ergebnis: dist/alpenwerk-hr-windows-<datum>-<commit>/ und daneben dieselbe
// Fassung als .zip. Auf dem Server wird nur Node gebraucht — kein npm, kein
// Zugang zur Paketquelle, kein Build.
//
// ═══ Warum das Paket überall gebaut werden kann ═══
//
// Der Standalone-Build enthält nur JavaScript, mit einer Ausnahme: `sharp`,
// das Next für die Bildoptimierung von next/image mitverfolgt — samt einer
// Binärdatei für das Betriebssystem, auf dem gebaut wurde. Die Anwendung
// benutzt next/image nirgends (das Logo ist ein schlichtes <img>), sharp wird
// also nie geladen und fliegt hier raus. Danach prüft das Skript, dass keine
// einzige native Datei (*.node) mehr im Paket liegt; sonst bricht es ab.
//
// ═══ Symlinks ═══
//
// Turbopack legt unter .next/node_modules Verweise wie `pg-<hash>` →
// ../../node_modules/pg an. Ein Zip-Archiv trägt die unter Windows nicht
// verlässlich, deshalb werden sie beim Kopieren aufgelöst.
import { execFileSync } from "node:child_process";
import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
import { join, relative } from "node:path";
const ohneBuild = process.argv.includes("--ohne-build");
function lauf(befehl, args) {
execFileSync(befehl, args, { stdio: "inherit", shell: process.platform === "win32" });
}
if (!ohneBuild) lauf("npm", ["run", "build"]);
if (!existsSync(".next/standalone/server.js")) {
console.error("Kein Standalone-Build gefunden (.next/standalone/server.js). Erst `npm run build`.");
process.exit(1);
}
const commit = execFileSync("git", ["rev-parse", "--short", "HEAD"], { encoding: "utf8" }).trim();
const unsauber = execFileSync("git", ["status", "--porcelain"], { encoding: "utf8" }).trim() !== "";
const datum = new Date().toISOString().slice(0, 10).replace(/-/g, "");
const name = `alpenwerk-hr-windows-${datum}-${commit}${unsauber ? "-lokal" : ""}`;
const ziel = join("dist", name);
const app = join(ziel, "app");
rmSync(ziel, { recursive: true, force: true });
rmSync(`${ziel}.zip`, { force: true });
mkdirSync(app, { recursive: true });
// ── Anwendung ─────────────────────────────────────────────────────────
cpSync(".next/standalone", app, { recursive: true });
// `dereference` von cpSync wirkt nur auf die Quelle selbst, nicht auf
// verschachtelte Verweise — deshalb hier von Hand: Verweis weg, Ziel als
// echtes Verzeichnis an seine Stelle.
(function aufloesen(verzeichnis) {
for (const eintrag of readdirSync(verzeichnis)) {
const pfad = join(verzeichnis, eintrag);
const info = lstatSync(pfad);
if (info.isSymbolicLink()) {
const quelle = realpathSync(join(".next/standalone", relative(app, pfad)));
rmSync(pfad, { force: true });
cpSync(quelle, pfad, { recursive: true });
} else if (info.isDirectory()) {
aufloesen(pfad);
}
}
})(app);
cpSync("public", join(app, "public"), { recursive: true });
cpSync(".next/static", join(app, ".next/static"), { recursive: true });
for (const weg of ["node_modules/sharp", "node_modules/@img"]) {
rmSync(join(app, weg), { recursive: true, force: true });
}
// Eine .env gehört nie ins Paket — sie liegt auf dem Server neben der
// Anwendung, nicht darin.
for (const datei of readdirSync(app)) {
if (datei.startsWith(".env")) rmSync(join(app, datei), { force: true });
}
// ── Datenbank-Werkzeuge ───────────────────────────────────────────────
// Mit denselben relativen Pfaden wie im Repository: beide Skripte lesen
// db/migrations bzw. deploy/db-init vom Arbeitsverzeichnis aus, und `pg` finden
// sie in app/node_modules.
mkdirSync(join(app, "scripts"), { recursive: true });
cpSync("scripts/migrate.mjs", join(app, "scripts/migrate.mjs"));
cpSync("scripts/db-setup.mjs", join(app, "scripts/db-setup.mjs"));
cpSync("db/migrations", join(app, "db/migrations"), { recursive: true });
// Der Rauchtest gehoert mit aufs Ziel.
//
// Er ist die einzige Pruefung, die die Funktionen wirklich **aufruft** statt
// ihren Text zu lesen: Einstellung, Versetzung, Befoerderung, Austritt,
// Wiedereintritt, in einer Transaktion, die am Ende verworfen wird. Genau die
// Luecke, die er schliesst, hat eine kaputte Funktion zwoelf Tage lang
// unbemerkt gelassen.
//
// Ohne ihn im Paket gibt es auf dem Zielserver keine Moeglichkeit zu pruefen,
// ob die Anwendung dort nicht nur startet, sondern auch arbeitet.
cpSync("db/tests", join(app, "db/tests"), { recursive: true });
mkdirSync(join(app, "deploy/db-init"), { recursive: true });
cpSync("deploy/db-init/01-auth-attrappe.sql", join(app, "deploy/db-init/01-auth-attrappe.sql"));
// ── Betriebsskripte ───────────────────────────────────────────────────
cpSync("deploy/windows", join(ziel, "windows"), { recursive: true });
writeFileSync(
join(ziel, "VERSION.txt"),
[
`Commit: ${commit}${unsauber ? " (mit lokalen, nicht eingecheckten Änderungen)" : ""}`,
`Gebaut: ${new Date().toISOString()}`,
`Mit Node: ${process.version}`,
"",
].join("\r\n")
);
// ── Prüfungen ─────────────────────────────────────────────────────────
const fremd = [];
(function durchsuchen(verzeichnis) {
for (const eintrag of readdirSync(verzeichnis)) {
const pfad = join(verzeichnis, eintrag);
const info = lstatSync(pfad);
if (info.isSymbolicLink()) fremd.push(`Symlink: ${pfad}`);
else if (info.isDirectory()) durchsuchen(pfad);
else if (eintrag.endsWith(".node")) fremd.push(`Native Datei: ${pfad}`);
}
})(ziel);
if (fremd.length > 0) {
console.error("Das Paket ist nicht plattformunabhängig:\n " + fremd.join("\n "));
process.exit(1);
}
if (!existsSync(join(app, ".next/node_modules")) || !statSync(join(app, "node_modules/pg")).isDirectory()) {
console.error("pg fehlt im Paket — der Build hat sich verändert, die Annahmen hier stimmen nicht mehr.");
process.exit(1);
}
// ── Zip ──────────────────────────────────────────────────────────────
// tar mit -a wählt das Format nach der Endung; bsdtar auf macOS und das tar
// in Windows 10+ können beide Zip schreiben.
try {
execFileSync("tar", ["-a", "-c", "-f", `${name}.zip`, name], { cwd: "dist", stdio: "inherit" });
console.log(`\nPaket: ${ziel}.zip`);
} catch {
console.log(`\nZip konnte nicht erstellt werden; das Verzeichnis ${ziel} ist vollständig.`);
}