diff --git a/TODO.md b/TODO.md index a60241d5..bc1bb4fd 100644 --- a/TODO.md +++ b/TODO.md @@ -211,11 +211,21 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC. am Masterlayout gespeichert, `MasterLayout.guides` — kein neues Modellfeld, gilt für alle Blätter des Masters, ohne Master nicht setzbar), **Bild-Zuschnitt durch Ziehen** (Knopf „Zuschneiden“ oder Doppelklick, Griffe am Ausschnitt, Original bleibt stehen, ein Undo-Schritt je Zug). Tests: vitest `sheetSnap`, `sheetGuides`, e2e `competition`. Offen: Fang für Texte (es gibt keine freien Text-Elemente auf dem Blatt) und - Legenden-Verschieben (Legende hat keinen Zug am Blatt); Hilfslinien je Blatt statt je Master; Bild in DXF/IFC-Exporten nicht; frei eingegebene Texte - (Layer-/Ebenen-, Raum-, Geschoss-, Blockbezeichnungen, Textobjekte, Blattnamen im PDF) prüft niemand — der Satz „Anonym“ gilt für - Projekt-Stammdaten, nicht für Freitext; Eigenschaftssatz-Namen `Dossier_Qto_…` im IFC (Programmkonvention) bleiben; Download-Namen im Browser ohne Tauri-Dialog; grosse Bilder: jede + Legenden-Verschieben (Legende hat keinen Zug am Blatt); Hilfslinien je Blatt statt je Master; Bild in DXF/IFC-Exporten nicht; Eigenschaftssatz-Namen `Dossier_Qto_…` im IFC (Programmkonvention) bleiben; Download-Namen im Browser ohne Tauri-Dialog; grosse Bilder: jede Blatt-Änderung (Viewport verschieben …) ersetzt das ganze Layout samt Data-URL im Op und im Verlauf (wie `ContextImage`) — bei vielen MB Bilder in eine eigene Sammlung auslagern; nicht in der Tauri-App/auf dem Mac geprüft. · M + **Anonymitäts-Prüfung des Freitexts (14.11.)**: vor PDF-/SVG-/DXF-Export, Direkt-Export (CSV/IFC/OBJ/STL/GLB) und Publikationssatz einer + anonymen Abgabe sucht der Kern (`competition.rs`, Bindung `anonymity_findings`, TS-Fassade `export/competitionCheck.ts`, Tor + `state/anonymityGate.ts`) in jeder Zeichenkette des Projekts (Raum-, Geschoss-, Ebenen-/Klassen-, Gruppen-, Block-, Layout-/Blattnamen, Textobjekte, + Bild-Dateinamen, Bauteil-/Schraffurnamen …; ausser Ids, Data-URLs und den Quellfeldern selbst) nach Projektname, -nummer, Titelblock-Büro/-Bearbeiter, + Adresse des Standort-Bezugs, Projekt-Dateiname und der neuen Liste `competition.identifiers` („Weitere Angaben“ in der Mappe: Büro, Namen, E-Mail, + Telefon), dazu E-Mail-Adressen und Telefonnummern an sich. Ganze Wörter, Gross-/Kleinschreibung, Umlaute (ä = ae = a) und Trenner egal; Phrase ab 3, + Einzelwort ab 5 Zeichen, allgemeine Wörter („Haus“, „Wohnen“ …) und blosse Zahlen zählen nicht. Dialog `ui/AnonymityDialog.tsx` listet Bereich, + Fundstelle, Text, Begriff; „Trotzdem exportieren“ / „Abbrechen“ (Overlay, kein `window.confirm`). Kopfdaten waren schon leer (PDF-Info nur Kennwort, + Producer/Datum neutralisiert — auch „Dossier“ bleibt weg, weil Programm + Version + Datum die Herkunft eingrenzen; IFC-Kopf/IfcOwnerHistory, DXF-Kopf, STEP): + keine Lücke gefunden. Tests: Rust `competition` (Treffer je Textort, Fehlalarme, Umlaute), vitest `competitionCheck`, e2e `competition`. Offen: Berichte-PDF + (Flächen, Raumbuch …) und Bild-/Rendering-Exporte laufen nicht durch das Tor; Prüfung läuft nur im Dialog-Weg (CLI/KI-Werkzeuge nicht); der + Dateiname der Ausgabe wird nur beim Direkt-Export geprüft; nicht in der Tauri-App/auf dem Mac geprüft. - [61] Raumprogramm gegen Modell und Flächennachweis SIA 416 als Tabelle/Layout-Element ([70]); Kennzahlen (GF, GV, HNF/GF, Fassadenanteil). - 3D-Bilder für die Abgabe: hochaufgelöster PNG-Export (Perspektive, Axonometrie, Schatten), Sonnenstand; [205] Pausfolie. - [199]/[204] Plan- und App-Review-Reste im Darstellungsbereich 1:500/1:200 schliessen. diff --git a/e2e/competition.spec.ts b/e2e/competition.spec.ts index 5330ed8e..518c0037 100644 --- a/e2e/competition.spec.ts +++ b/e2e/competition.spec.ts @@ -163,3 +163,35 @@ test("Plakat A1 quer aus Vorlage, Bild einsetzen, anonym als WBW-Abgabe exportie await page.screenshot({ path: `${process.env.DOSSIER_SHOTS}/plakat-a1-quer-blatt.png` }); } }); + +// Anonymitäts-Prüfung des Freitexts: eine Angabe aus der Liste „Weitere Angaben" steht im Projekt (hier ein Schraffur-/ +// Bauteilname) → vor dem Export erscheint der Dialog mit Fundstelle; Abbrechen exportiert nichts, „Trotzdem exportieren" +// läuft weiter. Ohne Treffer kein Dialog. +test("Anonymitäts-Prüfung: Dialog bei Treffer im Freitext, Abbrechen / Trotzdem exportieren", async ({ page }) => { + await startNewProject(page); + await openSample(page); + await openTab(page, "Mappe"); + await page.locator("[data-testid=competition-anonymous]").check(); + await page.locator("[data-testid=competition-keyword]").fill("FALKE 7"); + await page.locator("[data-testid=publish-add-wbw]").click(); + await expect(page.locator("[data-publish-set]")).toHaveCount(1); + + // Ohne Angaben aus der Liste: kein Treffer, kein Dialog. + await page.locator("[data-publish-set] [data-publish-run]").click(); + await expect(page.locator("[data-testid=anonymity-dialog]")).toHaveCount(0); + + // „Wärmedämmung" kommt im Beispielprojekt als Name vor: Dialog listet Fundstelle und Begriff. + await page.locator("[data-testid=competition-identifiers]").fill("Wärmedämmung"); + await page.locator("[data-publish-set] [data-publish-run]").click(); + const dialog = page.locator("[data-testid=anonymity-dialog]"); + await expect(dialog).toBeVisible(); + await expect(dialog.locator("[data-testid=anonymity-findings] li").first()).toContainText("Wärmedämmung"); + await page.locator("[data-testid=anonymity-cancel]").click(); + await expect(dialog).toHaveCount(0); + + // „Trotzdem exportieren": der Export läuft weiter (Dialog weg). + await page.locator("[data-publish-set] [data-publish-run]").click(); + await expect(dialog).toBeVisible(); + await page.locator("[data-testid=anonymity-proceed]").click(); + await expect(dialog).toHaveCount(0); +}); diff --git a/src-tauri/core/src/competition.rs b/src-tauri/core/src/competition.rs index 8bcb44f6..7f804136 100644 --- a/src-tauri/core/src/competition.rs +++ b/src-tauri/core/src/competition.rs @@ -15,6 +15,319 @@ pub fn anonymous_keyword(p: &Project) -> Option { p.competition.as_ref().filter(|c| c.anonymous).map(|c| c.keyword.trim().to_string()) } +// --------------------------------------------------------------------------------------------------------- +// Anonymitäts-Prüfung des Freitexts (vor dem Export einer anonymen Abgabe) +// --------------------------------------------------------------------------------------------------------- +// +// Die Ausgaben neutralisieren die Stammdaten selbst (Plankopf, PDF-Info, IFC-/DXF-/STEP-Kopf, Dateinamen). Frei +// eingegebene Texte kennt keiner dieser Wege: ein Raum „Büro Muster", eine Ebene „Entwurf Meier", ein Textobjekt +// mit Telefonnummer. Die Prüfung läuft über das Projekt-JSON (jede Zeichenkette ausser Ids, Data-URLs und den +// Quellfeldern selbst) und sucht identifizierende Begriffe: Projektname, -nummer, Titelblock-Büro/-Bearbeiter, +// Adresse des Standort-Bezugs, die Angaben unter `competition.identifiers`, den Projekt-Dateinamen, dazu +// E-Mail-Adressen und Telefonnummern an sich. Treffer: ganze Wörter, Gross-/Kleinschreibung, Umlaute (ä = ae = a) +// und Trennzeichen egal. +// +// Producer in den PDF-Metadaten: bleibt leer, auch „Dossier" kommt nicht hinein — Programm und Version zusammen +// mit dem Datum grenzen die Herkunft ein (`export/pdfInfo.ts` neutralisiert Producer und Datum längengleich). + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// Ein zusätzlicher Text von aussen (z. B. Dateiname der Ausgabe), den der Kern nicht im Projekt findet. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(default)] +pub struct ExtraText { + pub area: String, + pub place: String, + pub text: String, +} + +/// Eingabe der Prüfung von der TS-Seite: Projekt-Dateiname (Begriff) und weitere zu prüfende Texte. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(default)] +pub struct CheckInput { + /// Dateiname des Projekts (mit oder ohne Endung): als Begriff gesucht. + #[serde(rename = "fileName")] + pub file_name: String, + /// Weitere Texte (Dateiname der Ausgabe …), geprüft wie Projekttexte. + pub texts: Vec, +} + +/// Ein Treffer. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Finding { + /// Oberste Projekt-Liste (`rooms`, `drawingLevels`, `layouts` …) bzw. Bereich des Zusatztexts. + pub area: String, + /// Fundstelle: Elementname und Feld, z. B. `Küche.name`. + pub place: String, + /// Der Text (gekürzt auf 80 Zeichen). + pub text: String, + /// Der gefundene Begriff bzw. die gefundene E-Mail/Telefonnummer. + pub term: String, + /// Herkunft des Begriffs: `name`, `number`, `titleBlock`, `address`, `identifier`, `file`, `email`, `phone`. + pub kind: String, +} + +/// Wörter, die als Einzelbegriff nie zählen (zu allgemein): Namensteile in Projekt- und Büronamen. +const GENERIC: &[&str] = &[ + "projekt", "neubau", "umbau", "wohnhaus", "gebäude", "architekten", "architektur", "architekt", "büro", "bureau", + "wettbewerb", "haus", "strasse", "wohnen", "schule", "zentrum", "areal", "überbauung", "siedlung", "erweiterung", + "sanierung", "entwurf", "vorprojekt", "studie", "partner", "pläne", +]; + +/// Mindestlänge: ganze Angabe (Phrase) und Einzelwort daraus. +const MIN_PHRASE: usize = 3; +const MIN_WORD: usize = 5; + +/// Vergleichsform: klein, Umlaute/Akzente zu Grundbuchstaben (ä = ae = a), Nicht-Buchstaben/Ziffern → ein Leerzeichen. +fn norm(s: &str) -> String { + let mut t = String::with_capacity(s.len()); + for c in s.chars().flat_map(|c| c.to_lowercase()) { + match c { + 'ä' | 'à' | 'á' | 'â' | 'ã' | 'å' => t.push('a'), + 'ö' | 'ò' | 'ó' | 'ô' | 'õ' => t.push('o'), + 'ü' | 'ù' | 'ú' | 'û' => t.push('u'), + 'é' | 'è' | 'ê' | 'ë' => t.push('e'), + 'ì' | 'í' | 'î' | 'ï' => t.push('i'), + 'ç' => t.push('c'), + 'ß' => t.push_str("ss"), + c if c.is_alphanumeric() => t.push(c), + _ => t.push(' '), + } + } + let t = t.replace("ae", "a").replace("oe", "o").replace("ue", "u"); + t.split_whitespace().collect::>().join(" ") +} + +fn is_generic(word_norm: &str) -> bool { + GENERIC.iter().any(|g| norm(g) == word_norm) +} + +struct Term { + raw: String, + norm: String, + kind: &'static str, +} + +fn split_list(s: &str) -> impl Iterator { + s.split([',', ';', '\n']).map(str::trim).filter(|x| !x.is_empty()) +} + +/// Nimmt die Angabe als Phrase auf; mit `words` zusätzlich ihre Einzelwörter (lang genug, nicht allgemein, keine Zahl). +fn push_term(out: &mut Vec, raw: &str, kind: &'static str, words: bool) { + let raw = raw.trim(); + let n = norm(raw); + if n.chars().count() < MIN_PHRASE { + return; + } + let digits_only = n.chars().all(|c| c.is_ascii_digit() || c == ' '); + if !digits_only || kind == "number" { + out.push(Term { raw: raw.to_string(), norm: n.clone(), kind }); + } + if words { + for w in n.split(' ') { + if w.chars().count() >= MIN_WORD && !w.chars().all(|c| c.is_ascii_digit()) && !is_generic(w) && w != n { + out.push(Term { raw: w.to_string(), norm: w.to_string(), kind }); + } + } + } +} + +fn str_at<'a>(v: &'a Value, path: &[&str]) -> Option<&'a str> { + let mut cur = v; + for k in path { + cur = cur.get(*k)?; + } + cur.as_str() +} + +/// Begriffe aus den Stammdaten des Projekts und der Eingabe. +fn terms_of(root: &Value, input: &CheckInput) -> Vec { + let mut out = Vec::new(); + if let Some(n) = str_at(root, &["name"]) { + push_term(&mut out, n, "name", true); + } + if let Some(n) = str_at(root, &["projectNumber"]) { + push_term(&mut out, n, "number", false); + } + for m in root.get("masterLayouts").and_then(Value::as_array).into_iter().flatten() { + for f in ["projectName", "author"] { + if let Some(n) = str_at(m, &["titleBlock", f]) { + push_term(&mut out, n, "titleBlock", true); + } + } + } + if let Some(label) = str_at(root, &["geoAnchor", "label"]) { + for part in label.split([',', ';']) { + push_term(&mut out, part, "address", false); + } + } + if let Some(ids) = str_at(root, &["competition", "identifiers"]) { + for e in split_list(ids) { + push_term(&mut out, e, "identifier", true); + } + } + let base = input.file_name.rsplit(['/', '\\']).next().unwrap_or(""); + let stem = base.rsplit_once('.').map(|(a, _)| a).unwrap_or(base); + if norm(stem).chars().count() >= 4 { + push_term(&mut out, stem, "file", false); + } + // Das Kennwort selbst ist erlaubt. + let keyword = norm(str_at(root, &["competition", "keyword"]).unwrap_or("")); + out.retain(|t| keyword.is_empty() || t.norm != keyword); + let mut seen = std::collections::HashSet::new(); + out.retain(|t| seen.insert(t.norm.clone())); + out +} + +/// Kommt der Begriff (normiert) als ganze Wörter im Text (normiert) vor? +fn contains_words(hay_norm: &str, needle_norm: &str) -> bool { + !needle_norm.is_empty() && format!(" {hay_norm} ").contains(&format!(" {needle_norm} ")) +} + +/// E-Mail-Adresse im Text (`x@y.z`)? +fn find_email(s: &str) -> Option { + for tok in s.split(|c: char| c.is_whitespace() || matches!(c, '<' | '>' | '(' | ')' | ',' | ';' | '"' | '\'')) { + let tok = tok.trim_matches(|c: char| c == '.' || c == ':'); + if let Some((l, d)) = tok.split_once('@') { + let dom_ok = d.contains('.') && !d.starts_with('.') && !d.ends_with('.') && d.chars().all(|c| c.is_alphanumeric() || c == '.' || c == '-'); + if !l.is_empty() && dom_ok { + return Some(tok.to_string()); + } + } + } + None +} + +/// Telefonnummer im Text: beginnt mit `+` oder `0`, 9 bis 15 Ziffern, nur Ziffern und übliche Trenner, und +/// hat Trenner oder `+` (eine blosse Ziffernfolge ist eher eine Nummer als ein Telefon). +fn find_phone(s: &str) -> Option { + let cs: Vec = s.chars().collect(); + let mut i = 0; + while i < cs.len() { + let next = cs.get(i + 1).copied().unwrap_or(' '); + let starts = (i == 0 || !cs[i - 1].is_alphanumeric()) && ((cs[i] == '0' && next.is_ascii_digit()) || (cs[i] == '+' && (next.is_ascii_digit() || next == ' ' || next == '('))); + if !starts { + i += 1; + continue; + } + let mut j = i; + let mut digits = 0; + while j < cs.len() && (cs[j].is_ascii_digit() || matches!(cs[j], ' ' | '-' | '/' | '.' | '(' | ')' | '+')) { + if cs[j].is_ascii_digit() { + digits += 1; + } + j += 1; + } + let run: String = cs[i..j].iter().collect::().trim_end_matches([' ', '-', '/', '.']).to_string(); + let has_sep = run.chars().any(|c| matches!(c, ' ' | '-' | '/' | '(' | '+')); + if (9..=15).contains(&digits) && has_sep { + return Some(run); + } + i = j.max(i + 1); + } + None +} + +fn shorten(s: &str) -> String { + let one: String = s.split_whitespace().collect::>().join(" "); + if one.chars().count() > 80 { + let mut c: String = one.chars().take(79).collect(); + c.push('…'); + c + } else { + one + } +} + +fn skip_key(k: &str) -> bool { + k == "id" || k.ends_with("Id") || k.ends_with("Ids") || matches!(k, "src" | "dataUrl" | "formatVersion") +} + +/// Kennzeichnung eines Array-Elements: sein Name, sonst der Index. +fn element_label(v: &Value, i: usize) -> String { + match v.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()) { + Some(n) => shorten(n), + None => i.to_string(), + } +} + +struct Walk<'a> { + terms: &'a [Term], + out: Vec, +} + +impl Walk<'_> { + fn push(&mut self, area: &str, place: &str, text: &str, term: &str, kind: &str) { + self.out.push(Finding { area: area.into(), place: place.into(), text: shorten(text), term: term.into(), kind: kind.into() }); + } + + fn check(&mut self, area: &str, place: &str, text: &str) { + if text.trim().is_empty() || text.starts_with("data:") { + return; + } + let hay = norm(text); + let hits: Vec<&Term> = self.terms.iter().filter(|t| contains_words(&hay, &t.norm)).collect(); + // Ein Treffer, der in einem längeren steckt (Wort der Phrase), zählt nicht extra. + for t in &hits { + if !hits.iter().any(|o| o.norm != t.norm && contains_words(&o.norm, &t.norm)) { + self.push(area, place, text, &t.raw, t.kind); + } + } + if let Some(e) = find_email(text) { + self.push(area, place, text, &e, "email"); + } + if let Some(p) = find_phone(text) { + self.push(area, place, text, &p, "phone"); + } + } + + fn walk(&mut self, area: &str, path: &str, v: &Value) { + match v { + Value::String(s) => self.check(area, path, s), + Value::Array(a) => { + for (i, e) in a.iter().enumerate() { + let label = element_label(e, i); + let p = if path.is_empty() { label } else { format!("{path}.{label}") }; + self.walk(area, &p, e); + } + } + Value::Object(m) => { + for (k, e) in m { + if skip_key(k) { + continue; + } + let p = if path.is_empty() { k.clone() } else { format!("{path}.{k}") }; + self.walk(area, &p, e); + } + } + _ => {} + } + } +} + +/// Prüft den Freitext des Projekts (JSON-Wurzel) und die Zusatztexte; leer = sauber. Nur bei anonymer Abgabe +/// sinnvoll — die Aufrufer entscheiden das (`anonymous_keyword`). +pub fn anonymity_findings(root: &Value, input: &CheckInput) -> Vec { + let terms = terms_of(root, input); + let mut w = Walk { terms: &terms, out: Vec::new() }; + if let Value::Object(m) = root { + for (k, v) in m { + // Quellen der Begriffe und Programm-Interna: nicht Freitext der Ausgabe. + if skip_key(k) || matches!(k.as_str(), "name" | "projectNumber" | "competition" | "geoAnchor" | "uiState" | "publishLog") { + continue; + } + w.walk(k, "", v); + } + } + // Titelblock-Quellfelder sind Stammdaten (der Plankopf löst sie anonym auf): nicht melden. + w.out.retain(|f| !(f.area == "masterLayouts" && (f.place.ends_with("titleBlock.projectName") || f.place.ends_with("titleBlock.author")))); + for x in &input.texts { + w.check(&x.area, &x.place, &x.text); + } + w.out +} + #[cfg(test)] mod tests { use super::*; @@ -29,4 +342,99 @@ mod tests { p.competition = Some(CompetitionSettings { anonymous: true, keyword: " FALKE 7 ".into(), ..Default::default() }); assert_eq!(anonymous_keyword(&p).as_deref(), Some("FALKE 7")); } + + fn root() -> Value { + serde_json::json!({ + "name": "Haus Meierhofer", + "projectNumber": "2026-017", + "competition": { "anonymous": true, "keyword": "FALKE 7", "identifiers": "Atelier Brunner AG; Anna Zürcher\ninfo@brunner-arch.ch" }, + "geoAnchor": { "label": "Bahnhofstrasse 12, 8001 Zürich" }, + "masterLayouts": [{ "id": "m", "name": "Plakat", "titleBlock": { "projectName": "Meierhofer Haus", "author": "B. Brunner", "sheetName": "Grundriss" } }], + "rooms": [{ "id": "r1", "name": "Küche" }, { "id": "r2", "name": "Büro Meierhofer", "note": "Tel +41 44 123 45 67" }], + "drawingLevels": [{ "id": "l1", "name": "Erdgeschoss" }, { "id": "l2", "name": "EG MEIERHOFER" }], + "layers": [{ "id": "k1", "name": "Wände", "layers": [{ "id": "k2", "name": "Anna Zuercher" }] }], + "drawings2d": [{ "id": "d1", "kind": "text", "text": "Entwurf: Atelier Brunner AG", "layerId": "Meierhofer" }], + "layouts": [{ "id": "y1", "name": "Plan 2026/017 Süd", "images": [{ "id": "i1", "src": "data:image/png;base64,Meierhofer", "name": "logo-brunner.png" }] }], + "blockDefs": [{ "id": "b1", "name": "Stuhl" }], + }) + } + fn find(r: &Value, input: &CheckInput) -> Vec { + anonymity_findings(r, input) + } + fn has(f: &[Finding], area: &str, kind: &str, contains: &str) -> bool { + f.iter().any(|x| x.area == area && x.kind == kind && x.text.contains(contains) || x.area == area && x.kind == kind && x.place.contains(contains)) + } + + #[test] + fn treffer_in_jedem_textort() { + let f = find(&root(), &CheckInput::default()); + // Raumname (Wort aus dem Projektnamen), Geschoss (Gross-/Kleinschreibung), Kategorie (Umlaut-Variante) + assert!(has(&f, "rooms", "name", "Büro Meierhofer"), "{f:?}"); + assert!(has(&f, "drawingLevels", "name", "EG MEIERHOFER"), "{f:?}"); + assert!(has(&f, "layers", "identifier", "Anna Zuercher"), "{f:?}"); + // Textobjekt: Angabe aus der Liste, trotz doppeltem Leerzeichen + assert!(has(&f, "drawings2d", "identifier", "Atelier Brunner AG") || has(&f, "drawings2d", "identifier", "Atelier Brunner AG"), "{f:?}"); + // Blattname mit Projektnummer, Bild-Dateiname mit Büro-Wort + assert!(has(&f, "layouts", "number", "Plan 2026/017 Süd"), "{f:?}"); + assert!(has(&f, "layouts", "titleBlock", "logo-brunner.png"), "{f:?}"); + // Telefon im Raum + assert!(f.iter().any(|x| x.kind == "phone" && x.area == "rooms"), "{f:?}"); + } + + #[test] + fn stammdaten_und_ids_selbst_sind_keine_treffer() { + let f = find(&root(), &CheckInput::default()); + // Projektname, Titelblock-Quellfelder, Adresse, competition und Data-URL/Ids nie melden + assert!(f.iter().all(|x| x.area != "competition" && x.area != "geoAnchor" && x.area != "name"), "{f:?}"); + assert!(!f.iter().any(|x| x.place.contains("titleBlock.projectName") || x.place.contains("titleBlock.author")), "{f:?}"); + assert!(!f.iter().any(|x| x.text.starts_with("data:")), "{f:?}"); + assert!(!f.iter().any(|x| x.place.ends_with("layerId")), "{f:?}"); + // Das Kennwort ist erlaubt, auch im Freitext + let mut r = root(); + r["rooms"][0]["name"] = Value::from("FALKE 7 Kern"); + assert!(!find(&r, &CheckInput::default()).iter().any(|x| x.text.contains("FALKE 7"))); + } + + #[test] + fn adresse_und_email_und_dateiname() { + let mut r = root(); + r["rooms"][0]["name"] = Value::from("Treffpunkt Bahnhofstrasse 12"); + r["layers"][0]["name"] = Value::from("mail info@brunner-arch.ch bitte"); + let f = find(&r, &CheckInput { file_name: "/tmp/Wettbewerb_Seeblick_v3.obp".into(), texts: vec![ExtraText { area: "export".into(), place: "Dateiname".into(), text: "Wettbewerb Seeblick v3.pdf".into() }] }); + assert!(has(&f, "rooms", "address", "Bahnhofstrasse 12"), "{f:?}"); + assert!(f.iter().any(|x| x.kind == "email" && x.area == "layers"), "{f:?}"); + assert!(f.iter().any(|x| x.area == "export" && x.kind == "file"), "{f:?}"); + } + + #[test] + fn keine_fehlalarme_bei_kurzen_und_allgemeinen_woertern() { + let r = serde_json::json!({ + "name": "Haus Muster Wohnen", + "projectNumber": "26", + "competition": { "anonymous": true, "keyword": "K", "identifiers": "AG, Ab, Anna" }, + "rooms": [{ "name": "Wohnen" }, { "name": "Haus" }, { "name": "Wohnhaus" }, { "name": "AG Raum" }, { "name": "Annahme" }, { "name": "Anna" }], + "notes": [{ "text": "Fläche 1234567890 m2" }, { "text": "Mass 0.25 / 0.30 / 12.5" }, { "text": "a@b" }, { "text": "Preis 100.- 0 8 15" }], + }); + let f = find(&r, &CheckInput::default()); + // „Muster" (≥ 5, kein allgemeines Wort) zählt, „Haus"/„Wohnen" nicht, „AG"/„Ab"/„Anna" (zu kurz) nicht als Wort + assert!(f.iter().all(|x| x.kind != "email" && x.kind != "phone"), "{f:?}"); + assert!(!f.iter().any(|x| x.text == "Wohnen" || x.text == "Haus" || x.text == "Wohnhaus" || x.text == "Annahme"), "{f:?}"); + // ganze Wörter: „Annahme" enthält „Anna" nicht als Wort, „AG Raum" meldet die Phrase AG (≥ 3? nein, 2 Zeichen) + assert!(!f.iter().any(|x| x.text == "AG Raum"), "{f:?}"); + // Die Phrase „Anna" (4 Zeichen, ≥ 3) trifft das ganze Wort in Raum „Anna". + assert!(f.iter().any(|x| x.text == "Anna" && x.kind == "identifier"), "{f:?}"); + } + + #[test] + fn umlaute_und_trenner_tolerant() { + let r = serde_json::json!({ "name": "Müller-Schöni", "rooms": [{ "name": "Mueller Schoeni Studio" }, { "name": "MULLER/SCHONI" }] }); + let f = find(&r, &CheckInput::default()); + assert_eq!(f.iter().filter(|x| x.area == "rooms").count(), 2, "{f:?}"); + } + + #[test] + fn leeres_oder_kaputtes_projekt_ist_sauber() { + assert!(find(&Value::Null, &CheckInput::default()).is_empty()); + assert!(find(&serde_json::json!({}), &CheckInput::default()).is_empty()); + } } diff --git a/src-tauri/core/src/model/generated.rs b/src-tauri/core/src/model/generated.rs index 8e454604..2b10d7ab 100644 --- a/src-tauri/core/src/model/generated.rs +++ b/src-tauri/core/src/model/generated.rs @@ -5799,6 +5799,11 @@ pub struct CompetitionSettings { pub anonymous: bool, /// Kennwort der Abgabe (steht in Plankopf und PDF-Titel). pub keyword: String, + /// Weitere identifizierende Angaben (Büro, Personen, E-Mail, Telefon, Adresse), getrennt durch Komma, Semikolon + /// oder Zeilenumbruch: die Anonymitäts-Prüfung sucht sie im Freitext des Projekts. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub identifiers: Option, #[serde(flatten)] #[ts(skip)] pub extra: Extra, diff --git a/src-tauri/core/src/web/competition.rs b/src-tauri/core/src/web/competition.rs new file mode 100644 index 00000000..99b5b527 --- /dev/null +++ b/src-tauri/core/src/web/competition.rs @@ -0,0 +1,14 @@ +//! Bindung der Anonymitäts-Prüfung (`crate::competition`) für die TS-Fassade `anonymityFindings` +//! (`src/export/competitionCheck.ts`). Eingabe das Projekt und die Zusatzangaben als JSON, Ausgabe ein +//! JSON-Array der Treffer; kaputte Eingaben ergeben eine leere Liste, nie einen Panic. + +use serde_json::Value; +use wasm_bindgen::prelude::wasm_bindgen; + +/// Treffer identifizierender Angaben im Freitext des Projekts (JSON-Array, leer = sauber). +#[wasm_bindgen] +pub fn anonymity_findings(project_json: &str, input_json: &str) -> String { + let root = serde_json::from_str::(project_json).unwrap_or(Value::Null); + let input = serde_json::from_str::(input_json).unwrap_or_default(); + serde_json::to_string(&crate::competition::anonymity_findings(&root, &input)).unwrap_or_else(|_| "[]".into()) +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 5cfb2e9c..d2de09ae 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -39,6 +39,7 @@ mod reorder; mod text_layout; mod grips; mod grip_drag; +mod competition; mod project_refs; mod commands; mod import; diff --git a/src/core/extra.ts b/src/core/extra.ts index 2bafbbf8..efc7b963 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -47,6 +47,8 @@ export { computeSiteProof } from "../analysis/siteProof"; export type { SiteProof, ProofRow, ProofBasis } from "../analysis/siteProof"; export { exportProjectName, competitionIdentity, isAnonymous, competitionKeyword, identityLeaks, NEUTRAL_DATE, NEUTRAL_ISO } from "../export/competitionIdentity"; export type { CompetitionIdentity } from "../export/competitionIdentity"; +export { anonymityFindings } from "../export/competitionCheck"; +export type { AnonymityFinding, AnonymityKind } from "../export/competitionCheck"; export { buildAreaReport, areaReportToCsv, parseAreaReportCsv, areaReportToSvg, buildAreaReportPdf } from "../export/areaReport"; export type { AreaReport, AreaReportOptions } from "../export/areaReport"; export { sunPosition, shadowPolygons, shadowOfPrism, projectLatLon } from "../analysis/sun"; diff --git a/src/export/competitionCheck.test.ts b/src/export/competitionCheck.test.ts new file mode 100644 index 00000000..042632b9 --- /dev/null +++ b/src/export/competitionCheck.test.ts @@ -0,0 +1,47 @@ +// [208] Anonymitäts-Prüfung des Freitexts: Treffer je Textort, keine Treffer ohne Anonymität, Kopfdaten leer. +// Die Logik liegt im Kern (`competition.rs`, dort die ausführlichen Fälle); hier die TS-Fassade und die Kopfdaten. + +import "../engine/fileioWasm.setup"; +import { describe, expect, it } from "vitest"; +import { sampleProject } from "../model/sampleProject"; +import type { Project } from "../model/types"; +import { anonymityFindings } from "./competitionCheck"; +import { competitionIdentity } from "./competitionIdentity"; +import { pdfInfoFields } from "./pdfInfo"; +import { exportIfcSpf } from "./exportIfc"; + +function project(anonymous: boolean): Project { + const p = structuredClone(sampleProject) as Project; + return { + ...p, + name: "Seeblick Meierhofer", + projectNumber: "2026-017", + competition: { anonymous, keyword: "FALKE 7", identifiers: "Atelier Brunner AG, info@brunner-arch.ch" }, + rooms: [{ ...(p.rooms?.[0] ?? { id: "r1", levelId: p.drawingLevels[0].id, polygon: [] }), id: "r1", name: "Büro Brunner" }] as Project["rooms"], + layouts: [{ id: "l1", name: "Plan 2026/017", paper: "a1", orientation: "landscape", viewports: [] }], + } as Project; +} + +describe("anonymityFindings", () => { + it("findet Treffer in Räumen und Blattnamen, mit Ort und Begriff", () => { + const f = anonymityFindings(project(true), { texts: [{ area: "export", place: "fileName", text: "Seeblick Meierhofer.pdf" }] }); + expect(f.some((x) => x.area === "rooms" && x.kind === "identifier" && x.text === "Büro Brunner")).toBe(true); + expect(f.some((x) => x.area === "layouts" && x.kind === "number")).toBe(true); + expect(f.some((x) => x.area === "export" && x.kind === "name")).toBe(true); + }); + + it("meldet nichts, wenn die Abgabe nicht anonym ist", () => { + expect(anonymityFindings(project(false))).toEqual([]); + }); + + it("Kopfdaten anonym leer: PDF-Info nur Kennwort, Bearbeiter leer, IFC ohne Projektname", () => { + const p = project(true); + expect(pdfInfoFields(p, "Anna Brunner")).toEqual({ title: "FALKE 7", author: "", subject: "", keywords: "", creator: "" }); + expect(competitionIdentity(p).author("Anna Brunner")).toBe(""); + expect(competitionIdentity(p).creator()).toBe(""); + const ifc = exportIfcSpf(p); + expect(ifc.toLowerCase()).not.toContain("meierhofer"); // Stammdaten: neutralisiert + // Der Raumname „Büro Brunner" (Freitext) steht dagegen im IFC — genau das meldet die Prüfung vorher. + expect(ifc.toLowerCase()).toContain("brunner"); + }); +}); diff --git a/src/export/competitionCheck.ts b/src/export/competitionCheck.ts new file mode 100644 index 00000000..24db4de1 --- /dev/null +++ b/src/export/competitionCheck.ts @@ -0,0 +1,50 @@ +// Anonymitäts-Prüfung des Freitexts ([208]): dünne Fassade über den Kern (`src-tauri/core/src/competition.rs`). +// Vor dem Export einer anonymen Abgabe sucht sie identifizierende Angaben (Projektname, -nummer, Büro/Bearbeiter +// des Titelblocks, Adresse, Angaben unter `competition.identifiers`, Dateiname, E-Mail, Telefon) in allen frei +// eingegebenen Texten des Projekts. Die Kopfdaten der Ausgaben leert `competitionIdentity.ts` selbst. +// +// Bezeichner englisch, Kommentare deutsch. + +import { core } from "../engine/coreWasm"; +import type { Project } from "../model/types"; +import { isAnonymous } from "./competitionIdentity"; + +/** Herkunft des gefundenen Begriffs. */ +export type AnonymityKind = "name" | "number" | "titleBlock" | "address" | "identifier" | "file" | "email" | "phone"; + +export interface AnonymityFinding { + /** Oberste Projekt-Liste (`rooms`, `drawingLevels` …) bzw. Bereich eines Zusatztexts (`export`). */ + area: string; + /** Fundstelle: Elementname und Feld. */ + place: string; + /** Der Text (gekürzt). */ + text: string; + /** Der gefundene Begriff. */ + term: string; + kind: AnonymityKind; +} + +export interface AnonymityExtraText { + area: string; + place: string; + text: string; +} + +export interface AnonymityOptions { + /** Dateiname des Projekts (als Begriff gesucht). */ + fileName?: string; + /** Weitere zu prüfende Texte, z. B. der Dateiname der Ausgabe. */ + texts?: AnonymityExtraText[]; +} + +/** Treffer im Freitext; leer bei nicht anonymer Abgabe und wenn alles sauber ist. */ +export function anonymityFindings(project: Project, options: AnonymityOptions = {}): AnonymityFinding[] { + if (!isAnonymous(project)) return []; + const out = core().anonymity_findings(JSON.stringify(project), JSON.stringify({ fileName: options.fileName ?? "", texts: options.texts ?? [] })); + try { + const parsed: unknown = JSON.parse(out); + return Array.isArray(parsed) ? (parsed as AnonymityFinding[]) : []; + } catch { + return []; + } +} diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 075c1c7e..6a71436d 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -4151,6 +4151,49 @@ export const de = { "layouts.newLayout.poster": "Plakat-Vorlage (Wettbewerb)", "layouts.newLayout.posterHint": "Gestaltungsraster als Hilfslinien, Kopfzeile mit Kennwort und „Plan x/n“, Massstab unter jedem Viewport.", "publish.competition.anonymous": "Wettbewerb (anonym)", + "anonymity.title": "Anonymität prüfen", + "anonymity.message": "{count} Stelle(n) im Freitext könnten die Abgabe verraten:", + "anonymity.proceed": "Trotzdem exportieren", + "anonymity.area.hatches": "Schraffuren", + "anonymity.area.lineStyles": "Linienstile", + "anonymity.area.rooms": "Räume", + "anonymity.area.drawingLevels": "Geschosse", + "anonymity.area.layers": "Ebenen / Klassen", + "anonymity.area.groups": "Gruppen", + "anonymity.area.blockDefs": "Blöcke", + "anonymity.area.layouts": "Layouts / Blätter", + "anonymity.area.masterLayouts": "Masterlayouts", + "anonymity.area.drawings2d": "2D-Zeichnung / Texte", + "anonymity.area.walls": "Wände", + "anonymity.area.openings": "Öffnungen", + "anonymity.area.stairs": "Treppen", + "anonymity.area.columns": "Stützen", + "anonymity.area.context": "Kontext", + "anonymity.area.extrudedSolids": "Körper", + "anonymity.area.viewSnapshots": "Ausschnitte", + "anonymity.area.viewSnapshotFolders": "Ausschnitt-Ordner", + "anonymity.area.viewTemplates": "Ansichtsvorlagen", + "anonymity.area.layoutFolders": "Layout-Ordner", + "anonymity.area.publishSets": "Publikationssätze", + "anonymity.area.roomProgram": "Raumprogramm", + "anonymity.area.export": "Ausgabe", + "anonymity.area.cameras": "Kameras", + "anonymity.area.components": "Bauteile", + "anonymity.area.wallTypes": "Wandtypen", + "anonymity.area.textStyles": "Textstile", + "anonymity.area.ceilings": "Decken", + "anonymity.area.roofs": "Dächer", + "anonymity.area.trees": "Bäume", + "anonymity.kind.name": "Projektname", + "anonymity.kind.number": "Projektnummer", + "anonymity.kind.titleBlock": "Büro / Bearbeiter:in", + "anonymity.kind.address": "Adresse", + "anonymity.kind.identifier": "Angabe aus der Liste", + "anonymity.kind.file": "Dateiname", + "anonymity.kind.email": "E-Mail", + "anonymity.kind.phone": "Telefon", + "publish.competition.identifiers": "Weitere Angaben, die nicht vorkommen dürfen", + "publish.competition.identifiersHint": "Büro, Namen, E-Mail, Telefon, getrennt durch Komma. Vor dem Export der anonymen Abgabe im Freitext gesucht.", "publish.competition.keyword": "Kennwort", "publish.competition.hint": "Plankopf, PDF-Titel und Dateinamen zeigen nur das Kennwort; kein Büro- oder Autorname, keine Programm- und Datumsangaben im PDF.", "publish.wbw.add": "WBW-Abgabe anlegen", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 217cb8db..70f761b4 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -4137,6 +4137,49 @@ export const en: Record = { "layouts.newLayout.poster": "Poster template (competition)", "layouts.newLayout.posterHint": "Layout grid as guides, header with keyword and \"Plan x/n\", scale under every viewport.", "publish.competition.anonymous": "Competition (anonymous)", + "anonymity.title": "Check anonymity", + "anonymity.message": "{count} place(s) in free text could identify the submission:", + "anonymity.proceed": "Export anyway", + "anonymity.area.hatches": "Hatches", + "anonymity.area.lineStyles": "Line styles", + "anonymity.area.rooms": "rooms", + "anonymity.area.drawingLevels": "floors", + "anonymity.area.layers": "layers / classes", + "anonymity.area.groups": "groups", + "anonymity.area.blockDefs": "blocks", + "anonymity.area.layouts": "layouts / sheets", + "anonymity.area.masterLayouts": "master layouts", + "anonymity.area.drawings2d": "2D drawing / text", + "anonymity.area.walls": "walls", + "anonymity.area.openings": "openings", + "anonymity.area.stairs": "stairs", + "anonymity.area.columns": "columns", + "anonymity.area.context": "context", + "anonymity.area.extrudedSolids": "solids", + "anonymity.area.viewSnapshots": "view snapshots", + "anonymity.area.viewSnapshotFolders": "snapshot folders", + "anonymity.area.viewTemplates": "view templates", + "anonymity.area.layoutFolders": "layout folders", + "anonymity.area.publishSets": "publish sets", + "anonymity.area.roomProgram": "room program", + "anonymity.area.export": "output", + "anonymity.area.cameras": "cameras", + "anonymity.area.components": "components", + "anonymity.area.wallTypes": "wall types", + "anonymity.area.textStyles": "text styles", + "anonymity.area.ceilings": "ceilings", + "anonymity.area.roofs": "roofs", + "anonymity.area.trees": "trees", + "anonymity.kind.name": "project name", + "anonymity.kind.number": "project number", + "anonymity.kind.titleBlock": "office / author", + "anonymity.kind.address": "address", + "anonymity.kind.identifier": "listed detail", + "anonymity.kind.file": "file name", + "anonymity.kind.email": "e-mail", + "anonymity.kind.phone": "phone", + "publish.competition.identifiers": "Further details that must not appear", + "publish.competition.identifiersHint": "Office, names, e-mail, phone, separated by commas. Searched in free text before an anonymous submission is exported.", "publish.competition.keyword": "Keyword", "publish.competition.hint": "Title block, PDF title and file names show only the keyword; no office or author name, no program or date details in the PDF.", "publish.wbw.add": "Create competition set", diff --git a/src/model/types.generated.ts b/src/model/types.generated.ts index 1147f15a..6409cb08 100644 --- a/src/model/types.generated.ts +++ b/src/model/types.generated.ts @@ -345,6 +345,11 @@ export type CompetitionSettings = { anonymous: boolean; /** Kennwort der Abgabe (steht in Plankopf und PDF-Titel). */ keyword: string; + /** + * Weitere identifizierende Angaben (Büro, Personen, E-Mail, Telefon, Adresse), getrennt durch Komma, Semikolon + * oder Zeilenumbruch: die Anonymitäts-Prüfung sucht sie im Freitext des Projekts. + */ + identifiers?: string; }; /** diff --git a/src/panels/PublishSection.tsx b/src/panels/PublishSection.tsx index 3cebfc2c..3513ccaf 100644 --- a/src/panels/PublishSection.tsx +++ b/src/panels/PublishSection.tsx @@ -194,7 +194,18 @@ export function PublishSection() { onChange={(e) => host.onSetCompetition({ keyword: e.target.value })} /> +