Alpenwerk HR -- interne HR-Stammdatenverwaltung
Mitarbeiter:innen, Organisationsstruktur, Planstellen, Eintritt, Austritt, Versetzung, Befoerderung, Karenz, On- und Offboarding, Berichte, Massenimport und ein lueckenloser Nachweis jeder Aenderung. Next.js 16 mit React 19 und TypeScript, PostgreSQL 17 ueber Kysely, Anmeldung ueber Microsoft Entra ID. Die Fachlogik liegt in der Datenbank: rund dreissig PL/pgSQL-Funktionen fuehren eine Aenderung, ihren Historieneintrag und ihren Protokolleintrag in einer Transaktion aus. Die Zugriffsschranke ist Row Level Security, nicht die Oberflaeche. Betrieb auf Windows Server ohne Docker: ein fertiges Paket, ein Windows-Dienst, der IIS als HTTPS-Vorschaltung und zwei geplante Aufgaben. Siehe deploy/windows/README.md.
This commit is contained in:
94
tests/integration/employee-status-filter.test.ts
Normal file
94
tests/integration/employee-status-filter.test.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { Kysely, PostgresDialect } from "kysely";
|
||||
import { Pool } from "pg";
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
import { derivedStatusFilter } from "@/lib/employee-status-filter";
|
||||
import type { Schema } from "@/lib/db/schema";
|
||||
import { todayIso } from "@/lib/format";
|
||||
import { deriveStatusAsOf } from "@/lib/reports";
|
||||
import type { EmploymentStatus } from "@/lib/types";
|
||||
|
||||
// lib/employee-status-filter.ts is a SQL restatement of deriveStatusAsOf():
|
||||
// the employee list pages in the database and cannot derive status in JS, so
|
||||
// the same rule exists twice. Two copies of a rule drift, and the drift is
|
||||
// invisible — a dashboard tile and the list it links to just quietly show
|
||||
// different numbers.
|
||||
//
|
||||
// Only a real database can settle it, so this runs both over the whole
|
||||
// seeded roster and demands the same set of ids.
|
||||
//
|
||||
// Eigene Verbindung statt der Zugriffsschicht: geprüft wird die Bedingung,
|
||||
// nicht die Berechtigung. Mit RLS dazwischen liefe der Test gegen eine
|
||||
// gefilterte Teilmenge und bewiese nichts über die Regel.
|
||||
const db = new Kysely<Schema>({
|
||||
dialect: new PostgresDialect({ pool: new Pool({ connectionString: process.env.DATABASE_URL, max: 2 }) }),
|
||||
});
|
||||
|
||||
describe.skipIf(!process.env.DATABASE_URL)("derived status filter matches deriveStatusAsOf", () => {
|
||||
const asOf = todayIso();
|
||||
|
||||
afterAll(async () => {
|
||||
await db.destroy();
|
||||
});
|
||||
|
||||
async function idsFromDatabase(statuses: EmploymentStatus[]): Promise<Set<string>> {
|
||||
const rows = await db
|
||||
.selectFrom("employees")
|
||||
.select("id")
|
||||
.where((eb) => derivedStatusFilter(eb, statuses, asOf) ?? eb.val(true))
|
||||
.execute();
|
||||
return new Set(rows.map((r) => r.id));
|
||||
}
|
||||
|
||||
async function idsFromDerivation(statuses: EmploymentStatus[]): Promise<Set<string>> {
|
||||
const rows = await db
|
||||
.selectFrom("employees")
|
||||
.select(["id", "entry_date", "exit_date", "karenz_start_date", "karenz_return_date"])
|
||||
.execute();
|
||||
return new Set(rows.filter((e) => statuses.includes(deriveStatusAsOf(e, asOf))).map((e) => e.id));
|
||||
}
|
||||
|
||||
async function expectSameSet(statuses: EmploymentStatus[]) {
|
||||
const [fromDb, fromJs] = await Promise.all([idsFromDatabase(statuses), idsFromDerivation(statuses)]);
|
||||
|
||||
const onlyInDb = [...fromDb].filter((id) => !fromJs.has(id));
|
||||
const onlyInJs = [...fromJs].filter((id) => !fromDb.has(id));
|
||||
|
||||
expect({ statuses, onlyInDb: onlyInDb.slice(0, 5), onlyInJs: onlyInJs.slice(0, 5) }).toEqual({
|
||||
statuses,
|
||||
onlyInDb: [],
|
||||
onlyInJs: [],
|
||||
});
|
||||
// Guards against a filter so narrow it matches nothing and passes
|
||||
// trivially.
|
||||
expect(fromJs.size).toBeGreaterThan(0);
|
||||
}
|
||||
|
||||
it("agrees for Aktiv + Karenz — the definition the dashboard headcount uses", async () => {
|
||||
await expectSameSet(["Aktiv", "Karenz"]);
|
||||
});
|
||||
|
||||
it("agrees for Aktiv alone", async () => {
|
||||
await expectSameSet(["Aktiv"]);
|
||||
});
|
||||
|
||||
it("agrees for Karenz alone", async () => {
|
||||
await expectSameSet(["Karenz"]);
|
||||
});
|
||||
|
||||
it("agrees for Geplant", async () => {
|
||||
await expectSameSet(["Geplant"]);
|
||||
});
|
||||
|
||||
it("agrees for Ausgetreten", async () => {
|
||||
await expectSameSet(["Ausgetreten"]);
|
||||
});
|
||||
|
||||
it("returns everyone when no status is selected", async () => {
|
||||
const total = await db
|
||||
.selectFrom("employees")
|
||||
.select(({ fn }) => fn.countAll<string>().as("anzahl"))
|
||||
.executeTakeFirstOrThrow();
|
||||
const filtered = await idsFromDatabase([]);
|
||||
expect(filtered.size).toBe(Number(total.anzahl));
|
||||
});
|
||||
});
|
||||
128
tests/integration/om-reporting.test.ts
Normal file
128
tests/integration/om-reporting.test.ts
Normal file
@@ -0,0 +1,128 @@
|
||||
import { Pool } from "pg";
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
import { todayIso } from "@/lib/format";
|
||||
import { resolveReportingLines, type OmHolder, type OmUnit } from "@/lib/om-reporting";
|
||||
|
||||
// Die Berichtslinien-Regel existiert zweimal: als om_reporting_lines() in
|
||||
// der Datenbank und als resolveReportingLines() im Anwendungscode. Zwei
|
||||
// Fassungen derselben Regel driften auseinander, und die Abweichung fällt
|
||||
// niemandem auf — im Organigramm stünde einfach eine andere Führungskraft
|
||||
// als im Export. Also über den gesamten Bestand gegeneinanderhalten.
|
||||
//
|
||||
// Eigene Verbindung statt der Zugriffsschicht: geprüft wird die Regel, nicht
|
||||
// die Berechtigung. Mit dem Zeilenschutz dazwischen liefe der Vergleich über
|
||||
// eine gefilterte Teilmenge und bewiese nichts.
|
||||
const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 2 });
|
||||
|
||||
describe.skipIf(!process.env.DATABASE_URL)("om_reporting_lines stimmt mit resolveReportingLines überein", () => {
|
||||
const asOf = todayIso();
|
||||
|
||||
afterAll(async () => {
|
||||
await pool.end();
|
||||
});
|
||||
|
||||
type DbZeile = { employee_id: string; formal_manager_id: string | null; acting_manager_id: string | null };
|
||||
|
||||
async function fromDatabase(): Promise<DbZeile[]> {
|
||||
const { rows } = await pool.query<DbZeile>("select * from om_reporting_lines($1)", [asOf]);
|
||||
return rows;
|
||||
}
|
||||
|
||||
async function fromTypeScript() {
|
||||
const { rows: units } = await pool.query<{ id: string; parent_id: string | null }>(
|
||||
"select id, parent_id from org_units"
|
||||
);
|
||||
|
||||
// Dieselbe Gültigkeitsprüfung wie in der Datenbankfunktion: halboffen,
|
||||
// das Ende ausgeschlossen. Sie steht hier ausgeschrieben und nicht als
|
||||
// Aufruf einer gemeinsamen Hilfsfunktion — sonst prüfte der Test die
|
||||
// Regel gegen sich selbst.
|
||||
const { rows: besetzungen } = await pool.query<{
|
||||
employee_id: string;
|
||||
position_id: string;
|
||||
org_unit_id: string;
|
||||
is_chief: boolean;
|
||||
}>(
|
||||
`select a.employee_id, a.position_id, p.org_unit_id, p.is_chief
|
||||
from position_assignments a
|
||||
join om_positions p on p.id = a.position_id
|
||||
where a.valid_from <= $1 and (a.valid_to is null or a.valid_to > $1)
|
||||
and p.valid_from <= $1 and (p.valid_to is null or p.valid_to > $1)`,
|
||||
[asOf]
|
||||
);
|
||||
|
||||
const { rows: personen } = await pool.query<{
|
||||
id: string;
|
||||
karenz_start_date: string | null;
|
||||
karenz_return_date: string | null;
|
||||
}>("select id, karenz_start_date, karenz_return_date from employees");
|
||||
|
||||
const abwesend = new Map(
|
||||
personen.map((e) => [
|
||||
e.id,
|
||||
Boolean(
|
||||
e.karenz_start_date && e.karenz_start_date <= asOf && (!e.karenz_return_date || asOf < e.karenz_return_date)
|
||||
),
|
||||
])
|
||||
);
|
||||
|
||||
const omUnits: OmUnit[] = units.map((u) => ({ id: u.id, parentId: u.parent_id }));
|
||||
const holders: OmHolder[] = besetzungen.map((a) => ({
|
||||
employeeId: a.employee_id,
|
||||
positionId: a.position_id,
|
||||
orgUnitId: a.org_unit_id,
|
||||
isChief: a.is_chief,
|
||||
absent: abwesend.get(a.employee_id) ?? false,
|
||||
}));
|
||||
|
||||
return resolveReportingLines(omUnits, holders);
|
||||
}
|
||||
|
||||
it("liefert für jede Person dieselbe formale und tatsächliche Führungskraft", async () => {
|
||||
const [db, ts] = await Promise.all([fromDatabase(), fromTypeScript()]);
|
||||
|
||||
expect(db.length).toBe(ts.length);
|
||||
expect(db.length).toBeGreaterThan(0);
|
||||
|
||||
const tsById = new Map(ts.map((l) => [l.employeeId, l]));
|
||||
const abweichungen = db
|
||||
.map((row) => {
|
||||
const mine = tsById.get(row.employee_id);
|
||||
if (!mine) return `${row.employee_id}: fehlt in der TypeScript-Fassung`;
|
||||
if (mine.actingManagerId !== row.acting_manager_id)
|
||||
return `${row.employee_id}: acting DB=${row.acting_manager_id} TS=${mine.actingManagerId}`;
|
||||
if (mine.formalManagerId !== row.formal_manager_id)
|
||||
return `${row.employee_id}: formal DB=${row.formal_manager_id} TS=${mine.formalManagerId}`;
|
||||
return null;
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
expect(abweichungen.slice(0, 10)).toEqual([]);
|
||||
});
|
||||
|
||||
it("gibt genau einer Person keine Führungskraft — der obersten Leitung", async () => {
|
||||
const db = await fromDatabase();
|
||||
expect(db.filter((r) => r.acting_manager_id === null)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("erzeugt keine Berichtslinie auf sich selbst", async () => {
|
||||
const db = await fromDatabase();
|
||||
expect(db.filter((r) => r.acting_manager_id === r.employee_id)).toEqual([]);
|
||||
});
|
||||
|
||||
it("lässt jede Berichtslinie an der obersten Leitung enden", async () => {
|
||||
// Ein Ring in den abgeleiteten Linien wäre im Organigramm ein Teilbaum,
|
||||
// der nie gerendert wird — und niemand würde es merken.
|
||||
const db = await fromDatabase();
|
||||
const managerOf = new Map(db.map((r) => [r.employee_id, r.acting_manager_id]));
|
||||
for (const start of db) {
|
||||
const gesehen = new Set<string>();
|
||||
let cur: string | null = start.employee_id;
|
||||
while (cur && !gesehen.has(cur)) {
|
||||
gesehen.add(cur);
|
||||
cur = managerOf.get(cur) ?? null;
|
||||
}
|
||||
expect(cur, `Ring in der Berichtslinie ab ${start.employee_id}`).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
118
tests/integration/session-context.test.ts
Normal file
118
tests/integration/session-context.test.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { Kysely, PostgresDialect, sql } from "kysely";
|
||||
import { Pool } from "pg";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
// Der Test, ohne den die Zugriffsschicht eine Behauptung wäre.
|
||||
//
|
||||
// Die Zugriffsrechte hängen an `current_setting('app.user_id')`. Diese
|
||||
// Variable gehört der *Verbindung*, nicht der Anfrage — und Verbindungen
|
||||
// kommen aus einem Pool. Wird sie ohne Transaktion gesetzt, sieht die
|
||||
// nächste Anfrage auf derselben Verbindung die Kennung der vorherigen
|
||||
// Person.
|
||||
//
|
||||
// Deshalb läuft hier ein Pool mit **genau einer** Verbindung: so ist
|
||||
// garantiert, dass zwei aufeinanderfolgende Zugriffe dieselbe physische
|
||||
// Verbindung benutzen. Mit mehreren Verbindungen würde der Test die Lücke
|
||||
// zufällig mal treffen und mal nicht — und wäre damit wertlos.
|
||||
|
||||
const CONNECTION = process.env.DATABASE_URL;
|
||||
|
||||
// Ohne Datenbank lässt sich lokal nichts prüfen — in der CI wäre ein
|
||||
// stillschweigend übersprungener Sicherheitstest allerdings schlimmer als
|
||||
// gar keiner. Deshalb schlägt dort schon das Fehlen des Verbindungsstrings
|
||||
// fehl, statt eine grüne Anzeige vorzutäuschen.
|
||||
describe("Voraussetzung", () => {
|
||||
it.runIf(process.env.CI)("DATABASE_URL ist in der CI gesetzt", () => {
|
||||
expect(
|
||||
CONNECTION,
|
||||
"DATABASE_URL fehlt. Ohne sie wird der Nachweis zum Sitzungskontext übersprungen — " +
|
||||
"und genau dieser Nachweis trägt die Zugriffsabsicherung."
|
||||
).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
const pool = new Pool({ connectionString: CONNECTION, max: 1 });
|
||||
const db = new Kysely<Record<string, never>>({ dialect: new PostgresDialect({ pool }) });
|
||||
|
||||
/** Die Fassung aus lib/db: transaktionslokal. */
|
||||
async function withUser<T>(userId: string | null, fn: () => Promise<T>): Promise<T> {
|
||||
return db.transaction().execute(async (tx) => {
|
||||
await sql`select set_config('app.user_id', ${userId ?? ""}, true)`.execute(tx);
|
||||
return fn();
|
||||
});
|
||||
}
|
||||
|
||||
async function currentUserOnConnection(): Promise<string | null> {
|
||||
const r = await sql<{ v: string | null }>`select nullif(current_setting('app.user_id', true), '') as v`.execute(db);
|
||||
return r.rows[0]?.v ?? null;
|
||||
}
|
||||
|
||||
describe.skipIf(!CONNECTION)("Sitzungskontext über eine gepoolte Verbindung", () => {
|
||||
const alice = randomUUID();
|
||||
const bob = randomUUID();
|
||||
|
||||
beforeAll(async () => {
|
||||
// Ein Pool mit einer Verbindung: der Test ist nur dann aussagekräftig,
|
||||
// wenn beide Zugriffe garantiert dieselbe benutzen.
|
||||
await sql`select 1`.execute(db);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await db.destroy();
|
||||
});
|
||||
|
||||
it("sieht innerhalb der Transaktion die eigene Kennung", async () => {
|
||||
const seen = await withUser(alice, async () => {
|
||||
const r = await sql<{ v: string }>`select current_setting('app.user_id', true) as v`.execute(db);
|
||||
return r.rows[0].v;
|
||||
});
|
||||
expect(seen).toBe(alice);
|
||||
});
|
||||
|
||||
it("lässt nach der Transaktion nichts an der Verbindung zurück", async () => {
|
||||
// Das ist der eigentliche Befund: nach dem Commit muss die Variable weg
|
||||
// sein. Bliebe sie stehen, liefe die nächste Anfrage im Namen von Alice.
|
||||
await withUser(alice, async () => {
|
||||
await sql`select 1`.execute(db);
|
||||
});
|
||||
expect(await currentUserOnConnection()).toBeNull();
|
||||
});
|
||||
|
||||
it("trägt die Kennung nicht von einer Anfrage in die nächste", async () => {
|
||||
await withUser(alice, async () => {
|
||||
await sql`select 1`.execute(db);
|
||||
});
|
||||
|
||||
const seenByBob = await withUser(bob, async () => {
|
||||
const r = await sql<{ v: string }>`select current_setting('app.user_id', true) as v`.execute(db);
|
||||
return r.rows[0].v;
|
||||
});
|
||||
expect(seenByBob).toBe(bob);
|
||||
expect(seenByBob).not.toBe(alice);
|
||||
});
|
||||
|
||||
it("hinterlässt auch nach einem Fehler keinen Kontext", async () => {
|
||||
// Ein Rollback muss die Variable genauso zurücknehmen wie ein Commit —
|
||||
// sonst wird ausgerechnet der Fehlerfall zur Lücke.
|
||||
await expect(
|
||||
withUser(alice, async () => {
|
||||
await sql`select 1 / 0`.execute(db);
|
||||
})
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(await currentUserOnConnection()).toBeNull();
|
||||
});
|
||||
|
||||
it("zeigt, dass eine Einstellung ohne Transaktion tatsächlich hängen bleibt", async () => {
|
||||
// Die Gegenprobe. Sie belegt, dass die Vorsichtsmassnahme kein Ritual
|
||||
// ist: ohne das dritte Argument `true` überlebt die Kennung die Anfrage
|
||||
// und die nächste Person erbt sie.
|
||||
await sql`select set_config('app.user_id', ${alice}, false)`.execute(db);
|
||||
expect(await currentUserOnConnection()).toBe(alice);
|
||||
|
||||
// Aufräumen, sonst verfälscht dieser Test die anderen.
|
||||
await sql`select set_config('app.user_id', '', false)`.execute(db);
|
||||
expect(await currentUserOnConnection()).toBeNull();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user