0.47.0: Kontaktmaske, übergeordnete Kontakte, freie Rollen, Ansprechpartner im Projekt
Some checks failed
Prüfung / tests (push) Has been cancelled
Prüfung / container (push) Has been cancelled

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AmyPfuNc4sCRfaF3oURXZz
This commit is contained in:
Claude
2026-11-08 07:29:16 +00:00
parent 3e8abd0eeb
commit 82da397c96
22 changed files with 1413 additions and 169 deletions

108
src/domain/kontaktdaten.ts Normal file
View File

@@ -0,0 +1,108 @@
// Kontaktdaten wie in der Nextcloud (Henning, 08.11.2026): Telefon, E-Mail und Adresse beliebig oft, je mit Typ,
// ein Eintrag als Haupteintrag (★). Die alten Einzelfelder telefon, mobil, email, strasse, plz, ort bleiben als
// Haupteinträge in der Tabelle, damit Listen, Suche, Projektseite und Handy-Einsatz weiter einfach lesen können.
export interface Nummer { typ: string; wert: string; haupt?: boolean }
export interface Anschrift {
typ: string; strasse: string; zusatz?: string; plz: string; ort: string; region?: string; land?: string; postfach?: string; haupt?: boolean;
}
export interface Listen { telefone: Nummer[]; emails: Nummer[]; adressen: Anschrift[] }
export interface Einzelfelder {
telefon: string | null; mobil: string | null; email: string | null; strasse: string | null; plz: string | null; ort: string | null;
}
export const TYP_TEXT: Record<string, string> = {
mobil: "Mobil", privat: "Privat", geschaeftlich: "Geschäftlich", zentrale: "Zentrale", rechnung: "Rechnungen", fax: "Fax", sonstige: "Sonstige",
};
export const TELEFON_TYPEN = ["mobil", "privat", "geschaeftlich", "zentrale", "fax", "sonstige"];
export const EMAIL_TYPEN = ["privat", "geschaeftlich", "rechnung", "sonstige"];
export const ADRESS_TYPEN = ["privat", "geschaeftlich", "rechnung", "sonstige"];
/** Übergeordnete Kontakte */
export const ARTEN: [string, string][] = [["firma", "Firma / Institution"], ["behoerde", "Behörde / Gemeinde"], ["familie", "Familie"], ["ehepaar", "Ehepaar"], ["weg", "Eigentümergemeinschaft (WEG)"]];
export const ART_KURZ: Record<string, string> = { firma: "Firma", behoerde: "Behörde", familie: "Familie", ehepaar: "Ehepaar", weg: "WEG" };
/** Wofür ein Ansprechpartner zuständig ist */
export const ZUSTAENDIG: [string, string][] = [["haupt", "Haupt"], ["rechnungen", "Rechnungen"], ["baustelle", "Baustelle"], ["planung", "Planung"]];
const t = (s: unknown) => (typeof s === "string" ? s.trim() : "");
const leer = (s: string) => (s ? s : null);
/** Leere Einträge weg, genau ein Haupteintrag je Liste (der erste markierte, sonst der erste) */
function aufraeumen<T extends { haupt?: boolean }>(liste: T[], voll: (x: T) => boolean): T[] {
const l = liste.filter(voll).map((x) => ({ ...x, haupt: !!x.haupt }));
const i = Math.max(0, l.findIndex((x) => x.haupt));
return l.map((x, j) => ({ ...x, haupt: j === i }));
}
export function listenBereinigt(l: Partial<Listen>): Listen {
const nr = (x: Nummer): Nummer => ({ typ: t(x.typ) || "sonstige", wert: t(x.wert), haupt: !!x.haupt });
const adr = (x: Anschrift): Anschrift => ({
typ: t(x.typ) || "sonstige", strasse: t(x.strasse), zusatz: t(x.zusatz), plz: t(x.plz), ort: t(x.ort), region: t(x.region), land: t(x.land), postfach: t(x.postfach), haupt: !!x.haupt,
});
return {
telefone: aufraeumen((l.telefone ?? []).map(nr), (x) => !!x.wert),
emails: aufraeumen((l.emails ?? []).map(nr), (x) => !!x.wert),
adressen: aufraeumen((l.adressen ?? []).map(adr), (x) => !!(x.strasse || x.plz || x.ort || x.postfach)),
};
}
const haupt = <T extends { haupt?: boolean }>(l: T[]) => l.find((x) => x.haupt) ?? l[0];
/** Einzelfelder aus den Listen: Mobil = erste Mobilnummer, Telefon = Hauptnummer, sonst die erste andere */
export function einzelfelder(l: Listen): Einzelfelder {
const mobil = l.telefone.find((x) => x.typ === "mobil" && x.haupt) ?? l.telefone.find((x) => x.typ === "mobil");
const andere = l.telefone.filter((x) => x !== mobil && x.typ !== "fax");
const telefon = andere.find((x) => x.haupt) ?? andere[0];
const a = haupt(l.adressen);
return {
telefon: leer(telefon?.wert ?? ""), mobil: leer(mobil?.wert ?? ""), email: leer(haupt(l.emails)?.wert ?? ""),
strasse: leer(a?.strasse ?? ""), plz: leer(a?.plz ?? ""), ort: leer(a?.ort ?? ""),
};
}
/**
* Einzelfelder in vorhandene Listen einarbeiten, für Teile, die nur Einzelfelder schreiben (Kunde im Projekt anlegen,
* Datei-Import). Nur die übergebenen Felder ändern etwas; null entfernt den passenden Eintrag.
*/
export function einarbeiten(l: Listen, f: Partial<Einzelfelder>, firma = false): Listen {
const neu: Listen = { telefone: [...l.telefone], emails: [...l.emails], adressen: [...l.adressen] };
const typ = firma ? "geschaeftlich" : "privat";
const setze = (liste: Nummer[], finde: (x: Nummer) => boolean, wert: string | null | undefined, neuTyp: string) => {
if (wert === undefined) return;
const i = liste.findIndex(finde);
if (!t(wert)) { if (i >= 0) liste.splice(i, 1); return; }
if (i >= 0) liste[i] = { ...liste[i]!, wert: t(wert) };
else liste.push({ typ: neuTyp, wert: t(wert), haupt: !liste.length });
};
const mobil = neu.telefone.find((x) => x.typ === "mobil" && x.haupt) ?? neu.telefone.find((x) => x.typ === "mobil");
const andere = neu.telefone.filter((x) => x !== mobil && x.typ !== "fax");
const tel = andere.find((x) => x.haupt) ?? andere[0];
setze(neu.telefone, (x) => x === mobil, f.mobil, "mobil");
setze(neu.telefone, (x) => x === tel, f.telefon, typ);
setze(neu.emails, (x) => x === haupt(neu.emails), f.email, typ);
if (f.strasse !== undefined || f.plz !== undefined || f.ort !== undefined) {
const a = haupt(neu.adressen);
const x: Anschrift = a ? { ...a } : { typ, strasse: "", zusatz: "", plz: "", ort: "", region: "", land: "", postfach: "", haupt: true };
if (f.strasse !== undefined) { x.strasse = t(f.strasse); x.zusatz = ""; }
if (f.plz !== undefined) x.plz = t(f.plz);
if (f.ort !== undefined) x.ort = t(f.ort);
if (a) neu.adressen[neu.adressen.indexOf(a)] = x; else neu.adressen.push(x);
}
return listenBereinigt(neu);
}
/** Adresse in einer Zeile */
export const adressZeile = (a: Pick<Anschrift, "strasse" | "zusatz" | "plz" | "ort"> | undefined) =>
a ? [[a.strasse, a.zusatz].filter(Boolean).join(", "), [a.plz, a.ort].filter(Boolean).join(" ")].filter(Boolean).join(", ") : "";
/** Kürzel für den runden Platzhalter: JP für Jan Petersen, WN für Wohnbau Nord eG */
export function kuerzel(name: string): string {
const w = name.replace(/[^\p{L}\p{N}\s-]/gu, " ").split(/\s+/).filter((x) => x && !/^(eG|GmbH|AG|KG|e\.?V|mbH|und|&)$/i.test(x));
return ((w[0]?.[0] ?? "") + (w.length > 1 ? w[w.length - 1]![0] : w[0]?.[1] ?? "")).toUpperCase() || "?";
}
/** Rollen-Kennung aus einem Namen: „Statiker“ → statiker */
export function rollenId(name: string): string {
return name.trim().toLowerCase().replace(/ä/g, "ae").replace(/ö/g, "oe").replace(/ü/g, "ue").replace(/ß/g, "ss")
.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "rolle";
}

