Testversion im Browser und Sicherung einspielen

Die Testversion bündelt Oberfläche und Server-Logik mit PGlite (Postgres als
WebAssembly). POST /api/import/stand spielt einen kompletten Stand mit allen IDs
in ein leeres Programm ein; damit ziehen die Daten später auf den Server um.

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-20 04:18:42 +00:00
parent e406c5a842
commit 9bd88bb7ec
17 changed files with 510 additions and 8 deletions

View File

@@ -14,6 +14,9 @@ Stufe 1, Aufgaben und Termine:
- Kalender-Abos „Baustellen“ und „Aufgaben“ für Outlook classic. - Kalender-Abos „Baustellen“ und „Aufgaben“ für Outlook classic.
- Projektordner in der Nextcloud werden angelegt und je nach Status verschoben. - Projektordner in der Nextcloud werden angelegt und je nach Status verschoben.
- Aufgaben werden aus der V70-Sicherung übernommen, Vorgangsnummern bleiben erhalten. - Aufgaben werden aus der V70-Sicherung übernommen, Vorgangsnummern bleiben erhalten.
- Sicherung einspielen: ein kompletter Stand (Daten → sichern) lässt sich in ein leeres Programm übernehmen, alle Datensätze behalten ihre IDs.
- Testversion, die komplett im Browser läuft (npm run build:demo), mit derselben Oberfläche und Rechenlogik.
- Dunkle Darstellung folgt auch einer ausdrücklich gewählten Hell/Dunkel-Einstellung.
## 0.1.0 ## 0.1.0

79
demo/fastify.ts Normal file
View File

@@ -0,0 +1,79 @@
// Ersatz für Fastify in der Browser-Testversion: dieselben Routen, aber ohne Netzwerk.
// Unterstützt nur das, was src/server/app.ts benutzt.
type Handler = (req: Anfrage, reply: Antwort) => unknown;
export interface Anfrage {
method: string;
url: string;
params: Record<string, string>;
query: Record<string, string>;
body: unknown;
headers: Record<string, string>;
}
export class Antwort {
statusCode = 200;
kopf: Record<string, string> = {};
inhalt: unknown = undefined;
gesendet = false;
status(code: number) { this.statusCode = code; return this; }
code(code: number) { return this.status(code); }
header(name: string, wert: string) { this.kopf[name.toLowerCase()] = wert; return this; }
send(inhalt?: unknown) { this.inhalt = inhalt; this.gesendet = true; return this; }
sendFile() { return this.status(404).send({ fehler: "Nicht gefunden" }); }
}
interface Route { methode: string; teile: string[]; handler: Handler }
export default function Fastify(_o?: unknown) {
const routen: Route[] = [];
let fehlerHandler: (err: unknown, req: Anfrage, reply: Antwort) => unknown = (err, _r, reply) =>
reply.status(500).send({ fehler: (err as Error).message });
const neu = (methode: string) => (pfad: string, handler: Handler) => { routen.push({ methode, teile: pfad.split("/"), handler }); };
const app = {
log: { error: console.error, warn: console.warn, info: () => {} },
get: neu("GET"), post: neu("POST"), put: neu("PUT"), patch: neu("PATCH"), delete: neu("DELETE"),
setErrorHandler(fn: typeof fehlerHandler) { fehlerHandler = fn; },
setNotFoundHandler() {},
async register() {},
async close() {},
/** Bearbeitet eine Anfrage wie der Server und liefert eine fetch-Antwort. */
async verarbeite(methode: string, adresse: string, body: unknown, headers: Record<string, string> = {}): Promise<Response> {
const u = new URL(adresse, "http://demo");
const teile = u.pathname.split("/").map(decodeURIComponent);
const reply = new Antwort();
let route: Route | undefined;
const params: Record<string, string> = {};
for (const r of routen) {
if (r.methode !== methode || r.teile.length !== teile.length) continue;
if (r.teile.every((t, i) => t.startsWith(":") || t === teile[i])) {
route = r;
r.teile.forEach((t, i) => { if (t.startsWith(":")) params[t.slice(1)] = teile[i]!; });
break;
}
}
const req: Anfrage = { method: methode, url: u.pathname + u.search, params, query: Object.fromEntries(u.searchParams), body, headers };
if (!route) reply.status(404).send({ fehler: "Nicht gefunden" });
else {
try {
const erg = await route.handler(req, reply);
if (!reply.gesendet && erg !== reply) reply.send(erg);
} catch (err) {
await fehlerHandler(err, req, reply);
}
}
const leer = reply.inhalt === undefined || reply.statusCode === 204;
const text = typeof reply.inhalt === "string";
return new Response(leer ? null : text ? (reply.inhalt as string) : JSON.stringify(reply.inhalt), {
status: reply.statusCode,
headers: { "content-type": text ? "text/plain; charset=utf-8" : "application/json", ...reply.kopf },
});
},
};
return app;
}
export type FastifyInstance = ReturnType<typeof Fastify>;
export type FastifyRequest = Anfrage;

