[K4] S2: Bauteilliste (Zeilen und CSV) in Rust (export_schedule.rs); exportSchedule.ts nur noch Fassade

This commit is contained in:
karim committed 2026-10-28 02:22:31 +01:00
1 parent aaa7fae812
commit f16cf44b60
7 files changed
+290 -323

No files matched your search

+1 -11
View File
@@ -514,7 +514,7 @@ pub fn export_ifc_spf(project_in: &Project, now_ms: f64) -> Result<String, Strin
let (placement, shape) = emit_box_product!(&ceiling.outline, z_bottom - structure.base_elevation, z_top - z_bottom, structure.placement_id);
let mut name = ceiling.id.clone();
let mut type_idx = None;
if let Some((tid, tname, layers)) = ceiling_type_of(p, ceiling) {
if let Some((tid, tname, layers)) = model3d::ceiling_type_ref(p, ceiling) {
name = tname.to_string();
type_idx = Some(type_for!("IFCSLABTYPE", "FLOOR", tid, tname, layers));
}
@@ -720,16 +720,6 @@ pub fn export_ifc_spf(project_in: &Project, now_ms: f64) -> Result<String, Strin
Ok(out.join("\n") + "\n")
}
/// Deckentyp (id, Name, Schichten): Deckentyp, sonst Wandtyp (`getCeilingType`).
fn ceiling_type_of<'a>(p: &'a Project, c: &Ceiling) -> Option<(&'a str, &'a str, &'a [Layer])> {
if let Some(id) = c.ceiling_type_id.as_deref() {
if let Some(t) = p.ceiling_types.as_deref().and_then(|v| v.iter().find(|t| t.id == id)) {
return Some((&t.id, &t.name, &t.layers));
}
}
p.wall_types.iter().find(|t| t.id == c.wall_type_id).map(|t| (t.id.as_str(), t.name.as_str(), t.layers.as_slice()))
}
#[cfg(test)]
mod tests {
use super::*;
+257
View File
@@ -0,0 +1,257 @@
//! Bauteilliste ([K4] S2, vorher `src/export/exportSchedule.ts`): eine Zeile je Bauteil-Vorkommen
//! (Wand, Decke, Tür/Fenster, Treppe, Extrusion, Dach, Stütze) mit Kennwerten aus dem Modell, dazu
//! CSV-Ausgabe (RFC 4180, Feldtrenner `;`, Zeilenende CRLF) mit Aggregat je Bauteil-Typ.
use crate::js_fmt::to_fixed;
use crate::jsmath::hypot2;
use crate::jsnum::round;
use crate::model::*;
use serde::Serialize;
/// Eine ausgewertete Zeile (JSON-Form wie `ScheduleRow` in TS).
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduleRow {
pub kind: &'static str,
pub id: String,
pub type_name: String,
pub floor: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub floor_id: Option<String>,
pub length: Option<f64>,
pub height_m: Option<f64>,
pub thickness: Option<f64>,
pub area: Option<f64>,
}
fn polygon_area(pts: &[Vec2]) -> f64 {
let flat: Vec<[f64; 2]> = pts.iter().map(|v| [v.x, v.y]).collect();
crate::room_area::evaluate(&flat, 0.0).gross
}
fn floor_name(p: &Project, floor_id: &str) -> String {
p.floor(floor_id).map_or(floor_id.to_string(), |f| f.name.clone())
}
/// Wertet ALLE Bauteil-Vorkommen aus: Wände, Decken, Öffnungen, Treppen, Extrusionen, Dächer, Stützen.
pub fn schedule_rows(p: &Project) -> Vec<ScheduleRow> {
let mut rows = Vec::new();
for w in &p.walls {
let (type_name, thickness) = match p.wall_type(w) {
Some(t) => (t.name.clone(), Project::type_thickness(&t.layers)),
None => (w.wall_type_id.clone(), 0.0),
};
let length = hypot2(w.end.x - w.start.x, w.end.y - w.start.y);
rows.push(ScheduleRow {
kind: "Wand",
id: w.id.clone(),
type_name,
floor: floor_name(p, &w.floor_id),
floor_id: Some(w.floor_id.clone()),
length: Some(length),
height_m: Some(w.height),
thickness: Some(thickness),
area: Some(length * w.height),
});
}
for c in p.ceilings.as_deref().unwrap_or(&[]) {
let type_name = match crate::model3d::ceiling_type_ref(p, c) {
Some((_, name, _)) => name.to_string(),
None => c.ceiling_type_id.clone().unwrap_or_else(|| c.wall_type_id.clone()),
};
rows.push(ScheduleRow {
kind: "Decke",
id: c.id.clone(),
type_name,
floor: floor_name(p, &c.floor_id),
floor_id: Some(c.floor_id.clone()),
length: None,
height_m: None,
thickness: Some(p.ceiling_thickness(c)),
area: Some(polygon_area(&c.outline)),
});
}
for o in p.openings.as_deref().unwrap_or(&[]) {
let kind = if o.kind == ElementKind::Window { "Fenster" } else { "Tür" };
let host = p.walls.iter().find(|w| w.id == o.host_wall_id);
rows.push(ScheduleRow {
kind,
id: o.id.clone(),
type_name: kind.to_string(),
floor: host.map_or(o.host_wall_id.clone(), |w| floor_name(p, &w.floor_id)),
floor_id: host.map(|w| w.floor_id.clone()),
length: Some(o.width),
height_m: Some(o.height),
thickness: None,
area: Some(o.width * o.height),
});
}
for s in p.stairs.as_deref().unwrap_or(&[]) {
rows.push(ScheduleRow {
kind: "Treppe",
id: s.id.clone(),
type_name: "Treppe".into(),
floor: floor_name(p, &s.floor_id),
floor_id: Some(s.floor_id.clone()),
length: Some(s.run_length + s.run2_length.unwrap_or(0.0)),
height_m: s.total_rise,
thickness: None,
area: None,
});
}
for e in p.extruded_solids.as_deref().unwrap_or(&[]) {
rows.push(ScheduleRow {
kind: "Extrusion",
id: e.id.clone(),
type_name: "Extrusion".into(),
floor: floor_name(p, &e.level_id),
floor_id: Some(e.level_id.clone()),
length: None,
height_m: Some(e.height),
thickness: None,
area: Some(polygon_area(&e.points)),
});
}
for r in p.roofs.as_deref().unwrap_or(&[]) {
let mut type_name = r.roof_type_id.clone().unwrap_or_else(|| shape_name(r.shape).to_string());
if let Some(rt) = r.roof_type_id.as_deref().and_then(|id| p.roof_types.as_deref()?.iter().find(|t| t.id == id)) {
type_name = rt.name.clone();
}
rows.push(ScheduleRow {
kind: "Dach",
id: r.id.clone(),
type_name,
floor: floor_name(p, &r.floor_id),
floor_id: Some(r.floor_id.clone()),
length: None,
height_m: None,
thickness: Some(r.thickness),
area: Some(polygon_area(&r.outline)),
});
}
for c in p.columns.as_deref().unwrap_or(&[]) {
let (type_name, length, thickness) = match &c.profile {
ColumnProfile::Round { radius } => ("Rund", None, radius * 2.0),
ColumnProfile::Rect { width, depth } => ("Rechteck", Some(*width), *depth),
};
rows.push(ScheduleRow {
kind: "Stütze",
id: c.id.clone(),
type_name: type_name.into(),
floor: floor_name(p, &c.floor_id),
floor_id: Some(c.floor_id.clone()),
length,
height_m: Some(c.height),
thickness: Some(thickness),
area: None,
});
}
rows
}
fn shape_name(s: RoofShape) -> &'static str {
match s {
RoofShape::Flach => "flach",
RoofShape::Pult => "pult",
RoofShape::Sattel => "sattel",
RoofShape::Walm => "walm",
RoofShape::Mansarde => "mansarde",
RoofShape::Zelt => "zelt",
}
}
/// Ein Feld CSV-sicher quoten: „…" bei , " \n \r ; — `"` wird verdoppelt.
fn csv_field(v: &str) -> String {
if v.contains(['"', ',', '\n', '\r', ';']) {
format!("\"{}\"", v.replace('"', "\"\""))
} else {
v.to_string()
}
}
/// Zahl auf 2 Nachkommastellen, Punkt; leer bei `None`/nicht endlich.
fn fmt_num(v: Option<f64>) -> String {
match v {
Some(x) if x.is_finite() => to_fixed(round(x * 100.0) / 100.0, 2),
_ => String::new(),
}
}
struct Aggregate {
kind: &'static str,
type_name: String,
count: usize,
total_length: f64,
total_area: f64,
}
/// Bauteilliste als CSV (`exportScheduleCsv`): Kopfzeile, eine Zeile je Bauteil, optional Aggregat.
pub fn export_schedule_csv(p: &Project, delimiter: &str, include_summary: bool) -> String {
let rows = schedule_rows(p);
let d = delimiter;
let mut lines: Vec<String> = Vec::new();
let header = ["Typ", "ID", "Bauteil", "Geschoss", "Länge [m]", "Höhe [m]", "Dicke [m]", "Fläche [m²]"];
lines.push(header.iter().map(|h| csv_field(h)).collect::<Vec<_>>().join(d));
for r in &rows {
lines.push(
[csv_field(r.kind), csv_field(&r.id), csv_field(&r.type_name), csv_field(&r.floor), fmt_num(r.length), fmt_num(r.height_m), fmt_num(r.thickness), fmt_num(r.area)].join(d),
);
}
if include_summary && !rows.is_empty() {
lines.push(String::new());
lines.push([csv_field("Zusammenfassung (je Bauteil-Typ)"), "".into(), "".into(), "".into(), "".into(), "".into(), "".into(), "".into()].join(d));
let mut aggs: Vec<Aggregate> = Vec::new();
for r in &rows {
let i = match aggs.iter().position(|a| a.kind == r.kind && a.type_name == r.type_name) {
Some(i) => i,
None => {
aggs.push(Aggregate { kind: r.kind, type_name: r.type_name.clone(), count: 0, total_length: 0.0, total_area: 0.0 });
aggs.len() - 1
}
};
aggs[i].count += 1;
aggs[i].total_length += r.length.unwrap_or(0.0);
aggs[i].total_area += r.area.unwrap_or(0.0);
}
for a in &aggs {
lines.push(
[
csv_field(a.kind),
String::new(),
csv_field(&a.type_name),
csv_field(&format!("{} Stk", a.count)),
if a.total_length > 0.0 { fmt_num(Some(a.total_length)) } else { String::new() },
String::new(),
String::new(),
if a.total_area > 0.0 { fmt_num(Some(a.total_area)) } else { String::new() },
]
.join(d),
);
}
}
lines.join("\r\n")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn beispielprojekt_hat_zeilen_und_csv() {
let p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap();
let rows = schedule_rows(&p);
assert!(rows.iter().any(|r| r.kind == "Wand"));
let csv = export_schedule_csv(&p, ";", true);
assert!(csv.starts_with("Typ;ID;Bauteil;Geschoss;Länge [m];Höhe [m];Dicke [m];Fläche [m²]\r\n"));
assert!(csv.contains("Zusammenfassung (je Bauteil-Typ)"));
assert_eq!(export_schedule_csv(&Project::default(), ";", true), "Typ;ID;Bauteil;Geschoss;Länge [m];Höhe [m];Dicke [m];Fläche [m²]");
}
#[test]
fn csv_quoting() {
assert_eq!(csv_field("a;b"), "\"a;b\"");
assert_eq!(csv_field("a\"b"), "\"a\"\"b\"");
assert_eq!(fmt_num(Some(1.005)), "1.00");
assert_eq!(fmt_num(None), "");
}
}
+1
View File
@@ -5,6 +5,7 @@
//! Datenübergabe: flache `f64`-Puffer (s. [`flat`]), kein JSON — schnell und ohne Serde-Kosten.
pub mod export_ifc;
pub mod export_schedule;
pub mod flat;
pub mod geo_rebase;
pub mod flat_write;
+10
View File
@@ -59,6 +59,16 @@ pub struct RMesh {
// ── Decken ──────────────────────────────────────────────────────────────────
/// Deckentyp (id, Name, Schichten): Deckentyp, sonst Wandtyp (`getCeilingType`).
pub fn ceiling_type_ref<'a>(p: &'a Project, c: &Ceiling) -> Option<(&'a str, &'a str, &'a [Layer])> {
if let Some(id) = c.ceiling_type_id.as_deref() {
if let Some(t) = p.ceiling_types.as_deref().and_then(|v| v.iter().find(|t| t.id == id)) {
return Some((&t.id, &t.name, &t.layers));
}
}
p.wall_types.iter().find(|t| t.id == c.wall_type_id).map(|t| (t.id.as_str(), t.name.as_str(), t.layers.as_slice()))
}
fn ceiling_layers<'a>(p: &'a Project, c: &Ceiling) -> Option<&'a [Layer]> {
if let Some(id) = c.ceiling_type_id.as_deref() {
if let Some(t) = p.ceiling_types.as_deref().and_then(|v| v.iter().find(|t| t.id == id)) {
+3 -1
View File
@@ -2,7 +2,7 @@
//! antwortet. TS ruft sie über `ProjectDocument.query(name, args, text)`.
use crate::model::Project;
use crate::{kennzahlen, model3d, site_rules, sun};
use crate::{export_schedule, kennzahlen, model3d, site_rules, sun};
fn json<T: serde::Serialize>(v: &T) -> Result<String, String> {
serde_json::to_string(v).map_err(|e| e.to_string())
@@ -26,6 +26,8 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
("stairRailings", _) => json(&model3d::emit_stair_railings(p)),
("roofMeshes", _) => json(&model3d::emit_roofs(p, if text.is_empty() { None } else { Some(text) })?),
("roofCutLayers", _) => json(&model3d::emit_roof_cut_layers(p)?),
("scheduleRows", _) => json(&export_schedule::schedule_rows(p)),
("scheduleCsv", 1) => Ok(export_schedule::export_schedule_csv(p, text, args[0] != 0.0)),
("pickGeometry", _) => json(&model3d::pick_geometry(p)?),
("model3dParts", 3) => json(&model3d::parts(p, args[0] != 0.0, args[1], args[2] != 0.0)?),
_ => Err(format!("Unbekannte Abfrage: {name}")),
+2
View File
@@ -25,6 +25,8 @@ export type QueryName =
| "stairRailings"
| "roofMeshes"
| "roofCutLayers"
| "scheduleRows"
| "scheduleCsv"
| "pickGeometry"
| "model3dParts";
+16 -311
View File
@@ -1,60 +1,12 @@
// Bauteil-Schedule (Bauteilliste) — CSV-Export einer Bauteilaufstellung des
// Projekts (AUDIT A6, DOSSIER-Parität). Reiner Rechen-/Serialisierungskern:
// keine UI, kein Datei-IO — nur Modell → CSV-String (unit-testbar). Der
// Download (Blob + Anchor) passiert im App-Layer, analog zum Raum-CSV
// (geometry/roomArea → roomsToCsv) und zum Projekt-JSON-Speichern.
//
// Granularität: EINE Zeile je Bauteil-VORKOMMEN (Wand, Decke, Tür, Fenster/
// Öffnung, Treppe, Extrusion). Räume sind bewusst NICHT enthalten — die haben
// ihren eigenen CSV-Export (geometry/roomArea → roomsToCsv), keine Duplikation.
// Optional folgt darunter ein Aggregat-Block je Bauteil-Typ.
// Bezeichner englisch, Labels/Kommentare deutsch (CONVENTIONS.md). Einheit: METER.
// Bauteil-Schedule (Bauteilliste) — CSV-Export einer Bauteilaufstellung des Projekts
// (AUDIT A6, DOSSIER-Parität). Gerechnet wird im Rust-Kern (`src-tauri/core/src/export_schedule.rs`,
// [K4] S2) auf dem Projekt-Dokument: EINE Zeile je Bauteil-VORKOMMEN (Wand, Decke, Tür, Fenster,
// Treppe, Extrusion, Dach, Stütze); Räume sind bewusst nicht enthalten (eigener CSV-Export in
// `geometry/roomArea`). Optional folgt ein Aggregat-Block je Bauteil-Typ. Der Download
// (Blob + Anchor) passiert im App-Layer. Einheit: METER.
import type {
Project,
Wall,
Ceiling,
Opening,
Stair,
ExtrudedSolid,
Roof,
Column,
} from "../model/types";
import {
getWallType,
getCeilingType,
wallTypeThickness,
ceilingThickness,
} from "../model/types";
import { polygonArea } from "../geometry/roomArea";
// ── CSV-Primitive (RFC 4180, gespiegelt vom Raum-CSV) ───────────────────────
/** Ein Feld CSV-sicher quoten: „..." bei , " \n \r ; → " wird verdoppelt. */
function csvField(value: string): string {
if (/[",\n\r;]/.test(value)) {
return `"${value.replace(/"/g, '""')}"`;
}
return value;
}
/** Zahl auf 2 Nachkommastellen, Punkt als Dezimaltrenner. Leer bei null. */
function fmtNum(value: number | null | undefined): string {
if (value == null || !Number.isFinite(value)) return "";
return (Math.round(value * 100) / 100).toFixed(2);
}
// ── Kennwert-Ableitung (aus dem Modell, keine erfundenen Felder) ────────────
/** Achslänge einer Wand (Meter) = Abstand Start→End der Centerline. */
function wallLength(wall: Wall): number {
return Math.hypot(wall.end.x - wall.start.x, wall.end.y - wall.start.y);
}
/** Anzeigename eines Geschosses (oder die roh-ID, wenn unbekannt). */
function floorNameOf(project: Project, floorId: string): string {
return project.drawingLevels.find((z) => z.id === floorId)?.name ?? floorId;
}
import type { Project } from "../model/types";
import { documentFor } from "../core/document";
/** Bauteilklassen der Bauteilliste. */
export type ScheduleKind =
@@ -79,10 +31,8 @@ export interface ScheduleRow {
/** Geschoss-Name. */
floor: string;
/**
* Geschoss-ID (rohe DrawingLevel-Referenz, additiv für Konsumenten wie das
* Elemente-Panel — NICHT Teil der CSV-Spalten, siehe exportScheduleCsv).
* `undefined` bei verwaister/nicht auflösbarer Referenz (z. B. Tür/Öffnung
* mit gelöschter Wirtswand).
* Geschoss-ID (rohe DrawingLevel-Referenz, additiv für Konsumenten wie das Elemente-Panel — NICHT
* Teil der CSV-Spalten). Fehlt bei verwaister Referenz (z. B. Öffnung mit gelöschter Wirtswand).
*/
floorId?: string;
/** Achslänge bzw. lichte Breite in Metern (null wo nicht verlässlich ableitbar). */
@@ -95,200 +45,14 @@ export interface ScheduleRow {
area: number | null;
}
/** Wertet eine Wand für die Bauteilliste aus (defensiv gegen fehlende Typen). */
function evalWall(project: Project, wall: Wall): ScheduleRow {
let typeName = wall.wallTypeId;
let thickness = 0;
try {
const wt = getWallType(project, wall);
typeName = wt.name;
thickness = wallTypeThickness(wt);
} catch {
/* verwaister Wandtyp — Roh-ID + Dicke 0 */
}
const length = wallLength(wall);
return {
kind: "Wand",
id: wall.id,
typeName,
floor: floorNameOf(project, wall.floorId),
floorId: wall.floorId,
length,
heightM: wall.height,
thickness,
area: length * wall.height,
};
}
/** Wertet eine Decke für die Bauteilliste aus (defensiv gegen fehlende Typen). */
function evalCeiling(project: Project, ceiling: Ceiling): ScheduleRow {
let typeName = ceiling.ceilingTypeId ?? ceiling.wallTypeId;
try {
typeName = getCeilingType(project, ceiling).name;
} catch {
/* verwaister Deckentyp — Roh-ID */
}
return {
kind: "Decke",
id: ceiling.id,
typeName,
floor: floorNameOf(project, ceiling.floorId),
floorId: ceiling.floorId,
length: null,
heightM: null,
thickness: ceilingThickness(project, ceiling),
area: polygonArea(ceiling.outline),
};
}
/** Geschoss eines wandgehosteten Elements (Tür/Öffnung) über die Wirtswand. */
function floorOfHostWall(project: Project, hostWallId: string): string {
const wall = project.walls.find((w) => w.id === hostWallId);
if (!wall) return hostWallId; // verwaiste Wirtswand — Roh-ID, analog verwaister Typreferenzen
return floorNameOf(project, wall.floorId);
}
/** Rohe Geschoss-ID eines wandgehosteten Elements (Tür/Öffnung), oder `undefined` bei verwaister Wirtswand. */
function floorIdOfHostWall(project: Project, hostWallId: string): string | undefined {
return project.walls.find((w) => w.id === hostWallId)?.floorId;
}
/** Wertet eine Öffnung (Fenster oder Tür-Öffnung) für die Bauteilliste aus. */
function evalOpening(project: Project, opening: Opening): ScheduleRow {
const kind = opening.kind === "window" ? "Fenster" : "Tür";
return {
kind,
id: opening.id,
typeName: kind,
floor: floorOfHostWall(project, opening.hostWallId),
floorId: floorIdOfHostWall(project, opening.hostWallId),
length: opening.width,
heightM: opening.height,
thickness: null,
area: opening.width * opening.height,
};
}
/**
* Wertet eine Treppe für die Bauteilliste aus. Fläche bleibt bewusst leer —
* eine echte Footprint-Fläche bräuchte stairGeometry() (geometry/stair.ts)
* samt dessen Geschosshöhen-Fallback, den wir hier nicht koppeln wollen.
*/
function evalStair(project: Project, stair: Stair): ScheduleRow {
return {
kind: "Treppe",
id: stair.id,
typeName: "Treppe",
floor: floorNameOf(project, stair.floorId),
floorId: stair.floorId,
length: stair.runLength + (stair.run2Length ?? 0),
heightM: stair.totalRise ?? null,
thickness: null,
area: null,
};
}
/** Wertet einen extrudierten Körper für die Bauteilliste aus. */
function evalExtrudedSolid(project: Project, solid: ExtrudedSolid): ScheduleRow {
return {
kind: "Extrusion",
id: solid.id,
typeName: "Extrusion",
floor: floorNameOf(project, solid.levelId),
floorId: solid.levelId,
length: null,
heightM: solid.height,
thickness: null,
area: polygonArea(solid.points),
};
}
/** Wertet ein Dach für die Bauteilliste aus (defensiv gegen fehlenden Dachtyp). */
function evalRoof(project: Project, roof: Roof): ScheduleRow {
let typeName = roof.roofTypeId ?? roof.shape;
if (roof.roofTypeId) {
const rt = (project.roofTypes ?? []).find((t) => t.id === roof.roofTypeId);
if (rt) typeName = rt.name;
}
return {
kind: "Dach",
id: roof.id,
typeName,
floor: floorNameOf(project, roof.floorId),
floorId: roof.floorId,
length: null,
heightM: null,
thickness: roof.thickness,
area: polygonArea(roof.outline),
};
}
/** Wertet eine Stütze für die Bauteilliste aus (Querschnitt als „Dicke", Rechteck-Breite als „Länge"). */
function evalColumn(project: Project, column: Column): ScheduleRow {
return {
kind: "Stütze",
id: column.id,
typeName: column.profile.kind === "round" ? "Rund" : "Rechteck",
floor: floorNameOf(project, column.floorId),
floorId: column.floorId,
length: column.profile.kind === "rect" ? column.profile.width : null,
heightM: column.height,
thickness:
column.profile.kind === "rect" ? column.profile.depth : column.profile.radius * 2,
area: null,
};
}
/**
* Wertet ALLE Bauteil-Vorkommen eines Projekts aus (Wände, Decken, Türen,
* Fenster/Öffnungen, Treppen, Extrusionen, Dächer, Stützen — Räume bewusst
* ausgenommen, siehe Dateikopf). Reine Ableitung aus dem Modell — nichts wird
* gespeichert. Reihenfolge: Wände, Decken, Türen, Öffnungen, Treppen,
* Wertet ALLE Bauteil-Vorkommen eines Projekts aus. Reihenfolge: Wände, Decken, Öffnungen, Treppen,
* Extrusionen, Dächer, Stützen (je in Dokumentreihenfolge).
*/
export function scheduleRows(project: Project): ScheduleRow[] {
const rows: ScheduleRow[] = [];
for (const w of project.walls ?? []) rows.push(evalWall(project, w));
for (const c of project.ceilings ?? []) rows.push(evalCeiling(project, c));
for (const o of project.openings ?? []) rows.push(evalOpening(project, o));
for (const s of project.stairs ?? []) rows.push(evalStair(project, s));
for (const e of project.extrudedSolids ?? []) rows.push(evalExtrudedSolid(project, e));
for (const r of project.roofs ?? []) rows.push(evalRoof(project, r));
for (const c of project.columns ?? []) rows.push(evalColumn(project, c));
return rows;
return documentFor(project).query<ScheduleRow[]>("scheduleRows");
}
// ── Aggregat je Bauteil-Typ ─────────────────────────────────────────────────
interface TypeAggregate {
kind: ScheduleKind;
typeName: string;
count: number;
/** Summe der Längen (Meter) — Bauteile ohne Länge tragen 0 bei. */
totalLength: number;
/** Summe der Flächen (m²) — Bauteile ohne Fläche tragen 0 bei. */
totalArea: number;
}
/** Rollt die Zeilen je (Klasse + Typname) zu Zwischensummen zusammen. */
function aggregateByType(rows: ScheduleRow[]): TypeAggregate[] {
const map = new Map<string, TypeAggregate>();
for (const r of rows) {
const key = `${r.kind} ${r.typeName}`;
let agg = map.get(key);
if (!agg) {
agg = { kind: r.kind, typeName: r.typeName, count: 0, totalLength: 0, totalArea: 0 };
map.set(key, agg);
}
agg.count += 1;
agg.totalLength += r.length ?? 0;
agg.totalArea += r.area ?? 0;
}
return [...map.values()];
}
// ── CSV-Serialisierung ───────────────────────────────────────────────────────
export interface ScheduleCsvOptions {
/** Feldtrenner. Default „;" (Excel-DE-freundlich, wie der Raum-CSV). */
delimiter?: string;
@@ -296,69 +60,10 @@ export interface ScheduleCsvOptions {
includeSummary?: boolean;
}
/** Spaltenüberschriften der Bauteilliste (fix Deutsch, wie der Raum-CSV). */
const HEADER = [
"Typ",
"ID",
"Bauteil",
"Geschoss",
"Länge [m]",
"Höhe [m]",
"Dicke [m]",
"Fläche [m²]",
];
/**
* Baut die Bauteilliste des Projekts als CSV-String (kein Datei-IO). Eine Zeile
* je Bauteil-Vorkommen mit den aus dem Modell verlässlich ableitbaren
* Kennwerten; optional ein Aggregat-Block je Bauteil-Typ.
*
* Leeres Projekt ⇒ nur die Kopfzeile (kein Crash).
* Baut die Bauteilliste des Projekts als CSV-String (kein Datei-IO). Leeres Projekt ⇒ nur die
* Kopfzeile (kein Crash).
*/
export function exportScheduleCsv(
project: Project,
options: ScheduleCsvOptions = {},
): string {
const d = options.delimiter ?? ";";
const includeSummary = options.includeSummary ?? true;
const rows = scheduleRows(project);
const lines: string[] = [];
lines.push(HEADER.map(csvField).join(d));
for (const r of rows) {
lines.push(
[
csvField(r.kind),
csvField(r.id),
csvField(r.typeName),
csvField(r.floor),
fmtNum(r.length),
fmtNum(r.heightM),
fmtNum(r.thickness),
fmtNum(r.area),
].join(d),
);
}
if (includeSummary && rows.length > 0) {
lines.push(""); // Leerzeile trennt Liste von Aggregat
lines.push([csvField("Zusammenfassung (je Bauteil-Typ)"), "", "", "", "", "", "", ""].join(d));
for (const agg of aggregateByType(rows)) {
lines.push(
[
csvField(agg.kind),
"",
csvField(agg.typeName),
csvField(`${agg.count} Stk`),
agg.totalLength > 0 ? fmtNum(agg.totalLength) : "",
"",
"",
agg.totalArea > 0 ? fmtNum(agg.totalArea) : "",
].join(d),
);
}
}
return lines.join("\r\n");
export function exportScheduleCsv(project: Project, options: ScheduleCsvOptions = {}): string {
return documentFor(project).queryJson("scheduleCsv", [options.includeSummary ?? true ? 1 : 0], options.delimiter ?? ";");
}