Files
Betriebsf-hrungssoftware/src/server/nextcloud.ts
Claude fc9a4c4dcf
Some checks failed
Prüfung / tests (push) Has been cancelled
Prüfung / container (push) Has been cancelled
0.53.0: Bauherr im Nextcloud-Ordnernamen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AmyPfuNc4sCRfaF3oURXZz
2026-11-13 19:30:42 +00:00

181 lines
8.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// P10: Projektordner in Hennings Nextcloud anlegen und je nach Status verschieben (WebDAV, App-Passwort).
// Statusordner und Unterordner wie in seiner Ablage (Henning, 18./19.10.2026).
export interface NextcloudZugang {
/** WebDAV-Adresse des Ordners, in dem „01 Angebot“ … „04 Archiv“ liegen */
url: string;
benutzer: string;
passwort: string;
}
export interface AblageEintrag {
name: string;
ordner: boolean;
groesse: number;
geaendert: string | null;
}
export const STATUSORDNER: Record<string, string> = {
anfrage: "01 Angebot",
angebot: "01 Angebot",
auftrag: "02 laufende Projekte",
ausfuehrung: "02 laufende Projekte",
abgerechnet: "02 laufende Projekte",
gewaehrleistung: "03 Gewährl.-Projekte",
abgeschlossen: "04 Archiv",
// interne Projekte (Henning, 24.10.2026)
intern: "05 Intern",
};
export const UNTERORDNER = ["01 Auftrag", "01 Auftrag/03 Stundenlohnarb.", "02 Umsetzung", "03 Bilder"];
/**
* „P-26-020 Terrassendachsanierung - Fam. Krause“: Nummer, Titel und Bauherr (Henning, 13.11.2026).
* Schrägstriche und Steuerzeichen sind in Ordnernamen nicht erlaubt.
*/
export function ordnerName(nummer: string, bezeichnung: string, bauherr?: string | null): string {
const name = `${nummer} ${bezeichnung}${bauherr?.trim() ? ` - ${bauherr.trim()}` : ""}`;
return name.replace(/[\\/:*?"<>|\u0000-\u001f]/g, "-").replace(/\s+/g, " ").trim();
}
export function zielPfad(p: { nummer: string; bezeichnung: string; status: string; bauherr?: string | null }): string {
return `${STATUSORDNER[p.status] ?? STATUSORDNER.anfrage}/${ordnerName(p.nummer, p.bezeichnung, p.bauherr)}`;
}
/**
* WebDAV-Adresse des Ordners mit „01 Angebot“ … „04 Archiv“. Die Adresse darf die volle WebDAV-Adresse aus den
* Dateien-Einstellungen sein (…/remote.php/dav/files/<benutzer>) oder nur die Serveradresse; dann wird sie ergänzt.
*/
export function webdavBasis(z: { adresse: string; benutzer: string; ordner: string }): string {
let a = z.adresse.trim().replace(/\/+$/, "");
if (!/\/remote\.php\//.test(a)) a = `${a}/remote.php/dav/files/${encodeURIComponent(z.benutzer)}`;
const teile = z.ordner.split(/[\\/]/).filter(Boolean);
return teile.length ? `${a}/${teile.map(encodeURIComponent).join("/")}` : a;
}
/**
* Fehlertext mit Ursache: „fetch failed“ allein sagt nichts; die Ursache (z. B. Zertifikat, DNS, Verbindung abgelehnt)
* steckt in err.cause mit code und message.
*/
export function fehlerText(err: unknown): string {
const teile: string[] = [];
for (let e = err as { message?: string; code?: string; cause?: unknown } | undefined, n = 0; e && n < 4; e = e.cause as typeof e, n++) {
const t = [e.code, e.message].filter(Boolean).join(": ");
if (t && !teile.includes(t)) teile.push(t);
}
return teile.join(" – ") || String(err);
}
/** Netzfehler mit Ziel und Ursache weiterreichen */
export async function abrufMitUrsache(abruf: typeof fetch, adresse: string, init: RequestInit): Promise<Response> {
try {
return await abruf(adresse, init);
} catch (err) {
throw new Error(`${new URL(adresse).host} nicht erreichbar: ${fehlerText(err)}`, { cause: err });
}
}
const kodiert = (pfad: string) => pfad.split("/").map(encodeURIComponent).join("/");
export class Nextcloud {
constructor(readonly z: NextcloudZugang, readonly abruf: typeof fetch = fetch) {}
private adresse(pfad: string): string {
return `${this.z.url.replace(/\/+$/, "")}/${kodiert(pfad)}`;
}
private async anfrage(methode: string, pfad: string, kopf: Record<string, string> = {}, body?: string): Promise<Response> {
return abrufMitUrsache(this.abruf, this.adresse(pfad), {
method: methode,
headers: { authorization: `Basic ${btoa(`${this.z.benutzer}:${this.z.passwort}`)}`, ...kopf },
body,
});
}
async gibtEs(pfad: string): Promise<boolean> {
const r = await this.anfrage("PROPFIND", pfad, { depth: "0" });
if (r.status === 404) return false;
if (r.ok || r.status === 207) return true;
throw new Error(`Nextcloud antwortet mit ${r.status} für ${pfad}`);
}
/** Namen der Unterordner (eine Ebene) */
async liste(pfad: string): Promise<string[]> {
const r = await this.anfrage("PROPFIND", pfad, { depth: "1" });
if (r.status === 404) return [];
if (r.status !== 207) throw new Error(`Nextcloud antwortet mit ${r.status} für ${pfad}`);
const xml = await r.text();
const basis = new URL(this.adresse(pfad)).pathname.replace(/\/+$/, "");
return [...xml.matchAll(/<d:href>([^<]+)<\/d:href>/gi)]
.map((m) => decodeURIComponent(m[1]!).replace(/\/+$/, ""))
.filter((h) => h !== decodeURIComponent(basis) && h.startsWith(decodeURIComponent(basis)))
.map((h) => h.slice(decodeURIComponent(basis).length + 1));
}
/** Inhalt eines Ordners mit Art, Größe und Änderungsdatum, Ordner zuerst (Ablage auf der Projektseite) */
async inhalt(pfad: string): Promise<AblageEintrag[] | null> {
const r = await this.anfrage("PROPFIND", pfad, { depth: "1" });
if (r.status === 404) return null;
if (r.status !== 207) throw new Error(`Nextcloud antwortet mit ${r.status} für ${pfad}`);
const xml = await r.text();
const basis = decodeURIComponent(new URL(this.adresse(pfad)).pathname.replace(/\/+$/, ""));
const eintraege: AblageEintrag[] = [];
for (const m of xml.matchAll(/<d:response>([\s\S]*?)<\/d:response>/gi)) {
const teil = m[1]!;
const href = decodeURIComponent(/<d:href>([^<]+)<\/d:href>/i.exec(teil)?.[1] ?? "").replace(/\/+$/, "");
if (href === basis || !href.startsWith(basis + "/")) continue;
const wert = (tag: string) => new RegExp(`<d:${tag}>([^<]*)</d:${tag}>`, "i").exec(teil)?.[1];
eintraege.push({
name: href.slice(basis.length + 1),
ordner: /<d:collection\s*\/>/i.test(teil),
groesse: Number(wert("getcontentlength") ?? 0),
geaendert: wert("getlastmodified") ? new Date(wert("getlastmodified")!).toISOString() : null,
});
}
return eintraege.sort((a, b) => Number(b.ordner) - Number(a.ordner) || a.name.localeCompare(b.name, "de"));
}
/** Eine Datei abrufen, um sie durchzureichen */
async datei(pfad: string): Promise<Response> {
const r = await this.anfrage("GET", pfad);
if (r.status === 404) throw Object.assign(new Error("Datei nicht gefunden"), { statusCode: 404 });
if (!r.ok) throw new Error(`Nextcloud antwortet mit ${r.status} für ${pfad}`);
return r;
}
async ordner(pfad: string): Promise<void> {
const r = await this.anfrage("MKCOL", pfad);
if (!(r.status === 201 || r.status === 405)) throw new Error(`Ordner ${pfad} ließ sich nicht anlegen (${r.status})`);
}
async verschiebe(von: string, nach: string): Promise<void> {
const r = await this.anfrage("MOVE", von, { destination: this.adresse(nach), overwrite: "F" });
if (!(r.status === 201 || r.status === 204)) throw new Error(`${von} ließ sich nicht nach ${nach} verschieben (${r.status})`);
}
}
/**
* Bringt den Ordner eines Projekts an die richtige Stelle. `bisher` ist der zuletzt bekannte Pfad
* (projekt.nextcloud_link). Ohne bekannten Pfad wird ein vorhandener Ordner mit derselben Nummer in
* den Statusordnern gesucht und übernommen, sonst ein neuer mit Unterordnern angelegt.
* Gibt den neuen Pfad zurück.
*/
export async function ordnerAbgleichen(nc: Nextcloud, p: { nummer: string; bezeichnung: string; status: string; bauherr?: string | null }, bisher: string | null): Promise<string> {
const ziel = zielPfad(p);
if (bisher === ziel && (await nc.gibtEs(ziel))) return ziel;
let quelle = bisher && (await nc.gibtEs(bisher)) ? bisher : null;
if (!quelle) {
for (const s of new Set(Object.values(STATUSORDNER))) {
const treffer = (await nc.liste(s)).find((n) => n === p.nummer || n.startsWith(`${p.nummer} `));
if (treffer) { quelle = `${s}/${treffer}`; break; }
}
}
await nc.ordner(ziel.split("/")[0]!);
if (quelle && quelle !== ziel) await nc.verschiebe(quelle, ziel);
if (!quelle) {
await nc.ordner(ziel);
for (const u of UNTERORDNER) await nc.ordner(`${ziel}/${u}`);
}
return ziel;
}