Merge [209] Kostenschätzung grob

This commit is contained in:
Claude committed 2026-11-12 23:13:59 +00:00
commit 59de7ea7e7
28 files changed
+1595 -24

No files matched your search

+3 -4
View File
@@ -59,7 +59,7 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC.
oben ein Test; was fehlt, wird hier als Aufgabe eingetragen. · M
Umgesetzt (12.11.): `e2e/release10.spec.ts` spielt leeres Projekt → Kataster-DXF (LV95) → Baurecht → Wände/Decke/Dach → Raum +
Raumprogramm → SIA 416/Kennzahlen (CSV/PDF) → 1:200 → Schnitt → Axonometrie/Schatten → Präsentationsplan A1 → Publikation PDF → DXF/IFC
→ Speichern in 13 Schritten durch; fehlende Schritte als `test.fixme` ([207] [208] [209] [211] [222]–[224]; [221] und [225] seit 12.11. aktiv). Behoben: GV in der
→ Speichern in 13 Schritten durch; fehlende Schritte als `test.fixme` ([207] [208] [211] [222]–[224]; [209], [221] und [225] seit 12.11. aktiv). Behoben: GV in der
Kennzahlenleiste war ohne freie Körper 0 m³, neue Decken bekamen den Aussenwand-Aufbau statt eines Deckentyps. Offen: Durchlauf
der Checkliste auf dem Mac (Maintainer); 3D-Bild headless nicht prüfbar (kein WebGPU).
@@ -184,8 +184,6 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC.
Ort: `ui/PresentationDialog.tsx`, `commands/cmds/presentation.ts`. · S
### Phase 3 (27.11.–3.12.): Vorprojekt
- ○ **[209]** Kostenschätzung grob (Vorprojekt ±15–25 %): Kennwerte je m³ GV (SIA 416) bzw. je m² GF und eBKP-H-Hauptgruppen,
Kennwert-Tabelle im Projekt editierbar, Ergebnis als Tabelle/Layout-Element und CSV. · M
- 1:100-Pläne in Abgabequalität (Bemassung, Koten, Raumstempel, Öffnungen nach Detailgrad) — Plan-Review-Runde 4 nach [199].
- Fachplaner-Austausch: DXF/DWG je Geschoss/Schnitt/Ansicht ([200]), IFC mit Räumen/Psets ([201]); Rundreise in Archicad/Revit einmal
real prüfen ([C9]).
@@ -1046,7 +1044,7 @@ Punktwolken/BCF-Ausbau, Windows-Paket, [C5]/[C7]/[15] Kern-Umbauten — ausser s
Auf dem Mac (Tauri/Metal) noch nicht angesehen oder geprüft; bisher nur Linux-Container, CLI-SVG, Chromium oder
Unit-Tests: [116] (atomares Speichern), [117] (CSP unter `tauri://`), [118], [122], [123], [126], [110], [101],
[102], [131], [133], [136], [140], [145], [194], [146], [153], [64], [T2], [T4], [34], [108], [65], [169], [113], [181], [G1], [214]. Je Punkt ansehen, dann hier und
[102], [131], [133], [136], [140], [145], [194], [146], [153], [64], [T2], [T4], [34], [108], [65], [169], [113], [181], [G1], [214], [209]. Je Punkt ansehen, dann hier und
im jeweiligen Eintrag streichen. · M (gesamt)
---
@@ -1057,6 +1055,7 @@ Einzeilig mit ID, Titel, Datum (2026). Kleine Reste erledigter Punkte (z. B. [T7
exakte Durchdringung, [61] Zuordnung per Hand, [63] Profil je Kante, [70] Flächentabelle als Layout-Element,
[80] Einzelplan-PDF ohne Ebenen, [82] Legende per Ziehen) stehen im Archiv beim jeweiligen Eintrag.
- [209] Kostenschätzung grob (12.11.): Kennwert-Methode Menge × Kennwert je eBKP-H-Hauptgruppe B–J (Bezug m³ GV oder m² GF je Methode, wahlweise HNF/Fassade/Dach/pauschal), Honorare/Reserve/MwSt in %, Genauigkeit ±, Region- und Index-Faktor, Preisstand; `Project.costEstimate`, Kern `kosten.rs` (Mengen aus der SIA-416-Flächentabelle, eine Quelle mit [225]). Panel im Flächenbilanz-Panel, Blatt-Tabelle Quelle „costs", CSV/PDF wie der Flächen-Nachweis; e2e-Schritte 5b/10b in `release10.spec.ts`. Vorgaben sind Beispielwerte (≈ 800 CHF/m³ GV bzw. 2'600 CHF/m² GF, keine offizielle Quelle) und als solche markiert; belegt nur MwSt 8.1 % und die SIA-102-Genauigkeiten. Offen: Varianten nebeneinander, Kennwerte aus einer echten Quelle (Büro/CRB), Mac-Gegenprobe
- [185] Navigation wie Archicad (12.11.): Geschosswechsel behält den Ausschnitt, Cmd+5/6 Geschoss runter/hoch, Cmd+3 „3D · Auswahl", Cmd+4 Auswahl im 3D ausblenden.
- [195] Objekt-Einstellungsfenster (12.11.): Taste T öffnet die Objekteinstellungen (Objekt + Darstellung) für alle Bauteile; Weiterführung als natives Nebenfenster in [195b].
- [197] Cmd+3/4: Kamera bleibt stehen (`fitSeq` entfällt, Einpassen nur Cmd/Ctrl+Shift+F); bei „nur Auswahl" bleiben Dachfenster/Deckenöffnungen nicht mehr stehen (Öffnungen folgen ihrem Wirt Wand, Dach oder Decke, `classes.rs::opening_hosts`); Rust-Test + e2e (`navigation185`: Pick-Öffnungen nur der gewählten Wand). Nicht geprüft: Kamera im echten 3D (headless kein WebGPU) und nicht in der Tauri-App (12.11.)
+1
View File
@@ -293,6 +293,7 @@ Beispiel: Die Plan-Ansicht zeigt das Erdgeschoss im Massstab 1:100.
| PDF eines Plans | `src/export/exportPdf.ts`: `planToRenderScene()` → `sceneToPrintSvg()` (`src/export/sceneToPrintSvg.ts`) | `plan_scene_f64()` in `plan/scene.rs` | jsPDF und svg2pdf.js |
| Layout-Blatt, Blatt-PDF | `planToPrintSvg()` in `src/export/planToPrintSvg.ts`, aufgerufen von `src/ui/LayoutSheet.tsx` und `src/export/layoutPdf.ts` | `plan_print_svg_ops()` → `print_svg_ops()` in `plan/print_svg.rs` | SVG-Knoten in Papier-mm |
| Bild auf dem Layout-Blatt, Plakat-Vorlage ([208]) | `src/model/layoutImages.ts` (Data-URL, Zuschnitt), `src/model/posterTemplates.ts`, Bildzeichnen in `layoutPdf.ts` (`drawImagesPdf`, JPEG ohne Neukompression), `LayoutSheet.tsx` | `layout_image.rs`, `layout_poster.rs` über `layout_call` | `Layout.images`, Master mit Raster/Kopfzeile |
| Kostenschätzung grob ([209]) | Panel `src/panels/CostEstimateSection.tsx`, Fassade `src/analysis/costEstimate.ts`, Bericht `src/export/costReport.ts`, Blatt-Tabelle Quelle `costs` | `kosten.rs` (Abfragen `costEstimate`, `costDefaults`; Mengen aus `flaechen.rs`), `sheet_table.rs` | `Project.costEstimate`; CSV/PDF wie Flächen-Nachweis |
| DXF, DWG | `src/export/exportDxf.ts` | `plan_dxf_flat()` → `collect()`, `encode()` in `plan/dxf.rs` | `fileio`: `export_dxf()`, `export_dwg()` in `src-tauri/fileio/src/export.rs` |
Runde Formen (Stütze, Bogenwand, Bogen-Umrisse) reisen im Puffer als Vielecke; die Ausgaben erkennen die Bögen
+4 -1
View File
@@ -106,7 +106,10 @@ E 2'600'048 / N 1'200'046 und E 2'600'060 / N 1'200'056. Raumprogramm als CSV (`
| # | Schritt in Dossier | Erwartet | Status |
|---|---|---|---|
| 9.1 | Kennwerte je m³ GV / m² GF, eBKP-H-Hauptgruppen, Ergebnis als Tabelle/CSV | Kosten ±15–25 % | ❌ **[209]** |
| 9.1 | Flächenbilanz → „Kostenschätzung grob“: Methode CHF/m³ GV, Kennwert C ändern | Tabelle B–J mit Menge, Kennwert, Betrag; Summe B–J, Honorare, Reserve, Total exkl./inkl. MwSt, Bandbreite ±15 %; Beispielwerte als solche markiert | ✅ (Spec 5b) |
| 9.2 | Methode auf CHF/m² GF umstellen | Beispielwerte der Methode, eigene Kennwerte umgerechnet (Betrag gleich) | ✅ (Spec 5b) |
| 9.3 | „CSV“ / „PDF“ in der Kostenschätzung | CSV mit Zahlen ohne Tausender-Trenner, PDF A4 quer mit Fussnoten (Preisstand, Faktoren, Herkunft) | ✅ (Spec 5b; PDF nur auf %PDF- geprüft) |
| 9.4 | Layout-Blatt → „+ Tabelle“ → „Kostenschätzung grob (eBKP-H)“ | lebendige Tabelle auf dem Blatt, im Blatt-PDF | ✅ (Spec 10b; Bild auf dem Mac prüfen) |
## 10. Abgabe-Layouts als PDF
+53 -2
View File
@@ -1,7 +1,7 @@
// [206] Referenz-Ablauf „Wettbewerb/Vorprojekt" für Release 1.0 (TODO.md, Abschnitt „Release 1.0"):
// derselbe Ablauf wie die Mac-Abnahme-Checkliste `doc/RELEASE-1.0.md`, so weit er im Browser geht.
// Ein durchgehender Test (leeres Projekt → Kataster → Baurecht → Volumen → Raumprogramm → Pläne →
// Flächen/Kennzahlen → Abgabe-PDF → DXF/IFC), jeder Schritt ein `test.step` mit Prüfung des Ergebnisses.
// Flächen/Kennzahlen → Kostenschätzung → Abgabe-PDF → DXF/IFC), jeder Schritt ein `test.step` mit Prüfung des Ergebnisses.
// Schritte, die noch fehlen, stehen als eigene `test.fixme` mit TODO-ID unten — nicht weglassen, damit
// sichtbar bleibt, was für 1.0 fehlt.
// Netzabrufe (swisstopo/geo.admin) gibt es offline nicht: Grundstück und Nachbarbauten kommen aus der
@@ -173,6 +173,40 @@ test("Referenz-Ablauf WBW/Vorprojekt: leeres Projekt bis Abgabe", async ({ page
await areas.screenshot({ path: shotPath("05-flaechen") }).catch(() => undefined);
});
await test.step("5b Kostenschätzung grob: Kennwerte je m³ GV (eBKP-H), Total inkl. MwSt, CSV/PDF", async () => {
const cost = page.getByTestId("cost-section");
await cost.scrollIntoViewIfNeeded();
// Ohne eigene Werte: Beispielwerte, deutlich als solche markiert.
await expect(cost).toContainText("Beispielwerte, bitte anpassen");
await expect(cost.getByTestId("cost-rate-C")).toHaveValue("192");
const gross = cost.getByTestId("cost-gross");
await expect(gross).toContainText(/\d'\d{3}/);
await expect(cost.getByTestId("cost-range")).toContainText("±15 %");
const before = await gross.textContent();
// Kennwert C ändern: das Total folgt.
await cost.getByTestId("cost-rate-C").fill("250");
await cost.getByTestId("cost-rate-C").press("Enter");
await expect(gross).not.toHaveText(before ?? "");
const csv = await download(page, () => cost.getByTestId("cost-export-csv").click());
expect(csv.name).toMatch(/kosten\.csv$/);
const text = csv.bytes.toString("utf8");
expect(text).toContain("Konstruktion Gebäude");
expect(text).toMatch(/Total inkl\. MwSt\./);
expect(text).toMatch(/;250;/);
const pdf = await download(page, () => cost.getByTestId("cost-export-pdf").click());
expect(pdf.bytes.subarray(0, 5).toString("latin1")).toBe("%PDF-");
// Methode m² GF: Beispielwerte der Methode, eigene Werte umgerechnet.
await cost.getByTestId("cost-method").selectOption("gf");
await expect(cost.getByTestId("cost-rate-B")).toHaveValue("50");
if (process.env.DOSSIER_SHOTS) {
// Panel hoch genug, damit die ganze Kostenschätzung aufs Bild passt.
await page.setViewportSize({ width: 1600, height: 2600 });
await cost.scrollIntoViewIfNeeded();
await cost.screenshot({ path: shotPath("05b-kosten") }).catch(() => undefined);
await page.setViewportSize({ width: 1600, height: 1200 });
}
});
await test.step("6 Baurecht gegen Modell: Gebäude in der zulässigen Fläche, Höhe geprüft", async () => {
await openTab(page, "Gelände");
await expect(page.locator(".site-rules-result")).toContainText("Gebäude innerhalb der zulässigen Fläche");
@@ -230,6 +264,22 @@ test("Referenz-Ablauf WBW/Vorprojekt: leeres Projekt bis Abgabe", async ({ page
await shot(page, "10-praesentationsplan");
});
await test.step("10b Kostenschätzung als Layout-Element (Blatt-Tabelle eBKP-H)", async () => {
await page.locator("[data-table-add]").selectOption({ label: "Kostenschätzung grob (eBKP-H)" });
await expect(page.locator("[data-table-id] text", { hasText: /^Total inkl\. MwSt\./ })).toHaveCount(1);
await expect(page.locator("[data-table-id] text", { hasText: "Konstruktion Gebäude" })).toHaveCount(1);
await page.waitForTimeout(500);
if (process.env.DOSSIER_SHOTS) {
await page.locator(".layout-sheet-stage").screenshot({ path: shotPath("10b-kosten-blatt") }).catch(() => undefined);
// Tabelle allein als SVG (auf dem Übersichtsbild ist der Text zu klein zum Prüfen).
const svg = await page.locator("[data-table-id]").first().evaluate((g) => {
const b = (g as SVGGraphicsElement).getBBox();
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${b.x - 2} ${b.y - 2} ${b.width + 4} ${b.height + 4}" width="${(b.width + 4) * 8}" height="${(b.height + 4) * 8}" style="background:#fff">${g.outerHTML}</svg>`;
});
await writeFile(`${process.env.DOSSIER_SHOTS}/10b-kosten-tabelle.svg`, svg);
}
});
await test.step("11 Abgabe als PDF: Publikationssatz mit dem Blatt → PDF-Datei", async () => {
await openTab(page, "Mappe");
await page.locator("[data-publish-add]").click();
@@ -287,6 +337,8 @@ test("Referenz-Ablauf WBW/Vorprojekt: leeres Projekt bis Abgabe", async ({ page
expect(Math.max(sa[0].x, sa[1].x)).toBeGreaterThan(B.x1);
expect(line("Ansicht Süd")[0].y).toBeLessThan(B.y0);
expect(j.layouts.length).toBeGreaterThanOrEqual(1);
expect(j.costEstimate.method).toBe("gf");
expect(j.costEstimate.groups).toHaveLength(9);
if (process.env.DOSSIER_SHOTS) await writeFile(`${process.env.DOSSIER_SHOTS}/release10.obp`, saved.bytes);
});
});
@@ -301,7 +353,6 @@ test.fixme("[223] 3D-Bild für die Abgabe: hochaufgelöster PNG-Export (Perspekt
test.fixme("[211] Rendering mit Blender/Cycles aus der 3D-Ansicht", async () => {});
test.fixme("[209] Kostenschätzung grob (Kennwerte je m³ GV / m² GF, eBKP-H)", async () => {});
test.fixme("[224] Präsentationsplan: leere Geschosse nicht vorgewählt, Ansichten N/O/W aus dem Gebäude", async () => {});
+1
View File
@@ -92,6 +92,7 @@ Neues Modul: `<modul>.rs` und `mod` in `lib.rs`, Bindungen in `web/<modul>.rs` u
| `sun.rs` | Sonnenstand und Boden-Schatten |
| `site_rules.rs` | Baurecht der Parzelle |
| `kennzahlen.rs`, `flaechen.rs`, `area_report.rs` | Kennzahlen und Flächennachweise nach SIA 416 |
| `kosten.rs` | Kostenschätzung grob nach Kennwerten je eBKP-H-Hauptgruppe, Mengen aus `flaechen.rs` ([209]) |
| `room_program.rs`, `room_book.rs` | Raumprogramm (Soll/Ist), Raumbuch |
| `u_value.rs`, `clash_broad.rs` | U-Wert aus dem Schichtaufbau; Vorstufe der Kollisionsprüfung |
+34 -4
View File
@@ -7,12 +7,42 @@ use serde_json::{json, Value};
use crate::js_fmt::{js_number, to_fixed};
/// Zelle: Text oder Zahl (`d` Nachkommastellen, `n = null` = nicht berechenbar).
/// Zelle: Text oder Zahl (`d` Nachkommastellen, `n = null` = nicht berechenbar; `g`: Tausender mit
/// Apostroph in Blatt/PDF, z. B. Franken [209] — die CSV bleibt ohne Trenner).
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum Cell {
Text(String),
Num { n: Option<f64>, d: usize },
Num {
n: Option<f64>,
d: usize,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
g: bool,
},
}
/// Zahl wie `toFixed`, mit `g` Tausender-Apostroph (Schweizer Schreibweise, 1'234'567.50).
pub fn fmt_num(n: f64, d: usize, g: bool) -> String {
let s = to_fixed(n, d);
if !g {
return s;
}
let (sign, rest) = if let Some(r) = s.strip_prefix('-') { ("-", r) } else { ("", s.as_str()) };
let (int, frac) = match rest.find('.') {
Some(i) => (&rest[..i], &rest[i..]),
None => (rest, ""),
};
if !int.bytes().all(|b| b.is_ascii_digit()) {
return s;
}
let mut out = String::new();
for (i, ch) in int.chars().enumerate() {
if i > 0 && (int.len() - i) % 3 == 0 {
out.push('\'');
}
out.push(ch);
}
format!("{sign}{out}{frac}")
}
#[derive(Debug, Clone, Deserialize, Serialize)]
@@ -74,7 +104,7 @@ pub fn cell_text(c: &Cell) -> String {
match c {
Cell::Text(s) => s.clone(),
Cell::Num { n: None, .. } => String::new(),
Cell::Num { n: Some(n), d } => to_fixed(*n, *d),
Cell::Num { n: Some(n), d, .. } => to_fixed(*n, *d),
}
}
@@ -379,7 +409,7 @@ pub fn layout(report: &Report, o: &LayoutOptions) -> Layout {
.map(|c| match c {
Cell::Text(t) => t.clone(),
Cell::Num { n: None, .. } => "–".to_string(),
Cell::Num { n: Some(n), d } => to_fixed(*n, *d),
Cell::Num { n: Some(n), d, g } => fmt_num(*n, *d, *g),
})
.collect();
let total = r.total == Some(true);
+58 -1
View File
@@ -391,6 +391,15 @@ fn solid_volume_above(s: &SolidIn, base: f64) -> f64 {
/// Vereinigte Grundfläche der oberirdischen Bauteile (Wände, Räume, positive Körper).
fn above_ground_footprint(p: &Project) -> f64 {
let parts = above_ground_parts(p);
if parts.is_empty() {
return 0.0;
}
finite(multi_polygon_area(&polygon_bool::union(&parts))).max(0.0)
}
/// Grundrisse der oberirdischen Bauteile (Wände, Räume, positive Körper).
fn above_ground_parts(p: &Project) -> Vec<Polygon> {
let mut parts: Vec<Polygon> = Vec::new();
for l in p.drawing_levels.iter().filter(|l| l.kind == DrawingLevelKind::Floor && !is_underground(l)) {
parts.extend(wall_polygons(p, &l.id));
@@ -405,10 +414,58 @@ fn above_ground_footprint(p: &Project) -> f64 {
parts.push(vec![s.points.iter().map(|v| [v.x, v.y]).collect()]);
}
}
parts
}
/// [209] Fläche innerhalb der Aussenumrisse der oberirdischen Bauteile (Löcher gefüllt: ein Wandring ohne
/// Räume zählt als ganzes Gebäude, Innenhöfe werden nicht abgezogen). Dient als Dachfläche ohne Dachelement.
pub fn above_ground_outline_area(p: &Project) -> f64 {
let parts = above_ground_parts(p);
if parts.is_empty() {
return 0.0;
}
finite(multi_polygon_area(&polygon_bool::union(&parts))).max(0.0)
finite(polygon_bool::union(&parts).iter().filter_map(|poly| poly.first()).map(|r| signed_area(r).abs()).sum::<f64>()).max(0.0)
}
/// [209] Fassadenfläche (m²) der oberirdischen Geschosse, gleiche Quelle wie das GV: mit freien Körpern
/// deren Umfang × Höhe über ±0.00, sonst je Geschoss der Aussenumfang der vereinigten Wand- und
/// Raumgrundrisse × Geschosshöhe. Innenhöfe (Löcher) zählen nicht; Brüstungen/Attiken fehlen.
pub fn facade_area(p: &Project) -> f64 {
let perimeter = |r: &[[f64; 2]]| -> f64 { (0..r.len()).map(|i| crate::jsmath::hypot2(r[(i + 1) % r.len()][0] - r[i][0], r[(i + 1) % r.len()][1] - r[i][1])).sum() };
let t = area_table(p);
if t.gv_source == GvSource::Solids {
return p
.extruded_solids
.as_deref()
.unwrap_or(&[])
.iter()
.filter(|s| s.operation.as_deref() != Some("subtract"))
.map(|s| {
let base = p.floor(&s.level_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0)) + s.base_offset.unwrap_or(0.0);
let h = finite((base + s.height).min(s.height)).max(0.0);
let u = match &s.circle {
Some(c) => 2.0 * std::f64::consts::PI * finite(c.r).abs(),
None => perimeter(&s.points.iter().map(|v| [v.x, v.y]).collect::<Vec<_>>()),
};
finite(u * h)
})
.sum();
}
floors_sorted(p)
.into_iter()
.filter(|l| !is_underground(l))
.map(|l| {
let mut parts = wall_polygons(p, &l.id);
parts.extend(room_polygons(p, &l.id, |c| c < CATEGORIES && c != AGF));
if parts.is_empty() {
return 0.0;
}
let u: f64 = polygon_bool::union(&parts).iter().filter_map(|poly| poly.first()).map(|r| perimeter(r)).sum();
// Teilweise eingegrabenes Geschoss: nur der Teil über ±0.00.
let (base, h) = (l.base_elevation.unwrap_or(0.0), level_height(l));
finite(u * (base + h).min(h).max(0.0))
})
.sum()
}
/// IVHB-Kennziffern des Projekts.
+372
View File
@@ -0,0 +1,372 @@
//! Kostenschätzung grob ([209]) für Wettbewerb und Vorprojekt nach der Kennwert-Methode:
//! Kosten = Menge × Kennwert je eBKP-H-Hauptgruppe, dann Honorare, Reserve und MwSt in Prozent.
//!
//! # Gliederung (eBKP-H, SN 506 511 „Baukostenplan Hochbau“, CRB)
//!
//! ```text
//! B Vorbereitung · C Konstruktion Gebäude · D Technik Gebäude · E Äussere Wandbekleidung Gebäude
//! F Bedachung Gebäude · G Ausbau Gebäude · H Nutzungsspezifische Anlage Gebäude · I Umgebung Gebäude
//! J Ausstattung Gebäude (A Grundstück fehlt bewusst)
//! V Planungskosten (Honorare, %) · Y Reserve (%) · Z Mehrwertsteuer (%)
//! ```
//!
//! # Mengen (eine Quelle, [225])
//!
//! GV, GF und HNF kommen aus der SIA-416-Flächentabelle (`flaechen::area_table`), dieselben Zahlen wie
//! Flächen-Nachweis und Kennzahlenleiste. Fassade: `flaechen::facade_area`; Dach: geneigte Dachflächen
//! der Dächer (`u_value::element_schedule`), ohne Dach die Fläche im Aussenumriss der oberirdischen Bauteile
//! (Flachdach-Annahme, `flaechen::above_ground_outline_area`).
//!
//! # Vorgabewerte — BEISPIELWERTE, keine offiziellen Kennwerte
//!
//! Für Kennwerte je eBKP-H-Hauptgruppe gibt es keine frei zugängliche, verbindliche Quelle (Kennwerte
//! publizieren u. a. CRB „Werk-Kennwerte“, Bauökonomie-Büros und Fachzeitschriften, meist kostenpflichtig
//! und objektbezogen). Die Vorgaben unten sind darum eine runde Annahme für ein Wohn-/Bürogebäude mittleren
//! Standards (Grössenordnung Schweiz, Preisstand 2025): rund 800 CHF/m³ GV bzw. 2'600 CHF/m² GF für B–J,
//! aufgeteilt nach einer typischen Verteilung (B 2 %, C 24 %, D 20 %, E 13 %, F 5 %, G 25 %, H 2 %, I 6 %,
//! J 3 %). Sie sind in Panel, Tabelle und Export als „Beispielwert“ markiert, bis der Mensch sie ändert.
//! Belegt sind nur: MwSt 8.1 % (Normalsatz CH seit 1.1.2024, MWSTG Art. 25) und die üblichen Genauigkeiten
//! nach SIA 102 (Vorstudie/Grobschätzung ±25 %, Vorprojekt/Kostenschätzung ±15 %). Honorare 15 % und
//! Reserve 10 % sind ebenfalls Annahmen.
use crate::flaechen::{self, GvSource};
use crate::model::{CostBasis, CostEstimate, CostGroup, CostMethod, Project};
use serde::Serialize;
/// eBKP-H-Hauptgruppen B–J mit Beispiel-Kennwerten (CHF/m³ GV, CHF/m² GF), Preisstand 2025, s. Moduldoku.
pub const EXAMPLE_RATES: [(&str, f64, f64); 9] = [
("B", 16.0, 50.0),
("C", 192.0, 620.0),
("D", 160.0, 520.0),
("E", 104.0, 340.0),
("F", 40.0, 130.0),
("G", 200.0, 650.0),
("H", 16.0, 50.0),
("I", 48.0, 160.0),
("J", 24.0, 80.0),
];
pub const EXAMPLE_FEES_PCT: f64 = 15.0;
pub const EXAMPLE_RESERVE_PCT: f64 = 10.0;
/// Normalsatz der Schweizer MwSt seit 1.1.2024.
pub const VAT_PCT: f64 = 8.1;
/// SIA 102, Vorprojekt (Kostenschätzung).
pub const ACCURACY_PCT: f64 = 15.0;
pub const EXAMPLE_PRICE_BASE: &str = "2025";
/// Beispiel-Kennwert einer Hauptgruppe für die Methode.
pub fn example_rate(code: &str, method: CostMethod) -> Option<f64> {
EXAMPLE_RATES.iter().find(|(c, _, _)| *c == code).map(|&(_, gv, gf)| if method == CostMethod::Gf { gf } else { gv })
}
/// Vorgabe der Kostenschätzung (Beispielwerte) für eine Methode.
pub fn default_estimate(method: CostMethod) -> CostEstimate {
let method = if method == CostMethod::Gf { CostMethod::Gf } else { CostMethod::Gv };
CostEstimate {
method,
groups: EXAMPLE_RATES
.iter()
.map(|&(code, gv, gf)| CostGroup { code: code.to_string(), name: None, basis: CostBasis::Method, rate: if method == CostMethod::Gf { gf } else { gv }, extra: Default::default() })
.collect(),
fees_pct: EXAMPLE_FEES_PCT,
reserve_pct: EXAMPLE_RESERVE_PCT,
vat_pct: VAT_PCT,
accuracy_pct: ACCURACY_PCT,
region_factor: 1.0,
index_factor: 1.0,
price_base: EXAMPLE_PRICE_BASE.to_string(),
extra: Default::default(),
}
}
/// Mengen aus dem Modell.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CostQuantities {
pub gv: f64,
pub gf: f64,
pub hnf: f64,
pub facade: f64,
pub roof: f64,
pub gv_source: Option<GvSource>,
}
/// Eine Zeile des Ergebnisses (eine Kennwert-Zeile).
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CostRow {
pub code: String,
/// Eigene Bezeichnung (sonst übersetzt die UI den eBKP-H-Namen aus `code`).
pub name: Option<String>,
/// Aufgelöste Bezugsmenge (nie `method`).
pub basis: CostBasis,
pub quantity: f64,
/// „m³“, „m²“ oder „" (pauschal).
pub unit: &'static str,
pub rate: f64,
/// Menge × Kennwert × Region × Index.
pub amount: f64,
/// Kennwert ist (noch) der Beispielwert.
pub example: bool,
}
/// Ergebnis der Kostenschätzung (CHF).
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CostResult {
pub method: CostMethod,
pub quantities: CostQuantities,
pub rows: Vec<CostRow>,
/// Region × Index.
pub factor: f64,
pub region_factor: f64,
pub index_factor: f64,
/// Summe der Gruppen (B–J).
pub subtotal: f64,
pub fees_pct: f64,
pub fees: f64,
pub reserve_pct: f64,
pub reserve: f64,
/// Total exkl. MwSt.
pub net: f64,
pub vat_pct: f64,
pub vat: f64,
/// Total inkl. MwSt.
pub gross: f64,
pub accuracy_pct: f64,
/// Bandbreite des Totals inkl. MwSt.
pub low: f64,
pub high: f64,
/// Total inkl. MwSt. je m³ GV bzw. m² GF (`None` ohne Menge).
pub per_gv: Option<f64>,
pub per_gf: Option<f64>,
pub price_base: String,
/// Kein `costEstimate` im Projekt: alles Vorgaben.
pub is_default: bool,
/// Mindestens ein Kennwert ist ein Beispielwert.
pub has_example: bool,
/// Hinweis-Schlüssel (`costs.note.*`).
pub notes: Vec<String>,
}
fn pct(v: f64) -> f64 {
if v.is_finite() {
v.max(0.0)
} else {
0.0
}
}
fn factor(v: f64) -> f64 {
if v.is_finite() && v > 0.0 {
v
} else {
1.0
}
}
/// Mengen des Projekts (eine Quelle: Flächentabelle).
pub fn quantities(p: &Project) -> (CostQuantities, bool) {
let t = flaechen::area_table(p);
let roofs: f64 = crate::u_value::element_schedule(p).iter().filter(|r| r.kind == crate::u_value::Kind::Roof).map(|r| r.area).filter(|a| a.is_finite()).sum();
let roof_from_footprint = roofs <= 1e-9;
let roof = if roof_from_footprint { flaechen::above_ground_outline_area(p) } else { roofs };
(CostQuantities { gv: t.gv, gf: t.total.gf, hnf: t.total.hnf, facade: flaechen::facade_area(p), roof, gv_source: Some(t.gv_source) }, roof_from_footprint)
}
/// Kostenschätzung des Projekts (ohne `costEstimate` mit den Beispielwerten).
pub fn estimate(p: &Project) -> CostResult {
let is_default = p.cost_estimate.is_none();
let est = p.cost_estimate.clone().unwrap_or_else(|| default_estimate(CostMethod::Gv));
let method = if est.method == CostMethod::Gf { CostMethod::Gf } else { CostMethod::Gv };
let (q, roof_from_footprint) = quantities(p);
let region = factor(est.region_factor);
let index = factor(est.index_factor);
let f = region * index;
let mut notes: Vec<String> = Vec::new();
let rows: Vec<CostRow> = est
.groups
.iter()
.map(|g| {
let basis = match g.basis {
CostBasis::Method | CostBasis::Unknown => {
if method == CostMethod::Gf {
CostBasis::Gf
} else {
CostBasis::Gv
}
}
b => b,
};
let (quantity, unit) = match basis {
CostBasis::Gv => (q.gv, "m³"),
CostBasis::Gf => (q.gf, "m²"),
CostBasis::Hnf => (q.hnf, "m²"),
CostBasis::Facade => (q.facade, "m²"),
CostBasis::Roof => (q.roof, "m²"),
_ => (1.0, ""),
};
let rate = if g.rate.is_finite() { g.rate } else { 0.0 };
let quantity = if quantity.is_finite() { quantity } else { 0.0 };
// Beispielwert: Bezug der Methode und Kennwert wie die Vorgabe.
let example = matches!(g.basis, CostBasis::Method) && example_rate(&g.code, method).is_some_and(|r| (r - rate).abs() < 1e-9);
CostRow { code: g.code.clone(), name: g.name.clone().filter(|s| !s.trim().is_empty()), basis, quantity, unit, rate, amount: quantity * rate * f, example }
})
.collect();
let subtotal: f64 = rows.iter().map(|r| r.amount).sum();
let (fees_pct, reserve_pct, vat_pct, accuracy_pct) = (pct(est.fees_pct), pct(est.reserve_pct), pct(est.vat_pct), pct(est.accuracy_pct));
let fees = subtotal * fees_pct / 100.0;
let reserve = (subtotal + fees) * reserve_pct / 100.0;
let net = subtotal + fees + reserve;
let vat = net * vat_pct / 100.0;
let gross = net + vat;
let has_example = rows.iter().any(|r| r.example);
if has_example {
notes.push("example".into());
}
if q.gv <= 1e-9 && q.gf <= 1e-9 {
notes.push("noQuantity".into());
}
notes.push(if q.gv_source == Some(GvSource::Solids) { "gvSolids" } else { "gvLevels" }.into());
if rows.iter().any(|r| r.basis == CostBasis::Facade) {
notes.push("facade".into());
}
if roof_from_footprint && rows.iter().any(|r| r.basis == CostBasis::Roof) {
notes.push("roofFootprint".into());
}
notes.push("accuracy".into());
let per = |m: f64| if m > 1e-9 { Some(gross / m) } else { None };
CostResult {
method,
rows,
factor: f,
region_factor: region,
index_factor: index,
subtotal,
fees_pct,
fees,
reserve_pct,
reserve,
net,
vat_pct,
vat,
gross,
accuracy_pct,
low: gross * (1.0 - accuracy_pct / 100.0),
high: gross * (1.0 + accuracy_pct / 100.0),
per_gv: per(q.gv),
per_gf: per(q.gf),
price_base: est.price_base.clone(),
is_default,
has_example,
notes,
quantities: q,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::{DrawingLevel, DrawingLevelKind, Vec2, Wall};
fn level(id: &str, base: f64, h: f64) -> DrawingLevel {
DrawingLevel { id: id.into(), name: id.into(), kind: DrawingLevelKind::Floor, base_elevation: Some(base), floor_height: Some(h), ..Default::default() }
}
fn wall(id: &str, a: (f64, f64), b: (f64, f64)) -> Wall {
Wall { id: id.into(), floor_id: "eg".into(), start: Vec2 { x: a.0, y: a.1 }, end: Vec2 { x: b.0, y: b.1 }, height: 3.0, ..Default::default() }
}
/// 10 × 8 m Achsmass, Wände 20 cm, ein Geschoss 3 m.
fn box_project() -> Project {
let mut p = Project { drawing_levels: vec![level("eg", 0.0, 3.0)], ..Default::default() };
p.walls = vec![wall("a", (0.0, 0.0), (10.0, 0.0)), wall("b", (10.0, 0.0), (10.0, 8.0)), wall("c", (10.0, 8.0), (0.0, 8.0)), wall("d", (0.0, 8.0), (0.0, 0.0))];
p
}
#[test]
fn vorgaben_sind_beispielwerte_und_summen_stimmen() {
let gv: f64 = EXAMPLE_RATES.iter().map(|r| r.1).sum();
let gf: f64 = EXAMPLE_RATES.iter().map(|r| r.2).sum();
assert_eq!(gv, 800.0);
assert_eq!(gf, 2600.0);
let d = default_estimate(CostMethod::Gf);
assert_eq!(d.groups.len(), 9);
assert_eq!(d.groups[1].rate, 620.0);
assert_eq!(d.vat_pct, 8.1);
}
#[test]
fn mengen_aus_der_flaechentabelle() {
let p = box_project();
let r = estimate(&p);
let t = flaechen::area_table(&p);
assert!(r.is_default && r.has_example);
assert_eq!(r.quantities.gv, t.gv);
assert_eq!(r.quantities.gf, t.total.gf);
// Aussenmass 10.2 × 8.2 m: Umfang 36.8 m × 3 m.
assert!((r.quantities.facade - 36.8 * 3.0).abs() < 1e-3, "{}", r.quantities.facade);
// Kein Dach: Grundfläche 10.2 × 8.2.
assert!((r.quantities.roof - 10.2 * 8.2).abs() < 1e-3, "{}", r.quantities.roof);
assert!(r.notes.iter().any(|n| n == "example"));
}
#[test]
fn rechnung_mit_zuschlaegen() {
let mut p = box_project();
let gv = flaechen::area_table(&p).gv;
assert!(gv > 0.0);
p.cost_estimate = Some(CostEstimate {
method: CostMethod::Gv,
groups: vec![
CostGroup { code: "B–J".into(), name: Some("Gebäude".into()), basis: CostBasis::Method, rate: 1000.0, extra: Default::default() },
CostGroup { code: "E".into(), basis: CostBasis::Facade, rate: 100.0, ..Default::default() },
CostGroup { code: "X".into(), basis: CostBasis::Lump, rate: 5000.0, ..Default::default() },
],
fees_pct: 10.0,
reserve_pct: 10.0,
vat_pct: 8.1,
accuracy_pct: 20.0,
region_factor: 1.1,
index_factor: 0.0, // ungültig ⇒ 1
price_base: "Okt. 2025".into(),
extra: Default::default(),
});
let r = estimate(&p);
assert!(!r.is_default && !r.has_example);
assert_eq!(r.rows[0].basis, CostBasis::Gv);
assert_eq!(r.rows[0].unit, "m³");
assert!((r.rows[0].amount - gv * 1000.0 * 1.1).abs() < 1e-6);
assert!((r.rows[1].amount - r.quantities.facade * 100.0 * 1.1).abs() < 1e-6);
assert_eq!(r.rows[2].quantity, 1.0);
assert!((r.rows[2].amount - 5500.0).abs() < 1e-9);
let sub = r.rows.iter().map(|x| x.amount).sum::<f64>();
assert!((r.subtotal - sub).abs() < 1e-9);
assert!((r.fees - sub * 0.1).abs() < 1e-6);
assert!((r.reserve - sub * 1.1 * 0.1).abs() < 1e-6);
assert!((r.net - sub * 1.1 * 1.1).abs() < 1e-6);
assert!((r.gross - r.net * 1.081).abs() < 1e-6);
assert!((r.low - r.gross * 0.8).abs() < 1e-6 && (r.high - r.gross * 1.2).abs() < 1e-6);
assert!((r.per_gv.unwrap() - r.gross / gv).abs() < 1e-9);
assert!(r.notes.iter().any(|n| n == "facade"));
}
#[test]
fn methode_gf_und_kaputte_werte_ohne_panic() {
let mut p = box_project();
let mut e = default_estimate(CostMethod::Gf);
e.groups.push(CostGroup { code: "Z?".into(), basis: CostBasis::Unknown, rate: f64::NAN, ..Default::default() });
e.fees_pct = f64::NAN;
e.vat_pct = -5.0;
p.cost_estimate = Some(e);
let r = estimate(&p);
assert_eq!(r.rows[0].unit, "m²");
assert!(r.rows.iter().take(9).all(|x| x.example));
assert!(r.gross.is_finite() && r.fees == 0.0 && r.vat == 0.0);
// Leeres Projekt: alles 0, keine Kennwerte je Menge.
let r0 = estimate(&Project::default());
assert_eq!(r0.gross, 0.0);
assert!(r0.per_gv.is_none());
assert!(r0.notes.iter().any(|n| n == "noQuantity"));
}
}
+1
View File
@@ -145,5 +145,6 @@ pub mod opening_slide;
mod web;
pub mod presentation_sheet;
pub mod drawing_recognize;
pub mod kosten;
#[cfg(test)]
mod wall_join3d_tests;
+108
View File
@@ -5563,6 +5563,9 @@ pub enum LayoutTableSource {
/// [158] Raumbuch: Oberflächen je Raum.
#[serde(rename = "roomBook")]
RoomBook,
/// [209] Kostenschätzung grob (eBKP-H-Hauptgruppen, Zuschläge, Total).
#[serde(rename = "costs")]
Costs,
#[serde(other)]
#[ts(skip)]
Unknown,
@@ -5764,6 +5767,101 @@ pub struct CompetitionSettings {
pub extra: Extra,
}
/// [209] Bezugsmenge eines Kostenkennwerts (Kostenschätzung nach der Kennwert-Methode).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, TS)]
pub enum CostBasis {
/// Die Menge der Methode des Projekts (`CostEstimate.method`: m³ GV oder m² GF).
#[default]
#[serde(rename = "method")]
Method,
/// Gebäudevolumen GV (m³, SIA 416).
#[serde(rename = "gv")]
Gv,
/// Geschossfläche GF (m², SIA 416).
#[serde(rename = "gf")]
Gf,
/// Hauptnutzfläche HNF (m², SIA 416).
#[serde(rename = "hnf")]
Hnf,
/// Fassadenfläche (m², Aussenumfang × Geschosshöhe).
#[serde(rename = "facade")]
Facade,
/// Dachfläche (m², geneigte Dachflächen, ohne Dach die oberirdische Grundfläche).
#[serde(rename = "roof")]
Roof,
/// Pauschal: der Kennwert ist der Betrag (Menge 1).
#[serde(rename = "lump")]
Lump,
#[serde(other)]
#[ts(skip)]
Unknown,
}
/// [209] Hauptmenge der Kostenschätzung: m³ GV oder m² GF.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, TS)]
pub enum CostMethod {
#[default]
#[serde(rename = "gv")]
Gv,
#[serde(rename = "gf")]
Gf,
#[serde(other)]
#[ts(skip)]
Unknown,
}
/// [209] Eine Zeile der Kennwert-Tabelle: eBKP-H-Hauptgruppe (B–J) oder eine zusammengefasste Gruppe.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
#[serde(default)]
pub struct CostGroup {
/// Kennung der Gruppe nach eBKP-H (SN 506 511), z. B. „C“ oder „B–J“.
pub code: String,
/// Eigene Bezeichnung; fehlt = Name der eBKP-H-Hauptgruppe (aus `code`).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub name: Option<String>,
pub basis: CostBasis,
/// Kennwert in CHF je Einheit der Bezugsmenge (pauschal: CHF).
pub rate: f64,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
}
/// [209] Grobe Kostenschätzung (Vorprojekt/Wettbewerb) nach der Kennwert-Methode: Menge × Kennwert je
/// eBKP-H-Hauptgruppe, dazu Honorare, Reserve und MwSt in Prozent. Fehlt das Feld, rechnet der Kern mit
/// Beispielwerten (`kosten::default_estimate`).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
#[serde(default)]
pub struct CostEstimate {
pub method: CostMethod,
pub groups: Vec<CostGroup>,
/// Honorare (eBKP-H V) in % der Summe B–J.
#[serde(rename = "feesPct")]
pub fees_pct: f64,
/// Reserve/Unvorhergesehenes (eBKP-H Y) in % der Summe B–J + Honorare.
#[serde(rename = "reservePct")]
pub reserve_pct: f64,
/// Mehrwertsteuer (eBKP-H Z) in %.
#[serde(rename = "vatPct")]
pub vat_pct: f64,
/// Genauigkeit der Schätzung ± in %.
#[serde(rename = "accuracyPct")]
pub accuracy_pct: f64,
/// Region-Faktor auf alle Kennwerte (1 = keiner).
#[serde(rename = "regionFactor")]
pub region_factor: f64,
/// Teuerung vom Preisstand der Kennwerte bis heute als Faktor (Baupreisindex neu / alt; 1 = keine).
#[serde(rename = "indexFactor")]
pub index_factor: f64,
/// Preisstand der Kennwerte (Text, z. B. „Okt. 2025, Baupreisindex Hochbau“).
#[serde(rename = "priceBase")]
pub price_base: String,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
}
/// Grafische Legende auf einem Layout-Blatt ([82]): listet Schraffuren/Materialien, Linientypen und/oder
/// Kategorien der gezeigten Viewports (`manualKeys` leer) oder einer Handauswahl, mit Muster und Name.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
@@ -6298,6 +6396,10 @@ pub struct Project {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub competition: Option<CompetitionSettings>,
/// [209] Kostenschätzung grob (Kennwerte, Zuschläge); fehlt = Beispielwerte.
#[serde(rename = "costEstimate", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub cost_estimate: Option<CostEstimate>,
/// Höhe von ±0.00 (OK fertig Boden des Bezugsgeschosses, `DrawingLevel.zeroLevel`)
/// in Metern über Meer (m ü. M.), editierbar im Einstellungs-Fenster. Optional.
/// Die automatischen Koten im Schnitt/in der Ansicht schreiben „±0.00 = 512.40"
@@ -7167,6 +7269,12 @@ impl Project {
None => Default::default(),
};
}
"costEstimate" => {
self.cost_estimate = match v {
Some(v) => <Option<CostEstimate>>::deserialize(v).map_err(|e| e.to_string())?,
None => Default::default(),
};
}
"referenceElevationMasl" => {
self.reference_elevation_masl = match v {
Some(v) => <Option<f64>>::deserialize(v).map_err(|e| e.to_string())?,
+2 -1
View File
@@ -15,7 +15,7 @@ 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; 58] = [
const KNOWN_KEYS: [&str; 59] = [
"formatVersion", "id", "name", "lineStyles", "textStyles", "hatches", "components", "wallTypes",
"ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens",
"penSets", "activePenSetId", "customPalettes", "builtinPaletteBanks", "drawingLevels", "layers",
@@ -25,6 +25,7 @@ const KNOWN_KEYS: [&str; 58] = [
"geoAnchor", "roomProgram", "roomProgramTolerance", "parcelArea", "sunStudy", "siteRules", "scaleLineWeights",
"lineCap", "lineJoin", "trees", "uiState",
"modelViewOptions", "cameras",
"costEstimate",
];
/// Ergebnis des Einlesens.
+3
View File
@@ -68,6 +68,9 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
match (name, args.len()) {
("kennzahlen", _) => json(&kennzahlen::compute(p)),
("areaTable", _) => json(&flaechen::area_table(p)),
// [209] Kostenschätzung grob; `costDefaults` mit Text „gf“/„gv“ = Beispielwerte der Methode.
("costEstimate", _) => json(&crate::kosten::estimate(p)),
("costDefaults", _) => json(&crate::kosten::default_estimate(if text.trim() == "gf" { crate::model::CostMethod::Gf } else { crate::model::CostMethod::Gv })),
("ivhb", _) => {
let opt: flaechen::IvhbOptions = if text.trim().is_empty() { Default::default() } else { serde_json::from_str(text).map_err(|e| format!("ivhb: {e}"))? };
json(&flaechen::ivhb(p, &opt))
+79 -5
View File
@@ -118,6 +118,16 @@ const ROOM_BOOK: &[Col] = &[
c("wet", "roomBook.col.wet", 1.0, false, false),
];
/// [209] Kostenschätzung grob.
const COSTS: &[Col] = &[
c("code", "sheetTable.col.costCode", 0.9, false, true),
c("group", "sheetTable.col.costGroup", 3.6, false, true),
c("quantity", "sheetTable.col.quantity", 1.4, true, true),
c("unit", "sheetTable.col.unit", 0.8, false, true),
c("rate", "sheetTable.col.rate", 1.3, true, true),
c("amount", "sheetTable.col.amount", 1.8, true, true),
];
/// [158] Raumbuch-Spalten, die nur erscheinen, wenn ein Raum eine Dachschräge hat.
const SLOPE_COLS: &[&str] = &["heightMin", "heightMean", "areaUnder1", "area1To15"];
@@ -152,6 +162,22 @@ pub const VALUE_KEYS: &[&str] = &[
"roomBook.usage.office",
"roomBook.usage.other",
"roomBook.wet",
"costs.group.B",
"costs.group.C",
"costs.group.D",
"costs.group.E",
"costs.group.F",
"costs.group.G",
"costs.group.H",
"costs.group.I",
"costs.group.J",
"costs.row.subtotal",
"costs.row.fees",
"costs.row.reserve",
"costs.row.net",
"costs.row.vat",
"costs.row.gross",
"costs.lump",
];
pub fn catalog(source: LayoutTableSource) -> &'static [Col] {
@@ -162,6 +188,7 @@ pub fn catalog(source: LayoutTableSource) -> &'static [Col] {
LayoutTableSource::Elements => ELEMENTS,
LayoutTableSource::Earthworks => EARTHWORKS,
LayoutTableSource::RoomBook => ROOM_BOOK,
LayoutTableSource::Costs => COSTS,
}
}
@@ -169,7 +196,7 @@ pub fn catalog(source: LayoutTableSource) -> &'static [Col] {
pub fn catalog_json() -> Value {
let one = |s: &[Col]| s.iter().map(|k| json!({"id": k.id, "key": k.key, "numeric": k.numeric, "default": k.default})).collect::<Vec<_>>();
json!({
"sources": {"openings": one(OPENINGS), "areas": one(AREAS), "rooms": one(ROOMS), "elements": one(ELEMENTS), "earthworks": one(EARTHWORKS), "roomBook": one(ROOM_BOOK)},
"sources": {"openings": one(OPENINGS), "areas": one(AREAS), "rooms": one(ROOMS), "elements": one(ELEMENTS), "earthworks": one(EARTHWORKS), "roomBook": one(ROOM_BOOK), "costs": one(COSTS)},
"valueKeys": VALUE_KEYS,
})
}
@@ -188,7 +215,7 @@ impl Labels {
}
fn num(n: f64, d: usize) -> Cell {
Cell::Num { n: if n.is_finite() { Some(n) } else { None }, d }
Cell::Num { n: if n.is_finite() { Some(n) } else { None }, d, g: false }
}
fn txt(s: impl Into<String>) -> Cell {
Cell::Text(s.into())
@@ -233,7 +260,7 @@ fn openings_data(p: &Project, filter: Option<&str>, lb: &Labels) -> Data {
txt(swing),
txt(r.fire_rating),
txt(r.sound_class),
Cell::Num { n: r.u_value, d: 2 },
Cell::Num { n: r.u_value, d: 2, g: false },
txt(r.burglary_class),
txt(match r.external {
Some(true) => lb.get("openings.external"),
@@ -262,7 +289,7 @@ fn rooms_data(p: &Project) -> Data {
let rows = cmp
.rows
.iter()
.map(|r| vec![txt(r.name.clone()), opt(&r.group), num(r.target_count as f64, 0), num(r.target_area, 2), num(r.soll, 2), num(r.ist, 2), num(r.diff, 2), Cell::Num { n: r.diff_pct.map(|v| v * 100.0), d: 1 }])
.map(|r| vec![txt(r.name.clone()), opt(&r.group), num(r.target_count as f64, 0), num(r.target_area, 2), num(r.soll, 2), num(r.ist, 2), num(r.diff, 2), Cell::Num { n: r.diff_pct.map(|v| v * 100.0), d: 1, g: false }])
.collect();
Data { rows, sloped: false, total_last: false }
}
@@ -305,6 +332,7 @@ fn data_of(p: &Project, t: &LayoutTable, lb: &Labels) -> Data {
LayoutTableSource::Elements => elements_data(p, lb),
LayoutTableSource::Earthworks => earthworks_data(p, lb),
LayoutTableSource::RoomBook => room_book_data(p, lb),
LayoutTableSource::Costs => costs_data(p, lb),
}
}
@@ -342,6 +370,31 @@ fn room_book_data(p: &Project, lb: &Labels) -> Data {
Data { rows, sloped, total_last: false }
}
/// [209] Kostenschätzung: eine Zeile je Kennwert, dann Summe B–J, Honorare, Reserve, Total exkl. MwSt, MwSt und
/// Total inkl. MwSt mit Genauigkeit (Summenzeile). Beträge in CHF mit Tausender-Apostroph.
fn costs_data(p: &Project, lb: &Labels) -> Data {
let r = crate::kosten::estimate(p);
let chf = |n: f64| Cell::Num { n: if n.is_finite() { Some(n) } else { None }, d: 0, g: true };
let empty = || txt("");
let mut rows: Vec<Vec<Cell>> = r
.rows
.iter()
.map(|g| {
let name = g.name.clone().unwrap_or_else(|| lb.get(&format!("costs.group.{}", g.code)));
let unit = if g.unit.is_empty() { lb.get("costs.lump") } else { g.unit.to_string() };
vec![txt(g.code.clone()), txt(name), Cell::Num { n: Some(g.quantity), d: if g.unit.is_empty() { 0 } else { 1 }, g: true }, txt(unit), chf(g.rate), chf(g.amount)]
})
.collect();
let pct = |label: &str, v: f64| format!("{} {} %", lb.get(label), to_fixed(v, 1).trim_end_matches(".0"));
rows.push(vec![empty(), txt(lb.get("costs.row.subtotal")), empty(), empty(), empty(), chf(r.subtotal)]);
rows.push(vec![txt("V"), txt(pct("costs.row.fees", r.fees_pct)), empty(), empty(), empty(), chf(r.fees)]);
rows.push(vec![txt("Y"), txt(pct("costs.row.reserve", r.reserve_pct)), empty(), empty(), empty(), chf(r.reserve)]);
rows.push(vec![empty(), txt(lb.get("costs.row.net")), empty(), empty(), empty(), chf(r.net)]);
rows.push(vec![txt("Z"), txt(pct("costs.row.vat", r.vat_pct)), empty(), empty(), empty(), chf(r.vat)]);
rows.push(vec![empty(), txt(format!("{} (±{} %)", lb.get("costs.row.gross"), to_fixed(r.accuracy_pct, 0))), empty(), empty(), empty(), chf(r.gross)]);
Data { rows, sloped: false, total_last: true }
}
/// [68] Erdarbeiten je Baugrube (m³ gegen das gewachsene Terrain) mit Summenzeile.
fn earthworks_data(p: &Project, lb: &Labels) -> Data {
let q = crate::excavation::quantities(p);
@@ -413,7 +466,7 @@ fn cell_text(c: &Cell) -> String {
match c {
Cell::Text(s) => s.clone(),
Cell::Num { n: None, .. } => "–".to_string(),
Cell::Num { n: Some(n), d } => to_fixed(*n, *d),
Cell::Num { n: Some(n), d, g } => crate::area_report::fmt_num(*n, *d, *g),
}
}
@@ -756,4 +809,25 @@ mod tests {
assert_eq!(query(&p, r#"{"layoutId":"nix"}"#), json!([]));
assert!(catalog_json()["sources"]["elements"].as_array().unwrap().len() >= 6);
}
/// [209] Kostenschätzung als Blatt-Tabelle: Gruppen beschriftet, Franken mit Apostroph, Total als Summenzeile.
#[test]
fn kosten_tabelle() {
let mut t = table("k", None);
t.source = LayoutTableSource::Costs;
let mut p = project(0, vec![t]);
p.drawing_levels[0].floor_height = Some(3.0);
let r = render(&p, &p.layouts.as_ref().unwrap()[0], &Labels::parse(&json!({"costs.group.C": "Konstruktion", "costs.row.gross": "Total inkl. MwSt."})));
assert_eq!(r[0].total, 9 + 6, "9 Hauptgruppen + Summe, V, Y, exkl., MwSt, inkl.");
let tx = texts(&r[0]);
assert!(tx.contains(&"Konstruktion".to_string()), "{tx:?}");
let gross = crate::kosten::estimate(&p).gross;
assert!(gross > 1000.0);
assert!(tx.contains(&crate::area_report::fmt_num(gross, 0, true)), "{tx:?}");
assert!(tx.iter().any(|s| s.starts_with("Total inkl. MwSt. (±15 %)")), "{tx:?}");
assert_eq!(serde_json::to_value(LayoutTableSource::Costs).unwrap(), "costs");
assert_eq!(crate::area_report::fmt_num(1234567.5, 2, true), "1'234'567.50");
assert_eq!(crate::area_report::fmt_num(-999.0, 0, true), "-999");
assert_eq!(crate::area_report::fmt_num(-1000.0, 0, true), "-1'000");
}
}
+79
View File
@@ -0,0 +1,79 @@
// Kostenschätzung grob ([209]): Menge × Kennwert je eBKP-H-Hauptgruppe, Honorare, Reserve, MwSt. Rechnet der
// Kern auf dem Projekt-Dokument (`src-tauri/core/src/kosten.rs`; Mengen aus der SIA-416-Flächentabelle,
// Herkunft der Vorgabewerte im Modulkopf dort). Diese Datei ist nur die typisierte Fassade.
import type { CostBasis, CostEstimate, CostMethod, Project } from "../model/types";
import { documentFor } from "../core/document";
export type { CostBasis, CostEstimate, CostGroup, CostMethod } from "../model/types";
export interface CostQuantities {
gv: number;
gf: number;
hnf: number;
facade: number;
roof: number;
gvSource: "solids" | "levels" | null;
}
export interface CostRow {
code: string;
name: string | null;
/** Aufgelöste Bezugsmenge (nie „method“). */
basis: Exclude<CostBasis, "method">;
quantity: number;
/** „m³“, „m²“ oder leer (pauschal). */
unit: string;
rate: number;
amount: number;
/** Kennwert ist der Beispielwert. */
example: boolean;
}
export interface CostResult {
method: CostMethod;
quantities: CostQuantities;
rows: CostRow[];
factor: number;
regionFactor: number;
indexFactor: number;
subtotal: number;
feesPct: number;
fees: number;
reservePct: number;
reserve: number;
net: number;
vatPct: number;
vat: number;
gross: number;
accuracyPct: number;
low: number;
high: number;
perGv: number | null;
perGf: number | null;
priceBase: string;
isDefault: boolean;
hasExample: boolean;
/** Hinweis-Schlüssel (`costs.note.*`). */
notes: string[];
}
/** Kostenschätzung des Projekts (ohne `costEstimate` mit Beispielwerten). */
export function computeCostEstimate(project: Project): CostResult {
return documentFor(project).query<CostResult>("costEstimate");
}
/** Beispielwerte (Kennwerte B–J, Zuschläge) für eine Methode. */
export function defaultCostEstimate(project: Project, method: CostMethod = "gv"): CostEstimate {
return documentFor(project).query<CostEstimate>("costDefaults", [], method);
}
/** Schweizer Schreibweise mit Tausender-Apostroph (wie der Kern, `area_report::fmt_num`). */
export function formatChf(n: number, digits = 0): string {
if (!Number.isFinite(n)) return "–";
const s = n.toFixed(digits);
const [int, frac] = s.split(".");
const neg = int.startsWith("-");
const grouped = (neg ? int.slice(1) : int).replace(/\B(?=(\d{3})+(?!\d))/g, "'");
return `${neg ? "-" : ""}${grouped}${frac !== undefined ? `.${frac}` : ""}`;
}
+2
View File
@@ -147,6 +147,8 @@ export type QueryName =
| "presentationSheet"
| "kennzahlen"
| "areaTable"
| "costEstimate"
| "costDefaults"
| "programCompare"
| "programLayout"
| "ivhb"
+4
View File
@@ -104,3 +104,7 @@ export {
BlenderMissingError, RenderCancelled, RENDER_SIZE_PRESETS, RENDER_QUALITY_PRESETS, RENDER_VIEW_PRESETS, BLENDER_CANDIDATES, BLENDER_DOWNLOAD_URL,
} from "../export/blenderRender";
export type { BlenderHost, RenderPackage, RenderOptions, RenderScene, RenderCamera, RenderCameraSpec, RenderViewPreset, RenderMaterial, RenderRole, RenderCameraChoice, TextureLoader, BlenderEvent, RenderResult, RenderRunOptions } from "../export/blenderRender";
// [209] Kostenschätzung grob (Kern kosten.rs): Rechnung, Beispielwerte, Bericht (CSV/PDF wie der Flächen-Nachweis)
export { computeCostEstimate, defaultCostEstimate, formatChf } from "../analysis/costEstimate";
export type { CostResult, CostRow, CostQuantities, CostEstimate, CostGroup, CostMethod, CostBasis } from "../analysis/costEstimate";
export { buildCostReport, costGroupLabel, costUnitLabel } from "../export/costReport";
+1
View File
@@ -36,6 +36,7 @@ bekommen.
| Datei | Inhalt |
|---|---|
| `areaReport.ts` | Flächen- und Kennzahlen-Nachweis (`[70]`); Aufbau, den die übrigen Berichte nutzen |
| `costReport.ts` | Kostenschätzung grob als Bericht (CSV/PDF über `areaReport.ts`, [209]) |
| `programReport.ts` | Soll/Ist-Vergleich des Raumprogramms (`[61]`) |
| `elementSchedule.ts` | Bauteilliste mit U-Werten (`[71]`) |
| `openingSchedule.ts` | Fenster- und Türliste (`[97]`) |
+1 -1
View File
@@ -17,7 +17,7 @@ import { computeAreaTable, computeIvhb } from "../analysis/areaTable";
import type { AreaRow, IvhbOptions } from "../analysis/areaTable";
/** Zelle: Text oder Zahl (`d` Nachkommastellen, `null` = nicht berechenbar). */
export type Cell = string | { n: number | null; d: number };
export type Cell = string | { n: number | null; d: number; g?: boolean };
export interface ReportRow {
cells: Cell[];
+91
View File
@@ -0,0 +1,91 @@
import { describe, expect, it } from "vitest";
import { sampleProject } from "../model/sampleProject";
import type { Layout, Project, Room, Wall } from "../model/types";
import { computeAreaTable } from "../analysis/areaTable";
import { computeCostEstimate, defaultCostEstimate, formatChf } from "../analysis/costEstimate";
import { areaReportToCsv, layoutAreaReport, parseAreaReportCsv } from "./areaReport";
import { buildCostReport } from "./costReport";
import { sheetTables } from "./sheetTable";
// Haus wie im Flächen-Nachweis-Test: Achsen 10 × 8 m, Wände 0.3 m, GF 85.49 m², GV = GF × 2.6 m.
function house(): Project {
const base = structuredClone(sampleProject) as Project;
const wt = base.wallTypes[0]!;
const type = { ...wt, id: "w30", layers: [{ ...wt.layers[0]!, thickness: 0.3 }] };
const pts = [[0, 0], [10, 0], [10, 8], [0, 8]] as const;
const walls = pts.map((a, i): Wall => {
const b = pts[(i + 1) % 4]!;
return { ...(base.walls[0] as Wall), id: `hw${i}`, floorId: "eg", start: { x: a[0], y: a[1] }, end: { x: b[0], y: b[1] }, wallTypeId: "w30", height: 2.6, bottom: undefined, top: undefined };
});
const room: Room = { ...(base.rooms![0] as Room), id: "a", floorId: "eg", siaCategory: "HNF", name: "a", boundary: [{ x: 0.15, y: 0.15 }, { x: 9.85, y: 0.15 }, { x: 9.85, y: 7.85 }, { x: 0.15, y: 7.85 }] };
return { ...base, name: "Haus", wallTypes: [type], walls, rooms: [room], openings: [], extrudedSolids: undefined, roofs: undefined, layouts: [] };
}
describe("Kostenschätzung grob [209]", () => {
it("Beispielwerte: Mengen aus der Flächentabelle, Summen und MwSt", () => {
const p = house();
const r = computeCostEstimate(p);
const area = computeAreaTable(p);
expect(r.isDefault).toBe(true);
expect(r.hasExample).toBe(true);
expect(r.method).toBe("gv");
expect(r.quantities.gv).toBeCloseTo(area.gv, 9);
expect(r.quantities.gf).toBeCloseTo(area.total.gf, 9);
expect(r.rows.map((x) => x.code)).toEqual(["B", "C", "D", "E", "F", "G", "H", "I", "J"]);
// 800 CHF/m³ GV für B–J (Beispiel), +15 % Honorare, +10 % Reserve, +8.1 % MwSt.
expect(r.subtotal).toBeCloseTo(area.gv * 800, 6);
expect(r.gross).toBeCloseTo(area.gv * 800 * 1.15 * 1.1 * 1.081, 4);
expect(r.low).toBeCloseTo(r.gross * 0.85, 4);
expect(r.perGv).toBeCloseTo(r.gross / area.gv, 6);
});
it("Methode m² GF, eigene Kennwerte und Bezug Fassade", () => {
const p = house();
const est = defaultCostEstimate(p, "gf");
est.groups = [{ code: "B–J", name: "Gebäude", basis: "method", rate: 3000 }, { code: "E", basis: "facade", rate: 200 }];
est.feesPct = 0;
est.reservePct = 0;
const r = computeCostEstimate({ ...p, costEstimate: est });
expect(r.hasExample).toBe(false);
expect(r.rows[0]!.unit).toBe("m²");
expect(r.rows[0]!.amount).toBeCloseTo(85.49 * 3000, 1); // i_overlay-Raster
// Fassade: Aussenumfang 2 × (10.3 + 8.3) × 2.6 m.
expect(r.rows[1]!.quantity).toBeCloseTo(37.2 * 2.6, 3);
expect(r.net).toBeCloseTo(r.subtotal, 9);
});
it("Bericht: CSV-Rundreise mit denselben Zahlen, PDF-Layout mit Apostroph", () => {
const p = house();
const r = computeCostEstimate(p);
const report = buildCostReport(p, r);
const csv = areaReportToCsv(report);
expect(csv).toContain("Kostenschätzung grob");
expect(csv).toContain("Konstruktion Gebäude");
expect(csv).not.toMatch(/\d'\d{3}/); // CSV ohne Tausender-Trenner
const back = parseAreaReportCsv(csv);
const rows = back.sections[0]!.rows;
const gross = rows.find((x) => x[1] === "Total inkl. MwSt.")!;
expect(gross[5]).toBe(Math.round(r.gross));
const texts = layoutAreaReport(report).pages.flat().flatMap((x) => (x.k === "text" ? [x.s] : []));
expect(texts).toContain(formatChf(r.gross));
expect(texts.some((s) => s.includes("Beispielwert"))).toBe(true);
});
it("Blatt-Tabelle „costs“ folgt dem Modell", () => {
const p = house();
const layout: Layout = { id: "L", name: "Blatt", tables: [{ id: "k", source: "costs", xMm: 10, yMm: 10, widthMm: 180 }] } as unknown as Layout;
const q = { ...p, layouts: [layout] };
const out = sheetTables(q, "L");
const texts = out[0]!.prims.flatMap((x) => (x.k === "text" ? [x.s] : []));
expect(texts).toContain(formatChf(computeCostEstimate(q).gross));
expect(texts.some((s) => s.startsWith("Total inkl. MwSt."))).toBe(true);
expect(texts).toContain("Konstruktion Gebäude");
});
it("formatChf: Schweizer Schreibweise", () => {
expect(formatChf(1234567.5, 2)).toBe("1'234'567.50");
expect(formatChf(-1000)).toBe("-1'000");
expect(formatChf(999)).toBe("999");
expect(formatChf(Number.NaN)).toBe("–");
});
});
+87
View File
@@ -0,0 +1,87 @@
// Kostenschätzung grob ([209]) als Bericht: dasselbe Berichtsmodell wie der Flächen-Nachweis ([70]), daher
// dieselben Ausgaben (CSV über `areaReportToCsv`, Vektor-PDF über `buildAreaReportPdf`). Gerechnet wird im
// Kern (`analysis/costEstimate.ts` → `kosten.rs`); hier nur Aufbau und Beschriftung mit `t()`.
import type { Project } from "../model/types";
import { t } from "../i18n/translate";
import { computeCostEstimate, formatChf } from "../analysis/costEstimate";
import type { CostResult, CostRow } from "../analysis/costEstimate";
import type { AreaReport, Cell, ReportRow } from "./areaReport";
/** Franken (ganze, Tausender-Apostroph in PDF/Blatt; die CSV bleibt ohne Trenner). */
const chf = (n: number | null | undefined): Cell => ({ n: n === undefined || n === null || !Number.isFinite(n) ? null : n, d: 0, g: true });
const qty = (n: number, d = 1): Cell => ({ n: Number.isFinite(n) ? n : null, d, g: true });
const pctText = (v: number) => `${Number.isInteger(v) ? v.toFixed(0) : v.toFixed(1)} %`;
/** Bezeichnung einer Kennwert-Zeile: eigener Name oder eBKP-H-Hauptgruppe. */
export function costGroupLabel(code: string, name?: string | null): string {
if (name && name.trim()) return name;
const key = `costs.group.${code}`;
const s = t(key);
return s === key ? code : s;
}
export function costUnitLabel(r: Pick<CostRow, "unit">): string {
return r.unit || t("costs.lump");
}
/** Bericht der Kostenschätzung (Tabelle, Mengen, Kennwerte/Bandbreite, Fussnoten). */
export function buildCostReport(project: Project, result: CostResult = computeCostEstimate(project)): AreaReport {
const r = result;
const rows: ReportRow[] = r.rows.map((g) => ({
cells: [g.code, costGroupLabel(g.code, g.name) + (g.example ? " *" : ""), qty(g.quantity, g.unit ? 1 : 0), costUnitLabel(g), chf(g.rate), chf(g.amount)],
}));
const sum = (label: string, n: number, total = false, code = ""): ReportRow => ({ total, cells: [code, label, "", "", "", chf(n)] });
rows.push(sum(t("costs.row.subtotal"), r.subtotal, true));
rows.push(sum(`${t("costs.row.fees")} ${pctText(r.feesPct)}`, r.fees, false, "V"));
rows.push(sum(`${t("costs.row.reserve")} ${pctText(r.reservePct)}`, r.reserve, false, "Y"));
rows.push(sum(t("costs.row.net"), r.net, true));
rows.push(sum(`${t("costs.row.vat")} ${pctText(r.vatPct)}`, r.vat, false, "Z"));
rows.push(sum(t("costs.row.gross"), r.gross, true));
const q = r.quantities;
const notes: string[] = [];
if (r.hasExample) notes.push(t("costs.foot.example"));
notes.push(t("costs.foot.priceBase", { base: r.priceBase || "–", region: r.regionFactor.toFixed(2), index: r.indexFactor.toFixed(2) }));
for (const k of r.notes) notes.push(t(`costs.note.${k}`, { pct: pctText(r.accuracyPct) }));
notes.push(t("costs.foot.ebkp"));
return {
title: t("costs.title"),
projectName: project.name ?? "",
sections: [
{
heading: `${t("costs.table")} · ${t(`costs.method.${r.method}`)}`,
columns: [t("costs.col.code"), t("costs.col.group"), t("costs.col.quantity"), t("costs.col.unit"), t("costs.col.rate"), t("costs.col.amount")],
widths: [1, 5, 1.8, 1, 1.6, 2.2],
rows,
},
{
heading: t("costs.range.title"),
columns: [t("costs.col.value"), "CHF"],
widths: [6, 2.2],
rows: [
{ cells: [t("costs.range.low", { pct: pctText(r.accuracyPct) }), chf(r.low)] },
{ cells: [t("costs.range.high", { pct: pctText(r.accuracyPct) }), chf(r.high)] },
{ cells: [t("costs.perGv"), chf(r.perGv)] },
{ cells: [t("costs.perGf"), chf(r.perGf)] },
],
},
{
heading: t("costs.quantities"),
columns: [t("costs.col.quantityName"), t("costs.col.quantity"), t("costs.col.unit")],
widths: [6, 1.8, 1],
rows: [
{ cells: [t("costs.q.gv"), qty(q.gv), "m³"] },
{ cells: [t("costs.q.gf"), qty(q.gf), "m²"] },
{ cells: [t("costs.q.hnf"), qty(q.hnf), "m²"] },
{ cells: [t("costs.q.facade"), qty(q.facade), "m²"] },
{ cells: [t("costs.q.roof"), qty(q.roof), "m²"] },
],
},
],
notes,
};
}
export { formatChf };
+3 -3
View File
@@ -55,10 +55,10 @@ describe("Tabellen auf dem Blatt ([111])", () => {
it("alle Quellen liefern Primitive; Katalog nennt die Spalten", () => {
const cat = tableCatalog(sampleProject);
expect(Object.keys(cat.sources).sort()).toEqual(["areas", "earthworks", "elements", "openings", "roomBook", "rooms"]);
const p = withTables((["openings", "areas", "rooms", "elements", "earthworks", "roomBook"] as const).map((source) => table({ id: source, source })));
expect(Object.keys(cat.sources).sort()).toEqual(["areas", "costs", "earthworks", "elements", "openings", "roomBook", "rooms"]);
const p = withTables((["openings", "areas", "rooms", "elements", "earthworks", "roomBook", "costs"] as const).map((source) => table({ id: source, source })));
const out = sheetTables(p, "L1");
expect(out.map((o) => o.id)).toEqual(["openings", "areas", "rooms", "elements", "earthworks", "roomBook"]);
expect(out.map((o) => o.id)).toEqual(["openings", "areas", "rooms", "elements", "earthworks", "roomBook", "costs"]);
for (const o of out) expect(o.prims.some((x) => x.k === "text")).toBe(true);
});
+1 -1
View File
@@ -38,7 +38,7 @@ interface Catalog {
valueKeys: string[];
}
export const TABLE_SOURCES: readonly LayoutTableSource[] = ["openings", "areas", "rooms", "elements", "earthworks", "roomBook"];
export const TABLE_SOURCES: readonly LayoutTableSource[] = ["openings", "areas", "rooms", "elements", "earthworks", "roomBook", "costs"];
export function tableSourceLabel(s: LayoutTableSource): string {
return t(`sheetTable.source.${s}`);
+84
View File
@@ -4006,6 +4006,90 @@ export const de = {
"render.toLayout.target": "Blatt",
"render.toLayout.none": "Noch kein Layout-Blatt vorhanden: zuerst ein Blatt anlegen.",
"render.toLayout.done": "Rendering ins Blatt „{name}“ eingesetzt.",
// ── [209] Kostenschätzung grob ──
"sheetTable.source.costs": "Kostenschätzung grob (eBKP-H)",
"sheetTable.col.costCode": "eBKP-H",
"sheetTable.col.costGroup": "Gruppe",
"sheetTable.col.quantity": "Menge",
"sheetTable.col.unit": "Einheit",
"sheetTable.col.rate": "Kennwert CHF",
"sheetTable.col.amount": "Betrag CHF",
"costs.title": "Kostenschätzung grob",
"costs.table": "Kennwert-Methode nach eBKP-H",
"costs.method": "Methode",
"costs.method.gv": "CHF/m³ GV",
"costs.method.gf": "CHF/m² GF",
"costs.basis.method": "Methode",
"costs.basis.gv": "m³ GV",
"costs.basis.gf": "m² GF",
"costs.basis.hnf": "m² HNF",
"costs.basis.facade": "m² Fassade",
"costs.basis.roof": "m² Dach",
"costs.basis.lump": "pauschal",
"costs.group.B": "Vorbereitung",
"costs.group.C": "Konstruktion Gebäude",
"costs.group.D": "Technik Gebäude",
"costs.group.E": "Äussere Wandbekleidung Gebäude",
"costs.group.F": "Bedachung Gebäude",
"costs.group.G": "Ausbau Gebäude",
"costs.group.H": "Nutzungsspezifische Anlage Gebäude",
"costs.group.I": "Umgebung Gebäude",
"costs.group.J": "Ausstattung Gebäude",
"costs.row.subtotal": "Summe Gebäude (B–J)",
"costs.row.fees": "Honorare",
"costs.row.reserve": "Reserve",
"costs.row.net": "Total exkl. MwSt.",
"costs.row.vat": "MwSt.",
"costs.row.gross": "Total inkl. MwSt.",
"costs.lump": "pauschal",
"costs.col.code": "eBKP-H",
"costs.col.group": "Gruppe",
"costs.col.basis": "Bezug",
"costs.col.quantity": "Menge",
"costs.col.unit": "Einheit",
"costs.col.rate": "Kennwert CHF",
"costs.col.amount": "Betrag CHF",
"costs.col.value": "Kennzahl",
"costs.col.quantityName": "Menge (SIA 416)",
"costs.fees": "Honorare %",
"costs.reserve": "Reserve %",
"costs.vat": "MwSt. %",
"costs.accuracy": "Genauigkeit ± %",
"costs.accuracy.hint": "SIA 102: Vorstudie/Wettbewerb ±25 %, Vorprojekt ±15 %.",
"costs.region": "Region-Faktor",
"costs.index": "Index-Faktor",
"costs.index.hint": "Teuerung seit dem Preisstand der Kennwerte: Baupreisindex heute / Index beim Preisstand.",
"costs.priceBase": "Preisstand",
"costs.reset": "Beispielwerte",
"costs.reset.hint": "Kennwerte und Zuschläge auf die Beispielwerte der Methode zurücksetzen.",
"costs.addGroup": "Zeile",
"costs.addGroup.hint": "Kennwert-Zeile hinzufügen (z. B. zusammengefasste Gruppe B–J).",
"costs.removeGroup": "Zeile entfernen",
"costs.example": "Beispielwert",
"costs.exampleBanner": "Beispielwerte, bitte anpassen: keine offiziellen Kennwerte (Herkunft s. Fussnote).",
"costs.range": "Bandbreite",
"costs.range.title": "Bandbreite und Kennwerte gesamt",
"costs.range.low": "Untergrenze (−{pct})",
"costs.range.high": "Obergrenze (+{pct})",
"costs.perGv": "Total inkl. MwSt. je m³ GV",
"costs.perGf": "Total inkl. MwSt. je m² GF",
"costs.quantities": "Mengen aus dem Modell",
"costs.q.gv": "Gebäudevolumen GV",
"costs.q.gf": "Geschossfläche GF",
"costs.q.hnf": "Hauptnutzfläche HNF",
"costs.q.facade": "Fassadenfläche (Aussenumfang × Geschosshöhe)",
"costs.q.roof": "Dachfläche",
"costs.note.example": "* Beispielwert: runde Annahme für ein Gebäude mittleren Standards (Preisstand 2025), keine offizielle Quelle — bitte durch eigene Kennwerte ersetzen.",
"costs.note.noQuantity": "Keine Mengen: das Modell hat weder GV noch GF (Geschosse mit Wänden/Räumen oder freie Körper zeichnen).",
"costs.note.gvSolids": "GV aus den freien Körpern (Massenmodell), GF/HNF aus der Flächentabelle SIA 416.",
"costs.note.gvLevels": "Mengen aus der Flächentabelle SIA 416 (GV ≈ GF × Geschosshöhe).",
"costs.note.facade": "Fassadenfläche = Aussenumfang der oberirdischen Geschosse × Geschosshöhe; Innenhöfe, Brüstungen und Attiken fehlen.",
"costs.note.roofFootprint": "Kein Dach im Modell: Dachfläche = Fläche im Aussenumriss (Flachdach-Annahme).",
"costs.note.accuracy": "Genauigkeit ±{pct} (SIA 102: Vorstudie ±25 %, Vorprojekt ±15 %).",
"costs.foot.example": "Mit * markierte Kennwerte sind Beispielwerte, bitte anpassen.",
"costs.foot.priceBase": "Preisstand {base}; Region-Faktor {region}, Index-Faktor {index}.",
"costs.foot.ebkp": "Gliederung nach eBKP-H (SN 506 511); ohne Grundstück (A). Honorare (V) auf B–J, Reserve (Y) auf B–J + V, MwSt (Z) auf das Total.",
"costs.export.fail": "Export der Kostenschätzung fehlgeschlagen.",
} as const;
export type TranslationKey = keyof typeof de;
+84
View File
@@ -3992,4 +3992,88 @@ export const en: Record<TranslationKey, string> = {
"render.toLayout.target": "Sheet",
"render.toLayout.none": "No layout sheet yet: create a sheet first.",
"render.toLayout.done": "Rendering placed on sheet \"{name}\".",
// ── [209] Kostenschätzung grob ──
"sheetTable.source.costs": "Cost estimate (eBKP-H)",
"sheetTable.col.costCode": "eBKP-H",
"sheetTable.col.costGroup": "Group",
"sheetTable.col.quantity": "Quantity",
"sheetTable.col.unit": "Unit",
"sheetTable.col.rate": "Rate CHF",
"sheetTable.col.amount": "Amount CHF",
"costs.title": "Rough cost estimate",
"costs.table": "Cost rates by eBKP-H",
"costs.method": "Method",
"costs.method.gv": "CHF/m³ GV",
"costs.method.gf": "CHF/m² GF",
"costs.basis.method": "Method",
"costs.basis.gv": "m³ GV",
"costs.basis.gf": "m² GF",
"costs.basis.hnf": "m² HNF",
"costs.basis.facade": "m² facade",
"costs.basis.roof": "m² roof",
"costs.basis.lump": "lump sum",
"costs.group.B": "Preparation",
"costs.group.C": "Building structure",
"costs.group.D": "Building services",
"costs.group.E": "External wall cladding",
"costs.group.F": "Roofing",
"costs.group.G": "Interior fit-out",
"costs.group.H": "Use-specific installations",
"costs.group.I": "Surroundings",
"costs.group.J": "Furnishings",
"costs.row.subtotal": "Building total (B–J)",
"costs.row.fees": "Fees",
"costs.row.reserve": "Contingency",
"costs.row.net": "Total excl. VAT",
"costs.row.vat": "VAT",
"costs.row.gross": "Total incl. VAT",
"costs.lump": "lump sum",
"costs.col.code": "eBKP-H",
"costs.col.group": "Group",
"costs.col.basis": "Basis",
"costs.col.quantity": "Quantity",
"costs.col.unit": "Unit",
"costs.col.rate": "Rate CHF",
"costs.col.amount": "Amount CHF",
"costs.col.value": "Figure",
"costs.col.quantityName": "Quantity (SIA 416)",
"costs.fees": "Fees %",
"costs.reserve": "Contingency %",
"costs.vat": "VAT %",
"costs.accuracy": "Accuracy ± %",
"costs.accuracy.hint": "SIA 102: preliminary study/competition ±25 %, preliminary design ±15 %.",
"costs.region": "Regional factor",
"costs.index": "Index factor",
"costs.index.hint": "Price increase since the rates' price base: construction price index today / index at price base.",
"costs.priceBase": "Price base",
"costs.reset": "Example values",
"costs.reset.hint": "Reset rates and surcharges to the example values of the method.",
"costs.addGroup": "Row",
"costs.addGroup.hint": "Add a rate row (e.g. a combined group B–J).",
"costs.removeGroup": "Remove row",
"costs.example": "Example value",
"costs.exampleBanner": "Example values, please adjust: no official rates (source see footnote).",
"costs.range": "Range",
"costs.range.title": "Range and overall rates",
"costs.range.low": "Lower bound (−{pct})",
"costs.range.high": "Upper bound (+{pct})",
"costs.perGv": "Total incl. VAT per m³ GV",
"costs.perGf": "Total incl. VAT per m² GF",
"costs.quantities": "Quantities from the model",
"costs.q.gv": "Building volume GV",
"costs.q.gf": "Gross floor area GF",
"costs.q.hnf": "Main usable area HNF",
"costs.q.facade": "Facade area (outer perimeter × storey height)",
"costs.q.roof": "Roof area",
"costs.note.example": "* Example value: round assumption for a building of medium standard (price base 2025), no official source — please replace with your own rates.",
"costs.note.noQuantity": "No quantities: the model has neither GV nor GF (draw storeys with walls/rooms or free solids).",
"costs.note.gvSolids": "GV from the free solids (massing model), GF/HNF from the SIA 416 area table.",
"costs.note.gvLevels": "Quantities from the SIA 416 area table (GV ≈ GF × storey height).",
"costs.note.facade": "Facade area = outer perimeter of the storeys above ground × storey height; courtyards, parapets and attics missing.",
"costs.note.roofFootprint": "No roof in the model: roof area = area inside the outline (flat roof assumption).",
"costs.note.accuracy": "Accuracy ±{pct} (SIA 102: preliminary study ±25 %, preliminary design ±15 %).",
"costs.foot.example": "Rates marked * are example values, please adjust.",
"costs.foot.priceBase": "Price base {base}; regional factor {region}, index factor {index}.",
"costs.foot.ebkp": "Structure per eBKP-H (SN 506 511); without land (A). Fees (V) on B–J, contingency (Y) on B–J + V, VAT (Z) on the total.",
"costs.export.fail": "Export of the cost estimate failed.",
};
+55 -1
View File
@@ -590,6 +590,51 @@ export type ContourSet = {
contours: Array<Contour>;
};
/** [209] Bezugsmenge eines Kostenkennwerts (Kostenschätzung nach der Kennwert-Methode). */
export type CostBasis = "method" | "gv" | "gf" | "hnf" | "facade" | "roof" | "lump";
/**
* [209] Grobe Kostenschätzung (Vorprojekt/Wettbewerb) nach der Kennwert-Methode: Menge × Kennwert je
* eBKP-H-Hauptgruppe, dazu Honorare, Reserve und MwSt in Prozent. Fehlt das Feld, rechnet der Kern mit
* Beispielwerten (`kosten::default_estimate`).
*/
export type CostEstimate = {
method: CostMethod;
groups: Array<CostGroup>;
/** Honorare (eBKP-H V) in % der Summe B–J. */
feesPct: number;
/** Reserve/Unvorhergesehenes (eBKP-H Y) in % der Summe B–J + Honorare. */
reservePct: number;
/** Mehrwertsteuer (eBKP-H Z) in %. */
vatPct: number;
/** Genauigkeit der Schätzung ± in %. */
accuracyPct: number;
/** Region-Faktor auf alle Kennwerte (1 = keiner). */
regionFactor: number;
/**
* Teuerung vom Preisstand der Kennwerte bis heute als Faktor (Baupreisindex neu / alt; 1 = keine).
*/
indexFactor: number;
/** Preisstand der Kennwerte (Text, z. B. „Okt. 2025, Baupreisindex Hochbau“). */
priceBase: string;
};
/**
* [209] Eine Zeile der Kennwert-Tabelle: eBKP-H-Hauptgruppe (B–J) oder eine zusammengefasste Gruppe.
*/
export type CostGroup = {
/** Kennung der Gruppe nach eBKP-H (SN 506 511), z. B. „C“ oder „B–J“. */
code: string;
/** Eigene Bezeichnung; fehlt = Name der eBKP-H-Hauptgruppe (aus `code`). */
name?: string;
basis: CostBasis;
/** Kennwert in CHF je Einheit der Bezugsmenge (pauschal: CHF). */
rate: number;
};
/** [209] Hauptmenge der Kostenschätzung: m³ GV oder m² GF. */
export type CostMethod = "gv" | "gf";
/**
* Eine benutzerdefinierte Farbpalette (Farbmischer → „Diese Farbe
* speichern", `ui/FreeColorPicker.tsx`). Anders als Stiftsätze: reine
@@ -1993,7 +2038,14 @@ export type LayoutTable = {
};
/** Quelle einer Blatt-Tabelle ([111]). */
export type LayoutTableSource = "openings" | "areas" | "rooms" | "elements" | "earthworks" | "roomBook";
export type LayoutTableSource =
| "openings"
| "areas"
| "rooms"
| "elements"
| "earthworks"
| "roomBook"
| "costs";
/**
* Einfache Textfelder des Titelblocks (Master). Alle optional — leere Felder
@@ -3058,6 +3110,8 @@ export type Project = {
projectNumber?: string;
/** Wettbewerb ([208]): anonyme Abgabe mit Kennwort. */
competition?: CompetitionSettings;
/** [209] Kostenschätzung grob (Kennwerte, Zuschläge); fehlt = Beispielwerte. */
costEstimate?: CostEstimate;
/**
* Höhe von ±0.00 (OK fertig Boden des Bezugsgeschosses, `DrawingLevel.zeroLevel`)
* in Metern über Meer (m ü. M.), editierbar im Einstellungs-Fenster. Optional.
+288
View File
@@ -0,0 +1,288 @@
// Kostenschätzung grob ([209]) im Flächenbilanz-Panel: Kennwert-Tabelle (eBKP-H-Hauptgruppen) und Zuschläge
// bearbeiten, Ergebnis mit Summen, Bandbreite und Mengen; Export CSV/PDF aus demselben Bericht.
//
// • Rechnet der Kern (`kosten.rs`, Mengen aus der SIA-416-Flächentabelle); hier nur Anzeige und Eingabe.
// • Fehlt `Project.costEstimate`, zeigt die Tabelle die Beispielwerte; die erste Änderung schreibt sie ins
// Projekt (eine Op, Undo-fähig; Tippen in dasselbe Feld = ein Undo-Schritt über den coalesceKey).
// • Methodenwechsel: Beispiel-Kennwerte werden durch die der neuen Methode ersetzt, eigene Kennwerte über das
// Mengenverhältnis umgerechnet (Betrag bleibt gleich).
import { useEffect, useMemo, useState } from "react";
import { t } from "../i18n";
import { areaReportToCsv, buildAreaReportPdf, buildCostReport, computeCostEstimate, costGroupLabel, costUnitLabel, defaultCostEstimate, formatChf, setField } from "../core";
import type { CostBasis, CostEstimate, CostGroup, CostMethod, CostResult } from "../core";
import type { Project } from "../model/types";
import { downloadCsv } from "./downloadFile";
import { useStore } from "../state/appStore";
const BASES: CostBasis[] = ["method", "gv", "gf", "hnf", "facade", "roof", "lump"];
const METHODS: CostMethod[] = ["gv", "gf"];
/** Zahl-Eingabe, übernimmt bei Enter/Verlassen (Komma oder Punkt). */
function NumField(props: { value: number; onCommit: (v: number) => void; testId?: string; title?: string; width?: number }) {
const [text, setText] = useState(String(props.value));
useEffect(() => setText(String(props.value)), [props.value]);
const commit = () => {
const v = Number(text.replace(/'/g, "").replace(",", "."));
if (Number.isFinite(v) && v !== props.value) props.onCommit(v);
else setText(String(props.value));
};
return (
<input
type="text"
inputMode="decimal"
className="kz-input kz-num"
style={props.width ? { width: props.width } : undefined}
value={text}
title={props.title}
data-testid={props.testId}
onChange={(e) => setText(e.target.value)}
onBlur={commit}
onKeyDown={(e) => {
if (e.key === "Enter") commit();
}}
/>
);
}
/** Kennwerte beim Methodenwechsel: Beispielwerte tauschen, eigene Werte über das Mengenverhältnis umrechnen. */
function switchMethod(p: Project, est: CostEstimate, res: CostResult, method: CostMethod): CostEstimate {
const from = est.method === "gf" ? res.quantities.gf : res.quantities.gv;
const to = method === "gf" ? res.quantities.gf : res.quantities.gv;
const examples = new Map(defaultCostEstimate(p, method).groups.map((g) => [g.code, g.rate]));
const groups = est.groups.map((g, i) => {
if (g.basis !== "method") return g;
const ex = examples.get(g.code);
if (res.rows[i]?.example && ex !== undefined) return { ...g, rate: ex };
return from > 0 && to > 0 ? { ...g, rate: Math.round((g.rate * from) / to) } : g;
});
return { ...est, method, groups };
}
export function CostEstimateSection() {
const project = useStore((s) => s.project);
const applyChange = useStore((s) => s.applyChange);
const notify = useStore((s) => s.notify);
const res = useMemo(() => computeCostEstimate(project), [project]);
const est: CostEstimate = useMemo(() => project.costEstimate ?? defaultCostEstimate(project, "gv"), [project]);
const stem = `${project.name || "projekt"}-kosten`;
const update = (next: (e: CostEstimate) => CostEstimate, key: string) =>
applyChange((p: Project) => [setField("costEstimate", next(p.costEstimate ?? defaultCostEstimate(p, "gv")))], `costEstimate.${key}`);
const patch = (fields: Partial<CostEstimate>, key: string) => update((e) => ({ ...e, ...fields }), key);
const patchGroup = (i: number, g: Partial<CostGroup>, key: string) =>
update((e) => ({ ...e, groups: e.groups.map((x, j) => (j === i ? { ...x, ...g } : x)) }), `${key}.${i}`);
const exportCsv = () => downloadCsv(`${stem}.csv`, areaReportToCsv(buildCostReport(project, res)));
const exportPdf = () => {
try {
buildAreaReportPdf(buildCostReport(project, res)).save(`${stem}.pdf`);
} catch {
notify(t("costs.export.fail"));
}
};
const pctLabel = (v: number) => `${Number.isInteger(v) ? v.toFixed(0) : v.toFixed(1)} %`;
const sumRow = (label: string, n: number, testId: string, total = false, code = "") => (
<tr className={total ? "total" : ""} data-testid={testId}>
<td>{code}</td>
<td colSpan={2}>{label}</td>
<td className="num">{formatChf(n)}</td>
<td />
</tr>
);
return (
<div className="area-section cost-section" data-testid="cost-section">
<div className="balance-head">
<span className="balance-section-label">{t("costs.title")}</span>
<span className="area-actions">
<button type="button" className="balance-export" data-testid="cost-export-csv" onClick={exportCsv}>
{t("areas.exportCsv")}
</button>
<button type="button" className="balance-export" data-testid="cost-export-pdf" onClick={exportPdf}>
{t("areas.exportPdf")}
</button>
</span>
</div>
{res.hasExample && <div className="cost-example-banner">{t("costs.exampleBanner")}</div>}
<div className="cost-settings">
<label className="kz-parcel">
<span>{t("costs.method")}</span>
<select
className="kz-input"
data-testid="cost-method"
value={res.method}
onChange={(e) => update((x) => switchMethod(project, x, res, e.target.value as CostMethod), "method")}
>
{METHODS.map((m) => (
<option key={m} value={m}>
{t(`costs.method.${m}`)}
</option>
))}
</select>
</label>
<label className="kz-parcel">
<span>{t("costs.priceBase")}</span>
<input
type="text"
className="kz-input"
style={{ width: 64 }}
value={est.priceBase}
data-testid="cost-price-base"
onChange={(e) => patch({ priceBase: e.target.value }, "priceBase")}
/>
</label>
<label className="kz-parcel">
<span>{t("costs.fees")}</span>
<NumField value={est.feesPct} testId="cost-fees" onCommit={(v) => patch({ feesPct: v }, "fees")} />
</label>
<label className="kz-parcel">
<span>{t("costs.reserve")}</span>
<NumField value={est.reservePct} testId="cost-reserve" onCommit={(v) => patch({ reservePct: v }, "reserve")} />
</label>
<label className="kz-parcel">
<span>{t("costs.vat")}</span>
<NumField value={est.vatPct} testId="cost-vat" onCommit={(v) => patch({ vatPct: v }, "vat")} />
</label>
<label className="kz-parcel" title={t("costs.accuracy.hint")}>
<span>{t("costs.accuracy")}</span>
<NumField value={est.accuracyPct} testId="cost-accuracy" title={t("costs.accuracy.hint")} onCommit={(v) => patch({ accuracyPct: v }, "accuracy")} />
</label>
<label className="kz-parcel">
<span>{t("costs.region")}</span>
<NumField value={est.regionFactor} testId="cost-region" onCommit={(v) => patch({ regionFactor: v }, "region")} />
</label>
<label className="kz-parcel" title={t("costs.index.hint")}>
<span>{t("costs.index")}</span>
<NumField value={est.indexFactor} testId="cost-index" title={t("costs.index.hint")} onCommit={(v) => patch({ indexFactor: v }, "index")} />
</label>
</div>
<table className="area-table cost-table" data-testid="cost-table">
<thead>
<tr>
<th>{t("costs.col.code")}</th>
<th>
{t("costs.col.group")} · {t("costs.col.basis")}
</th>
<th className="num">{t("costs.col.rate")}</th>
<th className="num">{t("costs.col.amount")}</th>
<th />
</tr>
</thead>
<tbody>
{res.rows.map((r, i) => (
<tr key={i} data-testid={`cost-row-${r.code}`}>
<td>
<input type="text" className="kz-input cost-code" value={est.groups[i]?.code ?? r.code} onChange={(e) => patchGroup(i, { code: e.target.value }, "code")} />
</td>
<td className="cost-name">
<input
type="text"
className="kz-input"
value={est.groups[i]?.name ?? ""}
placeholder={costGroupLabel(r.code)}
title={costGroupLabel(r.code, r.name)}
onChange={(e) => patchGroup(i, { name: e.target.value || undefined }, "name")}
/>
<div className="cost-sub">
<select className="kz-input" value={est.groups[i]?.basis ?? "method"} title={t("costs.col.basis")} onChange={(e) => patchGroup(i, { basis: e.target.value as CostBasis }, "basis")}>
{BASES.map((b) => (
<option key={b} value={b}>
{b === "method" ? `${t(`costs.basis.${res.method}`)} (${t("costs.basis.method")})` : t(`costs.basis.${b}`)}
</option>
))}
</select>
<span className="cost-qty">{r.unit ? `${formatChf(r.quantity, 1)} ${r.unit}` : costUnitLabel(r)}</span>
</div>
</td>
<td className="num">
<span className={r.example ? "cost-rate example" : "cost-rate"} title={r.example ? t("costs.example") : undefined}>
<NumField value={r.rate} testId={`cost-rate-${r.code}`} width={52} onCommit={(v) => patchGroup(i, { rate: v }, "rate")} />
{r.example ? "*" : ""}
</span>
</td>
<td className="num">{formatChf(r.amount)}</td>
<td>
<button
type="button"
className="site-remove"
title={t("costs.removeGroup")}
aria-label={t("costs.removeGroup")}
onClick={() => update((e) => ({ ...e, groups: e.groups.filter((_, j) => j !== i) }), "remove")}
>
×
</button>
</td>
</tr>
))}
{sumRow(t("costs.row.subtotal"), res.subtotal, "cost-subtotal", true)}
{sumRow(`${t("costs.row.fees")} ${pctLabel(res.feesPct)}`, res.fees, "cost-fees-row", false, "V")}
{sumRow(`${t("costs.row.reserve")} ${pctLabel(res.reservePct)}`, res.reserve, "cost-reserve-row", false, "Y")}
{sumRow(t("costs.row.net"), res.net, "cost-net", true)}
{sumRow(`${t("costs.row.vat")} ${pctLabel(res.vatPct)}`, res.vat, "cost-vat-row", false, "Z")}
{sumRow(t("costs.row.gross"), res.gross, "cost-gross", true)}
<tr data-testid="cost-range" className="cost-range">
<td />
<td colSpan={3}>
{t("costs.range")} ±{pctLabel(res.accuracyPct)}: {formatChf(res.low)} – {formatChf(res.high)}
</td>
<td />
</tr>
</tbody>
</table>
<div className="area-actions">
<button
type="button"
className="balance-export"
title={t("costs.addGroup.hint")}
onClick={() => update((e) => ({ ...e, groups: [...e.groups, { code: "", basis: "method", rate: 0 }] }), "add")}
>
+ {t("costs.addGroup")}
</button>
<button
type="button"
className="balance-export"
title={t("costs.reset.hint")}
data-testid="cost-reset"
onClick={() => applyChange((p: Project) => [setField("costEstimate", defaultCostEstimate(p, res.method))], "costEstimate.reset")}
>
{t("costs.reset")}
</button>
</div>
<table className="area-table cost-quantities" data-testid="cost-quantities">
<tbody>
{(
[
["costs.q.gv", formatChf(res.quantities.gv, 1), "m³"],
["costs.q.gf", formatChf(res.quantities.gf, 1), "m²"],
["costs.q.hnf", formatChf(res.quantities.hnf, 1), "m²"],
["costs.q.facade", formatChf(res.quantities.facade, 1), "m²"],
["costs.q.roof", formatChf(res.quantities.roof, 1), "m²"],
["costs.perGv", res.perGv === null ? "–" : formatChf(res.perGv), "CHF"],
["costs.perGf", res.perGf === null ? "–" : formatChf(res.perGf), "CHF"],
] as const
).map(([key, value, unit]) => (
<tr key={key}>
<td>{t(key)}</td>
<td className="num">
{value} {unit}
</td>
</tr>
))}
</tbody>
</table>
<ul className="area-notes">
{res.notes.map((k) => (
<li key={k}>{t(`costs.note.${k}`, { pct: pctLabel(res.accuracyPct) })}</li>
))}
<li>{t("costs.foot.ebkp")}</li>
</ul>
</div>
);
}
+5
View File
@@ -14,6 +14,7 @@ import type { Room } from "../model/types";
import { roomDisplayName } from "../model/roomStamp";
import { KennzahlenSection } from "./KennzahlenSection";
import { AreaTableSection } from "./AreaTableSection";
import { CostEstimateSection } from "./CostEstimateSection";
import { OpeningScheduleSection } from "./OpeningScheduleSection";
import { ElementScheduleSection } from "./ElementScheduleSection";
import { RoomBookSection } from "./RoomBookSection";
@@ -45,6 +46,7 @@ export function RoomBalancePanel() {
<div className="balance-panel">
<KennzahlenSection />
<AreaTableSection />
<CostEstimateSection />
<OpeningScheduleSection />
<ElementScheduleSection />
<div className="balance-empty">{t("balance.empty")}</div>
@@ -82,6 +84,9 @@ export function RoomBalancePanel() {
{/* Flächentabelle und IVHB-Kennziffern. */}
<AreaTableSection />
{/* Kostenschätzung grob ([209]). */}
<CostEstimateSection />
{/* Fenster- und Türliste. */}
<OpeningScheduleSection />
+91
View File
@@ -8550,6 +8550,97 @@ body {
color: var(--ink-2);
}
/* [209] Kostenschätzung grob (CostEstimateSection). */
.cost-example-banner {
padding: 4px 6px;
border-radius: 4px;
background: var(--panel-2);
border-left: 3px solid var(--accent);
color: var(--ink);
font-size: 11px;
}
.cost-settings {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
gap: 3px 10px;
}
.cost-settings .kz-num {
width: 48px;
}
.cost-settings .kz-parcel > span:first-child {
font-size: 11px;
}
.cost-table {
table-layout: fixed;
}
.cost-table th:nth-child(1) {
width: 34px;
}
.cost-table th:nth-child(3) {
width: 62px;
}
.cost-table th:nth-child(4) {
width: 62px;
}
.cost-table th:nth-child(5) {
width: 16px;
}
.cost-table th:nth-child(5),
.cost-table td:nth-child(5) {
padding: 2px 0;
}
.cost-table th {
white-space: normal;
}
.cost-table td {
vertical-align: top;
}
.cost-table .kz-input {
font-size: 11px;
max-width: 100%;
box-sizing: border-box;
}
.cost-table .cost-code {
width: 30px;
}
.cost-table .cost-name {
white-space: normal;
}
.cost-table .cost-name > .kz-input {
width: 100%;
}
.cost-sub {
display: flex;
align-items: center;
gap: 4px;
margin-top: 2px;
color: var(--ink-2);
font-size: 10px;
}
.cost-sub select {
flex: 0 0 auto;
width: 84px;
font-size: 10px;
}
.cost-qty {
white-space: nowrap;
}
.cost-table tr.cost-range td {
white-space: normal;
color: var(--ink-2);
}
.cost-rate {
white-space: nowrap;
}
.cost-rate.example .kz-input {
font-style: italic;
color: var(--ink-2);
}
.cost-quantities td {
white-space: normal;
border-bottom: none;
}
/* Raumprogramm: Gruppenspalte, Aktionen, Soll/Ist-Vergleich, Import-Dialog ([61]). */
.kz-program-row {
grid-template-columns: minmax(0, 1fr) 52px 36px 64px 56px 18px;