18
demo/index.html Normal file
View File

@@ -0,0 +1,18 @@
<title>Betrieb Testversion</title>
<style>/*STYLES*/
#test-leiste { position: fixed; z-index: 50; right: calc(12px + env(safe-area-inset-right, 0px)); bottom: calc(12px + env(safe-area-inset-bottom, 0px));
max-width: min(420px, calc(100vw - 24px)); background: var(--fl); color: var(--text); border: 1px solid var(--linie); border-radius: 10px;
padding: 7px 12px; font-size: 13px; box-shadow: 0 2px 10px rgb(0 0 0 / 0.12); display: flex; gap: 8px; align-items: baseline; }
#test-leiste b { color: var(--holz); white-space: nowrap; }
#test-zustand.ok { color: var(--leise); }
#test-zustand.fehler { color: var(--warn); }
</style>
<aside id="seitenleiste">
<div id="marke"><img src="/*LOGO*/" alt="Holzbau Schaarschmidt"></div>
<nav id="reiter"></nav>
<span id="version"></span>
</aside>
<main id="inhalt"></main>
<div id="dialog-huelle" hidden></div>
<div id="test-leiste" role="status"><b>Testversion</b><span id="test-zustand">Programm wird geladen …</span></div>
<script type="module">/*APP*/</script>

32
demo/kern.ts Normal file
View File

@@ -0,0 +1,32 @@
// Startet die echte Server-Logik (src/server/app.ts) auf PGlite, ohne Netzwerk.
import type { PGlite } from "@electric-sql/pglite";
import { baueApp } from "../src/server/app.js";
import { alsPool } from "./pool.js";
import m001 from "../src/server/migrations/001_grundlage.sql";
import m002 from "../src/server/migrations/002_v70_uebernahme.sql";
import m003 from "../src/server/migrations/003_vorgangsnummer.sql";
import m004 from "../src/server/migrations/004_besetzung.sql";
const MIGRATIONEN: [string, string][] = [
["001_grundlage.sql", m001], ["002_v70_uebernahme.sql", m002], ["003_vorgangsnummer.sql", m003], ["004_besetzung.sql", m004],
];
export async function starte(db: PGlite, v70?: unknown) {
await db.exec("create table if not exists schema_version (name text primary key, eingespielt_am timestamptz not null default now())");
const da = new Set((await db.query<{ name: string }>("select name from schema_version")).rows.map((r) => r.name));
for (const [name, sql] of MIGRATIONEN) {
if (da.has(name)) continue;
await db.transaction(async (t) => {
await t.exec(sql);
await t.query("insert into schema_version (name) values ($1)", [name]);
});
}
const app = (await baueApp({ pool: alsPool(db) as any })) as unknown as {
verarbeite(methode: string, adresse: string, body?: unknown, headers?: Record<string, string>): Promise<Response>;
};
if (v70 && (await db.query("select 1 from projekt limit 1")).rows.length === 0) {
const r = await app.verarbeite("POST", "/api/import/v70", v70);
if (!r.ok) throw new Error(`Übernahme der V70-Daten: ${await r.text()}`);
}
return app;
}

2
demo/leer.ts Normal file
View File

@@ -0,0 +1,2 @@
// Leerer Ersatz für Node-Module, die PGlite nur unter Node benutzt
export default {};

135
demo/main.ts Normal file
View File

