[61] Raumprogramm: Import aus Tabellen (.xlsx, .ods, .csv)
Leser in Rust (fileio/sheet_import.rs, nur zip + quick-xml, kein neues Crate): xlsx und ods mit Blättern, CSV in UTF-8/UTF-16/Windows-1252 mit Trenner Semikolon, Komma oder Tab; Zahlparser für "1'250,5", "12,5 m²". Zuordnung in io/roomProgramImport.ts (Kopfzeile und Spalten nach Namen de/en/fr, Summen- und Leerzeilen, Zwischentitel als Gruppe), Dialog mit Vorschau, ersetzen oder anhängen, Knopf "Raumprogramm importieren …" im Raumprogramm-Bereich. Neue optionale Felder RoomProgramRow.group/note und Project.roomProgramTolerance (generated.rs von Hand ergänzt, KNOWN_KEYS nachgeführt); Gruppenspalte im Editor. Geprüft: cargo test fileio (echte LibreOffice-xlsx/ods als Fixture), vitest, Browser-Build mit Playwright. Nicht in der Tauri-App getestet. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
16 files changed
+1769
-10
No files matched your search
@@ -814,6 +814,10 @@ pub struct RoomProgramRow {
|
||||
pub area: f64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub count: Option<f64>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub group: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub note: Option<String>,
|
||||
#[serde(flatten)]
|
||||
pub extra: Extra,
|
||||
}
|
||||
@@ -2022,6 +2026,8 @@ pub struct Project {
|
||||
pub drawing_levels: Vec<DrawingLevel>,
|
||||
#[serde(rename = "roomProgram", default, skip_serializing_if = "Option::is_none")]
|
||||
pub room_program: Option<Vec<RoomProgramRow>>,
|
||||
#[serde(rename = "roomProgramTolerance", default, skip_serializing_if = "Option::is_none")]
|
||||
pub room_program_tolerance: Option<f64>,
|
||||
#[serde(rename = "parcelArea", default, skip_serializing_if = "Option::is_none")]
|
||||
pub parcel_area: Option<f64>,
|
||||
#[serde(rename = "sunStudy", default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -2432,6 +2438,12 @@ impl Project {
|
||||
None => Default::default(),
|
||||
};
|
||||
}
|
||||
"roomProgramTolerance" => {
|
||||
self.room_program_tolerance = match v {
|
||||
Some(v) => <Option<f64>>::deserialize(v).map_err(|e| e.to_string())?,
|
||||
None => Default::default(),
|
||||
};
|
||||
}
|
||||
"parcelArea" => {
|
||||
self.parcel_area = match v {
|
||||
Some(v) => <Option<f64>>::deserialize(v).map_err(|e| e.to_string())?,
|
||||
|
||||
@@ -15,14 +15,14 @@ const REQUIRED_ARRAYS: [&str; 3] = ["walls", "layers", "drawingLevels"];
|
||||
const DEFAULT_ARRAYS: [&str; 5] = ["lineStyles", "hatches", "components", "wallTypes", "drawings2d"];
|
||||
|
||||
/// Bekannte Felder von `Project` (für die Meldung unbekannter Felder).
|
||||
const KNOWN_KEYS: [&str; 46] = [
|
||||
const KNOWN_KEYS: [&str; 47] = [
|
||||
"formatVersion", "id", "name", "lineStyles", "textStyles", "hatches", "components", "wallTypes",
|
||||
"ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens",
|
||||
"penSets", "activePenSetId", "customPalettes", "builtinPaletteBanks", "drawingLevels", "layers",
|
||||
"walls", "ceilings", "roofs", "openings", "stairs", "rooms", "drawings2d", "context",
|
||||
"extrudedSolids", "columns", "groups", "parametricWalls", "overrideRules", "viewSnapshots",
|
||||
"viewSnapshotFolders", "layouts", "masterLayouts", "layoutFolders", "referenceElevationMasl",
|
||||
"geoAnchor", "roomProgram", "parcelArea", "sunStudy", "siteRules", "scaleLineWeights",
|
||||
"geoAnchor", "roomProgram", "roomProgramTolerance", "parcelArea", "sunStudy", "siteRules", "scaleLineWeights",
|
||||
];
|
||||
|
||||
/// Ergebnis des Einlesens.
|
||||
|
||||
@@ -40,6 +40,9 @@ pub mod pointcloud_text;
|
||||
pub mod pdf_object;
|
||||
pub mod pdf_vector;
|
||||
pub mod pdf_geom;
|
||||
pub mod sheet_import;
|
||||
#[cfg(feature = "web")]
|
||||
mod web_sheet;
|
||||
#[cfg(feature = "web")]
|
||||
mod web_pdf;
|
||||
|
||||
|
||||
@@ -0,0 +1,852 @@
|
||||
// Tabellen lesen ([61] Raumprogramm-Import): .xlsx, .ods und .csv/.tsv/.txt → Tabellenblätter mit Zellen
|
||||
// (Text/Zahl/leer). Eigener Leser auf den ohnehin vorhandenen Crates `zip` und `quick-xml` (kein
|
||||
// zusätzliches Crate, WASM-tauglich). Nur Werte, keine Formeln/Formate: bei xlsx/ods zählt der
|
||||
// zwischengespeicherte Wert der Zelle; Daten erscheinen als Zahl (Seriennummer).
|
||||
//
|
||||
// Grenzen gegen Zip-Bomben und Riesenblätter: `MAX_ENTRY_BYTES`, `MAX_ROWS`, `MAX_COLS`. Unsinn ergibt
|
||||
// einen Fehler-String, nie einen Panic.
|
||||
//
|
||||
// CSV: Kodierung UTF-8 (mit/ohne BOM), UTF-16 (mit BOM) oder sonst Windows-1252; Trenner Semikolon,
|
||||
// Komma oder Tab, erkannt an den ersten Zeilen (Anführungszeichen beachtet). CSV-Zellen bleiben Text —
|
||||
// ob "1'250,5" eine Zahl ist, entscheidet `parse_number`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Cursor, Read};
|
||||
|
||||
use quick_xml::events::Event;
|
||||
use quick_xml::Reader;
|
||||
|
||||
const MAX_ENTRY_BYTES: u64 = 256 * 1024 * 1024;
|
||||
const MAX_ROWS: usize = 100_000;
|
||||
const MAX_COLS: usize = 512;
|
||||
const MAX_SHEETS: usize = 64;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Cell {
|
||||
Empty,
|
||||
Text(String),
|
||||
Num(f64),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Sheet {
|
||||
pub name: String,
|
||||
pub rows: Vec<Vec<Cell>>,
|
||||
}
|
||||
|
||||
/// Tabelle lesen; das Format wird am Inhalt erkannt (ZIP → xlsx/ods, sonst CSV). `file_name` ist nur Hinweis
|
||||
/// (Endung `.tsv` bevorzugt Tab als Trenner, Blattname bei CSV).
|
||||
pub fn read_sheets(bytes: &[u8], file_name: &str) -> Result<Vec<Sheet>, String> {
|
||||
if bytes.is_empty() {
|
||||
return Err("Leere Datei".into());
|
||||
}
|
||||
if bytes.starts_with(b"PK\x03\x04") {
|
||||
read_zip(bytes)
|
||||
} else {
|
||||
Ok(vec![read_csv(bytes, file_name)])
|
||||
}
|
||||
}
|
||||
|
||||
// ── Zahlen ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Zahl aus Zelltext: Komma oder Punkt als Dezimaltrenner, Apostroph/Leerzeichen/Punkt/Komma als Tausender
|
||||
/// ("1'250,5", "1 250,5", "1.250,5", "1,250.5"), Einheit am Ende ("25 m²", "m2", "qm") wird ignoriert.
|
||||
/// Ein einzelnes Trennzeichen gilt als Dezimaltrenner ("12,5", "12.5", auch "1,250"); mehrere gleiche als
|
||||
/// Tausender. Alles andere → `None`.
|
||||
pub fn parse_number(text: &str) -> Option<f64> {
|
||||
let mut s = text.trim().to_string();
|
||||
let lower = s.to_lowercase();
|
||||
for unit in ["m²", "m2", "m^2", "qm", "㎡", "sqm"] {
|
||||
if lower.ends_with(unit) {
|
||||
// `lower` kann bei exotischen Zeichen andere Bytelängen haben als `s`: über Zeichen kürzen.
|
||||
let n = unit.chars().count();
|
||||
let keep = s.chars().count().saturating_sub(n);
|
||||
s = s.chars().take(keep).collect();
|
||||
break;
|
||||
}
|
||||
}
|
||||
let s = s.trim();
|
||||
if s.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (neg, body) = match s.strip_prefix('-').or_else(|| s.strip_prefix('−')) {
|
||||
Some(r) => (true, r.trim_start()),
|
||||
None => (false, s.strip_prefix('+').unwrap_or(s)),
|
||||
};
|
||||
// Tausender-Apostrophe und Leerzeichen (auch schmal/geschützt) entfernen.
|
||||
let body: String = body
|
||||
.chars()
|
||||
.filter(|c| !matches!(c, '\'' | '’' | 'ʼ' | '´' | '`' | ' ' | '\u{a0}' | '\u{202f}' | '\u{2009}'))
|
||||
.collect();
|
||||
if !body.chars().all(|c| c.is_ascii_digit() || c == '.' || c == ',') || !body.chars().any(|c| c.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let dots = body.matches('.').count();
|
||||
let commas = body.matches(',').count();
|
||||
let normalized = if dots > 0 && commas > 0 {
|
||||
// Das hintere der beiden Zeichen ist der Dezimaltrenner (nur einmal), das andere nur Tausender.
|
||||
let last_dot = body.rfind('.')?;
|
||||
let last_comma = body.rfind(',')?;
|
||||
let (dec, thou) = if last_dot > last_comma { ('.', ',') } else { (',', '.') };
|
||||
if body.matches(dec).count() != 1 || body.rfind(thou)? > body.rfind(dec)? {
|
||||
return None;
|
||||
}
|
||||
body.replace(thou, "").replace(dec, ".")
|
||||
} else if dots > 1 || commas > 1 {
|
||||
// Mehrfach gleiches Zeichen = Tausender: erste Gruppe 1–3 Ziffern, übrige genau 3.
|
||||
let sep = if dots > 1 { '.' } else { ',' };
|
||||
let groups: Vec<&str> = body.split(sep).collect();
|
||||
if groups.iter().skip(1).any(|g| g.len() != 3) || groups[0].is_empty() || groups[0].len() > 3 {
|
||||
return None;
|
||||
}
|
||||
groups.concat()
|
||||
} else {
|
||||
body.replace(',', ".")
|
||||
};
|
||||
let v: f64 = normalized.parse().ok()?;
|
||||
if v.is_finite() {
|
||||
Some(if neg { -v } else { v })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
// ── ZIP: xlsx / ods ─────────────────────────────────────────────────────────
|
||||
|
||||
fn read_zip(bytes: &[u8]) -> Result<Vec<Sheet>, String> {
|
||||
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("Keine Tabellendatei (ZIP): {e}"))?;
|
||||
let mut files: HashMap<String, Vec<u8>> = HashMap::new();
|
||||
for i in 0..zip.len() {
|
||||
let Ok(entry) = zip.by_index(i) else { continue };
|
||||
if entry.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let name = entry.name().replace('\\', "/");
|
||||
// Nur, was wir brauchen (Bilder u. ä. nicht in den Speicher laden).
|
||||
let wanted = name == "content.xml"
|
||||
|| name == "xl/workbook.xml"
|
||||
|| name == "xl/_rels/workbook.xml.rels"
|
||||
|| name == "xl/sharedStrings.xml"
|
||||
|| (name.starts_with("xl/worksheets/") && name.ends_with(".xml"));
|
||||
if !wanted {
|
||||
continue;
|
||||
}
|
||||
let mut buf = Vec::new();
|
||||
entry.take(MAX_ENTRY_BYTES + 1).read_to_end(&mut buf).map_err(|e| format!("ZIP-Eintrag {name}: {e}"))?;
|
||||
if buf.len() as u64 > MAX_ENTRY_BYTES {
|
||||
return Err(format!("ZIP-Eintrag {name} ist zu gross"));
|
||||
}
|
||||
files.insert(name, buf);
|
||||
}
|
||||
if let Some(content) = files.get("content.xml") {
|
||||
return read_ods(content);
|
||||
}
|
||||
if files.contains_key("xl/workbook.xml") {
|
||||
return read_xlsx(&files);
|
||||
}
|
||||
Err("Weder xlsx noch ods: keine Tabelle in der ZIP-Datei".into())
|
||||
}
|
||||
|
||||
fn local(name: &[u8]) -> String {
|
||||
let s = String::from_utf8_lossy(name);
|
||||
match s.rfind(':') {
|
||||
Some(i) => s[i + 1..].to_string(),
|
||||
None => s.into_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn attr(e: &quick_xml::events::BytesStart, key: &str) -> Option<String> {
|
||||
for a in e.attributes().flatten() {
|
||||
if local(a.key.as_ref()) == key {
|
||||
return a.unescape_value().ok().map(|c| c.into_owned());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn strip_bom(b: &[u8]) -> &[u8] {
|
||||
b.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(b)
|
||||
}
|
||||
|
||||
/// "B3" → Spalte 1 (0-basiert); ohne Buchstaben → None.
|
||||
fn col_of(r: &str) -> Option<usize> {
|
||||
let mut c = 0usize;
|
||||
let mut any = false;
|
||||
for ch in r.chars() {
|
||||
if ch.is_ascii_alphabetic() {
|
||||
c = c.checked_mul(26)?.checked_add((ch.to_ascii_uppercase() as u8 - b'A' + 1) as usize)?;
|
||||
any = true;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if any {
|
||||
Some(c - 1)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn set_cell(rows: &mut Vec<Vec<Cell>>, r: usize, c: usize, cell: Cell) {
|
||||
if r >= MAX_ROWS || c >= MAX_COLS {
|
||||
return;
|
||||
}
|
||||
while rows.len() <= r {
|
||||
rows.push(Vec::new());
|
||||
}
|
||||
let row = &mut rows[r];
|
||||
while row.len() <= c {
|
||||
row.push(Cell::Empty);
|
||||
}
|
||||
row[c] = cell;
|
||||
}
|
||||
|
||||
fn trim_rows(rows: &mut Vec<Vec<Cell>>) {
|
||||
for row in rows.iter_mut() {
|
||||
while matches!(row.last(), Some(Cell::Empty)) {
|
||||
row.pop();
|
||||
}
|
||||
}
|
||||
while matches!(rows.last(), Some(r) if r.is_empty()) {
|
||||
rows.pop();
|
||||
}
|
||||
}
|
||||
|
||||
fn entity_text(r: &quick_xml::events::BytesRef) -> String {
|
||||
if let Ok(Some(c)) = r.resolve_char_ref() {
|
||||
c.to_string()
|
||||
} else {
|
||||
quick_xml::escape::resolve_predefined_entity(&String::from_utf8_lossy(r)).unwrap_or("").to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Texte der `<si>`-Elemente (alle `<t>`, ohne Phonetik `<rPh>`).
|
||||
fn read_xlsx_strings(xml: &[u8]) -> Result<Vec<String>, String> {
|
||||
let mut reader = Reader::from_reader(strip_bom(xml));
|
||||
let mut out = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let (mut in_si, mut in_t, mut in_ph) = (false, false, false);
|
||||
loop {
|
||||
match reader.read_event().map_err(|e| format!("XML: {e}"))? {
|
||||
Event::Start(e) => match local(e.name().as_ref()).as_str() {
|
||||
"si" => {
|
||||
in_si = true;
|
||||
cur.clear();
|
||||
}
|
||||
"t" if in_si && !in_ph => in_t = true,
|
||||
"rPh" => in_ph = true,
|
||||
_ => {}
|
||||
},
|
||||
Event::Empty(e) if local(e.name().as_ref()) == "si" => out.push(String::new()),
|
||||
Event::End(e) => match local(e.name().as_ref()).as_str() {
|
||||
"si" => {
|
||||
in_si = false;
|
||||
out.push(std::mem::take(&mut cur));
|
||||
}
|
||||
"t" => in_t = false,
|
||||
"rPh" => in_ph = false,
|
||||
_ => {}
|
||||
},
|
||||
Event::Text(t) if in_t => cur.push_str(&t.decode().map_err(|e| format!("XML: {e}"))?),
|
||||
Event::GeneralRef(r) if in_t => cur.push_str(&entity_text(&r)),
|
||||
Event::Eof => break,
|
||||
_ => {}
|
||||
}
|
||||
if out.len() > 2_000_000 {
|
||||
return Err("Zu viele Texte".into());
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn read_xlsx(files: &HashMap<String, Vec<u8>>) -> Result<Vec<Sheet>, String> {
|
||||
let shared = match files.get("xl/sharedStrings.xml") {
|
||||
Some(x) => read_xlsx_strings(x)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
// Beziehungen: Id → Ziel
|
||||
let mut rels: HashMap<String, String> = HashMap::new();
|
||||
if let Some(x) = files.get("xl/_rels/workbook.xml.rels") {
|
||||
let mut reader = Reader::from_reader(strip_bom(x));
|
||||
loop {
|
||||
match reader.read_event().map_err(|e| format!("XML: {e}"))? {
|
||||
Event::Start(e) | Event::Empty(e) if local(e.name().as_ref()) == "Relationship" => {
|
||||
if let (Some(id), Some(target)) = (attr(&e, "Id"), attr(&e, "Target")) {
|
||||
rels.insert(id, target);
|
||||
}
|
||||
}
|
||||
Event::Eof => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Blätter in Reihenfolge
|
||||
let mut sheet_refs: Vec<(String, String)> = Vec::new();
|
||||
{
|
||||
let wb = files.get("xl/workbook.xml").ok_or("workbook.xml fehlt")?;
|
||||
let mut reader = Reader::from_reader(strip_bom(wb));
|
||||
loop {
|
||||
match reader.read_event().map_err(|e| format!("XML: {e}"))? {
|
||||
Event::Start(e) | Event::Empty(e) if local(e.name().as_ref()) == "sheet" => {
|
||||
sheet_refs.push((attr(&e, "name").unwrap_or_default(), attr(&e, "id").unwrap_or_default()));
|
||||
}
|
||||
Event::Eof => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
sheet_refs.truncate(MAX_SHEETS);
|
||||
let mut out = Vec::new();
|
||||
for (i, (name, rid)) in sheet_refs.iter().enumerate() {
|
||||
let target = rels.get(rid).cloned().unwrap_or_else(|| format!("worksheets/sheet{}.xml", i + 1));
|
||||
let path = match target.strip_prefix('/') {
|
||||
Some(abs) => abs.to_string(),
|
||||
None => format!("xl/{target}"),
|
||||
};
|
||||
let Some(xml) = files.get(&path) else { continue };
|
||||
out.push(Sheet { name: name.clone(), rows: read_xlsx_sheet(xml, &shared)? });
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err("Keine Tabellenblätter gefunden".into());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn read_xlsx_sheet(xml: &[u8], shared: &[String]) -> Result<Vec<Vec<Cell>>, String> {
|
||||
let mut reader = Reader::from_reader(strip_bom(xml));
|
||||
let mut rows: Vec<Vec<Cell>> = Vec::new();
|
||||
let (mut row_i, mut next_col, mut col) = (0usize, 0usize, 0usize);
|
||||
let mut ctype = String::new();
|
||||
let (mut in_v, mut in_t, mut in_cell) = (false, false, false);
|
||||
let (mut vtext, mut ttext) = (String::new(), String::new());
|
||||
loop {
|
||||
match reader.read_event().map_err(|e| format!("XML: {e}"))? {
|
||||
Event::Start(e) => match local(e.name().as_ref()).as_str() {
|
||||
"row" => {
|
||||
if let Some(r) = attr(&e, "r").and_then(|s| s.parse::<usize>().ok()) {
|
||||
row_i = r.saturating_sub(1);
|
||||
}
|
||||
next_col = 0;
|
||||
}
|
||||
"c" => {
|
||||
col = attr(&e, "r").and_then(|r| col_of(&r)).unwrap_or(next_col);
|
||||
next_col = col + 1;
|
||||
ctype = attr(&e, "t").unwrap_or_default();
|
||||
in_cell = true;
|
||||
vtext.clear();
|
||||
ttext.clear();
|
||||
}
|
||||
"v" if in_cell => in_v = true,
|
||||
"t" if in_cell => in_t = true,
|
||||
_ => {}
|
||||
},
|
||||
Event::Empty(e) => {
|
||||
if local(e.name().as_ref()) == "c" {
|
||||
let c = attr(&e, "r").and_then(|r| col_of(&r)).unwrap_or(next_col);
|
||||
next_col = c + 1;
|
||||
}
|
||||
}
|
||||
Event::Text(t) => {
|
||||
if in_v {
|
||||
vtext.push_str(&t.decode().map_err(|e| format!("XML: {e}"))?);
|
||||
} else if in_t {
|
||||
ttext.push_str(&t.decode().map_err(|e| format!("XML: {e}"))?);
|
||||
}
|
||||
}
|
||||
Event::GeneralRef(r) if in_v || in_t => {
|
||||
let s = entity_text(&r);
|
||||
if in_v {
|
||||
vtext.push_str(&s)
|
||||
} else {
|
||||
ttext.push_str(&s)
|
||||
}
|
||||
}
|
||||
Event::End(e) => match local(e.name().as_ref()).as_str() {
|
||||
"v" => in_v = false,
|
||||
"t" => in_t = false,
|
||||
"row" => row_i += 1,
|
||||
"c" => {
|
||||
in_cell = false;
|
||||
let cell = match ctype.as_str() {
|
||||
"s" => vtext
|
||||
.trim()
|
||||
.parse::<usize>()
|
||||
.ok()
|
||||
.and_then(|i| shared.get(i))
|
||||
.map(|s| Cell::Text(s.clone()))
|
||||
.unwrap_or(Cell::Empty),
|
||||
"inlineStr" => Cell::Text(ttext.clone()),
|
||||
"str" | "e" => Cell::Text(vtext.clone()),
|
||||
"b" => Cell::Num(if vtext.trim() == "1" { 1.0 } else { 0.0 }),
|
||||
_ => match vtext.trim().parse::<f64>() {
|
||||
Ok(v) if v.is_finite() => Cell::Num(v),
|
||||
_ if !vtext.trim().is_empty() => Cell::Text(vtext.clone()),
|
||||
_ => Cell::Empty,
|
||||
},
|
||||
};
|
||||
match cell {
|
||||
Cell::Empty => {}
|
||||
Cell::Text(ref s) if s.is_empty() => {}
|
||||
c => set_cell(&mut rows, row_i, col, c),
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Event::Eof => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
trim_rows(&mut rows);
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
fn read_ods(xml: &[u8]) -> Result<Vec<Sheet>, String> {
|
||||
let mut reader = Reader::from_reader(strip_bom(xml));
|
||||
let mut sheets: Vec<Sheet> = Vec::new();
|
||||
let mut cur: Option<Sheet> = None;
|
||||
let (mut row_i, mut col_i) = (0usize, 0usize);
|
||||
let mut row_repeat = 1usize;
|
||||
let mut row_cells: Vec<(usize, Cell)> = Vec::new();
|
||||
let mut cell_val: Option<Cell> = None;
|
||||
let mut cell_repeat = 1usize;
|
||||
let (mut in_cell, mut in_p) = (false, false);
|
||||
let mut para: Vec<String> = Vec::new();
|
||||
let mut depth_table = 0usize; // verschachtelte Tabellen (Unterobjekte) ignorieren
|
||||
loop {
|
||||
let ev = reader.read_event().map_err(|e| format!("XML: {e}"))?;
|
||||
match &ev {
|
||||
Event::Start(e) | Event::Empty(e) => {
|
||||
let is_empty = matches!(ev, Event::Empty(_));
|
||||
match local(e.name().as_ref()).as_str() {
|
||||
"table" => {
|
||||
if depth_table == 0 && cur.is_none() && sheets.len() < MAX_SHEETS {
|
||||
cur = Some(Sheet { name: attr(e, "name").unwrap_or_default(), rows: Vec::new() });
|
||||
row_i = 0;
|
||||
}
|
||||
if !is_empty {
|
||||
depth_table += 1;
|
||||
} else if depth_table == 0 {
|
||||
if let Some(s) = cur.take() {
|
||||
sheets.push(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
"table-row" if depth_table == 1 => {
|
||||
row_repeat = attr(e, "number-rows-repeated").and_then(|s| s.parse().ok()).unwrap_or(1);
|
||||
col_i = 0;
|
||||
row_cells.clear();
|
||||
if is_empty {
|
||||
row_i = row_i.saturating_add(row_repeat);
|
||||
}
|
||||
}
|
||||
"table-cell" | "covered-table-cell" if depth_table == 1 => {
|
||||
cell_repeat = attr(e, "number-columns-repeated").and_then(|s| s.parse().ok()).unwrap_or(1);
|
||||
let vtype = attr(e, "value-type").unwrap_or_default();
|
||||
cell_val = match vtype.as_str() {
|
||||
"float" | "percentage" | "currency" => {
|
||||
attr(e, "value").and_then(|s| s.parse::<f64>().ok()).filter(|v| v.is_finite()).map(Cell::Num)
|
||||
}
|
||||
"boolean" => attr(e, "boolean-value").map(|s| Cell::Num(if s == "true" { 1.0 } else { 0.0 })),
|
||||
"date" => attr(e, "date-value").map(Cell::Text),
|
||||
_ => None,
|
||||
};
|
||||
para.clear();
|
||||
if is_empty {
|
||||
finish_ods_cell(&mut row_cells, &mut col_i, cell_val.take(), ¶, cell_repeat);
|
||||
} else {
|
||||
in_cell = true;
|
||||
}
|
||||
}
|
||||
"p" if in_cell => {
|
||||
in_p = true;
|
||||
para.push(String::new());
|
||||
}
|
||||
"s" if in_p => {
|
||||
// text:s = Leerzeichen (c = Anzahl)
|
||||
let n = attr(e, "c").and_then(|s| s.parse::<usize>().ok()).unwrap_or(1).min(100);
|
||||
if let Some(p) = para.last_mut() {
|
||||
p.push_str(&" ".repeat(n));
|
||||
}
|
||||
}
|
||||
"tab" if in_p => {
|
||||
if let Some(p) = para.last_mut() {
|
||||
p.push('\t');
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Event::Text(t) if in_p => {
|
||||
if let Some(p) = para.last_mut() {
|
||||
p.push_str(&t.decode().map_err(|e| format!("XML: {e}"))?);
|
||||
}
|
||||
}
|
||||
Event::GeneralRef(r) if in_p => {
|
||||
if let Some(p) = para.last_mut() {
|
||||
p.push_str(&entity_text(r));
|
||||
}
|
||||
}
|
||||
Event::End(e) => match local(e.name().as_ref()).as_str() {
|
||||
"p" => in_p = false,
|
||||
"table-cell" | "covered-table-cell" if depth_table == 1 => {
|
||||
in_cell = false;
|
||||
finish_ods_cell(&mut row_cells, &mut col_i, cell_val.take(), ¶, cell_repeat);
|
||||
}
|
||||
"table-row" if depth_table == 1 => {
|
||||
if let Some(s) = cur.as_mut() {
|
||||
if !row_cells.is_empty() {
|
||||
for k in 0..row_repeat.min(1000) {
|
||||
for (c, cell) in &row_cells {
|
||||
set_cell(&mut s.rows, row_i + k, *c, cell.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
row_i = row_i.saturating_add(row_repeat);
|
||||
}
|
||||
"table" => {
|
||||
depth_table = depth_table.saturating_sub(1);
|
||||
if depth_table == 0 {
|
||||
if let Some(mut s) = cur.take() {
|
||||
trim_rows(&mut s.rows);
|
||||
sheets.push(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Event::Eof => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if sheets.is_empty() {
|
||||
return Err("Keine Tabellenblätter gefunden".into());
|
||||
}
|
||||
Ok(sheets)
|
||||
}
|
||||
|
||||
fn finish_ods_cell(row: &mut Vec<(usize, Cell)>, col: &mut usize, val: Option<Cell>, para: &[String], repeat: usize) {
|
||||
let cell = match val {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
let text = para.join("\n");
|
||||
if text.is_empty() {
|
||||
Cell::Empty
|
||||
} else {
|
||||
Cell::Text(text)
|
||||
}
|
||||
}
|
||||
};
|
||||
if cell != Cell::Empty {
|
||||
for k in 0..repeat.min(64) {
|
||||
if *col + k < MAX_COLS {
|
||||
row.push((*col + k, cell.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
*col = col.saturating_add(repeat);
|
||||
}
|
||||
|
||||
// ── CSV ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
const CP1252_HIGH: [char; 32] = [
|
||||
'€', '\u{81}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{8d}', 'Ž', '\u{8f}', '\u{90}', '‘', '’', '“', '”', '•', '–', '—', '˜', '™', 'š', '›', 'œ',
|
||||
'\u{9d}', 'ž', 'Ÿ',
|
||||
];
|
||||
|
||||
/// Bytes → Text: UTF-8 (mit/ohne BOM), UTF-16 mit BOM, sonst Windows-1252.
|
||||
pub fn decode_text(bytes: &[u8]) -> String {
|
||||
if let Some(b) = bytes.strip_prefix(&[0xFF, 0xFE]) {
|
||||
return decode_utf16(b, true);
|
||||
}
|
||||
if let Some(b) = bytes.strip_prefix(&[0xFE, 0xFF]) {
|
||||
return decode_utf16(b, false);
|
||||
}
|
||||
let b = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes);
|
||||
match std::str::from_utf8(b) {
|
||||
Ok(s) => s.to_string(),
|
||||
Err(_) => b
|
||||
.iter()
|
||||
.map(|&x| match x {
|
||||
0x80..=0x9f => CP1252_HIGH[(x - 0x80) as usize],
|
||||
_ => x as char, // 0x00–0x7f ASCII, 0xa0–0xff = Latin-1 = gleiche Codepunkte
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_utf16(b: &[u8], le: bool) -> String {
|
||||
let units: Vec<u16> = b
|
||||
.chunks_exact(2)
|
||||
.map(|c| if le { u16::from_le_bytes([c[0], c[1]]) } else { u16::from_be_bytes([c[0], c[1]]) })
|
||||
.collect();
|
||||
String::from_utf16_lossy(&units)
|
||||
}
|
||||
|
||||
/// Trenner erkennen: in den ersten Zeilen (ausserhalb von Anführungszeichen) je Kandidat zählen; die meisten
|
||||
/// Zeilen mit dem Trenner (und dann die kleinste Anzahl je Zeile) gewinnen. Gleichstand: Reihenfolge der
|
||||
/// Kandidaten (Semikolon, Tab, Komma; bei `.tsv` zuerst Tab).
|
||||
fn detect_delimiter(text: &str, prefer_tab: bool) -> char {
|
||||
let candidates: [char; 3] = if prefer_tab { ['\t', ';', ','] } else { [';', '\t', ','] };
|
||||
let mut best = (candidates[0], 0usize);
|
||||
for &d in &candidates {
|
||||
let mut counts: Vec<usize> = Vec::new();
|
||||
let (mut n, mut quoted) = (0usize, false);
|
||||
for ch in text.chars() {
|
||||
if ch == '"' {
|
||||
quoted = !quoted;
|
||||
} else if !quoted && ch == d {
|
||||
n += 1;
|
||||
} else if !quoted && ch == '\n' {
|
||||
counts.push(n);
|
||||
n = 0;
|
||||
if counts.len() >= 12 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if counts.len() < 12 {
|
||||
counts.push(n);
|
||||
}
|
||||
let nonzero: Vec<usize> = counts.iter().copied().filter(|&c| c > 0).collect();
|
||||
let Some(&min) = nonzero.iter().min() else { continue };
|
||||
let score = nonzero.len() * 10 + min.min(9);
|
||||
if score > best.1 {
|
||||
best = (d, score);
|
||||
}
|
||||
}
|
||||
best.0
|
||||
}
|
||||
|
||||
fn push_field(row: &mut Vec<String>, field: &mut String, was_quoted: &mut bool) {
|
||||
let f = std::mem::take(field);
|
||||
if row.len() < MAX_COLS {
|
||||
row.push(if *was_quoted { f } else { f.trim().to_string() });
|
||||
}
|
||||
*was_quoted = false;
|
||||
}
|
||||
|
||||
fn parse_csv_text(text: &str, delim: char) -> Vec<Vec<String>> {
|
||||
let mut rows: Vec<Vec<String>> = Vec::new();
|
||||
let mut row: Vec<String> = Vec::new();
|
||||
let mut field = String::new();
|
||||
let (mut quoted, mut was_quoted) = (false, false);
|
||||
let mut chars = text.chars().peekable();
|
||||
while let Some(ch) = chars.next() {
|
||||
if quoted {
|
||||
if ch == '"' {
|
||||
if chars.peek() == Some(&'"') {
|
||||
field.push('"');
|
||||
chars.next();
|
||||
} else {
|
||||
quoted = false;
|
||||
}
|
||||
} else {
|
||||
field.push(ch);
|
||||
}
|
||||
} else if ch == '"' && field.trim().is_empty() {
|
||||
field.clear();
|
||||
quoted = true;
|
||||
was_quoted = true;
|
||||
} else if ch == delim {
|
||||
push_field(&mut row, &mut field, &mut was_quoted);
|
||||
} else if ch == '\n' || ch == '\r' {
|
||||
if ch == '\r' && chars.peek() == Some(&'\n') {
|
||||
chars.next();
|
||||
}
|
||||
push_field(&mut row, &mut field, &mut was_quoted);
|
||||
rows.push(std::mem::take(&mut row));
|
||||
if rows.len() >= MAX_ROWS {
|
||||
return rows;
|
||||
}
|
||||
} else {
|
||||
field.push(ch);
|
||||
}
|
||||
}
|
||||
if !field.is_empty() || !row.is_empty() || was_quoted {
|
||||
push_field(&mut row, &mut field, &mut was_quoted);
|
||||
rows.push(row);
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
fn read_csv(bytes: &[u8], file_name: &str) -> Sheet {
|
||||
let text = decode_text(bytes);
|
||||
let delim = detect_delimiter(&text, file_name.to_lowercase().ends_with(".tsv"));
|
||||
let mut rows: Vec<Vec<Cell>> = parse_csv_text(&text, delim)
|
||||
.into_iter()
|
||||
.map(|r| r.into_iter().map(|f| if f.is_empty() { Cell::Empty } else { Cell::Text(f) }).collect())
|
||||
.collect();
|
||||
trim_rows(&mut rows);
|
||||
let base = file_name.rsplit(['/', '\\']).next().unwrap_or(file_name);
|
||||
let name = base.rsplit_once('.').map(|(n, _)| n).unwrap_or(base);
|
||||
Sheet { name: if name.is_empty() { "CSV".into() } else { name.to_string() }, rows }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
|
||||
fn t(s: &str) -> Cell {
|
||||
Cell::Text(s.into())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zahlen_formate() {
|
||||
assert_eq!(parse_number("12"), Some(12.0));
|
||||
assert_eq!(parse_number("12,5"), Some(12.5));
|
||||
assert_eq!(parse_number("12.5"), Some(12.5));
|
||||
assert_eq!(parse_number("1'250,5"), Some(1250.5));
|
||||
assert_eq!(parse_number("1’250.5"), Some(1250.5));
|
||||
assert_eq!(parse_number("1 250,5"), Some(1250.5));
|
||||
assert_eq!(parse_number("1.250,5"), Some(1250.5));
|
||||
assert_eq!(parse_number("1,250.5"), Some(1250.5));
|
||||
assert_eq!(parse_number("1,250,000"), Some(1_250_000.0));
|
||||
assert_eq!(parse_number("1'250'000"), Some(1_250_000.0));
|
||||
assert_eq!(parse_number("25 m²"), Some(25.0));
|
||||
assert_eq!(parse_number("25,5m2"), Some(25.5));
|
||||
assert_eq!(parse_number("-3,5"), Some(-3.5));
|
||||
assert_eq!(parse_number(""), None);
|
||||
assert_eq!(parse_number("abc"), None);
|
||||
assert_eq!(parse_number("1.2.3"), None);
|
||||
assert_eq!(parse_number("12,5,3"), None);
|
||||
assert_eq!(parse_number("-"), None);
|
||||
assert_eq!(parse_number("."), None);
|
||||
assert_eq!(parse_number("1e5"), None);
|
||||
assert_eq!(parse_number("İİİ"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_trenner_und_kodierung() {
|
||||
let s = read_sheets("Raum;Fläche;Anzahl\nKüche;12,5;1\n\"Bad; WC\";6;2\n".as_bytes(), "p.csv").unwrap();
|
||||
assert_eq!(s[0].name, "p");
|
||||
assert_eq!(s[0].rows[1], vec![t("Küche"), t("12,5"), t("1")]);
|
||||
assert_eq!(s[0].rows[2][0], t("Bad; WC"));
|
||||
let s = read_sheets(b"Raum,Fl\xe4che,Anzahl\nK\xfcche,12.5,1\n", "p.csv").unwrap();
|
||||
assert_eq!(s[0].rows[0], vec![t("Raum"), t("Fläche"), t("Anzahl")]);
|
||||
assert_eq!(s[0].rows[1][0], t("Küche"));
|
||||
// Windows-1252-Sonderzeichen: Euro und m²-Hochzahl (0xB2).
|
||||
let s = read_sheets(b"a\x80;m\xb2\n", "x.csv").unwrap();
|
||||
assert_eq!(s[0].rows[0], vec![t("a€"), t("m²")]);
|
||||
let s = read_sheets("Raum\tFläche\nKüche\t12,5\n".as_bytes(), "p.tsv").unwrap();
|
||||
assert_eq!(s[0].rows[1], vec![t("Küche"), t("12,5")]);
|
||||
// BOM + Zeilenumbruch in Anführungszeichen + CRLF
|
||||
let s = read_sheets(b"\xef\xbb\xbfA;B\r\n\"x\ny\";2\r\n", "q.csv").unwrap();
|
||||
assert_eq!(s[0].rows[1], vec![t("x\ny"), t("2")]);
|
||||
// Dezimalkomma in Semikolon-Datei darf nicht als Trenner gelten.
|
||||
let s = read_sheets(b"A;B\nx;1,5\ny;2,5\n", "q.csv").unwrap();
|
||||
assert_eq!(s[0].rows[1], vec![t("x"), t("1,5")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_utf16() {
|
||||
let mut b = vec![0xFF, 0xFE];
|
||||
for u in "A\tB\nä\t1\n".encode_utf16() {
|
||||
b.extend_from_slice(&u.to_le_bytes());
|
||||
}
|
||||
let s = read_sheets(&b, "u.txt").unwrap();
|
||||
assert_eq!(s[0].rows[1], vec![t("ä"), t("1")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsinn_ist_fehler_oder_leer() {
|
||||
assert!(read_sheets(b"", "x.csv").is_err());
|
||||
assert!(read_sheets(b"PK\x03\x04kaputt", "x.xlsx").is_err());
|
||||
let s = read_sheets(&[0u8, 1, 2, 255, 254], "x.csv").unwrap();
|
||||
assert_eq!(s.len(), 1);
|
||||
}
|
||||
|
||||
fn zip_of(files: &[(&str, &str)]) -> Vec<u8> {
|
||||
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
for (n, c) in files {
|
||||
z.start_file(*n, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
z.write_all(c.as_bytes()).unwrap();
|
||||
}
|
||||
z.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xlsx_lesen() {
|
||||
let bytes = zip_of(&[
|
||||
("[Content_Types].xml", "<Types/>"),
|
||||
(
|
||||
"xl/workbook.xml",
|
||||
r#"<workbook xmlns="x" xmlns:r="r"><sheets><sheet name="Programm" sheetId="1" r:id="rId1"/><sheet name="Leer" sheetId="2" r:id="rId2"/></sheets></workbook>"#,
|
||||
),
|
||||
(
|
||||
"xl/_rels/workbook.xml.rels",
|
||||
r#"<Relationships><Relationship Id="rId1" Type="t" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="t" Target="/xl/worksheets/sheet2.xml"/></Relationships>"#,
|
||||
),
|
||||
(
|
||||
"xl/sharedStrings.xml",
|
||||
r#"<sst><si><t>Raum</t></si><si><t>Fläche</t></si><si><r><t>Wohn</t></r><r><t xml:space="preserve">en & Essen</t></r></si><si><t>Bad</t><rPh><t>x</t></rPh></si></sst>"#,
|
||||
),
|
||||
(
|
||||
"xl/worksheets/sheet1.xml",
|
||||
r#"<worksheet><sheetData>
|
||||
<row r="1"><c r="A1" t="s"><v>0</v></c><c r="B1" t="s"><v>1</v></c><c r="D1" t="inlineStr"><is><t>Bem</t></is></c></row>
|
||||
<row r="2"><c r="A2" t="s"><v>2</v></c><c r="B2"><v>28.5</v></c></row>
|
||||
<row r="4"><c r="B4"><f>B2*2</f><v>57</v></c><c r="A4" t="s"><v>3</v></c><c r="C4"/></row>
|
||||
</sheetData></worksheet>"#,
|
||||
),
|
||||
("xl/worksheets/sheet2.xml", "<worksheet><sheetData/></worksheet>"),
|
||||
]);
|
||||
let s = read_sheets(&bytes, "p.xlsx").unwrap();
|
||||
assert_eq!(s.len(), 2);
|
||||
assert_eq!(s[0].name, "Programm");
|
||||
assert_eq!(s[0].rows[0], vec![t("Raum"), t("Fläche"), Cell::Empty, t("Bem")]);
|
||||
assert_eq!(s[0].rows[1], vec![t("Wohnen & Essen"), Cell::Num(28.5)]);
|
||||
assert!(s[0].rows[2].is_empty());
|
||||
assert_eq!(s[0].rows[3], vec![t("Bad"), Cell::Num(57.0)]);
|
||||
assert!(s[1].rows.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ods_lesen() {
|
||||
let content = r#"<?xml version="1.0"?><office:document-content xmlns:office="o" xmlns:table="t" xmlns:text="x"><office:body><office:spreadsheet>
|
||||
<table:table table:name="Blatt1">
|
||||
<table:table-row><table:table-cell office:value-type="string"><text:p>Raum</text:p></table:table-cell><table:table-cell office:value-type="string"><text:p>Fläche</text:p></table:table-cell></table:table-row>
|
||||
<table:table-row><table:table-cell office:value-type="string"><text:p>Wohnen</text:p><text:p>zwei</text:p></table:table-cell><table:table-cell office:value-type="float" office:value="28.5"><text:p>28,5</text:p></table:table-cell></table:table-row>
|
||||
<table:table-row table:number-rows-repeated="3"><table:table-cell table:number-columns-repeated="2"/></table:table-row>
|
||||
<table:table-row><table:table-cell table:number-columns-repeated="100"/><table:table-cell office:value-type="float" office:value="7"/></table:table-row>
|
||||
<table:table-row table:number-rows-repeated="1048000"><table:table-cell table:number-columns-repeated="16384"/></table:table-row>
|
||||
</table:table>
|
||||
<table:table table:name="Zwei"><table:table-row><table:table-cell office:value-type="string"><text:p>a<text:s text:c="2"/>b</text:p></table:table-cell></table:table-row></table:table>
|
||||
</office:spreadsheet></office:body></office:document-content>"#;
|
||||
let bytes = zip_of(&[("mimetype", "application/vnd.oasis.opendocument.spreadsheet"), ("content.xml", content)]);
|
||||
let s = read_sheets(&bytes, "p.ods").unwrap();
|
||||
assert_eq!(s.len(), 2);
|
||||
assert_eq!(s[0].name, "Blatt1");
|
||||
assert_eq!(s[0].rows[0], vec![t("Raum"), t("Fläche")]);
|
||||
assert_eq!(s[0].rows[1], vec![t("Wohnen\nzwei"), Cell::Num(28.5)]);
|
||||
assert_eq!(s[0].rows.len(), 6);
|
||||
assert_eq!(s[0].rows[5].len(), 101);
|
||||
assert_eq!(s[0].rows[5][100], Cell::Num(7.0));
|
||||
assert_eq!(s[1].rows[0], vec![t("a b")]);
|
||||
}
|
||||
|
||||
/// Echte Dateien aus LibreOffice (xlsx, ods) mit Formel-Summe, zwei Blättern und Zahl-als-Text.
|
||||
fn check_fixture(bytes: &[u8], name: &str) {
|
||||
let s = read_sheets(bytes, name).unwrap();
|
||||
assert_eq!(s.len(), 2);
|
||||
assert_eq!(s[0].name, "Programm");
|
||||
assert_eq!(s[1].name, "Notizen");
|
||||
let r = &s[0].rows;
|
||||
assert_eq!(r[0], vec![t("Raumprogramm Schulhaus Muster")]);
|
||||
assert!(r[1].is_empty());
|
||||
assert_eq!(r[2], vec![t("Raum"), t("Fläche [m²]"), t("Anzahl"), t("Flächenart"), t("Gruppe"), t("Bemerkung")]);
|
||||
assert_eq!(r[3], vec![t("Klassenzimmer"), Cell::Num(72.0), Cell::Num(6.0), t("HNF"), t("Unterricht"), t("Südlicht")]);
|
||||
assert_eq!(r[4][1], Cell::Num(36.5));
|
||||
assert_eq!(r[6][1], t("18,5")); // als Text eingegeben
|
||||
// Summenzelle: zwischengespeicherter Wert der Formel (72·6 + 36.5·4 + 60 + 18,5-Text zählt 0 → 638).
|
||||
assert!(matches!(r[7][1], Cell::Num(v) if v > 600.0), "Formelwert fehlt: {:?}", r[7]);
|
||||
assert_eq!(s[1].rows, vec![vec![t("nur Text")]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn echte_dateien() {
|
||||
check_fixture(include_bytes!("../testdata/raumprogramm.xlsx"), "p.xlsx");
|
||||
check_fixture(include_bytes!("../testdata/raumprogramm.ods"), "p.ods");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// WASM-Bindung des Tabellen-Lesers (`sheet_import.rs`, [61]): Bytes rein, JSON raus
|
||||
// (`[{"name":…,"rows":[[null|"text"|1.5,…],…]}]`). Kaputte Dateien → JS-Fehler mit Meldung (kein Panic).
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
use crate::sheet_import::{parse_number, read_sheets, Cell};
|
||||
|
||||
/// Tabellenblätter einer .xlsx/.ods/.csv-Datei als JSON-Text.
|
||||
#[wasm_bindgen]
|
||||
pub fn sheet_read(bytes: Vec<u8>, file_name: String) -> Result<String, JsValue> {
|
||||
let sheets = read_sheets(&bytes, &file_name).map_err(|e| JsValue::from_str(&e))?;
|
||||
let out: Vec<Value> = sheets
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let rows: Vec<Value> = s
|
||||
.rows
|
||||
.iter()
|
||||
.map(|r| {
|
||||
Value::Array(
|
||||
r.iter()
|
||||
.map(|c| match c {
|
||||
Cell::Empty => Value::Null,
|
||||
Cell::Text(t) => Value::String(t.clone()),
|
||||
Cell::Num(n) => json!(n),
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
json!({ "name": s.name, "rows": rows })
|
||||
})
|
||||
.collect();
|
||||
Ok(Value::Array(out).to_string())
|
||||
}
|
||||
|
||||
/// Zahl aus Zelltext ("1'250,5", "12,5 m²") oder NaN.
|
||||
#[wasm_bindgen]
|
||||
pub fn sheet_parse_number(text: String) -> f64 {
|
||||
parse_number(&text).unwrap_or(f64::NAN)
|
||||
}
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -24,6 +24,8 @@ export type { CoreOp } from "./ops";
|
||||
export type { Project, DrawingLevel } from "../model/types";
|
||||
export { computeKennzahlen, checkRoomProgram, solidVolume } from "../analysis/kennzahlen";
|
||||
export type { Kennzahlen, ProgramCheck } from "../analysis/kennzahlen";
|
||||
export { readSheetFile, suggestMapping, mapRows, importedRows, applyRoomProgram, cellNumber, cellText, detectHeaderRow, parseKind, PROGRAM_FIELDS } from "../io/roomProgramImport";
|
||||
export type { SheetData, SheetCell, Mapping, ColumnMap, ProgramField, ImportLine, ImportMode, SkipReason } from "../io/roomProgramImport";
|
||||
export { computeAreaTable, computeIvhb } from "../analysis/areaTable";
|
||||
export type { AreaTable, AreaRow, Ivhb, IvhbOptions, AgfBasis } from "../analysis/areaTable";
|
||||
export { buildAreaReport, areaReportToCsv, parseAreaReportCsv, areaReportToSvg, buildAreaReportPdf } from "../export/areaReport";
|
||||
|
||||
@@ -1995,6 +1995,39 @@ export const de = {
|
||||
"program.status.missing": "fehlt",
|
||||
"program.status.tooFew": "zu wenige",
|
||||
"program.status.tooMany": "zu viele",
|
||||
"program.field.name": "Name",
|
||||
"program.field.area": "Fläche je Raum",
|
||||
"program.field.count": "Anzahl",
|
||||
"program.field.kind": "Flächenart",
|
||||
"program.field.group": "Gruppe / Geschoss",
|
||||
"program.field.note": "Bemerkung",
|
||||
"program.import": "Raumprogramm importieren …",
|
||||
"program.import.title": "Raumprogramm importieren",
|
||||
"program.import.sheet": "Tabellenblatt",
|
||||
"program.import.header": "Kopfzeile",
|
||||
"program.import.header.none": "keine",
|
||||
"program.import.row": "Zeile {n}",
|
||||
"program.import.columns": "Spalten zuordnen",
|
||||
"program.import.columnOf": "Inhalt der Spalte {col}",
|
||||
"program.import.state": "Übernahme",
|
||||
"program.import.skip.empty": "leer",
|
||||
"program.import.skip.sum": "Summe, übersprungen",
|
||||
"program.import.skip.noName": "ohne Name, übersprungen",
|
||||
"program.import.skip.noArea": "ohne Fläche, übersprungen",
|
||||
"program.import.skip.header": "Kopfzeile",
|
||||
"program.import.skip.group": "Zwischentitel → Gruppe",
|
||||
"program.import.skipSums": "Summenzeilen überspringen",
|
||||
"program.import.mode.replace": "Bestehendes Raumprogramm ersetzen",
|
||||
"program.import.mode.append": "An das bestehende anhängen ({n} Zeilen)",
|
||||
"program.import.summary": "{n} Zeilen werden übernommen, {s} übersprungen.",
|
||||
"program.import.needNameArea": "Bitte mindestens die Spalten Name und Fläche zuordnen.",
|
||||
"program.import.unknownKind": "Flächenart «{kind}» unbekannt",
|
||||
"program.import.unknownKinds": "{n} Zeilen mit unbekannter Flächenart werden ohne Flächenart übernommen.",
|
||||
"program.import.more": "… {n} weitere Zeilen",
|
||||
"program.import.confirm": "Importieren",
|
||||
"program.import.readFail": "Die Tabelle konnte nicht gelesen werden: {msg}",
|
||||
"program.import.empty": "Die Datei enthält keine Zellen.",
|
||||
"program.import.done": "{n} Programmzeilen importiert.",
|
||||
"sun.show": "Schatten im Grundriss zeigen",
|
||||
"sun.time": "Uhrzeit",
|
||||
"sun.equinox": "Tagundnachtgleiche",
|
||||
|
||||
@@ -1945,6 +1945,39 @@ export const en: Record<TranslationKey, string> = {
|
||||
"program.status.missing": "missing",
|
||||
"program.status.tooFew": "too few",
|
||||
"program.status.tooMany": "too many",
|
||||
"program.field.name": "Name",
|
||||
"program.field.area": "Area per room",
|
||||
"program.field.count": "Count",
|
||||
"program.field.kind": "Area type",
|
||||
"program.field.group": "Group / floor",
|
||||
"program.field.note": "Note",
|
||||
"program.import": "Import room program …",
|
||||
"program.import.title": "Import room program",
|
||||
"program.import.sheet": "Sheet",
|
||||
"program.import.header": "Header row",
|
||||
"program.import.header.none": "none",
|
||||
"program.import.row": "Row {n}",
|
||||
"program.import.columns": "Map columns",
|
||||
"program.import.columnOf": "Content of column {col}",
|
||||
"program.import.state": "Result",
|
||||
"program.import.skip.empty": "empty",
|
||||
"program.import.skip.sum": "total, skipped",
|
||||
"program.import.skip.noName": "no name, skipped",
|
||||
"program.import.skip.noArea": "no area, skipped",
|
||||
"program.import.skip.header": "header",
|
||||
"program.import.skip.group": "heading → group",
|
||||
"program.import.skipSums": "Skip total rows",
|
||||
"program.import.mode.replace": "Replace the existing room program",
|
||||
"program.import.mode.append": "Append to the existing one ({n} rows)",
|
||||
"program.import.summary": "{n} rows will be imported, {s} skipped.",
|
||||
"program.import.needNameArea": "Please map at least the Name and Area columns.",
|
||||
"program.import.unknownKind": "area type “{kind}” unknown",
|
||||
"program.import.unknownKinds": "{n} rows with an unknown area type are imported without one.",
|
||||
"program.import.more": "… {n} more rows",
|
||||
"program.import.confirm": "Import",
|
||||
"program.import.readFail": "The spreadsheet could not be read: {msg}",
|
||||
"program.import.empty": "The file contains no cells.",
|
||||
"program.import.done": "{n} program rows imported.",
|
||||
"sun.show": "Show shadows in plan",
|
||||
"sun.time": "Time of day",
|
||||
"sun.equinox": "Equinox",
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import "../engine/fileioWasm.setup";
|
||||
import { applyRoomProgram, cellNumber, detectHeaderRow, importedRows, mapRows, parseKind, readSheetFile, suggestMapping } from "./roomProgramImport";
|
||||
import type { SheetCell } from "./roomProgramImport";
|
||||
import { emptyProject } from "../model/sampleProject";
|
||||
|
||||
const enc = (s: string) => new TextEncoder().encode(s);
|
||||
|
||||
describe("cellNumber", () => {
|
||||
it("Zahlen mit Komma, Apostroph und Einheit", () => {
|
||||
expect(cellNumber(12.5)).toBe(12.5);
|
||||
expect(cellNumber("1'250,5")).toBe(1250.5);
|
||||
expect(cellNumber("28,5 m²")).toBe(28.5);
|
||||
expect(cellNumber("abc")).toBeNull();
|
||||
expect(cellNumber("")).toBeNull();
|
||||
expect(cellNumber(null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("readSheetFile", () => {
|
||||
it("liest CSV mit Semikolon und Dezimalkomma", async () => {
|
||||
const sheets = await readSheetFile(enc("Raum;Fläche;Anzahl\nWohnen;28,5;1\n"), "p.csv");
|
||||
expect(sheets).toHaveLength(1);
|
||||
expect(sheets[0].rows[1]).toEqual(["Wohnen", "28,5", "1"]);
|
||||
});
|
||||
it("kaputte Datei → Fehler statt Absturz", async () => {
|
||||
await expect(readSheetFile(enc(""), "x.xlsx")).rejects.toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
const T: SheetCell[][] = [
|
||||
["Raumprogramm Schulhaus", null, null, null],
|
||||
[null, null, null, null],
|
||||
["Raum", "Fläche [m²]", "Anzahl", "Bemerkung", "Flächenart"],
|
||||
["Unterricht", null, null, null],
|
||||
["Klassenzimmer", "72,0", 6, "hell", "HNF"],
|
||||
["Gruppenraum", 36, 4, null, "Hauptnutzfläche"],
|
||||
["Total", 576, 10, null, null],
|
||||
["Lehrerzimmer", "1'050,5", null, null, "xyz"],
|
||||
[null, null, null, null, null],
|
||||
[null, 1626.5, null, null, null],
|
||||
];
|
||||
|
||||
describe("Zuordnung", () => {
|
||||
it("erkennt Kopfzeile und Spalten", () => {
|
||||
expect(detectHeaderRow(T)).toBe(2);
|
||||
const m = suggestMapping(T);
|
||||
expect(m.headerRow).toBe(2);
|
||||
expect(m.columns).toEqual({ name: 0, area: 1, count: 2, note: 3, kind: 4 });
|
||||
});
|
||||
it("englische und französische Überschriften", () => {
|
||||
expect(suggestMapping([["Room name", "Area (m2)", "Qty"], ["A", 10, 1]]).columns).toEqual({ name: 0, area: 1, count: 2 });
|
||||
expect(suggestMapping([["Désignation", "Surface", "Nombre", "Étage"], ["A", 10, 1, "EG"]]).columns).toEqual({ name: 0, area: 1, count: 2, group: 3 });
|
||||
expect(suggestMapping([["Bezeichnung", "m2", "Stk"], ["A", 10, 1]]).columns).toEqual({ name: 0, area: 1, count: 2 });
|
||||
});
|
||||
it("ohne Kopfzeile: Spalten aus den Daten", () => {
|
||||
const m = suggestMapping([["Küche", 12.5, 1], ["Bad", 6, 2], ["Zimmer", 14, 3]]);
|
||||
expect(m.headerRow).toBeNull();
|
||||
expect(m.columns).toEqual({ name: 0, area: 1, count: 2 });
|
||||
});
|
||||
it("Zeilen: Gruppentitel, Summenzeilen, Flächenart, Komma/Apostroph", () => {
|
||||
const m = suggestMapping(T);
|
||||
const lines = mapRows(T, m);
|
||||
const rows = importedRows(lines);
|
||||
expect(rows).toEqual([
|
||||
{ name: "Klassenzimmer", area: 72, count: 6, siaCategory: "HNF", group: "Unterricht", note: "hell" },
|
||||
{ name: "Gruppenraum", area: 36, count: 4, siaCategory: "HNF", group: "Unterricht" },
|
||||
{ name: "Lehrerzimmer", area: 1050.5, group: "Unterricht" },
|
||||
]);
|
||||
const by = Object.fromEntries(lines.map((l) => [l.sheetRow, l]));
|
||||
expect(by[3].groupHeading).toBe("Unterricht");
|
||||
expect(by[6].skip).toBe("sum");
|
||||
expect(by[7].unknownKind).toBe("xyz");
|
||||
expect(by[8].skip).toBe("empty");
|
||||
expect(by[9].skip).toBe("noName"); // Summe ohne Name, aber nicht gleich der laufenden Summe
|
||||
expect(mapRows(T, m, { skipSums: false }).find((l) => l.sheetRow === 6)?.row?.name).toBe("Total");
|
||||
});
|
||||
it("Summe ohne Namen, gleich der laufenden Summe, wird übersprungen", () => {
|
||||
const rows: SheetCell[][] = [["Raum", "Fläche"], ["A", 10], ["B", 20], [null, 30], ["C", 5]];
|
||||
const lines = mapRows(rows, suggestMapping(rows));
|
||||
expect(lines[3].skip).toBe("sum");
|
||||
expect(importedRows(lines).map((r) => r.name)).toEqual(["A", "B", "C"]);
|
||||
});
|
||||
it("Gruppenspalte hat Vorrang vor Zwischentiteln", () => {
|
||||
const rows: SheetCell[][] = [["Raum", "Fläche", "Geschoss"], ["A", 10, "EG"], ["B", 20, "OG"]];
|
||||
expect(importedRows(mapRows(rows, suggestMapping(rows))).map((r) => r.group)).toEqual(["EG", "OG"]);
|
||||
});
|
||||
it("Flächenart erkennen", () => {
|
||||
expect(parseKind("HNF 1.1")).toBe("HNF");
|
||||
expect(parseKind("Verkehrsfläche")).toBe("VF");
|
||||
expect(parseKind("foo")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyRoomProgram", () => {
|
||||
const p = { ...emptyProject, roomProgram: [{ name: "Alt", area: 5 }] };
|
||||
it("ersetzen und anhängen", () => {
|
||||
expect(applyRoomProgram(p, [{ name: "Neu", area: 9 }], "replace").roomProgram).toEqual([{ name: "Neu", area: 9 }]);
|
||||
expect(applyRoomProgram(p, [{ name: "Neu", area: 9 }], "append").roomProgram).toHaveLength(2);
|
||||
expect(applyRoomProgram(p, [], "replace")).toBe(p);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,291 @@
|
||||
// Raumprogramm aus einer Tabelle importieren ([61]): .xlsx, .ods, .csv/.tsv.
|
||||
//
|
||||
// • Lesen der Datei und Zahlen-Parser stehen im Rust-Modul `fileio/src/sheet_import.rs`
|
||||
// (`readSheetFile`, `cellNumber`).
|
||||
// • Hier die Zuordnung: Kopfzeile erkennen, Spalten nach Spaltennamen vorschlagen (de/en/fr),
|
||||
// Zeilen in `RoomProgramRow`s abbilden (Summenzeilen und Leerzeilen überspringen, Gruppenzeilen
|
||||
// als Gruppe der folgenden Zeilen) und ins Projekt einfügen (ersetzen oder anhängen).
|
||||
// Reine Funktionen ohne UI; der Dialog ist `ui/RoomProgramImportDialog.tsx`.
|
||||
|
||||
import type { Project, RoomProgramRow, SiaCategory } from "../model/types";
|
||||
import { fileio, loadFileio } from "../engine/fileioWasm";
|
||||
|
||||
export type SheetCell = string | number | null;
|
||||
|
||||
export interface SheetData {
|
||||
name: string;
|
||||
rows: SheetCell[][];
|
||||
}
|
||||
|
||||
/** Felder einer Programmzeile, denen eine Spalte zugeordnet werden kann. */
|
||||
export type ProgramField = "name" | "area" | "count" | "kind" | "group" | "note";
|
||||
|
||||
export const PROGRAM_FIELDS: readonly ProgramField[] = ["name", "area", "count", "kind", "group", "note"];
|
||||
|
||||
/** Spaltenindex je Feld (0-basiert); fehlend = nicht zugeordnet. */
|
||||
export type ColumnMap = Partial<Record<ProgramField, number>>;
|
||||
|
||||
export interface Mapping {
|
||||
/** Zeile (0-basiert) der Spaltenüberschriften; `null` = keine Kopfzeile. */
|
||||
headerRow: number | null;
|
||||
columns: ColumnMap;
|
||||
}
|
||||
|
||||
/** Tabellenblätter einer Datei (lädt das Format-Modul beim ersten Aufruf). */
|
||||
export async function readSheetFile(bytes: Uint8Array, fileName: string): Promise<SheetData[]> {
|
||||
const m = await loadFileio();
|
||||
return JSON.parse(m.sheet_read(bytes, fileName)) as SheetData[];
|
||||
}
|
||||
|
||||
/** Zahl einer Zelle: Zahl bleibt, Text wird geparst ("1'250,5", "12,5 m²"), sonst `null`. Format-Modul muss geladen sein. */
|
||||
export function cellNumber(c: SheetCell | undefined): number | null {
|
||||
if (typeof c === "number") return Number.isFinite(c) ? c : null;
|
||||
if (typeof c !== "string" || c.trim() === "") return null;
|
||||
const v = fileio().sheet_parse_number(c);
|
||||
return Number.isNaN(v) ? null : v;
|
||||
}
|
||||
|
||||
/** Text einer Zelle (Zahlen ohne Nachkomma-Rauschen, leer = ""). */
|
||||
export function cellText(c: SheetCell | undefined): string {
|
||||
if (c === null || c === undefined) return "";
|
||||
if (typeof c === "number") return Number.isInteger(c) ? String(c) : String(Math.round(c * 1e6) / 1e6);
|
||||
return c.trim();
|
||||
}
|
||||
|
||||
// ── Spaltennamen ────────────────────────────────────────────────────────────
|
||||
|
||||
/** Vergleichsform: klein, ohne Umlaut-Punkte/Akzente, nur Buchstaben und Ziffern. */
|
||||
function key(s: string): string {
|
||||
return s
|
||||
.toLowerCase()
|
||||
.replace(/ä/g, "a")
|
||||
.replace(/ö/g, "o")
|
||||
.replace(/ü/g, "u")
|
||||
.replace(/ß/g, "ss")
|
||||
.normalize("NFD")
|
||||
.replace(/[̀-ͯ]/g, "")
|
||||
.replace(/²/g, "2")
|
||||
.replace(/[^a-z0-9]+/g, "");
|
||||
}
|
||||
|
||||
/** Bekannte Spaltenüberschriften (Vergleichsform) je Feld, deutsch/englisch/französisch. */
|
||||
const HEADERS: Record<ProgramField, string[]> = {
|
||||
name: ["raum", "raume", "raumname", "raumbezeichnung", "bezeichnung", "name", "nutzung", "raumnutzung", "room", "rooms", "roomname", "designation", "description", "space", "piece", "local", "pieces", "designationdupiece", "nomdupiece"],
|
||||
area: ["flache", "m2", "qm", "sollflache", "flachem2", "flachejeraum", "flacheproraum", "grosse", "area", "surface", "sollm2", "soll", "nettoflache", "nutzflache", "size", "m2jeraum", "flachesoll", "areasqm", "aream2"],
|
||||
count: ["anzahl", "anz", "stk", "stuck", "stuk", "menge", "n", "count", "qty", "quantity", "number", "nombre", "nb", "nbre", "quantite", "pcs", "sollanzahl"],
|
||||
kind: ["flachenart", "art", "kategorie", "category", "sia", "sia416", "typ", "type", "nutzungsart", "nutzungskategorie", "kat", "flachentyp", "kind", "categorie", "genre"],
|
||||
group: ["gruppe", "geschoss", "etage", "bereich", "group", "level", "floor", "storey", "abteilung", "zone", "nutzungseinheit", "cluster", "gruppierung", "stockwerk", "niveau", "groupe", "secteur"],
|
||||
note: ["bemerkung", "bemerkungen", "kommentar", "notiz", "notizen", "anmerkung", "anmerkungen", "note", "notes", "comment", "comments", "remark", "remarks", "remarque", "remarques", "commentaire", "hinweis", "beschreibung"],
|
||||
};
|
||||
|
||||
/** Wie gut passt eine Überschrift zu einem Feld: 2 = genau, 1 = enthält (ab 3 Zeichen), 0 = nein. */
|
||||
function headerScore(cell: string, field: ProgramField): number {
|
||||
const k = key(cell);
|
||||
if (k === "") return 0;
|
||||
if (HEADERS[field].includes(k)) return 2;
|
||||
if (field === "area" && /(flache|m2|qm)/.test(k) && k.length <= 24) return 1;
|
||||
if (field === "name" && /(raum|bezeichnung)/.test(k)) return 1;
|
||||
if (field === "count" && /(anzahl|stuck|stk)/.test(k)) return 1;
|
||||
if (field === "kind" && /(flachenart|kategorie|nutzungsart)/.test(k)) return 1;
|
||||
if (field === "group" && /(gruppe|geschoss|etage)/.test(k)) return 1;
|
||||
if (field === "note" && /(bemerk|kommentar|notiz)/.test(k)) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Spalten nach Überschriften der Zeile `headerRow`: jedem Feld höchstens eine Spalte, beste Treffer zuerst. */
|
||||
function columnsFromHeader(row: SheetCell[]): ColumnMap {
|
||||
const cand: { field: ProgramField; col: number; score: number }[] = [];
|
||||
row.forEach((c, col) => {
|
||||
const text = cellText(c);
|
||||
if (!text) return;
|
||||
for (const field of PROGRAM_FIELDS) {
|
||||
const score = headerScore(text, field);
|
||||
if (score > 0) cand.push({ field, col, score });
|
||||
}
|
||||
});
|
||||
cand.sort((a, b) => b.score - a.score || a.col - b.col);
|
||||
const out: ColumnMap = {};
|
||||
const usedCols = new Set<number>();
|
||||
for (const c of cand) {
|
||||
if (out[c.field] !== undefined || usedCols.has(c.col)) continue;
|
||||
out[c.field] = c.col;
|
||||
usedCols.add(c.col);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Kopfzeile in den ersten Zeilen: die mit den meisten erkannten Feldern (mindestens Name und Fläche, oder zwei Felder). */
|
||||
export function detectHeaderRow(rows: SheetCell[][]): number | null {
|
||||
let best: { row: number; n: number; hasCore: boolean } | null = null;
|
||||
for (let r = 0; r < Math.min(rows.length, 20); r++) {
|
||||
const cols = columnsFromHeader(rows[r] ?? []);
|
||||
const n = Object.keys(cols).length;
|
||||
if (n < 2) continue;
|
||||
const hasCore = cols.name !== undefined && cols.area !== undefined;
|
||||
if (!best || (hasCore && !best.hasCore) || (hasCore === best.hasCore && n > best.n)) best = { row: r, n, hasCore };
|
||||
}
|
||||
return best ? best.row : null;
|
||||
}
|
||||
|
||||
/** Spalten aus den Daten raten, wenn Überschriften fehlen: erste Textspalte = Name, Zahlenspalte mit Nachkommastellen/grössten Werten = Fläche, kleine ganze Zahlen = Anzahl. */
|
||||
function columnsFromData(rows: SheetCell[][], from: number): ColumnMap {
|
||||
const sample = rows.slice(from, from + 60);
|
||||
const width = sample.reduce((m, r) => Math.max(m, r.length), 0);
|
||||
const stats = Array.from({ length: width }, (_, col) => {
|
||||
let text = 0, nums = 0, ints = 0, sum = 0;
|
||||
for (const r of sample) {
|
||||
const c = r[col];
|
||||
if (c === null || c === undefined || cellText(c) === "") continue;
|
||||
const n = cellNumber(c);
|
||||
if (n === null) text++;
|
||||
else {
|
||||
nums++;
|
||||
sum += n;
|
||||
if (Number.isInteger(n) && n >= 1 && n <= 50) ints++;
|
||||
}
|
||||
}
|
||||
return { col, text, nums, ints, mean: nums ? sum / nums : 0 };
|
||||
});
|
||||
const out: ColumnMap = {};
|
||||
const name = stats.find((s) => s.text > 0 && s.text >= s.nums);
|
||||
if (name) out.name = name.col;
|
||||
const numeric = stats.filter((s) => s.nums > s.text && s.nums > 0);
|
||||
const area = [...numeric].sort((a, b) => b.mean - a.mean)[0];
|
||||
if (area) out.area = area.col;
|
||||
const count = numeric.find((s) => s.col !== area?.col && s.ints === s.nums);
|
||||
if (count) out.count = count.col;
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Vorschlag: Kopfzeile erkennen und Spalten zuordnen; was die Überschriften offen lassen, ergänzen die Daten (Name, Fläche, Anzahl). */
|
||||
export function suggestMapping(rows: SheetCell[][]): Mapping {
|
||||
const headerRow = detectHeaderRow(rows);
|
||||
const columns = headerRow !== null ? columnsFromHeader(rows[headerRow] ?? []) : {};
|
||||
const guessed = columnsFromData(rows, headerRow === null ? 0 : headerRow + 1);
|
||||
const taken = new Set(Object.values(columns));
|
||||
for (const f of ["name", "area", "count"] as const) {
|
||||
const col = guessed[f];
|
||||
if (columns[f] === undefined && col !== undefined && !taken.has(col) && (headerRow === null || f !== "count")) {
|
||||
columns[f] = col;
|
||||
taken.add(col);
|
||||
}
|
||||
}
|
||||
return { headerRow, columns };
|
||||
}
|
||||
|
||||
// ── Zeilen abbilden ─────────────────────────────────────────────────────────
|
||||
|
||||
export type SkipReason = "empty" | "sum" | "noName" | "noArea" | "header";
|
||||
|
||||
export interface ImportLine {
|
||||
/** Zeile im Blatt (0-basiert). */
|
||||
sheetRow: number;
|
||||
/** Fertige Programmzeile; `undefined`, wenn die Zeile übersprungen wird. */
|
||||
row?: RoomProgramRow;
|
||||
skip?: SkipReason;
|
||||
/** Gruppenzeile: Name wird zur Gruppe der folgenden Zeilen (ohne zugeordnete Gruppenspalte). */
|
||||
groupHeading?: string;
|
||||
/** Die Flächenart-Zelle war gefüllt, aber nicht erkannt. */
|
||||
unknownKind?: string;
|
||||
}
|
||||
|
||||
const SUM_WORDS = /^(σ|∑|total|totale?|summe|zwischensumme|gesamt|gesamtsumme|gesamtfläche|übertrag|sum|subtotal|grand total|somme|sous-total|totaux)\b/i;
|
||||
|
||||
const KIND_WORDS: [RegExp, SiaCategory][] = [
|
||||
[/^hnf\b|^hauptnutz/i, "HNF"],
|
||||
[/^nnf\b|^nebennutz/i, "NNF"],
|
||||
[/^vf\b|^verkehrsfl/i, "VF"],
|
||||
[/^ff\b|^funktionsfl/i, "FF"],
|
||||
[/^kgf\b|^kf\b|^konstruktionsfl/i, "KGF"],
|
||||
[/^agf\b|^aussengeschoss|^außengeschoss/i, "AGF"],
|
||||
];
|
||||
|
||||
/** Flächenart aus Text ("HNF", "HNF 1.1", "Hauptnutzfläche"); sonst `undefined`. */
|
||||
export function parseKind(text: string): SiaCategory | undefined {
|
||||
const t = text.trim();
|
||||
for (const [re, cat] of KIND_WORDS) if (re.test(t)) return cat;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export interface MapOptions {
|
||||
/** Summenzeilen überspringen (Default ja). */
|
||||
skipSums?: boolean;
|
||||
}
|
||||
|
||||
/** Eine Tabelle mit Zuordnung in Programmzeilen übersetzen (Format-Modul für Zahlen muss geladen sein). */
|
||||
export function mapRows(rows: SheetCell[][], mapping: Mapping, opts: MapOptions = {}): ImportLine[] {
|
||||
const { columns } = mapping;
|
||||
const skipSums = opts.skipSums ?? true;
|
||||
const start = mapping.headerRow === null ? 0 : mapping.headerRow + 1;
|
||||
const out: ImportLine[] = [];
|
||||
if (mapping.headerRow !== null) out.push({ sheetRow: mapping.headerRow, skip: "header" });
|
||||
const get = (r: SheetCell[], f: ProgramField): SheetCell => (columns[f] === undefined ? null : (r[columns[f]!] ?? null));
|
||||
let heading = "";
|
||||
let runningSum = 0; // Summe der Flächen seit der letzten Summenzeile
|
||||
for (let i = start; i < rows.length; i++) {
|
||||
const r = rows[i] ?? [];
|
||||
if (r.every((c) => cellText(c) === "")) {
|
||||
out.push({ sheetRow: i, skip: "empty" });
|
||||
continue;
|
||||
}
|
||||
const name = cellText(get(r, "name"));
|
||||
const area = cellNumber(get(r, "area"));
|
||||
const countRaw = cellNumber(get(r, "count"));
|
||||
// Summenzeile: Stichwort in Name oder (bei leerem Namen) irgendeiner Textzelle; oder ohne Namen und gleich der laufenden Summe.
|
||||
const anyText = r.map((c) => (typeof c === "string" ? c.trim() : "")).filter(Boolean);
|
||||
const keyword = SUM_WORDS.test(name) || (name === "" && anyText.some((t) => SUM_WORDS.test(t)));
|
||||
const matchesRunning = name === "" && area !== null && runningSum > 0 && Math.abs(area - runningSum) < 0.005 * Math.max(1, runningSum);
|
||||
if (skipSums && (keyword || matchesRunning)) {
|
||||
out.push({ sheetRow: i, skip: "sum" });
|
||||
runningSum = 0;
|
||||
continue;
|
||||
}
|
||||
if (name === "") {
|
||||
out.push({ sheetRow: i, skip: "noName" });
|
||||
continue;
|
||||
}
|
||||
if (area === null && countRaw === null && columns.group === undefined) {
|
||||
// Nur ein Name: Zwischentitel („Wohnen") → Gruppe der folgenden Zeilen.
|
||||
const others = r.filter((_, c) => c !== columns.name && cellText(r[c]) !== "");
|
||||
if (others.length === 0) {
|
||||
heading = name;
|
||||
out.push({ sheetRow: i, skip: "noArea", groupHeading: name });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (area === null || area <= 0) {
|
||||
out.push({ sheetRow: i, skip: "noArea" });
|
||||
continue;
|
||||
}
|
||||
const row: RoomProgramRow = { name, area };
|
||||
const count = countRaw === null ? 1 : Math.round(countRaw);
|
||||
if (count > 1) row.count = count;
|
||||
const kindText = cellText(get(r, "kind"));
|
||||
let unknownKind: string | undefined;
|
||||
if (kindText) {
|
||||
const k = parseKind(kindText);
|
||||
if (k) row.siaCategory = k;
|
||||
else unknownKind = kindText;
|
||||
}
|
||||
const group = columns.group !== undefined ? cellText(get(r, "group")) : heading;
|
||||
if (group) row.group = group;
|
||||
const note = cellText(get(r, "note"));
|
||||
if (note) row.note = note;
|
||||
runningSum += area * Math.max(1, count);
|
||||
out.push({ sheetRow: i, row, ...(unknownKind ? { unknownKind } : {}) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Programmzeilen der Übersetzung. */
|
||||
export function importedRows(lines: ImportLine[]): RoomProgramRow[] {
|
||||
return lines.flatMap((l) => (l.row ? [l.row] : []));
|
||||
}
|
||||
|
||||
export type ImportMode = "replace" | "append";
|
||||
|
||||
/** Fügt Programmzeilen in das Projekt ein (für `setProject`): ersetzen oder anhängen. Keine Zeilen → unverändert. */
|
||||
export function applyRoomProgram(project: Project, rows: RoomProgramRow[], mode: ImportMode): Project {
|
||||
if (rows.length === 0) return project;
|
||||
return { ...project, roomProgram: mode === "append" ? [...(project.roomProgram ?? []), ...rows] : rows };
|
||||
}
|
||||
@@ -935,6 +935,10 @@ export interface RoomProgramRow {
|
||||
area: number;
|
||||
/** Soll-Anzahl (Default 1). */
|
||||
count?: number;
|
||||
/** Gruppe/Bereich/Geschoss aus dem Programm (z. B. „Wohnen", „EG"): Zwischensummen und Farbe beim Generieren. */
|
||||
group?: string;
|
||||
/** Bemerkung aus dem Programm (reiner Text). */
|
||||
note?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2935,6 +2939,8 @@ export interface Project {
|
||||
drawingLevels: DrawingLevel[];
|
||||
/** Raumprogramm (Soll) für die Prüfung gegen das Modell. */
|
||||
roomProgram?: RoomProgramRow[];
|
||||
/** Toleranz der Soll/Ist-Ampel des Raumprogramms als Anteil der Soll-Fläche (Default 0.05 = ±5 %). */
|
||||
roomProgramTolerance?: number;
|
||||
/** Parzellenfläche (m²) für Ausnützungs- und Überbauungsziffer. */
|
||||
parcelArea?: number;
|
||||
/** Schattenstudie: Zeitpunkt (ISO 8601, UTC) und ob der Boden-Schatten im Grundriss erscheint. */
|
||||
|
||||
@@ -12,6 +12,7 @@ import { usePanelHost } from "./host";
|
||||
import { useStore } from "../state/appStore";
|
||||
import { checkRoomProgram, computeKennzahlen, polygonArea } from "../core";
|
||||
import type { Project, RoomProgramRow } from "../model/types";
|
||||
import { RoomProgramImportButton } from "../ui/RoomProgramImportDialog";
|
||||
|
||||
type ProgramStatus = ReturnType<typeof checkRoomProgram>["rows"][number]["status"];
|
||||
|
||||
@@ -40,6 +41,7 @@ const fmt = (n: number, d = 1) => n.toLocaleString("de-CH", { minimumFractionDig
|
||||
export function KennzahlenSection() {
|
||||
const host = usePanelHost();
|
||||
const setProject = useStore((s) => s.setProject);
|
||||
const notify = useStore((s) => s.notify);
|
||||
const project = host.project;
|
||||
const k = computeKennzahlen(project);
|
||||
const prog = checkRoomProgram(project);
|
||||
@@ -118,6 +120,7 @@ export function KennzahlenSection() {
|
||||
<span>{t("program.name")}</span>
|
||||
<span>{t("program.area")}</span>
|
||||
<span>{t("program.count")}</span>
|
||||
<span>{t("program.field.group")}</span>
|
||||
<span>{t("program.status")}</span>
|
||||
<span />
|
||||
</div>
|
||||
@@ -154,6 +157,12 @@ export function KennzahlenSection() {
|
||||
if (v !== null && v >= 1) patchRow(i, { count: Math.round(v) }, "count");
|
||||
}}
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
className="kz-input"
|
||||
value={row.group ?? ""}
|
||||
onChange={(e) => patchRow(i, { group: e.target.value === "" ? undefined : e.target.value }, "group")}
|
||||
/>
|
||||
<span
|
||||
className={"kz-status" + (res?.status === "ok" ? " ok" : " bad")}
|
||||
title={res ? t("program.actual", { count: res.count, area: fmt(res.area) }) : undefined}
|
||||
@@ -168,9 +177,12 @@ export function KennzahlenSection() {
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<button type="button" className="kz-add" onClick={addRow}>
|
||||
{t("program.add")}
|
||||
</button>
|
||||
<div className="kz-program-actions">
|
||||
<button type="button" className="kz-add" onClick={addRow}>
|
||||
{t("program.add")}
|
||||
</button>
|
||||
<RoomProgramImportButton project={project} onApply={(fn) => setProject(fn)} notify={notify} />
|
||||
</div>
|
||||
{rows.length > 0 && prog.extra.length > 0 && (
|
||||
<div className="kz-extra" title={prog.extra.map((r) => r.name).join(", ")}>
|
||||
{t("program.extra", { n: prog.extra.length })}
|
||||
|
||||
+88
-5
@@ -8424,11 +8424,6 @@ body {
|
||||
}
|
||||
|
||||
/* Punktwolken-Import ([27]): Bericht im Dialog kompakt wie die übrigen Hinweise. */
|
||||
.pc-report {
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--ink-2);
|
||||
}
|
||||
|
||||
.bcf-vps {
|
||||
display: flex;
|
||||
@@ -8554,3 +8549,91 @@ body {
|
||||
font-size: 10px;
|
||||
color: var(--ink-2);
|
||||
}
|
||||
|
||||
/* Raumprogramm: Gruppenspalte, Aktionen, Soll/Ist-Vergleich, Import-Dialog ([61]). */
|
||||
.kz-program-row {
|
||||
grid-template-columns: minmax(0, 1fr) 52px 36px 64px 56px 18px;
|
||||
}
|
||||
.kz-program-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
.rpi-dialog {
|
||||
width: min(880px, 94vw);
|
||||
}
|
||||
.rpi-file {
|
||||
font-size: 12px;
|
||||
color: var(--ink-2);
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.rpi-controls {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
}
|
||||
.rpi-controls label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.rpi-select {
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
padding: 3px 6px;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
background: var(--field-bg);
|
||||
color: var(--ink);
|
||||
max-width: 100%;
|
||||
}
|
||||
.rpi-colsel.mapped {
|
||||
font-weight: 600;
|
||||
outline: 1px solid var(--accent-border, #4a7bd0);
|
||||
}
|
||||
.rpi-scroll {
|
||||
max-height: 300px;
|
||||
overflow: auto;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
}
|
||||
.rpi-table {
|
||||
border-collapse: collapse;
|
||||
font-size: 12px;
|
||||
width: 100%;
|
||||
}
|
||||
.rpi-table th,
|
||||
.rpi-table td {
|
||||
padding: 2px 6px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
max-width: 200px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.rpi-table thead th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: var(--panel);
|
||||
z-index: 1;
|
||||
}
|
||||
.rpi-table td.mapped {
|
||||
background: var(--field-bg);
|
||||
}
|
||||
.rpi-table tr.skip td {
|
||||
color: var(--ink-2);
|
||||
opacity: 0.65;
|
||||
}
|
||||
.rpi-table tr.head td {
|
||||
font-weight: 600;
|
||||
}
|
||||
.rpi-rownr {
|
||||
color: var(--ink-2);
|
||||
text-align: right;
|
||||
width: 28px;
|
||||
}
|
||||
.rpi-state {
|
||||
font-size: 11px;
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
// Raumprogramm aus einer Tabelle importieren ([61]): Blatt wählen, Kopfzeile und Spalten zuordnen
|
||||
// (Vorschlag nach den Spaltennamen), Vorschau, ersetzen oder anhängen. Die Datei liest der Rust-Leser
|
||||
// (`fileio/src/sheet_import.rs`: .xlsx, .ods, .csv/.tsv); die Zuordnung steht in `io/roomProgramImport.ts`.
|
||||
//
|
||||
// `RoomProgramImportButton` zeigt den Knopf „Raumprogramm importieren …" samt verstecktem Datei-Feld und
|
||||
// öffnet danach den Dialog (Overlay über ein Portal, damit er im Panel nicht abgeschnitten wird).
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { t } from "../i18n";
|
||||
import type { TranslationKey } from "../i18n";
|
||||
import { applyRoomProgram, cellText, importedRows, mapRows, PROGRAM_FIELDS, readSheetFile, suggestMapping } from "../core";
|
||||
import type { ImportMode, Mapping, ProgramField, SheetData, SkipReason } from "../core";
|
||||
import type { Project, RoomProgramRow } from "../model/types";
|
||||
|
||||
const FIELD_KEY: Record<ProgramField, TranslationKey> = {
|
||||
name: "program.field.name",
|
||||
area: "program.field.area",
|
||||
count: "program.field.count",
|
||||
kind: "program.field.kind",
|
||||
group: "program.field.group",
|
||||
note: "program.field.note",
|
||||
};
|
||||
|
||||
const SKIP_KEY: Record<SkipReason, TranslationKey> = {
|
||||
empty: "program.import.skip.empty",
|
||||
sum: "program.import.skip.sum",
|
||||
noName: "program.import.skip.noName",
|
||||
noArea: "program.import.skip.noArea",
|
||||
header: "program.import.skip.header",
|
||||
};
|
||||
|
||||
/** Spaltenbuchstabe: 0 → A, 26 → AA. */
|
||||
function colLetter(i: number): string {
|
||||
let s = "";
|
||||
for (let n = i + 1; n > 0; n = Math.floor((n - 1) / 26)) s = String.fromCharCode(65 + ((n - 1) % 26)) + s;
|
||||
return s;
|
||||
}
|
||||
|
||||
const MAX_PREVIEW_ROWS = 60;
|
||||
const MAX_PREVIEW_COLS = 12;
|
||||
|
||||
export interface RoomProgramImportDialogProps {
|
||||
fileName: string;
|
||||
sheets: SheetData[];
|
||||
/** Zeilen, die das Projekt schon hat (für „anhängen"). */
|
||||
existing: number;
|
||||
onImport: (rows: RoomProgramRow[], mode: ImportMode) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function RoomProgramImportDialog({ fileName, sheets, existing, onImport, onClose }: RoomProgramImportDialogProps) {
|
||||
const [sheetIdx, setSheetIdx] = useState(() => {
|
||||
// Erstes Blatt mit Inhalt.
|
||||
const i = sheets.findIndex((s) => s.rows.length > 0);
|
||||
return i < 0 ? 0 : i;
|
||||
});
|
||||
const sheet = sheets[sheetIdx];
|
||||
const rows = sheet?.rows ?? [];
|
||||
const [mapping, setMapping] = useState<Mapping>(() => suggestMapping(rows));
|
||||
const [skipSums, setSkipSums] = useState(true);
|
||||
const [mode, setMode] = useState<ImportMode>(existing > 0 ? "append" : "replace");
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") onClose();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [onClose]);
|
||||
|
||||
const pickSheet = (i: number) => {
|
||||
setSheetIdx(i);
|
||||
setMapping(suggestMapping(sheets[i]?.rows ?? []));
|
||||
};
|
||||
|
||||
const lines = useMemo(() => mapRows(rows, mapping, { skipSums }), [rows, mapping, skipSums]);
|
||||
const imported = useMemo(() => importedRows(lines), [lines]);
|
||||
const lineByRow = useMemo(() => new Map(lines.map((l) => [l.sheetRow, l] as const)), [lines]);
|
||||
const skipped = lines.filter((l) => l.skip && l.skip !== "empty" && l.skip !== "header" && !l.groupHeading).length;
|
||||
const unknownKinds = lines.filter((l) => l.unknownKind).length;
|
||||
const ready = mapping.columns.name !== undefined && mapping.columns.area !== undefined && imported.length > 0;
|
||||
|
||||
const width = Math.min(MAX_PREVIEW_COLS, rows.reduce((m, r) => Math.max(m, r.length), 0));
|
||||
const fieldOfCol = (c: number): ProgramField | "" => PROGRAM_FIELDS.find((f) => mapping.columns[f] === c) ?? "";
|
||||
const setColumn = (c: number, f: ProgramField | "") =>
|
||||
setMapping((m) => {
|
||||
const columns = { ...m.columns };
|
||||
for (const k of PROGRAM_FIELDS) if (columns[k] === c) delete columns[k];
|
||||
if (f) columns[f] = c;
|
||||
return { ...m, columns };
|
||||
});
|
||||
const shown = rows.slice(0, MAX_PREVIEW_ROWS);
|
||||
|
||||
const dialog = (
|
||||
<div className="imp-overlay" onClick={onClose}>
|
||||
<div className="imp-dialog rpi-dialog" role="dialog" aria-modal="true" aria-label={t("program.import.title")} onClick={(e) => e.stopPropagation()}>
|
||||
<header className="imp-head">
|
||||
<span className="imp-head-title">{t("program.import.title")}</span>
|
||||
<button className="imp-close" onClick={onClose} aria-label={t("export.close")}>
|
||||
×
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div className="imp-body">
|
||||
<section className="imp-section">
|
||||
<div className="rpi-file">{fileName}</div>
|
||||
<div className="rpi-controls">
|
||||
{sheets.length > 1 && (
|
||||
<label>
|
||||
<span>{t("program.import.sheet")}</span>
|
||||
<select className="rpi-select" value={sheetIdx} onChange={(e) => pickSheet(Number(e.target.value))}>
|
||||
{sheets.map((s, i) => (
|
||||
<option key={i} value={i}>
|
||||
{s.name || `${i + 1}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<label>
|
||||
<span>{t("program.import.header")}</span>
|
||||
<select
|
||||
className="rpi-select"
|
||||
value={mapping.headerRow === null ? "" : String(mapping.headerRow)}
|
||||
onChange={(e) => setMapping((m) => ({ ...m, headerRow: e.target.value === "" ? null : Number(e.target.value) }))}
|
||||
>
|
||||
<option value="">{t("program.import.header.none")}</option>
|
||||
{rows.slice(0, 20).map((_, i) => (
|
||||
<option key={i} value={i}>
|
||||
{t("program.import.row", { n: i + 1 })}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="imp-section">
|
||||
<div className="imp-section-title">{t("program.import.columns")}</div>
|
||||
<div className="rpi-scroll">
|
||||
<table className="rpi-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="rpi-rownr" />
|
||||
{Array.from({ length: width }, (_, c) => (
|
||||
<th key={c}>
|
||||
<select
|
||||
className={"rpi-select rpi-colsel" + (fieldOfCol(c) ? " mapped" : "")}
|
||||
value={fieldOfCol(c)}
|
||||
aria-label={t("program.import.columnOf", { col: colLetter(c) })}
|
||||
onChange={(e) => setColumn(c, e.target.value as ProgramField | "")}
|
||||
>
|
||||
<option value="">{colLetter(c)} · –</option>
|
||||
{PROGRAM_FIELDS.map((f) => (
|
||||
<option key={f} value={f}>
|
||||
{colLetter(c)} · {t(FIELD_KEY[f])}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</th>
|
||||
))}
|
||||
<th>{t("program.import.state")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{shown.map((r, i) => {
|
||||
const line = lineByRow.get(i);
|
||||
const before = mapping.headerRow !== null && i < mapping.headerRow;
|
||||
const cls = line?.row ? "ok" : "skip";
|
||||
return (
|
||||
<tr key={i} className={before ? "skip" : cls + (line?.skip === "header" ? " head" : "")}>
|
||||
<td className="rpi-rownr">{i + 1}</td>
|
||||
{Array.from({ length: width }, (_, c) => (
|
||||
<td key={c} className={fieldOfCol(c) ? "mapped" : ""}>
|
||||
{cellText(r[c])}
|
||||
</td>
|
||||
))}
|
||||
<td className="rpi-state">
|
||||
{line?.row
|
||||
? line.unknownKind
|
||||
? t("program.import.unknownKind", { kind: line.unknownKind })
|
||||
: "✓"
|
||||
: line?.groupHeading
|
||||
? t("program.import.skip.group")
|
||||
: line?.skip
|
||||
? t(SKIP_KEY[line.skip])
|
||||
: ""}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{rows.length > shown.length && <div className="imp-note">{t("program.import.more", { n: rows.length - shown.length })}</div>}
|
||||
</section>
|
||||
|
||||
<section className="imp-section">
|
||||
<label className="imp-check">
|
||||
<input type="checkbox" checked={skipSums} onChange={(e) => setSkipSums(e.target.checked)} />
|
||||
<span>{t("program.import.skipSums")}</span>
|
||||
</label>
|
||||
<label className="imp-radio">
|
||||
<input type="radio" name="rpi-mode" checked={mode === "replace"} onChange={() => setMode("replace")} />
|
||||
<span>{t("program.import.mode.replace")}</span>
|
||||
</label>
|
||||
<label className="imp-radio">
|
||||
<input type="radio" name="rpi-mode" checked={mode === "append"} onChange={() => setMode("append")} disabled={existing === 0} />
|
||||
<span>{t("program.import.mode.append", { n: existing })}</span>
|
||||
</label>
|
||||
<div className={"imp-note" + (ready ? "" : " imp-warn")}>
|
||||
{mapping.columns.name === undefined || mapping.columns.area === undefined
|
||||
? t("program.import.needNameArea")
|
||||
: t("program.import.summary", { n: imported.length, s: skipped })}
|
||||
{unknownKinds > 0 ? ` ${t("program.import.unknownKinds", { n: unknownKinds })}` : ""}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<footer className="imp-foot">
|
||||
<button className="imp-btn" onClick={onClose}>
|
||||
{t("export.cancel")}
|
||||
</button>
|
||||
<button className="imp-btn primary" disabled={!ready} onClick={() => onImport(imported, mode)}>
|
||||
{t("program.import.confirm")}
|
||||
</button>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
return createPortal(dialog, document.body);
|
||||
}
|
||||
|
||||
export interface RoomProgramImportButtonProps {
|
||||
project: Project;
|
||||
/** Übernimmt die Zeilen ins Projekt (ein Undo-Schritt). */
|
||||
onApply: (project: (p: Project) => Project) => void;
|
||||
notify: (message: string, kind?: "info" | "warning" | "error") => void;
|
||||
}
|
||||
|
||||
/** Knopf mit Datei-Auswahl; liest die Tabelle und öffnet den Dialog. */
|
||||
export function RoomProgramImportButton({ project, onApply, notify }: RoomProgramImportButtonProps) {
|
||||
const input = useRef<HTMLInputElement>(null);
|
||||
const [data, setData] = useState<{ name: string; sheets: SheetData[] } | null>(null);
|
||||
|
||||
const onFile = async (file: File | undefined) => {
|
||||
if (!file) return;
|
||||
try {
|
||||
const sheets = await readSheetFile(new Uint8Array(await file.arrayBuffer()), file.name);
|
||||
if (sheets.every((s) => s.rows.length === 0)) throw new Error(t("program.import.empty"));
|
||||
setData({ name: file.name, sheets });
|
||||
} catch (e) {
|
||||
notify(t("program.import.readFail", { msg: e instanceof Error ? e.message : String(e) }), "error");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<input
|
||||
ref={input}
|
||||
type="file"
|
||||
accept=".xlsx,.ods,.csv,.tsv,.txt"
|
||||
hidden
|
||||
data-testid="program-import-file"
|
||||
onChange={(e) => {
|
||||
void onFile(e.target.files?.[0]);
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
<button type="button" className="kz-add" onClick={() => input.current?.click()}>
|
||||
{t("program.import")}
|
||||
</button>
|
||||
{data && (
|
||||
<RoomProgramImportDialog
|
||||
fileName={data.name}
|
||||
sheets={data.sheets}
|
||||
existing={project.roomProgram?.length ?? 0}
|
||||
onClose={() => setData(null)}
|
||||
onImport={(rows, mode) => {
|
||||
onApply((p) => applyRoomProgram(p, rows, mode));
|
||||
notify(t("program.import.done", { n: rows.length }));
|
||||
setData(null);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user