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 { z, ZodError } from "zod"; import { type Client, type Pool, transaktion } from "./db.js"; import { mitNeuplanung, pruefeVerknuepfung, terminplan } from "./terminplan.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 { VERSION } from "./version.js"; export interface Optionen { pool: Pool; webOrdner?: string; logger?: boolean; } /** Benutzer kommt vom Proxy (Anmeldung); ohne Proxy, z. B. lokal, gilt "lokal". */ function benutzer(req: FastifyRequest): string { const h = req.headers["x-benutzer"]; return (Array.isArray(h) ? h[0] : h)?.trim() || "lokal"; } 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" }); }); app.get("/api/status", async () => { await pool.query("select 1"); return { ok: true, version: VERSION }; }); // Änderungen an Vorgängen und Verknüpfungen planen die Nachfolger in derselben Transaktion neu const PLAN = new Set(["vorgang", "vorgang_vorgaenger"]); async function geplant(c: Client, tabelle: string, fn: () => Promise, bewegt: string[] = []): Promise { if (!PLAN.has(tabelle)) return fn(); const e = await ladeEinstellungen(); return (await mitNeuplanung(c, { tage: e.arbeitstage }, fn, bewegt)).ergebnis; } for (const t of TABELLEN) { const felder = Object.keys(t.schema.shape); const teil = t.schema.partial(); app.get(`/api/${t.pfad}`, async () => (await pool.query(`select * from ${t.name} order by ${t.sortierung}`)).rows); 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 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; 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]); }); return reply.status(201).send(row); }); app.patch(`/api/${t.pfad}/:id`, async (req, reply) => { const { id } = IdParam.parse(req.params); const daten = teil.parse(req.body) as Record; 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); } 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] : []); }); return 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)); 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), }); app.get("/api/liquiditaet", async (req) => { const q = LiquiAnfrage.parse(req.query); 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/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: 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; 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; }