import Fastify, { type FastifyInstance, type FastifyRequest } from "fastify"; import fastifyStatic from "@fastify/static"; import { fileURLToPath } from "node:url"; import path from "node:path"; import { existsSync } from "node:fs"; import { randomBytes, timingSafeEqual } from "node:crypto"; import { z, ZodError } from "zod"; import { type Client, type Pool, transaktion } from "./db.js"; import { mitNeuplanung, pruefeVerknuepfung, terminplan } from "./terminplan.js"; import { legeZahlungsplanAn, zahlungsplanFest, zahlungsplaeneAutomatisch } from "./zahlungsplan.js"; import { uebersicht } from "./uebersicht.js"; import { aufgabenKalender, baustellenKalender } from "./kalender.js"; import { type Nextcloud, ordnerAbgleichen } from "./nextcloud.js"; import { TABELLEN } from "./tabellen.js"; import { EinstellungenSchema, type Einstellungen } from "./einstellungen.js"; import { liquiditaet } from "../domain/liquiditaet.js"; import { liquiditaetsDaten } from "../domain/projektplan.js"; import { uebernimmV70 } from "../domain/v70.js"; import { speichereUebernahme } from "./v70import.js"; import { benutzerFuerSicherung, pruefeStand, speichereStand } from "./stand.js"; import { VERSION } from "./version.js"; import { type Anmeldeart, registriereAnmeldung, werName } from "./anmeldung.js"; import { istEingeteilt, registriereIch } from "./ich.js"; import { registrierePersonal } from "./personal.js"; export interface Optionen { pool: Pool; /** P10: Projektordner in der Nextcloud; ohne Zugang wird nichts angelegt */ nextcloud?: Nextcloud; webOrdner?: string; logger?: boolean; /** passwort: Server; testversion: Browser-Testversion und Tests, ohne Passwörter */ anmeldung?: Anmeldeart; /** Nur auf dem Server: Code, mit dem der erste Benutzer (Inhaber) angelegt wird */ einrichtungsCode?: string; } /** Wer angemeldet ist, steht im Änderungsprotokoll */ const benutzer = (req: FastifyRequest): string => werName(req); const IdParam = z.object({ id: z.uuid() }); export async function baueApp(o: Optionen): Promise { const app = Fastify({ logger: o.logger ?? false, bodyLimit: 50 * 1024 * 1024 }); const { pool } = o; app.setErrorHandler((err, _req, reply) => { if (err instanceof ZodError) { return reply.status(400).send({ fehler: "Eingabe ungültig", details: err.issues.map((i) => `${i.path.join(".")}: ${i.message}`) }); } const pgCode = (err as { code?: string }).code; if (pgCode === "23503") return reply.status(409).send({ fehler: "Verknüpfter Datensatz fehlt oder wird noch verwendet" }); if (pgCode === "23505") return reply.status(409).send({ fehler: "Eintrag gibt es schon" }); if (pgCode === "23514" || pgCode === "22P02" || pgCode === "22007" || pgCode === "22008") { return reply.status(400).send({ fehler: "Eingabe ungültig" }); } const status = (err as { statusCode?: number }).statusCode; if (status && status < 500) return reply.status(status).send({ fehler: (err as Error).message }); app.log.error(err); return reply.status(500).send({ fehler: "Interner Fehler" }); }); registriereAnmeldung(app, pool, o.anmeldung ?? "passwort", o.einrichtungsCode); registriereIch(app, pool, ladeEinstellungen); registrierePersonal(app, pool, ladeEinstellungen); app.get("/api/status", async () => { await pool.query("select 1"); return { ok: true, version: VERSION }; }); // P10: Ordner nach dem Speichern abgleichen. Ein Fehler in der Nextcloud macht die Änderung nicht // rückgängig; der Hinweis kommt mit zurück, und der Abgleich lässt sich wiederholen. async function mitOrdner(p: Record, wer: string): Promise> { if (!o.nextcloud) return p; try { const pfad = await ordnerAbgleichen(o.nextcloud, p as { nummer: string; bezeichnung: string; status: string }, p.nextcloud_link ?? null); if (pfad === p.nextcloud_link) return p; return await transaktion(pool, wer, async (c) => (await c.query("update projekt set nextcloud_link = $2 where id = $1 returning *", [p.id, pfad])).rows[0]); } catch (err) { app.log.warn(err); return { ...p, ordner_fehler: `Projektordner in der Nextcloud: ${(err as Error).message}` }; } } app.post("/api/projekte/:id/ordner", async (req, reply) => { const { id } = IdParam.parse(req.params); const p = (await pool.query("select * from projekt where id = $1", [id])).rows[0]; if (!p) return reply.status(404).send({ fehler: "Nicht gefunden" }); if (!o.nextcloud) return reply.status(409).send({ fehler: "Für die Projektordner ist kein Nextcloud-Zugang eingerichtet." }); return mitOrdner(p, benutzer(req)); }); // Ablage auf der Projektseite (Henning, 20.10.2026): Inhalt des Nextcloud-Projektordners anzeigen und Dateien öffnen const AblageAnfrage = z.object({ pfad: z.string().max(500).default("") }) .refine((q) => !q.pfad.split("/").some((t) => t === ".." || t === "."), { message: "Pfad ungültig" }); async function ablagePfad(id: string, unter: string): Promise { const p = (await pool.query("select nextcloud_link from projekt where id = $1", [id])).rows[0]; if (!p) return null; return [p.nextcloud_link, unter.replace(/^\/+|\/+$/g, "")].filter(Boolean).join("/"); } // P13: Mitarbeiter sehen die Ablage der Projekte, auf denen sie eingeteilt sind const ablageErlaubt = async (req: FastifyRequest, id: string) => req.wer?.rolle !== "mitarbeiter" || istEingeteilt(pool, req.wer.kontakt_id, id); app.get("/api/projekte/:id/ablage", async (req, reply) => { const { id } = IdParam.parse(req.params); const { pfad } = AblageAnfrage.parse(req.query); if (!(await ablageErlaubt(req, id))) return reply.status(403).send({ fehler: "Dafür fehlt dir die Berechtigung." }); if (!o.nextcloud) return reply.status(409).send({ fehler: "Die Ablage zeigt den Projektordner in der Nextcloud. Das geht, sobald das Programm auf dem Server läuft." }); const p = (await pool.query("select nextcloud_link from projekt where id = $1", [id])).rows[0]; if (!p) return reply.status(404).send({ fehler: "Nicht gefunden" }); if (!p.nextcloud_link) return reply.status(409).send({ fehler: "Für dieses Projekt gibt es noch keinen Ordner in der Nextcloud." }); const eintraege = await o.nextcloud.inhalt((await ablagePfad(id, pfad))!); if (!eintraege) return reply.status(404).send({ fehler: "Ordner nicht gefunden" }); return { ordner: p.nextcloud_link, pfad, eintraege }; }); app.get("/api/projekte/:id/ablage/datei", async (req, reply) => { const { id } = IdParam.parse(req.params); const { pfad } = AblageAnfrage.parse(req.query); if (!(await ablageErlaubt(req, id))) return reply.status(403).send({ fehler: "Dafür fehlt dir die Berechtigung." }); if (!o.nextcloud || !pfad) return reply.status(404).send({ fehler: "Nicht gefunden" }); const voll = await ablagePfad(id, pfad); if (!voll) return reply.status(404).send({ fehler: "Nicht gefunden" }); const r = await o.nextcloud.datei(voll); const name = pfad.split("/").at(-1)!; reply.header("content-type", r.headers.get("content-type") ?? "application/octet-stream"); reply.header("content-disposition", `inline; filename*=UTF-8''${encodeURIComponent(name)}`); return reply.send(Buffer.from(await r.arrayBuffer())); }); // Standard-Zahlungsplan von Hand anlegen (P9), z. B. für schon laufende Projekte; nur solange das Projekt keine Raten hat app.post("/api/projekte/:id/zahlungsplan", async (req, reply) => { const { id } = IdParam.parse(req.params); const p = (await pool.query("select id, umsatz_netto from projekt where id = $1", [id])).rows[0]; if (!p) return reply.status(404).send({ fehler: "Nicht gefunden" }); if (!(Number(p.umsatz_netto) > 0)) return reply.status(400).send({ fehler: "Bitte zuerst beim Projekt den Auftragswert (Umsatz netto) eintragen." }); const e = await ladeEinstellungen(); const raten = await transaktion(pool, benutzer(req), async (c) => { if ((await c.query("select 1 from zahlung where projekt_id = $1 limit 1", [id])).rowCount) return null; return legeZahlungsplanAn(c, id, Number(p.umsatz_netto), { tage: e.arbeitstage }); }); if (!raten) return reply.status(409).send({ fehler: "Das Projekt hat schon einen Zahlungsplan." }); return reply.status(201).send(raten); }); // Änderungen an Vorgängen und Verknüpfungen planen die Nachfolger in derselben Transaktion neu const PLAN = new Set(["vorgang", "vorgang_vorgaenger", "zahlung"]); // P12: Projektänderungen legen den Zahlungsplan an oder führen ihn nach; eine Rate von Hand ändern stellt ihn fest async function geplant(c: Client, tabelle: string, fn: () => Promise, bewegt: string[] = [], zahlungVon?: string): Promise { const e = await ladeEinstellungen(); if (tabelle === "projekt") { const ergebnis = await fn(); await zahlungsplaeneAutomatisch(c, { tage: e.arbeitstage }); return ergebnis; } if (!PLAN.has(tabelle)) return fn(); const aenderung = zahlungVon ? async () => { const r = await fn(); await zahlungsplanFest(c, zahlungVon); return r; } : fn; return (await mitNeuplanung(c, { tage: e.arbeitstage }, aenderung, bewegt)).ergebnis; } const projektDerZahlung = async (c: Client, tabelle: string, id: string) => tabelle === "zahlung" ? (await c.query("select projekt_id from zahlung where id = $1", [id])).rows[0]?.projekt_id as string | undefined : undefined; // U2: Felder wie der Stundenlohn gehen nur an den Inhaber; Zahlen-Arrays (Arbeitszeitmodell) als Zahlen const fuer = (req: FastifyRequest, t: (typeof TABELLEN)[number]) => (z: Record | undefined) => { if (!z) return z; const aus: Record = { ...z }; if (req.wer?.rolle !== "inhaber") for (const f of t.nurInhaber ?? []) delete aus[f]; for (const [k, v] of Object.entries(aus)) if (Array.isArray(v)) aus[k] = v.map((x) => (typeof x === "string" && /^-?\d+(\.\d+)?$/.test(x) ? Number(x) : x)); return aus; }; const verboten = (req: FastifyRequest, t: (typeof TABELLEN)[number], daten: Record) => req.wer?.rolle !== "inhaber" && (t.nurInhaber ?? []).some((f) => daten[f] !== undefined); for (const t of TABELLEN) { const felder = Object.keys(t.schema.shape); const teil = t.schema.partial(); app.get(`/api/${t.pfad}`, async (req) => (await pool.query(`select * from ${t.name} order by ${t.sortierung}`)).rows.map(fuer(req, t))); app.get(`/api/${t.pfad}/:id`, async (req, reply) => { const { id } = IdParam.parse(req.params); const r = await pool.query(`select * from ${t.name} where id = $1`, [id]); return fuer(req, t)(r.rows[0]) ?? reply.status(404).send({ fehler: "Nicht gefunden" }); }); app.post(`/api/${t.pfad}`, async (req, reply) => { const daten = t.schema.parse(req.body) as Record; if (verboten(req, t, daten)) return reply.status(403).send({ fehler: "Dafür fehlt dir die Berechtigung." }); const spalten = felder.filter((f) => daten[f] !== undefined); const row = await transaktion(pool, benutzer(req), async (c) => { if (t.name === "vorgang_vorgaenger") await pruefeVerknuepfung(c, daten as { vorgang_id: string; vorgaenger_id: string }); return geplant(c, t.name, async () => (await c.query( spalten.length ? `insert into ${t.name} (${spalten.join(", ")}) values (${spalten.map((_, i) => `$${i + 1}`).join(", ")}) returning *` : `insert into ${t.name} default values returning *`, spalten.map((s) => daten[s]), )).rows[0], [], t.name === "zahlung" ? daten.projekt_id as string : undefined); }); if (t.name === "projekt") return reply.status(201).send(await mitOrdner(row, benutzer(req))); return reply.status(201).send(fuer(req, t)(row)); }); app.patch(`/api/${t.pfad}/:id`, async (req, reply) => { const { id } = IdParam.parse(req.params); const daten = teil.parse(req.body) as Record; if (verboten(req, t, daten)) return reply.status(403).send({ fehler: "Dafür fehlt dir die Berechtigung." }); const spalten = felder.filter((f) => daten[f] !== undefined); if (spalten.length === 0) return reply.status(400).send({ fehler: "Keine Änderung angegeben" }); const row = await transaktion(pool, benutzer(req), async (c) => { if (t.name === "vorgang_vorgaenger" && (daten.vorgang_id || daten.vorgaenger_id)) { const alt = (await c.query("select vorgang_id, vorgaenger_id from vorgang_vorgaenger where id = $1", [id])).rows[0]; if (alt) await pruefeVerknuepfung(c, { ...alt, ...daten } as { vorgang_id: string; vorgaenger_id: string }, id); } const zahlungVon = await projektDerZahlung(c, t.name, id); return geplant(c, t.name, async () => (await c.query( `update ${t.name} set ${spalten.map((s, i) => `${s} = $${i + 2}`).join(", ")} where id = $1 returning *`, [id, ...spalten.map((s) => daten[s])], )).rows[0], t.name === "vorgang" && daten.start !== undefined ? [id] : [], zahlungVon); }); if (row && t.name === "projekt" && (daten.nummer || daten.bezeichnung || daten.status)) return mitOrdner(row, benutzer(req)); return fuer(req, t)(row) ?? reply.status(404).send({ fehler: "Nicht gefunden" }); }); app.delete(`/api/${t.pfad}/:id`, async (req, reply) => { const { id } = IdParam.parse(req.params); const n = await transaktion(pool, benutzer(req), async (c) => geplant(c, t.name, async () => (await c.query(`delete from ${t.name} where id = $1`, [id])).rowCount, [], await projektDerZahlung(c, t.name, id))); return n ? reply.status(204).send() : reply.status(404).send({ fehler: "Nicht gefunden" }); }); } async function ladeEinstellungen(): Promise { const r = await pool.query<{ daten: unknown }>("select daten from einstellungen limit 1"); return EinstellungenSchema.parse(r.rows[0]?.daten ?? {}); } app.get("/api/einstellungen", ladeEinstellungen); app.put("/api/einstellungen", async (req) => { const neu = EinstellungenSchema.parse(req.body); await transaktion(pool, benutzer(req), (c) => c.query("update einstellungen set daten = $1", [neu])); return neu; }); const LiquiAnfrage = z.object({ ansicht: z.enum(["woche", "monat"]).default("woche"), start: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(), anzahl: z.coerce.number().int().min(1).max(104).default(12), }); async function berechneLiquiditaet(q: z.infer) { const e = await ladeEinstellungen(); const [projekte, vorgaenge, zahlungen, kosten, laufend] = await Promise.all([ pool.query("select * from projekt"), pool.query("select v.id, a.projekt_id, v.start, v.dauer from vorgang v join abschnitt a on a.id = v.abschnitt_id"), pool.query("select * from zahlung"), pool.query("select * from kosten"), pool.query("select * from laufende_kosten"), ]); const daten = liquiditaetsDaten( { projekte: projekte.rows, vorgaenge: vorgaenge.rows, zahlungen: zahlungen.rows, kosten: kosten.rows, laufend: laufend.rows.map((l) => ({ bezeichnung: l.bezeichnung, kategorie: l.kategorie, betrag: l.betrag, rhythmus: l.rhythmus, start: l.start, ende: l.ende ?? undefined, })), }, { tage: e.arbeitstage }, ); const start = q.start ?? new Date().toISOString().slice(0, 10); return liquiditaet(daten, { ansicht: q.ansicht, start, anzahl: q.anzahl, startsaldo: e.startsaldo, ziele: e.zahlungsziele, ust: e.ust }); } app.get("/api/liquiditaet", async (req) => berechneLiquiditaet(LiquiAnfrage.parse(req.query))); // Startseite: Aufgaben, Warnungen, wer macht was in den nächsten zwei Wochen, Liquidität 4 Wochen app.get("/api/uebersicht", async (req) => { const heute = z.object({ heute: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional() }).parse(req.query).heute ?? new Date().toISOString().slice(0, 10); const e = await ladeEinstellungen(); const woche = { tage: e.arbeitstage }; const [tp, aufgaben, liqui] = await Promise.all([ terminplan(pool, woche), pool.query(`select a.*, p.nummer as projekt_nummer, p.bezeichnung as projekt_name, k.name as kontakt_name, g.name as kategorie from aufgabe a left join projekt p on p.id = a.projekt_id left join kontakt k on k.id = a.kontakt_id left join aufgabe_kategorie g on g.id = a.kategorie_id where a.erledigt_am is null order by a.faellig_am nulls last, a.angelegt_am`), berechneLiquiditaet({ ansicht: "woche", start: heute, anzahl: 4 }), ]); return uebersicht({ heute, woche, tp, aufgaben: aufgaben.rows, liqui, mindestreserve: e.mindestreserve, kontostandErfasst: e.startsaldo !== 0 || e.startsaldoDatum !== null }); }); // T11: Kalender-Abos. Ohne Anmeldung erreichbar (Outlook classic kann das nicht), geschützt durch das Geheimnis im Link const KalenderParam = z.object({ token: z.string().min(20).max(100), name: z.enum(["baustellen.ics", "aufgaben.ics"]) }); app.get("/kalender/:token/:name", async (req, reply) => { const q = KalenderParam.safeParse(req.params); const e = await ladeEinstellungen(); const soll = Buffer.from(e.kalenderToken ?? ""); const ist = Buffer.from(q.success ? q.data.token : ""); if (!q.success || !e.kalenderToken || soll.length !== ist.length || !timingSafeEqual(soll, ist)) { return reply.status(404).send({ fehler: "Nicht gefunden" }); } const ics = q.data.name === "baustellen.ics" ? await baustellenKalender(pool, { tage: e.arbeitstage }) : await aufgabenKalender(pool); return reply.header("content-type", "text/calendar; charset=utf-8").header("cache-control", "no-store").send(ics); }); // Neues Geheimnis für die Kalender-Links; alte Abos hören dann auf zu funktionieren app.post("/api/kalender/neu", async (req) => { const e = await ladeEinstellungen(); const neu = { ...e, kalenderToken: randomBytes(24).toString("base64url") }; await transaktion(pool, benutzer(req), (c) => c.query("update einstellungen set daten = $1", [neu])); return { kalenderToken: neu.kalenderToken }; }); app.get("/api/terminplan", async () => { const e = await ladeEinstellungen(); return terminplan(pool, { tage: e.arbeitstage }); }); // Übernahme aus dem Projektplaner V70 (JSON-Sicherung), nur in ein leeres Programm app.post("/api/import/v70", async (req, reply) => { let u; try { u = uebernimmV70(req.body); } catch (err) { return reply.status(400).send({ fehler: (err as Error).message }); } const e = await ladeEinstellungen(); // nach der Übernahme gelten die Verknüpfungen: Nachfolger rücken hinter ihre Vorgänger wie in V70 const anzahl = await transaktion(pool, benutzer(req), async (c) => (await mitNeuplanung(c, { tage: e.arbeitstage }, () => speichereUebernahme(c, u))).ergebnis); return reply.status(201).send({ anzahl, hinweise: u.hinweise }); }); // D1: Sicherung aus GET /api/export in ein leeres Programm einspielen (Umzug aus der Testversion) app.post("/api/import/stand", async (req, reply) => { let s; try { s = pruefeStand(req.body); } catch (err) { return reply.status(400).send({ fehler: (err as Error).message }); } const anzahl = await transaktion(pool, benutzer(req), (c) => speichereStand(c, s)); return reply.status(201).send({ anzahl }); }); // D1: kompletter Stand als JSON-Datei app.get("/api/export", async (_req, reply) => { const daten: Record = {}; for (const t of TABELLEN) daten[t.pfad] = (await pool.query(`select * from ${t.name} order by ${t.sortierung}`)).rows; daten.benutzer = await benutzerFuerSicherung(pool); const stand = new Date().toISOString(); reply.header("content-disposition", `attachment; filename="betrieb-${stand.slice(0, 10)}.json"`); return { programm: "betrieb", version: VERSION, stand, einstellungen: await ladeEinstellungen(), daten }; }); app.get("/api/protokoll", async (req) => { const q = z.object({ datensatz: z.uuid().optional(), limit: z.coerce.number().int().min(1).max(500).default(100) }).parse(req.query); const r = q.datensatz ? await pool.query("select * from protokoll where datensatz = $1 order by id desc limit $2", [q.datensatz, q.limit]) : await pool.query("select * from protokoll order by id desc limit $1", [q.limit]); return r.rows; }); const web = o.webOrdner ?? path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "web"); if (existsSync(web)) { await app.register(fastifyStatic, { root: web, prefix: "/" }); app.setNotFoundHandler((req, reply) => req.url.startsWith("/api/") ? reply.status(404).send({ fehler: "Nicht gefunden" }) : reply.sendFile("index.html"), ); } return app; }