Stufe 0: Grundgerüst mit Rechenkern, Datenbank, Oberfläche und Docker-Betrieb

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AmyPfuNc4sCRfaF3oURXZz
This commit is contained in:
Claude
2026-10-17 16:37:54 +00:00
commit 92d26baa4b
45 changed files with 6143 additions and 0 deletions

168
src/server/app.ts Normal file
View File

@@ -0,0 +1,168 @@
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 Pool, transaktion } from "./db.js";
import { TABELLEN } from "./tabellen.js";
import { EinstellungenSchema, type Einstellungen } from "./einstellungen.js";
import { liquiditaet, type Daten } from "../domain/liquiditaet.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<FastifyInstance> {
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 };
});
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<string, unknown>;
const spalten = felder.filter((f) => daten[f] !== undefined);
const row = await transaktion(pool, benutzer(req), async (c) =>
(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<string, unknown>;
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) =>
(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],
);
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) => (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<Einstellungen> {
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 [zahlungen, kosten, laufend] = await Promise.all([
pool.query(`select z.*, p.nummer from zahlung z join projekt p on p.id = z.projekt_id`),
pool.query(`select k.*, p.nummer from kosten k join projekt p on p.id = k.projekt_id`),
pool.query(`select * from laufende_kosten`),
]);
const daten: Daten = {
einnahmen: zahlungen.rows.map((z) => ({
projekt: z.nummer, bezeichnung: z.bezeichnung, netto: z.netto,
termin: z.rechnungsdatum ?? z.termin, bezahltAm: z.bezahlt_am ?? undefined,
})),
ausgaben: kosten.rows.map((k) => ({
projekt: k.nummer, bezeichnung: k.bezeichnung, art: k.art, netto: k.netto, termin: k.termin, mitVorsteuer: k.mit_vorsteuer,
})),
laufend: laufend.rows.map((l) => ({
bezeichnung: l.bezeichnung, kategorie: l.kategorie, betrag: l.betrag, rhythmus: l.rhythmus, start: l.start, ende: l.ende ?? undefined,
})),
};
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 });
});
// D1: kompletter Stand als JSON-Datei
app.get("/api/export", async (_req, reply) => {
const daten: Record<string, unknown[]> = {};
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;
}