Files
Betriebsf-hrungssoftware/test/kontaktabgleich.test.ts
Claude 82da397c96
Some checks failed
Prüfung / tests (push) Has been cancelled
Prüfung / container (push) Has been cancelled
0.47.0: Kontaktmaske, übergeordnete Kontakte, freie Rollen, Ansprechpartner im Projekt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AmyPfuNc4sCRfaF3oURXZz
2026-11-08 07:29:16 +00:00

161 lines
11 KiB
TypeScript

// Kontakte mit dem Handy abgleichen: Programm ↔ Adressbuch in der Nextcloud (CardDAV-Nachbildung im Speicher)
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import type { FastifyInstance } from "fastify";
import { erstellePool, type Pool } from "../src/server/db.js";
import { migriere } from "../src/server/migrate.js";
import { baueApp } from "../src/server/app.js";
import { Nextcloud } from "../src/server/nextcloud.js";
import { felderAus, karteMit } from "../src/domain/vcard.js";
const url = process.env.TEST_DATABASE_URL;
const BUCH = "/remote.php/dav/addressbooks/users/henning/holzbau/";
function falschesAdressbuch() {
const karten = new Map<string, { etag: string; karte: string }>();
let n = 0;
const etag = () => `"e${++n}"`;
const x = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
const abruf = (async (u: string | URL, init?: RequestInit) => {
const p = decodeURIComponent(new URL(String(u)).pathname);
const kopf = (init?.headers ?? {}) as Record<string, string>;
switch (init?.method) {
case "PROPFIND":
return new Response(`<?xml version="1.0"?><d:multistatus xmlns:d="DAV:" xmlns:card="urn:ietf:params:xml:ns:carddav">
<d:response><d:href>/remote.php/dav/addressbooks/users/henning/</d:href><d:propstat><d:prop><d:resourcetype><d:collection/></d:resourcetype></d:prop></d:propstat></d:response>
<d:response><d:href>${BUCH}</d:href><d:propstat><d:prop><d:displayname>Holzbau</d:displayname><d:resourcetype><d:collection/><card:addressbook/></d:resourcetype></d:prop></d:propstat></d:response>
</d:multistatus>`, { status: 207 });
case "REPORT":
return new Response(`<?xml version="1.0"?><d:multistatus xmlns:d="DAV:" xmlns:card="urn:ietf:params:xml:ns:carddav">${[...karten].map(([h, k]) =>
`<d:response><d:href>${h}</d:href><d:propstat><d:prop><d:getetag>${x(k.etag)}</d:getetag><card:address-data>${x(k.karte)}</card:address-data></d:prop></d:propstat></d:response>`).join("")}</d:multistatus>`, { status: 207 });
case "PUT": {
const da = karten.get(p);
if (kopf["if-none-match"] === "*" && da) return new Response(null, { status: 412 });
if (kopf["if-match"] && kopf["if-match"] !== da?.etag) return new Response(null, { status: 412 });
const e = etag();
karten.set(p, { etag: e, karte: String(init!.body) });
return new Response(null, { status: da ? 204 : 201, headers: { etag: e } });
}
case "DELETE":
karten.delete(p);
return new Response(null, { status: 204 });
}
return new Response(null, { status: 400 });
}) as typeof fetch;
/** Änderung am Handy */
const handy = (href: string, karte: string) => karten.set(href, { etag: etag(), karte });
return { abruf, karten, handy };
}
describe.skipIf(!url)("Kontakte mit dem Handy abgleichen", () => {
let pool: Pool;
let app: FastifyInstance;
const f = falschesAdressbuch();
const nc = new Nextcloud({ url: "https://cloud.test/remote.php/dav/files/henning/01 Projekte", benutzer: "henning", passwort: "geheim" }, f.abruf);
const jetzt = async () => { const r = await app.inject({ method: "POST", url: "/api/kontakte-abgleich/jetzt" }); expect(r.statusCode, r.body).toBe(200); return r.json().meldung as string; };
const kontakt = async (name: string) => (await app.inject("/api/kontakte")).json().find((k: { name: string }) => k.name === name);
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", nextcloud: nc, anmeldung: "testversion" });
});
afterAll(async () => {
await app?.close();
await pool?.end();
});
it("Adressbuch wählen, erster Abgleich führt zusammen und legt an", async () => {
expect((await app.inject("/api/kontakte-abgleich/adressbuecher")).json()).toEqual([{ href: BUCH, name: "Holzbau" }]);
await app.inject({ method: "POST", url: "/api/kontakte", payload: { name: "Petra Braun", rolle: "bauherr", email: "petra@example.de" } });
await app.inject({ method: "POST", url: "/api/kontakte", payload: { name: "Holzhandel Nord", firma: "Holzhandel Nord", rolle: "lieferant" } });
f.handy(`${BUCH}a1.vcf`, "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Petra Braun\r\nN:Braun;Petra;;;\r\nTEL;type=CELL:0171 1\r\nEMAIL:petra@example.de\r\nUID:a1\r\nBDAY:1970-05-04\r\nEND:VCARD\r\n");
f.handy(`${BUCH}a2.vcf`, "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Jan Peters\r\nTEL;type=WORK:0451 2\r\nUID:a2\r\nEND:VCARD\r\n");
expect((await app.inject({ method: "PUT", url: "/api/kontakte-abgleich", payload: { adressbuch: BUCH, an: true } })).statusCode).toBe(200);
expect(await jetzt()).toBe("1 neu vom Handy, 1 neu ins Handy, 1 zusammengeführt");
// Petra: Mobilnummer vom Handy ergänzt, Rolle bleibt
expect(await kontakt("Petra Braun")).toMatchObject({ mobil: "0171 1", rolle: "bauherr" });
expect(await kontakt("Jan Peters")).toMatchObject({ telefon: "0451 2", rolle: "sonstige" });
expect(f.karten.size).toBe(3);
expect(await jetzt()).toBe("alles gleich");
const s = (await app.inject("/api/kontakte-abgleich")).json();
expect(s).toMatchObject({ an: true, adressbuch: BUCH, moeglich: true, verknuepft: 3, geloescht: 0 });
});
it("Änderungen gehen in beide Richtungen, Rest der Karte bleibt", async () => {
const petra = await kontakt("Petra Braun");
await app.inject({ method: "PATCH", url: `/api/kontakte/${petra.id}`, payload: { ort: "Ratzeburg" } });
expect(await jetzt()).toBe("1 ins Handy geschrieben");
const karte = f.karten.get(`${BUCH}a1.vcf`)!.karte;
expect(felderAus(karte).adressen[0]?.ort).toBe("Ratzeburg");
expect(karte).toContain("BDAY:1970-05-04");
// am Handy geändert
f.handy(`${BUCH}a2.vcf`, karteMit({ ...felderAus(f.karten.get(`${BUCH}a2.vcf`)!.karte), emails: [{ typ: "privat", wert: "jan@peters.de", haupt: true }] }, "a2", f.karten.get(`${BUCH}a2.vcf`)!.karte));
expect(await jetzt()).toBe("1 vom Handy übernommen");
expect((await kontakt("Jan Peters")).email).toBe("jan@peters.de");
});
it("im Handy gelöscht bleibt im Programm; im Programm gelöscht verschwindet die Karte", async () => {
f.karten.delete(`${BUCH}a2.vcf`);
expect(await jetzt()).toBe("1 im Handy gelöscht");
expect(await kontakt("Jan Peters")).toBeTruthy();
expect((await app.inject("/api/kontakte-abgleich/kontakte")).json().filter((k: { geloescht: boolean }) => k.geloescht)).toHaveLength(1);
expect(await jetzt()).toBe("alles gleich");
const holz = await kontakt("Holzhandel Nord");
expect((await app.inject({ method: "DELETE", url: `/api/kontakte/${holz.id}` })).statusCode).toBeLessThan(300);
expect(await jetzt()).toBe("1 aus dem Adressbuch entfernt");
expect([...f.karten.values()].some((k) => k.karte.includes("Holzhandel"))).toBe(false);
});
it("übergeordnete Kontakte: ORG ordnet zu, Firmenkarte nur mit eigener Nummer", async () => {
const wn = (await app.inject({ method: "POST", url: "/api/kontakte", payload: { name: "Wohnbau Nord eG", art: "firma" } })).json();
const ohne = (await app.inject({ method: "POST", url: "/api/kontakte", payload: { name: "Familie Ohnenummer", art: "familie" } })).json();
expect(await jetzt()).toBe("alles gleich");
// Person am Handy mit ORG = vorhandene Firma und zwei Nummern
f.handy(`${BUCH}t1.vcf`, "BEGIN:VCARD\r\nVERSION:3.0\r\nN:Möller;Tim;;;\r\nFN:Tim Möller\r\nORG:Wohnbau Nord eG;\r\nTITLE:Hausmeister\r\n"
+ "TEL;type=CELL;type=pref:0160 5550101\r\nTEL;type=WORK:04541 80801\r\nUID:t1\r\nEND:VCARD\r\n");
// Person mit unbekannter Firma
f.handy(`${BUCH}t2.vcf`, "BEGIN:VCARD\r\nVERSION:3.0\r\nN:Lange;Uwe;;;\r\nFN:Uwe Lange\r\nORG:Lange Bedachungen;\r\nUID:t2\r\nEND:VCARD\r\n");
expect(await jetzt()).toBe("2 neu vom Handy");
const tim = await kontakt("Tim Möller");
expect(tim.telefone).toEqual([{ typ: "mobil", wert: "0160 5550101", haupt: true }, { typ: "geschaeftlich", wert: "04541 80801", haupt: false }]);
expect(tim).toMatchObject({ mobil: "0160 5550101", telefon: "04541 80801", firma: null });
const zug = (await app.inject("/api/kontakt-zugehoerigkeiten")).json();
expect(zug).toEqual([expect.objectContaining({ gruppe_id: wn.id, person_id: tim.id, funktion: "Hausmeister" })]);
expect((await kontakt("Uwe Lange")).firma).toBe("Lange Bedachungen");
// Funktion im Programm geändert: geht ins Handy
await app.inject({ method: "PATCH", url: `/api/kontakt-zugehoerigkeiten/${zug[0].id}`, payload: { funktion: "Hauswart" } });
await app.inject({ method: "PATCH", url: `/api/kontakte/${tim.id}`, payload: { notiz: "Schlüssel" } });
expect(await jetzt()).toBe("1 ins Handy geschrieben");
expect(felderAus(f.karten.get(`${BUCH}t1.vcf`)!.karte)).toMatchObject({ funktion: "Hauswart", firma: "Wohnbau Nord eG", notiz: "Schlüssel" });
// Firma bekommt eine eigene Nummer: eigene Firmenkarte; die Familie ohne Nummer nicht
await app.inject({ method: "PATCH", url: `/api/kontakte/${wn.id}`, payload: { telefone: [{ typ: "zentrale", wert: "04541 80800", haupt: true }] } });
expect(await jetzt()).toBe("1 neu ins Handy");
const karte = f.karten.get(`${BUCH}${wn.id}.vcf`)!.karte;
expect(felderAus(karte)).toMatchObject({ name: "Wohnbau Nord eG", gruppe: true, telefone: [{ typ: "zentrale", wert: "04541 80800", haupt: true }] });
expect([...f.karten.values()].some((k) => k.karte.includes("Ohnenummer"))).toBe(false);
expect(ohne.id).toBeTruthy();
expect(await jetzt()).toBe("alles gleich");
});
it("Umstellung von 0.46: Nummern aus dem Handy gehen nicht verloren", async () => {
const tim = await kontakt("Tim Möller");
// so stand es nach 0.46 da: alter Fingerabdruck, im Handy eine dritte Nummer
const href = `${BUCH}t1.vcf`;
const alt = f.karten.get(href)!.karte.replace("END:VCARD", "TEL;type=HOME:04541 7777\r\nEND:VCARD");
f.handy(href, alt);
await pool.query("update kontakt_abgleich set stand = '[\"alt\"]', etag = $2 where href = $1", [href, f.karten.get(href)!.etag]);
expect(await jetzt()).toBe("1 zusammengeführt");
expect((await kontakt("Tim Möller")).telefone.map((x: { wert: string }) => x.wert)).toEqual(["0160 5550101", "04541 80801", "04541 7777"]);
expect(tim.id).toBeTruthy();
expect(await jetzt()).toBe("alles gleich");
});
it(".vcf-Datei einlesen ergänzt und legt an", async () => {
const r = await app.inject({ method: "POST", url: "/api/kontakte/vcf", payload: { text: "BEGIN:VCARD\nVERSION:3.0\nFN:Petra Braun\nTEL;type=HOME:04541 8899\nEND:VCARD\nBEGIN:VCARD\nVERSION:3.0\nFN:Stadt Ratzeburg\nORG:Stadt Ratzeburg;\nEND:VCARD\n" } });
expect(r.json()).toEqual({ neu: 1, ergaenzt: 1, gleich: 0 });
expect((await kontakt("Petra Braun")).telefon).toBe("04541 8899");
expect((await app.inject({ method: "POST", url: "/api/kontakte/vcf", payload: { text: "kein vcard" } })).statusCode).toBe(400);
});
});