- Projekt-Detailseite mit Kacheln und Reitern, Baustellenadresse und Notiz (Migration 005) - Aufgaben mit Projekt, Kunde und Kategorie; Kategorien im Auswahlmenü bearbeiten - Terminplan: Bearbeitung direkt in der Tabelle, Spalten ausblendbar Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AmyPfuNc4sCRfaF3oURXZz
293 lines
14 KiB
TypeScript
293 lines
14 KiB
TypeScript
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 { 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 { pruefeStand, speichereStand } from "./stand.js";
|
|
import { VERSION } from "./version.js";
|
|
|
|
export interface Optionen {
|
|
pool: Pool;
|
|
/** P10: Projektordner in der Nextcloud; ohne Zugang wird nichts angelegt */
|
|
nextcloud?: Nextcloud;
|
|
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 };
|
|
});
|
|
|
|
// 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<string, any>, wer: string): Promise<Record<string, unknown>> {
|
|
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));
|
|
});
|
|
|
|
// Änderungen an Vorgängen und Verknüpfungen planen die Nachfolger in derselben Transaktion neu
|
|
const PLAN = new Set(["vorgang", "vorgang_vorgaenger"]);
|
|
async function geplant<T>(c: Client, tabelle: string, fn: () => Promise<T>, bewegt: string[] = []): Promise<T> {
|
|
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<string, unknown>;
|
|
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]);
|
|
});
|
|
if (t.name === "projekt") return reply.status(201).send(await mitOrdner(row, benutzer(req)));
|
|
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) => {
|
|
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] : []);
|
|
});
|
|
if (row && t.name === "projekt" && (daten.nummer || daten.bezeichnung || daten.status)) return mitOrdner(row, benutzer(req));
|
|
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<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),
|
|
});
|
|
|
|
async function berechneLiquiditaet(q: z.infer<typeof LiquiAnfrage>) {
|
|
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<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;
|
|
}
|