@@ -0,0 +1,135 @@
// Testversion im Browser: dieselbe Oberfläche und Server-Logik wie Version 0.2.0, Postgres als WebAssembly.
// Gespeichert wird im Datenspeicher des Testlinks (db-Fähigkeit), je Datensatz ein Dokument.
import { PGlite } from "@electric-sql/pglite";
import { starte } from "./kern.js";
import { PARSER } from "./pool.js";
import { TABELLEN } from "../src/server/tabellen.js";
type Doc = { id: string; exists: boolean; data(): Record<string, unknown> | undefined };
type Query = { where(f: string, op: string, v: unknown): Query; orderBy(f: string): Query; limit(n: number): Query; get(): Promise<{ docs: Doc[] }> };
type Speicher = { collection(p: string): Query; doc(p: string): { get(): Promise<Doc>; set(d: Record<string, unknown>): Promise<void>; delete(): Promise<void> } };
type Claude = { use(name: string): Promise<any> };
const claude = (globalThis as { claude?: Claude }).claude;
const leiste = document.getElementById("test-leiste")!;
const zustand = document.getElementById("test-zustand")!;
const melde = (text: string, art = "") => { zustand.textContent = text; zustand.className = art; };
async function pglite(): Promise<PGlite> {
const adresse = (f: string) => new URL(f, document.baseURI).href;
const modul = (f: string) => fetch(adresse(f)).then(async (r) => {
if (!r.ok) throw new Error(`${f}: ${r.status}`);
return WebAssembly.compile(await r.arrayBuffer());
});
const [wasm, initdb, daten] = await Promise.all([
modul("pglite.wasm"),
modul("initdb.wasm"),
fetch(adresse("pglite.data")).then((r) => { if (!r.ok) throw new Error(`pglite.data: ${r.status}`); return r.blob(); }),
]);
return PGlite.create({ pgliteWasmModule: wasm, initdbWasmModule: initdb, fsBundle: daten, parsers: PARSER } as ConstructorParameters<typeof PGlite>[1] & object);
}
/** Alle Dokumente einer Sammlung, seitenweise nach id */
async function alle(s: Speicher, sammlung: string): Promise<Record<string, unknown>[]> {
const aus: Record<string, unknown>[] = [];
let letzte = "";
for (;;) {
let q = s.collection(sammlung).orderBy("id").limit(500);
if (letzte) q = q.where("id", ">", letzte);
const { docs } = await q.get();
for (const d of docs) aus.push(d.data()!);
if (docs.length < 500) return aus;
letzte = String(aus[aus.length - 1]!.id);
}
}
/** Mehrmals versuchen, wenn der Speicher kurz nicht erreichbar ist */
async function nochmal<T>(fn: () => Promise<T>): Promise<T> {
try { return await fn(); } catch (e) {
if ((e as { code?: string }).code !== "unavailable" && (e as { code?: string }).code !== "resource_exhausted") throw e;
await new Promise((r) => setTimeout(r, 800 + Math.random() * 800));
return fn();
}
}
async function main() {
melde("Programm wird geladen …");
const [db, speicher, laden] = await Promise.all([pglite(), claude?.use("db") as Promise<Speicher | null> ?? null, claude?.use("downloads") ?? null]);
const app = await starte(db);
// gespeicherten Stand holen und einspielen
if (speicher) {
melde("Deine Daten werden geladen …");
const daten: Record<string, Record<string, unknown>[]> = {};
for (const t of TABELLEN) daten[t.pfad] = await nochmal(() => alle(speicher, t.pfad));
const e = await nochmal(() => speicher.doc("meta/einstellungen").get());
if (Object.values(daten).some((z) => z.length) || e.exists) {
const r = await app.verarbeite("POST", "/api/import/stand", { programm: "betrieb", einstellungen: e.data()?.daten, daten });
if (!r.ok) throw new Error(`Gespeicherte Daten ließen sich nicht einspielen: ${await r.text()}`);
}
}
const exportiere = async () => (await (await app.verarbeite("GET", "/api/export")).json()) as { einstellungen: unknown; daten: Record<string, { id: string }[]> };
// was zuletzt im Speicher steht, je Dokumentpfad als JSON
const stand = new Map<string, string>();
const spiegel = (x: Awaited<ReturnType<typeof exportiere>>) => {
const m = new Map<string, string>();
for (const [pfad, zeilen] of Object.entries(x.daten)) for (const z of zeilen) m.set(`${pfad}/${z.id}`, JSON.stringify(z));
m.set("meta/einstellungen", JSON.stringify({ daten: x.einstellungen }));
return m;
};
for (const [k, v] of spiegel(await exportiere())) stand.set(k, v);
let kette = Promise.resolve();
const speichern = () => (kette = kette.then(async () => {
if (!speicher) return;
const neu = spiegel(await exportiere());
const auftraege: (() => Promise<void>)[] = [];
for (const [k, v] of neu) if (stand.get(k) !== v) auftraege.push(async () => { await nochmal(() => speicher.doc(k).set(JSON.parse(v))); stand.set(k, v); });
for (const k of stand.keys()) if (!neu.has(k)) auftraege.push(async () => { await nochmal(() => speicher.doc(k).delete()); stand.delete(k); });
if (!auftraege.length) return;
melde("Speichert …");
try {
for (let i = 0; i < auftraege.length; i += 4) await Promise.all(auftraege.slice(i, i + 4).map((a) => a()));
melde("Gespeichert", "ok");
} catch (e) {
melde(`Speichern fehlgeschlagen: ${(e as Error).message}. Bitte Seite neu laden und die letzte Änderung prüfen.`, "fehler");
}
}));
const original = window.fetch.bind(window);
window.fetch = async (eingabe: RequestInfo | URL, init?: RequestInit) => {
const adresse = typeof eingabe === "string" ? eingabe : eingabe instanceof URL ? eingabe.href : eingabe.url;
if (!adresse.startsWith("/api/")) return original(eingabe, init);
const methode = (init?.method ?? "GET").toUpperCase();
const body = typeof init?.body === "string" ? JSON.parse(init.body) : undefined;
const antwort = await app.verarbeite(methode, adresse, body, { "x-benutzer": "henning" });
if (methode !== "GET" && antwort.ok) await speichern();
return antwort;
};
(globalThis as { betriebTestversion?: unknown }).betriebTestversion = {
async sichern() {
if (!laden) throw new Error("Speichern als Datei geht in dieser Ansicht nicht.");
const datei = JSON.stringify(await exportiere(), null, 1);
const tag = new Date().toISOString().slice(0, 10);
try {
await laden.save({ filename: `betrieb-${tag}.json`, data: datei });
return "Datei gesichert.";
} catch (e) {
if ((e as { code?: string }).code === "declined") return "Abgebrochen.";
throw e;
}
},
};
melde(speicher ? "Gespeichert" : "Nur ansehen: Änderungen werden hier nicht gespeichert.", speicher ? "ok" : "fehler");
leiste.hidden = false;
await import("../src/web/app.js");
}
main().catch((e) => {
console.error(e);
melde(`Die Testversion ließ sich nicht starten: ${(e as Error).message}`, "fehler");
leiste.hidden = false;
});