View File

@@ -1,24 +1,33 @@
// Kontakte mit dem Handy abgleichen (Henning, 04.11.2026): vCard lesen und schreiben (RFC 2426/6350, wie Apple sie liefert).
// Das Programm pflegt nur Name, Firma, Telefon, Mobil, E-Mail und Adresse; alles andere in der Karte (Foto,
// Geburtstag, weitere Nummern) bleibt beim Zurückschreiben unverändert stehen.
// Seit 0.47 (Henning, 08.11.2026) eine Karte je Person mit allen Telefonnummern, E-Mail-Adressen und Adressen samt Typ;
// ORG ist der erste übergeordnete Kontakt. Alles andere in der Karte (Foto, Geburtstag, Webseiten) bleibt beim
// Zurückschreiben unverändert stehen, ebenso Nummern- oder Adresszeilen, solange sich an ihnen nichts geändert hat.
import { type Anschrift, type Nummer, ADRESS_TYPEN, EMAIL_TYPEN, TELEFON_TYPEN, listenBereinigt } from "./kontaktdaten.js";
export interface KontaktFelder {
name: string;
anrede: string | null;
titel: string | null;
/** ORG: bei Personen der erste übergeordnete Kontakt (sonst die frei eingetragene Firma), bei Firmen der eigene Name */
firma: string | null;
telefon: string | null;
mobil: string | null;
email: string | null;
strasse: string | null;
plz: string | null;
ort: string | null;
/** TITLE; undefined: im Programm nicht gepflegt (Person ohne übergeordneten Kontakt), die Karte behält ihre Angabe */
funktion?: string | null;
/** Firmenkarte (X-ABShowAs:COMPANY) */
gruppe: boolean;
telefone: Nummer[];
emails: Nummer[];
adressen: Anschrift[];
notiz: string | null;
}
export const FELDER: (keyof KontaktFelder)[] = ["name", "firma", "telefon", "mobil", "email", "strasse", "plz", "ort"];
interface Zeile {
/** Gruppe wie „item1“ bei Apple */
gruppe: string;
/** Name in Großbuchstaben zum Vergleichen */
name: string;
/** Name wie in der Karte geschrieben (X-ABLabel bleibt X-ABLabel) */
roh: string;
params: string;
wert: string;
}
@@ -32,7 +41,8 @@ function zeilen(text: string): Zeile[] {
const wert = i < 0 ? "" : z.slice(i + 1);
const [nameTeil, ...params] = kopf.split(";");
const punkt = nameTeil!.lastIndexOf(".");
return { gruppe: punkt < 0 ? "" : nameTeil!.slice(0, punkt), name: nameTeil!.slice(punkt + 1).toUpperCase(), params: params.join(";"), wert };
const n = nameTeil!.slice(punkt + 1);
return { gruppe: punkt < 0 ? "" : nameTeil!.slice(0, punkt), name: n.toUpperCase(), roh: n, params: params.join(";"), wert };
});
}
@@ -41,14 +51,15 @@ const esc = (s: string) => s.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replac
/** Strukturierte Werte (N, ADR, ORG) an unmaskierten Semikolons teilen */
const teile = (s: string) => s.split(/(?<!\\);/).map(ent);
const leer = (s: string | undefined | null) => (s && s.trim() ? s.trim() : null);
const istMobil = (z: Zeile) => /type=[^;:]*\b(cell|iphone|mobile)\b/i.test(z.params) || /\bcell\b/i.test(z.params);
const istTelefon = (z: Zeile) => z.name === "TEL" && !/\bfax\b/i.test(z.params);
/** Einzelne Karten aus einer .vcf-Datei mit vielen Kontakten */
export function kartenAus(text: string): string[] {
return [...text.replace(/\r\n|\r/g, "\n").matchAll(/BEGIN:VCARD[\s\S]*?END:VCARD/gi)].map((m) => m[0]);
}
/** Kontaktgruppe (Verteiler) der Nextcloud oder von Apple, kein Kontakt */
export const istVerteiler = (karte: string) => /^(X-ADDRESSBOOKSERVER-KIND|KIND):\s*group\s*$/im.test(karte.replace(/\r/g, ""));
export function uidVon(karte: string): string | null {
return leer(zeilen(karte).find((z) => z.name === "UID")?.wert);
}
@@ -61,33 +72,100 @@ export function revVon(karte: string): string | null {
return m ? `${m[1]}-${m[2]}-${m[3]}T${m[4] ?? "00"}:${m[5] ?? "00"}:${m[6] ?? "00"}Z` : null;
}
/** type=CELL;type=pref, TYPE="work,voice", PREF=1 oder TEL;CELL (vCard 2.1) */
function typen(z: Zeile): string[] {
const t: string[] = [];
for (const p of z.params.split(";").filter(Boolean)) {
const i = p.indexOf("=");
const k = (i < 0 ? "type" : p.slice(0, i)).toLowerCase();
const v = i < 0 ? p : p.slice(i + 1);
if (k === "type") t.push(...v.replace(/"/g, "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean));
if (k === "pref") t.push("pref");
}
return t;
}
/** Apple-Bezeichnung (_$!<Mobile>!$_) oder eigene Bezeichnung wie „Rechnungen“ */
function ausBezeichnung(l: string): string | undefined {
const m = /^_\$!<(.+)>!\$_$/.exec(l);
const s = (m ? m[1]! : l).toLowerCase();
if (/fax/.test(s)) return "fax";
if (/mobil|handy|iphone|cell/.test(s)) return "mobil";
if (/rechnung|buchhaltung|invoice|billing/.test(s)) return "rechnung";
if (/zentrale|main/.test(s)) return "zentrale";
if (/home|privat|zuhause/.test(s)) return "privat";
if (/work|büro|buero|geschäft|geschaeft|arbeit|firma/.test(s)) return "geschaeftlich";
if (/other|sonstig|andere/.test(s)) return "sonstige";
return undefined;
}
function typVon(z: Zeile, alle: Zeile[]): string {
const erlaubt = z.name === "TEL" ? TELEFON_TYPEN : z.name === "EMAIL" ? EMAIL_TYPEN : ADRESS_TYPEN;
const label = z.gruppe ? alle.find((x) => x.gruppe === z.gruppe && x.name === "X-ABLABEL")?.wert : undefined;
let typ = label ? ausBezeichnung(ent(label)) : undefined;
if (!typ) {
const t = typen(z);
const tel = z.name === "TEL";
typ = tel && t.includes("fax") ? "fax" : tel && t.some((x) => ["cell", "iphone", "mobile"].includes(x)) ? "mobil" : tel && t.includes("main") ? "zentrale"
: t.includes("work") ? "geschaeftlich" : t.includes("home") ? "privat" : "sonstige";
}
return erlaubt.includes(typ) ? typ : "sonstige";
}
const bevorzugt = (z: Zeile) => typen(z).includes("pref");
const ANREDE_WORTE: Record<string, string> = { herr: "Herr", hr: "Herr", frau: "Frau", fr: "Frau", familie: "Familie", eheleute: "Eheleute" };
export function felderAus(karte: string): KontaktFelder {
const z = zeilen(karte);
const erstes = (n: string) => z.find((x) => x.name === n);
const org = leer(teile(erstes("ORG")?.wert ?? "").filter(Boolean).join(", "));
const org = leer(teile(erstes("ORG")?.wert ?? "")[0]);
const n = teile(erstes("N")?.wert ?? "");
const ausN = leer([n[3], n[1], n[2], n[0], n[4]].filter((x) => x && x.trim()).join(" "));
const namen = leer([n[1], n[2], n[0], n[4]].filter((x) => x && x.trim()).join(" "));
const fn = leer(ent(erstes("FN")?.wert ?? ""));
const tels = z.filter(istTelefon);
const mobil = tels.find(istMobil);
const telefon = tels.find((t) => t !== mobil);
const adr = z.find((x) => x.name === "ADR");
const a = adr ? teile(adr.wert) : [];
const gruppe = /^company$/i.test(erstes("X-ABSHOWAS")?.wert.trim() ?? "") || /^org$/i.test(erstes("KIND")?.wert.trim() ?? "") || (!namen && !!org && (fn ?? org) === org);
// Namenspräfix: Anrede und Titel
const praefix = (n[3] ?? "").split(/\s+/).filter(Boolean);
const anredeWort = praefix[0] ? ANREDE_WORTE[praefix[0].replace(/\.$/, "").toLowerCase()] : undefined;
const titel = leer((anredeWort ? praefix.slice(1) : praefix).join(" "));
const listen = listenBereinigt({
telefone: z.filter((x) => x.name === "TEL").map((x) => ({ typ: typVon(x, z), wert: ent(x.wert).replace(/^tel:/i, ""), haupt: bevorzugt(x) })),
emails: z.filter((x) => x.name === "EMAIL").map((x) => ({ typ: typVon(x, z), wert: ent(x.wert).replace(/^mailto:/i, ""), haupt: bevorzugt(x) })),
adressen: z.filter((x) => x.name === "ADR").map((x) => {
const a = teile(x.wert);
const [strasse = "", ...rest] = (a[2] ?? "").split("\n");
return {
typ: typVon(x, z), postfach: a[0] ?? "", strasse, zusatz: [...rest, a[1] ?? ""].map((s) => s.trim()).filter(Boolean).join(", "),
ort: a[3] ?? "", region: a[4] ?? "", plz: a[5] ?? "", land: a[6] ?? "", haupt: bevorzugt(x),
};
}),
});
return {
name: fn ?? ausN ?? org ?? "(ohne Namen)",
name: (gruppe ? org ?? fn : namen ?? fn ?? org) ?? "(ohne Namen)",
anrede: gruppe ? null : anredeWort ?? null,
titel: gruppe ? null : titel,
firma: org,
telefon: leer(telefon?.wert),
mobil: leer(mobil?.wert),
email: leer(erstes("EMAIL")?.wert),
strasse: leer([a[1], a[2]].filter((x) => x && x.trim()).join(" ")),
plz: leer(a[5]),
ort: leer(a[3]),
funktion: gruppe ? undefined : leer(ent(erstes("TITLE")?.wert ?? "")),
gruppe,
...listen,
notiz: leer(ent(erstes("NOTE")?.wert ?? "")),
};
}
/** Gleiche Inhalte erkennen, ohne auf Schreibweise von Leerzeichen zu achten */
const s = (x: unknown) => (x ?? "").toString().replace(/\s+/g, " ").trim();
const listenText = (f: Partial<KontaktFelder>) => {
const l = listenBereinigt({ telefone: f.telefone ?? [], emails: f.emails ?? [], adressen: f.adressen ?? [] });
return {
telefone: l.telefone.map((x) => [x.typ, s(x.wert), !!x.haupt]),
emails: l.emails.map((x) => [x.typ, s(x.wert).toLowerCase(), !!x.haupt]),
adressen: l.adressen.map((a) => [a.typ, s(a.strasse), s(a.zusatz), s(a.plz), s(a.ort), s(a.region), s(a.land), s(a.postfach), !!a.haupt]),
};
};
/** Gleiche Inhalte erkennen, ohne auf Schreibweise von Leerzeichen zu achten. „v2“: seit 0.47 mit Listen. */
export function fingerabdruck(f: Partial<KontaktFelder>): string {
return JSON.stringify(FELDER.map((k) => (f[k] ?? "").toString().replace(/\s+/g, " ").trim()));
const l = listenText(f);
return "v2" + JSON.stringify([s(f.name), f.gruppe ? "" : s(f.anrede), f.gruppe ? "" : s(f.titel), s(f.firma), f.funktion === undefined || f.gruppe ? "–" : s(f.funktion),
!!f.gruppe, s(f.notiz), l.telefone, l.emails, l.adressen]);
}
/** Telefonnummern vergleichbar machen: nur Ziffern, +49/0049 wie 0 */
@@ -96,37 +174,97 @@ export function nummer(t: string | null | undefined): string {
return d.replace(/^0049/, "0");
}
const adrSchluessel = (a: Anschrift) => [a.strasse, a.plz, a.ort, a.postfach].map((x) => s(x).toLowerCase()).join("|");
function dazu<T>(alt: T[], neu: T[], schluessel: (x: T) => string): T[] {
const da = new Set(alt.map(schluessel));
return [...alt, ...neu.filter((x) => !da.has(schluessel(x))).map((x) => ({ ...x, haupt: false }))];
}
/** Programm um die Karte ergänzen: Leeres füllen, fehlende Nummern, E-Mails und Adressen anhängen; was im Programm steht, bleibt */
export function ergaenzt(k: KontaktFelder, f: KontaktFelder): KontaktFelder {
return {
...k,
anrede: k.anrede ?? f.anrede, titel: k.titel ?? f.titel, firma: k.firma ?? f.firma, notiz: k.notiz ?? f.notiz,
funktion: k.funktion === undefined ? undefined : k.funktion ?? f.funktion ?? null,
...listenBereinigt({
telefone: dazu(k.telefone, f.telefone, (x) => nummer(x.wert)),
emails: dazu(k.emails, f.emails, (x) => x.wert.trim().toLowerCase()),
adressen: dazu(k.adressen, f.adressen, adrSchluessel),
}),
};
}
const TEL_PARAMS: Record<string, string> = { mobil: "type=CELL;type=VOICE", privat: "type=HOME;type=VOICE", geschaeftlich: "type=WORK;type=VOICE", zentrale: "type=MAIN", fax: "type=WORK;type=FAX" };
const EMAIL_PARAMS: Record<string, string> = { privat: "type=INTERNET;type=HOME", geschaeftlich: "type=INTERNET;type=WORK" };
const ADR_PARAMS: Record<string, string> = { privat: "type=HOME", geschaeftlich: "type=WORK" };
/** Typen ohne eigenes vCard-Kennwort bekommen wie bei Apple eine Bezeichnung */
const BEZEICHNUNG: Record<string, Record<string, string>> = {
TEL: { sonstige: "_$!<Other>!$_" },
EMAIL: { rechnung: "Rechnungen", sonstige: "_$!<Other>!$_" },
ADR: { rechnung: "Rechnungsadresse", sonstige: "_$!<Other>!$_" },
};
/**
* Karte mit den Feldern aus dem Programm. Eine vorhandene Karte wird nur in den gepflegten Zeilen geändert;
* ohne Karte entsteht eine neue (vCard 3.0, wie Apple sie anlegt).
*/
export function karteMit(f: KontaktFelder, uid: string, alt: string | null, jetzt = new Date()): string {
const z = alt ? zeilen(alt).filter((x) => !["BEGIN", "END"].includes(x.name)) : [{ gruppe: "", name: "VERSION", params: "", wert: "3.0" }];
const setze = (finde: (x: Zeile) => boolean, name: string, params: string, wert: string | null) => {
const i = z.findIndex(finde);
if (!wert) { if (i >= 0) z.splice(i, 1); return; }
let z: Zeile[] = alt ? zeilen(alt).filter((x) => !["BEGIN", "END"].includes(x.name)) : [{ gruppe: "", name: "VERSION", roh: "VERSION", params: "", wert: "3.0" }];
const vorher = alt ? felderAus(alt) : null;
const setze = (name: string, params: string, wert: string | null) => {
const i = z.findIndex((x) => x.name === name.toUpperCase());
if (!wert) { z = z.filter((x) => x.name !== name.toUpperCase()); return; }
if (i >= 0) z[i] = { ...z[i]!, wert };
else z.push({ gruppe: "", name, params, wert });
else z.push({ gruppe: "", name: name.toUpperCase(), roh: name, params, wert });
};
const firmaKontakt = !!f.firma && f.name === f.firma;
const altFn = ent(z.find((x) => x.name === "FN")?.wert ?? "");
setze((x) => x.name === "FN", "FN", "", esc(f.name));
// N: Nachname;Vorname – bei Firmen bleibt N leer wie bei Apple
const worte = f.name.trim().split(/\s+/);
const nWert = firmaKontakt ? ";;;;" : worte.length > 1 ? `${esc(worte.at(-1)!)};${esc(worte.slice(0, -1).join(" "))};;;` : `${esc(f.name)};;;;`;
// N nur neu setzen, wenn sich der Name geändert hat; sonst bleibt Apples Aufteilung (z. B. Titel, Namenszusatz)
if (!z.some((x) => x.name === "N") || altFn !== f.name) setze((x) => x.name === "N", "N", "", nWert);
setze((x) => x.name === "ORG", "ORG", "", f.firma ? `${esc(f.firma)};` : null);
setze((x) => istTelefon(x) && istMobil(x), "TEL", "type=CELL;type=VOICE", f.mobil);
setze((x) => istTelefon(x) && !istMobil(x), "TEL", "type=WORK;type=VOICE", f.telefon);
setze((x) => x.name === "EMAIL", "EMAIL", "type=INTERNET;type=WORK", f.email);
const adr = f.strasse || f.plz || f.ort ? `;;${esc(f.strasse ?? "")};${esc(f.ort ?? "")};;${esc(f.plz ?? "")};` : null;
const altAdr = z.find((x) => x.name === "ADR");
// Land und Region einer vorhandenen Adresse bleiben stehen
const adrWert = adr && altAdr ? (() => { const t = altAdr.wert.split(/(?<!\\);/); return [t[0] ?? "", t[1] ?? "", esc(f.strasse ?? ""), esc(f.ort ?? ""), t[4] ?? "", esc(f.plz ?? ""), t[6] ?? ""].join(";"); })() : adr;
setze((x) => x.name === "ADR", "ADR", "type=WORK", adrWert);
setze((x) => x.name === "UID", "UID", "", uid);
setze((x) => x.name === "REV", "REV", "", jetzt.toISOString().replace(/\.\d+Z$/, "Z"));
const zeile = (x: Zeile) => `${x.gruppe ? `${x.gruppe}.` : ""}${x.name}${x.params ? `;${x.params}` : ""}:${x.wert}`;
setze("FN", "", esc(f.name));
// N: Nachname;Vorname;weitere;Präfix;Suffix – bei Firmen leer wie bei Apple. Apples Aufteilung bleibt, solange der Name gleich ist.
const praefix = esc([f.gruppe ? "" : f.anrede, f.gruppe ? "" : f.titel].filter((x) => x && x.trim()).join(" "));
const altN = z.find((x) => x.name === "N");
if (f.gruppe) setze("N", "", ";;;;");
else if (!altN || !vorher || vorher.gruppe || vorher.name !== f.name) {
const worte = f.name.trim().split(/\s+/);
setze("N", "", worte.length > 1 ? `${esc(worte.at(-1)!)};${esc(worte.slice(0, -1).join(" "))};;${praefix};` : `${esc(f.name)};;;${praefix};`);
} else if ((vorher.anrede ?? null) !== (f.anrede ?? null) || (vorher.titel ?? null) !== (f.titel ?? null)) {
const t = altN.wert.split(/(?<!\\);/);
while (t.length < 5) t.push("");
t[3] = praefix;
setze("N", "", t.join(";"));
}
// ORG: Abteilung einer vorhandenen Karte bleibt, solange die Firma gleich ist
if (!f.firma) setze("ORG", "", null);
else if (vorher?.firma !== f.firma) setze("ORG", "", `${esc(f.firma)};`);
if (f.gruppe) setze("TITLE", "", null);
else if (f.funktion !== undefined) setze("TITLE", "", f.funktion ? esc(f.funktion) : null);
if (f.gruppe) setze("X-ABShowAs", "", "COMPANY");
else setze("X-ABShowAs", "", null);
// Nummern, E-Mails, Adressen: nur neu schreiben, was sich geändert hat
const neu = listenText(f), alteListen = vorher ? listenText(vorher) : null;
const l = listenBereinigt(f);
let item = Math.max(0, ...z.map((x) => /^item(\d+)$/i.exec(x.gruppe)?.[1]).filter(Boolean).map(Number));
const schreibe = (name: string, typ: string, params: Record<string, string>, haupt: boolean | undefined, wert: string) => {
const pref = haupt ? ";type=pref" : "";
const label = BEZEICHNUNG[name]?.[typ];
if (params[typ]) { z.push({ gruppe: "", name, roh: name, params: params[typ] + pref, wert }); return; }
const g = `item${++item}`;
z.push({ gruppe: g, name, roh: name, params: (name === "EMAIL" ? "type=INTERNET" : "") + pref, wert });
if (label) z.push({ gruppe: g, name: "X-ABLABEL", roh: "X-ABLabel", params: "", wert: esc(label) });
};
const ersetze = (name: string, gleich: boolean, neuSchreiben: () => void) => {
if (gleich) return;
const gruppen = new Set(z.filter((x) => x.name === name && x.gruppe).map((x) => x.gruppe));
z = z.filter((x) => x.name !== name && !gruppen.has(x.gruppe));
neuSchreiben();
};
const gleich = (k: "telefone" | "emails" | "adressen") => !!alteListen && JSON.stringify(alteListen[k]) === JSON.stringify(neu[k]);
ersetze("TEL", gleich("telefone"), () => l.telefone.forEach((x) => schreibe("TEL", x.typ, TEL_PARAMS, x.haupt, esc(x.wert))));
ersetze("EMAIL", gleich("emails"), () => l.emails.forEach((x) => schreibe("EMAIL", x.typ, EMAIL_PARAMS, x.haupt, esc(x.wert))));
ersetze("ADR", gleich("adressen"), () => l.adressen.forEach((a) => schreibe("ADR", a.typ, ADR_PARAMS, a.haupt,
[a.postfach ?? "", "", [a.strasse, a.zusatz].filter((x) => x && x.trim()).join("\n"), a.ort, a.region ?? "", a.plz, a.land ?? ""].map((x) => esc(x ?? "")).join(";"))));
setze("NOTE", "", f.notiz ? esc(f.notiz) : null);
setze("UID", "", uid);
setze("REV", "", jetzt.toISOString().replace(/\.\d+Z$/, "Z"));
const zeile = (x: Zeile) => `${x.gruppe ? `${x.gruppe}.` : ""}${x.roh}${x.params ? `;${x.params}` : ""}:${x.wert}`;
return ["BEGIN:VCARD", ...z.map(zeile), "END:VCARD"].join("\r\n") + "\r\n";
}