Das erste Blatt jeder Datei ist eine Anleitung fuer genau diese Seite (Mitarbeiter, Positionen, Organigramm, Gesamtdatei): vier Schritte, "Gut zu wissen", die haeufigen Aufgaben dieser Seite, die Farben, was tun, wenn es nicht klappt. Gestaltung nach der fachlichen Vorlage. Abhaengig vom Inhalt: die zweite Zeile (erstellt am/von; bei Mitarbeiter Anzahl, Filter mit Namen, Themen, Zusatzblaetter), "Leere Vorlage", wenn der Filter niemanden findet, "Spalte fehlt?" ausser bei "Alle Felder", "Wofuer ist diese Datei?" nur in der Gesamtdatei. Gegenueber der Vorlage: "Gueltig bis" als erster Tag ohne die Planstelle oder Einheit, keine Stellenzahl der Kostenstellennummer, kein Jobkatalog, neue Planstelle mit Taetigkeit und ohne Nummer, Kostenstelle umbenennen, Befoerdern ueber die Taetigkeit, Austritt zuruecknehmen, "Wirksam ab" bei Positionen und Organigramm so, wie der Import es auslegt. Geprueft: Unit-Test, dass jede genannte Spalte, jedes Blatt und jeder Knopf existiert, die bedingten Abschnitte, die zweite Zeile; Integrationstest fuer Anzahl und Filter; lint, tsc, types:check, 1021 Unit-Tests, Waechter.
200 lines
10 KiB
TypeScript
200 lines
10 KiB
TypeScript
import ExcelJS from "exceljs";
|
|
import { Kysely, PostgresDialect, sql } from "kysely";
|
|
import { Pool } from "pg";
|
|
import { afterAll, describe, expect, it, vi } from "vitest";
|
|
import { pruefsumme } from "@/lib/austausch/abgleich";
|
|
import { auswahlAus } from "@/lib/austausch/auswahl";
|
|
import { alsZelle, ausZelle, type Rohzelle } from "@/lib/austausch/format";
|
|
import { austauschdatei, BLATT_ABGLEICH, type BlattInhalt } from "@/lib/austausch/herunterladen";
|
|
import { austauschInhalte } from "@/lib/austausch/zusammenstellen";
|
|
import type { Tx } from "@/lib/db";
|
|
import type { Schema } from "@/lib/db/schema";
|
|
import { todayIso } from "@/lib/format";
|
|
|
|
// Die Austauschdatei gegen eine echte Datenbank: was die Abfragen liefern,
|
|
// was in der Datei steht und was der Import daraus wieder liest.
|
|
//
|
|
// Läuft als Anwendungsrolle mit gesetztem Benutzer — wie die Anwendung, mit
|
|
// Zeilenschutz — und legt seine Daten über dieselben SQL-Funktionen an wie
|
|
// die Oberfläche. Am Ende wird alles zurückgerollt.
|
|
|
|
// lib/db sperrt sich gegen jede Umgebung ausser dem Server von Next. Gebraucht
|
|
// wird von dort nur `sql` (über lib/placement.ts); die Verbindung kommt hier
|
|
// aus dem Test selbst.
|
|
vi.mock("server-only", () => ({}));
|
|
|
|
const db = new Kysely<Schema>({
|
|
dialect: new PostgresDialect({ pool: new Pool({ connectionString: process.env.DATABASE_URL, max: 2 }) }),
|
|
});
|
|
|
|
class Zurueckrollen extends Error {}
|
|
|
|
async function inTransaktion(fn: (tx: Tx) => Promise<void>) {
|
|
try {
|
|
await db.transaction().execute(async (tx) => {
|
|
await sql`select set_config('app.user_id', (select id::text from profiles where role = 'hr' and is_active limit 1), true)`.execute(tx);
|
|
await sql`set local role alpenwerk_app`.execute(tx);
|
|
await fn(tx as unknown as Tx);
|
|
throw new Zurueckrollen();
|
|
});
|
|
} catch (e) {
|
|
if (!(e instanceof Zurueckrollen)) throw e;
|
|
}
|
|
}
|
|
|
|
async function rufe<T>(tx: Tx, funktion: string, payload: Record<string, unknown>): Promise<T> {
|
|
const r = await sql<{ r: T }>`select ${sql.raw(funktion)}(${JSON.stringify(payload)}::jsonb) as r`.execute(tx);
|
|
return r.rows[0].r;
|
|
}
|
|
|
|
function roh(wert: ExcelJS.CellValue): Rohzelle {
|
|
if (wert === null || wert === undefined) return null;
|
|
if (typeof wert === "object" && !(wert instanceof Date)) return null;
|
|
return wert as Rohzelle;
|
|
}
|
|
|
|
describe.skipIf(!process.env.DATABASE_URL)("Austauschdatei gegen die Datenbank", () => {
|
|
afterAll(async () => {
|
|
await db.destroy();
|
|
});
|
|
|
|
it("schreibt den Bestand so, dass der Import ihn unverändert zurückliest", async () => {
|
|
await inTransaktion(async (tx) => {
|
|
const heute = todayIso();
|
|
const wurzel = (await tx.selectFrom("org_units").select("id").where("parent_id", "is", null).executeTakeFirstOrThrow()).id;
|
|
const ort = await tx.selectFrom("locations").select(["id", "name"]).orderBy("name").executeTakeFirstOrThrow();
|
|
const nr = Number((await sql<{ n: number }>`select coalesce(max(personnel_number), 0) + 1 as n from employees`.execute(tx)).rows[0].n);
|
|
|
|
const einheit = await rufe<string>(tx, "create_org_unit", {
|
|
parent_id: wurzel, org_number: "AUSTAUSCH-1", name: "Austausch", unit_type: "Team", valid_from: "2020-01-01",
|
|
});
|
|
await rufe(tx, "create_job", { code: "AUSTAUSCH-J", title: "Austausch Tätigkeit" });
|
|
const stelle = await rufe<string>(tx, "create_position", {
|
|
org_unit_id: einheit, position_number: "ID9101", job_title: "Austausch Tätigkeit", valid_from: "2020-01-01",
|
|
});
|
|
const stelle2 = await rufe<string>(tx, "create_position", {
|
|
org_unit_id: einheit, position_number: "ID9102", job_title: "Austausch Tätigkeit", valid_from: "2020-01-01",
|
|
});
|
|
const stelle3 = await rufe<string>(tx, "create_position", {
|
|
org_unit_id: einheit, position_number: "ID9103", job_title: "Austausch Tätigkeit", valid_from: "2020-01-01",
|
|
});
|
|
await rufe(tx, "create_position", {
|
|
org_unit_id: einheit, position_number: "ID9104", job_title: "Austausch Tätigkeit", valid_from: "2020-01-01",
|
|
});
|
|
const kst = await rufe<string>(tx, "create_cost_center", { code: "AUSTAUSCH-K", name: "Austausch Kostenstelle", valid_from: "2020-01-01" });
|
|
await rufe(tx, "set_position_cost_center", { position_id: stelle, cost_center_id: kst, valid_from: "2020-01-01" });
|
|
|
|
const a = await rufe<string>(tx, "hire_employee", {
|
|
personnel_number: nr, first_name: "Anna", last_name: "Austausch", gender: "w", birth_date: "1985-06-30",
|
|
location_id: ort.id, position_id: stelle, entry_date: "2021-03-01", title_prefix: ["Mag."],
|
|
employment_type: "Teilzeit", weekly_hours: 30, work_days: ["Mo", "Di", "Mi", "Do"],
|
|
arbeitszeitmodell: { Mo: 8, Di: 8, Mi: 8, Do: 6 }, paygrade: "HG12", vl: 3, is_betriebsrat: true,
|
|
nationality: "Österreich", phone: "+43 660 1",
|
|
});
|
|
await rufe(tx, "hire_employee", {
|
|
personnel_number: nr + 1, first_name: "Bert", last_name: "Austauschmann", gender: "m",
|
|
location_id: ort.id, position_id: stelle2, entry_date: heute,
|
|
});
|
|
// Dritte Person: in Abwesenheit, Rückkehr reduziert geplant.
|
|
const c = await rufe<string>(tx, "hire_employee", {
|
|
personnel_number: nr + 2, first_name: "Clara", last_name: "Austauschfrau", gender: "w",
|
|
location_id: ort.id, position_id: stelle3, entry_date: "2022-01-01",
|
|
});
|
|
await rufe(tx, "start_karenz", {
|
|
employee_id: c, karenz_start_date: "2025-01-01", absence_type: "Bildungskarenz",
|
|
});
|
|
await rufe(tx, "rueckkehr_anpassen", {
|
|
employee_id: c, return_date: "2099-03-01", employment_mode: "Teilzeit", weekly_hours: 20,
|
|
reduction_reason: "Elternteilzeit", teilzeit_bis: "2099-12-31",
|
|
});
|
|
await rufe(tx, "add_employee_dependent", {
|
|
employee_id: a, first_name: "Kurt", last_name: "Austausch", relationship: "Kind", birth_date: "2015-01-01",
|
|
});
|
|
await rufe(tx, "add_emergency_contact", { employee_id: a, name: "Nora Austausch", phone: "+43 1 234", relation: "Onkel" });
|
|
|
|
// ── Was die Seite „Import" herunterlädt ───────────────────────────
|
|
const { inhalte, listen } = await austauschInhalte(tx, auswahlAus(new URLSearchParams("seite=import")), heute);
|
|
const blatt = (name: string) => inhalte.find((i) => i.blatt.name === name)!;
|
|
expect(inhalte.map((i) => i.blatt.name)).toEqual([
|
|
"Standorte", "Kostenstellen", "Organisationseinheiten", "Planstellen",
|
|
"Mitarbeiter", "Angehörige", "Notfallkontakte", "Historie",
|
|
]);
|
|
|
|
const zeileA = blatt("Mitarbeiter").datensaetze.find((d) => d.schluessel === nr)!;
|
|
expect(zeileA.werte).toMatchObject({
|
|
location_id: ort.name,
|
|
position_number: "ID9101",
|
|
job_title: "Austausch Tätigkeit",
|
|
org_unit: "Austausch",
|
|
cost_center: "AUSTAUSCH-K · Austausch Kostenstelle",
|
|
status: "Aktiv",
|
|
});
|
|
const ps1 = blatt("Planstellen").datensaetze.find((d) => d.schluessel === "ID9101")!;
|
|
expect(ps1.werte).toMatchObject({ job_title: "Austausch Tätigkeit", org_number: "AUSTAUSCH-1", cost_center: "AUSTAUSCH-K" });
|
|
expect(String(ps1.werte.holder)).toContain(String(nr));
|
|
expect(blatt("Angehörige").datensaetze.filter((d) => d.schluessel === nr)).toHaveLength(1);
|
|
expect(blatt("Notfallkontakte").datensaetze.find((d) => d.schluessel === nr)?.werte.relation).toBe("Onkel");
|
|
expect(blatt("Mitarbeiter").datensaetze.find((d) => d.schluessel === nr + 2)!.werte).toMatchObject({
|
|
karenz_return_date: "2099-03-01",
|
|
rueckkehr_ausmass: "Teilzeit",
|
|
rueckkehr_stunden: 20,
|
|
rueckkehr_grund: "Elternteilzeit",
|
|
rueckkehr_teilzeit_bis: "2099-12-31",
|
|
});
|
|
expect(zeileA.werte).toMatchObject({ rueckkehr_ausmass: null });
|
|
|
|
// Zur Auswahl stehen nur freie Planstellen.
|
|
expect(listen.planstellen).toContain("ID9104");
|
|
expect(listen.planstellen).not.toContain("ID9101");
|
|
expect(listen.planstellen).not.toContain("ID9102");
|
|
expect(listen.planstellen).not.toContain("ID9103");
|
|
expect(blatt("Mitarbeiter").schluesselPruefung?.werte).toContain(nr + 1);
|
|
expect(blatt("Angehörige").schluesselPruefung?.art).toBe("vorhanden");
|
|
|
|
// ── Datei schreiben und zurücklesen ───────────────────────────────
|
|
const mappe = new ExcelJS.Workbook();
|
|
await mappe.xlsx.load((await austauschdatei(inhalte, listen, { am: "heute", von: "Test" })).buffer as ArrayBuffer);
|
|
|
|
for (const inhalt of inhalte as BlattInhalt[]) {
|
|
if (inhalt.blatt.nurLesen) continue;
|
|
const ws = mappe.getWorksheet(inhalt.blatt.name)!;
|
|
inhalt.datensaetze.forEach((d, z) => {
|
|
const zeile = ws.getRow(z + 2);
|
|
inhalt.spalten.forEach((s, i) => {
|
|
if (s.nurLesen) return;
|
|
const gelesen = ausZelle(s.format, roh(zeile.getCell(i + 3).value));
|
|
const erwartet = ausZelle(s.format, alsZelle(s.format, d.werte[s.feld]));
|
|
expect(gelesen, `${inhalt.blatt.name} / ${d.schluessel} / ${s.titel}`).toEqual(erwartet);
|
|
});
|
|
});
|
|
}
|
|
|
|
// Die Prüfsumme in der Datei ist die, die ein erneutes Laden ergibt —
|
|
// sonst meldete der Import jede Zeile als „inzwischen geändert".
|
|
const neu = await austauschInhalte(tx, auswahlAus(new URLSearchParams("seite=import")), heute);
|
|
const abgleich = mappe.getWorksheet(BLATT_ABGLEICH)!.getSheetValues().filter(Boolean) as unknown[][];
|
|
const gespeichert = abgleich.find((r) => r[1] === "Mitarbeiter" && r[2] === String(nr))![3];
|
|
const mitarbeiter = neu.inhalte.find((i) => i.blatt.name === "Mitarbeiter")!;
|
|
const frisch = mitarbeiter.datensaetze.find((d) => d.schluessel === nr)!;
|
|
expect(gespeichert).toBe(pruefsumme(mitarbeiter.spalten, frisch.werte));
|
|
|
|
// ── Die Mitarbeiterliste filtert wie die Seite ────────────────────
|
|
const gefiltert = await austauschInhalte(
|
|
tx,
|
|
auswahlAus(new URLSearchParams("seite=mitarbeiter&q=Austauschmann&status=Aktiv")),
|
|
heute
|
|
);
|
|
const personen = gefiltert.inhalte.find((i) => i.blatt.name === "Mitarbeiter")!.datensaetze.map((d) => d.schluessel);
|
|
expect(personen).toEqual([nr + 1]);
|
|
expect(gefiltert.inhalte.map((i) => i.blatt.name)).toEqual(["Mitarbeiter"]);
|
|
// Die Anleitung nennt Anzahl und Filter so, wie die Liste sie zeigt.
|
|
expect(gefiltert.angaben).toMatchObject({
|
|
seite: "mitarbeiter",
|
|
personen: 1,
|
|
filter: ["Suche „Austauschmann“", "Status Aktiv"],
|
|
alleFelder: false,
|
|
});
|
|
});
|
|
});
|
|
});
|