Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AmyPfuNc4sCRfaF3oURXZz
174 lines
9.7 KiB
TypeScript
174 lines
9.7 KiB
TypeScript
// 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 { NUR_SICHERUNG, TABELLEN } from "../src/server/tabellen.js";
|
|
import { kiAnfrage, kiVorschlaege } from "../src/domain/ki.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> };
|
|
// Tabelle, deren Zeilen gebündelt gespeichert werden (Speicher: ein Dokument je Zeile wäre bei 20 000 Artikeln zu viel)
|
|
const PAKETE = "artikel";
|
|
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"),
|
|
// Dateisystem-Abbild von Postgres (pglite.data, beim Bauen umbenannt)
|
|
fetch(adresse("pglite-data.wasm")).then((r) => { if (!r.ok) throw new Error(`pglite-data.wasm: ${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]);
|
|
// KI-Vorschlag im Angebot: fragt Claude über das Konto dessen, der die Testversion offen hat (sample-Fähigkeit)
|
|
const sample = claude?.use("sample").catch(() => null) ?? Promise.resolve(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 pfad of [...TABELLEN, ...NUR_SICHERUNG].map((t) => t.pfad).concat("benutzer", "ansichten")) {
|
|
daten[pfad] = pfad === PAKETE ? (await nochmal(() => alle(speicher, `${PAKETE}-paket`))).flatMap((p) => p.zeilen as Record<string, unknown>[]) : await nochmal(() => alle(speicher, 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)) {
|
|
if (pfad !== PAKETE) { for (const z of zeilen) m.set(`${pfad}/${z.id}`, JSON.stringify(z)); continue; }
|
|
// Artikel kommen zu Tausenden (DATANORM): je Paket ein Dokument, nach den ersten zwei Zeichen der id
|
|
const pakete = new Map<string, { id: string }[]>();
|
|
for (const z of zeilen) { const k = z.id.slice(0, 2); if (!pakete.has(k)) pakete.set(k, []); pakete.get(k)!.push(z); }
|
|
for (const [k, liste] of pakete) m.set(`${PAKETE}-paket/${k}`, JSON.stringify({ id: k, zeilen: liste }));
|
|
}
|
|
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");
|
|
}
|
|
}));
|
|
|
|
// Aufgaben-Vorlage für beauftragte Projekte, die sie noch nicht haben (z. B. nach einem Update der Testversion)
|
|
const vorlage = await app.verarbeite("POST", "/api/vorlage/anwenden");
|
|
// auch ohne neue Aufgaben: vermerkt, was ein Projekt schon bekommen hat
|
|
if (vorlage.ok) await speichern();
|
|
|
|
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;
|
|
if (adresse === "/api/ki" && methode === "POST") return ki(body);
|
|
// die Oberfläche schickt mit, als wer Henning gerade arbeitet (x-test-benutzer)
|
|
const antwort = await app.verarbeite(methode, adresse, body, Object.fromEntries(new Headers(init?.headers).entries()));
|
|
if (methode !== "GET" && antwort.ok) await speichern();
|
|
return antwort;
|
|
};
|
|
|
|
const ki = async (body: { text?: string }): Promise<Response> => {
|
|
const antwort = (status: number, x: unknown) => new Response(JSON.stringify(x), { status, headers: { "content-type": "application/json" } });
|
|
const s = await sample;
|
|
if (!s) return antwort(409, { fehler: "Claude ist in dieser Ansicht nicht erreichbar. Die Testversion im Claude-Fenster öffnen." });
|
|
const text = String(body?.text ?? "").trim();
|
|
if (text.length < 5) return antwort(400, { fehler: "Bitte kurz beschreiben, was gemacht werden soll." });
|
|
const leistungen = (await (await app.verarbeite("GET", "/api/leistungen")).json()) as { id: string; kurztext: string; einheit: string | null; gruppe: string; nummer: string | null }[];
|
|
if (!leistungen.length) return antwort(409, { fehler: "Es gibt noch keine Leistungen in den Stammdaten." });
|
|
try {
|
|
const r = await s(kiAnfrage(text, leistungen.slice(0, 800).map((l) => ({ id: l.id, kurztext: l.kurztext, einheit: l.einheit, ordner: l.gruppe, nummer: l.nummer }))), { modelTier: "default" });
|
|
return antwort(200, { vorschlaege: kiVorschlaege(r.text, new Set(leistungen.map((l) => l.id))) });
|
|
} catch (e) {
|
|
const code = (e as { code?: string }).code;
|
|
return antwort(409, { fehler: code === "not_granted" ? "Claude wurde nicht erlaubt. Beim nächsten Versuch die Anfrage zulassen." : code === "rate_limited" ? "Gerade zu viele Anfragen. Bitte gleich noch einmal." : `Claude hat nicht geantwortet: ${(e as Error).message ?? code}` });
|
|
}
|
|
};
|
|
|
|
const datei = async (filename: string, data: string) => {
|
|
if (!laden) throw new Error("Speichern als Datei geht in dieser Ansicht nicht.");
|
|
try {
|
|
await laden.save({ filename, data });
|
|
return "Datei gesichert.";
|
|
} catch (e) {
|
|
if ((e as { code?: string }).code === "declined") return "Abgebrochen.";
|
|
throw e;
|
|
}
|
|
};
|
|
(globalThis as { betriebTestversion?: unknown }).betriebTestversion = {
|
|
sichern: async () => datei(`betrieb-${new Date().toISOString().slice(0, 10)}.json`, JSON.stringify(await exportiere(), null, 1)),
|
|
datei,
|
|
};
|
|
|
|
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;
|
|
});
|