diff --git a/TODO.md b/TODO.md index e0f2b0f1..f8fdc23b 100644 --- a/TODO.md +++ b/TODO.md @@ -753,6 +753,11 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern Zeilen → Programmzeilen, Summen-/Zwischentitel, Flächenart, Zellentext), Bindungen in `web_sheet.rs`; `io/roomProgramImport.ts` nur noch Fassade (JSON, Signaturen gleich) + `roomProgramOps`. Gleichheit (einmalig, Test gelöscht): 400 Zufallstabellen alt/neu gleich. Bekannte Abweichung: Akzente über feste Tabelle statt Unicode-NFD (exotische Zeichen). + ✅ (29.10.) **Flächen-Nachweis-Ausgabe im Kern** ([70]/[K4]): `core/src/area_report.rs` (CSV schreiben/lesen, Seitenaufteilung + in Papier-mm, SVG; Bericht reist als JSON, Zahlen über `js_fmt`), Bindungen `web/area_report.rs`; `export/areaReport.ts` + behält Aufbau mit `t()` und jsPDF-Zeichnen (`buildAreaReportPdf`), der Rest ist Fassade mit gleichen Signaturen + (`cellText` gelöscht). Gleichheit (einmalig, Test gelöscht): 300 Zufallsberichte × Trenner × Seitenformate alt/neu + gleich (CSV byteweise, Rückleser, Seiten, SVG; Layout bis auf `bold:false`/`align:"left"` statt fehlend). ✅ (29.10.) **Fang-Kandidaten aus dem Modell im Kern** ([K4] S3/[K3d]): `snap_model.rs` sammelt je Dokument-Stand, Geschoss und sichtbaren Ebenen (vorher `baseSegments`/`collectCircles`/`roomAnchors`/`ellipseCenters` in `tools/snapping.ts`): Wandachsen + Schichtgrenzen, Raum-/Decken- (mit Aussparungen)/Dach-/Treppen-/Stützen-Umrisse, diff --git a/src-tauri/core/src/area_report.rs b/src-tauri/core/src/area_report.rs new file mode 100644 index 00000000..aaee8920 --- /dev/null +++ b/src-tauri/core/src/area_report.rs @@ -0,0 +1,432 @@ +//! Flächen-/Kennzahlen-Nachweis ([70]): CSV schreiben und lesen, Seitenaufteilung (Papier-mm) und SVG. +//! Hervorgegangen aus `src/export/areaReport.ts` (dort bleiben Aufbau mit `t()`-Beschriftung und die +//! jsPDF-Ausgabe; das PDF zeichnet die Primitive aus [`layout`]). Zahlen wie JS (`toFixed`, `String(n)`). + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +use crate::js_fmt::{js_number, to_fixed}; + +/// Zelle: Text oder Zahl (`d` Nachkommastellen, `n = null` = nicht berechenbar). +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum Cell { + Text(String), + Num { n: Option, d: usize }, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct Row { + pub cells: Vec, + #[serde(default)] + pub total: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct Section { + pub heading: String, + pub columns: Vec, + pub widths: Vec, + pub rows: Vec, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Report { + pub title: String, + pub project_name: String, + pub sections: Vec
, + pub notes: Vec, +} + +#[derive(Debug, Clone, Default, Deserialize)] +pub struct LayoutOptions { + pub width: Option, + pub height: Option, + pub margin: Option, +} + +/// Zeichen-Primitiv einer Seite (Papier-mm). +#[derive(Debug, Clone, PartialEq)] +pub enum Prim { + Text { x: f64, y: f64, s: String, size: f64, bold: bool, right: bool }, + Line { x1: f64, y1: f64, x2: f64, y2: f64, w: f64 }, +} + +pub struct Layout { + pub width: f64, + pub height: f64, + pub pages: Vec>, +} + +// ── CSV ───────────────────────────────────────────────────────────────────── + +fn csv_field(v: &str) -> String { + if v.contains(['"', ',', '\n', '\r', ';']) { + format!("\"{}\"", v.replace('"', "\"\"")) + } else { + v.to_string() + } +} + +/// Zelle als Text, so wie sie ausgegeben wird (Punkt als Dezimaltrenner, `null` = leer). +pub fn cell_text(c: &Cell) -> String { + match c { + Cell::Text(s) => s.clone(), + Cell::Num { n: None, .. } => String::new(), + Cell::Num { n: Some(n), d } => to_fixed(*n, *d), + } +} + +/// CSV des Berichts: Titel, Projekt, dann je Abschnitt Überschrift, Kopf, Zeilen; Fussnoten mit „* ". +pub fn to_csv(report: &Report, delimiter: &str) -> String { + let line = |cells: &[String]| cells.iter().map(|c| csv_field(c)).collect::>().join(delimiter); + let mut out: Vec = vec![line(&[report.title.clone()]), line(&[report.project_name.clone()]), String::new()]; + for s in &report.sections { + out.push(line(&[s.heading.clone()])); + out.push(line(&s.columns)); + for r in &s.rows { + out.push(line(&r.cells.iter().map(cell_text).collect::>())); + } + out.push(String::new()); + } + for n in &report.notes { + out.push(line(&[format!("* {n}")])); + } + out.join("\n") + "\n" +} + +/// Zerlegt CSV-Text in Zeilen von Feldern (Anführungszeichen, Trenner, Zeilenumbruch im Feld). +fn parse_csv_rows(text: &str, delimiter: &str) -> Vec> { + let cs: Vec = text.chars().collect(); + let delim = { + let mut it = delimiter.chars(); + match (it.next(), it.next()) { + (Some(c), None) => Some(c), + _ => None, // mehrstelliger Trenner trifft nie (wie `c === delimiter` in TS) + } + }; + let mut rows: Vec> = Vec::new(); + let mut row: Vec = Vec::new(); + let mut field = String::new(); + let mut quoted = false; + let mut i = 0; + while i < cs.len() { + let c = cs[i]; + if quoted { + if c == '"' { + if cs.get(i + 1) == Some(&'"') { + field.push('"'); + i += 1; + } else { + quoted = false; + } + } else { + field.push(c); + } + } else if c == '"' { + quoted = true; + } else if Some(c) == delim { + row.push(std::mem::take(&mut field)); + } else if c == '\n' || c == '\r' { + if c == '\r' && cs.get(i + 1) == Some(&'\n') { + i += 1; + } + row.push(std::mem::take(&mut field)); + rows.push(std::mem::take(&mut row)); + } else { + field.push(c); + } + i += 1; + } + if !field.is_empty() || !row.is_empty() { + row.push(field); + rows.push(row); + } + rows +} + +/// `/^-?\d+(\.\d+)?$/` (ASCII-Ziffern). +fn is_number(c: &str) -> bool { + let b = c.strip_prefix('-').unwrap_or(c); + let (int, frac) = match b.split_once('.') { + Some((i, f)) => (i, Some(f)), + None => (b, None), + }; + let digits = |s: &str| !s.is_empty() && s.bytes().all(|x| x.is_ascii_digit()); + digits(int) && frac.map_or(true, digits) +} + +/// Liest eine mit [`to_csv`] geschriebene CSV zurück (Rundreise): JSON `{title, projectName, sections, notes}`; +/// Zahlen als Zahl (Zelle leer → `null` an Zahlenstellen), Texte als Text. +pub fn parse_csv(text: &str, delimiter: &str) -> Value { + let rows = parse_csv_rows(text, delimiter); + let mut blocks: Vec>> = Vec::new(); + let mut cur: Vec> = Vec::new(); + for r in rows { + if r.len() == 1 && r[0].is_empty() { + if !cur.is_empty() { + blocks.push(std::mem::take(&mut cur)); + } + } else { + cur.push(r); + } + } + if !cur.is_empty() { + blocks.push(cur); + } + let mut it = blocks.into_iter(); + let head = it.next().unwrap_or_default(); + let first = |b: &Vec>, i: usize| b.get(i).and_then(|r| r.first()).cloned().unwrap_or_default(); + let mut sections: Vec = Vec::new(); + let mut notes: Vec = Vec::new(); + for b in it { + if b.first().and_then(|r| r.first()).map_or(false, |c| c.starts_with("* ")) { + for r in &b { + notes.push(json!(r[0].chars().skip(2).collect::())); + } + continue; + } + let rows: Vec = b + .iter() + .skip(2) + .map(|r| { + Value::Array( + r.iter() + .enumerate() + .map(|(i, c)| { + if is_number(c) { + json!(c.parse::().unwrap_or(f64::NAN)) + } else if i == 0 || !c.is_empty() { + json!(c) + } else { + Value::Null + } + }) + .collect(), + ) + }) + .collect(); + sections.push(json!({ "heading": first(&b, 0), "columns": b.get(1).cloned().unwrap_or_default(), "rows": rows })); + } + json!({ "title": first(&head, 0), "projectName": first(&head, 1), "sections": sections, "notes": notes }) +} + +// ── Seitenaufteilung ──────────────────────────────────────────────────────── + +fn utf16_len(s: &str) -> usize { + s.encode_utf16().count() +} + +/// Zeilenumbruch nach Zeichenzahl (Helvetica ≈ 0.5 em je Zeichen). +fn wrap(text: &str, max_mm: f64, size_pt: f64) -> Vec { + let per = (max_mm / (size_pt * 0.3528 * 0.5)).floor().max(10.0); + let mut lines: Vec = Vec::new(); + let mut cur = String::new(); + for w in text.split_whitespace() { + if !cur.is_empty() && (utf16_len(&cur) + 1 + utf16_len(w)) as f64 > per { + lines.push(std::mem::take(&mut cur)); + cur = w.to_string(); + } else if cur.is_empty() { + cur = w.to_string(); + } else { + cur = format!("{cur} {w}"); + } + } + if !cur.is_empty() { + lines.push(cur); + } + lines +} + +fn text(x: f64, y: f64, s: &str, size: f64, bold: bool, right: bool) -> Prim { + Prim::Text { x, y, s: s.to_string(), size, bold, right } +} + +/// Teilt den Bericht in Seiten mit Zeichen-Primitiven (Blattgrösse in mm, Default A4 quer). +pub fn layout(report: &Report, o: &LayoutOptions) -> Layout { + let width = o.width.unwrap_or(297.0); + let height = o.height.unwrap_or(210.0); + let m = o.margin.unwrap_or(12.0); + let inner = width - 2.0 * m; + let row_h = 6.0; + let mut pages: Vec> = vec![Vec::new()]; + let mut y = m; + macro_rules! page { + () => { + pages.last_mut().unwrap() + }; + } + macro_rules! ensure { + ($h:expr) => { + if y + $h > height - m { + pages.push(Vec::new()); + y = m; + } + }; + } + page!().push(text(m, y + 5.0, &report.title, 15.0, true, false)); + y += 8.0; + if !report.project_name.is_empty() { + page!().push(text(m, y + 4.0, &report.project_name, 10.0, false, false)); + y += 6.0; + } + y += 4.0; + + for s in &report.sections { + ensure!(row_h * 3.0 + 6.0); + page!().push(text(m, y + 4.0, &s.heading, 10.0, true, false)); + y += 7.0; + let sum: f64 = s.widths.iter().sum(); + let mut xs: Vec = Vec::new(); + let mut x = m; + for w in &s.widths { + xs.push(x); + x += (w / sum) * inner; + } + xs.push(x); + let numeric: Vec = (0..s.columns.len()).map(|i| s.rows.iter().any(|r| matches!(r.cells.get(i), Some(Cell::Num { .. })))).collect(); + // 0 = keine Linie, 1 = oben + let draw_row = |pages: &mut Vec>, y: &mut f64, cells: &[String], bold: bool, top: bool| { + if *y + row_h > height - m { + pages.push(Vec::new()); + *y = m; + } + let pg = pages.last_mut().unwrap(); + if top { + pg.push(Prim::Line { x1: m, y1: *y, x2: m + inner, y2: *y, w: 0.35 }); + } + for (i, c) in cells.iter().enumerate() { + let right = numeric.get(i).copied().unwrap_or(false); + let xi = xs.get(i).copied().unwrap_or(f64::NAN); + let xn = xs.get(i + 1).copied().unwrap_or(f64::NAN); + pg.push(text(if right { xn - 1.5 } else { xi + 1.5 }, *y + 4.2, c, 8.5, bold, right)); + } + *y += row_h; + }; + draw_row(&mut pages, &mut y, &s.columns, true, false); + page!().push(Prim::Line { x1: m, y1: y, x2: m + inner, y2: y, w: 0.35 }); + for r in &s.rows { + let cells: Vec = r + .cells + .iter() + .map(|c| match c { + Cell::Text(t) => t.clone(), + Cell::Num { n: None, .. } => "–".to_string(), + Cell::Num { n: Some(n), d } => to_fixed(*n, *d), + }) + .collect(); + let total = r.total == Some(true); + draw_row(&mut pages, &mut y, &cells, total, total); + } + page!().push(Prim::Line { x1: m, y1: y, x2: m + inner, y2: y, w: 0.35 }); + y += 6.0; + } + + for n in &report.notes { + let lines = wrap(n, inner, 7.5); + ensure!(lines.len() as f64 * 3.4 + 1.0); + for l in &lines { + page!().push(text(m, y + 2.8, l, 7.5, false, false)); + y += 3.4; + } + y += 1.0; + } + let total = pages.len(); + for (i, p) in pages.iter_mut().enumerate() { + p.push(text(width - m, height - m / 2.0, &format!("{} / {}", i + 1, total), 7.0, false, true)); + } + Layout { width, height, pages } +} + +/// Layout als JSON `{width, height, pages: [[{k:"text"|"line", …}]]}`. +pub fn layout_json(l: &Layout) -> Value { + let pages: Vec = l + .pages + .iter() + .map(|p| { + Value::Array( + p.iter() + .map(|q| match q { + Prim::Line { x1, y1, x2, y2, w } => json!({ "k": "line", "x1": x1, "y1": y1, "x2": x2, "y2": y2, "w": w }), + Prim::Text { x, y, s, size, bold, right } => { + let mut o = json!({ "k": "text", "x": x, "y": y, "s": s, "size": size }); + if *bold { + o["bold"] = json!(true); + } + if *right { + o["align"] = json!("right"); + } + o + } + }) + .collect(), + ) + }) + .collect(); + json!({ "width": l.width, "height": l.height, "pages": pages }) +} + +fn esc(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">") +} + +/// SVG einer Seite (Papier-mm, viewBox in mm); eine zu grosse Seitennummer wählt die letzte. +pub fn to_svg(report: &Report, page: usize, o: &LayoutOptions) -> String { + let lay = layout(report, o); + let prims = lay.pages.get(page.min(lay.pages.len() - 1)).map(|p| p.as_slice()).unwrap_or(&[]); + let body: Vec = prims + .iter() + .map(|p| match p { + Prim::Line { x1, y1, x2, y2, w } => format!( + "", + js_number(*x1), js_number(*y1), js_number(*x2), js_number(*y2), js_number(*w) + ), + Prim::Text { x, y, s, size, bold, right } => format!( + "{}", + js_number(*x), js_number(*y), to_fixed(size * 0.3528, 3), if *bold { 700 } else { 400 }, if *right { "end" } else { "start" }, esc(s) + ), + }) + .collect(); + let (w, h) = (js_number(lay.width), js_number(lay.height)); + format!( + "\n\n{}\n\n", + body.join("\n") + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample() -> Report { + serde_json::from_value(json!({ + "title": "Flächen", "projectName": "Haus \"A\"; B", + "sections": [{ "heading": "Tabelle", "columns": ["Geschoss", "HNF"], "widths": [3, 2], + "rows": [{ "cells": ["EG", { "n": 12.345, "d": 2 }] }, { "cells": ["Σ", { "n": null, "d": 2 }], "total": true }] }], + "notes": ["Eine Fussnote"] + })) + .unwrap() + } + + #[test] + fn csv_rundreise() { + let csv = to_csv(&sample(), ";"); + assert!(csv.starts_with("Flächen\n\"Haus \"\"A\"\"; B\"\n\nTabelle\nGeschoss;HNF\nEG;12.35\nΣ;\n\n* Eine Fussnote\n")); + let p = parse_csv(&csv, ";"); + assert_eq!(p["projectName"], "Haus \"A\"; B"); + assert_eq!(p["sections"][0]["rows"][0], json!(["EG", 12.35])); + assert_eq!(p["sections"][0]["rows"][1], json!(["Σ", null])); + assert_eq!(p["notes"][0], "Eine Fussnote"); + } + + #[test] + fn seiten_und_svg() { + let l = layout(&sample(), &LayoutOptions::default()); + assert_eq!(l.pages.len(), 1); + let svg = to_svg(&sample(), 0, &LayoutOptions::default()); + assert!(svg.contains("viewBox=\"0 0 297 210\"") && svg.contains("1 / 1")); + let lang = Report { notes: (0..200).map(|i| format!("Notiz {i}")).collect(), ..sample() }; + assert!(layout(&lang, &LayoutOptions::default()).pages.len() > 1); + } +} diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 2a1f9487..5aeb5425 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -17,6 +17,7 @@ pub mod auto_dimensions; pub mod kennzahlen; pub mod flaechen; pub mod room_program; +pub mod area_report; pub mod bulge; pub mod stair; pub mod joins; diff --git a/src-tauri/core/src/web/area_report.rs b/src-tauri/core/src/web/area_report.rs new file mode 100644 index 00000000..bcc8c141 --- /dev/null +++ b/src-tauri/core/src/web/area_report.rs @@ -0,0 +1,40 @@ +//! Bindungen des Flächen-Nachweises (`crate::area_report`): der Bericht reist als JSON (Texte und +//! wenige Zahlen, keine Geometrie). Kaputte Eingaben → leeres Ergebnis ("" bzw. "null"), nie Panic. + +use crate::area_report as ar; +use wasm_bindgen::prelude::wasm_bindgen; + +fn report(json: &str) -> Option { + serde_json::from_str(json).ok() +} + +fn opts(json: &str) -> ar::LayoutOptions { + serde_json::from_str(json).unwrap_or_default() +} + +/// Bericht-JSON → CSV-Text ("" bei kaputtem Bericht). +#[wasm_bindgen] +pub fn area_report_csv(report_json: &str, delimiter: &str) -> String { + report(report_json).map(|r| ar::to_csv(&r, delimiter)).unwrap_or_default() +} + +/// CSV-Text → JSON `{title, projectName, sections, notes}`. +#[wasm_bindgen] +pub fn area_report_parse_csv(text: &str, delimiter: &str) -> String { + ar::parse_csv(text, delimiter).to_string() +} + +/// Bericht-JSON, Optionen-JSON → Layout-JSON `{width, height, pages}` ("null" bei kaputtem Bericht). +#[wasm_bindgen] +pub fn area_report_layout(report_json: &str, opts_json: &str) -> String { + match report(report_json) { + Some(r) => ar::layout_json(&ar::layout(&r, &opts(opts_json))).to_string(), + None => "null".into(), + } +} + +/// Bericht-JSON, Seite, Optionen-JSON → SVG-Text ("" bei kaputtem Bericht). +#[wasm_bindgen] +pub fn area_report_svg(report_json: &str, page: u32, opts_json: &str) -> String { + report(report_json).map(|r| ar::to_svg(&r, page as usize, &opts(opts_json))).unwrap_or_default() +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 52cd564a..49164269 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -41,6 +41,7 @@ mod project_refs; mod commands; mod import; mod cmd_create; +mod area_report; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src/export/areaReport.test.ts b/src/export/areaReport.test.ts index 8210fec4..56a62d1f 100644 --- a/src/export/areaReport.test.ts +++ b/src/export/areaReport.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest"; import { sampleProject } from "../model/sampleProject"; import type { Project, Room, Wall } from "../model/types"; import { computeAreaTable, computeIvhb } from "../analysis/areaTable"; -import { areaReportToCsv, areaReportToSvg, buildAreaReport, buildAreaReportPdf, cellText, layoutAreaReport, parseAreaReportCsv } from "./areaReport"; +import { areaReportToCsv, areaReportToSvg, buildAreaReport, buildAreaReportPdf, layoutAreaReport, parseAreaReportCsv } from "./areaReport"; // Einfaches Haus: Achsen 10 × 8 m, Wände 0.3 m, EG-Räume innen 9.7 × 7.7 m (Handrechnung siehe flaechen.rs). function house(): Project { @@ -83,7 +83,7 @@ describe("Bericht", () => { r.cells.forEach((c, k) => { const got = back.sections[i]!.rows[j]![k]; if (typeof c === "string") expect(got).toBe(c); - else expect(got).toBe(c.n === null ? null : Number(cellText(c))); + else expect(got).toBe(c.n === null ? null : Number(c.n.toFixed(c.d))); }); }); }); diff --git a/src/export/areaReport.ts b/src/export/areaReport.ts index b5441eb0..66321116 100644 --- a/src/export/areaReport.ts +++ b/src/export/areaReport.ts @@ -2,16 +2,17 @@ // SVG und PDF (Vektor, jsPDF) — alle Ausgaben haben dieselbe Quelle. // // • `buildAreaReport`: rechnet über den Kern (`analysis/areaTable.ts`) und beschriftet mit `t()`. -// • `areaReportToCsv` / `parseAreaReportCsv`: CSV mit „;" und Punkt als Dezimaltrenner; die -// Rückwärtsrichtung gibt die Zahlen so zurück, wie sie ausgegeben wurden (gerundet). -// • `layoutAreaReport`: Seitenaufteilung in Papier-mm (A4 quer); `areaReportToSvg` und -// `buildAreaReportPdf` zeichnen dieselben Primitive. +// • `areaReportToCsv` / `parseAreaReportCsv` / `layoutAreaReport` / `areaReportToSvg`: Fassade über den Kern +// (`area_report.rs`): CSV mit „;" und Punkt als Dezimaltrenner (die Rückwärtsrichtung gibt die Zahlen so +// zurück, wie sie ausgegeben wurden), Seitenaufteilung in Papier-mm (A4 quer), SVG. +// • `buildAreaReportPdf` zeichnet dieselben Primitive mit jsPDF. // // Die Flächenarten folgen SIA 416, die Kennziffern der IVHB; Herleitung im Kern (`flaechen.rs`). import { jsPDF } from "jspdf"; import type { Project } from "../model/types"; import { t } from "../i18n"; +import { core } from "../engine/coreWasm"; import { computeAreaTable, computeIvhb } from "../analysis/areaTable"; import type { AreaRow, IvhbOptions } from "../analysis/areaTable"; @@ -113,29 +114,11 @@ export function buildAreaReport(project: Project, opts: AreaReportOptions = {}): return { title: t("areas.title"), projectName: project.name ?? "", sections, notes }; } -// ── CSV ───────────────────────────────────────────────────────────────────── - -function csvField(v: string): string { - return /[",\n\r;]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v; -} - -/** Zelle als Text, so wie sie ausgegeben wird (Punkt als Dezimaltrenner, `null` = leer). */ -export function cellText(c: Cell): string { - if (typeof c === "string") return c; - return c.n === null ? "" : c.n.toFixed(c.d); -} +// ── CSV, Seitenaufteilung, SVG: rechnet der Kern (`core/src/area_report.rs`, Bericht als JSON) ───────────── /** CSV des Berichts: Titel, Projekt, dann je Abschnitt Überschrift, Kopf, Zeilen; Fussnoten mit „* ". */ export function areaReportToCsv(report: AreaReport, delimiter = ";"): string { - const line = (cells: string[]) => cells.map(csvField).join(delimiter); - const out: string[] = [line([report.title]), line([report.projectName]), ""]; - for (const s of report.sections) { - out.push(line([s.heading]), line(s.columns)); - for (const r of s.rows) out.push(line(r.cells.map(cellText))); - out.push(""); - } - for (const n of report.notes) out.push(line([`* ${n}`])); - return out.join("\n") + "\n"; + return core().area_report_csv(JSON.stringify(report), delimiter); } export interface ParsedSection { @@ -152,73 +135,11 @@ export interface ParsedReport { notes: string[]; } -/** Zerlegt CSV-Text in Zeilen von Feldern (Anführungszeichen, Trenner, Zeilenumbruch im Feld). */ -function parseCsvRows(text: string, delimiter: string): string[][] { - const rows: string[][] = []; - let row: string[] = []; - let field = ""; - let quoted = false; - for (let i = 0; i < text.length; i++) { - const c = text[i]!; - if (quoted) { - if (c === '"') { - if (text[i + 1] === '"') { - field += '"'; - i++; - } else quoted = false; - } else field += c; - } else if (c === '"') quoted = true; - else if (c === delimiter) { - row.push(field); - field = ""; - } else if (c === "\n" || c === "\r") { - if (c === "\r" && text[i + 1] === "\n") i++; - row.push(field); - rows.push(row); - row = []; - field = ""; - } else field += c; - } - if (field !== "" || row.length > 0) { - row.push(field); - rows.push(row); - } - return rows; -} - -const NUMBER = /^-?\d+(\.\d+)?$/; - /** Liest eine mit {@link areaReportToCsv} geschriebene CSV zurück (Rundreise). */ export function parseAreaReportCsv(text: string, delimiter = ";"): ParsedReport { - const rows = parseCsvRows(text, delimiter); - // Blöcke zwischen Leerzeilen (eine Leerzeile = ein Feld ""). - const blocks: string[][][] = []; - let cur: string[][] = []; - for (const r of rows) { - if (r.length === 1 && r[0] === "") { - if (cur.length) blocks.push(cur); - cur = []; - } else cur.push(r); - } - if (cur.length) blocks.push(cur); - const head = blocks.shift() ?? []; - const result: ParsedReport = { title: head[0]?.[0] ?? "", projectName: head[1]?.[0] ?? "", sections: [], notes: [] }; - for (const b of blocks) { - if (b[0]?.[0]?.startsWith("* ")) { - for (const r of b) result.notes.push(r[0]!.slice(2)); - continue; - } - result.sections.push({ - heading: b[0]?.[0] ?? "", - columns: b[1] ?? [], - rows: b.slice(2).map((r) => r.map((c, i) => (NUMBER.test(c) ? Number(c) : i === 0 || c !== "" ? c : null))), - }); - } - return result; + return JSON.parse(core().area_report_parse_csv(text, delimiter)) as ParsedReport; } -// ── Seitenaufteilung (Papier-mm) und Ausgabe ───────────────────────────────── - type Prim = | { k: "text"; x: number; y: number; s: string; size: number; bold?: boolean; align?: "left" | "right" } | { k: "line"; x1: number; y1: number; x2: number; y2: number; w: number }; @@ -230,110 +151,14 @@ export interface ReportLayoutOptions { margin?: number; } -/** Zeilenumbruch nach Zeichenzahl (Helvetica ≈ 0.5 em je Zeichen). */ -function wrap(text: string, maxMm: number, sizePt: number): string[] { - const per = Math.max(10, Math.floor(maxMm / (sizePt * 0.3528 * 0.5))); - const words = text.split(/\s+/); - const lines: string[] = []; - let cur = ""; - for (const w of words) { - if (cur && (cur + " " + w).length > per) { - lines.push(cur); - cur = w; - } else cur = cur ? cur + " " + w : w; - } - if (cur) lines.push(cur); - return lines; -} - -/** Teilt den Bericht in Seiten mit Zeichen-Primitiven. */ +/** Teilt den Bericht in Seiten mit Zeichen-Primitiven (Papier-mm). */ export function layoutAreaReport(report: AreaReport, o: ReportLayoutOptions = {}): { width: number; height: number; pages: Prim[][] } { - const width = o.width ?? 297; - const height = o.height ?? 210; - const m = o.margin ?? 12; - const inner = width - 2 * m; - const rowH = 6; - const pages: Prim[][] = [[]]; - let y = m; - const page = () => pages[pages.length - 1]!; - const ensure = (h: number) => { - if (y + h > height - m) { - pages.push([]); - y = m; - } - }; - - page().push({ k: "text", x: m, y: y + 5, s: report.title, size: 15, bold: true }); - y += 8; - if (report.projectName) { - page().push({ k: "text", x: m, y: y + 4, s: report.projectName, size: 10 }); - y += 6; - } - y += 4; - - for (const s of report.sections) { - ensure(rowH * 3 + 6); - page().push({ k: "text", x: m, y: y + 4, s: s.heading, size: 10, bold: true }); - y += 7; - const sum = s.widths.reduce((a, b) => a + b, 0); - const xs: number[] = []; - let x = m; - for (const w of s.widths) { - xs.push(x); - x += (w / sum) * inner; - } - xs.push(x); - const drawRow = (cells: string[], bold: boolean, numeric: boolean[], line: "top" | "bottom" | "none") => { - ensure(rowH); - if (line === "top") page().push({ k: "line", x1: m, y1: y, x2: m + inner, y2: y, w: 0.35 }); - cells.forEach((c, i) => { - const right = numeric[i] === true; - page().push({ k: "text", x: right ? xs[i + 1]! - 1.5 : xs[i]! + 1.5, y: y + 4.2, s: c, size: 8.5, bold, align: right ? "right" : "left" }); - }); - y += rowH; - if (line === "bottom") page().push({ k: "line", x1: m, y1: y, x2: m + inner, y2: y, w: 0.35 }); - }; - const isNum = (i: number) => s.rows.some((r) => typeof r.cells[i] === "object"); - const numeric = s.columns.map((_, i) => isNum(i)); - drawRow(s.columns, true, numeric, "none"); - page().push({ k: "line", x1: m, y1: y, x2: m + inner, y2: y, w: 0.35 }); - for (const r of s.rows) { - drawRow(r.cells.map((c) => (typeof c === "string" ? c : c.n === null ? "–" : c.n.toFixed(c.d))), r.total === true, numeric, r.total ? "top" : "none"); - } - page().push({ k: "line", x1: m, y1: y, x2: m + inner, y2: y, w: 0.35 }); - y += 6; - } - - for (const n of report.notes) { - const lines = wrap(n, inner, 7.5); - ensure(lines.length * 3.4 + 1); - for (const l of lines) { - page().push({ k: "text", x: m, y: y + 2.8, s: l, size: 7.5 }); - y += 3.4; - } - y += 1; - } - const total = pages.length; - pages.forEach((p, i) => { - p.push({ k: "text", x: width - m, y: height - m / 2, s: `${i + 1} / ${total}`, size: 7, align: "right" }); - }); - return { width, height, pages }; + return JSON.parse(core().area_report_layout(JSON.stringify(report), JSON.stringify(o))); } -const esc = (s: string) => s.replace(/&/g, "&").replace(//g, ">"); - /** SVG der ersten Seite (Papier-mm, viewBox in mm); `page` wählt eine andere. */ export function areaReportToSvg(report: AreaReport, page = 0, o: ReportLayoutOptions = {}): string { - const lay = layoutAreaReport(report, o); - const prims = lay.pages[Math.min(page, lay.pages.length - 1)] ?? []; - const body = prims - .map((p) => - p.k === "line" - ? `` - : `${esc(p.s)}`, - ) - .join("\n"); - return `\n\n${body}\n\n`; + return core().area_report_svg(JSON.stringify(report), Math.max(0, page), JSON.stringify(o)); } /** Die eingebaute Helvetica kennt nur WinAnsi: Zeichen ausserhalb ersetzen. */