15
demo/node.ts Normal file
View File

@@ -0,0 +1,15 @@
// Was src/server/app.ts aus Node braucht, für den Browser nachgebaut.
export const existsSync = () => false;
export const fileURLToPath = (u: string) => u;
export default { join: (...t: string[]) => t.join("/"), dirname: (p: string) => p };
export function randomBytes(n: number) {
const b = crypto.getRandomValues(new Uint8Array(n));
return { toString: () => btoa(String.fromCharCode(...b)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "") };
}
export function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {
return a.length === b.length && a.every((x, i) => x === b[i]);
}
(globalThis as any).Buffer ??= { from: (s: string) => new TextEncoder().encode(s) };

2
demo/pg.ts Normal file
View File

@@ -0,0 +1,2 @@
// Ersatz für das Paket pg: die Typumwandlung macht hier die PGlite-Anbindung (pool.ts).
export default { types: { setTypeParser() {} }, Pool: class {} };

32
demo/pool.ts Normal file
View File

@@ -0,0 +1,32 @@
// Pool-Schnittstelle von pg auf PGlite (Postgres als WebAssembly im Browser).
import { PGlite, types } from "@electric-sql/pglite";
export const PARSER = {
[types.DATE]: (v: string) => v,
[types.INT8]: (v: string) => Number(v),
[types.NUMERIC]: (v: string) => Number(v),
};
export function alsPool(db: PGlite) {
const query = async (sql: string, params?: unknown[]) => {
if (!params?.length && /;\s*\S/.test(sql.trim().replace(/;\s*$/, ""))) {
await db.exec(sql);
return { rows: [], rowCount: 0 };
}
const r = await db.query(sql, params ?? []);
return { rows: r.rows as any[], rowCount: r.affectedRows ?? r.rows.length };
};
// PGlite hat nur eine Verbindung: Transaktionen laufen nacheinander
let kette: Promise<void> = Promise.resolve();
return {
query,
async connect() {
let frei!: () => void;
const vorher = kette;
kette = new Promise<void>((r) => (frei = r));
await vorher;
return { query, release: () => frei() };
},
async end() {},
};
}

8
package-lock.json generated
View File

