[278] Nutzungseinheiten und Wohnungsspiegel: Project.units, Room.unitId/roomCount, Kern-Abfrage mit Zimmerzahl und SIA-416-Flächen, Panel, Objekt-Info, Blatt-Tabelle, CSV/PDF, CLI, Beispiel Wettbewerb

This commit is contained in:
Claude committed 2026-11-17 22:08:06 +00:00
1 parent 605a54713c
commit 89c2d0c9a8
38 files changed
+1445 -54

No files matched your search

+116
View File
@@ -0,0 +1,116 @@
// [278] Wohnungsspiegel: Fassade über den Kern, Ops der Oberfläche (ein Undo-Schritt), Bericht/CSV, Blatt-Tabelle, Beispielprojekt.
import { beforeEach, describe, expect, it } from "vitest";
import { withDocument } from "../core/document";
import { getState } from "../state/appStore";
import { buildWettbewerbSampleProject } from "../model/sampleProjectWettbewerb";
import type { Project } from "../model/types";
import { computeUnitSchedule, unitScheduleCsv } from "./unitSchedule";
import { buildAreaReport, areaReportToCsv, hasUnits } from "../export/areaReport";
import { sheetTables } from "../export/sheetTable";
import { patchItem } from "../core/opsBuild";
import { addUnitOps, assignRoomsOps, deleteUnitOps, draftUnit, patchUnitOps } from "../panels/unitOps";
const st = () => getState();
let wb: Project;
beforeEach(() => {
st().loadProject(buildWettbewerbSampleProject());
st().clearHistory();
wb = st().project;
});
describe("Wohnungsspiegel (Beispiel Wettbewerb)", () => {
it("sechs Wohnungen: Typ, Zimmerzahl, Fläche je Einheit; Treppenhaus/Abstellraum ohne Einheit", () => {
const s = computeUnitSchedule(wb);
expect(s.units.map((u) => u.name)).toEqual(["0.1", "0.2", "1.1", "1.2", "2.1", "2.2"]);
expect(s.units.map((u) => u.typeLabel)).toEqual(["2-Zi-Whg", "2.5-Zi-Whg", "2-Zi-Whg", "2.5-Zi-Whg", "2-Zi-Whg", "2.5-Zi-Whg"]);
expect(s.units.map((u) => u.rooms)).toEqual([4, 4, 4, 4, 4, 4]);
expect(s.units.map((u) => u.floors)).toEqual([["Erdgeschoss"], ["Erdgeschoss"], ["1. Obergeschoss"], ["1. Obergeschoss"], ["2. Obergeschoss"], ["2. Obergeschoss"]]);
// HNF = Wohnen/Essen + Zimmer + Diele, NNF = Bad; NF = HNF + NNF (Handrechnung gegen die Raumliste).
const area = (id: string) => computeUnitSchedule(wb).units.find((u) => u.id === id)!;
const u = area("whg-eg-w");
expect(u.hnf).toBeGreaterThan(40);
expect(u.nnf).toBeGreaterThan(3);
expect(u.nf).toBeCloseTo(u.hnf + u.nnf, 9);
expect(u.agf).toBe(0);
// Typ-Summen: je 3 Wohnungen.
expect(s.byType.map((t) => [t.typeLabel, t.count, t.roomCount])).toEqual([["2-Zi-Whg", 3, 6], ["2.5-Zi-Whg", 3, 7.5]]);
expect(s.total.count).toBe(6);
expect(s.total.roomCount).toBeCloseTo(13.5, 9);
// Geschoss-Summen: drei Geschosse mit je zwei Wohnungen.
expect(s.byLevel.map((l) => l.count)).toEqual([2, 2, 2]);
expect(s.byLevel.reduce((a, l) => a + l.hnf, 0)).toBeCloseTo(s.total.hnf, 9);
// Gemeinschaftsflächen: je Geschoss Treppenhaus + Abstellraum/Eingang.
expect(s.unassigned.rooms).toBe(6);
expect(s.unassigned.vf).toBeGreaterThan(10);
});
it("CSV: Kopf und je Einheit eine Zeile; Bericht hat Spiegel, Typ- und Geschoss-Summen", () => {
const csv = unitScheduleCsv(wb, ["Nr", "Geschoss", "Typ", "Nutzung", "Zimmer", "HNF", "NNF", "NF", "Aussen"]);
expect(csv.trim().split("\n").length).toBe(7);
expect(csv.split("\n")[1]).toMatch(/^0\.1;Erdgeschoss;2-Zi-Whg;living;2;\d+\.\d\d;/);
expect(hasUnits(wb)).toBe(true);
const r = buildAreaReport(wb, { areas: false, units: true });
expect(r.sections.length).toBe(3);
expect(r.sections[0].rows.length).toBe(7);
expect(r.sections[0].rows.at(-1)!.total).toBe(true);
expect(areaReportToCsv(r)).toContain("2.5-Zi-Whg");
// Ohne Einheiten kein Abschnitt.
const none: Project = { ...wb, units: undefined };
expect(withDocument(none, () => buildAreaReport(none, { areas: false, units: true })).sections.length).toBe(0);
});
it("Blatt-Tabelle: Layout „Wohnungsspiegel“ rechnet mit dem Modell mit", () => {
const lay = wb.layouts!.find((l) => l.id === "lay-wohnungsspiegel")!;
const [t] = sheetTables(wb, lay.id);
expect(t.total).toBe(7);
const texts = t.prims.filter((p) => p.k === "text").map((p) => (p as { s: string }).s);
expect(texts).toContain("2.5-Zi-Whg");
expect(texts).toContain("1. Obergeschoss");
// Eine Wohnung mehr im Modell: die Tabelle hat eine Zeile mehr.
const more: Project = { ...wb, units: [...wb.units!, { id: "neu", name: "3.1", unitType: "Atelier" }] };
const [t2] = withDocument(more, () => sheetTables(more, lay.id));
expect(t2.total).toBe(8);
});
});
describe("Ops der Oberfläche: eine Aktion = ein Undo-Schritt", () => {
it("neue Einheit aus Auswahl, Zuordnen, Ändern, Löschen", () => {
const p0 = st().project;
const ids = ["raum-E.10", "raum-1.10"];
const unit = draftUnit(p0, "Whg");
expect(unit.name).toBe("Whg 7");
st().applyChange((p: Project) => addUnitOps(p, unit, ids));
expect(st().undoDepth).toBe(1);
expect(st().project.units!.length).toBe(7);
expect(st().project.rooms!.filter((r) => r.unitId === unit.id).map((r) => r.id)).toEqual(ids);
st().undo();
expect(st().project.units!.length).toBe(6);
expect(st().project.rooms!.find((r) => r.id === "raum-E.10")!.unitId).toBeUndefined();
st().applyChange((p: Project) => assignRoomsOps(p, ["raum-E.09", "raum-1.09"], "whg-eg-w"));
expect(st().project.rooms!.find((r) => r.id === "raum-1.09")!.unitId).toBe("whg-eg-w");
expect(computeUnitSchedule(st().project).units.find((u) => u.id === "whg-eg-w")!.floors).toEqual(["Erdgeschoss", "1. Obergeschoss"]);
st().applyChange((p: Project) => patchUnitOps(p, "whg-eg-w", { unitType: "Maisonette" }), "unit:whg-eg-w:type");
expect(computeUnitSchedule(st().project).units.find((u) => u.id === "whg-eg-w")!.typeLabel).toBe("Maisonette");
const before = st().undoDepth;
st().applyChange((p: Project) => deleteUnitOps(p, "whg-eg-w"));
expect(st().undoDepth).toBe(before + 1);
expect(st().project.units!.some((u) => u.id === "whg-eg-w")).toBe(false);
expect(st().project.rooms!.some((r) => r.unitId === "whg-eg-w")).toBe(false);
st().undo();
expect(st().project.rooms!.filter((r) => r.unitId === "whg-eg-w").length).toBe(6);
});
it("alle Einheiten gelöscht: Feld verschwindet; Zimmer-Zählung eines Raums ändert den Typ", () => {
for (const u of structuredClone(st().project.units!)) st().applyChange((p: Project) => deleteUnitOps(p, u.id));
expect(st().project.units).toBeUndefined();
expect(computeUnitSchedule(st().project).units).toEqual([]);
st().clearHistory();
st().loadProject(buildWettbewerbSampleProject());
st().applyChange((p: Project) => patchItem(p, "rooms", "raum-E.01", { roomCount: 1.5 }));
expect(computeUnitSchedule(st().project).units.find((u) => u.id === "whg-eg-w")!.typeLabel).toBe("2.5-Zi-Whg");
});
});
+88
View File
@@ -0,0 +1,88 @@
// Wohnungsspiegel ([278]): Nutzungseinheiten mit Geschoss, Typ, Zimmerzahl und Flächen nach SIA 416.
// Rechnet der Kern auf dem Projekt-Dokument (`src-tauri/core/src/unit_schedule.rs`; Annahmen stehen im Modulkopf).
// Diese Datei ist nur die typisierte Fassade plus kleine Helfer der Oberfläche.
import type { Project, Unit, UnitUsage } from "../model/types";
import { documentFor } from "../core/document";
/** Flächen einer Einheit (m²). */
export interface UnitAreas {
hnf: number;
nnf: number;
/** NF = HNF + NNF. */
nf: number;
vf: number;
ff: number;
/** Aussenraum (Balkon, Loggia): Flächenart AGF. */
agf: number;
}
export interface UnitRow extends UnitAreas {
id: string;
name: string;
/** Typ (eingegeben oder aus der Zimmerzahl abgeleitet, z. B. „3.5-Zi-Whg“; leer ohne beides). */
typeLabel: string;
usage: UnitUsage;
/** Namen der Geschosse (unten → oben). */
floors: string[];
floorIds: string[];
/** Zahl der Räume. */
rooms: number;
/** Zimmerzahl (nur Wohnnutzung). */
roomCount: number;
color: string | null;
note: string;
}
export interface UnitTypeSum extends UnitAreas {
typeLabel: string;
count: number;
roomCount: number;
avgHnf: number;
}
export interface UnitLevelSum extends UnitAreas {
levelId: string;
name: string;
count: number;
}
export interface UnitSchedule {
units: UnitRow[];
byType: UnitTypeSum[];
byLevel: UnitLevelSum[];
total: UnitTypeSum;
/** Räume ohne (gültige) Einheit. */
unassigned: UnitAreas & { rooms: number };
}
/** Nutzungen einer Einheit in der Reihenfolge der Auswahl. */
export const UNIT_USAGES: readonly UnitUsage[] = ["living", "commercial", "office", "other"];
/** Wohnungsspiegel des Projekts (`renovation`: Umbau-Zustand, leer = alle Bauteile). */
export function computeUnitSchedule(project: Project, renovation = ""): UnitSchedule {
return documentFor(project).query<UnitSchedule>("unitSchedule", [], renovation);
}
/** CSV des Spiegels (Trenner „;“); `head` = Spaltenköpfe (Nr., Geschoss, Typ, Nutzung, Zimmer, HNF, NNF, NF, Aussenraum). */
export function unitScheduleCsv(project: Project, head: string[]): string {
return documentFor(project).query<string>("unitSchedule", [], JSON.stringify({ head }));
}
/** Vorschlag für den Namen einer neuen Einheit: Präfix + erste freie Zahl („Whg 3“). */
export function nextUnitName(units: readonly Unit[], prefix: string): string {
const taken = new Set(units.map((u) => u.name));
for (let n = units.length + 1; ; n++) {
const name = `${prefix} ${n}`;
if (!taken.has(name)) return name;
}
}
/** Neue, noch unbenutzte Einheiten-Id. */
export function newUnitId(units: readonly Unit[]): string {
const taken = new Set(units.map((u) => u.id));
for (let n = units.length + 1; ; n++) {
const id = `unit-${n}`;
if (!taken.has(id)) return id;
}
}
+9 -5
View File
@@ -37,7 +37,7 @@
// (Linienzeichnung, Silhouette kräftig, Flächen nach Lage grau; ohne GPU)
// dossier-cli <projekt.obp> ifc [--ebkph] [--ebenen] [--kontext] (IFC mit eBKP-H-Hauptgruppen bzw. Modell-Ebenen als Klassifikation; --kontext: Gelände/Nachbarn mitgeben)
// --schema 4|2x3: IFC4 (Standard) oder IFC2x3 (Coordination View 2.0)
// dossier-cli <projekt.obp> dxf [--binary] [--scale 100] [--dim-unit cm] [--layout]|dwg|ifc|step|obj [--no-mtl]|stl|glb|gltf|schedule [--openings|--elements|--rooms] [--format json|csv|svg|pdf]|kennzahlen [--sia416] [--ivhb] [--nachweis] [--format json|csv|svg|pdf] [--agsf m2] [--gruenflaeche m2] [--agf-basis gf|ngf|nf] [--untergeschosse]|raumprogramm [--import tabelle] [--sheet name|nr] [--mode replace|append] [--tolerance %] [--generate] [--format json|csv|svg|pdf] [--save projekt.obp]|sun [--level EG] [--out datei]
// dossier-cli <projekt.obp> dxf [--binary] [--scale 100] [--dim-unit cm] [--layout]|dwg|ifc|step|obj [--no-mtl]|stl|glb|gltf|schedule [--openings|--elements|--rooms] [--format json|csv|svg|pdf]|kennzahlen [--sia416] [--ivhb] [--nachweis] [--wohnungsspiegel] [--format json|csv|svg|pdf] [--agsf m2] [--gruenflaeche m2] [--agf-basis gf|ngf|nf] [--untergeschosse]|raumprogramm [--import tabelle] [--sheet name|nr] [--mode replace|append] [--tolerance %] [--generate] [--format json|csv|svg|pdf] [--save projekt.obp]|sun [--level EG] [--out datei]
// glb/gltf = glTF 2.0 (Y-up, Meter, Geschoss als Eltern; --flat ohne Geschoss-Knoten)
// dossier-cli convert <eingabe> <ausgabe> [--cmd "befehl"]… Format nach Endung: dxf/dwg/ifc/obp → obp-Import,
// obp → dxf/dwg/ifc/obj/stl/glb/gltf/step; --cmd: weitere Befehle
@@ -107,6 +107,7 @@ import {
exportScheduleCsv,
computeKennzahlen,
computeAreaTable,
computeUnitSchedule,
computeIvhb,
computeSiteProof,
buildAreaReport,
@@ -1365,7 +1366,7 @@ async function execute(project: Project, file: string, command: string, rest: st
return 0;
case "kennzahlen": {
// --sia416 / --ivhb: Flächentabelle bzw. IVHB-Kennziffern [70]; --format json|csv|svg|pdf (Default json).
if (args.flags.has("sia416") || args.flags.has("ivhb") || args.flags.has("nachweis")) {
if (args.flags.has("sia416") || args.flags.has("ivhb") || args.flags.has("nachweis") || args.flags.has("wohnungsspiegel")) {
const num = (k: string): number | undefined => {
const v = args.flags.get(k);
if (v === undefined) return undefined;
@@ -1379,14 +1380,15 @@ async function execute(project: Project, file: string, command: string, rest: st
const wantAreas = args.flags.has("sia416");
const wantIvhb = args.flags.has("ivhb");
const wantProof = args.flags.has("nachweis");
const wantUnits = args.flags.has("wohnungsspiegel");
const format = args.flags.get("format") ?? "json";
const stem = `${exportProjectName(project) || "projekt"}-flaechen`;
if (format === "json") {
const json = { ...(wantAreas ? { flaechentabelle: computeAreaTable(project) } : {}), ...(wantIvhb ? { ivhb: computeIvhb(project, ivhbOptions) } : {}), ...(wantProof ? { baurechtNachweis: computeSiteProof(project, ivhbOptions) } : {}) };
const json = { ...(wantAreas ? { flaechentabelle: computeAreaTable(project) } : {}), ...(wantIvhb ? { ivhb: computeIvhb(project, ivhbOptions) } : {}), ...(wantProof ? { baurechtNachweis: computeSiteProof(project, ivhbOptions) } : {}), ...(wantUnits ? { wohnungsspiegel: computeUnitSchedule(project) } : {}) };
out(args, JSON.stringify(json, null, 2), `${stem}.json`);
return 0;
}
const report = buildAreaReport(project, { areas: wantAreas, ivhb: wantIvhb, siteProof: wantProof, ivhbOptions });
const report = buildAreaReport(project, { areas: wantAreas, ivhb: wantIvhb, siteProof: wantProof, units: wantUnits, ivhbOptions });
if (format === "csv") out(args, areaReportToCsv(report), `${stem}.csv`);
else if (format === "svg") out(args, areaReportToSvg(report), `${stem}.svg`);
else if (format === "pdf") out(args, new Uint8Array((await buildAreaReportPdf(report)).output("arraybuffer")), `${stem}.pdf`);
@@ -1399,7 +1401,9 @@ async function execute(project: Project, file: string, command: string, rest: st
const baurecht = checkSiteRules(project);
// [68] Erdarbeiten je Baugrube (Abtrag/Auftrag/Hinterfüllung, m³).
const erdarbeiten = excavationQuantities(project);
out(args, JSON.stringify({ kennzahlen: k, raumprogramm: prog, baurecht, erdarbeiten }, null, 2), `${exportProjectName(project) || "projekt"}-kennzahlen.json`);
// [278] Wohnungsspiegel, sobald das Projekt Nutzungseinheiten hat.
const wohnungsspiegel = (project.units ?? []).length > 0 ? computeUnitSchedule(project) : undefined;
out(args, JSON.stringify({ kennzahlen: k, raumprogramm: prog, baurecht, erdarbeiten, ...(wohnungsspiegel ? { wohnungsspiegel } : {}) }, null, 2), `${exportProjectName(project) || "projekt"}-kennzahlen.json`);
return 0;
}
case "designoptions": {
+1
View File
@@ -183,6 +183,7 @@ export type QueryName =
| "presentationSheet"
| "kennzahlen"
| "areaTable"
| "unitSchedule"
| "renovationFilters"
| "renovationStyles"
| "renovationPair"
+3 -1
View File
@@ -45,6 +45,8 @@ export type { RoomBook, RoomBookRow, FinishQty, WallSide } from "../export/roomB
export { sheetTables, createTable, drawTablesPdf, tableCatalog, tableLabels, tableSourceLabel, TABLE_SOURCES } from "../export/sheetTable";
export type { TableOut, TablePrim, TableColumn } from "../export/sheetTable";
export { computeAreaTable, computeIvhb } from "../analysis/areaTable";
export { computeUnitSchedule, unitScheduleCsv, nextUnitName, newUnitId, UNIT_USAGES } from "../analysis/unitSchedule";
export type { UnitSchedule, UnitRow, UnitTypeSum, UnitLevelSum, UnitAreas } from "../analysis/unitSchedule";
export type { AreaTable, AreaRow, Ivhb, IvhbOptions, AgfBasis } from "../analysis/areaTable";
export { computeSiteProof } from "../analysis/siteProof";
export type { SiteProof, ProofRow, ProofBasis } from "../analysis/siteProof";
@@ -52,7 +54,7 @@ export { exportProjectName, competitionIdentity, isAnonymous, competitionKeyword
export type { CompetitionIdentity } from "../export/competitionIdentity";
export { anonymityFindings } from "../export/competitionCheck";
export type { AnonymityFinding, AnonymityKind } from "../export/competitionCheck";
export { isAreaReportEmpty, buildAreaReport, areaReportToCsv, parseAreaReportCsv, areaReportToSvg, buildAreaReportPdf } from "../export/areaReport";
export { isAreaReportEmpty, hasUnits, buildAreaReport, areaReportToCsv, parseAreaReportCsv, areaReportToSvg, buildAreaReportPdf } from "../export/areaReport";
export { setPdfFontLoader } from "../export/pdfFonts";
export type { AreaReport, AreaReportOptions } from "../export/areaReport";
export { sunPosition, shadowPolygons, shadowOfPrism, projectLatLon } from "../analysis/sun";
+42
View File
@@ -19,6 +19,7 @@ import { ensurePdfFonts, hasPdfFont, PDF_DEFAULT_FONT, setPdfFont } from "./pdfF
import { computeAreaTable, computeIvhb } from "../analysis/areaTable";
import type { AreaRow, IvhbOptions } from "../analysis/areaTable";
import { computeSiteProof } from "../analysis/siteProof";
import { computeUnitSchedule } from "../analysis/unitSchedule";
/** Zelle: Text oder Zahl (`d` Nachkommastellen, `null` = nicht berechenbar). */
export type Cell = string | { n: number | null; d: number; g?: boolean };
@@ -55,6 +56,8 @@ export interface AreaReportOptions {
ivhbOptions?: IvhbOptions;
/** Baurecht-Nachweis ([255]): Vorgaben der Parzelle gegen Kennzahlen, mit Grundlagen (Default nein). */
siteProof?: boolean;
/** Wohnungsspiegel ([278]): Nutzungseinheiten, Summe je Typ und je Geschoss (Default nein; ohne Einheiten kein Abschnitt). */
units?: boolean;
}
const num = (n: number | null | undefined, d: number): Cell => ({ n: n === undefined || n === null || !Number.isFinite(n) ? null : n, d });
@@ -71,6 +74,44 @@ export function isAreaReportEmpty(project: Project): boolean {
return [total.hnf, total.nnf, total.vf, total.ff, total.kf, total.gf, total.agf, total.rooms, gv].every((v) => !(Math.abs(v) > 0));
}
/** [278] Hat das Projekt Nutzungseinheiten (sonst wäre der Wohnungsspiegel leer)? */
export function hasUnits(project: Project): boolean {
return (project.units ?? []).length > 0;
}
/** [278] Wohnungsspiegel als Abschnitte: Einheiten mit Summe, je Typ, je Geschoss (samt Räumen ohne Einheit). */
function addUnitSections(project: Project, sections: ReportSection[], notes: string[]): void {
if (!hasUnits(project)) return;
const u = computeUnitSchedule(project);
const dash = "–";
sections.push({
heading: t("units.table"),
columns: [t("units.col.name"), t("units.col.floor"), t("units.col.type"), t("units.col.rooms"), "HNF", "NNF", "NF", t("units.col.outdoor")],
widths: [1.4, 3, 2.6, 1.4, 1.6, 1.6, 1.6, 2],
rows: [
...u.units.map((r): ReportRow => ({ cells: [r.name, r.floors.join(", "), r.typeLabel, r.usage === "living" ? num(r.roomCount, 1) : dash, num(r.hnf, 2), num(r.nnf, 2), num(r.nf, 2), num(r.agf, 2)] })),
{ total: true, cells: [t("areas.total"), "", String(u.total.count), num(u.total.roomCount, 1), num(u.total.hnf, 2), num(u.total.nnf, 2), num(u.total.nf, 2), num(u.total.agf, 2)] },
],
});
sections.push({
heading: t("units.byType"),
columns: [t("units.col.type"), t("units.col.count"), t("units.col.rooms"), t("units.col.avgHnf"), "HNF", "NF", t("units.col.outdoor")],
widths: [3, 1.4, 1.6, 1.8, 1.8, 1.8, 2],
rows: u.byType.map((r): ReportRow => ({ cells: [r.typeLabel || t("units.noType"), String(r.count), num(r.roomCount, 1), num(r.avgHnf, 2), num(r.hnf, 2), num(r.nf, 2), num(r.agf, 2)] })),
});
sections.push({
heading: t("units.byLevel"),
columns: [t("units.col.floor"), t("units.col.count"), "HNF", "NNF", "NF", t("units.col.outdoor")],
widths: [3, 1.4, 1.8, 1.8, 1.8, 2],
rows: [
...u.byLevel.map((r): ReportRow => ({ cells: [r.name, String(r.count), num(r.hnf, 2), num(r.nnf, 2), num(r.nf, 2), num(r.agf, 2)] })),
...(u.unassigned.rooms > 0 ? [{ cells: [t("units.unassigned"), "", num(u.unassigned.hnf, 2), num(u.unassigned.nnf, 2), num(u.unassigned.nf, 2), num(u.unassigned.agf, 2)] } as ReportRow] : []),
],
});
const foot = t("units.foot");
if (!notes.includes(foot)) notes.push(foot);
}
/** Baut den Bericht aus dem Projekt. */
export function buildAreaReport(project: Project, opts: AreaReportOptions = {}): AreaReport {
const sections: ReportSection[] = [];
@@ -149,6 +190,7 @@ export function buildAreaReport(project: Project, opts: AreaReportOptions = {}):
if (!notes.includes(text)) notes.push(text);
}
}
if (opts.units) addUnitSections(project, sections, notes);
return { title: t("areas.title"), ...reportHead(project), sections, notes };
}
+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", "costs", "designOptionCompare", "earthworks", "elements", "openings", "roomBook", "rooms", "siteProof"]);
const p = withTables((["openings", "areas", "rooms", "elements", "earthworks", "roomBook", "costs", "siteProof", "designOptionCompare"] as const).map((source) => table({ id: source, source })));
expect(Object.keys(cat.sources).sort()).toEqual(["areas", "costs", "designOptionCompare", "earthworks", "elements", "openings", "roomBook", "rooms", "siteProof", "unitSchedule"]);
const p = withTables((["openings", "areas", "rooms", "elements", "earthworks", "roomBook", "costs", "siteProof", "designOptionCompare", "unitSchedule"] 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", "costs", "siteProof", "designOptionCompare"]);
expect(out.map((o) => o.id)).toEqual(["openings", "areas", "rooms", "elements", "earthworks", "roomBook", "costs", "siteProof", "designOptionCompare", "unitSchedule"]);
for (const o of out) expect(o.prims.some((x) => x.k === "text")).toBe(true);
});
+1 -1
View File
@@ -39,7 +39,7 @@ interface Catalog {
valueKeys: string[];
}
export const TABLE_SOURCES: readonly LayoutTableSource[] = ["openings", "areas", "rooms", "elements", "earthworks", "roomBook", "costs", "siteProof", "designOptionCompare"];
export const TABLE_SOURCES: readonly LayoutTableSource[] = ["openings", "areas", "rooms", "elements", "earthworks", "roomBook", "costs", "siteProof", "designOptionCompare", "unitSchedule"];
export function tableSourceLabel(s: LayoutTableSource): string {
return t(`sheetTable.source.${s}`);
+51
View File
@@ -4919,6 +4919,57 @@ export const de = {
"cmd.designOptionCopy.prompt": "Kopieren in Variante (z. B. Dachform=B, Variantenname oder Nummer; H = Hauptmodell)",
"cmd.designOption.needsSelection": "Zuerst Elemente wählen, dann die Variante wählen.",
"cmd.designOption.needsSet": "Das Projekt hat noch keinen Variantensatz (Ressourcen › Varianten).",
"sheetTable.source.unitSchedule": "Wohnungsspiegel",
"units.title": "Nutzungseinheiten und Wohnungsspiegel",
"units.col.name": "Nr.",
"units.col.type": "Typ",
"units.col.usage": "Nutzung",
"units.col.rooms": "Zimmer",
"units.col.outdoor": "Aussenraum m²",
"units.col.note": "Bemerkung",
"units.col.count": "Anzahl",
"units.col.avgHnf": "Ø HNF m²",
"units.col.floor": "Geschoss",
"units.col.roomsCount": "Räume",
"units.usage.living": "Wohnen",
"units.usage.commercial": "Gewerbe",
"units.usage.office": "Büro",
"units.usage.other": "Andere",
"units.add": "Neue Einheit",
"units.addFromSelection": "Neue Einheit aus Auswahl",
"units.assign": "Auswahl zuordnen",
"units.assignTo": "Ausgewählte Räume zuordnen zu …",
"units.delete": "Einheit löschen (Räume bleiben, ohne Einheit)",
"units.empty": "Noch keine Nutzungseinheiten. Räume wählen und „Neue Einheit aus Auswahl“ — oder im Raum unter Einheit „Neue Einheit …“.",
"units.nameDefault": "Whg",
"units.autoType": "automatisch",
"units.typeHint": "Typ, z. B. 3.5-Zi-Whg (leer: aus der Zimmerzahl)",
"units.nameHint": "Nummer, z. B. 2.1",
"units.color": "Farbe der Einheit",
"units.rooms": "{n} Räume",
"units.table": "Wohnungsspiegel [m²]",
"units.byType": "Summe je Typ",
"units.byLevel": "Summe je Geschoss",
"units.unassigned": "Räume ohne Einheit (Gemeinschaftsflächen)",
"units.noType": "ohne Typ",
"units.exportCsv": "Spiegel CSV",
"units.exportPdf": "Spiegel PDF",
"units.export.empty": "Noch keine Nutzungseinheiten — der Spiegel wäre leer. Es wurde nichts exportiert.",
"units.exportPdf.fail": "PDF-Export des Wohnungsspiegels fehlgeschlagen.",
"units.foot": "Wohnungsspiegel: Flächen je Raum nach SIA 416 (NF = HNF + NNF), Aussenraum = Aussengeschossfläche (Balkon, Loggia); Zimmerzahl nur Wohnnutzung: Wohnen, Schlafen, Essen, Büro = 1, sonst 0, je Raum einstellbar (Wohnküche 0.5). Maisonetten zählen in jedem Geschoss.",
"units.field": "Einheit",
"units.field.none": "– keine –",
"units.field.new": "Neue Einheit …",
"units.roomCount": "Zimmer-Zählung",
"units.roomCount.auto": "automatisch (aus Nutzung)",
"units.roomCount.hint": "Beitrag zur Zimmerzahl der Einheit: 1 = Zimmer, 0.5 = halbes Zimmer/Wohnküche, 0 = zählt nicht",
"units.roomCount.0": "0 (zählt nicht)",
"units.roomCount.05": "0.5",
"units.roomCount.1": "1",
"units.roomCount.15": "1.5",
"units.roomCount.2": "2",
"units.zi": "{n} Zi",
"units.plan.layer": "Nutzungseinheiten",
} as const;
export type TranslationKey = keyof typeof de;
+51
View File
@@ -4905,4 +4905,55 @@ export const en: Record<TranslationKey, string> = {
"cmd.designOptionCopy.prompt": "Copy into option (e.g. Roof=B, option name or number; H = main model)",
"cmd.designOption.needsSelection": "Select elements first, then choose the option.",
"cmd.designOption.needsSet": "The project has no option set yet (Resources › Design options).",
"sheetTable.source.unitSchedule": "Unit schedule",
"units.title": "Units and unit schedule",
"units.col.name": "No.",
"units.col.type": "Type",
"units.col.usage": "Use",
"units.col.rooms": "Rooms",
"units.col.outdoor": "Outdoor m²",
"units.col.note": "Note",
"units.col.count": "Count",
"units.col.avgHnf": "Avg. HNF m²",
"units.col.floor": "Floor",
"units.col.roomsCount": "Spaces",
"units.usage.living": "Residential",
"units.usage.commercial": "Commercial",
"units.usage.office": "Office",
"units.usage.other": "Other",
"units.add": "New unit",
"units.addFromSelection": "New unit from selection",
"units.assign": "Assign selection",
"units.assignTo": "Assign selected rooms to …",
"units.delete": "Delete unit (rooms stay, without unit)",
"units.empty": "No units yet. Select rooms and use “New unit from selection”, or choose “New unit …” in the room's Unit field.",
"units.nameDefault": "Apt",
"units.autoType": "automatic",
"units.typeHint": "Type, e.g. 3.5-room apartment (empty: from room count)",
"units.nameHint": "Number, e.g. 2.1",
"units.color": "Unit color",
"units.rooms": "{n} spaces",
"units.table": "Unit schedule [m²]",
"units.byType": "Totals by type",
"units.byLevel": "Totals by floor",
"units.unassigned": "Spaces without unit (common areas)",
"units.noType": "no type",
"units.exportCsv": "Schedule CSV",
"units.exportPdf": "Schedule PDF",
"units.export.empty": "No units yet — the schedule would be empty. Nothing was exported.",
"units.exportPdf.fail": "PDF export of the unit schedule failed.",
"units.foot": "Unit schedule: areas per room to SIA 416 (NF = HNF + NNF), outdoor = external floor area (balcony, loggia); room count for residential use only: living, sleeping, dining, office = 1, else 0, adjustable per room (open kitchen 0.5). Maisonettes count on each floor.",
"units.field": "Unit",
"units.field.none": "– none –",
"units.field.new": "New unit …",
"units.roomCount": "Room count",
"units.roomCount.auto": "automatic (from use)",
"units.roomCount.hint": "Contribution to the unit's room count: 1 = room, 0.5 = half room/open kitchen, 0 = not counted",
"units.roomCount.0": "0 (not counted)",
"units.roomCount.05": "0.5",
"units.roomCount.1": "1",
"units.roomCount.15": "1.5",
"units.roomCount.2": "2",
"units.zi": "{n} rm",
"units.plan.layer": "Units",
};
+24 -1
View File
@@ -20,6 +20,8 @@ import type {
Project,
Room,
RoomStamp,
RoomUsage,
Unit,
RoofType,
SiaCategory,
Vec2,
@@ -223,6 +225,21 @@ const ROOMS_PER_FLOOR: RoomDef[] = [
[P(10, 9.5), "10", "Abstellraum", "NNF"],
];
/** Nutzung je Raumname (Raumbuch, Zimmerzahl im Wohnungsspiegel [278]). */
const USAGE: Record<string, RoomUsage> = { "Wohnen/Essen": "living", Zimmer: "sleeping", Diele: "circulation", Bad: "bath", Treppenhaus: "circulation", Eingang: "circulation", Abstellraum: "storage" };
/** [278] Nutzungseinheiten: je Geschoss eine West- (Räume 01–04) und eine Ost-Wohnung (05–08); Nummer „Geschoss.Seite“ (EG = 0). */
const UNIT_NR = { eg: "0", og1: "1", og2: "2" } as const;
const unitOf = (floor: keyof typeof UNIT_NR, key: string): string | undefined => {
const n = Number(key);
return n >= 1 && n <= 4 ? `whg-${floor}-w` : n >= 5 && n <= 8 ? `whg-${floor}-o` : undefined;
};
function units(): Unit[] {
return FLOORS.flatMap((f) => [
{ id: `whg-${f.id}-w`, name: `${UNIT_NR[f.id]}.1`, usage: "living" as const, color: "#4f8fc0" },
{ id: `whg-${f.id}-o`, name: `${UNIT_NR[f.id]}.2`, usage: "living" as const, color: "#c0874f" },
]);
}
function addRooms(p: Project): Project {
const prefix = { eg: "E", og1: "1", og2: "2" } as const;
for (const f of FLOORS) {
@@ -235,7 +252,10 @@ function addRooms(p: Project): Project {
const made = ops.find((o) => o.kind === "add" && o.collection === "rooms");
if (!made || made.kind !== "add") throw new Error(`Wettbewerb: Raum ${nr} nicht erkannt`);
const stamp: RoomStamp = { number: nr, name, showFloorArea: true, showUsage: false, roundingStep: 0.1 };
const room = { ...(made.items[0] as unknown as Room), id: `raum-${nr}`, name, siaCategory: cat, stamp };
const unitId = unitOf(f.id, key);
// Ost-Wohnungen: Wohnen/Essen mit offener Küche zählt 1.5 Zimmer (2.5-Zi-Whg), West: 2-Zi-Whg nach der Vorgabe aus der Nutzung.
const roomCount = unitId?.endsWith("-o") && baseName === "Wohnen/Essen" ? 1.5 : undefined;
const room = { ...(made.items[0] as unknown as Room), id: `raum-${nr}`, name, siaCategory: cat, stamp, usage: USAGE[name], ...(unitId ? { unitId } : {}), ...(roomCount !== undefined ? { roomCount } : {}) };
p = applyOps(p, [{ kind: "add", collection: "rooms", items: [room as unknown as { id: string }] } as CoreOp]);
}
}
@@ -274,6 +294,7 @@ export function buildWettbewerbSampleProject(): Project {
roofs,
stairs,
rooms: [],
units: units(),
drawings2d: cadastre(),
context: [neighbours()],
// Raumprogramm des Wettbewerbs (Soll); die Räume im Modell liefern das Ist.
@@ -322,6 +343,8 @@ export function buildWettbewerbSampleProject(): Project {
],
layouts: [
{ id: "lay-situation", name: "Situation 1:500", paper: "a3", orientation: "landscape", planNumber: "001", viewports: [{ id: "vp-situation", snapshotId: "vs-situation", xMm: 20, yMm: 20, widthMm: 380, heightMm: 260, scaleDenominator: 500 }] },
// [278] Wohnungsspiegel als lebendige Tabelle (folgt dem Modell).
{ id: "lay-wohnungsspiegel", name: "Wohnungsspiegel", paper: "a4", orientation: "landscape", planNumber: "002", viewports: [], tables: [{ id: "tab-wohnungsspiegel", source: "unitSchedule", xMm: 20, yMm: 20, widthMm: 257 }] },
],
};
+39 -1
View File
@@ -2213,7 +2213,8 @@ export type LayoutTableSource =
| "roomBook"
| "costs"
| "siteProof"
| "designOptionCompare";
| "designOptionCompare"
| "unitSchedule";
/**
* Einfache Textfelder des Titelblocks (Master). Alle optional — leere Felder
@@ -3376,6 +3377,10 @@ export type Project = {
* [272] Benannte Variantenkombinationen (Archicad „Design Option Combinations“): je Satz genau eine Variante.
*/
designOptionCombinations?: Array<DesignOptionCombination>;
/**
* [278] Nutzungseinheiten (Wohnungen, Gewerbe) für den Wohnungsspiegel; Räume verweisen mit `unitId` darauf.
*/
units?: Array<Unit>;
};
/** Protokolleintrag einer Publikation ([79]): Datum, Blätter mit Revision, erzeugte Dateien. */
@@ -3770,6 +3775,16 @@ export type Room = {
* [272] Variante, zu der das Element gehört (`Project.designOptionSets`). Fehlt ⇒ Hauptmodell (immer sichtbar).
*/
designOption?: DesignOptionRef;
/**
* [278] Nutzungseinheit (`Project.units`, Id), zu der der Raum gehört (Wohnung, Gewerbeeinheit). Fehlt oder
* unbekannt ⇒ keiner Einheit zugeordnet (Gemeinschaftsfläche).
*/
unitId?: string;
/**
* [278] Zimmerzahl-Beitrag dieses Raums für den Wohnungsspiegel (CH-Konvention: Zimmer 1, Wohnküche/halbes Zimmer 0.5,
* Nebenraum 0). Fehlt ⇒ Vorgabe aus der Nutzung (`unit_schedule::default_room_count`).
*/
roomCount?: number;
};
/**
@@ -4445,6 +4460,29 @@ export type UiViewTabs = {
activeId: string;
};
/**
* [278] Nutzungseinheit (Wohnung, Gewerbe-, Büroeinheit): fasst Räume für den Wohnungsspiegel zusammen. Die Räume
* verweisen mit `Room.unitId` auf sie; Fläche, Geschoss und Zimmerzahl rechnet der Kern aus den Räumen.
*/
export type Unit = {
id: string;
/** Nummer/Bezeichnung, z. B. „2.1“. */
name: string;
/**
* Typ, z. B. „3.5-Zi-Whg“. Fehlt er, leitet der Spiegel bei Wohnungen „n-Zi-Whg“ aus der Zimmerzahl ab.
*/
unitType?: string;
/** Nutzung (Fehlt ⇒ Wohnen). */
usage?: UnitUsage;
/** Farbe der Einheit (hex) für Darstellungen. */
color?: string;
/** Bemerkung (reiner Text). */
note?: string;
};
/** [278] Nutzung einer Nutzungseinheit. */
export type UnitUsage = "living" | "commercial" | "office" | "other";
export type Vec2 = { x: number; y: number };
/**
+6 -36
View File
@@ -12,6 +12,7 @@ import { exportProjectName, areaReportToCsv, buildAreaReport, buildAreaReportPdf
import type { AgfBasis } from "../core";
import { DEFAULT_AREA_INPUTS, ivhbOptionsOf, type AreaInputs } from "./areaInputs";
import { downloadCsv } from "./downloadFile";
import { ReportTable } from "./ReportTable";
import { runWithAnonymityGate } from "../state/anonymityGate";
import { useStore } from "../state/appStore";
@@ -26,6 +27,8 @@ export function AreaTableSection() {
// eslint-disable-next-line react-hooks/exhaustive-deps
[project, inputs],
);
// [278] CSV/PDF enthalten zusätzlich den Wohnungsspiegel (die Anzeige hat ihn im Abschnitt „Nutzungseinheiten“).
const buildExport = () => buildAreaReport(project, { areas: true, ivhb: true, siteProof: true, units: true, ivhbOptions: ivhbOptionsOf(inputs) });
const set = (patch: Partial<AreaInputs>) => setInputs((i) => ({ ...i, ...patch }));
const stem = `${exportProjectName(project) || "projekt"}-flaechen`;
@@ -37,13 +40,13 @@ export function AreaTableSection() {
};
const exportCsv = () => {
if (emptyHint()) return;
runWithAnonymityGate(project, [`${stem}.csv`], () => downloadCsv(`${stem}.csv`, areaReportToCsv(report)));
runWithAnonymityGate(project, [`${stem}.csv`], () => downloadCsv(`${stem}.csv`, areaReportToCsv(buildExport())));
};
const exportPdf = () => {
if (emptyHint()) return;
runWithAnonymityGate(project, [`${stem}.pdf`], async () => {
try {
(await buildAreaReportPdf(report)).save(`${stem}.pdf`);
(await buildAreaReportPdf(buildExport())).save(`${stem}.pdf`);
} catch {
notify(t("areas.exportPdf.fail"));
}
@@ -65,40 +68,7 @@ export function AreaTableSection() {
</div>
{report.sections.map((s, si) => (
<div key={si} className="area-block">
<div className="area-heading">{s.heading}</div>
<div className="area-scroll">
<table className={s.columns.length > 6 ? "area-table wide" : "area-table"}>
<thead>
<tr>
{s.columns.map((c, i) => (
<th key={i} className={i === 0 ? "" : "num"}>
{c}
</th>
))}
</tr>
</thead>
<tbody>
{s.rows.map((r, ri) => (
<tr key={ri} className={r.total ? "total" : ""}>
{r.cells.map((c, ci) =>
typeof c === "string" ? (
// Kurze Textzellen in Zahlenspalten (Strich, ja/nein) stehen wie die Zahlen rechts.
<td key={ci} data-label={ci > 0 ? s.columns[ci] : undefined} className={ci > 0 && c.length <= 4 ? "num" : undefined}>
{c}
</td>
) : (
<td key={ci} data-label={ci > 0 ? s.columns[ci] : undefined} className="num">
{c.n === null ? "–" : c.n.toFixed(c.d)}
</td>
),
)}
</tr>
))}
</tbody>
</table>
</div>
</div>
<ReportTable key={si} section={s} />
))}
<div className="area-inputs">
+1 -1
View File
@@ -24,7 +24,7 @@ Kern; hier stehen Eingabe und Darstellung. Zustand über den Store (`src/state`)
| `objectInfo/*.tsx` | Abschnitte je Element-Art (`WallSection`, `CeilingSection`, `RoofSections`, `OpeningSections`, `StairSection`, `RoomSection`, `RoomStampSection` (Raumstempel samt Schrift, [218]), `SolidSections`, `SectionLineSection`, `RefSections`, `TreeSection`), gemeinsame Felder (`fields.tsx`) und Info-Blöcke (`InfoBlocks.tsx`); `ObjectInfoPanel` zeigt sie als einklappbare Gruppen (`InfoGroups.tsx`, `InfoGroup.tsx`, Zustand `infoGroupState.ts`); `groups.ts` hält die Zuordnung (Attribute = nur Gestaltung, Objekt-Info = Bauteil/BIM) und das Ziel der Taste T (`[189]`) |
| `DrawingLevelsPanel.tsx`, `LayersPanel.tsx`, `ElementTreePanel.tsx` | Zeichnungsebenen, Ebenen, Baum Geschoss → Bauteilklasse → Element |
| `LayoutsPanel.tsx`, `PublishSection.tsx`, `ViewSnapshotsPanel.tsx` | Layouts als Baum, Publikationssätze (`[79]`), gespeicherte Ansichten |
| `RoomBalancePanel.tsx` | Flächenbilanz mit den Abschnitten `AreaTableSection.tsx`, `KennzahlenSection.tsx`, `ProgramCompareSection.tsx`, `ElementScheduleSection.tsx`, `OpeningScheduleSection.tsx`, `RoomBookSection.tsx` |
| `RoomBalancePanel.tsx` | Flächenbilanz mit den Abschnitten `AreaTableSection.tsx`, `KennzahlenSection.tsx`, `ProgramCompareSection.tsx`, `ElementScheduleSection.tsx`, `OpeningScheduleSection.tsx`, `RoomBookSection.tsx`, `UnitsSection.tsx` (Nutzungseinheiten und Wohnungsspiegel [278]; Ops in `unitOps.ts`, Tabelle `ReportTable.tsx`) |
| `SitePanel.tsx` | Aktionen zu Gelände und Lage (Import, Gelände erzeugen, Baugrube; keine Import-Liste, [181]), mit `SiteRulesSection.tsx` (Baurecht), `SunStudySection.tsx` (Schatten) und `PointCloudSection.tsx` |
| `BcfPanel.tsx`, `ClashPanel.tsx` | BCF-Themen und Kollisionsliste; Sitzungszustand in `bcfSession.ts` und `clashSession.ts` |
| `HistoryPanel.tsx` | Undo-Verlauf mit Sprung auf einen Schritt |
+43
View File
@@ -0,0 +1,43 @@
// Ein Abschnitt des Berichtsmodells (`ReportSection` aus `export/areaReport.ts`) als Tabelle im Panel. Gemeinsam für die
// Flächentabelle (`AreaTableSection`) und den Wohnungsspiegel (`UnitsSection`): was hier steht, steht auch im Export.
import type { ReportSection } from "../export/areaReport";
export function ReportTable({ section: s }: { section: ReportSection }) {
return (
<div className="area-block">
<div className="area-heading">{s.heading}</div>
<div className="area-scroll">
<table className={s.columns.length > 6 ? "area-table wide" : "area-table"}>
<thead>
<tr>
{s.columns.map((c, i) => (
<th key={i} className={i === 0 ? "" : "num"}>
{c}
</th>
))}
</tr>
</thead>
<tbody>
{s.rows.map((r, ri) => (
<tr key={ri} className={r.total ? "total" : ""}>
{r.cells.map((c, ci) =>
typeof c === "string" ? (
// Kurze Textzellen in Zahlenspalten (Strich, ja/nein) stehen wie die Zahlen rechts.
<td key={ci} data-label={ci > 0 ? s.columns[ci] : undefined} className={ci > 0 && c.length <= 4 ? "num" : undefined}>
{c}
</td>
) : (
<td key={ci} data-label={ci > 0 ? s.columns[ci] : undefined} className="num">
{c.n === null ? "–" : c.n.toFixed(c.d)}
</td>
),
)}
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
+4
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 { UnitsSection } from "./UnitsSection";
import { CostEstimateSection } from "./CostEstimateSection";
import { OpeningScheduleSection } from "./OpeningScheduleSection";
import { ElementScheduleSection } from "./ElementScheduleSection";
@@ -85,6 +86,9 @@ export function RoomBalancePanel() {
{/* Flächentabelle und IVHB-Kennziffern. */}
<AreaTableSection />
{/* Nutzungseinheiten und Wohnungsspiegel ([278]). */}
<UnitsSection />
{/* Kostenschätzung grob ([209]). */}
<CostEstimateSection />
+161
View File
@@ -0,0 +1,161 @@
// Nutzungseinheiten und Wohnungsspiegel im Flächenbilanz-Panel ([278]).
//
// • Liste der Einheiten (Nummer, Typ, Nutzung, Farbe) bearbeiten, neue Einheit anlegen (leer oder aus der Raum-Auswahl),
// Auswahl einer Einheit zuordnen, Einheit löschen (die Räume bleiben, ohne Einheit).
// • Wohnungsspiegel (Einheiten mit Zimmerzahl und Flächen, Summe je Typ und je Geschoss) aus demselben Berichtsmodell wie
// CSV/PDF (`buildAreaReport` mit `units`); gerechnet im Kern (`unit_schedule.rs`).
// Alle Änderungen laufen über `applyChange` (Ops), eine Aktion = ein Undo-Schritt; Tippen verschmilzt über den coalesceKey.
import { useMemo } from "react";
import { t } from "../i18n";
import { useStore } from "../state/appStore";
import { UNIT_USAGES, buildAreaReport, computeUnitSchedule, exportProjectName, areaReportToCsv, buildAreaReportPdf } from "../core";
import type { Project, UnitUsage } from "../model/types";
import { ReportTable } from "./ReportTable";
import { downloadCsv } from "./downloadFile";
import { runWithAnonymityGate } from "../state/anonymityGate";
import { addUnitOps, assignRoomsOps, deleteUnitOps, draftUnit, patchUnitOps } from "./unitOps";
/** Auswahlwert „keine Einheit“ (leer ist der Platzhalter). */
const NONE = "-";
export function UnitsSection() {
const project = useStore((s) => s.project);
const applyChange = useStore((s) => s.applyChange);
const notify = useStore((s) => s.notify);
const selectedRooms = useStore((s) => s.selection.rooms);
const units = project.units ?? [];
const sched = useMemo(() => computeUnitSchedule(project), [project]);
const rowOf = new Map(sched.units.map((r) => [r.id, r]));
// Reihenfolge der Liste wie im Spiegel (nach Nummer natürlich sortiert).
const ordered = sched.units.map((r) => units.find((u) => u.id === r.id)).filter((u): u is NonNullable<typeof u> => !!u);
const report = useMemo(() => buildAreaReport(project, { areas: false, units: true }), [project]);
const stem = `${exportProjectName(project) || "projekt"}-wohnungsspiegel`;
const add = (fromSelection: boolean) =>
applyChange((p: Project) => addUnitOps(p, draftUnit(p, t("units.nameDefault")), fromSelection ? selectedRooms : []));
const patch = (id: string, field: string, v: Parameters<typeof patchUnitOps>[2]) => applyChange((p: Project) => patchUnitOps(p, id, v), `unit:${id}:${field}`);
const assign = (unitId: string) => {
if (selectedRooms.length === 0 || unitId === "") return;
applyChange((p: Project) => assignRoomsOps(p, selectedRooms, unitId === NONE ? undefined : unitId));
};
const exportCsv = () => {
if (!units.length) return notify(t("units.export.empty"));
runWithAnonymityGate(project, [`${stem}.csv`], () => downloadCsv(`${stem}.csv`, areaReportToCsv(report)));
};
const exportPdf = () => {
if (!units.length) return notify(t("units.export.empty"));
runWithAnonymityGate(project, [`${stem}.pdf`], async () => {
try {
(await buildAreaReportPdf(report)).save(`${stem}.pdf`);
} catch {
notify(t("units.exportPdf.fail"));
}
});
};
return (
<div className="area-section units-section" data-testid="units-section">
<div className="balance-head">
<span className="balance-section-label">{t("units.title")}</span>
<span className="area-actions">
<button type="button" className="balance-export" onClick={exportCsv}>
{t("units.exportCsv")}
</button>
<button type="button" className="balance-export" onClick={exportPdf}>
{t("units.exportPdf")}
</button>
</span>
</div>
{units.length === 0 && <div className="balance-empty">{t("units.empty")}</div>}
{ordered.length > 0 && (
<div className="units-list">
{ordered.map((u) => {
const r = rowOf.get(u.id);
return (
<div key={u.id} className="units-row" data-testid="unit-row">
<input
type="text"
className="kz-input units-name"
value={u.name}
title={t("units.nameHint")}
placeholder={t("units.nameHint")}
onChange={(e) => patch(u.id, "name", { name: e.target.value })}
/>
<input
type="text"
className="kz-input units-type"
value={u.unitType ?? ""}
title={t("units.typeHint")}
placeholder={r?.typeLabel || t("units.autoType")}
onChange={(e) => patch(u.id, "type", { unitType: e.target.value === "" ? undefined : e.target.value })}
/>
<button type="button" className="site-remove" title={t("units.delete")} aria-label={t("units.delete")} onClick={() => applyChange((p: Project) => deleteUnitOps(p, u.id))}>
×
</button>
<select
className="kz-input units-usage"
value={u.usage ?? "living"}
aria-label={t("units.col.usage")}
title={t("units.col.usage")}
onChange={(e) => patch(u.id, "usage", { usage: e.target.value as UnitUsage })}
>
{UNIT_USAGES.map((x) => (
<option key={x} value={x}>
{t(`units.usage.${x}`)}
</option>
))}
</select>
<input
type="color"
className="units-color"
value={u.color ?? "#9aa4b2"}
title={t("units.color")}
aria-label={t("units.color")}
onChange={(e) => patch(u.id, "color", { color: e.target.value })}
/>
<span className="units-facts" title={r ? t("units.rooms", { n: r.rooms }) : undefined}>
{r ? `${r.usage === "living" ? t("units.zi", { n: r.roomCount }) + " · " : ""}${r.hnf.toFixed(1)} m²` : ""}
</span>
</div>
);
})}
</div>
)}
<div className="kz-program-actions">
<button type="button" className="kz-add" onClick={() => add(false)}>
{t("units.add")}
</button>
<button type="button" className="kz-add" disabled={selectedRooms.length === 0} onClick={() => add(true)}>
{t("units.addFromSelection")}
</button>
{units.length > 0 && (
<select className="kz-input" value="" disabled={selectedRooms.length === 0} aria-label={t("units.assignTo")} title={t("units.assignTo")} onChange={(e) => assign(e.target.value)}>
<option value="">{t("units.assign")}</option>
<option value={NONE}>{t("units.field.none")}</option>
{ordered.map((u) => (
<option key={u.id} value={u.id}>
{u.name}
</option>
))}
</select>
)}
</div>
{report.sections.map((s, si) => (
<ReportTable key={si} section={s} />
))}
{report.sections.length > 0 && (
<ul className="area-notes">
{report.notes.map((n, i) => (
<li key={i}>{n}</li>
))}
</ul>
)}
</div>
);
}
+73
View File
@@ -7,6 +7,7 @@ import { t } from "../../i18n";
import { Dropdown } from "../../ui/Dropdown";
import type { SiaCategory, Project, Room } from "../../model/types";
import { SIA_CATEGORIES, siaLabelFull, patchItems, roomBook, ROOM_USAGES, usageLabel } from "../../core";
import { addUnitOps, assignRoomsOps, draftUnit } from "../unitOps";
import { formatM } from "../../model/types";
import { useStore } from "../../state/appStore";
import type { TranslationKey } from "../../i18n";
@@ -82,6 +83,78 @@ export function RoomSection({
{/* [158] Raumbuch: Nutzung und Oberflächen. */}
<RoomFinishFields roomId={roomId} />
{/* [278] Nutzungseinheit und Zimmer-Zählung (Wohnungsspiegel). */}
<RoomUnitFields roomId={roomId} />
</>
);
}
const UNIT_NONE = "";
const UNIT_NEW = "__new";
const UNIT_MIXED = "__mixed";
/** Zimmer-Zählung: automatisch (aus der Nutzung) oder fest 0 / 0.5 / 1 / 1.5 / 2. */
const ROOM_COUNTS = [0, 0.5, 1, 1.5, 2] as const;
const COUNT_KEY = { 0: "units.roomCount.0", 0.5: "units.roomCount.05", 1: "units.roomCount.1", 1.5: "units.roomCount.15", 2: "units.roomCount.2" } as const satisfies Record<(typeof ROOM_COUNTS)[number], TranslationKey>;
/** [278] Einheit des Raums (Auswahl, „Neue Einheit …“) und Beitrag zur Zimmerzahl. Bei Mehrfachauswahl gilt die Wahl für alle
* gewählten Räume in einem Undo-Schritt; unterschiedliche Werte zeigt die Auswahl als „gemischt“. */
function RoomUnitFields({ roomId }: { roomId: string }) {
const project = useStore((st) => st.project);
const applyChange = useStore((s) => s.applyChange);
const selectedRooms = useStore((s) => s.selection.rooms);
const room = (project.rooms ?? []).find((r) => r.id === roomId);
if (!room) return null;
const ids = selectedRooms.length > 1 && selectedRooms.includes(roomId) ? [...selectedRooms] : [roomId];
const group = ids.map((id) => (project.rooms ?? []).find((r) => r.id === id)).filter((r): r is Room => !!r);
const unitIds = new Set(group.map((r) => r.unitId ?? UNIT_NONE));
const counts = new Set(group.map((r) => (r.roomCount === undefined ? "auto" : String(r.roomCount))));
const units = project.units ?? [];
const known = new Set(units.map((u) => u.id));
const unitValue = unitIds.size > 1 ? UNIT_MIXED : known.has(room.unitId ?? "") ? (room.unitId as string) : UNIT_NONE;
const countValue = counts.size > 1 ? UNIT_MIXED : room.roomCount === undefined ? "auto" : String(room.roomCount);
const onUnit = (v: string) => {
if (v === UNIT_MIXED) return;
if (v === UNIT_NEW) applyChange((p: Project) => addUnitOps(p, draftUnit(p, t("units.nameDefault")), ids), "unit:new");
else applyChange((p: Project) => assignRoomsOps(p, ids, v === UNIT_NONE ? undefined : v), `room:${roomId}:unit`);
};
const onCount = (v: string) => {
if (v === UNIT_MIXED) return;
applyChange((p: Project) => patchItems(p, "rooms", ids, (r) => ({ ...r, roomCount: v === "auto" ? undefined : Number(v) }) as Room), `room:${roomId}:roomCount`);
};
const mixed = { value: UNIT_MIXED, label: t("objsettings.mixed"), disabled: true };
return (
<>
<div className="objinfo-section-label">{t("units.title")}</div>
<div className="objinfo-field">
<span className="objinfo-flabel">{t("units.field")}</span>
<Dropdown
value={unitValue}
onChange={onUnit}
options={[
...(unitValue === UNIT_MIXED ? [mixed] : []),
{ value: UNIT_NONE, label: t("units.field.none") },
...units.map((u) => ({ value: u.id, label: u.unitType ? `${u.name} · ${u.unitType}` : u.name })),
{ value: UNIT_NEW, label: t("units.field.new") },
]}
title={t("units.field")}
width={170}
/>
</div>
<div className="objinfo-field">
<span className="objinfo-flabel">{t("units.roomCount")}</span>
<Dropdown
value={countValue}
onChange={onCount}
options={[
...(countValue === UNIT_MIXED ? [mixed] : []),
{ value: "auto", label: t("units.roomCount.auto") },
...ROOM_COUNTS.map((c) => ({ value: String(c), label: t(COUNT_KEY[c]) })),
]}
title={t("units.roomCount.hint")}
width={170}
/>
</div>
</>
);
}
+34
View File
@@ -0,0 +1,34 @@
// Ops der Nutzungseinheiten ([278]): Einheit anlegen, Räumen zuordnen, löschen. Jede Funktion liefert alle Ops einer
// Benutzeraktion (Projekt-Feld `units` und `unitId` der Räume), damit `applyChange` sie zu EINEM Undo-Schritt macht.
import type { Project, Room, Unit } from "../model/types";
import { setField, patchItems, nextUnitName, newUnitId } from "../core";
import type { CoreOp } from "../core";
/** Räume `roomIds` der Einheit `unitId` zuordnen (`undefined` = keiner Einheit). */
export function assignRoomsOps(p: Project, roomIds: readonly string[], unitId: string | undefined): CoreOp[] {
return patchItems(p, "rooms", roomIds, (r) => ({ ...r, unitId }) as Room);
}
/** Neue Einheit anlegen und (optional) `roomIds` ihr zuordnen. `id` kommt vom Aufrufer, damit er sie danach kennt. */
export function addUnitOps(p: Project, unit: Unit, roomIds: readonly string[] = []): CoreOp[] {
return [setField("units", [...(p.units ?? []), unit]), ...assignRoomsOps(p, roomIds, unit.id)];
}
/** Vorschlag einer neuen Einheit (Name „Whg n“, frische id). */
export function draftUnit(p: Project, namePrefix: string): Unit {
const units = p.units ?? [];
return { id: newUnitId(units), name: nextUnitName(units, namePrefix) };
}
/** Einheit ändern. */
export function patchUnitOps(p: Project, id: string, patch: Partial<Unit>): CoreOp[] {
const units = p.units ?? [];
return [setField("units", units.map((u) => (u.id === id ? { ...u, ...patch } : u)))];
}
/** Einheit löschen; ihre Räume bleiben, ohne Einheit. */
export function deleteUnitOps(p: Project, id: string): CoreOp[] {
const next = (p.units ?? []).filter((u) => u.id !== id);
return [setField("units", next.length > 0 ? next : undefined), ...patchItems(p, "rooms", (r) => r.unitId === id, (r) => ({ ...r, unitId: undefined }) as Room)];
}
+32
View File
@@ -10494,3 +10494,35 @@ body {
.look-icon {
display: block;
}
/* [278] Nutzungseinheiten: je Einheit drei Zeilen (Nummer · Typ · ×, Nutzung · Farbe, Kennwerte) in der schmalen Dock-Spalte. */
.units-list {
display: flex;
flex-direction: column;
gap: 6px;
}
.units-row {
display: grid;
grid-template-columns: 4.5em minmax(0, 1fr) 2.2em;
gap: 4px;
align-items: center;
padding-bottom: 6px;
border-bottom: 1px solid var(--line);
}
.units-row .units-usage {
grid-column: 1 / 3;
}
.units-row .units-color {
width: 100%;
height: 24px;
padding: 0;
border: 1px solid var(--line);
border-radius: 4px;
background: transparent;
}
.units-row .units-facts {
grid-column: 1 / -1;
font-size: 11px;
color: var(--ink-2);
font-variant-numeric: tabular-nums;
}