Files
alpenwerk-hr/app/api/import/template/route.ts
Maximilian Stubhan 3926f1bb80 Load a whole organisation from a file, or none of it
Second half of the mass import: the transactional loader, the /import page
and a template generated from the same schema the validation uses.

Everything happens in one transaction. A half-loaded organisation — areas
without departments, positions without people — is worse than none, because
it looks like data. The dry run is the same code path with a rollback at the
end, so the report is built against the real current state rather than a
copy, and nothing is cached between checking and committing: the file is
sent twice. That costs one upload and avoids server-side state that can
expire, fill up, or be confused between two people.

Personnel numbers are taken from the file, not reassigned. personnel_number
is GENERATED ALWAYS AS IDENTITY, so this needs OVERRIDING SYSTEM VALUE and a
hand-written insert — worth it, because the number is on payslips, in files
and on badges. An import that reissues it is not a migration. The identity
counter is advanced afterwards; without that the next hire draws a number
the import already used, and the unique index refuses it weeks later, far
from the cause.

Three defects the first real run against the database exposed, none of which
typecheck, lint or 231 tests could have found:

  - weekly_hours is bound to employment type by a CHECK constraint: full time
    is exactly 38.5. The import reached the insert and was rolled back. Now
    it is a finding with a row number.
  - Titles are restricted to a fixed list by another CHECK. Same treatment.
  - setval() needs UPDATE on the sequence, which `usage, select` does not
    grant. Migration 20260803120000 adds it; until it is applied, an import
    containing people will fail at the last step and take itself back.

I also had exit_date > entry_date where the database has >=. Someone who
never starts enters and leaves the same day; the stricter rule would have
rejected a real case.

Verified against the live database through the actual route and session: a
file with four deliberate faults produced exactly four findings, each with
sheet, row and column, and the rollback left nothing behind.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 14:40:33 +02:00

97 lines
3.4 KiB
TypeScript

import ExcelJS from "exceljs";
import { NextResponse } from "next/server";
import { requireHrUser } from "@/lib/auth/require-hr";
import { exportFilename, exportResponseHeaders } from "@/lib/export";
import { BLAETTER } from "@/lib/import/schema";
// Die Vorlage entsteht aus demselben Schema wie die Prüfung.
//
// Das ist der Punkt: eine von Hand gepflegte Beispieldatei läuft dem Code
// hinterher, und dann verlangt die Vorlage eine Spalte, die es nicht mehr
// gibt — oder umgekehrt. Hier kann das nicht passieren; kommt in schema.ts
// eine Spalte dazu, steht sie beim nächsten Herunterladen drin.
export async function GET() {
const gate = await requireHrUser();
if ("denied" in gate) return gate.denied;
const mappe = new ExcelJS.Workbook();
mappe.creator = "Alpenwerk HR";
mappe.created = new Date();
const hinweise = mappe.addWorksheet("Hinweise");
hinweise.columns = [
{ header: "Blatt", width: 16 },
{ header: "Spalte", width: 26 },
{ header: "Pflicht", width: 9 },
{ header: "Format", width: 30 },
{ header: "Hinweis", width: 70 },
];
hinweise.getRow(1).font = { bold: true };
const formatText = (typ: (typeof BLAETTER)[number]["spalten"][number]["typ"]): string => {
switch (typ.art) {
case "datum":
return "Datum (31.12.2026)";
case "zahl":
return "Zahl (38,5)";
case "ganzzahl":
return "Ganze Zahl";
case "janein":
return "ja / nein";
case "liste":
return typ.werte ? `Mehrere mit Semikolon aus: ${typ.werte.join(", ")}` : "Mehrere mit Semikolon";
case "auswahl":
return typ.werte.join(" | ");
default:
return "Text";
}
};
for (const schema of BLAETTER) {
hinweise.addRow([schema.name, "", "", "", schema.zweck]).font = { bold: true };
for (const s of schema.spalten) {
hinweise.addRow([schema.name, s.name, s.pflicht ? "ja" : "", formatText(s.typ), s.hinweis]);
}
hinweise.addRow([]);
}
for (const schema of BLAETTER) {
const blatt = mappe.addWorksheet(schema.name);
blatt.columns = schema.spalten.map((s) => ({
header: s.name,
width: Math.max(12, Math.min(28, s.name.length + 4)),
}));
const kopf = blatt.getRow(1);
kopf.font = { bold: true };
kopf.eachCell((zelle, i) => {
const spalte = schema.spalten[i - 1];
if (!spalte) return;
// Pflichtspalten sichtbar markieren — sonst ist die erste Rückmeldung
// eine Fehlerliste statt eines Hinweises beim Ausfüllen.
if (spalte.pflicht) {
zelle.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFDE7EF" } };
}
const teile = [spalte.pflicht ? "Pflichtfeld." : "Optional.", formatText(spalte.typ), spalte.hinweis].filter(Boolean);
zelle.note = teile.join("\n");
});
// Eine Beispielzeile. Alles als Text, damit Excel nicht selbst
// interpretiert — der Leser deutet die Werte ohnehin.
const beispiel = schema.spalten.map((s) => s.beispiel);
if (beispiel.some(Boolean)) {
const zeile = blatt.addRow(beispiel);
zeile.font = { italic: true, color: { argb: "FF8A8A8A" } };
zeile.eachCell((z) => {
z.numFmt = "@";
});
}
blatt.views = [{ state: "frozen", ySplit: 1 }];
}
const puffer = await mappe.xlsx.writeBuffer();
const dateiname = exportFilename("import-vorlage", "xlsx");
return new NextResponse(new Blob([puffer as BlobPart]), { headers: exportResponseHeaders(dateiname, "xlsx") });
}