@@ -14,6 +14,7 @@
"zod": "^4.0.0" "zod": "^4.0.0"
}, },
"devDependencies": { "devDependencies": {
"@electric-sql/pglite": "^0.5.10",
"@types/node": "^22.10.0", "@types/node": "^22.10.0",
"@types/pg": "^8.11.0", "@types/pg": "^8.11.0",
"esbuild": "^0.25.0", "esbuild": "^0.25.0",
@@ -25,6 +26,13 @@
"node": ">=22" "node": ">=22"
} }
}, },
"node_modules/@electric-sql/pglite": {
"version": "0.5.10",
"resolved": "https://registry.npmjs.org/@electric-sql/pglite/-/pglite-0.5.10.tgz",
"integrity": "sha512-tXc/25U3ulOkiRQuTFdwIv+JhBqtMdAF7Gvo6CfZZWtSB4+hgC4Wr2vwK5ngvvN5PJfAAEGIsfyCVy1JhCOBYw==",
"dev": true,
"license": "Apache-2.0"
},
"node_modules/@esbuild/aix-ppc64": { "node_modules/@esbuild/aix-ppc64": {
"version": "0.25.12", "version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",

View File

@@ -15,7 +15,8 @@
"start": "node dist/server/index.js", "start": "node dist/server/index.js",
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.web.json --noEmit", "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.web.json --noEmit",
"test": "vitest run", "test": "vitest run",
"test:watch": "vitest" "test:watch": "vitest",
"build:demo": "node scripts/build-demo.mjs"
}, },
"dependencies": { "dependencies": {
"@fastify/static": "^10.1.6", "@fastify/static": "^10.1.6",
@@ -24,6 +25,7 @@
"zod": "^4.0.0" "zod": "^4.0.0"
}, },
"devDependencies": { "devDependencies": {
"@electric-sql/pglite": "^0.5.10",
"@types/node": "^22.10.0", "@types/node": "^22.10.0",
"@types/pg": "^8.11.0", "@types/pg": "^8.11.0",
"esbuild": "^0.25.0", "esbuild": "^0.25.0",

39
scripts/build-demo.mjs Normal file
View File

@@ -0,0 +1,39 @@
// Testversion, die komplett im Browser läuft: echte Server-Logik auf PGlite (Postgres als WebAssembly).
// Ergebnis in dist/demo: index.html (Seite mit Oberfläche und Logik) und die drei Datenbankdateien daneben.
import { build } from "esbuild";
import { cp, readFile, writeFile } from "node:fs/promises";
import { readFileSync } from "node:fs";
const ersatz = {
fastify: "./demo/fastify.ts",
"@fastify/static": "./demo/pg.ts",
pg: "./demo/pg.ts",
"node:crypto": "./demo/node.ts",
"node:fs": "./demo/node.ts",
"node:path": "./demo/node.ts",
"node:url": "./demo/node.ts",
};
const version = JSON.parse(await readFile("package.json", "utf8")).version;
await build({
entryPoints: ["demo/main.ts"],
bundle: true,
format: "esm",
platform: "browser",
target: "es2022",
outfile: "dist/demo/app.js",
alias: ersatz,
loader: { ".sql": "text", ".png": "dataurl" },
// PGlite lädt Node-Module nur, wenn es unter Node läuft
plugins: [{ name: "node-extern", setup(b) { b.onResolve({ filter: /^(node:)?(module|fs|fs\/promises|path|url|crypto|worker_threads|os|util)$/ }, (a) => a.importer.includes("node_modules") ? { path: new URL("../demo/leer.ts", import.meta.url).pathname } : undefined); } }],
define: { "process.env.APP_VERSION": JSON.stringify(`${version} Testversion`) },
minify: true,
logLevel: "warning",
});
for (const f of ["pglite.wasm", "initdb.wasm", "pglite.data"]) await cp(`node_modules/@electric-sql/pglite/dist/${f}`, `dist/demo/${f}`);
const js = (await readFile("dist/demo/app.js", "utf8")).replaceAll("</script", "<\\/script");
const logo = `data:image/png;base64,${(await readFile("src/web/bilder/logo.png")).toString("base64")}`;
const seite = (await readFile("demo/index.html", "utf8"))
.replace("/*STYLES*/", () => "\n" + readFileSync("src/web/styles.css", "utf8"))
.replace("/*LOGO*/", logo)
.replace("/*APP*/", () => js);
await writeFile("dist/demo/index.html", seite);

View File

@@ -16,6 +16,7 @@ import { liquiditaet } from "../domain/liquiditaet.js";
import { liquiditaetsDaten } from "../domain/projektplan.js"; import { liquiditaetsDaten } from "../domain/projektplan.js";
import { uebernimmV70 } from "../domain/v70.js"; import { uebernimmV70 } from "../domain/v70.js";
import { speichereUebernahme } from "./v70import.js"; import { speichereUebernahme } from "./v70import.js";
import { pruefeStand, speichereStand } from "./stand.js";
import { VERSION } from "./version.js"; import { VERSION } from "./version.js";
export interface Optionen { export interface Optionen {
@@ -248,6 +249,18 @@ export async function baueApp(o: Optionen): Promise<FastifyInstance> {
return reply.status(201).send({ anzahl, hinweise: u.hinweise }); 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 // D1: kompletter Stand als JSON-Datei
app.get("/api/export", async (_req, reply) => { app.get("/api/export", async (_req, reply) => {
const daten: Record<string, unknown[]> = {}; const daten: Record<string, unknown[]> = {};

42
src/server/stand.ts Normal file
View File

@@ -0,0 +1,42 @@
// D1: einen kompletten Stand (GET /api/export) in ein leeres Programm einspielen, alle IDs bleiben.
// Damit ziehen die Daten aus der Testversion im Browser auf den Server um.
import type { Client } from "./db.js";
import { EinstellungenSchema } from "./einstellungen.js";
import { TABELLEN } from "./tabellen.js";
import { NichtLeer } from "./v70import.js";
export interface Stand {
programm: "betrieb";
einstellungen?: unknown;
daten: Record<string, Record<string, unknown>[]>;
}
export function pruefeStand(x: unknown): Stand {
const s = x as Partial<Stand>;
if (!s || s.programm !== "betrieb" || typeof s.daten !== "object" || s.daten === null) {
throw new Error("Das ist keine Sicherung aus diesem Programm.");
}
return s as Stand;
}
export async function speichereStand(c: Client, s: Stand): Promise<Record<string, number>> {
const belegt = await c.query<{ n: number }>(
`select ${TABELLEN.map((t) => `(select count(*) from ${t.name})`).join(" + ")} as n`,
);
if (Number(belegt.rows[0]!.n) > 0) throw new NichtLeer("Eine Sicherung lässt sich nur in ein leeres Programm einspielen.");
const anzahl: Record<string, number> = {};
// TABELLEN steht in der Reihenfolge der Fremdschlüssel
for (const t of TABELLEN) {
const zeilen = s.daten[t.pfad] ?? [];
for (const z of zeilen) {
await c.query(`insert into ${t.name} select * from json_populate_record(null::${t.name}, $1::json)`, [JSON.stringify(z)]);
}
anzahl[t.pfad] = zeilen.length;
}
if (s.einstellungen !== undefined) {
await c.query("update einstellungen set daten = $1", [EinstellungenSchema.parse(s.einstellungen)]);
}
await c.query("select setval('vorgang_nummer_seq', greatest((select max(nummer) from vorgang), 1000))");
return anzahl;
}

View File

@@ -381,12 +381,22 @@ function kalenderLinks(token: string | null): void {
}; };
} }
/** Testversion im Browser (demo/): speichert anders und kennt keine Kalender-Abos */
const testversion = (globalThis as { betriebTestversion?: { sichern(): Promise<string> } }).betriebTestversion;
async function daten(): Promise<void> { async function daten(): Promise<void> {
seite("Daten und Einstellungen"); seite("Daten und Einstellungen");
const e = await api<Zeile>("einstellungen"); const e = await api<Zeile>("einstellungen");
inhalt.insertAdjacentHTML("beforeend", ` inhalt.insertAdjacentHTML("beforeend", `
<p><a class="neben" href="/api/export" download>Kompletten Stand als JSON sichern</a></p> ${testversion
<p class="hinweis">Die Datenbank wird jede Nacht gesichert und in die Nextcloud kopiert.</p> ? `<p><button class="neben" id="sichern">Kompletten Stand als Datei sichern</button> <span id="sichern-ergebnis"></span></p>
<p class="hinweis">Testversion: Deine Eingaben werden mit diesem Link gespeichert. Mit der Sicherungsdatei ziehen sie später auf den Server um.</p>`
: `<p><a class="neben" href="/api/export" download>Kompletten Stand als JSON sichern</a></p>
<p class="hinweis">Die Datenbank wird jede Nacht gesichert und in die Nextcloud kopiert.</p>`}
<h2>Sicherung einspielen</h2>
<p class="hinweis">Sicherungsdatei aus diesem Programm wählen (betrieb-….json), zum Beispiel aus der Testversion. Geht nur, solange noch nichts erfasst ist.</p>
<p><input type="file" id="stand-datei" accept=".json,application/json"></p>
<div id="stand-ergebnis"></div>
<h2>Übernahme aus dem Projektplaner V70</h2> <h2>Übernahme aus dem Projektplaner V70</h2>
<p class="hinweis">Sicherungsdatei aus V70 wählen (projektplaner-sicherung-….json). Geht nur, solange noch nichts erfasst ist.</p> <p class="hinweis">Sicherungsdatei aus V70 wählen (projektplaner-sicherung-….json). Geht nur, solange noch nichts erfasst ist.</p>
<p><input type="file" id="v70-datei" accept=".json,application/json"></p> <p><input type="file" id="v70-datei" accept=".json,application/json"></p>
@@ -394,7 +404,26 @@ async function daten(): Promise<void> {
<h2>Kalender in Outlook</h2> <h2>Kalender in Outlook</h2>
<div id="kalender"></div> <div id="kalender"></div>
<h2>Einstellungen</h2>`); <h2>Einstellungen</h2>`);
kalenderLinks(e.kalenderToken); if (testversion) {
document.getElementById("kalender")!.innerHTML = `<p class="hinweis">Die Kalender-Abos für Outlook funktionieren erst auf dem Server.</p>`;
const knopf = document.getElementById("sichern")!, ergebnis = document.getElementById("sichern-ergebnis")!;
knopf.onclick = async () => {
try { ergebnis.textContent = await testversion.sichern(); } catch (err) { ergebnis.textContent = (err as Error).message; }
};
} else kalenderLinks(e.kalenderToken);
const stand = document.getElementById("stand-datei") as HTMLInputElement;
stand.onchange = async () => {
const f = stand.files?.[0];
const ziel = document.getElementById("stand-ergebnis")!;
if (!f) return;
try {
const r = await api<{ anzahl: Record<string, number> }>("import/stand", "POST", JSON.parse(await f.text()));
ziel.innerHTML = `<p>Eingespielt: ${r.anzahl.projekte} Projekte, ${r.anzahl.vorgaenge} Vorgänge, ${r.anzahl.aufgaben} Aufgaben, ${r.anzahl.kontakte} Kontakte.</p>`;
} catch (e) {
ziel.innerHTML = `<p class="fehler">${esc((e as Error).message)}</p>`;
}
stand.value = "";
};
const datei = document.getElementById("v70-datei") as HTMLInputElement; const datei = document.getElementById("v70-datei") as HTMLInputElement;
datei.onchange = async () => { datei.onchange = async () => {
const f = datei.files?.[0]; const f = datei.files?.[0];

View File

@@ -6,16 +6,24 @@
--leiste: #13294a; --leiste-text: #b9c7da; --leiste-aktiv: #234a7c; --leiste: #13294a; --leiste-text: #b9c7da; --leiste-aktiv: #234a7c;
--bg: #f2f4f8; --fl: #ffffff; --text: #18202c; --leise: #5f6b7a; --linie: #e0e5ec; --bg: #f2f4f8; --fl: #ffffff; --text: #18202c; --leise: #5f6b7a; --linie: #e0e5ec;
--akzent: #1d5fa8; --akzent-hover: #174d89; --akzent-text: #ffffff; --akzent-hell: #e4eefa; --akzent: #1d5fa8; --akzent-hover: #174d89; --akzent-text: #ffffff; --akzent-hell: #e4eefa;
--warn: #b42318; --warn: #b42318; --warnung-bg: #fdecea; --warnung-text: #7a1c14; --warnung-linie: #f5c2bd;
font-family: system-ui, -apple-system, "Segoe UI", sans-serif; font-size: 15px; font-family: system-ui, -apple-system, "Segoe UI", sans-serif; font-size: 15px;
} }
/* dunkel nach Systemeinstellung, außer jemand wählt ausdrücklich hell (data-theme) */
@media (prefers-color-scheme: dark) { @media (prefers-color-scheme: dark) {
:root { :root:not([data-theme="light"]) {
--leiste: #0d1a2e; --leiste-aktiv: #1d3a62; --leiste: #0d1a2e; --leiste-aktiv: #1d3a62;
--bg: #111822; --fl: #1a2331; --text: #e8edf4; --leise: #9aa7b8; --linie: #2b3747; --bg: #111822; --fl: #1a2331; --text: #e8edf4; --leise: #9aa7b8; --linie: #2b3747;
--akzent: #5a9be0; --akzent-hover: #78b0ea; --akzent-text: #0d1a2e; --akzent-hell: #1d3352; --warn: #f97066; --akzent: #5a9be0; --akzent-hover: #78b0ea; --akzent-text: #0d1a2e; --akzent-hell: #1d3352; --warn: #f97066;
--warnung-bg: #3a1714; --warnung-text: #f9c9c3; --warnung-linie: #6b2620; color-scheme: dark;
} }
} }
:root[data-theme="dark"] {
--leiste: #0d1a2e; --leiste-aktiv: #1d3a62;
--bg: #111822; --fl: #1a2331; --text: #e8edf4; --leise: #9aa7b8; --linie: #2b3747;
--akzent: #5a9be0; --akzent-hover: #78b0ea; --akzent-text: #0d1a2e; --akzent-hell: #1d3352; --warn: #f97066;
--warnung-bg: #3a1714; --warnung-text: #f9c9c3; --warnung-linie: #6b2620; color-scheme: dark;
}
* { box-sizing: border-box; } * { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--text); display: flex; min-height: 100vh; } body { margin: 0; background: var(--bg); color: var(--text); display: flex; min-height: 100vh; }
@@ -154,12 +162,11 @@ button.neben.an { background: var(--akzent-hell); border-color: var(--akzent); c
.person.vorgemerkt { background: transparent; border: 1px dashed var(--leise); color: var(--leise); font-style: italic; } .person.vorgemerkt { background: transparent; border: 1px dashed var(--leise); color: var(--leise); font-style: italic; }
.balken-leute { position: absolute; top: 9px; display: flex; gap: 3px; pointer-events: none; white-space: nowrap; } .balken-leute { position: absolute; top: 9px; display: flex; gap: 3px; pointer-events: none; white-space: nowrap; }
.balken.konflikt { outline: 2px solid var(--warn); outline-offset: 1px; } .balken.konflikt { outline: 2px solid var(--warn); outline-offset: 1px; }
.warnung { background: #fdecea; color: #7a1c14; border: 1px solid #f5c2bd; border-radius: 10px; padding: 10px 14px; margin-bottom: 12px; font-size: 14px; } .warnung { background: var(--warnung-bg); color: var(--warnung-text); border: 1px solid var(--warnung-linie); border-radius: 10px; padding: 10px 14px; margin-bottom: 12px; font-size: 14px; }
.warnung ul { margin: 4px 0 0; padding-left: 18px; } .warnung ul { margin: 4px 0 0; padding-left: 18px; }
.dialog.besetzung table { margin: 8px 0; font-size: 14px; } .dialog.besetzung table { margin: 8px 0; font-size: 14px; }
.dialog.besetzung td { padding: 6px 8px; } .dialog.besetzung td { padding: 6px 8px; }
.dialog.besetzung td .neben { padding: 2px 8px; } .dialog.besetzung td .neben { padding: 2px 8px; }
@media (prefers-color-scheme: dark) { .warnung { background: #3a1714; color: #f9c9c3; border-color: #6b2620; } }
/* Startseite */ /* Startseite */
.kopf h1 .datum { font-size: 15px; font-weight: 400; color: var(--leise); margin-left: 8px; } .kopf h1 .datum { font-size: 15px; font-weight: 400; color: var(--leise); margin-left: 8px; }

View File

@@ -267,3 +267,47 @@ describe.skipIf(!url)("Projektordner in der Nextcloud über die API", () => {
expect(nochmal.nextcloud_link).toBe("01 Angebot/A-26-131 Gaube"); expect(nochmal.nextcloud_link).toBe("01 Angebot/A-26-131 Gaube");
}); });
}); });
describe.skipIf(!url)("Sicherung einspielen (Umzug aus der Testversion)", () => {
let pool: Pool;
let app: FastifyInstance;
const sicherung = JSON.parse(readFileSync(new URL("./daten/v70-sicherung-2026-10-19.json", import.meta.url), "utf8"));
beforeAll(async () => {
pool = erstellePool(url!);
await pool.query("drop schema public cascade; create schema public;");
await migriere(pool);
app = await baueApp({ pool, webOrdner: "/gibt-es-nicht" });
});
afterAll(async () => {
await app?.close();
await pool?.end();
});
it("bringt jeden Datensatz mit derselben ID zurück", async () => {
expect((await app.inject({ method: "POST", url: "/api/import/v70", payload: sicherung })).statusCode).toBe(201);
await app.inject({ method: "PUT", url: "/api/einstellungen", payload: { ...(await app.inject("/api/einstellungen")).json(), startsaldo: 1234500 } });
const vorher = (await app.inject("/api/export")).json();
expect((await app.inject({ method: "POST", url: "/api/import/stand", payload: vorher })).statusCode).toBe(409);
expect((await app.inject({ method: "POST", url: "/api/import/stand", payload: { programm: "anders" } })).statusCode).toBe(400);
await pool.query("drop schema public cascade; create schema public;");
await migriere(pool);
const r = await app.inject({ method: "POST", url: "/api/import/stand", payload: vorher });
expect(r.statusCode, r.body).toBe(201);
expect(r.json().anzahl.vorgaenge).toBe(13);
const nachher = (await app.inject("/api/export")).json();
const ohneZeit = (d: Record<string, Record<string, unknown>[]>) =>
Object.fromEntries(Object.entries(d).map(([k, z]) => [k, z.map(({ angelegt_am, geaendert_am, ...rest }) => rest)]));
expect(ohneZeit(nachher.daten)).toEqual(ohneZeit(vorher.daten));
expect(nachher.einstellungen.startsaldo).toBe(1234500);
// neue Vorgänge bekommen Nummern hinter den übernommenen
const a = vorher.daten.abschnitte[0];
const v = await app.inject({ method: "POST", url: "/api/vorgaenge", payload: { abschnitt_id: a.id, name: "Neu", start: "2026-11-02", dauer: 1 } });
expect(v.statusCode, v.body).toBe(201);
expect(v.json().nummer).toBeGreaterThan(Math.max(...vorher.daten.vorgaenge.map((x: { nummer: number }) => x.nummer)));
});
});