diff --git a/TODO.md b/TODO.md index c12b6829..4b52a1cc 100644 --- a/TODO.md +++ b/TODO.md @@ -158,10 +158,15 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC. nur Titel = Kennwort, Producer/Datum längengleich neutralisiert (`export/pdfInfo.ts`; jsPDF schreibt sie sonst immer), Dateinamen und Schriftfeld des Einzelplan-PDF mit Kennwort. **Publikationssatz „WBW-Abgabe“** (Knopf in der Publikation): alle Plakate als ein PDF, Format über den Satz-Editor auf Einzeldateien umstellbar. Tests: Rust (`layout_image`, `layout_poster`, Titelblock anonym), vitest - (`layoutImages`, `posterTemplates`, `layoutPdf.images`), e2e `competition` (A1 quer aus Vorlage, Bild, anonym, PDF). Offen: Hilfslinien nicht - als Fang und nicht frei setzbar; Bild-Zuschnitt nur per Prozentfeldern (kein Ziehen), Bild in DXF/IFC-Exporten nicht; Anonymität nur im PDF und - in Dateinamen (IFC/DXF/SVG-Metadaten, Layer-/Blattnamen mit Büroangaben prüft niemand); Berichts-PDF (`areaReport`) - noch nicht anonymisiert (Blatt-, Ordner- und Satz-PDF sind es); Download-Namen im Browser ohne Tauri-Dialog; grosse Bilder: jede + (`layoutImages`, `posterTemplates`, `layoutPdf.images`), e2e `competition` (A1 quer aus Vorlage, Bild, anonym, PDF). Anonymität vollständig (13.11., zentral `export/competitionIdentity.ts` + Kern `competition.rs`): Berichte (Fläche, Raumbuch, Kosten, + Öffnungen, Bauteile, Programm) mit Kennwort im Kopf/CSV und anonymem PDF; IFC4/2x3 (Kern-Sammler: Kennwort statt Projektname in + IfcProject/IfcBuilding und Dateiname, fester Zeitstempel; Schreiber `fileio/ifc_export`: leerer Zeitstempel = anonym → Organisation/Person/ + Anwendung „-“, Kopf ohne Autor/Programm), DXF/DWG (Header war schon neutral, Blattnamen der Projekt-Layouts → „Blatt n“), STEP (Zeitstempel fest), + Blender-`scene.json`, Dateinamen (Panels, CLI, Export-Dialog). Geprüft ohne Befund: SVG, Druck-SVG, OBJ/MTL/STL/glTF/GLB, CSV-Bauteilliste, PNG (Bild-Export + schreibt keine tEXt-Chunks). Test `competitionAnonymous.test.ts` (alle Formate, Gegenprobe ohne Anonymität). Offen: Hilfslinien nicht + als Fang und nicht frei setzbar; Bild-Zuschnitt nur per Prozentfeldern (kein Ziehen), 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 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 - [61] Raumprogramm gegen Modell und Flächennachweis SIA 416 als Tabelle/Layout-Element ([70]); Kennzahlen (GF, GV, HNF/GF, Fassadenanteil). diff --git a/src-tauri/core/src/README.md b/src-tauri/core/src/README.md index 3f1a1ca8..935578b7 100644 --- a/src-tauri/core/src/README.md +++ b/src-tauri/core/src/README.md @@ -84,6 +84,7 @@ Neues Modul: `.rs` und `mod` in `lib.rs`, Bindungen in `web/.rs` u | `layers.rs`, `levels.rs`, `groups.rs`, `pens.rs`, `reorder.rs`, `folder_tree.rs` | Ebenen, Geschosse, Gruppen, Stiftsätze, Z-Reihenfolge, Ordner | | `layout_model.rs`, `sheet_viewports.rs`, `sheet_table.rs`, `presentation_sheet.rs` | Layout-Blätter, Viewports, Tabellen, Präsentationsplan | | `layout_image.rs`, `layout_poster.rs` | Bilder auf Blättern (Dateikopf, Zuschnitt, dpi) und Plakat-Vorlagen mit Raster und Kopfzeile ([208]) | +| `competition.rs` | Anonyme Abgabe ([208]): `anonymous_keyword`, neutraler Zeitstempel für IFC-Sammler und DXF-Blattnamen (TS-Gegenstück `export/competitionIdentity.ts`) | | `parametric_walls.rs`, `geo_translate.rs`, `geo_rebase.rs` | parametrische Wände; Projekt verschieben; Ursprung für Exporte | | `auto_lines.rs` | [221] Standard-Schnitt/-Ansicht folgen dem Gebauten (im `commit` nachgeführt, wie `dim_assoc`) | diff --git a/src-tauri/core/src/competition.rs b/src-tauri/core/src/competition.rs new file mode 100644 index 00000000..8bcb44f6 --- /dev/null +++ b/src-tauri/core/src/competition.rs @@ -0,0 +1,32 @@ +// Anonyme Wettbewerbs-Abgabe ([208]): was die Ausgaben über die Herkunft sagen dürfen. Ist +// `Project.competition` anonym, trägt keine Ausgabe Büro, Bearbeiter:in, Projektname, Projektnummer, Adresse +// oder Benutzername — nur das Kennwort. Gegenstück in TS: `src/export/competitionIdentity.ts` (dieselbe Regel für +// PDF, Berichte, STEP, Blender-Paket, Dateinamen). Der Plankopf löst das selbst auf (`layout_model.rs`). + +use crate::model::Project; + +/// Fester Zeitstempel anonymer Ausgaben: 2000-01-01 00:00:00 UTC (Sekunden seit 1970). +pub const NEUTRAL_EPOCH: f64 = 946_684_800.0; +/// Derselbe Zeitstempel als ISO-Text ohne Zone. +pub const NEUTRAL_ISO: &str = "2000-01-01T00:00:00"; + +/// Kennwort der Abgabe, wenn sie anonym ist (getrimmt; leer = anonym ohne Kennwort); `None` = nicht anonym. +pub fn anonymous_keyword(p: &Project) -> Option { + p.competition.as_ref().filter(|c| c.anonymous).map(|c| c.keyword.trim().to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::CompetitionSettings; + + #[test] + fn nur_anonym_liefert_kennwort() { + let mut p = Project::default(); + assert_eq!(anonymous_keyword(&p), None); + p.competition = Some(CompetitionSettings { anonymous: false, keyword: "K".into(), ..Default::default() }); + assert_eq!(anonymous_keyword(&p), None); + p.competition = Some(CompetitionSettings { anonymous: true, keyword: " FALKE 7 ".into(), ..Default::default() }); + assert_eq!(anonymous_keyword(&p).as_deref(), Some("FALKE 7")); + } +} diff --git a/src-tauri/core/src/ifc_data.rs b/src-tauri/core/src/ifc_data.rs index 5461a361..a8d58b1a 100644 --- a/src-tauri/core/src/ifc_data.rs +++ b/src-tauri/core/src/ifc_data.rs @@ -881,12 +881,15 @@ pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result // Kopf: RefElevation = reale Datumshöhe (informativ), RefLatitude/-Longitude des Bezugspunkts. let anchor = p.geo_anchor.clone(); let lat_lon = anchor.as_ref().map(|a| (a.lv95.e, a.lv95.n)).filter(|(e, n)| e.is_finite() && n.is_finite()).map(|(e, n)| lv95_to_wgs84(e, n)).filter(|(la, lo)| la.is_finite() && lo.is_finite()); - let (pid, pname) = (f.str(&p.id), f.str(&p.name)); - let iso = f.str(&opt.iso); + // Anonyme Abgabe ([208]): Kennwort statt Projektname, fester Zeitstempel; leerer `iso` heisst für den Schreiber + // „anonym" (neutrale Erzeuger-/Autorangaben, `fileio/ifc_export`). + let anon = crate::competition::anonymous_keyword(&p); + let (pid, pname) = (f.str(&p.id), f.str(anon.as_deref().unwrap_or(&p.name))); + let (now, iso) = if anon.is_some() { (crate::competition::NEUTRAL_EPOCH, f.str("")) } else { (opt.now, f.str(&opt.iso)) }; f.nums(&[ pid, pname, - opt.now, + now, iso, if anchor.is_some() { 1.0 } else { 0.0 }, anchor.as_ref().and_then(|a| a.height).unwrap_or(f64::NAN), @@ -1725,6 +1728,23 @@ mod tests { text.split('\0').map(String::from).collect() } + /// [208] Anonyme Abgabe: Kopf trägt Kennwort, festen Zeitstempel und leeren ISO-Text, nie den Projektnamen. + #[test] + fn anonyme_abgabe_kopf() { + let mut p = sample(); + p.name = "BUEROXY Haus".into(); + let opt = IfcOptions { now: 1_794_583_435.0, iso: "2026-11-13T15:23:55".into(), ..Default::default() }; + let plain = ifc_export_data(&p, &opt).unwrap(); + assert!(strings(&plain).iter().any(|s| s == "BUEROXY Haus")); + p.competition = Some(crate::model::CompetitionSettings { anonymous: true, keyword: "FALKE 7".into(), ..Default::default() }); + let f = ifc_export_data(&p, &opt).unwrap(); + let s = strings(&f); + assert!(!s.iter().any(|x| x.contains("BUEROXY")), "{s:?}"); + assert!(s.iter().any(|x| x == "FALKE 7")); + assert!(!s.iter().any(|x| x.starts_with("2026-"))); + assert_eq!(f.nums[3], crate::competition::NEUTRAL_EPOCH); + } + /// [149] Baum als eigener Datensatz (nach den Stützen): Name = Art, Netz Stamm + Krone relativ zur /// Geschoss-UK, Höhe als Menge. #[test] diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index f46f86ee..81211a59 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -4,6 +4,7 @@ //! //! Datenübergabe: flache `f64`-Puffer (s. [`flat`]), kein JSON — schnell und ohne Serde-Kosten. +pub mod competition; pub mod export_schedule; pub mod opening_schedule; pub mod room_book; diff --git a/src-tauri/core/src/plan/dxf.rs b/src-tauri/core/src/plan/dxf.rs index 3f6df556..f1c8740a 100644 --- a/src-tauri/core/src/plan/dxf.rs +++ b/src-tauri/core/src/plan/dxf.rs @@ -1599,7 +1599,8 @@ fn sheets(cx: &mut Ctx, main: &mut Buf, layer_by_code: &HashMap<&str, String>) { .and_then(|v| crate::layout_model::effective_sheet_size(&v)); let Some((pw, ph)) = size else { continue }; // Eindeutiger Name (gleichnamige Blätter, Kollision mit dem Plan-Layout). - let base = if js_trim(&layout.name).is_empty() { format!("Blatt {}", n + 1) } else { layout.name.clone() }; + // Anonyme Abgabe ([208]): Blattnamen sind frei wählbar und können Büro- oder Projektangaben tragen. + let base = if js_trim(&layout.name).is_empty() || crate::competition::anonymous_keyword(p).is_some() { format!("Blatt {}", n + 1) } else { layout.name.clone() }; let mut name = base.clone(); let mut k = 2; while used.contains(&name) { @@ -1778,6 +1779,27 @@ mod tests { assert!(!f2.nums.windows(2).any(|w| w[0] == REC_SHEET_VP && f2.strings.get(w[1] as usize).is_some_and(|s| s == "Blatt"))); } + /// [208] Anonyme Abgabe: Blattnamen (frei wählbar) kommen nicht in die Datei, das Blatt heisst „Blatt n". + #[test] + fn anonyme_abgabe_blattnamen() { + let mut p: Project = serde_json::from_value(crate::sheet_viewports::tests::json()).unwrap(); + p.layouts.as_mut().unwrap()[0].name = "BUEROXY Plan".into(); + let a = crate::plan::domains::PlanArgs::parse(1.0, r#"{"floor":"eg","show":["20"],"scale":100}"#).unwrap(); + let buf = crate::plan::domains::plan_domains_buf(&p, &a).unwrap(); + let o = DxfOptions { scale: 100.0, include_hatches: true, dim_cm: false, paper_layout: true, bounds: [0.0, 0.0, 10.0, 4.0], default_font: "Arial".into(), floor: "eg".into(), table_labels: String::new() }; + let run = |p: &Project| { + let view = View::parse(&buf).unwrap(); + let len = view.len(); + let mut parts = [Part::new(view, 0, len).unwrap()]; + collect(&mut parts, p, &o).unwrap().strings + }; + assert!(run(&p).iter().any(|s| s == "BUEROXY Plan")); + p.competition = Some(crate::model::CompetitionSettings { anonymous: true, keyword: "FALKE 7".into(), ..Default::default() }); + let s = run(&p); + assert!(!s.iter().any(|x| x.contains("BUEROXY")), "{s:?}"); + assert!(s.iter().any(|x| x == "Blatt 1")); + } + /// [111] Blatt-Tabelle als Block mit Text und Linien, eingefügt oben links. #[test] fn blatt_tabelle_im_dxf() { diff --git a/src-tauri/fileio/src/ifc_export/mod.rs b/src-tauri/fileio/src/ifc_export/mod.rs index 60f17f5a..4dbbe6e4 100644 --- a/src-tauri/fileio/src/ifc_export/mod.rs +++ b/src-tauri/fileio/src/ifc_export/mod.rs @@ -9,7 +9,8 @@ // Zeichenkette, Teile durch `\0` getrennt; im Zahlenpuffer steht ihr Index (−1 = keine). // // [FLAT_VERSION, META, Datensatz, Datensatz, …] -// META = project_id, project_name, now (Sekunden, ganzzahlig), iso (Zeitstempel, Text), has_geo (0/1), +// META = project_id, project_name, now (Sekunden, ganzzahlig), iso (Zeitstempel, Text; leer = anonyme Abgabe [208]: +// neutrale Programm-/Personenangaben, fester Kopf-Zeitstempel), has_geo (0/1), // ref_elevation (NaN = keine), ref_lat, ref_lon (WGS84-Grad, NaN = keine; nur IFC2x3), // schema (0 = IFC4, 1 = IFC2x3), n_storeys, (id, name, base) × n_storeys // PTS = n, x0, y0, …, x(n−1), y(n−1) (Profil, offen; Rust schliesst es) @@ -227,6 +228,9 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { } let now = now_f as i64; let iso = r.string()?; + // Leerer Zeitstempel = anonyme Abgabe ([208]): neutrale Erzeuger-/Autorangaben, fester Kopf-Zeitstempel. + let anon = iso.is_empty(); + let iso = if anon { "2000-01-01T00:00:00".to_string() } else { iso }; let has_geo = r.flag()?; let ref_elevation = r.raw()?; let (ref_lat, ref_lon) = (r.raw()?, r.raw()?); @@ -279,17 +283,20 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { w.extrude_dir = w.add("IFCDIRECTION", list(&[fmt_real(0.0), fmt_real(0.0), fmt_real(1.0)])); w.identity_axis = w.add("IFCAXIS2PLACEMENT3D", format!("#{origin},$,$")); - // Owner-History (minimal, aber vorhanden — manche Importer verlangen sie). - let org = w.add("IFCORGANIZATION", format!("$,{},$,$,$", ifc_string("dossier"))); + // Owner-History (minimal, aber vorhanden — manche Importer verlangen sie). Anonyme Abgabe ([208], leerer + // Zeitstempel in META): keine Angabe zu Programm, Person oder Organisation — nur der Strich als Pflichtwert. + let who = if anon { "-" } else { "dossier" }; + let app_version = if anon { "-" } else { "1.0" }; + let org = w.add("IFCORGANIZATION", format!("$,{},$,$,$", ifc_string(who))); // IFC2x3 verlangt FamilyName oder GivenName (WR1), IFC4 genügt die Kennung. let person = w.add( "IFCPERSON", - if v2 { format!("{0},{0},$,$,$,$,$,$", ifc_string("dossier")) } else { format!("{},$,$,$,$,$,$,$", ifc_string("dossier")) }, + if v2 { format!("{0},{0},$,$,$,$,$,$", ifc_string(who)) } else { format!("{},$,$,$,$,$,$,$", ifc_string(who)) }, ); let person_org = w.add("IFCPERSONANDORGANIZATION", format!("#{person},#{org},$")); let app = w.add( "IFCAPPLICATION", - format!("#{org},{},{},{}", ifc_string("1.0"), ifc_string("dossier"), ifc_string("dossier")), + format!("#{org},{},{},{}", ifc_string(app_version), ifc_string(who), ifc_string(who)), ); // ChangeAction ADDED verlangt ein LastModifiedDate (IFC4-Regel IfcOwnerHistory.CorrectChangeAction). w.owner_history = w.add( @@ -1260,10 +1267,10 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { "FILE_NAME({},{},{},{},{},{},{});\n", ifc_string(&file_name), ifc_string(&iso), - list(&[ifc_string("dossier")]), - list(&[ifc_string("dossier")]), - ifc_string("dossier"), - ifc_string("dossier"), + list(&[ifc_string(if anon { "" } else { "dossier" })]), + list(&[ifc_string(if anon { "" } else { "dossier" })]), + ifc_string(if anon { "" } else { "dossier" }), + ifc_string(if anon { "" } else { "dossier" }), ifc_string("") )); out.push_str(&format!("FILE_SCHEMA(('{}'));\nENDSEC;\n\nDATA;\n", if v2 { "IFC2X3" } else { "IFC4" })); diff --git a/src-tauri/fileio/src/ifc_export/tests.rs b/src-tauri/fileio/src/ifc_export/tests.rs index eccc369e..84068d09 100644 --- a/src-tauri/fileio/src/ifc_export/tests.rs +++ b/src-tauri/fileio/src/ifc_export/tests.rs @@ -1187,6 +1187,23 @@ fn leeres_projekt_ist_gueltig() { assert_eq!(count(&ifc, "IFCRELAGGREGATES"), 2); } +/// [208] Leerer Zeitstempel = anonyme Abgabe: weder Programm noch Person noch aktuelle Zeit im Kopf und in der Owner-History. +#[test] +fn anonyme_abgabe_ohne_erzeuger_und_zeit() { + let mut b = B::new(); + b.str("p"); + b.str("FALKE 7"); + b.n(&[946_684_800.0]); + b.str(""); + b.meta_tail(false, f64::NAN, 0.0); + let ifc = build(&b).unwrap(); + check_structure(&ifc); + assert!(!ifc.to_lowercase().contains("dossier"), "{ifc}"); + assert!(ifc.contains("FILE_NAME('FALKE 7.ifc','2000-01-01T00:00:00',(''),(''),'','',''")); + assert!(ifc.contains("IFCORGANIZATION($,'-'") && ifc.contains("IFCAPPLICATION(#")); + assert!(ifc.contains("IFCPROJECT('") && ifc.contains("'FALKE 7'")); +} + #[test] fn oeffnung_ohne_wirtswand_wird_uebersprungen() { let mut b = B::new(); diff --git a/src/cli/main.ts b/src/cli/main.ts index eb064487..444f327a 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -95,6 +95,7 @@ import { areaReportToCsv, areaReportToSvg, buildAreaReportPdf, + exportProjectName, sunPosition, shadowPolygons, projectLatLon, @@ -813,7 +814,7 @@ function blenderFailure(e: unknown): number { /** `dossier-cli … render`: Paket bauen, Blender starten, Bild nach `--out`. Rückgabe = Exit-Code. */ async function runRender(project: Project, args: Args): Promise { const pkg = await buildCliPackage(project, args, "render"); - const target = args.flags.get("out") ?? `${project.name || "projekt"}.png`; + const target = args.flags.get("out") ?? `${exportProjectName(project) || "projekt"}.png`; try { const res = await runBlenderRender(nodeBlenderHost(args.flags.has("keep")), pkg, { script: renderScript(args), @@ -835,7 +836,7 @@ async function runRender(project: Project, args: Args): Promise { /** [228] `dossier-cli … blend`: Szene wie fürs Rendering aufbauen und als .blend nach `--out` speichern (nicht rendern). */ async function runBlend(project: Project, args: Args): Promise { const pkg = await buildCliPackage(project, args, "save"); - const target = args.flags.get("out") ?? `${project.name || "projekt"}.blend`; + const target = args.flags.get("out") ?? `${exportProjectName(project) || "projekt"}.blend`; try { const res = await runBlenderSave(nodeBlenderHost(args.flags.has("keep")), pkg, { script: renderScript(args), @@ -992,16 +993,16 @@ async function execute(project: Project, file: string, command: string, rest: st case "ifc": await loadFileio(); // --ebkph: eBKP-H-Hauptgruppen je Bauteilart; --ebenen: Ebene (categoryCode) des Modells als Klassifikation. - out(args, exportIfcSpf(project, { ebkph: args.flags.has("ebkph"), layerCodes: args.flags.has("ebenen"), schema: ifcSchemaFlag(args) }), `${project.name || "projekt"}.ifc`); + out(args, exportIfcSpf(project, { ebkph: args.flags.has("ebkph"), layerCodes: args.flags.has("ebenen"), schema: ifcSchemaFlag(args) }), `${exportProjectName(project) || "projekt"}.ifc`); return 0; case "obj": await loadFileio(); // [201] Mit MTL (Farben) daneben: `--out haus.obj` schreibt auch `haus.mtl`; `--out -` oder `--no-mtl`: nur das OBJ // (Farben dann als Kommentar im Kopf). { - const target = args.flags.get("out") ?? `${project.name || "projekt"}.obj`; + const target = args.flags.get("out") ?? `${exportProjectName(project) || "projekt"}.obj`; if (target === "-" || args.flags.has("no-mtl")) { - out(args, exportObj(project), `${project.name || "projekt"}.obj`); + out(args, exportObj(project), `${exportProjectName(project) || "projekt"}.obj`); } else { const mtlPath = target.replace(/\.obj$/i, "") + ".mtl"; out(args, exportObj(project, {}, basename(mtlPath)), target); @@ -1012,15 +1013,15 @@ async function execute(project: Project, file: string, command: string, rest: st return 0; case "stl": await loadFileio(); - out(args, exportStl(project), `${project.name || "projekt"}.stl`); + out(args, exportStl(project), `${exportProjectName(project) || "projekt"}.stl`); return 0; case "glb": await loadFileio(); - out(args, exportGlb(project, { byLevel: !args.flags.has("flat") }), `${project.name || "projekt"}.glb`); + out(args, exportGlb(project, { byLevel: !args.flags.has("flat") }), `${exportProjectName(project) || "projekt"}.glb`); return 0; case "gltf": await loadFileio(); - out(args, exportGltf(project, { byLevel: !args.flags.has("flat") }), `${project.name || "projekt"}.gltf`); + out(args, exportGltf(project, { byLevel: !args.flags.has("flat") }), `${exportProjectName(project) || "projekt"}.gltf`); return 0; case "kennzahlen": { // --sia416 / --ivhb: Flächentabelle bzw. IVHB-Kennziffern [70]; --format json|csv|svg|pdf (Default json). @@ -1038,7 +1039,7 @@ async function execute(project: Project, file: string, command: string, rest: st const wantAreas = args.flags.has("sia416"); const wantIvhb = args.flags.has("ivhb"); const format = args.flags.get("format") ?? "json"; - const stem = `${project.name || "projekt"}-flaechen`; + const stem = `${exportProjectName(project) || "projekt"}-flaechen`; if (format === "json") { const json = { ...(wantAreas ? { flaechentabelle: computeAreaTable(project) } : {}), ...(wantIvhb ? { ivhb: computeIvhb(project, ivhbOptions) } : {}) }; out(args, JSON.stringify(json, null, 2), `${stem}.json`); @@ -1056,7 +1057,7 @@ async function execute(project: Project, file: string, command: string, rest: st const baurecht = checkSiteRules(project); // [68] Erdarbeiten je Baugrube (Abtrag/Auftrag/Hinterfüllung, m³). const erdarbeiten = excavationQuantities(project); - out(args, JSON.stringify({ kennzahlen: k, raumprogramm: prog, baurecht, erdarbeiten }, null, 2), `${project.name || "projekt"}-kennzahlen.json`); + out(args, JSON.stringify({ kennzahlen: k, raumprogramm: prog, baurecht, erdarbeiten }, null, 2), `${exportProjectName(project) || "projekt"}-kennzahlen.json`); return 0; } case "raumprogramm": { @@ -1114,14 +1115,14 @@ async function execute(project: Project, file: string, command: string, rest: st if (Number.isNaN(when.getTime())) throw new Error("--when: ungültiges Datum"); const { lat, lon } = projectLatLon(project); const sun = sunPosition(lat, lon, when); - out(args, JSON.stringify({ when: when.toISOString(), lat, lon, sun, shadows: shadowPolygons(project, sun) }, null, 2), `${project.name || "projekt"}-sonne.json`); + out(args, JSON.stringify({ when: when.toISOString(), lat, lon, sun, shadows: shadowPolygons(project, sun) }, null, 2), `${exportProjectName(project) || "projekt"}-sonne.json`); return 0; } case "schedule": { // --openings: Fenster- und Türliste statt Bauteilliste [--format json|csv|svg|pdf] (Default csv) if (args.flags.has("openings")) { const format = args.flags.get("format") ?? "csv"; - const stem = `${project.name || "projekt"}-fenster-tueren`; + const stem = `${exportProjectName(project) || "projekt"}-fenster-tueren`; if (format === "json") out(args, JSON.stringify(openingSchedule(project), null, 2), `${stem}.json`); else { const report = buildOpeningReport(project); @@ -1135,7 +1136,7 @@ async function execute(project: Project, file: string, command: string, rest: st // --rooms: Raumbuch mit Oberflächen und Mengen ([158]) [--format json|csv|svg|pdf] (Default csv) if (args.flags.has("rooms")) { const format = args.flags.get("format") ?? "csv"; - const stem = `${project.name || "projekt"}-raumbuch`; + const stem = `${exportProjectName(project) || "projekt"}-raumbuch`; if (format === "json") out(args, JSON.stringify(roomBook(project), null, 2), `${stem}.json`); else { const report = buildRoomBookReport(project); @@ -1149,7 +1150,7 @@ async function execute(project: Project, file: string, command: string, rest: st // --elements: Bauteilliste mit U-Werten aus den Schichten ([71]) [--format json|csv|svg|pdf] (Default csv) if (args.flags.has("elements")) { const format = args.flags.get("format") ?? "csv"; - const stem = `${project.name || "projekt"}-bauteile`; + const stem = `${exportProjectName(project) || "projekt"}-bauteile`; if (format === "json") out(args, JSON.stringify(elementSchedule(project), null, 2), `${stem}.json`); else { const report = buildElementReport(project); @@ -1160,13 +1161,13 @@ async function execute(project: Project, file: string, command: string, rest: st } return 0; } - out(args, exportScheduleCsv(project), `${project.name || "projekt"}-liste.csv`); + out(args, exportScheduleCsv(project), `${exportProjectName(project) || "projekt"}-liste.csv`); return 0; } case "step": { const r = await exportProjectStep(project, project.name || "projekt"); if (r.skipped.length) process.stderr.write(`${r.skipped.length} Körper übersprungen/ungeschnitten.\n`); - out(args, r.text, `${project.name || "projekt"}.stp`); + out(args, r.text, `${exportProjectName(project) || "projekt"}.stp`); return 0; } case "import-ifc": { @@ -1251,7 +1252,7 @@ async function execute(project: Project, file: string, command: string, rest: st ghostPattern: Array.from(emitSurfacePatternLines(project, explode, ghost)), } : model; - out(args, JSON.stringify(json), `${project.name || "projekt"}.model3d.json`); + out(args, JSON.stringify(json), `${exportProjectName(project) || "projekt"}.model3d.json`); return 0; } case "bench": { diff --git a/src/core/extra.ts b/src/core/extra.ts index 94985f23..c7177954 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -43,6 +43,8 @@ export { sheetTables, createTable, drawTablesPdf, tableCatalog, tableLabels, tab export type { TableOut, TablePrim, TableColumn } from "../export/sheetTable"; export { computeAreaTable, computeIvhb } from "../analysis/areaTable"; export type { AreaTable, AreaRow, Ivhb, IvhbOptions, AgfBasis } from "../analysis/areaTable"; +export { exportProjectName, competitionIdentity, isAnonymous, competitionKeyword, identityLeaks, NEUTRAL_DATE, NEUTRAL_ISO } from "../export/competitionIdentity"; +export type { CompetitionIdentity } from "../export/competitionIdentity"; 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/README.md b/src/export/README.md index 9e9b3658..9b568b84 100644 --- a/src/export/README.md +++ b/src/export/README.md @@ -17,6 +17,7 @@ Abschnitt 3.4). | `layoutPdf.ts` | alle Layouts eines Ordners als Mehrseiten-PDF | | `pdfLayers.ts` | PDF-Ebenen (Optional Content Groups, `[80]`) | | `pdfInfo.ts` | PDF-Info-Wörterbuch; bei anonymer Wettbewerbs-Abgabe nur das Kennwort, Producer/Datum längengleich neutralisiert (`[208]`) | +| `competitionIdentity.ts` | Anonyme Abgabe ([208]): `competitionIdentity`, `exportProjectName`, `reportHead`, Gegenprüfer `identityLeaks`; alle Exporter holen Name/Autor/Zeitstempel hier. Test `competitionAnonymous.test.ts` | | `exportDxf.ts` | DXF/DWG des Grundrisses in Modellmetern; Schreiben in `src-tauri/fileio/src/export.rs` | | `legendSvg.ts` | Legende als Plan-/Druck-SVG (`[82]`) | diff --git a/src/export/areaReport.ts b/src/export/areaReport.ts index ac2ff140..1beb2829 100644 --- a/src/export/areaReport.ts +++ b/src/export/areaReport.ts @@ -9,6 +9,8 @@ // // Die Flächenarten folgen SIA 416, die Kennziffern der IVHB; Herleitung im Kern (`flaechen.rs`). +import { reportHead } from "./competitionIdentity"; +import { anonymizeJsPdf } from "./pdfInfo"; import { jsPDF } from "jspdf"; import type { Project } from "../model/types"; import { t } from "../i18n/translate"; @@ -36,6 +38,8 @@ export interface ReportSection { export interface AreaReport { title: string; projectName: string; + /** Anonyme Wettbewerbs-Abgabe ([208]): `projectName` ist das Kennwort; das PDF trägt keine Erzeuger- und Datumsangaben. */ + anonymous?: boolean; sections: ReportSection[]; /** Fussnoten (Quellen, Annahmen). */ notes: string[]; @@ -111,7 +115,7 @@ export function buildAreaReport(project: Project, opts: AreaReportOptions = {}): notes.push(t("areas.foot.ivhb")); addNotes(v.notes); } - return { title: t("areas.title"), projectName: project.name ?? "", sections, notes }; + return { title: t("areas.title"), ...reportHead(project), sections, notes }; } // ── CSV, Seitenaufteilung, SVG: rechnet der Kern (`core/src/area_report.rs`, Bericht als JSON) ───────────── @@ -185,5 +189,6 @@ export function buildAreaReportPdf(report: AreaReport, o: ReportLayoutOptions = } } }); + if (report.anonymous) anonymizeJsPdf(doc, report.projectName); return doc; } diff --git a/src/export/blenderRender.ts b/src/export/blenderRender.ts index c5708c04..c6c27bbc 100644 --- a/src/export/blenderRender.ts +++ b/src/export/blenderRender.ts @@ -19,6 +19,7 @@ // Achsen in `scene.json`: Modell-Koordinaten (x Ost, y Nord, z oben, Meter) — Blenders glTF-Import dreht das // Y-oben-GLB genau dorthin zurück, Kamera und Sonne brauchen im Skript keine Umrechnung. +import { exportProjectName } from "./competitionIdentity"; import type { Camera, ComponentMaterial, LayoutOrientation, LayoutPaperFormat, Project } from "../model/types"; import { projectLatLon, sunPosition } from "../analysis/sun"; import { sheetSizeMm } from "../model/layoutModel"; @@ -392,7 +393,7 @@ export async function buildRenderPackage(project: Project, opts: RenderOptions, const scene: RenderScene = { version: 1, - project: project.name || "projekt", + project: exportProjectName(project) || "projekt", model: "model.glb", output: "render.png", resolution: { width: Math.round(opts.width), height: Math.round(opts.height) }, diff --git a/src/export/competitionAnonymous.test.ts b/src/export/competitionAnonymous.test.ts new file mode 100644 index 00000000..3b7e0b52 --- /dev/null +++ b/src/export/competitionAnonymous.test.ts @@ -0,0 +1,186 @@ +// [208] Anonyme Wettbewerbs-Abgabe: kein Export verrät Büro, Bearbeiter:in, Projektname oder Projektnummer — nur das +// Kennwort. Ein Beispielprojekt mit gesetzten Namen geht durch alle Formate (PDF-Info und -Text, Berichte als CSV/PDF, +// IFC4/IFC2x3, DXF ASCII/Binär/DWG, SVG, OBJ/MTL/STL/glTF, STEP, CSV, Blender-Paket); danach darf keiner der Namen +// vorkommen (Gross-/Kleinschreibung egal). Gegenprobe: ohne Anonymität stehen die Namen in den Ausgaben, der Test +// prüft also wirklich etwas. Muster: e2e `competition`, `layoutPdf.images.test.ts`. + +import "../engine/fileioWasm.setup"; +import { readFileSync } from "node:fs"; +import { inflateSync } from "node:zlib"; +import { describe, expect, it } from "vitest"; +import { sampleProject } from "../model/sampleProject"; +import { createPosterMaster, posterTemplate } from "../model/posterTemplates"; +import { flattenCategories } from "../model/types"; +import type { Layout, Project } from "../model/types"; +import { generatePlan } from "../plan/generatePlan"; +import { buildPlanDwg, buildPlanDxf, buildPlanDxfBinary } from "./exportDxf"; +import { exportIfcSpf } from "./exportIfc"; +import { exportGlb, exportGltf, exportMtl, exportObj, exportStl } from "./exportMesh"; +import { exportScheduleCsv } from "./exportSchedule"; +import { exportProjectStep } from "./exportStep"; +import { buildPagesPdf, layoutPages, pdfBytes } from "./layoutPdf"; +import { planToSvgString } from "./planToSvgString"; +import { areaReportToCsv, buildAreaReport, buildAreaReportPdf } from "./areaReport"; +import { buildProgramReport } from "./programReport"; +import { buildRoomBookReport } from "./roomBook"; +import { buildOpeningReport } from "./openingSchedule"; +import { buildElementReport } from "./elementSchedule"; +import { buildCostReport } from "./costReport"; +import { buildRenderPackage } from "./blenderRender"; +import { identityLeaks, identifyingTexts, NEUTRAL_ISO } from "./competitionIdentity"; +import { pdfInfoText } from "./pdfInfo"; + +const OFFICE = "BUEROXYZ Architekten AG"; +const AUTHOR = "BEARBEITERQ Muster"; +const NAME = "PROJEKTNAMEZ Haus"; +const NUMBER = "NUMMER4711"; +const KEYWORD = "FALKE 7"; +const SECRETS = [OFFICE, AUTHOR, NAME, NUMBER]; + +/** Ganzes Beispielprojekt mit Büro-, Bearbeiter- und Projektangaben; Blatt mit Plakat-Kopf (zeigt Projekt/Autor). */ +function project(anonymous: boolean | null): Project { + const master = createPosterMaster("m1", posterTemplate("poster-a1-landscape")!); + master.titleBlock = { projectName: `${OFFICE} ${NAME}`, author: AUTHOR }; + const layout: Layout = { id: "l1", name: "Grundriss", paper: "a1", orientation: "landscape", masterId: "m1", viewports: [] }; + return { + ...sampleProject, + name: NAME, + projectNumber: NUMBER, + masterLayouts: [master], + layouts: [layout], + ...(anonymous === null ? {} : { competition: { anonymous, keyword: KEYWORD } }), + } as Project; +} + +const latin1 = (b: Uint8Array): string => Buffer.from(b).toString("latin1"); + +/** Seiteninhalt (Flate-Streams) des PDF entpackt, hintereinander. */ +function streamsText(bytes: Uint8Array): string { + const all = Buffer.from(bytes); + const text = all.toString("latin1"); + let out = ""; + for (const m of text.matchAll(/stream\r?\n/g)) { + const from = m.index! + m[0].length; + const to = text.indexOf("endstream", from); + try { + out += inflateSync(all.subarray(from, to)).toString("latin1") + "\n"; + } catch { + // kein Flate-Stream + } + } + return out; +} + +/** Alle Ausgaben, die ohne Browser/GPU entstehen: Name → Text (Binärformate als latin1). */ +async function allOutputs(p: Project): Promise> { + const plan = generatePlan(p, "eg", new Set(flattenCategories(p.layers).map((l) => l.code))); + const out: Record = {}; + // PDF: Blatt (Info + Seiteninhalt) und Berichte (Info + Inhalt) + const doc = await buildPagesPdf(p, layoutPages(p, ["l1"])); + const sheet = pdfBytes(p, doc!); + out["PDF-Blatt"] = latin1(sheet); + out["PDF-Blatt-Text"] = streamsText(sheet); + out["PDF-Blatt-Info"] = pdfInfoText(sheet); + const reports = { Flaechen: buildAreaReport(p, { ivhb: true }), Programm: buildProgramReport(p), Raumbuch: buildRoomBookReport(p), Oeffnungen: buildOpeningReport(p), Bauteile: buildElementReport(p), Kosten: buildCostReport(p) }; + for (const [name, report] of Object.entries(reports)) { + out[`CSV-${name}`] = areaReportToCsv(report); + const bytes = new Uint8Array(buildAreaReportPdf(report).output("arraybuffer")); + out[`PDF-${name}`] = latin1(bytes); + out[`PDF-${name}-Text`] = streamsText(bytes); + out[`PDF-${name}-Info`] = pdfInfoText(bytes); + } + // IFC + out["IFC4"] = exportIfcSpf(p); + out["IFC2x3"] = exportIfcSpf(p, { schema: "IFC2X3" }); + // DXF/DWG (mit Papierbereich der Projekt-Layouts) + out["DXF"] = buildPlanDxf(plan, p, { paperLayout: true, levelId: "eg" }); + out["DXF-binaer"] = latin1(buildPlanDxfBinary(plan, p, { paperLayout: true, levelId: "eg" })); + out["DWG"] = latin1(buildPlanDwg(plan, p, { paperLayout: true, levelId: "eg" })); + // SVG, Mesh, CSV + out["SVG"] = planToSvgString(plan, { hatch: true }); + out["OBJ"] = exportObj(p, {}, "m.mtl"); + out["OBJ-ohne-MTL"] = exportObj(p); + out["MTL"] = exportMtl(p); + out["STL"] = exportStl(p); + out["glTF"] = exportGltf(p); + out["GLB"] = latin1(exportGlb(p)); + out["CSV-Bauteilliste"] = exportScheduleCsv(p); + // STEP (truck-WASM) + const mod: any = await import("../engine/pkgTruck/trucksolid.js"); + await mod.default({ module_or_path: readFileSync("src/engine/pkgTruck/trucksolid_bg.wasm") }); + out["STEP"] = (await exportProjectStep(p)).text; + // Blender-Paket (scene.json) + const pkg = await buildRenderPackage(p, { width: 640, height: 360, samples: 16, when: new Date(Date.UTC(2026, 5, 21, 10, 0, 0)), camera: { preset: "iso" } }); + out["Blender-scene.json"] = new TextDecoder().decode(pkg.files.find((f) => f.path === "scene.json")!.bytes); + return out; +} + +describe("anonyme Wettbewerbs-Abgabe in allen Ausgaben", () => { + it("Gegenprobe: ohne Anonymität stehen die Angaben in den Ausgaben (der Test prüft etwas)", async () => { + const p = project(false); + expect(identifyingTexts(p)).toEqual(expect.arrayContaining([NAME, NUMBER, AUTHOR])); + const o = await allOutputs(p); + for (const [where, what] of [ + ["IFC4", NAME], + ["CSV-Flaechen", NAME], + ["PDF-Flaechen-Text", NAME], + ["PDF-Blatt-Text", AUTHOR], + ["Blender-scene.json", NAME], + ] as const) { + expect(o[where], where).toContain(what); + } + }, 120000); + + it("anonym: keine Ausgabe nennt Büro, Bearbeiter:in, Projektname oder Projektnummer", async () => { + const p = project(true); + const o = await allOutputs(p); + const leaks: string[] = []; + for (const [where, text] of Object.entries(o)) { + for (const secret of SECRETS) if (text.toLowerCase().includes(secret.toLowerCase())) leaks.push(`${where}: ${secret}`); + for (const l of identityLeaks(p, text)) leaks.push(`${where}: ${l}`); + } + expect(leaks).toEqual([]); + }, 120000); + + it("anonym: das Kennwort steht, wo es stehen soll", async () => { + const o = await allOutputs(project(true)); + expect(o["PDF-Blatt-Text"]).toContain(`(${KEYWORD})`); + expect(o["PDF-Blatt-Info"]).toContain(`/Title (${KEYWORD})`); + expect(o["PDF-Flaechen-Info"]).toContain(`/Title (${KEYWORD})`); + expect(o["PDF-Flaechen-Text"]).toContain(KEYWORD); + expect(o["CSV-Flaechen"].split("\n")[1]).toBe(KEYWORD); + expect(o["IFC4"]).toContain(`IFCPROJECT('`); + expect(o["IFC4"]).toContain(`'${KEYWORD}'`); + expect(o["IFC4"]).toContain(`FILE_NAME('${KEYWORD}.ifc','${NEUTRAL_ISO}'`); + expect(JSON.parse(o["Blender-scene.json"]).project).toBe(KEYWORD); + }, 120000); + + it("anonym: keine Zeit- und Erzeugerspuren in PDF-Info, IFC und STEP", async () => { + const o = await allOutputs(project(true)); + const year = String(new Date().getFullYear()); + for (const key of ["PDF-Blatt-Info", "PDF-Flaechen-Info", "PDF-Raumbuch-Info"]) { + expect(o[key], key).not.toMatch(/jsPDF|Dossier/i); + expect(o[key], key).not.toContain(`D:${year}`); + expect(o[key], key).toContain("D:20000101000000"); + } + for (const key of ["IFC4", "IFC2x3"]) { + // „Dossier_Qto_…" ist der Name eines Eigenschaftssatzes (Programm-Konvention), keine Angabe zur Herkunft. + expect(o[key].replace(/Dossier_Qto_/g, ""), key).not.toMatch(/dossier/i); + expect(o[key], key).not.toContain(`${year}-`); + expect(o[key], key).toContain(`'${NEUTRAL_ISO}'`); + } + expect(o["STEP"]).not.toContain(`${year}-`); + expect(o["STEP"]).toContain("2000-01-01 00:00:00.000"); + }, 120000); + + it("anonym: Blattnamen der Projekt-Layouts erscheinen im DXF nur als „Blatt n“", async () => { + const p = project(true); + p.layouts = [{ ...p.layouts![0], name: `${OFFICE} Plan 1` }]; + const plan = generatePlan(p, "eg", new Set(flattenCategories(p.layers).map((l) => l.code))); + const dxf = buildPlanDxf(plan, p, { paperLayout: true, levelId: "eg" }); + expect(dxf).not.toContain("BUEROXYZ"); + expect(dxf).toContain("Blatt_1"); + const plain = { ...p, competition: undefined } as Project; + expect(buildPlanDxf(plan, plain, { paperLayout: true, levelId: "eg" })).toContain("BUEROXYZ_Architekten_AG_Plan_1"); + }); +}); diff --git a/src/export/competitionIdentity.ts b/src/export/competitionIdentity.ts new file mode 100644 index 00000000..8ec6056a --- /dev/null +++ b/src/export/competitionIdentity.ts @@ -0,0 +1,94 @@ +// Anonyme Wettbewerbs-Abgabe ([208]): EINE Stelle, die sagt, welche Angaben in eine Ausgabe dürfen. Ist +// `Project.competition` anonym, trägt keine Ausgabe (PDF, IFC, DXF/DWG, SVG, CSV, Bilder, Blender-Paket, STEP …) +// Büro, Bearbeiter:in, Projektname, Projektnummer, Adresse oder Benutzername — nur das Kennwort. Jeder Exporter holt +// seine Angaben hier, statt `project.name` selbst zu lesen. Das Gegenstück im Kern: `src-tauri/core/src/competition.rs` +// (IFC-Sammler, DXF-Blattnamen, Plankopf); dort gilt dieselbe Regel. +// +// Bezeichner englisch, Kommentare deutsch. + +import type { Project } from "../model/types"; + +type CompetitionSource = Pick; + +/** Fester Zeitstempel anonymer Ausgaben (2000-01-01 00:00:00 UTC): keine Spur, wann und wo gespeichert wurde. */ +export const NEUTRAL_DATE = new Date(Date.UTC(2000, 0, 1, 0, 0, 0)); +/** Derselbe Zeitstempel als ISO-Text ohne Zone (STEP-/IFC-Kopf). */ +export const NEUTRAL_ISO = "2000-01-01T00:00:00"; + +/** Ist die Abgabe anonym? */ +export function isAnonymous(project: CompetitionSource): boolean { + return project.competition?.anonymous === true; +} + +/** Kennwort der Abgabe (getrimmt, leer ohne Wettbewerb). */ +export function competitionKeyword(project: CompetitionSource): string { + return (project.competition?.keyword ?? "").trim(); +} + +/** Projektname für Schriftfelder, Berichtsköpfe, Dateinamen und Metadaten der Exporte: bei anonymer Abgabe das Kennwort. */ +export function exportProjectName(project: Pick): string { + return isAnonymous(project) ? competitionKeyword(project) : (project.name ?? ""); +} + +/** Was eine Ausgabe über die Herkunft sagen darf. */ +export interface CompetitionIdentity { + anonymous: boolean; + keyword: string; + /** Projektname der Ausgabe (anonym: das Kennwort). */ + projectName: string; + /** Bearbeiter:in der Ausgabe (anonym: leer). */ + author(raw?: string | null): string; + /** Zeitstempel der Ausgabe (anonym: fest {@link NEUTRAL_DATE}). */ + timestamp(now?: Date): Date; + /** Erzeuger-/Programmangabe in Metadaten (anonym: leer). */ + creator(name?: string): string; +} + +/** Die Angaben, die in die Ausgaben dieses Projekts dürfen. */ +export function competitionIdentity(project: Pick): CompetitionIdentity { + const anonymous = isAnonymous(project); + return { + anonymous, + keyword: competitionKeyword(project), + projectName: exportProjectName(project), + author: (raw) => (anonymous ? "" : (raw ?? "")), + timestamp: (now = new Date()) => (anonymous ? NEUTRAL_DATE : now), + creator: (name = "Dossier") => (anonymous ? "" : name), + }; +} + +/** + * Angaben des Projekts, die eine anonyme Ausgabe nicht verraten darf (Name, Nummer, Titelblock-Bearbeiter:in): + * Grundlage für den Gegenprüfer {@link identityLeaks} und die Tests. + */ +export function identifyingTexts(project: Project): string[] { + const out: string[] = []; + const add = (s: string | null | undefined) => { + const v = (s ?? "").trim(); + if (v.length >= 3) out.push(v); + }; + add(project.name); + add(project.projectNumber); + for (const m of project.masterLayouts ?? []) { + add(m.titleBlock?.projectName); + add(m.titleBlock?.author); + } + return [...new Set(out)]; +} + +/** Kopf der Berichte (Flächen, Raumbuch, Kosten …): Projektname der Ausgabe und Anonym-Kennzeichen für das PDF. */ +export function reportHead(project: Pick): { projectName: string; anonymous?: boolean } { + return isAnonymous(project) ? { projectName: competitionKeyword(project), anonymous: true } : { projectName: project.name ?? "" }; +} + +/** STEP-Kopf anonym: der Zeitstempel in FILE_NAME wird fest ({@link NEUTRAL_ISO}); Autor und Organisation schreibt truck leer. */ +export function neutralizeStepText(text: string): string { + const stamp = `${NEUTRAL_ISO.replace("T", " ")}.000`; + return text.replace(/(FILE_NAME\('[^']*', ')\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?(')/, `$1${stamp}$2`); +} + +/** Welche der Angaben stehen (ohne Beachtung der Gross-/Kleinschreibung) im Text? Leer = sauber. */ +export function identityLeaks(project: Project, text: string): string[] { + const hay = text.toLowerCase(); + return identifyingTexts(project).filter((s) => hay.includes(s.toLowerCase())); +} diff --git a/src/export/costReport.ts b/src/export/costReport.ts index cfe15eaa..a94b8ef8 100644 --- a/src/export/costReport.ts +++ b/src/export/costReport.ts @@ -2,6 +2,7 @@ // dieselben Ausgaben (CSV über `areaReportToCsv`, Vektor-PDF über `buildAreaReportPdf`). Gerechnet wird im // Kern (`analysis/costEstimate.ts` → `kosten.rs`); hier nur Aufbau und Beschriftung mit `t()`. +import { reportHead } from "./competitionIdentity"; import type { Project } from "../model/types"; import { t } from "../i18n/translate"; import { computeCostEstimate, formatChf } from "../analysis/costEstimate"; @@ -48,7 +49,7 @@ export function buildCostReport(project: Project, result: CostResult = computeCo return { title: t("costs.title"), - projectName: project.name ?? "", + ...reportHead(project), sections: [ { heading: `${t("costs.table")} · ${t(`costs.method.${r.method}`)}`, diff --git a/src/export/elementSchedule.ts b/src/export/elementSchedule.ts index 104e0c8e..f9f32da2 100644 --- a/src/export/elementSchedule.ts +++ b/src/export/elementSchedule.ts @@ -3,6 +3,7 @@ // `elementSchedule` und `uValue`); hier nur Beschriftung mit `t()` und das Berichtsmodell für CSV/SVG/PDF // (wie die Fenster-/Türliste, `openingSchedule.ts`). +import { reportHead } from "./competitionIdentity"; import type { Layer, Project } from "../model/types"; import { t } from "../i18n/translate"; import { documentFor } from "../core/document"; @@ -71,5 +72,5 @@ export function buildElementReport(project: Project): AreaReport { widths: [4, 1.6, 1.4, 1.3, 1.3, 1.4], rows: g.list.map((r): ReportRow => ({ cells: [r.typeName, r.floor, num(r.area, 2), num(r.thickness * 100, 1), r.u === null ? t("elemSchedule.incomplete") : num(r.u, 2), externalText(r.external)] })), })); - return { title: t("elemSchedule.title"), projectName: project.name ?? "", sections, notes: [t("elemSchedule.foot")] }; + return { title: t("elemSchedule.title"), ...reportHead(project), sections, notes: [t("elemSchedule.foot")] }; } diff --git a/src/export/exportStep.ts b/src/export/exportStep.ts index c4adca3f..e597e462 100644 --- a/src/export/exportStep.ts +++ b/src/export/exportStep.ts @@ -13,6 +13,7 @@ // // Koordinaten: Modell-Meter, X/Y = Grundriss, Z = Höhe (wie die Eingabe von render3d). +import { exportProjectName, isAnonymous, neutralizeStepText } from "./competitionIdentity"; import type { Project } from "../model/types"; import { documentFor } from "../core/document"; import { exportStepSolids } from "../engine/truckSolid"; @@ -52,8 +53,8 @@ export async function exportProjectStep(project: Project, fileName = ""): Promis const skipped: StepExportResult["skipped"] = []; // Erst alle zusammen versuchen (Normalfall); nur bei Fehler einzeln prüfen. try { - const text = await exportStepSolids(specs, fileName || project.name); - return { text, count: specs.length, skipped }; + const text = await exportStepSolids(specs, fileName || exportProjectName(project)); + return { text: isAnonymous(project) ? neutralizeStepText(text) : text, count: specs.length, skipped }; } catch { /* einzeln weiter */ } @@ -76,6 +77,6 @@ export async function exportProjectStep(project: Project, fileName = ""): Promis skipped.push({ index: i, error: e instanceof Error ? e.message : String(e) }); } } - const text = await exportStepSolids(good, fileName || project.name); - return { text, count: good.length, skipped }; + const text = await exportStepSolids(good, fileName || exportProjectName(project)); + return { text: isAnonymous(project) ? neutralizeStepText(text) : text, count: good.length, skipped }; } diff --git a/src/export/openingSchedule.ts b/src/export/openingSchedule.ts index 3f587953..260e89e7 100644 --- a/src/export/openingSchedule.ts +++ b/src/export/openingSchedule.ts @@ -3,6 +3,7 @@ // und der Berichtsaufbau, damit CSV, SVG und PDF dieselbe Quelle haben wie der Flächennachweis // (`areaReport.ts`: `areaReportToCsv` / `areaReportToSvg` / `buildAreaReportPdf`). +import { reportHead } from "./competitionIdentity"; import type { Project } from "../model/types"; import { t } from "../i18n/translate"; import { documentFor } from "../core/document"; @@ -141,5 +142,5 @@ export function buildOpeningReport(project: Project): AreaReport { const doors = rows.filter((r) => r.kind === "door"); if (windows.length) sections.push(windowSection(windows)); if (doors.length) sections.push(doorSection(doors)); - return { title: t("openings.title"), projectName: project.name ?? "", sections, notes: rows.some((r) => r.revealAreas?.length) ? [t("openings.foot"), t("openings.revealFoot")] : [t("openings.foot")] }; + return { title: t("openings.title"), ...reportHead(project), sections, notes: rows.some((r) => r.revealAreas?.length) ? [t("openings.foot"), t("openings.revealFoot")] : [t("openings.foot")] }; } diff --git a/src/export/pdfInfo.ts b/src/export/pdfInfo.ts index b38833a6..2bc44bf8 100644 --- a/src/export/pdfInfo.ts +++ b/src/export/pdfInfo.ts @@ -7,21 +7,9 @@ import type { jsPDF } from "jspdf"; import type { Project } from "../model/types"; +import { competitionKeyword, exportProjectName, isAnonymous } from "./competitionIdentity"; -/** Ist die Abgabe anonym? */ -export function isAnonymous(project: Pick): boolean { - return project.competition?.anonymous === true; -} - -/** Kennwort der Abgabe (getrimmt, leer ohne Wettbewerb). */ -export function competitionKeyword(project: Pick): string { - return (project.competition?.keyword ?? "").trim(); -} - -/** Projektname für Schriftfelder und Dateinamen der Exporte: bei anonymer Abgabe das Kennwort. */ -export function exportProjectName(project: Pick): string { - return isAnonymous(project) ? competitionKeyword(project) : (project.name ?? ""); -} +export { isAnonymous, competitionKeyword, exportProjectName }; /** Info-Felder, die ins PDF gehören: anonym nur das Kennwort als Titel, sonst Projektname und Autor des Titelblocks. */ export function pdfInfoFields(project: Pick, author?: string): { title: string; author: string; subject: string; keywords: string; creator: string } { @@ -29,6 +17,32 @@ export function pdfInfoFields(project: Pick, au return { title: project.name ?? "", author: author ?? "", subject: "", keywords: "", creator: "Dossier" }; } +/** + * Anonymes jsPDF-Dokument: Info-Felder nur mit Kennwort, und `output("arraybuffer"|"blob")` sowie `save()` liefern die + * nachbearbeiteten Bytes (jsPDF schreibt Producer und Datum selbst). So bleiben die Aufrufer (`doc.save(name)`) gleich. + */ +export function anonymizeJsPdf(doc: jsPDF, keyword: string): void { + const project = { name: "", competition: { anonymous: true, keyword } }; + applyPdfInfo(doc, project); + type Output = (type?: string, options?: unknown) => unknown; + const output = (doc.output as unknown as Output).bind(doc); + const bytes = () => finishPdfBytes(project, new Uint8Array(output("arraybuffer") as ArrayBuffer)); + (doc as unknown as { output: Output }).output = (type, options) => { + if (type === "arraybuffer") return bytes().slice().buffer; + if (type === "blob") return new Blob([bytes() as BlobPart], { type: "application/pdf" }); + return output(type, options); + }; + doc.save = ((fileName?: string) => { + const url = URL.createObjectURL(new Blob([bytes() as BlobPart], { type: "application/pdf" })); + const a = document.createElement("a"); + a.href = url; + a.download = fileName ?? "bericht.pdf"; + a.click(); + setTimeout(() => URL.revokeObjectURL(url), 1000); + return doc; + }) as typeof doc.save; +} + /** Setzt die Info-Felder auf dem jsPDF-Dokument. */ export function applyPdfInfo(doc: jsPDF, project: Pick, author?: string): void { doc.setProperties(pdfInfoFields(project, author)); diff --git a/src/export/programReport.ts b/src/export/programReport.ts index 0bbd1826..08b9e0d1 100644 --- a/src/export/programReport.ts +++ b/src/export/programReport.ts @@ -2,6 +2,7 @@ // (`areaReport.ts`), damit CSV, SVG und PDF dieselbe Quelle und denselben Seitenaufbau haben. // Die Zahlen rechnet der Kern (`analysis/roomProgram.ts`); hier nur die Beschriftung mit `t()`. +import { reportHead } from "./competitionIdentity"; import type { Project } from "../model/types"; import { t } from "../i18n/translate"; import { compareRoomProgram } from "../analysis/roomProgram"; @@ -75,5 +76,5 @@ export function buildProgramReport(project: Project): AreaReport { const notes = [t("program.report.note.tolerance", { pct: (c.tolerance * 100).toFixed(0), pct2: (c.tolerance * 200).toFixed(0) })]; if (c.kinds.some((k) => k.key !== "")) notes.push(t("program.report.note.sia")); if (c.extra.length > 0) notes.push(t("program.compare.extra", { n: c.extra.length, area: c.extraArea.toFixed(1) })); - return { title: t("program.report.title"), projectName: project.name ?? "", sections, notes }; + return { title: t("program.report.title"), ...reportHead(project), sections, notes }; } diff --git a/src/export/roomBook.ts b/src/export/roomBook.ts index 33c7d6fe..f0912218 100644 --- a/src/export/roomBook.ts +++ b/src/export/roomBook.ts @@ -3,6 +3,7 @@ // Beschriftung mit `t()` und der Berichtsaufbau, damit CSV, SVG und PDF dieselbe Quelle haben wie die // Fenster-/Türliste (`openingSchedule.ts`). Die Blatt-Tabelle (Quelle `roomBook`) rechnet der Kern selbst. +import { reportHead } from "./competitionIdentity"; import type { Project, RoomUsage } from "../model/types"; import { t } from "../i18n/translate"; import type { TranslationKey } from "../i18n/translate"; @@ -131,5 +132,5 @@ export function buildRoomBookReport(project: Project): AreaReport { const sections: ReportSection[] = []; if (b.rows.length) sections.push(roomSection(b.rows)); if (b.quantities.length) sections.push(quantitySection(b.quantities)); - return { title: t("roomBook.title"), projectName: project.name ?? "", sections, notes: [t("roomBook.foot")] }; + return { title: t("roomBook.title"), ...reportHead(project), sections, notes: [t("roomBook.foot")] }; } diff --git a/src/panels/AreaTableSection.tsx b/src/panels/AreaTableSection.tsx index 5683ee3c..8e6d0470 100644 --- a/src/panels/AreaTableSection.tsx +++ b/src/panels/AreaTableSection.tsx @@ -8,7 +8,7 @@ import { useMemo, useState } from "react"; import { t } from "../i18n"; -import { areaReportToCsv, buildAreaReport, buildAreaReportPdf } from "../core"; +import { exportProjectName, areaReportToCsv, buildAreaReport, buildAreaReportPdf } from "../core"; import type { AgfBasis } from "../core"; import { DEFAULT_AREA_INPUTS, ivhbOptionsOf, type AreaInputs } from "./areaInputs"; import { downloadCsv } from "./downloadFile"; @@ -26,7 +26,7 @@ export function AreaTableSection() { [project, inputs], ); const set = (patch: Partial) => setInputs((i) => ({ ...i, ...patch })); - const stem = `${project.name || "projekt"}-flaechen`; + const stem = `${exportProjectName(project) || "projekt"}-flaechen`; const exportPdf = () => { try { diff --git a/src/panels/CostEstimateSection.tsx b/src/panels/CostEstimateSection.tsx index 9b295e4c..91a059d2 100644 --- a/src/panels/CostEstimateSection.tsx +++ b/src/panels/CostEstimateSection.tsx @@ -9,7 +9,7 @@ import { useEffect, useMemo, useState } from "react"; import { t } from "../i18n"; -import { areaReportToCsv, buildAreaReportPdf, buildCostReport, computeCostEstimate, costGroupLabel, costUnitLabel, defaultCostEstimate, formatChf, setField } from "../core"; +import { exportProjectName, areaReportToCsv, buildAreaReportPdf, buildCostReport, computeCostEstimate, costGroupLabel, costUnitLabel, defaultCostEstimate, formatChf, setField } from "../core"; import type { CostBasis, CostEstimate, CostGroup, CostMethod, CostResult } from "../core"; import type { Project } from "../model/types"; import { downloadCsv } from "./downloadFile"; @@ -65,7 +65,7 @@ export function CostEstimateSection() { const notify = useStore((s) => s.notify); const res = useMemo(() => computeCostEstimate(project), [project]); const est: CostEstimate = useMemo(() => project.costEstimate ?? defaultCostEstimate(project, "gv"), [project]); - const stem = `${project.name || "projekt"}-kosten`; + const stem = `${exportProjectName(project) || "projekt"}-kosten`; const update = (next: (e: CostEstimate) => CostEstimate, key: string) => applyChange((p: Project) => [setField("costEstimate", next(p.costEstimate ?? defaultCostEstimate(p, "gv")))], `costEstimate.${key}`); diff --git a/src/panels/ElementScheduleSection.tsx b/src/panels/ElementScheduleSection.tsx index 7e3a6d78..a3c5c412 100644 --- a/src/panels/ElementScheduleSection.tsx +++ b/src/panels/ElementScheduleSection.tsx @@ -4,7 +4,7 @@ import { useMemo } from "react"; import { t } from "../i18n"; -import { areaReportToCsv, buildAreaReportPdf, buildElementReport, elementSchedule } from "../core"; +import { exportProjectName, areaReportToCsv, buildAreaReportPdf, buildElementReport, elementSchedule } from "../core"; import { downloadCsv } from "./downloadFile"; import { useStore } from "../state/appStore"; @@ -12,7 +12,7 @@ export function ElementScheduleSection() { const project = useStore((s) => s.project); const notify = useStore((s) => s.notify); const rows = useMemo(() => elementSchedule(project), [project]); - const stem = `${project.name || "projekt"}-bauteile`; + const stem = `${exportProjectName(project) || "projekt"}-bauteile`; const exportPdf = () => { try { buildAreaReportPdf(buildElementReport(project)).save(`${stem}.pdf`); diff --git a/src/panels/OpeningScheduleSection.tsx b/src/panels/OpeningScheduleSection.tsx index 58ffd6ab..6fd69e79 100644 --- a/src/panels/OpeningScheduleSection.tsx +++ b/src/panels/OpeningScheduleSection.tsx @@ -7,7 +7,7 @@ import { useMemo } from "react"; import { t } from "../i18n"; import { usePanelHost } from "./host"; -import { areaReportToCsv, buildAreaReportPdf, buildOpeningReport, externalText, openingSchedule, patchItem, revealArea, revealColumns, roomsText, swingText } from "../core"; +import { exportProjectName, areaReportToCsv, buildAreaReportPdf, buildOpeningReport, externalText, openingSchedule, patchItem, revealArea, revealColumns, roomsText, swingText } from "../core"; import type { OpeningScheduleRow } from "../core"; import type { Opening, Project } from "../model/types"; import { downloadCsv } from "./downloadFile"; @@ -25,7 +25,7 @@ export function OpeningScheduleSection() { const rows = useMemo(() => openingSchedule(project), [project]); // [106] Leibungsflächen je Schicht: Spalten nur, wenn eine Öffnung Schichteinzug hat. const reveals = useMemo(() => revealColumns(rows), [rows]); - const stem = `${project.name || "projekt"}-fenster-tueren`; + const stem = `${exportProjectName(project) || "projekt"}-fenster-tueren`; const patch = (id: string, change: Partial, field: string) => applyChange((p: Project) => patchItem(p, "openings", id, change), `opening:${id}:${field}`); diff --git a/src/panels/ProgramCompareSection.tsx b/src/panels/ProgramCompareSection.tsx index d6918992..eaacaf86 100644 --- a/src/panels/ProgramCompareSection.tsx +++ b/src/panels/ProgramCompareSection.tsx @@ -11,7 +11,7 @@ import { t } from "../i18n"; import type { TranslationKey } from "../i18n"; import { usePanelHost } from "./host"; import { useStore } from "../state/appStore"; -import { addProgramSheetOps, areaReportToCsv, buildAreaReportPdf, buildProgramReport, buildProgramSheet, compareRoomProgram, defaultSheetLabels, DEFAULT_PROGRAM_TOLERANCE, setFieldIfChanged } from "../core"; +import { exportProjectName, addProgramSheetOps, areaReportToCsv, buildAreaReportPdf, buildProgramReport, buildProgramSheet, compareRoomProgram, defaultSheetLabels, DEFAULT_PROGRAM_TOLERANCE, setFieldIfChanged } from "../core"; import type { CompareRow, CompareSum, Light } from "../core"; import type { Project } from "../model/types"; import { downloadCsv } from "./downloadFile"; @@ -45,7 +45,7 @@ export function ProgramCompareSection({ statusLabel }: { statusLabel: (status: C const notify = useStore((s) => s.notify); const c = compareRoomProgram(project); if (c.rows.length === 0) return null; - const stem = `${project.name || "projekt"}-raumprogramm`; + const stem = `${exportProjectName(project) || "projekt"}-raumprogramm`; const hasGroups = c.groups.some((g) => g.key !== ""); const hasKinds = c.kinds.some((k) => k.key !== ""); diff --git a/src/panels/RoomBookSection.tsx b/src/panels/RoomBookSection.tsx index b8981daa..7ed1b16d 100644 --- a/src/panels/RoomBookSection.tsx +++ b/src/panels/RoomBookSection.tsx @@ -5,7 +5,7 @@ import { useMemo } from "react"; import { t } from "../i18n"; -import { areaReportToCsv, buildAreaReportPdf, buildRoomBookReport, hasSlope, roomBook, usageLabel } from "../core"; +import { exportProjectName, areaReportToCsv, buildAreaReportPdf, buildRoomBookReport, hasSlope, roomBook, usageLabel } from "../core"; import { downloadCsv } from "./downloadFile"; import { useStore } from "../state/appStore"; @@ -16,7 +16,7 @@ export function RoomBookSection() { const notify = useStore((s) => s.notify); const book = useMemo(() => roomBook(project), [project]); const sloped = book.rows.some(hasSlope); - const stem = `${project.name || "projekt"}-raumbuch`; + const stem = `${exportProjectName(project) || "projekt"}-raumbuch`; const exportPdf = () => { try { diff --git a/src/state/useProjectFileActions.ts b/src/state/useProjectFileActions.ts index 363cbac2..8a586c03 100644 --- a/src/state/useProjectFileActions.ts +++ b/src/state/useProjectFileActions.ts @@ -22,6 +22,7 @@ import { emptyImport, type ParsedImport } from "../io/importSource"; import { beginBusy, endBusy } from "./busyStore"; import type { ImportDecision, PdfImportOptions } from "../ui/ImportDialog"; import { isPdfFile, pdfImport, readPdfVector, type PdfRead } from "../io/pdfVector"; +import { exportProjectName } from "../export/competitionIdentity"; import { exportScheduleCsv } from "../export/exportSchedule"; import { exportIfcSpf, type IfcExportOptions } from "../export/exportIfc"; import { loadFileio } from "../engine/fileioWasm"; @@ -572,7 +573,7 @@ export function useProjectFileActions( ) => { void saveTextFile(content, filename, mime); }; - const projectFileName = () => getState().project.name || "modell"; + const projectFileName = () => exportProjectName(getState().project) || "modell"; // Führt den gewählten Direkt-Export (CSV/IFC/OBJ/STL) mit dem im Dialog // gewählten Dateinamen aus. Erzeugung aus dem jeweiligen reinen Kern, Download // über den robusten Helfer.